web-dc-api 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/cjs/babel-tools-BoLJtxtW.js +1 -0
  2. package/dist/cjs/cache-CRG9ugF3.js +1 -0
  3. package/dist/cjs/helia-core-B1Xqha7a.js +1 -0
  4. package/dist/cjs/helia-core-D8Uv1KjQ.js +1 -0
  5. package/dist/cjs/{index-B9UlHr3P.js → index-DtuGISOe.js} +1 -1
  6. package/dist/cjs/index.js +1 -1
  7. package/dist/cjs/{jwt-CcLVpKo_.js → jwt-DW2WimlW.js} +1 -1
  8. package/dist/cjs/polkadot-api-7PhQf3ws.js +1 -0
  9. package/dist/cjs/polkadot-api-CtrJVWuZ.js +1 -0
  10. package/dist/cjs/protobuf-BYUoud7y.js +1 -0
  11. package/dist/cjs/{validation-DfsHeOHP.js → validation-DPN2BqQd.js} +1 -1
  12. package/dist/dc.min.js +1 -1
  13. package/dist/esm/chunks/babel-tools-sSecqeD4.js +1 -0
  14. package/dist/esm/chunks/cache-C0pUsIbC.js +1 -0
  15. package/dist/esm/chunks/helia-core-BxMqyK2Y.js +1 -0
  16. package/dist/esm/chunks/helia-core-DMXRpcO-.js +1 -0
  17. package/dist/esm/chunks/{index-BUlGxni-.js → index-CsnoYfJo.js} +1 -1
  18. package/dist/esm/chunks/{jwt-DLILrtNW.js → jwt-DfD7pIy4.js} +1 -1
  19. package/dist/esm/chunks/polkadot-api-5Y9Bw8VT.js +1 -0
  20. package/dist/esm/chunks/polkadot-api-D69Ioun_.js +1 -0
  21. package/dist/esm/chunks/protobuf-25futi__.js +1 -0
  22. package/dist/esm/chunks/{validation-D9YLFwug.js → validation-C90ZcLFM.js} +1 -1
  23. package/dist/esm/index.js +1 -1
  24. package/dist/index.d.ts +3 -2
  25. package/lib/common/define.ts +1 -1
  26. package/lib/implements/threaddb/common/logstore.ts +1 -1
  27. package/lib/implements/threaddb/core/logstore.ts +2 -2
  28. package/lib/implements/threaddb/dbclient.ts +34 -11
  29. package/lib/implements/threaddb/lsstoreds/addr_book.ts +134 -48
  30. package/lib/implements/threaddb/lsstoreds/headbook.ts +48 -24
  31. package/lib/implements/threaddb/net/net.ts +18 -3
  32. package/lib/implements/wallet/manager.ts +4 -2
  33. package/lib/interfaces/components/news-component.ts +0 -0
  34. package/lib/modules/auth-module.ts +2 -2
  35. package/lib/modules/components/news-components.ts +390 -0
  36. package/package.json +1 -1
  37. package/dist/cjs/babel-tools-BWeUL20Q.js +0 -1
  38. package/dist/cjs/cache-DB5vOYUa.js +0 -1
  39. package/dist/cjs/helia-core-CGrygIE7.js +0 -1
  40. package/dist/cjs/polkadot-api-9SXYLDre.js +0 -1
  41. package/dist/cjs/protobuf-89JdugaK.js +0 -1
  42. package/dist/esm/chunks/babel-tools-CmeA0jUH.js +0 -1
  43. package/dist/esm/chunks/cache-NFMLvSTk.js +0 -1
  44. package/dist/esm/chunks/helia-core-BkEzHB9G.js +0 -1
  45. package/dist/esm/chunks/polkadot-api-BIp1_8eq.js +0 -1
  46. package/dist/esm/chunks/protobuf-De5gI78A.js +0 -1
@@ -0,0 +1 @@
1
+ import{e,j as t,g as r,d as n,f as i,_ as o,k as a,l as s,m as l,n as u,o as c,c as d,b as h,p as v,q as p,h as f,r as g,s as y,t as m,u as w}from"./babel-tools-sSecqeD4.js";var b=new Uint8Array(0);function S(e){var t=e.match(/../g);return null!=t?new Uint8Array(t.map((e=>parseInt(e,16)))):b}function E(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")}var k=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 i=0;i<e.length;i++){var o=e.charAt(i),a=o.charCodeAt(0);if(255!==r[a])throw new TypeError(o+" is ambiguous");r[a]=i}var s=e.length,l=e.charAt(0),u=Math.log(s)/Math.log(256),c=Math.log(256)/Math.log(s);function d(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,i=0;e[t]===l;)n++,t++;for(var o=(e.length-t)*u+1>>>0,a=new Uint8Array(o);e[t];){var c=r[e.charCodeAt(t)];if(255===c)return;for(var d=0,h=o-1;(0!==c||d<i)&&-1!==h;h--,d++)c+=s*a[h]>>>0,a[h]=c%256>>>0,c=c/256>>>0;if(0!==c)throw new Error("Non-zero carry");i=d,t++}if(" "!==e[t]){for(var v=o-i;v!==o&&0===a[v];)v++;for(var p=new Uint8Array(n+(o-v)),f=n;v!==o;)p[f++]=a[v++];return p}}}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,i=0,o=t.length;i!==o&&0===t[i];)i++,r++;for(var a=(o-i)*c+1>>>0,u=new Uint8Array(a);i!==o;){for(var d=t[i],h=0,v=a-1;(0!==d||h<n)&&-1!==v;v--,h++)d+=256*u[v]>>>0,u[v]=d%s>>>0,d=d/s>>>0;if(0!==d)throw new Error("Non-zero carry");n=h,i++}for(var p=a-n;p!==a&&0===u[p];)p++;for(var f=l.repeat(r);p<a;++p)f+=e.charAt(u[p]);return f},decodeUnsafe:d,decode:function(e){var r=d(e);if(r)return r;throw new Error("Non-".concat(t," character"))}}},x=k;let A=class{constructor(t,r,n){e(this,"name",void 0),e(this,"prefix",void 0),e(this,"baseEncode",void 0),this.name=t,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return"".concat(this.prefix).concat(this.baseEncode(e));throw Error("Unknown type, must be binary type")}},C=class{constructor(t,r,n){e(this,"name",void 0),e(this,"prefix",void 0),e(this,"baseDecode",void 0),e(this,"prefixCodePoint",void 0),this.name=t,this.prefix=r;var i=r.codePointAt(0);if(void 0===i)throw new Error("Invalid prefix character");this.prefixCodePoint=i,this.baseDecode=n}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error("Unable to decode multibase string ".concat(JSON.stringify(e),", ").concat(this.name," decoder only supports inputs prefixed with ").concat(this.prefix));return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return T(this,e)}};class I{constructor(t){e(this,"decoders",void 0),this.decoders=t}or(e){return T(this,e)}decode(e){var t=e[0],r=this.decoders[t];if(null!=r)return r.decode(e);throw RangeError("Unable to decode multibase string ".concat(JSON.stringify(e),", only inputs prefixed with ").concat(Object.keys(this.decoders)," are supported"))}}function T(e,r){var n,i;return new I(t(t({},null!==(n=e.decoders)&&void 0!==n?n:{[e.prefix]:e}),null!==(i=r.decoders)&&void 0!==i?i:{[r.prefix]:r}))}class P{constructor(t,r,n,i){e(this,"name",void 0),e(this,"prefix",void 0),e(this,"baseEncode",void 0),e(this,"baseDecode",void 0),e(this,"encoder",void 0),e(this,"decoder",void 0),this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new A(t,r,n),this.decoder=new C(t,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function _(e){var{name:t,prefix:r,encode:n,decode:i}=e;return new P(t,r,n,i)}function B(e){var{name:t,prefix:r,alphabet:n}=e,{encode:i,decode:o}=x(n,t);return _({prefix:r,name:t,encode:i,decode:e=>E(o(e))})}function N(e){var{name:t,prefix:r,bitsPerChar:n,alphabet:i}=e,o=function(e){for(var t={},r=0;r<e.length;++r)t[e[r]]=r;return t}(i);return _({prefix:r,name:t,encode:e=>function(e,t,r){for(var n="="===t[t.length-1],i=(1<<r)-1,o="",a=0,s=0,l=0;l<e.length;++l)for(s=s<<8|e[l],a+=8;a>r;)o+=t[i&s>>(a-=r)];if(0!==a&&(o+=t[i&s<<r-a]),n)for(;o.length*r&7;)o+="=";return o}(e,i,n),decode:e=>function(e,t,r,n){for(var i=e.length;"="===e[i-1];)--i;for(var o=new Uint8Array(i*r/8|0),a=0,s=0,l=0,u=0;u<i;++u){var c=t[e[u]];if(void 0===c)throw new SyntaxError("Non-".concat(n," character"));s=s<<r|c,(a+=r)>=8&&(a-=8,o[l++]=255&s>>a)}if(a>=r||255&s<<8-a)throw new SyntaxError("Unexpected end of data");return o}(e,o,n,t)})}var D=B({prefix:"9",name:"base10",alphabet:"0123456789"}),R=Object.freeze({__proto__:null,base10:D}),O=N({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),L=N({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),M=Object.freeze({__proto__:null,base16:O,base16upper:L}),U=N({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),F=Object.freeze({__proto__:null,base2:U}),z=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),j=z.reduce(((e,t,r)=>(e[r]=t,e)),[]),V=z.reduce(((e,t,r)=>{var n=t.codePointAt(0);if(null==n)throw new Error("Invalid character: ".concat(t));return e[n]=r,e}),[]);var q=_({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+=j[t]),"")},decode:function(e){var t=[];for(var r of e){var n=r.codePointAt(0);if(null==n)throw new Error("Invalid character: ".concat(r));var i=V[n];if(null==i)throw new Error("Non-base256emoji character: ".concat(r));t.push(i)}return new Uint8Array(t)}}),H=Object.freeze({__proto__:null,base256emoji:q}),K=N({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),W=N({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),G=N({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Q=N({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Y=N({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),J=N({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Z=N({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),$=N({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),X=N({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),ee=Object.freeze({__proto__:null,base32:K,base32hex:Y,base32hexpad:Z,base32hexpadupper:$,base32hexupper:J,base32pad:G,base32padupper:Q,base32upper:W,base32z:X}),te=B({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),re=B({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),ne=Object.freeze({__proto__:null,base36:te,base36upper:re}),ie=B({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),oe=B({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),ae=Object.freeze({__proto__:null,base58btc:ie,base58flickr:oe}),se=N({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),le=N({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ue=N({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ce=N({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),de=Object.freeze({__proto__:null,base64:se,base64pad:le,base64url:ue,base64urlpad:ce}),he=N({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),ve=Object.freeze({__proto__:null,base8:he}),pe=_({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)}),fe=Object.freeze({__proto__:null,identity:pe}),ge=new TextEncoder,ye=new TextDecoder,me=512;function we(e){return JSON.parse(ye.decode(e))}var be=Object.freeze({__proto__:null,code:512,decode:we,encode:function(e){return ge.encode(JSON.stringify(e))},name:"json"}),Se=85;var Ee=Object.freeze({__proto__:null,code:Se,decode:function(e){return E(e)},encode:function(e){return E(e)},name:"raw"}),ke=function e(t,r,n){r=r||[];var i=n=n||0;for(;t>=Ce;)r[n++]=255&t|xe,t/=128;for(;t&Ae;)r[n++]=255&t|xe,t>>>=7;return r[n]=0|t,e.bytes=n-i+1,r},xe=128,Ae=-128,Ce=Math.pow(2,31);var Ie=function e(t,r){var n,i=0,o=0,a=r=r||0,s=t.length;do{if(a>=s)throw e.bytes=0,new RangeError("Could not decode varint");n=t[a++],i+=o<28?(n&Pe)<<o:(n&Pe)*Math.pow(2,o),o+=7}while(n>=Te);return e.bytes=a-r,i},Te=128,Pe=127;var _e=Math.pow(2,7),Be=Math.pow(2,14),Ne=Math.pow(2,21),De=Math.pow(2,28),Re=Math.pow(2,35),Oe=Math.pow(2,42),Le=Math.pow(2,49),Me=Math.pow(2,56),Ue=Math.pow(2,63),Fe={encode:ke,decode:Ie,encodingLength:function(e){return e<_e?1:e<Be?2:e<Ne?3:e<De?4:e<Re?5:e<Oe?6:e<Le?7:e<Me?8:e<Ue?9:10}};function ze(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return[Fe.decode(e,t),Fe.decode.bytes]}function je(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return Fe.encode(e,t,r),t}function Ve(e){return Fe.encodingLength(e)}function qe(e,t){var r=t.byteLength,n=Ve(e),i=n+Ve(r),o=new Uint8Array(i+r);return je(e,o,0),je(r,o,n),o.set(t,i),new Ke(e,r,t,o)}function He(e){var t=E(e),[r,n]=ze(t),[i,o]=ze(t.subarray(n)),a=t.subarray(n+o);if(a.byteLength!==i)throw new Error("Incorrect length");return new Ke(r,i,a,t)}class Ke{constructor(t,r,n,i){e(this,"code",void 0),e(this,"size",void 0),e(this,"digest",void 0),e(this,"bytes",void 0),this.code=t,this.size=r,this.digest=n,this.bytes=i}}var We=E;var Ge={code:0,name:"identity",encode:We,digest:function(e){return qe(0,We(e))}},Qe=Object.freeze({__proto__:null,identity:Ge});function Ye(e){var{name:t,code:r,encode:n}=e;return new Je(t,r,n)}class Je{constructor(t,r,n){e(this,"name",void 0),e(this,"code",void 0),e(this,"encode",void 0),this.name=t,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){var t=this.encode(e);return t instanceof Uint8Array?qe(this.code,t):t.then((e=>qe(this.code,e)))}throw Error("Unknown type, must be binary type")}}function Ze(e){return function(){var t=r((function*(t){return new Uint8Array(yield crypto.subtle.digest(e,t))}));return function(e){return t.apply(this,arguments)}}()}var $e=Ye({name:"sha2-256",code:18,encode:Ze("SHA-256")}),Xe=Ye({name:"sha2-512",code:19,encode:Ze("SHA-512")}),et=Object.freeze({__proto__:null,sha256:$e,sha512:Xe});function tt(e,t){var{bytes:r,version:n}=e;return 0===n?function(e,t,r){var{prefix:n}=r;if(n!==ie.prefix)throw Error("Cannot string encode V0 in ".concat(r.name," encoding"));var i=t.get(n);if(null==i){var o=r.encode(e).slice(1);return t.set(n,o),o}return i}(r,nt(e),null!=t?t:ie.encoder):function(e,t,r){var{prefix:n}=r,i=t.get(n);if(null==i){var o=r.encode(e);return t.set(n,o),o}return i}(r,nt(e),null!=t?t:K.encoder)}var rt=new WeakMap;function nt(e){var t=rt.get(e);if(null==t){var r=new Map;return rt.set(e,r),r}return t}class it{constructor(t,r,n,i){e(this,"code",void 0),e(this,"version",void 0),e(this,"multihash",void 0),e(this,"bytes",void 0),e(this,"/",void 0),e(this,Symbol.toStringTag,"CID"),this.code=r,this.version=t,this.multihash=n,this.bytes=i,this["/"]=i}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:var{code:e,multihash:t}=this;if(e!==ot)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==at)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return it.createV0(t);default:throw Error("Can not convert CID version ".concat(this.version," to version 0. This is a bug please report"))}}toV1(){switch(this.version){case 0:var{code:e,digest:t}=this.multihash,r=qe(e,t);return it.createV1(this.code,r);case 1:return this;default:throw Error("Can not convert CID version ".concat(this.version," to version 1. This is a bug please report"))}}equals(e){return it.equals(this,e)}static equals(e,t){var r=t;return null!=r&&e.code===r.code&&e.version===r.version&&function(e,t){if(e===t)return!0;var 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(var 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 tt(this,e)}toJSON(){return{"/":tt(this)}}link(){return this}[Symbol.for("nodejs.util.inspect.custom")](){return"CID(".concat(this.toString(),")")}static asCID(e){if(null==e)return null;var t=e;if(t instanceof it)return t;if(null!=t["/"]&&t["/"]===t.bytes||t.asCID===t){var{version:r,code:n,multihash:i,bytes:o}=t;return new it(r,n,i,null!=o?o:st(r,n,i.bytes))}if(!0===t[lt]){var{version:a,multihash:s,code:l}=t,u=He(s);return it.create(a,l,u)}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!==ot)throw new Error("Version 0 CID must use dag-pb (code: ".concat(ot,") block encoding"));return new it(e,t,r,r.bytes);case 1:var n=st(e,t,r.bytes);return new it(e,t,r,n);default:throw new Error("Invalid version")}}static createV0(e){return it.create(0,ot,e)}static createV1(e,t){return it.create(1,e,t)}static decode(e){var[t,r]=it.decodeFirst(e);if(0!==r.length)throw new Error("Incorrect length");return t}static decodeFirst(e){var t=it.inspectBytes(e),r=t.size-t.multihashSize,n=E(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");var i=n.subarray(t.multihashSize-t.digestSize),o=new Ke(t.multihashCode,t.digestSize,i,n);return[0===t.version?it.createV0(o):it.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){var t=0,r=()=>{var[r,n]=ze(e.subarray(t));return t+=n,r},n=r(),i=ot;if(18===n?(n=0,t=0):i=r(),0!==n&&1!==n)throw new RangeError("Invalid CID version ".concat(n));var o=t,a=r(),s=r(),l=t+s;return{version:n,codec:i,multihashCode:a,digestSize:s,multihashSize:l-o,size:l}}static parse(e,t){var[r,n]=function(e,t){switch(e[0]){case"Q":var r=null!=t?t:ie;return[ie.prefix,r.decode("".concat(ie.prefix).concat(e))];case ie.prefix:var n=null!=t?t:ie;return[ie.prefix,n.decode(e)];case K.prefix:var i=null!=t?t:K;return[K.prefix,i.decode(e)];case te.prefix:var o=null!=t?t:te;return[te.prefix,o.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),i=it.decode(n);if(0===i.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return nt(i).set(r,e),i}}var ot=112,at=18;function st(e,t,r){var n=Ve(e),i=n+Ve(t),o=new Uint8Array(i+r.byteLength);return je(e,o,0),je(t,o,n),o.set(r,i),o}var lt=Symbol.for("@ipld/js-cid/CID"),ut=t(t(t(t(t(t(t(t(t(t({},fe),F),ve),R),M),ee),ne),ae),de),H);function ct(){return new Uint8Array(arguments.length>0&&void 0!==arguments[0]?arguments[0]:0)}function dt(){return new Uint8Array(arguments.length>0&&void 0!==arguments[0]?arguments[0]:0)}function ht(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}t(t({},et),Qe);var vt=ht("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),pt=ht("ascii","a",(e=>{for(var t="a",r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t}),(e=>{for(var t=dt((e=e.substring(1)).length),r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t})),ft=t({utf8:vt,"utf-8":vt,hex:ut.base16,latin1:pt,ascii:pt,binary:pt},ut);function gt(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8",r=ft[t];if(null==r)throw new Error('Unsupported encoding "'.concat(t,'"'));return r.encoder.encode(e).substring(1)}var yt=Object.freeze({__proto__:null,toString:gt});let mt=class extends Error{constructor(){super(...arguments),e(this,"name","InvalidMultiaddrError")}};e(mt,"name","InvalidMultiaddrError");class wt extends Error{constructor(){super(...arguments),e(this,"name","ValidationError")}}e(wt,"name","ValidationError");let bt=class extends Error{constructor(){super(...arguments),e(this,"name","InvalidParametersError")}};e(bt,"name","InvalidParametersError");class St extends Error{constructor(){super(...arguments),e(this,"name","UnknownProtocolError")}}function Et(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(var r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}e(St,"name","UnknownProtocolError");var kt=Object.freeze({__proto__:null,equals:Et});function xt(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8",r=ft[t];if(null==r)throw new Error('Unsupported encoding "'.concat(t,'"'));return r.decoder.decode("".concat(r.prefix).concat(e))}var At=Object.freeze({__proto__:null,fromString:xt}),Ct=Math.pow(2,7),It=Math.pow(2,14),Tt=Math.pow(2,21),Pt=Math.pow(2,28),_t=Math.pow(2,35),Bt=Math.pow(2,42),Nt=Math.pow(2,49),Dt=128,Rt=127;function Ot(e){if(e<Ct)return 1;if(e<It)return 2;if(e<Tt)return 3;if(e<Pt)return 4;if(e<_t)return 5;if(e<Bt)return 6;if(e<Nt)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Lt(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;switch(Ot(e)){case 8:t[r++]=255&e|Dt,e/=128;case 7:t[r++]=255&e|Dt,e/=128;case 6:t[r++]=255&e|Dt,e/=128;case 5:t[r++]=255&e|Dt,e/=128;case 4:t[r++]=255&e|Dt,e>>>=7;case 3:t[r++]=255&e|Dt,e>>>=7;case 2:t[r++]=255&e|Dt,e>>>=7;case 1:t[r++]=255&e,e>>>=7;break;default:throw new Error("unreachable")}return t}function Mt(e,t){var r=e[t],n=0;if(n+=r&Rt,r<Dt)return n;if(n+=((r=e[t+1])&Rt)<<7,r<Dt)return n;if(n+=((r=e[t+2])&Rt)<<14,r<Dt)return n;if(n+=((r=e[t+3])&Rt)<<21,r<Dt)return n;if(n+=((r=e[t+4])&Rt)*Pt,r<Dt)return n;if(n+=((r=e[t+5])&Rt)*_t,r<Dt)return n;if(n+=((r=e[t+6])&Rt)*Bt,r<Dt)return n;if(n+=((r=e[t+7])&Rt)*Nt,r<Dt)return n;throw new RangeError("Could not decode varint")}function Ut(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return null==t&&(t=dt(Ot(e))),t instanceof Uint8Array?Lt(e,t,r):function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;switch(Ot(e)){case 8:t.set(r++,255&e|Dt),e/=128;case 7:t.set(r++,255&e|Dt),e/=128;case 6:t.set(r++,255&e|Dt),e/=128;case 5:t.set(r++,255&e|Dt),e/=128;case 4:t.set(r++,255&e|Dt),e>>>=7;case 3:t.set(r++,255&e|Dt),e>>>=7;case 2:t.set(r++,255&e|Dt),e>>>=7;case 1:t.set(r++,255&e),e>>>=7;break;default:throw new Error("unreachable")}return t}(e,t,r)}function Ft(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return e instanceof Uint8Array?Mt(e,t):function(e,t){var r=e.get(t),n=0;if(n+=r&Rt,r<Dt)return n;if(n+=((r=e.get(t+1))&Rt)<<7,r<Dt)return n;if(n+=((r=e.get(t+2))&Rt)<<14,r<Dt)return n;if(n+=((r=e.get(t+3))&Rt)<<21,r<Dt)return n;if(n+=((r=e.get(t+4))&Rt)*Pt,r<Dt)return n;if(n+=((r=e.get(t+5))&Rt)*_t,r<Dt)return n;if(n+=((r=e.get(t+6))&Rt)*Bt,r<Dt)return n;if(n+=((r=e.get(t+7))&Rt)*Nt,r<Dt)return n;throw new RangeError("Could not decode varint")}(e,t)}function zt(e,t){null==t&&(t=e.reduce(((e,t)=>e+t.length),0));var r=dt(t),n=0;for(var i of e)r.set(i,n),n+=i.length;return r}var jt=Object.freeze({__proto__:null,concat:zt});var Vt=new class{constructor(){e(this,"index",0),e(this,"input","")}new(e){return this.index=0,this.input=e,this}readAtomically(e){var t=this.index,r=e();return void 0===r&&(this.index=t),r}parseWith(e){var 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((()=>{var 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((()=>{var i=0,o=0,a=this.peekChar();if(void 0!==a){for(var s="0"===a,l=2**(8*n)-1;;){var u=this.readAtomically((()=>{var t=this.readChar();if(void 0!==t){var r=Number.parseInt(t,e);if(!Number.isNaN(r))return r}}));if(void 0===u)break;if(i*=e,(i+=u)>l)return;if(o+=1,void 0!==t&&o>t)return}return 0===o||!r&&s&&o>1?void 0:i}}))}readIPv4Addr(){return this.readAtomically((()=>{for(var e=new Uint8Array(4),t=0;t<e.length;t++){var r=this.readSeparator(".",t,(()=>this.readNumber(10,3,!1,1)));if(void 0===r)return;e[t]=r}return e}))}readIPv6Addr(){var e=e=>{for(var t=0;t<e.length/2;t++){var r=2*t;if(t<e.length-3){var 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]}var i=this.readSeparator(":",t,(()=>this.readNumber(16,4,!0,2)));if(void 0===i)return[r,!1];e[r]=i>>8,e[r+1]=255&i}return[e.length,!1]};return this.readAtomically((()=>{var t=new Uint8Array(16),[r,n]=e(t);if(16===r)return t;if(!n&&void 0!==this.readGivenChar(":")&&void 0!==this.readGivenChar(":")){var i=new Uint8Array(14),o=16-(r+2),[a]=e(i.subarray(0,o));return t.set(i.subarray(0,a),16-a),t}}))}readIPAddr(){var e;return null!==(e=this.readIPv4Addr())&&void 0!==e?e:this.readIPv6Addr()}};function qt(e){if(!(e.length>15))return Vt.new(e).parseWith((()=>Vt.readIPv4Addr()))}function Ht(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return Vt.new(e).parseWith((()=>Vt.readIPv6Addr()))}function Kt(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45)){var r=Vt.new(e).parseWith((()=>Vt.readIPAddr()));if(r)return 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}}function Wt(e){return Boolean(qt(e))}function Gt(e){return Boolean(Ht(e))}function Qt(e){return t=>gt(t,e)}function Yt(e){return t=>xt(t,e)}function Jt(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function Zt(e){var t=new ArrayBuffer(2);return new DataView(t).setUint16(0,"string"==typeof e?parseInt(e):e),new Uint8Array(t)}function $t(e){var t=e.subarray(0,e.length-2),r=e.subarray(e.length-2),n=gt(t,"base32"),i=Jt(r);return"".concat(n,":").concat(i)}var Xt=function(e){e=e.toString().trim();var t=new Uint8Array(4);return e.split(/\./g).forEach(((e,r)=>{var n=parseInt(e,10);if(isNaN(n)||n<0||n>255)throw new mt("Invalid byte value in IP address");t[r]=n})),t};var er,tr=Object.values(ut).map((e=>e.decoder)),rr=(er=tr[0].or(tr[1]),tr.slice(2).forEach((e=>er=er.or(e))),er);var nr,ir=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return e=>{for(var r of t)r(e)}}((function(e){if(parseInt(e).toString()!==e)throw new wt("Value must be an integer")}),(function(e){if(e<0)throw new wt("Value must be a positive integer, or zero")}),(nr=65535,e=>{if(e>nr)throw new wt("Value must be smaller than or equal to ".concat(nr))})),or=-1;var ar=new class{constructor(){e(this,"protocolsByCode",new Map),e(this,"protocolsByName",new Map)}getProtocol(e){var t;if(null==(t="string"==typeof e?this.protocolsByName.get(e):this.protocolsByCode.get(e)))throw new St("Protocol ".concat(e," was unknown"));return t}addProtocol(e){var t;this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),null===(t=e.aliases)||void 0===t||t.forEach((t=>{this.protocolsByName.set(t,e)}))}removeProtocol(e){var t,r=this.protocolsByCode.get(e);null!=r&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),null===(t=r.aliases)||void 0===t||t.forEach((e=>{this.protocolsByName.delete(e)})))}},sr=[{code:4,name:"ip4",size:32,valueToBytes:Xt,bytesToValue:function(e){if(4!==e.byteLength)throw new mt("IPv4 address was incorrect length");for(var t=[],r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},validate:e=>{if(!Wt(e))throw new wt('Invalid IPv4 address "'.concat(e,'"'))}},{code:6,name:"tcp",size:16,valueToBytes:Zt,bytesToValue:Jt,validate:ir},{code:273,name:"udp",size:16,valueToBytes:Zt,bytesToValue:Jt,validate:ir},{code:33,name:"dccp",size:16,valueToBytes:Zt,bytesToValue:Jt,validate:ir},{code:41,name:"ip6",size:128,valueToBytes:function(e){var t,r=0,n=(e=e.toString().trim()).split(":",8);for(t=0;t<n.length;t++){var i=void 0;Wt(n[t])&&(i=Xt(n[t]),n[t]=gt(i.subarray(0,2),"base16")),null!=i&&++t<8&&n.splice(t,0,gt(i.subarray(2,4),"base16"))}if(""===n[0])for(;n.length<8;)n.unshift("0");else if(""===n[n.length-1])for(;n.length<8;)n.push("0");else if(n.length<8){for(t=0;t<n.length&&""!==n[t];t++);var o=[t,1];for(t=9-n.length;t>0;t--)o.push("0");n.splice.apply(n,o)}var a=new Uint8Array(r+16);for(t=0;t<n.length;t++){""===n[t]&&(n[t]="0");var s=parseInt(n[t],16);if(isNaN(s)||s<0||s>65535)throw new mt("Invalid byte value in IP address");a[r++]=s>>8&255,a[r++]=255&s}return a},bytesToValue:function(e){if(16!==e.byteLength)throw new mt("IPv6 address was incorrect length");for(var t=[],r=0;r<e.byteLength;r+=2){var n=e[r],i=e[r+1],o="".concat(n.toString(16).padStart(2,"0")).concat(i.toString(16).padStart(2,"0"));t.push(o)}var a=t.join(":");try{var s=new URL("http://[".concat(a,"]"));return s.hostname.substring(1,s.hostname.length-1)}catch(e){throw new mt('Invalid IPv6 address "'.concat(a,'"'))}},stringToValue:function(e){try{var t=new URL("http://[".concat(e,"]"));return t.hostname.substring(1,t.hostname.length-1)}catch(t){throw new mt('Invalid IPv6 address "'.concat(e,'"'))}},validate:e=>{if(!Gt(e))throw new wt('Invalid IPv6 address "'.concat(e,'"'))}},{code:42,name:"ip6zone",size:or},{code:43,name:"ipcidr",size:8,bytesToValue:Qt("base10"),valueToBytes:Yt("base10")},{code:53,name:"dns",size:or,resolvable:!0},{code:54,name:"dns4",size:or,resolvable:!0},{code:55,name:"dns6",size:or,resolvable:!0},{code:56,name:"dnsaddr",size:or,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Zt,bytesToValue:Jt,validate:ir},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:or,path:!0,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:or,bytesToValue:Qt("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?Yt("base58btc")(e):it.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:$t,valueToBytes:function(e){var t=e.split(":");if(2!==t.length)throw new Error("failed to parse onion addr: [\"'".concat(t.join('", "'),"'\"]' does not contain a port number"));if(16!==t[0].length)throw new Error("failed to parse onion addr: ".concat(t[0]," not a Tor onion address."));var 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)");var i=Zt(n);return zt([r,i],r.length+i.length)}},{code:445,name:"onion3",size:296,bytesToValue:$t,valueToBytes:function(e){var t=e.split(":");if(2!==t.length)throw new Error("failed to parse onion addr: [\"'".concat(t.join('", "'),"'\"]' does not contain a port number"));if(56!==t[0].length)throw new Error("failed to parse onion addr: ".concat(t[0]," not a Tor onion3 address."));var r=K.decode("b".concat(t[0])),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");var i=Zt(n);return zt([r,i],r.length+i.length)}},{code:446,name:"garlic64",size:or},{code:447,name:"garlic32",size:or},{code:448,name:"tls"},{code:449,name:"sni",size:or},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:or,bytesToValue:function(e){return t=>e.encoder.encode(t)}(ue),valueToBytes:function(e){return rr.decode(e)}},{code:480,name:"http"},{code:481,name:"http-path",size:or,stringToValue:e=>"/".concat(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:or}];function lr(e,t,r){return null==e.size||0===e.size?0:e.size>0?e.size/8:Ft(t,r)}sr.forEach((e=>{ar.addProtocol(e)}));var ur=Symbol.for("nodejs.util.inspect.custom"),cr=Symbol.for("@multiformats/multiaddr"),dr=[53,54,55,56];class hr extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No available resolver"),this.name="NoAvailableResolverError"}}function vr(e){if(null==e&&(e="/"),Cr(e))return e.getComponents();if(e instanceof Uint8Array)return function(e){for(var t=[],r=0;r<e.length;){var n=Ft(e,r),i=ar.getProtocol(n),o=Ot(n),a=lr(i,e,r+o),s=0;a>0&&i.size===or&&(s=Ot(a));var l=o+s+a,u={code:n,name:i.name,bytes:e.subarray(r,r+l)};if(a>0){var c,d,h=r+o+s,v=e.subarray(h,h+a);u.value=null!==(c=null===(d=i.bytesToValue)||void 0===d?void 0:d.call(i,v))&&void 0!==c?c:gt(v)}t.push(u),r+=l}return t}(e);if("string"==typeof e)return""===(e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""))&&(e="/"),function(e){if("/"!==e.charAt(0))throw new mt('String multiaddr must start with "/"');for(var t=[],r="protocol",n="",i="",o=1;o<e.length;o++){var a=e.charAt(o);"/"!==a&&("protocol"===r?i+=e.charAt(o):n+=e.charAt(o));var s=o===e.length-1;if("/"===a||s){var l=ar.getProtocol(i);if("protocol"===r){if(null==l.size||0===l.size){t.push({code:l.code,name:l.name}),n="",i="",r="protocol";continue}if(s)throw new mt("Component ".concat(i," was missing value"));r="value"}else if("value"===r){var u={code:l.code,name:l.name};if(null!=l.size&&0!==l.size){var c,d;if(""===n)throw new mt("Component ".concat(i," was missing value"));u.value=null!==(c=null===(d=l.stringToValue)||void 0===d?void 0:d.call(l,n))&&void 0!==c?c:n}t.push(u),n="",i="",r="protocol"}}}if(""!==i&&""!==n)throw new mt("Incomplete multiaddr");return t}(e);if(Array.isArray(e))return e;throw new mt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var pr=new WeakMap,fr=new WeakMap,gr=new WeakMap;class yr{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/",r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,cr,!0),n(this,pr,void 0),n(this,fr,void 0),n(this,gr,void 0),i(pr,this,vr(t)),!1!==r.validate&&function(e){e.getComponents().forEach((e=>{var t,r=ar.getProtocol(e.code);null!=e.value&&(null===(t=r.validate)||void 0===t||t.call(r,e.value))}))}(this)}get bytes(){return null==o(gr,this)&&i(gr,this,function(e){var t=0,r=[];for(var n of e){if(null==n.bytes){var i,o,a=ar.getProtocol(n.code),s=Ot(n.code),l=void 0,u=0,c=0;null!=n.value&&(u=(l=null!==(i=null===(o=a.valueToBytes)||void 0===o?void 0:o.call(a,n.value))&&void 0!==i?i:xt(n.value)).byteLength,a.size===or&&(c=Ot(u)));var d=new Uint8Array(s+c+u),h=0;Lt(n.code,d,h),h+=s,null!=l&&(a.size===or&&(Lt(u,d,h),h+=c),d.set(l,h)),n.bytes=d}r.push(n.bytes),t+=n.bytes.byteLength}return zt(r,t)}(o(pr,this))),o(gr,this)}toString(){var e;return null==o(fr,this)&&i(fr,this,(e=o(pr,this),"/".concat(e.flatMap((e=>{var t,r;if(null==e.value)return e.name;var n=ar.getProtocol(e.code);if(null==n)throw new mt("Unknown protocol code ".concat(e.code));return[e.name,null!==(t=null===(r=n.valueToString)||void 0===r?void 0:r.call(n,e.value))&&void 0!==t?t:e.value]})).join("/")))),o(fr,this)}toJSON(){return this.toString()}toOptions(){var e,t,r,n,i="";for(var{code:a,name:s,value:l}of o(pr,this))42===a&&(i="%".concat(null!=l?l:"")),dr.includes(a)&&(t="tcp",n=443,r="".concat(null!=l?l:"").concat(i),e=55===a?6:4),6!==a&&273!==a||(t="tcp"===s?"tcp":"udp",n=parseInt(null!=l?l:"")),4!==a&&41!==a||(t="tcp",r="".concat(null!=l?l:"").concat(i),e=41===a?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[...o(pr,this)]}protos(){return o(pr,this).map((e=>{var t,{code:r,value:n}=e,i=ar.getProtocol(r);return{code:r,size:null!==(t=i.size)&&void 0!==t?t:0,name:i.name,resolvable:Boolean(i.resolvable),path:Boolean(i.path)}}))}protoCodes(){return o(pr,this).map((e=>{var{code:t}=e;return t}))}protoNames(){return o(pr,this).map((e=>{var{name:t}=e;return t}))}tuples(){return o(pr,this).map((e=>{var{code:t,value:r}=e;if(null==r)return[t];var n,i,o=ar.getProtocol(t),a=[t];null!=r&&a.push(null!==(n=null===(i=o.valueToBytes)||void 0===i?void 0:i.call(o,r))&&void 0!==n?n:xt(r));return a}))}stringTuples(){return o(pr,this).map((e=>{var{code:t,value:r}=e;return null==r?[t]:[t,r]}))}encapsulate(e){var t=new yr(e);return new yr([...o(pr,this),...t.getComponents()],{validate:!1})}decapsulate(e){var t=e.toString(),r=this.toString(),n=r.lastIndexOf(t);if(n<0)throw new bt("Address ".concat(this.toString()," does not contain subaddress: ").concat(e.toString()));return new yr(r.slice(0,n),{validate:!1})}decapsulateCode(e){for(var t,r=o(pr,this).length-1;r>-1;r--)if(o(pr,this)[r].code===e){t=r;break}return new yr(o(pr,this).slice(0,t),{validate:!1})}getPeerId(){try{var e=[];o(pr,this).forEach((t=>{var{code:r,value:n}=t;421===r&&e.push([r,n]),290===r&&(e=[])}));var t=e.pop();if(null!=(null==t?void 0:t[1])){var r=t[1];return"Q"===r[0]||"1"===r[0]?gt(ie.decode("z".concat(r)),"base58btc"):gt(it.parse(r).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){for(var e of o(pr,this)){var t;if(ar.getProtocol(e.code).path)return null!==(t=e.value)&&void 0!==t?t:null}return null}equals(e){return Et(this.bytes,e.bytes)}resolve(e){var t=this;return r((function*(){var r=t.protos().find((e=>e.resolvable));if(null==r)return[t];var n=xr.get(r.name);if(null==n)throw new hr("no available resolver for ".concat(r.name));return(yield n(t,e)).map((e=>Ir(e)))}))()}nodeAddress(){var e=this.toOptions();if("tcp"!==e.transport&&"udp"!==e.transport)throw new Error('multiaddr must have a valid format - no protocol with name: "'.concat(e.transport,'". Must have a valid transport protocol: "{tcp, udp}"'));return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(){return 2===o(pr,this).length&&((4===o(pr,this)[0].code||41===o(pr,this)[0].code)&&(6===o(pr,this)[1].code||273===o(pr,this)[1].code))}[ur](){return"Multiaddr(".concat(this.toString(),")")}}var mr=4,wr=16,br=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Sr(e,t){t.length===wr&&e.length===mr&&function(e,t,r){var n=0;for(var i of e)if(!(n<t)){if(n>r)break;if(255!==i)return!1;n++}return!0}(t,0,11)&&(t=t.slice(12)),t.length===mr&&e.length===wr&&function(e,t,r,n){var i=0;for(var o of e)if(!(i<r)){if(i>n)break;if(o!==t[i])return!1;i++}return!0}(e,br,0,11)&&(e=e.slice(12));var r=e.length;if(r!=t.length)throw new Error("Failed to mask ip");for(var n=new Uint8Array(r),i=0;i<r;i++)n[i]=e[i]&t[i];return n}function Er(e,t){if(t!==8*mr&&t!==8*wr)throw new Error("Invalid CIDR mask");if(e<0||e>t)throw new Error("Invalid CIDR mask");for(var r=t/8,n=new Uint8Array(r),i=0;i<r;i++)e>=8?(n[i]=255,e-=8):(n[i]=255-(255>>e),e=0);return n}class kr{constructor(e,t){if(null==t)({network:this.network,mask:this.mask}=function(e){var[t,r]=e.split("/");if(!t||!r)throw new Error("Failed to parse given CIDR: "+e);var n=mr,i=qt(t);if(null==i&&(n=wr,null==(i=Ht(t))))throw new Error("Failed to parse given CIDR: "+e);var o=parseInt(r,10);if(Number.isNaN(o)||String(o).length!==r.length||o<0||o>8*n)throw new Error("Failed to parse given CIDR: "+e);var a=Er(o,8*n);return{network:Sr(i,a),mask:a}}(e));else{var r=Kt(e);if(null==r)throw new Error("Failed to parse network");t=String(t);var n=parseInt(t,10);if(Number.isNaN(n)||String(n).length!==t.length||n<0||n>8*r.length){var i=Kt(t);if(null==i)throw new Error("Failed to parse mask");this.mask=i}else this.mask=Er(n,8*r.length);this.network=Sr(r,this.mask)}}contains(e){return function(e,t){if("string"==typeof t&&(t=Kt(t)),null==t)throw new Error("Invalid ip");if(t.length!==e.network.length)return!1;for(var 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(){var e=function(e){var t=0;for(var[r,n]of e.entries()){if(255!==n){for(;128&n;)t++,n<<=1;if(128&n)return-1;for(var i=r+1;i<e.length;i++)if(0!=e[i])return-1;break}t+=8}return t}(this.mask),t=-1!==e?String(e):function(e){var t="0x";for(var r of e)t+=(r>>4).toString(16)+(15&r).toString(16);return t}(this.mask);return function(e){switch(e.length){case mr:return e.join(".");case wr:for(var t=[],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}}var xr=new Map;function Ar(e){return!!Cr(e)&&e.protos().some((e=>e.resolvable))}function Cr(e){return Boolean(null==e?void 0:e[cr])}function Ir(e){return new yr(e)}function Tr(e){var t,r=ar.getProtocol(e);return{code:r.code,size:null!==(t=r.size)&&void 0!==t?t:0,name:r.name,resolvable:Boolean(r.resolvable),path:Boolean(r.path)}}var Pr="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function _r(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Br(e){if(!((t=e)instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name))throw new Error("Uint8Array expected");for(var t,r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];if(n.length>0&&!n.includes(e.length))throw new Error("Uint8Array expected of length "+n+", got length="+e.length)}function Nr(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");_r(e.outputLen),_r(e.blockLen)}function Dr(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];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 Rr(e,t){Br(e);var r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Or(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Lr(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];for(var n=0;n<t.length;n++)t[n].fill(0)}function Mr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ur(e,t){return e<<32-t|e>>>t}function Fr(e,t){return e<<t|e>>>32-t>>>0}var zr=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function jr(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}var Vr=zr?e=>e:e=>jr(e);var qr=zr?e=>e:function(e){for(var t=0;t<e.length;t++)e[t]=jr(e[t]);return e},Hr=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Kr=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Wr(e){if(Br(e),Hr)return e.toHex();for(var t="",r=0;r<e.length;r++)t+=Kr[e[r]];return t}var Gr=48,Qr=57,Yr=65,Jr=70,Zr=97,$r=102;function Xr(e){return e>=Gr&&e<=Qr?e-Gr:e>=Yr&&e<=Jr?e-(Yr-10):e>=Zr&&e<=$r?e-(Zr-10):void 0}function en(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Hr)return Uint8Array.fromHex(e);var t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);for(var n=new Uint8Array(r),i=0,o=0;i<r;i++,o+=2){var a=Xr(e.charCodeAt(o)),s=Xr(e.charCodeAt(o+1));if(void 0===a||void 0===s){var l=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+l+'" at index '+o)}n[i]=16*a+s}return n}var tn=function(){var e=r((function*(){}));return function(){return e.apply(this,arguments)}}();function rn(){return rn=r((function*(e,t,r){for(var n=Date.now(),i=0;i<e;i++){r(i);var o=Date.now()-n;o>=0&&o<t||(yield tn(),n+=o)}})),rn.apply(this,arguments)}function nn(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function on(e){return"string"==typeof e&&(e=nn(e)),Br(e),e}function an(e){return"string"==typeof e&&(e=nn(e)),Br(e),e}function sn(){for(var e=0,t=0;t<arguments.length;t++){var r=t<0||arguments.length<=t?void 0:arguments[t];Br(r),e+=r.length}for(var n=new Uint8Array(e),i=0,o=0;i<arguments.length;i++){var a=i<0||arguments.length<=i?void 0:arguments[i];n.set(a,o),o+=a.length}return n}class ln{}function un(e){var t=t=>e().update(on(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function cn(e){var t=(t,r)=>e(r).update(on(t)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}function dn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:32;if(Pr&&"function"==typeof Pr.getRandomValues)return Pr.getRandomValues(new Uint8Array(e));if(Pr&&"function"==typeof Pr.randomBytes)return Uint8Array.from(Pr.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function hn(e,t,r){return e&t^~e&r}function vn(e,t,r){return e&t^e&r^t&r}class pn extends ln{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=Mr(this.buffer)}update(e){Dr(this),Br(e=on(e));for(var{view:t,buffer:r,blockLen:n}=this,i=e.length,o=0;o<i;){var a=Math.min(n-this.pos,i-o);if(a!==n)r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(t,0),this.pos=0);else for(var s=Mr(e);n<=i-o;o+=n)this.process(s,o)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Dr(this),Rr(e,this),this.finished=!0;var{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,Lr(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(r,0),o=0);for(var a=o;a<n;a++)t[a]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);var i=BigInt(32),o=BigInt(4294967295),a=Number(r>>i&o),s=Number(r&o),l=n?4:0,u=n?0:4;e.setUint32(t+l,a,n),e.setUint32(t+u,s,n)}(r,n-8,BigInt(8*this.length),i),this.process(r,0);var s=Mr(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");var u=l/4,c=this.get();if(u>c.length)throw new Error("_sha2: outputLen bigger than state");for(var d=0;d<u;d++)s.setUint32(4*d,c[d],i)}digest(){var{buffer:e,outputLen:t}=this;this.digestInto(e);var r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());var{blockLen:t,buffer:r,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}var fn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),gn=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),yn=BigInt(2**32-1),mn=BigInt(32);function wn(e){return arguments.length>1&&void 0!==arguments[1]&&arguments[1]?{h:Number(e&yn),l:Number(e>>mn&yn)}:{h:0|Number(e>>mn&yn),l:0|Number(e&yn)}}function bn(e){for(var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=e.length,n=new Uint32Array(r),i=new Uint32Array(r),o=0;o<r;o++){var{h:a,l:s}=wn(e[o],t);[n[o],i[o]]=[a,s]}return[n,i]}var Sn=(e,t,r)=>e>>>r,En=(e,t,r)=>e<<32-r|t>>>r,kn=(e,t,r)=>e>>>r|t<<32-r,xn=(e,t,r)=>e<<32-r|t>>>r,An=(e,t,r)=>e<<64-r|t>>>r-32,Cn=(e,t,r)=>e>>>r-32|t<<64-r,In=(e,t)=>t,Tn=(e,t)=>e,Pn=(e,t,r)=>e<<r|t>>>32-r,_n=(e,t,r)=>t<<r|e>>>32-r,Bn=(e,t,r)=>t<<r-32|e>>>64-r,Nn=(e,t,r)=>e<<r-32|t>>>64-r;function Dn(e,t,r,n){var i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:0|i}}var Rn=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),On=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,Ln=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Mn=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,Un=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Fn=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,zn=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]),jn=new Uint32Array(64);class Vn extends pn{constructor(){super(64,arguments.length>0&&void 0!==arguments[0]?arguments[0]:32,8,!1),this.A=0|fn[0],this.B=0|fn[1],this.C=0|fn[2],this.D=0|fn[3],this.E=0|fn[4],this.F=0|fn[5],this.G=0|fn[6],this.H=0|fn[7]}get(){var{A:e,B:t,C:r,D:n,E:i,F:o,G:a,H:s}=this;return[e,t,r,n,i,o,a,s]}set(e,t,r,n,i,o,a,s){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|i,this.F=0|o,this.G=0|a,this.H=0|s}process(e,t){for(var r=0;r<16;r++,t+=4)jn[r]=e.getUint32(t,!1);for(var n=16;n<64;n++){var i=jn[n-15],o=jn[n-2],a=Ur(i,7)^Ur(i,18)^i>>>3,s=Ur(o,17)^Ur(o,19)^o>>>10;jn[n]=s+jn[n-7]+a+jn[n-16]|0}for(var{A:l,B:u,C:c,D:d,E:h,F:v,G:p,H:f}=this,g=0;g<64;g++){var y=f+(Ur(h,6)^Ur(h,11)^Ur(h,25))+hn(h,v,p)+zn[g]+jn[g]|0,m=(Ur(l,2)^Ur(l,13)^Ur(l,22))+vn(l,u,c)|0;f=p,p=v,v=h,h=d+y|0,d=c,c=u,u=l,l=y+m|0}l=l+this.A|0,u=u+this.B|0,c=c+this.C|0,d=d+this.D|0,h=h+this.E|0,v=v+this.F|0,p=p+this.G|0,f=f+this.H|0,this.set(l,u,c,d,h,v,p,f)}roundClean(){Lr(jn)}destroy(){this.set(0,0,0,0,0,0,0,0),Lr(this.buffer)}}var qn=(()=>bn(["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)))))(),Hn=(()=>qn[0])(),Kn=(()=>qn[1])(),Wn=new Uint32Array(80),Gn=new Uint32Array(80);class Qn extends pn{constructor(){super(128,arguments.length>0&&void 0!==arguments[0]?arguments[0]:64,16,!1),this.Ah=0|gn[0],this.Al=0|gn[1],this.Bh=0|gn[2],this.Bl=0|gn[3],this.Ch=0|gn[4],this.Cl=0|gn[5],this.Dh=0|gn[6],this.Dl=0|gn[7],this.Eh=0|gn[8],this.El=0|gn[9],this.Fh=0|gn[10],this.Fl=0|gn[11],this.Gh=0|gn[12],this.Gl=0|gn[13],this.Hh=0|gn[14],this.Hl=0|gn[15]}get(){var{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:o,Dh:a,Dl:s,Eh:l,El:u,Fh:c,Fl:d,Gh:h,Gl:v,Hh:p,Hl:f}=this;return[e,t,r,n,i,o,a,s,l,u,c,d,h,v,p,f]}set(e,t,r,n,i,o,a,s,l,u,c,d,h,v,p,f){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|i,this.Cl=0|o,this.Dh=0|a,this.Dl=0|s,this.Eh=0|l,this.El=0|u,this.Fh=0|c,this.Fl=0|d,this.Gh=0|h,this.Gl=0|v,this.Hh=0|p,this.Hl=0|f}process(e,t){for(var r=0;r<16;r++,t+=4)Wn[r]=e.getUint32(t),Gn[r]=e.getUint32(t+=4);for(var n=16;n<80;n++){var i=0|Wn[n-15],o=0|Gn[n-15],a=kn(i,o,1)^kn(i,o,8)^Sn(i,0,7),s=xn(i,o,1)^xn(i,o,8)^En(i,o,7),l=0|Wn[n-2],u=0|Gn[n-2],c=kn(l,u,19)^An(l,u,61)^Sn(l,0,6),d=xn(l,u,19)^Cn(l,u,61)^En(l,u,6),h=Ln(s,d,Gn[n-7],Gn[n-16]),v=Mn(h,a,c,Wn[n-7],Wn[n-16]);Wn[n]=0|v,Gn[n]=0|h}for(var{Ah:p,Al:f,Bh:g,Bl:y,Ch:m,Cl:w,Dh:b,Dl:S,Eh:E,El:k,Fh:x,Fl:A,Gh:C,Gl:I,Hh:T,Hl:P}=this,_=0;_<80;_++){var B=kn(E,k,14)^kn(E,k,18)^An(E,k,41),N=xn(E,k,14)^xn(E,k,18)^Cn(E,k,41),D=E&x^~E&C,R=Un(P,N,k&A^~k&I,Kn[_],Gn[_]),O=Fn(R,T,B,D,Hn[_],Wn[_]),L=0|R,M=kn(p,f,28)^An(p,f,34)^An(p,f,39),U=xn(p,f,28)^Cn(p,f,34)^Cn(p,f,39),F=p&g^p&m^g&m,z=f&y^f&w^y&w;T=0|C,P=0|I,C=0|x,I=0|A,x=0|E,A=0|k,({h:E,l:k}=Dn(0|b,0|S,0|O,0|L)),b=0|m,S=0|w,m=0|g,w=0|y,g=0|p,y=0|f;var j=Rn(L,U,z);p=On(j,O,M,F),f=0|j}({h:p,l:f}=Dn(0|this.Ah,0|this.Al,0|p,0|f)),({h:g,l:y}=Dn(0|this.Bh,0|this.Bl,0|g,0|y)),({h:m,l:w}=Dn(0|this.Ch,0|this.Cl,0|m,0|w)),({h:b,l:S}=Dn(0|this.Dh,0|this.Dl,0|b,0|S)),({h:E,l:k}=Dn(0|this.Eh,0|this.El,0|E,0|k)),({h:x,l:A}=Dn(0|this.Fh,0|this.Fl,0|x,0|A)),({h:C,l:I}=Dn(0|this.Gh,0|this.Gl,0|C,0|I)),({h:T,l:P}=Dn(0|this.Hh,0|this.Hl,0|T,0|P)),this.set(p,f,g,y,m,w,b,S,E,k,x,A,C,I,T,P)}roundClean(){Lr(Wn,Gn)}destroy(){Lr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}var Yn=un((()=>new Vn)),Jn=un((()=>new Qn));class Zn extends ln{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Nr(e);var r=on(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;var n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(var o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(var a=0;a<i.length;a++)i[a]^=106;this.oHash.update(i),Lr(i)}update(e){return Dr(this),this.iHash.update(e),this}digestInto(e){Dr(this),Br(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){var e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));var{oHash:t,iHash:r,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,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()}}var $n=(e,t,r)=>new Zn(e,t).update(r).digest();$n.create=(e,t)=>new Zn(e,t);var Xn=BigInt(0),ei=BigInt(1);function ti(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function ri(e){if(!ti(e))throw new Error("Uint8Array expected")}function ni(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}function ii(e){var t=e.toString(16);return 1&t.length?"0"+t:t}function oi(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Xn:BigInt("0x"+e)}var ai="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,si=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function li(e){if(ri(e),ai)return e.toHex();for(var t="",r=0;r<e.length;r++)t+=si[e[r]];return t}var ui=48,ci=57,di=65,hi=70,vi=97,pi=102;function fi(e){return e>=ui&&e<=ci?e-ui:e>=di&&e<=hi?e-(di-10):e>=vi&&e<=pi?e-(vi-10):void 0}function gi(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(ai)return Uint8Array.fromHex(e);var t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);for(var n=new Uint8Array(r),i=0,o=0;i<r;i++,o+=2){var a=fi(e.charCodeAt(o)),s=fi(e.charCodeAt(o+1));if(void 0===a||void 0===s){var l=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+l+'" at index '+o)}n[i]=16*a+s}return n}function yi(e){return oi(li(e))}function mi(e){return ri(e),oi(li(Uint8Array.from(e).reverse()))}function wi(e,t){return gi(e.toString(16).padStart(2*t,"0"))}function bi(e,t){return wi(e,t).reverse()}function Si(e,t,r){var n;if("string"==typeof t)try{n=gi(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!ti(t))throw new Error(e+" must be hex string or Uint8Array");n=Uint8Array.from(t)}var i=n.length;if("number"==typeof r&&i!==r)throw new Error(e+" of length "+r+" expected, got "+i);return n}function Ei(){for(var e=0,t=0;t<arguments.length;t++){var r=t<0||arguments.length<=t?void 0:arguments[t];ri(r),e+=r.length}for(var n=new Uint8Array(e),i=0,o=0;i<arguments.length;i++){var a=i<0||arguments.length<=i?void 0:arguments[i];n.set(a,o),o+=a.length}return n}var ki=e=>"bigint"==typeof e&&Xn<=e;function xi(e,t,r){return ki(e)&&ki(t)&&ki(r)&&t<=e&&e<r}function Ai(e,t,r,n){if(!xi(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}var Ci=e=>(ei<<BigInt(e))-ei,Ii=e=>new Uint8Array(e),Ti=e=>Uint8Array.from(e);var Pi={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||ti(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function _i(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=(t,r,n)=>{var i=Pi[r];if("function"!=typeof i)throw new Error("invalid validator function");var o=e[t];if(!(n&&void 0===o||i(o,e)))throw new Error("param "+String(t)+" is invalid. Expected "+r+", got "+o)};for(var[i,o]of Object.entries(t))n(i,o,!1);for(var[a,s]of Object.entries(r))n(a,s,!0);return e}function Bi(e){var t=new WeakMap;return function(r){var n=t.get(r);if(void 0!==n)return n;for(var i=arguments.length,o=new Array(i>1?i-1:0),a=1;a<i;a++)o[a-1]=arguments[a];var s=e(r,...o);return t.set(r,s),s}}var Ni=BigInt(0),Di=BigInt(1),Ri=BigInt(2),Oi=BigInt(3),Li=BigInt(4),Mi=BigInt(5),Ui=BigInt(8);function Fi(e,t){var r=e%t;return r>=Ni?r:t+r}function zi(e,t,r){for(var n=e;t-- >Ni;)n*=n,n%=r;return n}function ji(e,t){if(e===Ni)throw new Error("invert: expected non-zero number");if(t<=Ni)throw new Error("invert: expected positive modulus, got "+t);for(var r=Fi(e,t),n=t,i=Ni,o=Di;r!==Ni;){var a=n%r,s=i-o*(n/r);n=r,r=a,i=o,o=s}if(n!==Di)throw new Error("invert: does not exist");return Fi(i,t)}function Vi(e,t){var r=(e.ORDER+Di)/Li,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function qi(e,t){var r=(e.ORDER-Mi)/Ui,n=e.mul(t,Ri),i=e.pow(n,r),o=e.mul(t,i),a=e.mul(e.mul(o,Ri),i),s=e.mul(o,e.sub(a,e.ONE));if(!e.eql(e.sqr(s),t))throw new Error("Cannot find square root");return s}function Hi(e){return e%Li===Oi?Vi:e%Ui===Mi?qi:function(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");for(var t=e-Di,r=0;t%Ri===Ni;)t/=Ri,r++;for(var n=Ri,i=Yi(e);1===Gi(i,n);)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===r)return Vi;var o=i.pow(n,t),a=(t+Di)/Ri;return function(e,n){if(e.is0(n))return n;if(1!==Gi(e,n))throw new Error("Cannot find square root");for(var i=r,s=e.mul(e.ONE,o),l=e.pow(n,t),u=e.pow(n,a);!e.eql(l,e.ONE);){if(e.is0(l))return e.ZERO;for(var c=1,d=e.sqr(l);!e.eql(d,e.ONE);)if(c++,d=e.sqr(d),c===i)throw new Error("Cannot find square root");var h=Di<<BigInt(i-c-1),v=e.pow(s,h);i=c,s=e.sqr(v),l=e.mul(l,s),u=e.mul(u,v)}return u}}(e)}var Ki=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Wi(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=new Array(t.length).fill(r?e.ZERO:void 0),i=t.reduce(((t,r,i)=>e.is0(r)?t:(n[i]=t,e.mul(t,r))),e.ONE),o=e.inv(i);return t.reduceRight(((t,r,i)=>e.is0(r)?t:(n[i]=e.mul(t,n[i]),e.mul(t,r))),o),n}function Gi(e,t){var r=(e.ORDER-Di)/Ri,n=e.pow(t,r),i=e.eql(n,e.ONE),o=e.eql(n,e.ZERO),a=e.eql(n,e.neg(e.ONE));if(!i&&!o&&!a)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function Qi(e,t){void 0!==t&&_r(t);var r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function Yi(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(e<=Ni)throw new Error("invalid field: expected ORDER > 0, got "+e);var i,{nBitLength:o,nByteLength:a}=Qi(e,t);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");var s=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:a,MASK:Ci(o),ZERO:Ni,ONE:Di,create:t=>Fi(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Ni<=t&&t<e},is0:e=>e===Ni,isOdd:e=>(e&Di)===Di,neg:t=>Fi(-t,e),eql:(e,t)=>e===t,sqr:t=>Fi(t*t,e),add:(t,r)=>Fi(t+r,e),sub:(t,r)=>Fi(t-r,e),mul:(t,r)=>Fi(t*r,e),pow:(e,t)=>function(e,t,r){if(r<Ni)throw new Error("invalid exponent, negatives unsupported");if(r===Ni)return e.ONE;if(r===Di)return t;for(var n=e.ONE,i=t;r>Ni;)r&Di&&(n=e.mul(n,i)),i=e.sqr(i),r>>=Di;return n}(s,e,t),div:(t,r)=>Fi(t*ji(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>ji(t,e),sqrt:n.sqrt||(t=>(i||(i=Hi(e)),i(s,t))),toBytes:e=>r?bi(e,a):wi(e,a),fromBytes:e=>{if(e.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+e.length);return r?mi(e):yi(e)},invertBatch:e=>Wi(s,e),cmov:(e,t,r)=>r?t:e});return Object.freeze(s)}function Ji(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");var t=e.toString(2).length;return Math.ceil(t/8)}function Zi(e){var t=Ji(e);return t+Math.ceil(t/2)}var $i=BigInt(0),Xi=BigInt(1);function eo(e,t){var r=t.negate();return e?r:t}function to(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function ro(e,t){to(e,t);var r=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Ci(e),maxNumber:r,shiftBy:BigInt(e)}}function no(e,t,r){var{windowSize:n,mask:i,maxNumber:o,shiftBy:a}=r,s=Number(e&i),l=e>>a;s>n&&(s-=o,l+=Xi);var u=t*n;return{nextN:l,offset:u+Math.abs(s)-1,isZero:0===s,isNeg:s<0,isNegF:t%2!=0,offsetF:u}}var io=new WeakMap,oo=new WeakMap;function ao(e){return oo.get(e)||1}function so(e,t){return{constTimeNegate:eo,hasPrecomputes:e=>1!==ao(e),unsafeLadder(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.ZERO,i=t;r>$i;)r&Xi&&(n=n.add(i)),i=i.double(),r>>=Xi;return n},precomputeWindow(e,r){for(var{windows:n,windowSize:i}=ro(r,t),o=[],a=e,s=a,l=0;l<n;l++){s=a,o.push(s);for(var u=1;u<i;u++)s=s.add(a),o.push(s);a=s.double()}return o},wNAF(r,n,i){for(var o=e.ZERO,a=e.BASE,s=ro(r,t),l=0;l<s.windows;l++){var{nextN:u,offset:c,isZero:d,isNeg:h,isNegF:v,offsetF:p}=no(i,l,s);i=u,d?a=a.add(eo(v,n[p])):o=o.add(eo(h,n[c]))}return{p:o,f:a}},wNAFUnsafe(r,n,i){for(var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e.ZERO,a=ro(r,t),s=0;s<a.windows&&i!==$i;s++){var{nextN:l,offset:u,isZero:c,isNeg:d}=no(i,s,a);if(i=l,!c){var h=n[u];o=o.add(d?h.negate():h)}}return o},getPrecomputes(e,t,r){var n=io.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&io.set(t,r(n))),n},wNAFCached(e,t,r){var n=ao(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)},wNAFCachedUnsafe(e,t,r,n){var i=ao(e);return 1===i?this.unsafeLadder(e,t,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),t,n)},setWindowSize(e,r){to(r,t),oo.set(e,r),io.delete(e)}}}function lo(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);var i=r.length,o=n.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");var a=e.ZERO,s=function(e){var t;for(t=0;e>Xn;e>>=ei,t+=1);return t}(BigInt(i)),l=1;s>12?l=s-3:s>4?l=s-2:s>0&&(l=2);for(var u=Ci(l),c=new Array(Number(u)+1).fill(a),d=a,h=Math.floor((t.BITS-1)/l)*l;h>=0;h-=l){c.fill(a);for(var v=0;v<o;v++){var p=n[v],f=Number(p>>BigInt(h)&u);c[f]=c[f].add(r[v])}for(var g=a,y=c.length-1,m=a;y>0;y--)m=m.add(c[y]),g=g.add(m);if(d=d.add(g),0!==h)for(var w=0;w<l;w++)d=d.double()}return d}function uo(e){var r,n;return r=e.Fp,n=Ki.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"}),_i(r,n),_i(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze(t(t(t({},Qi(e.n,e.nBitLength)),e),{p:e.Fp.ORDER}))}function co(e){void 0!==e.lowS&&ni("lowS",e.lowS),void 0!==e.prehash&&ni("prehash",e.prehash)}class ho extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"")}}var vo={Err:ho,_tlv:{encode:(e,t)=>{var{Err:r}=vo;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");var n=t.length/2,i=ii(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");var o=n>127?ii(i.length/2|128):"";return ii(e)+o+i+t},decode(e,t){var{Err:r}=vo,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");var i=t[n++],o=0;if(!!(128&i)){var a=127&i;if(!a)throw new r("tlv.decode(long): indefinite length not supported");if(a>4)throw new r("tlv.decode(long): byte length is too big");var s=t.subarray(n,n+a);if(s.length!==a)throw new r("tlv.decode: length bytes not complete");if(0===s[0])throw new r("tlv.decode(long): zero leftmost byte");for(var l of s)o=o<<8|l;if(n+=a,o<128)throw new r("tlv.decode(long): not minimal encoding")}else o=i;var u=t.subarray(n,n+o);if(u.length!==o)throw new r("tlv.decode: wrong value length");return{v:u,l:t.subarray(n+o)}}},_int:{encode(e){var{Err:t}=vo;if(e<fo)throw new t("integer: negative integers are not allowed");var r=ii(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){var{Err:t}=vo;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 yi(e)}},toSig(e){var{Err:t,_int:r,_tlv:n}=vo,i=Si("signature",e),{v:o,l:a}=n.decode(48,i);if(a.length)throw new t("invalid signature: left bytes after parsing");var{v:s,l:l}=n.decode(2,o),{v:u,l:c}=n.decode(2,l);if(c.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(s),s:r.decode(u)}},hexFromSig(e){var{_tlv:t,_int:r}=vo,n=t.encode(2,r.encode(e.r))+t.encode(2,r.encode(e.s));return t.encode(48,n)}};function po(e,t){return li(wi(e,t))}var fo=BigInt(0),go=BigInt(1);BigInt(2);var yo=BigInt(3),mo=BigInt(4);function wo(e){var r=function(e){var r=uo(e);_i(r,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});var{endo:n,Fp:i,a:o}=r;if(n){if(!i.eql(o,i.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if("object"!=typeof n||"bigint"!=typeof n.beta||"function"!=typeof n.splitScalar)throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze(t({},r))}(e),{Fp:n}=r,i=Yi(r.n,r.nBitLength),o=r.toBytes||((e,t,r)=>{var i=t.toAffine();return Ei(Uint8Array.from([4]),n.toBytes(i.x),n.toBytes(i.y))}),a=r.fromBytes||(e=>{var t=e.subarray(1);return{x:n.fromBytes(t.subarray(0,n.BYTES)),y:n.fromBytes(t.subarray(n.BYTES,2*n.BYTES))}});function s(e){var{a:t,b:i}=r,o=n.sqr(e),a=n.mul(o,e);return n.add(n.add(a,n.mul(e,t)),i)}function l(e,t){var r=n.sqr(t),i=s(e);return n.eql(r,i)}if(!l(r.Gx,r.Gy))throw new Error("bad curve params: generator point");var u=n.mul(n.pow(r.a,yo),mo),c=n.mul(n.sqr(r.b),BigInt(27));if(n.is0(n.add(u,c)))throw new Error("bad curve params: a or b");function d(e){var t,{allowedPrivateKeyLengths:n,nByteLength:i,wrapPrivateKey:o,n:a}=r;if(n&&"bigint"!=typeof e){if(ti(e)&&(e=li(e)),"string"!=typeof e||!n.includes(e.length))throw new Error("invalid private key");e=e.padStart(2*i,"0")}try{t="bigint"==typeof e?e:yi(Si("private key",e,i))}catch(t){throw new Error("invalid private key, expected hex or "+i+" bytes, got "+typeof e)}return o&&(t=Fi(t,a)),Ai("private key",t,go,a),t}function h(e){if(!(e instanceof f))throw new Error("ProjectivePoint expected")}var v=Bi(((e,t)=>{var{px:r,py:i,pz:o}=e;if(n.eql(o,n.ONE))return{x:r,y:i};var a=e.is0();null==t&&(t=a?n.ONE:n.inv(o));var s=n.mul(r,t),l=n.mul(i,t),u=n.mul(o,t);if(a)return{x:n.ZERO,y:n.ZERO};if(!n.eql(u,n.ONE))throw new Error("invZ was invalid");return{x:s,y:l}})),p=Bi((e=>{if(e.is0()){if(r.allowInfinityPoint&&!n.is0(e.py))return;throw new Error("bad point: ZERO")}var{x:t,y:i}=e.toAffine();if(!n.isValid(t)||!n.isValid(i))throw new Error("bad point: x or y not FE");if(!l(t,i))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0}));class f{constructor(e,t,r){if(null==e||!n.isValid(e))throw new Error("x required");if(null==t||!n.isValid(t)||n.is0(t))throw new Error("y required");if(null==r||!n.isValid(r))throw new Error("z required");this.px=e,this.py=t,this.pz=r,Object.freeze(this)}static fromAffine(e){var{x:t,y:r}=e||{};if(!e||!n.isValid(t)||!n.isValid(r))throw new Error("invalid affine point");if(e instanceof f)throw new Error("projective point not allowed");var i=e=>n.eql(e,n.ZERO);return i(t)&&i(r)?f.ZERO:new f(t,r,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){var t=Wi(n,e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(f.fromAffine)}static fromHex(e){var t=f.fromAffine(a(Si("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return f.BASE.multiply(d(e))}static msm(e,t){return lo(f,i,e,t)}_setWindowSize(e){m.setWindowSize(this,e)}assertValidity(){p(this)}hasEvenY(){var{y:e}=this.toAffine();if(n.isOdd)return!n.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){h(e);var{px:t,py:r,pz:i}=this,{px:o,py:a,pz:s}=e,l=n.eql(n.mul(t,s),n.mul(o,i)),u=n.eql(n.mul(r,s),n.mul(a,i));return l&&u}negate(){return new f(this.px,n.neg(this.py),this.pz)}double(){var{a:e,b:t}=r,i=n.mul(t,yo),{px:o,py:a,pz:s}=this,l=n.ZERO,u=n.ZERO,c=n.ZERO,d=n.mul(o,o),h=n.mul(a,a),v=n.mul(s,s),p=n.mul(o,a);return p=n.add(p,p),c=n.mul(o,s),c=n.add(c,c),l=n.mul(e,c),u=n.mul(i,v),u=n.add(l,u),l=n.sub(h,u),u=n.add(h,u),u=n.mul(l,u),l=n.mul(p,l),c=n.mul(i,c),v=n.mul(e,v),p=n.sub(d,v),p=n.mul(e,p),p=n.add(p,c),c=n.add(d,d),d=n.add(c,d),d=n.add(d,v),d=n.mul(d,p),u=n.add(u,d),v=n.mul(a,s),v=n.add(v,v),d=n.mul(v,p),l=n.sub(l,d),c=n.mul(v,h),c=n.add(c,c),c=n.add(c,c),new f(l,u,c)}add(e){h(e);var{px:t,py:i,pz:o}=this,{px:a,py:s,pz:l}=e,u=n.ZERO,c=n.ZERO,d=n.ZERO,v=r.a,p=n.mul(r.b,yo),g=n.mul(t,a),y=n.mul(i,s),m=n.mul(o,l),w=n.add(t,i),b=n.add(a,s);w=n.mul(w,b),b=n.add(g,y),w=n.sub(w,b),b=n.add(t,o);var S=n.add(a,l);return b=n.mul(b,S),S=n.add(g,m),b=n.sub(b,S),S=n.add(i,o),u=n.add(s,l),S=n.mul(S,u),u=n.add(y,m),S=n.sub(S,u),d=n.mul(v,b),u=n.mul(p,m),d=n.add(u,d),u=n.sub(y,d),d=n.add(y,d),c=n.mul(u,d),y=n.add(g,g),y=n.add(y,g),m=n.mul(v,m),b=n.mul(p,b),y=n.add(y,m),m=n.sub(g,m),m=n.mul(v,m),b=n.add(b,m),g=n.mul(y,b),c=n.add(c,g),g=n.mul(S,b),u=n.mul(w,u),u=n.sub(u,g),g=n.mul(w,y),d=n.mul(S,d),d=n.add(d,g),new f(u,c,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(f.ZERO)}wNAF(e){return m.wNAFCached(this,e,f.normalizeZ)}multiplyUnsafe(e){var{endo:t,n:i}=r;Ai("scalar",e,fo,i);var o=f.ZERO;if(e===fo)return o;if(this.is0()||e===go)return this;if(!t||m.hasPrecomputes(this))return m.wNAFCachedUnsafe(this,e,f.normalizeZ);for(var{k1neg:a,k1:s,k2neg:l,k2:u}=t.splitScalar(e),c=o,d=o,h=this;s>fo||u>fo;)s&go&&(c=c.add(h)),u&go&&(d=d.add(h)),h=h.double(),s>>=go,u>>=go;return a&&(c=c.negate()),l&&(d=d.negate()),d=new f(n.mul(d.px,t.beta),d.py,d.pz),c.add(d)}multiply(e){var t,i,{endo:o,n:a}=r;if(Ai("scalar",e,go,a),o){var{k1neg:s,k1:l,k2neg:u,k2:c}=o.splitScalar(e),{p:d,f:h}=this.wNAF(l),{p:v,f:p}=this.wNAF(c);d=m.constTimeNegate(s,d),v=m.constTimeNegate(u,v),v=new f(n.mul(v.px,o.beta),v.py,v.pz),t=d.add(v),i=h.add(p)}else{var{p:g,f:y}=this.wNAF(e);t=g,i=y}return f.normalizeZ([t,i])[0]}multiplyAndAddUnsafe(e,t,r){var n=f.BASE,i=(e,t)=>t!==fo&&t!==go&&e.equals(n)?e.multiply(t):e.multiplyUnsafe(t),o=i(this,t).add(i(e,r));return o.is0()?void 0:o}toAffine(e){return v(this,e)}isTorsionFree(){var{h:e,isTorsionFree:t}=r;if(e===go)return!0;if(t)return t(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){var{h:e,clearCofactor:t}=r;return e===go?this:t?t(f,this):this.multiplyUnsafe(r.h)}toRawBytes(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return ni("isCompressed",e),this.assertValidity(),o(f,this,e)}toHex(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return ni("isCompressed",e),li(this.toRawBytes(e))}}f.BASE=new f(r.Gx,r.Gy,n.ONE),f.ZERO=new f(n.ZERO,n.ONE,n.ZERO);var{endo:g,nBitLength:y}=r,m=so(f,g?Math.ceil(y/2):y);return{CURVE:r,ProjectivePoint:f,normPrivateKeyToScalar:d,weierstrassEquation:s,isWithinCurveOrder:function(e){return xi(e,go,r.n)}}}function bo(e){var r,n=(_i(r=uo(e),{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze(t({lowS:!0},r))),{Fp:i,n:o,nByteLength:a,nBitLength:s}=n,l=i.BYTES+1,u=2*i.BYTES+1;function c(e){return Fi(e,o)}function d(e){return ji(e,o)}var{ProjectivePoint:h,normPrivateKeyToScalar:v,weierstrassEquation:p,isWithinCurveOrder:f}=wo(t(t({},n),{},{toBytes(e,t,r){var n=t.toAffine(),o=i.toBytes(n.x),a=Ei;return ni("isCompressed",r),r?a(Uint8Array.from([t.hasEvenY()?2:3]),o):a(Uint8Array.from([4]),o,i.toBytes(n.y))},fromBytes(e){var t=e.length,r=e[0],n=e.subarray(1);if(t!==l||2!==r&&3!==r){if(t===u&&4===r)return{x:i.fromBytes(n.subarray(0,i.BYTES)),y:i.fromBytes(n.subarray(i.BYTES,2*i.BYTES))};throw new Error("invalid Point, expected length of "+l+", or uncompressed "+u+", got "+t)}var o=yi(n);if(!xi(o,go,i.ORDER))throw new Error("Point is not on curve");var a,s=p(o);try{a=i.sqrt(s)}catch(e){var c=e instanceof Error?": "+e.message:"";throw new Error("Point is not on curve"+c)}return!(1&~r)!==((a&go)===go)&&(a=i.neg(a)),{x:o,y:a}}}));function g(e){return e>o>>go}var y=(e,t,r)=>yi(e.slice(t,r));class m{constructor(e,t,r){Ai("r",e,go,o),Ai("s",t,go,o),this.r=e,this.s=t,null!=r&&(this.recovery=r),Object.freeze(this)}static fromCompact(e){var t=a;return e=Si("compactSignature",e,2*t),new m(y(e,0,t),y(e,t,2*t))}static fromDER(e){var{r:t,s:r}=vo.toSig(Si("DER",e));return new m(t,r)}assertValidity(){}addRecoveryBit(e){return new m(this.r,this.s,e)}recoverPublicKey(e){var{r:t,s:r,recovery:o}=this,a=E(Si("msgHash",e));if(null==o||![0,1,2,3].includes(o))throw new Error("recovery id invalid");var s=2===o||3===o?t+n.n:t;if(s>=i.ORDER)throw new Error("recovery id 2 or 3 invalid");var l=1&o?"03":"02",u=h.fromHex(l+po(s,i.BYTES)),v=d(s),p=c(-a*v),f=c(r*v),g=h.BASE.multiplyAndAddUnsafe(u,p,f);if(!g)throw new Error("point at infinify");return g.assertValidity(),g}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new m(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return gi(this.toDERHex())}toDERHex(){return vo.hexFromSig(this)}toCompactRawBytes(){return gi(this.toCompactHex())}toCompactHex(){var e=a;return po(this.r,e)+po(this.s,e)}}var w={isValidPrivateKey(e){try{return v(e),!0}catch(e){return!1}},normPrivateKeyToScalar:v,randomPrivateKey:()=>{var e=Zi(n.n);return function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=e.length,i=Ji(t),o=Zi(t);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);var a=Fi(r?mi(e):yi(e),t-Di)+Di;return r?bi(a,i):wi(a,i)}(n.randomBytes(e),n.n)},precompute(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:8,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:h.BASE;return t._setWindowSize(e),t.multiply(BigInt(3)),t}};function b(e){if("bigint"==typeof e)return!1;if(e instanceof h)return!0;var t=Si("key",e).length,r=i.BYTES,o=r+1,s=2*r+1;return n.allowedPrivateKeyLengths||a===o?void 0:t===o||t===s}var S=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");var t=yi(e),r=8*e.length-s;return r>0?t>>BigInt(r):t},E=n.bits2int_modN||function(e){return c(S(e))},k=Ci(s);function x(e){return Ai("num < 2^"+s,e,fo,k),wi(e,a)}function A(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:C;if(["recovered","canonical"].some((e=>e in r)))throw new Error("sign() legacy options not supported");var{hash:o,randomBytes:a}=n,{lowS:s,prehash:l,extraEntropy:u}=r;null==s&&(s=!0),e=Si("msgHash",e),co(r),l&&(e=Si("prehashed msgHash",o(e)));var p=E(e),y=v(t),w=[x(y),x(p)];if(null!=u&&!1!==u){var b=!0===u?a(i.BYTES):u;w.push(Si("extraEntropy",b))}var k=Ei(...w),A=p;return{seed:k,k2sig:function(e){var t=S(e);if(f(t)){var r=d(t),n=h.BASE.multiply(t).toAffine(),i=c(n.x);if(i!==fo){var o=c(r*c(A+i*y));if(o!==fo){var a=(n.x===i?0:2)|Number(n.y&go),l=o;return s&&g(o)&&(l=function(e){return g(e)?c(-e):e}(o),a^=1),new m(i,l,a)}}}}}}var C={lowS:n.lowS,prehash:!1},I={lowS:n.lowS,prehash:!1};return h.BASE._setWindowSize(8),{CURVE:n,getPublicKey:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return h.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(!0===b(e))throw new Error("first arg must be private key");if(!1===b(t))throw new Error("second arg must be public key");return h.fromHex(t).multiply(v(e)).toRawBytes(r)},sign:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:C,{seed:i,k2sig:o}=A(e,t,r),a=n,s=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");var n=Ii(e),i=Ii(e),o=0,a=()=>{n.fill(1),i.fill(0),o=0},s=function(){for(var e=arguments.length,t=new Array(e),o=0;o<e;o++)t[o]=arguments[o];return r(i,n,...t)},l=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Ii(0);i=s(Ti([0]),e),n=s(),0!==e.length&&(i=s(Ti([1]),e),n=s())},u=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");for(var e=0,r=[];e<t;){var i=(n=s()).slice();r.push(i),e+=n.length}return Ei(...r)};return(e,t)=>{a(),l(e);for(var r=void 0;!(r=t(u()));)l();return a(),r}}(a.hash.outputLen,a.nByteLength,a.hmac);return s(i,o)},verify:function(e,t,r){var i,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:I,a=e;t=Si("msgHash",t),r=Si("publicKey",r);var{lowS:s,prehash:l,format:u}=o;if(co(o),"strict"in o)throw new Error("options.strict was renamed to lowS");if(void 0!==u&&"compact"!==u&&"der"!==u)throw new Error("format must be compact or der");var v="string"==typeof a||ti(a),p=!v&&!u&&"object"==typeof a&&null!==a&&"bigint"==typeof a.r&&"bigint"==typeof a.s;if(!v&&!p)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");var f,g=void 0;try{if(p&&(g=new m(a.r,a.s)),v){try{"compact"!==u&&(g=m.fromDER(a))}catch(e){if(!(e instanceof vo.Err))throw e}g||"der"===u||(g=m.fromCompact(a))}f=h.fromHex(r)}catch(e){return!1}if(!g)return!1;if(s&&g.hasHighS())return!1;l&&(t=n.hash(t));var{r:y,s:w}=g,b=E(t),S=d(w),k=c(b*S),x=c(y*S),A=null===(i=h.BASE.multiplyAndAddUnsafe(f,k,x))||void 0===i?void 0:i.toAffine();return!!A&&c(A.x)===y},ProjectivePoint:h,Signature:m,utils:w}}var So=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Eo=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),ko=BigInt(0),xo=BigInt(1),Ao=BigInt(2),Co=(e,t)=>(e+t/Ao)/t;var Io=Yi(So,void 0,void 0,{sqrt:function(e){var t=So,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),a=BigInt(23),s=BigInt(44),l=BigInt(88),u=e*e*e%t,c=u*u*e%t,d=zi(c,r,t)*c%t,h=zi(d,r,t)*c%t,v=zi(h,Ao,t)*u%t,p=zi(v,i,t)*v%t,f=zi(p,o,t)*p%t,g=zi(f,s,t)*f%t,y=zi(g,l,t)*g%t,m=zi(y,s,t)*f%t,w=zi(m,r,t)*c%t,b=zi(w,a,t)*p%t,S=zi(b,n,t)*u%t,E=zi(S,Ao,t);if(!Io.eql(Io.sqr(E),e))throw new Error("Cannot find square root");return E}}),To=function(e,r){var n=r=>bo(t(t({},e),function(e){return{hash:e,hmac:function(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return $n(e,t,sn(...n))},randomBytes:dn}}(r)));return t(t({},n(r)),{},{create:n})}({a:ko,b:BigInt(7),Fp:Io,n:Eo,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{var t=Eo,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-xo*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,a=BigInt("0x100000000000000000000000000000000"),s=Co(o*e,t),l=Co(-n*e,t),u=Fi(e-s*r-l*i,t),c=Fi(-s*n-l*o,t),d=u>a,h=c>a;if(d&&(u=t-u),h&&(c=t-c),u>a||c>a)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:d,k1:u,k2neg:h,k2:c}}}},Yn),Po=BigInt(0),_o=BigInt(1),Bo=BigInt(2),No=BigInt(8),Do={zip215:!0};function Ro(e){var r,n,i=(n=uo(r=e),_i(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze(t({},n))),{Fp:o,n:a,prehash:s,hash:l,randomBytes:u,nByteLength:c,h:d}=i,h=Bo<<BigInt(8*c)-_o,v=o.create,p=Yi(i.n,i.nBitLength);if(!function(e,t){var r=o.sqr(e),n=o.sqr(t),a=o.add(o.mul(i.a,r),n),s=o.add(o.ONE,o.mul(i.d,o.mul(r,n)));return o.eql(a,s)}(i.Gx,i.Gy))throw new Error("bad curve params: generator point");var f=i.uvRatio||((e,t)=>{try{return{isValid:!0,value:o.sqrt(e*o.inv(t))}}catch(e){return{isValid:!1,value:Po}}}),g=i.adjustScalarBytes||(e=>e),y=i.domain||((e,t,r)=>{if(ni("phflag",r),t.length||r)throw new Error("Contexts/pre-hash are not supported");return e});function m(e,t){Ai("coordinate "+e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2]?_o:Po,h)}function w(e){if(!(e instanceof E))throw new Error("ExtendedPoint expected")}var b=Bi(((e,t)=>{var{ex:r,ey:n,ez:i}=e,a=e.is0();null==t&&(t=a?No:o.inv(i));var s=v(r*t),l=v(n*t),u=v(i*t);if(a)return{x:Po,y:_o};if(u!==_o)throw new Error("invZ was invalid");return{x:s,y:l}})),S=Bi((e=>{var{a:t,d:r}=i;if(e.is0())throw new Error("bad point: ZERO");var{ex:n,ey:o,ez:a,et:s}=e,l=v(n*n),u=v(o*o),c=v(a*a),d=v(c*c),h=v(l*t);if(v(c*v(h+u))!==v(d+v(r*v(l*u))))throw new Error("bad point: equation left != right (1)");if(v(n*o)!==v(a*s))throw new Error("bad point: equation left != right (2)");return!0}));class E{constructor(e,t,r,n){m("x",e),m("y",t),m("z",r,!0),m("t",n),this.ex=e,this.ey=t,this.ez=r,this.et=n,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof E)throw new Error("extended point not allowed");var{x:t,y:r}=e||{};return m("x",t),m("y",r),new E(t,r,_o,v(t*r))}static normalizeZ(e){var t=Wi(o,e.map((e=>e.ez)));return e.map(((e,r)=>e.toAffine(t[r]))).map(E.fromAffine)}static msm(e,t){return lo(E,p,e,t)}_setWindowSize(e){A.setWindowSize(this,e)}assertValidity(){S(this)}equals(e){w(e);var{ex:t,ey:r,ez:n}=this,{ex:i,ey:o,ez:a}=e,s=v(t*a),l=v(i*n),u=v(r*a),c=v(o*n);return s===l&&u===c}is0(){return this.equals(E.ZERO)}negate(){return new E(v(-this.ex),this.ey,this.ez,v(-this.et))}double(){var{a:e}=i,{ex:t,ey:r,ez:n}=this,o=v(t*t),a=v(r*r),s=v(Bo*v(n*n)),l=v(e*o),u=t+r,c=v(v(u*u)-o-a),d=l+a,h=d-s,p=l-a,f=v(c*h),g=v(d*p),y=v(c*p),m=v(h*d);return new E(f,g,m,y)}add(e){w(e);var{a:t,d:r}=i,{ex:n,ey:o,ez:a,et:s}=this,{ex:l,ey:u,ez:c,et:d}=e,h=v(n*l),p=v(o*u),f=v(s*r*d),g=v(a*c),y=v((n+o)*(l+u)-h-p),m=g-f,b=g+f,S=v(p-t*h),k=v(y*m),x=v(b*S),A=v(y*S),C=v(m*b);return new E(k,x,C,A)}subtract(e){return this.add(e.negate())}wNAF(e){return A.wNAFCached(this,e,E.normalizeZ)}multiply(e){var t=e;Ai("scalar",t,_o,a);var{p:r,f:n}=this.wNAF(t);return E.normalizeZ([r,n])[0]}multiplyUnsafe(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:E.ZERO,r=e;return Ai("scalar",r,Po,a),r===Po?x:this.is0()||r===_o?this:A.wNAFCachedUnsafe(this,r,E.normalizeZ,t)}isSmallOrder(){return this.multiplyUnsafe(d).is0()}isTorsionFree(){return A.unsafeLadder(this,a).is0()}toAffine(e){return b(this,e)}clearCofactor(){var{h:e}=i;return e===_o?this:this.multiplyUnsafe(e)}static fromHex(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],{d:r,a:n}=i,a=o.BYTES;e=Si("pointHex",e,a),ni("zip215",t);var s=e.slice(),l=e[a-1];s[a-1]=-129&l;var u=mi(s),c=t?h:o.ORDER;Ai("pointHex.y",u,Po,c);var d=v(u*u),p=v(d-_o),g=v(r*d-n),{isValid:y,value:m}=f(p,g);if(!y)throw new Error("Point.fromHex: invalid y coordinate");var w=(m&_o)===_o,b=!!(128&l);if(!t&&m===Po&&b)throw new Error("Point.fromHex: x=0 and x_0=1");return b!==w&&(m=v(-m)),E.fromAffine({x:m,y:u})}static fromPrivateKey(e){var{scalar:t}=T(e);return k.multiply(t)}toRawBytes(){var{x:e,y:t}=this.toAffine(),r=bi(t,o.BYTES);return r[r.length-1]|=e&_o?128:0,r}toHex(){return li(this.toRawBytes())}}E.BASE=new E(i.Gx,i.Gy,_o,v(i.Gx*i.Gy)),E.ZERO=new E(Po,_o,_o,Po);var{BASE:k,ZERO:x}=E,A=so(E,8*c);function C(e){return Fi(e,a)}function I(e){return C(mi(e))}function T(e){var t=o.BYTES;e=Si("private key",e,t);var r=Si("hashed private key",l(e),2*t),n=g(r.slice(0,t));return{head:n,prefix:r.slice(t,2*t),scalar:I(n)}}function P(e){var{head:t,prefix:r,scalar:n}=T(e),i=k.multiply(n),o=i.toRawBytes();return{head:t,prefix:r,scalar:n,point:i,pointBytes:o}}function _(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Uint8Array.of(),t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];var i=Ei(...r);return I(l(y(i,Si("context",e),!!s)))}var B=Do;k._setWindowSize(8);var N={getExtendedPublicKey:P,randomPrivateKey:()=>u(o.BYTES),precompute(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:8,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:E.BASE;return t._setWindowSize(e),t.multiply(BigInt(3)),t}};return{CURVE:i,getPublicKey:function(e){return P(e).pointBytes},sign:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e=Si("message",e),s&&(e=s(e));var{prefix:n,scalar:i,pointBytes:l}=P(t),u=_(r.context,n,e),c=k.multiply(u).toRawBytes(),d=C(u+_(r.context,c,l,e)*i);return Ai("signature.s",d,Po,a),Si("result",Ei(c,bi(d,o.BYTES)),2*o.BYTES)},verify:function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:B,{context:i,zip215:a}=n,l=o.BYTES;e=Si("signature",e,2*l),t=Si("message",t),r=Si("publicKey",r,l),void 0!==a&&ni("zip215",a),s&&(t=s(t));var u,c,d,h=mi(e.slice(l,2*l));try{u=E.fromHex(r,a),c=E.fromHex(e.slice(0,l),a),d=k.multiplyUnsafe(h)}catch(e){return!1}if(!a&&u.isSmallOrder())return!1;var v=_(i,c.toRawBytes(),u.toRawBytes(),t);return c.add(u.multiplyUnsafe(v)).subtract(d).clearCofactor().equals(E.ZERO)},ExtendedPoint:E,utils:N}}var Oo=BigInt(0),Lo=BigInt(1),Mo=BigInt(2);function Uo(e){var r,n=(_i(r=e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze(t({},r))),{P:i,type:o,adjustScalarBytes:a,powPminus2:s}=n,l="x25519"===o;if(!l&&"x448"!==o)throw new Error("invalid type");var u=l?255:448,c=l?32:56,d=l?BigInt(9):BigInt(5),h=l?BigInt(121665):BigInt(39081),v=l?Mo**BigInt(254):Mo**BigInt(447),p=l?BigInt(8)*Mo**BigInt(251)-Lo:BigInt(4)*Mo**BigInt(445)-Lo,f=v+p+Lo,g=e=>Fi(e,i),y=m(d);function m(e){return bi(g(e),c)}function w(e,t){var r=function(e,t){Ai("u",e,Oo,i),Ai("scalar",t,v,f);for(var r=t,n=e,o=Lo,a=Oo,l=e,c=Lo,d=Oo,p=BigInt(u-1);p>=Oo;p--){var y=r>>p&Lo;d^=y,({x_2:o,x_3:l}=S(d,o,l)),({x_2:a,x_3:c}=S(d,a,c)),d=y;var m=o+a,w=g(m*m),b=o-a,E=g(b*b),k=w-E,x=l+c,A=g((l-c)*m),C=g(x*b),I=A+C,T=A-C;l=g(I*I),c=g(n*g(T*T)),o=g(w*E),a=g(k*(w+g(h*k)))}({x_2:o,x_3:l}=S(d,o,l)),({x_2:a,x_3:c}=S(d,a,c));var P=s(a);return g(o*P)}(function(e){var t=Si("u coordinate",e,c);return l&&(t[31]&=127),g(mi(t))}(t),function(e){return mi(a(Si("scalar",e,c)))}(e));if(r===Oo)throw new Error("invalid private or public key received");return m(r)}function b(e){return w(e,y)}function S(e,t,r){var n=g(e*(t-r));return{x_2:t=g(t-n),x_3:r=g(r+n)}}return{scalarMult:w,scalarMultBase:b,getSharedSecret:(e,t)=>w(e,t),getPublicKey:e=>b(e),utils:{randomPrivateKey:()=>n.randomBytes(c)},GuBytes:y.slice()}}var Fo=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),zo=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);var jo=BigInt(1),Vo=BigInt(2),qo=BigInt(3),Ho=BigInt(5),Ko=BigInt(8);function Wo(e){var t=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),o=Fo,a=e*e%o*e%o,s=zi(a,Vo,o)*a%o,l=zi(s,jo,o)*e%o,u=zi(l,Ho,o)*l%o,c=zi(u,t,o)*u%o,d=zi(c,r,o)*c%o,h=zi(d,n,o)*d%o,v=zi(h,i,o)*h%o,p=zi(v,i,o)*h%o,f=zi(p,t,o)*u%o;return{pow_p_5_8:zi(f,Vo,o)*e%o,b2:a}}function Go(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function Qo(e,t){var r=Fo,n=Fi(t*t*t,r),i=Fi(n*n*t,r),o=Fi(e*n*Wo(e*i).pow_p_5_8,r),a=Fi(t*o*o,r),s=o,l=Fi(o*zo,r),u=a===e,c=a===Fi(-e,r),d=a===Fi(-e*zo,r);return u&&(o=s),(c||d)&&(o=l),(Fi(o,r)&Di)===Di&&(o=Fi(-o,r)),{isValid:u||c,value:o}}var Yo=(()=>Yi(Fo,void 0,!0))(),Jo=(()=>({a:Yo.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Yo,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Ko,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Jn,randomBytes:dn,adjustScalarBytes:Go,uvRatio:Qo}))(),Zo=(()=>Ro(Jo))(),$o=(()=>Uo({P:Fo,type:"x25519",powPminus2:e=>{var t=Fo,{pow_p_5_8:r,b2:n}=Wo(e);return Fi(zi(r,qo,t)*n,t)},adjustScalarBytes:Go,randomBytes:dn}))(),Xo=Yn,ea=Jn;function ta(e,t,r,n){Nr(e);var i=function(e,t){if(void 0!==t&&"[object Object]"!=={}.toString.call(t))throw new Error("options should be object or undefined");return Object.assign(e,t)}({dkLen:32,asyncTick:10},n),{c:o,dkLen:a,asyncTick:s}=i;if(_r(o),_r(a),_r(s),o<1)throw new Error("iterations (c) should be >= 1");var l=an(t),u=an(r),c=new Uint8Array(a),d=$n.create(e,l),h=d._cloneInto().update(u);return{c:o,dkLen:a,asyncTick:s,DK:c,PRF:d,PRFSalt:h}}function ra(e,t,r,n,i){return e.destroy(),t.destroy(),n&&n.destroy(),Lr(i),r}function na(e,t,r,n){return ia.apply(this,arguments)}function ia(){return ia=r((function*(e,t,r,n){for(var i,{c:o,dkLen:a,asyncTick:s,DK:l,PRF:u,PRFSalt:c}=ta(e,t,r,n),d=new Uint8Array(4),h=Mr(d),v=new Uint8Array(u.outputLen),p=function*(){var e=l.subarray(g,g+u.outputLen);h.setInt32(0,f,!1),(i=c._cloneInto(i)).update(d).digestInto(v),e.set(v.subarray(0,e.length)),yield function(e,t,r){return rn.apply(this,arguments)}(o-1,s,(()=>{u._cloneInto(i).update(v).digestInto(v);for(var t=0;t<e.length;t++)e[t]^=v[t]}))},f=1,g=0;g<a;f++,g+=u.outputLen)yield*p();return ra(u,c,l,i,v)})),ia.apply(this,arguments)}var oa,aa={exports:{}};var sa=(oa||(oa=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function o(e,t,n,o,a){if("function"!=typeof n)throw new TypeError("The listener must be a function");var s=new i(n,o||e,a),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],s]:e._events[l].push(s):(e._events[l]=s,e._eventsCount++),e}function a(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function s(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),s.prototype.eventNames=function(){var e,n,i=[];if(0===this._eventsCount)return i;for(n in e=this._events)t.call(e,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},s.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 i=0,o=n.length,a=new Array(o);i<o;i++)a[i]=n[i].fn;return a},s.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},s.prototype.emit=function(e,t,n,i,o,a){var s=r?r+e:e;if(!this._events[s])return!1;var l,u,c=this._events[s],d=arguments.length;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,o),!0;case 6:return c.fn.call(c.context,t,n,i,o,a),!0}for(u=1,l=new Array(d-1);u<d;u++)l[u-1]=arguments[u];c.fn.apply(c.context,l)}else{var h,v=c.length;for(u=0;u<v;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),d){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,n);break;case 4:c[u].fn.call(c[u].context,t,n,i);break;default:if(!l)for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];c[u].fn.apply(c[u].context,l)}}return!0},s.prototype.on=function(e,t,r){return o(this,e,t,r,!1)},s.prototype.once=function(e,t,r){return o(this,e,t,r,!0)},s.prototype.removeListener=function(e,t,n,i){var o=r?r+e:e;if(!this._events[o])return this;if(!t)return a(this,o),this;var s=this._events[o];if(s.fn)s.fn!==t||i&&!s.once||n&&s.context!==n||a(this,o);else{for(var l=0,u=[],c=s.length;l<c;l++)(s[l].fn!==t||i&&!s[l].once||n&&s[l].context!==n)&&u.push(s[l]);u.length?this._events[o]=1===u.length?u[0]:u:a(this,o)}return this},s.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&a(this,t)):(this._events=new n,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prefixed=r,s.EventEmitter=s,e.exports=s}(aa)),aa.exports),la=a(sa),ua=function(e,t){return ua=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},ua(e,t)};function ca(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}ua(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function da(e,t,r,n){var i,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,n);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(a=(o<3?i(a):o>3?i(t,r,a):i(t,r))||a);return o>3&&a&&Object.defineProperty(t,r,a),a}function ha(e,t,r,n){return new(r||(r=Promise))((function(i,o){function a(e){try{l(n.next(e))}catch(e){o(e)}}function s(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,s)}l((n=n.apply(e,t||[])).next())}))}function va(e,t){var r,n,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(l){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],n=0}finally{r=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,l])}}}function pa(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function fa(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a}function ga(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(fa(arguments[t]));return e}function ya(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i<o;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))}function ma(e){return this instanceof ma?(this.v=e,this):new ma(e)}function wa(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,i=r.apply(e,t||[]),o=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",(function(e){return function(t){return Promise.resolve(t).then(e,u)}})),n[Symbol.asyncIterator]=function(){return this},n;function a(e,t){i[e]&&(n[e]=function(t){return new Promise((function(r,n){o.push([e,t,r,n])>1||s(e,t)}))},t&&(n[e]=t(n[e])))}function s(e,t){try{(r=i[e](t)).value instanceof ma?Promise.resolve(r.value.v).then(l,u):c(o[0][2],r)}catch(e){c(o[0][3],e)}var r}function l(e){s("next",e)}function u(e){s("throw",e)}function c(e,t){e(t),o.shift(),o.length&&s(o[0][0],o[0][1])}}function ba(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=pa(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,i){(function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)})(n,i,(t=e[r](t)).done,t.value)}))}}}function Sa(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)}"function"==typeof SuppressedError&&SuppressedError;var Ea=Symbol.for("@libp2p/connection"),ka=Symbol.for("@libp2p/content-routing"),xa=Symbol.for("@libp2p/peer-discovery"),Aa=Symbol.for("@libp2p/peer-id");function Ca(e){return Boolean(null==e?void 0:e[Aa])}var Ia,Ta=Symbol.for("@libp2p/peer-routing"),Pa="keep-alive",_a=Symbol.for("@libp2p/transport");!function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"}(Ia||(Ia={}));let Ba=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The operation was aborted"),this.name="AbortError"}};e(Ba,"name","AbortError");class Na extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unexpected Peer"),this.name="UnexpectedPeerError"}}e(Na,"name","UnexpectedPeerError");let Da=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid crypto exchange"),this.name="InvalidCryptoExchangeError"}};e(Da,"name","InvalidCryptoExchangeError");let Ra=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid parameters"),this.name="InvalidParametersError"}};e(Ra,"name","InvalidParametersError");class Oa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid public key"),this.name="InvalidPublicKeyError"}}e(Oa,"name","InvalidPublicKeyError");class La extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid private key"),this.name="InvalidPrivateKeyError"}}e(La,"name","InvalidPrivateKeyError");class Ma extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unsupported operation"),this.name="UnsupportedOperationError"}}e(Ma,"name","UnsupportedOperationError");class Ua extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The connection is closing"),this.name="ConnectionClosingError"}}e(Ua,"name","ConnectionClosingError");class Fa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The connection is closed"),this.name="ConnectionClosedError"}}e(Fa,"name","ConnectionClosedError");class za extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Connection failed"),this.name="ConnectionFailedError"}}e(za,"name","ConnectionFailedError");class ja extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The muxer is closed"),this.name="MuxerClosedError"}}e(ja,"name","MuxerClosedError");class Va extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The stream has been reset"),this.name="StreamResetError"}}e(Va,"name","StreamResetError");class qa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The stream is in an invalid state"),this.name="StreamStateError"}}e(qa,"name","StreamStateError");let Ha=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not found"),this.name="NotFoundError"}};e(Ha,"name","NotFoundError");class Ka extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid PeerID"),this.name="InvalidPeerIdError"}}e(Ka,"name","InvalidPeerIdError");class Wa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid multiaddr"),this.name="InvalidMultiaddrError"}}e(Wa,"name","InvalidMultiaddrError");class Ga extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid CID"),this.name="InvalidCIDError"}}e(Ga,"name","InvalidCIDError");class Qa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid Multihash"),this.name="InvalidMultihashError"}}e(Qa,"name","InvalidMultihashError");class Ya extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unsupported protocol error"),this.name="UnsupportedProtocolError"}}e(Ya,"name","UnsupportedProtocolError");class Ja extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid message"),this.name="InvalidMessageError"}}e(Ja,"name","InvalidMessageError");class Za extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Protocol error"),this.name="ProtocolError"}}e(Za,"name","ProtocolError");let $a=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Timed out"),this.name="TimeoutError"}};e($a,"name","TimeoutError");class Xa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not started"),this.name="NotStartedError"}}e(Xa,"name","NotStartedError");class es extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Already started"),this.name="AlreadyStartedError"}}e(es,"name","AlreadyStartedError");class ts extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Dial error"),this.name="DialError"}}e(ts,"name","DialError");class rs extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Listen error"),this.name="ListenError"}}e(rs,"name","ListenError");class ns extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Limited connection"),this.name="LimitedConnectionError"}}e(ns,"name","LimitedConnectionError");class is extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Too many inbound protocol streams"),this.name="TooManyInboundProtocolStreamsError"}}e(is,"name","TooManyInboundProtocolStreamsError");class os extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Too many outbound protocol streams"),this.name="TooManyOutboundProtocolStreamsError"}}e(os,"name","TooManyOutboundProtocolStreamsError");class as extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unsupported key type"),this.name="UnsupportedKeyTypeError"}}e(as,"name","UnsupportedKeyTypeError");class ss extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not implemented"),this.name="NotImplementedError"}}e(ss,"name","NotImplementedError");var ls=new WeakMap;let us=class extends EventTarget{constructor(){super(),n(this,ls,new Map)}listenerCount(e){var t=o(ls,this).get(e);return null==t?0:t.length}addEventListener(e,t,r){var n;super.addEventListener(e,t,r);var i=o(ls,this).get(e);null==i&&(i=[],o(ls,this).set(e,i)),i.push({callback:t,once:null!==(n=!0!==r&&!1!==r&&(null==r?void 0:r.once))&&void 0!==n&&n})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),null!=t?t:null,r);var n=o(ls,this).get(e);null!=n&&(n=n.filter((e=>{var{callback:r}=e;return r!==t})),o(ls,this).set(e,n))}dispatchEvent(e){var t=super.dispatchEvent(e),r=o(ls,this).get(e.type);return null==r||(r=r.filter((e=>{var{once:t}=e;return!t})),o(ls,this).set(e.type,r)),t}safeDispatchEvent(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.dispatchEvent(new CustomEvent(e,t))}};function cs(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}function ds(){return hs.apply(this,arguments)}function hs(){return hs=r((function*(){for(var e=[],t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];for(var o of n)cs(o)&&e.push(o);yield Promise.all(e.map(function(){var e=r((function*(e){null!=e.beforeStart&&(yield e.beforeStart())}));return function(t){return e.apply(this,arguments)}}())),yield Promise.all(e.map(function(){var e=r((function*(e){yield e.start()}));return function(t){return e.apply(this,arguments)}}())),yield Promise.all(e.map(function(){var e=r((function*(e){null!=e.afterStart&&(yield e.afterStart())}));return function(t){return e.apply(this,arguments)}}()))})),hs.apply(this,arguments)}function vs(){return ps.apply(this,arguments)}function ps(){return ps=r((function*(){for(var e=[],t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];for(var o of n)cs(o)&&e.push(o);yield Promise.all(e.map(function(){var e=r((function*(e){null!=e.beforeStop&&(yield e.beforeStop())}));return function(t){return e.apply(this,arguments)}}())),yield Promise.all(e.map(function(){var e=r((function*(e){yield e.stop()}));return function(t){return e.apply(this,arguments)}}())),yield Promise.all(e.map(function(){var e=r((function*(e){null!=e.afterStop&&(yield e.afterStop())}));return function(t){return e.apply(this,arguments)}}()))})),ps.apply(this,arguments)}var fs=Symbol.for("@libp2p/service-capabilities"),gs=Symbol.for("@libp2p/service-dependencies"),ys=Symbol.for("@achingbrain/uint8arraylist");function ms(e,t){if(null==t||t<0)throw new RangeError("index is out of bounds");var r=0;for(var n of e){var i=r+n.byteLength;if(t<i)return{buf:n,index:t-r};r=i}throw new RangeError("index is out of bounds")}function ws(e){return Boolean(null==e?void 0:e[ys])}class bs{constructor(){e(this,"bufs",void 0),e(this,"length",void 0),e(this,ys,!0),this.bufs=[],this.length=0;for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];r.length>0&&this.appendAll(r)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.appendAll(t)}appendAll(e){var t=0;for(var r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else{if(!ws(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(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.prependAll(t)}prependAll(e){var t=0;for(var r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else{if(!ws(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){var t=ms(this.bufs,e);return t.buf[t.index]}set(e,t){var r=ms(this.bufs,e);r.buf[r.index]=t}write(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(e instanceof Uint8Array)for(var r=0;r<e.length;r++)this.set(t+r,e[r]);else{if(!ws(e))throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList");for(var n=0;n<e.length;n++)this.set(t+n,e.get(n))}}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){var{bufs:r,length:n}=this._subList(e,t);return zt(r,n)}subarray(e,t){var{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:zt(r,n)}sublist(e,t){var{bufs:r,length:n}=this._subList(e,t),i=new bs;return i.length=n,i.bufs=[...r],i}_subList(e,t){if(e=null!=e?e:0,t=null!=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};for(var r=[],n=0,i=0;i<this.bufs.length;i++){var o=this.bufs[i],a=n,s=a+o.byteLength;if(n=s,!(e>=s)){var l=e>=a&&e<s,u=t>a&&t<=s;if(l&&u){if(e===a&&t===s){r.push(o);break}var c=e-a;r.push(o.subarray(c,c+(t-e)));break}if(l){if(0===e){r.push(o);continue}r.push(o.subarray(e-a))}else{if(u){if(t===s){r.push(o);break}r.push(o.subarray(0,t-a));break}r.push(o)}}}return{bufs:r,length:t-e}}indexOf(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!(ws(e)||e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');var r=e instanceof Uint8Array?e:e.subarray();if(t=Number(null!=t?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;var n=r.byteLength;if(0===n)throw new TypeError("search must be at least 1 byte long");for(var i=new Int32Array(256),o=0;o<256;o++)i[o]=-1;for(var a=0;a<n;a++)i[r[a]]=a;for(var s,l=i,u=this.byteLength-r.byteLength,c=r.byteLength-1,d=t;d<=u;d+=s){s=0;for(var h=c;h>=0;h--){var v=this.get(d+h);if(r[h]!==v){s=Math.max(1,h-l[v]);break}}if(0===s)return d}return-1}getInt8(e){var t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){var r=dt(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){var r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){var n=ct(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){var r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){var n=ct(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){var r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){var n=ct(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){var t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){var r=dt(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){var r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){var n=ct(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){var r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){var n=ct(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){var r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){var n=ct(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){var r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){var n=ct(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){var r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){var n=ct(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 bs))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(var t=0;t<this.bufs.length;t++)if(!Et(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){var r=new bs;return r.bufs=e,null==t&&(t=e.reduce(((e,t)=>e+t.byteLength),0)),r.length=t,r}}var Ss=parseInt("11111",2),Es=parseInt("10000000",2),ks=parseInt("01111111",2),xs={0:Is,1:Is,2:function(e,t){for(var r=Cs(e,t),n=t.offset,i=t.offset+r,o=[],a=n;a<i;a++)a===n&&0===e[a]||o.push(e[a]);return t.offset+=r,Uint8Array.from(o)},3:function(e,t){var r=Cs(e,t),n=e[t.offset];t.offset++;var i=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 i},4:function(e,t){var r=Cs(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){var r=Cs(e,t),n=t.offset+r,i=e[t.offset];t.offset++;var o=0,a=0;i<40?(o=0,a=i):i<80?(o=1,a=i-40):(o=2,a=i-80);var s="".concat(o,".").concat(a),l=[];for(;t.offset<n;){var u=e[t.offset];if(t.offset++,l.push(127&u),u<128){l.reverse();for(var c=0,d=0;d<l.length;d++)c+=l[d]<<7*d;s+=".".concat(c),l=[]}}return s},16:Is,22:Is,48:Is};function As(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{offset:0},r=e[t.offset]&Ss;if(t.offset++,null!=xs[r])return xs[r](e,t);throw new Error("No decoder for tag "+r)}function Cs(e,t){var r=0;if((e[t.offset]&Es)===Es){var n=e[t.offset]&ks,i="0x";t.offset++;for(var o=0;o<n;o++,t.offset++)i+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(i,16)}else r=e[t.offset],t.offset++;return r}function Is(e,t){Cs(e,t);for(var r=[];!(t.offset>=e.byteLength);){var n=As(e,t);if(null===n)break;r.push(n)}return r}function Ts(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);var t=function(e){var t=e.toString(16);t.length%2==1&&(t="0"+t);for(var r=new bs,n=0;n<t.length;n+=2)r.append(Uint8Array.from([parseInt("".concat(t[n]).concat(t[n+1]),16)]));return r}(e.byteLength);return new bs(Uint8Array.from([t.byteLength|Es]),t)}function Ps(e){var t=new bs;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new bs(Uint8Array.from([2]),Ts(t),t)}function _s(e){var t=Uint8Array.from([0]),r=new bs(t,e);return new bs(Uint8Array.from([3]),Ts(r),r)}function Bs(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48,r=new bs;for(var n of e)r.append(n);return new bs(Uint8Array.from([t]),Ts(r),r)}var Ns="1.2.840.10045.3.1.7",Ds="1.3.132.0.34",Rs="1.3.132.0.35";function Os(){return Os=r((function*(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"P-256",t=yield crypto.subtle.generateKey({name:"ECDSA",namedCurve:e},!0,["sign","verify"]);return{publicKey:yield crypto.subtle.exportKey("jwk",t.publicKey),privateKey:yield crypto.subtle.exportKey("jwk",t.privateKey)}})),Os.apply(this,arguments)}function Ls(){return(Ls=r((function*(e,t){var r,n=yield crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:null!==(r=e.crv)&&void 0!==r?r:"P-256"},!1,["sign"]),i=yield crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,t.subarray());return new Uint8Array(i,0,i.byteLength)}))).apply(this,arguments)}function Ms(){return Ms=r((function*(e,t,r){var n,i=yield crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:null!==(n=e.crv)&&void 0!==n?n:"P-256"},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},i,t,r.subarray())})),Ms.apply(this,arguments)}var Us=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Fs=Uint8Array.from([6,5,43,129,4,0,34]),zs=Uint8Array.from([6,5,43,129,4,0,35]),js={ext:!0,kty:"EC",crv:"P-256"},Vs={ext:!0,kty:"EC",crv:"P-384"},qs={ext:!0,kty:"EC",crv:"P-521"},Hs=32,Ks=48,Ws=66;function Gs(e){var r,n,i=e[1],o=gt(i,"base64url"),a=e[2][1][0];if(i.byteLength===Hs)return r=gt(a.subarray(1,33),"base64url"),n=gt(a.subarray(33),"base64url"),new Xs(t(t({},js),{},{key_ops:["sign"],d:o,x:r,y:n}));if(i.byteLength===Ks)return r=gt(a.subarray(1,49),"base64url"),n=gt(a.subarray(49),"base64url"),new Xs(t(t({},Vs),{},{key_ops:["sign"],d:o,x:r,y:n}));if(i.byteLength===Ws)return r=gt(a.subarray(1,67),"base64url"),n=gt(a.subarray(67),"base64url"),new Xs(t(t({},qs),{},{key_ops:["sign"],d:o,x:r,y:n}));throw new Ra("Private key length was wrong length, got ".concat(i.byteLength,", expected 32, 48 or 66"))}function Qs(e){return Ys(As(e))}function Ys(e){var r,n,i=e[1][1][0];if(65===i.byteLength)return r=gt(i.subarray(1,33),"base64url"),n=gt(i.subarray(33),"base64url"),new $s(t(t({},js),{},{key_ops:["verify"],x:r,y:n}));if(97===i.byteLength)return r=gt(i.subarray(1,49),"base64url"),n=gt(i.subarray(49),"base64url"),new $s(t(t({},Vs),{},{key_ops:["verify"],x:r,y:n}));if(133===i.byteLength)return r=gt(i.subarray(1,67),"base64url"),n=gt(i.subarray(67),"base64url"),new $s(t(t({},qs),{},{key_ops:["verify"],x:r,y:n}));throw new Ra("coordinates were wrong length, got ".concat(i.byteLength,", expected 65, 97 or 133"))}function Js(e){if("P-256"===e)return Us;if("P-384"===e)return Fs;if("P-521"===e)return zs;throw new Ra("Invalid curve ".concat(e))}function Zs(){return Zs=r((function*(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"P-256",t=yield function(){return Os.apply(this,arguments)}(e);return new Xs(t.privateKey)})),Zs.apply(this,arguments)}class $s{constructor(t){e(this,"type","ECDSA"),e(this,"jwk",void 0),e(this,"_raw",void 0),this.jwk=t}get raw(){return null==this._raw&&(this._raw=function(e){var t,r;return Bs([Ps(Uint8Array.from([1])),Bs([Js(e.crv)],160),Bs([_s(new bs(Uint8Array.from([4]),xt(null!==(t=e.x)&&void 0!==t?t:"","base64url"),xt(null!==(r=e.y)&&void 0!==r?r:"","base64url")))],161)]).subarray()}(this.jwk)),this._raw}toMultihash(){return Ge.digest(Au(this))}toCID(){return it.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Et(this.raw,e.raw)}verify(e,t){var n=this;return r((function*(){return function(e,t,r){return Ms.apply(this,arguments)}(n.jwk,t,e)}))()}}class Xs{constructor(t){e(this,"type","ECDSA"),e(this,"jwk",void 0),e(this,"publicKey",void 0),e(this,"_raw",void 0),this.jwk=t,this.publicKey=new $s({crv:t.crv,ext:t.ext,key_ops:["verify"],kty:"EC",x:t.x,y:t.y})}get raw(){var e,t,r,n,i;return null==this._raw&&(this._raw=(e=this.jwk,Bs([Ps(Uint8Array.from([1])),(i=xt(null!==(t=e.d)&&void 0!==t?t:"","base64url"),new bs(Uint8Array.from([4]),Ts(i),i)),Bs([Js(e.crv)],160),Bs([_s(new bs(Uint8Array.from([4]),xt(null!==(r=e.x)&&void 0!==r?r:"","base64url"),xt(null!==(n=e.y)&&void 0!==n?n:"","base64url")))],161)]).subarray())),this._raw}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Et(this.raw,e.raw)}sign(e){var t=this;return r((function*(){return function(e,t){return Ls.apply(this,arguments)}(t.jwk,e)}))()}}var el=64;function tl(){var e=Zo.utils.randomPrivateKey(),t=Zo.getPublicKey(e),r=function(e,t){for(var r=new Uint8Array(el),n=0;n<32;n++)r[n]=e[n],r[32+n]=t[n];return r}(e,t);return{privateKey:r,publicKey:t}}class rl{constructor(t){e(this,"type","Ed25519"),e(this,"raw",void 0),this.raw=sl(t,32)}toMultihash(){return Ge.digest(Au(this))}toCID(){return it.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Et(this.raw,e.raw)}verify(e,t){return function(e,t,r){return Zo.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this.raw,t,e)}}class nl{constructor(t,r){e(this,"type","Ed25519"),e(this,"raw",void 0),e(this,"publicKey",void 0),this.raw=sl(t,el),this.publicKey=new rl(r)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Et(this.raw,e.raw)}sign(e){return t=this.raw,r=e,n=t.subarray(0,32),Zo.sign(r instanceof Uint8Array?r:r.subarray(),n);var t,r,n}}function il(e){if(e.length>el){var t=(e=sl(e,96)).subarray(0,el),r=e.subarray(el,e.length);return new nl(t,r)}var n=(e=sl(e,el)).subarray(0,el),i=e.subarray(32);return new nl(n,i)}function ol(e){return e=sl(e,32),new rl(e)}function al(){return al=r((function*(){var{privateKey:e,publicKey:t}=tl();return new nl(e,t)})),al.apply(this,arguments)}function sl(e,t){if((e=Uint8Array.from(null!=e?e:[])).length!==t)throw new Ra("Key must be a Uint8Array of length ".concat(t,", got ").concat(e.length));return e}var ll=new Float32Array([-0]),ul=new Uint8Array(ll.buffer);function cl(e,t,r){ll[0]=e,t[r]=ul[0],t[r+1]=ul[1],t[r+2]=ul[2],t[r+3]=ul[3]}var dl=new Float64Array([-0]),hl=new Uint8Array(dl.buffer);function vl(e,t,r){dl[0]=e,t[r]=hl[0],t[r+1]=hl[1],t[r+2]=hl[2],t[r+3]=hl[3],t[r+4]=hl[4],t[r+5]=hl[5],t[r+6]=hl[6],t[r+7]=hl[7]}var pl=BigInt(Number.MAX_SAFE_INTEGER),fl=BigInt(Number.MIN_SAFE_INTEGER);class gl{constructor(t,r){e(this,"lo",void 0),e(this,"hi",void 0),this.lo=0|t,this.hi=0|r}toNumber(){if(!(arguments.length>0&&void 0!==arguments[0]&&arguments[0])&&this.hi>>>31>0){var e=1+~this.lo>>>0,t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(){if(arguments.length>0&&void 0!==arguments[0]&&arguments[0])return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){var e=1+~this.lo>>>0,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(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this.toBigInt(e).toString()}zzEncode(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){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}static fromBigInt(e){if(0n===e)return yl;if(e<pl&&e>fl)return this.fromNumber(Number(e));var t=e<0n;t&&(e=-e);var r=e>>32n,n=e-(r<<32n);return t&&(r=0n|~r,n=0n|~n,++n>ml&&(n=0n,++r>ml&&(r=0n))),new gl(Number(n),Number(r))}static fromNumber(e){if(0===e)return yl;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 gl(r,n)}static from(e){return"number"==typeof e?gl.fromNumber(e):"bigint"==typeof e?gl.fromBigInt(e):"string"==typeof e?gl.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new gl(e.low>>>0,e.high>>>0):yl}}var yl=new gl(0,0);yl.toBigInt=function(){return 0n},yl.zzEncode=yl.zzDecode=function(){return this},yl.length=function(){return 1};var ml=4294967296n;function wl(e,t,r){for(var n,i,o=r,a=0;a<e.length;++a)(n=e.charCodeAt(a))<128?t[r++]=n:n<2048?(t[r++]=n>>6|192,t[r++]=63&n|128):55296==(64512&n)&&56320==(64512&(i=e.charCodeAt(a+1)))?(n=65536+((1023&n)<<10)+(1023&i),++a,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-o}function bl(e,t){return RangeError("index out of range: ".concat(e.pos," + ").concat(null!=t?t:1," > ").concat(e.len))}function Sl(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class El{constructor(t){e(this,"buf",void 0),e(this,"pos",void 0),e(this,"len",void 0),e(this,"_slice",Uint8Array.prototype.subarray),this.buf=t,this.pos=0,this.len=t.length}uint32(){var 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,bl(this,10);return e}int32(){return 0|this.uint32()}sint32(){var e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw bl(this,4);return Sl(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw bl(this,4);return 0|Sl(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw bl(this,4);var e=function(e,t){return ul[0]=e[t],ul[1]=e[t+1],ul[2]=e[t+2],ul[3]=e[t+3],ll[0]}(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw bl(this,4);var e=function(e,t){return hl[0]=e[t],hl[1]=e[t+1],hl[2]=e[t+2],hl[3]=e[t+3],hl[4]=e[t+4],hl[5]=e[t+5],hl[6]=e[t+6],hl[7]=e[t+7],dl[0]}(this.buf,this.pos);return this.pos+=8,e}bytes(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw bl(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){var e=this.bytes();return function(e,t,r){var n;if(r-t<1)return"";for(var i,o=[],a=0;t<r;)(i=e[t++])<128?o[a++]=i:i>191&&i<224?o[a++]=(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,o[a++]=55296+(i>>10),o[a++]=56320+(1023&i)):o[a++]=(15&i)<<12|(63&e[t++])<<6|63&e[t++],a>8191&&((null!=n?n:n=[]).push(String.fromCharCode.apply(String,o)),a=0);return null!=n?(a>0&&n.push(String.fromCharCode.apply(String,o.slice(0,a))),n.join("")):String.fromCharCode.apply(String,o.slice(0,a))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw bl(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw bl(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 ".concat(e," at offset ").concat(this.pos))}return this}readLongVarint(){var e=new gl(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw bl(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 bl(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 bl(this,8);var e=Sl(this.buf,this.pos+=4),t=Sl(this.buf,this.pos+=4);return new gl(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){var e=Mt(this.buf,this.pos);return this.pos+=Ot(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 kl(e,t,r){var n=function(e){return new El(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(n,void 0,r)}class xl{constructor(t,r,n){e(this,"fn",void 0),e(this,"len",void 0),e(this,"next",void 0),e(this,"val",void 0),this.fn=t,this.len=r,this.next=void 0,this.val=n}}function Al(){}class Cl{constructor(t){e(this,"head",void 0),e(this,"tail",void 0),e(this,"len",void 0),e(this,"next",void 0),this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}}var Il,Tl,Pl,_l,Bl,Nl,Dl,Rl,Ol=(Pl=Tl=8192,function(e){if(e<1||e>4096)return dt(e);Pl+e>Tl&&(Il=dt(Tl),Pl=0);var t=Il.subarray(Pl,Pl+=e);return 7&Pl&&(Pl=1+(7|Pl)),t});class Ll{constructor(){e(this,"len",void 0),e(this,"head",void 0),e(this,"tail",void 0),e(this,"states",void 0),this.len=0,this.head=new xl(Al,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new xl(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Fl((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(zl,10,gl.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){var t=gl.fromBigInt(e);return this._push(zl,t.length(),t)}uint64Number(e){return this._push(Lt,Ot(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){var t=gl.fromBigInt(e).zzEncode();return this._push(zl,t.length(),t)}sint64Number(e){var t=gl.fromNumber(e).zzEncode();return this._push(zl,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ml,1,e?1:0)}fixed32(e){return this._push(jl,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){var t=gl.fromBigInt(e);return this._push(jl,4,t.lo)._push(jl,4,t.hi)}fixed64Number(e){var t=gl.fromNumber(e);return this._push(jl,4,t.lo)._push(jl,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(cl,4,e)}double(e){return this._push(vl,8,e)}bytes(e){var t=e.length>>>0;return 0===t?this._push(Ml,1,0):this.uint32(t)._push(Vl,t,e)}string(e){var t=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}(e);return 0!==t?this.uint32(t)._push(wl,t,e):this._push(Ml,1,0)}fork(){return this.states=new Cl(this),this.head=this.tail=new xl(Al,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 xl(Al,0,0),this.len=0),this}ldelim(){var 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(){for(var e,t=this.head.next,r=(e=this.len,null!=globalThis.Buffer?dt(e):Ol(e)),n=0;null!=t;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}}function Ml(e,t,r){t[r]=255&e}function Ul(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class Fl extends xl{constructor(t,r){super(Ul,t,r),e(this,"next",void 0),this.next=void 0}}function zl(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 jl(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 Vl(e,t,r){t.set(e,r)}function ql(e,t,r){t.set(e,r)}function Hl(e,t,r){e.length<40?wl(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set(xt(e),r)}function Kl(e,t){var r=new Ll;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}function Wl(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function Gl(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Wl("enum",_l.VARINT,(function(e,r){var n=t(e);r.int32(n)}),(function(e){return t(e.int32())}))}function Ql(e,t){return Wl("message",_l.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(Ll.prototype.bytes=function(e){var t=e.length>>>0;return this.uint32(t),t>0&&this._push(ql,t,e),this},Ll.prototype.string=function(e){var t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Hl,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"}(_l||(_l={}));class Yl extends Error{constructor(){super(...arguments),e(this,"code","ERR_MAX_LENGTH"),e(this,"name","MaxLengthError")}}class Jl extends Error{constructor(){super(...arguments),e(this,"code","ERR_MAX_SIZE"),e(this,"name","MaxSizeError")}}function Zl(e){if(isNaN(e)||e<=0)throw new Ra("random bytes length must be a Number bigger than 0");return dn(e)}!function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"}(Bl||(Bl={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"}(Nl||(Nl={})),function(e){e.codec=()=>Gl(Nl)}(Bl||(Bl={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Bl.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.Type=Bl.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(Dl||(Dl={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Bl.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.Type=Bl.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(Rl||(Rl={}));class $l extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"An error occurred while signing a message"),this.name="SigningError"}}class Xl extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"An error occurred while verifying a message"),this.name="VerificationError"}}class eu extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Missing Web Crypto API"),this.name="WebCryptoMissingError"}}var tu={get(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:globalThis).crypto;if(null==(null==e?void 0:e.subtle))throw new eu("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 e}};let ru=class{constructor(t,r){e(this,"type","RSA"),e(this,"jwk",void 0),e(this,"_raw",void 0),e(this,"_multihash",void 0),this.jwk=t,this._multihash=r}get raw(){return null==this._raw&&(this._raw=au(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return it.createV1(114,this._multihash)}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Et(this.raw,e.raw)}verify(e,t){return function(e,t,r){return hu.apply(this,arguments)}(this.jwk,t,e)}},nu=class{constructor(t,r){e(this,"type","RSA"),e(this,"jwk",void 0),e(this,"_raw",void 0),e(this,"publicKey",void 0),this.jwk=t,this.publicKey=r}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 Ra("JWK was missing components");return Bs([Ps(Uint8Array.from([0])),Ps(xt(e.n,"base64url")),Ps(xt(e.e,"base64url")),Ps(xt(e.d,"base64url")),Ps(xt(e.p,"base64url")),Ps(xt(e.q,"base64url")),Ps(xt(e.dp,"base64url")),Ps(xt(e.dq,"base64url")),Ps(xt(e.qi,"base64url"))]).subarray()}(this.jwk)),this._raw}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Et(this.raw,e.raw)}sign(e){return function(e,t){return du.apply(this,arguments)}(this.jwk,e)}};var iu=8192,ou=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function au(e){if(null==e.n||null==e.e)throw new Ra("JWK was missing components");return Bs([ou,_s(Bs([Ps(xt(e.n,"base64url")),Ps(xt(e.e,"base64url"))]))]).subarray()}function su(e){var t=function(e){return{n:gt(e[1],"base64url"),e:gt(e[2],"base64url"),d:gt(e[3],"base64url"),p:gt(e[4],"base64url"),q:gt(e[5],"base64url"),dp:gt(e[6],"base64url"),dq:gt(e[7],"base64url"),qi:gt(e[8],"base64url"),kty:"RSA"}}(e);return function(e){if(function(e){if("RSA"!==e.kty)throw new Ra("invalid key type");if(null==e.n)throw new Ra("invalid key modulus");var t=xt(e.n,"base64url");return 8*t.length}(e)>iu)throw new Ra("Key size is too large");var t=function(e){if(null==e)throw new Ra("Missing key parameter");return{privateKey:e,publicKey:{kty:e.kty,n:e.n,e:e.e}}}(e),r=Xo(Dl.encode({Type:Bl.RSA,Data:au(t.publicKey)})),n=qe(18,r);return new nu(t.privateKey,new ru(t.publicKey,n))}(t)}function lu(e,t,r){var n=function(e){var t=As(e[1],{offset:0});return{kty:"RSA",n:gt(t[0],"base64url"),e:gt(t[1],"base64url")}}(e);null==r&&(r=qe(18,Xo(Dl.encode({Type:Bl.RSA,Data:t}))));return new ru(n,r)}function uu(){return uu=r((function*(e){if(e>iu)throw new Ra("Key size is too large");var t=yield function(e){return cu.apply(this,arguments)}(e),r=qe(18,Xo(Dl.encode({Type:Bl.RSA,Data:au(t.publicKey)})));return new nu(t.privateKey,new ru(t.publicKey,r))})),uu.apply(this,arguments)}function cu(){return cu=r((function*(e){var t=yield tu.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=yield function(e){return vu.apply(this,arguments)}(t);return{privateKey:r[0],publicKey:r[1]}})),cu.apply(this,arguments)}function du(){return(du=r((function*(e,t){var r=yield tu.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=yield tu.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}))).apply(this,arguments)}function hu(){return hu=r((function*(e,t,r){var n=yield tu.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return tu.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())})),hu.apply(this,arguments)}function vu(){return vu=r((function*(e){if(null==e.privateKey||null==e.publicKey)throw new Ra("Private and public key are required");return Promise.all([tu.get().subtle.exportKey("jwk",e.privateKey),tu.get().subtle.exportKey("jwk",e.publicKey)])})),vu.apply(this,arguments)}function pu(e){return null!=e&&("function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally)}class fu{constructor(t){e(this,"type","secp256k1"),e(this,"raw",void 0),e(this,"_key",void 0),this._key=function(e){try{return To.ProjectivePoint.fromHex(e),e}catch(e){throw new Oa(String(e))}}(t),this.raw=function(e){var t=To.ProjectivePoint.fromHex(e).toRawBytes(!0);return t}(this._key)}toMultihash(){return Ge.digest(Au(this))}toCID(){return it.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Et(this.raw,e.raw)}verify(e,t){return function(e,t,r){var n=$e.digest(r instanceof Uint8Array?r:r.subarray());if(pu(n))return n.then((r=>{var{digest:n}=r;return To.verify(t,n,e)})).catch((e=>{throw new Xl(String(e))}));try{return To.verify(t,n.digest,e)}catch(e){throw new Xl(String(e))}}(this._key,t,e)}}class gu{constructor(t,r){e(this,"type","secp256k1"),e(this,"raw",void 0),e(this,"publicKey",void 0),this.raw=function(e){try{return To.getPublicKey(e,!0),e}catch(e){throw new La(String(e))}}(t),this.publicKey=new fu(null!=r?r:function(e){try{return To.getPublicKey(e,!0)}catch(e){throw new La(String(e))}}(t))}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Et(this.raw,e.raw)}sign(e){return function(e,t){var r=$e.digest(t instanceof Uint8Array?t:t.subarray());if(pu(r))return r.then((t=>{var{digest:r}=t;return To.sign(r,e).toDERRawBytes()})).catch((e=>{throw new $l(String(e))}));try{return To.sign(r.digest,e).toDERRawBytes()}catch(e){throw new $l(String(e))}}(this.raw,e)}}function yu(e){return new gu(e)}function mu(e){return new fu(e)}function wu(){return(wu=r((function*(){var e=To.utils.randomPrivateKey();return new gu(e)}))).apply(this,arguments)}function bu(e,t){return Su.apply(this,arguments)}function Su(){return Su=r((function*(e,t){if("Ed25519"===e)return function(){return al.apply(this,arguments)}();if("secp256k1"===e)return function(){return wu.apply(this,arguments)}();if("RSA"===e)return function(e){return uu.apply(this,arguments)}(function(e){if(null==e)return 2048;return parseInt(e,10)}(t));if("ECDSA"===e)return function(){return Zs.apply(this,arguments)}(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 Ra("Unsupported curve, should be P-256, P-384 or P-521")}(t));throw new as})),Su.apply(this,arguments)}function Eu(e,t){var{Type:r,Data:n}=Dl.decode(e),i=null!=n?n:new Uint8Array;switch(r){case Bl.RSA:return function(e,t){if(e.byteLength>=1062)throw new Oa("Key size is too large");return lu(As(e,{offset:0}),e,t)}(i,t);case Bl.Ed25519:return ol(i);case Bl.secp256k1:return mu(i);case Bl.ECDSA:return Qs(i);default:throw new as}}function ku(e){var t,r;if(32===e.byteLength)return ol(e);if(33===e.byteLength)return mu(e);var n=As(e),i=null===(t=n[1])||void 0===t?void 0:t[0];if(i===Ns||i===Ds||i===Rs)return Ys(n);if("1.2.840.113549.1.1.1"===(null===(r=n[0])||void 0===r?void 0:r[0]))return lu(n,e);throw new Ra("Could not extract public key from raw bytes")}function xu(e){var{Type:t,Data:r}=Dl.decode(e.digest),n=null!=r?r:new Uint8Array;switch(t){case Bl.Ed25519:return ol(n);case Bl.secp256k1:return mu(n);case Bl.ECDSA:return Qs(n);default:throw new as}}function Au(e){return Dl.encode({Type:Bl[e.type],Data:e.raw})}function Cu(e){var t,r=Rl.decode(e),n=null!==(t=r.Data)&&void 0!==t?t:new Uint8Array;switch(r.Type){case Bl.RSA:return su(As(n));case Bl.Ed25519:return il(n);case Bl.secp256k1:return yu(n);case Bl.ECDSA:return function(e){return Gs(As(e))}(n);default:throw new as}}function Iu(e){var t;if(e.byteLength===el)return il(e);if(32===e.byteLength)return yu(e);var r=As(e),n=null===(t=r[2])||void 0===t?void 0:t[0];if(n===Ns||n===Ds||n===Rs)return Gs(r);if(r.length>8)return su(r);throw new Ra("Could not extract private key from raw bytes")}function Tu(e){return Rl.encode({Type:Bl[e.type],Data:e.raw})}function Pu(e){return _u.apply(this,arguments)}function _u(){return(_u=r((function*(e){if("RSA"===e.type)return{privateKey:yield crypto.subtle.importKey("jwk",e.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),publicKey:yield crypto.subtle.importKey("jwk",e.publicKey.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])};var t,r;if("ECDSA"===e.type)return{privateKey:yield crypto.subtle.importKey("jwk",e.jwk,{name:"ECDSA",namedCurve:null!==(t=e.jwk.crv)&&void 0!==t?t:"P-256"},!0,["sign"]),publicKey:yield crypto.subtle.importKey("jwk",e.publicKey.jwk,{name:"ECDSA",namedCurve:null!==(r=e.publicKey.jwk.crv)&&void 0!==r?r:"P-256"},!0,["verify"])};throw new Ra("Only RSA and ECDSA keys are supported")}))).apply(this,arguments)}var Bu=Symbol.for("nodejs.util.inspect.custom");class Nu{constructor(t){e(this,"type",void 0),e(this,"multihash",void 0),e(this,"publicKey",void 0),e(this,"string",void 0),e(this,Aa,!0),this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return"PeerId(".concat(this.toString(),")")}toString(){return null==this.string&&(this.string=ie.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return it.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){var t;if(null==e)return!1;if(e instanceof Uint8Array)return Et(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=(null==e||null===(t=e.toMultihash())||void 0===t?void 0:t.bytes))return Et(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Bu](){return"PeerId(".concat(this.toString(),")")}}class Du extends Nu{constructor(r){super(t(t({},r),{},{type:"RSA"})),e(this,"type","RSA"),e(this,"publicKey",void 0),this.publicKey=r.publicKey}}class Ru extends Nu{constructor(r){super(t(t({},r),{},{type:"Ed25519"})),e(this,"type","Ed25519"),e(this,"publicKey",void 0),this.publicKey=r.publicKey}}class Ou extends Nu{constructor(r){super(t(t({},r),{},{type:"secp256k1"})),e(this,"type","secp256k1"),e(this,"publicKey",void 0),this.publicKey=r.publicKey}}class Lu{constructor(t){e(this,"type","url"),e(this,"multihash",void 0),e(this,"publicKey",void 0),e(this,"url",void 0),e(this,Aa,!0),this.url=t.toString(),this.multihash=Ge.digest(xt(this.url))}[Bu](){return"PeerId(".concat(this.url,")")}toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return it.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=gt(e)),e.toString()===this.toString())}}function Mu(e,t){if("1"!==e.charAt(0)&&"Q"!==e.charAt(0)){if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return ju(it.parse(e));throw new Ra('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return zu(He(ie.decode("z".concat(e))))}function Uu(e){if("Ed25519"===e.type)return new Ru({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new Ou({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new Du({multihash:e.toCID().multihash,publicKey:e});throw new as}function Fu(e){return Uu(e.publicKey)}function zu(e){if(function(e){return e.code===$e.code}(e))return new Du({multihash:e});if(function(e){return e.code===Ge.code}(e))try{var t=xu(e);if("Ed25519"===t.type)return new Ru({multihash:e,publicKey:t});if("secp256k1"===t.type)return new Ou({multihash:e,publicKey:t})}catch(t){var r=gt(e.digest);return new Lu(new URL(r))}throw new Qa("Supplied PeerID Multihash is invalid")}function ju(e){if(null==(null==e?void 0:e.multihash)||null==e.version||1===e.version&&114!==e.code&&2336!==e.code)throw new Ga("Supplied PeerID CID is invalid");if(2336===e.code){var t=gt(e.multihash.digest);return new Lu(new URL(t))}return zu(e.multihash)}var Vu=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),qu=new Uint32Array(80);class Hu extends pn{constructor(){super(64,20,8,!1),this.A=0|Vu[0],this.B=0|Vu[1],this.C=0|Vu[2],this.D=0|Vu[3],this.E=0|Vu[4]}get(){var{A:e,B:t,C:r,D:n,E:i}=this;return[e,t,r,n,i]}set(e,t,r,n,i){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|i}process(e,t){for(var r=0;r<16;r++,t+=4)qu[r]=e.getUint32(t,!1);for(var n=16;n<80;n++)qu[n]=Fr(qu[n-3]^qu[n-8]^qu[n-14]^qu[n-16],1);for(var{A:i,B:o,C:a,D:s,E:l}=this,u=0;u<80;u++){var c=void 0,d=void 0;u<20?(c=hn(o,a,s),d=1518500249):u<40?(c=o^a^s,d=1859775393):u<60?(c=vn(o,a,s),d=2400959708):(c=o^a^s,d=3395469782);var h=Fr(i,5)+c+l+d+qu[u]|0;l=s,s=a,a=Fr(o,30),o=i,i=h}i=i+this.A|0,o=o+this.B|0,a=a+this.C|0,s=s+this.D|0,l=l+this.E|0,this.set(i,o,a,s,l)}roundClean(){Lr(qu)}destroy(){this.set(0,0,0,0,0),Lr(this.buffer)}}var Ku=un((()=>new Hu)),Wu=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Gu=(()=>Uint8Array.from(new Array(16).fill(0).map(((e,t)=>t))))(),Qu=(()=>Gu.map((e=>(9*e+5)%16)))(),Yu=(()=>{for(var e=[[Gu],[Qu]],t=0;t<4;t++)for(var r of e)r.push(r[t].map((e=>Wu[e])));return e})(),Ju=(()=>Yu[0])(),Zu=(()=>Yu[1])(),$u=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map((e=>Uint8Array.from(e))),Xu=Ju.map(((e,t)=>e.map((e=>$u[t][e])))),ec=Zu.map(((e,t)=>e.map((e=>$u[t][e])))),tc=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),rc=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function nc(e,t,r,n){return 0===e?t^r^n:1===e?t&r|~t&n:2===e?(t|~r)^n:3===e?t&n|r&~n:t^(r|~n)}var ic=new Uint32Array(16);class oc extends pn{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){var{h0:e,h1:t,h2:r,h3:n,h4:i}=this;return[e,t,r,n,i]}set(e,t,r,n,i){this.h0=0|e,this.h1=0|t,this.h2=0|r,this.h3=0|n,this.h4=0|i}process(e,t){for(var r=0;r<16;r++,t+=4)ic[r]=e.getUint32(t,!0);for(var n=0|this.h0,i=n,o=0|this.h1,a=o,s=0|this.h2,l=s,u=0|this.h3,c=u,d=0|this.h4,h=d,v=0;v<5;v++){for(var p=4-v,f=tc[v],g=rc[v],y=Ju[v],m=Zu[v],w=Xu[v],b=ec[v],S=0;S<16;S++){var E=Fr(n+nc(v,o,s,u)+ic[y[S]]+f,w[S])+d|0;n=d,d=u,u=0|Fr(s,10),s=o,o=E}for(var k=0;k<16;k++){var x=Fr(i+nc(p,a,l,c)+ic[m[k]]+g,b[k])+h|0;i=h,h=c,c=0|Fr(l,10),l=a,a=x}}this.set(this.h1+s+c|0,this.h2+u+h|0,this.h3+d+i|0,this.h4+n+a|0,this.h0+o+l|0)}roundClean(){Lr(ic)}destroy(){this.destroyed=!0,Lr(this.buffer),this.set(0,0,0,0,0)}}var ac=un((()=>new oc)),sc={sha1:Ku,"sha2-256":Xo,"sha2-512":ea};function lc(e,t,r,n,i){if("sha1"!==i&&"sha2-256"!==i&&"sha2-512"!==i){var o=Object.keys(sc).join(" / ");throw new Ra("Hash '".concat(i,"' is unknown or not supported. Must be ").concat(o))}var a=function(e,t,r,n){for(var i,{c:o,dkLen:a,DK:s,PRF:l,PRFSalt:u}=ta(e,t,r,n),c=new Uint8Array(4),d=Mr(c),h=new Uint8Array(l.outputLen),v=1,p=0;p<a;v++,p+=l.outputLen){var f=s.subarray(p,p+l.outputLen);d.setInt32(0,v,!1),(i=u._cloneInto(i)).update(c).digestInto(h),f.set(h.subarray(0,f.length));for(var g=1;g<o;g++){l._cloneInto(i).update(h).digestInto(h);for(var y=0;y<f.length;y++)f[y]^=h[y]}}return ra(l,u,s,i,h)}(sc[i],e,t,{c:r,dkLen:n});return se.encode(a).substring(1)}var uc="/",cc=(new TextEncoder).encode(uc),dc=cc[0];class hc{constructor(t,r){if(e(this,"_buf",void 0),"string"==typeof t)this._buf=xt(t);else{if(!(t instanceof Uint8Array))throw new Error("Invalid key, should be String of Uint8Array");this._buf=t}if(null==r&&(r=!0),r&&this.clean(),0===this._buf.byteLength||this._buf[0]!==dc)throw new Error("Invalid key")}toString(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"utf8";return gt(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return"Key(".concat(this.toString(),")")}static withNamespaces(e){return new hc(e.join(uc))}static random(){return new hc(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new hc(e):"function"==typeof e.uint8Array?new hc(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=cc),this._buf[0]!==dc){var e=new Uint8Array(this._buf.byteLength+1);e.fill(dc,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===dc;)this._buf=this._buf.subarray(0,-1)}less(e){for(var t=this.list(),r=e.list(),n=0;n<t.length;n++){if(r.length<n+1)return!1;var i=t[n],o=r[n];if(i<o)return!0;if(i>o)return!1}return t.length<r.length}reverse(){return hc.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){var e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(uc).slice(1)}type(){return function(e){var t=e.split(":");if(t.length<2)return"";return t.slice(0,-1).join(":")}(this.baseNamespace())}name(){return e=this.baseNamespace(),(t=e.split(":"))[t.length-1];var e,t}instance(e){return new hc(this.toString()+":"+e)}path(){var e=this.parent().toString();return e.endsWith(uc)||(e+=uc),e+=this.type(),new hc(e)}parent(){var e=this.list();return 1===e.length?new hc(uc):new hc(e.slice(0,-1).join(uc))}child(e){return this.toString()===uc?e:e.toString()===uc?this:new hc(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(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return hc.withNamespaces([...this.namespaces(),...(n=t.map((e=>e.namespaces())),[].concat(...n))]);var n}}function vc(e){if(null!=e[Symbol.asyncIterator])return r((function*(){var t,r=!1,n=!1;try{for(var i,o=s(e);r=!(i=yield o.next()).done;r=!1)i.value}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield o.return())}finally{if(n)throw t}}}))();for(var t of e);}function pc(e){var[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}}}function fc(e,t){var r=0;if(null!=e[Symbol.asyncIterator])return l((function*(){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var c=a.value;(yield u(t(c,r++)))&&(yield c)}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}))();var n=pc(e),{value:i,done:o}=n.next();if(!0===o)return function*(){}();var a=t(i,r++);if("function"==typeof a.then)return l((function*(){for(var e of((yield u(a))&&(yield i),n))(yield u(t(e,r++)))&&(yield e)}))();var c=t;return function*(){for(var e of(!0===a&&(yield i),n))c(e,r++)&&(yield e)}()}function gc(e){if(null!=e[Symbol.asyncIterator])return r((function*(){var t,r=[],n=!1,i=!1;try{for(var o,a=s(e);n=!(o=yield a.next()).done;n=!1){var l=o.value;r.push(l)}}catch(e){i=!0,t=e}finally{try{n&&null!=a.return&&(yield a.return())}finally{if(i)throw t}}return r}))();var t=[];for(var n of e)t.push(n);return t}function yc(e,t){return null!=e[Symbol.asyncIterator]?l((function*(){var r=yield u(gc(e));yield*c(s(r.sort(t)))}))():function*(){var r=gc(e);yield*r.sort(t)}()}function mc(e,t){return null!=e[Symbol.asyncIterator]?l((function*(){var r=0;if(!(t<1)){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var c=a.value;if(yield c,++r===t)return}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}}))():function*(){var r=0;if(!(t<1))for(var n of e)if(yield n,++r===t)return}()}class wc{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"))}putMany(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var{key:c,value:d}=a.value;yield u(t.put(c,d,r)),yield c}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}()})).apply(this,arguments)}getMany(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var c=a.value;yield{key:c,value:yield u(t.get(c,r))}}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}()})).apply(this,arguments)}deleteMany(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var c=a.value;yield u(t.delete(c,r)),yield c}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}()})).apply(this,arguments)}batch(){var e,t=this,n=[],i=[];return{put(e,t){n.push({key:e,value:t})},delete(e){i.push(e)},commit:(e=r((function*(e){yield vc(t.putMany(n,e)),n=[],yield vc(t.deleteMany(i,e)),i=[]})),function(t){return e.apply(this,arguments)})}}_all(e,t){return l((function*(){throw new Error("._all is not implemented")}))()}_allKeys(e,t){return l((function*(){throw new Error("._allKeys is not implemented")}))()}query(e,t){var r=this._all(e,t);if(null!=e.prefix){var n=e.prefix;r=fc(r,(e=>e.key.toString().startsWith(n)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>fc(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>yc(e,t)),r)),null!=e.offset){var i=0,o=e.offset;r=fc(r,(()=>i++>=o))}return null!=e.limit&&(r=mc(r,e.limit)),r}queryKeys(e,t){var r=this._allKeys(e,t);if(null!=e.prefix){var n=e.prefix;r=fc(r,(e=>e.toString().startsWith(n)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>fc(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>yc(e,t)),r)),null!=e.offset){var i=e.offset,o=0;r=fc(r,(()=>o++>=i))}return null!=e.limit&&(r=mc(r,e.limit)),r}}class bc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Open failed"),e(this,"name",bc.name),e(this,"code",bc.code)}}e(bc,"name","OpenFailedError"),e(bc,"code","ERR_OPEN_FAILED");class Sc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Close failed"),e(this,"name",Sc.name),e(this,"code",Sc.code)}}e(Sc,"name","CloseFailedError"),e(Sc,"code","ERR_CLOSE_FAILED");class Ec extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Put failed"),e(this,"name",Ec.name),e(this,"code",Ec.code)}}e(Ec,"name","PutFailedError"),e(Ec,"code","ERR_PUT_FAILED");class kc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Get failed"),e(this,"name",kc.name),e(this,"code",kc.code)}}e(kc,"name","GetFailedError"),e(kc,"code","ERR_GET_FAILED");class xc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Delete failed"),e(this,"name",xc.name),e(this,"code",xc.code)}}e(xc,"name","DeleteFailedError"),e(xc,"code","ERR_DELETE_FAILED");class Ac extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Has failed"),e(this,"name",Ac.name),e(this,"code",Ac.code)}}e(Ac,"name","HasFailedError"),e(Ac,"code","ERR_HAS_FAILED");let Cc=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not Found"),e(this,"name",t.name),e(this,"code",t.code)}};e(Cc,"name","NotFoundError"),e(Cc,"code","ERR_NOT_FOUND");let Ic=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Aborted"),e(this,"name",t.name),e(this,"code",t.code)}};e(Ic,"name","AbortError"),e(Ic,"code","ERR_ABORTED");class Tc extends wc{constructor(){super(),e(this,"data",void 0),this.data=new Map}put(e,t,r){var n;return null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){var r;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted();var n=this.data.get(e.toString());if(null==n)throw new Cc;return n}has(e,t){var r;return null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.data.has(e.toString())}delete(e,t){var r;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){var r;for(var[n,i]of(null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.data.entries())){var o;yield{key:new hc(n),value:i},null==t||null===(o=t.signal)||void 0===o||o.throwIfAborted()}}*_allKeys(e,t){var r;for(var n of(null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.data.keys())){var i;yield new hc(n),null==t||null===(i=t.signal)||void 0===i||i.throwIfAborted()}}}function Pc(e,t){var r=0;if(null!=e[Symbol.asyncIterator])return l((function*(){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var c=a.value;yield t(c,r++)}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}))();var n=pc(e),{value:i,done:o}=n.next();if(!0===o)return function*(){}();var a=t(i,r++);if("function"==typeof a.then)return l((function*(){for(var e of(yield yield u(a),n))yield t(e,r++)}))();var c=t;return function*(){for(var e of(yield a,n))yield c(e,r++)}()}function _c(){var e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}class Bc{constructor(t){if(e(this,"buffer",void 0),e(this,"mask",void 0),e(this,"top",void 0),e(this,"btm",void 0),e(this,"next",void 0),!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-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(){var 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 Nc{constructor(){var t,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e(this,"size",void 0),e(this,"hwm",void 0),e(this,"head",void 0),e(this,"tail",void 0),this.hwm=null!==(t=r.splitLimit)&&void 0!==t?t:16,this.head=new Bc(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return null!=(null==e?void 0:e.byteLength)?e.byteLength:1}push(e){if(null!=(null==e?void 0:e.value)&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){var t=this.head;this.head=t.next=new Bc(2*this.head.buffer.length),this.head.push(e)}}shift(){var e,t=this.tail.shift();if(void 0===t&&null!=this.tail.next){var r=this.tail.next;this.tail.next=null,this.tail=r,t=this.tail.shift()}return null!=(null===(e=t)||void 0===e?void 0:e.value)&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}}let Dc=class extends Error{constructor(t,r){super(null!=t?t:"The operation was aborted"),e(this,"type",void 0),e(this,"code",void 0),this.type="aborted",this.code=null!=r?r:"ABORT_ERR"}};function Rc(){return function(e,t){t=null!=t?t:{};var n,i,o,a=t.onEnd,s=new Nc,l=_c(),u=function(){var t=r((function*(){try{return s.isEmpty()?o?{done:!0}:yield new Promise(((t,r)=>{i=o=>{i=null,s.push(o);try{t(e(s))}catch(e){r(e)}return n}})):e(s)}finally{s.isEmpty()&&queueMicrotask((()=>{l.resolve(),l=_c()}))}}));return function(){return t.apply(this,arguments)}}(),c=e=>null!=i?i(e):(s.push(e),n),d=e=>(s=new Nc,null!=i?i({error:e}):(s.push({error:e}),n)),h=e=>{var r;if(o)return n;if(!0!==(null===(r=t)||void 0===r?void 0:r.objectMode)&&null==(null==e?void 0:e.byteLength))throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:e})},v=e=>o?n:(o=!0,null!=e?d(e):c({done:!0})),p=()=>(s=new Nc,v(),{done:!0}),f=e=>(v(e),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:u,return:p,throw:f,push:h,end:v,get readableLength(){return s.size},onEmpty:function(){var e=r((function*(e){var t=null==e?void 0:e.signal;if(null==t||t.throwIfAborted(),!s.isEmpty()){var r,n;null!=t&&(r=new Promise(((e,r)=>{n=()=>{r(new Dc)},t.addEventListener("abort",n)})));try{yield Promise.race([l.promise,r])}finally{null!=n&&null!=t&&(null==t||t.removeEventListener("abort",n))}}}));function t(t){return e.apply(this,arguments)}return t}()},null==a)return n;var g=n;return n={[Symbol.asyncIterator](){return this},next:()=>g.next(),throw:e=>(g.throw(e),null!=a&&(a(e),a=void 0),{done:!0}),return:()=>(g.return(),null!=a&&(a(),a=void 0),{done:!0}),push:h,end:e=>(g.end(e),null!=a&&(a(e),a=void 0),n),get readableLength(){return g.readableLength},onEmpty:e=>g.onEmpty(e)},n}((e=>{var t=e.shift();if(null==t)return{done:!0};if(null!=t.error)throw t.error;return{done:!0===t.done,value:t.value}}),arguments.length>0&&void 0!==arguments[0]?arguments[0]:{})}let Oc=class extends Error{constructor(t,r,n){super(null!=t?t:"The operation was aborted"),e(this,"type",void 0),e(this,"code",void 0),this.type="aborted",this.name=null!=n?n:"AbortError",this.code=null!=r?r:"ABORT_ERR"}};function Lc(e,t,r){return Mc.apply(this,arguments)}function Mc(){return(Mc=r((function*(e,t,r){if(null==t)return e;if(t.aborted)return e.catch((()=>{})),Promise.reject(new Oc(null==r?void 0:r.errorMessage,null==r?void 0:r.errorCode,null==r?void 0:r.errorName));var n,i=new Oc(null==r?void 0:r.errorMessage,null==r?void 0:r.errorCode,null==r?void 0:r.errorName);try{return yield Promise.race([e,new Promise(((e,r)=>{n=()=>{r(i)},t.addEventListener("abort",n)}))])}finally{null!=n&&t.removeEventListener("abort",n)}}))).apply(this,arguments)}let Uc=class{constructor(){e(this,"readNext",void 0),e(this,"haveNext",void 0),e(this,"ended",void 0),e(this,"nextResult",void 0),e(this,"error",void 0),this.ended=!1,this.readNext=_c(),this.haveNext=_c()}[Symbol.asyncIterator](){return this}next(){var e=this;return r((function*(){if(null==e.nextResult&&(yield e.haveNext.promise),null==e.nextResult)throw new Error("HaveNext promise resolved but nextResult was undefined");var t=e.nextResult;return e.nextResult=void 0,e.readNext.resolve(),e.readNext=_c(),t}))()}throw(e){var t=this;return r((function*(){return t.ended=!0,t.error=e,null!=e&&(t.haveNext.promise.catch((()=>{})),t.haveNext.reject(e)),{done:!0,value:void 0}}))()}return(){var e=this;return r((function*(){var t={done:!0,value:void 0};return e.ended=!0,e.nextResult=t,e.haveNext.resolve(),t}))()}push(e,t){var n=this;return r((function*(){yield n._push(e,t)}))()}end(e,t){var n=this;return r((function*(){null!=e?yield n.throw(e):yield n._push(void 0,t)}))()}_push(e,t){var n=this;return r((function*(){var r;if(null!=e&&n.ended)throw null!==(r=n.error)&&void 0!==r?r:new Error("Cannot push value onto an ended pushable");for(;null!=n.nextResult;)yield n.readNext.promise;null!=e?n.nextResult={done:!1,value:e}:(n.ended=!0,n.nextResult={done:!0,value:void 0}),n.haveNext.resolve(),n.haveNext=_c(),yield Lc(n.readNext.promise,null==t?void 0:t.signal,t)}))()}};function Fc(){return new Uc}function zc(){return zc=r((function*(e,t,n){try{yield Promise.all(e.map(function(){var e=r((function*(e){var r,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield l.next()).done;i=!1){var u=a.value;yield t.push(u,{signal:n}),n.throwIfAborted()}}catch(e){o=!0,r=e}finally{try{i&&null!=l.return&&(yield l.return())}finally{if(o)throw r}}}));return function(t){return e.apply(this,arguments)}}())),yield t.end(void 0,{signal:n})}catch(e){yield t.end(e,{signal:n}).catch((()=>{}))}})),zc.apply(this,arguments)}function jc(){return jc=l((function*(e){var t=new AbortController,r=Fc();(function(e,t,r){return zc.apply(this,arguments)})(e,r,t.signal).catch((()=>{}));try{yield*c(s(r),u)}finally{t.abort()}})),jc.apply(this,arguments)}function Vc(){for(var e=[],t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];for(var i of r)null==i[Symbol.asyncIterator]&&e.push(i);return e.length===r.length?function*(e){for(var t of e)yield*t}(e):function(e){return jc.apply(this,arguments)}(r)}function qc(e){if(null==e)throw new Error("Empty pipeline");if(Gc(e)){var t=e;e=()=>t.source}else if(Wc(e)||Kc(e)){var r=e;e=()=>r}for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;o<n;o++)i[o-1]=arguments[o];var a=[e,...i];if(a.length>1&&Gc(a[a.length-1])&&(a[a.length-1]=a[a.length-1].sink),a.length>2)for(var s=1;s<a.length-1;s++)Gc(a[s])&&(a[s]=Qc(a[s]));return Hc(...a)}var Hc=function(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];for(;r.length>0;)e=r.shift()(e);return e},Kc=e=>null!=(null==e?void 0:e[Symbol.asyncIterator]),Wc=e=>null!=(null==e?void 0:e[Symbol.iterator]),Gc=e=>null!=e&&(null!=e.sink&&null!=e.source),Qc=e=>t=>{var r=e.sink(t);if(null!=(null==r?void 0:r.then)){var n,i=Rc({objectMode:!0});r.then((()=>{i.end()}),(e=>{i.end(e)}));var o=e.source;if(Kc(o))n=function(){var e=l((function*(){yield*c(s(o)),i.end()}));return function(){return e.apply(this,arguments)}}();else{if(!Wc(o))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");n=function*(){yield*o,i.end()}}return Vc(i,n())}return e.source};new hc("SHARDING");var Yc,Jc,Zc=1e3,$c=60*Zc,Xc=60*$c,ed=24*Xc,td=7*ed,rd=365.25*ed;function nd(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.");var 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;var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*rd;case"weeks":case"week":case"w":return r*td;case"days":case"day":case"d":return r*ed;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Xc;case"minutes":case"minute":case"mins":case"min":case"m":return r*$c;case"seconds":case"second":case"secs":case"sec":case"s":return r*Zc;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:throw new Error("The unit ".concat(n," was matched, but no matching case exists."))}}(e);if("number"==typeof e&&isFinite(e))return null!=t&&t.long?function(e){var t=Math.abs(e);if(t>=ed)return id(e,t,ed,"day");if(t>=Xc)return id(e,t,Xc,"hour");if(t>=$c)return id(e,t,$c,"minute");if(t>=Zc)return id(e,t,Zc,"second");return"".concat(e," ms")}(e):function(e){var t=Math.abs(e);if(t>=ed)return"".concat(Math.round(e/ed),"d");if(t>=Xc)return"".concat(Math.round(e/Xc),"h");if(t>=$c)return"".concat(Math.round(e/$c),"m");if(t>=Zc)return"".concat(Math.round(e/Zc),"s");return"".concat(e,"ms")}(e);throw new Error("Value is not a string or number.")}catch(t){var r=function(e){return"object"==typeof e&&null!==e&&"message"in e}(t)?"".concat(t.message,". value=").concat(JSON.stringify(e)):"An unknown error has occured.";throw new Error(r)}}function id(e,t,r,n){var i=t>=1.5*r;return"".concat(Math.round(e/r)," ").concat(n).concat(i?"s":"")}var od=function(){try{return localStorage}catch(e){}}();var ad=null!==(Yc=null!==(Jc=console.debug)&&void 0!==Jc?Jc:console.log)&&void 0!==Yc?Yc:()=>{};var sd,ld,ud=function(e){function t(e){var n,i,o,a=null;function s(){for(var e=arguments.length,r=new Array(e),i=0;i<e;i++)r[i]=arguments[i];if(s.enabled){var o=s,a=Number(new Date),l=a-(n||a);o.diff=l,o.prev=n,o.curr=a,n=a,r[0]=t.coerce(r[0]),"string"!=typeof r[0]&&r.unshift("%O");var u=0;r[0]=r[0].replace(/%([a-zA-Z%])/g,((e,n)=>{if("%%"===e)return"%";u++;var i=t.formatters[n];if("function"==typeof i){var a=r[u];e=i.call(o,a),r.splice(u,1),u--}return e})),t.formatArgs.call(o,r),(o.log||t.log).apply(o,r)}}return s.namespace=e,s.useColors=t.useColors(),s.color=t.selectColor(e),s.extend=r,s.destroy=t.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(i!==t.namespaces&&(i=t.namespaces,o=t.enabled(e)),o),set:e=>{a=e}}),"function"==typeof t.init&&t.init(s),s}function r(e,r){var 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){var t;return e instanceof Error?null!==(t=e.stack)&&void 0!==t?t:e.message:e},t.disable=function(){var e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){var r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];var n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r<i;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;var 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=nd,t.destroy=function(){},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){for(var r=0,n=0;n<e.length;n++)r=(r<<5)-r+e.charCodeAt(n),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 ":" ")+"+"+nd(this.diff),this.useColors){var t="color: "+this.color;e.splice(1,0,t,"color: inherit");var 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?null==od||od.setItem("debug",e):null==od||od.removeItem("debug")}catch(e){}},load:function(){var e;try{e=null==od?void 0:od.getItem("debug")}catch(e){}return!e&&void 0!==globalThis.process&&"env"in globalThis.process&&(e=globalThis.process.env.DEBUG),e},useColors:function(){var e,t,r,n;return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||null==(null===(e=navigator.userAgent)||void 0===e?void 0:e.toLowerCase().match(/(edge|trident)\/(\d+)/)))&&("undefined"!=typeof document&&(null===(t=document.documentElement)||void 0===t||null===(t=t.style)||void 0===t?void 0:t.WebkitAppearance)||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&null!=(null===(r=navigator.userAgent)||void 0===r?void 0:r.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&(null===(n=navigator.userAgent)||void 0===n?void 0:n.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:od,log:ad});function cd(){return{forComponent:e=>dd(e)}}function dd(e){var t=function(e){var t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}("".concat(e,":trace"));return ud.enabled("".concat(e,":trace"))&&null!=ud.names.map((e=>e.toString())).find((e=>e.includes(":trace")))&&(t=ud("".concat(e,":trace"))),Object.assign(ud(e),{error:ud("".concat(e,":error")),trace:t})}function hd(e){if(null!=e&&0!==(e=e.trim()).length)return e}ud.formatters.b=e=>null==e?"undefined":ie.baseEncode(e),ud.formatters.t=e=>null==e?"undefined":K.baseEncode(e),ud.formatters.m=e=>null==e?"undefined":se.baseEncode(e),ud.formatters.p=e=>null==e?"undefined":e.toString(),ud.formatters.c=e=>null==e?"undefined":e.toString(),ud.formatters.k=e=>null==e?"undefined":e.toString(),ud.formatters.a=e=>null==e?"undefined":e.toString(),ud.formatters.e=e=>{var t,r;return null==e?"undefined":null!==(t=null!==(r=hd(e.stack))&&void 0!==r?r:hd(e.message))&&void 0!==t?t:e.toString()},dd("datastore:core:tiered");class vd{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,r){return Promise.reject(new Error(".put is not implemented"))}putMany(e,t){var r=this;return l((function*(){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var{cid:c,block:d}=a.value;yield u(r.put(c,d,t)),yield c}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}))()}get(e,t){return Promise.reject(new Error(".get is not implemented"))}getMany(e,t){var r=this;return l((function*(){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var c=a.value;yield{cid:c,block:yield u(r.get(c,t))}}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}))()}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}deleteMany(e,t){var r=this;return l((function*(){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var c=a.value;yield u(r.delete(c,t)),yield c}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}))()}getAll(e){return l((function*(){throw new Error(".getAll is not implemented")}))()}}class pd extends vd{constructor(){super(),e(this,"data",void 0),this.data=new Map}put(e,t,r){var n;return null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted(),this.data.set(K.encode(e.multihash.bytes),t),e}get(e,t){var r;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted();var n=this.data.get(K.encode(e.multihash.bytes));if(null==n)throw new Cc;return n}has(e,t){var r;return null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.data.has(K.encode(e.multihash.bytes))}delete(e,t){var n=this;return r((function*(){var r;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),n.data.delete(K.encode(e.multihash.bytes))}))()}getAll(e){var t=this;return l((function*(){var r;for(var[n,i]of(null==e||null===(r=e.signal)||void 0===r||r.throwIfAborted(),t.data.entries())){var o;yield{cid:it.createV1(Se,He(K.decode(n))),block:i},null==e||null===(o=e.signal)||void 0===o||o.throwIfAborted()}}))()}}dd("blockstore:core:tiered"),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!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()}),(function(e,t){for(var r={publicKey:ct(0),payloadType:ct(0),payload:ct(0),signature:ct(0)},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.publicKey=e.bytes();break;case 2:r.payloadType=e.bytes();break;case 3:r.payload=e.bytes();break;case 5:r.signature=e.bytes();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(sd||(sd={}));class fd extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid signature"),this.name="InvalidSignatureError"}}class gd{constructor(t){e(this,"publicKey",void 0),e(this,"payloadType",void 0),e(this,"payload",void 0),e(this,"signature",void 0),e(this,"marshaled",void 0);var{publicKey:r,payloadType:n,payload:i,signature:o}=t;this.publicKey=r,this.payloadType=n,this.payload=i,this.signature=o}marshal(){return null==this.marshaled&&(this.marshaled=sd.encode({publicKey:Au(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return null!=e&&Et(this.marshal(),e.marshal())}validate(e){var t=this;return r((function*(){var r=yd(e,t.payloadType,t.payload);return t.publicKey.verify(r.subarray(),t.signature)}))()}}ld=gd,e(gd,"createFromProtobuf",function(){var e=r((function*(e){var t=sd.decode(e),r=Eu(t.publicKey);return new ld({publicKey:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})}));return function(t){return e.apply(this,arguments)}}()),e(gd,"seal",function(){var e=r((function*(e,t){if(null==t)throw new Error("Missing private key");var r=e.domain,n=e.codec,i=e.marshal(),o=yd(r,n,i),a=yield t.sign(o.subarray());return new ld({publicKey:t.publicKey,payloadType:n,payload:i,signature:a})}));return function(t,r){return e.apply(this,arguments)}}()),e(gd,"openAndCertify",function(){var e=r((function*(e,t){var r=yield ld.createFromProtobuf(e);if(!(yield r.validate(t)))throw new fd("Envelope signature is not valid for the given domain");return r}));return function(t,r){return e.apply(this,arguments)}}());var yd=(e,t,r)=>{var n=xt(e),i=Ut(n.byteLength),o=Ut(t.length),a=Ut(r.length);return new bs(i,n,o,t,a,r)};var md,wd,bd=Uint8Array.from([3,1]);!function(e){var t;!function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={multiaddr:ct(0)},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();if(i>>>3==1)r.multiaddr=e.bytes();else e.skipType(7&i)}return r}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==t&&(t=Ql((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};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(var i of t.addresses)r.uint32(26),e.AddressInfo.codec().encode(i,r);!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={peerId:ct(0),seq:0n,addresses:[]},o=null==r?t.len:t.pos+r;t.pos<o;){var a=t.uint32();switch(a>>>3){case 1:i.peerId=t.bytes();break;case 2:i.seq=t.uint64();break;case 3:var s,l;if(null!=(null===(s=n.limits)||void 0===s?void 0:s.addresses)&&i.addresses.length===n.limits.addresses)throw new Yl('Decode error - map field "addresses" had too many elements');i.addresses.push(e.AddressInfo.codec().decode(t,t.uint32(),{limits:null===(l=n.limits)||void 0===l?void 0:l.addresses$}));break;default:t.skipType(7&a)}}return i}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(md||(md={}));class Sd{constructor(t){e(this,"peerId",void 0),e(this,"multiaddrs",void 0),e(this,"seqNumber",void 0),e(this,"domain",Sd.DOMAIN),e(this,"codec",Sd.CODEC),e(this,"marshaled",void 0);var{peerId:r,multiaddrs:n,seqNumber:i}=t;this.peerId=r,this.multiaddrs=null!=n?n:[],this.seqNumber=null!=i?i:BigInt(Date.now())}marshal(){return null==this.marshaled&&(this.marshaled=md.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 Sd&&(!!this.peerId.equals(e.peerId)&&(this.seqNumber===e.seqNumber&&!!function(e,t){var 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)))}}wd=Sd,e(Sd,"createFromProtobuf",(e=>{var t,r=md.decode(e),n=zu(He(r.peerId)),i=(null!==(t=r.addresses)&&void 0!==t?t:[]).map((e=>Ir(e.multiaddr))),o=r.seq;return new wd({peerId:n,multiaddrs:i,seqNumber:o})})),e(Sd,"DOMAIN","libp2p-peer-record"),e(Sd,"CODEC",bd);let Ed=class extends Error{constructor(){super(...arguments),e(this,"name","UnexpectedEOFError"),e(this,"code","ERR_UNEXPECTED_EOF")}};function kd(e,t){var n=Fc();e.sink(n).catch(function(){var e=r((function*(e){yield n.end(e)}));return function(t){return e.apply(this,arguments)}}()),e.sink=function(){var e=r((function*(e){var t,r=!1,i=!1;try{for(var o,a=s(e);r=!(o=yield a.next()).done;r=!1){var l=o.value;yield n.push(l)}}catch(e){i=!0,t=e}finally{try{r&&null!=a.return&&(yield a.return())}finally{if(i)throw t}}yield n.end()}));return function(t){return e.apply(this,arguments)}}();var i=e.source;null!=e.source[Symbol.iterator]?i=e.source[Symbol.iterator]():null!=e.source[Symbol.asyncIterator]&&(i=e.source[Symbol.asyncIterator]());var o,a=new bs,u={read:function(){var e=r((function*(e){var t;if(null==e||null===(t=e.signal)||void 0===t||t.throwIfAborted(),null==(null==e?void 0:e.bytes)){var{done:r,value:n}=yield Lc(i.next(),null==e?void 0:e.signal);return!0===r?null:n}for(;a.byteLength<e.bytes;){var{value:o,done:s}=yield Lc(i.next(),null==e?void 0:e.signal);if(!0===s)throw new Ed("unexpected end of input");a.append(o)}var l=a.sublist(0,e.bytes);return a.consume(e.bytes),l}));return function(t){return e.apply(this,arguments)}}(),write:(o=r((function*(e,t){var r;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),e instanceof Uint8Array?yield n.push(e,t):yield n.push(e.subarray(),t)})),function(e,t){return o.apply(this,arguments)}),unwrap:()=>{if(a.byteLength>0){var r=e.source;e.source=l((function*(){!1===(null==t?void 0:t.yieldBytes)?yield a:yield*c(s(a)),yield*c(s(r))}))()}return e}};return u}let xd=class extends Error{constructor(){super(...arguments),e(this,"name","InvalidMessageLengthError"),e(this,"code","ERR_INVALID_MSG_LENGTH")}},Ad=class extends Error{constructor(){super(...arguments),e(this,"name","InvalidDataLengthError"),e(this,"code","ERR_MSG_DATA_TOO_LONG")}},Cd=class extends Error{constructor(){super(...arguments),e(this,"name","InvalidDataLengthLengthError"),e(this,"code","ERR_MSG_LENGTH_TOO_LONG")}};function Id(e){var n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=kd(e,o);null!=o.maxDataLength&&null==o.maxLengthLength&&(o.maxLengthLength=Ot(o.maxDataLength));var s,l=null!==(n=null==o?void 0:o.lengthDecoder)&&void 0!==n?n:Ft,u=null!==(i=null==o?void 0:o.lengthEncoder)&&void 0!==i?i:Ut,c={read:function(){var e=r((function*(e){for(var r=-1,n=new bs;;){n.append(yield a.read(t(t({},e),{},{bytes:1})));try{r=l(n)}catch(e){if(e instanceof RangeError)continue;throw e}if(r<0)throw new xd("Invalid message length");if(null!=(null==o?void 0:o.maxLengthLength)&&n.byteLength>o.maxLengthLength)throw new Cd("message length length too long");if(r>-1)break}if(null!=(null==o?void 0:o.maxDataLength)&&r>o.maxDataLength)throw new Ad("message length too long");return a.read(t(t({},e),{},{bytes:r}))}));return function(t){return e.apply(this,arguments)}}(),write:function(){var e=r((function*(e,t){yield a.write(new bs(u(e.byteLength),e),t)}));return function(t,r){return e.apply(this,arguments)}}(),writeV:(s=r((function*(e,t){var r=new bs(...e.flatMap((e=>[u(e.byteLength),e])));yield a.write(r,t)})),function(e,t){return s.apply(this,arguments)}),unwrap:()=>a.unwrap()};return c}function Td(e,t){var n,i=Id(e,t),o={read:function(){var e=r((function*(e,t){var r=yield i.read(t);return e.decode(r)}));return function(t,r){return e.apply(this,arguments)}}(),write:function(){var e=r((function*(e,t,r){yield i.write(t.encode(e),r)}));return function(t,r,n){return e.apply(this,arguments)}}(),writeV:(n=r((function*(e,t,r){yield i.writeV(e.map((e=>t.encode(e))),r)})),function(e,t,r){return n.apply(this,arguments)}),pb:e=>{return{read:(i=r((function*(t){return o.read(e,t)})),function(e){return i.apply(this,arguments)}),write:(n=r((function*(t,r){return o.write(t,e,r)})),function(e,t){return n.apply(this,arguments)}),writeV:(t=r((function*(t,r){return o.writeV(t,e,r)})),function(e,r){return t.apply(this,arguments)}),unwrap:()=>o};var t,n,i},unwrap:()=>i.unwrap()};return o}var Pd="".concat(Pa,"-circuit-relay");BigInt(1<<17);var _d,Bd,Nd,Dd,Rd,Od,Ld,Md,Ud,Fd="/libp2p/circuit/relay/0.2.0/hop",zd="/libp2p/circuit/relay/0.2.0/stop";!function(e){var t,r;!function(e){e.RESERVE="RESERVE",e.CONNECT="CONNECT",e.STATUS="STATUS"}(e.Type||(e.Type={})),function(e){e[e.RESERVE=0]="RESERVE",e[e.CONNECT=1]="CONNECT",e[e.STATUS=2]="STATUS"}(t||(t={})),function(e){e.codec=()=>Gl(t)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=Ql((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==n.lengthDelimited&&r.fork(),null!=t.type&&(r.uint32(8),e.Type.codec().encode(t.type,r)),null!=t.peer&&(r.uint32(18),Nd.codec().encode(t.peer,r)),null!=t.reservation&&(r.uint32(26),Dd.codec().encode(t.reservation,r)),null!=t.limit&&(r.uint32(34),Rd.codec().encode(t.limit,r)),null!=t.status&&(r.uint32(40),Od.codec().encode(t.status,r)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={},o=null==r?t.len:t.pos+r;t.pos<o;){var a=t.uint32();switch(a>>>3){case 1:i.type=e.Type.codec().decode(t);break;case 2:var s;i.peer=Nd.codec().decode(t,t.uint32(),{limits:null===(s=n.limits)||void 0===s?void 0:s.peer});break;case 3:var l;i.reservation=Dd.codec().decode(t,t.uint32(),{limits:null===(l=n.limits)||void 0===l?void 0:l.reservation});break;case 4:var u;i.limit=Rd.codec().decode(t,t.uint32(),{limits:null===(u=n.limits)||void 0===u?void 0:u.limit});break;case 5:i.status=Od.codec().decode(t);break;default:t.skipType(7&a)}}return i}))),r),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(_d||(_d={})),function(e){var t,r;!function(e){e.CONNECT="CONNECT",e.STATUS="STATUS"}(e.Type||(e.Type={})),function(e){e[e.CONNECT=0]="CONNECT",e[e.STATUS=1]="STATUS"}(t||(t={})),function(e){e.codec=()=>Gl(t)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=Ql((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==n.lengthDelimited&&r.fork(),null!=t.type&&(r.uint32(8),e.Type.codec().encode(t.type,r)),null!=t.peer&&(r.uint32(18),Nd.codec().encode(t.peer,r)),null!=t.limit&&(r.uint32(26),Rd.codec().encode(t.limit,r)),null!=t.status&&(r.uint32(32),Od.codec().encode(t.status,r)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={},o=null==r?t.len:t.pos+r;t.pos<o;){var a=t.uint32();switch(a>>>3){case 1:i.type=e.Type.codec().decode(t);break;case 2:var s;i.peer=Nd.codec().decode(t,t.uint32(),{limits:null===(s=n.limits)||void 0===s?void 0:s.peer});break;case 3:var l;i.limit=Rd.codec().decode(t,t.uint32(),{limits:null===(l=n.limits)||void 0===l?void 0:l.limit});break;case 4:i.status=Od.codec().decode(t);break;default:t.skipType(7&a)}}return i}))),r),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(Bd||(Bd={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.id&&e.id.byteLength>0&&(t.uint32(10),t.bytes(e.id)),null!=e.addrs)for(var n of e.addrs)t.uint32(18),t.bytes(n);!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={id:ct(0),addrs:[]},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.id=e.bytes();break;case 2:var a;if(null!=(null===(a=r.limits)||void 0===a?void 0:a.addrs)&&n.addrs.length===r.limits.addrs)throw new Yl('Decode error - map field "addrs" had too many elements');n.addrs.push(e.bytes());break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(Nd||(Nd={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.expire&&0n!==e.expire&&(t.uint32(8),t.uint64(e.expire)),null!=e.addrs)for(var n of e.addrs)t.uint32(18),t.bytes(n);null!=e.voucher&&(t.uint32(26),Ud.codec().encode(e.voucher,t)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={expire:0n,addrs:[]},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.expire=e.uint64();break;case 2:var a;if(null!=(null===(a=r.limits)||void 0===a?void 0:a.addrs)&&n.addrs.length===r.limits.addrs)throw new Yl('Decode error - map field "addrs" had too many elements');n.addrs.push(e.bytes());break;case 3:var s;n.voucher=Ud.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.voucher});break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(Dd||(Dd={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.duration&&(t.uint32(8),t.uint32(e.duration)),null!=e.data&&(t.uint32(16),t.uint64(e.data)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.duration=e.uint32();break;case 2:r.data=e.uint64();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(Rd||(Rd={})),function(e){e.UNUSED="UNUSED",e.OK="OK",e.RESERVATION_REFUSED="RESERVATION_REFUSED",e.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",e.PERMISSION_DENIED="PERMISSION_DENIED",e.CONNECTION_FAILED="CONNECTION_FAILED",e.NO_RESERVATION="NO_RESERVATION",e.MALFORMED_MESSAGE="MALFORMED_MESSAGE",e.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"}(Od||(Od={})),function(e){e[e.UNUSED=0]="UNUSED",e[e.OK=100]="OK",e[e.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",e[e.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",e[e.PERMISSION_DENIED=202]="PERMISSION_DENIED",e[e.CONNECTION_FAILED=203]="CONNECTION_FAILED",e[e.NO_RESERVATION=204]="NO_RESERVATION",e[e.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",e[e.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"}(Ld||(Ld={})),function(e){e.codec=()=>Gl(Ld)}(Od||(Od={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.relay&&e.relay.byteLength>0&&(t.uint32(10),t.bytes(e.relay)),null!=e.peer&&e.peer.byteLength>0&&(t.uint32(18),t.bytes(e.peer)),null!=e.expiration&&0n!==e.expiration&&(t.uint32(24),t.uint64(e.expiration)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={relay:ct(0),peer:ct(0),expiration:0n},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.relay=e.bytes();break;case 2:r.peer=e.bytes();break;case 3:r.expiration=e.uint64();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(Md||(Md={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!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&&(t.uint32(26),Md.codec().encode(e.payload,t)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={publicKey:ct(0),payloadType:ct(0),signature:ct(0)},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.publicKey=e.bytes();break;case 2:n.payloadType=e.bytes();break;case 3:var a;n.payload=Md.codec().decode(e,e.uint32(),{limits:null===(a=r.limits)||void 0===a?void 0:a.payload});break;case 5:n.signature=e.bytes();break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(Ud||(Ud={}));var jd=e=>({match:t=>!(t.length<1)&&(!!e(t[0])&&t.slice(1)),pattern:"fn"}),Vd=e=>({match:t=>jd((t=>t===e)).match(t),pattern:e}),qd=()=>({match:e=>jd((e=>"string"==typeof e)).match(e),pattern:"{string}"}),Hd=()=>({match:e=>jd((e=>!isNaN(parseInt(e)))).match(e),pattern:"{number}"}),Kd=()=>({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{ie.decode("z".concat(e[1]))}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),Wd=()=>({match:e=>{if(e.length<2)return!1;if("certhash"!==e[0])return!1;try{ue.decode(e[1])}catch(e){return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),Gd=e=>({match:t=>{var r=e.match(t);return!1===r?t:r},pattern:"optional(".concat(e.pattern,")")}),Qd=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return{match:e=>{var r;for(var n of t){var i=n.match(e);!1!==i&&((null==r||i.length<r.length)&&(r=i))}return null!=r&&r},pattern:"or(".concat(t.map((e=>e.pattern)).join(", "),")")}},Yd=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return{match:e=>{for(var r of t){var n=r.match(e);if(!1===n)return!1;e=n}return e},pattern:"and(".concat(t.map((e=>e.pattern)).join(", "),")")}};function Jd(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];function n(e){var r=(e=>e.toString().split("/").slice(1))(e);for(var n of t){var i=n.match(r);if(!1===i)return!1;r=i}return r}return{matchers:t,matches:function(e){return!1!==n(e)},exactMatch:function(e){var t=n(e);return!1!==t&&0===t.length}}}var Zd=Jd(Kd()),$d=Yd(Vd("dns4"),qd()),Xd=Yd(Vd("dns6"),qd()),eh=Yd(Vd("dnsaddr"),qd()),th=Yd(Vd("dns"),qd());Jd($d,Gd(Kd())),Jd(Xd,Gd(Kd())),Jd(eh,Gd(Kd()));var rh=Jd(Qd(th,eh,$d,Xd),Gd(Kd())),nh=Yd(Vd("ip4"),jd(Wt)),ih=Yd(Vd("ip6"),jd(Gt)),oh=Qd(nh,ih),ah=Qd(oh,th,$d,Xd,eh),sh=Jd(Qd(oh,Yd(Qd(th,eh,$d,Xd),Gd(Kd())))),lh=Jd(nh),uh=Jd(ih),ch=Jd(oh),dh=Yd(ah,Vd("tcp"),Hd()),hh=Yd(ah,Vd("udp"),Hd()),vh=Jd(Yd(dh,Gd(Kd())));Jd(hh);var ph=Yd(hh,Vd("quic"),Gd(Kd())),fh=Yd(hh,Vd("quic-v1"),Gd(Kd())),gh=Qd(ph,fh);Jd(ph);var yh=Jd(fh),mh=Qd(ah,dh,hh,ph,fh),wh=Qd(Yd(mh,Vd("ws"),Gd(Kd()))),bh=Jd(wh),Sh=Qd(Yd(mh,Vd("wss"),Gd(Kd())),Yd(mh,Vd("tls"),Gd(Yd(Vd("sni"),qd())),Vd("ws"),Gd(Kd()))),Eh=Jd(Sh),kh=Yd(hh,Vd("webrtc-direct"),Gd(Wd()),Gd(Wd()),Gd(Kd())),xh=Jd(kh),Ah=Yd(fh,Vd("webtransport"),Gd(Wd()),Gd(Wd()),Gd(Kd())),Ch=Jd(Ah),Ih=Qd(wh,Sh,Yd(dh,Gd(Kd())),Yd(gh,Gd(Kd())),Yd(ah,Gd(Kd())),kh,Ah,Kd()),Th=Jd(Ih),Ph=Jd(Yd(Ih,Vd("p2p-circuit"),Kd())),_h=Jd(Qd(Yd(Ih,Vd("p2p-circuit"),Vd("webrtc"),Gd(Kd())),Yd(Ih,Vd("webrtc"),Gd(Kd())),Yd(Vd("webrtc"),Gd(Kd())))),Bh=Jd(Qd(Yd(ah,Vd("tcp"),Hd(),Vd("http"),Gd(Kd())),Yd(ah,Vd("http"),Gd(Kd())))),Nh=Jd(Qd(Yd(ah,Vd("tcp"),Qd(Yd(Vd("443"),Vd("http")),Yd(Hd(),Vd("https")),Yd(Hd(),Vd("tls"),Vd("http"))),Gd(Kd())),Yd(ah,Vd("tls"),Vd("http"),Gd(Kd())),Yd(ah,Vd("https"),Gd(Kd()))));function Dh(e){var t=new globalThis.AbortController;function r(){for(var n of(t.abort(),e))null!=(null==n?void 0:n.removeEventListener)&&n.removeEventListener("abort",r)}for(var n of e){if(!0===(null==n?void 0:n.aborted)){r();break}null!=(null==n?void 0:n.addEventListener)&&n.addEventListener("abort",r)}var i=t.signal;return i.clear=function(){for(var t of e)null!=(null==t?void 0:t.removeEventListener)&&t.removeEventListener("abort",r)},i}Jd(Qd(Yd(Vd("memory"),qd(),Gd(Kd()))));class Rh extends Error{constructor(){super(...arguments),e(this,"name","HadEnoughRelaysError")}}e(Rh,"name","HadEnoughRelaysError");class Oh extends Error{constructor(){super(...arguments),e(this,"name","DoubleRelayError")}}e(Oh,"name","DoubleRelayError");class Lh extends Error{constructor(){super(...arguments),e(this,"name","RelayQueueFullError")}}function Mh(e){var t=e*BigInt(1e3),r=(new Date).getTime();return Number(t-BigInt(r))}e(Lh,"name","RelayQueueFullError");class Uh{constructor(t){e(this,"expires",void 0),e(this,"bytes",void 0),null!=(null==t?void 0:t.duration)&&0!==(null==t?void 0:t.duration)&&(this.expires=Date.now()+1e3*t.duration),this.bytes=null==t?void 0:t.data,0n===this.bytes&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){null!=this.bytes&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(null!=this.expires||null!=this.bytes){var e={};if(null!=this.bytes){var t=this;Object.defineProperty(e,"bytes",{get:()=>t.bytes})}if(null!=this.expires){var r=this;Object.defineProperty(e,"seconds",{get(){var e;return Math.round(((null!==(e=r.expires)&&void 0!==e?e:0)-Date.now())/1e3)}})}return e}}}var Fh=Jd(Yd(Th.matchers[0],Vd("p2p-circuit"))),zh=Jd(Vd("p2p-circuit"));function jh(e,t){var r={[Symbol.iterator]:()=>r,next:()=>{var 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 Vh(e){return zu(He(ie.decode("z".concat(e))))}class qh{constructor(t){if(e(this,"map",void 0),this.map=new Map,null!=t)for(var[r,n]of t.entries())this.map.set(r.toString(),{key:r,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return jh(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){var t;return null===(t=this.map.get(e.toString()))||void 0===t?void 0:t.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return jh(this.map.values(),(e=>e.key))}values(){return jh(this.map.values(),(e=>e.value))}get size(){return this.map.size}}class Hh{constructor(t){if(e(this,"set",void 0),this.set=new Set,null!=t)for(var r of t)this.set.add(r.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 jh(this.set.entries(),(e=>{var t=Vh(e[0]);return[t,t]}))}forEach(e){this.set.forEach((t=>{var r=Vh(t);e(r,r,this)}))}has(e){return this.set.has(e.toString())}values(){return jh(this.set.values(),(e=>Vh(e)))}intersection(e){var t=new Hh;for(var r of e)this.has(r)&&t.add(r);return t}difference(e){var t=new Hh;for(var r of this)e.has(r)||t.add(r);return t}union(e){var t=new Hh;for(var r of e)t.add(r);for(var n of this)t.add(n);return t}}var Kh={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Wh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Gh=new globalThis.TextEncoder;function Qh(e){var{size:t=32,utf8Buffer:r}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Kh[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");for(var n=Kh[t],i=Wh[t],o=e;o.length>0;){var a=Gh.encodeInto(o,r);o=o.slice(a.read);for(var s=0;s<a.written;s++)i^=BigInt(r[s]),i=BigInt.asUintN(t,i*n)}return i}(e,t,r);e=Gh.encode(e)}return function(e,t){for(var r=Kh[t],n=Wh[t],i=0;i<e.length;i++)n^=BigInt(e[i]),n=BigInt.asUintN(t,n*r);return n}(e,t)}var Yh={hash:e=>Number(Qh(e,{size:32})),hashV:(e,t)=>function(e){var t=e.toString(16);t.length%2==1&&(t="0".concat(t));return xt(t,"base16")}(Yh.hash(e,t))};class Jh{constructor(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:2;if(e(this,"fp",void 0),e(this,"h",void 0),e(this,"seed",void 0),i>64)throw new TypeError("Invalid Fingerprint Size");for(var o=r.hashV(t,n),a=ct(i),s=0;s<a.length;s++)a[s]=o[s];0===a.length&&(a[0]=7),this.fp=a,this.h=r,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return(null==e?void 0:e.fp)instanceof Uint8Array&&Et(this.fp,e.fp)}}function Zh(e,t){return Math.floor(Math.random()*(t-e))+e}let $h=class{constructor(t){e(this,"contents",void 0),this.contents=new Array(t).fill(null)}has(e){if(!(e instanceof Jh))throw new TypeError("Invalid Fingerprint");return this.contents.some((t=>e.equals(t)))}add(e){if(!(e instanceof Jh))throw new TypeError("Invalid Fingerprint");for(var 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 Jh))throw new TypeError("Invalid Fingerprint");var t=Zh(0,this.contents.length-1),r=this.contents[t];return this.contents[t]=e,r}remove(e){if(!(e instanceof Jh))throw new TypeError("Invalid Fingerprint");var t=this.contents.findIndex((t=>e.equals(t)));return t>-1&&(this.contents[t]=null,!0)}};class Xh{constructor(t){var r,n,i,o;e(this,"bucketSize",void 0),e(this,"filterSize",void 0),e(this,"fingerprintSize",void 0),e(this,"buckets",void 0),e(this,"count",void 0),e(this,"hash",void 0),e(this,"seed",void 0),this.filterSize=t.filterSize,this.bucketSize=null!==(r=t.bucketSize)&&void 0!==r?r:4,this.fingerprintSize=null!==(n=t.fingerprintSize)&&void 0!==n?n:2,this.count=0,this.buckets=[],this.hash=null!==(i=t.hash)&&void 0!==i?i:Yh,this.seed=null!==(o=t.seed)&&void 0!==o?o:Zh(0,Math.pow(2,10))}add(e){"string"==typeof e&&(e=xt(e));var t=new Jh(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 $h(this.bucketSize)),null==this.buckets[n]&&(this.buckets[n]=new $h(this.bucketSize)),this.buckets[r].add(t)||this.buckets[n].add(t))return this.count++,!0;var i=[r,n],o=i[Zh(0,i.length-1)];null==this.buckets[o]&&(this.buckets[o]=new $h(this.bucketSize));for(var a=0;a<500;a++){var s=this.buckets[o].swap(t);if(null!=s&&(o=(o^s.hash())%this.filterSize,null==this.buckets[o]&&(this.buckets[o]=new $h(this.bucketSize)),this.buckets[o].add(s)))return this.count++,!0}return!1}has(e){var t,r,n,i;"string"==typeof e&&(e=xt(e));var o=new Jh(e,this.hash,this.seed,this.fingerprintSize),a=this.hash.hash(e,this.seed)%this.filterSize,s=null!==(t=null===(r=this.buckets[a])||void 0===r?void 0:r.has(o))&&void 0!==t&&t;if(s)return s;var l=(a^o.hash())%this.filterSize;return null!==(n=null===(i=this.buckets[l])||void 0===i?void 0:i.has(o))&&void 0!==n&&n}remove(e){var t,r,n,i;"string"==typeof e&&(e=xt(e));var o=new Jh(e,this.hash,this.seed,this.fingerprintSize),a=this.hash.hash(e,this.seed)%this.filterSize,s=null!==(t=null===(r=this.buckets[a])||void 0===r?void 0:r.remove(o))&&void 0!==t&&t;if(s)return this.count--,s;var l=(a^o.hash())%this.filterSize,u=null!==(n=null===(i=this.buckets[l])||void 0===i?void 0:i.remove(o))&&void 0!==n&&n;return u&&this.count--,u}get reliable(){return Math.floor(this.count/this.filterSize*100)<=90}}var ev={1:.5,2:.84,4:.95,8:.98};class tv{constructor(t){var r,n,i,o,a,s;e(this,"filterSize",void 0),e(this,"bucketSize",void 0),e(this,"fingerprintSize",void 0),e(this,"scale",void 0),e(this,"filterSeries",void 0),e(this,"hash",void 0),e(this,"seed",void 0),this.bucketSize=null!==(r=t.bucketSize)&&void 0!==r?r:4,this.filterSize=null!==(n=t.filterSize)&&void 0!==n?n:(1<<18)/this.bucketSize,this.fingerprintSize=null!==(i=t.fingerprintSize)&&void 0!==i?i:2,this.scale=null!==(o=t.scale)&&void 0!==o?o:2,this.hash=null!==(a=t.hash)&&void 0!==a?a:Yh,this.seed=null!==(s=t.seed)&&void 0!==s?s:Zh(0,Math.pow(2,10)),this.filterSeries=[new Xh({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;var t=this.filterSeries.find((e=>e.reliable));if(null==t){var r=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Xh({filterSize:r,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(var 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(var 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 rv(e){var r=arguments.length>2?arguments[2]:void 0;return new tv(t(t({},function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:.001,r=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:.001;return e>.002?2:e>1e-5?4:8}(t),n=ev[r];return{filterSize:Math.round(e/n),bucketSize:r,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*r)),64)}}(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:.001)),null!=r?r:{}))}class nv{constructor(t,r){e(this,"filter",void 0),this.filter=rv(t,r)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){var t,r;null===(t=(r=this.filter).remove)||void 0===t||t.call(r,e.toMultihash().bytes)}}function iv(e){return new nv(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:.001)}class ov extends qh{constructor(t){super(),e(this,"metric",void 0);var{name:r,metrics:n}=t;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){var t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function av(e){var{name:t,metrics:r}=e;return null!=r?new ov({name:t,metrics:r}):new qh}function sv(e){return null!=(null==e?void 0:e.then)}function lv(e,t){var r=0;if(null!=e[Symbol.asyncIterator])return l((function*(){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var c=a.value,d=t(c,r++);sv(d)&&(yield u(d)),yield c}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}))();var n=pc(e),{value:i,done:o}=n.next();if(!0===o)return function*(){}();var a=t(i,r++);if("function"==typeof(null==a?void 0:a.then))return l((function*(){for(var e of(yield i,n)){var o=t(e,r++);sv(o)&&(yield u(o)),yield e}}))();var c=t;return function*(){for(var e of(yield i,n))c(e,r++),yield e}()}function uv(e){var{stream:t,remoteAddr:n,logger:i,onDataRead:o,onDataWrite:a}=e,c=i.forComponent("libp2p:stream:converter"),d=!1,h=!1,v=t.close.bind(t);t.close=function(){var e=r((function*(e){yield v(e),y(!0)}));return function(t){return e.apply(this,arguments)}}();var p=t.abort.bind(t);t.abort=e=>{p(e),y(!0)};var f=t.sink.bind(t);t.sink=function(){var e=r((function*(e){try{yield f(qc(e,(e=>lv(e,(e=>null==a?void 0:a(e))))))}catch(e){"aborted"!==e.type&&c.error("%s error in sink",n,e)}finally{h=!0,y()}}));return function(t){return e.apply(this,arguments)}}();var g={log:c,sink:t.sink,source:l((function*(){try{var e,r=!1,n=!1;try{for(var i,a=s(t.source);r=!(i=yield u(a.next())).done;r=!1){var l=i.value;null==o||o(l),yield l}}catch(t){n=!0,e=t}finally{try{r&&null!=a.return&&(yield u(a.return()))}finally{if(n)throw e}}}finally{d=!0,y()}}))(),remoteAddr:n,timeline:{open:Date.now(),close:void 0},close:t.close,abort:t.abort};function y(e){!0===e&&(d=!0,h=!0),d&&h&&null==g.timeline.close&&(g.timeline.close=Date.now())}return g}class cv extends Event{constructor(t,r){super(t),e(this,"type",void 0),e(this,"detail",void 0),this.type=t,this.detail=r}}let dv=class extends Error{constructor(t,r){super(null!=t?t:"The operation was aborted"),e(this,"type",void 0),e(this,"code",void 0),this.type="aborted",this.name="AbortError",this.code=null!=r?r:"ABORT_ERR"}};function hv(e,t,r,n){return vv.apply(this,arguments)}function vv(){return vv=r((function*(e,t,r,n){var i=new dv(null==n?void 0:n.errorMessage,null==n?void 0:n.errorCode);return!0===(null==r?void 0:r.aborted)?Promise.reject(i):new Promise(((o,a)=>{function s(){null==r||r.removeEventListener("abort",c),e.removeEventListener(t,l),null!=(null==n?void 0:n.errorEvent)&&e.removeEventListener(n.errorEvent,u)}var l=e=>{try{var t;if(!1===(null==n||null===(t=n.filter)||void 0===t?void 0:t.call(n,e)))return}catch(e){return s(),void a(e)}s(),o(e)},u=e=>{s(),a(e.detail)},c=()=>{s(),a(i)};null==r||r.addEventListener("abort",c),e.addEventListener(t,l),null!=(null==n?void 0:n.errorEvent)&&e.addEventListener(n.errorEvent,u)}))})),vv.apply(this,arguments)}function pv(e,t){var r,n=function(){clearTimeout(r),r=setTimeout((function(){r=void 0,e()}),t)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}class fv extends Error{constructor(){var t=arguments.length>1?arguments[1]:void 0;super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Rate limit exceeded"),e(this,"remainingPoints",void 0),e(this,"msBeforeNext",void 0),e(this,"consumedPoints",void 0),e(this,"isFirstInDuration",void 0),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}}let gv=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The queue was full"),this.name="QueueFullError"}};e(gv,"name","QueueFullError");let yv=class{constructor(t){var r;e(this,"deferred",void 0),e(this,"signal",void 0),this.signal=t,this.deferred=_c(),this.onAbort=this.onAbort.bind(this),null===(r=this.signal)||void 0===r||r.addEventListener("abort",this.onAbort)}onAbort(){var e,t;this.deferred.reject(null!==(e=null===(t=this.signal)||void 0===t?void 0:t.reason)&&void 0!==e?e:new Ba)}cleanup(){var e;null===(e=this.signal)||void 0===e||e.removeEventListener("abort",this.onAbort)}};let mv=class{constructor(t,r){e(this,"id",void 0),e(this,"fn",void 0),e(this,"options",void 0),e(this,"recipients",void 0),e(this,"status",void 0),e(this,"timeline",void 0),e(this,"controller",void 0),this.id="".concat(parseInt(String(1e9*Math.random()),10).toString()).concat(Date.now()),this.status="queued",this.fn=t,this.options=r,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(){var e=this.recipients.reduce(((e,t)=>{var r;return e&&!0===(null===(r=t.signal)||void 0===r?void 0:r.aborted)}),!0);e&&(this.controller.abort(new Ba),this.cleanup())}join(){var e=arguments,t=this;return r((function*(){var r,n=e.length>0&&void 0!==e[0]?e[0]:{},i=new yv(n.signal);return t.recipients.push(i),null===(r=n.signal)||void 0===r||r.addEventListener("abort",t.onAbort),i.deferred.promise}))()}run(){var e=this;return r((function*(){e.status="running",e.timeline.started=Date.now();try{var r;e.controller.signal.throwIfAborted();var n=yield Lc(e.fn(t(t({},null!==(r=e.options)&&void 0!==r?r:{}),{},{signal:e.controller.signal})),e.controller.signal);e.recipients.forEach((e=>{e.deferred.resolve(n)})),e.status="complete"}catch(t){e.recipients.forEach((e=>{e.deferred.reject(t)})),e.status="errored"}finally{e.timeline.finished=Date.now(),e.cleanup()}}))()}cleanup(){this.recipients.forEach((e=>{var t;e.cleanup(),null===(t=e.signal)||void 0===t||t.removeEventListener("abort",this.onAbort)}))}},wv=class extends us{constructor(){var t,r,n,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(super(),e(this,"concurrency",void 0),e(this,"maxSize",void 0),e(this,"queue",void 0),e(this,"pending",void 0),e(this,"sort",void 0),this.concurrency=null!==(t=i.concurrency)&&void 0!==t?t:Number.POSITIVE_INFINITY,this.maxSize=null!==(r=i.maxSize)&&void 0!==r?r:Number.POSITIVE_INFINITY,this.pending=0,null!=i.metricName)&&(null===(n=i.metrics)||void 0===n||n.registerMetricGroup(i.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}));this.sort=i.sort,this.queue=[],this.emitEmpty=pv(this.emitEmpty.bind(this),1),this.emitIdle=pv(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){var e;for(var t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally((()=>{for(var 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)}add(e,t){var n=this;return r((function*(){var r;if(null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),n.size===n.maxSize)throw new gv;var i=new mv(e,t);return n.enqueue(i),n.safeDispatchEvent("add"),n.tryToStartAnother(),i.join(t).then((e=>(n.safeDispatchEvent("completed",{detail:e}),n.safeDispatchEvent("success",{detail:{job:i,result:e}}),e))).catch((e=>{if("queued"===i.status)for(var t=0;t<n.queue.length;t++)if(n.queue[t]===i){n.queue.splice(t,1);break}throw n.safeDispatchEvent("error",{detail:e}),n.safeDispatchEvent("failure",{detail:{job:i,error:e}}),e}))}))()}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach((e=>{e.abort(new Ba)})),this.clear()}onEmpty(e){var t=this;return r((function*(){0!==t.size&&(yield hv(t,"empty",null==e?void 0:e.signal))}))()}onSizeLessThan(e,t){var n=this;return r((function*(){n.size<e||(yield hv(n,"next",null==t?void 0:t.signal,{filter:()=>n.size<e}))}))()}onIdle(e){var t=this;return r((function*(){0===t.pending&&0===t.size||(yield hv(t,"idle",null==e?void 0:e.signal))}))()}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}toGenerator(e){var t=this;return l((function*(){var r,n;null==e||null===(r=e.signal)||void 0===r||r.throwIfAborted();var i=Rc({objectMode:!0}),o=e=>{null!=e?t.abort():t.clear(),i.end(e)},a=e=>{null!=e.detail&&i.push(e.detail)},l=e=>{o(e.detail)},d=()=>{o()},h=()=>{o(new Ba("Queue aborted"))};t.addEventListener("completed",a),t.addEventListener("error",l),t.addEventListener("idle",d),null==e||null===(n=e.signal)||void 0===n||n.addEventListener("abort",h);try{yield*c(s(i),u)}finally{var v;t.removeEventListener("completed",a),t.removeEventListener("error",l),t.removeEventListener("idle",d),null==e||null===(v=e.signal)||void 0===v||v.removeEventListener("abort",h),o()}}))()}};class bv extends wv{has(e){return null!=this.find(e)}find(e){return this.queue.find((t=>e.equals(t.options.peerId)))}}class Sv extends us{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),e(this,"peerStore",void 0),e(this,"registrar",void 0),e(this,"connectionManager",void 0),e(this,"randomWalk",void 0),e(this,"started",void 0),e(this,"running",void 0),e(this,"topologyId",void 0),e(this,"log",void 0),e(this,"discoveryController",void 0),e(this,"filter",void 0),e(this,"queue",void 0),this.log=t.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.started=!1,this.running=!1,this.peerStore=t.peerStore,this.registrar=t.registrar,this.connectionManager=t.connectionManager,this.randomWalk=t.randomWalk,this.filter=r.filter,this.discoveryController=new AbortController,this.discoveryController.signal}isStarted(){return this.started}start(){var e=this;return r((function*(){e.topologyId=yield e.registrar.register(Fd,{filter:e.filter,onConnect:t=>{var r,n;e.log.trace("discovered relay %p queue (length: %d, active %d)",t,null===(r=e.queue)||void 0===r?void 0:r.size,null===(n=e.queue)||void 0===n?void 0:n.running),e.safeDispatchEvent("relay:discover",{detail:t})}}),e.started=!0}))()}stop(){var e;null!=this.topologyId&&this.registrar.unregister(this.topologyId),null===(e=this.discoveryController)||void 0===e||e.abort(),this.started=!1}startDiscovery(){var e=this;this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,Promise.resolve().then(r((function*(){e.log("searching peer store for relays");var t=yield e.peerStore.all({filters:[e=>e.protocols.includes(Fd)],orders:[()=>Math.random()<.5?1:-1,(e,t)=>{var r=Ev(e),n=Ev(t);return r>n?-1:n>r?1:0}]});for(var n of t)e.log.trace("found relay peer %p in peer store",n.id),e.safeDispatchEvent("relay:discover",{detail:n.id});e.log("found %d relay peers in peer store",t.length);var i=e.queue=new bv({concurrency:5});e.log("start random walk");var o,a=!1,l=!1;try{for(var u,c=function*(){var t,n=u.value;return e.log.trace("found random peer %p",n.id),i.has(n.id)?(e.log.trace("random peer %p was already in queue",n.id),0):(null===(t=e.connectionManager.getConnections(n.id))||void 0===t?void 0:t.length)>0?(e.log.trace("random peer %p was already connected",n.id),0):(yield e.connectionManager.isDialable(n.multiaddrs))?(i.queued>10&&(e.log.trace("wait for space in queue for %p",n.id),yield i.onSizeLessThan(10,{signal:e.discoveryController.signal})),e.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,i.size,i.running),void i.add(r((function*(){var t=Dh([e.discoveryController.signal,AbortSignal.timeout(5e3)]);try{yield e.connectionManager.openConnection(n.id,{signal:t})}finally{t.clear()}})),{peerId:n.id,signal:e.discoveryController.signal}).catch((t=>{e.log.error("error opening connection to random peer %p",n.id,t)}))):(e.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map((e=>e.toString()))),0)},d=s(e.randomWalk.walk({signal:e.discoveryController.signal}));a=!(u=yield d.next()).done;a=!1)yield*c()}catch(e){l=!0,o=e}finally{try{a&&null!=d.return&&(yield d.return())}finally{if(l)throw o}}e.log("stop random walk"),yield i.onIdle()}))).catch((e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network",e)})))}stopDiscovery(){var e;this.log("stop discovery"),this.running=!1,null===(e=this.discoveryController)||void 0===e||e.abort()}}function Ev(e){var t=e.metadata.get("last-dial-success");return null==t?0:new Date(gt(t)).getTime()}class kv extends us{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),e(this,"connectionManager",void 0),e(this,"addressManager",void 0),e(this,"reservationStore",void 0),e(this,"listeningAddrs",void 0),e(this,"log",void 0),e(this,"listenTimeout",void 0),e(this,"reservationId",void 0),e(this,"relay",void 0),e(this,"_onRemoveRelayPeer",(e=>{var t,r;this.log("relay removed %p our relay %p",e.detail.relay,this.relay,null===(t=this.relay)||void 0===t?void 0:t.equals(e.detail.relay)),!0===(null===(r=this.relay)||void 0===r?void 0:r.equals(e.detail.relay))&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach((e=>{this.addressManager.removeObservedAddr(e)})),this.listeningAddrs=[],this.safeDispatchEvent("listening"))})),e(this,"_onAddRelayPeer",(e=>{var{details:t}=e.detail;"configured"!==t.type&&t.id===this.reservationId&&this.addedRelay(e.detail)})),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=t.connectionManager,this.addressManager=t.addressManager,this.reservationStore=t.reservationStore,this.listeningAddrs=[],this.listenTimeout=null!==(r=n.listenTimeout)&&void 0!==r?r:2e3,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}listen(e){var t=this;return r((function*(){if(zh.exactMatch(e))t.log("searching for circuit relay servers"),t.reservationId=t.reservationStore.reserveRelay();else{if(!Fh.exactMatch(e))throw new rs('Could not listen on p2p-circuit address "'.concat(e,'"'));t.log("listen on specific relay server %a",e);var r=AbortSignal.timeout(t.listenTimeout),n=e.decapsulate("/p2p-circuit"),i=yield t.connectionManager.openConnection(n,{signal:r});if(!t.reservationStore.hasReservation(i.remotePeer)){t.log("making reservation on peer %p",i.remotePeer);var o=yield t.reservationStore.addRelay(i.remotePeer,"configured");t.addedRelay(o)}}}))()}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}close(){var e=this;return r((function*(){e.reservationStore.cancelReservations(),e.listeningAddrs=[],e.reservationStore.removeEventListener("relay:removed",e._onRemoveRelayPeer),queueMicrotask((()=>{e.safeDispatchEvent("close")}))}))()}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map((e=>Ir(e).encapsulate("/p2p-circuit"))),this.listeningAddrs.forEach((e=>{this.addressManager.confirmObservedAddr(e,{type:"transport"})})),queueMicrotask((()=>{this.safeDispatchEvent("listening")}))}}var xv=function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:21,t="",r=crypto.getRandomValues(new Uint8Array(e|=0));e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&r[e]];return t},Av=new WeakSet;class Cv extends us{constructor(t,r){var n,i,o;super(),d(this,Av),e(this,"peerId",void 0),e(this,"connectionManager",void 0),e(this,"peerStore",void 0),e(this,"events",void 0),e(this,"reserveQueue",void 0),e(this,"reservations",void 0),e(this,"pendingReservations",void 0),e(this,"maxReservationQueueLength",void 0),e(this,"reservationCompletionTimeout",void 0),e(this,"started",void 0),e(this,"log",void 0),e(this,"relayFilter",void 0),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=t.peerId,this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.reservations=new qh,this.pendingReservations=[],this.maxReservationQueueLength=null!==(n=null==r?void 0:r.maxReservationQueueLength)&&void 0!==n?n:100,this.reservationCompletionTimeout=null!==(i=null==r?void 0:r.reservationCompletionTimeout)&&void 0!==i?i:2e3,this.started=!1,this.relayFilter=rv(100),this.reserveQueue=new bv({concurrency:null!==(o=null==r?void 0:r.reservationConcurrency)&&void 0!==o?o:1,metricName:"libp2p_relay_reservation_queue",metrics:t.metrics}),this.events.addEventListener("connection:close",(e=>{null!=[...this.reservations.values()].find((t=>t.connection===e.detail.id))&&h(Av,this,Pv).call(this,e.detail.remotePeer).catch((t=>{this.log("could not remove relay %p - %e",e.detail,t)}))}))}isStarted(){return this.started}start(){this.started=!0}afterStart(){var e=this;Promise.resolve().then(r((function*(){var t=yield e.peerStore.all({filters:[e=>e.tags.has(Pd)]});e.log("removing tag from %d old relays",t.length),yield Promise.all(t.map(function(){var t=r((function*(t){yield e.peerStore.merge(t.id,{tags:{[Pd]:void 0}})}));return function(e){return t.apply(this,arguments)}}())),e.log("redialing %d old relays",t.length),yield Promise.all(t.map(function(){var t=r((function*(t){return e.addRelay(t.id,"discovered")}));return function(e){return t.apply(this,arguments)}}())),h(Av,e,Bv).call(e)}))).catch((e=>{this.log.error(e)}))}stop(){this.reserveQueue.clear(),this.reservations.forEach((e=>{var{timeout:t}=e;clearTimeout(t)})),this.reservations.clear(),this.started=!1}reserveRelay(){var e=xv();return this.pendingReservations.push(e),h(Av,this,Bv).call(this),e}addRelay(e,t){var n=this;return r((function*(){if(n.peerId.equals(e))throw n.log.trace("not trying to use self as relay"),new rs("Cannot use self as relay");if(n.reserveQueue.size>n.maxReservationQueueLength)throw new Lh("The reservation queue is full");var i=n.reserveQueue.find(e);if(null!=i)return n.log.trace("potential relay peer %p is already in the reservation queue",e),i.join();if(n.relayFilter.has(e.toMultihash().bytes))throw new rs("The relay was previously invalid");return n.log.trace("try to reserve relay slot with %p",e),n.reserveQueue.add(r((function*(){var i=Date.now();try{var o=n.reservations.get(e);if(null!=o){var a=n.connectionManager.getConnections(e),s=!1;if(0===a.length&&n.log("already have relay reservation with %p but we are no longer connected",e),a.map((e=>e.id)).includes(o.connection)&&(n.log("already have relay reservation with %p and the original connection is still open",e),s=!0),s&&Mh(o.reservation.expire)>6e5)return n.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:o};yield h(Av,n,Pv).call(n,e)}if("discovered"===t&&0===n.pendingReservations.length)throw new Rh("Not making reservation on discovered relay because we do not need any more relays");var l=AbortSignal.timeout(n.reservationCompletionTimeout),u=yield n.connectionManager.openConnection(e,{signal:l});if(Ph.matches(u.remoteAddr))throw new Oh("not creating reservation over relayed connection");var c=yield h(Av,n,Iv).call(n,u,{signal:l}),d=Mh(c.expire);n.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+d).toString());var v,p=Math.min(Math.max(d-3e5,3e4),Math.pow(2,31)-1),f=setTimeout((()=>{n.log("refresh reservation to relay %p",e),n.addRelay(e,t).catch(function(){var t=r((function*(t){n.log.error("could not refresh reservation to relay %p - %e",e,t),yield h(Av,n,Pv).call(n,e)}));return function(e){return t.apply(this,arguments)}}()).catch((t=>{n.log.error("could not remove expired reservation to relay %p - %e",e,t)}))}),p);if("discovered"===t){var g=n.pendingReservations.pop();if(null==g)throw new Rh("Made reservation on relay but did not need any more discovered relays");v={timeout:f,reservation:c,type:t,connection:u.id,id:g}}else v={timeout:f,reservation:c,type:t,connection:u.id};n.reservations.set(e,v),yield n.peerStore.merge(e,{tags:{[Pd]:{value:1,ttl:d}}}),h(Av,n,Bv).call(n);var y={relay:e,details:v};return n.safeDispatchEvent("relay:created-reservation",{detail:y}),y}catch(r){throw"discovered"===t&&"HadEnoughRelaysError"===r.name||n.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-i,r),"DialError"!==r.name&&"UnsupportedProtocolError"!==r.name||n.relayFilter.add(e.toMultihash().bytes),h(Av,n,Pv).call(n,e).catch((t=>{n.log.error("could not remove reservation on %p after reserving slot failed - %e",e,t)})),r}})),{peerId:e})}))()}hasReservation(e){return this.reservations.has(e)}getReservation(e){var t;return null===(t=this.reservations.get(e))||void 0===t?void 0:t.reservation}reservationCount(e){return null==e?this.reservations.size:[...this.reservations.values()].reduce(((t,r)=>(r.type===e&&t++,t)),0)}cancelReservations(){[...this.reservations.values()].forEach((e=>{clearTimeout(e.timeout)})),this.reservations.clear()}}function Iv(e,t){return Tv.apply(this,arguments)}function Tv(){return Tv=r((function*(e,t){var r,n;null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);var i,o=yield e.newStream(Fd,t),a=Td(o).pb(_d);this.log.trace("send RESERVE to %p",e.remotePeer),yield a.write({type:_d.Type.RESERVE},t);try{this.log.trace("reading response from %p",e.remotePeer),i=yield a.read(t)}catch(e){throw o.abort(e),e}finally{"closed"!==o.status&&(yield o.close(t))}if(this.log.trace("read response %o",i),i.status===Od.OK&&null!=i.reservation){var s=new Set;for(var l of(s.add(e.remoteAddr.toString()),i.reservation.addrs)){var u=Ir(l);null==u.getPeerId()&&(u=u.encapsulate("/p2p/".concat(e.remotePeer))),u=Ir(u.toString().replace("/p2p/".concat(e.remotePeer,"/p2p/").concat(e.remotePeer),"/p2p/".concat(e.remotePeer))),s.add(u.toString())}return i.reservation.addrs=[...s].map((e=>Ir(e).bytes)),i.reservation}var c="reservation failed with status ".concat(null!==(n=i.status)&&void 0!==n?n:"undefined");throw this.log.error(c),new Error(c)})),Tv.apply(this,arguments)}function Pv(e){return _v.apply(this,arguments)}function _v(){return _v=r((function*(e){var t=this.reservations.get(e);null!=t&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),"discovered"===t.type&&this.pendingReservations.push(t.id),yield this.peerStore.merge(e,{tags:{[Pd]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),h(Av,this,Bv).call(this))})),_v.apply(this,arguments)}function Bv(){if(0===this.pendingReservations.length)return this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),void this.safeDispatchEvent("relay:found-enough-relays");this.relayFilter=rv(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}var Nv,Dv=300,Rv=300;class Ov{constructor(t){var r,n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"discovery",void 0),e(this,"registrar",void 0),e(this,"peerStore",void 0),e(this,"connectionManager",void 0),e(this,"transportManager",void 0),e(this,"peerId",void 0),e(this,"upgrader",void 0),e(this,"addressManager",void 0),e(this,"connectionGater",void 0),e(this,"reservationStore",void 0),e(this,"logger",void 0),e(this,"maxInboundStopStreams",void 0),e(this,"maxOutboundStopStreams",void 0),e(this,"started",void 0),e(this,"log",void 0),e(this,"shutdownController",void 0),e(this,Symbol.toStringTag,"@libp2p/circuit-relay-v2-transport"),e(this,fs,["@libp2p/transport","@libp2p/circuit-relay-v2-transport"]),e(this,_a,!0),this.log=t.logger.forComponent("libp2p:circuit-relay:transport"),this.registrar=t.registrar,this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.transportManager=t.transportManager,this.logger=t.logger,this.peerId=t.peerId,this.upgrader=t.upgrader,this.addressManager=t.addressManager,this.connectionGater=t.connectionGater,this.maxInboundStopStreams=null!==(r=o.maxInboundStopStreams)&&void 0!==r?r:Dv,this.maxOutboundStopStreams=null!==(n=o.maxOutboundStopStreams)&&void 0!==n?n:Rv,this.shutdownController=new AbortController,this.discovery=new Sv(t,{filter:null!==(i=o.discoveryFilter)&&void 0!==i?i:iv(4096,.001)}),this.discovery.addEventListener("relay:discover",(e=>{this.reservationStore.addRelay(e.detail,"discovered").catch((t=>{"HadEnoughRelaysError"!==t.name&&"RelayQueueFullError"!==t.name&&this.log.error("could not add discovered relay %p",e.detail,t)}))})),this.reservationStore=new Cv(t,o),this.reservationStore.addEventListener("relay:not-enough-relays",(()=>{var e;null===(e=this.discovery)||void 0===e||e.startDiscovery()})),this.reservationStore.addEventListener("relay:found-enough-relays",(()=>{var e;null===(e=this.discovery)||void 0===e||e.stopDiscovery()})),this.started=!1}get[gs](){return null!=this.discovery?["@libp2p/identify"]:[]}isStarted(){return this.started}start(){var e=this;return r((function*(){e.shutdownController=new AbortController,e.shutdownController.signal,yield e.registrar.handle(zd,(t=>{var r=e.upgrader.createInboundAbortSignal(e.shutdownController.signal);e.onStop(t,r).catch((r=>{e.log.error("error while handling STOP protocol",r),t.stream.abort(r)})).finally((()=>{r.clear()}))}),{maxInboundStreams:e.maxInboundStopStreams,maxOutboundStreams:e.maxOutboundStopStreams,runOnLimitedConnection:!0}),yield ds(e.discovery,e.reservationStore),e.started=!0}))()}stop(){var e=this;return r((function*(){e.shutdownController.abort(),yield vs(e.discovery,e.reservationStore),yield e.registrar.unhandle(zd),e.started=!1}))()}dial(e,n){var i=this;return r((function*(){if(1!==e.protoCodes().filter((e=>290===e)).length){var r="Invalid circuit relay address";throw i.log.error(r,e),new ts(r)}var o=e.toString().split("/p2p-circuit"),a=Ir(o[0]),s=Ir(o[o.length-1]),l=a.getPeerId(),u=s.getPeerId();if(null==l||null==u){var c="ircuit relay dial to ".concat(e.toString()," failed as address did not have both relay and destination PeerIDs");throw i.log.error("c".concat(c)),new ts("C".concat(c))}var d,h,v,p=Mu(l),f=Mu(u),g=i.connectionManager.getConnections(p)[0];null==g?(yield i.peerStore.merge(p,{multiaddrs:[a]}),null===(d=n.onProgress)||void 0===d||d.call(n,new cv("circuit-relay:open-connection")),g=yield i.connectionManager.openConnection(p,n)):null===(h=n.onProgress)||void 0===h||h.call(n,new cv("circuit-relay:reuse-connection"));try{var y,m,w;null===(y=n.onProgress)||void 0===y||y.call(n,new cv("circuit-relay:open-hop-stream"));var b=Td(v=yield g.newStream(Fd,n)),S=b.pb(_d);null===(m=n.onProgress)||void 0===m||m.call(n,new cv("circuit-relay:write-connect-message")),yield S.write({type:_d.Type.CONNECT,peer:{id:f.toMultihash().bytes,addrs:[Ir(s).bytes]}},n),null===(w=n.onProgress)||void 0===w||w.call(n,new cv("circuit-relay:read-connect-response"));var E,k,x=yield S.read(n);if(x.status!==Od.OK)throw new Ja("failed to connect via relay with status ".concat(null!==(E=null==x||null===(k=x.status)||void 0===k?void 0:k.toString())&&void 0!==E?E:"undefined"));var A=new Uh(x.limit),C=uv({stream:b.unwrap(),remoteAddr:e,localAddr:a.encapsulate("/p2p-circuit/p2p/".concat(i.peerId.toString())),logger:i.logger,onDataRead:A.onData,onDataWrite:A.onData});return i.log("new outbound relayed connection %a",C.remoteAddr),yield i.upgrader.upgradeOutbound(C,t(t({},n),{},{limits:A.getLimits()}))}catch(e){var I;throw i.log.error("circuit relay dial to destination %p via relay %p failed",f,p,e),null===(I=v)||void 0===I||I.abort(e),e}}))()}createListener(e){return function(e){return new kv(e)}({peerId:this.peerId,connectionManager:this.connectionManager,addressManager:this.addressManager,reservationStore:this.reservationStore,logger:this.logger})}listenFilter(e){return(e=Array.isArray(e)?e:[e]).filter((e=>Fh.exactMatch(e)||zh.exactMatch(e)))}dialFilter(e){return(e=Array.isArray(e)?e:[e]).filter((e=>Ph.exactMatch(e)))}onStop(e,t){var n=this;return r((function*(){var r,i,{connection:o,stream:a}=e;if(!n.reservationStore.hasReservation(o.remotePeer))try{n.log("dialed via relay we did not have a reservation on, start listening on that relay address"),yield n.transportManager.listen([o.remoteAddr.encapsulate("/p2p-circuit")])}catch(e){n.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on",e)}var s=Td(a).pb(Bd),l=yield s.read({signal:t});if(n.log("new circuit relay v2 stop stream from %p with type %s",o.remotePeer,l.type),void 0===(null==l?void 0:l.type))return n.log.error("type was missing from circuit v2 stop protocol request from %s",o.remotePeer),yield s.write({type:Bd.Type.STATUS,status:Od.MALFORMED_MESSAGE},{signal:t}),void(yield a.close());if(l.type!==Bd.Type.CONNECT)return n.log.error("invalid stop connect request via peer %p",o.remotePeer),yield s.write({type:Bd.Type.STATUS,status:Od.UNEXPECTED_MESSAGE},{signal:t}),void(yield a.close());if(!(e=>{if(null==e.peer)return!1;try{e.peer.addrs.forEach(Ir)}catch(e){return!1}return!0})(l))return n.log.error("invalid stop connect request via peer %p",o.remotePeer),yield s.write({type:Bd.Type.STATUS,status:Od.MALFORMED_MESSAGE},{signal:t}),void(yield a.close({signal:t}));var u=zu(He(l.peer.id));if(!0===(yield null===(r=(i=n.connectionGater).denyInboundRelayedConnection)||void 0===r?void 0:r.call(i,o.remotePeer,u)))return n.log.error("connection gater denied inbound relayed connection from %p",o.remotePeer),yield s.write({type:Bd.Type.STATUS,status:Od.PERMISSION_DENIED},{signal:t}),void(yield a.close({signal:t}));n.log.trace("sending success response to %p",o.remotePeer),yield s.write({type:Bd.Type.STATUS,status:Od.OK},{signal:t});var c=new Uh(l.limit),d=o.remoteAddr.encapsulate("/p2p-circuit/p2p/".concat(u.toString()));n.addressManager.getAddresses()[0];var h=uv({stream:s.unwrap().unwrap(),remoteAddr:d,logger:n.logger,onDataRead:c.onData,onDataWrite:c.onData});n.log("new inbound relayed connection %a",h.remoteAddr),yield n.upgrader.upgradeInbound(h,{limits:c.getLimits(),signal:t}),n.log("%s connection %a upgraded","inbound",h.remoteAddr)}))()}}function Lv(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new Ov(t,e)}!function(e){var t,r;!function(e){e.FIN="FIN",e.STOP_SENDING="STOP_SENDING",e.RESET="RESET",e.FIN_ACK="FIN_ACK"}(e.Flag||(e.Flag={})),function(e){e[e.FIN=0]="FIN",e[e.STOP_SENDING=1]="STOP_SENDING",e[e.RESET=2]="RESET",e[e.FIN_ACK=3]="FIN_ACK"}(t||(t={})),function(e){e.codec=()=>Gl(t)}(e.Flag||(e.Flag={})),e.codec=()=>(null==r&&(r=Ql((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==n.lengthDelimited&&r.fork(),null!=t.flag&&(r.uint32(8),e.Flag.codec().encode(t.flag,r)),null!=t.message&&(r.uint32(18),r.bytes(t.message)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n={},i=null==r?t.len:t.pos+r;t.pos<i;){var o=t.uint32();switch(o>>>3){case 1:n.flag=e.Flag.codec().decode(t);break;case 2:n.message=t.bytes();break;default:t.skipType(7&o)}}return n}))),r),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(Nv||(Nv={}));var Mv=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],Uv=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Fv=16384;var zv=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Fv,t=Ot(e-Ot(e)),r=1+Ot(Object.keys(Nv.Flag).length-1);return t+r+1+Ot(e-t-r-1)}(),jv="/webrtc",Vv="/webrtc-signaling/0.0.1",qv=864e5,Hv=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i<o;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))},Kv=function(e,t,r){this.name=e,this.version=t,this.os=r,this.type="browser"},Wv=function(e){this.version=e,this.type="node",this.name="node",this.os=v.platform},Gv=function(e,t,r,n){this.name=e,this.version=t,this.os=r,this.bot=n,this.type="bot-device"},Qv=function(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null},Yv=function(){this.type="react-native",this.name="react-native",this.version=null,this.os=null},Jv=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Zv=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/]],$v=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];class Xv extends Error{constructor(e){super(e),this.name="TimeoutError"}}let ep=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}};var tp=e=>void 0===globalThis.DOMException?new ep(e):new DOMException(e),rp=e=>{var t=void 0===e.reason?tp("This operation was aborted."):e.reason;return t instanceof Error?t:tp(t)};function np(e,t){var n,i,{milliseconds:o,fallback:a,message:s,customTimers:l={setTimeout:setTimeout,clearTimeout:clearTimeout}}=t,u=new Promise(((u,c)=>{if("number"!=typeof o||1!==Math.sign(o))throw new TypeError("Expected `milliseconds` to be a positive number, got `".concat(o,"`"));if(t.signal){var{signal:d}=t;d.aborted&&c(rp(d)),i=()=>{c(rp(d))},d.addEventListener("abort",i,{once:!0})}if(o!==Number.POSITIVE_INFINITY){var h=new Xv;n=l.setTimeout.call(void 0,(()=>{if(a)try{u(a())}catch(e){c(e)}else"function"==typeof e.cancel&&e.cancel(),!1===s?u():s instanceof Error?c(s):(h.message=null!=s?s:"Promise timed out after ".concat(o," milliseconds"),c(h))}),o),r((function*(){try{u(yield e)}catch(e){c(e)}}))()}else e.then(u,c)})),c=u.finally((()=>{c.clear(),i&&t.signal&&t.signal.removeEventListener("abort",i)}));return c.clear=()=>{l.clearTimeout.call(void 0,n),n=void 0},c}var ip="undefined"==typeof document&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product?new Yv:"undefined"!=typeof navigator?function(e){var t=function(e){return""!==e&&Zv.reduce((function(t,r){var n=r[0],i=r[1];if(t)return t;var o=i.exec(e);return!!o&&[n,o]}),!1)}(e);if(!t)return null;var r=t[0],n=t[1];if("searchbot"===r)return new Qv;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length<3&&(i=Hv(Hv([],i,!0),function(e){for(var t=[],r=0;r<e;r++)t.push("0");return t}(3-i.length),!0)):i=[];var o=i.join("."),a=function(e){for(var t=0,r=$v.length;t<r;t++){var n=$v[t],i=n[0];if(n[1].exec(e))return i}return null}(e),s=Jv.exec(e);return s&&s[1]?new Gv(r,o,a,s[1]):new Kv(r,o,a)}(navigator.userAgent):void 0!==v&&v.version?new Wv(v.version.slice(1)):null,op=null!=ip&&"firefox"===ip.name,ap=function(){var e=l((function*(){}));return function(){return e.apply(this,arguments)}}(),sp=function(){var e=r((function*(e){}));return function(t){return e.apply(this,arguments)}}();function lp(e){return up.apply(this,arguments)}function up(){return(up=r((function*(e){var t;return"function"==typeof(e=null!=e?e:{})&&(e=yield e()),e.iceServers=null!==(t=e.iceServers)&&void 0!==t?t:Mv.map((e=>({urls:[e]}))),e}))).apply(this,arguments)}class cp{constructor(t,r){e(this,"log",void 0),e(this,"peerConnection",void 0),e(this,"remoteAddr",void 0),e(this,"timeline",void 0),e(this,"metrics",void 0),e(this,"source",ap()),e(this,"sink",sp),this.log=t.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=r.remoteAddr,this.timeline=r.timeline,this.peerConnection=r.peerConnection;var n=this.peerConnection,i=n.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",n.connectionState,"initial state",i),"disconnected"!==n.connectionState&&"failed"!==n.connectionState&&"closed"!==n.connectionState||(this.timeline.close=Date.now())}}close(e){var t=this;return r((function*(){var e;t.log.trace("closing connection"),t.peerConnection.close(),t.timeline.close=Date.now(),null===(e=t.metrics)||void 0===e||e.increment({close:!0})}))()}abort(e){var t;this.log.error("closing connection due to error",e),this.peerConnection.close(),this.timeline.close=Date.now(),null===(t=this.metrics)||void 0===t||t.increment({abort:!0})}}function dp(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")}function hp(e,t){var r,n,i,o=null===(r=(n=dp(e)).return)||void 0===r?void 0:r.call(n);null!=(i=o)&&"function"==typeof i.then&&"function"==typeof i.catch&&"function"==typeof i.finally&&o.catch((e=>{t.error("could not cause iterator to return",e)}))}function vp(e){return null!=e&&("function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally)}class pp{constructor(t){var r,n;e(this,"id",void 0),e(this,"direction",void 0),e(this,"timeline",void 0),e(this,"protocol",void 0),e(this,"metadata",void 0),e(this,"source",void 0),e(this,"status",void 0),e(this,"readStatus",void 0),e(this,"writeStatus",void 0),e(this,"log",void 0),e(this,"sinkController",void 0),e(this,"sinkEnd",void 0),e(this,"closed",void 0),e(this,"endErr",void 0),e(this,"streamSource",void 0),e(this,"onEnd",void 0),e(this,"onCloseRead",void 0),e(this,"onCloseWrite",void 0),e(this,"onReset",void 0),e(this,"onAbort",void 0),e(this,"sendCloseWriteTimeout",void 0),e(this,"sendingData",void 0),this.sinkController=new AbortController,this.sinkEnd=_c(),this.closed=_c(),this.log=t.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=t.id,this.metadata=null!==(r=t.metadata)&&void 0!==r?r:{},this.direction=t.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=null!==(n=t.sendCloseWriteTimeout)&&void 0!==n?n:5e3,this.onEnd=t.onEnd,this.onCloseRead=t.onCloseRead,this.onCloseWrite=t.onCloseWrite,this.onReset=t.onReset,this.onAbort=t.onAbort,this.source=this.streamSource=Rc({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)}sink(e){var t=this;return r((function*(){if("ready"!==t.writeStatus)throw new qa('writable end state is "'.concat(t.writeStatus,'" not "ready"'));try{t.writeStatus="writing";var r={signal:t.sinkController.signal};if("outbound"===t.direction){var n=t.sendNewStream(r);vp(n)&&(yield n)}var i=()=>{hp(e,t.log)};try{t.sinkController.signal.addEventListener("abort",i),t.log.trace("sink reading from source");var o,a=!1,l=!1;try{for(var u,c=s(e);a=!(u=yield c.next()).done;a=!1){var d=u.value;d=d instanceof Uint8Array?new bs(d):d;var h=t.sendData(d,r);vp(h)&&(t.sendingData=_c(),yield h,t.sendingData.resolve(),t.sendingData=void 0)}}catch(e){l=!0,o=e}finally{try{a&&null!=c.return&&(yield c.return())}finally{if(l)throw o}}}finally{t.sinkController.signal.removeEventListener("abort",i)}t.log.trace('sink finished reading from source, write status is "%s"',t.writeStatus),"writing"===t.writeStatus&&(t.writeStatus="closing",t.log.trace("send close write to remote"),yield t.sendCloseWrite({signal:AbortSignal.timeout(t.sendCloseWriteTimeout)}),t.writeStatus="closed"),t.onSinkEnd()}catch(e){throw t.log.trace("sink ended with error, calling abort with error",e),t.abort(e),e}finally{t.log.trace("resolve sink end"),t.sinkEnd.resolve()}}))()}onSourceEnd(e){var t;null==this.timeline.closeRead&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),null===(t=this.onCloseRead)||void 0===t||t.call(this),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){var t;null==this.timeline.closeWrite&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),null===(t=this.onCloseWrite)||void 0===t||t.call(this),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"))}close(e){var t=this;return r((function*(){"open"===t.status&&(t.log.trace("closing gracefully"),t.status="closing",yield Lc(Promise.all([t.closeWrite(e),t.closeRead(e),t.closed.promise]),null==e?void 0:e.signal),t.status="closed",t.log.trace("closed gracefully"))}))()}closeRead(){var e=arguments,t=this;return r((function*(){var r=e.length>0&&void 0!==e[0]?e[0]:{};if("closing"!==t.readStatus&&"closed"!==t.readStatus){t.log.trace('closing readable end of stream with starting read status "%s"',t.readStatus);var n=t.readStatus;t.readStatus="closing","reset"!==t.status&&"aborted"!==t.status&&null==t.timeline.closeRead&&(t.log.trace("send close read to remote"),yield t.sendCloseRead(r)),"ready"===n&&(t.log.trace("ending internal source queue with %d queued bytes",t.streamSource.readableLength),t.streamSource.end()),t.log.trace("closed readable end of stream")}}))()}closeWrite(){var e=arguments,t=this;return r((function*(){var r=e.length>0&&void 0!==e[0]?e[0]:{};"closing"!==t.writeStatus&&"closed"!==t.writeStatus&&(t.log.trace('closing writable end of stream with starting write status "%s"',t.writeStatus),"ready"===t.writeStatus&&(t.log.trace("sink was never sunk, sink an empty array"),yield Lc(t.sink([]),r.signal)),"writing"===t.writeStatus&&(null!=t.sendingData&&(yield Lc(t.sendingData.promise,r.signal)),t.log.trace("aborting source passed to .sink"),t.sinkController.abort(),yield Lc(t.sinkEnd.promise,r.signal)),t.writeStatus="closed",t.log.trace("closed writable end of stream"))}))()}abort(e){var t;if("closed"!==this.status&&"aborted"!==this.status&&"reset"!==this.status){this.log("abort with error",e),this.log("try to send reset to remote");var r=this.sendReset();vp(r)&&r.catch((e=>{this.log.error("error sending reset message",e)})),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),null===(t=this.onAbort)||void 0===t||t.call(this,e)}}reset(){var e;if("closed"!==this.status&&"aborted"!==this.status&&"reset"!==this.status){var t=new Va("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(t),null===(e=this.onReset)||void 0===e||e.call(this)}}_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}}var fp=4194304;let gp=class extends Error{constructor(){super(...arguments),e(this,"name","InvalidMessageLengthError"),e(this,"code","ERR_INVALID_MSG_LENGTH")}},yp=class extends Error{constructor(){super(...arguments),e(this,"name","InvalidDataLengthError"),e(this,"code","ERR_MSG_DATA_TOO_LONG")}},mp=class extends Error{constructor(){super(...arguments),e(this,"name","InvalidDataLengthLengthError"),e(this,"code","ERR_MSG_LENGTH_TOO_LONG")}},wp=class extends Error{constructor(){super(...arguments),e(this,"name","UnexpectedEOFError"),e(this,"code","ERR_UNEXPECTED_EOF")}};function bp(e){return null!=e[Symbol.asyncIterator]}function Sp(e,t){if(e.byteLength>t)throw new yp("Message length too long")}var Ep,kp=e=>{var t=Ot(e),r=dt(t);return Ut(e,r),kp.bytes=t,r};function xp(e,t){var r,n,i,o=null!==(r=(t=null!=t?t:{}).lengthEncoder)&&void 0!==r?r:kp,a=null!==(n=null===(i=t)||void 0===i?void 0:i.maxDataLength)&&void 0!==n?n:fp;function*d(e){Sp(e,a);var t=o(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return bp(e)?l((function*(){var t,r=!1,n=!1;try{for(var i,o=s(e);r=!(i=yield u(o.next())).done;r=!1){var a=i.value;yield*c(s(d(a)),u)}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw t}}}))():function*(){for(var t of e)yield*d(t)}()}kp.bytes=0,xp.single=(e,t)=>{var r,n,i,o=null!==(r=(t=null!=t?t:{}).lengthEncoder)&&void 0!==r?r:kp;return Sp(e,null!==(n=null===(i=t)||void 0===i?void 0:i.maxDataLength)&&void 0!==n?n:fp),new bs(o(e.byteLength),e)},function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(Ep||(Ep={}));var Ap=e=>{var t=Ft(e);return Ap.bytes=Ot(t),t};function Cp(e,t){var r,n,i,o=new bs,a=Ep.LENGTH,d=-1,h=null!==(r=null==t?void 0:t.lengthDecoder)&&void 0!==r?r:Ap,v=null!==(n=null==t?void 0:t.maxLengthLength)&&void 0!==n?n:8,p=null!==(i=null==t?void 0:t.maxDataLength)&&void 0!==i?i:fp;function*f(){for(;o.byteLength>0;){if(a===Ep.LENGTH)try{if((d=h(o))<0)throw new gp("Invalid message length");if(d>p)throw new yp("Message length too long");var e=h.bytes;o.consume(e),null!=(null==t?void 0:t.onLength)&&t.onLength(d),a=Ep.DATA}catch(e){if(e instanceof RangeError){if(o.byteLength>v)throw new mp("Message length length too long");break}throw e}if(a===Ep.DATA){if(o.byteLength<d)break;var r=o.sublist(0,d);o.consume(d),null!=(null==t?void 0:t.onData)&&t.onData(r),yield r,a=Ep.LENGTH}}}return bp(e)?l((function*(){var t,r=!1,n=!1;try{for(var i,a=s(e);r=!(i=yield u(a.next())).done;r=!1){var l=i.value;o.append(l),yield*c(s(f()),u)}}catch(e){n=!0,t=e}finally{try{r&&null!=a.return&&(yield u(a.return()))}finally{if(n)throw t}}if(o.byteLength>0)throw new wp("Unexpected end of input")}))():function*(){for(var t of e)o.append(t),yield*f();if(o.byteLength>0)throw new wp("Unexpected end of input")}()}Ap.bytes=0,Cp.fromReader=(e,r)=>{var n=1;return Cp(l((function*(){for(;;)try{var{done:t,value:r}=yield u(e.next(n));if(!0===t)return;null!=r&&(yield r)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{n=1}}))(),t(t({},null!=r?r:{}),{},{onLength:e=>{n=e}}))};class Ip extends pp{constructor(t){var n,i,o,a,l,u,c=t.onEnd;switch(t.onEnd=e=>{this.log.trace('readable and writeable ends closed with status "%s"',this.status),Promise.resolve(r((function*(){if(null==n.timeline.abort&&null===n.timeline.reset)try{yield np(n.receiveFinAck.promise,{milliseconds:n.finAckTimeout})}catch(e){n.log.error("error receiving FIN_ACK",e)}}))).then((()=>{this.incomingData.end(),null==c||c(e)})).catch((e=>{this.log.error("error ending stream",e)})).finally((()=>{this.channel.close()}))},super(t),n=this,e(this,"channel",void 0),e(this,"incomingData",void 0),e(this,"maxBufferedAmount",void 0),e(this,"bufferedAmountLowEventTimeout",void 0),e(this,"maxMessageSize",void 0),e(this,"receiveFinAck",void 0),e(this,"finAckTimeout",void 0),e(this,"openTimeout",void 0),e(this,"closeController",void 0),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=Rc(),this.bufferedAmountLowEventTimeout=null!==(i=t.bufferedAmountLowEventTimeout)&&void 0!==i?i:3e4,this.maxBufferedAmount=null!==(o=t.maxBufferedAmount)&&void 0!==o?o:2097152,this.maxMessageSize=(null!==(a=t.maxMessageSize)&&void 0!==a?a:Fv)-zv,this.receiveFinAck=_c(),this.finAckTimeout=null!==(l=t.closeTimeout)&&void 0!==l?l:5e3,this.openTimeout=null!==(u=t.openTimeout)&&void 0!==u?u:5e3,this.closeController=new AbortController,this.channel.readyState){case"open":this.timeline.open=(new Date).getTime();break;case"closed":case"closing":void 0!==this.timeline.close&&0!==this.timeline.close||(this.timeline.close=Date.now());break;case"connecting":break;default:throw this.log.error("unknown datachannel state %s",this.channel.readyState),new qa("Unknown datachannel state")}this.channel.onopen=e=>{this.timeline.open=(new Date).getTime()},this.channel.onclose=e=>{this.log.trace("received onclose event"),this.closeController.abort(),this.receiveFinAck.resolve(),this.close().catch((e=>{this.log.error("error closing stream after channel closed",e)}))},this.channel.onerror=e=>{this.log.trace("received onerror event"),this.closeController.abort();var t=e.error;this.abort(t)},this.channel.onmessage=function(){var e=r((function*(e){var{data:t}=e;null!==t&&0!==t.byteLength&&n.incomingData.push(new Uint8Array(t,0,t.byteLength))}));return function(t){return e.apply(this,arguments)}}();var d=this;Promise.resolve().then(r((function*(){var e,t=!1,r=!1;try{for(var i,o=s(Cp(n.incomingData));t=!(i=yield o.next()).done;t=!1){var a=i.value,l=d.processIncomingProtobuf(a);null!=l&&d.sourcePush(new bs(l))}}catch(t){r=!0,e=t}finally{try{t&&null!=o.return&&(yield o.return())}finally{if(r)throw e}}}))).catch((e=>{this.log.error("error processing incoming data channel messages",e)}))}sendNewStream(){}_sendMessage(e){var t=arguments,n=this;return r((function*(){var r=!(t.length>1&&void 0!==t[1])||t[1];if("closed"===n.channel.readyState||"closing"===n.channel.readyState)throw new qa("Invalid datachannel state - ".concat(n.channel.readyState));if("open"!==n.channel.readyState){var i=AbortSignal.timeout(n.openTimeout),o=Dh([n.closeController.signal,i]);try{n.log('channel state is "%s" and not "open", waiting for "open" event before sending data',n.channel.readyState),yield hv(n.channel,"open",o)}finally{o.clear()}n.log('channel state is now "%s", sending data',n.channel.readyState)}if(r&&n.channel.bufferedAmount>n.maxBufferedAmount){var a=AbortSignal.timeout(n.bufferedAmountLowEventTimeout),s=Dh([n.closeController.signal,a]);try{n.log('channel buffer is %d, wait for "bufferedamountlow" event',n.channel.bufferedAmount),yield hv(n.channel,"bufferedamountlow",s)}catch(e){if(a.aborted)throw new $a("Timed out waiting for DataChannel buffer to clear after ".concat(n.bufferedAmountLowEventTimeout,"ms"));throw e}finally{s.clear()}}try{n.log.trace('sending message, channel state "%s"',n.channel.readyState),n.channel.send(e.subarray())}catch(e){n.log.error("error while sending message",e)}}))()}sendData(e){var t=this;return r((function*(){var r=e.byteLength;for(e=e.sublist();e.byteLength>0;){var n=Math.min(e.byteLength,t.maxMessageSize),i=e.subarray(0,n),o=Nv.encode({message:i}),a=xp.single(o);t.log.trace("sending %d/%d bytes on channel",i.byteLength,r),yield t._sendMessage(a),e.consume(n)}t.log.trace('finished sending data, channel state "%s"',t.channel.readyState)}))()}sendReset(){var e=this;return r((function*(){try{yield e._sendFlag(Nv.Flag.RESET)}catch(t){e.log.error("failed to send reset - %e",t)}finally{e.channel.close()}}))()}sendCloseWrite(e){var t=this;return r((function*(){if("open"===t.channel.readyState){if(yield t._sendFlag(Nv.Flag.FIN)){t.log.trace("awaiting FIN_ACK");try{yield Lc(t.receiveFinAck.promise,null==e?void 0:e.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorName:"FinAckNotReceivedError"})}catch(e){t.log.error("failed to await FIN_ACK",e)}}else t.log.trace("sending FIN failed, not awaiting FIN_ACK");t.receiveFinAck.resolve()}else t.receiveFinAck.resolve()}))()}sendCloseRead(){var e=this;return r((function*(){"open"===e.channel.readyState&&(yield e._sendFlag(Nv.Flag.STOP_SENDING))}))()}processIncomingProtobuf(e){var t=Nv.decode(e);if(void 0!==t.flag&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',t.flag,this.writeStatus,this.readStatus),t.flag===Nv.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Nv.Flag.FIN_ACK).catch((e=>{this.log.error("error sending FIN_ACK immediately",e)}))),t.flag===Nv.Flag.RESET&&this.reset(),t.flag===Nv.Flag.STOP_SENDING&&this.remoteCloseRead(),t.flag===Nv.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),"ready"===this.readStatus)return t.message}_sendFlag(e){var t=this;return r((function*(){if("open"!==t.channel.readyState)return t.log.trace('not sending flag %s because channel is "%s" and not "open"',e.toString(),t.channel.readyState),!1;t.log.trace("sending flag %s",e.toString());var r=Nv.encode({flag:e}),n=xp.single(r);try{return yield t._sendMessage(n,!1),!0}catch(r){t.log.error("could not send flag %s - %e",e.toString(),r)}return!1}))()}}function Tp(e){var{channel:r,direction:n,handshake:i}=e;return new Ip(t({id:"".concat(r.id),log:e.logger.forComponent("libp2p:webrtc:stream:".concat(!0===i?"handshake":n,":").concat(r.id))},e))}class Pp{constructor(r,n){var i,o;e(this,"protocol",void 0),e(this,"peerConnection",void 0),e(this,"bufferedStreams",[]),e(this,"metrics",void 0),e(this,"dataChannelOptions",void 0),e(this,"components",void 0),e(this,"log",void 0),this.components=r,this.peerConnection=n.peerConnection,this.metrics=n.metrics,this.protocol=null!==(i=n.protocol)&&void 0!==i?i:jv,this.dataChannelOptions=null!==(o=n.dataChannelOptions)&&void 0!==o?o:{},this.log=r.logger.forComponent("libp2p:webrtc:muxerfactory"),this.peerConnection.ondatachannel=e=>{var{channel:n}=e;if(this.log.trace('incoming early datachannel with channel id %d and label "%s"',n.id),"init"===n.label)return this.log.trace("closing early init channel"),void n.close();var i={},o=Tp(t({channel:n,direction:"inbound",onEnd:e=>{i.onEnd(e)},logger:r.logger},this.dataChannelOptions));i.stream=o,i.channel=n,i.onEnd=()=>{this.bufferedStreams=this.bufferedStreams.filter((e=>e.stream.id!==o.id))},this.bufferedStreams.push(i)}}createStreamMuxer(e){return new Bp(this.components,t(t({},e),{},{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol}))}}var _p=new WeakSet;class Bp{constructor(r,n){var i,o;d(this,_p),e(this,"init",void 0),e(this,"streams",void 0),e(this,"protocol",void 0),e(this,"log",void 0),e(this,"peerConnection",void 0),e(this,"dataChannelOptions",void 0),e(this,"metrics",void 0),e(this,"logger",void 0),e(this,"source",ap()),e(this,"sink",sp),this.init=n,this.log=r.logger.forComponent("libp2p:webrtc:muxer"),this.logger=r.logger,this.streams=n.streams.map((e=>e.stream)),this.peerConnection=n.peerConnection,this.protocol=null!==(i=n.protocol)&&void 0!==i?i:jv,this.metrics=n.metrics,this.dataChannelOptions=null!==(o=n.dataChannelOptions)&&void 0!==o?o:{},this.peerConnection.ondatachannel=e=>{var r,i,{channel:o}=e;if(this.log.trace("incoming datachannel with channel id %d",o.id),"init"===o.label)return this.log.trace("closing init channel"),void o.close();var a=o.id,s=Tp(t({channel:o,direction:"inbound",onEnd:()=>{h(_p,this,Np).call(this,s,o),this.log("incoming channel %s ended",a)},logger:this.logger},this.dataChannelOptions));this.streams.push(s),null===(r=this.metrics)||void 0===r||r.increment({incoming_stream:!0}),null==n||null===(i=n.onIncomingStream)||void 0===i||i.call(n,s)},this.init.streams.length>0&&queueMicrotask((()=>{this.init.streams.forEach((e=>{var t,r,n;e.onEnd=()=>{this.log("incoming early channel %s ended with state %s",e.channel.id,e.channel.readyState),h(_p,this,Np).call(this,e.stream,e.channel)},null===(t=this.metrics)||void 0===t||t.increment({incoming_stream:!0}),null===(r=this.init)||void 0===r||null===(n=r.onIncomingStream)||void 0===n||n.call(r,e.stream)}))}))}close(e){var t=this;return r((function*(){try{yield Promise.all(t.streams.map(function(){var t=r((function*(t){return t.close(e)}));return function(e){return t.apply(this,arguments)}}()))}catch(e){t.abort(e)}}))()}abort(e){for(var t of this.streams)t.abort(e)}newStream(){var e,r=this.peerConnection.createDataChannel(""),n=r.id;this.log.trace("opened outgoing datachannel with channel id %s",n);var i=Tp(t({channel:r,direction:"outbound",onEnd:()=>{h(_p,this,Np).call(this,i,r),this.log("outgoing channel %s ended",n)},logger:this.logger},this.dataChannelOptions));return this.streams.push(i),null===(e=this.metrics)||void 0===e||e.increment({outgoing_stream:!0}),i}}function Np(e,t){var n,i,o;this.log.trace("stream %s %s %s onEnd",e.direction,e.id,e.protocol),function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3e4,i=arguments.length>3?arguments[3]:void 0;"open"===e.readyState&&Promise.resolve().then(r((function*(){if(e.bufferedAmount>0){i.log("%s drain channel with %d buffered bytes",t,e.bufferedAmount);var r=_c(),o=!1;e.bufferedAmountLowThreshold=0;var a=()=>{o||(i.log("%s drain channel closed before drain",t),r.resolve())};e.addEventListener("close",a,{once:!0}),e.addEventListener("bufferedamountlow",(()=>{o=!0,e.removeEventListener("close",a),r.resolve()})),yield np(r.promise,{milliseconds:n})}}))).then(r((function*(){"open"===e.readyState&&e.close()}))).catch((e=>{i.log.error("error closing outbound stream",e)}))}(t,"".concat(e.direction," ").concat(e.id," ").concat(e.protocol),this.dataChannelOptions.drainTimeout,{log:this.log}),this.streams=this.streams.filter((t=>t.id!==e.id)),null===(n=this.metrics)||void 0===n||n.increment({stream_end:!0}),null===(i=this.init)||void 0===i||null===(o=i.onStreamEnd)||void 0===o||o.call(i,e)}var Dp,Rp=globalThis.RTCPeerConnection,Op=globalThis.RTCSessionDescription,Lp=globalThis.RTCIceCandidate;class Mp extends Error{constructor(e){super("WebRTC transport error: ".concat(e)),this.name="WebRTCTransportError"}}class Up extends Mp{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SDP handshake failed"),this.name="SDPHandshakeFailedError"}}class Fp extends Mp{constructor(e,t){super('Invalid fingerprint "'.concat(e,'" within ').concat(t)),this.name="WebRTC/InvalidFingerprintError"}}class zp extends Mp{constructor(e){super("A method (".concat(e,") was called though it has been intentionally left unimplemented.")),this.name="WebRTC/UnimplementedError"}}class jp extends Mp{constructor(e){super("unsupported hash algorithm code: ".concat(e," please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv ")),this.name="WebRTC/UnsupportedHashAlgorithmError"}}!function(e){var t,r;!function(e){e.SDP_OFFER="SDP_OFFER",e.SDP_ANSWER="SDP_ANSWER",e.ICE_CANDIDATE="ICE_CANDIDATE"}(e.Type||(e.Type={})),function(e){e[e.SDP_OFFER=0]="SDP_OFFER",e[e.SDP_ANSWER=1]="SDP_ANSWER",e[e.ICE_CANDIDATE=2]="ICE_CANDIDATE"}(t||(t={})),function(e){e.codec=()=>Gl(t)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=Ql((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==n.lengthDelimited&&r.fork(),null!=t.type&&(r.uint32(8),e.Type.codec().encode(t.type,r)),null!=t.data&&(r.uint32(18),r.string(t.data)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n={},i=null==r?t.len:t.pos+r;t.pos<i;){var o=t.uint32();switch(o>>>3){case 1:n.type=e.Type.codec().decode(t);break;case 2:n.data=t.string();break;default:t.skipType(7&o)}}return n}))),r),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(Dp||(Dp={}));var Vp=function(){var e=r((function*(e,t,r){try{var n=_c();for(!function(e,t){e[op?"oniceconnectionstatechange":"onconnectionstatechange"]=r=>{switch(qp(e)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new za("RTCPeerConnection was closed"))}}}(e,n);;){var i,o=yield Promise.race([n.promise,t.read({signal:r.signal}).catch((()=>{}))]);if(null==o){var a;null===(a=r.signal)||void 0===a||a.throwIfAborted();break}if(o.type!==Dp.Type.ICE_CANDIDATE)throw new Ja("ICE candidate message expected");var s=JSON.parse(null!==(i=o.data)&&void 0!==i?i:"null");if(""!==s&&null!==s){var l=new Lp(s);r.log.trace("%s received new ICE candidate %o",r.direction,s);try{var u;null===(u=r.onProgress)||void 0===u||u.call(r,new cv("webrtc:add-ice-candidate",l.candidate)),yield e.addIceCandidate(l)}catch(e){r.log.error("%s bad candidate received",r.direction,s,e)}}else{var c;null===(c=r.onProgress)||void 0===c||c.call(r,new cv("webrtc:end-of-ice-candidates")),r.log.trace("end-of-candidates received")}}}catch(t){var d;if(r.log.error("%s error parsing ICE candidate",r.direction,t),!0===(null===(d=r.signal)||void 0===d?void 0:d.aborted)&&"connected"!==qp(e))throw t}}));return function(t,r,n){return e.apply(this,arguments)}}();function qp(e){return op?e.iceConnectionState:e.connectionState}function Hp(){return Hp=r((function*(e){var{rtcConfiguration:t,dataChannel:r,signal:n,metrics:i,multiaddr:o,connectionManager:a,transportManager:s,log:l,logger:u,onProgress:c}=e,{baseAddr:d}=function(e){var t=e.toString().split("/webrtc/");if(2!==t.length)throw new Ra("webrtc protocol was not present in multiaddr");if(!t[0].includes("/p2p-circuit"))throw new Ra("p2p-circuit protocol was not present in multiaddr");var r=Ir(t[0]),n=Ir("/"+t[1]).getPeerId();if(null==n)throw new Ra("destination peer id was missing");var i=r.protos().pop();if(void 0===i)throw new Ra("invalid multiaddr");"p2p"!==i.name&&(r=r.encapsulate("/p2p/".concat(n)));return{baseAddr:r,peerId:Mu(n)}}(o);null==i||i.dialerEvents.increment({open:!0}),l.trace("dialing base address: %a",d);var h=d.getPeerId();if(null==h)throw new Ra("Relay peer was missing");var v,p=a.getConnections(Mu(h)),f=!1;0===p.length?(null==c||c(new cv("webrtc:dial-relay")),v=yield s.dial(d,{signal:n,onProgress:c}),f=!0):(null==c||c(new cv("webrtc:reuse-relay-connection")),v=p[0]);try{null==c||c(new cv("webrtc:open-signaling-stream"));var g=yield v.newStream(Vv,{signal:n,runOnLimitedConnection:!0}),y=Td(g).pb(Dp),m=new Rp(t),w=new Pp({logger:u},{peerConnection:m,dataChannelOptions:r});try{var b=m.createDataChannel("init");m.onicecandidate=e=>{var t,{candidate:r}=e,i=JSON.stringify(null!==(t=null==r?void 0:r.toJSON())&&void 0!==t?t:null);l.trace("initiator sending ICE candidate %o",r),y.write({type:Dp.Type.ICE_CANDIDATE,data:i},{signal:n}).catch((e=>{l.error("error sending ICE candidate",e)}))},m.onicecandidateerror=e=>{l.error("initiator ICE candidate error",e)};var S=yield m.createOffer().catch((e=>{throw l.error("could not execute createOffer",e),new Up("Failed to set createOffer")}));l.trace("initiator send SDP offer %s",S.sdp),null==c||c(new cv("webrtc:send-sdp-offer")),yield y.write({type:Dp.Type.SDP_OFFER,data:S.sdp},{signal:n}),yield m.setLocalDescription(S).catch((e=>{throw l.error("could not execute setLocalDescription",e),new Up("Failed to set localDescription")})),null==c||c(new cv("webrtc:read-sdp-answer")),l.trace("initiator read SDP answer");var E=yield y.read({signal:n});if(E.type!==Dp.Type.SDP_ANSWER)throw new Up("Remote should send an SDP answer");l.trace("initiator received SDP answer %s",E.data);var k=new Op({type:"answer",sdp:E.data});return yield m.setRemoteDescription(k).catch((e=>{throw l.error("could not execute setRemoteDescription",e),new Up("Failed to set remoteDescription")})),l.trace("initiator read candidates until connected"),null==c||c(new cv("webrtc:read-ice-candidates")),yield Vp(m,y,{direction:"initiator",signal:n,log:l,onProgress:c}),l.trace("initiator connected, closing init channel"),b.close(),null==c||c(new cv("webrtc:close-signaling-stream")),l.trace("closing signaling channel"),yield g.close({signal:n}),l.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:m,muxerFactory:w}}catch(e){throw l.error("outgoing signaling error",e),m.close(),g.abort(e),e}finally{m.onicecandidate=null,m.onicecandidateerror=null}}finally{if(f)try{yield v.close({signal:n})}catch(e){v.abort(e)}}})),Hp.apply(this,arguments)}var Kp=Jd(Th.matchers[0],Vd("p2p-circuit"));class Wp extends us{constructor(t,r){super(),e(this,"transportManager",void 0),e(this,"shutdownController",void 0),e(this,"events",void 0),this.transportManager=t.transportManager,this.events=t.events,this.shutdownController=r.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}listen(){var e=this;return r((function*(){e.events.addEventListener("transport:listening",e.onTransportListening)}))()}onTransportListening(e){e.detail.getAddrs().filter((e=>Kp.exactMatch(e))).map((e=>e.encapsulate("/webrtc"))).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter((e=>!(e instanceof Wp))).map((e=>e.getAddrs().filter((e=>Kp.exactMatch(e))).map((e=>e.encapsulate("/webrtc"))))).flat()}updateAnnounceAddrs(){}close(){var e=this;return r((function*(){e.events.removeEventListener("transport:listening",e.onTransportListening),e.shutdownController.abort(),queueMicrotask((()=>{e.safeDispatchEvent("close")}))}))()}}function Gp(){return Gp=r((function*(e){var{peerConnection:t,stream:r,signal:n,connection:i,log:o}=e;o.trace("new inbound signaling stream");var a=Td(r).pb(Dp);try{t.onicecandidate=e=>{var t,{candidate:r}=e,i=JSON.stringify(null!==(t=null==r?void 0:r.toJSON())&&void 0!==t?t:null);o.trace("recipient sending ICE candidate %s",i),a.write({type:Dp.Type.ICE_CANDIDATE,data:i},{signal:n}).catch((e=>{o.error("error sending ICE candidate",e)}))},o.trace("recipient read SDP offer");var s,l=yield a.read({signal:n});if(l.type!==Dp.Type.SDP_OFFER)throw new Up("expected message type SDP_OFFER, received: ".concat(null!==(s=l.type)&&void 0!==s?s:"undefined"," "));o.trace("recipient received SDP offer %s",l.data);var u=new Op({type:"offer",sdp:l.data});yield t.setRemoteDescription(u).catch((e=>{throw o.error("could not execute setRemoteDescription",e),new Up("Failed to set remoteDescription")}));var c=yield t.createAnswer().catch((e=>{throw o.error("could not execute createAnswer",e),new Up("Failed to create answer")}));o.trace("recipient send SDP answer %s",c.sdp),yield a.write({type:Dp.Type.SDP_ANSWER,data:c.sdp},{signal:n}),yield t.setLocalDescription(c).catch((e=>{throw o.error("could not execute setLocalDescription",e),new Up("Failed to set localDescription")})),o.trace("recipient read candidates until connected"),yield Vp(t,a,{direction:"recipient",signal:n,log:o})}catch(e){if("connected"!==qp(t))throw o.error("error while handling signaling stream from peer %a",i.remoteAddr,e),t.close(),e;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",i.remoteAddr,e)}var d=Ir("/webrtc/p2p/".concat(i.remoteAddr.getPeerId()));return o.trace("recipient connected to remote address %s",d),{remoteAddress:d}})),Gp.apply(this,arguments)}class Qp{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"components",void 0),e(this,"init",void 0),e(this,"log",void 0),e(this,"_started",!1),e(this,"metrics",void 0),e(this,"shutdownController",void 0),e(this,_a,!0),e(this,Symbol.toStringTag,"@libp2p/webrtc"),e(this,fs,["@libp2p/transport"]),e(this,gs,["@libp2p/identify","@libp2p/circuit-relay-v2-transport"]),this.components=t,this.init=r,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,null!=t.metrics&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}isStarted(){return this._started}start(){var e=this;return r((function*(){yield e.components.registrar.handle(Vv,(t=>{var r=e.components.upgrader.createInboundAbortSignal(e.shutdownController.signal);e._onProtocol(t,r).catch((r=>{e.log.error("failed to handle incoming connect from %p",t.connection.remotePeer,r)})).finally((()=>{r.clear()}))}),{runOnLimitedConnection:!0}),e._started=!0}))()}stop(){var e=this;return r((function*(){yield e.components.registrar.unhandle(Vv),e._started=!1}))()}createListener(e){return new Wp(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(_h.exactMatch)}dialFilter(e){return this.listenFilter(e)}dial(e,t){var n=this;return r((function*(){var r;n.log.trace("dialing address: %a",e);var{remoteAddress:i,peerConnection:o,muxerFactory:a}=yield function(e){return Hp.apply(this,arguments)}({rtcConfiguration:yield lp(n.init.rtcConfiguration),dataChannel:n.init.dataChannel,multiaddr:e,dataChannelOptions:n.init.dataChannel,signal:t.signal,connectionManager:n.components.connectionManager,transportManager:n.components.transportManager,log:n.log,logger:n.components.logger,onProgress:t.onProgress}),s=new cp(n.components,{peerConnection:o,timeline:{open:Date.now()},remoteAddr:i,metrics:null===(r=n.metrics)||void 0===r?void 0:r.dialerEvents}),l=yield t.upgrader.upgradeOutbound(s,{skipProtection:!0,skipEncryption:!0,muxerFactory:a,onProgress:t.onProgress,signal:t.signal});return n._closeOnShutdown(o,s),l}))()}_onProtocol(e,t){var n=this;return r((function*(){var{connection:r,stream:i}=e,o=new Rp(yield lp(n.init.rtcConfiguration)),a=new Pp(n.components,{peerConnection:o,dataChannelOptions:n.init.dataChannel});try{var s,{remoteAddress:l}=yield function(e){return Gp.apply(this,arguments)}({peerConnection:o,connection:r,stream:i,signal:t,log:n.log});yield i.close({signal:t});var u=new cp(n.components,{peerConnection:o,timeline:{open:(new Date).getTime()},remoteAddr:l,metrics:null===(s=n.metrics)||void 0===s?void 0:s.listenerEvents});yield n.components.upgrader.upgradeInbound(u,{skipEncryption:!0,skipProtection:!0,muxerFactory:a,signal:t}),n._closeOnShutdown(o,u)}catch(e){throw n.log.error("incoming signaling error",e),o.close(),i.abort(e),e}}))()}_closeOnShutdown(e,t){var r=()=>{t.close().catch((e=>{this.log.error("could not close WebRTCMultiaddrConnection",e)}))};this.shutdownController.signal.addEventListener("abort",r),e.addEventListener("close",(()=>{this.shutdownController.signal.removeEventListener("abort",r)}))}}var Yp,Jp={};!function(){return Yp||(Yp=1,function(e){!function(){var t="object"==typeof globalThis?globalThis:"object"==typeof p?p:"object"==typeof self?self:"object"==typeof this?this:function(){try{return Function("return this;")()}catch(e){}}()||function(){try{return(0,eval)("(function() { return this; })()")}catch(e){}}(),r=n(e);function n(e,t){return function(r,n){Object.defineProperty(e,r,{configurable:!0,writable:!0,value:n}),t&&t(r,n)}}void 0!==t.Reflect&&(r=n(t.Reflect,r)),function(e,t){var r=Object.prototype.hasOwnProperty,n="function"==typeof Symbol,i=n&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",o=n&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",a="function"==typeof Object.create,s={__proto__:[]}instanceof Array,l=!a&&!s,u={create:a?function(){return de(Object.create(null))}:s?function(){return de({__proto__:null})}:function(){return de({})},has:l?function(e,t){return r.call(e,t)}:function(e,t){return t in e},get:l?function(e,t){return r.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},c=Object.getPrototypeOf(Function),d="function"==typeof Map&&"function"==typeof Map.prototype.entries?Map:le(),h="function"==typeof Set&&"function"==typeof Set.prototype.entries?Set:ue(),v="function"==typeof WeakMap?WeakMap:ce(),p=n?Symbol.for("@reflect-metadata:registry"):void 0,f=ie(),g=oe(f);function y(e,t,r,n){if(M(r)){if(!W(e))throw new TypeError;if(!Q(t))throw new TypeError;return I(e,t)}if(!W(e))throw new TypeError;if(!z(t))throw new TypeError;if(!z(n)&&!M(n)&&!U(n))throw new TypeError;return U(n)&&(n=void 0),T(e,t,r=K(r),n)}function m(e,t){function r(r,n){if(!z(r))throw new TypeError;if(!M(n)&&!Y(n))throw new TypeError;D(e,t,r,n)}return r}function w(e,t,r,n){if(!z(r))throw new TypeError;return M(n)||(n=K(n)),D(e,t,r,n)}function b(e,t,r){if(!z(t))throw new TypeError;return M(r)||(r=K(r)),P(e,t,r)}function S(e,t,r){if(!z(t))throw new TypeError;return M(r)||(r=K(r)),_(e,t,r)}function E(e,t,r){if(!z(t))throw new TypeError;return M(r)||(r=K(r)),B(e,t,r)}function k(e,t,r){if(!z(t))throw new TypeError;return M(r)||(r=K(r)),N(e,t,r)}function x(e,t){if(!z(e))throw new TypeError;return M(t)||(t=K(t)),R(e,t)}function A(e,t){if(!z(e))throw new TypeError;return M(t)||(t=K(t)),O(e,t)}function C(e,t,r){if(!z(t))throw new TypeError;if(M(r)||(r=K(r)),!z(t))throw new TypeError;M(r)||(r=K(r));var n=se(t,r,!1);return!M(n)&&n.OrdinaryDeleteMetadata(e,t,r)}function I(e,t){for(var r=e.length-1;r>=0;--r){var n=(0,e[r])(t);if(!M(n)&&!U(n)){if(!Q(n))throw new TypeError;t=n}}return t}function T(e,t,r,n){for(var i=e.length-1;i>=0;--i){var o=(0,e[i])(t,r,n);if(!M(o)&&!U(o)){if(!z(o))throw new TypeError;n=o}}return n}function P(e,t,r){if(_(e,t,r))return!0;var n=re(t);return!U(n)&&P(e,n,r)}function _(e,t,r){var n=se(t,r,!1);return!M(n)&&q(n.OrdinaryHasOwnMetadata(e,t,r))}function B(e,t,r){if(_(e,t,r))return N(e,t,r);var n=re(t);return U(n)?void 0:B(e,n,r)}function N(e,t,r){var n=se(t,r,!1);if(!M(n))return n.OrdinaryGetOwnMetadata(e,t,r)}function D(e,t,r,n){se(r,n,!0).OrdinaryDefineOwnMetadata(e,t,r,n)}function R(e,t){var r=O(e,t),n=re(e);if(null===n)return r;var i=R(n,t);if(i.length<=0)return r;if(r.length<=0)return i;for(var o=new h,a=[],s=0,l=r;s<l.length;s++){var u=l[s];o.has(u)||(o.add(u),a.push(u))}for(var c=0,d=i;c<d.length;c++){u=d[c];o.has(u)||(o.add(u),a.push(u))}return a}function O(e,t){var r=se(e,t,!1);return r?r.OrdinaryOwnMetadataKeys(e,t):[]}function L(e){if(null===e)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return null===e?1:6;default:return 6}}function M(e){return void 0===e}function U(e){return null===e}function F(e){return"symbol"==typeof e}function z(e){return"object"==typeof e?null!==e:"function"==typeof e}function j(e,t){switch(L(e)){case 0:case 1:case 2:case 3:case 4:case 5:return e}var r="string",n=Z(e,i);if(void 0!==n){var o=n.call(e,r);if(z(o))throw new TypeError;return o}return V(e)}function V(e,t){var r,n,i=e.toString;if(G(i)&&!z(n=i.call(e)))return n;if(G(r=e.valueOf)&&!z(n=r.call(e)))return n;throw new TypeError}function q(e){return!!e}function H(e){return""+e}function K(e){var t=j(e);return F(t)?t:H(t)}function W(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function G(e){return"function"==typeof e}function Q(e){return"function"==typeof e}function Y(e){switch(L(e)){case 3:case 4:return!0;default:return!1}}function J(e,t){return e===t||e!=e&&t!=t}function Z(e,t){var r=e[t];if(null!=r){if(!G(r))throw new TypeError;return r}}function $(e){var t=Z(e,o);if(!G(t))throw new TypeError;var r=t.call(e);if(!z(r))throw new TypeError;return r}function X(e){return e.value}function ee(e){var t=e.next();return!t.done&&t}function te(e){var t=e.return;t&&t.call(e)}function re(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===c)return t;if(t!==c)return t;var r=e.prototype,n=r&&Object.getPrototypeOf(r);if(null==n||n===Object.prototype)return t;var i=n.constructor;return"function"!=typeof i||i===e?t:i}function ne(){var e,r,n,i;M(p)||void 0===t.Reflect||p in t.Reflect||"function"!=typeof t.Reflect.defineMetadata||(e=ae(t.Reflect));var o=new v,a={registerProvider:s,getProvider:u,setProvider:f};return a;function s(t){if(!Object.isExtensible(a))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case e===t:break;case M(r):r=t;break;case r===t:break;case M(n):n=t;break;case n===t:break;default:void 0===i&&(i=new h),i.add(t)}}function l(t,o){if(!M(r)){if(r.isProviderFor(t,o))return r;if(!M(n)){if(n.isProviderFor(t,o))return r;if(!M(i))for(var a=$(i);;){var s=ee(a);if(!s)return;var l=X(s);if(l.isProviderFor(t,o))return te(a),l}}}if(!M(e)&&e.isProviderFor(t,o))return e}function u(e,t){var r,n=o.get(e);return M(n)||(r=n.get(t)),M(r)?(M(r=l(e,t))||(M(n)&&(n=new d,o.set(e,n)),n.set(t,r)),r):r}function c(e){if(M(e))throw new TypeError;return r===e||n===e||!M(i)&&i.has(e)}function f(e,t,r){if(!c(r))throw new Error("Metadata provider not registered.");var n=u(e,t);if(n!==r){if(!M(n))return!1;var i=o.get(e);M(i)&&(i=new d,o.set(e,i)),i.set(t,r)}return!0}}function ie(){var e;return!M(p)&&z(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[p]),M(e)&&(e=ne()),!M(p)&&z(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,p,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}function oe(e){var t=new v,r={isProviderFor:function(e,r){var n=t.get(e);return!M(n)&&n.has(r)},OrdinaryDefineOwnMetadata:a,OrdinaryHasOwnMetadata:i,OrdinaryGetOwnMetadata:o,OrdinaryOwnMetadataKeys:s,OrdinaryDeleteMetadata:l};return f.registerProvider(r),r;function n(n,i,o){var a=t.get(n),s=!1;if(M(a)){if(!o)return;a=new d,t.set(n,a),s=!0}var l=a.get(i);if(M(l)){if(!o)return;if(l=new d,a.set(i,l),!e.setProvider(n,i,r))throw a.delete(i),s&&t.delete(n),new Error("Wrong provider for target.")}return l}function i(e,t,r){var i=n(t,r,!1);return!M(i)&&q(i.has(e))}function o(e,t,r){var i=n(t,r,!1);if(!M(i))return i.get(e)}function a(e,t,r,i){n(r,i,!0).set(e,t)}function s(e,t){var r=[],i=n(e,t,!1);if(M(i))return r;for(var o=$(i.keys()),a=0;;){var s=ee(o);if(!s)return r.length=a,r;var l=X(s);try{r[a]=l}catch(e){try{te(o)}finally{throw e}}a++}}function l(e,r,i){var o=n(r,i,!1);if(M(o))return!1;if(!o.delete(e))return!1;if(0===o.size){var a=t.get(r);M(a)||(a.delete(i),0===a.size&&t.delete(a))}return!0}}function ae(e){var t=e.defineMetadata,r=e.hasOwnMetadata,n=e.getOwnMetadata,i=e.getOwnMetadataKeys,o=e.deleteMetadata,a=new v;return{isProviderFor:function(e,t){var r=a.get(e);return!(M(r)||!r.has(t))||!!i(e,t).length&&(M(r)&&(r=new h,a.set(e,r)),r.add(t),!0)},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:n,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:o}}function se(e,t,r){var n=f.getProvider(e,t);if(!M(n))return n;if(r){if(f.setProvider(e,t,g))return g;throw new Error("Illegal state.")}}function le(){var e={},t=[],r=function(){function e(e,t,r){this._index=0,this._keys=e,this._values=t,this._selector=r}return e.prototype["@@iterator"]=function(){return this},e.prototype[o]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var r=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:r,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:e,done:!0}},e}(),n=function(){function t(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(t.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),t.prototype.has=function(e){return this._find(e,!1)>=0},t.prototype.get=function(e){var t=this._find(e,!1);return t>=0?this._values[t]:void 0},t.prototype.set=function(e,t){var r=this._find(e,!0);return this._values[r]=t,this},t.prototype.delete=function(t){var r=this._find(t,!1);if(r>=0){for(var n=this._keys.length,i=r+1;i<n;i++)this._keys[i-1]=this._keys[i],this._values[i-1]=this._values[i];return this._keys.length--,this._values.length--,J(t,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},t.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},t.prototype.keys=function(){return new r(this._keys,this._values,i)},t.prototype.values=function(){return new r(this._keys,this._values,a)},t.prototype.entries=function(){return new r(this._keys,this._values,s)},t.prototype["@@iterator"]=function(){return this.entries()},t.prototype[o]=function(){return this.entries()},t.prototype._find=function(e,t){if(!J(this._cacheKey,e)){this._cacheIndex=-1;for(var r=0;r<this._keys.length;r++)if(J(this._keys[r],e)){this._cacheIndex=r;break}}return this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();return n;function i(e,t){return e}function a(e,t){return t}function s(e,t){return[e,t]}}function ue(){return function(){function e(){this._map=new d}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype["@@iterator"]=function(){return this.keys()},e.prototype[o]=function(){return this.keys()},e}()}function ce(){var e=16,t=u.create(),n=i();return function(){function e(){this._key=i()}return e.prototype.has=function(e){var t=o(e,!1);return void 0!==t&&u.has(t,this._key)},e.prototype.get=function(e){var t=o(e,!1);return void 0!==t?u.get(t,this._key):void 0},e.prototype.set=function(e,t){return o(e,!0)[this._key]=t,this},e.prototype.delete=function(e){var t=o(e,!1);return void 0!==t&&delete t[this._key]},e.prototype.clear=function(){this._key=i()},e}();function i(){var e;do{e="@@WeakMap@@"+l()}while(u.has(t,e));return t[e]=!0,e}function o(e,t){if(!r.call(e,n)){if(!t)return;Object.defineProperty(e,n,{value:u.create()})}return e[n]}function a(e,t){for(var r=0;r<t;++r)e[r]=255*Math.random()|0;return e}function s(e){if("function"==typeof Uint8Array){var t=new Uint8Array(e);return"undefined"!=typeof crypto?crypto.getRandomValues(t):"undefined"!=typeof msCrypto?msCrypto.getRandomValues(t):a(t,e),t}return a(new Array(e),e)}function l(){var t=s(e);t[6]=79&t[6]|64,t[8]=191&t[8]|128;for(var r="",n=0;n<e;++n){var i=t[n];4!==n&&6!==n&&8!==n||(r+="-"),i<16&&(r+="0"),r+=i.toString(16).toLowerCase()}return r}}function de(e){return e.__=void 0,delete e.__,e}e("decorate",y),e("metadata",m),e("defineMetadata",w),e("hasMetadata",b),e("hasOwnMetadata",S),e("getMetadata",E),e("getOwnMetadata",k),e("getMetadataKeys",x),e("getOwnMetadataKeys",A),e("deleteMetadata",C)}(r,t),void 0===t.Reflect&&(t.Reflect=e)}()}(e||(e={}))),Jp;var e}();var Zp,$p={};var Xp=function(){if(Zp)return $p;Zp=1;class e{static isArrayBuffer(e){return"[object ArrayBuffer]"===Object.prototype.toString.call(e)}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(t,r){var n=e.toUint8Array(t),i=e.toUint8Array(r);if(n.length!==i.byteLength)return!1;for(var o=0;o<n.length;o++)if(n[o]!==i[o])return!1;return!0}static concat(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];e=!Array.isArray(r[0])||r[1]instanceof Function?Array.isArray(r[0])&&r[1]instanceof Function?r[0]:r[r.length-1]instanceof Function?r.slice(0,r.length-1):r:r[0];var i=0;for(var o of e)i+=o.byteLength;var a=new Uint8Array(i),s=0;for(var l of e){var u=this.toUint8Array(l);a.set(u,s),s+=u.length}return r[r.length-1]instanceof Function?this.toView(a,r[r.length-1]):a.buffer}}var t="string",r=/^[0-9a-f\s]+$/i,n=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,i=/^[a-zA-Z0-9-_]+$/;class o{static fromString(e){for(var t=unescape(encodeURIComponent(e)),r=new Uint8Array(t.length),n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r.buffer}static toString(t){for(var r=e.toUint8Array(t),n="",i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return decodeURIComponent(escape(n))}}class a{static toString(t){for(var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=e.toArrayBuffer(t),i=new DataView(n),o="",a=0;a<n.byteLength;a+=2){var s=i.getUint16(a,r);o+=String.fromCharCode(s)}return o}static fromString(e){for(var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=new ArrayBuffer(2*e.length),n=new DataView(r),i=0;i<e.length;i++)n.setUint16(2*i,e.charCodeAt(i),t);return r}}class s{static isHex(e){return typeof e===t&&r.test(e)}static isBase64(e){return typeof e===t&&n.test(e)}static isBase64Url(e){return typeof e===t&&i.test(e)}static ToString(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8",n=e.toUint8Array(t);switch(r.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return a.toString(n,!0);case"utf16":case"utf16be":return a.toString(n);default:throw new Error("Unknown type of encoding '".concat(r,"'"))}}static FromString(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8";if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return a.fromString(e,!0);case"utf16":case"utf16be":return a.fromString(e);default:throw new Error("Unknown type of encoding '".concat(t,"'"))}}static ToBase64(t){var r=e.toUint8Array(t);if("undefined"!=typeof btoa){var n=this.ToString(r,"binary");return btoa(n)}return Buffer.from(r).toString("base64")}static FromBase64(e){var t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!s.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return"undefined"!=typeof atob?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){var t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!s.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s.DEFAULT_UTF8_ENCODING;switch(t){case"ascii":return this.FromBinary(e);case"utf8":return o.fromString(e);case"utf16":case"utf16be":return a.fromString(e);case"utf16le":case"usc2":return a.fromString(e,!0);default:throw new Error("Unknown type of encoding '".concat(t,"'"))}}static ToUtf8String(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s.DEFAULT_UTF8_ENCODING;switch(t){case"ascii":return this.ToBinary(e);case"utf8":return o.toString(e);case"utf16":case"utf16be":return a.toString(e);case"utf16le":case"usc2":return a.toString(e,!0);default:throw new Error("Unknown type of encoding '".concat(t,"'"))}}static FromBinary(e){for(var t=e.length,r=new Uint8Array(t),n=0;n<t;n++)r[n]=e.charCodeAt(n);return r.buffer}static ToBinary(t){for(var r=e.toUint8Array(t),n="",i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return n}static ToHex(t){for(var r=e.toUint8Array(t),n="",i=r.length,o=0;o<i;o++){var a=r[o];a<16&&(n+="0"),n+=a.toString(16)}return n}static FromHex(e){var t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!s.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t="0".concat(t));for(var r=new Uint8Array(t.length/2),n=0;n<t.length;n+=2){var i=t.slice(n,n+2);r[n/2]=parseInt(i,16)}return r.buffer}static ToUtf16String(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return a.toString(e,t)}static FromUtf16String(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return a.fromString(e,t)}static Base64Padding(e){var t=4-e.length%4;if(t<4)for(var r=0;r<t;r++)e+="=";return e}static formatString(e){return(null==e?void 0:e.replace(/[\n\r\t ]/g,""))||""}}return s.DEFAULT_UTF8_ENCODING="utf8",$p.BufferSourceConverter=e,$p.Convert=s,$p.assign=function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];for(var i=arguments[0],o=1;o<arguments.length;o++){var a=arguments[o];for(var s in a)i[s]=a[s]}return i},$p.combine=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];var n=t.map((e=>e.byteLength)).reduce(((e,t)=>e+t)),i=new Uint8Array(n),o=0;return t.map((e=>new Uint8Array(e))).forEach((e=>{for(var t of e)i[o++]=t})),i.buffer},$p.isEqual=function(e,t){if(!e||!t)return!1;if(e.byteLength!==t.byteLength)return!1;for(var r=new Uint8Array(e),n=new Uint8Array(t),i=0;i<e.byteLength;i++)if(r[i]!==n[i])return!1;return!0},$p}();function ef(e,t){var r=0;if(1===e.length)return e[0];for(var n=e.length-1;n>=0;n--)r+=e[e.length-1-n]*Math.pow(2,t*n);return r}function tf(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1,n=e,i=0,o=Math.pow(2,t),a=1;a<8;a++){if(e<o){var s=void 0;if(r<0)s=new ArrayBuffer(a),i=a;else{if(r<a)return new ArrayBuffer(0);s=new ArrayBuffer(r),i=r}for(var l=new Uint8Array(s),u=a-1;u>=0;u--){var c=Math.pow(2,u*t);l[i-u-1]=Math.floor(n/c),n-=l[i-u-1]*c}return s}o*=Math.pow(2,t)}return new ArrayBuffer(0)}function rf(){for(var e=0,t=0,r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];for(var o of n)e+=o.length;var a=new ArrayBuffer(e),s=new Uint8Array(a);for(var l of n)s.set(l,t),t+=l.length;return s}function nf(){var e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){var t=255===e[0]&&128&e[1],r=0===e[0]&&!(128&e[1]);(t||r)&&this.warnings.push("Needlessly long format")}for(var n=new ArrayBuffer(this.valueHex.byteLength),i=new Uint8Array(n),o=0;o<this.valueHex.byteLength;o++)i[o]=0;i[0]=128&e[0];for(var a=ef(i,8),s=new ArrayBuffer(this.valueHex.byteLength),l=new Uint8Array(s),u=0;u<this.valueHex.byteLength;u++)l[u]=e[u];return l[0]&=127,ef(l,8)-a}function of(e,t){var r=e.toString(10);if(t<r.length)return"";for(var n=t-r.length,i=new Array(n),o=0;o<n;o++)i[o]="0";return i.join("").concat(r)}var af=["name","optional","primitiveSchema"],sf=["value"],lf=["isHexOnly"],uf=["value","isIndefiniteForm"],cf=["value"],df=["isConstructed"],hf=["idBlock","lenBlock"],vf=["unusedBits","isConstructed"],pf=["idBlock","lenBlock"],ff=["value"],gf=["valueDec","isFirstSid"],yf=["value"],mf=["valueDec"],wf=["value"],bf=["value","valueDate"],Sf=["value"],Ef=["value","local"];function kf(){if("undefined"==typeof BigInt)throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function xf(e){for(var t=0,r=0,n=0;n<e.length;n++){t+=e[n].byteLength}for(var i=new Uint8Array(t),o=0;o<e.length;o++){var a=e[o];i.set(new Uint8Array(a),r),r+=a.byteLength}return i.buffer}function Af(e,t,r,n){return t instanceof Uint8Array?t.byteLength?r<0?(e.error="Wrong parameter: inputOffset less than zero",!1):n<0?(e.error="Wrong parameter: inputLength less than zero",!1):!(t.byteLength-r-n<0)||(e.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):(e.error="Wrong parameter: inputBuffer has zero length",!1):(e.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}class Cf{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return xf(this.items)}}var If=[new Uint8Array([1])],Tf="0123456789",Pf="name",_f="valueHexView",Bf="",Nf=new ArrayBuffer(0),Df=new Uint8Array(0),Rf="EndOfContent",Of="OCTET STRING",Lf="BIT STRING";function Mf(e){var r;return r=class extends e{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(e){this.valueHexView=new Uint8Array(e)}constructor(){var e;super(...arguments);var t=(arguments.length<=0?void 0:arguments[0])||{};this.isHexOnly=null!==(e=t.isHexOnly)&&void 0!==e&&e,this.valueHexView=t.valueHex?Xp.BufferSourceConverter.toUint8Array(t.valueHex):Df}fromBER(e,t,r){var n=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!Af(this,n,t,r))return-1;var i=t+r;return this.valueHexView=n.subarray(t,i),this.valueHexView.length?(this.blockLength=r,i):(this.warnings.push("Zero buffer length"),t)}toBER(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this.isHexOnly?e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Nf)}toJSON(){return t(t({},super.toJSON()),{},{isHexOnly:this.isHexOnly,valueHex:Xp.Convert.ToHex(this.valueHexView)})}},r.NAME="hexBlock",r}class Uf{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor(){var{blockLength:e=0,error:t=Bf,warnings:r=[],valueBeforeDecode:n=Df}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=Xp.BufferSourceConverter.toUint8Array(n)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:Xp.Convert.ToHex(this.valueBeforeDecodeView)}}}Uf.NAME="baseBlock";class Ff extends Uf{fromBER(e,t,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}Ff.NAME="valueBlock";class zf extends(Mf(Uf)){constructor(){var e,t,r,n,{idBlock:i={}}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),i?(this.isHexOnly=null!==(e=i.isHexOnly)&&void 0!==e&&e,this.valueHexView=i.valueHex?Xp.BufferSourceConverter.toUint8Array(i.valueHex):Df,this.tagClass=null!==(t=i.tagClass)&&void 0!==t?t:-1,this.tagNumber=null!==(r=i.tagNumber)&&void 0!==r?r:-1,this.isConstructed=null!==(n=i.isConstructed)&&void 0!==n&&n):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",Nf}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){var r=new Uint8Array(1);if(!e){var n=this.tagNumber;t|=n&=31,r[0]=t}return r.buffer}if(!this.isHexOnly){var i=tf(this.tagNumber,7),o=new Uint8Array(i),a=i.byteLength,s=new Uint8Array(a+1);if(s[0]=31|t,!e){for(var l=0;l<a-1;l++)s[l+1]=128|o[l];s[a]=o[a-1]}return s.buffer}var u=new Uint8Array(this.valueHexView.byteLength+1);if(u[0]=31|t,!e){for(var c=this.valueHexView,d=0;d<c.length-1;d++)u[d+1]=128|c[d];u[this.valueHexView.byteLength]=c[c.length-1]}return u.buffer}fromBER(e,t,r){var n=Xp.BufferSourceConverter.toUint8Array(e);if(!Af(this,n,t,r))return-1;var i=n.subarray(t,t+r);if(0===i.length)return this.error="Zero buffer length",-1;switch(192&i[0]){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=!(32&~i[0]),this.isHexOnly=!1;var o=31&i[0];if(31!==o)this.tagNumber=o,this.blockLength=1;else{for(var a=1,s=this.valueHexView=new Uint8Array(255),l=255;128&i[a];){if(s[a-1]=127&i[a],++a>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(a===l){l+=255;for(var u=new Uint8Array(l),c=0;c<s.length;c++)u[c]=s[c];s=this.valueHexView=new Uint8Array(l)}}this.blockLength=a+1,s[a-1]=127&i[a];for(var d=new Uint8Array(a),h=0;h<a;h++)d[h]=s[h];(s=this.valueHexView=new Uint8Array(a)).set(d),this.blockLength<=9?this.tagNumber=ef(s,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(1===this.tagClass&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return t(t({},super.toJSON()),{},{tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed})}}zf.NAME="identificationBlock";class jf extends Uf{constructor(){var e,t,r,{lenBlock:n={}}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.isIndefiniteForm=null!==(e=n.isIndefiniteForm)&&void 0!==e&&e,this.longFormUsed=null!==(t=n.longFormUsed)&&void 0!==t&&t,this.length=null!==(r=n.length)&&void 0!==r?r:0}fromBER(e,t,r){var n=Xp.BufferSourceConverter.toUint8Array(e);if(!Af(this,n,t,r))return-1;var i=n.subarray(t,t+r);if(0===i.length)return this.error="Zero buffer length",-1;if(255===i[0])return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=128===i[0],this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(128&i[0]),!1===this.longFormUsed)return this.length=i[0],this.blockLength=1,t+this.blockLength;var o=127&i[0];if(o>8)return this.error="Too big integer",-1;if(o+1>i.length)return this.error="End of input reached before message was fully decoded",-1;var a=t+1,s=n.subarray(a,a+o);return 0===s[o-1]&&this.warnings.push("Needlessly long encoded length"),this.length=ef(s,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=o+1,t+this.blockLength}toBER(){var e,t,r=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return e=new ArrayBuffer(1),!1===r&&((t=new Uint8Array(e))[0]=128),e;if(this.longFormUsed){var n=tf(this.length,8);if(n.byteLength>127)return this.error="Too big length",Nf;if(e=new ArrayBuffer(n.byteLength+1),r)return e;var i=new Uint8Array(n);(t=new Uint8Array(e))[0]=128|n.byteLength;for(var o=0;o<n.byteLength;o++)t[o+1]=i[o];return e}return e=new ArrayBuffer(1),!1===r&&((t=new Uint8Array(e))[0]=this.length),e}toJSON(){return t(t({},super.toJSON()),{},{isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length})}}jf.NAME="lengthBlock";var Vf,qf,Hf,Kf,Wf,Gf={};class Qf extends Uf{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{name:t=Bf,optional:r=!1,primitiveSchema:n}=e,i=f(e,af),o=arguments.length>1?arguments[1]:void 0;super(i),this.name=t,this.optional=r,n&&(this.primitiveSchema=n),this.idBlock=new zf(i),this.lenBlock=new jf(i),this.valueBlock=o?new o(i):new Ff(i)}fromBER(e,t,r){var n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===n?(this.error=this.valueBlock.error,n):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),n)}toBER(e,t){var r=t||new Cf;t||Yf(this);var n=this.idBlock.toBER(e);if(r.write(n),this.lenBlock.isIndefiniteForm)r.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,r),r.write(new ArrayBuffer(2));else{var i=this.valueBlock.toBER(e);this.lenBlock.length=i.byteLength;var o=this.lenBlock.toBER(e);r.write(o),r.write(i)}return t?Nf:r.final()}toJSON(){var e=t(t({},super.toJSON()),{},{idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional});return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(){return"ascii"===(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"ascii")?this.onAsciiEncoding():Xp.Convert.ToHex(this.toBER())}onAsciiEncoding(){var e=this.constructor.NAME,t=Xp.Convert.ToHex(this.valueBlock.valueBeforeDecodeView);return"".concat(e," : ").concat(t)}isEqual(e){return this===e||e instanceof this.constructor&&function(e,t){if(e.byteLength!==t.byteLength)return!1;for(var r=new Uint8Array(e),n=new Uint8Array(t),i=0;i<r.length;i++)if(r[i]!==n[i])return!1;return!0}(this.toBER(),e.toBER())}}function Yf(e){var t;if(e instanceof Gf.Constructed)for(var r of e.valueBlock.value)Yf(r)&&(e.lenBlock.isIndefiniteForm=!0);return!!(null===(t=e.lenBlock)||void 0===t?void 0:t.isIndefiniteForm)}Qf.NAME="BaseBlock";class Jf extends Qf{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:t=Bf}=e;super(f(e,sf),arguments.length>1?arguments[1]:void 0),t&&this.fromString(t)}fromBER(e,t,r){var n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===n?(this.error=this.valueBlock.error,n):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),n)}onAsciiEncoding(){return"".concat(this.constructor.NAME," : '").concat(this.valueBlock.value,"'")}}Jf.NAME="BaseStringBlock";class Zf extends(Mf(Ff)){constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{isHexOnly:t=!0}=e;super(f(e,lf)),this.isHexOnly=t}}Zf.NAME="PrimitiveValueBlock";class $f extends Qf{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},Zf),this.idBlock.isConstructed=!1}}function Xf(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.length,n=t,i=new Qf({},Ff),o=new Uf;if(!Af(o,e,t,r))return i.error=o.error,{offset:-1,result:i};if(!e.subarray(t,t+r).length)return i.error="Zero buffer length",{offset:-1,result:i};var a=i.idBlock.fromBER(e,t,r);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),-1===a)return i.error=i.idBlock.error,{offset:-1,result:i};if(t=a,r-=i.idBlock.blockLength,a=i.lenBlock.fromBER(e,t,r),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),-1===a)return i.error=i.lenBlock.error,{offset:-1,result:i};if(t=a,r-=i.lenBlock.blockLength,!i.idBlock.isConstructed&&i.lenBlock.isIndefiniteForm)return i.error="Indefinite length form used for primitive encoding form",{offset:-1,result:i};var s=Qf;if(1===i.idBlock.tagClass){if(i.idBlock.tagNumber>=37&&!1===i.idBlock.isHexOnly)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};s=Gf.EndOfContent;break;case 1:s=Gf.Boolean;break;case 2:s=Gf.Integer;break;case 3:s=Gf.BitString;break;case 4:s=Gf.OctetString;break;case 5:s=Gf.Null;break;case 6:s=Gf.ObjectIdentifier;break;case 10:s=Gf.Enumerated;break;case 12:s=Gf.Utf8String;break;case 13:s=Gf.RelativeObjectIdentifier;break;case 14:s=Gf.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:s=Gf.Sequence;break;case 17:s=Gf.Set;break;case 18:s=Gf.NumericString;break;case 19:s=Gf.PrintableString;break;case 20:s=Gf.TeletexString;break;case 21:s=Gf.VideotexString;break;case 22:s=Gf.IA5String;break;case 23:s=Gf.UTCTime;break;case 24:s=Gf.GeneralizedTime;break;case 25:s=Gf.GraphicString;break;case 26:s=Gf.VisibleString;break;case 27:s=Gf.GeneralString;break;case 28:s=Gf.UniversalString;break;case 29:s=Gf.CharacterString;break;case 30:s=Gf.BmpString;break;case 31:s=Gf.DATE;break;case 32:s=Gf.TimeOfDay;break;case 33:s=Gf.DateTime;break;case 34:s=Gf.Duration;break;default:var l=i.idBlock.isConstructed?new Gf.Constructed:new Gf.Primitive;l.idBlock=i.idBlock,l.lenBlock=i.lenBlock,l.warnings=i.warnings,i=l}}else s=i.idBlock.isConstructed?Gf.Constructed:Gf.Primitive;return i=function(e,t){if(e instanceof t)return e;var r=new t;return r.idBlock=e.idBlock,r.lenBlock=e.lenBlock,r.warnings=e.warnings,r.valueBeforeDecodeView=e.valueBeforeDecodeView,r}(i,s),a=i.fromBER(e,t,i.lenBlock.isIndefiniteForm?r:i.lenBlock.length),i.valueBeforeDecodeView=e.subarray(n,n+i.blockLength),{offset:a,result:i}}function eg(e){if(!e.byteLength){var t=new Qf({},Ff);return t.error="Input buffer has zero length",{offset:-1,result:t}}return Xf(Xp.BufferSourceConverter.toUint8Array(e).slice(),0,e.byteLength)}function tg(e,t){return e?1:t}Vf=$f,Gf.Primitive=Vf,$f.NAME="PRIMITIVE";class rg extends Ff{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:t=[],isIndefiniteForm:r=!1}=e;super(f(e,uf)),this.value=t,this.isIndefiniteForm=r}fromBER(e,t,r){var n=Xp.BufferSourceConverter.toUint8Array(e);if(!Af(this,n,t,r))return-1;if(this.valueBeforeDecodeView=n.subarray(t,t+r),0===this.valueBeforeDecodeView.length)return this.warnings.push("Zero buffer length"),t;for(var i=t;tg(this.isIndefiniteForm,r)>0;){var o=Xf(n,i,r);if(-1===o.offset)return this.error=o.result.error,this.warnings.concat(o.result.warnings),-1;if(i=o.offset,this.blockLength+=o.result.blockLength,r-=o.result.blockLength,this.value.push(o.result),this.isIndefiniteForm&&o.result.constructor.NAME===Rf)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Rf?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){for(var r=t||new Cf,n=0;n<this.value.length;n++)this.value[n].toBER(e,r);return t?Nf:r.final()}toJSON(){var e=t(t({},super.toJSON()),{},{isIndefiniteForm:this.isIndefiniteForm,value:[]});for(var r of this.value)e.value.push(r.toJSON());return e}}rg.NAME="ConstructedValueBlock";class ng extends Qf{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},rg),this.idBlock.isConstructed=!0}fromBER(e,t,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;var n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===n?(this.error=this.valueBlock.error,n):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),n)}onAsciiEncoding(){var e=[];for(var t of this.valueBlock.value)e.push(t.toString("ascii").split("\n").map((e=>" ".concat(e))).join("\n"));var r=3===this.idBlock.tagClass?"[".concat(this.idBlock.tagNumber,"]"):this.constructor.NAME;return e.length?"".concat(r," :\n").concat(e.join("\n")):"".concat(r," :")}}qf=ng,Gf.Constructed=qf,ng.NAME="CONSTRUCTED";class ig extends Ff{fromBER(e,t,r){return t}toBER(e){return Nf}}ig.override="EndOfContentValueBlock";class og extends Qf{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},ig),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}Hf=og,Gf.EndOfContent=Hf,og.NAME=Rf;class ag extends Qf{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},Ff),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,r){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=r,t+r>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+r}toBER(e,t){var r=new ArrayBuffer(2);if(!e){var n=new Uint8Array(r);n[0]=5,n[1]=0}return t&&t.write(r),r}onAsciiEncoding(){return"".concat(this.constructor.NAME)}}Kf=ag,Gf.Null=Kf,ag.NAME="NULL";class sg extends(Mf(Ff)){get value(){for(var e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:t}=e,r=f(e,cf);super(r),r.valueHex?this.valueHexView=Xp.BufferSourceConverter.toUint8Array(r.valueHex):this.valueHexView=new Uint8Array(1),t&&(this.value=t)}fromBER(e,t,r){var n=Xp.BufferSourceConverter.toUint8Array(e);return Af(this,n,t,r)?(this.valueHexView=n.subarray(t,t+r),r>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,nf.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return t(t({},super.toJSON()),{},{value:this.value})}}sg.NAME="BooleanValueBlock";let lg=class extends Qf{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},sg),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.getValue)}};Wf=lg,Gf.Boolean=Wf,lg.NAME="BOOLEAN";class ug extends(Mf(rg)){constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{isConstructed:t=!1}=e;super(f(e,df)),this.isConstructed=t}fromBER(e,t,r){var n=0;if(this.isConstructed){if(this.isHexOnly=!1,-1===(n=rg.prototype.fromBER.call(this,e,t,r)))return n;for(var i=0;i<this.value.length;i++){var o=this.value[i].constructor.NAME;if(o===Rf){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(o!==Of)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,n=super.fromBER(e,t,r),this.blockLength=r;return n}toBER(e,t){return this.isConstructed?rg.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return t(t({},super.toJSON()),{},{isConstructed:this.isConstructed})}}var cg;ug.NAME="OctetStringValueBlock";let dg=class extends Qf{constructor(){var e,r,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{idBlock:i={},lenBlock:o={}}=n,a=f(n,hf);null!==(e=a.isConstructed)&&void 0!==e||(a.isConstructed=!!(null===(r=a.value)||void 0===r?void 0:r.length)),super(t({idBlock:t({isConstructed:a.isConstructed},i),lenBlock:t(t({},o),{},{isIndefiniteForm:!!a.isIndefiniteForm})},a),ug),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,r){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,0===r)return 0===this.idBlock.error.length&&(this.blockLength+=this.idBlock.blockLength),0===this.lenBlock.error.length&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){var n=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+r);try{if(n.byteLength){var i=Xf(n,0,n.byteLength);-1!==i.offset&&i.offset===r&&(this.valueBlock.value=[i.result])}}catch(e){}}return super.fromBER(e,t,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return ng.prototype.onAsciiEncoding.call(this);var e=this.constructor.NAME,t=Xp.Convert.ToHex(this.valueBlock.valueHexView);return"".concat(e," : ").concat(t)}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;var e=[];for(var t of this.valueBlock.value)t instanceof cg&&e.push(t.valueBlock.valueHexView);return Xp.BufferSourceConverter.concat(e)}};cg=dg,Gf.OctetString=cg,dg.NAME=Of;class hg extends(Mf(rg)){constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{unusedBits:t=0,isConstructed:r=!1}=e;super(f(e,vf)),this.unusedBits=t,this.isConstructed=r,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,r){if(!r)return t;var n=-1;if(this.isConstructed){if(-1===(n=rg.prototype.fromBER.call(this,e,t,r)))return n;for(var i of this.value){var o=i.constructor.NAME;if(o===Rf){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(o!==Lf)return this.error="BIT STRING may consists of BIT STRINGs only",-1;var a=i.valueBlock;if(this.unusedBits>0&&a.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=a.unusedBits}return n}var s=Xp.BufferSourceConverter.toUint8Array(e);if(!Af(this,s,t,r))return-1;var l=s.subarray(t,t+r);if(this.unusedBits=l[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){var u=l.subarray(1);try{if(u.byteLength){var c=Xf(u,0,u.byteLength);-1!==c.offset&&c.offset===r-1&&(this.value=[c.result])}}catch(e){}}return this.valueHexView=l.subarray(1),this.blockLength=l.length,t+r}toBER(e,t){if(this.isConstructed)return rg.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Nf;var r=new Uint8Array(this.valueHexView.length+1);return r[0]=this.unusedBits,r.set(this.valueHexView,1),r.buffer}toJSON(){return t(t({},super.toJSON()),{},{unusedBits:this.unusedBits,isConstructed:this.isConstructed})}}var vg;hg.NAME="BitStringValueBlock";let pg=class extends Qf{constructor(){var e,r,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{idBlock:i={},lenBlock:o={}}=n,a=f(n,pf);null!==(e=a.isConstructed)&&void 0!==e||(a.isConstructed=!!(null===(r=a.value)||void 0===r?void 0:r.length)),super(t({idBlock:t({isConstructed:a.isConstructed},i),lenBlock:t(t({},o),{},{isIndefiniteForm:!!a.isIndefiniteForm})},a),hg),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,r){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return ng.prototype.onAsciiEncoding.call(this);var e=[],t=this.valueBlock.valueHexView;for(var r of t)e.push(r.toString(2).padStart(8,"0"));var n=e.join(""),i=this.constructor.NAME,o=n.substring(0,n.length-this.valueBlock.unusedBits);return"".concat(i," : ").concat(o)}};var fg,gg,yg,mg,wg,bg,Sg;function Eg(e,t){for(var r=new Uint8Array([0]),n=new Uint8Array(e),i=new Uint8Array(t),o=n.slice(0),a=o.length-1,s=i.slice(0),l=s.length-1,u=0,c=0,d=l<a?a:l;d>=0;d--,c++){if(!0==c<s.length)u=o[a-c]+s[l-c]+r[0];else u=o[a-c]+r[0];if(r[0]=u/10,!0==c>=o.length)o=rf(new Uint8Array([u%10]),o);else o[a-c]=u%10}return r[0]>0&&(o=rf(r,o)),o}function kg(e){if(e>=If.length)for(var t=If.length;t<=e;t++){for(var r=new Uint8Array([0]),n=If[t-1].slice(0),i=n.length-1;i>=0;i--){var o=new Uint8Array([(n[i]<<1)+r[0]]);r[0]=o[0]/10,n[i]=o[0]%10}r[0]>0&&(n=rf(r,n)),If.push(n)}return If[e]}function xg(e,t){for(var r,n=0,i=new Uint8Array(e),o=new Uint8Array(t),a=i.slice(0),s=a.length-1,l=o.slice(0),u=l.length-1,c=0,d=u;d>=0;d--,c++)if(!0==(r=a[s-c]-l[u-c]-n)<0)n=1,a[s-c]=r+10;else n=0,a[s-c]=r;if(n>0)for(var h=s-u+1;h>=0;h--,c++){if(!((r=a[s-c]-n)<0)){n=0,a[s-c]=r;break}n=1,a[s-c]=r+10}return a.slice()}vg=pg,Gf.BitString=vg,pg.NAME=Lf;class Ag extends(Mf(Ff)){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=nf.call(this)))}constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:t}=e,r=f(e,ff);super(r),this._valueDec=0,r.valueHex&&this.setValueHex(),void 0!==t&&(this.valueDec=t)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(function(e){for(var t=e<0?-1*e:e,r=128,n=1;n<8;n++){if(t<=r){if(e<0){var i=tf(r-t,8,n);return new Uint8Array(i)[0]|=128,i}var o=tf(t,8,n),a=new Uint8Array(o);if(128&a[0]){var s=o.slice(0),l=new Uint8Array(s);o=new ArrayBuffer(o.byteLength+1),a=new Uint8Array(o);for(var u=0;u<s.byteLength;u++)a[u+1]=l[u];a[0]=0}return o}r*=Math.pow(2,8)}return new ArrayBuffer(0)}(e))}get valueDec(){return this._valueDec}fromDER(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=this.fromBER(e,t,r);if(-1===i)return i;var o=this.valueHexView;return 0===o[0]&&128&o[1]?this.valueHexView=o.subarray(1):0!==n&&o.length<n&&(n-o.length>1&&(n=o.length+1),this.valueHexView=o.subarray(n-o.length)),i}toDER(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.valueHexView;switch(!0){case!!(128&t[0]):var r=new Uint8Array(this.valueHexView.length+1);r[0]=0,r.set(t,1),this.valueHexView=r;break;case 0===t[0]&&!(128&t[1]):this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,r){var n=super.fromBER(e,t,r);return-1===n||this.setValueHex(),n}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return t(t({},super.toJSON()),{},{valueDec:this.valueDec})}toString(){for(var e,t=8*this.valueHexView.length-1,r=new Uint8Array(8*this.valueHexView.length/3),n=0,i=this.valueHexView,o="",a=!1,s=i.byteLength-1;s>=0;s--){e=i[s];for(var l=0;l<8;l++){if(!(1&~e))if(n===t)r=xg(kg(n),r),o="-";else r=Eg(r,kg(n));n++,e>>=1}}for(var u=0;u<r.length;u++)r[u]&&(a=!0),a&&(o+=Tf.charAt(r[u]));return!1===a&&(o+=Tf.charAt(0)),o}}fg=Ag,Ag.NAME="IntegerValueBlock",Object.defineProperty(fg.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class Cg extends Qf{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},Ag),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return kf(),BigInt(this.valueBlock.toString())}static fromBigInt(e){kf();var t=BigInt(e),r=new Cf,n=t.toString(16).replace(/^-/,""),i=new Uint8Array(Xp.Convert.FromHex(n));if(t<0){var o=new Uint8Array(i.length+(128&i[0]?1:0));o[0]|=128;var a=BigInt("0x".concat(Xp.Convert.ToHex(o)))+t,s=Xp.BufferSourceConverter.toUint8Array(Xp.Convert.FromHex(a.toString(16)));s[0]|=128,r.write(s)}else 128&i[0]&&r.write(new Uint8Array([0])),r.write(i);return new gg({valueHex:r.final()})}convertToDER(){var e=new gg({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new gg({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.valueBlock.toString())}}gg=Cg,Gf.Integer=gg,Cg.NAME="INTEGER";class Ig extends Cg{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}yg=Ig,Gf.Enumerated=yg,Ig.NAME="ENUMERATED";class Tg extends(Mf(Ff)){constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{valueDec:t=-1,isFirstSid:r=!1}=e;super(f(e,gf)),this.valueDec=t,this.isFirstSid=r}fromBER(e,t,r){if(!r)return t;var n=Xp.BufferSourceConverter.toUint8Array(e);if(!Af(this,n,t,r))return-1;var i=n.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(var o=0;o<r&&(this.valueHexView[o]=127&i[o],this.blockLength++,128&i[o]);o++);for(var a=new Uint8Array(this.blockLength),s=0;s<this.blockLength;s++)a[s]=this.valueHexView[s];return this.valueHexView=a,128&i[this.blockLength-1]?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=ef(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){kf();for(var t=BigInt(e).toString(2);t.length%7;)t="0"+t;for(var r=new Uint8Array(t.length/7),n=0;n<r.length;n++)r[n]=parseInt(t.slice(7*n,7*n+7),2)+(n+1<r.length?128:0);this.fromBER(r.buffer,0,r.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);for(var t=this.valueHexView,r=new Uint8Array(this.blockLength),n=0;n<this.blockLength-1;n++)r[n]=128|t[n];return r[this.blockLength-1]=t[this.blockLength-1],r.buffer}var i=tf(this.valueDec,7);if(0===i.byteLength)return this.error="Error during encoding SID value",Nf;var o=new Uint8Array(i.byteLength);if(!e){for(var a=new Uint8Array(i),s=i.byteLength-1,l=0;l<s;l++)o[l]=128|a[l];o[s]=a[s]}return o}toString(){var e="";if(this.isHexOnly)e=Xp.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){var t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return t(t({},super.toJSON()),{},{valueDec:this.valueDec,isFirstSid:this.isFirstSid})}}Tg.NAME="sidBlock";class Pg extends Ff{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:t=Bf}=e;super(f(e,yf)),this.value=[],t&&this.fromString(t)}fromBER(e,t,r){for(var n=t;r>0;){var i=new Tg;if(-1===(n=i.fromBER(e,n,r)))return this.blockLength=0,this.error=i.error,n;0===this.value.length&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,r-=i.blockLength,this.value.push(i)}return n}toBER(e){for(var t=[],r=0;r<this.value.length;r++){var n=this.value[r].toBER(e);if(0===n.byteLength)return this.error=this.value[r].error,Nf;t.push(n)}return xf(t)}fromString(e){this.value=[];var t=0,r=0,n="",i=!1;do{if(n=-1===(r=e.indexOf(".",t))?e.substring(t):e.substring(t,r),t=r+1,i){var o=this.value[0],a=0;switch(o.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:return void(this.value=[])}var s=parseInt(n,10);if(isNaN(s))return;o.valueDec=s+a,i=!1}else{var l=new Tg;if(n>Number.MAX_SAFE_INTEGER){kf();var u=BigInt(n);l.valueBigInt=u}else if(l.valueDec=parseInt(n,10),isNaN(l.valueDec))return;this.value.length||(l.isFirstSid=!0,i=!0),this.value.push(l)}}while(-1!==r)}toString(){for(var e="",t=!1,r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;var n=this.value[r].toString();0!==r&&(e="".concat(e,".")),t?(n="{".concat(n,"}"),this.value[r].isFirstSid?e="2.{".concat(n," - 80}"):e+=n):e+=n}return e}toJSON(){for(var e=t(t({},super.toJSON()),{},{value:this.toString(),sidArray:[]}),r=0;r<this.value.length;r++)e.sidArray.push(this.value[r].toJSON());return e}}Pg.NAME="ObjectIdentifierValueBlock";class _g extends Qf{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},Pg),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.valueBlock.toString()||"empty")}toJSON(){return t(t({},super.toJSON()),{},{value:this.getValue()})}}mg=_g,Gf.ObjectIdentifier=mg,_g.NAME="OBJECT IDENTIFIER";class Bg extends(Mf(Uf)){constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{valueDec:t=0}=e;super(f(e,mf)),this.valueDec=t}fromBER(e,t,r){if(0===r)return t;var n=Xp.BufferSourceConverter.toUint8Array(e);if(!Af(this,n,t,r))return-1;var i=n.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(var o=0;o<r&&(this.valueHexView[o]=127&i[o],this.blockLength++,128&i[o]);o++);for(var a=new Uint8Array(this.blockLength),s=0;s<this.blockLength;s++)a[s]=this.valueHexView[s];return this.valueHexView=a,128&i[this.blockLength-1]?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=ef(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);for(var t=this.valueHexView,r=new Uint8Array(this.blockLength),n=0;n<this.blockLength-1;n++)r[n]=128|t[n];return r[this.blockLength-1]=t[this.blockLength-1],r.buffer}var i=tf(this.valueDec,7);if(0===i.byteLength)return this.error="Error during encoding SID value",Nf;var o=new Uint8Array(i.byteLength);if(!e){for(var a=new Uint8Array(i),s=i.byteLength-1,l=0;l<s;l++)o[l]=128|a[l];o[s]=a[s]}return o.buffer}toString(){return this.isHexOnly?Xp.Convert.ToHex(this.valueHexView):this.valueDec.toString()}toJSON(){return t(t({},super.toJSON()),{},{valueDec:this.valueDec})}}Bg.NAME="relativeSidBlock";class Ng extends Ff{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:t=Bf}=e;super(f(e,wf)),this.value=[],t&&this.fromString(t)}fromBER(e,t,r){for(var n=t;r>0;){var i=new Bg;if(-1===(n=i.fromBER(e,n,r)))return this.blockLength=0,this.error=i.error,n;this.blockLength+=i.blockLength,r-=i.blockLength,this.value.push(i)}return n}toBER(e,t){for(var r=[],n=0;n<this.value.length;n++){var i=this.value[n].toBER(e);if(0===i.byteLength)return this.error=this.value[n].error,Nf;r.push(i)}return xf(r)}fromString(e){this.value=[];var t=0,r=0,n="";do{n=-1===(r=e.indexOf(".",t))?e.substring(t):e.substring(t,r),t=r+1;var i=new Bg;if(i.valueDec=parseInt(n,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(-1!==r);return!0}toString(){for(var e="",t=!1,r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;var n=this.value[r].toString();0!==r&&(e="".concat(e,".")),e+=t?n="{".concat(n,"}"):n}return e}toJSON(){for(var e=t(t({},super.toJSON()),{},{value:this.toString(),sidArray:[]}),r=0;r<this.value.length;r++)e.sidArray.push(this.value[r].toJSON());return e}}Ng.NAME="RelativeObjectIdentifierValueBlock";class Dg extends Qf{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},Ng),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.valueBlock.toString()||"empty")}toJSON(){return t(t({},super.toJSON()),{},{value:this.getValue()})}}wg=Dg,Gf.RelativeObjectIdentifier=wg,Dg.NAME="RelativeObjectIdentifier";class Rg extends ng{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}bg=Rg,Gf.Sequence=bg,Rg.NAME="SEQUENCE";let Og=class extends ng{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Sg=Og,Gf.Set=Sg,Og.NAME="SET";class Lg extends(Mf(Ff)){constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(g({},(y(e),e))),this.isHexOnly=!0,this.value=Bf}toJSON(){return t(t({},super.toJSON()),{},{value:this.value})}}Lg.NAME="StringValueBlock";class Mg extends Lg{}Mg.NAME="SimpleStringValueBlock";class Ug extends Jf{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(g({},(y(e),e)),Mg)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,Xp.BufferSourceConverter.toUint8Array(e))}fromString(e){for(var t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(t),n=0;n<t;n++)r[n]=e.charCodeAt(n);this.valueBlock.value=e}}Ug.NAME="SIMPLE STRING";class Fg extends Ug{fromBuffer(e){this.valueBlock.valueHexView=Xp.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=Xp.Convert.ToUtf8String(e)}catch(t){this.warnings.push('Error during "decodeURIComponent": '.concat(t,", using raw string")),this.valueBlock.value=Xp.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(Xp.Convert.FromUtf8String(e)),this.valueBlock.value=e}}var zg,jg,Vg,qg,Hg,Kg,Wg,Gg,Qg,Yg,Jg,Zg,$g,Xg,ey,ty,ry,ny,iy;Fg.NAME="Utf8StringValueBlock";class oy extends Fg{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}zg=oy,Gf.Utf8String=zg,oy.NAME="UTF8String";class ay extends Ug{fromBuffer(e){this.valueBlock.value=Xp.Convert.ToUtf16String(e),this.valueBlock.valueHexView=Xp.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(Xp.Convert.FromUtf16String(e))}}ay.NAME="BmpStringValueBlock";class sy extends ay{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(g({},(y(e),e))),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}jg=sy,Gf.BmpString=jg,sy.NAME="BMPString";class ly extends Ug{fromBuffer(e){for(var t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),r=new Uint8Array(t),n=0;n<r.length;n+=4)r[n]=r[n+3],r[n+1]=r[n+2],r[n+2]=0,r[n+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){for(var t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(4*t),n=0;n<t;n++){var i=tf(e.charCodeAt(n),8),o=new Uint8Array(i);if(!(o.length>4))for(var a=4-o.length,s=o.length-1;s>=0;s--)r[4*n+s+a]=o[s]}this.valueBlock.value=e}}ly.NAME="UniversalStringValueBlock";class uy extends ly{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(g({},(y(e),e))),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}Vg=uy,Gf.UniversalString=Vg,uy.NAME="UniversalString";class cy extends Ug{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}qg=cy,Gf.NumericString=qg,cy.NAME="NumericString";class dy extends Ug{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}Hg=dy,Gf.PrintableString=Hg,dy.NAME="PrintableString";class hy extends Ug{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}Kg=hy,Gf.TeletexString=Kg,hy.NAME="TeletexString";class vy extends Ug{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}Wg=vy,Gf.VideotexString=Wg,vy.NAME="VideotexString";class py extends Ug{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}Gg=py,Gf.IA5String=Gg,py.NAME="IA5String";class fy extends Ug{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}Qg=fy,Gf.GraphicString=Qg,fy.NAME="GraphicString";class gy extends Ug{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}Yg=gy,Gf.VisibleString=Yg,gy.NAME="VisibleString";class yy extends Ug{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}Jg=yy,Gf.GeneralString=Jg,yy.NAME="GeneralString";class my extends Ug{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}Zg=my,Gf.CharacterString=Zg,my.NAME="CharacterString";class wy extends gy{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:t,valueDate:r}=e;if(super(f(e,bf)),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,t){this.fromString(t),this.valueBlock.valueHexView=new Uint8Array(t.length);for(var n=0;n<t.length;n++)this.valueBlock.valueHexView[n]=t.charCodeAt(n)}r&&(this.fromDate(r),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,Xp.BufferSourceConverter.toUint8Array(e)))}toBuffer(){for(var e=this.toString(),t=new ArrayBuffer(e.length),r=new Uint8Array(t),n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){var t=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/gi.exec(e);if(null!==t){var r=parseInt(t[1],10);this.year=r>=50?1900+r:2e3+r,this.month=parseInt(t[2],10),this.day=parseInt(t[3],10),this.hour=parseInt(t[4],10),this.minute=parseInt(t[5],10),this.second=parseInt(t[6],10)}else this.error="Wrong input string for conversion"}toString(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"iso";if("iso"===e){var t=new Array(7);return t[0]=of(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=of(this.month,2),t[2]=of(this.day,2),t[3]=of(this.hour,2),t[4]=of(this.minute,2),t[5]=of(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.toDate().toISOString())}toJSON(){return t(t({},super.toJSON()),{},{year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second})}}$g=wy,Gf.UTCTime=$g,wy.NAME="UTCTime";class by extends wy{constructor(){var e;super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),null!==(e=this.millisecond)&&void 0!==e||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){var e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){var t,r=!1,n="",i="",o=0,a=0,s=0;if("Z"===e[e.length-1])n=e.substring(0,e.length-1),r=!0;else{var l=new Number(e[e.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(r){if(-1!==n.indexOf("+"))throw new Error("Wrong input string for conversion");if(-1!==n.indexOf("-"))throw new Error("Wrong input string for conversion")}else{var u=1,c=n.indexOf("+"),d="";if(-1===c&&(c=n.indexOf("-"),u=-1),-1!==c){if(d=n.substring(c+1),n=n.substring(0,c),2!==d.length&&4!==d.length)throw new Error("Wrong input string for conversion");var h=parseInt(d.substring(0,2),10);if(isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");if(a=u*h,4===d.length){if(h=parseInt(d.substring(2,4),10),isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");s=u*h}}}var v=n.indexOf(".");if(-1===v&&(v=n.indexOf(",")),-1!==v){var p=new Number("0".concat(n.substring(v)));if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");o=p.valueOf(),i=n.substring(0,v)}else i=n;switch(!0){case 8===i.length:if(t=/(\d{4})(\d{2})(\d{2})/gi,-1!==v)throw new Error("Wrong input string for conversion");break;case 10===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})/gi,-1!==v){var f=60*o;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case 12===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==v){var g=60*o;this.second=Math.floor(g),g=1e3*(g-this.second),this.millisecond=Math.floor(g)}break;case 14===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==v){var y=1e3*o;this.millisecond=Math.floor(y)}break;default:throw new Error("Wrong input string for conversion")}var m=t.exec(i);if(null===m)throw new Error("Wrong input string for conversion");for(var w=1;w<m.length;w++)switch(w){case 1:this.year=parseInt(m[w],10);break;case 2:this.month=parseInt(m[w],10);break;case 3:this.day=parseInt(m[w],10);break;case 4:this.hour=parseInt(m[w],10)+a;break;case 5:this.minute=parseInt(m[w],10)+s;break;case 6:this.second=parseInt(m[w],10);break;default:throw new Error("Wrong input string for conversion")}if(!1===r){var b=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=b.getUTCFullYear(),this.month=b.getUTCMonth(),this.day=b.getUTCDay(),this.hour=b.getUTCHours(),this.minute=b.getUTCMinutes(),this.second=b.getUTCSeconds(),this.millisecond=b.getUTCMilliseconds()}}toString(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"iso";if("iso"===e){var t=[];return t.push(of(this.year,4)),t.push(of(this.month,2)),t.push(of(this.day,2)),t.push(of(this.hour,2)),t.push(of(this.minute,2)),t.push(of(this.second,2)),0!==this.millisecond&&(t.push("."),t.push(of(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return t(t({},super.toJSON()),{},{millisecond:this.millisecond})}}Xg=by,Gf.GeneralizedTime=Xg,by.NAME="GeneralizedTime";class Sy extends oy{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}ey=Sy,Gf.DATE=ey,Sy.NAME="DATE";class Ey extends oy{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}ty=Ey,Gf.TimeOfDay=ty,Ey.NAME="TimeOfDay";class ky extends oy{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}ry=ky,Gf.DateTime=ry,ky.NAME="DateTime";class xy extends oy{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}ny=xy,Gf.Duration=ny,xy.NAME="Duration";class Ay extends oy{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}iy=Ay,Gf.TIME=iy,Ay.NAME="TIME";class Cy{constructor(){var{name:e=Bf,optional:t=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.name=e,this.optional=t}}class Iy extends Cy{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:t=[]}=e;super(f(e,Sf)),this.value=t}}class Ty extends Cy{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:t=new Cy,local:r=!1}=e;super(f(e,Ef)),this.value=t,this.local=r}}function Py(e,t,r){if(r instanceof Iy){for(var n of r.value){if(Py(e,t,n).verified)return{verified:!0,result:e}}var i={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(Pf)&&(i.name=r.name),i}if(r instanceof Cy)return r.hasOwnProperty(Pf)&&(e[r.name]=t),{verified:!0,result:e};if(e instanceof Object==!1)return{verified:!1,result:{error:"Wrong root object"}};if(t instanceof Object==!1)return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(r instanceof Object==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if("idBlock"in r==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if("fromBER"in r.idBlock==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if("toBER"in r.idBlock==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};var o=r.idBlock.toBER(!1);if(0===o.byteLength)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(-1===r.idBlock.fromBER(o,0,o.byteLength))return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(!1===r.idBlock.hasOwnProperty("tagClass"))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagClass!==t.idBlock.tagClass)return{verified:!1,result:e};if(!1===r.idBlock.hasOwnProperty("tagNumber"))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagNumber!==t.idBlock.tagNumber)return{verified:!1,result:e};if(!1===r.idBlock.hasOwnProperty("isConstructed"))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!("isHexOnly"in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isHexOnly!==t.idBlock.isHexOnly)return{verified:!1,result:e};if(r.idBlock.isHexOnly){if(_f in r.idBlock==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};var a=r.idBlock.valueHexView,s=t.idBlock.valueHexView;if(a.length!==s.length)return{verified:!1,result:e};for(var l=0;l<a.length;l++)if(a[l]!==s[1])return{verified:!1,result:e}}if(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Bf),r.name&&(e[r.name]=t)),r instanceof Gf.Constructed){var u=0,c={verified:!1,result:{error:"Unknown error"}},d=r.valueBlock.value.length;if(d>0&&r.valueBlock.value[0]instanceof Ty&&(d=t.valueBlock.value.length),0===d)return{verified:!0,result:e};if(0===t.valueBlock.value.length&&0!==r.valueBlock.value.length){for(var h=!0,v=0;v<r.valueBlock.value.length;v++)h=h&&(r.valueBlock.value[v].optional||!1);return h?{verified:!0,result:e}:(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Bf),r.name&&delete e[r.name]),e.error="Inconsistent object length",{verified:!1,result:e})}for(var p=0;p<d;p++)if(p-u>=t.valueBlock.value.length){if(!1===r.valueBlock.value[p].optional){var f={verified:!1,result:e};return e.error="Inconsistent length between ASN.1 data and schema",r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Bf),r.name&&(delete e[r.name],f.name=r.name)),f}}else if(r.valueBlock.value[0]instanceof Ty){if(!1===(c=Py(e,t.valueBlock.value[p],r.valueBlock.value[0].value)).verified){if(!r.valueBlock.value[0].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Bf),r.name&&delete e[r.name]),c;u++}if(Pf in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){var g={};void 0===(g="local"in r.valueBlock.value[0]&&r.valueBlock.value[0].local?t:e)[r.valueBlock.value[0].name]&&(g[r.valueBlock.value[0].name]=[]),g[r.valueBlock.value[0].name].push(t.valueBlock.value[p])}}else if(!1===(c=Py(e,t.valueBlock.value[p-u],r.valueBlock.value[p])).verified){if(!r.valueBlock.value[p].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Bf),r.name&&delete e[r.name]),c;u++}if(!1===c.verified){var y={verified:!1,result:e};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Bf),r.name&&(delete e[r.name],y.name=r.name)),y}return{verified:!0,result:e}}if(r.primitiveSchema&&_f in t.valueBlock){var m=Xf(t.valueBlock.valueHexView);if(-1===m.offset){var w={verified:!1,result:m.result};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Bf),r.name&&(delete e[r.name],w.name=r.name)),w}return Py(e,m.result,r.primitiveSchema)}return{verified:!0,result:e}}var _y,By,Ny=Object.freeze({__proto__:null,Any:Cy,BaseBlock:Qf,BaseStringBlock:Jf,BitString:pg,BmpString:sy,Boolean:lg,CharacterString:my,Choice:Iy,Constructed:ng,DATE:Sy,DateTime:ky,Duration:xy,EndOfContent:og,Enumerated:Ig,GeneralString:yy,GeneralizedTime:by,GraphicString:fy,HexBlock:Mf,IA5String:py,Integer:Cg,Null:ag,NumericString:cy,ObjectIdentifier:_g,OctetString:dg,Primitive:$f,PrintableString:dy,RawData:class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=Xp.BufferSourceConverter.toUint8Array(e)}constructor(){var{data:e=Df}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.dataView=Xp.BufferSourceConverter.toUint8Array(e)}fromBER(e,t,r){var n=t+r;return this.dataView=Xp.BufferSourceConverter.toUint8Array(e).subarray(t,n),n}toBER(e){return this.dataView.slice().buffer}},RelativeObjectIdentifier:Dg,Repeated:Ty,Sequence:Rg,Set:Og,TIME:Ay,TeletexString:hy,TimeOfDay:Ey,UTCTime:wy,UniversalString:uy,Utf8String:oy,ValueBlock:Ff,VideotexString:vy,ViewWriter:Cf,VisibleString:gy,compareSchema:Py,fromBER:eg,verifySchema:function(e,t){if(t instanceof Object==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};var r=Xf(Xp.BufferSourceConverter.toUint8Array(e));return-1===r.offset?{verified:!1,result:r.result}:Py(r.result,r.result,t)}});!function(e){e[e.Sequence=0]="Sequence",e[e.Set=1]="Set",e[e.Choice=2]="Choice"}(_y||(_y={})),function(e){e[e.Any=1]="Any",e[e.Boolean=2]="Boolean",e[e.OctetString=3]="OctetString",e[e.BitString=4]="BitString",e[e.Integer=5]="Integer",e[e.Enumerated=6]="Enumerated",e[e.ObjectIdentifier=7]="ObjectIdentifier",e[e.Utf8String=8]="Utf8String",e[e.BmpString=9]="BmpString",e[e.UniversalString=10]="UniversalString",e[e.NumericString=11]="NumericString",e[e.PrintableString=12]="PrintableString",e[e.TeletexString=13]="TeletexString",e[e.VideotexString=14]="VideotexString",e[e.IA5String=15]="IA5String",e[e.GraphicString=16]="GraphicString",e[e.VisibleString=17]="VisibleString",e[e.GeneralString=18]="GeneralString",e[e.CharacterString=19]="CharacterString",e[e.UTCTime=20]="UTCTime",e[e.GeneralizedTime=21]="GeneralizedTime",e[e.DATE=22]="DATE",e[e.TimeOfDay=23]="TimeOfDay",e[e.DateTime=24]="DateTime",e[e.Duration=25]="Duration",e[e.TIME=26]="TIME",e[e.Null=27]="Null"}(By||(By={}));class Dy{constructor(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(this.unusedBits=0,this.value=new ArrayBuffer(0),e)if("number"==typeof e)this.fromNumber(e);else{if(!Xp.BufferSourceConverter.isBufferSource(e))throw TypeError("Unsupported type of 'params' argument for BitString");this.unusedBits=t,this.value=Xp.BufferSourceConverter.toArrayBuffer(e)}}fromASN(e){if(!(e instanceof pg))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=e.valueBlock.valueHex,this}toASN(){return new pg({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new pg({name:e})}toNumber(){var e="",t=new Uint8Array(this.value);for(var r of t)e+=r.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){var t=e.toString(2),r=t.length+7>>3;this.unusedBits=(r<<3)-t.length;var n=new Uint8Array(r);t=t.padStart(r<<3,"0").split("").reverse().join("");for(var i=0;i<r;)n[i]=parseInt(t.slice(i<<3,8+(i<<3)),2),i++;this.value=n.buffer}}class Ry{get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){"number"==typeof e?this.buffer=new ArrayBuffer(e):Xp.BufferSourceConverter.isBufferSource(e)?this.buffer=Xp.BufferSourceConverter.toArrayBuffer(e):Array.isArray(e)?this.buffer=new Uint8Array(e):this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof dg))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=e.valueBlock.valueHex,this}toASN(){return new dg({valueHex:this.buffer})}toSchema(e){return new dg({name:e})}}var Oy={fromASN:e=>e instanceof ag?null:e.valueBeforeDecodeView,toASN:e=>{if(null===e)return new ag;var t=eg(e);if(t.result.error)throw new Error(t.result.error);return t.result}},Ly={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new Cg({value:+e})},My={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new Ig({value:e})},Uy={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new Cg({valueHex:e})},Fy={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new pg({valueHex:e})},zy={fromASN:e=>e.valueBlock.toString(),toASN:e=>new _g({value:e})},jy={fromASN:e=>e.valueBlock.value,toASN:e=>new lg({value:e})},Vy={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new dg({valueHex:e})},qy={fromASN:e=>new Ry(e.getValue()),toASN:e=>e.toASN()};function Hy(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}var Ky=Hy(oy),Wy=Hy(sy),Gy=Hy(uy),Qy=Hy(cy),Yy=Hy(dy),Jy=Hy(hy),Zy=Hy(vy),$y=Hy(py),Xy=Hy(fy),em=Hy(gy),tm=Hy(yy),rm=Hy(my),nm={fromASN:e=>e.toDate(),toASN:e=>new wy({valueDate:e})},im={fromASN:e=>e.toDate(),toASN:e=>new by({valueDate:e})},om={fromASN:()=>null,toASN:()=>new ag};function am(e){switch(e){case By.Any:return Oy;case By.BitString:return Fy;case By.BmpString:return Wy;case By.Boolean:return jy;case By.CharacterString:return rm;case By.Enumerated:return My;case By.GeneralString:return tm;case By.GeneralizedTime:return im;case By.GraphicString:return Xy;case By.IA5String:return $y;case By.Integer:return Ly;case By.Null:return om;case By.NumericString:return Qy;case By.ObjectIdentifier:return zy;case By.OctetString:return Vy;case By.PrintableString:return Yy;case By.TeletexString:return Jy;case By.UTCTime:return nm;case By.UniversalString:return Gy;case By.Utf8String:return Ky;case By.VideotexString:return Zy;case By.VisibleString:return em;default:return null}}function sm(e){return"function"==typeof e&&e.prototype?!(!e.prototype.toASN||!e.prototype.fromASN)||sm(e.prototype):!!(e&&"object"==typeof e&&"toASN"in e&&"fromASN"in e)}function lm(e){var t;if(e){var r=Object.getPrototypeOf(e);return(null===(t=null==r?void 0:r.prototype)||void 0===t?void 0:t.constructor)===Array||lm(r)}return!1}function um(e,t){if(!e||!t)return!1;if(e.byteLength!==t.byteLength)return!1;for(var r=new Uint8Array(e),n=new Uint8Array(t),i=0;i<e.byteLength;i++)if(r[i]!==n[i])return!1;return!0}var cm,dm,hm,vm=new class{constructor(){this.items=new WeakMap}has(e){return this.items.has(e)}get(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.items.get(e);if(!r)throw new Error("Cannot get schema for '".concat(e.prototype.constructor.name,"' target"));if(t&&!r.schema)throw new Error("Schema '".concat(e.prototype.constructor.name,"' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'."));return r}cache(e){var t=this.get(e);t.schema||(t.schema=this.create(e,!0))}createDefault(e){var t={type:_y.Sequence,items:{}},r=this.findParentSchema(e);return r&&(Object.assign(t,r),t.items=Object.assign({},t.items,r.items)),t}create(e,t){var r=this.items.get(e)||this.createDefault(e),n=[];for(var i in r.items){var o=r.items[i],a=t?i:"",s=void 0;if("number"==typeof o.type){var l=By[o.type],u=Ny[l];if(!u)throw new Error("Cannot get ASN1 class by name '".concat(l,"'"));s=new u({name:a})}else if(sm(o.type)){s=(new o.type).toSchema(a)}else if(o.optional){this.get(o.type).type===_y.Choice?s=new Cy({name:a}):(s=this.create(o.type,!1)).name=a}else s=new Cy({name:a});var c=!!o.optional||void 0!==o.defaultValue;if(o.repeated)s.name="",s=new("set"===o.repeated?Og:Rg)({name:"",value:[new Ty({name:a,value:s})]});if(null!==o.context&&void 0!==o.context)if(o.implicit)if("number"==typeof o.type||sm(o.type)){var d=o.repeated?ng:$f;n.push(new d({name:a,optional:c,idBlock:{tagClass:3,tagNumber:o.context}}))}else{this.cache(o.type);var h=!!o.repeated,v=h?s:this.get(o.type,!0).schema;v="valueBlock"in v?v.valueBlock.value:v.value,n.push(new ng({name:h?"":a,optional:c,idBlock:{tagClass:3,tagNumber:o.context},value:v}))}else n.push(new ng({optional:c,idBlock:{tagClass:3,tagNumber:o.context},value:[s]}));else s.optional=c,n.push(s)}switch(r.type){case _y.Sequence:return new Rg({value:n,name:""});case _y.Set:return new Og({value:n,name:""});case _y.Choice:return new Iy({value:n,name:""});default:throw new Error("Unsupported ASN1 type in use")}}set(e,t){return this.items.set(e,t),this}findParentSchema(e){var t=Object.getPrototypeOf(e);return t?this.items.get(t)||this.findParentSchema(t):null}},pm=e=>t=>{var r;vm.has(t)?r=vm.get(t):(r=vm.createDefault(t),vm.set(t,r)),Object.assign(r,e)},fm=e=>(t,r)=>{var n;vm.has(t.constructor)?n=vm.get(t.constructor):(n=vm.createDefault(t.constructor),vm.set(t.constructor,n));var i=Object.assign({},e);if("number"==typeof i.type&&!i.converter){var o=am(e.type);if(!o)throw new Error("Cannot get default converter for property '".concat(r,"' of ").concat(t.constructor.name));i.converter=o}n.items[r]=i};class gm extends Error{constructor(){super(...arguments),this.schemas=[]}}class ym{static parse(e,t){var r=eg(e);if(r.result.error)throw new Error(r.result.error);return this.fromASN(r.result,t)}static fromASN(e,t){var r,n=this;try{if(sm(t))return(new t).fromASN(e);var i=vm.get(t);vm.cache(t);var o=i.schema;if(e.constructor===ng&&i.type!==_y.Choice)for(var a in o=new ng({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:i.schema.valueBlock.value}),i.items)delete e[a];var s=Py({},e,o);if(!s.verified)throw new gm("Data does not match to ".concat(t.name," ASN1 schema. ").concat(s.result.error));var l=new t;if(lm(t)){if(!("value"in e.valueBlock)||!Array.isArray(e.valueBlock.value))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");var u=i.itemType;if("number"==typeof u){var c=am(u);if(!c)throw new Error("Cannot get default converter for array item of ".concat(t.name," ASN1 schema"));return t.from(e.valueBlock.value,(e=>c.fromASN(e)))}return t.from(e.valueBlock.value,(e=>this.fromASN(e,u)))}var d=function(){var e=s.result[h];if(!e)return 1;var t=i.items[h],o=t.type;if("number"==typeof o||sm(o)){var a=null!==(r=t.converter)&&void 0!==r?r:sm(o)?new o:null;if(!a)throw new Error("Converter is empty");if(t.repeated)if(t.implicit){var u=new("sequence"===t.repeated?Rg:Og);u.valueBlock=e.valueBlock;var c=eg(u.toBER(!1));if(-1===c.offset)throw new Error("Cannot parse the child item. ".concat(c.result.error));if(!("value"in c.result.valueBlock)||!Array.isArray(c.result.valueBlock.value))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");var d=c.result.valueBlock.value;l[h]=Array.from(d,(e=>a.fromASN(e)))}else l[h]=Array.from(e,(e=>a.fromASN(e)));else{var v=e;if(t.implicit){var p;if(sm(o))p=(new o).toSchema("");else{var f=By[o],g=Ny[f];if(!g)throw new Error("Cannot get '".concat(f,"' class from asn1js module"));p=new g}p.valueBlock=v.valueBlock,v=eg(p.toBER(!1)).result}l[h]=a.fromASN(v)}}else if(t.repeated){if(!Array.isArray(e))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");l[h]=Array.from(e,(e=>n.fromASN(e,o)))}else l[h]=n.fromASN(e,o)};for(var h in i.items)d();return l}catch(e){throw e instanceof gm&&e.schemas.push(t.name),e}}}class mm{static serialize(e){return e instanceof Qf?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&"object"==typeof e&&sm(e))return e.toASN();if(!e||"object"!=typeof e)throw new TypeError("Parameter 1 should be type of Object.");var r=e.constructor,n=vm.get(r);vm.cache(r);var i,o=[];if(n.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if("number"==typeof n.itemType){var a=am(n.itemType);if(!a)throw new Error("Cannot get default converter for array item of ".concat(r.name," ASN1 schema"));o=e.map((e=>a.toASN(e)))}else o=e.map((e=>this.toAsnItem({type:n.itemType},"[]",r,e)))}else for(var s in n.items){var l=n.items[s],u=e[s];if(!(void 0===u||l.defaultValue===u||"object"==typeof l.defaultValue&&"object"==typeof u&&um(this.serialize(l.defaultValue),this.serialize(u)))){var c=mm.toAsnItem(l,s,r,u);if("number"==typeof l.context)if(l.implicit)if(l.repeated||"number"!=typeof l.type&&!sm(l.type))o.push(new ng({optional:l.optional,idBlock:{tagClass:3,tagNumber:l.context},value:c.valueBlock.value}));else{var d={};d.valueHex=c instanceof ag?c.valueBeforeDecodeView:c.valueBlock.toBER(),o.push(new $f(t({optional:l.optional,idBlock:{tagClass:3,tagNumber:l.context}},d)))}else o.push(new ng({optional:l.optional,idBlock:{tagClass:3,tagNumber:l.context},value:[c]}));else l.repeated?o=o.concat(c):o.push(c)}}switch(n.type){case _y.Sequence:i=new Rg({value:o});break;case _y.Set:i=new Og({value:o});break;case _y.Choice:if(!o[0])throw new Error("Schema '".concat(r.name,"' has wrong data. Choice cannot be empty."));i=o[0]}return i}static toAsnItem(e,t,r,n){var i;if("number"==typeof e.type){var o=e.converter;if(!o)throw new Error("Property '".concat(t,"' doesn't have converter for type ").concat(By[e.type]," in schema '").concat(r.name,"'"));if(e.repeated){if(!Array.isArray(n))throw new TypeError("Parameter 'objProp' should be type of Array.");var a=Array.from(n,(e=>o.toASN(e)));i=new("sequence"===e.repeated?Rg:Og)({value:a})}else i=o.toASN(n)}else if(e.repeated){if(!Array.isArray(n))throw new TypeError("Parameter 'objProp' should be type of Array.");var s=Array.from(n,(e=>this.toASN(e)));i=new("sequence"===e.repeated?Rg:Og)({value:s})}else i=this.toASN(n);return i}}class wm extends Array{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];if("number"==typeof e)super(e);else for(var t of(super(),e))this.push(t)}}class bm{static serialize(e){return mm.serialize(e)}static parse(e,t){return ym.parse(e,t)}static toString(e){var t=eg(Xp.BufferSourceConverter.isBufferSource(e)?Xp.BufferSourceConverter.toArrayBuffer(e):bm.serialize(e));if(-1===t.offset)throw new Error("Cannot decode ASN.1 data. ".concat(t.result.error));return t.result.toString()}}class Sm{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){var t=e.split(".");if(4!==t.length)throw new Error("Invalid IPv4 address");return t.map((e=>{var t=parseInt(e,10);if(isNaN(t)||t<0||t>255)throw new Error("Invalid IPv4 address part");return t}))}static parseIPv6(e){var t=this.expandIPv6(e).split(":");if(8!==t.length)throw new Error("Invalid IPv6 address");return t.reduce(((e,t)=>{var r=parseInt(t,16);if(isNaN(r)||r<0||r>65535)throw new Error("Invalid IPv6 address part");return e.push(r>>8&255),e.push(255&r),e}),[])}static expandIPv6(e){if(!e.includes("::"))return e;var t=e.split("::");if(t.length>2)throw new Error("Invalid IPv6 address");var r=t[0]?t[0].split(":"):[],n=t[1]?t[1].split(":"):[],i=8-(r.length+n.length);if(i<0)throw new Error("Invalid IPv6 address");return[...r,...Array(i).fill("0"),...n].join(":")}static formatIPv6(e){for(var t=[],r=0;r<16;r+=2)t.push((e[r]<<8|e[r+1]).toString(16));return this.compressIPv6(t.join(":"))}static compressIPv6(e){for(var t=e.split(":"),r=-1,n=0,i=-1,o=0,a=0;a<t.length;a++)"0"===t[a]?(-1===i&&(i=a),o++):(o>n&&(r=i,n=o),i=-1,o=0);if(o>n&&(r=i,n=o),n>1){var s=t.slice(0,r).join(":"),l=t.slice(r+n).join(":");return"".concat(s,"::").concat(l)}return e}static parseCIDR(e){var[t,r]=e.split("/"),n=parseInt(r,10);if(this.isIPv4(t)){if(n<0||n>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(t),n]}if(n<0||n>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(t),n]}static decodeIP(e){if(64===e.length&&0===parseInt(e,16))return"::/0";if(16!==e.length)return e;var t=parseInt(e.slice(8),16).toString(2).split("").reduce(((e,t)=>e+ +t),0),r=e.slice(0,8).replace(/(.{2})/g,(e=>"".concat(parseInt(e,16),".")));return r=r.slice(0,-1),"".concat(r,"/").concat(t)}static toString(e){var t=new Uint8Array(e);if(4===t.length)return Array.from(t).join(".");if(16===t.length)return this.formatIPv6(t);if(8===t.length||32===t.length){var r=t.length/2,n=t.slice(0,r),i=t.slice(r);if(t.every((e=>0===e)))return 8===t.length?"0.0.0.0/0":"::/0";var o=i.reduce(((e,t)=>e+(t.toString(2).match(/1/g)||[]).length),0);if(8===t.length){var a=Array.from(n).join(".");return"".concat(a,"/").concat(o)}var s=this.formatIPv6(n);return"".concat(s,"/").concat(o)}return this.decodeIP(Xp.Convert.ToHex(e))}static fromString(e){if(e.includes("/")){for(var[t,r]=this.parseCIDR(e),n=new Uint8Array(t.length),i=r,o=0;o<n.length;o++)i>=8?(n[o]=255,i-=8):i>0&&(n[o]=255<<8-i,i=0);var a=new Uint8Array(2*t.length);return a.set(t,0),a.set(n,t.length),a.buffer}var s=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(s).buffer}}var Em=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};da([fm({type:By.TeletexString})],Em.prototype,"teletexString",void 0),da([fm({type:By.PrintableString})],Em.prototype,"printableString",void 0),da([fm({type:By.UniversalString})],Em.prototype,"universalString",void 0),da([fm({type:By.Utf8String})],Em.prototype,"utf8String",void 0),da([fm({type:By.BmpString})],Em.prototype,"bmpString",void 0),Em=da([pm({type:_y.Choice})],Em);var km=class extends Em{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Xp.Convert.ToHex(this.anyValue):super.toString())}};da([fm({type:By.IA5String})],km.prototype,"ia5String",void 0),da([fm({type:By.Any})],km.prototype,"anyValue",void 0),km=da([pm({type:_y.Choice})],km);class xm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.type="",this.value=new km,Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier})],xm.prototype,"type",void 0),da([fm({type:km})],xm.prototype,"value",void 0);var Am=cm=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,cm.prototype)}};Am=cm=da([pm({type:_y.Set,itemType:xm})],Am);var Cm=dm=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,dm.prototype)}};Cm=dm=da([pm({type:_y.Sequence,itemType:Am})],Cm);var Im=hm=class extends Cm{constructor(e){super(e),Object.setPrototypeOf(this,hm.prototype)}};Im=hm=da([pm({type:_y.Sequence})],Im);var Tm={fromASN:e=>Sm.toString(Vy.fromASN(e)),toASN:e=>Vy.toASN(Sm.fromString(e))};class Pm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.typeId="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier})],Pm.prototype,"typeId",void 0),da([fm({type:By.Any,context:0})],Pm.prototype,"value",void 0);class _m{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.partyName=new Em,Object.assign(this,e)}}da([fm({type:Em,optional:!0,context:0,implicit:!0})],_m.prototype,"nameAssigner",void 0),da([fm({type:Em,context:1,implicit:!0})],_m.prototype,"partyName",void 0);var Bm=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};da([fm({type:Pm,context:0,implicit:!0})],Bm.prototype,"otherName",void 0),da([fm({type:By.IA5String,context:1,implicit:!0})],Bm.prototype,"rfc822Name",void 0),da([fm({type:By.IA5String,context:2,implicit:!0})],Bm.prototype,"dNSName",void 0),da([fm({type:By.Any,context:3,implicit:!0})],Bm.prototype,"x400Address",void 0),da([fm({type:Im,context:4,implicit:!1})],Bm.prototype,"directoryName",void 0),da([fm({type:_m,context:5})],Bm.prototype,"ediPartyName",void 0),da([fm({type:By.IA5String,context:6,implicit:!0})],Bm.prototype,"uniformResourceIdentifier",void 0),da([fm({type:By.OctetString,context:7,implicit:!0,converter:Tm})],Bm.prototype,"iPAddress",void 0),da([fm({type:By.ObjectIdentifier,context:8,implicit:!0})],Bm.prototype,"registeredID",void 0),Bm=da([pm({type:_y.Choice})],Bm);var Nm,Dm="1.3.6.1.5.5.7",Rm="".concat(Dm,".1"),Om="".concat(Dm,".3"),Lm="".concat(Dm,".48"),Mm="".concat(Lm,".1"),Um="".concat(Lm,".2"),Fm="".concat(Lm,".3"),zm="".concat(Lm,".5"),jm="2.5.29",Vm="".concat(Rm,".1");class qm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.accessMethod="",this.accessLocation=new Bm,Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier})],qm.prototype,"accessMethod",void 0),da([fm({type:Bm})],qm.prototype,"accessLocation",void 0);var Hm=Nm=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,Nm.prototype)}};Hm=Nm=da([pm({type:_y.Sequence,itemType:qm})],Hm);var Km="".concat(jm,".35");class Wm extends Ry{}class Gm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e&&Object.assign(this,e)}}da([fm({type:Wm,context:0,optional:!0,implicit:!0})],Gm.prototype,"keyIdentifier",void 0),da([fm({type:Bm,context:1,optional:!0,implicit:!0,repeated:"sequence"})],Gm.prototype,"authorityCertIssuer",void 0),da([fm({type:By.Integer,context:2,optional:!0,implicit:!0,converter:Uy})],Gm.prototype,"authorityCertSerialNumber",void 0);var Qm,Ym="".concat(jm,".19");class Jm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.cA=!1,Object.assign(this,e)}}da([fm({type:By.Boolean,defaultValue:!1})],Jm.prototype,"cA",void 0),da([fm({type:By.Integer,optional:!0})],Jm.prototype,"pathLenConstraint",void 0);var Zm,$m=Qm=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,Qm.prototype)}};$m=Qm=da([pm({type:_y.Sequence,itemType:Bm})],$m);var Xm,ew=Zm=class extends $m{constructor(e){super(e),Object.setPrototypeOf(this,Zm.prototype)}};ew=Zm=da([pm({type:_y.Sequence})],ew);var tw="".concat(jm,".32"),rw=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};da([fm({type:By.IA5String})],rw.prototype,"ia5String",void 0),da([fm({type:By.VisibleString})],rw.prototype,"visibleString",void 0),da([fm({type:By.BmpString})],rw.prototype,"bmpString",void 0),da([fm({type:By.Utf8String})],rw.prototype,"utf8String",void 0),rw=da([pm({type:_y.Choice})],rw);class nw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.organization=new rw,this.noticeNumbers=[],Object.assign(this,e)}}da([fm({type:rw})],nw.prototype,"organization",void 0),da([fm({type:By.Integer,repeated:"sequence"})],nw.prototype,"noticeNumbers",void 0);class iw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}da([fm({type:nw,optional:!0})],iw.prototype,"noticeRef",void 0),da([fm({type:rw,optional:!0})],iw.prototype,"explicitText",void 0);var ow=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};da([fm({type:By.IA5String})],ow.prototype,"cPSuri",void 0),da([fm({type:iw})],ow.prototype,"userNotice",void 0),ow=da([pm({type:_y.Choice})],ow);class aw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.policyQualifierId="",this.qualifier=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier})],aw.prototype,"policyQualifierId",void 0),da([fm({type:By.Any})],aw.prototype,"qualifier",void 0);class sw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.policyIdentifier="",Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier})],sw.prototype,"policyIdentifier",void 0),da([fm({type:aw,repeated:"sequence",optional:!0})],sw.prototype,"policyQualifiers",void 0);var lw=Xm=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,Xm.prototype)}};lw=Xm=da([pm({type:_y.Sequence,itemType:sw})],lw);var uw=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.value=e}};da([fm({type:By.Integer})],uw.prototype,"value",void 0),uw=da([pm({type:_y.Choice})],uw);var cw,dw=class extends uw{};dw=da([pm({type:_y.Choice})],dw);var hw,vw="".concat(jm,".31");!function(e){e[e.unused=1]="unused",e[e.keyCompromise=2]="keyCompromise",e[e.cACompromise=4]="cACompromise",e[e.affiliationChanged=8]="affiliationChanged",e[e.superseded=16]="superseded",e[e.cessationOfOperation=32]="cessationOfOperation",e[e.certificateHold=64]="certificateHold",e[e.privilegeWithdrawn=128]="privilegeWithdrawn",e[e.aACompromise=256]="aACompromise"}(hw||(hw={}));class pw extends Dy{toJSON(){var e=[],t=this.toNumber();return t&hw.aACompromise&&e.push("aACompromise"),t&hw.affiliationChanged&&e.push("affiliationChanged"),t&hw.cACompromise&&e.push("cACompromise"),t&hw.certificateHold&&e.push("certificateHold"),t&hw.cessationOfOperation&&e.push("cessationOfOperation"),t&hw.keyCompromise&&e.push("keyCompromise"),t&hw.privilegeWithdrawn&&e.push("privilegeWithdrawn"),t&hw.superseded&&e.push("superseded"),t&hw.unused&&e.push("unused"),e}toString(){return"[".concat(this.toJSON().join(", "),"]")}}var fw=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};da([fm({type:Bm,context:0,repeated:"sequence",implicit:!0})],fw.prototype,"fullName",void 0),da([fm({type:Am,context:1,implicit:!0})],fw.prototype,"nameRelativeToCRLIssuer",void 0),fw=da([pm({type:_y.Choice})],fw);class gw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}da([fm({type:fw,context:0,optional:!0})],gw.prototype,"distributionPoint",void 0),da([fm({type:pw,context:1,optional:!0,implicit:!0})],gw.prototype,"reasons",void 0),da([fm({type:Bm,context:2,optional:!0,repeated:"sequence",implicit:!0})],gw.prototype,"cRLIssuer",void 0);var yw,mw=cw=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,cw.prototype)}};mw=cw=da([pm({type:_y.Sequence,itemType:gw})],mw);var ww,bw=yw=class extends mw{constructor(e){super(e),Object.setPrototypeOf(this,yw.prototype)}};bw=yw=da([pm({type:_y.Sequence,itemType:gw})],bw);class Sw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.onlyContainsUserCerts=Sw.ONLY,this.onlyContainsCACerts=Sw.ONLY,this.indirectCRL=Sw.ONLY,this.onlyContainsAttributeCerts=Sw.ONLY,Object.assign(this,e)}}Sw.ONLY=!1,da([fm({type:fw,context:0,optional:!0})],Sw.prototype,"distributionPoint",void 0),da([fm({type:By.Boolean,context:1,defaultValue:Sw.ONLY,implicit:!0})],Sw.prototype,"onlyContainsUserCerts",void 0),da([fm({type:By.Boolean,context:2,defaultValue:Sw.ONLY,implicit:!0})],Sw.prototype,"onlyContainsCACerts",void 0),da([fm({type:pw,context:3,optional:!0,implicit:!0})],Sw.prototype,"onlySomeReasons",void 0),da([fm({type:By.Boolean,context:4,defaultValue:Sw.ONLY,implicit:!0})],Sw.prototype,"indirectCRL",void 0),da([fm({type:By.Boolean,context:5,defaultValue:Sw.ONLY,implicit:!0})],Sw.prototype,"onlyContainsAttributeCerts",void 0),function(e){e[e.unspecified=0]="unspecified",e[e.keyCompromise=1]="keyCompromise",e[e.cACompromise=2]="cACompromise",e[e.affiliationChanged=3]="affiliationChanged",e[e.superseded=4]="superseded",e[e.cessationOfOperation=5]="cessationOfOperation",e[e.certificateHold=6]="certificateHold",e[e.removeFromCRL=8]="removeFromCRL",e[e.privilegeWithdrawn=9]="privilegeWithdrawn",e[e.aACompromise=10]="aACompromise"}(ww||(ww={}));var Ew,kw=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ww.unspecified;this.reason=ww.unspecified,this.reason=e}toJSON(){return ww[this.reason]}toString(){return this.toJSON()}};da([fm({type:By.Enumerated})],kw.prototype,"reason",void 0),kw=da([pm({type:_y.Choice})],kw);var xw="".concat(jm,".37"),Aw=Ew=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,Ew.prototype)}};Aw=Ew=da([pm({type:_y.Sequence,itemType:By.ObjectIdentifier})],Aw);var Cw="".concat(Om,".1"),Iw="".concat(Om,".2"),Tw="".concat(Om,".3"),Pw="".concat(Om,".4"),_w="".concat(Om,".8"),Bw="".concat(Om,".9"),Nw=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new ArrayBuffer(0);this.value=e}};da([fm({type:By.Integer,converter:Uy})],Nw.prototype,"value",void 0),Nw=da([pm({type:_y.Choice})],Nw);var Dw,Rw=class{constructor(e){this.value=new Date,e&&(this.value=e)}};da([fm({type:By.GeneralizedTime})],Rw.prototype,"value",void 0),Rw=da([pm({type:_y.Choice})],Rw);var Ow=Dw=class extends $m{constructor(e){super(e),Object.setPrototypeOf(this,Dw.prototype)}};Ow=Dw=da([pm({type:_y.Sequence})],Ow);var Lw,Mw,Uw="".concat(jm,".15");!function(e){e[e.digitalSignature=1]="digitalSignature",e[e.nonRepudiation=2]="nonRepudiation",e[e.keyEncipherment=4]="keyEncipherment",e[e.dataEncipherment=8]="dataEncipherment",e[e.keyAgreement=16]="keyAgreement",e[e.keyCertSign=32]="keyCertSign",e[e.cRLSign=64]="cRLSign",e[e.encipherOnly=128]="encipherOnly",e[e.decipherOnly=256]="decipherOnly"}(Lw||(Lw={}));class Fw extends Dy{toJSON(){var e=this.toNumber(),t=[];return e&Lw.cRLSign&&t.push("crlSign"),e&Lw.dataEncipherment&&t.push("dataEncipherment"),e&Lw.decipherOnly&&t.push("decipherOnly"),e&Lw.digitalSignature&&t.push("digitalSignature"),e&Lw.encipherOnly&&t.push("encipherOnly"),e&Lw.keyAgreement&&t.push("keyAgreement"),e&Lw.keyCertSign&&t.push("keyCertSign"),e&Lw.keyEncipherment&&t.push("keyEncipherment"),e&Lw.nonRepudiation&&t.push("nonRepudiation"),t}toString(){return"[".concat(this.toJSON().join(", "),"]")}}class zw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.base=new Bm,this.minimum=0,Object.assign(this,e)}}da([fm({type:Bm})],zw.prototype,"base",void 0),da([fm({type:By.Integer,context:0,defaultValue:0,implicit:!0})],zw.prototype,"minimum",void 0),da([fm({type:By.Integer,context:1,optional:!0,implicit:!0})],zw.prototype,"maximum",void 0);var jw,Vw=Mw=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,Mw.prototype)}};Vw=Mw=da([pm({type:_y.Sequence,itemType:zw})],Vw);class qw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}da([fm({type:Vw,context:0,optional:!0,implicit:!0})],qw.prototype,"permittedSubtrees",void 0),da([fm({type:Vw,context:1,optional:!0,implicit:!0})],qw.prototype,"excludedSubtrees",void 0);class Hw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}da([fm({type:By.Integer,context:0,implicit:!0,optional:!0,converter:Uy})],Hw.prototype,"requireExplicitPolicy",void 0),da([fm({type:By.Integer,context:1,implicit:!0,optional:!0,converter:Uy})],Hw.prototype,"inhibitPolicyMapping",void 0);class Kw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.issuerDomainPolicy="",this.subjectDomainPolicy="",Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier})],Kw.prototype,"issuerDomainPolicy",void 0),da([fm({type:By.ObjectIdentifier})],Kw.prototype,"subjectDomainPolicy",void 0);var Ww,Gw=jw=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,jw.prototype)}};Gw=jw=da([pm({type:_y.Sequence,itemType:Kw})],Gw);var Qw="".concat(jm,".17"),Yw=Ww=class extends $m{constructor(e){super(e),Object.setPrototypeOf(this,Ww.prototype)}};Yw=Ww=da([pm({type:_y.Sequence})],Yw);let Jw=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.type="",this.values=[],Object.assign(this,e)}};var Zw;da([fm({type:By.ObjectIdentifier})],Jw.prototype,"type",void 0),da([fm({type:By.Any,repeated:"set"})],Jw.prototype,"values",void 0);var $w=Zw=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,Zw.prototype)}};$w=Zw=da([pm({type:_y.Sequence,itemType:Jw})],$w);var Xw,eb,tb="".concat(jm,".14");class rb extends Wm{}class nb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}da([fm({type:By.GeneralizedTime,context:0,implicit:!0,optional:!0})],nb.prototype,"notBefore",void 0),da([fm({type:By.GeneralizedTime,context:1,implicit:!0,optional:!0})],nb.prototype,"notAfter",void 0),function(e){e[e.keyUpdateAllowed=1]="keyUpdateAllowed",e[e.newExtensions=2]="newExtensions",e[e.pKIXCertificate=4]="pKIXCertificate"}(Xw||(Xw={}));class ib extends Dy{toJSON(){var e=[],t=this.toNumber();return t&Xw.pKIXCertificate&&e.push("pKIXCertificate"),t&Xw.newExtensions&&e.push("newExtensions"),t&Xw.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return"[".concat(this.toJSON().join(", "),"]")}}class ob{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.entrustVers="",this.entrustInfoFlags=new ib,Object.assign(this,e)}}da([fm({type:By.GeneralString})],ob.prototype,"entrustVers",void 0),da([fm({type:ib})],ob.prototype,"entrustInfoFlags",void 0);var ab=eb=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,eb.prototype)}};ab=eb=da([pm({type:_y.Sequence,itemType:qm})],ab);class sb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.algorithm="",Object.assign(this,e)}isEqual(e){return e instanceof sb&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&Xp.isEqual(e.parameters,this.parameters)||e.parameters===this.parameters)}}da([fm({type:By.ObjectIdentifier})],sb.prototype,"algorithm",void 0),da([fm({type:By.Any,optional:!0})],sb.prototype,"parameters",void 0);class lb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.algorithm=new sb,this.subjectPublicKey=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:sb})],lb.prototype,"algorithm",void 0),da([fm({type:By.BitString})],lb.prototype,"subjectPublicKey",void 0);var ub,cb=class{constructor(e){if(e)if("string"==typeof e||"number"==typeof e||e instanceof Date){var t=new Date(e);t.getUTCFullYear()>2049?this.generalTime=t:this.utcTime=t}else Object.assign(this,e)}getTime(){var e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};da([fm({type:By.UTCTime})],cb.prototype,"utcTime",void 0),da([fm({type:By.GeneralizedTime})],cb.prototype,"generalTime",void 0),cb=da([pm({type:_y.Choice})],cb);class db{constructor(e){this.notBefore=new cb(new Date),this.notAfter=new cb(new Date),e&&(this.notBefore=new cb(e.notBefore),this.notAfter=new cb(e.notAfter))}}da([fm({type:cb})],db.prototype,"notBefore",void 0),da([fm({type:cb})],db.prototype,"notAfter",void 0);let hb=class e{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.extnID="",this.critical=e.CRITICAL,this.extnValue=new Ry,Object.assign(this,t)}};hb.CRITICAL=!1,da([fm({type:By.ObjectIdentifier})],hb.prototype,"extnID",void 0),da([fm({type:By.Boolean,defaultValue:hb.CRITICAL})],hb.prototype,"critical",void 0),da([fm({type:Ry})],hb.prototype,"extnValue",void 0);var vb,pb=ub=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,ub.prototype)}};pb=ub=da([pm({type:_y.Sequence,itemType:hb})],pb),function(e){e[e.v1=0]="v1",e[e.v2=1]="v2",e[e.v3=2]="v3"}(vb||(vb={}));class fb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=vb.v1,this.serialNumber=new ArrayBuffer(0),this.signature=new sb,this.issuer=new Im,this.validity=new db,this.subject=new Im,this.subjectPublicKeyInfo=new lb,Object.assign(this,e)}}da([fm({type:By.Integer,context:0,defaultValue:vb.v1})],fb.prototype,"version",void 0),da([fm({type:By.Integer,converter:Uy})],fb.prototype,"serialNumber",void 0),da([fm({type:sb})],fb.prototype,"signature",void 0),da([fm({type:Im})],fb.prototype,"issuer",void 0),da([fm({type:db})],fb.prototype,"validity",void 0),da([fm({type:Im})],fb.prototype,"subject",void 0),da([fm({type:lb})],fb.prototype,"subjectPublicKeyInfo",void 0),da([fm({type:By.BitString,context:1,implicit:!0,optional:!0})],fb.prototype,"issuerUniqueID",void 0),da([fm({type:By.BitString,context:2,implicit:!0,optional:!0})],fb.prototype,"subjectUniqueID",void 0),da([fm({type:pb,context:3,optional:!0})],fb.prototype,"extensions",void 0);class gb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.tbsCertificate=new fb,this.signatureAlgorithm=new sb,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:fb})],gb.prototype,"tbsCertificate",void 0),da([fm({type:sb})],gb.prototype,"signatureAlgorithm",void 0),da([fm({type:By.BitString})],gb.prototype,"signatureValue",void 0);class yb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.userCertificate=new ArrayBuffer(0),this.revocationDate=new cb,Object.assign(this,e)}}da([fm({type:By.Integer,converter:Uy})],yb.prototype,"userCertificate",void 0),da([fm({type:cb})],yb.prototype,"revocationDate",void 0),da([fm({type:hb,optional:!0,repeated:"sequence"})],yb.prototype,"crlEntryExtensions",void 0);class mb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.signature=new sb,this.issuer=new Im,this.thisUpdate=new cb,Object.assign(this,e)}}da([fm({type:By.Integer,optional:!0})],mb.prototype,"version",void 0),da([fm({type:sb})],mb.prototype,"signature",void 0),da([fm({type:Im})],mb.prototype,"issuer",void 0),da([fm({type:cb})],mb.prototype,"thisUpdate",void 0),da([fm({type:cb,optional:!0})],mb.prototype,"nextUpdate",void 0),da([fm({type:yb,repeated:"sequence",optional:!0})],mb.prototype,"revokedCertificates",void 0),da([fm({type:hb,optional:!0,context:0,repeated:"sequence"})],mb.prototype,"crlExtensions",void 0);class wb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.tbsCertList=new mb,this.signatureAlgorithm=new sb,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:mb})],wb.prototype,"tbsCertList",void 0),da([fm({type:sb})],wb.prototype,"signatureAlgorithm",void 0),da([fm({type:By.BitString})],wb.prototype,"signature",void 0);class bb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.issuer=new Im,this.serialNumber=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:Im})],bb.prototype,"issuer",void 0),da([fm({type:By.Integer,converter:Uy})],bb.prototype,"serialNumber",void 0);var Sb,Eb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};da([fm({type:rb,context:0,implicit:!0})],Eb.prototype,"subjectKeyIdentifier",void 0),da([fm({type:bb})],Eb.prototype,"issuerAndSerialNumber",void 0),Eb=da([pm({type:_y.Choice})],Eb),function(e){e[e.v0=0]="v0",e[e.v1=1]="v1",e[e.v2=2]="v2",e[e.v3=3]="v3",e[e.v4=4]="v4",e[e.v5=5]="v5"}(Sb||(Sb={}));var kb=class extends sb{};kb=da([pm({type:_y.Sequence})],kb);var xb=class extends sb{};xb=da([pm({type:_y.Sequence})],xb);var Ab=class extends sb{};Ab=da([pm({type:_y.Sequence})],Ab);var Cb=class extends sb{};Cb=da([pm({type:_y.Sequence})],Cb);var Ib=class extends sb{};Ib=da([pm({type:_y.Sequence})],Ib);var Tb=class extends sb{};Tb=da([pm({type:_y.Sequence})],Tb);let Pb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.attrType="",this.attrValues=[],Object.assign(this,e)}};var _b;da([fm({type:By.ObjectIdentifier})],Pb.prototype,"attrType",void 0),da([fm({type:By.Any,repeated:"set"})],Pb.prototype,"attrValues",void 0);class Bb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Sb.v0,this.sid=new Eb,this.digestAlgorithm=new kb,this.signatureAlgorithm=new xb,this.signature=new Ry,Object.assign(this,e)}}da([fm({type:By.Integer})],Bb.prototype,"version",void 0),da([fm({type:Eb})],Bb.prototype,"sid",void 0),da([fm({type:kb})],Bb.prototype,"digestAlgorithm",void 0),da([fm({type:Pb,repeated:"set",context:0,implicit:!0,optional:!0})],Bb.prototype,"signedAttrs",void 0),da([fm({type:xb})],Bb.prototype,"signatureAlgorithm",void 0),da([fm({type:Ry})],Bb.prototype,"signature",void 0),da([fm({type:Pb,repeated:"set",context:1,implicit:!0,optional:!0})],Bb.prototype,"unsignedAttrs",void 0);var Nb=_b=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,_b.prototype)}};Nb=_b=da([pm({type:_y.Set,itemType:Bb})],Nb);var Db=class extends cb{};Db=da([pm({type:_y.Choice})],Db);var Rb,Ob=class extends Bb{};Ob=da([pm({type:_y.Sequence})],Ob);class Lb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.acIssuer=new Bm,this.acSerial=0,this.attrs=[],Object.assign(this,e)}}da([fm({type:Bm})],Lb.prototype,"acIssuer",void 0),da([fm({type:By.Integer})],Lb.prototype,"acSerial",void 0),da([fm({type:Jw,repeated:"sequence"})],Lb.prototype,"attrs",void 0);var Mb,Ub=Rb=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,Rb.prototype)}};Ub=Rb=da([pm({type:_y.Sequence,itemType:By.ObjectIdentifier})],Ub);class Fb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.permitUnSpecified=!0,Object.assign(this,e)}}da([fm({type:By.Integer,optional:!0})],Fb.prototype,"pathLenConstraint",void 0),da([fm({type:Ub,implicit:!0,context:0,optional:!0})],Fb.prototype,"permittedAttrs",void 0),da([fm({type:Ub,implicit:!0,context:1,optional:!0})],Fb.prototype,"excludedAttrs",void 0),da([fm({type:By.Boolean,defaultValue:!0})],Fb.prototype,"permitUnSpecified",void 0);class zb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.issuer=new $m,this.serial=new ArrayBuffer(0),this.issuerUID=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:$m})],zb.prototype,"issuer",void 0),da([fm({type:By.Integer,converter:Uy})],zb.prototype,"serial",void 0),da([fm({type:By.BitString,optional:!0})],zb.prototype,"issuerUID",void 0),function(e){e[e.publicKey=0]="publicKey",e[e.publicKeyCert=1]="publicKeyCert",e[e.otherObjectTypes=2]="otherObjectTypes"}(Mb||(Mb={}));class jb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.digestedObjectType=Mb.publicKey,this.digestAlgorithm=new sb,this.objectDigest=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:By.Enumerated})],jb.prototype,"digestedObjectType",void 0),da([fm({type:By.ObjectIdentifier,optional:!0})],jb.prototype,"otherObjectTypeID",void 0),da([fm({type:sb})],jb.prototype,"digestAlgorithm",void 0),da([fm({type:By.BitString})],jb.prototype,"objectDigest",void 0);class Vb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}da([fm({type:$m,optional:!0})],Vb.prototype,"issuerName",void 0),da([fm({type:zb,context:0,implicit:!0,optional:!0})],Vb.prototype,"baseCertificateID",void 0),da([fm({type:jb,context:1,implicit:!0,optional:!0})],Vb.prototype,"objectDigestInfo",void 0);var qb,Hb,Kb,Wb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};da([fm({type:Bm,repeated:"sequence"})],Wb.prototype,"v1Form",void 0),da([fm({type:Vb,context:0,implicit:!0})],Wb.prototype,"v2Form",void 0),Wb=da([pm({type:_y.Choice})],Wb);class Gb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.notBeforeTime=new Date,this.notAfterTime=new Date,Object.assign(this,e)}}da([fm({type:By.GeneralizedTime})],Gb.prototype,"notBeforeTime",void 0),da([fm({type:By.GeneralizedTime})],Gb.prototype,"notAfterTime",void 0);class Qb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}da([fm({type:zb,implicit:!0,context:0,optional:!0})],Qb.prototype,"baseCertificateID",void 0),da([fm({type:$m,implicit:!0,context:1,optional:!0})],Qb.prototype,"entityName",void 0),da([fm({type:jb,implicit:!0,context:2,optional:!0})],Qb.prototype,"objectDigestInfo",void 0),function(e){e[e.v2=1]="v2"}(qb||(qb={}));class Yb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=qb.v2,this.holder=new Qb,this.issuer=new Wb,this.signature=new sb,this.serialNumber=new ArrayBuffer(0),this.attrCertValidityPeriod=new Gb,this.attributes=[],Object.assign(this,e)}}da([fm({type:By.Integer})],Yb.prototype,"version",void 0),da([fm({type:Qb})],Yb.prototype,"holder",void 0),da([fm({type:Wb})],Yb.prototype,"issuer",void 0),da([fm({type:sb})],Yb.prototype,"signature",void 0),da([fm({type:By.Integer,converter:Uy})],Yb.prototype,"serialNumber",void 0),da([fm({type:Gb})],Yb.prototype,"attrCertValidityPeriod",void 0),da([fm({type:Jw,repeated:"sequence"})],Yb.prototype,"attributes",void 0),da([fm({type:By.BitString,optional:!0})],Yb.prototype,"issuerUniqueID",void 0),da([fm({type:pb,optional:!0})],Yb.prototype,"extensions",void 0);class Jb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.acinfo=new Yb,this.signatureAlgorithm=new sb,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:Yb})],Jb.prototype,"acinfo",void 0),da([fm({type:sb})],Jb.prototype,"signatureAlgorithm",void 0),da([fm({type:By.BitString})],Jb.prototype,"signatureValue",void 0),function(e){e[e.unmarked=1]="unmarked",e[e.unclassified=2]="unclassified",e[e.restricted=4]="restricted",e[e.confidential=8]="confidential",e[e.secret=16]="secret",e[e.topSecret=32]="topSecret"}(Hb||(Hb={}));class Zb extends Dy{}class $b{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.type="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier,implicit:!0,context:0})],$b.prototype,"type",void 0),da([fm({type:By.Any,implicit:!0,context:1})],$b.prototype,"value",void 0);class Xb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.policyId="",this.classList=new Zb(Hb.unclassified),Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier})],Xb.prototype,"policyId",void 0),da([fm({type:Zb,defaultValue:new Zb(Hb.unclassified)})],Xb.prototype,"classList",void 0),da([fm({type:$b,repeated:"set"})],Xb.prototype,"securityCategories",void 0);class eS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}da([fm({type:Ry})],eS.prototype,"cotets",void 0),da([fm({type:By.ObjectIdentifier})],eS.prototype,"oid",void 0),da([fm({type:By.Utf8String})],eS.prototype,"string",void 0);class tS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.values=[],Object.assign(this,e)}}da([fm({type:$m,implicit:!0,context:0,optional:!0})],tS.prototype,"policyAuthority",void 0),da([fm({type:eS,repeated:"sequence"})],tS.prototype,"values",void 0);class rS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.targetCertificate=new zb,Object.assign(this,e)}}da([fm({type:zb})],rS.prototype,"targetCertificate",void 0),da([fm({type:Bm,optional:!0})],rS.prototype,"targetName",void 0),da([fm({type:jb,optional:!0})],rS.prototype,"certDigestInfo",void 0);var nS=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};da([fm({type:Bm,context:0,implicit:!0})],nS.prototype,"targetName",void 0),da([fm({type:Bm,context:1,implicit:!0})],nS.prototype,"targetGroup",void 0),da([fm({type:rS,context:2,implicit:!0})],nS.prototype,"targetCert",void 0),nS=da([pm({type:_y.Choice})],nS);var iS,oS=Kb=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,Kb.prototype)}};oS=Kb=da([pm({type:_y.Sequence,itemType:nS})],oS);var aS,sS=iS=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,iS.prototype)}};sS=iS=da([pm({type:_y.Sequence,itemType:oS})],sS);class lS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}da([fm({type:$m,implicit:!0,context:0,optional:!0})],lS.prototype,"roleAuthority",void 0),da([fm({type:Bm,implicit:!0,context:1})],lS.prototype,"roleName",void 0);class uS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.service=new Bm,this.ident=new Bm,Object.assign(this,e)}}da([fm({type:Bm})],uS.prototype,"service",void 0),da([fm({type:Bm})],uS.prototype,"ident",void 0),da([fm({type:Ry,optional:!0})],uS.prototype,"authInfo",void 0);class cS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.otherCertFormat="",this.otherCert=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier})],cS.prototype,"otherCertFormat",void 0),da([fm({type:By.Any})],cS.prototype,"otherCert",void 0);var dS=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};da([fm({type:gb})],dS.prototype,"certificate",void 0),da([fm({type:Jb,context:2,implicit:!0})],dS.prototype,"v2AttrCert",void 0),da([fm({type:cS,context:3,implicit:!0})],dS.prototype,"other",void 0),dS=da([pm({type:_y.Choice})],dS);var hS=aS=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,aS.prototype)}};hS=aS=da([pm({type:_y.Set,itemType:dS})],hS);class vS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.contentType="",this.content=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier})],vS.prototype,"contentType",void 0),da([fm({type:By.Any,context:0})],vS.prototype,"content",void 0);var pS=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};da([fm({type:Ry})],pS.prototype,"single",void 0),da([fm({type:By.Any})],pS.prototype,"any",void 0),pS=da([pm({type:_y.Choice})],pS);class fS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.eContentType="",Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier})],fS.prototype,"eContentType",void 0),da([fm({type:pS,context:0,optional:!0})],fS.prototype,"eContent",void 0);var gS,yS=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};da([fm({type:Ry,context:0,implicit:!0,optional:!0})],yS.prototype,"value",void 0),da([fm({type:Ry,converter:qy,context:0,implicit:!0,optional:!0,repeated:"sequence"})],yS.prototype,"constructedValue",void 0),yS=da([pm({type:_y.Choice})],yS);class mS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.contentType="",this.contentEncryptionAlgorithm=new Cb,Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier})],mS.prototype,"contentType",void 0),da([fm({type:Cb})],mS.prototype,"contentEncryptionAlgorithm",void 0),da([fm({type:yS,optional:!0})],mS.prototype,"encryptedContent",void 0);class wS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.keyAttrId="",Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier})],wS.prototype,"keyAttrId",void 0),da([fm({type:By.Any,optional:!0})],wS.prototype,"keyAttr",void 0);class bS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.subjectKeyIdentifier=new rb,Object.assign(this,e)}}da([fm({type:rb})],bS.prototype,"subjectKeyIdentifier",void 0),da([fm({type:By.GeneralizedTime,optional:!0})],bS.prototype,"date",void 0),da([fm({type:wS,optional:!0})],bS.prototype,"other",void 0);var SS=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};da([fm({type:bS,context:0,implicit:!0,optional:!0})],SS.prototype,"rKeyId",void 0),da([fm({type:bb,optional:!0})],SS.prototype,"issuerAndSerialNumber",void 0),SS=da([pm({type:_y.Choice})],SS);class ES{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.rid=new SS,this.encryptedKey=new Ry,Object.assign(this,e)}}da([fm({type:SS})],ES.prototype,"rid",void 0),da([fm({type:Ry})],ES.prototype,"encryptedKey",void 0);var kS=gS=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,gS.prototype)}};kS=gS=da([pm({type:_y.Sequence,itemType:ES})],kS);class xS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.algorithm=new sb,this.publicKey=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:sb})],xS.prototype,"algorithm",void 0),da([fm({type:By.BitString})],xS.prototype,"publicKey",void 0);var AS=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};da([fm({type:rb,context:0,implicit:!0,optional:!0})],AS.prototype,"subjectKeyIdentifier",void 0),da([fm({type:xS,context:1,implicit:!0,optional:!0})],AS.prototype,"originatorKey",void 0),da([fm({type:bb,optional:!0})],AS.prototype,"issuerAndSerialNumber",void 0),AS=da([pm({type:_y.Choice})],AS);class CS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Sb.v3,this.originator=new AS,this.keyEncryptionAlgorithm=new Ab,this.recipientEncryptedKeys=new kS,Object.assign(this,e)}}da([fm({type:By.Integer})],CS.prototype,"version",void 0),da([fm({type:AS,context:0})],CS.prototype,"originator",void 0),da([fm({type:Ry,context:1,optional:!0})],CS.prototype,"ukm",void 0),da([fm({type:Ab})],CS.prototype,"keyEncryptionAlgorithm",void 0),da([fm({type:kS})],CS.prototype,"recipientEncryptedKeys",void 0);var IS=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};da([fm({type:rb,context:0,implicit:!0})],IS.prototype,"subjectKeyIdentifier",void 0),da([fm({type:bb})],IS.prototype,"issuerAndSerialNumber",void 0),IS=da([pm({type:_y.Choice})],IS);class TS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Sb.v0,this.rid=new IS,this.keyEncryptionAlgorithm=new Ab,this.encryptedKey=new Ry,Object.assign(this,e)}}da([fm({type:By.Integer})],TS.prototype,"version",void 0),da([fm({type:IS})],TS.prototype,"rid",void 0),da([fm({type:Ab})],TS.prototype,"keyEncryptionAlgorithm",void 0),da([fm({type:Ry})],TS.prototype,"encryptedKey",void 0);class PS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.keyIdentifier=new Ry,Object.assign(this,e)}}da([fm({type:Ry})],PS.prototype,"keyIdentifier",void 0),da([fm({type:By.GeneralizedTime,optional:!0})],PS.prototype,"date",void 0),da([fm({type:wS,optional:!0})],PS.prototype,"other",void 0);class _S{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Sb.v4,this.kekid=new PS,this.keyEncryptionAlgorithm=new Ab,this.encryptedKey=new Ry,Object.assign(this,e)}}da([fm({type:By.Integer})],_S.prototype,"version",void 0),da([fm({type:PS})],_S.prototype,"kekid",void 0),da([fm({type:Ab})],_S.prototype,"keyEncryptionAlgorithm",void 0),da([fm({type:Ry})],_S.prototype,"encryptedKey",void 0);class BS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Sb.v0,this.keyEncryptionAlgorithm=new Ab,this.encryptedKey=new Ry,Object.assign(this,e)}}da([fm({type:By.Integer})],BS.prototype,"version",void 0),da([fm({type:Tb,context:0,optional:!0})],BS.prototype,"keyDerivationAlgorithm",void 0),da([fm({type:Ab})],BS.prototype,"keyEncryptionAlgorithm",void 0),da([fm({type:Ry})],BS.prototype,"encryptedKey",void 0);class NS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.oriType="",this.oriValue=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier})],NS.prototype,"oriType",void 0),da([fm({type:By.Any})],NS.prototype,"oriValue",void 0);var DS,RS=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};da([fm({type:TS,optional:!0})],RS.prototype,"ktri",void 0),da([fm({type:CS,context:1,implicit:!0,optional:!0})],RS.prototype,"kari",void 0),da([fm({type:_S,context:2,implicit:!0,optional:!0})],RS.prototype,"kekri",void 0),da([fm({type:BS,context:3,implicit:!0,optional:!0})],RS.prototype,"pwri",void 0),da([fm({type:NS,context:4,implicit:!0,optional:!0})],RS.prototype,"ori",void 0),RS=da([pm({type:_y.Choice})],RS);var OS,LS=DS=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,DS.prototype)}};LS=DS=da([pm({type:_y.Set,itemType:RS})],LS);class MS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.otherRevInfoFormat="",this.otherRevInfo=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier})],MS.prototype,"otherRevInfoFormat",void 0),da([fm({type:By.Any})],MS.prototype,"otherRevInfo",void 0);var US=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.other=new MS,Object.assign(this,e)}};da([fm({type:MS,context:1,implicit:!0})],US.prototype,"other",void 0),US=da([pm({type:_y.Choice})],US);var FS,zS=OS=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,OS.prototype)}};zS=OS=da([pm({type:_y.Set,itemType:US})],zS);class jS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}da([fm({type:hS,context:0,implicit:!0,optional:!0})],jS.prototype,"certs",void 0),da([fm({type:zS,context:1,implicit:!0,optional:!0})],jS.prototype,"crls",void 0);var VS=FS=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,FS.prototype)}};VS=FS=da([pm({type:_y.Set,itemType:Pb})],VS);class qS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Sb.v0,this.recipientInfos=new LS,this.encryptedContentInfo=new mS,Object.assign(this,e)}}da([fm({type:By.Integer})],qS.prototype,"version",void 0),da([fm({type:jS,context:0,implicit:!0,optional:!0})],qS.prototype,"originatorInfo",void 0),da([fm({type:LS})],qS.prototype,"recipientInfos",void 0),da([fm({type:mS})],qS.prototype,"encryptedContentInfo",void 0),da([fm({type:VS,context:1,implicit:!0,optional:!0})],qS.prototype,"unprotectedAttrs",void 0);var HS,KS="1.2.840.113549.1.7.2",WS=HS=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,HS.prototype)}};WS=HS=da([pm({type:_y.Set,itemType:kb})],WS);class GS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Sb.v0,this.digestAlgorithms=new WS,this.encapContentInfo=new fS,this.signerInfos=new Nb,Object.assign(this,e)}}da([fm({type:By.Integer})],GS.prototype,"version",void 0),da([fm({type:WS})],GS.prototype,"digestAlgorithms",void 0),da([fm({type:fS})],GS.prototype,"encapContentInfo",void 0),da([fm({type:hS,context:0,implicit:!0,optional:!0})],GS.prototype,"certificates",void 0),da([fm({type:zS,context:1,implicit:!0,optional:!0})],GS.prototype,"crls",void 0),da([fm({type:Nb})],GS.prototype,"signerInfos",void 0);var QS="1.2.840.10045.2.1",YS="1.2.840.10045.4.1",JS="1.2.840.10045.4.3.1",ZS="1.2.840.10045.4.3.2",$S="1.2.840.10045.4.3.3",XS="1.2.840.10045.4.3.4",eE="1.2.840.10045.3.1.7",tE="1.3.132.0.34",rE="1.3.132.0.35";function nE(e){return new sb({algorithm:e})}var iE=nE(YS);nE(JS);var oE=nE(ZS),aE=nE($S),sE=nE(XS),lE=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};da([fm({type:By.ObjectIdentifier})],lE.prototype,"fieldType",void 0),da([fm({type:By.Any})],lE.prototype,"parameters",void 0),lE=da([pm({type:_y.Sequence})],lE);var uE,cE=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};da([fm({type:By.OctetString})],cE.prototype,"a",void 0),da([fm({type:By.OctetString})],cE.prototype,"b",void 0),da([fm({type:By.BitString,optional:!0})],cE.prototype,"seed",void 0),cE=da([pm({type:_y.Sequence})],cE),function(e){e[e.ecpVer1=1]="ecpVer1"}(uE||(uE={}));var dE=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=uE.ecpVer1,Object.assign(this,e)}};da([fm({type:By.Integer})],dE.prototype,"version",void 0),da([fm({type:lE})],dE.prototype,"fieldID",void 0),da([fm({type:cE})],dE.prototype,"curve",void 0),da([fm({type:class extends Ry{}})],dE.prototype,"base",void 0),da([fm({type:By.Integer,converter:Uy})],dE.prototype,"order",void 0),da([fm({type:By.Integer,optional:!0})],dE.prototype,"cofactor",void 0),dE=da([pm({type:_y.Sequence})],dE);var hE=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};da([fm({type:By.ObjectIdentifier})],hE.prototype,"namedCurve",void 0),da([fm({type:By.Null})],hE.prototype,"implicitCurve",void 0),da([fm({type:dE})],hE.prototype,"specifiedCurve",void 0),hE=da([pm({type:_y.Choice})],hE);class vE{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=1,this.privateKey=new Ry,Object.assign(this,e)}}da([fm({type:By.Integer})],vE.prototype,"version",void 0),da([fm({type:Ry})],vE.prototype,"privateKey",void 0),da([fm({type:hE,context:0,optional:!0})],vE.prototype,"parameters",void 0),da([fm({type:By.BitString,context:1,optional:!0})],vE.prototype,"publicKey",void 0);class pE{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:By.Integer,converter:Uy})],pE.prototype,"r",void 0),da([fm({type:By.Integer,converter:Uy})],pE.prototype,"s",void 0);var fE="1.2.840.113549.1.1",gE="".concat(fE,".1"),yE="".concat(fE,".7"),mE="".concat(fE,".9"),wE="".concat(fE,".10"),bE="".concat(fE,".2"),SE="".concat(fE,".4"),EE="".concat(fE,".5"),kE="".concat(fE,".14"),xE="".concat(fE,".11"),AE="".concat(fE,".12"),CE="".concat(fE,".13"),IE="".concat(fE,".15"),TE="".concat(fE,".16"),PE="1.3.14.3.2.26",_E="2.16.840.1.101.3.4.2.4",BE="2.16.840.1.101.3.4.2.1",NE="2.16.840.1.101.3.4.2.2",DE="2.16.840.1.101.3.4.2.3",RE="".concat(fE,".8");function OE(e){return new sb({algorithm:e,parameters:null})}OE("1.2.840.113549.2.2"),OE("1.2.840.113549.2.5");var LE=OE(PE);OE(_E),OE(BE),OE(NE),OE(DE),OE("2.16.840.1.101.3.4.2.5"),OE("2.16.840.1.101.3.4.2.6");var ME,UE=new sb({algorithm:RE,parameters:bm.serialize(LE)}),FE=new sb({algorithm:mE,parameters:bm.serialize(Vy.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});OE(gE),OE(bE),OE(SE),OE(EE),OE(IE),OE(TE),OE(AE),OE(CE),OE(IE),OE(TE);class zE{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.hashAlgorithm=new sb(LE),this.maskGenAlgorithm=new sb({algorithm:RE,parameters:bm.serialize(LE)}),this.pSourceAlgorithm=new sb(FE),Object.assign(this,e)}}da([fm({type:sb,context:0,defaultValue:LE})],zE.prototype,"hashAlgorithm",void 0),da([fm({type:sb,context:1,defaultValue:UE})],zE.prototype,"maskGenAlgorithm",void 0),da([fm({type:sb,context:2,defaultValue:FE})],zE.prototype,"pSourceAlgorithm",void 0),new sb({algorithm:yE,parameters:bm.serialize(new zE)});class jE{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.hashAlgorithm=new sb(LE),this.maskGenAlgorithm=new sb({algorithm:RE,parameters:bm.serialize(LE)}),this.saltLength=20,this.trailerField=1,Object.assign(this,e)}}da([fm({type:sb,context:0,defaultValue:LE})],jE.prototype,"hashAlgorithm",void 0),da([fm({type:sb,context:1,defaultValue:UE})],jE.prototype,"maskGenAlgorithm",void 0),da([fm({type:By.Integer,context:2,defaultValue:20})],jE.prototype,"saltLength",void 0),da([fm({type:By.Integer,context:3,defaultValue:1})],jE.prototype,"trailerField",void 0),new sb({algorithm:wE,parameters:bm.serialize(new jE)});class VE{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.digestAlgorithm=new sb,this.digest=new Ry,Object.assign(this,e)}}da([fm({type:sb})],VE.prototype,"digestAlgorithm",void 0),da([fm({type:Ry})],VE.prototype,"digest",void 0);class qE{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.prime=new ArrayBuffer(0),this.exponent=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:By.Integer,converter:Uy})],qE.prototype,"prime",void 0),da([fm({type:By.Integer,converter:Uy})],qE.prototype,"exponent",void 0),da([fm({type:By.Integer,converter:Uy})],qE.prototype,"coefficient",void 0);var HE,KE=ME=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,ME.prototype)}};KE=ME=da([pm({type:_y.Sequence,itemType:qE})],KE);class WE{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=0,this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),this.privateExponent=new ArrayBuffer(0),this.prime1=new ArrayBuffer(0),this.prime2=new ArrayBuffer(0),this.exponent1=new ArrayBuffer(0),this.exponent2=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:By.Integer})],WE.prototype,"version",void 0),da([fm({type:By.Integer,converter:Uy})],WE.prototype,"modulus",void 0),da([fm({type:By.Integer,converter:Uy})],WE.prototype,"publicExponent",void 0),da([fm({type:By.Integer,converter:Uy})],WE.prototype,"privateExponent",void 0),da([fm({type:By.Integer,converter:Uy})],WE.prototype,"prime1",void 0),da([fm({type:By.Integer,converter:Uy})],WE.prototype,"prime2",void 0),da([fm({type:By.Integer,converter:Uy})],WE.prototype,"exponent1",void 0),da([fm({type:By.Integer,converter:Uy})],WE.prototype,"exponent2",void 0),da([fm({type:By.Integer,converter:Uy})],WE.prototype,"coefficient",void 0),da([fm({type:KE,optional:!0})],WE.prototype,"otherPrimeInfos",void 0);class GE{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:By.Integer,converter:Uy})],GE.prototype,"modulus",void 0),da([fm({type:By.Integer,converter:Uy})],GE.prototype,"publicExponent",void 0),function(e){e[e.Transient=0]="Transient",e[e.Singleton=1]="Singleton",e[e.ResolutionScoped=2]="ResolutionScoped",e[e.ContainerScoped=3]="ContainerScoped"}(HE||(HE={}));var QE=HE;function YE(e){return!!e.useClass}function JE(e){return!!e.useFactory}var ZE=function(){function e(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return e.prototype.createProxy=function(e){var t,r=this,n=!1;return new Proxy({},this.createHandler((function(){return n||(t=e(r.wrap()),n=!0),t})))},e.prototype.createHandler=function(e){var t={};return this.reflectMethods.forEach((function(r){t[r]=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return t[0]=e(),Reflect[r].apply(void 0,ga(t))}})),t},e}();function $E(e){return"string"==typeof e||"symbol"==typeof e}function XE(e){return"object"==typeof e&&"token"in e&&"transform"in e}function ek(e){return!!e.useToken}function tk(e){return null!=e.useValue}var rk=function(){function e(){this._registryMap=new Map}return e.prototype.entries=function(){return this._registryMap.entries()},e.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},e.prototype.get=function(e){this.ensure(e);var t=this._registryMap.get(e);return t[t.length-1]||null},e.prototype.set=function(e,t){this.ensure(e),this._registryMap.get(e).push(t)},e.prototype.setAll=function(e,t){this._registryMap.set(e,t)},e.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},e.prototype.clear=function(){this._registryMap.clear()},e.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},e}(),nk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return ca(t,e),t}(rk),ik=function(){this.scopedResolutions=new Map};function ok(e,t,r){var n,i,o=fa(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2)[1],a=function(e,t){return null===e?"at position #"+t:'"'+e.split(",")[t].trim()+'" at position #'+t}(void 0===o?null:o,t);return n="Cannot inject the dependency "+a+' of "'+e.name+'" constructor. Reason:',void 0===i&&(i=" "),ga([n],r.message.split("\n").map((function(e){return i+e}))).join("\n")}var ak,sk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return ca(t,e),t}(rk),lk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return ca(t,e),t}(rk),uk=function(){this.preResolution=new sk,this.postResolution=new lk},ck=new Map,dk=function(){function e(e){this.parent=e,this._registry=new nk,this.interceptors=new uk,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,r){var n;if(void 0===r&&(r={lifecycle:QE.Transient}),this.ensureNotDisposed(),n=function(e){return YE(e)||tk(e)||ek(e)||JE(e)}(t)?t:{useClass:t},ek(n))for(var i=[e],o=n;null!=o;){var a=o.useToken;if(i.includes(a))throw new Error("Token registration cycle detected! "+ga(i,[a]).join(" -> "));i.push(a);var s=this._registry.get(a);o=s&&ek(s.provider)?s.provider:null}if((r.lifecycle===QE.Singleton||r.lifecycle==QE.ContainerScoped||r.lifecycle==QE.ResolutionScoped)&&(tk(n)||JE(n)))throw new Error('Cannot use lifecycle "'+QE[r.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:n,options:r}),this},e.prototype.registerType=function(e,t){return this.ensureNotDisposed(),$E(t)?this.register(e,{useToken:t}):this.register(e,{useClass:t})},e.prototype.registerInstance=function(e,t){return this.ensureNotDisposed(),this.register(e,{useValue:t})},e.prototype.registerSingleton=function(e,t){if(this.ensureNotDisposed(),$E(e)){if($E(t))return this.register(e,{useToken:t},{lifecycle:QE.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:QE.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var r=e;return t&&!$E(t)&&(r=t),this.register(e,{useClass:r},{lifecycle:QE.Singleton})},e.prototype.resolve=function(e,t,r){void 0===t&&(t=new ik),void 0===r&&(r=!1),this.ensureNotDisposed();var n=this.getRegistration(e);if(!n&&$E(e)){if(r)return;throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"Single"),n){var i=this.resolveRegistration(n,t);return this.executePostResolutionInterceptor(e,i,"Single"),i}if(function(e){return"function"==typeof e||e instanceof ZE}(e)){i=this.construct(e,t);return this.executePostResolutionInterceptor(e,i,"Single"),i}throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},e.prototype.executePreResolutionInterceptor=function(e,t){var r,n;if(this.interceptors.preResolution.has(e)){var i=[];try{for(var o=pa(this.interceptors.preResolution.getAll(e)),a=o.next();!a.done;a=o.next()){var s=a.value;"Once"!=s.options.frequency&&i.push(s),s.callback(e,t)}}catch(e){r={error:e}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}this.interceptors.preResolution.setAll(e,i)}},e.prototype.executePostResolutionInterceptor=function(e,t,r){var n,i;if(this.interceptors.postResolution.has(e)){var o=[];try{for(var a=pa(this.interceptors.postResolution.getAll(e)),s=a.next();!s.done;s=a.next()){var l=s.value;"Once"!=l.options.frequency&&o.push(l),l.callback(e,t,r)}}catch(e){n={error:e}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}this.interceptors.postResolution.setAll(e,o)}},e.prototype.resolveRegistration=function(e,t){if(this.ensureNotDisposed(),e.options.lifecycle===QE.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var r,n=e.options.lifecycle===QE.Singleton,i=e.options.lifecycle===QE.ContainerScoped,o=n||i;return r=tk(e.provider)?e.provider.useValue:ek(e.provider)?o?e.instance||(e.instance=this.resolve(e.provider.useToken,t)):this.resolve(e.provider.useToken,t):YE(e.provider)?o?e.instance||(e.instance=this.construct(e.provider.useClass,t)):this.construct(e.provider.useClass,t):JE(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t),e.options.lifecycle===QE.ResolutionScoped&&t.scopedResolutions.set(e,r),r},e.prototype.resolveAll=function(e,t,r){var n=this;void 0===t&&(t=new ik),void 0===r&&(r=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&$E(e)){if(r)return[];throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"All"),i){var o=i.map((function(e){return n.resolveRegistration(e,t)}));return this.executePostResolutionInterceptor(e,o,"All"),o}var a=[this.construct(e,t)];return this.executePostResolutionInterceptor(e,a,"All"),a},e.prototype.isRegistered=function(e,t){return void 0===t&&(t=!1),this.ensureNotDisposed(),this._registry.has(e)||t&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},e.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},e.prototype.clearInstances=function(){var e,t;this.ensureNotDisposed();try{for(var r=pa(this._registry.entries()),n=r.next();!n.done;n=r.next()){var i=fa(n.value,2),o=i[0],a=i[1];this._registry.setAll(o,a.filter((function(e){return!tk(e.provider)})).map((function(e){return e.instance=void 0,e})))}}catch(t){e={error:t}}finally{try{n&&!n.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}},e.prototype.createChildContainer=function(){var t,r;this.ensureNotDisposed();var n=new e(this);try{for(var i=pa(this._registry.entries()),o=i.next();!o.done;o=i.next()){var a=fa(o.value,2),s=a[0],l=a[1];l.some((function(e){return e.options.lifecycle===QE.ContainerScoped}))&&n._registry.setAll(s,l.map((function(e){return e.options.lifecycle===QE.ContainerScoped?{provider:e.provider,options:e.options}:e})))}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return n},e.prototype.beforeResolution=function(e,t,r){void 0===r&&(r={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:t,options:r})},e.prototype.afterResolution=function(e,t,r){void 0===r&&(r={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:t,options:r})},e.prototype.dispose=function(){return ha(this,void 0,void 0,(function(){var e;return va(this,(function(t){switch(t.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach((function(t){var r=t.dispose();r&&e.push(r)})),[4,Promise.all(e)];case 1:return t.sent(),[2]}}))}))},e.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},e.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},e.prototype.construct=function(e,t){var r=this;if(e instanceof ZE)return e.createProxy((function(e){return r.resolve(e,t)}));var n,i=function(){var n=ck.get(e);if(!n||0===n.length){if(0===e.length)return new e;throw new Error('TypeInfo not known for "'+e.name+'"')}var i=n.map(r.resolveParams(t,e));return new(e.bind.apply(e,ga([void 0],i)))}();return"function"!=typeof(n=i).dispose||n.dispose.length>0||this.disposables.add(i),i},e.prototype.resolveParams=function(e,t){var r=this;return function(n,i){var o,a,s,l;try{return"object"==typeof(l=n)&&"token"in l&&"multiple"in l?XE(n)?n.multiple?(o=r.resolve(n.transform)).transform.apply(o,ga([r.resolveAll(n.token,new ik,n.isOptional)],n.transformArgs)):(a=r.resolve(n.transform)).transform.apply(a,ga([r.resolve(n.token,e,n.isOptional)],n.transformArgs)):n.multiple?r.resolveAll(n.token,new ik,n.isOptional):r.resolve(n.token,e,n.isOptional):XE(n)?(s=r.resolve(n.transform,e)).transform.apply(s,ga([r.resolve(n.token,e)],n.transformArgs)):r.resolve(n,e)}catch(e){throw new Error(ok(t,i,e))}}},e.prototype.ensureNotDisposed=function(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")},e}(),hk=new dk;function vk(e){return function(e){ck.set(e,function(e){var t=Reflect.getMetadata("design:paramtypes",e)||[],r=Reflect.getOwnMetadata("injectionTokens",e)||{};return Object.keys(r).forEach((function(e){t[+e]=r[e]})),t}(e))}}if("undefined"==typeof Reflect||!Reflect.getMetadata)throw new Error("tsyringe requires a reflect polyfill. Please add 'import \"reflect-metadata\"' to the top of your entry point.");class pk{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.attrId="",this.attrValues=[],Object.assign(e)}}da([fm({type:By.ObjectIdentifier})],pk.prototype,"attrId",void 0),da([fm({type:By.Any,repeated:"set"})],pk.prototype,"attrValues",void 0);var fk,gk=ak=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,ak.prototype)}};gk=ak=da([pm({type:_y.Sequence,itemType:pk})],gk);var yk=fk=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,fk.prototype)}};yk=fk=da([pm({type:_y.Sequence,itemType:vS})],yk);class mk{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.certId="",this.certValue=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier})],mk.prototype,"certId",void 0),da([fm({type:By.Any,context:0})],mk.prototype,"certValue",void 0);class wk{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.crlId="",this.crltValue=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier})],wk.prototype,"crlId",void 0),da([fm({type:By.Any,context:0})],wk.prototype,"crltValue",void 0);class bk extends Ry{}let Sk=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.encryptionAlgorithm=new sb,this.encryptedData=new bk,Object.assign(this,e)}};var Ek,kk;da([fm({type:sb})],Sk.prototype,"encryptionAlgorithm",void 0),da([fm({type:bk})],Sk.prototype,"encryptedData",void 0),function(e){e[e.v1=0]="v1"}(kk||(kk={}));class xk extends Ry{}var Ak=Ek=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,Ek.prototype)}};Ak=Ek=da([pm({type:_y.Sequence,itemType:Jw})],Ak);class Ck{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=kk.v1,this.privateKeyAlgorithm=new sb,this.privateKey=new xk,Object.assign(this,e)}}da([fm({type:By.Integer})],Ck.prototype,"version",void 0),da([fm({type:sb})],Ck.prototype,"privateKeyAlgorithm",void 0),da([fm({type:xk})],Ck.prototype,"privateKey",void 0),da([fm({type:Ak,implicit:!0,context:0,optional:!0})],Ck.prototype,"attributes",void 0);var Ik=class extends Ck{};Ik=da([pm({type:_y.Sequence})],Ik);var Tk,Pk=class extends Sk{};Pk=da([pm({type:_y.Sequence})],Pk);class _k{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.secretTypeId="",this.secretValue=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier})],_k.prototype,"secretTypeId",void 0),da([fm({type:By.Any,context:0})],_k.prototype,"secretValue",void 0);class Bk{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.mac=new VE,this.macSalt=new Ry,this.iterations=1,Object.assign(this,e)}}da([fm({type:VE})],Bk.prototype,"mac",void 0),da([fm({type:Ry})],Bk.prototype,"macSalt",void 0),da([fm({type:By.Integer,defaultValue:1})],Bk.prototype,"iterations",void 0);class Nk{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=3,this.authSafe=new vS,this.macData=new Bk,Object.assign(this,e)}}da([fm({type:By.Integer})],Nk.prototype,"version",void 0),da([fm({type:vS})],Nk.prototype,"authSafe",void 0),da([fm({type:Bk,optional:!0})],Nk.prototype,"macData",void 0);class Dk{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.bagId="",this.bagValue=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:By.ObjectIdentifier})],Dk.prototype,"bagId",void 0),da([fm({type:By.Any,context:0})],Dk.prototype,"bagValue",void 0),da([fm({type:pk,repeated:"set",optional:!0})],Dk.prototype,"bagAttributes",void 0);var Rk,Ok,Lk,Mk=Tk=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,Tk.prototype)}};Mk=Tk=da([pm({type:_y.Sequence,itemType:Dk})],Mk);var Uk="1.2.840.113549.1.9",Fk="".concat(Uk,".7"),zk="".concat(Uk,".14"),jk=class extends Em{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{})}toString(){return this.ia5String||super.toString()}};da([fm({type:By.IA5String})],jk.prototype,"ia5String",void 0),jk=da([pm({type:_y.Choice})],jk);var Vk=class extends vS{};Vk=da([pm({type:_y.Sequence})],Vk);var qk=class extends Nk{};qk=da([pm({type:_y.Sequence})],qk);var Hk=class extends Sk{};Hk=da([pm({type:_y.Sequence})],Hk);var Kk=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.value=e}toString(){return this.value}};da([fm({type:By.IA5String})],Kk.prototype,"value",void 0),Kk=da([pm({type:_y.Choice})],Kk);var Wk=class extends jk{};Wk=da([pm({type:_y.Choice})],Wk);var Gk=class extends Em{};Gk=da([pm({type:_y.Choice})],Gk);var Qk=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Date;this.value=e}};da([fm({type:By.GeneralizedTime})],Qk.prototype,"value",void 0),Qk=da([pm({type:_y.Choice})],Qk);var Yk=class extends Em{};Yk=da([pm({type:_y.Choice})],Yk);var Jk=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"M";this.value=e}toString(){return this.value}};da([fm({type:By.PrintableString})],Jk.prototype,"value",void 0),Jk=da([pm({type:_y.Choice})],Jk);var Zk=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.value=e}toString(){return this.value}};da([fm({type:By.PrintableString})],Zk.prototype,"value",void 0),Zk=da([pm({type:_y.Choice})],Zk);var $k=class extends Zk{};$k=da([pm({type:_y.Choice})],$k);var Xk=class extends Em{};Xk=da([pm({type:_y.Choice})],Xk);var ex=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.value=e}toString(){return this.value}};da([fm({type:By.ObjectIdentifier})],ex.prototype,"value",void 0),ex=da([pm({type:_y.Choice})],ex);var tx=class extends cb{};tx=da([pm({type:_y.Choice})],tx);var rx=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.value=e}toString(){return this.value.toString()}};da([fm({type:By.Integer})],rx.prototype,"value",void 0),rx=da([pm({type:_y.Choice})],rx);var nx=class extends Bb{};nx=da([pm({type:_y.Sequence})],nx);var ix=class extends Em{};ix=da([pm({type:_y.Choice})],ix);var ox=Rk=class extends pb{constructor(e){super(e),Object.setPrototypeOf(this,Rk.prototype)}};ox=Rk=da([pm({type:_y.Sequence})],ox);var ax=Ok=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,Ok.prototype)}};ax=Ok=da([pm({type:_y.Set,itemType:Pb})],ax);var sx=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.value=e}toString(){return this.value}};da([fm({type:By.BmpString})],sx.prototype,"value",void 0),sx=da([pm({type:_y.Choice})],sx);var lx=class extends sb{};lx=da([pm({type:_y.Sequence})],lx);var ux,cx=Lk=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,Lk.prototype)}};cx=Lk=da([pm({type:_y.Sequence,itemType:lx})],cx);var dx=ux=class extends wm{constructor(e){super(e),Object.setPrototypeOf(this,ux.prototype)}};dx=ux=da([pm({type:_y.Sequence,itemType:Jw})],dx);class hx{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=0,this.subject=new Im,this.subjectPKInfo=new lb,this.attributes=new dx,Object.assign(this,e)}}da([fm({type:By.Integer})],hx.prototype,"version",void 0),da([fm({type:Im})],hx.prototype,"subject",void 0),da([fm({type:lb})],hx.prototype,"subjectPKInfo",void 0),da([fm({type:dx,implicit:!0,context:0})],hx.prototype,"attributes",void 0);class vx{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.certificationRequestInfo=new hx,this.signatureAlgorithm=new sb,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}da([fm({type:hx})],vx.prototype,"certificationRequestInfo",void 0),da([fm({type:sb})],vx.prototype,"signatureAlgorithm",void 0),da([fm({type:By.BitString})],vx.prototype,"signature",void 0);var px="crypto.algorithm";var fx,gx="crypto.algorithmProvider";hk.registerSingleton(gx,class{getAlgorithms(){return hk.resolveAll(px)}toAsnAlgorithm(e){for(var r of(t({},e),this.getAlgorithms())){var n=r.toAsnAlgorithm(e);if(n)return n}if(/^[0-9.]+$/.test(e.name)){var i=new sb({algorithm:e.name});if("parameters"in e){var o=e;i.parameters=o.parameters}return i}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(var t of this.getAlgorithms()){var r=t.toWebAlgorithm(e);if(r)return r}return{name:e.algorithm,parameters:e.parameters}}});var yx="1.3.36.3.3.2.8.1.1",mx="".concat(yx,".1"),wx="".concat(yx,".2"),bx="".concat(yx,".3"),Sx="".concat(yx,".4"),Ex="".concat(yx,".5"),kx="".concat(yx,".6"),xx="".concat(yx,".7"),Ax="".concat(yx,".8"),Cx="".concat(yx,".9"),Ix="".concat(yx,".10"),Tx="".concat(yx,".11"),Px="".concat(yx,".12"),_x="".concat(yx,".13"),Bx="".concat(yx,".14"),Nx="brainpoolP160r1",Dx="brainpoolP160t1",Rx="brainpoolP192r1",Ox="brainpoolP192t1",Lx="brainpoolP224r1",Mx="brainpoolP224t1",Ux="brainpoolP256r1",Fx="brainpoolP256t1",zx="brainpoolP320r1",jx="brainpoolP320t1",Vx="brainpoolP384r1",qx="brainpoolP384t1",Hx="brainpoolP512r1",Kx="brainpoolP512t1",Wx="ECDSA",Gx=fx=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===Wx.toLowerCase())if("hash"in e)switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return iE;case"sha-256":return oE;case"sha-384":return aE;case"sha-512":return sE}else if("namedCurve"in e){var t="";switch(e.namedCurve){case"P-256":t=eE;break;case"K-256":t=fx.SECP256K1;break;case"P-384":t=tE;break;case"P-521":t=rE;break;case Nx:t=mx;break;case Dx:t=wx;break;case Rx:t=bx;break;case Ox:t=Sx;break;case Lx:t=Ex;break;case Mx:t=kx;break;case Ux:t=xx;break;case Fx:t=Ax;break;case zx:t=Cx;break;case jx:t=Ix;break;case Vx:t=Tx;break;case qx:t=Px;break;case Hx:t=_x;break;case Kx:t=Bx}if(t)return new sb({algorithm:QS,parameters:bm.serialize(new hE({namedCurve:t}))})}return null}toWebAlgorithm(e){switch(e.algorithm){case YS:return{name:Wx,hash:{name:"SHA-1"}};case ZS:return{name:Wx,hash:{name:"SHA-256"}};case $S:return{name:Wx,hash:{name:"SHA-384"}};case XS:return{name:Wx,hash:{name:"SHA-512"}};case QS:if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(bm.parse(e.parameters,hE).namedCurve){case eE:return{name:Wx,namedCurve:"P-256"};case fx.SECP256K1:return{name:Wx,namedCurve:"K-256"};case tE:return{name:Wx,namedCurve:"P-384"};case rE:return{name:Wx,namedCurve:"P-521"};case mx:return{name:Wx,namedCurve:Nx};case wx:return{name:Wx,namedCurve:Dx};case bx:return{name:Wx,namedCurve:Rx};case Sx:return{name:Wx,namedCurve:Ox};case Ex:return{name:Wx,namedCurve:Lx};case kx:return{name:Wx,namedCurve:Mx};case xx:return{name:Wx,namedCurve:Ux};case Ax:return{name:Wx,namedCurve:Fx};case Cx:return{name:Wx,namedCurve:zx};case Ix:return{name:Wx,namedCurve:jx};case Tx:return{name:Wx,namedCurve:Vx};case Px:return{name:Wx,namedCurve:qx};case _x:return{name:Wx,namedCurve:Hx};case Bx:return{name:Wx,namedCurve:Kx}}}return null}};Gx.SECP256K1="1.3.132.0.10",Gx=fx=da([vk()],Gx),hk.registerSingleton(px,Gx);var Qx,Yx=Symbol("name"),Jx=Symbol("value");class Zx{constructor(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";for(var n in this[Yx]=e,this[Jx]=r,t)this[n]=t[n]}}Zx.NAME=Yx,Zx.VALUE=Jx;class $x{static toString(e){var t=this.items[e];return t||e}}$x.items={[PE]:"sha1",[_E]:"sha224",[BE]:"sha256",[NE]:"sha384",[DE]:"sha512",[gE]:"rsaEncryption",[EE]:"sha1WithRSAEncryption",[kE]:"sha224WithRSAEncryption",[xE]:"sha256WithRSAEncryption",[AE]:"sha384WithRSAEncryption",[CE]:"sha512WithRSAEncryption",[QS]:"ecPublicKey",[YS]:"ecdsaWithSHA1",[JS]:"ecdsaWithSHA224",[ZS]:"ecdsaWithSHA256",[$S]:"ecdsaWithSHA384",[XS]:"ecdsaWithSHA512",[Cw]:"TLS WWW server authentication",[Iw]:"TLS WWW client authentication",[Tw]:"Code Signing",[Pw]:"E-mail Protection",[_w]:"Time Stamping",[Bw]:"OCSP Signing",[KS]:"Signed Data"};class Xx{static serialize(e){return this.serializeObj(e).join("\n")}static pad(){return"".padStart(2*(arguments.length>0&&void 0!==arguments[0]?arguments[0]:0)," ")}static serializeObj(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=[],n=this.pad(t++),i="",o=e[Zx.VALUE];for(var a in o&&(i=" ".concat(o)),r.push("".concat(n).concat(e[Zx.NAME],":").concat(i)),n=this.pad(t),e)if("symbol"!=typeof a){var s=e[a],l=a?"".concat(a,": "):"";if("string"==typeof s||"number"==typeof s||"boolean"==typeof s)r.push("".concat(n).concat(l).concat(s));else if(s instanceof Date)r.push("".concat(n).concat(l).concat(s.toUTCString()));else if(Array.isArray(s))for(var u of s)u[Zx.NAME]=a,r.push(...this.serializeObj(u,t));else if(s instanceof Zx)s[Zx.NAME]=a,r.push(...this.serializeObj(s,t));else if(Xp.BufferSourceConverter.isBufferSource(s))a?(r.push("".concat(n).concat(l)),r.push(...this.serializeBufferSource(s,t+1))):r.push(...this.serializeBufferSource(s,t));else{if(!("toTextObject"in s))throw new TypeError("Cannot serialize data in text format. Unsupported type.");var c=s.toTextObject();c[Zx.NAME]=a,r.push(...this.serializeObj(c,t))}}return r}static serializeBufferSource(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=this.pad(t),n=Xp.BufferSourceConverter.toUint8Array(e),i=[],o=0;o<n.length;){for(var a=[],s=0;s<16&&o<n.length;s++){8===s&&a.push("");var l=n[o++].toString(16).padStart(2,"0");a.push(l)}i.push("".concat(r).concat(a.join(" ")))}return i}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}}Xx.oidSerializer=$x,Xx.algorithmSerializer=class{static toTextObject(e){var t=new Zx("Algorithm Identifier",{},$x.toString(e.algorithm));if(e.parameters)if(e.algorithm===QS){var r=(new Gx).toWebAlgorithm(e);r&&"namedCurve"in r?t["Named Curve"]=r.namedCurve:t.Parameters=e.parameters}else t.Parameters=e.parameters;return t}};class eA{constructor(){if(1===arguments.length){var e=arguments.length<=0?void 0:arguments[0];this.rawData=bm.serialize(e),this.onInit(e)}else{var t=bm.parse(arguments.length<=0?void 0:arguments[0],arguments.length<=1?void 0:arguments[1]);this.rawData=Xp.BufferSourceConverter.toArrayBuffer(arguments.length<=0?void 0:arguments[0]),this.onInit(t)}}equal(e){return e instanceof eA&&Xp.isEqual(e.rawData,this.rawData)}toString(){switch(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"text"){case"asn":return bm.toString(this.rawData);case"text":return Xx.serialize(this.toTextObject());case"hex":return Xp.Convert.ToHex(this.rawData);case"base64":return Xp.Convert.ToBase64(this.rawData);case"base64url":return Xp.Convert.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){var e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new Zx(this.getTextName(),{},e)}}eA.NAME="ASN";class tA extends eA{constructor(){super(Xp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])?Xp.BufferSourceConverter.toArrayBuffer(arguments.length<=0?void 0:arguments[0]):bm.serialize(new hb({extnID:arguments.length<=0?void 0:arguments[0],critical:arguments.length<=1?void 0:arguments[1],extnValue:new Ry(Xp.BufferSourceConverter.toArrayBuffer(arguments.length<=2?void 0:arguments[2]))})),hb)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){var e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){var e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[Zx.NAME]===tA.NAME&&(e[Zx.NAME]=$x.toString(this.type)),e}}class rA{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&void 0!==e.extractable}constructor(){this.items=new Map,this[Qx]="CryptoProvider","undefined"!=typeof self&&"undefined"!=typeof crypto?this.set(rA.DEFAULT,crypto):"undefined"!=typeof global&&global.crypto&&global.crypto.subtle&&this.set(rA.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,t){return this.items.forEach(e,t)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:rA.DEFAULT,t=this.items.get(e.toLowerCase());if(!t)throw new Error("Cannot get Crypto by name '".concat(e,"'"));return t}set(e,t){if("string"==typeof e){if(!t)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),t)}else this.items.set(rA.DEFAULT,e);return this}}Qx=Symbol.toStringTag,rA.DEFAULT="default";var nA=new rA,iA=/^[0-2](?:\.[1-9][0-9]*)+$/;class oA{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(var t in this.items={},e)this.register(t,e[t])}get(e){return this.items[e]||null}findId(e){return t=e,new RegExp(iA).test(t)?e:this.get(e);var t}register(e,t){this.items[e]=t,this.items[t]=e}}var aA=new oA;function sA(e,t){return"\\".concat(Xp.Convert.ToHex(Xp.Convert.FromUtf8String(t)).toUpperCase())}aA.register("CN","2.5.4.3"),aA.register("L","2.5.4.7"),aA.register("ST","2.5.4.8"),aA.register("O","2.5.4.10"),aA.register("OU","2.5.4.11"),aA.register("C","2.5.4.6"),aA.register("DC","0.9.2342.19200300.100.1.25"),aA.register("E","1.2.840.113549.1.9.1"),aA.register("G","2.5.4.42"),aA.register("I","2.5.4.43"),aA.register("SN","2.5.4.4"),aA.register("T","2.5.4.12");class lA{static isASCII(e){for(var t=0;t<e.length;t++){if(e.charCodeAt(t)>255)return!1}return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};for(var r in this.extraNames=new oA,this.asn=new Im,t)if(Object.prototype.hasOwnProperty.call(t,r)){var n=t[r];this.extraNames.register(r,n)}"string"==typeof e?this.asn=this.fromString(e):e instanceof Im?this.asn=e:Xp.BufferSourceConverter.isBufferSource(e)?this.asn=bm.parse(e,Im):this.asn=this.fromJSON(e)}getField(e){var t=this.extraNames.findId(e)||aA.findId(e),r=[];for(var n of this.asn)for(var i of n)i.type===t&&r.push(i.value.toString());return r}getName(e){return this.extraNames.get(e)||aA.get(e)}toString(){return this.asn.map((e=>e.map((e=>{var t=this.getName(e.type)||e.type,r=e.value.anyValue?"#".concat(Xp.Convert.ToHex(e.value.anyValue)):e.value.toString().replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,sA);return"".concat(t,"=").concat(r)})).join("+"))).join(", ")}toJSON(){var e,t=[];for(var r of this.asn){var n={};for(var i of r){var o=this.getName(i.type)||i.type;null!==(e=n[o])&&void 0!==e||(n[o]=[]),n[o].push(i.value.anyValue?"#".concat(Xp.Convert.ToHex(i.value.anyValue)):i.value.toString())}t.push(n)}return t}fromString(e){for(var t=new Im,r=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g,n=null,i=",";n=r.exec("".concat(e,","));){var[,o,a]=n,s=a[a.length-1];","!==s&&"+"!==s||(a=a.slice(0,a.length-1),n[3]=s);var l=n[3];o=this.getTypeOid(o);var u=this.createAttribute(o,a);"+"===i?t[t.length-1].push(u):t.push(new Am([u])),i=l}return t}fromJSON(e){var t=new Im;for(var r of e){var n=new Am;for(var i in r){var o=this.getTypeOid(i),a=r[i];for(var s of a){var l=this.createAttribute(o,s);n.push(l)}}t.push(n)}return t}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error("Cannot get OID for name type '".concat(e,"'"));return e}createAttribute(e,t){var r=new xm({type:e});if("object"==typeof t)for(var n in t)switch(n){case"ia5String":r.value.ia5String=t[n];break;case"utf8String":r.value.utf8String=t[n];break;case"universalString":r.value.universalString=t[n];break;case"bmpString":r.value.bmpString=t[n];break;case"printableString":r.value.printableString=t[n]}else if("#"===t[0])r.value.anyValue=Xp.Convert.FromHex(t.slice(1));else{var i=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=i:lA.isPrintableString(i)?r.value.printableString=i:r.value.utf8String=i}return r}processStringValue(e){var t=/"(.*?[^\\])?"/.exec(e);return t&&(e=t[1]),e.replace(/\\0a/gi,"\n").replace(/\\0d/gi,"\r").replace(/\\0g/gi,"\t").replace(/\\(.)/g,"$1")}toArrayBuffer(){return bm.serialize(this.asn)}getThumbprint(){var e=arguments,t=this;return r((function*(){var r,n,i="SHA-1";return e.length>=1&&!(null===(r=e.length<=0?void 0:e[0])||void 0===r?void 0:r.subtle)?(i=(e.length<=0?void 0:e[0])||i,n=(e.length<=1?void 0:e[1])||nA.get()):n=(e.length<=0?void 0:e[0])||nA.get(),yield n.subtle.digest(i,t.toArrayBuffer())}))()}}var uA="Cannot initialize GeneralName from ASN.1 data.",cA="".concat(uA," Unsupported string format in use."),dA="".concat(uA," Value doesn't match to GUID regular expression."),hA=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,vA="1.3.6.1.4.1.311.25.1",pA="1.3.6.1.4.1.311.20.2.3",fA="dns",gA="dn",yA="email",mA="ip",wA="url",bA="guid",SA="upn",EA="id";class kA extends eA{constructor(){var e;if(2===arguments.length)switch(arguments.length<=0?void 0:arguments[0]){case gA:var t=new lA(arguments.length<=1?void 0:arguments[1]).toArrayBuffer(),r=bm.parse(t,Im);e=new Bm({directoryName:r});break;case fA:e=new Bm({dNSName:arguments.length<=1?void 0:arguments[1]});break;case yA:e=new Bm({rfc822Name:arguments.length<=1?void 0:arguments[1]});break;case bA:var n=new RegExp(hA,"i").exec(arguments.length<=1?void 0:arguments[1]);if(!n)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");var i=n.slice(1).map(((e,t)=>t<3?Xp.Convert.ToHex(new Uint8Array(Xp.Convert.FromHex(e)).reverse()):e)).join("");e=new Bm({otherName:new Pm({typeId:vA,value:bm.serialize(new Ry(Xp.Convert.FromHex(i)))})});break;case mA:e=new Bm({iPAddress:arguments.length<=1?void 0:arguments[1]});break;case EA:e=new Bm({registeredID:arguments.length<=1?void 0:arguments[1]});break;case SA:e=new Bm({otherName:new Pm({typeId:pA,value:bm.serialize(Ky.toASN(arguments.length<=1?void 0:arguments[1]))})});break;case wA:e=new Bm({uniformResourceIdentifier:arguments.length<=1?void 0:arguments[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else e=Xp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])?bm.parse(arguments.length<=0?void 0:arguments[0],Bm):arguments.length<=0?void 0:arguments[0];super(e)}onInit(e){if(null!=e.dNSName)this.type=fA,this.value=e.dNSName;else if(null!=e.rfc822Name)this.type=yA,this.value=e.rfc822Name;else if(null!=e.iPAddress)this.type=mA,this.value=e.iPAddress;else if(null!=e.uniformResourceIdentifier)this.type=wA,this.value=e.uniformResourceIdentifier;else if(null!=e.registeredID)this.type=EA,this.value=e.registeredID;else if(null!=e.directoryName)this.type=gA,this.value=new lA(e.directoryName).toString();else{if(null==e.otherName)throw new Error(cA);if(e.otherName.typeId===vA){this.type=bA;var t=bm.parse(e.otherName.value,Ry),r=new RegExp(hA,"i").exec(Xp.Convert.ToHex(t));if(!r)throw new Error(dA);this.value=r.slice(1).map(((e,t)=>t<3?Xp.Convert.ToHex(new Uint8Array(Xp.Convert.FromHex(e)).reverse()):e)).join("-")}else{if(e.otherName.typeId!==pA)throw new Error(cA);this.type=SA,this.value=bm.parse(e.otherName.value,Em).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){var e;switch(this.type){case gA:case fA:case bA:case mA:case EA:case SA:case wA:e=this.type.toUpperCase();break;case yA:e="Email";break;default:throw new Error("Unsupported GeneralName type")}var t=this.value;return this.type===EA&&(t=$x.toString(t)),new Zx(e,void 0,t)}}class xA extends eA{constructor(e){var t;if(e instanceof $m)t=e;else if(Array.isArray(e)){var r=[];for(var n of e)if(n instanceof Bm)r.push(n);else{var i=bm.parse(new kA(n.type,n.value).rawData,Bm);r.push(i)}t=new $m(r)}else{if(!Xp.BufferSourceConverter.isBufferSource(e))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");t=bm.parse(e,$m)}super(t)}onInit(e){var t=[];for(var r of e){var n=null;try{n=new kA(r)}catch(e){continue}t.push(n)}this.items=t}toJSON(){return this.items.map((e=>e.toJSON()))}toTextObject(){var e=super.toTextObjectEmpty();for(var t of this.items){var r=t.toTextObject(),n=e[r[Zx.NAME]];Array.isArray(n)||(n=[],e[r[Zx.NAME]]=n),n.push(r)}return e}}xA.NAME="GeneralNames";var AA,CA,IA="-{5}",TA="\\n",PA="[^".concat(TA,"]+"),_A="".concat(IA,"BEGIN (").concat(PA,"(?=").concat(IA,"))").concat(IA),BA="".concat(IA,"END \\1").concat(IA),NA="\\n",DA="[^:".concat(TA,"]+"),RA="(?:[^".concat(TA,"]+").concat(NA,"(?: +[^").concat(TA,"]+").concat(NA,")*)"),OA="(?:".concat("[a-zA-Z0-9=+/]+").concat(NA,")+"),LA="".concat(_A).concat(NA,"(?:((?:").concat(DA,": ").concat(RA,")+))?").concat(NA,"?(").concat(OA,")").concat(BA);class MA{static isPem(e){return"string"==typeof e&&new RegExp(LA,"g").test(e)}static decodeWithHeaders(e){e=e.replace(/\r/g,"");for(var t=new RegExp(LA,"g"),r=[],n=null;n=t.exec(e);){var i=n[3].replace(new RegExp("[".concat(TA,"]+"),"g"),""),o={type:n[1],headers:[],rawData:Xp.Convert.FromBase64(i)},a=n[2];if(a){var s=a.split(new RegExp(NA,"g")),l=null;for(var u of s){var[c,d]=u.split(/:(.*)/);if(void 0===d){if(!l)throw new Error("Cannot parse PEM string. Incorrect header value");l.value+=c.trim()}else l&&o.headers.push(l),l={key:c,value:d.trim()}}l&&o.headers.push(l)}r.push(o)}return r}static decode(e){return this.decodeWithHeaders(e).map((e=>e.rawData))}static decodeFirst(e){var t=this.decode(e);if(!t.length)throw new RangeError("PEM string doesn't contain any objects");return t[0]}static encode(e,t){if(Array.isArray(e)){var r=new Array;return t?e.forEach((e=>{if(!Xp.BufferSourceConverter.isBufferSource(e))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");r.push(this.encodeStruct({type:t,rawData:Xp.BufferSourceConverter.toArrayBuffer(e)}))})):e.forEach((e=>{if(!("type"in e))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");r.push(this.encodeStruct(e))})),r.join("\n")}if(!t)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:t,rawData:Xp.BufferSourceConverter.toArrayBuffer(e)})}static encodeStruct(e){var t,r=e.type.toLocaleUpperCase(),n=[];if(n.push("-----BEGIN ".concat(r,"-----")),null===(t=e.headers)||void 0===t?void 0:t.length){for(var i of e.headers)n.push("".concat(i.key,": ").concat(i.value));n.push("")}for(var o,a=Xp.Convert.ToBase64(e.rawData),s=0,l=Array();s<a.length&&(a.length-s<64?o=a.substring(s):(o=a.substring(s,s+64),s+=64),0!==o.length)&&(l.push(o),!(o.length<64)););return n.push(...l),n.push("-----END ".concat(r,"-----")),n.join("\n")}}MA.CertificateTag="CERTIFICATE",MA.CrlTag="CRL",MA.CertificateRequestTag="CERTIFICATE REQUEST",MA.PublicKeyTag="PUBLIC KEY",MA.PrivateKeyTag="PRIVATE KEY";class UA extends eA{static isAsnEncoded(e){return Xp.BufferSourceConverter.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e){if(MA.isPem(e))return MA.decode(e)[0];if(Xp.Convert.isHex(e))return Xp.Convert.FromHex(e);if(Xp.Convert.isBase64(e))return Xp.Convert.FromBase64(e);if(Xp.Convert.isBase64Url(e))return Xp.Convert.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}var t=Xp.Convert.ToBinary(e);return MA.isPem(t)?MA.decode(t)[0]:Xp.Convert.isHex(t)?Xp.Convert.FromHex(t):Xp.Convert.isBase64(t)?Xp.Convert.FromBase64(t):Xp.Convert.isBase64Url(t)?Xp.Convert.FromBase64Url(t):Xp.BufferSourceConverter.toArrayBuffer(e)}constructor(){UA.isAsnEncoded(arguments.length<=0?void 0:arguments[0])?super(UA.toArrayBuffer(arguments.length<=0?void 0:arguments[0]),arguments.length<=1?void 0:arguments[1]):super(arguments.length<=0?void 0:arguments[0])}toString(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"pem";return"pem"===e?MA.encode(this.rawData,this.tag):super.toString(e)}}class FA extends UA{static create(e){var t=arguments;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:nA.get();if(e instanceof FA)return e;if(rA.isCryptoKey(e)){if("public"!==e.type)throw new TypeError("Public key is required");var n=yield r.subtle.exportKey("spki",e);return new FA(n)}if(e.publicKey)return e.publicKey;if(Xp.BufferSourceConverter.isBufferSource(e))return new FA(e);throw new TypeError("Unsupported PublicKeyType")}))()}constructor(e){UA.isAsnEncoded(e)?super(e,lb):super(e),this.tag=MA.PublicKeyTag}export(){var e=arguments,n=this;return r((function*(){var r,i=["verify"],o=t({hash:"SHA-256"},n.algorithm);e.length>1?(o=(e.length<=0?void 0:e[0])||o,i=(e.length<=1?void 0:e[1])||i,r=(e.length<=2?void 0:e[2])||nA.get()):r=(e.length<=0?void 0:e[0])||nA.get();var a=n.rawData,s=bm.parse(n.rawData,lb);return s.algorithm.algorithm===wE&&(a=function(e,t){return e.algorithm=new sb({algorithm:gE,parameters:null}),t=bm.serialize(e),t}(s,a)),r.subtle.importKey("spki",a,o,!0,i)}))()}onInit(e){var t=hk.resolve(gx),r=this.algorithm=t.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===gE){var n=bm.parse(e.subjectPublicKey,GE),i=Xp.BufferSourceConverter.toUint8Array(n.modulus);r.publicExponent=Xp.BufferSourceConverter.toUint8Array(n.publicExponent),r.modulusLength=(i[0]?i:i.slice(1)).byteLength<<3}}getThumbprint(){var e=arguments,t=this;return r((function*(){var r,n,i="SHA-1";return e.length>=1&&!(null===(r=e.length<=0?void 0:e[0])||void 0===r?void 0:r.subtle)?(i=(e.length<=0?void 0:e[0])||i,n=(e.length<=1?void 0:e[1])||nA.get()):n=(e.length<=0?void 0:e[0])||nA.get(),yield n.subtle.digest(i,t.rawData)}))()}getKeyIdentifier(){var e=arguments,t=this;return r((function*(){var r,n="SHA-1";1===e.length?"string"==typeof(e.length<=0?void 0:e[0])?(n=e.length<=0?void 0:e[0],r=nA.get()):r=e.length<=0?void 0:e[0]:2===e.length?(n=e.length<=0?void 0:e[0],r=e.length<=1?void 0:e[1]):r=nA.get();var i=bm.parse(t.rawData,lb);return yield r.subtle.digest(n,i.subjectPublicKey)}))()}toTextObject(){var e=this.toTextObjectEmpty(),t=bm.parse(this.rawData,lb);if(e.Algorithm=Xx.serializeAlgorithm(t.algorithm),t.algorithm.algorithm===QS)e["EC Point"]=t.subjectPublicKey;else e["Raw Data"]=t.subjectPublicKey;return e}}class zA extends tA{static create(e){var t=arguments;return r((function*(){var r=t.length>1&&void 0!==t[1]&&t[1],n=t.length>2&&void 0!==t[2]?t[2]:nA.get();if("name"in e&&"serialNumber"in e)return new zA(e,r);var i=yield FA.create(e,n),o=yield i.getKeyIdentifier(n);return new zA(Xp.Convert.ToHex(o),r)}))()}constructor(){if(Xp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0]))super(arguments.length<=0?void 0:arguments[0]);else if("string"==typeof(arguments.length<=0?void 0:arguments[0])){var e=new Gm({keyIdentifier:new Wm(Xp.Convert.FromHex(arguments.length<=0?void 0:arguments[0]))});super(Km,arguments.length<=1?void 0:arguments[1],bm.serialize(e))}else{var t=arguments.length<=0?void 0:arguments[0],r=t.name instanceof xA?bm.parse(t.name.rawData,$m):t.name,n=new Gm({authorityCertIssuer:r,authorityCertSerialNumber:Xp.Convert.FromHex(t.serialNumber)});super(Km,arguments.length<=1?void 0:arguments[1],bm.serialize(n))}}onInit(e){super.onInit(e);var t=bm.parse(e.extnValue,Gm);t.keyIdentifier&&(this.keyId=Xp.Convert.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?Xp.Convert.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){var e=this.toTextObjectWithoutValue(),t=bm.parse(this.value,Gm);return t.authorityCertIssuer&&(e["Authority Issuer"]=new xA(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}}zA.NAME="Authority Key Identifier";class jA extends tA{constructor(){if(Xp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var e=bm.parse(this.value,Jm);this.ca=e.cA,this.pathLength=e.pathLenConstraint}else{var t=new Jm({cA:arguments.length<=0?void 0:arguments[0],pathLenConstraint:arguments.length<=1?void 0:arguments[1]});super(Ym,arguments.length<=2?void 0:arguments[2],bm.serialize(t)),this.ca=arguments.length<=0?void 0:arguments[0],this.pathLength=arguments.length<=1?void 0:arguments[1]}}toTextObject(){var e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),void 0!==this.pathLength&&(e["Path Length"]=this.pathLength),e}}jA.NAME="Basic Constraints",function(e){e.serverAuth="1.3.6.1.5.5.7.3.1",e.clientAuth="1.3.6.1.5.5.7.3.2",e.codeSigning="1.3.6.1.5.5.7.3.3",e.emailProtection="1.3.6.1.5.5.7.3.4",e.timeStamping="1.3.6.1.5.5.7.3.8",e.ocspSigning="1.3.6.1.5.5.7.3.9"}(AA||(AA={}));class VA extends tA{constructor(){if(Xp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var e=bm.parse(this.value,Aw);this.usages=e.map((e=>e))}else{var t=new Aw(arguments.length<=0?void 0:arguments[0]);super(xw,arguments.length<=1?void 0:arguments[1],bm.serialize(t)),this.usages=arguments.length<=0?void 0:arguments[0]}}toTextObject(){var e=this.toTextObjectWithoutValue();return e[""]=this.usages.map((e=>$x.toString(e))).join(", "),e}}VA.NAME="Extended Key Usages",function(e){e[e.digitalSignature=1]="digitalSignature",e[e.nonRepudiation=2]="nonRepudiation",e[e.keyEncipherment=4]="keyEncipherment",e[e.dataEncipherment=8]="dataEncipherment",e[e.keyAgreement=16]="keyAgreement",e[e.keyCertSign=32]="keyCertSign",e[e.cRLSign=64]="cRLSign",e[e.encipherOnly=128]="encipherOnly",e[e.decipherOnly=256]="decipherOnly"}(CA||(CA={}));class qA extends tA{constructor(){if(Xp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var e=bm.parse(this.value,Fw);this.usages=e.toNumber()}else{var t=new Fw(arguments.length<=0?void 0:arguments[0]);super(Uw,arguments.length<=1?void 0:arguments[1],bm.serialize(t)),this.usages=arguments.length<=0?void 0:arguments[0]}}toTextObject(){var e=this.toTextObjectWithoutValue(),t=bm.parse(this.value,Fw);return e[""]=t.toJSON().join(", "),e}}qA.NAME="Key Usages";class HA extends tA{static create(e){var t=arguments;return r((function*(){var r=t.length>1&&void 0!==t[1]&&t[1],n=t.length>2&&void 0!==t[2]?t[2]:nA.get(),i=yield FA.create(e,n),o=yield i.getKeyIdentifier(n);return new HA(Xp.Convert.ToHex(o),r)}))()}constructor(){if(Xp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var e=bm.parse(this.value,rb);this.keyId=Xp.Convert.ToHex(e)}else{var t="string"==typeof(arguments.length<=0?void 0:arguments[0])?Xp.Convert.FromHex(arguments.length<=0?void 0:arguments[0]):arguments.length<=0?void 0:arguments[0],r=new rb(t);super(tb,arguments.length<=1?void 0:arguments[1],bm.serialize(r)),this.keyId=Xp.Convert.ToHex(t)}}toTextObject(){var e=this.toTextObjectWithoutValue(),t=bm.parse(this.value,rb);return e[""]=t,e}}HA.NAME="Subject Key Identifier";class KA extends tA{constructor(){Xp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])?super(arguments.length<=0?void 0:arguments[0]):super(Qw,arguments.length<=1?void 0:arguments[1],new xA((arguments.length<=0?void 0:arguments[0])||[]).rawData)}onInit(e){super.onInit(e);var t=bm.parse(e.extnValue,Yw);this.names=new xA(t)}toTextObject(){var e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(var r in t)e[r]=t[r];return e}}KA.NAME="Subject Alternative Name";class WA{static register(e,t){this.items.set(e,t)}static create(e){var t=new tA(e),r=this.items.get(t.type);return r?new r(e):t}}WA.items=new Map;class GA extends tA{constructor(){var e;if(Xp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var t=bm.parse(this.value,lw);this.policies=t.map((e=>e.policyIdentifier))}else{var r=arguments.length<=0?void 0:arguments[0],n=null!==(e=arguments.length<=1?void 0:arguments[1])&&void 0!==e&&e,i=new lw(r.map((e=>new sw({policyIdentifier:e}))));super(tw,n,bm.serialize(i)),this.policies=r}}toTextObject(){var e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map((e=>new Zx("",{},$x.toString(e)))),e}}GA.NAME="Certificate Policies",WA.register(tw,GA);class QA extends tA{constructor(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];if(Xp.BufferSourceConverter.isBufferSource(r[0]))super(r[0]);else if(Array.isArray(r[0])&&"string"==typeof r[0][0]){var i=r[0].map((e=>new gw({distributionPoint:new fw({fullName:[new Bm({uniformResourceIdentifier:e})]})}))),o=new mw(i);super(vw,r[1],bm.serialize(o))}else{var a=new mw(r[0]);super(vw,r[1],bm.serialize(a))}null!==(e=this.distributionPoints)&&void 0!==e||(this.distributionPoints=[])}onInit(e){super.onInit(e);var t=bm.parse(e.extnValue,mw);this.distributionPoints=t}toTextObject(){var e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map((e=>{var t,r={};return e.distributionPoint&&(r[""]=null===(t=e.distributionPoint.fullName)||void 0===t?void 0:t.map((e=>new kA(e).toString())).join(", ")),e.reasons&&(r.Reasons=e.reasons.toString()),e.cRLIssuer&&(r["CRL Issuer"]=e.cRLIssuer.map((e=>e.toString())).join(", ")),r})),e}}QA.NAME="CRL Distribution Points";class YA extends tA{constructor(){var e,t,r,n;if(Xp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0]))super(arguments.length<=0?void 0:arguments[0]);else if((arguments.length<=0?void 0:arguments[0])instanceof Hm){var i=new Hm(arguments.length<=0?void 0:arguments[0]);super(Vm,arguments.length<=1?void 0:arguments[1],bm.serialize(i))}else{var o=arguments.length<=0?void 0:arguments[0],a=new Hm;ZA(a,o,Mm,"ocsp"),ZA(a,o,Um,"caIssuers"),ZA(a,o,Fm,"timeStamping"),ZA(a,o,zm,"caRepository"),super(Vm,arguments.length<=1?void 0:arguments[1],bm.serialize(a))}null!==(e=this.ocsp)&&void 0!==e||(this.ocsp=[]),null!==(t=this.caIssuers)&&void 0!==t||(this.caIssuers=[]),null!==(r=this.timeStamping)&&void 0!==r||(this.timeStamping=[]),null!==(n=this.caRepository)&&void 0!==n||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],bm.parse(e.extnValue,Hm).forEach((e=>{switch(e.accessMethod){case Mm:this.ocsp.push(new kA(e.accessLocation));break;case Um:this.caIssuers.push(new kA(e.accessLocation));break;case Fm:this.timeStamping.push(new kA(e.accessLocation));break;case zm:this.caRepository.push(new kA(e.accessLocation))}}))}toTextObject(){var e=this.toTextObjectWithoutValue();return this.ocsp.length&&JA(e,"OCSP",this.ocsp),this.caIssuers.length&&JA(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&JA(e,"Time Stamping",this.timeStamping),this.caRepository.length&&JA(e,"CA Repository",this.caRepository),e}}function JA(e,t,r){if(1===r.length)e[t]=r[0].toTextObject();else{var n=new Zx("");r.forEach(((e,t)=>{var r=e.toTextObject(),i="".concat(r[Zx.NAME]," ").concat(t+1),o=n[i];Array.isArray(o)||(o=[],n[i]=o),o.push(r)})),e[t]=n}}function ZA(e,t,r,n){var i=t[n];i&&(Array.isArray(i)?i:[i]).forEach((t=>{"string"==typeof t&&(t=new kA("url",t)),e.push(new qm({accessMethod:r,accessLocation:bm.parse(t.rawData,Bm)}))}))}YA.NAME="Authority Info Access";class $A extends eA{constructor(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];if(Xp.BufferSourceConverter.isBufferSource(r[0]))e=Xp.BufferSourceConverter.toArrayBuffer(r[0]);else{var i=r[0],o=Array.isArray(r[1])?r[1].map((e=>Xp.BufferSourceConverter.toArrayBuffer(e))):[];e=bm.serialize(new Jw({type:i,values:o}))}super(e,Jw)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){var e=this.toTextObjectWithoutValue();return e.Value=this.values.map((e=>new Zx("",{"":e}))),e}toTextObjectWithoutValue(){var e=this.toTextObjectEmpty();return e[Zx.NAME]===$A.NAME&&(e[Zx.NAME]=$x.toString(this.type)),e}}$A.NAME="Attribute";class XA extends $A{constructor(){var e;if(Xp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0]))super(arguments.length<=0?void 0:arguments[0]);else{var t=new ix({printableString:arguments.length<=0?void 0:arguments[0]});super(Fk,[bm.serialize(t)])}null!==(e=this.password)&&void 0!==e||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){var t=bm.parse(this.values[0],ix);this.password=t.toString()}}toTextObject(){var e=this.toTextObjectWithoutValue();return e[Zx.VALUE]=this.password,e}}XA.NAME="Challenge Password";class eC extends $A{constructor(){var e;if(Xp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0]))super(arguments.length<=0?void 0:arguments[0]);else{var t=arguments.length<=0?void 0:arguments[0],r=new pb;for(var n of t)r.push(bm.parse(n.rawData,hb));super(zk,[bm.serialize(r)])}null!==(e=this.items)&&void 0!==e||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){var t=bm.parse(this.values[0],pb);this.items=t.map((e=>WA.create(bm.serialize(e))))}}toTextObject(){var e=this.toTextObjectWithoutValue(),t=this.items.map((e=>e.toTextObject()));for(var r of t)e[r[Zx.NAME]]=r;return e}}eC.NAME="Extensions";class tC{static register(e,t){this.items.set(e,t)}static create(e){var t=new $A(e),r=this.items.get(t.type);return r?new r(e):t}}tC.items=new Map;var rC,nC="crypto.signatureFormatter";var iC=rC=class{static createPssParams(e,t){var r=rC.getHashAlgorithm(e);return r?new jE({hashAlgorithm:r,maskGenAlgorithm:new sb({algorithm:RE,parameters:bm.serialize(r)}),saltLength:t}):null}static getHashAlgorithm(e){var t=hk.resolve(gx);return"string"==typeof e?t.toAsnAlgorithm({name:e}):"object"==typeof e&&e&&"name"in e?t.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if(!("hash"in e))return new sb({algorithm:gE,parameters:null});var t;if("string"==typeof e.hash)t=e.hash;else{if(!e.hash||"object"!=typeof e.hash||!("name"in e.hash)||"string"!=typeof e.hash.name)throw new Error("Cannot get hash algorithm name");t=e.hash.name.toUpperCase()}switch(t.toLowerCase()){case"sha-1":return new sb({algorithm:EE,parameters:null});case"sha-256":return new sb({algorithm:xE,parameters:null});case"sha-384":return new sb({algorithm:AE,parameters:null});case"sha-512":return new sb({algorithm:CE,parameters:null})}break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e)||"number"!=typeof e.saltLength)throw new Error("Cannot get 'saltLength' from 'alg' argument");var r=rC.createPssParams(e.hash,e.saltLength);if(!r)throw new Error("Cannot create PSS parameters");return new sb({algorithm:wE,parameters:bm.serialize(r)})}return new sb({algorithm:wE,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case gE:return{name:"RSASSA-PKCS1-v1_5"};case EE:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case xE:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case AE:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case CE:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case wE:if(e.parameters){var t=bm.parse(e.parameters,jE);return{name:"RSA-PSS",hash:hk.resolve(gx).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:"RSA-PSS"}}return null}};iC=rC=da([vk()],iC),hk.registerSingleton(px,iC);var oC=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new sb({algorithm:PE});case"sha-256":return new sb({algorithm:BE});case"sha-384":return new sb({algorithm:NE});case"sha-512":return new sb({algorithm:DE})}return null}toWebAlgorithm(e){switch(e.algorithm){case PE:return{name:"SHA-1"};case BE:return{name:"SHA-256"};case NE:return{name:"SHA-384"};case DE:return{name:"SHA-512"}}return null}};oC=da([vk()],oC),hk.registerSingleton(px,oC);class aC{addPadding(e,t){var r=Xp.BufferSourceConverter.toUint8Array(t),n=new Uint8Array(e);return n.set(r,e-r.length),n}removePadding(e){for(var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=Xp.BufferSourceConverter.toUint8Array(e),n=0;n<r.length;n++)if(r[n]){r=r.slice(n);break}if(t&&r[0]>127){var i=new Uint8Array(r.length+1);return i.set(r,1),i.buffer}return r.buffer}toAsnSignature(e,t){if("ECDSA"===e.name){var r=e.namedCurve,n=aC.namedCurveSize.get(r)||aC.defaultNamedCurveSize,i=new pE,o=Xp.BufferSourceConverter.toUint8Array(t);return i.r=this.removePadding(o.slice(0,n),!0),i.s=this.removePadding(o.slice(n,n+n),!0),bm.serialize(i)}return null}toWebSignature(e,t){if("ECDSA"===e.name){var r=bm.parse(t,pE),n=e.namedCurve,i=aC.namedCurveSize.get(n)||aC.defaultNamedCurveSize,o=this.addPadding(i,this.removePadding(r.r)),a=this.addPadding(i,this.removePadding(r.s));return Xp.combine(o,a)}return null}}aC.namedCurveSize=new Map,aC.defaultNamedCurveSize=32;var sC,lC,uC="1.3.101.110",cC="1.3.101.111",dC="1.3.101.112",hC="1.3.101.113",vC=class{toAsnAlgorithm(e){var t=null;switch(e.name.toLowerCase()){case"ed25519":t=dC;break;case"x25519":t=uC;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=dC;break;case"ed448":t=hC}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=uC;break;case"x448":t=cC}}return t?new sb({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case dC:return{name:"Ed25519"};case hC:return{name:"EdDSA",namedCurve:"Ed448"};case uC:return{name:"X25519"};case cC:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};vC=da([vk()],vC),hk.registerSingleton(px,vC);(class extends UA{constructor(e){UA.isAsnEncoded(e)?super(e,vx):super(e),this.tag=MA.CertificateRequestTag}onInit(e){this.tbs=bm.serialize(e.certificationRequestInfo),this.publicKey=new FA(e.certificationRequestInfo.subjectPKInfo);var t=hk.resolve(gx);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map((e=>tC.create(bm.serialize(e))));var r=this.getAttribute(zk);this.extensions=[],r instanceof eC&&(this.extensions=r.items),this.subjectName=new lA(e.certificationRequestInfo.subject),this.subject=this.subjectName.toString()}getAttribute(e){for(var t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter((t=>t.type===e))}getExtension(e){for(var t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter((t=>t.type===e))}verify(){var e=arguments,n=this;return r((function*(){var r=e.length>0&&void 0!==e[0]?e[0]:nA.get(),i=t(t({},n.publicKey.algorithm),n.signatureAlgorithm),o=yield n.publicKey.export(i,["verify"],r),a=hk.resolveAll(nC).reverse(),s=null;for(var l of a)if(s=l.toWebSignature(i,n.signature))break;if(!s)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return yield r.subtle.verify(n.signatureAlgorithm,o,s,n.tbs)}))()}toTextObject(){var e=this.toTextObjectEmpty(),t=bm.parse(this.rawData,vx),r=t.certificationRequestInfo,n=new Zx("",{Version:"".concat(vb[r.version]," (").concat(r.version,")"),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){var i=new Zx("");for(var o of this.attributes){var a=o.toTextObject();i[a[Zx.NAME]]=a}n.Attributes=i}return e.Data=n,e.Signature=new Zx("",{Algorithm:Xx.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}).NAME="PKCS#10 Certificate Request";class pC extends UA{constructor(e){UA.isAsnEncoded(e)?super(e,gb):super(e),this.tag=MA.CertificateTag}onInit(e){var t=e.tbsCertificate;this.tbs=bm.serialize(t),this.serialNumber=Xp.Convert.ToHex(t.serialNumber),this.subjectName=new lA(t.subject),this.subject=new lA(t.subject).toString(),this.issuerName=new lA(t.issuer),this.issuer=this.issuerName.toString();var r=hk.resolve(gx);this.signatureAlgorithm=r.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signatureValue;var n=t.validity.notBefore.utcTime||t.validity.notBefore.generalTime;if(!n)throw new Error("Cannot get 'notBefore' value");this.notBefore=n;var i=t.validity.notAfter.utcTime||t.validity.notAfter.generalTime;if(!i)throw new Error("Cannot get 'notAfter' value");this.notAfter=i,this.extensions=[],t.extensions&&(this.extensions=t.extensions.map((e=>WA.create(bm.serialize(e))))),this.publicKey=new FA(t.subjectPublicKeyInfo)}getExtension(e){for(var t of this.extensions)if("string"==typeof e){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter((t=>"string"==typeof e?t.type===e:t instanceof e))}verify(){var e=arguments,n=this;return r((function*(){var r,i,o=e.length>0&&void 0!==e[0]?e[0]:{},a=e.length>1&&void 0!==e[1]?e[1]:nA.get(),s=o.publicKey;try{if(s)if("publicKey"in s)r=t(t({},s.publicKey.algorithm),n.signatureAlgorithm),i=yield s.publicKey.export(r,["verify"],a);else if(s instanceof FA)r=t(t({},s.algorithm),n.signatureAlgorithm),i=yield s.export(r,["verify"],a);else if(Xp.BufferSourceConverter.isBufferSource(s)){var l=new FA(s);r=t(t({},l.algorithm),n.signatureAlgorithm),i=yield l.export(r,["verify"],a)}else r=t(t({},s.algorithm),n.signatureAlgorithm),i=s;else r=t(t({},n.publicKey.algorithm),n.signatureAlgorithm),i=yield n.publicKey.export(r,["verify"],a)}catch(e){return!1}var u=hk.resolveAll(nC).reverse(),c=null;for(var d of u)if(c=d.toWebSignature(r,n.signature))break;if(!c)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");var h=yield a.subtle.verify(n.signatureAlgorithm,i,c,n.tbs);if(o.signatureOnly)return h;var v=(o.date||new Date).getTime();return h&&n.notBefore.getTime()<v&&v<n.notAfter.getTime()}))()}getThumbprint(){var e=arguments,t=this;return r((function*(){for(var r,n="SHA-1",i=e.length,o=new Array(i),a=0;a<i;a++)o[a]=e[a];return o[0]&&(o[0].subtle?r=o[0]:(n=o[0]||n,r=o[1])),null!=r||(r=nA.get()),yield r.subtle.digest(n,t.rawData)}))()}isSelfSigned(){var e=arguments,t=this;return r((function*(){var r=e.length>0&&void 0!==e[0]?e[0]:nA.get();return t.subject===t.issuer&&(yield t.verify({signatureOnly:!0},r))}))()}toTextObject(){var e=this.toTextObjectEmpty(),t=bm.parse(this.rawData,gb),r=t.tbsCertificate,n=new Zx("",{Version:"".concat(vb[r.version]," (").concat(r.version,")"),"Serial Number":r.serialNumber,"Signature Algorithm":Xx.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new Zx("",{"Not Before":r.validity.notBefore.getTime(),"Not After":r.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(r.issuerUniqueID&&(n["Issuer Unique ID"]=r.issuerUniqueID),r.subjectUniqueID&&(n["Subject Unique ID"]=r.subjectUniqueID),this.extensions.length){var i=new Zx("");for(var o of this.extensions){var a=o.toTextObject();i[a[Zx.NAME]]=a}n.Extensions=i}return e.Data=n,e.Signature=new Zx("",{Algorithm:Xx.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}}pC.NAME="Certificate";class fC{static createSelfSigned(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:nA.get();if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return n.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},r)}))()}static create(e){var n=arguments;return r((function*(){var r,i,o=n.length>1&&void 0!==n[1]?n[1]:nA.get();i=e.publicKey instanceof FA?e.publicKey.rawData:"publicKey"in e.publicKey?e.publicKey.publicKey.rawData:Xp.BufferSourceConverter.isBufferSource(e.publicKey)?e.publicKey:yield o.subtle.exportKey("spki",e.publicKey);var a=e.serialNumber?Xp.BufferSourceConverter.toUint8Array(Xp.Convert.FromHex(e.serialNumber)):o.getRandomValues(new Uint8Array(16));a[0]>127&&(a[0]&=127),a.length>1&&0===a[0]&&(a[1]|=128);var s=e.notBefore||new Date,l=e.notAfter||new Date(s.getTime()+31536e6),u=new gb({tbsCertificate:new fb({version:vb.v3,serialNumber:a,validity:new db({notBefore:s,notAfter:l}),extensions:new pb((null===(r=e.extensions)||void 0===r?void 0:r.map((e=>bm.parse(e.rawData,hb))))||[]),subjectPublicKeyInfo:bm.parse(i,lb)})});if(e.subject){var c=e.subject instanceof lA?e.subject:new lA(e.subject);u.tbsCertificate.subject=bm.parse(c.toArrayBuffer(),Im)}if(e.issuer){var d=e.issuer instanceof lA?e.issuer:new lA(e.issuer);u.tbsCertificate.issuer=bm.parse(d.toArrayBuffer(),Im)}var h={hash:"SHA-256"},v="signingKey"in e?t(t(t({},h),e.signingAlgorithm),e.signingKey.algorithm):t(t({},h),e.signingAlgorithm),p=hk.resolve(gx);u.tbsCertificate.signature=u.signatureAlgorithm=p.toAsnAlgorithm(v);var f=bm.serialize(u.tbsCertificate),g="signingKey"in e?yield o.subtle.sign(v,e.signingKey,f):e.signature,y=hk.resolveAll(nC).reverse(),m=null;for(var w of y)if(m=w.toAsnSignature(v,g))break;if(!m)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return u.signatureValue=m,new pC(bm.serialize(u))}))()}}!function(e){e[e.unspecified=0]="unspecified",e[e.keyCompromise=1]="keyCompromise",e[e.cACompromise=2]="cACompromise",e[e.affiliationChanged=3]="affiliationChanged",e[e.superseded=4]="superseded",e[e.cessationOfOperation=5]="cessationOfOperation",e[e.certificateHold=6]="certificateHold",e[e.removeFromCRL=8]="removeFromCRL",e[e.privilegeWithdrawn=9]="privilegeWithdrawn",e[e.aACompromise=10]="aACompromise"}(sC||(sC={})),WA.register(Ym,jA),WA.register(xw,VA),WA.register(Uw,qA),WA.register(tb,HA),WA.register(Km,zA),WA.register(Qw,KA),WA.register(vw,QA),WA.register(Vm,YA),tC.register(Fk,XA),tC.register(zk,eC),hk.registerSingleton(nC,class{toAsnSignature(e,t){return Xp.BufferSourceConverter.toArrayBuffer(t)}toWebSignature(e,t){return Xp.BufferSourceConverter.toArrayBuffer(t)}}),hk.registerSingleton(nC,aC),aC.namedCurveSize.set("P-256",32),aC.namedCurveSize.set("K-256",32),aC.namedCurveSize.set("P-384",48),aC.namedCurveSize.set("P-521",66);class gC extends us{listen(){return r((function*(){throw new zp("WebRTCTransport.createListener")}))()}getAddrs(){return[]}updateAnnounceAddrs(){}close(){return r((function*(){}))()}}function yC(){var e,t=_c(),n=!1;return{sink:(e=r((function*(e){if(n)throw new Error("already piped");n=!0,t.resolve(e)})),function(t){return e.apply(this,arguments)}),source:l((function*(){var e=yield u(t.promise);yield*c(s(e))}))()}}var mC=65535,wC=Boolean(null===(lC=globalThis.process)||void 0===lC||null===(lC=lC.env)||void 0===lC?void 0:lC.DUMP_SESSION_KEYS);function bC(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function SC(e){if("boolean"!=typeof e)throw new Error("boolean expected, not ".concat(e))}function EC(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function kC(e){if(!bC(e))throw new Error("Uint8Array expected");for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];if(r.length>0&&!r.includes(e.length))throw new Error("Uint8Array expected of length "+r+", got length="+e.length)}function xC(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];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 AC(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function CC(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];for(var n=0;n<t.length;n++)t[n].fill(0)}var IC=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function TC(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(!bC(e))throw new Error("Uint8Array expected, got "+typeof e);e=DC(e)}return e}var PC=(e,t)=>{function r(r){if(kC(r),!IC)throw new Error("Non little-endian hardware is not yet supported");for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;o<n;o++)i[o-1]=arguments[o];if(void 0!==e.nonceLength){var a=i[0];if(!a)throw new Error("nonce / iv required");e.varSizeNonce?kC(a):kC(a,e.nonceLength)}var s=e.tagLength;s&&void 0!==i[1]&&kC(i[1]);var l=t(r,...i),u=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");kC(t)}},c=!1;return{encrypt(e,t){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,kC(e),u(l.encrypt.length,t),l.encrypt(e,t)},decrypt(e,t){if(kC(e),s&&e.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return u(l.decrypt.length,t),l.decrypt(e,t)}}}return Object.assign(r,e),r};function _C(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];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 BC(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);var i=BigInt(32),o=BigInt(4294967295),a=Number(r>>i&o),s=Number(r&o);e.setUint32(t+4,a,n),e.setUint32(t+0,s,n)}function NC(e,t,r){SC(r);var n,i=new Uint8Array(16),o=(n=i,new DataView(n.buffer,n.byteOffset,n.byteLength));return BC(o,0,BigInt(t),r),BC(o,8,BigInt(e),r),i}function DC(e){return Uint8Array.from(e)}var RC=e=>Uint8Array.from(e.split("").map((e=>e.charCodeAt(0)))),OC=RC("expand 16-byte k"),LC=RC("expand 32-byte k"),MC=AC(OC),UC=AC(LC);function FC(e,t){return e<<t|e>>>32-t}function zC(e){return e.byteOffset%4==0}var jC=2**32-1,VC=new Uint32Array;function qC(e,t){var{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:o,rounds:a}=function(e,t){if(null==t||"object"!=typeof t)throw new Error("options must be defined");return Object.assign(e,t)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if("function"!=typeof e)throw new Error("core must be a function");return EC(i),EC(a),SC(o),SC(r),function(t,s,l,u){var c=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0;kC(t),kC(s),kC(l);var d=l.length;if(void 0===u&&(u=new Uint8Array(d)),kC(u),EC(c),c<0||c>=jC)throw new Error("arx: counter overflow");if(u.length<d)throw new Error("arx: output (".concat(u.length,") is shorter than data (").concat(d,")"));var h,v,p=[],f=t.length;if(32===f)p.push(h=DC(t)),v=UC;else{if(16!==f||!r)throw new Error("arx: invalid 32-byte key, got length=".concat(f));(h=new Uint8Array(32)).set(t),h.set(t,16),v=MC,p.push(h)}zC(s)||p.push(s=DC(s));var g=AC(h);if(n){if(24!==s.length)throw new Error("arx: extended nonce must be 24 bytes");n(v,g,AC(s.subarray(0,16)),g),s=s.subarray(16)}var y=16-i;if(y!==s.length)throw new Error("arx: nonce must be ".concat(y," or 16 bytes"));if(12!==y){var m=new Uint8Array(12);m.set(s,o?0:12-s.length),s=m,p.push(s)}var w=AC(s);return function(e,t,r,n,i,o,a,s){for(var l=i.length,u=new Uint8Array(64),c=AC(u),d=zC(i)&&zC(o),h=d?AC(i):VC,v=d?AC(o):VC,p=0;p<l;a++){if(e(t,r,n,c,a,s),a>=jC)throw new Error("arx: counter overflow");var f=Math.min(64,l-p);if(d&&64===f){var g=p/4;if(p%4!=0)throw new Error("arx: invalid block position");for(var y,m=0;m<16;m++)v[y=g+m]=h[y]^c[m];p+=64}else{for(var w,b=0;b<f;b++)o[w=p+b]=i[w]^u[b];p+=f}}}(e,v,g,w,l,u,c,a),CC(...p),u}}var HC=(e,t)=>255&e[t++]|(255&e[t++])<<8;class KC{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,kC(e=TC(e),32);var t=HC(e,0),r=HC(e,2),n=HC(e,4),i=HC(e,6),o=HC(e,8),a=HC(e,10),s=HC(e,12),l=HC(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|i<<9),this.r[4]=255&(i>>>4|o<<12),this.r[5]=o>>>1&8190,this.r[6]=8191&(o>>>14|a<<2),this.r[7]=8065&(a>>>11|s<<5),this.r[8]=8191&(s>>>8|l<<8),this.r[9]=l>>>5&127;for(var u=0;u<8;u++)this.pad[u]=HC(e,16+2*u)}process(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2]?0:2048,{h:n,r:i}=this,o=i[0],a=i[1],s=i[2],l=i[3],u=i[4],c=i[5],d=i[6],h=i[7],v=i[8],p=i[9],f=HC(e,t+0),g=HC(e,t+2),y=HC(e,t+4),m=HC(e,t+6),w=HC(e,t+8),b=HC(e,t+10),S=HC(e,t+12),E=HC(e,t+14),k=n[0]+(8191&f),x=n[1]+(8191&(f>>>13|g<<3)),A=n[2]+(8191&(g>>>10|y<<6)),C=n[3]+(8191&(y>>>7|m<<9)),I=n[4]+(8191&(m>>>4|w<<12)),T=n[5]+(w>>>1&8191),P=n[6]+(8191&(w>>>14|b<<2)),_=n[7]+(8191&(b>>>11|S<<5)),B=n[8]+(8191&(S>>>8|E<<8)),N=n[9]+(E>>>5|r),D=0,R=D+k*o+x*(5*p)+A*(5*v)+C*(5*h)+I*(5*d);D=R>>>13,R&=8191;var O=(D+=(R+=T*(5*c)+P*(5*u)+_*(5*l)+B*(5*s)+N*(5*a))>>>13)+k*a+x*o+A*(5*p)+C*(5*v)+I*(5*h);D=O>>>13,O&=8191,D+=(O+=T*(5*d)+P*(5*c)+_*(5*u)+B*(5*l)+N*(5*s))>>>13,O&=8191;var L=D+k*s+x*a+A*o+C*(5*p)+I*(5*v);D=L>>>13,L&=8191,D+=(L+=T*(5*h)+P*(5*d)+_*(5*c)+B*(5*u)+N*(5*l))>>>13,L&=8191;var M=D+k*l+x*s+A*a+C*o+I*(5*p);D=M>>>13,M&=8191,D+=(M+=T*(5*v)+P*(5*h)+_*(5*d)+B*(5*c)+N*(5*u))>>>13,M&=8191;var U=D+k*u+x*l+A*s+C*a+I*o;D=U>>>13,U&=8191,D+=(U+=T*(5*p)+P*(5*v)+_*(5*h)+B*(5*d)+N*(5*c))>>>13,U&=8191;var F=D+k*c+x*u+A*l+C*s+I*a;D=F>>>13,F&=8191,D+=(F+=T*o+P*(5*p)+_*(5*v)+B*(5*h)+N*(5*d))>>>13,F&=8191;var z=D+k*d+x*c+A*u+C*l+I*s;D=z>>>13,z&=8191,D+=(z+=T*a+P*o+_*(5*p)+B*(5*v)+N*(5*h))>>>13,z&=8191;var j=D+k*h+x*d+A*c+C*u+I*l;D=j>>>13,j&=8191,D+=(j+=T*s+P*a+_*o+B*(5*p)+N*(5*v))>>>13,j&=8191;var V=D+k*v+x*h+A*d+C*c+I*u;D=V>>>13,V&=8191,D+=(V+=T*l+P*s+_*a+B*o+N*(5*p))>>>13,V&=8191;var q=D+k*p+x*v+A*h+C*d+I*c;D=q>>>13,q&=8191,D+=(q+=T*u+P*l+_*s+B*a+N*o)>>>13,q&=8191,R=8191&(D=(D=(D<<2)+D|0)+(R&=8191)|0),O+=D>>>=13,n[0]=R,n[1]=O,n[2]=L,n[3]=M,n[4]=U,n[5]=F,n[6]=z,n[7]=j,n[8]=V,n[9]=q}finalize(){var{h:e,pad:t}=this,r=new Uint16Array(10),n=e[1]>>>13;e[1]&=8191;for(var i=2;i<10;i++)e[i]+=n,n=e[i]>>>13,e[i]&=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(var o=1;o<10;o++)r[o]=e[o]+n,n=r[o]>>>13,r[o]&=8191;r[9]-=8192;for(var a=(1^n)-1,s=0;s<10;s++)r[s]&=a;a=~a;for(var l=0;l<10;l++)e[l]=e[l]&a|r[l];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);var u=e[0]+t[0];e[0]=65535&u;for(var c=1;c<8;c++)u=(e[c]+t[c]|0)+(u>>>16)|0,e[c]=65535&u;CC(r)}update(e){xC(this),kC(e=TC(e));for(var{buffer:t,blockLen:r}=this,n=e.length,i=0;i<n;){var o=Math.min(r-this.pos,n-i);if(o!==r)t.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===r&&(this.process(t,0,!1),this.pos=0);else for(;r<=n-i;i+=r)this.process(e,i)}return this}destroy(){CC(this.h,this.r,this.buffer,this.pad)}digestInto(e){xC(this),function(e,t){kC(e);var r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;var{buffer:t,h:r}=this,{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();for(var i=0,o=0;o<8;o++)e[i++]=r[o]>>>0,e[i++]=r[o]>>>8;return e}digest(){var{buffer:e,outputLen:t}=this;this.digestInto(e);var r=e.slice(0,t);return this.destroy(),r}}var WC,GC,QC,YC=(GC=(e,t)=>WC(t).update(TC(e)).digest(),QC=(WC=e=>new KC(e))(new Uint8Array(32)),GC.outputLen=QC.outputLen,GC.blockLen=QC.blockLen,GC.create=e=>WC(e),GC);function JC(e,t,r,n,i){for(var o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:20,a=e[0],s=e[1],l=e[2],u=e[3],c=t[0],d=t[1],h=t[2],v=t[3],p=t[4],f=t[5],g=t[6],y=t[7],m=i,w=r[0],b=r[1],S=r[2],E=a,k=s,x=l,A=u,C=c,I=d,T=h,P=v,_=p,B=f,N=g,D=y,R=m,O=w,L=b,M=S,U=0;U<o;U+=2)R=FC(R^(E=E+C|0),16),C=FC(C^(_=_+R|0),12),R=FC(R^(E=E+C|0),8),C=FC(C^(_=_+R|0),7),O=FC(O^(k=k+I|0),16),I=FC(I^(B=B+O|0),12),O=FC(O^(k=k+I|0),8),I=FC(I^(B=B+O|0),7),L=FC(L^(x=x+T|0),16),T=FC(T^(N=N+L|0),12),L=FC(L^(x=x+T|0),8),T=FC(T^(N=N+L|0),7),M=FC(M^(A=A+P|0),16),P=FC(P^(D=D+M|0),12),M=FC(M^(A=A+P|0),8),P=FC(P^(D=D+M|0),7),M=FC(M^(E=E+I|0),16),I=FC(I^(N=N+M|0),12),M=FC(M^(E=E+I|0),8),I=FC(I^(N=N+M|0),7),R=FC(R^(k=k+T|0),16),T=FC(T^(D=D+R|0),12),R=FC(R^(k=k+T|0),8),T=FC(T^(D=D+R|0),7),O=FC(O^(x=x+P|0),16),P=FC(P^(_=_+O|0),12),O=FC(O^(x=x+P|0),8),P=FC(P^(_=_+O|0),7),L=FC(L^(A=A+C|0),16),C=FC(C^(B=B+L|0),12),L=FC(L^(A=A+C|0),8),C=FC(C^(B=B+L|0),7);var F=0;n[F++]=a+E|0,n[F++]=s+k|0,n[F++]=l+x|0,n[F++]=u+A|0,n[F++]=c+C|0,n[F++]=d+I|0,n[F++]=h+T|0,n[F++]=v+P|0,n[F++]=p+_|0,n[F++]=f+B|0,n[F++]=g+N|0,n[F++]=y+D|0,n[F++]=m+R|0,n[F++]=w+O|0,n[F++]=b+L|0,n[F++]=S+M|0}var ZC=qC(JC,{counterRight:!1,counterLength:4,allowShortKeys:!1}),$C=new Uint8Array(16),XC=(e,t)=>{e.update(t);var r=t.length%16;r&&e.update($C.subarray(r))},eI=new Uint8Array(32);function tI(e,t,r,n,i){var o=e(t,r,eI),a=YC.create(o);i&&XC(a,i),XC(a,n);var s=NC(n.length,i?i.length:0,!0);a.update(s);var l=a.digest();return CC(o,s),l}var rI,nI=PC({blockSize:64,nonceLength:12,tagLength:16},(rI=ZC,(e,t,r)=>{var n=16;return{encrypt(i,o){var a=i.length;(o=_C(a+n,o,!1)).set(i);var s=o.subarray(0,-16);rI(e,t,s,s,1);var l=tI(rI,e,t,s,r);return o.set(l,a),CC(l),o},decrypt(i,o){o=_C(i.length-n,o,!1);var a=i.subarray(0,-16),s=i.subarray(-16),l=tI(rI,e,t,a,r);if(!function(e,t){if(e.length!==t.length)return!1;for(var r=0,n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(s,l))throw new Error("invalid tag");return o.set(i.subarray(0,-16)),rI(e,t,o,o,1),CC(l),o}}}));var iI=Uint8Array.from([0]),oI=Uint8Array.of();var aI={hashSHA256:e=>Xo(e.subarray()),getHKDF(e,t){var r=function(e,t,r){return Nr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),$n(e,on(r),on(t))}(Xo,t,e),n=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:32;Nr(e),_r(n);var i=e.outputLen;if(n>255*i)throw new Error("Length should be <= 255*HashLen");var o=Math.ceil(n/i);void 0===r&&(r=oI);for(var a=new Uint8Array(o*i),s=$n.create(e,t),l=s._cloneInto(),u=new Uint8Array(s.outputLen),c=0;c<o;c++)iI[0]=c+1,l.update(0===c?oI:u).update(r).update(iI).digestInto(u),a.set(u,i*c),s._cloneInto(l);return s.destroy(),l.destroy(),Lr(u,iI),a.slice(0,n)}(Xo,r,void 0,96),i=n;return[i.subarray(0,32),i.subarray(32,64),i.subarray(64,96)]},generateX25519KeyPair(){var e=$o.utils.randomPrivateKey();return{publicKey:$o.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:$o.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>$o.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>nI(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,i)=>nI(n,t,r).decrypt(e.subarray(),i)},sI=aI;var lI=e=>{var t=dt(2);return t[0]=e>>8,t[1]=e,t};lI.bytes=2;var uI=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){var t=0;return t+=e[0]<<8,t+=e[1]}return e.getUint16(0)};function cI(e,t){t.enabled&&wC&&(e?(t("LOCAL_STATIC_PUBLIC_KEY ".concat(gt(e.publicKey,"hex"))),t("LOCAL_STATIC_PRIVATE_KEY ".concat(gt(e.privateKey,"hex")))):t("Missing local static keys."))}function dI(e,t){t.enabled&&wC&&(e?(t("LOCAL_PUBLIC_EPHEMERAL_KEY ".concat(gt(e.publicKey,"hex"))),t("LOCAL_PRIVATE_EPHEMERAL_KEY ".concat(gt(e.privateKey,"hex")))):t("Missing local ephemeral keys."))}function hI(e,t){t.enabled&&wC&&t(e?"REMOTE_EPHEMERAL_PUBLIC_KEY ".concat(gt(e.subarray(),"hex")):"Missing remote ephemeral keys.")}function vI(e,t,r){r.enabled&&wC&&(r("CIPHER_STATE_1 ".concat(e.n.getUint64()," ").concat(e.k&&gt(e.k,"hex"))),r("CIPHER_STATE_2 ".concat(t.n.getUint64()," ").concat(t.k&&gt(t.k,"hex"))))}function pI(e,t){if(e.length!==t.length)throw new Error("Inputs should have the same length");for(var r=dt(e.length),n=0;n<e.length;n++)r[n]=e[n]^t[n];return r}function fI(e,t){for(var r=0;r<e.byteLength;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return e.byteLength>t.byteLength?1:e.byteLength<t.byteLength?-1:0}uI.bytes=2;class gI extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid crypto exchange"),e(this,"code",void 0),this.code=gI.code}}e(gI,"code","ERR_INVALID_CRYPTO_EXCHANGE");class yI{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;e(this,"n",void 0),e(this,"bytes",void 0),e(this,"view",void 0),this.n=t,this.bytes=ct(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!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")}}var mI,wI,bI=ct(0);class SI{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;e(this,"k",void 0),e(this,"n",void 0),e(this,"crypto",void 0),this.crypto=t,this.k=r,this.n=new yI(n)}hasKey(){return Boolean(this.k)}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();var 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();var n=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,r);return this.n.increment(),n}}class EI{constructor(t,r){e(this,"cs",void 0),e(this,"ck",void 0),e(this,"h",void 0),e(this,"crypto",void 0),this.crypto=t;var n=xt(r,"utf-8");this.h=function(e,t){if(t.length<=32){var r=ct(32);return r.set(t),r}return e.hash(t)}(t,n),this.ck=this.h,this.cs=new SI(t)}mixKey(e){var[t,r]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new SI(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new bs(this.h,e))}encryptAndHash(e){var t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){var t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){var[e,t]=this.crypto.hkdf(this.ck,bI);return[new SI(this.crypto,e),new SI(this.crypto,t)]}}class kI{constructor(t){e(this,"ss",void 0),e(this,"s",void 0),e(this,"e",void 0),e(this,"rs",void 0),e(this,"re",void 0),e(this,"initiator",void 0),e(this,"crypto",void 0);var{crypto:r,protocolName:n,prologue:i,initiator:o,s:a,e:s,rs:l,re:u}=t;this.crypto=r,this.ss=new EI(r,n),this.ss.mixHash(i),this.initiator=o,this.s=a,this.e=s,this.rs=l,this.re=u}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");var 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){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]: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){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(this.rs)throw new Error("remote static public key is already set");var r=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+r)throw new Error("message is not long enough");var n=e.sublist(t,t+r);return this.rs=this.ss.decryptAndHash(n),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class xI extends kI{writeMessageA(e){return new bs(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){var t=this.writeE();this.writeEE();var r=this.writeS();return this.writeES(),new bs(t,r,this.ss.encryptAndHash(e))}writeMessageC(e){var t=this.writeS();return this.writeSE(),new bs(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(e){throw new gI("handshake stage 0 validation fail: ".concat(e.message))}}readMessageB(e){try{this.readE(e),this.readEE();var t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(e){throw new gI("handshake stage 1 validation fail: ".concat(e.message))}}readMessageC(e){try{var t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(e){throw new gI("handshake stage 2 validation fail: ".concat(e.message))}}}function AI(e,t,r){return CI.apply(this,arguments)}function CI(){return(CI=r((function*(e,t,r){var n=yield e.sign(PI(t));return wI.encode({identityKey:Au(e.publicKey),identitySig:n,extensions:r})}))).apply(this,arguments)}function II(e,t,r){return TI.apply(this,arguments)}function TI(){return TI=r((function*(e,t,r){try{var n=wI.decode(e),i=Eu(n.identityKey);if(!1===(null==r?void 0:r.equals(i)))throw new Error("Payload identity key ".concat(i," does not match expected remote identity key ").concat(r));if(!t)throw new Error("Remote static does not exist");var o=PI(t);if(!(yield i.verify(o,n.identitySig)))throw new Error("Invalid payload signature");return n}catch(e){throw new Na(e.message)}})),TI.apply(this,arguments)}function PI(e){var t=xt("noise-libp2p-static-key:");return e instanceof Uint8Array?zt([t,e],t.length+e.length):(e.prepend(t),e)}function _I(){return _I=r((function*(e,t){var{log:r,connection:n,crypto:i,privateKey:o,prologue:a,s:s,remoteIdentityKey:l,extensions:u}=e,c=yield AI(o,s.publicKey,u),d=new xI({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:a,s:s});cI(d.s,r),r.trace("Stage 0 - Initiator starting to send first message."),yield n.write(d.writeMessageA(bI),t),r.trace("Stage 0 - Initiator finished sending first message."),dI(d.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");var h,v,p=d.readMessageB(yield n.read(t));r.trace("Stage 1 - Initiator received the message."),hI(d.re,r),h=d.rs,(v=r).enabled&&wC&&v(h?"REMOTE_STATIC_PUBLIC_KEY ".concat(gt(h.subarray(),"hex")):"Missing remote static public key."),r.trace("Initiator going to check remote's signature...");var f=yield II(p,d.rs,l);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),yield n.write(d.writeMessageC(c),t),r.trace("Stage 2 - Initiator sent message with signed payload.");var[g,y]=d.ss.split();return vI(g,y,r),{payload:f,encrypt:e=>g.encryptWithAd(bI,e),decrypt:(e,t)=>y.decryptWithAd(bI,e,t)}})),_I.apply(this,arguments)}function BI(){return BI=r((function*(e,t){var{log:r,connection:n,crypto:i,privateKey:o,prologue:a,s:s,remoteIdentityKey:l,extensions:u}=e,c=yield AI(o,s.publicKey,u),d=new xI({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:a,s:s});cI(d.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),d.readMessageA(yield n.read(t)),r.trace("Stage 0 - Responder received first message."),hI(d.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),yield n.write(d.writeMessageB(c),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),dI(d.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");var h=d.readMessageC(yield n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");var v=yield II(h,d.rs,l),[p,f]=d.ss.split();return vI(p,f,r),{payload:v,encrypt:e=>f.encryptWithAd(bI,e),decrypt:(e,t)=>p.decryptWithAd(bI,e,t)}})),BI.apply(this,arguments)}!function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.webtransportCerthashes)for(var n of e.webtransportCerthashes)t.uint32(10),t.bytes(n);if(null!=e.streamMuxers)for(var i of e.streamMuxers)t.uint32(18),t.string(i);!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={webtransportCerthashes:[],streamMuxers:[]},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:var a;if(null!=(null===(a=r.limits)||void 0===a?void 0:a.webtransportCerthashes)&&n.webtransportCerthashes.length===r.limits.webtransportCerthashes)throw new Yl('Decode error - map field "webtransportCerthashes" had too many elements');n.webtransportCerthashes.push(e.bytes());break;case 2:var s;if(null!=(null===(s=r.limits)||void 0===s?void 0:s.streamMuxers)&&n.streamMuxers.length===r.limits.streamMuxers)throw new Yl('Decode error - map field "streamMuxers" had too many elements');n.streamMuxers.push(e.string());break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(mI||(mI={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!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),mI.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={identityKey:ct(0),identitySig:ct(0)},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.identityKey=e.bytes();break;case 2:n.identitySig=e.bytes();break;case 4:var a;n.extensions=mI.codec().decode(e,e.uint32(),{limits:null===(a=r.limits)||void 0===a?void 0:a.extensions});break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(wI||(wI={}));class NI{constructor(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"protocol","/noise"),e(this,"crypto",void 0),e(this,"prologue",void 0),e(this,"staticKey",void 0),e(this,"extensions",void 0),e(this,"metrics",void 0),e(this,"components",void 0),e(this,Symbol.toStringTag,"@chainsafe/libp2p-noise"),e(this,fs,["@libp2p/connection-encryption","@chainsafe/libp2p-noise"]);var{staticNoiseKey:i,extensions:o,crypto:a,prologueBytes:s}=n,{metrics:l}=r;this.components=r;var u=null!=a?a:sI;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}}(u),this.extensions=t({webtransportCerthashes:[]},o),this.metrics=l?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"})}}(l):void 0,this.staticKey=i?u.generateX25519KeyPairFromSeed(i):u.generateX25519KeyPair(),this.prologue=null!=s?s:ct(0)}secureOutbound(e,t){var n=this;return r((function*(){var r,i,o=Id(e,{lengthEncoder:lI,lengthDecoder:uI,maxDataLength:mC}),a=yield n.performHandshakeInitiator(o,n.components.privateKey,null==t||null===(r=t.remotePeer)||void 0===r?void 0:r.publicKey,t),s=yield n.createSecureConnection(o,a);e.source=s.source,e.sink=s.sink;var l=Eu(a.payload.identityKey);return{conn:e,remoteExtensions:a.payload.extensions,remotePeer:Uu(l),streamMuxer:!0===(null==t?void 0:t.skipStreamMuxerNegotiation)?void 0:n.getStreamMuxer(null===(i=a.payload.extensions)||void 0===i?void 0:i.streamMuxers)}}))()}getStreamMuxer(e){if(null!=e&&0!==e.length){var t=this.components.upgrader.getStreamMuxers();if(null!=t)for(var r of e){var n=t.get(r);if(null!=n)return n}if(e.length)throw new Da("Early muxer negotiation was requested but the initiator and responder had no common muxers")}}secureInbound(e,t){var n=this;return r((function*(){var r,i,o=Id(e,{lengthEncoder:lI,lengthDecoder:uI,maxDataLength:mC}),a=yield n.performHandshakeResponder(o,n.components.privateKey,null==t||null===(r=t.remotePeer)||void 0===r?void 0:r.publicKey,t),s=yield n.createSecureConnection(o,a);e.source=s.source,e.sink=s.sink;var l=Eu(a.payload.identityKey);return{conn:e,remoteExtensions:a.payload.extensions,remotePeer:Uu(l),streamMuxer:!0===(null==t?void 0:t.skipStreamMuxerNegotiation)?void 0:n.getStreamMuxer(null===(i=a.payload.extensions)||void 0===i?void 0:i.streamMuxers)}}))()}performHandshakeInitiator(e,n,i,o){var a=this;return r((function*(){var r,s=!0===(null==o?void 0:o.skipStreamMuxerNegotiation)?[]:[...a.components.upgrader.getStreamMuxers().keys()];try{var l;r=yield function(e,t){return _I.apply(this,arguments)}({connection:e,privateKey:n,remoteIdentityKey:i,log:a.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:a.crypto,prologue:a.prologue,s:a.staticKey,extensions:t({streamMuxers:s,webtransportCerthashes:[]},a.extensions)},o),null===(l=a.metrics)||void 0===l||l.xxHandshakeSuccesses.increment()}catch(e){var u;throw null===(u=a.metrics)||void 0===u||u.xxHandshakeErrors.increment(),e}return r}))()}performHandshakeResponder(e,n,i,o){var a=this;return r((function*(){var r,s=!0===(null==o?void 0:o.skipStreamMuxerNegotiation)?[]:[...a.components.upgrader.getStreamMuxers().keys()];try{var l;r=yield function(e,t){return BI.apply(this,arguments)}({connection:e,privateKey:n,remoteIdentityKey:i,log:a.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:a.crypto,prologue:a.prologue,s:a.staticKey,extensions:t({streamMuxers:s,webtransportCerthashes:[]},a.extensions)},o),null===(l=a.metrics)||void 0===l||l.xxHandshakeSuccesses.increment()}catch(e){var u;throw null===(u=a.metrics)||void 0===u||u.xxHandshakeErrors.increment(),e}return r}))()}createSecureConnection(e,t){var n=this;return r((function*(){var r,i,[o,a]=(r=yC(),i=yC(),[{source:r.source,sink:i.sink},{source:i.source,sink:r.sink}]),c=e.unwrap();return yield qc(o,function(e,t){return function(){var r=l((function*(r){var n,i=!1,o=!1;try{for(var a,l=s(r);i=!(a=yield u(l.next())).done;i=!1)for(var c=a.value,d=0;d<c.length;d+=65519){var h=d+65519;h>c.length&&(h=c.length);var v=void 0;v=c instanceof Uint8Array?e.encrypt(c.subarray(d,h)):e.encrypt(c.sublist(d,h)),null==t||t.encryptedPackets.increment(),yield new bs(lI(v.byteLength),v)}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}));return function(e){return r.apply(this,arguments)}}()}(t,n.metrics),c,(e=>Cp(e,{lengthDecoder:uI})),function(e,t){return function(){var r=l((function*(r){var n,i=!1,o=!1;try{for(var a,l=s(r);i=!(a=yield u(l.next())).done;i=!1)for(var c=a.value,d=0;d<c.length;d+=mC){var h=d+mC;if(h>c.length&&(h=c.length),h-16<d)throw new Error("Invalid chunk");var v=c.sublist(d,h),p=c.subarray(d,h-16);try{var f=e.decrypt(v,p);null==t||t.decryptedPackets.increment(),yield f}catch(e){throw null==t||t.decryptErrors.increment(),e}}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}));return function(e){return r.apply(this,arguments)}}()}(t,n.metrics),o),a}))()}}function DI(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new NI(t,e)}var RI=Object.values(ut).map((e=>e.decoder)).reduce(((e,t)=>e.or(t))),OI=m(/^a=fingerprint:(?:\w+-[0-9]+)\s((:?[0-9a-fA-F]{2})+)$/m,{fingerprint:1});function LI(e){var t=e.stringTuples().filter((e=>466===e[0])).map((e=>e[1]))[0];if(void 0===t||""===t)throw new Ra("Couldn't find a certhash component of multiaddr: ".concat(e.toString()));return t}function MI(e){var t=function(e){return He(RI.decode(e))}(LI(e)),r=function(e){switch(e){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new jp(e)}}(t.code),n=t.digest.reduce(((e,t)=>e+t.toString(16).padStart(2,"0")),""),i=n.match(/.{1,2}/g);if(null==i)throw new Fp(n,e.toString());return"".concat(r," ").concat(i.join(":").toUpperCase())}function UI(e,t){if(void 0===e.sdp)throw new Ra("Can't munge a missing SDP");var r=e.sdp.includes("\r\n")?"\r\n":"\n";return e.sdp=e.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,"\na=ice-ufrag:"+t+r).replace(/\na=ice-pwd:[^\n]*\n/,"\na=ice-pwd:"+t+r),e}var FI=xt("libp2p-webrtc-noise:");var zI=op?"iceconnectionstatechange":"connectionstatechange";function jI(){return jI=r((function*(e,r,n){var i=e.createDataChannel("",{negotiated:!0,id:0});try{var o,a,s;if("client"===n.role){n.log.trace("client creating local offer");var l=yield e.createOffer();n.log.trace("client created local offer %s",l.sdp);var u=UI(l,r);n.log.trace("client setting local offer %s",u.sdp),yield e.setLocalDescription(u);var c=function(e,t){var{host:r,port:n,family:i}=e.toOptions(),o=MI(e);return{type:"answer",sdp:"v=0\no=- 0 0 IN IP".concat(i," ").concat(r,"\ns=-\nt=0 0\na=ice-lite\nm=application ").concat(n," UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP").concat(i," ").concat(r,"\na=mid:0\na=ice-options:ice2\na=ice-ufrag:").concat(t,"\na=ice-pwd:").concat(t,"\na=fingerprint:").concat(o,"\na=setup:passive\na=sctp-port:5000\na=max-message-size:").concat(Fv,"\na=candidate:1467250027 1 UDP 1467250027 ").concat(r," ").concat(n," typ host\na=end-of-candidates\n")}}(n.remoteAddr,r);n.log.trace("client setting server description %s",c.sdp),yield e.setRemoteDescription(c)}else{var d=function(e,t){var{host:r,port:n,family:i}=e.toOptions();return{type:"offer",sdp:"v=0\no=- 0 0 IN IP".concat(i," ").concat(r,"\ns=-\nc=IN IP").concat(i," ").concat(r,"\nt=0 0\na=ice-options:ice2,trickle\nm=application ").concat(n," UDP/DTLS/SCTP webrtc-datachannel\na=mid:0\na=setup:active\na=ice-ufrag:").concat(t,"\na=ice-pwd:").concat(t,"\na=fingerprint:sha-256 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\na=sctp-port:5000\na=max-message-size:").concat(Fv,"\na=candidate:1467250027 1 UDP 1467250027 ").concat(r," ").concat(n," typ host\na=end-of-candidates\n")}}(n.remoteAddr,r);n.log.trace("server setting client %s %s",d.type,d.sdp),yield e.setRemoteDescription(d),n.log.trace("server creating local answer");var h=yield e.createAnswer();n.log.trace("server created local answer");var v=UI(h,r);n.log.trace("server setting local description %s",h.sdp),yield e.setLocalDescription(v)}if("open"!==i.readyState&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,i.readyState),yield hv(i,"open",n.signal)),n.log.trace("%s handshake channel opened",n.role),"server"===n.role){var p,f,g=null!==(p=null===(f=e.remoteFingerprint())||void 0===f?void 0:f.value)&&void 0!==p?p:"";n.remoteAddr=n.remoteAddr.encapsulate(function(e){var t=e.split(":").map((e=>parseInt(e,16))),r=Uint8Array.from(t),n=qe($e.code,r);return Ir("/certhash/".concat(ue.encode(n.bytes)))}(g))}var y=function(e){var t;if(null!=e){var r=e.match(OI);return null==r||null===(t=r.groups)||void 0===t?void 0:t.fingerprint}}(null===(o=e.localDescription)||void 0===o?void 0:o.sdp);if(null==y)throw new Mp("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);var m=function(e,t,r){var n=xt(e.trim().toLowerCase().replaceAll(":",""),"hex"),i=qe($e.code,n),o=RI.decode(LI(t)),a=FI.byteLength+i.bytes.byteLength+o.byteLength;return zt("server"===r?[FI,o,i.bytes]:[FI,i.bytes,o],a)}(y,n.remoteAddr,n.role),w=DI({prologueBytes:m})(n),b=Tp(t({channel:i,direction:"outbound",handshake:!0,logger:n.logger},null!==(a=n.dataChannel)&&void 0!==a?a:{})),S=new cp(n,{peerConnection:e,remoteAddr:n.remoteAddr,timeline:{open:Date.now()},metrics:n.events});e.addEventListener(zI,(()=>{switch(e.connectionState){case"failed":case"disconnected":case"closed":S.close().catch((e=>{n.log.error("error closing connection",e),S.abort(e)}))}})),null===(s=n.events)||void 0===s||s.increment({peer_connection:!0});var E=new Pp(n,{peerConnection:e,metrics:n.events,dataChannelOptions:n.dataChannel});if("client"===n.role)return n.log.trace("%s secure inbound",n.role),yield w.secureInbound(b,{remotePeer:n.remotePeerId,signal:n.signal,skipStreamMuxerNegotiation:!0}),n.log.trace("%s upgrade outbound",n.role),yield n.upgrader.upgradeOutbound(S,{skipProtection:!0,skipEncryption:!0,muxerFactory:E,signal:n.signal});n.log.trace("%s secure outbound",n.role);var k=yield w.secureOutbound(b,{remotePeer:n.remotePeerId,signal:n.signal,skipStreamMuxerNegotiation:!0});S.remoteAddr=S.remoteAddr.encapsulate("/p2p/".concat(k.remotePeer)),n.log.trace("%s upgrade inbound",n.role),yield n.upgrader.upgradeInbound(S,{skipProtection:!0,skipEncryption:!0,muxerFactory:E,signal:n.signal})}catch(e){throw i.close(),e}})),jI.apply(this,arguments)}function VI(){return(VI=r((function*(e,r,n,i){null==i&&(i=yield RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));var o="function"==typeof n?yield n():n;return new RTCPeerConnection(t(t({},null!=o?o:{}),{},{certificates:[i]}))}))).apply(this,arguments)}function qI(e){return HI.apply(this,arguments)}function HI(){return(HI=r((function*(e){var t=yield Pu(e),r=yield crypto.subtle.exportKey("pkcs8",t.privateKey);return["-----BEGIN PRIVATE KEY-----",...gt(new Uint8Array(r),"base64pad").split(/(.{64})/).filter(Boolean),"-----END PRIVATE KEY-----"].join("\n")}))).apply(this,arguments)}class KI{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e(this,"log",void 0),e(this,"metrics",void 0),e(this,"components",void 0),e(this,"init",void 0),e(this,"certificate",void 0),e(this,"privateKey",void 0),e(this,"emitter",void 0),e(this,"renewCertificateTask",void 0),e(this,_a,!0),e(this,Symbol.toStringTag,"@libp2p/webrtc-direct"),e(this,fs,["@libp2p/transport"]),this.log=t.logger.forComponent("libp2p:webrtc-direct"),this.components=t,this.init=r,this.emitter=new us,null!=r.certificateLifespan&&null!=r.certificateRenewalThreshold&&r.certificateRenewalThreshold>=r.certificateLifespan)throw new Ra("Certificate renewal threshold must be less than certificate lifespan");null!=t.metrics&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}start(){var e=this;return r((function*(){e.certificate=yield e.getCertificate()}))()}stop(){var e=this;return r((function*(){null!=e.renewCertificateTask&&clearTimeout(e.renewCertificateTask),e.certificate=void 0}))()}dial(e,t){var n=this;return r((function*(){var r,i;n.log("dial %a",e),t.signal.throwIfAborted();var o=e.getPeerId();null!=o&&(i=Mu(o));var a=function(){return"libp2p+webrtc+v1/"+[...Array(arguments.length>0&&void 0!==arguments[0]?arguments[0]:32)].map((()=>Uv.at(Math.floor(Math.random()*Uv.length)))).join("")}(),s=yield function(e,t,r,n){return VI.apply(this,arguments)}("client",a,"function"==typeof n.init.rtcConfiguration?yield n.init.rtcConfiguration():null!==(r=n.init.rtcConfiguration)&&void 0!==r?r:{});try{var l;return yield function(e,t,r){return jI.apply(this,arguments)}(s,a,{role:"client",log:n.log,logger:n.components.logger,metrics:n.components.metrics,events:null===(l=n.metrics)||void 0===l?void 0:l.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:n.init.dataChannel,upgrader:t.upgrader,peerId:n.components.peerId,remotePeerId:i,privateKey:n.components.privateKey})}catch(e){throw s.close(),e}}))()}createListener(e){if(null==this.certificate)throw new Xa;return new gC(this.components,t(t(t({},this.init),e),{},{certificate:this.certificate,emitter:this.emitter}))}listenFilter(e){return e.filter(xh.exactMatch)}dialFilter(e){return this.listenFilter(e)}getCertificate(e){var t=this;return r((function*(){if(function(e){if(null==e)return!1;return"string"==typeof e.privateKey&&"string"==typeof e.pem&&"string"==typeof e.certhash}(t.init.certificate))return t.log("using provided TLS certificate"),t.init.certificate;var r=yield t.loadOrCreatePrivateKey(),{pem:n,certhash:i}=yield t.loadOrCreateCertificate(r,e);return{privateKey:yield qI(r),pem:n,certhash:i}}))()}loadOrCreatePrivateKey(){var e=this;return r((function*(){var t;if(null!=e.privateKey)return e.privateKey;var r=null!==(t=e.init.certificateKeychainName)&&void 0!==t?t:"webrtc-direct-certificate-private-key",n=e.getKeychain();try{if(null==n)throw e.log("no keychain configured - not checking for stored private key"),new Ha;e.log.trace("checking for stored private key"),e.privateKey=yield n.exportKey(r)}catch(t){if("NotFoundError"!==t.name)throw t;e.log.trace("generating private key"),e.privateKey=yield bu("ECDSA","P-256"),null!=n?(e.log.trace("storing private key"),yield n.importKey(r,e.privateKey)):e.log("no keychain configured - not storing private key")}return e.privateKey}))()}loadOrCreateCertificate(e,t){var n=this;return r((function*(){var r,i,o;if(null!=n.certificate&&!0!==t)return n.certificate;var a=new hc(null!==(r=n.init.certificateDatastoreKey)&&void 0!==r?r:"/libp2p/webrtc-direct/certificate"),s=yield Pu(e);try{if(!0===t)throw n.log.trace("forcing renewal of TLS certificate"),new Ha;n.log.trace("checking for stored TLS certificate"),o=yield n.loadCertificate(a,s)}catch(e){if("NotFoundError"!==e.name)throw e;n.log.trace("generating new TLS certificate"),o=yield n.createCertificate(a,s)}var l=o.notAfter.getTime()-(null!==(i=n.init.certificateRenewalThreshold)&&void 0!==i?i:qv)-Date.now();return l<0&&(l=100),n.log("will renew TLS certificate after %d ms",l),n.renewCertificateTask=setTimeout((()=>{n.log("renewing TLS certificate"),n.getCertificate(!0).then((e=>{n.certificate=e,n.emitter.safeDispatchEvent("certificate:renew",{detail:e})})).catch((e=>{n.log.error("could not renew certificate - %e",e)}))}),l),{pem:o.toString("pem"),certhash:ue.encode((yield $e.digest(new Uint8Array(o.rawData))).bytes)}}))()}loadCertificate(e,t){var n=this;return r((function*(){var r,i=yield n.components.datastore.get(e),o=new pC(i),a=o.notAfter.getTime()-(null!==(r=n.init.certificateRenewalThreshold)&&void 0!==r?r:qv);if(Date.now()>a)throw n.log("stored TLS certificate has expired"),new Ha;n.log("loaded certificate, expires in %d ms",a);var s=yield o.publicKey.export(crypto),l=yield crypto.subtle.exportKey("raw",s),u=yield crypto.subtle.exportKey("raw",t.publicKey);if(!Et(new Uint8Array(l,0,l.byteLength),new Uint8Array(u,0,u.byteLength)))throw n.log("stored TLS certificate public key did not match public key from private key"),new Ha;return n.log("loaded certificate, expiry time is %o",a),o}))()}createCertificate(e,t){var n=this;return r((function*(){var r,i=new Date,o=new Date(Date.now()+(null!==(r=n.init.certificateLifespan)&&void 0!==r?r:12096e5));i.setMilliseconds(0),o.setMilliseconds(0);var a=yield fC.createSelfSigned({serialNumber:(100000n*BigInt(Math.random().toString().replace(".",""))).toString(16),name:"CN=example.com, C=US, L=CA, O=example, ST=CA",notBefore:i,notAfter:o,keys:t,extensions:[new jA(!1,void 0,!0)]},crypto);return null!=n.getKeychain()?(n.log.trace("storing TLS certificate"),yield n.components.datastore.put(e,xt(a.toString("pem")))):n.log("no keychain is configured so not storing TLS certificate since the private key will not be reused"),a}))()}getKeychain(){try{return this.components.keychain}catch(e){}}}function WI(e){return t=>new KI(t,e)}function GI(e){return t=>new Qp(t,e)}var QI,YI,JI,ZI,$I,XI,eT,tT,rT,nT="/ipfs/bitswap/1.2.0",iT=4194304,oT=iT;!function(e){e.WantBlock="WantBlock",e.WantHave="WantHave"}(QI||(QI={})),function(e){e[e.WantBlock=0]="WantBlock",e[e.WantHave=1]="WantHave"}(YI||(YI={})),function(e){e.codec=()=>Gl(YI)}(QI||(QI={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.cid&&e.cid.byteLength>0&&(t.uint32(10),t.bytes(e.cid)),null!=e.priority&&0!==e.priority&&(t.uint32(16),t.int32(e.priority)),null!=e.cancel&&(t.uint32(24),t.bool(e.cancel)),null!=e.wantType&&(t.uint32(32),QI.codec().encode(e.wantType,t)),null!=e.sendDontHave&&(t.uint32(40),t.bool(e.sendDontHave)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={cid:ct(0),priority:0},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.cid=e.bytes();break;case 2:r.priority=e.int32();break;case 3:r.cancel=e.bool();break;case 4:r.wantType=QI.codec().decode(e);break;case 5:r.sendDontHave=e.bool();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(JI||(JI={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.entries)for(var n of e.entries)t.uint32(10),JI.codec().encode(n,t);null!=e.full&&(t.uint32(16),t.bool(e.full)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={entries:[]},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:var a,s;if(null!=(null===(a=r.limits)||void 0===a?void 0:a.entries)&&n.entries.length===r.limits.entries)throw new Yl('Decode error - map field "entries" had too many elements');n.entries.push(JI.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.entries$}));break;case 2:n.full=e.bool();break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(ZI||(ZI={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.prefix&&e.prefix.byteLength>0&&(t.uint32(10),t.bytes(e.prefix)),null!=e.data&&e.data.byteLength>0&&(t.uint32(18),t.bytes(e.data)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={prefix:ct(0),data:ct(0)},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.prefix=e.bytes();break;case 2:r.data=e.bytes();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}($I||($I={})),function(e){e.HaveBlock="HaveBlock",e.DoNotHaveBlock="DoNotHaveBlock"}(XI||(XI={})),function(e){e[e.HaveBlock=0]="HaveBlock",e[e.DoNotHaveBlock=1]="DoNotHaveBlock"}(eT||(eT={})),function(e){e.codec=()=>Gl(eT)}(XI||(XI={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.cid&&e.cid.byteLength>0&&(t.uint32(10),t.bytes(e.cid)),null!=e.type&&0!==eT[e.type]&&(t.uint32(16),XI.codec().encode(e.type,t)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={cid:ct(0),type:XI.HaveBlock},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.cid=e.bytes();break;case 2:r.type=XI.codec().decode(e);break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(tT||(tT={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.wantlist&&(t.uint32(10),ZI.codec().encode(e.wantlist,t)),null!=e.blocks)for(var n of e.blocks)t.uint32(26),$I.codec().encode(n,t);if(null!=e.blockPresences)for(var i of e.blockPresences)t.uint32(34),tT.codec().encode(i,t);null!=e.pendingBytes&&0!==e.pendingBytes&&(t.uint32(40),t.int32(e.pendingBytes)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={blocks:[],blockPresences:[],pendingBytes:0},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:var a;n.wantlist=ZI.codec().decode(e,e.uint32(),{limits:null===(a=r.limits)||void 0===a?void 0:a.wantlist});break;case 3:var s,l;if(null!=(null===(s=r.limits)||void 0===s?void 0:s.blocks)&&n.blocks.length===r.limits.blocks)throw new Yl('Decode error - map field "blocks" had too many elements');n.blocks.push($I.codec().decode(e,e.uint32(),{limits:null===(l=r.limits)||void 0===l?void 0:l.blocks$}));break;case 4:var u,c;if(null!=(null===(u=r.limits)||void 0===u?void 0:u.blockPresences)&&n.blockPresences.length===r.limits.blockPresences)throw new Yl('Decode error - map field "blockPresences" had too many elements');n.blockPresences.push(tT.codec().decode(e,e.uint32(),{limits:null===(c=r.limits)||void 0===c?void 0:c.blockPresences$}));break;case 5:n.pendingBytes=e.int32();break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(rT||(rT={}));class aT extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Block too large"),this.name="BlockTooLargeError"}}e(aT,"name","BlockTooLargeError");function sT(e,t,r,n,i,o){for(var a=0,s=!1,l=r;l<e.length;l++){var u=e[l],c=o(u);if(c>4193664)throw new aT("Cannot send block as after encoding it is over the max message size");var d=i+c;if(d>n){s=!0;break}t.push(u),a++,i=d}return{hasMore:s,added:a,newSize:i}}function lT(e){return dT(3,$I.encode(e))}function uT(e){return dT(4,tT.encode(e))}function cT(e){return dT(1,JI.encode(e))}function dT(e,t){return Ot(e)+Ot(t.byteLength)+t.byteLength}let hT=class extends us{constructor(t){var r,n,i,o,a,s,l,u,c,d,h,v=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),e(this,"log",void 0),e(this,"libp2p",void 0),e(this,"routing",void 0),e(this,"protocols",void 0),e(this,"running",void 0),e(this,"maxInboundStreams",void 0),e(this,"maxOutboundStreams",void 0),e(this,"messageReceiveTimeout",void 0),e(this,"registrarIds",void 0),e(this,"metrics",void 0),e(this,"sendQueue",void 0),e(this,"runOnLimitedConnections",void 0),e(this,"maxOutgoingMessageSize",void 0),e(this,"maxIncomingMessageSize",void 0),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=null!==(r=v.protocols)&&void 0!==r?r:[nT],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=null!==(n=v.maxInboundStreams)&&void 0!==n?n:1024,this.maxOutboundStreams=null!==(i=v.maxOutboundStreams)&&void 0!==i?i:1024,this.messageReceiveTimeout=null!==(o=v.messageReceiveTimeout)&&void 0!==o?o:5e3,this.runOnLimitedConnections=null!==(a=v.runOnLimitedConnections)&&void 0!==a&&a,this.maxIncomingMessageSize=null!==(s=v.maxIncomingMessageSize)&&void 0!==s?s:iT,this.maxOutgoingMessageSize=null!==(l=null!==(u=v.maxOutgoingMessageSize)&&void 0!==u?u:v.maxIncomingMessageSize)&&void 0!==l?l:oT,this.metrics={blocksSent:null===(c=t.metrics)||void 0===c?void 0:c.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:null===(d=t.metrics)||void 0===d?void 0:d.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new bv({concurrency:null!==(h=v.messageSendConcurrency)&&void 0!==h?h:50,metrics:t.metrics,metricName:"helia_bitswap_message_send_queue"}),this.sendQueue.addEventListener("error",(e=>{this.log.error("error sending wantlist to peer",e.detail)}))}start(){var e=this;return r((function*(){if(!e.running){e.running=!0,yield e.libp2p.handle(e.protocols,e._onStream,{maxInboundStreams:e.maxInboundStreams,maxOutboundStreams:e.maxOutboundStreams,runOnLimitedConnection:e.runOnLimitedConnections});var t={onConnect:t=>{e.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{e.safeDispatchEvent("peer:disconnected",{detail:t})}};for(var r of(e.registrarIds=[],e.protocols))e.registrarIds.push(yield e.libp2p.register(r,t));e.libp2p.getConnections().forEach((t=>{e.safeDispatchEvent("peer:connected",{detail:t.remotePeer})}))}}))()}stop(){var e=this;return r((function*(){if(e.running=!1,yield e.libp2p.unhandle(e.protocols),null!=e.registrarIds){for(var t of e.registrarIds)e.libp2p.unregister(t);e.registrarIds=[]}}))()}_onStream(e){var t=this;if(this.running){var{stream:n,connection:i}=e;Promise.resolve().then(r((function*(){t.log("incoming new bitswap %s stream from %p",n.protocol,i.remotePeer);var e=()=>{"open"===n.status?n.abort(new $a("Incoming Bitswap stream timed out after ".concat(t.messageReceiveTimeout,"ms"))):t.log("stream aborted with status %s",n.status)},o=AbortSignal.timeout(t.messageReceiveTimeout);o.addEventListener("abort",e),yield n.closeWrite(),yield qc(n,(e=>Cp(e,{maxDataLength:t.maxIncomingMessageSize})),function(){var a=r((function*(r){var a,l=!1,u=!1;try{for(var c,d=s(r);l=!(c=yield d.next()).done;l=!1){var h=c.value;try{var v=rT.decode(h);t.log("incoming new bitswap %s message from %p on stream",n.protocol,i.remotePeer,n.id),t.safeDispatchEvent("bitswap:message",{detail:{peer:i.remotePeer,message:v}}),o.removeEventListener("abort",e),(o=AbortSignal.timeout(t.messageReceiveTimeout)).addEventListener("abort",e)}catch(e){t.log.error("error reading incoming bitswap message from %p on stream",i.remotePeer,n.id,e),n.abort(e);break}}}catch(e){u=!0,a=e}finally{try{l&&null!=d.return&&(yield d.return())}finally{if(u)throw a}}}));return function(e){return a.apply(this,arguments)}}())}))).catch((e=>{this.log.error("error handling incoming stream from %p",i.remotePeer,e),n.abort(e)}))}}findProviders(e,t){var r=this;return l((function*(){var n;null==t||null===(n=t.onProgress)||void 0===n||n.call(t,new cv("bitswap:network:find-providers",e));var i,o=!1,a=!1;try{for(var l,c=s(r.routing.findProviders(e,t));o=!(l=yield u(c.next())).done;o=!1){var d=l.value;(yield u(r.libp2p.isDialable(d.multiaddrs,{runOnLimitedConnection:r.runOnLimitedConnections})))&&(yield d)}}catch(e){a=!0,i=e}finally{try{o&&null!=c.return&&(yield u(c.return()))}finally{if(a)throw i}}}))()}findAndConnect(e,t){var n=this;return r((function*(){var i;null!=(null==t?void 0:t.providers)&&(yield Promise.all(t.providers.map(function(){var e=r((function*(e){return n.connectTo(e).catch((e=>{n.log.error("could not connect to supplied provider - %e",e)}))}));return function(t){return e.apply(this,arguments)}}()))),yield vc(Pc(mc(n.findProviders(e,t),null!==(i=null==t?void 0:t.maxProviders)&&void 0!==i?i:3),function(){var e=r((function*(e){return n.connectTo(e.id,t)}));return function(t){return e.apply(this,arguments)}}())).catch((e=>{n.log.error(e)}))}))()}sendMessage(e,t,n){var i=this;return r((function*(){if(!i.running)throw new Error("network isn't running");var o=i.sendQueue.queue.find((t=>e.equals(t.options.peerId)&&"queued"===t.status));if(null!=o)return o.options.message=function(e,t){for(var[r,n]of t.wantlist.entries()){var i,o,a,s=e.wantlist.get(r);null!=s&&(s.priority>n.priority&&(n.priority=s.priority),n.cancel=null!==(i=n.cancel)&&void 0!==i?i:s.cancel,n.wantType=null!==(o=n.wantType)&&void 0!==o?o:s.wantType,n.sendDontHave=null!==(a=n.sendDontHave)&&void 0!==a?a:s.sendDontHave),e.wantlist.set(r,n)}for(var[l,u]of t.blockPresences.entries())e.blockPresences.set(l,u);for(var[c,d]of t.blocks.entries())e.blocks.set(c,d);return t.full&&!e.full&&(e.full=!0),e}(o.options.message,t),void(yield o.join({signal:null==n?void 0:n.signal}));yield i.sendQueue.add(function(){var t=r((function*(t){var r,n=null==t?void 0:t.message;if(null==n)throw new Ra("No message to send");i.log("sendMessage to %p",e),null==t||null===(r=t.onProgress)||void 0===r||r.call(t,new cv("bitswap:network:send-wantlist",e));var o=yield i.libp2p.dialProtocol(e,nT,t);yield o.closeRead();try{yield qc(function*(e,t){for(var r=[...e.wantlist.values()],n=[...e.blockPresences.values()],i=[...e.blocks.values()],o=0,a=0,s=0,l=!1;;){var u,c={wantlist:{full:null!==(u=e.full)&&void 0!==u&&u,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},d=rT.encode(c).byteLength,{added:h,hasMore:v,newSize:p}=sT(i,c.blocks,s,t,d,lT);s+=h,d=p;var f=v;({added:h,hasMore:v,newSize:p}=sT(n,c.blockPresences,a,t,d,uT)),a+=h,d=p;var g=v;if(({added:h,hasMore:v,newSize:p}=sT(r,c.wantlist.entries,o,t,d,cT)),o+=h,d=p,(l=!f&&!g&&!v)||(c.wantlist.full=!1),yield rT.encode(c),l)break}}(n,i.maxOutgoingMessageSize),(e=>xp(e)),o),yield o.close(t)}catch(r){var a;null==t||null===(a=t.onProgress)||void 0===a||a.call(t,new cv("bitswap:network:send-wantlist:error",{peer:e,error:r})),i.log.error("error sending message to %p",e,r),o.abort(r)}i._updateSentStats(n.blocks)}));return function(e){return t.apply(this,arguments)}}(),{peerId:e,signal:null==n?void 0:n.signal,message:t})}))()}connectTo(e,t){var n=this;return r((function*(){var r;if(!n.running)throw new Xa("Network isn't running");null==t||null===(r=t.onProgress)||void 0===r||r.call(t,new cv("bitswap:network:dial",e));var[i]=yield Promise.all([n.libp2p.dial(e,t),hv(n.libp2p,"peer:identify",null==t?void 0:t.signal,{filter:t=>{if(!t.detail.peerId.equals(e))return!1;if(t.detail.protocols.includes(nT))return!0;throw new Ya("".concat(e," did not support ").concat(nT))}})]);return i}))()}_updateSentStats(e){var t,r,n=0;for(var i of e.values())n+=i.data.byteLength;null===(t=this.metrics.dataSent)||void 0===t||t.increment(n),null===(r=this.metrics.blocksSent)||void 0===r||r.increment(e.size)}};class vT{constructor(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];e(this,"full",void 0),e(this,"pendingBytes",void 0),e(this,"wantlist",void 0),e(this,"blocks",void 0),e(this,"blockPresences",void 0),this.full=t,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){var r=se.encode(e.multihash.bytes);this.wantlist.set(r,t)}addBlockPresence(e,t){var r=se.encode(e.multihash.bytes);this.blockPresences.set(r,t)}addBlock(e,t){var r=se.encode(e.multihash.bytes);this.blocks.set(r,t)}}function pT(e){return function(e){var t=new Uint8Array(e.reduce(((e,t)=>e+Ot(t)),0)),r=0;for(var n of e)t=Ut(n,t,r),r+=Ot(n);return t}([e.version,e.code,e.multihash.code,e.multihash.digest.byteLength])}class fT{constructor(t,r){var n;e(this,"peerId",void 0),e(this,"blockstore",void 0),e(this,"network",void 0),e(this,"wants",void 0),e(this,"exchangeCount",void 0),e(this,"bytesSent",void 0),e(this,"bytesReceived",void 0),e(this,"lastExchange",void 0),e(this,"maxSizeReplaceHasWithBlock",void 0),e(this,"log",void 0),this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,this.log=t.logger.forComponent("helia:bitswap:ledger:".concat(t.peerId)),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=null!==(n=r.maxSizeReplaceHasWithBlock)&&void 0!==n?n:1024}sentBytes(e){this.exchangeCount++,this.lastExchange=(new Date).getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=(new Date).getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}sendBlocksToPeer(e){var t=this;return r((function*(){var r=new vT,n=new Set;for(var[i,o]of t.wants.entries())try{var a=yield t.blockstore.get(o.cid,e);o.wantType===QI.WantHave?a.byteLength<t.maxSizeReplaceHasWithBlock?(t.log("sending have and block for %c",o.cid),n.add(i),r.addBlock(o.cid,{data:a,prefix:pT(o.cid)})):(t.log("sending have for %c",o.cid),r.addBlockPresence(o.cid,{cid:o.cid.bytes,type:XI.HaveBlock})):(t.log("sending block for %c",o.cid),n.add(i),r.addBlock(o.cid,{data:a,prefix:pT(o.cid)}))}catch(e){if("NotFoundError"!==e.name)throw e;if(t.log("do not have block for %c",o.cid),!o.sendDontHave)continue;if(!0===o.sentDoNotHave)continue;o.sentDoNotHave=!0,r.addBlockPresence(o.cid,{cid:o.cid.bytes,type:XI.DoNotHaveBlock})}if(r.blocks.size>0||r.blockPresences.size>0)for(var s of(t.log("sending message"),yield t.network.sendMessage(t.peerId,r,e),t.log("sent message"),t.sentBytes([...r.blocks.values()].reduce(((e,t)=>e+t.data.byteLength),0)),n))t.wants.delete(s)}))()}}class gT{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"blockstore",void 0),e(this,"network",void 0),e(this,"ledgerMap",void 0),e(this,"maxSizeReplaceHasWithBlock",void 0),e(this,"log",void 0),e(this,"logger",void 0),this.blockstore=t.blockstore,this.network=t.network,this.maxSizeReplaceHasWithBlock=r.maxSizeReplaceHasWithBlock,this.log=t.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=t.logger,this.ledgerMap=av({name:"helia_bitswap_ledger_map",metrics:t.metrics}),this.network.addEventListener("bitswap:message",(e=>{this.receiveMessage(e.detail.peer,e.detail.message).catch((t=>{this.log.error("error receiving bitswap message from %p",e.detail.peer,t)}))})),this.network.addEventListener("peer:disconnected",(e=>{this.peerDisconnected(e.detail)}))}ledgerForPeer(e){var t=this.ledgerMap.get(e);if(null!=t)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){var t=this.ledgerMap.get(e);if(null!=t)return[...t.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map((e=>e.peerId))}receiveMessage(e,t){var n=this;return r((function*(){var r,i,o=n.ledgerMap.get(e);if(null==o&&(o=new fT({peerId:e,blockstore:n.blockstore,network:n.network,logger:n.logger},{maxSizeReplaceHasWithBlock:n.maxSizeReplaceHasWithBlock}),n.ledgerMap.set(e,o)),o.receivedBytes(null!==(r=null===(i=t.blocks)||void 0===i?void 0:i.reduce(((e,t)=>e+t.data.byteLength),0))&&void 0!==r?r:0),null!=t.wantlist)for(var a of(!0===t.wantlist.full&&o.wants.clear(),t.wantlist.entries)){var s,l,u=it.decode(a.cid),c=gt(u.multihash.bytes,"base64");if(!0===a.cancel)n.log("peer %p cancelled want of block for %c",e,u),o.wants.delete(c);else a.wantType===QI.WantHave?n.log("peer %p wanted block presence for %c",e,u):n.log("peer %p wanted block for %c",e,u),o.wants.set(c,{cid:u,priority:a.priority,wantType:null!==(s=a.wantType)&&void 0!==s?s:QI.WantBlock,sendDontHave:null!==(l=a.sendDontHave)&&void 0!==l&&l})}n.log("send blocks to peer"),yield o.sendBlocksToPeer()}))()}receivedBlock(e,t){var n=this;return r((function*(){var i=gt(e.multihash.bytes,"base64"),o=[];for(var a of n.ledgerMap.values())a.wants.has(i)&&o.push(a);yield Promise.all(o.map(function(){var e=r((function*(e){return e.sendBlocksToPeer(t)}));return function(t){return e.apply(this,arguments)}}()))}))()}peerDisconnected(e){this.ledgerMap.delete(e)}}var yT=new WeakMap;let mT=class{constructor(){n(this,yT,[])}enqueue(e,r){var n={priority:(r=t({priority:0},r)).priority,id:r.id,run:e};if(0===this.size||o(yT,this)[this.size-1].priority>=r.priority)o(yT,this).push(n);else{var i=function(e,t,r){for(var n=0,i=e.length;i>0;){var o=Math.trunc(i/2),a=n+o;r(e[a],t)<=0?(n=++a,i-=o+1):i=o}return n}(o(yT,this),n,((e,t)=>t.priority-e.priority));o(yT,this).splice(i,0,n)}}setPriority(e,t){var r=o(yT,this).findIndex((t=>t.id===e));if(-1===r)throw new ReferenceError('No promise function with the id "'.concat(e,'" exists in the queue.'));var[n]=o(yT,this).splice(r,1);this.enqueue(n.run,{priority:t,id:e})}dequeue(){var e=o(yT,this).shift();return null==e?void 0:e.run}filter(e){return o(yT,this).filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return o(yT,this).length}};var wT=new WeakMap,bT=new WeakMap,ST=new WeakMap,ET=new WeakMap,kT=new WeakMap,xT=new WeakMap,AT=new WeakMap,CT=new WeakMap,IT=new WeakMap,TT=new WeakMap,PT=new WeakMap,_T=new WeakMap,BT=new WeakMap,NT=new WeakMap,DT=new WeakMap,RT=new WeakSet;class OT extends la{constructor(r){var o,a,s,l;if(super(),d(this,RT),n(this,wT,void 0),n(this,bT,void 0),n(this,ST,0),n(this,ET,void 0),n(this,kT,void 0),n(this,xT,0),n(this,AT,void 0),n(this,CT,void 0),n(this,IT,void 0),n(this,TT,void 0),n(this,PT,0),n(this,_T,void 0),n(this,BT,void 0),n(this,NT,void 0),n(this,DT,1n),e(this,"timeout",void 0),!("number"==typeof(r=t({carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:mT},r)).intervalCap&&r.intervalCap>=1))throw new TypeError("Expected `intervalCap` to be a number from 1 and up, got `".concat(null!==(o=null===(a=r.intervalCap)||void 0===a?void 0:a.toString())&&void 0!==o?o:"","` (").concat(typeof r.intervalCap,")"));if(void 0===r.interval||!(Number.isFinite(r.interval)&&r.interval>=0))throw new TypeError("Expected `interval` to be a finite number >= 0, got `".concat(null!==(s=null===(l=r.interval)||void 0===l?void 0:l.toString())&&void 0!==s?s:"","` (").concat(typeof r.interval,")"));i(wT,this,r.carryoverConcurrencyCount),i(bT,this,r.intervalCap===Number.POSITIVE_INFINITY||0===r.interval),i(ET,this,r.intervalCap),i(kT,this,r.interval),i(IT,this,new r.queueClass),i(TT,this,r.queueClass),this.concurrency=r.concurrency,this.timeout=r.timeout,i(NT,this,!0===r.throwOnTimeout),i(BT,this,!1===r.autoStart)}get concurrency(){return o(_T,this)}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError("Expected `concurrency` to be a number from 1 and up, got `".concat(e,"` (").concat(typeof e,")"));i(_T,this,e),h(RT,this,HT).call(this)}setPriority(e,t){o(IT,this).setPriority(e,t)}add(e){return r((function*(){var n,a,s,l,u=arguments,c=this,d=u.length>1&&void 0!==u[1]?u[1]:{};return null!==(a=(n=d).id)&&void 0!==a||(n.id=(i(DT,c,(s=o(DT,c),l=s++,s)),l).toString()),d=t({timeout:c.timeout,throwOnTimeout:o(NT,c)},d),new Promise(((t,n)=>{o(IT,c).enqueue(r((function*(){var r,a;i(PT,c,(r=o(PT,c),++r)),i(ST,c,(a=o(ST,c),++a));try{var s;null===(s=d.signal)||void 0===s||s.throwIfAborted();var l=e({signal:d.signal});d.timeout&&(l=np(Promise.resolve(l),{milliseconds:d.timeout})),d.signal&&(l=Promise.race([l,h(RT,c,KT).call(c,d.signal)]));var u=yield l;t(u),c.emit("completed",u)}catch(e){if(e instanceof Xv&&!d.throwOnTimeout)return void t();n(e),c.emit("error",e)}finally{h(RT,c,UT).call(c)}})),d),c.emit("add"),h(RT,c,jT).call(c)}))}))()}addAll(e,t){var n=this;return r((function*(){return Promise.all(e.map(function(){var e=r((function*(e){return n.add(e,t)}));return function(t){return e.apply(this,arguments)}}()))}))()}start(){return o(BT,this)?(i(BT,this,!1),h(RT,this,HT).call(this),this):this}pause(){i(BT,this,!0)}clear(){i(IT,this,new(o(TT,this)))}onEmpty(){var e=this;return r((function*(){0!==o(IT,e).size&&(yield h(RT,e,GT).call(e,"empty"))}))()}onSizeLessThan(e){var t=this;return r((function*(){o(IT,t).size<e||(yield h(RT,t,GT).call(t,"next",(()=>o(IT,t).size<e)))}))()}onIdle(){var e=this;return r((function*(){0===o(PT,e)&&0===o(IT,e).size||(yield h(RT,e,GT).call(e,"idle"))}))()}get size(){return o(IT,this).size}sizeBy(e){return o(IT,this).filter(e).length}get pending(){return o(PT,this)}get isPaused(){return o(BT,this)}}function LT(e){return o(bT,e)||o(ST,e)<o(ET,e)}function MT(e){return o(PT,e)<o(_T,e)}function UT(){var e;i(PT,this,(e=o(PT,this),--e)),h(RT,this,jT).call(this),this.emit("next")}function FT(){h(RT,this,qT).call(this),h(RT,this,VT).call(this),i(CT,this,void 0)}function zT(e){var t=Date.now();if(void 0===o(AT,e)){var r=o(xT,e)-t;if(!(r<0))return void 0===o(CT,e)&&i(CT,e,setTimeout((()=>{h(RT,e,FT).call(e)}),r)),!0;i(ST,e,o(wT,e)?o(PT,e):0)}return!1}function jT(){if(0===o(IT,this).size)return o(AT,this)&&clearInterval(o(AT,this)),i(AT,this,void 0),this.emit("empty"),0===o(PT,this)&&this.emit("idle"),!1;if(!o(BT,this)){var e=!w(RT,this,zT);if(w(RT,this,LT)&&w(RT,this,MT)){var t=o(IT,this).dequeue();return!!t&&(this.emit("active"),t(),e&&h(RT,this,VT).call(this),!0)}}return!1}function VT(){o(bT,this)||void 0!==o(AT,this)||(i(AT,this,setInterval((()=>{h(RT,this,qT).call(this)}),o(kT,this))),i(xT,this,Date.now()+o(kT,this)))}function qT(){0===o(ST,this)&&0===o(PT,this)&&o(AT,this)&&(clearInterval(o(AT,this)),i(AT,this,void 0)),i(ST,this,o(wT,this)?o(PT,this):0),h(RT,this,HT).call(this)}function HT(){for(;h(RT,this,jT).call(this););}function KT(e){return WT.apply(this,arguments)}function WT(){return(WT=r((function*(e){return new Promise(((t,r)=>{e.addEventListener("abort",(()=>{r(e.reason)}),{once:!0})}))}))).apply(this,arguments)}function GT(e,t){return QT.apply(this,arguments)}function QT(){return QT=r((function*(e,t){return new Promise((r=>{var n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)}))})),QT.apply(this,arguments)}function YT(e){var t=[iP.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function JT(e){var t,r,n,i,o,a,s,l,u,c,d,h,v,p,f;return{Status:null!==(t=e.Status)&&void 0!==t?t:0,TC:null!==(r=null!==(n=e.TC)&&void 0!==n?n:e.flag_tc)&&void 0!==r&&r,RD:null!==(i=null!==(o=e.RD)&&void 0!==o?o:e.flag_rd)&&void 0!==i&&i,RA:null!==(a=null!==(s=e.RA)&&void 0!==s?s:e.flag_ra)&&void 0!==a&&a,AD:null!==(l=null!==(u=e.AD)&&void 0!==u?u:e.flag_ad)&&void 0!==l&&l,CD:null!==(c=null!==(d=e.CD)&&void 0!==d?d:e.flag_cd)&&void 0!==c&&c,Question:(null!==(h=null!==(v=e.Question)&&void 0!==v?v:e.questions)&&void 0!==h?h:[]).map((e=>({name:e.name,type:iP[e.type]}))),Answer:(null!==(p=null!==(f=e.Answer)&&void 0!==f?f:e.answers)&&void 0!==p?p:[]).map((e=>{var t,r;return{name:e.name,type:iP[e.type],TTL:null!==(t=null!==(r=e.TTL)&&void 0!==r?r:e.ttl)&&void 0!==t?t:60,data:e.data instanceof Uint8Array?gt(e.data):e.data}}))}}var ZT,$T;function XT(e){var t,n=new OT({concurrency:null!==(t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).queryConcurrency)&&void 0!==t?t:4});return function(){var t=r((function*(t){var i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=new URLSearchParams;a.set("name",t),YT(o.types).forEach((e=>{a.append("type",iP[e])})),null===(i=o.onProgress)||void 0===i||i.call(o,new cv("dns:query",{detail:t}));var s=yield n.add(r((function*(){var t,r=yield fetch("".concat(e,"?").concat(a),{headers:{accept:"application/dns-json"},signal:null==o?void 0:o.signal});if(200!==r.status)throw new Error("Unexpected HTTP status: ".concat(r.status," - ").concat(r.statusText));var n=JT(yield r.json());return null===(t=o.onProgress)||void 0===t||t.call(o,new cv("dns:response",{detail:n})),n})),{signal:o.signal});if(null==s)throw new Error("No DNS response received");return s}));return function(e){return t.apply(this,arguments)}}()}var eP=($T||($T=1,ZT=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 i(i,o){r[i]=o,++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])?(i(e,t),t):void 0},set:function(e,t){void 0!==r[e]?r[e]=t:i(e,t)},clear:function(){r=Object.create(null),n=Object.create(null)}}}),ZT),tP=a(eP);class rP{constructor(t){e(this,"lru",void 0),this.lru=tP(t)}get(e,t){var r=!0,n=[];for(var i of t){var o=this.getAnswers(e,i);if(0===o.length){r=!1;break}n.push(...o)}if(r)return JT({answers:n})}getAnswers(e,r){var n="".concat(e.toLowerCase(),"-").concat(r),i=this.lru.get(n);if(null!=i){var o=i.filter((e=>e.expires>Date.now())).map((e=>{var{expires:r,value:n}=e;return t(t({},n),{},{TTL:Math.round((r-Date.now())/1e3),type:iP[n.type]})}));return 0===o.length&&this.lru.remove(n),o}return[]}add(e,t){var r,n,i="".concat(e.toLowerCase(),"-").concat(t.type),o=null!==(r=this.lru.get(i))&&void 0!==r?r:[];o.push({expires:Date.now()+1e3*(null!==(n=t.TTL)&&void 0!==n?n:60),value:t}),this.lru.set(i,o)}remove(e,t){var r="".concat(e.toLowerCase(),"-").concat(t);this.lru.remove(r)}clear(){this.lru.clear()}}let nP=class{constructor(t){var r,n,i;e(this,"resolvers",void 0),e(this,"cache",void 0),this.resolvers={},this.cache=(i=null!==(r=t.cacheSize)&&void 0!==r?r:1e3,new rP(i)),Object.entries(null!==(n=t.resolvers)&&void 0!==n?n:{}).forEach((e=>{var[t,r]=e;Array.isArray(r)||(r=[r]),t.endsWith(".")||(t="".concat(t,".")),this.resolvers[t]=r})),null==this.resolvers["."]&&(this.resolvers["."]=[XT("https://cloudflare-dns.com/dns-query"),XT("https://dns.google/resolve")])}query(e){var n=arguments,i=this;return r((function*(){var r,o,a=n.length>1&&void 0!==n[1]?n[1]:{},s=YT(a.types),l=!1!==a.cached?i.cache.get(e,s):void 0;if(null!=l)return null===(o=a.onProgress)||void 0===o||o.call(a,new cv("dns:cache",{detail:l})),l;var u="".concat(e.split(".").pop(),"."),c=(null!==(r=i.resolvers[u])&&void 0!==r?r:i.resolvers["."]).sort((()=>Math.random()>.5?-1:1)),d=[];for(var h of c){var v;if(!0===(null===(v=a.signal)||void 0===v?void 0:v.aborted))break;try{var p=yield h(e,t(t({},a),{},{types:s}));for(var f of p.Answer)i.cache.add(e,f);return p}catch(e){var g;d.push(e),null===(g=a.onProgress)||void 0===g||g.call(a,new cv("dns:error",{detail:e}))}}if(1===d.length)throw d[0];throw new AggregateError(d,"DNS lookup of ".concat(e," ").concat(s," failed"))}))()}};var iP;function oP(){return new nP(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{})}!function(e){e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"}(iP||(iP={}));var aP=["string","number","bigint","symbol"],sP=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function lP(e){if(null===e)return"null";if(void 0===e)return"undefined";if(!0===e||!1===e)return"boolean";var t=typeof e;if(aP.includes(t))return t;if("function"===t)return"Function";if(Array.isArray(e))return"Array";if(function(e){return e&&e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer.call(null,e)}(e))return"Buffer";var r=function(e){var t=Object.prototype.toString.call(e).slice(8,-1);if(sP.includes(t))return t;return}(e);return r||"Object"}class uP{constructor(e,t,r){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=r}toString(){return"Type[".concat(this.major,"].").concat(this.name)}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}}uP.uint=new uP(0,"uint",!0),uP.negint=new uP(1,"negint",!0),uP.bytes=new uP(2,"bytes",!0),uP.string=new uP(3,"string",!0),uP.array=new uP(4,"array",!1),uP.map=new uP(5,"map",!1),uP.tag=new uP(6,"tag",!1),uP.float=new uP(7,"float",!0),uP.false=new uP(7,"false",!0),uP.true=new uP(7,"true",!0),uP.null=new uP(7,"null",!0),uP.undefined=new uP(7,"undefined",!0),uP.break=new uP(7,"break",!0);class cP{constructor(e,t,r){this.type=e,this.value=t,this.encodedLength=r,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return"Token[".concat(this.type,"].").concat(this.value)}}var dP=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&"function"==typeof globalThis.Buffer.isBuffer,hP=new TextDecoder,vP=new TextEncoder;function pP(e){return dP&&globalThis.Buffer.isBuffer(e)}function fP(e){return e instanceof Uint8Array?pP(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e:Uint8Array.from(e)}var gP=dP?(e,t,r)=>r-t>64?globalThis.Buffer.from(e.subarray(t,r)).toString("utf8"):kP(e,t,r):(e,t,r)=>r-t>64?hP.decode(e.subarray(t,r)):kP(e,t,r),yP=dP?e=>e.length>64?globalThis.Buffer.from(e):EP(e):e=>e.length>64?vP.encode(e):EP(e),mP=e=>Uint8Array.from(e),wP=dP?(e,t,r)=>pP(e)?new Uint8Array(e.subarray(t,r)):e.slice(t,r):(e,t,r)=>e.slice(t,r),bP=dP?(e,t)=>(e=e.map((e=>e instanceof Uint8Array?e:globalThis.Buffer.from(e))),fP(globalThis.Buffer.concat(e,t))):(e,t)=>{var r=new Uint8Array(t),n=0;for(var i of e)n+i.length>r.length&&(i=i.subarray(0,r.length-n)),r.set(i,n),n+=i.length;return r},SP=dP?e=>globalThis.Buffer.allocUnsafe(e):e=>new Uint8Array(e);function EP(e){for(var t=[],r=0,n=0;n<e.length;n++){var i=e.charCodeAt(n);i<128?t[r++]=i:i<2048?(t[r++]=i>>6|192,t[r++]=63&i|128):55296==(64512&i)&&n+1<e.length&&56320==(64512&e.charCodeAt(n+1))?(i=65536+((1023&i)<<10)+(1023&e.charCodeAt(++n)),t[r++]=i>>18|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=63&i|128):(t[r++]=i>>12|224,t[r++]=i>>6&63|128,t[r++]=63&i|128)}return t}function kP(e,t,r){for(var n=[];t<r;){var i=e[t],o=null,a=i>239?4:i>223?3:i>191?2:1;if(t+a<=r){var s=void 0,l=void 0,u=void 0,c=void 0;switch(a){case 1:i<128&&(o=i);break;case 2:128==(192&(s=e[t+1]))&&(c=(31&i)<<6|63&s)>127&&(o=c);break;case 3:s=e[t+1],l=e[t+2],128==(192&s)&&128==(192&l)&&(c=(15&i)<<12|(63&s)<<6|63&l)>2047&&(c<55296||c>57343)&&(o=c);break;case 4:s=e[t+1],l=e[t+2],u=e[t+3],128==(192&s)&&128==(192&l)&&128==(192&u)&&(c=(15&i)<<18|(63&s)<<12|(63&l)<<6|63&u)>65535&&c<1114112&&(o=c)}}null===o?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),t+=a}return AP(n)}var xP=4096;function AP(e){var t=e.length;if(t<=xP)return String.fromCharCode.apply(String,e);for(var r="",n=0;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=xP));return r}class CP{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),null!==this._initReuseChunk&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){var t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){var r=t.length-(this.maxCursor-this.cursor)-1;t.set(e,r)}else{if(t){var n=t.length-(this.maxCursor-this.cursor)-1;n<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,n),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=SP(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,null===this._initReuseChunk&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(){var e,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(1===this.chunks.length){var r=this.chunks[0];t&&this.cursor>r.length/2?(e=this.cursor===r.length?r:r.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):e=wP(r,0,this.cursor)}else e=bP(this.chunks,this.cursor);return t&&this.reset(),e}}var IP="CBOR decode error:",TP="CBOR encode error:";function PP(e,t,r){if(e.length-t<r)throw new Error("".concat(IP," not enough data for type"))}var _P=[24,256,65536,4294967296,BigInt("18446744073709551616")];function BP(e,t,r){PP(e,t,1);var n=e[t];if(!0===r.strict&&n<_P[0])throw new Error("".concat(IP," integer encoded in more bytes than necessary (strict decode)"));return n}function NP(e,t,r){PP(e,t,2);var n=e[t]<<8|e[t+1];if(!0===r.strict&&n<_P[1])throw new Error("".concat(IP," integer encoded in more bytes than necessary (strict decode)"));return n}function DP(e,t,r){PP(e,t,4);var n=16777216*e[t]+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];if(!0===r.strict&&n<_P[2])throw new Error("".concat(IP," integer encoded in more bytes than necessary (strict decode)"));return n}function RP(e,t,r){PP(e,t,8);var n=16777216*e[t]+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3],i=16777216*e[t+4]+(e[t+5]<<16)+(e[t+6]<<8)+e[t+7],o=(BigInt(n)<<BigInt(32))+BigInt(i);if(!0===r.strict&&o<_P[3])throw new Error("".concat(IP," integer encoded in more bytes than necessary (strict decode)"));if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(!0===r.allowBigInt)return o;throw new Error("".concat(IP," integers outside of the safe integer range are not supported"))}function OP(e,t){return LP(e,0,t.value)}function LP(e,t,r){if(r<_P[0]){var n=Number(r);e.push([t|n])}else if(r<_P[1]){var i=Number(r);e.push([24|t,i])}else if(r<_P[2]){var o=Number(r);e.push([25|t,o>>>8,255&o])}else if(r<_P[3]){var a=Number(r);e.push([26|t,a>>>24&255,a>>>16&255,a>>>8&255,255&a])}else{var s=BigInt(r);if(!(s<_P[4]))throw new Error("".concat(IP," encountered BigInt larger than allowable range"));var l=[27|t,0,0,0,0,0,0,0],u=Number(s&BigInt(4294967295)),c=Number(s>>BigInt(32)&BigInt(4294967295));l[8]=255&u,u>>=8,l[7]=255&u,u>>=8,l[6]=255&u,u>>=8,l[5]=255&u,l[4]=255&c,c>>=8,l[3]=255&c,c>>=8,l[2]=255&c,c>>=8,l[1]=255&c,e.push(l)}}OP.encodedSize=function(e){return LP.encodedSize(e.value)},LP.encodedSize=function(e){return e<_P[0]?1:e<_P[1]?2:e<_P[2]?3:e<_P[3]?5:9},OP.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};var MP=BigInt(-1),UP=BigInt(1);function FP(e,t){var r=t.value,n="bigint"==typeof r?r*MP-UP:-1*r-1;LP(e,t.type.majorEncoded,n)}function zP(e,t,r,n){PP(e,t,r+n);var i=wP(e,t+r,t+r+n);return new cP(uP.bytes,i,r+n)}function jP(e,t,r,n){return zP(e,t,1,r)}function VP(e){return void 0===e.encodedBytes&&(e.encodedBytes=e.type===uP.string?yP(e.value):e.value),e.encodedBytes}function qP(e,t){var r=VP(t);LP(e,t.type.majorEncoded,r.length),e.push(r)}function HP(e,t,r,n,i){var o=r+n;PP(e,t,o);var a=new cP(uP.string,gP(e,t+r,t+o),o);return!0===i.retainStringBytes&&(a.byteValue=wP(e,t+r,t+o)),a}function KP(e,t,r,n){return HP(e,t,1,r,n)}FP.encodedSize=function(e){var t=e.value,r="bigint"==typeof t?t*MP-UP:-1*t-1;return r<_P[0]?1:r<_P[1]?2:r<_P[2]?3:r<_P[3]?5:9},FP.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0},qP.encodedSize=function(e){var t=VP(e);return LP.encodedSize(t.length)+t.length},qP.compareTokens=function(e,t){return r=VP(e),n=VP(t),r.length<n.length?-1:r.length>n.length?1:function(e,t){if(pP(e)&&pP(t))return e.compare(t);for(var r=0;r<e.length;r++)if(e[r]!==t[r])return e[r]<t[r]?-1:1;return 0}(r,n);var r,n};var WP=qP;function GP(e,t,r,n){return new cP(uP.array,n,r)}function QP(e,t,r,n){return GP(0,0,1,r)}function YP(e,t){LP(e,uP.array.majorEncoded,t.value)}function JP(e,t,r,n){return new cP(uP.map,n,r)}function ZP(e,t,r,n){return JP(0,0,1,r)}function $P(e,t){LP(e,uP.map.majorEncoded,t.value)}function XP(e,t,r,n){return new cP(uP.tag,r,1)}function e_(e,t){LP(e,uP.tag.majorEncoded,t.value)}YP.compareTokens=OP.compareTokens,YP.encodedSize=function(e){return LP.encodedSize(e.value)},$P.compareTokens=OP.compareTokens,$P.encodedSize=function(e){return LP.encodedSize(e.value)},e_.compareTokens=OP.compareTokens,e_.encodedSize=function(e){return LP.encodedSize(e.value)};function t_(e,t,r){if(r){if(!1===r.allowNaN&&Number.isNaN(e))throw new Error("".concat(IP," NaN values are not supported"));if(!1===r.allowInfinity&&(e===1/0||e===-1/0))throw new Error("".concat(IP," Infinity values are not supported"))}return new cP(uP.float,e,t)}function r_(e,t,r){var n,i=t.value;if(!1===i)e.push([20|uP.float.majorEncoded]);else if(!0===i)e.push([21|uP.float.majorEncoded]);else if(null===i)e.push([22|uP.float.majorEncoded]);else if(void 0===i)e.push([23|uP.float.majorEncoded]);else{var o=!1;r&&!0===r.float64||(a_(i),i===s_(o_,1)||Number.isNaN(i)?(o_[0]=249,e.push(o_.slice(0,3)),o=!0):(l_(i),i===u_(o_,1)&&(o_[0]=250,e.push(o_.slice(0,5)),o=!0))),o||(n=i,i_.setFloat64(0,n,!1),c_(o_,1),o_[0]=251,e.push(o_.slice(0,9)))}}r_.encodedSize=function(e,t){var r=e.value;if(!1===r||!0===r||null==r)return 1;if(!t||!0!==t.float64){a_(r);var n=s_(o_,1);if(r===n||Number.isNaN(r))return 3;if(l_(r),r===(n=u_(o_,1)))return 5}return 9};var n_=new ArrayBuffer(9),i_=new DataView(n_,1),o_=new Uint8Array(n_,0);function a_(e){if(e===1/0)i_.setUint16(0,31744,!1);else if(e===-1/0)i_.setUint16(0,64512,!1);else if(Number.isNaN(e))i_.setUint16(0,32256,!1);else{i_.setFloat32(0,e);var t=i_.getUint32(0),r=(2139095040&t)>>23,n=8388607&t;if(255===r)i_.setUint16(0,31744,!1);else if(0===r)i_.setUint16(0,(2147483648&e)>>16|n>>13,!1);else{var i=r-127;i<-24?i_.setUint16(0,0):i<-14?i_.setUint16(0,(2147483648&t)>>16|1<<24+i,!1):i_.setUint16(0,(2147483648&t)>>16|i+15<<10|n>>13,!1)}}}function s_(e,t){if(e.length-t<2)throw new Error("".concat(IP," not enough data for float16"));var r=(e[t]<<8)+e[t+1];if(31744===r)return 1/0;if(64512===r)return-1/0;if(32256===r)return NaN;var n,i=r>>10&31,o=1023&r;return n=0===i?o*2**-24:31!==i?(o+1024)*2**(i-25):0===o?1/0:NaN,32768&r?-n:n}function l_(e){i_.setFloat32(0,e,!1)}function u_(e,t){if(e.length-t<4)throw new Error("".concat(IP," not enough data for float32"));var r=(e.byteOffset||0)+t;return new DataView(e.buffer,r,4).getFloat32(0,!1)}function c_(e,t){if(e.length-t<8)throw new Error("".concat(IP," not enough data for float64"));var r=(e.byteOffset||0)+t;return new DataView(e.buffer,r,8).getFloat64(0,!1)}function d_(e,t,r){throw new Error("".concat(IP," encountered invalid minor (").concat(r,") for major ").concat(e[t]>>>5))}function h_(e){return()=>{throw new Error("".concat(IP," ").concat(e))}}r_.compareTokens=OP.compareTokens;for(var v_=[],p_=0;p_<=23;p_++)v_[p_]=d_;v_[24]=function(e,t,r,n){return new cP(uP.uint,BP(e,t+1,n),2)},v_[25]=function(e,t,r,n){return new cP(uP.uint,NP(e,t+1,n),3)},v_[26]=function(e,t,r,n){return new cP(uP.uint,DP(e,t+1,n),5)},v_[27]=function(e,t,r,n){return new cP(uP.uint,RP(e,t+1,n),9)},v_[28]=d_,v_[29]=d_,v_[30]=d_,v_[31]=d_;for(var f_=32;f_<=55;f_++)v_[f_]=d_;v_[56]=function(e,t,r,n){return new cP(uP.negint,-1-BP(e,t+1,n),2)},v_[57]=function(e,t,r,n){return new cP(uP.negint,-1-NP(e,t+1,n),3)},v_[58]=function(e,t,r,n){return new cP(uP.negint,-1-DP(e,t+1,n),5)},v_[59]=function(e,t,r,n){var i=RP(e,t+1,n);if("bigint"!=typeof i){var o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new cP(uP.negint,o,9)}if(!0!==n.allowBigInt)throw new Error("".concat(IP," integers outside of the safe integer range are not supported"));return new cP(uP.negint,MP-BigInt(i),9)},v_[60]=d_,v_[61]=d_,v_[62]=d_,v_[63]=d_;for(var g_=64;g_<=87;g_++)v_[g_]=jP;v_[88]=function(e,t,r,n){return zP(e,t,2,BP(e,t+1,n))},v_[89]=function(e,t,r,n){return zP(e,t,3,NP(e,t+1,n))},v_[90]=function(e,t,r,n){return zP(e,t,5,DP(e,t+1,n))},v_[91]=function(e,t,r,n){var i=RP(e,t+1,n);if("bigint"==typeof i)throw new Error("".concat(IP," 64-bit integer bytes lengths not supported"));return zP(e,t,9,i)},v_[92]=d_,v_[93]=d_,v_[94]=d_,v_[95]=h_("indefinite length bytes/strings are not supported");for(var y_=96;y_<=119;y_++)v_[y_]=KP;v_[120]=function(e,t,r,n){return HP(e,t,2,BP(e,t+1,n),n)},v_[121]=function(e,t,r,n){return HP(e,t,3,NP(e,t+1,n),n)},v_[122]=function(e,t,r,n){return HP(e,t,5,DP(e,t+1,n),n)},v_[123]=function(e,t,r,n){var i=RP(e,t+1,n);if("bigint"==typeof i)throw new Error("".concat(IP," 64-bit integer string lengths not supported"));return HP(e,t,9,i,n)},v_[124]=d_,v_[125]=d_,v_[126]=d_,v_[127]=h_("indefinite length bytes/strings are not supported");for(var m_=128;m_<=151;m_++)v_[m_]=QP;v_[152]=function(e,t,r,n){return GP(0,0,2,BP(e,t+1,n))},v_[153]=function(e,t,r,n){return GP(0,0,3,NP(e,t+1,n))},v_[154]=function(e,t,r,n){return GP(0,0,5,DP(e,t+1,n))},v_[155]=function(e,t,r,n){var i=RP(e,t+1,n);if("bigint"==typeof i)throw new Error("".concat(IP," 64-bit integer array lengths not supported"));return GP(0,0,9,i)},v_[156]=d_,v_[157]=d_,v_[158]=d_,v_[159]=function(e,t,r,n){if(!1===n.allowIndefinite)throw new Error("".concat(IP," indefinite length items not allowed"));return GP(0,0,1,1/0)};for(var w_=160;w_<=183;w_++)v_[w_]=ZP;v_[184]=function(e,t,r,n){return JP(0,0,2,BP(e,t+1,n))},v_[185]=function(e,t,r,n){return JP(0,0,3,NP(e,t+1,n))},v_[186]=function(e,t,r,n){return JP(0,0,5,DP(e,t+1,n))},v_[187]=function(e,t,r,n){var i=RP(e,t+1,n);if("bigint"==typeof i)throw new Error("".concat(IP," 64-bit integer map lengths not supported"));return JP(0,0,9,i)},v_[188]=d_,v_[189]=d_,v_[190]=d_,v_[191]=function(e,t,r,n){if(!1===n.allowIndefinite)throw new Error("".concat(IP," indefinite length items not allowed"));return JP(0,0,1,1/0)};for(var b_=192;b_<=215;b_++)v_[b_]=XP;v_[216]=function(e,t,r,n){return new cP(uP.tag,BP(e,t+1,n),2)},v_[217]=function(e,t,r,n){return new cP(uP.tag,NP(e,t+1,n),3)},v_[218]=function(e,t,r,n){return new cP(uP.tag,DP(e,t+1,n),5)},v_[219]=function(e,t,r,n){return new cP(uP.tag,RP(e,t+1,n),9)},v_[220]=d_,v_[221]=d_,v_[222]=d_,v_[223]=d_;for(var S_=224;S_<=243;S_++)v_[S_]=h_("simple values are not supported");v_[244]=d_,v_[245]=d_,v_[246]=d_,v_[247]=function(e,t,r,n){if(!1===n.allowUndefined)throw new Error("".concat(IP," undefined values are not supported"));return!0===n.coerceUndefinedToNull?new cP(uP.null,null,1):new cP(uP.undefined,void 0,1)},v_[248]=h_("simple values are not supported"),v_[249]=function(e,t,r,n){return t_(s_(e,t+1),3,n)},v_[250]=function(e,t,r,n){return t_(u_(e,t+1),5,n)},v_[251]=function(e,t,r,n){return t_(c_(e,t+1),9,n)},v_[252]=d_,v_[253]=d_,v_[254]=d_,v_[255]=function(e,t,r,n){if(!1===n.allowIndefinite)throw new Error("".concat(IP," indefinite length items not allowed"));return new cP(uP.break,void 0,1)};for(var E_=[],k_=0;k_<24;k_++)E_[k_]=new cP(uP.uint,k_,1);for(var x_=-1;x_>=-24;x_--)E_[31-x_]=new cP(uP.negint,x_,1);E_[64]=new cP(uP.bytes,new Uint8Array(0),1),E_[96]=new cP(uP.string,"",1),E_[128]=new cP(uP.array,0,1),E_[160]=new cP(uP.map,0,1),E_[244]=new cP(uP.false,!1,1),E_[245]=new cP(uP.true,!0,1),E_[246]=new cP(uP.null,null,1);var A_={float64:!1,mapSorter:function(e,t){var r=Array.isArray(e[0])?e[0][0]:e[0],n=Array.isArray(t[0])?t[0][0]:t[0];if(r.type!==n.type)return r.type.compare(n.type);var i=r.type.major,o=I_[i].compareTokens(r,n);return o},quickEncodeToken:function(e){switch(e.type){case uP.false:return mP([244]);case uP.true:return mP([245]);case uP.null:return mP([246]);case uP.bytes:return e.value.length?void 0:mP([64]);case uP.string:return""===e.value?mP([96]):void 0;case uP.array:return 0===e.value?mP([128]):void 0;case uP.map:return 0===e.value?mP([160]):void 0;case uP.uint:return e.value<24?mP([Number(e.value)]):void 0;case uP.negint:if(e.value>=-24)return mP([31-Number(e.value)])}}};var C_,I_=((C_=[])[uP.uint.major]=OP,C_[uP.negint.major]=FP,C_[uP.bytes.major]=qP,C_[uP.string.major]=WP,C_[uP.array.major]=YP,C_[uP.map.major]=$P,C_[uP.tag.major]=e_,C_[uP.float.major]=r_,C_),T_=new CP;class P_{constructor(e,t){this.obj=e,this.parent=t}includes(e){var t=this;do{if(t.obj===e)return!0}while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error("".concat(TP," object contains circular references"));return new P_(t,e)}}var __={null:new cP(uP.null,null),undefined:new cP(uP.undefined,void 0),true:new cP(uP.true,!0),false:new cP(uP.false,!1),emptyArray:new cP(uP.array,0),emptyMap:new cP(uP.map,0)},B_={number:(e,t,r,n)=>Number.isInteger(e)&&Number.isSafeInteger(e)?new cP(e>=0?uP.uint:uP.negint,e):new cP(uP.float,e),bigint:(e,t,r,n)=>e>=BigInt(0)?new cP(uP.uint,e):new cP(uP.negint,e),Uint8Array:(e,t,r,n)=>new cP(uP.bytes,e),string:(e,t,r,n)=>new cP(uP.string,e),boolean:(e,t,r,n)=>e?__.true:__.false,null:(e,t,r,n)=>__.null,undefined:(e,t,r,n)=>__.undefined,ArrayBuffer:(e,t,r,n)=>new cP(uP.bytes,new Uint8Array(e)),DataView:(e,t,r,n)=>new cP(uP.bytes,new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),Array(e,t,r,n){if(!e.length)return!0===r.addBreakTokens?[__.emptyArray,new cP(uP.break)]:__.emptyArray;n=P_.createCheck(n,e);var i=[],o=0;for(var a of e)i[o++]=D_(a,r,n);return r.addBreakTokens?[new cP(uP.array,e.length),i,new cP(uP.break)]:[new cP(uP.array,e.length),i]},Object(e,t,r,n){var i="Object"!==t,o=i?e.keys():Object.keys(e),a=i?e.size:o.length;if(!a)return!0===r.addBreakTokens?[__.emptyMap,new cP(uP.break)]:__.emptyMap;n=P_.createCheck(n,e);var s=[],l=0;for(var u of o)s[l++]=[D_(u,r,n),D_(i?e.get(u):e[u],r,n)];return function(e,t){t.mapSorter&&e.sort(t.mapSorter)}(s,r),r.addBreakTokens?[new cP(uP.map,a),s,new cP(uP.break)]:[new cP(uP.map,a),s]}};for(var N_ of(B_.Map=B_.Object,B_.Buffer=B_.Uint8Array,"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" ")))B_["".concat(N_,"Array")]=B_.DataView;function D_(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0,n=lP(e),i=t&&t.typeEncoders&&t.typeEncoders[n]||B_[n];if("function"==typeof i){var o=i(e,n,t,r);if(null!=o)return o}var a=B_[n];if(!a)throw new Error("".concat(TP," unsupported type: ").concat(n));return a(e,n,t,r)}function R_(e,t,r,n){if(Array.isArray(t))for(var i of t)R_(e,i,r,n);else r[t.type.major](e,t,n)}function O_(e,t,r){var n=D_(e,r);if(!Array.isArray(n)&&r.quickEncodeToken){var i=r.quickEncodeToken(n);if(i)return i;var o=t[n.type.major];if(o.encodedSize){var a=o.encodedSize(n,r),s=new CP(a);if(o(s,n,r),1!==s.chunks.length)throw new Error("Unexpected error: pre-calculated length for ".concat(n," was wrong"));return fP(s.chunks[0])}}return T_.reset(),R_(T_,n,t,r),T_.toBytes(!0)}function L_(e,t){return t=Object.assign({},A_,t),O_(e,I_,t)}var M_={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0};class U_{constructor(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){var e=this.data[this._pos],t=E_[e];if(void 0===t){var r=v_[e];if(!r)throw new Error("".concat(IP," no decoder for major type ").concat(e>>>5," (byte 0x").concat(e.toString(16).padStart(2,"0"),")"));var n=31&e;t=r(this.data,this._pos,n,this.options)}return this._pos+=t.encodedLength,t}}var F_=Symbol.for("DONE"),z_=Symbol.for("BREAK");function j_(e,t){if(e.done())return F_;var r=e.next();if(r.type===uP.break)return z_;if(r.type.terminal)return r.value;if(r.type===uP.array)return function(e,t,r){for(var n=[],i=0;i<e.value;i++){var o=j_(t,r);if(o===z_){if(e.value===1/0)break;throw new Error("".concat(IP," got unexpected break to lengthed array"))}if(o===F_)throw new Error("".concat(IP," found array but not enough entries (got ").concat(i,", expected ").concat(e.value,")"));n[i]=o}return n}(r,e,t);if(r.type===uP.map)return function(e,t,r){for(var n=!0===r.useMaps,i=n?void 0:{},o=n?new Map:void 0,a=0;a<e.value;a++){var s=j_(t,r);if(s===z_){if(e.value===1/0)break;throw new Error("".concat(IP," got unexpected break to lengthed map"))}if(s===F_)throw new Error("".concat(IP," found map but not enough entries (got ").concat(a," [no key], expected ").concat(e.value,")"));if(!0!==n&&"string"!=typeof s)throw new Error("".concat(IP," non-string keys not supported (got ").concat(typeof s,")"));if(!0===r.rejectDuplicateMapKeys&&(n&&o.has(s)||!n&&s in i))throw new Error("".concat(IP,' found repeat map key "').concat(s,'"'));var l=j_(t,r);if(l===F_)throw new Error("".concat(IP," found map but not enough entries (got ").concat(a," [no value], expected ").concat(e.value,")"));n?o.set(s,l):i[s]=l}return n?o:i}(r,e,t);if(r.type===uP.tag){if(t.tags&&"function"==typeof t.tags[r.value]){var n=j_(e,t);return t.tags[r.value](n)}throw new Error("".concat(IP," tag not supported (").concat(r.value,")"))}throw new Error("unsupported")}function V_(e,t){var[r,n]=function(e,t){if(!(e instanceof Uint8Array))throw new Error("".concat(IP," data to decode must be a Uint8Array"));var r=(t=Object.assign({},M_,t)).tokenizer||new U_(e,t),n=j_(r,t);if(n===F_)throw new Error("".concat(IP," did not find any content to decode"));if(n===z_)throw new Error("".concat(IP," got unexpected break"));return[n,e.subarray(r.pos())]}(e,t);if(n.length>0)throw new Error("".concat(IP," too many terminals, data makes no sense"));return r}function q_(){var{enumerable:e=!0,configurable:t=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{enumerable:e,configurable:t,writable:!1}}function*H_(e,t){if(null!=t&&"object"==typeof t)if(Array.isArray(t))for(var[r,n]of t.entries()){var i=[...e,r],o=it.asCID(n);null!=o?yield[i.join("/"),o]:"object"==typeof n&&(yield*K_(n,i))}else{var a=it.asCID(t);null!=a?yield[e.join("/"),a]:yield*K_(t,e)}}function*K_(e,t){if(!(null==e||e instanceof Uint8Array)){var r=it.asCID(e);for(var[n,i]of(null!=r&&(yield[t.join("/"),r]),Object.entries(e))){var o=[...t,n];yield*H_(o,i)}}}function*W_(e,t){if(Array.isArray(t))for(var[r,n]of t.entries()){var i=[...e,r];yield i.join("/"),"object"==typeof n&&null==it.asCID(n)&&(yield*G_(n,i))}else yield*G_(t,e)}function*G_(e,t){if(null!=e&&"object"==typeof e)for(var[r,n]of Object.entries(e)){var i=[...t,r];yield i.join("/"),null==n||n instanceof Uint8Array||"object"!=typeof n||null!=it.asCID(n)||(yield*W_(i,n))}}class Q_{constructor(t){var{cid:r,bytes:n,value:i}=t;if(e(this,"cid",void 0),e(this,"bytes",void 0),e(this,"value",void 0),e(this,"asBlock",void 0),null==r||null==n||void 0===i)throw new Error("Missing required argument");this.cid=r,this.bytes=n,this.value=i,this.asBlock=this,Object.defineProperties(this,{cid:q_(),bytes:q_(),value:q_(),asBlock:q_()})}links(){return K_(this.value,[])}tree(){return G_(this.value,[])}get(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/";return function(e,t){var r=e;for(var[n,i]of t.entries()){if(null==(r=r[i]))throw new Error("Object has no property at ".concat(t.slice(0,n+1).map((e=>"[".concat(JSON.stringify(e),"]"))).join("")));var o=it.asCID(r);if(null!=o)return{value:o,remaining:t.slice(n+1).join("/")}}return{value:r}}(this.value,e.split("/").filter(Boolean))}}var Y_="/pin/",J_="/pinned-block/",Z_=te;function $_(e){return 0===e.version&&(e=e.toV1()),new hc("".concat(Y_).concat(e.toString(Z_)))}var X_=new WeakSet;class eB{constructor(t,r,n){d(this,X_),e(this,"datastore",void 0),e(this,"blockstore",void 0),e(this,"getCodec",void 0),this.datastore=t,this.blockstore=r,this.getCodec=n}add(e){var r=this;return l((function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(i,o){var a=$_(e);if(yield u(r.datastore.has(a)))throw new Error("Already pinned");var l=Math.round(null!==(i=n.depth)&&void 0!==i?i:1/0);if(l<0)throw new Error("Depth must be greater than or equal to 0");var c,d=new wv({concurrency:1}),v=!1,p=!1;try{for(var f,g=s(h(X_,r,tB).call(r,e,d,t(t({},n),{},{depth:l})));v=!(f=yield u(g.next())).done;v=!1){var y=f.value;yield u(h(X_,r,rB).call(r,y,(t=>null==t.pinnedBy.find((t=>Et(t,e.bytes)))&&(t.pinCount++,t.pinnedBy.push(e.bytes),!0)),n)),yield y}}catch(e){p=!0,c=e}finally{try{v&&null!=g.return&&(yield u(g.return()))}finally{if(p)throw c}}var m={depth:l,metadata:null!==(o=n.metadata)&&void 0!==o?o:{}};yield u(r.datastore.put(a,L_(m),n))}()})).apply(this,arguments)}rm(e){var r=this;return l((function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var i=$_(e),o=V_(yield u(r.datastore.get(i,n)));yield u(r.datastore.delete(i,n));var a,l=new wv({concurrency:1}),c=!1,d=!1;try{for(var v,p=s(h(X_,r,tB).call(r,e,l,t(t({},n),{},{depth:o.depth})));c=!(v=yield u(p.next())).done;c=!1){var f=v.value;yield u(h(X_,r,rB).call(r,f,(t=>(t.pinCount--,t.pinnedBy=t.pinnedBy.filter((t=>Et(t,e.bytes))),!0)),t(t({},n),{},{depth:o.depth}))),yield f}}catch(e){d=!0,a=e}finally{try{c&&null!=p.return&&(yield u(p.return()))}finally{if(d)throw a}}}()})).apply(this,arguments)}ls(){var e=this;return l((function(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var n,i=!1,o=!1;try{for(var a,l=s(e.datastore.query({prefix:Y_+(null!=r.cid?"".concat(r.cid.toString(te)):"")},r));i=!(a=yield u(l.next())).done;i=!1){var{key:c,value:d}=a.value,h=it.parse(c.toString().substring(5),te),v=V_(d);yield t({cid:h},v)}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}()})).apply(this,arguments)}isPinned(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{},i=new hc("".concat(J_).concat(Z_.encode(e.multihash.bytes)));return n.datastore.has(i,r)}))()}get(e,t){var n=this;return r((function*(){var r=$_(e);return V_(yield n.datastore.get(r,t))}))()}setMetadata(e,t,n){var i=this;return r((function*(){var r=$_(e),o=V_(yield i.datastore.get(r,n));o.metadata=null!=t?t:{},yield i.datastore.put(r,L_(o),n)}))()}}function tB(e,n,i){var o=this;return l((function*(){if(-1!==i.depth){var a=yield u(o.getCodec(e.code)),l=function(e){var{bytes:t,cid:r,value:n,codec:i}=e,o=void 0!==n?n:null==i?void 0:i.decode(t);if(void 0===o)throw new Error('Missing required argument, must either provide "value" or "codec"');return new Q_({cid:r,bytes:t,value:o})}({bytes:yield u(o.blockstore.get(e,i)),cid:e,codec:a});yield e;var d=function*(e){yield*c(s(yield u(n.add(r((function*(){return h(X_,o,tB).call(o,e,n,t(t({},i),{},{depth:i.depth-1}))}))))))};for(var[,v]of l.links())yield*d(v)}}))()}function rB(e,t,r){return nB.apply(this,arguments)}function nB(){return nB=r((function*(e,t,r){var n,i=new hc("".concat(J_).concat(Z_.encode(e.multihash.bytes))),o={pinCount:0,pinnedBy:[]};try{o=V_(yield this.datastore.get(i,r))}catch(e){if("NotFoundError"!==e.name)throw e}t(o)&&(0===o.pinCount&&(yield this.datastore.has(i))?yield this.datastore.delete(i):(yield this.datastore.put(i,L_(o),r),null===(n=r.onProgress)||void 0===n||n.call(r,new cv("helia:pin:add",e))))})),nB.apply(this,arguments)}class iB extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Insufficient providers found"),this.name="InsufficientProvidersError"}}e(iB,"name","InsufficientProvidersError");class oB extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No routers available"),this.name="NoRoutersAvailableError"}}e(oB,"name","NoRoutersAvailableError");class aB extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unknown hash algorithm"),this.name="UnknownHashAlgorithmError"}}e(aB,"name","UnknownHashAlgorithmError");class sB extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unknown codec"),this.name="UnknownCodecError"}}e(sB,"name","UnknownCodecError");class lB{constructor(t,r){var n,i,o,a,s,l,u,c,d,h,v,p,f,g,y,m;e(this,"log",void 0),e(this,"routers",void 0),e(this,"providerLookupConcurrency",void 0),this.log=t.logger.forComponent("helia:routing"),this.routers=null!==(n=r.routers)&&void 0!==n?n:[],this.providerLookupConcurrency=null!==(i=r.providerLookupConcurrency)&&void 0!==i?i:5,this.findProviders=null!==(o=null===(a=t.metrics)||void 0===a?void 0:a.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1}))&&void 0!==o?o:this.findProviders,this.provide=null!==(s=null===(l=t.metrics)||void 0===l?void 0:l.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1}))&&void 0!==s?s:this.provide,this.cancelReprovide=null!==(u=null===(c=t.metrics)||void 0===c?void 0:c.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1}))&&void 0!==u?u:this.cancelReprovide,this.put=null!==(d=null===(h=t.metrics)||void 0===h?void 0:h.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2}))&&void 0!==d?d:this.put,this.get=null!==(v=null===(p=t.metrics)||void 0===p?void 0:p.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1}))&&void 0!==v?v:this.get,this.findPeer=null!==(f=null===(g=t.metrics)||void 0===g?void 0:g.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1}))&&void 0!==f?f:this.findPeer,this.getClosestPeers=null!==(y=null===(m=t.metrics)||void 0===m?void 0:m.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1}))&&void 0!==y?y:this.getClosestPeers}start(){var e=this;return r((function*(){yield ds(...e.routers)}))()}stop(){var e=this;return r((function*(){yield vs(...e.routers)}))()}findProviders(e){var t=this;return l((function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(0===t.routers.length)throw new oB("No content routers available");var i=new bv({concurrency:t.providerLookupConcurrency});i.addEventListener("error",(()=>{}));var o,a=!1,l=!1;try{for(var c,d=function*(){var e=c.value;if(null==e)return 0;if(0===e.multiaddrs.length){if(null!=i.find(e.id))return 0;i.add(r((function*(){try{var r=yield t.findPeer(e.id,n);return 0===r.multiaddrs.length?null:r}catch(r){return t.log.error("could not load multiaddrs for peer %p",e.id,r),null}})),{peerId:e.id,signal:n.signal}).catch((r=>{t.log.error("could not load multiaddrs for peer %p",e.id,r)}))}yield e},h=s(Vc(i.toGenerator(),...uB(t.routers,"findProviders").map((t=>t.findProviders(e,n)))));a=!(c=yield u(h.next())).done;a=!1)yield*d()}catch(e){l=!0,o=e}finally{try{a&&null!=h.return&&(yield u(h.return()))}finally{if(l)throw o}}}()})).apply(this,arguments)}provide(e){var t=arguments,n=this;return r((function*(){var i=t.length>1&&void 0!==t[1]?t[1]:{};if(0===n.routers.length)throw new oB("No content routers available");yield Promise.all(uB(n.routers,"provide").map(function(){var t=r((function*(t){yield t.provide(e,i)}));return function(e){return t.apply(this,arguments)}}()))}))()}cancelReprovide(e){var t=arguments,n=this;return r((function*(){var i=t.length>1&&void 0!==t[1]?t[1]:{};yield Promise.all(uB(n.routers,"cancelReprovide").map(function(){var t=r((function*(t){yield t.cancelReprovide(e,i)}));return function(e){return t.apply(this,arguments)}}()))}))()}put(e,t,n){var i=this;return r((function*(){yield Promise.all(uB(i.routers,"put").map(function(){var i=r((function*(r){yield r.put(e,t,n)}));return function(e){return i.apply(this,arguments)}}()))}))()}get(e,t){var n=this;return r((function*(){return Promise.any(uB(n.routers,"get").map(function(){var n=r((function*(r){return r.get(e,t)}));return function(e){return n.apply(this,arguments)}}()))}))()}findPeer(e,t){var n=this;return r((function*(){if(0===n.routers.length)throw new oB("No peer routers available");var r,i=n,o=Vc(...uB(n.routers,"findPeer").map((r=>l((function*(){try{yield yield u(r.findPeer(e,t))}catch(e){i.log.error(e)}}))()))),a=!1,c=!1;try{for(var d,h=s(o);a=!(d=yield h.next()).done;a=!1){var v=d.value;if(null!=v)return v}}catch(e){c=!0,r=e}finally{try{a&&null!=h.return&&(yield h.return())}finally{if(c)throw r}}throw new Ha("Could not find peer in routing")}))()}getClosestPeers(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(0===t.routers.length)throw new oB("No peer routers available");var n,i=!1,o=!1;try{for(var a,l=s(Vc(...uB(t.routers,"getClosestPeers").map((t=>t.getClosestPeers(e,r)))));i=!(a=yield u(l.next())).done;i=!1){var c=a.value;null!=c&&(yield c)}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}()})).apply(this,arguments)}}function uB(e,t){return e.filter((e=>null!=e[t]))}let cB=class extends Error{constructor(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The operation was aborted",t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];super(e,...r)}};var dB=new WeakMap;class hB extends EventTarget{constructor(){super(),n(this,dB,new Map)}listenerCount(e){var t=o(dB,this).get(e);return null==t?0:t.length}addEventListener(e,t,r){var n;super.addEventListener(e,t,r);var i=o(dB,this).get(e);null==i&&(i=[],o(dB,this).set(e,i)),i.push({callback:t,once:null!==(n=!0!==r&&!1!==r&&(null==r?void 0:r.once))&&void 0!==n&&n})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),null!=t?t:null,r);var n=o(dB,this).get(e);null!=n&&(n=n.filter((e=>{var{callback:r}=e;return r!==t})),o(dB,this).set(e,n))}dispatchEvent(e){var t=super.dispatchEvent(e),r=o(dB,this).get(e.type);return null==r||(r=r.filter((e=>{var{once:t}=e;return!t})),o(dB,this).set(e.type,r)),t}safeDispatchEvent(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.dispatchEvent(new CustomEvent(e,t))}}class vB extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The queue was full"),this.name="QueueFullError"}}e(vB,"name","QueueFullError");class pB{constructor(t){var r;e(this,"deferred",void 0),e(this,"signal",void 0),this.signal=t,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),null===(r=this.signal)||void 0===r||r.addEventListener("abort",this.onAbort)}onAbort(){var e,t;this.deferred.reject(null!==(e=null===(t=this.signal)||void 0===t?void 0:t.reason)&&void 0!==e?e:new cB)}cleanup(){var e;null===(e=this.signal)||void 0===e||e.removeEventListener("abort",this.onAbort)}}class fB{constructor(t,r){e(this,"id",void 0),e(this,"fn",void 0),e(this,"options",void 0),e(this,"recipients",void 0),e(this,"status",void 0),e(this,"timeline",void 0),e(this,"controller",void 0),this.id="".concat(parseInt(String(1e9*Math.random()),10).toString()).concat(Date.now()),this.status="queued",this.fn=t,this.options=r,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(){var e=this.recipients.reduce(((e,t)=>{var r;return e&&!0===(null===(r=t.signal)||void 0===r?void 0:r.aborted)}),!0);e&&(this.controller.abort(new cB),this.cleanup())}join(){var e=arguments,t=this;return r((function*(){var r,n=e.length>0&&void 0!==e[0]?e[0]:{},i=new pB(n.signal);return t.recipients.push(i),null===(r=n.signal)||void 0===r||r.addEventListener("abort",t.onAbort),i.deferred.promise}))()}run(){var e=this;return r((function*(){e.status="running",e.timeline.started=Date.now();try{var r;e.controller.signal.throwIfAborted();var n=yield Lc(e.fn(t(t({},null!==(r=e.options)&&void 0!==r?r:{}),{},{signal:e.controller.signal})),e.controller.signal);e.recipients.forEach((e=>{e.deferred.resolve(n)})),e.status="complete"}catch(t){e.recipients.forEach((e=>{e.deferred.reject(t)})),e.status="errored"}finally{e.timeline.finished=Date.now(),e.cleanup()}}))()}cleanup(){this.recipients.forEach((e=>{var t;e.cleanup(),null===(t=e.signal)||void 0===t||t.removeEventListener("abort",this.onAbort)}))}}function gB(e,t){var r,n=function(){clearTimeout(r),r=setTimeout((function(){r=void 0,e()}),t)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}class yB extends hB{constructor(){var t,r,n,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),e(this,"concurrency",void 0),e(this,"maxSize",void 0),e(this,"queue",void 0),e(this,"pending",void 0),e(this,"sort",void 0),e(this,"autoStart",void 0),this.concurrency=null!==(t=i.concurrency)&&void 0!==t?t:Number.POSITIVE_INFINITY,this.maxSize=null!==(r=i.maxSize)&&void 0!==r?r:Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=null===(n=i.autoStart)||void 0===n||n,this.sort=i.sort,this.queue=[],this.emitEmpty=gB(this.emitEmpty.bind(this),1),this.emitIdle=gB(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){var e;for(var t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally((()=>{for(var 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}add(e,t){var n=this;return r((function*(){var r;if(null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),n.size===n.maxSize)throw new vB;var i=new fB(e,t);return n.enqueue(i),n.safeDispatchEvent("add"),n.autoStart&&n.tryToStartAnother(),i.join(t).then((e=>(n.safeDispatchEvent("success",{detail:{job:i,result:e}}),e))).catch((e=>{if("queued"===i.status)for(var t=0;t<n.queue.length;t++)if(n.queue[t]===i){n.queue.splice(t,1);break}throw n.safeDispatchEvent("failure",{detail:{job:i,error:e}}),e}))}))()}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach((e=>{e.abort(new cB)})),this.clear()}onEmpty(e){var t=this;return r((function*(){0!==t.size&&(yield hv(t,"empty",null==e?void 0:e.signal))}))()}onSizeLessThan(e,t){var n=this;return r((function*(){n.size<e||(yield hv(n,"next",null==t?void 0:t.signal,{filter:()=>n.size<e}))}))()}onIdle(e){var t=this;return r((function*(){0===t.pending&&0===t.size||(yield hv(t,"idle",null==e?void 0:e.signal))}))()}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}toGenerator(e){var t=this;return l((function*(){var r,n;null==e||null===(r=e.signal)||void 0===r||r.throwIfAborted();var i=Rc({objectMode:!0}),o=e=>{null!=e?t.abort():t.clear(),i.end(e)},a=e=>{null!=e.detail&&i.push(e.detail.result)},l=e=>{o(e.detail.error)},d=()=>{o()},h=()=>{o(new cB("Queue aborted"))};t.addEventListener("success",a),t.addEventListener("failure",l),t.addEventListener("idle",d),null==e||null===(n=e.signal)||void 0===n||n.addEventListener("abort",h);try{yield*c(s(i),u)}finally{var v;t.removeEventListener("success",a),t.removeEventListener("failure",l),t.removeEventListener("idle",d),null==e||null===(v=e.signal)||void 0===v||v.removeEventListener("abort",h),o()}}))()}}var mB="lock:worker:request-read",wB="lock:worker:abort-read-request",bB="lock:worker:release-read",SB="lock:master:grant-read",EB="lock:master:error-read",kB="lock:worker:request-write",xB="lock:worker:abort-write-request",AB="lock:worker:release-write",CB="lock:master:grant-write",IB="lock:master:error-write",TB="lock:worker:finalize",PB="mortice",_B={singleProcess:!1},BB=(e,t,n,i,o,a,s,l,u)=>c=>{if(null!=c.data){var d,h={type:c.data.type,name:c.data.name,identifier:c.data.identifier};h.type===o&&e.safeDispatchEvent(n,{detail:{name:h.name,identifier:h.identifier,handler:(d=r((function*(){t.postMessage({type:u,name:h.name,identifier:h.identifier}),yield new Promise((e=>{var r=n=>{if(null!=(null==n?void 0:n.data)){var i=n.data.type,o=(n.data.name,n.data.identifier);i===l&&o===h.identifier&&(t.removeEventListener("message",r),e())}};t.addEventListener("message",r)}))})),function(){return d.apply(this,arguments)}),onError:e=>{t.postMessage({type:s,name:h.name,identifier:h.identifier,error:{message:e.message,name:e.name,stack:e.stack}})}}}),h.type===a&&e.safeDispatchEvent(i,{detail:{name:h.name,identifier:h.identifier}}),h.type===TB&&e.safeDispatchEvent("finalizeRequest",{detail:{name:h.name}})}};class NB{constructor(t){e(this,"name",void 0),e(this,"channel",void 0),this.name=t,this.channel=new BroadcastChannel(PB)}readLock(e){return this.sendRequest(mB,wB,SB,EB,bB,e)}writeLock(e){return this.sendRequest(kB,xB,CB,IB,AB,e)}finalize(){this.channel.postMessage({type:TB,name:this.name}),this.channel.close()}sendRequest(e,t,n,i,o,a){var s=this;return r((function*(){var r;null==a||null===(r=a.signal)||void 0===r||r.throwIfAborted();var l=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;return Math.random().toString().substring(2,e+2)}();return s.channel.postMessage({type:e,identifier:l,name:s.name}),new Promise(((e,r)=>{var u,c=()=>{s.channel.postMessage({type:t,identifier:l,name:s.name})};null==a||null===(u=a.signal)||void 0===u||u.addEventListener("abort",c,{once:!0});var d=t=>{var u,h;if((null===(u=t.data)||void 0===u?void 0:u.identifier)===l){var v;if((null===(h=t.data)||void 0===h?void 0:h.type)===n)s.channel.removeEventListener("message",d),null==a||null===(v=a.signal)||void 0===v||v.removeEventListener("abort",c),e((()=>{s.channel.postMessage({type:o,identifier:l,name:s.name})}));if(t.data.type===i){var p;s.channel.removeEventListener("message",d),null==a||null===(p=a.signal)||void 0===p||p.removeEventListener("abort",c);var f=new Error;null!=t.data.error&&(f.message=t.data.error.message,f.name=t.data.error.name,f.stack=t.data.error.stack),r(f)}}};s.channel.addEventListener("message",d)}))}))()}}var DB,RB=new Map;function OB(e){return"function"==typeof(null==e?void 0:e.readLock)&&"function"==typeof(null==e?void 0:e.writeLock)}function LB(e){if(null==DB&&(DB=(e=>{if(e=Object.assign({},_B,e),Boolean(globalThis.document)||e.singleProcess){var t=new BroadcastChannel(PB),r=new hB;return t.addEventListener("message",BB(r,t,"requestReadLock","abortReadLockRequest",mB,wB,EB,bB,SB)),t.addEventListener("message",BB(r,t,"requestWriteLock","abortWriteLockRequest",kB,xB,IB,AB,CB)),r}return new NB(e.name)})(e),!OB(DB))){var t=DB;t.addEventListener("requestReadLock",(e=>{var n=e.detail.name,i=e.detail.identifier,o=RB.get(n);if(null!=o){var a=new AbortController,s=e=>{e.detail.name===n&&e.detail.identifier===i&&a.abort()};t.addEventListener("abortReadLockRequest",s),o.readLock({signal:a.signal}).then(function(){var t=r((function*(t){yield e.detail.handler().finally((()=>{t()}))}));return function(e){return t.apply(this,arguments)}}()).catch((t=>{e.detail.onError(t)})).finally((()=>{t.removeEventListener("abortReadLockRequest",s)}))}})),t.addEventListener("requestWriteLock",(e=>{var n=e.detail.name,i=e.detail.identifier,o=RB.get(n);if(null!=o){var a=new AbortController,s=e=>{e.detail.name===n&&e.detail.identifier===i&&a.abort()};t.addEventListener("abortWriteLockRequest",s),o.writeLock({signal:a.signal}).then(function(){var t=r((function*(t){yield e.detail.handler().finally((()=>{t()}))}));return function(e){return t.apply(this,arguments)}}()).catch((t=>{e.detail.onError(t)})).finally((()=>{t.removeEventListener("abortWriteLockRequest",s)}))}})),t.addEventListener("finalizeRequest",(e=>{var t=e.detail.name,r=RB.get(t);null!=r&&r.finalize()}))}return DB}function MB(e,t){return UB.apply(this,arguments)}function UB(){return UB=r((function*(e,t){var n,i,o,a=new Promise(((e,t)=>{i=e,o=t})),s=()=>{o(new cB)};return null==t||null===(n=t.signal)||void 0===n||n.addEventListener("abort",s,{once:!0}),e.add(r((function*(){yield new Promise((e=>{i((()=>{var r;null==t||null===(r=t.signal)||void 0===r||r.removeEventListener("abort",s),e()}))}))})),{signal:null==t?void 0:t.signal}).catch((e=>{o(e)})),a})),UB.apply(this,arguments)}var FB={name:"lock",concurrency:1/0,singleProcess:!1};function zB(e){var t=Object.assign({},FB,e);return((e,t)=>{var n=RB.get(e);if(null!=n)return n;var i=LB(t);if(OB(i))return n=i,RB.set(e,n),n;var o,a=new yB({concurrency:1});return n={readLock:e=>r((function*(){if(null!=o)return MB(o,e);var n=o=new yB({concurrency:t.concurrency,autoStart:!1}),i=MB(o,e);return a.add(r((function*(){n.start(),yield n.onIdle().then((()=>{o===n&&(o=null)}))}))),i}))(),writeLock:e=>r((function*(){return o=null,MB(a,e)}))(),finalize:()=>{RB.delete(e)},queue:a},RB.set(e,n),n})(t.name,t)}class jB{constructor(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e(this,"lock",void 0),e(this,"child",void 0),e(this,"pins",void 0),e(this,"started",void 0),this.child=t,this.pins=r,this.lock=zB({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}start(){var e=this;return r((function*(){yield ds(e.child),e.started=!0}))()}stop(){var e=this;return r((function*(){yield vs(e.child),e.started=!1}))()}unwrap(){return this.child}put(e,t){var n=arguments,i=this;return r((function*(){var r,o=n.length>2&&void 0!==n[2]?n[2]:{};null==o||null===(r=o.signal)||void 0===r||r.throwIfAborted();var a=yield i.lock.readLock();try{return yield i.child.put(e,t,o)}finally{a()}}))()}putMany(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(n){null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted();var i=yield u(t.lock.readLock());try{yield*c(s(t.child.putMany(e,r)),u)}finally{i()}}()})).apply(this,arguments)}get(e){var t=arguments,n=this;return r((function*(){var r,i=t.length>1&&void 0!==t[1]?t[1]:{};null==i||null===(r=i.signal)||void 0===r||r.throwIfAborted();var o=yield n.lock.readLock();try{return yield n.child.get(e,i)}finally{o()}}))()}getMany(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(n){null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted();var i=yield u(t.lock.readLock());try{yield*c(s(t.child.getMany(e,r)),u)}finally{i()}}()})).apply(this,arguments)}delete(e){var t=arguments,n=this;return r((function*(){var r,i=t.length>1&&void 0!==t[1]?t[1]:{};null==i||null===(r=i.signal)||void 0===r||r.throwIfAborted();var o=yield n.lock.writeLock();try{if(yield n.pins.isPinned(e))throw new Error("CID was pinned");yield n.child.delete(e,i)}finally{o()}}))()}deleteMany(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(n){null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted();var i=yield u(t.lock.writeLock());try{var o=t;yield*c(s(t.child.deleteMany(l((function*(){var t,r=!1,n=!1;try{for(var i,a=s(e);r=!(i=yield u(a.next())).done;r=!1){var l=i.value;if(yield u(o.pins.isPinned(l)))throw new Error("CID was pinned");yield l}}catch(e){n=!0,t=e}finally{try{r&&null!=a.return&&(yield u(a.return()))}finally{if(n)throw t}}}))(),r)),u)}finally{i()}}()})).apply(this,arguments)}has(e){var t=arguments,n=this;return r((function*(){var r,i=t.length>1&&void 0!==t[1]?t[1]:{};null==i||null===(r=i.signal)||void 0===r||r.throwIfAborted();var o=yield n.lock.readLock();try{return yield n.child.has(e,i)}finally{o()}}))()}getAll(){var e=this;return l((function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(r){null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted();var n=yield u(e.lock.readLock());try{yield*c(s(e.child.getAll(t)),u)}finally{n()}}()})).apply(this,arguments)}createSession(e,t){var r;return null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.child.createSession(e,t)}}var VB=new hc("/version");function qB(){return(qB=r((function*(e){if(yield e.has(VB)){var t=gt(yield e.get(VB));if(1!==parseInt(t,10))throw new Error("Unknown datastore version, a datastore migration may be required")}else yield e.put(VB,xt("".concat(1)))}))).apply(this,arguments)}function HB(e){return e instanceof ArrayBuffer?new Uint8Array(e,0,e.byteLength):e}var KB={float64:!0,typeEncoders:{Object:function(e){if(e.asCID!==e&&e["/"]!==e.bytes)return null;var t=it.asCID(e);if(!t)return null;var r=new Uint8Array(t.bytes.byteLength+1);return r.set(t.bytes,1),[new cP(uP.tag,42),new cP(uP.bytes,r)]},undefined:function(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")},number:function(e){if(Number.isNaN(e))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(e===1/0||e===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}}},WB=t(t({},KB),{},{typeEncoders:t({},KB.typeEncoders)});var GB={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};GB.tags[42]=function(e){if(0!==e[0])throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return it.decode(e.subarray(1))};var QB=t(t({},GB),{},{tags:GB.tags.slice()}),YB="dag-cbor",JB=113,ZB=e=>L_(e,KB),$B=e=>V_(HB(e),GB),XB=Object.freeze({__proto__:null,code:JB,decode:$B,decodeOptions:QB,encode:ZB,encodeOptions:WB,name:YB,toByteView:HB});class eN extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){var t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===uP.array&&(t.elements++,1!==t.elements&&e.push([44])),t.type===uP.map&&(t.elements++,1!==t.elements&&(t.elements%2==1?e.push([44]):e.push([58]))))}[uP.uint.major](e,t){this.prefix(e);for(var r=String(t.value),n=[],i=0;i<r.length;i++)n[i]=r.charCodeAt(i);e.push(n)}[uP.negint.major](e,t){this[uP.uint.major](e,t)}[uP.bytes.major](e,t){throw new Error("".concat(TP," unsupported type: Uint8Array"))}[uP.string.major](e,t){this.prefix(e);var r=yP(JSON.stringify(t.value));e.push(r.length>32?fP(r):r)}[uP.array.major](e,t){this.prefix(e),this.inRecursive.push({type:uP.array,elements:0}),e.push([91])}[uP.map.major](e,t){this.prefix(e),this.inRecursive.push({type:uP.map,elements:0}),e.push([123])}[uP.tag.major](e,t){}[uP.float.major](e,t){if("break"===t.type.name){var r=this.inRecursive.pop();if(r){if(r.type===uP.array)e.push([93]);else{if(r.type!==uP.map)throw new Error("Unexpected recursive type; this should not happen!");e.push([125])}return}throw new Error("Unexpected break; this should not happen!")}if(void 0===t.value)throw new Error("".concat(TP," unsupported type: undefined"));if(this.prefix(e),"true"!==t.type.name)if("false"!==t.type.name)if("null"!==t.type.name){for(var n=String(t.value),i=[],o=!1,a=0;a<n.length;a++)i[a]=n.charCodeAt(a),o||46!==i[a]&&101!==i[a]&&69!==i[a]||(o=!0);o||(i.push(46),i.push(48)),e.push(i)}else e.push([110,117,108,108]);else e.push([102,97,108,115,101]);else e.push([116,114,117,101])}}var tN={addBreakTokens:!0,mapSorter:function(e,t){if(Array.isArray(e[0])||Array.isArray(t[0]))throw new Error("".concat(TP," complex map keys are not supported"));var r=e[0],n=t[0];if(r.type!==uP.string||n.type!==uP.string)throw new Error("".concat(TP," non-string map keys are not supported"));if(r<n)return-1;if(r>n)return 1;throw new Error("".concat(TP," unexpected duplicate map keys, this is not supported"))}};class rN{constructor(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){for(var e=this.ch();32===e||9===e||13===e||10===e;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error("".concat(IP," unexpected end of input at position ").concat(this._pos));for(var t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error("".concat(IP," unexpected token at position ").concat(this._pos,", expected to find '").concat(String.fromCharCode(...e),"'"))}parseNumber(){var e=this._pos,t=!1,r=!1,n=e=>{for(;!this.done();){var t=this.ch();if(!e.includes(t))break;this._pos++}};if(45===this.ch()&&(t=!0,this._pos++),48===this.ch()){if(this._pos++,46!==this.ch())return new cP(uP.uint,0,this._pos-e);this._pos++,r=!0}if(n([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error("".concat(IP," unexpected token at position ").concat(this._pos));if(!this.done()&&46===this.ch()){if(r)throw new Error("".concat(IP," unexpected token at position ").concat(this._pos));r=!0,this._pos++,n([48,49,50,51,52,53,54,55,56,57])}this.done()||101!==this.ch()&&69!==this.ch()||(r=!0,this._pos++,this.done()||43!==this.ch()&&45!==this.ch()||this._pos++,n([48,49,50,51,52,53,54,55,56,57]));var i=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),o=parseFloat(i);return r?new cP(uP.float,o,this._pos-e):!0!==this.options.allowBigInt||Number.isSafeInteger(o)?new cP(o>=0?uP.uint:uP.negint,o,this._pos-e):new cP(o>=0?uP.uint:uP.negint,BigInt(i),this._pos-e)}parseString(){if(34!==this.ch())throw new Error("".concat(IP," unexpected character at position ").concat(this._pos,"; this shouldn't happen"));this._pos++;for(var e=this._pos,t=0;e<this.data.length&&t<65536;e++,t++){var r=this.data[e];if(92===r||r<32||r>=128)break;if(34===r){var n=String.fromCharCode.apply(null,this.data.subarray(this._pos,e));return this._pos=e+1,new cP(uP.string,n,t)}}for(var i=this._pos,o=[],a=()=>{if(this._pos+4>=this.data.length)throw new Error("".concat(IP," unexpected end of unicode escape sequence at position ").concat(this._pos));for(var e=0,t=0;t<4;t++){var r=this.ch();if(r>=48&&r<=57)r-=48;else if(r>=97&&r<=102)r=r-97+10;else{if(!(r>=65&&r<=70))throw new Error("".concat(IP," unexpected unicode escape character at position ").concat(this._pos));r=r-65+10}e=16*e+r,this._pos++}return e},s=()=>{var e,t,r,n,i=this.ch(),a=null,s=i>239?4:i>223?3:i>191?2:1;if(this._pos+s>this.data.length)throw new Error("".concat(IP," unexpected unicode sequence at position ").concat(this._pos));switch(s){case 1:i<128&&(a=i);break;case 2:128==(192&(e=this.data[this._pos+1]))&&(n=(31&i)<<6|63&e)>127&&(a=n);break;case 3:e=this.data[this._pos+1],t=this.data[this._pos+2],128==(192&e)&&128==(192&t)&&(n=(15&i)<<12|(63&e)<<6|63&t)>2047&&(n<55296||n>57343)&&(a=n);break;case 4:e=this.data[this._pos+1],t=this.data[this._pos+2],r=this.data[this._pos+3],128==(192&e)&&128==(192&t)&&128==(192&r)&&(n=(15&i)<<18|(63&e)<<12|(63&t)<<6|63&r)>65535&&n<1114112&&(a=n)}null===a?(a=65533,s=1):a>65535&&(a-=65536,o.push(a>>>10&1023|55296),a=56320|1023&a),o.push(a),this._pos+=s};!this.done();){var l=this.ch(),u=void 0;switch(l){case 92:if(this._pos++,this.done())throw new Error("".concat(IP," unexpected string termination at position ").concat(this._pos));switch(u=this.ch(),this._pos++,u){case 34:case 39:case 92:case 47:o.push(u);break;case 98:o.push(8);break;case 116:o.push(9);break;case 110:o.push(10);break;case 102:o.push(12);break;case 114:o.push(13);break;case 117:o.push(a());break;default:throw new Error("".concat(IP," unexpected string escape character at position ").concat(this._pos))}break;case 34:return this._pos++,new cP(uP.string,AP(o),this._pos-i);default:if(l<32)throw new Error("".concat(IP," invalid control character at position ").concat(this._pos));l<128?(o.push(l),this._pos++):s()}}throw new Error("".concat(IP," unexpected end of string at position ").concat(this._pos))}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new cP(uP.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new cP(uP.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new cP(uP.null,null,4);case 102:return this.expect([102,97,108,115,101]),new cP(uP.false,!1,5);case 116:return this.expect([116,114,117,101]),new cP(uP.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error("".concat(IP," unexpected character at position ").concat(this._pos))}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":if(this.modeStack.pop(),93===this.ch())return this._pos++,this.skipWhitespace(),new cP(uP.break,void 0,1);if(44!==this.ch())throw new Error("".concat(IP," unexpected character at position ").concat(this._pos,", was expecting array delimiter but found '").concat(String.fromCharCode(this.ch()),"'"));return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue();case"array-start":return this.modeStack.pop(),93===this.ch()?(this._pos++,this.skipWhitespace(),new cP(uP.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(125===this.ch())return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new cP(uP.break,void 0,1);if(44!==this.ch())throw new Error("".concat(IP," unexpected character at position ").concat(this._pos,", was expecting object delimiter but found '").concat(String.fromCharCode(this.ch()),"'"));this._pos++,this.skipWhitespace();case"obj-start":if(this.modeStack.pop(),125===this.ch())return this._pos++,this.skipWhitespace(),new cP(uP.break,void 0,1);var e=this.parseString();if(this.skipWhitespace(),58!==this.ch())throw new Error("".concat(IP," unexpected character at position ").concat(this._pos,", was expecting key/value delimiter ':' but found '").concat(String.fromCharCode(this.ch()),"'"));return this._pos++,this.modeStack.push("obj-value"),e;case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error("".concat(IP," unexpected parse state at position ").concat(this._pos,"; this shouldn't happen"))}}}function nN(e){var t=se.encode(e).slice(1);return[new cP(uP.map,1/0,1),new cP(uP.string,"/",1),new cP(uP.map,1/0,1),new cP(uP.string,"bytes",5),new cP(uP.string,t,t.length),new cP(uP.break,void 0,1),new cP(uP.break,void 0,1)]}function iN(e){return nN(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}var oN={typeEncoders:{Object:function(e){if(e.asCID!==e&&e["/"]!==e.bytes)return null;var t=it.asCID(e);if(!t)return null;var r=t.toString();return[new cP(uP.map,1/0,1),new cP(uP.string,"/",1),new cP(uP.string,r,r.length),new cP(uP.break,void 0,1)]},Buffer:nN,Uint8Array:nN,Int8Array:iN,Uint16Array:iN,Int16Array:iN,Uint32Array:iN,Int32Array:iN,Float32Array:iN,Float64Array:iN,Uint8ClampedArray:iN,BigInt64Array:iN,BigUint64Array:iN,DataView:iN,ArrayBuffer:function(e){return nN(new Uint8Array(e))},undefined:function(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")},number:function(e){if(Number.isNaN(e))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(e===1/0||e===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}}};class aN extends rN{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return 0===this.tokenBuffer.length&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){var e=this._next();if(e.type===uP.map){var t=this._next();if(t.type===uP.string&&"/"===t.value){var r=this._next();if(r.type===uP.string){if(this._next().type!==uP.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(r),new cP(uP.tag,42,0)}if(r.type===uP.map){var n=this._next();if(n.type===uP.string&&"bytes"===n.value){var i=this._next();if(i.type===uP.string){for(var o=0;o<2;o++){if(this._next().type!==uP.break)throw new Error("Invalid encoded Bytes form")}var a=se.decode("m".concat(i.value));return new cP(uP.bytes,a,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(r)}this.tokenBuffer.push(t)}return e}}var sN={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};sN.tags[42]=it.parse;var lN=297,uN=e=>function(e,t){return t=Object.assign({},tN,t),O_(e,new eN,t)}(e,oN),cN=e=>{var t=function(e){return e instanceof ArrayBuffer?new Uint8Array(e,0,e.byteLength):e}(e);return function(e,t){return V_(e,t=Object.assign({tokenizer:new rN(e,t)},t))}(t,Object.assign(sN,{tokenizer:new aN(t,sN)}))},dN=e=>hN.decode(uN(e)),hN=new TextDecoder,vN=new TextEncoder,pN=Object.freeze({__proto__:null,code:297,decode:cN,encode:uN,format:dN,name:"dag-json",parse:e=>cN(vN.encode(e)),stringify:dN}),fN=new TextDecoder;function gN(e,t){for(var r=0,n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(t>=e.length)throw new Error("protobuf: unexpected end of data");var i=e[t++];if(r+=n<28?(127&i)<<n:(127&i)*2**n,i<128)break}return[r,t]}function yN(e,t){var r;[r,t]=gN(e,t);var n=t+r;if(r<0||n<0)throw new Error("protobuf: invalid length");if(n>e.length)throw new Error("protobuf: unexpected end of data");return[e.subarray(t,n),n]}function mN(e,t){var r;return[r,t]=gN(e,t),[7&r,r>>3,t]}function wN(e){for(var t={},r=e.length,n=0;n<r;){var i=void 0,o=void 0;if([i,o,n]=mN(e,n),1===o){if(t.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(2!==i)throw new Error("protobuf: (PBLink) wrong wireType (".concat(i,") for Hash"));if(void 0!==t.Name)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(void 0!==t.Tsize)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[t.Hash,n]=yN(e,n)}else if(2===o){if(void 0!==t.Name)throw new Error("protobuf: (PBLink) duplicate Name section");if(2!==i)throw new Error("protobuf: (PBLink) wrong wireType (".concat(i,") for Name"));if(void 0!==t.Tsize)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");var a=void 0;[a,n]=yN(e,n),t.Name=fN.decode(a)}else{if(3!==o)throw new Error("protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ".concat(o));if(void 0!==t.Tsize)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(0!==i)throw new Error("protobuf: (PBLink) wrong wireType (".concat(i,") for Tsize"));[t.Tsize,n]=gN(e,n)}}if(n>r)throw new Error("protobuf: (PBLink) unexpected end of data");return t}var bN=new TextEncoder,SN=2**32,EN=2**31;function kN(e,t){var r=t.length;if("number"==typeof e.Tsize){if(e.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(e.Tsize))throw new Error("Tsize too large for encoding");t[r=CN(t,r,e.Tsize)-1]=24}if("string"==typeof e.Name){var n=bN.encode(e.Name);r-=n.length,t.set(n,r),t[r=CN(t,r,n.length)-1]=18}return e.Hash&&(r-=e.Hash.length,t.set(e.Hash,r),t[r=CN(t,r,e.Hash.length)-1]=10),t.length-r}function xN(e){var t=function(e){var t=0;if(e.Data){var r=e.Data.length;t+=1+r+IN(r)}if(e.Links)for(var n of e.Links){var i=AN(n);t+=1+i+IN(i)}return t}(e),r=new Uint8Array(t),n=t;if(e.Data&&(n-=e.Data.length,r.set(e.Data,n),r[n=CN(r,n,e.Data.length)-1]=10),e.Links)for(var i=e.Links.length-1;i>=0;i--){var o=kN(e.Links[i],r.subarray(0,n));r[n=CN(r,n-=o,o)-1]=18}return r}function AN(e){var t=0;if(e.Hash){var r=e.Hash.length;t+=1+r+IN(r)}if("string"==typeof e.Name){var n=bN.encode(e.Name).length;t+=1+n+IN(n)}return"number"==typeof e.Tsize&&(t+=1+IN(e.Tsize)),t}function CN(e,t,r){for(var n=t-=IN(r);r>=EN;)e[t++]=127&r|128,r/=128;for(;r>=128;)e[t++]=127&r|128,r>>>=7;return e[t]=r,n}function IN(e){return e%2==0&&e++,Math.floor((function(e){var t=0;e>=SN&&(e=Math.floor(e/SN),t=32);e>=65536&&(e>>>=16,t+=16);e>=256&&(e>>>=8,t+=8);return t+TN[e]}(e)+6)/7)}var TN=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8],PN=["Data","Links"],_N=["Hash","Name","Tsize"],BN=new TextEncoder;function NN(e,t){if(e===t)return 0;for(var r=e.Name?BN.encode(e.Name):[],n=t.Name?BN.encode(t.Name):[],i=r.length,o=n.length,a=0,s=Math.min(i,o);a<s;++a)if(r[a]!==n[a]){i=r[a],o=n[a];break}return i<o?-1:o<i?1:0}function DN(e,t){return!Object.keys(e).some((e=>!t.includes(e)))}function RN(e){if("object"==typeof e.asCID){var t=it.asCID(e);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if("object"!=typeof e||Array.isArray(e))throw new TypeError("Invalid DAG-PB form");var r={};if(e.Hash){var n=it.asCID(e.Hash);try{n||("string"==typeof e.Hash?n=it.parse(e.Hash):e.Hash instanceof Uint8Array&&(n=it.decode(e.Hash)))}catch(e){throw new TypeError("Invalid DAG-PB form: ".concat(e.message))}n&&(r.Hash=n)}if(!r.Hash)throw new TypeError("Invalid DAG-PB form");return"string"==typeof e.Name&&(r.Name=e.Name),"number"==typeof e.Tsize&&(r.Tsize=e.Tsize),r}function ON(e){if((e instanceof Uint8Array||"string"==typeof e)&&(e={Data:e}),"object"!=typeof e||Array.isArray(e))throw new TypeError("Invalid DAG-PB form");var t={};if(void 0!==e.Data)if("string"==typeof e.Data)t.Data=BN.encode(e.Data);else{if(!(e.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form");t.Data=e.Data}if(void 0!==e.Links){if(!Array.isArray(e.Links))throw new TypeError("Invalid DAG-PB form");t.Links=e.Links.map(RN),t.Links.sort(NN)}else t.Links=[];return t}function LN(e){if(!e||"object"!=typeof e||Array.isArray(e)||e instanceof Uint8Array||e["/"]&&e["/"]===e.bytes)throw new TypeError("Invalid DAG-PB form");if(!DN(e,PN))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(void 0!==e.Data&&!(e.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(e.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(var t=0;t<e.Links.length;t++){var r=e.Links[t];if(!r||"object"!=typeof r||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!DN(r,_N))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(void 0===r.Hash)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(null==r.Hash||!r.Hash["/"]||r.Hash["/"]!==r.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(void 0!==r.Name&&"string"!=typeof r.Name)throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(void 0!==r.Tsize){if("number"!=typeof r.Tsize||r.Tsize%1!=0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(r.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(t>0&&-1===NN(r,e.Links[t-1]))throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}var MN=112;function UN(e){LN(e);var t={};return e.Links&&(t.Links=e.Links.map((e=>{var t={};return e.Hash&&(t.Hash=e.Hash.bytes),void 0!==e.Name&&(t.Name=e.Name),void 0!==e.Tsize&&(t.Tsize=e.Tsize),t}))),e.Data&&(t.Data=e.Data),xN(t)}function FN(e){var t=function(e){for(var t=e.length,r=0,n=void 0,i=!1,o=void 0;r<t;){var a=void 0,s=void 0;if([a,s,r]=mN(e,r),2!==a)throw new Error("protobuf: (PBNode) invalid wireType, expected 2, got ".concat(a));if(1===s){if(o)throw new Error("protobuf: (PBNode) duplicate Data section");[o,r]=yN(e,r),n&&(i=!0)}else{if(2!==s)throw new Error("protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ".concat(s));if(i)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);var l=void 0;[l,r]=yN(e,r),n.push(wN(l))}}if(r>t)throw new Error("protobuf: (PBNode) unexpected end of data");var u={};return o&&(u.Data=o),u.Links=n||[],u}(function(e){return e instanceof ArrayBuffer?new Uint8Array(e,0,e.byteLength):e}(e)),r={};return t.Data&&(r.Data=t.Data),t.Links&&(r.Links=t.Links.map((e=>{var t={};try{t.Hash=it.decode(e.Hash)}catch(e){}if(!t.Hash)throw new Error("Invalid Hash field found in link, expected CID");return void 0!==e.Name&&(t.Name=e.Name),void 0!==e.Tsize&&(t.Tsize=e.Tsize),t}))),r}var zN=Object.freeze({__proto__:null,code:MN,createLink:function(e,t,r){return RN({Hash:r,Name:e,Tsize:t})},createNode:function(e){return ON({Data:e,Links:arguments.length>1&&void 0!==arguments[1]?arguments[1]:[]})},decode:FN,encode:UN,name:"dag-pb",prepare:ON,validate:LN});function jN(e){return null!=(null==e?void 0:e.then)}class VN extends vd{constructor(t){super(),e(this,"child",void 0),this.child=t}put(e,t,r){var n,i;return 0===e.multihash.code?(null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted(),e):null==this.child?(null==r||null===(i=r.signal)||void 0===i||i.throwIfAborted(),e):this.child.put(e,t,r)}get(e,t){var r,n;if(0===e.multihash.code)return null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),e.multihash.digest;if(null==this.child)throw null==t||null===(n=t.signal)||void 0===n||n.throwIfAborted(),new Cc;return this.child.get(e,t)}has(e,t){var r,n;return 0===e.multihash.code?(null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),!0):null==this.child?(null==t||null===(n=t.signal)||void 0===n||n.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){var r;if(0!==e.code){if(null!=this.child)return this.child.delete(e,t)}else null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted()}getAll(e){var t;return null!=this.child?this.child.getAll(e):(null==e||null===(t=e.signal)||void 0===t||t.throwIfAborted(),[])}}class qN{constructor(t){e(this,"child",void 0),e(this,"getHasher",void 0),e(this,"log",void 0),e(this,"logger",void 0),e(this,"components",void 0),this.log=t.logger.forComponent("helia:networked-storage"),this.logger=t.logger,this.components=t,this.child=new VN(t.blockstore),this.getHasher=t.getHasher}put(e,t){var n=arguments,i=this;return r((function*(){var o,a,s,l=n.length>2&&void 0!==n[2]?n[2]:{};return(yield i.child.has(e,l))?(null===(s=l.onProgress)||void 0===s||s.call(l,new cv("blocks:put:duplicate",e)),e):(null===(o=l.onProgress)||void 0===o||o.call(l,new cv("blocks:put:providers:notify",e)),yield Promise.all(i.components.blockBrokers.map(function(){var n=r((function*(r){var n;return null===(n=r.announce)||void 0===n?void 0:n.call(r,e,t,l)}));return function(e){return n.apply(this,arguments)}}())),null===(a=l.onProgress)||void 0===a||a.call(l,new cv("blocks:put:blockstore:put",e)),i.child.put(e,t,l))}))()}putMany(e){var t=this;return l((function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(i){var o=fc(e,function(){var e=r((function*(e){var r,{cid:i}=e,o=yield t.child.has(i,n);o&&(null===(r=n.onProgress)||void 0===r||r.call(n,new cv("blocks:put-many:duplicate",i)));return!o}));return function(t){return e.apply(this,arguments)}}()),a=lv(o,function(){var e=r((function*(e){var i,{cid:o,block:a}=e;null===(i=n.onProgress)||void 0===i||i.call(n,new cv("blocks:put-many:providers:notify",o)),yield Promise.all(t.components.blockBrokers.map(function(){var e=r((function*(e){var t;return null===(t=e.announce)||void 0===t?void 0:t.call(e,o,a,n)}));return function(t){return e.apply(this,arguments)}}()))}));return function(t){return e.apply(this,arguments)}}());null===(i=n.onProgress)||void 0===i||i.call(n,new cv("blocks:put-many:blockstore:put-many")),yield*c(s(t.child.putMany(a,n)))}()})).apply(this,arguments)}get(e){var n=arguments,i=this;return r((function*(){var o,a=n.length>1&&void 0!==n[1]?n[1]:{};if(!0!==a.offline&&!(yield i.child.has(e,a))){var s,l,u,c=yield i.getHasher(e.multihash.code);null===(s=a.onProgress)||void 0===s||s.call(a,new cv("blocks:get:providers:get",e));var d=yield QN(e,i.components.blockBrokers,c,t(t({},a),{},{log:i.log}));return null===(l=a.onProgress)||void 0===l||l.call(a,new cv("blocks:get:blockstore:put",e)),yield i.child.put(e,d,a),null===(u=a.onProgress)||void 0===u||u.call(a,new cv("blocks:get:providers:notify",e)),yield Promise.all(i.components.blockBrokers.map(function(){var t=r((function*(t){var r;return null===(r=t.announce)||void 0===r?void 0:r.call(t,e,d,a)}));return function(e){return t.apply(this,arguments)}}())),d}return null===(o=a.onProgress)||void 0===o||o.call(a,new cv("blocks:get:blockstore:get",e)),i.child.get(e,a)}))()}getMany(e){var n=this;return l((function(e){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(o){null===(o=i.onProgress)||void 0===o||o.call(i,new cv("blocks:get-many:blockstore:get-many")),yield*c(s(n.child.getMany(lv(e,function(){var e=r((function*(e){if(!0!==i.offline&&!(yield n.child.has(e,i))){var o,a,s,l=yield n.getHasher(e.multihash.code);null===(o=i.onProgress)||void 0===o||o.call(i,new cv("blocks:get-many:providers:get",e));var u=yield QN(e,n.components.blockBrokers,l,t(t({},i),{},{log:n.log}));null===(a=i.onProgress)||void 0===a||a.call(i,new cv("blocks:get-many:blockstore:put",e)),yield n.child.put(e,u,i),null===(s=i.onProgress)||void 0===s||s.call(i,new cv("blocks:get-many:providers:notify",e)),yield Promise.all(n.components.blockBrokers.map(function(){var t=r((function*(t){var r;return null===(r=t.announce)||void 0===r?void 0:r.call(t,e,u,i)}));return function(e){return t.apply(this,arguments)}}()))}}));return function(t){return e.apply(this,arguments)}}()))))}()})).apply(this,arguments)}delete(e){var t=arguments,n=this;return r((function*(){var r,i=t.length>1&&void 0!==t[1]?t[1]:{};null===(r=i.onProgress)||void 0===r||r.call(i,new cv("blocks:delete:blockstore:delete",e)),yield n.child.delete(e,i)}))()}deleteMany(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(n){null===(n=r.onProgress)||void 0===n||n.call(r,new cv("blocks:delete-many:blockstore:delete-many")),yield*c(s(t.child.deleteMany(l((function*(){var t,r=!1,n=!1;try{for(var i,o=s(e);r=!(i=yield u(o.next())).done;r=!1){var a=i.value;yield a}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw t}}}))(),r)))}()})).apply(this,arguments)}has(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};return n.child.has(e,r)}))()}getAll(){var e=this;return l((function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(r){null===(r=t.onProgress)||void 0===r||r.call(t,new cv("blocks:get-all:blockstore:get-many")),yield*c(s(e.child.getAll(t)))}()})).apply(this,arguments)}}class HN extends qN{constructor(t){super(t),e(this,"started",void 0),this.started=!1}isStarted(){return this.started}start(){var e=this;return r((function*(){yield ds(e.child,...e.components.blockBrokers),e.started=!0}))()}stop(){var e=this;return r((function*(){yield vs(e.child,...e.components.blockBrokers),e.started=!1}))()}unwrap(){return this.child}createSession(e,t){var r=this.components.blockBrokers.map((e=>null==e.createSession?e:e.createSession(t)));return new KN({blockstore:this.child,blockBrokers:r,getHasher:this.getHasher,logger:this.logger},{root:e})}}class KN extends qN{constructor(t,r){super(t),e(this,"closeController",void 0),this.closeController=new AbortController,this.closeController.signal,this.log=t.logger.forComponent("helia:session-storage:".concat(r.root))}close(){this.closeController.abort()}put(e,n){var i=arguments,o=()=>super.put,a=this;return r((function*(){var r=i.length>2&&void 0!==i[2]?i[2]:{},s=Dh([a.closeController.signal,r.signal]);try{return yield o().call(a,e,n,t(t({},r),{},{signal:s}))}finally{s.clear()}}))()}putMany(e){var r=()=>super.putMany,n=this;return l((function(e){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var o=Dh([n.closeController.signal,i.signal]);try{yield*c(s(r().call(n,e,t(t({},i),{},{signal:o}))),u)}finally{o.clear()}}()})).apply(this,arguments)}get(e){var n=arguments,i=()=>super.get,o=this;return r((function*(){var r=n.length>1&&void 0!==n[1]?n[1]:{},a=Dh([o.closeController.signal,r.signal]);try{return yield i().call(o,e,t(t({},r),{},{signal:a}))}finally{a.clear()}}))()}getMany(e){var r=()=>super.getMany,n=this;return l((function(e){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var o=Dh([n.closeController.signal,i.signal]);try{yield*c(s(r().call(n,e,t(t({},i),{},{signal:o}))),u)}finally{o.clear()}}()})).apply(this,arguments)}delete(e){var n=arguments,i=()=>super.delete,o=this;return r((function*(){var r=n.length>1&&void 0!==n[1]?n[1]:{},a=Dh([o.closeController.signal,r.signal]);try{yield i().call(o,e,t(t({},r),{},{signal:a}))}finally{a.clear()}}))()}deleteMany(e){var r=()=>super.deleteMany,n=this;return l((function(e){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var o=Dh([n.closeController.signal,i.signal]);try{yield*c(s(r().call(n,e,t(t({},i),{},{signal:o}))),u)}finally{o.clear()}}()})).apply(this,arguments)}has(e){var n=arguments,i=()=>super.has,o=this;return r((function*(){var r=n.length>1&&void 0!==n[1]?n[1]:{},a=Dh([o.closeController.signal,r.signal]);try{return yield i().call(o,e,t(t({},r),{},{signal:a}))}finally{a.clear()}}))()}getAll(){var e=()=>super.getAll,r=this;return l((function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i=Dh([r.closeController.signal,n.signal]);try{yield*c(s(e().call(r,t(t({},n),{},{signal:i}))),u)}finally{i.clear()}}()})).apply(this,arguments)}}function WN(e){return"function"==typeof e.retrieve}var GN=(e,t)=>{if(null==t)throw new Ra("No hasher configured for multihash code 0x".concat(e.multihash.code.toString(16),", please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv"));return function(){var n=r((function*(r){var n=t.digest(r);if(!Et((jN(n)?yield n:n).digest,e.multihash.digest))throw new Qa("Hash of downloaded block did not match multihash from passed CID")}));return function(e){return n.apply(this,arguments)}}()};function QN(e,t,r,n){return YN.apply(this,arguments)}function YN(){return YN=r((function*(e,n,i,o){var a=GN(e,i),s=new AbortController,l=Dh([s.signal,o.signal]);s.signal;var u=[];for(var c of n)WN(c)&&u.push(c);try{return yield Promise.any(u.map(function(){var n=r((function*(n){try{var i=!1,s=yield n.retrieve(e,t(t({},o),{},{signal:l,validateFn:(u=r((function*(e){yield a(e),i=!0})),function(e){return u.apply(this,arguments)})}));return i||(yield a(s)),s}catch(t){throw o.log.error("could not retrieve verified block for %c",e,t),t}var u}));return function(e){return n.apply(this,arguments)}}()))}finally{s.abort(),l.clear()}})),YN.apply(this,arguments)}class JN extends us{constructor(t,r){var n,i,o;super(),e(this,"initialPeerSearchComplete",void 0),e(this,"requests",void 0),e(this,"name",void 0),e(this,"log",void 0),e(this,"logger",void 0),e(this,"minProviders",void 0),e(this,"maxProviders",void 0),e(this,"providers",void 0),e(this,"evictionFilter",void 0),e(this,"initialProviders",void 0),this.name=r.name,this.logger=t.logger,this.log=t.logger.forComponent(this.name),this.requests=new Map,this.minProviders=null!==(n=r.minProviders)&&void 0!==n?n:1,this.maxProviders=null!==(i=r.maxProviders)&&void 0!==i?i:5,this.providers=[],this.evictionFilter=rv(this.maxProviders),this.initialProviders=null!==(o=r.providers)&&void 0!==o?o:[]}retrieve(e){var t=arguments,n=this;return r((function*(){var i,o=t.length>1&&void 0!==t[1]?t[1]:{},a=se.encode(e.multihash.bytes),s=n.requests.get(a);if(null!=s)return n.log("join existing request for %c",e),s;var l=_c();if(n.requests.set(a,l.promise),0===n.providers.length){var u=!1;null==n.initialPeerSearchComplete&&(u=!0,n.log=n.logger.forComponent("".concat(n.name,":").concat(e)),n.initialPeerSearchComplete=n.findProviders(e,n.minProviders,o)),yield n.initialPeerSearchComplete,u&&n.log("found initial session peers for %c",e)}var c=!1,d=new wv({concurrency:n.maxProviders});d.addEventListener("error",(()=>{})),d.addEventListener("failure",(e=>{n.log.error("error querying provider %o, evicting from session",e.detail.job.options.provider,e.detail.error),n.evict(e.detail.job.options.provider)})),d.addEventListener("success",(e=>{c=!0,l.resolve(e.detail.result)})),d.addEventListener("idle",(()=>{var t;c||!0===(null===(t=o.signal)||void 0===t?void 0:t.aborted)?n.log.trace("session idle, found block"):Promise.resolve().then(r((function*(){n.log("no session peers had block for for %c, finding new providers",e);for(var t=0;t<n.minProviders&&0!==n.providers.length;t++){var r=n.providers[Math.floor(Math.random()*n.providers.length)];n.evict(r)}yield n.findProviders(e,n.minProviders,o),n.log("found new providers re-retrieving %c",e),n.requests.delete(a),l.resolve(yield n.retrieve(e,o))}))).catch((t=>{n.log.error("could not find new providers for %c",e,t),l.reject(t)}))}));var h=t=>{d.add(r((function*(){return n.queryProvider(e,t.detail,o)})),{provider:t.detail}).catch((t=>{var r;!0!==(null===(r=o.signal)||void 0===r?void 0:r.aborted)&&n.log.error("error retrieving session block for %c",e,t)}))};n.addEventListener("provider",h),Promise.all([...n.providers].map(function(){var t=r((function*(t){return d.add(r((function*(){return n.queryProvider(e,t,o)})),{provider:t})}));return function(e){return t.apply(this,arguments)}}())).catch((t=>{var r;!0!==(null===(r=o.signal)||void 0===r?void 0:r.aborted)&&n.log.error("error retrieving session block for %c",e,t)}));var v=()=>{var e,t;l.reject(new Ba(null!==(e=null===(t=o.signal)||void 0===t?void 0:t.reason)&&void 0!==e?e:"Session aborted")),d.abort()};null===(i=o.signal)||void 0===i||i.addEventListener("abort",v);try{return yield l.promise}finally{var p;n.removeEventListener("provider",h),null===(p=o.signal)||void 0===p||p.removeEventListener("abort",v),d.clear(),n.requests.delete(a)}}))()}evict(e){this.evictionFilter.add(this.toEvictionKey(e));var t=this.providers.findIndex((t=>this.equals(t,e)));-1!==t&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return null!=this.providers.find((t=>this.equals(t,e)))||!!this.isEvicted(e)}findProviders(e,t,n){var i=this;return r((function*(){var o=_c(),a=0;return Promise.resolve().then(r((function*(){if(i.log("finding %d-%d new provider(s) for %c",t,i.maxProviders,e),i.initialProviders.length>0)for(;a<t&&i.initialProviders.length>0;){var r,l=i.initialProviders.pop();if(null==l)break;var u=yield i.convertToProvider(l,n);if(!0===(null===(r=n.signal)||void 0===r?void 0:r.aborted))break;if(null!=u&&(!i.hasProvider(u)&&(i.log("found %d/%d new providers",a,i.maxProviders),i.providers.push(u),i.safeDispatchEvent("provider",{detail:u}),++a===t&&(i.log("session is ready"),o.resolve()),i.providers.length===i.maxProviders))){i.log("found max session peers",a);break}}if(a<i.maxProviders){var c,d=!1,h=!1;try{for(var v,p=s(i.findNewProviders(e,n));d=!(v=yield p.next()).done;d=!1){var f,g=v.value;if(a===i.maxProviders||!0===(null===(f=n.signal)||void 0===f?void 0:f.aborted))break;if(!i.hasProvider(g)&&(i.log("found %d/%d new providers",a,i.maxProviders),i.providers.push(g),i.safeDispatchEvent("provider",{detail:g}),++a===t&&(i.log("session is ready"),o.resolve()),i.providers.length===i.maxProviders)){i.log("found max session peers",a);break}}}catch(e){h=!0,c=e}finally{try{d&&null!=p.return&&(yield p.return())}finally{if(h)throw c}}}if(i.log("found %d/%d new session peers",a,i.maxProviders),a<t)throw new iB("Found ".concat(a," of ").concat(t," ").concat(i.name," providers for ").concat(e))}))).catch((t=>{var r;i.log.error("error searching routing for potential session peers for %c",e,null!==(r=t.errors)&&void 0!==r?r:t),o.reject(t)})),o.promise}))()}}class ZN{constructor(n){var i,o,a,s,l;e(this,"blockstore",void 0),e(this,"datastore",void 0),e(this,"pins",void 0),e(this,"logger",void 0),e(this,"routing",void 0),e(this,"getCodec",void 0),e(this,"getHasher",void 0),e(this,"dns",void 0),e(this,"metrics",void 0),e(this,"log",void 0),this.logger=null!==(i=n.logger)&&void 0!==i?i:cd(),this.log=this.logger.forComponent("helia"),this.getHasher=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1?arguments[1]:void 0,n={[$e.code]:$e,[Xe.code]:Xe,[Ge.code]:Ge};return e.forEach((e=>{n[e.code]=e})),function(){var e=r((function*(e){var r=n[e];if(null==r&&null!=t){var i=t(e);r=jN(i)?yield i:i,n[r.code]=r}if(null!=r)return r;throw new aB("No hasher configured for multihash code 0x".concat(e.toString(16),", please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv"))}));return function(t){return e.apply(this,arguments)}}()}(n.hashers,n.loadHasher),this.getCodec=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1?arguments[1]:void 0,n={[MN]:zN,[Se]:Ee,[JB]:XB,[lN]:pN,[me]:be};return e.forEach((e=>{n[e.code]=e})),function(){var e=r((function*(e){var r=n[e];if(null==r&&null!=t){var i=t(e);r=jN(i)?yield i:i,n[r.code]=r}if(null!=r)return r;throw new sB("Could not load codec for ".concat(e))}));return function(t){return e.apply(this,arguments)}}()}(n.codecs,n.loadCodec),this.dns=null!==(o=n.dns)&&void 0!==o?o:oP(),this.metrics=n.metrics;var u=t({blockstore:n.blockstore,datastore:n.datastore,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics},null!==(a=n.components)&&void 0!==a?a:{});this.routing=u.routing=new lB(u,{routers:(null!==(s=n.routers)&&void 0!==s?s:[]).flatMap((e=>{var t=[e];return null!=e[ka]&&t.push(e[ka]),null!=e[Ta]&&t.push(e[Ta]),t})),providerLookupConcurrency:n.providerLookupConcurrency});var c=new HN(u);this.pins=new eB(n.datastore,c,this.getCodec),this.blockstore=new jB(c,this.pins,{holdGcLock:null===(l=n.holdGcLock)||void 0===l||l}),this.datastore=n.datastore,u.blockBrokers=n.blockBrokers.map((e=>e(u)))}start(){var e=this;return r((function*(){yield function(e){return qB.apply(this,arguments)}(e.datastore),yield ds(e.blockstore,e.datastore,e.routing)}))()}stop(){var e=this;return r((function*(){yield vs(e.blockstore,e.datastore,e.routing)}))()}gc(){var e=arguments,t=this;return r((function*(){var r=e.length>0&&void 0!==e[0]?e[0]:{},n=yield t.blockstore.lock.writeLock();try{var i=t,o=t.blockstore.unwrap();t.log("gc start"),yield vc(o.deleteMany(l((function*(){var e,t=!1,n=!1;try{for(var a,l=s(o.getAll());t=!(a=yield u(l.next())).done;t=!1){var{cid:c}=a.value;try{var d;if(yield u(i.pins.isPinned(c,r)))continue;yield c,null===(d=r.onProgress)||void 0===d||d.call(r,new cv("helia:gc:deleted",c))}catch(e){var h;i.log.error("Error during gc",e),null===(h=r.onProgress)||void 0===h||h.call(r,new cv("helia:gc:error",e))}}}catch(t){n=!0,e=t}finally{try{t&&null!=l.return&&(yield u(l.return()))}finally{if(n)throw e}}}))()))}finally{n()}t.log("gc finished")}))()}}class $N extends JN{constructor(r,n){super(r,t(t({},n),{},{name:"helia:bitswap:session"})),e(this,"wantList",void 0),e(this,"network",void 0),e(this,"libp2p",void 0),this.wantList=r.wantList,this.network=r.network,this.libp2p=r.libp2p}queryProvider(e,t,n){var i=this;return r((function*(){i.log("sending WANT-BLOCK for %c to %p",e,t);var r=yield i.wantList.wantSessionBlock(e,t,n);if(i.log("%p %s %c",t,r.has?"has":"does not have",e),r.has&&null!=r.block)return r.block;throw new Error("Provider did not have block")}))()}findNewProviders(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var n,i=!1,o=!1;try{for(var a,l=s(t.network.findProviders(e,r));i=!(a=yield u(l.next())).done;i=!1){var c=a.value;yield c.id}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}()})).apply(this,arguments)}toEvictionKey(e){return e.toMultihash().bytes}equals(e,t){return e.equals(t)}convertToProvider(e,t){var n=this;return r((function*(){return Ca(e)?e:(yield n.libp2p.dial(e,t)).remotePeer}))()}}class XN{constructor(t){var r,n,i,o;e(this,"blocksReceived",void 0),e(this,"duplicateBlocksReceived",void 0),e(this,"dataReceived",void 0),e(this,"duplicateDataReceived",void 0),this.blocksReceived=null===(r=t.metrics)||void 0===r?void 0:r.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=null===(n=t.metrics)||void 0===n?void 0:n.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=null===(i=t.metrics)||void 0===i?void 0:i.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=null===(o=t.metrics)||void 0===o?void 0:o.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,r=arguments.length>1?arguments[1]:void 0,n={global:t};null!=r&&(n[r.toString()]=t),null===(e=this.blocksReceived)||void 0===e||e.increment(n)}updateDuplicateBlocksReceived(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,r=arguments.length>1?arguments[1]:void 0,n={global:t};null!=r&&(n[r.toString()]=t),null===(e=this.duplicateBlocksReceived)||void 0===e||e.increment(n)}updateDataReceived(e,t){var r,n={global:e};null!=t&&(n[t.toString()]=e),null===(r=this.dataReceived)||void 0===r||r.increment(n)}updateDuplicateDataReceived(e,t){var r,n={global:e};null!=t&&(n[t.toString()]=e),null===(r=this.duplicateDataReceived)||void 0===r||r.increment(n)}}class eD extends Map{constructor(t){super(),e(this,"metric",void 0);var{name:r,metrics:n}=t;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){var t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function tD(e){var{name:t,metrics:r}=e;return null!=r?new eD({name:t,metrics:r}):new Map}function rD(e){if(!(e instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");for(var t=[];e.length>0;){var r=Ft(e);t.push(r),e=e.slice(Ot(r))}return t}class nD extends us{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),e(this,"peers",void 0),e(this,"wants",void 0),e(this,"network",void 0),e(this,"log",void 0),e(this,"sendMessagesDelay",void 0),e(this,"sendMessagesTimeout",void 0),e(this,"hashLoader",void 0),e(this,"sendingMessages",void 0),this.peers=av({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=tD({name:"helia_bitswap_wantlist",metrics:t.metrics}),this.network=t.network,this.sendMessagesDelay=null!==(r=n.sendMessagesDelay)&&void 0!==r?r:10,this.log=t.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=n.hashLoader,this.network.addEventListener("bitswap:message",(e=>{this.receiveMessage(e.detail.peer,e.detail.message).catch((t=>{this.log.error("error receiving bitswap message from %p",e.detail.peer,t)}))})),this.network.addEventListener("peer:connected",(e=>{this.peerConnected(e.detail).catch((t=>{this.log.error("error processing newly connected bitswap peer %p",e.detail,t)}))})),this.network.addEventListener("peer:disconnected",(e=>{this.peerDisconnected(e.detail)}))}addEntry(e,t){var n=this;return r((function*(){var r,i,o=gt(e.multihash.bytes,"base64"),a=n.wants.get(o);null==a&&(a={cid:e,priority:null!==(r=t.priority)&&void 0!==r?r:1,wantType:null!==(i=t.wantType)&&void 0!==i?i:QI.WantBlock,cancel:!1,sendDontHave:!0},n.wants.set(o,a));a.wantType===QI.WantHave&&t.wantType===QI.WantBlock&&(a.wantType=QI.WantBlock),yield n.sendMessagesDebounced();try{if(t.wantType===QI.WantBlock){var s=yield hv(n,"block",null==t?void 0:t.signal,{filter:t=>Et(e.multihash.digest,t.detail.cid.multihash.digest),errorMessage:"Want was aborted"});return s.detail}return(yield hv(n,"presence",null==t?void 0:t.signal,{filter:t=>Et(e.multihash.digest,t.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{var l;!0===(null===(l=t.signal)||void 0===l?void 0:l.aborted)&&(n.log("want for %c was aborted, cancelling want",e),a.cancel=!0,yield n.sendMessagesDebounced())}}))()}sendMessagesDebounced(){var e=this;return r((function*(){var t;yield null===(t=e.sendingMessages)||void 0===t?void 0:t.promise,clearTimeout(e.sendMessagesTimeout),e.sendMessagesTimeout=setTimeout((()=>{e.sendMessages().catch((t=>{e.log("error sending messages to peers",t)}))}),e.sendMessagesDelay)}))()}sendMessages(){var e=this;return r((function*(){for(var[t,n]of(e.sendingMessages=_c(),yield Promise.all([...e.peers.entries()].map(function(){var t=r((function*(t){var[r,n]=t,i=new Set,o=new vT;for(var[a,s]of e.wants.entries()){n.has(a)||s.cancel||(i.add(a),o.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:s.priority,wantType:s.wantType,cancel:s.cancel,sendDontHave:s.sendDontHave}))}if(0!==o.wantlist.size)try{for(var l of(yield e.network.sendMessage(r,o),i))n.add(l)}catch(t){e.log.error("error sending full wantlist to new peer",t)}}));return function(e){return t.apply(this,arguments)}}())).catch((t=>{e.log.error("error sending messages",t)})),e.wants))if(n.cancel)for(var i of(e.wants.delete(t),e.peers.values()))i.delete(t);e.sendingMessages.resolve()}))()}has(e){var t=gt(e.multihash.bytes,"base64");return this.wants.has(t)}wantSessionPresence(e,t){var n=arguments,i=this;return r((function*(){var r=n.length>2&&void 0!==n[2]?n[2]:{},o=new vT;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:QI.WantHave,priority:1}),yield i.network.sendMessage(t,o),(yield hv(i,"presence",r.signal,{filter:r=>t.equals(r.detail.sender)&&Et(e.multihash.digest,r.detail.cid.multihash.digest)})).detail}))()}wantBlock(e){var n=arguments,i=this;return r((function*(){var r=n.length>1&&void 0!==n[1]?n[1]:{};return i.addEntry(e,t(t({},r),{},{wantType:QI.WantBlock}))}))()}wantSessionBlock(e,t){var n=arguments,i=this;return r((function*(){var r=n.length>2&&void 0!==n[2]?n[2]:{},o=new vT;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:QI.WantBlock,priority:1}),yield i.network.sendMessage(t,o),(yield hv(i,"presence",r.signal,{filter:r=>t.equals(r.detail.sender)&&Et(e.multihash.digest,r.detail.cid.multihash.digest)})).detail}))()}receivedBlock(e,t){var n=this;return r((function*(){var t=gt(e.multihash.bytes,"base64"),r=n.wants.get(t);null!=r&&(r.cancel=!0,yield n.sendMessagesDebounced())}))()}receiveMessage(e,t){var n=this;return r((function*(){n.log("received message from %p with %d blocks",e,t.blocks.length);var r=!1;for(var i of t.blocks){var o;if(null!=i.prefix&&null!=i.data){var a=rD(i.prefix),s=a[0],l=a[1],u=a[2],c=u===$e.code?$e:yield null===(o=n.hashLoader)||void 0===o?void 0:o.getHasher(u);if(null!=c){var d=c.digest(i.data);null!=d.then&&(d=yield d);var h=it.create(0===s?0:1,l,d);n.log("received block from %p for %c",e,h),n.safeDispatchEvent("block",{detail:{sender:e,cid:h,block:i.data}}),n.safeDispatchEvent("presence",{detail:{sender:e,cid:h,has:!0,block:i.data}});var v=gt(h.multihash.bytes,"base64"),p=n.wants.get(v);null!=p&&(p.cancel=!0,r=!0)}else n.log.error("unknown hash algorithm",u)}}for(var{cid:f,type:g}of t.blockPresences){var y=it.decode(f);n.log("received %s from %p for %c",g,e,y),n.safeDispatchEvent("presence",{detail:{sender:e,cid:y,has:g===XI.HaveBlock}})}r&&(yield n.sendMessagesDebounced())}))()}peerConnected(e){var t=this;return r((function*(){var r=new Set,n=new vT(!0);for(var[i,o]of t.wants.entries())o.cancel||(r.add(i),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:QI.WantBlock,cancel:!1,sendDontHave:!1}));if(0!==n.wantlist.size)try{yield t.network.sendMessage(e,n),t.peers.set(e,r)}catch(r){t.log.error("error sending full wantlist to new peer %p",e,r)}else t.peers.set(e,r)}))()}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}}class iD{constructor(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"log",void 0),e(this,"logger",void 0),e(this,"stats",void 0),e(this,"network",void 0),e(this,"blockstore",void 0),e(this,"peerWantLists",void 0),e(this,"wantList",void 0),e(this,"libp2p",void 0),this.logger=r.logger,this.log=r.logger.forComponent("helia:bitswap"),this.blockstore=r.blockstore,this.libp2p=r.libp2p,this.stats=new XN(r),this.network=new hT(r,n),this.peerWantLists=new gT(t(t({},r),{},{network:this.network}),n),this.wantList=new nD(t(t({},r),{},{network:this.network}),n)}createSession(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return e={wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},new $N(e,t)}want(e){var n=arguments,i=this;return r((function*(){var r=n.length>1&&void 0!==n[1]?n[1]:{},o=new AbortController,a=Dh([o.signal,r.signal]);o.signal,i.network.findAndConnect(e,t(t({},r),{},{signal:a})).catch((t=>{o.signal.aborted||i.log.error("error during finding and connect for cid %c",e,t)}));try{return(yield i.wantList.wantBlock(e,t(t({},r),{},{signal:a}))).block}finally{o.abort(),a.clear()}}))()}notify(e,t){var n=arguments,i=this;return r((function*(){var t=n.length>2&&void 0!==n[2]?n[2]:{};yield Promise.all([i.peerWantLists.receivedBlock(e,t),i.wantList.receivedBlock(e,t)])}))()}getWantlist(){return[...this.wantList.wants.values()].filter((e=>!e.cancel)).map((e=>({cid:e.cid,priority:e.priority,wantType:e.wantType})))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}start(){var e=this;return r((function*(){e.wantList.start(),yield e.network.start()}))()}stop(){var e=this;return r((function*(){e.wantList.stop(),yield e.network.stop()}))()}}class oD{constructor(n){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"bitswap",void 0),e(this,"started",void 0);var o,{getHasher:a}=n;this.bitswap=function(e){return new iD(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}(n,t({hashLoader:{getHasher:(o=r((function*(e){return a(e)})),function(e){return o.apply(this,arguments)})}},i)),this.started=!1}isStarted(){return this.started}start(){var e=this;return r((function*(){yield e.bitswap.start(),e.started=!0}))()}stop(){var e=this;return r((function*(){yield e.bitswap.stop(),e.started=!1}))()}announce(e,t,n){var i=this;return r((function*(){yield i.bitswap.notify(e,t,n)}))()}retrieve(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};return n.bitswap.want(e,r)}))()}createSession(e){var t,n,i=this,o=this.bitswap.createSession(e);return{announce:(n=r((function*(e,t,r){yield i.bitswap.notify(e,t,r)})),function(e,t,r){return n.apply(this,arguments)}),retrieve:(t=r((function*(e,t){return o.retrieve(e,t)})),function(e,r){return t.apply(this,arguments)})}}}function aD(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new oD(t,e)}var sD,lD={};var uD=(sD||(sD=1,function(){var e,t,r,n,i,o,a,s;s=function(e){return[(e&255<<24)>>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var r,n,i,o,a,s;for(r=[],i=o=0;o<=3&&0!==e.length;i=++o){if(i>0){if("."!==e[0])throw new Error("Invalid IP");e=e.substring(1)}a=(s=t(e))[0],n=s[1],e=e.substring(n),r.push(a)}if(0!==e.length)throw new Error("Invalid IP");switch(r.length){case 1:if(r[0]>4294967295)throw new Error("Invalid IP");return r[0]>>>0;case 2:if(r[0]>255||r[1]>16777215)throw new Error("Invalid IP");return(r[0]<<24|r[1])>>>0;case 3:if(r[0]>255||r[1]>255||r[2]>65535)throw new Error("Invalid IP");return(r[0]<<24|r[1]<<16|r[2])>>>0;case 4:if(r[0]>255||r[1]>255||r[2]>255||r[3]>255)throw new Error("Invalid IP");return(r[0]<<24|r[1]<<16|r[2]<<8|r[3])>>>0;default:throw new Error("Invalid IP")}},n=(r=function(e){return e.charCodeAt(0)})("0"),o=r("a"),i=r("A"),t=function(e){var t,a,s,l,u;for(l=0,t=10,a="9",s=0,e.length>1&&"0"===e[s]&&("x"===e[s+1]||"X"===e[s+1]?(s+=2,t=16):"0"<=e[s+1]&&e[s+1]<="9"&&(s++,t=8,a="7")),u=s;s<e.length;){if("0"<=e[s]&&e[s]<=a)l=l*t+(r(e[s])-n)>>>0;else{if(16!==t)break;if("a"<=e[s]&&e[s]<="f")l=l*t+(10+r(e[s])-o)>>>0;else{if(!("A"<=e[s]&&e[s]<="F"))break;l=l*t+(10+r(e[s])-i)>>>0}}if(l>4294967295)throw new Error("too large");s++}if(s===u)throw new Error("empty octet");return[l,s]},e=function(){function e(e,t){var r,n,i;if("string"!=typeof e)throw new Error("Missing `net' parameter");if(t||(i=e.split("/",2),e=i[0],t=i[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=s(this.netLong),this.mask=s(this.maskLong),this.hostmask=s(~this.maskLong),this.first=this.bitmask<=30?s(this.netLong+1):this.base,this.last=this.bitmask<=30?s(this.netLong+this.size-2):s(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?s(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(s(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(s(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),lD.ip2long=a,lD.long2ip=s,lD.Netmask=e}.call(lD)),lD),cD=["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 dD(e){for(var t of cD)if(t.contains(e))return!0;return!1}function hD(e){return Wt(e)?dD(e):/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(e)?function(e){var t=e.split(":");if(t.length<2)return!1;var r=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0");return dD("".concat(parseInt(n.substring(0,2),16),".").concat(parseInt(n.substring(2),16),".").concat(parseInt(r.substring(0,2),16),".").concat(parseInt(r.substring(2),16)))}(e):function(e){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)}(e)?function(e){var t=e.split(":");return dD(t[t.length-1])}(e):Gt(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}var vD=[Tr("tcp").code,Tr("dns").code,Tr("dnsaddr").code,Tr("dns4").code,Tr("dns6").code];function pD(e){var t;return null===(t=gD("sni",e))||void 0===t?void 0:t[1]}function fD(e){var t,r=null===(t=gD("tcp",e))||void 0===t?void 0:t[1];return null==r?"":":".concat(r)}function gD(e,t){var r;try{r=Tr(e).code}catch(e){return}for(var[n,i]of t)if(n===r&&null!=i)return[n,i]}function yD(e){return e.some((e=>{var[t,r]=e;return t===Tr("tls").code}))}function mD(e,t,r){var n=wD[Tr(e).name];if(null==n)throw new Error("Can't interpret protocol ".concat(Tr(e).name));var i=n(t,r);return e===Tr("ip6").code?"[".concat(i,"]"):i}var wD={ip4:(e,t)=>e,ip6:(e,t)=>0===t.length?e:"[".concat(e,"]"),tcp:(e,t)=>{var r,n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return"tcp://".concat(mD(n[0],null!==(r=n[1])&&void 0!==r?r:"",t),":").concat(e)},udp:(e,t)=>{var r,n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return"udp://".concat(mD(n[0],null!==(r=n[1])&&void 0!==r?r:"",t),":").concat(e)},dnsaddr:(e,t)=>e,dns4:(e,t)=>e,dns6:(e,t)=>e,dns:(e,t)=>e,ipfs:(e,t)=>{var r,n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return"".concat(mD(n[0],null!==(r=n[1])&&void 0!==r?r:"",t))},p2p:(e,t)=>{var r,n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return"".concat(mD(n[0],null!==(r=n[1])&&void 0!==r?r:"",t))},http:(e,t)=>{var r,n=yD(t),i=pD(t),o=fD(t);if(n&&null!=i)return"https://".concat(i).concat(o);var a=n?"https://":"http://",s=t.pop();if(null==s)throw new Error("Unexpected end of multiaddr");var l=mD(s[0],null!==(r=s[1])&&void 0!==r?r:"",t);return l=l.replace("tcp://",""),"".concat(a).concat(l)},"http-path":(e,t)=>{var r,n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");var i=mD(n[0],null!==(r=n[1])&&void 0!==r?r:"",t),o=decodeURIComponent(e);return"".concat(i,"/").concat(o)},tls:(e,t)=>{var r,n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return mD(n[0],null!==(r=n[1])&&void 0!==r?r:"",t)},sni:(e,t)=>{var r,n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return mD(n[0],null!==(r=n[1])&&void 0!==r?r:"",t)},https:(e,t)=>{var r,n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");var i=mD(n[0],null!==(r=n[1])&&void 0!==r?r:"",t);return i=i.replace("tcp://",""),"https://".concat(i)},ws:(e,t)=>{var r,n=yD(t),i=pD(t),o=fD(t);if(n&&null!=i)return"wss://".concat(i).concat(o);var a=n?"wss://":"ws://",s=t.pop();if(null==s)throw new Error("Unexpected end of multiaddr");var l=mD(s[0],null!==(r=s[1])&&void 0!==r?r:"",t);return l=l.replace("tcp://",""),"".concat(a).concat(l)},wss:(e,t)=>{var r,n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");var i=mD(n[0],null!==(r=n[1])&&void 0!==r?r:"",t);return i=i.replace("tcp://",""),"wss://".concat(i)}};function bD(e,t){var r,n=Ir(e).stringTuples(),i=n.pop();if(null==i)throw new Error("Unexpected end of multiaddr");var o=Tr(i[0]),a=wD[o.name];if(null==a)throw new Error("No interpreter found for ".concat(o.name));var s=a(null!==(r=i[1])&&void 0!==r?r:"",n);return vD.includes(i[0])&&(s=s.replace(/^.*:\/\//,""),s="443"===i[1]?"https://".concat(s):"http://".concat(s)),(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("ws://")||s.startsWith("wss://"))&&(s=new URL(s).toString()).endsWith("/")&&(s=s.substring(0,s.length-1)),s}var SD=new WeakMap,ED=new WeakMap,kD=new WeakMap,xD=new WeakMap,AD=new WeakMap,CD=new WeakSet;class ID{constructor(t,r){var{logger:i,transformRequestInit:o}=r;d(this,CD),e(this,"url",void 0),n(this,SD,0),n(this,ED,0),n(this,kD,0),n(this,xD,0),n(this,AD,new Map),e(this,"log",void 0),e(this,"transformRequestInit",void 0),this.url=t instanceof URL?t:new URL(t),this.transformRequestInit=o,this.log=i.forComponent("helia:trustless-gateway-block-broker:".concat(this.url.hostname))}getRawBlock(e,t){var n=this;return r((function*(){var a=new URL(n.url.toString());if(a.pathname="/ipfs/".concat(e.toString()),a.search="?format=raw",!0===(null==t?void 0:t.aborted))throw new Error("Signal to fetch raw block for CID ".concat(e," from gateway ").concat(n.url," was aborted prior to fetch"));var s=h(CD,n,TD).call(n,e),l=new AbortController,u=()=>{l.abort()};null==t||t.addEventListener("abort",u);try{var c=o(AD,n).get(s);if(null==c){var d;i(SD,n,(d=o(SD,n),d++,d));var v={signal:l.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},p=null!=n.transformRequestInit?yield n.transformRequestInit(v):v;c=fetch(a.toString(),p).then(function(){var t=r((function*(t){var r,s;if(n.log("GET %s %d",a,t.status),!t.ok)throw i(ED,n,(s=o(ED,n),s++,s)),new Error("unable to fetch raw block for CID ".concat(e," from gateway ").concat(n.url));return i(xD,n,(r=o(xD,n),r++,r)),new Uint8Array(yield t.arrayBuffer())}));return function(e){return t.apply(this,arguments)}}()),o(AD,n).set(s,c)}return yield c}catch(r){var f;if(!0===(null==t?void 0:t.aborted))throw new Error("fetching raw block for CID ".concat(e," from gateway ").concat(n.url," was aborted"));throw i(ED,n,(f=o(ED,n),++f)),new Error("unable to fetch raw block for CID ".concat(e))}finally{null==t||t.removeEventListener("abort",u),o(AD,n).delete(s)}}))()}reliability(){return 0===o(SD,this)?1:o(kD,this)>0?-1/0:o(xD,this)/(o(SD,this)+3*o(ED,this))}incrementInvalidBlocks(){var e;i(kD,this,(e=o(kD,this),++e))}getStats(){return{attempts:o(SD,this),errors:o(ED,this),invalidBlocks:o(kD,this),successes:o(xD,this),pendingResponses:o(AD,this).size}}}function TD(e){var t=e.multihash.bytes;return se.encode(t)}function PD(e,t,r){return e.filter((e=>{if(Nh.matches(e)||t&&Bh.matches(e))return!!r||(!!rh.matches(e)||!1===hD(e.toOptions().host));if(!t&&r){var{host:n}=e.toOptions();if("127.0.0.1"===n||"localhost"===n||n.endsWith(".localhost"))return!0}return!1}))}function _D(e,t,r,n,i){return BD.apply(this,arguments)}function BD(){return BD=l((function(e,t,r,n,i){var o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};return function*(){var a,l=!1,c=!1;try{for(var d,h=s(t.findProviders(e,o));l=!(d=yield u(h.next())).done;l=!1){var v=PD(d.value.multiaddrs,n,i);if(0!==v.length){var p=bD(v[0]);yield new ID(p,{logger:r,transformRequestInit:o.transformRequestInit})}}}catch(e){c=!0,a=e}finally{try{l&&null!=h.return&&(yield u(h.return()))}finally{if(c)throw a}}}()})),BD.apply(this,arguments)}class ND extends JN{constructor(r,n){var i,o;super(r,t(t({},n),{},{name:"helia:trustless-gateway:session"})),e(this,"routing",void 0),e(this,"allowInsecure",void 0),e(this,"allowLocal",void 0),e(this,"transformRequestInit",void 0),this.routing=r.routing,this.allowInsecure=null!==(i=n.allowInsecure)&&void 0!==i?i:RD,this.allowLocal=null!==(o=n.allowLocal)&&void 0!==o?o:OD,this.transformRequestInit=n.transformRequestInit}queryProvider(e,t,n){var i=this;return r((function*(){var r;i.log("fetching BLOCK for %c from %s",e,t.url);var o=yield t.getRawBlock(e,n.signal);return i.log.trace("got block for %c from %s",e,t.url),yield null===(r=n.validateFn)||void 0===r?void 0:r.call(n,o),o}))()}findNewProviders(e){var r=this;return l((function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(_D(e,r.routing,r.logger,r.allowInsecure,r.allowLocal,t(t({},n),{},{transformRequestInit:r.transformRequestInit}))))}()})).apply(this,arguments)}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}}class DD{constructor(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"allowInsecure",void 0),e(this,"allowLocal",void 0),e(this,"transformRequestInit",void 0),e(this,"routing",void 0),e(this,"log",void 0),e(this,"logger",void 0),this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.allowInsecure=null!==(r=i.allowInsecure)&&void 0!==r?r:RD,this.allowLocal=null!==(n=i.allowLocal)&&void 0!==n?n:OD,this.transformRequestInit=i.transformRequestInit}retrieve(e){var n=arguments,i=this;return r((function*(){var r,o=n.length>1&&void 0!==n[1]?n[1]:{},a=[],l=!1,u=!1;try{for(var c,d=s(_D(e,i.routing,i.logger,i.allowInsecure,i.allowLocal,t(t({},o),{},{transformRequestInit:i.transformRequestInit})));l=!(c=yield d.next()).done;l=!1){var h=c.value;i.log("getting block for %c from %s",e,h.url);try{var v=yield h.getRawBlock(e,o.signal);i.log.trace("got block for %c from %s",e,h.url);try{var p;yield null===(p=o.validateFn)||void 0===p?void 0:p.call(o,v)}catch(t){i.log.error("failed to validate block for %c from %s",e,h.url,t);continue}return v}catch(t){var f;if(i.log.error("failed to get block for %c from %s",e,h.url,t),t instanceof Error?a.push(t):a.push(new Error("Unable to fetch raw block for CID ".concat(e," from gateway ").concat(h.url))),!0===(null===(f=o.signal)||void 0===f?void 0:f.aborted)){i.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,h.url);break}}}}catch(e){u=!0,r=e}finally{try{l&&null!=d.return&&(yield d.return())}finally{if(u)throw r}}throw a.length>0?new AggregateError(a,"Unable to fetch raw block for CID ".concat(e," from any gateway")):new Error("Unable to fetch raw block for CID ".concat(e," from any gateway"))}))()}createSession(){var e,r,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return e={logger:this.logger,routing:this.routing},r=t(t({},n),{},{allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit}),new ND(e,r)}}var RD=!1,OD=!1;function LD(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new DD(t,e)}function MD(e){return UD.apply(this,arguments)}function UD(){return UD=l((function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var r=e.getReader();try{for(;;){var n=yield u(r.read());if(n.done)return;yield n.value}}finally{!0!==t.preventCancel&&(yield u(r.cancel())),r.releaseLock()}}()})),UD.apply(this,arguments)}var FD,zD={exports:{}};var jD,VD,qD=(FD||(FD=1,jD=zD,function(){jD.exports=f;var e=86400,t=3200,r=146097*t/400,n=e*r,i=1e3*n,o=864e13,a=4294967296,s=1e6,l="000000000",u=Math.trunc||function(e){var t=e-e%1;return 0==t&&(e<0||0===e&&1/e!=1/0)?-0:t},c=f.prototype,d=(f.fromDate=function(e){return new f(+e)},f.fromInt64BE=b(0,1,2,3,0,4),f.fromInt64LE=b(3,2,1,0,4,0),f.fromString=function(e){var t,r=new f;if(e=(e+="").replace(/^\s*[+\-]?\d+/,(function(e){var t=1970+((e=+e)-1970)%400;return r.year=e-t,t})).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,(function(e,r,n){return r<0&&(n*=-1),t=6e4*(60*+r+ +n),""})).replace(/\.\d+$/,(function(e){return r.nano=+(e+l).substr(1,9),""})).split(/\D+/),1<e.length?e[1]--:e[1]=0,r.time=t=Date.UTC.apply(Date,e)-(t||0),isNaN(t))throw new TypeError("Invalid Date");return g(r)},f.fromTimeT=function(e){return m(e,0)},c.year=0,c.time=0,c.nano=0,c.addNano=function(e){return this.nano+=+e||0,this},c.getNano=function(){var e=g(this);return(e.time%1e3*s+ +e.nano+1e9)%1e9},c.getTimeT=function(){var n=g(this),i=Math.floor(n.time/1e3);return(n=n.year)&&(i+=n*r*e/t),i},c.getYear=function(){return this.toDate().getUTCFullYear()+this.year},c.toDate=function(){return y(g(this).time)},c.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},c.toString=function(e){var t=this,r=t.toDate(),n={H:function(){return E(r.getUTCHours())},L:function(){return k(r.getUTCMilliseconds(),3)},M:function(){return E(r.getUTCMinutes())},N:function(){return k(t.getNano(),9)},S:function(){return E(r.getUTCSeconds())},Y:function(){var e=t.getYear();return 999999<e?"+"+e:9999<e?"+"+k(e,6):0<=e?k(e,4):-999999<=e?"-"+k(-e,6):e},a:function(){return v[r.getUTCDay()]},b:function(){return h[r.getUTCMonth()]},d:function(){return E(r.getUTCDate())},e:function(){return function(e){return(9<e?"":" ")+(0|e)}(r.getUTCDate())},m:function(){return E(r.getUTCMonth()+1)}};return function e(t){return t.replace(/%./g,(function(t){var r=t[1],i=p[r];return r=n[r],i?e(i):r?r():t}))}(e||d)},c.writeInt64BE=w(0,1,2,3,0,4),c.writeInt64LE=w(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),h=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],v=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],p={"%":"%",F:"%Y-%m-%d",n:"\n",R:"%H:%M",T:"%H:%M:%S",t:"\t",X:"%T",Z:"GMT",z:"+0000"};return f;function f(e,t,r){var n=this;if(!(n instanceof f))return new f(e,t,r);n.time=+e||0,n.nano=+t||0,n.year=+r||0,g(n)}function g(e){var r,n,a,l=e.year,c=e.time,d=e.nano,h=((d<0||s<=d)&&(d-=(n=Math.floor(d/s))*s,c+=n,n=1),l%t);return(c<-o||o<c||h)&&((r=u(c/i))&&(l+=r*t,c-=r*i),(a=y(c)).setUTCFullYear(h+a.getUTCFullYear()),a=(c=+a)+(r=u((l-=h)/t))*i,r&&-o<=a&&a<=o&&(l-=r*t,c=a),n=1),n&&(e.year=l,e.time=c,e.nano=d),e}function y(e){var t=new Date(0);return t.setTime(e),t}function m(e,r){e=+e||0;var i=u((r=(0|r)*a)/n)+u(e/n);return(e=u((r=r%n+e%n)/n))&&(i+=e,r-=e*n),new f(1e3*r,0,i*t)}function w(n,i,o,s,l,c){return function(n,i){var o=g(this);S(n=n||new Array(8),i|=0);var s=Math.floor(o.time/1e3),h=(o=o.year*(r*e/t),u(o/a)+u(s/a));return o=o%a+s%a,(s=Math.floor(o/a))&&(h+=s,o-=s*a),d(n,i+l,h),d(n,i+c,o),n};function d(e,t,r){e[t+n]=r>>24&255,e[t+i]=r>>16&255,e[t+o]=r>>8&255,e[t+s]=255&r}}function b(e,t,r,n,i,o){return function(e,t){S(e,t|=0);var r=a(e,t+i);return m(a(e,t+o),r)};function a(i,o){return 16777216*i[o+e]+(i[o+t]<<16|i[o+r]<<8|i[o+n])}}function S(e,t){if(null==(e=e&&e.length))throw new TypeError("Invalid Buffer");if(e<t+8)throw new RangeError("Out of range")}function E(e){return(9<e?"":"0")+(0|e)}function k(e,t){return(l+(0|e)).substr(-t)}}()),zD.exports),HD=a(qD);class KD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Record signature creation failed"),this.name="SignatureCreationError"}}e(KD,"name","SignatureCreationError");class WD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Record signature verification failed"),this.name="SignatureVerificationError"}}e(WD,"name","SignatureVerificationError");class GD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Record has expired"),this.name="RecordExpiredError"}}e(GD,"name","RecordExpiredError");class QD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The validity type is unsupported"),this.name="UnsupportedValidityError"}}e(QD,"name","UnsupportedValidityError");class YD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The record is too large"),this.name="RecordTooLargeError"}}e(YD,"name","RecordTooLargeError");class JD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Value must be a valid content path starting with /"),this.name="InvalidValueError"}}e(JD,"name","InvalidValueError");class ZD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid record data"),this.name="InvalidRecordDataError"}}e(ZD,"name","InvalidRecordDataError");class $D extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid embedded public key"),this.name="InvalidEmbeddedPublicKeyError"}}e($D,"name","InvalidEmbeddedPublicKeyError"),function(e){var t,r;(e.ValidityType||(e.ValidityType={})).EOL="EOL",function(e){e[e.EOL=0]="EOL"}(t||(t={})),function(e){e.codec=()=>Gl(t)}(e.ValidityType||(e.ValidityType={})),e.codec=()=>(null==r&&(r=Ql((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==n.lengthDelimited&&r.fork(),null!=t.value&&(r.uint32(10),r.bytes(t.value)),null!=t.signatureV1&&(r.uint32(18),r.bytes(t.signatureV1)),null!=t.validityType&&(r.uint32(24),e.ValidityType.codec().encode(t.validityType,r)),null!=t.validity&&(r.uint32(34),r.bytes(t.validity)),null!=t.sequence&&(r.uint32(40),r.uint64(t.sequence)),null!=t.ttl&&(r.uint32(48),r.uint64(t.ttl)),null!=t.pubKey&&(r.uint32(58),r.bytes(t.pubKey)),null!=t.signatureV2&&(r.uint32(66),r.bytes(t.signatureV2)),null!=t.data&&(r.uint32(74),r.bytes(t.data)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n={},i=null==r?t.len:t.pos+r;t.pos<i;){var o=t.uint32();switch(o>>>3){case 1:n.value=t.bytes();break;case 2:n.signatureV1=t.bytes();break;case 3:n.validityType=e.ValidityType.codec().decode(t);break;case 4:n.validity=t.bytes();break;case 5:n.sequence=t.uint64();break;case 6:n.ttl=t.uint64();break;case 7:n.pubKey=t.bytes();break;case 8:n.signatureV2=t.bytes();break;case 9:n.data=t.bytes();break;default:t.skipType(7&o)}}return n}))),r),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(VD||(VD={}));var XD=dd("ipns:utils"),eR=xt("/ipns/");function tR(e){return"signatureV1"in e?VD.encode({value:xt(e.value),signatureV1:e.signatureV1,validityType:e.validityType,validity:xt(e.validity),sequence:e.sequence,ttl:e.ttl,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data}):VD.encode({pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data})}function rR(e){var t=VD.decode(e);if(null!=t.sequence&&(t.sequence=BigInt(t.sequence)),null!=t.ttl&&(t.ttl=BigInt(t.ttl)),null==t.signatureV2||null==t.data)throw new WD("Missing data or signatureV2");var r=oR(t.data),n=function(e){var t=gt(e).trim();if(t.startsWith("/"))return t;try{return"/ipfs/".concat(it.decode(e).toV1().toString())}catch(e){}try{return"/ipfs/".concat(it.parse(t).toV1().toString())}catch(e){}throw new JD("Value must be a valid content path starting with /")}(r.Value),i=gt(r.Validity);if(null!=t.value&&null!=t.signatureV1)return function(e){var t,r;if(null==e.data)throw new ZD("Record data is missing");var n=oR(e.data);if(!Et(n.Value,null!==(t=e.value)&&void 0!==t?t:new Uint8Array(0)))throw new WD('Field "value" did not match between protobuf and CBOR');if(!Et(n.Validity,null!==(r=e.validity)&&void 0!==r?r:new Uint8Array(0)))throw new WD('Field "validity" did not match between protobuf and CBOR');if(n.ValidityType!==e.validityType)throw new WD('Field "validityType" did not match between protobuf and CBOR');if(n.Sequence!==e.sequence)throw new WD('Field "sequence" did not match between protobuf and CBOR');if(n.TTL!==e.ttl)throw new WD('Field "ttl" did not match between protobuf and CBOR')}(t),{value:n,validityType:VD.ValidityType.EOL,validity:i,sequence:r.Sequence,ttl:r.TTL,pubKey:t.pubKey,signatureV1:t.signatureV1,signatureV2:t.signatureV2,data:t.data};if(null!=t.signatureV2)return{value:n,validityType:VD.ValidityType.EOL,validity:i,sequence:r.Sequence,ttl:r.TTL,pubKey:t.pubKey,signatureV2:t.signatureV2,data:t.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}function nR(e){return zt([eR,e.bytes])}function iR(e){var t=He(e.slice(eR.length));if(!aR(t,0)&&!aR(t,18))throw new Qa("Multihash in IPNS key was not identity or sha2-256");return t}function oR(e){var t=V_(e);if(0!==t.ValidityType)throw new QD("The validity type is unsupported");return t.ValidityType=VD.ValidityType.EOL,Number.isInteger(t.Sequence)&&(t.Sequence=BigInt(t.Sequence)),Number.isInteger(t.TTL)&&(t.TTL=BigInt(t.TTL)),t}function aR(e,t){return e.code===t}var sR=dd("ipns:validator"),lR=function(){var e=r((function*(e,t){var r,n,i=rR(t);try{var o=(n=i.data,zt([xt("ipns-signature:"),n]));r=yield e.verify(o,i.signatureV2)}catch(e){r=!1}if(!r)throw sR.error("record signature verification failed"),new WD("Record signature verification failed");if(i.validityType===VD.ValidityType.EOL){if(HD.fromString(i.validity).toDate().getTime()<Date.now())throw sR.error("record has expired"),new GD("record has expired")}else if(null!=i.validityType)throw sR.error("the validity type is unsupported"),new QD("The validity type is unsupported");sR("ipns record for %s is valid",i.value)}));return function(t,r){return e.apply(this,arguments)}}();function uR(e,t){return cR.apply(this,arguments)}function cR(){return(cR=r((function*(e,t){var r;if(t.byteLength>10240)throw new YD("The record is too large");var n,i=iR(e);aR(i,0)&&(n=xu(i));var o=null!==(r=function(e){var t;if(null!=e.pubKey)try{t=Eu(e.pubKey)}catch(e){throw XD.error(e),e}if(null!=t)return t}(rR(t)))&&void 0!==r?r:n;if(null==o)throw new $D("Could not extract public key from IPNS record or routing key");if(!Et(nR(o.toMultihash()),e))throw new $D("Embedded public key did not match routing key");yield lR(o,t)}))).apply(this,arguments)}let dR=class extends Error{constructor(){super(...arguments),e(this,"name","InvalidMessageLengthError"),e(this,"code","ERR_INVALID_MESSAGE_LENGTH")}};function hR(e){return vR.apply(this,arguments)}function vR(){return vR=l((function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var r,n=/\r?\n/,i=new TextDecoder("utf8"),o="",a=!1,l=!1;try{for(var c,d=s(e);a=!(c=yield u(d.next())).done;a=!1){var h,v,p=c.value;if("string"==typeof p&&(p=(new TextEncoder).encode(p)),ws(p)&&(p=p.subarray()),(o+=i.decode(p,{stream:!0})).length>(null!==(h=null==t?void 0:t.maxMessageLength)&&void 0!==h?h:o.length))throw new dR("Incoming message too long");var f=o.split(n);o=null!==(v=f.pop())&&void 0!==v?v:"";for(var g=0;g<f.length;g++)yield JSON.parse(f[g])}}catch(e){l=!0,r=e}finally{try{a&&null!=d.return&&(yield u(d.return()))}finally{if(l)throw r}}""!==(o+=i.decode())&&(yield JSON.parse(o))}()})),vR.apply(this,arguments)}class pR extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid request"),this.name="InvalidRequestError"}}e(pR,"name","InvalidRequestError");class fR extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Bad response"),this.name="BadResponseError"}}function gR(e){if(null!=e[Symbol.asyncIterator])return r((function*(){var t,r=!1,n=!1;try{for(var i,o=s(e);r=!(i=yield o.next()).done;r=!1){return i.value}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield o.return())}finally{if(n)throw t}}}))();for(var t of e)return t}e(fR,"name","BadResponseError");var yR=xt("/ipns/");function mR(e){return Et(e.subarray(0,yR.byteLength),yR)}class wR{constructor(t){e(this,"client",void 0),this.client=t}findProviders(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(Pc(t.client.getProviders(e,r),(e=>{var t;return{id:e.ID,multiaddrs:null!==(t=e.Addrs)&&void 0!==t?t:[]}}))))}()})).apply(this,arguments)}provide(){return r((function*(){}))()}cancelReprovide(){return r((function*(){}))()}put(e,t,n){var i=this;return r((function*(){if(mR(e)){var r=iR(e),o=it.createV1(114,r),a=rR(t);yield i.client.putIPNS(o,a,n)}}))()}get(e,t){var n=this;return r((function*(){if(!mR(e))throw new Ha("Not found");var r=iR(e),i=it.createV1(114,r);try{return tR(yield n.client.getIPNS(i,t))}catch(e){if("BadResponseError"===e.name)throw new Ha("Not found");throw e}}))()}}class bR{constructor(t){e(this,"client",void 0),this.client=t}findPeer(e){var t=arguments,n=this;return r((function*(){var r,i=t.length>1&&void 0!==t[1]?t[1]:{},o=yield gR(n.client.getPeers(e,i));if(null!=o)return{id:o.ID,multiaddrs:null!==(r=o.Addrs)&&void 0!==r?r:[]};throw new Ha("Not found")}))()}getClosestPeers(e){return l((function(e){return function*(){}()})).apply(this,arguments)}}var SR=dd("delegated-routing-v1-http-api-client"),ER={concurrentRequests:4,timeout:3e4,cacheTTL:3e5,cacheName:"delegated-routing-v1-cache"},kR=new WeakSet;class xR{constructor(t){var r,n,i,o,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};d(this,kR),e(this,"started",void 0),e(this,"httpQueue",void 0),e(this,"shutDownController",void 0),e(this,"clientUrl",void 0),e(this,"timeout",void 0),e(this,"contentRouting",void 0),e(this,"peerRouting",void 0),e(this,"filterAddrs",void 0),e(this,"filterProtocols",void 0),e(this,"inFlightRequests",void 0),e(this,"cacheName",void 0),e(this,"cache",void 0),e(this,"cacheTTL",void 0),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new OT({concurrency:null!==(r=a.concurrentRequests)&&void 0!==r?r:ER.concurrentRequests}),this.inFlightRequests=new Map,this.clientUrl=t instanceof URL?t:new URL(t),this.timeout=null!==(n=a.timeout)&&void 0!==n?n:ER.timeout,this.filterAddrs=a.filterAddrs,this.filterProtocols=a.filterProtocols,this.contentRouting=new wR(this),this.peerRouting=new bR(this),this.cacheName=null!==(i=a.cacheName)&&void 0!==i?i:ER.cacheName,this.cacheTTL=null!==(o=a.cacheTTL)&&void 0!==o?o:ER.cacheTTL}get[ka](){return this.contentRouting}get[Ta](){return this.peerRouting}isStarted(){return this.started}start(){var e=this;return r((function*(){var t;e.started||(e.started=!0,e.cacheTTL>0&&(e.cache=yield null===(t=globalThis.caches)||void 0===t?void 0:t.open(e.cacheName),null!=e.cache&&SR("cache enabled with ttl %d",e.cacheTTL)))}))()}stop(){var e=this;return r((function*(){var t;e.httpQueue.clear(),e.shutDownController.abort(),yield null===(t=globalThis.caches)||void 0===t?void 0:t.delete(e.cacheName),e.started=!1}))()}getProviders(e){var t=this;return l((function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){SR("getProviders starts: %c",e);var i=AbortSignal.timeout(t.timeout),o=Dh([t.shutDownController.signal,i,n.signal]),a=_c(),l=_c();t.httpQueue.add(r((function*(){return a.resolve(),l.promise})));try{yield u(a.promise);var c=new URL("".concat(t.clientUrl,"routing/v1/providers/").concat(e.toString()));h(kR,t,CR).call(t,c,n.filterAddrs,n.filterProtocols);var d={headers:{Accept:"application/x-ndjson"},signal:o},v=yield u(h(kR,t,IR).call(t,c.toString(),d));if(null==v)throw new fR("No response received");if(!v.ok){if(404===v.status)throw new Ha("No matching records found");if(422===v.status)throw new pR("Request does not conform to schema or semantic constraints");throw new fR("Unexpected status code: ".concat(v.status))}if(null==v.body)throw new fR("Routing response had no body");var p=v.headers.get("Content-Type");if(null==p)throw new fR("No Content-Type header received");if(null!=p&&p.startsWith("application/json")){var f=yield u(v.json());for(var g of f.Providers){var y=h(kR,t,AR).call(t,g);null!=y&&(yield y)}}else{if(!p.includes("application/x-ndjson"))throw new fR("Unsupported Content-Type: ".concat(p));var m,w=!1,b=!1;try{for(var S,E=s(hR(MD(v.body)));w=!(S=yield u(E.next())).done;w=!1){var k=S.value,x=h(kR,t,AR).call(t,k);null!=x&&(yield x)}}catch(e){b=!0,m=e}finally{try{w&&null!=E.return&&(yield u(E.return()))}finally{if(b)throw m}}}}finally{o.clear(),l.resolve(),SR("getProviders finished: %c",e)}}()})).apply(this,arguments)}getPeers(e){var t=this;return l((function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){SR("getPeers starts: %c",e);var i=AbortSignal.timeout(t.timeout),o=Dh([t.shutDownController.signal,i,n.signal]),a=_c(),l=_c();t.httpQueue.add(r((function*(){return a.resolve(),l.promise})));try{yield u(a.promise);var c=new URL("".concat(t.clientUrl,"routing/v1/peers/").concat(e.toCID().toString()));h(kR,t,CR).call(t,c,n.filterAddrs,n.filterProtocols);var d={headers:{Accept:"application/x-ndjson"},signal:o},v=yield u(h(kR,t,IR).call(t,c.toString(),d));if(404===v.status)throw new Ha("No matching records found");if(422===v.status)throw new pR("Request does not conform to schema or semantic constraints");if(null==v.body)throw new fR("Routing response had no body");if("application/json"===v.headers.get("Content-Type")){var p=yield u(v.json());for(var f of p.Peers){var g=h(kR,t,AR).call(t,f);null!=g&&(yield g)}}else{var y,m=!1,w=!1;try{for(var b,S=s(hR(MD(v.body)));m=!(b=yield u(S.next())).done;m=!1){var E=b.value,k=h(kR,t,AR).call(t,E);null!=k&&(yield k)}}catch(e){w=!0,y=e}finally{try{m&&null!=S.return&&(yield u(S.return()))}finally{if(w)throw y}}}}catch(e){SR.error("getPeers errored:",e)}finally{o.clear(),l.resolve(),SR("getPeers finished: %c",e)}}()})).apply(this,arguments)}getIPNS(e){var t=arguments,n=this;return r((function*(){var i=t.length>1&&void 0!==t[1]?t[1]:{};SR("getIPNS starts: %s",e);var o=AbortSignal.timeout(n.timeout),a=Dh([n.shutDownController.signal,o,i.signal]),s=_c(),l=_c();n.httpQueue.add(r((function*(){return s.resolve(),l.promise})));var u="".concat(n.clientUrl,"routing/v1/ipns/").concat(e);try{yield s.promise;var c={headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:a},d=yield h(kR,n,IR).call(n,u,c);if(SR("getIPNS GET %s %d",u,d.status),404===d.status)throw new Ha("No matching records found");if(422===d.status)throw new pR("Request does not conform to schema or semantic constraints");if(null==d.body)throw new fR("GET ipns response had no body");var v=yield d.arrayBuffer(),p=new Uint8Array(v,0,v.byteLength);return!1!==i.validate&&(yield uR(nR(e.multihash),p)),rR(p)}catch(e){throw SR.error("getIPNS GET %s error:",u,e),e}finally{a.clear(),l.resolve(),SR("getIPNS finished: %s",e)}}))()}putIPNS(e,t){var n=arguments,i=this;return r((function*(){var o=n.length>2&&void 0!==n[2]?n[2]:{};SR("putIPNS starts: %c",e);var a=AbortSignal.timeout(i.timeout),s=Dh([i.shutDownController.signal,a,o.signal]),l=_c(),u=_c();i.httpQueue.add(r((function*(){return l.resolve(),u.promise})));var c="".concat(i.clientUrl,"routing/v1/ipns/").concat(e);try{yield l.promise;var d={method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:tR(t),signal:s},v=yield h(kR,i,IR).call(i,c,d);if(SR("putIPNS PUT %s %d",c,v.status),200!==v.status)throw new fR("PUT ipns response had status other than 200")}catch(e){throw SR.error("putIPNS PUT %s error:",c,e.stack),e}finally{s.clear(),u.resolve(),SR("putIPNS finished: %c",e)}}))()}}function AR(e){try{var r,n,i=[],o=null!==(r=null===(n=e.Addrs)||void 0===n?void 0:n.map(Ir))&&void 0!==r?r:[];return null!=e.Protocols&&i.push(...e.Protocols),null!=e.Protocol&&(i.push(e.Protocol),delete e.Protocol),t(t({},e),{},{Schema:"peer",ID:Mu(e.ID),Addrs:o,Protocols:i})}catch(e){SR.error("could not conform record to peer schema",e)}}function CR(e,t,r){if(null!=t||null!=this.filterAddrs){var n,i,o,a=null!==(n=null!==(i=null==t?void 0:t.join(","))&&void 0!==i?i:null===(o=this.filterAddrs)||void 0===o?void 0:o.join(","))&&void 0!==n?n:"";""!==a&&e.searchParams.set("filter-addrs",a)}if(null!=r||null!=this.filterProtocols){var s,l,u,c=null!==(s=null!==(l=null==r?void 0:r.join(","))&&void 0!==l?l:null===(u=this.filterProtocols)||void 0===u?void 0:u.join(","))&&void 0!==s?s:"";""!==c&&e.searchParams.set("filter-protocols",c)}}function IR(e,t){return TR.apply(this,arguments)}function TR(){return TR=r((function*(e,t){var n,i=this,o=null!==(n=t.method)&&void 0!==n?n:"GET",a="".concat(o,"-").concat(e);if("GET"===o){var s,l=yield null===(s=this.cache)||void 0===s?void 0:s.match(e);if(null!=l){var u,c;if(parseInt(null!==(u=l.headers.get("x-cache-expires"))&&void 0!==u?u:"0",10)>Date.now())return SR("returning cached response for %s",a),l;yield null===(c=this.cache)||void 0===c?void 0:c.delete(e)}}var d=this.inFlightRequests.get(a);if(null!=d){var h=yield d;return SR("deduplicating outgoing request for %s",a),h.clone()}var v=fetch(e,t).then(function(){var t=r((function*(t){if(null!=i.cache&&t.ok&&"GET"===o){var r=Date.now()+i.cacheTTL,n=new Headers(t.headers);n.set("x-cache-expires",r.toString());var a=new Response(t.clone().body,{status:t.status,statusText:t.statusText,headers:n});yield i.cache.put(e,a)}return t}));return function(e){return t.apply(this,arguments)}}()).finally((()=>{this.inFlightRequests.delete(a)}));return this.inFlightRequests.set(a,v),yield v})),TR.apply(this,arguments)}var PR="[a-fA-F\\d:]",_R=e=>e&&e.includeBoundaries?"(?:(?<=\\s|^)(?=".concat(PR,")|(?<=").concat(PR,")(?=\\s|$))"):"",BR="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",NR="[a-fA-F\\d]{1,4}",DR="\n(?:\n(?:".concat(NR,":){7}(?:").concat(NR,"|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:").concat(NR,":){6}(?:").concat(BR,"|:").concat(NR,"|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:").concat(NR,":){5}(?::").concat(BR,"|(?::").concat(NR,"){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:").concat(NR,":){4}(?:(?::").concat(NR,"){0,1}:").concat(BR,"|(?::").concat(NR,"){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:").concat(NR,":){3}(?:(?::").concat(NR,"){0,2}:").concat(BR,"|(?::").concat(NR,"){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:").concat(NR,":){2}(?:(?::").concat(NR,"){0,3}:").concat(BR,"|(?::").concat(NR,"){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:").concat(NR,":){1}(?:(?::").concat(NR,"){0,4}:").concat(BR,"|(?::").concat(NR,"){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::").concat(NR,"){0,5}:").concat(BR,"|(?::").concat(NR,"){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n").replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),RR=new RegExp("(?:^".concat(BR,"$)|(?:^").concat(DR,"$)")),OR=new RegExp("^".concat(BR,"$")),LR=new RegExp("^".concat(DR,"$")),MR=e=>e&&e.exact?RR:new RegExp("(?:".concat(_R(e)).concat(BR).concat(_R(e),")|(?:").concat(_R(e)).concat(DR).concat(_R(e),")"),"g");MR.v4=e=>e&&e.exact?OR:new RegExp("".concat(_R(e)).concat(BR).concat(_R(e)),"g"),MR.v6=e=>e&&e.exact?LR:new RegExp("".concat(_R(e)).concat(DR).concat(_R(e)),"g");var{toString:UR}=Object.prototype;var FR={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function zR(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t=e,"[object RegExp]"!==UR.call(t))throw new TypeError("Expected a RegExp instance");var n=Object.keys(FR).map((t=>("boolean"==typeof r[t]?r[t]:e[t])?FR[t]:"")).join(""),i=new RegExp(r.source||e.source,n);return i.lastIndex="number"==typeof r.lastIndex?r.lastIndex:e.lastIndex,i}function jR(e,t){var r,n,{timeout:i}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{return(r=()=>zR(e).test(t),n=function(){return r(...arguments)},Object.defineProperty(n,"name",{value:"functionTimeout(".concat(r.name||"<anonymous>",")"),configurable:!0}),n)()}catch(e){throw e}}var VR={timeout:400};function qR(e){return!(e.length>45)&&jR(MR.v6({exact:!0}),e,VR)}var HR={http:"80",https:"443",ws:"80",wss:"443"},KR=["http","https","ws","wss"];function WR(e,t){var r,n=null!==(r=(t=null!=t?t:{}).defaultDnsType)&&void 0!==r?r:"dns",{scheme:i,hostname:o,port:a,path:s}=function(e){var[t]=e.split(":");KR.includes(t)||(e="http"+e.substring(t.length));var r,{protocol:n,hostname:i,port:o,pathname:a,search:s}=new URL(e);if(null==o||""===o){var l=function(e){if(null==e||""===e||null==HR[e])return;return HR[e]}(t);null!=l&&(o=l),null==l&&"http:"===n&&(o="80")}null!=a&&""!==a&&"/"!==a&&(a.startsWith("/")&&(a=a.substring(1)),r=a);null!=s&&""!==s&&(r=null!=r?r:"",r+=s);return{scheme:t,hostname:i,port:o,path:r}}(e),l=[GR(o,n),QR(a,i),YR(i)];return null!=s&&l.push(function(e){if(null==e||""===e)return;return["http-path",encodeURIComponent(e)]}(s)),Ir("/"+l.filter((e=>Boolean(e))).reduce(((e,t)=>e.concat(t)),[]).join("/"))}function GR(e,t){if(null!=e&&""!==e){if(function(e){return!(e.length>15)&&jR(MR.v4({exact:!0}),e,VR)}(e))return["ip4",e];if(qR(e))return["ip6",e];if("["===e[0]){var r=e.substring(1,e.length-1);if(qR(r))return["ip6",r]}return[t,e]}}function QR(e,t){if(null!=e&&""!==e)return"udp"===t?["udp",e]:["tcp",e]}function YR(e){if(null==e.match(/^tcp$|^udp$/))return"https"===e?["/tls/http"]:"wss"===e?["/tls/ws"]:[e]}var JR=["https://trustless-gateway.link","https://4everland.io"];class ZR{constructor(){var t,r,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e(this,"gateways",void 0),e(this,"shuffle",void 0),this.gateways=(null!==(t=n.gateways)&&void 0!==t?t:JR).map((e=>function(e){return e=e.toString(),{id:ju(it.createV1(2336,Ge.digest(xt(e)))),multiaddrs:[WR(e)]}}(e))),this.shuffle=null===(r=n.shuffle)||void 0===r||r}findProviders(e,r){var n=this;return l((function*(){yield*c(s((n.shuffle?n.gateways.toSorted((()=>Math.random()>.5?1:-1)):n.gateways).map((e=>t(t({},e),{},{protocols:["transport-ipfs-gateway-http"]})))))}))()}}function $R(){return new ZR(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{})}class XR{constructor(t){e(this,"libp2p",void 0),this.libp2p=t}provide(e,t){var n=this;return r((function*(){yield n.libp2p.contentRouting.provide(e,t)}))()}cancelReprovide(e,t){var n=this;return r((function*(){yield n.libp2p.contentRouting.cancelReprovide(e,t)}))()}findProviders(e,t){var r=this;return l((function*(){yield*c(s(r.libp2p.contentRouting.findProviders(e,t)))}))()}put(e,t,n){var i=this;return r((function*(){yield i.libp2p.contentRouting.put(e,t,n)}))()}get(e,t){var n=this;return r((function*(){return n.libp2p.contentRouting.get(e,t)}))()}findPeer(e,t){var n=this;return r((function*(){return n.libp2p.peerRouting.findPeer(e,t)}))()}getClosestPeers(e,t){var r=this;return l((function*(){yield*c(s(r.libp2p.peerRouting.getClosestPeers(e,t)))}))()}}function eO(e){return new XR(e)}class tO extends ZN{constructor(r){super(t(t({},r),{},{components:{libp2p:r.libp2p}})),e(this,"libp2p",void 0),this.libp2p=r.libp2p}start(){var e=()=>super.start,t=this;return r((function*(){yield e().call(t),yield t.libp2p.start()}))()}stop(){var e=()=>super.stop,t=this;return r((function*(){yield e().call(t),yield t.libp2p.stop()}))()}}class rO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The frame was invalid"),this.name="InvalidFrameError"}}e(rO,"name","InvalidFrameError");class nO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unrequested ping error"),this.name="UnrequestedPingError"}}e(nO,"name","UnrequestedPingError");class iO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unrequested ping error"),this.name="NotMatchingPingError"}}e(iO,"name","NotMatchingPingError");class oO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid state"),this.name="InvalidStateError"}}e(oO,"name","InvalidStateError");class aO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Strean already exists"),this.name="StreamAlreadyExistsError"}}e(aO,"name","StreamAlreadyExistsError");class sO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Decode invalid version"),this.name="DecodeInvalidVersionError"}}e(sO,"name","DecodeInvalidVersionError");class lO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Both clients"),this.name="BothClientsError"}}e(lO,"name","BothClientsError");class uO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Receive window exceeded"),this.name="ReceiveWindowExceededError"}}e(uO,"name","ReceiveWindowExceededError");var cO,dO,hO=new Set([rO.name,nO.name,iO.name,aO.name,sO.name,lO.name,uO.name]),vO=262144,pO={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,initialStreamWindowSize:vO,maxStreamWindowSize:16777216,maxMessageSize:65536};!function(e){e[e.Data=0]="Data",e[e.WindowUpdate=1]="WindowUpdate",e[e.Ping=2]="Ping",e[e.GoAway=3]="GoAway"}(cO||(cO={})),function(e){e[e.SYN=1]="SYN",e[e.ACK=2]="ACK",e[e.FIN=4]="FIN",e[e.RST=8]="RST"}(dO||(dO={})),Object.values(dO).filter((e=>"string"!=typeof e));var fO;!function(e){e[e.NormalTermination=0]="NormalTermination",e[e.ProtocolError=1]="ProtocolError",e[e.InternalError=2]="InternalError"}(fO||(fO={}));var gO=2**24;let yO=class{constructor(t){e(this,"source",void 0),e(this,"buffer",void 0),e(this,"frameInProgress",void 0),this.source=function(e){if(void 0!==e[Symbol.iterator]){var t=e[Symbol.iterator]();return t.return=void 0,{[Symbol.iterator]:()=>t}}if(void 0!==e[Symbol.asyncIterator]){var r=e[Symbol.asyncIterator]();return r.return=void 0,{[Symbol.asyncIterator]:()=>r}}throw new Error("a source must be either an iterable or an async iterable")}(t),this.buffer=new bs,this.frameInProgress=!1}emitFrames(){var e=this;return l((function*(){var t,r=!1,n=!1;try{for(var i,o=s(e.source);r=!(i=yield u(o.next())).done;r=!1){var a=i.value;for(e.buffer.append(a);;){var l=e.readHeader();if(void 0===l)break;var{type:c,length:d}=l;c===cO.Data?(e.frameInProgress=!0,yield{header:l,readData:e.readBytes.bind(e,d)}):yield{header:l}}}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw t}}}))()}readHeader(){if(this.frameInProgress)throw new oO("decoding frame already in progress");if(!(this.buffer.length<12)){var e=function(e){if(0!==e[0])throw new rO("Invalid frame version");return{type:e[1],flag:(e[2]<<8)+e[3],streamID:e[4]*gO+(e[5]<<16)+(e[6]<<8)+e[7],length:e[8]*gO+(e[9]<<16)+(e[10]<<8)+e[11]}}(this.buffer.subarray(0,12));return this.buffer.consume(12),e}}readBytes(e){var t=this;return r((function*(){if(t.buffer.length<e){var r,n=!1,i=!1;try{for(var o,a=s(t.source);n=!(o=yield a.next()).done;n=!1){var l=o.value;if(t.buffer.append(l),t.buffer.length>=e)break}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield a.return())}finally{if(i)throw r}}}var u=t.buffer.sublist(0,e);return t.buffer.consume(e),t.frameInProgress=!1,u}))()}};function mO(e){var t=new Uint8Array(12);return t[1]=e.type,t[2]=e.flag>>>8,t[3]=e.flag,t[4]=e.streamID>>>24,t[5]=e.streamID>>>16,t[6]=e.streamID>>>8,t[7]=e.streamID,t[8]=e.length>>>24,t[9]=e.length>>>16,t[10]=e.length>>>8,t[11]=e.length,t}var wO;!function(e){e[e.Init=0]="Init",e[e.SYNSent=1]="SYNSent",e[e.SYNReceived=2]="SYNReceived",e[e.Established=3]="Established",e[e.Finished=4]="Finished"}(wO||(wO={}));class bO extends pp{constructor(r){super(t(t({},r),{},{onEnd:e=>{var t;this.state=wO.Finished,null===(t=r.onEnd)||void 0===t||t.call(r,e)}})),e(this,"name",void 0),e(this,"state",void 0),e(this,"config",void 0),e(this,"_id",void 0),e(this,"sendWindowCapacity",void 0),e(this,"sendWindowCapacityUpdate",void 0),e(this,"recvWindow",void 0),e(this,"recvWindowCapacity",void 0),e(this,"epochStart",void 0),e(this,"getRTT",void 0),e(this,"sendFrame",void 0),this.config=r.config,this._id=parseInt(r.id,10),this.name=r.name,this.state=r.state,this.sendWindowCapacity=vO,this.recvWindow=this.config.initialStreamWindowSize,this.recvWindowCapacity=this.recvWindow,this.epochStart=Date.now(),this.getRTT=r.getRTT,this.sendFrame=r.sendFrame,this.source=lv(this.source,(()=>{this.sendWindowUpdate()}))}sendNewStream(){return r((function*(){}))()}sendData(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};for(e=e.sublist();0!==e.byteLength;){var i,o;if(0===n.sendWindowCapacity)if(null===(i=n.log)||void 0===i||i.trace("wait for send window capacity, status %s",n.status),yield n.waitForSendWindowCapacity(r),"closed"===n.status||"aborted"===n.status||"reset"===n.status)return void(null===(o=n.log)||void 0===o||o.trace("%s while waiting for send window capacity",n.status));var a=Math.min(n.sendWindowCapacity,n.config.maxMessageSize-12,e.length),s=n.getSendFlags();n.sendFrame({type:cO.Data,flag:s,streamID:n._id,length:a},e.sublist(0,a)),n.sendWindowCapacity-=a,e.consume(a)}}))()}sendReset(){var e=this;return r((function*(){e.sendFrame({type:cO.WindowUpdate,flag:dO.RST,streamID:e._id,length:0})}))()}sendCloseWrite(){var e=this;return r((function*(){var t=e.getSendFlags()|dO.FIN;e.sendFrame({type:cO.WindowUpdate,flag:t,streamID:e._id,length:0})}))()}sendCloseRead(){return r((function*(){}))()}waitForSendWindowCapacity(){var e=arguments,t=this;return r((function*(){var r,n=e.length>0&&void 0!==e[0]?e[0]:{};if(!(t.sendWindowCapacity>0)){var i,o,a=()=>{"open"===t.status||"closing"===t.status?o(new Ba("Stream aborted")):i()};null===(r=n.signal)||void 0===r||r.addEventListener("abort",a);try{yield new Promise(((e,r)=>{t.sendWindowCapacityUpdate=()=>{e()},o=r,i=e}))}finally{var s;null===(s=n.signal)||void 0===s||s.removeEventListener("abort",a)}}}))()}handleWindowUpdate(e){var t;null===(t=this.log)||void 0===t||t.trace("stream received window update id=%s",this._id),this.processFlags(e.flag);var r,n=this.sendWindowCapacity;(this.sendWindowCapacity+=e.length,0===n&&e.length>0)&&(null===(r=this.sendWindowCapacityUpdate)||void 0===r||r.call(this))}handleData(e,t){var n=this;return r((function*(){var r;if(null===(r=n.log)||void 0===r||r.trace("stream received data id=%s",n._id),n.processFlags(e.flag),n.recvWindowCapacity<e.length)throw new uO("Receive window exceeded");var i=yield t();n.recvWindowCapacity-=e.length,n.sourcePush(i)}))()}processFlags(e){(e&dO.ACK)===dO.ACK&&this.state===wO.SYNSent&&(this.state=wO.Established),(e&dO.FIN)===dO.FIN&&this.remoteCloseWrite(),(e&dO.RST)===dO.RST&&this.reset()}getSendFlags(){switch(this.state){case wO.Init:return this.state=wO.SYNSent,dO.SYN;case wO.SYNReceived:return this.state=wO.Established,dO.ACK;default:return 0}}sendWindowUpdate(){var e=this.getSendFlags(),t=Date.now(),r=this.getRTT();if(0===e&&r>-1&&t-this.epochStart<4*r&&(this.recvWindow=Math.min(2*this.recvWindow,this.config.maxStreamWindowSize)),!(this.recvWindowCapacity>=this.recvWindow&&0===e)){var n=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:cO.WindowUpdate,flag:e,streamID:this._id,length:n})}}}var SO="/yamux/1.0.0";class EO{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"protocol",SO),e(this,"_components",void 0),e(this,"_init",void 0),e(this,Symbol.toStringTag,"@chainsafe/libp2p-yamux"),e(this,fs,["@libp2p/stream-multiplexing"]),this._components=t,this._init=r}createStreamMuxer(e){return new kO(this._components,t(t({},this._init),e))}}class kO{constructor(n,i){var o,a=this;e(this,"protocol",SO),e(this,"source",void 0),e(this,"sink",void 0),e(this,"config",void 0),e(this,"log",void 0),e(this,"logger",void 0),e(this,"closeController",void 0),e(this,"nextStreamID",void 0),e(this,"_streams",void 0),e(this,"nextPingID",void 0),e(this,"activePing",void 0),e(this,"rtt",void 0),e(this,"client",void 0),e(this,"localGoAway",void 0),e(this,"remoteGoAway",void 0),e(this,"numInboundStreams",void 0),e(this,"numOutboundStreams",void 0),e(this,"onIncomingStream",void 0),e(this,"onStreamEnd",void 0),this.client="outbound"===i.direction,this.config=t(t({},pO),i),this.logger=n.logger,this.log=this.logger.forComponent("libp2p:yamux"),function(e){if(e.keepAliveInterval<=0)throw new Ra("keep-alive interval must be positive");if(e.maxInboundStreams<0)throw new Ra("max inbound streams must be larger or equal 0");if(e.maxOutboundStreams<0)throw new Ra("max outbound streams must be larger or equal 0");if(e.initialStreamWindowSize<vO)throw new Ra("InitialStreamWindowSize must be larger or equal 256 kB");if(e.maxStreamWindowSize<e.initialStreamWindowSize)throw new Ra("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(e.maxStreamWindowSize>2**32-1)throw new Ra("MaxStreamWindowSize must be less than equal MAX_UINT32");if(e.maxMessageSize<1024)throw new Ra("MaxMessageSize must be greater than a kilobyte")}(this.config),this.closeController=new AbortController,this.closeController.signal,this.onIncomingStream=i.onIncomingStream,this.onStreamEnd=i.onStreamEnd,this._streams=new Map,this.source=Rc({onEnd:()=>{var e;null===(e=this.log)||void 0===e||e.trace("muxer source ended"),this._streams.forEach((e=>{e.destroy()}))}}),this.sink=function(){var e=r((function*(e){var t,r,n,i=()=>{var t,r=dp(e);if(null!=r.return){var n=r.return();null!=(t=n)&&"function"==typeof t.then&&n.catch((e=>{var t;null===(t=a.log)||void 0===t||t.call(a,"could not cause sink source to return",e)}))}};try{var o=new yO(e);try{a.closeController.signal.addEventListener("abort",i);var l,u=!1,c=!1;try{for(var d,h=s(o.emitFrames());u=!(d=yield h.next()).done;u=!1){var v=d.value;yield a.handleFrame(v.header,v.readData)}}catch(e){c=!0,l=e}finally{try{u&&null!=h.return&&(yield h.return())}finally{if(c)throw l}}}finally{a.closeController.signal.removeEventListener("abort",i)}r=fO.NormalTermination}catch(e){var p,f;if(hO.has(e.name))null===(p=a.log)||void 0===p||p.error("protocol error in sink",e),r=fO.ProtocolError;else null===(f=a.log)||void 0===f||f.error("internal error in sink",e),r=fO.InternalError;n=e}null===(t=a.log)||void 0===t||t.trace("muxer sink ended"),null!=n?a.abort(n,r):yield a.close({reason:r})}));return function(t){return e.apply(this,arguments)}}(),this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,null===(o=this.log)||void 0===o||o.trace("muxer created"),this.config.enableKeepAlive&&this.keepAliveLoop().catch((e=>{var t;return null===(t=this.log)||void 0===t?void 0:t.error("keepalive error: %s",e)})),this.ping().catch((e=>{var t;return null===(t=this.log)||void 0===t?void 0:t.error("ping error: %s",e)}))}get streams(){return Array.from(this._streams.values())}newStream(e){var t;if(void 0!==this.remoteGoAway)throw new ja("Muxer closed remotely");if(void 0!==this.localGoAway)throw new ja("Muxer closed locally");var r=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.config.maxOutboundStreams)throw new os("max outbound streams exceeded");null===(t=this.log)||void 0===t||t.trace("new outgoing stream id=%s",r);var n=this._newStream(r,e,wO.Init,"outbound");return this._streams.set(r,n),this.numOutboundStreams++,n.sendWindowUpdate(),n}ping(){var e=this;return r((function*(){if(void 0!==e.remoteGoAway)throw new ja("Muxer closed remotely");if(void 0!==e.localGoAway)throw new ja("Muxer closed locally");if(void 0===e.activePing){var t=()=>{};e.activePing={id:e.nextPingID++,promise:new Promise(((r,n)=>{var i=()=>{n(new ja("Muxer closed locally"))};e.closeController.signal.addEventListener("abort",i,{once:!0}),t=()=>{e.closeController.signal.removeEventListener("abort",i),r()}})),resolve:t};var r=Date.now();e.sendPing(e.activePing.id);try{yield e.activePing.promise}finally{delete e.activePing}var n=Date.now();e.rtt=n-r}else yield e.activePing.promise;return e.rtt}))()}getRTT(){return this.rtt}close(){var e=arguments,n=this;return r((function*(){var i,o,a,s=e.length>0&&void 0!==e[0]?e[0]:{};if(!n.closeController.signal.aborted){var l=null!==(i=null===(o=s)||void 0===o?void 0:o.reason)&&void 0!==i?i:fO.NormalTermination;if(null===(a=n.log)||void 0===a||a.trace("muxer close reason=%s",l),null==s.signal){var u=AbortSignal.timeout(500);s=t(t({},s),{},{signal:u})}try{yield Promise.all([...n._streams.values()].map(function(){var e=r((function*(e){return e.close(s)}));return function(t){return e.apply(this,arguments)}}())),n.sendGoAway(l),n._closeMuxer()}catch(e){n.abort(e)}}}))()}abort(e,t){var r;if(!this.closeController.signal.aborted){for(var n of(t=null!=t?t:fO.InternalError,null===(r=this.log)||void 0===r||r.error("muxer abort reason=%s error=%s",t,e),this._streams.values()))n.abort(e);this.sendGoAway(t),this._closeMuxer()}}isClosed(){return this.closeController.signal.aborted}_closeMuxer(){this.closeController.abort(),this.source.end()}_newStream(e,t,r,n){if(null!=this._streams.get(e))throw new Ra("Stream already exists with that id");var i=new bO({id:e.toString(),name:t,state:r,direction:n,sendFrame:this.sendFrame.bind(this),onEnd:()=>{var t;this.closeStream(e),null===(t=this.onStreamEnd)||void 0===t||t.call(this,i)},log:this.logger.forComponent("libp2p:yamux:".concat(n,":").concat(e)),config:this.config,getRTT:this.getRTT.bind(this)});return i}closeStream(e){this.client===(e%2==0)?this.numInboundStreams--:this.numOutboundStreams--,this._streams.delete(e)}keepAliveLoop(){var e=this;return r((function*(){var t,r=new Promise(((t,r)=>{e.closeController.signal.addEventListener("abort",r,{once:!0})}));null===(t=e.log)||void 0===t||t.trace("muxer keepalive enabled interval=%s",e.config.keepAliveInterval);for(var n,i=function*(){var t;try{yield Promise.race([r,new Promise((r=>{t=setTimeout(r,e.config.keepAliveInterval)}))]),e.ping().catch((t=>{var r;return null===(r=e.log)||void 0===r?void 0:r.error("ping error: %s",t)}))}catch(e){return clearInterval(t),{v:void 0}}};;)if(n=yield*i())return n.v}))()}handleFrame(e,t){var n=this;return r((function*(){var r,{streamID:i,type:o,length:a}=e;if(null===(r=n.log)||void 0===r||r.trace("received frame %o",e),0===i)switch(o){case cO.Ping:return void n.handlePing(e);case cO.GoAway:return void n.handleGoAway(a);default:throw new rO("Invalid frame type")}else switch(e.type){case cO.Data:case cO.WindowUpdate:return void(yield n.handleStreamMessage(e,t));default:throw new rO("Invalid frame type")}}))()}handlePing(e){if(e.flag===dO.SYN){var t;null===(t=this.log)||void 0===t||t.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,dO.ACK)}else{if(e.flag!==dO.ACK)throw new rO("Invalid frame flag");var r;null===(r=this.log)||void 0===r||r.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length)}}handlePingResponse(e){if(void 0===this.activePing)throw new nO("ping not requested");if(this.activePing.id!==e)throw new iO("ping doesn't match our id");this.activePing.resolve()}handleGoAway(e){var t,r;for(var n of(null===(t=this.log)||void 0===t||t.trace("received GoAway reason=%s",null!==(r=fO[e])&&void 0!==r?r:"unknown"),this.remoteGoAway=e,this._streams.values()))n.reset();this._closeMuxer()}handleStreamMessage(e,t){var n=this;return r((function*(){var{streamID:r,flag:i,type:o}=e;(i&dO.SYN)===dO.SYN&&n.incomingStream(r);var a=n._streams.get(r);if(void 0!==a)switch(o){case cO.WindowUpdate:return void a.handleWindowUpdate(e);case cO.Data:if(void 0===t)throw new Error("unreachable");return void(yield a.handleData(e,t));default:throw new Error("unreachable")}else if(o===cO.Data){var s;if(null===(s=n.log)||void 0===s||s.call(n,"discarding data for stream id=%s",r),void 0===t)throw new Error("unreachable");yield t()}else{var l;null===(l=n.log)||void 0===l||l.trace("frame for missing stream id=%s",r)}}))()}incomingStream(e){var t,r;if(this.client!==(e%2==0))throw new Ra("Both endpoints are clients");if(!this._streams.has(e))if(null===(t=this.log)||void 0===t||t.trace("new incoming stream id=%s",e),void 0===this.localGoAway){var n;if(this.numInboundStreams>=this.config.maxInboundStreams)return null===(n=this.log)||void 0===n||n.call(this,"maxIncomingStreams exceeded, forcing stream reset"),void this.sendFrame({type:cO.WindowUpdate,flag:dO.RST,streamID:e,length:0});var i=this._newStream(e,void 0,wO.SYNReceived,"inbound");this.numInboundStreams++,this._streams.set(e,i),null===(r=this.onIncomingStream)||void 0===r||r.call(this,i)}else this.sendFrame({type:cO.WindowUpdate,flag:dO.RST,streamID:e,length:0})}sendFrame(e,t){var r;if(null===(r=this.log)||void 0===r||r.trace("sending frame %o",e),e.type===cO.Data){if(void 0===t)throw new rO("Invalid frame");this.source.push(new bs(mO(e),t))}else this.source.push(mO(e))}sendPing(e){var t,r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:dO.SYN;n===dO.SYN?null===(t=this.log)||void 0===t||t.trace("sending ping request pingId=%s",e):null===(r=this.log)||void 0===r||r.trace("sending ping response pingId=%s",e);this.sendFrame({type:cO.Ping,flag:n,streamID:0,length:e})}sendGoAway(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:fO.NormalTermination;null===(e=this.log)||void 0===e||e.call(this,"sending GoAway reason=%s",fO[t]),this.localGoAway=t,this.sendFrame({type:cO.GoAway,flag:0,streamID:0,length:t})}}function xO(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new EO(t,e)}function AO(e){try{var[[t,r]]=e.stringTuples();if(null==r)return!1;if(41===t)return n=r,new kr("2000::/3").contains(n)}catch(e){}var n;return!1}function CO(e){try{var[[t]]=e.stringTuples();return 4===t||41===t}catch(e){}return!1}function IO(e){try{var t;if(!CO(e))return!1;var[[,r]]=e.stringTuples();return null!=r&&(null!==(t=hD(r))&&void 0!==t&&t)}catch(e){}return!0}var TO;!function(e){var t,r,n,i;!function(e){e.DIAL="DIAL",e.DIAL_RESPONSE="DIAL_RESPONSE"}(e.MessageType||(e.MessageType={})),function(e){e[e.DIAL=0]="DIAL",e[e.DIAL_RESPONSE=1]="DIAL_RESPONSE"}(t||(t={})),function(e){e.codec=()=>Gl(t)}(e.MessageType||(e.MessageType={})),(r=e.ResponseStatus||(e.ResponseStatus={})).OK="OK",r.E_DIAL_ERROR="E_DIAL_ERROR",r.E_DIAL_REFUSED="E_DIAL_REFUSED",r.E_BAD_REQUEST="E_BAD_REQUEST",r.E_INTERNAL_ERROR="E_INTERNAL_ERROR",function(e){e[e.OK=0]="OK",e[e.E_DIAL_ERROR=100]="E_DIAL_ERROR",e[e.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",e[e.E_BAD_REQUEST=200]="E_BAD_REQUEST",e[e.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"}(n||(n={})),function(e){e.codec=()=>Gl(n)}(e.ResponseStatus||(e.ResponseStatus={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.id&&(t.uint32(10),t.bytes(e.id)),null!=e.addrs)for(var n of e.addrs)t.uint32(18),t.bytes(n);!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={addrs:[]},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.id=e.bytes();break;case 2:var a;if(null!=(null===(a=r.limits)||void 0===a?void 0:a.addrs)&&n.addrs.length===r.limits.addrs)throw new Yl('Decode error - map field "addrs" had too many elements');n.addrs.push(e.bytes());break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(e.PeerInfo||(e.PeerInfo={})),function(t){var r;t.codec=()=>(null==r&&(r=Ql((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==n.lengthDelimited&&r.fork(),null!=t.peer&&(r.uint32(10),e.PeerInfo.codec().encode(t.peer,r)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={},o=null==r?t.len:t.pos+r;t.pos<o;){var a,s=t.uint32();if(s>>>3==1)i.peer=e.PeerInfo.codec().decode(t,t.uint32(),{limits:null===(a=n.limits)||void 0===a?void 0:a.peer});else t.skipType(7&s)}return i}))),r),t.encode=e=>Kl(e,t.codec()),t.decode=(e,r)=>kl(e,t.codec(),r)}(e.Dial||(e.Dial={})),function(t){var r;t.codec=()=>(null==r&&(r=Ql((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==n.lengthDelimited&&r.fork(),null!=t.status&&(r.uint32(8),e.ResponseStatus.codec().encode(t.status,r)),null!=t.statusText&&(r.uint32(18),r.string(t.statusText)),null!=t.addr&&(r.uint32(26),r.bytes(t.addr)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n={},i=null==r?t.len:t.pos+r;t.pos<i;){var o=t.uint32();switch(o>>>3){case 1:n.status=e.ResponseStatus.codec().decode(t);break;case 2:n.statusText=t.string();break;case 3:n.addr=t.bytes();break;default:t.skipType(7&o)}}return n}))),r),t.encode=e=>Kl(e,t.codec()),t.decode=(e,r)=>kl(e,t.codec(),r)}(e.DialResponse||(e.DialResponse={})),e.codec=()=>(null==i&&(i=Ql((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==n.lengthDelimited&&r.fork(),null!=t.type&&(r.uint32(8),e.MessageType.codec().encode(t.type,r)),null!=t.dial&&(r.uint32(18),e.Dial.codec().encode(t.dial,r)),null!=t.dialResponse&&(r.uint32(26),e.DialResponse.codec().encode(t.dialResponse,r)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={},o=null==r?t.len:t.pos+r;t.pos<o;){var a=t.uint32();switch(a>>>3){case 1:i.type=e.MessageType.codec().decode(t);break;case 2:var s;i.dial=e.Dial.codec().decode(t,t.uint32(),{limits:null===(s=n.limits)||void 0===s?void 0:s.dial});break;case 3:var l;i.dialResponse=e.DialResponse.codec().decode(t,t.uint32(),{limits:null===(l=n.limits)||void 0===l?void 0:l.dialResponse});break;default:t.skipType(7&a)}}return i}))),i),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(TO||(TO={}));class PO{constructor(t,n){var i,o,a,s,l,u;e(this,"components",void 0),e(this,"protocol",void 0),e(this,"timeout",void 0),e(this,"maxInboundStreams",void 0),e(this,"maxOutboundStreams",void 0),e(this,"maxMessageSize",void 0),e(this,"started",void 0),e(this,"log",void 0),e(this,"topologyId",void 0),e(this,"dialResults",void 0),e(this,"findPeers",void 0),e(this,"addressFilter",void 0),e(this,"connectionThreshold",void 0),e(this,Symbol.toStringTag,"@libp2p/autonat"),e(this,fs,["@libp2p/autonat"]),this.components=t,this.log=t.logger.forComponent("libp2p:auto-nat"),this.started=!1,this.protocol="/".concat(null!==(i=n.protocolPrefix)&&void 0!==i?i:"libp2p","/").concat("autonat","/").concat("1.0.0"),this.timeout=null!==(o=n.timeout)&&void 0!==o?o:3e4,this.maxInboundStreams=null!==(a=n.maxInboundStreams)&&void 0!==a?a:2,this.maxOutboundStreams=null!==(s=n.maxOutboundStreams)&&void 0!==s?s:20,this.connectionThreshold=null!==(l=n.connectionThreshold)&&void 0!==l?l:80,this.maxMessageSize=null!==(u=n.maxMessageSize)&&void 0!==u?u:8192,this.dialResults=new Map,this.findPeers=function(e,t,n){var i,o;function a(){var s,l={signal:o.signal};if(null!=(null===(s=n)||void 0===s?void 0:s.timeout)){var u=Dh([o.signal,AbortSignal.timeout(n.timeout)]);l.signal=u}Promise.resolve().then(r((function*(){yield e(l)}))).catch((()=>{})).finally((()=>{o.signal.aborted||(i=setTimeout(a,t))}))}var s=!1;return{setInterval:e=>{t!==e&&(t=e,null!=i&&(clearTimeout(i),i=setTimeout(a,t)))},setTimeout:e=>{null!=n||(n={}),n.timeout=e},start:()=>{var e;s||(s=!0,(o=new AbortController).signal,!0===(null===(e=n)||void 0===e?void 0:e.runImmediately)?queueMicrotask((()=>{a()})):i=setTimeout(a,t))},stop:()=>{var e;clearTimeout(i),null===(e=o)||void 0===e||e.abort(),s=!1}}}(this.findRandomPeers.bind(this),6e4),this.addressFilter=rv(1024)}get[gs](){return["@libp2p/identify"]}isStarted(){return this.started}start(){var e=this;return r((function*(){e.started||(yield e.components.registrar.handle(e.protocol,(t=>{e.handleIncomingAutonatStream(t).catch((t=>{e.log.error("error handling incoming autonat stream - %e",t)}))}),{maxInboundStreams:e.maxInboundStreams,maxOutboundStreams:e.maxOutboundStreams}),e.topologyId=yield e.components.registrar.register(e.protocol,{onConnect:(t,r)=>{e.verifyExternalAddresses(r).catch((t=>{e.log.error("could not verify addresses - %e",t)}))}}),e.findPeers.start(),e.started=!0)}))()}stop(){var e=this;return r((function*(){yield e.components.registrar.unhandle(e.protocol),null!=e.topologyId&&(yield e.components.registrar.unhandle(e.topologyId)),e.dialResults.clear(),e.findPeers.stop(),e.started=!1}))()}allAddressesAreVerified(){return this.components.addressManager.getAddressesWithMetadata().every((e=>e.expires>Date.now()||e.verified))}findRandomPeers(e){var t=this;return r((function*(){if(!t.allAddressesAreVerified()){var r=Dh([AbortSignal.timeout(1e4),null==e?void 0:e.signal]);try{t.log("starting random walk to find peers to run AutoNAT");var n,i=!1,o=!1;try{for(var a,l=s(t.components.randomWalk.walk({signal:r}));i=!(a=yield l.next()).done;i=!1){var u=a.value;if(yield t.components.connectionManager.isDialable(u.multiaddrs)){try{t.log.trace("dial random peer %p",u.id),yield t.components.connectionManager.openConnection(u.multiaddrs,{signal:r})}catch(e){}if(t.allAddressesAreVerified())return void t.log("stopping random walk, all addresses are verified");if(!t.hasConnectionCapacity())return void t.log("stopping random walk, too close to max connections")}else t.log.trace("random peer %p was not dialable %s",u.id,u.multiaddrs.map((e=>e.toString())).join(", "))}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield l.return())}finally{if(o)throw n}}}catch(e){}}}))()}handleIncomingAutonatStream(e){var t=this;return r((function*(){var r=AbortSignal.timeout(t.timeout),n=Td(e.stream,{maxDataLength:t.maxMessageSize}).pb(TO);try{var i=yield n.read({signal:r}),o=yield t.handleAutonatMessage(i,e.connection,{signal:r});yield n.write(o,{signal:r}),yield n.unwrap().unwrap().close({signal:r})}catch(r){t.log.error("error handling incoming autonat stream - %e",r),e.stream.abort(r)}}))()}handleAutonatMessage(e,t,n){var i=this;return r((function*(){var r,o=i.components.addressManager.getAddresses().map((e=>e.toOptions().host)),a=e.dial;if(null==a)return i.log.error("dial was missing from message"),{type:TO.MessageType.DIAL_RESPONSE,dialResponse:{status:TO.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}};var s=a.peer;if(null==(null==s?void 0:s.id))return i.log.error("PeerId missing from message"),{type:TO.MessageType.DIAL_RESPONSE,dialResponse:{status:TO.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}};try{var l=He(s.id);r=zu(l)}catch(e){return i.log.error("invalid PeerId - %e",e),{type:TO.MessageType.DIAL_RESPONSE,dialResponse:{status:TO.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}}}if(i.log("incoming request from %p",r),!t.remotePeer.equals(r))return i.log("target peer %p did not equal sending peer %p",r,t.remotePeer),{type:TO.MessageType.DIAL_RESPONSE,dialResponse:{status:TO.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}};var u=s.addrs.map((e=>Ir(e))).filter((e=>{var r=e.toOptions();return!IO(e)&&(r.host!==t.remoteAddr.toOptions().host?(i.log.trace("not dialing %a - target host did not match remote host %a",e,t.remoteAddr),!1):!o.includes(r.host)&&(null!=i.components.transportManager.dialTransportForMultiaddr(e)||(i.log.trace("not dialing %a - transport unsupported",e),!1)))})).map((e=>(null==e.getPeerId()&&(e=e.encapsulate("/p2p/".concat(r.toString()))),e)));if(0===u.length)return i.log("refused to dial all multiaddrs for %p from message",r),{type:TO.MessageType.DIAL_RESPONSE,dialResponse:{status:TO.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}};i.log("dial multiaddrs %s for peer %p",u.map((e=>e.toString())).join(", "),r);var c="",d=u[0];for(var h of u){var v=void 0;d=h;try{if(!(v=yield i.components.connectionManager.openConnection(h,n)).remoteAddr.equals(h))throw i.log.error("tried to dial %a but dialed %a",h,v.remoteAddr),new Error("Unexpected remote address");return i.log("successfully dialed %p via %a",r,h),{type:TO.MessageType.DIAL_RESPONSE,dialResponse:{status:TO.ResponseStatus.OK,addr:v.remoteAddr.decapsulateCode(Tr("p2p").code).bytes}}}catch(e){i.log.error("could not dial %p - %e",r,e),c=e.message}finally{null!=v&&(yield v.close())}}return{type:TO.MessageType.DIAL_RESPONSE,dialResponse:{status:TO.ResponseStatus.E_DIAL_ERROR,statusText:c,addr:d.bytes}}}))()}getFirstUnverifiedMultiaddr(e,t){var r=this.components.addressManager.getAddressesWithMetadata().sort(((e,t)=>"observed"===e.type&&"observed"!==t.type?1:"observed"===t.type&&"observed"!==e.type?-1:0)).filter((e=>{if(!(e.expires<Date.now()))return!1;if(6===e.multiaddr.toOptions().family){if(!t)return!1;if(!AO(e.multiaddr))return!1}return!IO(e.multiaddr)}));for(var n of r){var i=n.multiaddr.toString(),o=this.dialResults.get(i);if(null!=o){if(o.networkSegments.includes(e)){this.log.trace("%a already has a network segment result from %s",o.multiaddr,e);continue}if(o.queue.size>10){this.log.trace("%a already has enough peers queued",o.multiaddr);continue}}if(null==o){var a,s,l=n.expires<Date.now();if(l)null===(a=(s=this.addressFilter).remove)||void 0===a||a.call(s,i);if(this.addressFilter.has(i))continue;this.addressFilter.add(i),this.log.trace("creating dial result %s %s",l?"to revalidate":"for",i),o={multiaddr:n.multiaddr,success:0,failure:0,networkSegments:[],verifyingPeers:new Hh,queue:new bv({concurrency:3,maxSize:50}),type:n.type,lastVerified:n.lastVerified},this.dialResults.set(i,o)}return o}}removeOutdatedMultiaddrResults(){var e=new Set(this.components.addressManager.getAddressesWithMetadata().filter((e=>{var{expires:t}=e;return t<Date.now()})).map((e=>{var{multiaddr:t}=e;return t.toString()})));for(var t of this.dialResults.keys())e.has(t)||(this.log.trace("remove results for %a",t),this.dialResults.delete(t))}verifyExternalAddresses(e){var t=this;return r((function*(){if(t.isStarted()){t.removeOutdatedMultiaddrResults();var n=(yield t.components.peerStore.get(e.remotePeer)).addresses.some((e=>{var{multiaddr:t}=e;return 6===t.toOptions().family})),i=t.getNetworkSegment(e.remoteAddr),o=t.getFirstUnverifiedMultiaddr(i,n);null!=o?t.hasConnectionCapacity()?o.queue.add(function(){var n=r((function*(r){yield t.askPeerToVerify(e,i,r)}));return function(e){return n.apply(this,arguments)}}(),{peerId:e.remotePeer,multiaddr:o.multiaddr}).catch((r=>{null==(null==o?void 0:o.result)&&t.log.error("error from %p verifying address %a - %e",e.remotePeer,null==o?void 0:o.multiaddr,r)})):null!=o.lastVerified?(t.log("automatically re-verifying %a because we are too close to the connection limit",o.multiaddr),t.confirmAddress(o)):t.log("skipping verifying %a because we are too close to the connection limit",o.multiaddr):t.log.trace("no unverified public addresses found for peer %p to verify, not requesting verification",e.remotePeer)}}))()}askPeerToVerify(e,t,n){var i=this;return r((function*(){var r=i.dialResults.get(n.multiaddr.toString());if(null!=r){var o=AbortSignal.timeout(i.timeout);i.log.trace("asking %p to verify multiaddr %s",e.remotePeer,n.multiaddr);var a=yield e.newStream(i.protocol,{signal:o});try{var s=Td(a).pb(TO),[,l]=yield Promise.all([s.write({type:TO.MessageType.DIAL,dial:{peer:{id:i.components.peerId.toMultihash().bytes,addrs:[n.multiaddr.bytes]}}},{signal:o}),s.read({signal:o})]);if(l.type!==TO.MessageType.DIAL_RESPONSE||null==l.dialResponse)return void i.log("invalid autonat response from %p - %j",e.remotePeer,l);var u=l.dialResponse.status;if(i.log.trace("autonat response from %p for %a is %s",e.remotePeer,n.multiaddr,u),u!==TO.ResponseStatus.OK&&u!==TO.ResponseStatus.E_DIAL_ERROR)return;if(null==(r=i.dialResults.get(n.multiaddr.toString())))return void i.log.trace("peer reported %a as %s but there is no result object",n.multiaddr,l.dialResponse.status);if(r.networkSegments.includes(t))return void i.log.trace("%a results included network segment %s",n.multiaddr,t);if(null!=r.result)return void i.log.trace("already resolved result for %a, ignoring response from",n.multiaddr,e.remotePeer);if(r.verifyingPeers.has(e.remotePeer))return void i.log.trace("peer %p has already verified %a, ignoring response",e.remotePeer,n.multiaddr);if(r.verifyingPeers.add(e.remotePeer),r.networkSegments.push(t),u===TO.ResponseStatus.OK){if(r.success++,"observed"!==r.type)return void i.confirmAddress(r)}else u===TO.ResponseStatus.E_DIAL_ERROR&&r.failure++;i.log("%a success %d failure %d",r.multiaddr,r.success,r.failure),4===r.success&&i.confirmAddress(r),8===r.failure&&i.unconfirmAddress(r)}finally{try{yield a.close({signal:o})}catch(e){a.abort(e)}}}else i.log("%a was verified while %p was queued",n.multiaddr,e.remotePeer)}))()}hasConnectionCapacity(){return this.components.connectionManager.getConnections().length/this.components.connectionManager.getMaxConnections()*100<this.connectionThreshold}confirmAddress(e){this.log("%s address %a is externally dialable",e.type,e.multiaddr),this.components.addressManager.confirmObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!0,e.queue.abort()}unconfirmAddress(e){this.log("%s address %a is not externally dialable",e.type,e.multiaddr),this.components.addressManager.removeObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!1,e.queue.abort()}getNetworkSegment(e){var t=e.toOptions();return 4===t.family?t.host.split(".")[0].padStart(3,"0"):t.host.split(":")[0].padStart(4,"0")}}function _O(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new PO(t,e)}var BO=lL("dns4"),NO=lL("dns6"),DO=lL("dnsaddr"),RO=sL(lL("dns"),DO,BO,NO),OO=sL(lL("ip4"),lL("ip6")),LO=sL(aL(OO,lL("tcp")),aL(RO,lL("tcp"))),MO=aL(OO,lL("udp")),UO=aL(MO,lL("utp")),FO=aL(MO,lL("quic")),zO=aL(MO,lL("quic-v1")),jO=sL(aL(LO,lL("ws")),aL(RO,lL("ws"))),VO=sL(aL(jO,lL("p2p")),jO),qO=sL(aL(LO,lL("wss")),aL(RO,lL("wss")),aL(LO,lL("tls"),lL("ws")),aL(RO,lL("tls"),lL("ws"))),HO=sL(aL(qO,lL("p2p")),qO),KO=sL(aL(LO,lL("http")),aL(OO,lL("http")),aL(RO,lL("http"))),WO=sL(aL(LO,lL("https")),aL(OO,lL("https")),aL(RO,lL("https"))),GO=aL(MO,lL("webrtc-direct"),lL("certhash")),QO=sL(aL(GO,lL("p2p")),GO),YO=aL(zO,lL("webtransport"),lL("certhash"),lL("certhash")),JO=sL(aL(YO,lL("p2p")),YO),ZO=sL(aL(VO,lL("p2p-webrtc-star"),lL("p2p")),aL(HO,lL("p2p-webrtc-star"),lL("p2p")),aL(VO,lL("p2p-webrtc-star")),aL(HO,lL("p2p-webrtc-star")));sL(aL(VO,lL("p2p-websocket-star"),lL("p2p")),aL(HO,lL("p2p-websocket-star"),lL("p2p")),aL(VO,lL("p2p-websocket-star")),aL(HO,lL("p2p-websocket-star")));var $O=sL(aL(KO,lL("p2p-webrtc-direct"),lL("p2p")),aL(WO,lL("p2p-webrtc-direct"),lL("p2p")),aL(KO,lL("p2p-webrtc-direct")),aL(WO,lL("p2p-webrtc-direct"))),XO=sL(jO,qO,KO,WO,ZO,$O,LO,UO,FO,RO,QO,JO);sL(aL(XO,lL("p2p-stardust"),lL("p2p")),aL(XO,lL("p2p-stardust")));var eL=sL(aL(XO,lL("p2p")),ZO,$O,QO,JO,lL("p2p")),tL=sL(aL(eL,lL("p2p-circuit"),eL),aL(eL,lL("p2p-circuit")),aL(lL("p2p-circuit"),eL),aL(XO,lL("p2p-circuit")),aL(lL("p2p-circuit"),XO),lL("p2p-circuit")),rL=()=>sL(aL(tL,rL),tL),nL=rL(),iL=sL(aL(nL,eL,nL),aL(eL,nL),aL(nL,eL),nL,eL);function oL(e){return function(t){var r;try{r=Ir(t)}catch(e){return!1}var n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function aL(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];function n(e){if(e.length<t.length)return null;var r=e;return t.some((t=>(r="function"==typeof t?t().partialMatch(e):t.partialMatch(e),Array.isArray(r)&&(e=r),null===r))),r}return{toString:function(){return"{ "+t.join(" ")+" }"},input:t,matches:oL(n),partialMatch:n}}function sL(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];function n(e){var r=null;return t.some((t=>{var n="function"==typeof t?t().partialMatch(e):t.partialMatch(e);return null!=n&&(r=n,!0)})),r}return{toString:function(){return"{ "+t.join(" ")+" }"},input:t,matches:oL(n),partialMatch:n}}function lL(e){var t=e;return{toString:function(){return t},matches:function(e){var r;try{r=Ir(e)}catch(e){return!1}var 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}}}sL(aL(nL,lL("webrtc"),lL("p2p")),aL(nL,lL("webrtc")),aL(XO,lL("webrtc"),lL("p2p")),aL(XO,lL("webrtc")),lL("webrtc"));class uL extends us{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{list:[]};if(null==n.list||0===n.list.length)throw new Error("Bootstrap requires a list of peer addresses");for(var i of(super(),e(this,"log",void 0),e(this,"timer",void 0),e(this,"list",void 0),e(this,"timeout",void 0),e(this,"components",void 0),e(this,"_init",void 0),e(this,xa,this),e(this,Symbol.toStringTag,"@libp2p/bootstrap"),e(this,fs,["@libp2p/peer-discovery"]),this.components=t,this.log=t.logger.forComponent("libp2p:bootstrap"),this.timeout=null!==(r=n.timeout)&&void 0!==r?r:1e3,this.list=[],n.list))if(iL.matches(i)){var o=Ir(i),a=o.getPeerId();if(null!=a){var s={id:Mu(a),multiaddrs:[o]};this.list.push(s)}else this.log.error("Invalid bootstrap multiaddr without peer id")}else this.log.error("Invalid multiaddr");this._init=n}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))}_discoverBootstrapPeers(){var e=this;return r((function*(){if(null!=e.timer){var t,r=function*(t){var r,n;if(yield e.components.peerStore.merge(t.id,{tags:{[null!==(r=e._init.tagName)&&void 0!==r?r:"bootstrap"]:{value:null!==(n=e._init.tagValue)&&void 0!==n?n:50,ttl:e._init.tagTTL}},multiaddrs:t.multiaddrs}),null==e.timer)return{v:void 0};e.safeDispatchEvent("peer",{detail:t}),e.components.connectionManager.openConnection(t.id).catch((r=>{e.log.error("could not dial bootstrap peer %p",t.id,r)}))};for(var n of e.list)if(t=yield*r(n))return t.v}}))()}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}}e(uL,"tag","bootstrap");var cL=()=>{var e=new Error("Delay aborted");return e.name="AbortError",e},dL=new WeakMap;var hL,vL=function(){var{clearTimeout:e,setTimeout:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(r){var n,i,o,{value:a,signal:s}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!=s&&s.aborted)return Promise.reject(cL());var l=null!=e?e:clearTimeout,u=()=>{l(n),o(cL())},c=new Promise(((e,l)=>{i=()=>{s&&s.removeEventListener("abort",u),e(a)},o=l,n=(null!=t?t:setTimeout)(i,r)}));return s&&s.addEventListener("abort",u,{once:!0}),dL.set(c,(()=>{l(n),n=null,i()})),c}}();function pL(e,t){return!Ph.matches(e)&&(null!=t.dialTransportForMultiaddr(e)&&(!!rh.matches(e)||!!ch.matches(e)&&!1===hD(e.toOptions().host)))}!function(e){var t,r;!function(e){e.UNUSED="UNUSED",e.CONNECT="CONNECT",e.SYNC="SYNC"}(e.Type||(e.Type={})),function(e){e[e.UNUSED=0]="UNUSED",e[e.CONNECT=100]="CONNECT",e[e.SYNC=300]="SYNC"}(t||(t={})),function(e){e.codec=()=>Gl(t)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=Ql((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==n.lengthDelimited&&r.fork(),null!=t.type&&(r.uint32(8),e.Type.codec().encode(t.type,r)),null!=t.observedAddresses)for(var i of t.observedAddresses)r.uint32(18),r.bytes(i);!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={observedAddresses:[]},o=null==r?t.len:t.pos+r;t.pos<o;){var a=t.uint32();switch(a>>>3){case 1:i.type=e.Type.codec().decode(t);break;case 2:var s;if(null!=(null===(s=n.limits)||void 0===s?void 0:s.observedAddresses)&&i.observedAddresses.length===n.limits.observedAddresses)throw new Yl('Decode error - map field "observedAddresses" had too many elements');i.observedAddresses.push(t.bytes());break;default:t.skipType(7&a)}}return i}))),r),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(hL||(hL={}));var fL=5e3,gL=3,yL=1,mL=1;class wL{constructor(t,r){var n,i,o,a;e(this,"started",void 0),e(this,"timeout",void 0),e(this,"retries",void 0),e(this,"maxInboundStreams",void 0),e(this,"maxOutboundStreams",void 0),e(this,"peerStore",void 0),e(this,"registrar",void 0),e(this,"connectionManager",void 0),e(this,"addressManager",void 0),e(this,"transportManager",void 0),e(this,"topologyId",void 0),e(this,"log",void 0),e(this,Symbol.toStringTag,"@libp2p/dcutr"),e(this,gs,["@libp2p/identify"]),this.log=t.logger.forComponent("libp2p:dcutr"),this.started=!1,this.peerStore=t.peerStore,this.registrar=t.registrar,this.addressManager=t.addressManager,this.connectionManager=t.connectionManager,this.transportManager=t.transportManager,this.timeout=null!==(n=r.timeout)&&void 0!==n?n:fL,this.retries=null!==(i=r.retries)&&void 0!==i?i:gL,this.maxInboundStreams=null!==(o=r.maxInboundStreams)&&void 0!==o?o:yL,this.maxOutboundStreams=null!==(a=r.maxOutboundStreams)&&void 0!==a?a:mL}isStarted(){return this.started}start(){var e=this;return r((function*(){e.started||(e.topologyId=yield e.registrar.register(SL,{notifyOnLimitedConnection:!0,onConnect:(t,r)=>{Ph.exactMatch(r.remoteAddr)&&"inbound"===r.direction&&e.upgradeInbound(r).catch((t=>{e.log.error("error during outgoing DCUtR attempt",t)}))}}),yield e.registrar.handle(SL,(t=>{e.handleIncomingUpgrade(t.stream,t.connection).catch((r=>{e.log.error("error during incoming DCUtR attempt",r),t.stream.abort(r)}))}),{maxInboundStreams:e.maxInboundStreams,maxOutboundStreams:e.maxOutboundStreams,runOnLimitedConnection:!0}),e.started=!0)}))()}stop(){var e=this;return r((function*(){yield e.registrar.unhandle(SL),null!=e.topologyId&&e.registrar.unregister(e.topologyId),e.started=!1}))()}upgradeInbound(e){var t=this;return r((function*(){if(!(yield t.attemptUnilateralConnectionUpgrade(e)))for(var r,n=0;n<t.retries;n++){var i={signal:AbortSignal.timeout(t.timeout)};try{var o=Td(r=yield e.newStream([SL],{signal:i.signal,runOnLimitedConnection:!0}),{maxDataLength:4096}).pb(hL);t.log("B sending connect to %p",e.remotePeer);var a=Date.now();yield o.write({type:hL.Type.CONNECT,observedAddresses:t.addressManager.getAddresses().map((e=>e.bytes))},i),t.log("B receiving connect from %p",e.remotePeer);var s=yield o.read(i);if(s.type!==hL.Type.CONNECT)throw t.log("A sent wrong message type"),new Ja("DCUtR message type was incorrect");var l=t.getDialableMultiaddrs(s.observedAddresses);if(0===l.length)throw t.log("A did not have any dialable multiaddrs"),new Ja("DCUtR connect message had no multiaddrs");var u=Date.now()-a;t.log("A sending sync, rtt %dms",u),yield o.write({type:hL.Type.SYNC,observedAddresses:[]},i),t.log("A waiting for half RTT"),yield vL(u/2),t.log("B dialing",l);var c=yield t.connectionManager.openConnection(l,{signal:i.signal,priority:100,force:!0,initiator:!1});t.log("DCUtR to %p succeeded to address %a, closing relayed connection",e.remotePeer,c.remoteAddr),yield e.close(i);break}catch(e){var d;if(t.log.error("error while attempting DCUtR on attempt %d of %d",n+1,t.retries,e),null===(d=r)||void 0===d||d.abort(e),n===t.retries)throw e}finally{null!=r&&(yield r.close(i))}}}))()}attemptUnilateralConnectionUpgrade(e){var t=this;return r((function*(){var r=(yield t.peerStore.get(e.remotePeer)).addresses.map((t=>{var r=t.multiaddr;return null==r.getPeerId()?r.encapsulate("/p2p/".concat(e.remotePeer)):r})).filter((e=>pL(e,t.transportManager)));if(r.length>0){var n=AbortSignal.timeout(t.timeout);try{t.log("attempting unilateral connection upgrade to %a",r);var i=yield t.connectionManager.openConnection(r,{signal:n,force:!0});if(Ph.exactMatch(i.remoteAddr))throw new Error("Could not open a new, non-limited, connection");return t.log("unilateral connection upgrade to %p succeeded via %a, closing relayed connection",e.remotePeer,i.remoteAddr),yield e.close({signal:n}),!0}catch(n){t.log.error("unilateral connection upgrade to %p on addresses %a failed",e.remotePeer,r,n)}}else t.log("peer %p has no public addresses, not attempting unilateral connection upgrade",e.remotePeer);return!1}))()}handleIncomingUpgrade(e,t){var n=this;return r((function*(){var r={signal:AbortSignal.timeout(n.timeout)};try{var i=Td(e,{maxDataLength:4096}).pb(hL);n.log("A receiving connect");var o=yield i.read(r);if(o.type!==hL.Type.CONNECT)throw n.log("B sent wrong message type"),new Ja("DCUtR message type was incorrect");if(0===o.observedAddresses.length)throw n.log("B sent no multiaddrs"),new Ja("DCUtR connect message had no multiaddrs");var a=n.getDialableMultiaddrs(o.observedAddresses);if(0===a.length)throw n.log("B had no dialable multiaddrs"),new Ja("DCUtR connect message had no dialable multiaddrs");if(n.log("A sending connect"),yield i.write({type:hL.Type.CONNECT,observedAddresses:n.addressManager.getAddresses().map((e=>e.bytes))}),n.log("A receiving sync"),(yield i.read(r)).type!==hL.Type.SYNC)throw new Ja("DCUtR message type was incorrect");n.log("A dialing",a);var s=yield n.connectionManager.openConnection(a,{signal:r.signal,priority:100,force:!0});n.log("DCUtR to %p succeeded via %a, closing relayed connection",t.remotePeer,s.remoteAddr),yield t.close(r)}catch(r){n.log.error("incoming DCUtR from %p failed",t.remotePeer,r),e.abort(r)}finally{yield e.close(r)}}))()}getDialableMultiaddrs(e){var t=[];for(var r of e)if(null!=r&&0!==r.length)try{var n=Ir(r);if(!pL(n,this.transportManager))continue;t.push(n)}catch(e){}return t}}var bL,SL="/libp2p/dcutr";function EL(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new wL(t,e)}var kL=null!==(bL=globalThis.CustomEvent)&&void 0!==bL?bL:Event;function xL(e){return AL.apply(this,arguments)}function AL(){return AL=l((function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(n,i){var o=null!==(n=t.concurrency)&&void 0!==n?n:1/0;o<1&&(o=1/0);var a,l=null!==(i=t.ordered)&&void 0!==i&&i,d=new EventTarget,h=[],v=_c(),p=_c(),f=!1,g=!1;function y(){var e;return l?null===(e=h[0])||void 0===e?void 0:e.done:Boolean(h.find((e=>e.done)))}function*m(){for(;h.length>0&&h[0].done;){var e=h[0];if(h.shift(),!e.ok)throw g=!0,v.resolve(),e.err;yield e.value,v.resolve()}}function*w(){for(;y();)for(var e=0;e<h.length;e++)if(h[e].done){var t=h[e];if(h.splice(e,1),e--,!t.ok)throw g=!0,v.resolve(),t.err;yield t.value,v.resolve()}}for(d.addEventListener("task-complete",(()=>{p.resolve()})),Promise.resolve().then(r((function*(){try{var t,r=!1,n=!1;try{for(var i,l=function*(){var e=i.value;if(h.length===o&&(v=_c(),yield v.promise),g)return 1;var t={done:!1};h.push(t),e().then((e=>{t.done=!0,t.ok=!0,t.value=e,d.dispatchEvent(new kL("task-complete"))}),(e=>{t.done=!0,t.err=e,d.dispatchEvent(new kL("task-complete"))}))},u=s(e);(r=!(i=yield u.next()).done)&&!(yield*l());r=!1);}catch(e){n=!0,t=e}finally{try{r&&null!=u.return&&(yield u.return())}finally{if(n)throw t}}f=!0,d.dispatchEvent(new kL("task-complete"))}catch(e){a=e,d.dispatchEvent(new kL("task-complete"))}})));;){if(y()||(p=_c(),yield u(p.promise)),null!=a)throw a;if(l?yield*c(s(m())):yield*c(s(w())),null!=a)throw a;if(f&&0===h.length)break}}()})),AL.apply(this,arguments)}var CL;!function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};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(var n of e.listenAddrs)t.uint32(18),t.bytes(n);if(null!=e.observedAddr&&(t.uint32(34),t.bytes(e.observedAddr)),null!=e.protocols)for(var i of e.protocols)t.uint32(26),t.string(i);null!=e.signedPeerRecord&&(t.uint32(66),t.bytes(e.signedPeerRecord)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={listenAddrs:[],protocols:[]},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 5:n.protocolVersion=e.string();break;case 6:n.agentVersion=e.string();break;case 1:n.publicKey=e.bytes();break;case 2:var a;if(null!=(null===(a=r.limits)||void 0===a?void 0:a.listenAddrs)&&n.listenAddrs.length===r.limits.listenAddrs)throw new Yl('Decode error - map field "listenAddrs" had too many elements');n.listenAddrs.push(e.bytes());break;case 4:n.observedAddr=e.bytes();break;case 3:var s;if(null!=(null===(s=r.limits)||void 0===s?void 0:s.protocols)&&n.protocols.length===r.limits.protocols)throw new Yl('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&o)}}return n}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(CL||(CL={}));var IL={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:8192,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnLimitedConnection:!0,concurrency:32};function TL(e,t,r,n,i){return PL.apply(this,arguments)}function PL(){return PL=r((function*(e,t,r,n,i){if(r("received identify from %p",n.remotePeer),null==i)throw new Ja("message was null or undefined");var o,a={};if(i.listenAddrs.length>0&&(a.addresses=i.listenAddrs.map((e=>({isCertified:!1,multiaddr:Ir(e)})))),i.protocols.length>0&&(a.protocols=i.protocols),null!=i.publicKey){var s=Eu(i.publicKey);if(!Uu(s).equals(n.remotePeer))throw new Ja("public key did not match remote PeerId");a.publicKey=s}if(null!=i.signedPeerRecord){r.trace("received signedPeerRecord from %p",n.remotePeer);var l,u=i.signedPeerRecord,c=yield gd.openAndCertify(u,Sd.DOMAIN),d=Sd.createFromProtobuf(c.payload),h=ju(c.publicKey.toCID());if(!d.peerId.equals(h))throw new Ja("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(d.peerId))throw new Ja("signing key does not match remote PeerId");try{l=yield e.get(d.peerId)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=l&&(a.metadata=l.metadata,null!=l.peerRecordEnvelope)){var v=yield gd.createFromProtobuf(l.peerRecordEnvelope),p=Sd.createFromProtobuf(v.payload);p.seqNumber>=d.seqNumber&&(r("sequence number was lower or equal to existing sequence number - stored: %d received: %d",p.seqNumber,d.seqNumber),d=p,u=l.peerRecordEnvelope)}a.peerRecordEnvelope=u,a.addresses=d.multiaddrs.map((e=>({isCertified:!0,multiaddr:e}))),o={seq:d.seqNumber,addresses:d.multiaddrs}}else r("%p did not send a signed peer record",n.remotePeer);if(r.trace("patching %p with",n.remotePeer,a),yield e.patch(n.remotePeer,a),null!=i.agentVersion||null!=i.protocolVersion){var f={};null!=i.agentVersion&&(f.AgentVersion=xt(i.agentVersion)),null!=i.protocolVersion&&(f.ProtocolVersion=xt(i.protocolVersion)),r.trace("merging %p metadata",n.remotePeer,f),yield e.merge(n.remotePeer,{metadata:f})}var g={peerId:n.remotePeer,protocolVersion:i.protocolVersion,agentVersion:i.agentVersion,publicKey:i.publicKey,listenAddrs:i.listenAddrs.map((e=>Ir(e))),observedAddr:null==i.observedAddr?void 0:Ir(i.observedAddr),protocols:i.protocols,signedPeerRecord:o,connection:n};return t.safeDispatchEvent("peer:identify",{detail:g}),g})),PL.apply(this,arguments)}class _L{constructor(t,r){var n,i,o,a,s,l,u,c,d;e(this,"host",void 0),e(this,"protocol",void 0),e(this,"started",void 0),e(this,"timeout",void 0),e(this,"peerId",void 0),e(this,"privateKey",void 0),e(this,"peerStore",void 0),e(this,"registrar",void 0),e(this,"addressManager",void 0),e(this,"maxInboundStreams",void 0),e(this,"maxOutboundStreams",void 0),e(this,"maxMessageSize",void 0),e(this,"maxObservedAddresses",void 0),e(this,"events",void 0),e(this,"runOnLimitedConnection",void 0),e(this,"log",void 0),this.protocol=r.protocol,this.started=!1,this.peerId=t.peerId,this.privateKey=t.privateKey,this.peerStore=t.peerStore,this.registrar=t.registrar,this.addressManager=t.addressManager,this.events=t.events,this.log=r.log,this.timeout=null!==(n=r.timeout)&&void 0!==n?n:IL.timeout,this.maxInboundStreams=null!==(i=r.maxInboundStreams)&&void 0!==i?i:IL.maxInboundStreams,this.maxOutboundStreams=null!==(o=r.maxOutboundStreams)&&void 0!==o?o:IL.maxOutboundStreams,this.maxMessageSize=null!==(a=r.maxMessageSize)&&void 0!==a?a:IL.maxMessageSize,this.maxObservedAddresses=null!==(s=r.maxObservedAddresses)&&void 0!==s?s:IL.maxObservedAddresses,this.runOnLimitedConnection=null!==(l=r.runOnLimitedConnection)&&void 0!==l?l:IL.runOnLimitedConnection,this.host={protocolVersion:"".concat(null!==(u=r.protocolPrefix)&&void 0!==u?u:IL.protocolPrefix,"/").concat("0.1.0"),agentVersion:(c=t.nodeInfo,d=r.agentVersion,null!=d?d:c.userAgent)}}isStarted(){return this.started}start(){var e=this;return r((function*(){e.started||(yield e.peerStore.merge(e.peerId,{metadata:{AgentVersion:xt(e.host.agentVersion),ProtocolVersion:xt(e.host.protocolVersion)}}),yield e.registrar.handle(e.protocol,(t=>{e.handleProtocol(t).catch((t=>{e.log.error(t)}))}),{maxInboundStreams:e.maxInboundStreams,maxOutboundStreams:e.maxOutboundStreams,runOnLimitedConnection:e.runOnLimitedConnection}),e.started=!0)}))()}stop(){var e=this;return r((function*(){yield e.registrar.unhandle(e.protocol),e.started=!1}))()}}class BL extends _L{constructor(r){var n,i,o,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(r,t(t({},a),{},{protocol:"/".concat(null!==(n=a.protocolPrefix)&&void 0!==n?n:IL.protocolPrefix,"/").concat("id/push","/").concat("1.0.0"),log:r.logger.forComponent("libp2p:identify-push")})),e(this,"connectionManager",void 0),e(this,"concurrency",void 0),e(this,fs,["@libp2p/identify-push"]),this.connectionManager=r.connectionManager,this.concurrency=null!==(i=a.concurrency)&&void 0!==i?i:IL.concurrency,(null!==(o=a.runOnSelfUpdate)&&void 0!==o?o:IL.runOnSelfUpdate)&&r.events.addEventListener("self:peer:update",(e=>{this.push().catch((e=>{this.log.error(e)}))}))}push(){var e=this;return r((function*(){var t,n;if(e.isStarted()){var i=e.addressManager.getAddresses().map((e=>e.decapsulateCode(Tr("p2p").code))),o=new Sd({peerId:e.peerId,multiaddrs:i}),a=yield gd.seal(o,e.privateKey),s=e.registrar.getProtocols(),c=yield e.peerStore.get(e.peerId),d=gt(null!==(t=c.metadata.get("AgentVersion"))&&void 0!==t?t:xt(e.host.agentVersion)),h=gt(null!==(n=c.metadata.get("ProtocolVersion"))&&void 0!==n?n:xt(e.host.protocolVersion)),v=e;yield vc(xL(function(){return p.apply(this,arguments)}(),{concurrency:e.concurrency}))}function p(){return(p=l((function*(){var e=function*(e){if(!(yield u(v.peerStore.get(e.remotePeer))).protocols.includes(v.protocol))return 1;yield r((function*(){var t,r=AbortSignal.timeout(v.timeout);try{var n=Td(t=yield e.newStream(v.protocol,{signal:r,runOnLimitedConnection:v.runOnLimitedConnection}),{maxDataLength:v.maxMessageSize}).pb(CL);yield n.write({listenAddrs:i.map((e=>e.bytes)),signedPeerRecord:a.marshal(),protocols:s,agentVersion:d,protocolVersion:h},{signal:r}),yield t.close({signal:r})}catch(e){var o;v.log.error("could not push identify update to peer",e),null===(o=t)||void 0===o||o.abort(e)}}))};for(var t of v.connectionManager.getConnections())yield*e(t)}))).apply(this,arguments)}}))()}handleProtocol(e){var t=this;return r((function*(){var{connection:r,stream:n}=e;try{if(t.peerId.equals(r.remotePeer))throw new Error("received push from ourselves?");var i={signal:AbortSignal.timeout(t.timeout)},o=Td(n,{maxDataLength:t.maxMessageSize}).pb(CL),a=yield o.read(i);yield n.close(i),yield TL(t.peerStore,t.events,t.log,r,a)}catch(e){return t.log.error("received invalid message",e),void n.abort(e)}t.log.trace("handled push from %p",r.remotePeer)}))()}}class NL extends _L{constructor(r){var n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(r,t(t({},o),{},{protocol:"/".concat(null!==(n=o.protocolPrefix)&&void 0!==n?n:IL.protocolPrefix,"/").concat("id","/").concat("1.0.0"),log:r.logger.forComponent("libp2p:identify")})),e(this,fs,["@libp2p/identify"]),(null!==(i=o.runOnConnectionOpen)&&void 0!==i?i:IL.runOnConnectionOpen)&&r.events.addEventListener("connection:open",(e=>{var t=e.detail;this.identify(t).catch((e=>{e.name!==Ya.name&&this.log.error("error during identify trigged by connection:open",e)}))}))}_identify(e){var n=arguments,i=this;return r((function*(){var r,o=n.length>1&&void 0!==n[1]?n[1]:{};if(null==o.signal){var a=AbortSignal.timeout(i.timeout);o=t(t({},o),{},{signal:a})}try{var s=Td(r=yield e.newStream(i.protocol,t(t({},o),{},{runOnLimitedConnection:i.runOnLimitedConnection})),{maxDataLength:i.maxMessageSize}).pb(CL),l=yield s.read(o);return yield r.close(o),l}catch(e){var u;throw null===(u=r)||void 0===u||u.abort(e),e}}))()}identify(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{},i=yield n._identify(e,r),{publicKey:o,protocols:a,observedAddr:s}=i;if(null==o)throw new Ja("public key was missing from identify message");var l=ju(Eu(o).toCID());if(!e.remotePeer.equals(l))throw new Ja("identified peer does not match the expected peer");if(n.peerId.equals(l))throw new Ja("identified peer is our own peer id?");return n.maybeAddObservedAddress(s),n.log("identify completed for peer %p and protocols %o",l,a),TL(n.peerStore,n.events,n.log,e,i)}))()}maybeAddObservedAddress(e){var t=function(e){if(null!=e&&e.length>0)try{return Ir(e)}catch(e){}}(e);null!=t&&(this.log.trace("our observed address was %a",t),IO(t)?this.log.trace("our observed address was private"):41!==t.stringTuples()[0][0]||AO(t)?vh.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"))}handleProtocol(e){var t=this;return r((function*(){var{connection:r,stream:n}=e,i=AbortSignal.timeout(t.timeout);try{var o=yield t.peerStore.get(t.peerId),a=t.addressManager.getAddresses().map((e=>e.decapsulateCode(Tr("p2p").code))),s=o.peerRecordEnvelope;if(a.length>0&&null==s){var l=new Sd({peerId:t.peerId,multiaddrs:a});s=(yield gd.seal(l,t.privateKey)).marshal().subarray()}var u=r.remoteAddr.bytes;sh.matches(r.remoteAddr)||(u=void 0);var c=Td(n).pb(CL);yield c.write({protocolVersion:t.host.protocolVersion,agentVersion:t.host.agentVersion,publicKey:Au(t.privateKey.publicKey),listenAddrs:a.map((e=>e.bytes)),signedPeerRecord:s,observedAddr:u,protocols:o.protocols},{signal:i}),yield n.close({signal:i})}catch(e){t.log.error("could not respond to identify request",e),n.abort(e)}}))()}}function DL(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new NL(t,e)}function RL(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new BL(t,e)}var OL,LL,ML,UL,FL,zL,jL,VL,qL=36e5,HL=36*qL,KL=48*qL,WL=qL,GL="".concat(Pa,"-kad-dht");function QL(e){var t=e.getUTCFullYear(),r=String(e.getUTCMonth()+1).padStart(2,"0"),n=String(e.getUTCDate()).padStart(2,"0"),i=String(e.getUTCHours()).padStart(2,"0"),o=String(e.getUTCMinutes()).padStart(2,"0"),a=String(e.getUTCSeconds()).padStart(2,"0"),s=e.getUTCMilliseconds(),l=String(1e3*s*1e3).padStart(9,"0");return"".concat(t,"-").concat(r,"-").concat(n,"T").concat(i,":").concat(o,":").concat(a,".").concat(l,"Z")}!function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.key&&e.key.byteLength>0&&(t.uint32(10),t.bytes(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),null!=e.timeReceived&&""!==e.timeReceived&&(t.uint32(42),t.string(e.timeReceived)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={key:ct(0),value:ct(0),timeReceived:""},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.key=e.bytes();break;case 2:r.value=e.bytes();break;case 5:r.timeReceived=e.string();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(OL||(OL={}));class YL{constructor(t,r,n){if(e(this,"key",void 0),e(this,"value",void 0),e(this,"timeReceived",void 0),!(t instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(r instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=t,this.value=r,this.timeReceived=n}serialize(){return OL.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:QL(this.timeReceived)}}static deserialize(e){var t=OL.decode(e);return new YL(t.key,t.value,new Date(t.timeReceived))}static fromDeserialized(e){var t=function(e){var t=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),r=String(e).trim().match(t);if(null==r)throw new Error("Invalid format");var n=parseInt(r[1],10),i=parseInt(r[2],10)-1,o=parseInt(r[3],10),a=parseInt(r[4],10),s=parseInt(r[5],10),l=parseInt(r[6],10),u=parseInt(r[7].slice(0,-6),10);return new Date(Date.UTC(n,i,o,a,s,l,u))}(e.timeReceived);if(null==e.key)throw new Error("key missing from deserialized object");if(null==e.value)throw new Error("value missing from deserialized object");return new YL(e.key,e.value,t)}}class JL extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Query error"),this.name="QueryError"}}class ZL extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Query aborted"),this.name="QueryAbortedError"}}class $L extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid record"),this.name="InvalidRecordError"}}class XL extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No selector function configured for prefix"),this.name="MissingSelectorError"}}function eM(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t(t({},e),{},{name:"SEND_QUERY",type:0,messageName:e.type,messageType:e.type});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:send-query",{detail:i})),i}function tM(e){var r,n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=t(t({},e),{},{name:"PEER_RESPONSE",type:1,messageName:e.messageType,closer:null!==(r=e.closer)&&void 0!==r?r:[],providers:null!==(n=e.providers)&&void 0!==n?n:[]});return null===(i=o.onProgress)||void 0===i||i.call(o,new CustomEvent("kad-dht:query:peer-response",{detail:a})),a}function rM(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t(t({},e),{},{name:"FINAL_PEER",type:2});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:final-peer",{detail:i})),i}function nM(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t(t({},e),{},{name:"QUERY_ERROR",type:3});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:query-error",{detail:i})),i}function iM(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t(t({},e),{},{name:"PROVIDER",type:4});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:provider",{detail:i})),i}function oM(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t(t({},e),{},{name:"VALUE",type:5});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:value",{detail:i})),i}function aM(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t(t({},e),{},{name:"DIAL_PEER",type:7});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:dial-peer",{detail:i})),i}!function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.key&&(t.uint32(10),t.bytes(e.key)),null!=e.value&&(t.uint32(18),t.bytes(e.value)),null!=e.author&&(t.uint32(26),t.bytes(e.author)),null!=e.signature&&(t.uint32(34),t.bytes(e.signature)),null!=e.timeReceived&&(t.uint32(42),t.string(e.timeReceived)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.key=e.bytes();break;case 2:r.value=e.bytes();break;case 3:r.author=e.bytes();break;case 4:r.signature=e.bytes();break;case 5:r.timeReceived=e.string();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(LL||(LL={})),function(e){e.PUT_VALUE="PUT_VALUE",e.GET_VALUE="GET_VALUE",e.ADD_PROVIDER="ADD_PROVIDER",e.GET_PROVIDERS="GET_PROVIDERS",e.FIND_NODE="FIND_NODE",e.PING="PING"}(ML||(ML={})),function(e){e[e.PUT_VALUE=0]="PUT_VALUE",e[e.GET_VALUE=1]="GET_VALUE",e[e.ADD_PROVIDER=2]="ADD_PROVIDER",e[e.GET_PROVIDERS=3]="GET_PROVIDERS",e[e.FIND_NODE=4]="FIND_NODE",e[e.PING=5]="PING"}(UL||(UL={})),function(e){e.codec=()=>Gl(UL)}(ML||(ML={})),function(e){e.NOT_CONNECTED="NOT_CONNECTED",e.CONNECTED="CONNECTED",e.CAN_CONNECT="CAN_CONNECT",e.CANNOT_CONNECT="CANNOT_CONNECT"}(FL||(FL={})),function(e){e[e.NOT_CONNECTED=0]="NOT_CONNECTED",e[e.CONNECTED=1]="CONNECTED",e[e.CAN_CONNECT=2]="CAN_CONNECT",e[e.CANNOT_CONNECT=3]="CANNOT_CONNECT"}(zL||(zL={})),function(e){e.codec=()=>Gl(zL)}(FL||(FL={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.id&&e.id.byteLength>0&&(t.uint32(10),t.bytes(e.id)),null!=e.multiaddrs)for(var n of e.multiaddrs)t.uint32(18),t.bytes(n);null!=e.connection&&(t.uint32(24),FL.codec().encode(e.connection,t)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={id:ct(0),multiaddrs:[]},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.id=e.bytes();break;case 2:var a;if(null!=(null===(a=r.limits)||void 0===a?void 0:a.multiaddrs)&&n.multiaddrs.length===r.limits.multiaddrs)throw new Yl('Decode error - map field "multiaddrs" had too many elements');n.multiaddrs.push(e.bytes());break;case 3:n.connection=FL.codec().decode(e);break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(jL||(jL={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.type&&0!==UL[e.type]&&(t.uint32(8),ML.codec().encode(e.type,t)),null!=e.clusterLevel&&(t.uint32(80),t.int32(e.clusterLevel)),null!=e.key&&(t.uint32(18),t.bytes(e.key)),null!=e.record&&(t.uint32(26),t.bytes(e.record)),null!=e.closer)for(var n of e.closer)t.uint32(66),jL.codec().encode(n,t);if(null!=e.providers)for(var i of e.providers)t.uint32(74),jL.codec().encode(i,t);!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={type:ML.PUT_VALUE,closer:[],providers:[]},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.type=ML.codec().decode(e);break;case 10:n.clusterLevel=e.int32();break;case 2:n.key=e.bytes();break;case 3:n.record=e.bytes();break;case 8:var a,s;if(null!=(null===(a=r.limits)||void 0===a?void 0:a.closer)&&n.closer.length===r.limits.closer)throw new Yl('Decode error - map field "closer" had too many elements');n.closer.push(jL.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.closer$}));break;case 9:var l,u;if(null!=(null===(l=r.limits)||void 0===l?void 0:l.providers)&&n.providers.length===r.limits.providers)throw new Yl('Decode error - map field "providers" had too many elements');n.providers.push(jL.codec().decode(e,e.uint32(),{limits:null===(u=r.limits)||void 0===u?void 0:u.providers$}));break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(VL||(VL={}));var sM={pk:function(e,t){return 0}};function lM(e,t){return uM.apply(this,arguments)}function uM(){return uM=r((function*(e,t){var r=t.key,n=gt(r).split("/");if(!(n.length<3)){var i=e[n[1].toString()];if(null==i)throw new Ra('No validator available for key type "'.concat(n[1],'"'));yield i(r,t.value)}})),uM.apply(this,arguments)}var cM=function(){var e=r((function*(e,t){if(!(e instanceof Uint8Array))throw new Ra('"key" must be a Uint8Array');if(e.byteLength<5)throw new Ra("Invalid public key record");if("/pk/"!==gt(e.subarray(0,4)))throw new Ra("key was not prefixed with /pk/");var r=Eu(t);if(!Et(e.slice(4),r.toMultihash().bytes))throw new Ra("public key does not match passed in key")}));return function(t,r){return e.apply(this,arguments)}}(),dM={pk:cM},hM=xt("/pk/");function vM(e){return t(t({},e),{},{multiaddrs:e.multiaddrs.filter((e=>{var[[t,r]]=e.stringTuples();if(53===t||54===t||55===t)return"localhost"!==r;if(4!==t&&6!==t)return!1;if(null==r)return!1;var n=hD(r);return null==n||!n}))})}function pM(e){return fM.apply(this,arguments)}function fM(){return fM=r((function*(e){return(yield $e.digest(e)).digest})),fM.apply(this,arguments)}function gM(e){return yM.apply(this,arguments)}function yM(){return yM=r((function*(e){return pM(e.toMultihash().bytes)})),yM.apply(this,arguments)}function mM(e,t){return new hc("".concat(e,"/").concat(gt(t,"base32")),!1)}function wM(e,t){var r=new Date;return new YL(e,t,r).serialize()}function bM(e){var t=e.toString().split("/"),r=t.pop(),n=t.pop();if(null==r||null==n)throw new Error("incorrectly formatted provider entry key in datastore: ".concat(e.toString()));return{cid:it.createV1(Se,He(xt(n,"base32"))),peerId:Mu(r)}}function SM(e,t,r){var n=[e,"string"==typeof t?t:gt(t.multihash.bytes,"base32")];return null!=r&&n.push(r.toString()),new hc(n.join("/"))}function EM(e){return new Date(Ft(e))}function kM(e,t,r){return l((function*(){var n,i,o=null===(n=t.queryTime)||void 0===n?void 0:n.timer(r),a=null===(i=t.errorTime)||void 0===i?void 0:i.timer(r),l=!1;try{var d;null===(d=t.queries)||void 0===d||d.increment({[r]:!0}),yield*c(s(e(...arguments)),u)}catch(e){var h;throw l=!0,null==a||a(),null===(h=t.errors)||void 0===h||h.increment({[r]:!0}),e}finally{var v;null===(v=t.queries)||void 0===v||v.decrement({[r]:!0}),l||null==o||o()}}))}function xM(e,t,n){return r((function*(){var r,i,o=null==t||null===(r=t.queryTime)||void 0===r?void 0:r.timer(n),a=null==t||null===(i=t.errorTime)||void 0===i?void 0:i.timer(n),s=!1;try{var l;return null===(l=t.queries)||void 0===l||l.increment({[n]:!0}),yield e(...arguments)}catch(e){var u;throw s=!0,null==a||a(),null===(u=t.errors)||void 0===u||u.increment({[n]:!0}),e}finally{var c;null===(c=t.queries)||void 0===c||c.decrement({[n]:!0}),s||null==o||o()}}))}class AM{constructor(t,r){var n,i,o,a;e(this,"log",void 0),e(this,"components",void 0),e(this,"validators",void 0),e(this,"selectors",void 0),e(this,"peerRouting",void 0),e(this,"queryManager",void 0),e(this,"network",void 0),e(this,"datastorePrefix",void 0);var{validators:s,selectors:l,peerRouting:u,queryManager:c,network:d,logPrefix:h}=r;this.components=t,this.log=t.logger.forComponent("".concat(h,":content-fetching")),this.datastorePrefix="".concat(r.datastorePrefix,"/record"),this.validators=s,this.selectors=l,this.peerRouting=u,this.queryManager=c,this.network=d,this.get=null!==(n=null===(i=t.metrics)||void 0===i?void 0:i.traceFunction("libp2p.kadDHT.get",this.get.bind(this),{optionsIndex:1}))&&void 0!==n?n:this.get,this.put=null!==(o=null===(a=t.metrics)||void 0===a?void 0:a.traceFunction("libp2p.kadDHT.put",this.put.bind(this),{optionsIndex:2}))&&void 0!==o?o:this.put}getLocal(e){var t=this;return r((function*(){t.log("getLocal %b",e);var r=mM(t.datastorePrefix,e);t.log("fetching record for key %k",r);var n=yield t.components.datastore.get(r);t.log("found %k in local datastore",r);var i=YL.deserialize(n);return yield lM(t.validators,i),i}))()}sendCorrectionRecord(e,t,r){var n=this;return l((function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return function*(){n.log("sendCorrection for %b",e);var o=wM(e,r);for(var{value:a,from:l}of t)if(Et(a,r))n.log("record was ok");else if(n.components.peerId.equals(l))try{var c=mM(n.datastorePrefix,e);n.log("Storing corrected record for key ".concat(c.toString())),yield u(n.components.datastore.put(c,o.subarray()))}catch(e){n.log.error("Failed error correcting self",e)}else{var d,h=!1,v={type:ML.PUT_VALUE,key:e,record:o},p=!1,f=!1;try{for(var g,y=s(n.network.sendRequest(l,v,i));p=!(g=yield u(y.next())).done;p=!1){var m=g.value;"PEER_RESPONSE"===m.name&&null!=m.record&&Et(m.record.value,YL.deserialize(o).value)&&(h=!0),yield m}}catch(e){f=!0,d=e}finally{try{p&&null!=y.return&&(yield u(y.return()))}finally{if(f)throw d}}h||(yield nM({from:l,error:new JL("Value not put correctly")},i)),n.log.error("Failed error correcting entry")}}()})).apply(this,arguments)}put(e,n){var i=this;return l((function(e,n){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){i.log("put key %b value %b",e,n);var a=wM(e,n),d=mM(i.datastorePrefix,e);i.log("storing record for key ".concat(d.toString())),yield u(i.components.datastore.put(d,a.subarray())),yield*c(s(qc(i.peerRouting.getClosestPeers(e,t(t({},o),{},{signal:o.signal})),(t=>Pc(t,(t=>r((function*(){if("FINAL_PEER"!==t.name)return[t];var r=[],n={type:ML.PUT_VALUE,key:e,record:a};i.log("send put to %p",t.peer.id);var l,u=!1,c=!1;try{for(var d,h=s(i.network.sendRequest(t.peer.id,n,o));u=!(d=yield h.next()).done;u=!1){var v=d.value;(r.push(v),"PEER_RESPONSE"===v.name)&&(null!=v.record&&Et(v.record.value,YL.deserialize(a).value)||r.push(nM({from:t.peer.id,error:new JL("Value not put correctly")},o)))}}catch(e){c=!0,l=e}finally{try{u&&null!=h.return&&(yield h.return())}finally{if(c)throw l}}return r}))))),(e=>xL(e,{ordered:!1,concurrency:3})),function(){var e=l((function*(e){var t,r=!1,n=!1;try{for(var i,o=s(e);r=!(i=yield u(o.next())).done;r=!1){var a=i.value;yield*c(s(a),u)}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw t}}}));return function(t){return e.apply(this,arguments)}}())))}()})).apply(this,arguments)}get(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){t.log("get %b",e);var n,i=[],o=!1,a=!1;try{for(var l,d=s(t.getMany(e,r));o=!(l=yield u(d.next())).done;o=!1){var h=l.value;"VALUE"===h.name&&i.push(h),yield h}}catch(e){a=!0,n=e}finally{try{o&&null!=d.return&&(yield u(d.return()))}finally{if(a)throw n}}if(0!==i.length){var v=i.map((e=>e.value)),p=0;try{p=function(e,t,r){if(0===r.length)throw new Ra("No records given");var n=gt(t).split("/");if(n.length<3)throw new Ra("Record key does not have a selector function");var i=e[n[1].toString()];if(null==i)throw new XL('No selector function configured for key type "'.concat(n[1],'"'));return 1===r.length?0:i(t,r)}(t.selectors,e,v)}catch(e){if("InvalidParametersError"!==e.name)throw e}var f=v[p];if(t.log("GetValue %b %b",e,f),null==f)throw new Ha("Best value was not found");yield*c(s(t.sendCorrectionRecord(e,i,f,r))),yield i[p]}}()})).apply(this,arguments)}getMany(e){var r=this;return l((function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){r.log("getMany values for %b",e);try{var i=yield u(r.getLocal(e));yield oM({value:i.value,from:r.components.peerId},n)}catch(t){r.log("error getting local value for %b",e,t)}var o=r,a=function(){var r=l((function(r){var{peer:i,signal:a}=r;return function*(){var r,l=!1,c=!1;try{for(var d,h=s(o.peerRouting.getValueOrPeers(i,e,t(t({},n),{},{signal:a})));l=!(d=yield u(h.next())).done;l=!1){var v=d.value;yield v,"PEER_RESPONSE"===v.name&&null!=v.record&&(yield oM({from:i,value:v.record.value},n))}}catch(e){c=!0,r=e}finally{try{l&&null!=h.return&&(yield u(h.return()))}finally{if(c)throw r}}}()}));return function(e){return r.apply(this,arguments)}}();yield*c(s(r.queryManager.run(e,a,n)))}()})).apply(this,arguments)}}function CM(e){var t;if(null==e.id)throw new Error("Invalid peer in message");return{id:zu(He(e.id)),multiaddrs:(null!==(t=e.multiaddrs)&&void 0!==t?t:[]).map((e=>Ir(e)))}}class IM{constructor(t,r){var n,i,o,a;e(this,"log",void 0),e(this,"components",void 0),e(this,"network",void 0),e(this,"peerRouting",void 0),e(this,"queryManager",void 0),e(this,"routingTable",void 0),e(this,"providers",void 0);var{network:s,peerRouting:l,queryManager:u,routingTable:c,providers:d,logPrefix:h}=r;this.components=t,this.log=t.logger.forComponent("".concat(h,":content-routing")),this.network=s,this.peerRouting=l,this.queryManager=u,this.routingTable=c,this.providers=d,this.findProviders=null!==(n=null===(i=t.metrics)||void 0===i?void 0:i.traceFunction("libp2p.kadDHT.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromYieldedValue:(e,t)=>{var r;"PROVIDER"===e.name&&(null!==(r=t.providers)&&void 0!==r||(t.providers=[]),t.providers.push(...e.providers.map((e=>e.id.toString()))));return t}}))&&void 0!==n?n:this.findProviders,this.provide=null!==(o=null===(a=t.metrics)||void 0===a?void 0:a.traceFunction("libp2p.kadDHT.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromYieldedValue:(e,t)=>{var r;"PEER_RESPONSE"===e.name&&"ADD_PROVIDER"===e.messageName&&(null!==(r=t.providers)&&void 0!==r||(t.providers=[]),t.providers.push(e.from.toString()));return t}}))&&void 0!==o?o:this.provide}provide(e,t){var n=this;return l((function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){n.log("provide %s",e);var o=e.multihash.bytes;yield u(n.providers.addProvider(e,n.components.peerId));var a,d,h,v,p={type:ML.ADD_PROVIDER,key:o,providers:[(a={id:n.components.peerId,multiaddrs:t},v={id:a.id.toMultihash().bytes,multiaddrs:(null!==(h=a.multiaddrs)&&void 0!==h?h:[]).map((e=>e.bytes)),connection:d},v)]},f=0;yield*c(s(qc(n.peerRouting.getClosestPeers(o,i),(t=>Pc(t,(t=>(t=>r((function*(){if("FINAL_PEER"!==t.name)return[t];var r=[];n.log("putProvider %s to %p",e,t.peer.id);try{n.log("sending provider record for %s to %p",e,t.peer.id);var o,a=!1,l=!1;try{for(var u,c=s(n.network.sendMessage(t.peer.id,p,i));a=!(u=yield c.next()).done;a=!1){var d=u.value;"PEER_RESPONSE"===d.name&&(n.log("sent provider record for %s to %p",e,t.peer.id),f++),r.push(d)}}catch(e){l=!0,o=e}finally{try{a&&null!=c.return&&(yield c.return())}finally{if(l)throw o}}}catch(e){n.log.error("error sending provide record to peer %p",t.peer.id,e),r.push(nM({from:t.peer.id,error:e},i))}return r})))(t)))),(e=>xL(e,{ordered:!1,concurrency:3})),function(){var e=l((function*(e){var t,r=!1,n=!1;try{for(var i,o=s(e);r=!(i=yield u(o.next())).done;r=!1){var a=i.value;yield*c(s(a),u)}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw t}}}));return function(t){return e.apply(this,arguments)}}()))),n.log("sent provider records to %d peers",f)}()})).apply(this,arguments)}findProviders(e,r){var n=this;return l((function*(){var i=n.routingTable.kBucketSize,o=0,a=e.multihash.bytes,d=n;n.log("findProviders %c",e);var h=yield u(n.providers.getProviders(e));if(h.length>0){var v=[];for(var p of h.slice(0,i))try{var f=yield u(n.components.peerStore.get(p));v.push({id:p,multiaddrs:f.addresses.map((e=>{var{multiaddr:t}=e;return t}))})}catch(e){if("NotFoundError"!==e.name)throw e;n.log("no peer store entry for %p",p)}if(yield tM({from:n.components.peerId,messageType:ML.GET_PROVIDERS,providers:v},r),yield iM({from:n.components.peerId,providers:v},r),(o+=v.length)>=i)return}var g,y=function(){var e=l((function(e){var{peer:n,signal:i}=e;return function*(){var e={type:ML.GET_PROVIDERS,key:a};yield*c(s(d.network.sendRequest(n,e,t(t({},r),{},{signal:i}))))}()}));return function(t){return e.apply(this,arguments)}}(),m=new Hh(h),w=!1,b=!1;try{for(var S,E=s(n.queryManager.run(a,y,r));w=!(S=yield u(E.next())).done;w=!1){var k=S.value;if(yield k,"PEER_RESPONSE"===k.name){n.log("Found %d provider entries for %c and %d closer peers",k.providers.length,e,k.closer.length);var x=[];for(var A of k.providers)m.has(A.id)||(m.add(A.id),x.push(A));if(x.length>0&&(yield iM({from:k.from,providers:x},r),(o+=x.length)>=i))return}}}catch(e){b=!0,g=e}finally{try{w&&null!=E.return&&(yield u(E.return()))}finally{if(b)throw g}}}))()}}class TM{constructor(t){e(this,"movingAverage",void 0),e(this,"variance",void 0),e(this,"deviation",void 0),e(this,"forecast",void 0),e(this,"timeSpan",void 0),e(this,"previousTime",void 0),this.timeSpan=t,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){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();if(null!=this.previousTime){var r=this.alpha(t,this.previousTime),n=e-this.movingAverage,i=r*n;this.movingAverage=r*e+(1-r)*this.movingAverage,this.variance=(1-r)*(this.variance+n*i),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+r*n}else this.movingAverage=e;this.previousTime=t}}class PM{constructor(){var t,r,n,i,o,a,s,l=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e(this,"success",void 0),e(this,"failure",void 0),e(this,"next",void 0),e(this,"metric",void 0),e(this,"timeoutMultiplier",void 0),e(this,"failureMultiplier",void 0),e(this,"minTimeout",void 0),this.success=new TM(null!==(t=l.interval)&&void 0!==t?t:5e3),this.failure=new TM(null!==(r=l.interval)&&void 0!==r?r:5e3),this.next=new TM(null!==(n=l.interval)&&void 0!==n?n:5e3),this.failureMultiplier=null!==(i=l.failureMultiplier)&&void 0!==i?i:2,this.timeoutMultiplier=null!==(o=l.timeoutMultiplier)&&void 0!==o?o:1.2,this.minTimeout=null!==(a=l.minTimeout)&&void 0!==a?a:5e3,null!=l.metricName)&&(this.metric=null===(s=l.metrics)||void 0===s?void 0:s.registerMetricGroup(l.metricName))}getTimeoutSignal(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=Math.max(Math.round(this.next.movingAverage*(null!==(e=t.timeoutFactor)&&void 0!==e?e:this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(r),i=Dh([t.signal,n]);return i.start=Date.now(),i.timeout=r,i}cleanUp(e){var t,r,n=Date.now()-e.start;e.aborted?(this.failure.push(n),this.next.push(n*this.failureMultiplier),null===(t=this.metric)||void 0===t||t.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:n})):(this.success.push(n),this.next.push(n),null===(r=this.metric)||void 0===r||r.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:n}))}}class _M{constructor(){e(this,"readNext",void 0),e(this,"haveNext",void 0),e(this,"ended",void 0),e(this,"nextResult",void 0),this.ended=!1,this.readNext=_c(),this.haveNext=_c()}[Symbol.asyncIterator](){return this}next(){var e=this;return r((function*(){if(null==e.nextResult&&(yield e.haveNext.promise),null==e.nextResult)throw new Error("HaveNext promise resolved but nextResult was undefined");var t=e.nextResult;return e.nextResult=void 0,e.readNext.resolve(),e.readNext=_c(),t}))()}throw(e){var t=this;return r((function*(){return t.ended=!0,null!=e&&(t.haveNext.promise.catch((()=>{})),t.haveNext.reject(e)),{done:!0,value:void 0}}))()}return(){var e=this;return r((function*(){var t={done:!0,value:void 0};return e.ended=!0,e.nextResult=t,e.haveNext.resolve(),t}))()}push(e,t){var n=this;return r((function*(){yield n._push(e,t)}))()}end(e,t){var n=this;return r((function*(){null!=e?yield n.throw(e):yield n._push(void 0,t)}))()}_push(e,t){var n=this;return r((function*(){if(null!=e&&n.ended)throw new Error("Cannot push value onto an ended pushable");for(;null!=n.nextResult;)yield n.readNext.promise;null!=e?n.nextResult={done:!1,value:e}:(n.ended=!0,n.nextResult={done:!0,value:void 0}),n.haveNext.resolve(),n.haveNext=_c(),yield Lc(n.readNext.promise,null==t?void 0:t.signal,t)}))()}}class BM extends Error{constructor(){super(...arguments),e(this,"name","UnexpectedEOFError"),e(this,"code","ERR_UNEXPECTED_EOF")}}class NM extends Error{constructor(t,r){super(t),e(this,"code",void 0),this.code=r}}let DM=class extends NM{constructor(t){super(t,"ABORT_ERR"),e(this,"type",void 0),this.type="aborted",this.name="AbortError"}};function RM(e,t){var n=new _M;e.sink(n).catch(function(){var e=r((function*(e){yield n.end(e)}));return function(t){return e.apply(this,arguments)}}()),e.sink=function(){var e=r((function*(e){var t,r=!1,i=!1;try{for(var o,a=s(e);r=!(o=yield a.next()).done;r=!1){var l=o.value;yield n.push(l)}}catch(e){i=!0,t=e}finally{try{r&&null!=a.return&&(yield a.return())}finally{if(i)throw t}}yield n.end()}));return function(t){return e.apply(this,arguments)}}();var i=e.source;null!=e.source[Symbol.iterator]?i=e.source[Symbol.iterator]():null!=e.source[Symbol.asyncIterator]&&(i=e.source[Symbol.asyncIterator]());var o,a=new bs,u={read:function(){var e=r((function*(e,t){var r,n;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted();var o=new Promise(((e,r)=>{var i;n=()=>{r(new DM("Read aborted"))},null==t||null===(i=t.signal)||void 0===i||i.addEventListener("abort",n)}));try{if(null==e){var{done:s,value:l}=yield Promise.race([i.next(),o]);return!0===s?new bs:l}for(;a.byteLength<e;){var{value:u,done:c}=yield Promise.race([i.next(),o]);if(!0===c)throw new BM("unexpected end of input");a.append(u)}var d=a.sublist(0,e);return a.consume(e),d}finally{var h;if(null!=n)null==t||null===(h=t.signal)||void 0===h||h.removeEventListener("abort",n)}}));return function(t,r){return e.apply(this,arguments)}}(),write:(o=r((function*(e,t){var r;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),e instanceof Uint8Array?yield n.push(e,t):yield n.push(e.subarray(),t)})),function(e,t){return o.apply(this,arguments)}),unwrap:()=>{if(a.byteLength>0){var r=e.source;e.source=l((function*(){!1===(null==t?void 0:t.yieldBytes)?yield a:yield*c(s(a)),yield*c(s(r))}))()}return e}};return u}class OM extends Error{constructor(){super(...arguments),e(this,"name","InvalidMessageLengthError"),e(this,"code","ERR_INVALID_MSG_LENGTH")}}class LM extends Error{constructor(){super(...arguments),e(this,"name","InvalidDataLengthError"),e(this,"code","ERR_MSG_DATA_TOO_LONG")}}class MM extends Error{constructor(){super(...arguments),e(this,"name","InvalidDataLengthLengthError"),e(this,"code","ERR_MSG_LENGTH_TOO_LONG")}}function UM(e,t){var n,i=function(e){var t,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=RM(e,i);null!=i.maxDataLength&&null==i.maxLengthLength&&(i.maxLengthLength=Ot(i.maxDataLength));var a,s=null!==(t=null==i?void 0:i.lengthDecoder)&&void 0!==t?t:Ft,l=null!==(n=null==i?void 0:i.lengthEncoder)&&void 0!==n?n:Ut,u={read:function(){var e=r((function*(e){for(var t=-1,r=new bs;;){r.append(yield o.read(1,e));try{t=s(r)}catch(e){if(e instanceof RangeError)continue;throw e}if(t<0)throw new OM("Invalid message length");if(null!=(null==i?void 0:i.maxLengthLength)&&r.byteLength>i.maxLengthLength)throw new MM("message length length too long");if(t>-1)break}if(null!=(null==i?void 0:i.maxDataLength)&&t>i.maxDataLength)throw new LM("message length too long");return o.read(t,e)}));return function(t){return e.apply(this,arguments)}}(),write:function(){var e=r((function*(e,t){yield o.write(new bs(l(e.byteLength),e),t)}));return function(t,r){return e.apply(this,arguments)}}(),writeV:(a=r((function*(e,t){var r=new bs(...e.flatMap((e=>[l(e.byteLength),e])));yield o.write(r,t)})),function(e,t){return a.apply(this,arguments)}),unwrap:()=>o.unwrap()};return u}(e,t),o={read:function(){var e=r((function*(e,t){var r=yield i.read(t);return e.decode(r)}));return function(t,r){return e.apply(this,arguments)}}(),write:function(){var e=r((function*(e,t,r){yield i.write(t.encode(e),r)}));return function(t,r,n){return e.apply(this,arguments)}}(),writeV:(n=r((function*(e,t,r){yield i.writeV(e.map((e=>t.encode(e))),r)})),function(e,t,r){return n.apply(this,arguments)}),pb:e=>{return{read:(i=r((function*(t){return o.read(e,t)})),function(e){return i.apply(this,arguments)}),write:(n=r((function*(t,r){return o.write(t,e,r)})),function(e,t){return n.apply(this,arguments)}),writeV:(t=r((function*(t,r){return o.writeV(t,e,r)})),function(e,r){return t.apply(this,arguments)}),unwrap:()=>o};var t,n,i},unwrap:()=>i.unwrap()};return o}class FM extends us{constructor(r,n){var i,o,a,s,l,u,c;super(),e(this,"log",void 0),e(this,"protocol",void 0),e(this,"running",void 0),e(this,"components",void 0),e(this,"timeout",void 0),e(this,"metrics",void 0),this.components=r,this.log=r.logger.forComponent("".concat(n.logPrefix,":network")),this.running=!1,this.protocol=n.protocol,this.timeout=new PM(t(t({},null!==(i=n.timeout)&&void 0!==i?i:{}),{},{metrics:r.metrics,metricName:"".concat(n.metricsPrefix,"_network_message_send_times_milliseconds")})),this.metrics={operations:null===(o=r.metrics)||void 0===o?void 0:o.registerCounterGroup("".concat(n.metricsPrefix,"_outbound_rpc_requests_total")),errors:null===(a=r.metrics)||void 0===a?void 0:a.registerCounterGroup("".concat(n.metricsPrefix,"_outbound_rpc_errors_total"))},this.sendRequest=null!==(s=null===(l=r.metrics)||void 0===l?void 0:l.traceFunction("libp2p.kadDHT.sendRequest",this.sendRequest.bind(this),{optionsIndex:2,getAttributesFromArgs(e,r){var[n,i]=e;return t(t({},r),{},{to:n.toString(),"message type":"".concat(i.type)})},getAttributesFromYieldedValue:(e,t)=>("PEER_RESPONSE"===e.name&&(e.providers.length>0&&e.providers.forEach(((e,r)=>{t["providers-".concat(r)]=e.id.toString()})),e.closer.length>0&&e.closer.forEach(((e,r)=>{t["closer-".concat(r)]=e.id.toString()}))),t)}))&&void 0!==s?s:this.sendRequest,this.sendMessage=null!==(u=null===(c=r.metrics)||void 0===c?void 0:c.traceFunction("libp2p.kadDHT.sendMessage",this.sendMessage.bind(this),{optionsIndex:2,getAttributesFromArgs(e,r){var[n,i]=e;return t(t({},r),{},{to:n.toString(),"message type":"".concat(i.type)})},getAttributesFromYieldedValue:(e,t)=>("PEER_RESPONSE"===e.name&&(e.providers.length>0&&e.providers.forEach(((e,r)=>{t["providers-".concat(r)]=e.id.toString()})),e.closer.length>0&&e.closer.forEach(((e,r)=>{t["closer-".concat(r)]=e.id.toString()}))),t)}))&&void 0!==u?u:this.sendMessage}start(){var e=this;return r((function*(){e.running||(e.running=!0)}))()}stop(){var e=this;return r((function*(){e.running=!1}))()}isStarted(){return this.running}sendRequest(e,r){var n=this;return l((function(e,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){if(n.running){var o,a=r.type;if(null==a)throw new Ra("Message type was missing");n.log("sending %s to %p",r.type,e),yield aM({peer:e},i),yield eM({to:e,type:a},i);var s=n.timeout.getTimeoutSignal(i);i=t(t({},i),{},{signal:s});try{var l;null===(l=n.metrics.operations)||void 0===l||l.increment({[a]:!0});var c=yield u(n.components.connectionManager.openConnection(e,i));o=yield u(c.newStream(n.protocol,i));var d=yield u(n._writeReadMessage(o,r,i));o.close(i).catch((t=>{var r;n.log.error("error closing stream to %p",e,t),null===(r=o)||void 0===r||r.abort(t)})),yield tM({from:e,messageType:d.type,closer:d.closer.map(CM),providers:d.providers.map(CM),record:null==d.record?void 0:YL.deserialize(d.record)},i)}catch(t){var h,v,p;null===(h=n.metrics.errors)||void 0===h||h.increment({[a]:!0}),null===(v=o)||void 0===v||v.abort(t),!0!==(null===(p=i.signal)||void 0===p?void 0:p.aborted)&&n.log.error("could not send %s to %p - %e",r.type,e,t),yield nM({from:e,error:t},i)}finally{n.timeout.cleanUp(s)}}}()})).apply(this,arguments)}sendMessage(e,r){var n=this;return l((function(e,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){if(n.running){var o,a=r.type;if(null==a)throw new Ra("Message type was missing");n.log("sending %s to %p",r.type,e),yield aM({peer:e},i),yield eM({to:e,type:a},i);var s=n.timeout.getTimeoutSignal(i);i=t(t({},i),{},{signal:s});try{var l;null===(l=n.metrics.operations)||void 0===l||l.increment({[a]:!0});var c=yield u(n.components.connectionManager.openConnection(e,i));o=yield u(c.newStream(n.protocol,i)),yield u(n._writeMessage(o,r,i)),o.close(i).catch((t=>{var r;n.log.error("error closing stream to %p",e,t),null===(r=o)||void 0===r||r.abort(t)})),yield tM({from:e,messageType:a},i)}catch(t){var d,h;null===(d=n.metrics.errors)||void 0===d||d.increment({[a]:!0}),null===(h=o)||void 0===h||h.abort(t),yield nM({from:e,error:t},i)}finally{n.timeout.cleanUp(s)}}}()})).apply(this,arguments)}_writeMessage(e,t,n){return r((function*(){var r=UM(e);yield r.write(t,VL,n)}))()}_writeReadMessage(e,t,n){var i=this;return r((function*(){var r=UM(e);yield r.write(t,VL,n);var o=yield r.read(VL,n);return o.closer.forEach((e=>{i.safeDispatchEvent("peer",{detail:CM(e)})})),o.providers.forEach((e=>{i.safeDispatchEvent("peer",{detail:CM(e)})})),o}))()}}function zM(e,t){if(e.byteLength!==t.byteLength)throw new Error("Inputs should have the same length");for(var r=0;r<e.byteLength;r++)if(e[r]!==t[r])return e[r]<t[r]?-1:1;return 0}class jM{constructor(t,r){e(this,"originDhtKey",void 0),e(this,"capacity",void 0),e(this,"peerDistances",void 0),this.originDhtKey=t,this.capacity=r,this.peerDistances=[]}get length(){return this.peerDistances.length}get peers(){return this.peerDistances.map((e=>e.peer))}add(e){var t=this;return r((function*(){var r=yield gM(e.id);t.addWithKadId(e,r)}))()}addWithKadId(e,t){if(null==this.peerDistances.find((t=>t.peer.id.equals(e.id)))){for(var r={peer:e,distance:pI(this.originDhtKey,t)},n=!1,i=0;i<this.peerDistances.length;i++){var o=zM(this.peerDistances[i].distance,r.distance);if(0===o||1===o){n=!0,this.peerDistances.splice(i,0,r);break}}n||this.peerDistances.push(r),this.peerDistances=this.peerDistances.slice(0,this.capacity)}}isCloser(e){var t=this;return r((function*(){return 0===t.length||-1===zM(pI(yield gM(e),t.originDhtKey),t.peerDistances[t.peerDistances.length-1].distance)}))()}anyCloser(e){var t=this;return r((function*(){return 0!==e.length&&Promise.any(e.map(function(){var e=r((function*(e){return t.isCloser(e)}));return function(t){return e.apply(this,arguments)}}()))}))()}}class VM{constructor(t,r){var n,i,o,a;e(this,"log",void 0),e(this,"routingTable",void 0),e(this,"network",void 0),e(this,"validators",void 0),e(this,"queryManager",void 0),e(this,"peerStore",void 0),e(this,"peerId",void 0),this.routingTable=r.routingTable,this.network=r.network,this.validators=r.validators,this.queryManager=r.queryManager,this.peerStore=t.peerStore,this.peerId=t.peerId,this.log=t.logger.forComponent("".concat(r.logPrefix,":peer-routing")),this.findPeer=null!==(n=null===(i=t.metrics)||void 0===i?void 0:i.traceFunction("libp2p.kadDHT.findPeer",this.findPeer.bind(this),{optionsIndex:1}))&&void 0!==n?n:this.findPeer,this.getClosestPeers=null!==(o=null===(a=t.metrics)||void 0===a?void 0:a.traceFunction("libp2p.kadDHT.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1}))&&void 0!==o?o:this.getClosestPeers}findPeerLocal(e){var t=this;return r((function*(){var r,n=yield t.routingTable.find(e);if(null!=n){t.log("findPeerLocal found %p in routing table",e);try{r=yield t.peerStore.get(n)}catch(e){if("NotFoundError"!==e.name)throw e}}if(null==r)try{r=yield t.peerStore.get(e)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=r)return t.log("findPeerLocal found %p in peer store",e),{id:r.id,multiaddrs:r.addresses.map((e=>e.multiaddr))}}))()}_getValueSingle(e,t){var r=this;return l((function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var i={type:ML.GET_VALUE,key:t};yield*c(s(r.network.sendRequest(e,i,n)))}()})).apply(this,arguments)}getPublicKeyFromNode(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var n,i=function(e){return zt([hM,e.toMultihash().bytes])}(e),o=!1,a=!1;try{for(var l,c=s(t._getValueSingle(e,i,r));o=!(l=yield u(c.next())).done;o=!1){var d=l.value;if(yield d,"PEER_RESPONSE"===d.name&&null!=d.record){var h=Uu(Eu(d.record.value));if(!h.equals(e))throw new Oa("public key does not match id");if(null==h.publicKey)throw new Oa("public key missing");yield oM({from:e,value:d.record.value},r)}}}catch(e){a=!0,n=e}finally{try{o&&null!=c.return&&(yield u(c.return()))}finally{if(a)throw n}}throw new JL("Node not responding with its public key: ".concat(e.toString()))}()})).apply(this,arguments)}findPeer(e){var r=this;return l((function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(r.log("findPeer %p",e),!1!==n.useCache){var i=yield u(r.findPeerLocal(e));if(null!=i)return r.log("found local"),void(yield rM({from:r.peerId,peer:i},n))}var o=!1;if(!1!==n.useNetwork){var a,c=r,d=function(){var r=l((function(r){var{peer:i,signal:o}=r;return function*(){var r,a={type:ML.FIND_NODE,key:e.toMultihash().bytes},l=!1,d=!1;try{for(var h,v=s(c.network.sendRequest(i,a,t(t({},n),{},{signal:o})));l=!(h=yield u(v.next())).done;l=!1){var p=h.value;if(yield p,"PEER_RESPONSE"===p.name){var f=p.closer.find((t=>t.id.equals(e)));null!=f&&(yield rM({from:p.from,peer:f},n))}}}catch(e){d=!0,r=e}finally{try{l&&null!=v.return&&(yield u(v.return()))}finally{if(d)throw r}}}()}));return function(e){return r.apply(this,arguments)}}(),h=!1,v=!1;try{for(var p,f=s(r.queryManager.run(e.toMultihash().bytes,d,n));h=!(p=yield u(f.next())).done;h=!1){var g=p.value;"FINAL_PEER"===g.name&&(o=!0),yield g}}catch(e){v=!0,a=e}finally{try{h&&null!=f.return&&(yield u(f.return()))}finally{if(v)throw a}}}o||(yield nM({from:r.peerId,error:new Ha("Not found")},n))}()})).apply(this,arguments)}getClosestPeers(e){var n=this;return l((function(e){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){n.log("getClosestPeers to %b",e);var o=yield u(pM(e)),a=n.routingTable.closestPeers(o),d=n,h=new jM(o,n.routingTable.kBucketSize);yield u(Promise.all(a.map(function(){var e=r((function*(e){yield h.add({id:e,multiaddrs:[]})}));return function(t){return e.apply(this,arguments)}}())));var v,p=function(){var r=l((function(r){var{peer:n,signal:o}=r;return function*(){d.log("closerPeersSingle %s from %p",gt(e,"base32"),n);var r={type:ML.FIND_NODE,key:e};yield*c(s(d.network.sendRequest(n,r,t(t({},i),{},{signal:o}))))}()}));return function(e){return r.apply(this,arguments)}}(),f=!1,g=!1;try{for(var y,m=s(n.queryManager.run(e,p,i));f=!(y=yield u(m.next())).done;f=!1){var w=y.value;"PEER_RESPONSE"===w.name&&(yield u(Promise.all(w.closer.map(function(){var e=r((function*(e){yield h.add(e)}));return function(t){return e.apply(this,arguments)}}())))),yield w}}catch(e){g=!0,v=e}finally{try{f&&null!=m.return&&(yield u(m.return()))}finally{if(g)throw v}}for(var b of(n.log("found %d peers close to %b",h.length,e),h.peers))yield rM({from:n.peerId,peer:b},i)}()})).apply(this,arguments)}getValueOrPeers(e,t){var r=this;return l((function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var i,o=!1,a=!1;try{for(var l,c=s(r._getValueSingle(e,t,n));o=!(l=yield u(c.next())).done;o=!1){var d=l.value;if("PEER_RESPONSE"===d.name&&null!=d.record)try{yield u(r._verifyRecordOnline(d.record))}catch(e){var h="invalid record received, discarded";r.log(h),yield nM({from:d.from,error:new JL(h)},n);continue}yield d}}catch(e){a=!0,i=e}finally{try{o&&null!=c.return&&(yield u(c.return()))}finally{if(a)throw i}}}()})).apply(this,arguments)}_verifyRecordOnline(e){var t=this;return r((function*(){if(null==e.timeReceived)throw new $L("invalid record received");yield lM(t.validators,new YL(e.key,e.value,e.timeReceived))}))()}getCloserPeersOffline(e,t){var n=this;return r((function*(){var r=[];try{var i=zu(He(e)),o=yield n.peerStore.get(i);r.push({id:o.id,multiaddrs:o.addresses.map((e=>{var{multiaddr:t}=e;return t}))})}catch(e){}var a=yield pM(e),s=n.routingTable.closestPeers(a),l=pI(yield gM(t),a);for(var u of s){if(-1===zM(pI(yield gM(u),a),l))try{var c=yield n.peerStore.get(u);r.push({id:u,multiaddrs:c.addresses.map((e=>{var{multiaddr:t}=e;return t}))})}catch(e){if("NotFoundError"!==e.name)throw e}}return r.length>0?n.log("getCloserPeersOffline found %d peer(s) closer to %b than %p",r.length,e,t):n.log("getCloserPeersOffline could not find peer closer to %b than %p with %d peers in the routing table",e,t,n.routingTable.size),r}))()}}class qM{constructor(t,r){e(this,"log",void 0),e(this,"datastore",void 0),e(this,"datastorePrefix",void 0),e(this,"lock",void 0),this.log=t.logger.forComponent("".concat(r.logPrefix,":providers")),this.datastorePrefix="".concat(r.datastorePrefix,"/provider"),this.datastore=t.datastore,this.lock=r.lock}addProvider(e,t){var n=this;return r((function*(){var r=yield n.lock.readLock();try{n.log("%p provides %s",t,e),yield n.writeProviderEntry(e,t)}finally{r()}}))()}removeProvider(e,t){var n=this;return r((function*(){var r=yield n.lock.writeLock();try{var i=SM(n.datastorePrefix,e,t);n.log("%p no longer provides %s",t,e),yield n.datastore.delete(i)}finally{r()}}))()}getProviders(e){var t=this;return r((function*(){var r=yield t.lock.readLock();try{t.log("get providers for %c",e);var n=yield t.loadProviders(e);return t.log("got %d providers for %c",n.size,e),[...n.keys()]}finally{r()}}))()}writeProviderEntry(e,t){var n=arguments,i=this;return r((function*(){var r=n.length>2&&void 0!==n[2]?n[2]:new Date,o=SM(i.datastorePrefix,e,t),a=Ut(r.getTime());yield i.datastore.put(o,a)}))()}loadProviders(e){var t=this;return r((function*(){var r,n=new qh,i=SM(t.datastorePrefix,e),o=!1,a=!1;try{for(var l,u=s(t.datastore.query({prefix:i.toString()}));o=!(l=yield u.next()).done;o=!1){var c=l.value,{peerId:d}=bM(c.key);n.set(d,EM(c.value))}}catch(e){a=!0,r=e}finally{try{o&&null!=u.return&&(yield u.return())}finally{if(a)throw r}}return n}))()}}function HM(){return HM=l((function*(e){var{key:n,startingPeer:i,ourPeerId:o,signal:a,query:l,alpha:c,pathIndex:d,numPaths:h,queryFuncTimeout:v,log:p,peersSeen:f,connectionManager:g}=e,y=new wv({concurrency:c,sort:(e,t)=>zM(e.options.distance,t.options.distance)}),m=yield u(pM(n));!function i(u,c){if(null!=u){f.add(u);var w=pI(c,m);y.add(r((function*(){var r=[a];null!=v&&r.push(AbortSignal.timeout(v));var c=Dh(r);try{var b,S=!1,E=!1;try{for(var k,x=s(l(t(t({},e),{},{key:n,peer:u,signal:c,pathIndex:d,numPaths:h})));S=!(k=yield x.next()).done;S=!1){var A=k.value;if(c.aborted)return;if("PEER_RESPONSE"===A.name)for(var C of A.closer)if(f.has(C.id))p.trace("already seen %p in query",C.id);else if(o.equals(C.id))p("not querying ourselves");else if(yield g.isDialable(C.multiaddrs)){var I=yield gM(C.id);-1===zM(pI(I,m),w)?(p.trace("querying closer peer %p",C.id),i(C.id,I)):p.trace("skipping %p as they are not closer to %b than %p",C.id,n,u)}else p("not querying undialable peer");y.safeDispatchEvent("completed",{detail:A})}}catch(e){E=!0,b=e}finally{try{S&&null!=x.return&&(yield x.return())}finally{if(E)throw b}}}catch(t){if(!a.aborted)return nM({from:u,error:t},e)}finally{c.clear()}})),{distance:w}).catch((e=>{p.error(e)}))}}(i,yield u(gM(i)));try{var w,b=!1,S=!1;try{for(var E,k=s(y.toGenerator({signal:a}));b=!(E=yield u(k.next())).done;b=!1){var x=E.value;null!=x&&(yield x)}}catch(e){S=!0,w=e}finally{try{b&&null!=k.return&&(yield u(k.return()))}finally{if(S)throw w}}}catch(e){if(a.aborted)throw new ZL("Query aborted");throw e}})),HM.apply(this,arguments)}class KM{constructor(t,r){var n,i;e(this,"disjointPaths",void 0),e(this,"alpha",void 0),e(this,"shutDownController",void 0),e(this,"running",void 0),e(this,"logger",void 0),e(this,"peerId",void 0),e(this,"connectionManager",void 0),e(this,"routingTable",void 0),e(this,"initialQuerySelfHasRun",void 0),e(this,"logPrefix",void 0),this.logPrefix=r.logPrefix,this.disjointPaths=null!==(n=r.disjointPaths)&&void 0!==n?n:20,this.alpha=null!==(i=r.alpha)&&void 0!==i?i:3,this.initialQuerySelfHasRun=r.initialQuerySelfHasRun,this.routingTable=r.routingTable,this.logger=t.logger,this.peerId=t.peerId,this.connectionManager=t.connectionManager,this.shutDownController=new AbortController,this.shutDownController.signal,this.running=!1}isStarted(){return this.running}start(){var e=this;return r((function*(){e.running||(e.running=!0,e.shutDownController=new AbortController,e.shutDownController.signal)}))()}stop(){var e=this;return r((function*(){e.running=!1,e.shutDownController.abort()}))()}run(e,r){var n=this;return l((function(e,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){if(!n.running)throw new Error("QueryManager not started");if(null==i.signal){var o=AbortSignal.timeout(18e4);i=t(t({},i),{},{signal:o})}var a=new AbortController,l=Dh([n.shutDownController.signal,a.signal,i.signal]);a.signal;var c=n.logger.forComponent("".concat(n.logPrefix,":query:")+gt(e,"base58btc")),d=!1;try{!0!==i.isSelfQuery&&null!=n.initialQuerySelfHasRun&&(c("waiting for initial query-self query before continuing"),yield u(Lc(n.initialQuerySelfHasRun.promise,l)),n.initialQuerySelfHasRun=void 0),c("query:start");var h=yield u(pM(e)),v=n.routingTable.closestPeers(h),p=v.slice(0,Math.min(n.disjointPaths,v.length));if(0===v.length)return void c.error("Running query with no peers");var f,g=new Hh,y=p.map(((o,a)=>function(e){return HM.apply(this,arguments)}(t(t({},i),{},{key:e,startingPeer:o,ourPeerId:n.peerId,signal:l,query:r,pathIndex:a,numPaths:p.length,alpha:n.alpha,queryFuncTimeout:i.queryFuncTimeout,log:c,peersSeen:g,onProgress:i.onProgress,connectionManager:n.connectionManager})))),m=!1,w=!1;try{for(var b,S=s(Vc(...y));m=!(b=yield u(S.next())).done;m=!1){var E=b.value;if("QUERY_ERROR"===E.name&&c.error("query error",E.error),"PEER_RESPONSE"===E.name)for(var k of[...E.closer,...E.providers])(yield u(n.connectionManager.isDialable(k.multiaddrs)))&&(yield u(n.routingTable.add(k.id)));yield E}}catch(e){w=!0,f=e}finally{try{m&&null!=S.return&&(yield u(S.return()))}finally{if(w)throw f}}d=!0}catch(e){if(n.running||"QueryAbortedError"!==e.name)throw e}finally{d||(c("query exited early"),a.abort()),l.clear(),c("query:done")}}()})).apply(this,arguments)}}function WM(e){if(null!=e[Symbol.asyncIterator])return r((function*(){var t,r=0,n=!1,i=!1;try{for(var o,a=s(e);n=!(o=yield a.next()).done;n=!1){o.value;r++}}catch(e){i=!0,t=e}finally{try{n&&null!=a.return&&(yield a.return())}finally{if(i)throw t}}return r}))();var t=0;for(var n of e)t++;return t}function GM(e,r,n){var i,o=new Promise(((o,a)=>{var s;if(!((n=t({rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1},n)).count>=0)||n.count!==Number.POSITIVE_INFINITY&&!Number.isInteger(n.count))throw new TypeError("The `count` option should be at least 0 or more");null===(s=n.signal)||void 0===s||s.throwIfAborted();var l=[r].flat(),u=[],{addListener:c,removeListener:d}=(e=>{var t=e.addEventListener||e.on||e.addListener,r=e.removeEventListener||e.off||e.removeListener;if(!t||!r)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}})(e),h=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];var a=n.multiArgs?t:t[0];n.filter&&!n.filter(a)||(u.push(a),n.count===u.length&&(i(),o(u)))},v=e=>{i(),a(e)};for(var p of(i=()=>{for(var e of l)d(e,h);for(var t of n.rejectionEvents)d(t,v)},l))c(p,h);for(var f of n.rejectionEvents)c(f,v);n.signal&&n.signal.addEventListener("abort",(()=>{v(n.signal.reason)}),{once:!0}),n.resolveImmediately&&o(u)}));if(o.cancel=i,"number"==typeof n.timeout){var a=np(o,{milliseconds:n.timeout});return a.cancel=i,a}return o}class QM{constructor(t,r){var n,i,o,a;e(this,"log",void 0),e(this,"peerId",void 0),e(this,"peerRouting",void 0),e(this,"routingTable",void 0),e(this,"count",void 0),e(this,"interval",void 0),e(this,"initialInterval",void 0),e(this,"queryTimeout",void 0),e(this,"running",void 0),e(this,"timeoutId",void 0),e(this,"controller",void 0),e(this,"initialQuerySelfHasRun",void 0),e(this,"querySelfPromise",void 0),this.peerId=t.peerId,this.log=t.logger.forComponent("".concat(r.logPrefix,":query-self")),this.running=!1,this.peerRouting=r.peerRouting,this.routingTable=r.routingTable,this.count=null!==(n=r.count)&&void 0!==n?n:20,this.interval=null!==(i=r.interval)&&void 0!==i?i:3e5,this.initialInterval=null!==(o=r.initialInterval)&&void 0!==o?o:1e3,this.queryTimeout=null!==(a=r.queryTimeout)&&void 0!==a?a:5e3,this.initialQuerySelfHasRun=r.initialQuerySelfHasRun,this.querySelf=xM(this.querySelf.bind(this),r.operationMetrics,"SELF_QUERY")}isStarted(){return this.running}start(){this.running||(this.running=!0,clearTimeout(this.timeoutId),this.timeoutId=setTimeout((()=>{this.querySelf().catch((e=>{this.log.error("error running self-query",e)}))}),this.initialInterval))}stop(){this.running=!1,null!=this.timeoutId&&clearTimeout(this.timeoutId),null!=this.controller&&this.controller.abort()}querySelf(){var e=this;return r((function*(){if(e.running){if(null!=e.querySelfPromise)return e.log("joining existing self query"),e.querySelfPromise.promise;if(e.querySelfPromise=_c(),e.running){e.controller=new AbortController;var n=[e.controller.signal];if(null==e.initialQuerySelfHasRun){var i=AbortSignal.timeout(e.queryTimeout);n.push(i)}var o=Dh(n);e.controller.signal;try{0===e.routingTable.size&&(e.log("routing table was empty, waiting for some peers before running query"),yield function(e,r,n){"function"==typeof n&&(n={filter:n});var i=GM(e,r,n=t(t({},n),{},{count:1,resolveImmediately:!1})),o=i.then((e=>e[0]));return o.cancel=i.cancel,o}(e.routingTable,"peer:add",{signal:o,filter:t=>!e.peerId.equals(t.detail)}),e.log("routing table has peers, continuing with query")),e.log("run self-query, look for %d peers timing out after %dms",e.count,e.queryTimeout);var a=Date.now(),s=yield qc(e.peerRouting.getClosestPeers(e.peerId.toMultihash().bytes,{signal:o,isSelfQuery:!0}),(t=>mc(t,e.count)),function(){var e=r((function*(e){return WM(e)}));return function(t){return e.apply(this,arguments)}}());e.log("self-query found %d peers in %dms",s,Date.now()-a)}catch(t){e.log.error("self-query error",t)}finally{o.clear(),null!=e.initialQuerySelfHasRun&&(e.initialQuerySelfHasRun.resolve(),e.initialQuerySelfHasRun=void 0)}}e.querySelfPromise.resolve(),e.querySelfPromise=void 0,e.running&&(e.timeoutId=setTimeout((()=>{e.querySelf().catch((t=>{e.log.error("error running self-query",t)}))}),e.interval))}else e.log("skip self-query because we are not started")}))()}}class YM extends us{constructor(r,n){var i,o,a,s,l,u;super(),e(this,"log",void 0),e(this,"reprovideQueue",void 0),e(this,"maxQueueSize",void 0),e(this,"datastore",void 0),e(this,"timeout",void 0),e(this,"reprovideTimeout",void 0),e(this,"running",void 0),e(this,"shutdownController",void 0),e(this,"reprovideThreshold",void 0),e(this,"contentRouting",void 0),e(this,"datastorePrefix",void 0),e(this,"addressManager",void 0),e(this,"validity",void 0),e(this,"interval",void 0),e(this,"lock",void 0),e(this,"peerId",void 0),this.log=r.logger.forComponent("".concat(n.logPrefix,":reprovider")),this.peerId=r.peerId,this.reprovideQueue=new wv({concurrency:null!==(i=n.concurrency)&&void 0!==i?i:10,metrics:r.metrics,metricName:"".concat(n.metricsPrefix,"_reprovide_queue")}),this.reprovideTimeout=new PM(t(t({},null!==(o=n.timeout)&&void 0!==o?o:{}),{},{metrics:r.metrics,metricName:"".concat(n.metricsPrefix,"_reprovide_timeout_milliseconds")})),this.datastore=r.datastore,this.addressManager=r.addressManager,this.datastorePrefix="".concat(n.datastorePrefix,"/provider"),this.reprovideThreshold=null!==(a=n.threshold)&&void 0!==a?a:864e5,this.maxQueueSize=null!==(s=n.maxQueueSize)&&void 0!==s?s:16384,this.validity=null!==(l=n.validity)&&void 0!==l?l:KL,this.interval=null!==(u=n.interval)&&void 0!==u?u:WL,this.contentRouting=n.contentRouting,this.lock=n.lock,this.running=!1,this.reprovide=xM(this.reprovide.bind(this),n.operationMetrics,"PROVIDE")}start(){this.running||(this.running=!0,this.shutdownController=new AbortController,this.shutdownController.signal,this.timeout=setTimeout((()=>{this.cleanUp().catch((e=>{this.log.error("error running reprovide/cleanup - %e",e)}))}),this.interval))}stop(){var e;this.running=!1,this.reprovideQueue.clear(),clearTimeout(this.timeout),null===(e=this.shutdownController)||void 0===e||e.abort()}cleanUp(){var e=this;return r((function*(){var t=yield e.lock.writeLock();try{e.safeDispatchEvent("reprovide:start");var r,n=!1,i=!1;try{for(var o,a=function*(){var t=o.value;try{var{cid:r,peerId:n}=bM(t.key),i=EM(t.value).getTime(),a=i+e.validity,s=Date.now(),l=s>a;e.log.trace("comparing: %d < %d = %s %s",i,s-e.validity,l,l?"(expired)":""),l&&(yield e.datastore.delete(t.key)),e.peerId.equals(n)&&s-a<e.reprovideThreshold&&e.queueReprovide(r).catch((t=>{e.log.error("could not reprovide %c - %e",r,t)}))}catch(r){e.log.error("error processing datastore key %s - %e",t.key,r.message)}},l=s(e.datastore.query({prefix:e.datastorePrefix}));n=!(o=yield l.next()).done;n=!1)yield*a()}catch(e){i=!0,r=e}finally{try{n&&null!=l.return&&(yield l.return())}finally{if(i)throw r}}e.log("reprovide/cleanup successful")}finally{t(),e.safeDispatchEvent("reprovide:end"),e.running&&(e.timeout=setTimeout((()=>{e.cleanUp().catch((t=>{e.log.error("error running re-provide - %e",t)}))}),e.interval))}}))()}queueReprovide(e){var t=this;return r((function*(){var n;if(t.running){t.log.trace("waiting for queue capacity before adding %c to re-provide queue",e),yield t.reprovideQueue.onSizeLessThan(t.maxQueueSize);var i=t.reprovideQueue.queue.find((t=>t.options.cid.equals(e)));if(null!=i)return t.log.trace("not adding %c to re-provide queue - already in queue",e),i.join();t.log.trace("adding %c to re-provide queue",e),t.reprovideQueue.add(function(){var n=r((function*(r){var n;if(null===(n=r.signal)||void 0===n||n.throwIfAborted(),t.running){t.log.trace("re-providing %c",e);var i=t.reprovideTimeout.getTimeoutSignal(r);try{yield t.reprovide(r.cid,r)}finally{t.reprovideTimeout.cleanUp(i)}t.log.trace("re-provided %c",e)}}));return function(e){return n.apply(this,arguments)}}(),{signal:null===(n=t.shutdownController)||void 0===n?void 0:n.signal,cid:e}).catch((r=>{t.log.error("could not re-provide key %c - %e",e,r)}))}}))()}reprovide(e,t){var n=this;return r((function*(){yield vc(n.contentRouting.provide(e,n.addressManager.getAddresses(),t))}))()}}class JM{constructor(t,r){var n,i,o,a;e(this,"routingTable",void 0),e(this,"components",void 0),e(this,"closestPeers",void 0),e(this,"newPeers",void 0),e(this,"refreshInterval",void 0),e(this,"peerSetSize",void 0),e(this,"timeout",void 0),e(this,"closeTagName",void 0),e(this,"closeTagValue",void 0),e(this,"log",void 0),e(this,"running",void 0),this.components=t,this.log=t.logger.forComponent("".concat(r.logPrefix,":routing-table")),this.routingTable=r.routingTable,this.refreshInterval=null!==(n=r.refreshInterval)&&void 0!==n?n:5e3,this.peerSetSize=null!==(i=r.peerSetSize)&&void 0!==i?i:20,this.closeTagName=null!==(o=r.closeTagName)&&void 0!==o?o:"kad-close",this.closeTagValue=null!==(a=r.closeTagValue)&&void 0!==a?a:50,this.closestPeers=new Hh,this.onPeerPing=this.onPeerPing.bind(this),this.running=!1}start(){var e=this;return r((function*(){if(!e.running){e.running=!0;var t=yield gM(e.components.peerId);e.newPeers=new jM(t,e.peerSetSize),e.routingTable.addEventListener("peer:ping",e.onPeerPing),e.timeout=setInterval((()=>{e.updatePeerTags().catch((t=>{e.log.error("error updating peer tags - %e",t)}))}),e.refreshInterval)}}))()}stop(){this.running=!1,this.routingTable.removeEventListener("peer:ping",this.onPeerPing),clearTimeout(this.timeout)}onPeerPing(e){var t;null===(t=this.newPeers)||void 0===t||t.add({id:e.detail,multiaddrs:[]}).catch((e=>{this.log.error("error adding peer to distance list - %e",e)}))}updatePeerTags(){var e=this;return r((function*(){var t,n=new Hh(null===(t=e.newPeers)||void 0===t?void 0:t.peers.map((e=>e.id))),i=n.difference(e.closestPeers),o=e.closestPeers.difference(n);e.closestPeers=n,yield Promise.all([...[...i].map(function(){var t=r((function*(t){yield e.components.peerStore.merge(t,{tags:{[e.closeTagName]:{value:e.closeTagValue},[GL]:{value:1}}})}));return function(e){return t.apply(this,arguments)}}()),...[...o].map(function(){var t=r((function*(t){yield e.components.peerStore.merge(t,{tags:{[e.closeTagName]:void 0,[GL]:void 0}})}));return function(e){return t.apply(this,arguments)}}())])}))()}}function ZM(e){return Array.isArray(null==e?void 0:e.peers)}class $M{constructor(t){var r,n,i,o,a;e(this,"root",void 0),e(this,"localPeer",void 0),e(this,"prefixLength",void 0),e(this,"splitThreshold",void 0),e(this,"kBucketSize",void 0),e(this,"numberOfNodesToPing",void 0),e(this,"lastPingThreshold",void 0),e(this,"ping",void 0),e(this,"verify",void 0),e(this,"onAdd",void 0),e(this,"onRemove",void 0),e(this,"onMove",void 0),e(this,"addingPeerMap",void 0),this.prefixLength=null!==(r=t.prefixLength)&&void 0!==r?r:eU,this.kBucketSize=null!==(n=t.kBucketSize)&&void 0!==n?n:XM,this.splitThreshold=null!==(i=t.splitThreshold)&&void 0!==i?i:this.kBucketSize,this.numberOfNodesToPing=null!==(o=t.numberOfOldContactsToPing)&&void 0!==o?o:tU,this.lastPingThreshold=null!==(a=t.lastPingThreshold)&&void 0!==a?a:nU,this.ping=t.ping,this.verify=t.verify,this.onAdd=t.onAdd,this.onRemove=t.onRemove,this.addingPeerMap=new qh,this.root={prefix:"",depth:0,peers:[]}}addSelfPeer(e){var t=this;return r((function*(){t.localPeer={peerId:e,kadId:yield gM(e),lastPing:Date.now()}}))()}add(e,t){var n=this;return r((function*(){var r={peerId:e,kadId:yield gM(e),lastPing:0},i=n.addingPeerMap.get(e);if(null!=i)return i;try{var o=n._add(r,t);n.addingPeerMap.set(e,o),yield o}finally{n.addingPeerMap.delete(e)}}))()}_add(e,t){var n=this;return r((function*(){var r=n._determineBucket(e.kadId);if(!(n._indexOf(r,e.kadId)>-1)){if(r.peers.length===n.splitThreshold&&r.depth<n.prefixLength)return yield n._split(r),void(yield n._add(e,t));var i;if(r.peers.length<n.kBucketSize)return function(e,t){return e.lastPing<Date.now()-t}(e,n.lastPingThreshold)?void((yield n.verify(e,t))&&(e.lastPing=Date.now(),yield n._add(e,t))):(r.peers.push(e),void(yield null===(i=n.onAdd)||void 0===i?void 0:i.call(n,e,r)));var o,a=r.peers.filter((e=>{var t;return!e.peerId.equals(null===(t=n.localPeer)||void 0===t?void 0:t.peerId)&&!(e.lastPing>Date.now()-n.lastPingThreshold)})).sort(((e,t)=>e.lastPing<t.lastPing?-1:e.lastPing>t.lastPing?1:0)).slice(0,n.numberOfNodesToPing),l=!1,u=!1,c=!1;try{for(var d,h=s(n.ping(a,t));u=!(d=yield h.next()).done;u=!1){var v=d.value;l=!0,yield n.remove(v.kadId)}}catch(e){c=!0,o=e}finally{try{u&&null!=h.return&&(yield h.return())}finally{if(c)throw o}}l&&(yield n._add(e,t))}}))()}closest(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.kBucketSize;return function*(){var n=new jM(e,r);for(var i of t.toIterable())n.addWithKadId({id:i.peerId,multiaddrs:[]},i.kadId);yield*Pc(n.peers,(e=>e.id))}()}count(){return function e(t){if(ZM(t))return t.peers.length;var r=0;return null!=t.left&&(r+=e(t.left)),null!=t.right&&(r+=e(t.right)),r}(this.root)}get(e){var t=this._determineBucket(e),r=this._indexOf(t,e);return t.peers[r]}remove(e){var t=this;return r((function*(){var r=t._determineBucket(e),n=t._indexOf(r,e);if(n>-1){var i,o=r.peers.splice(n,1)[0];yield null===(i=t.onRemove)||void 0===i?void 0:i.call(t,o,r)}}))()}*toIterable(){yield*function*e(t){ZM(t)?yield*t.peers:(yield*e(t.left),yield*e(t.right))}(this.root)}distance(e,t){return BigInt("0x"+gt(pI(e,t),"base16"))}_determineBucket(e){var t=gt(e,"base2");return function e(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return ZM(r)?r:e("0"===t[n]?r.left:r.right,n+1)}(this.root)}_indexOf(e,t){return e.peers.findIndex((e=>Et(e.kadId,t)))}_split(e){var t=this;return r((function*(){var r={prefix:"0",depth:e.depth+1,peers:[]},n={prefix:"1",depth:e.depth+1,peers:[]};for(var i of e.peers){var o,a;if("0"===gt(i.kadId,"base2")[e.depth])r.peers.push(i),yield null===(o=t.onMove)||void 0===o?void 0:o.call(t,i,e,r);else n.peers.push(i),yield null===(a=t.onMove)||void 0===a?void 0:a.call(t,i,e,n)}!function(e,t,r){delete e.peers,e.left=t,e.right=r,""===e.prefix&&(delete e.depth,delete e.prefix)}(e,r,n)}))()}}var XM=20,eU=6,tU=3,rU="kad-peer",nU=6e5;class iU extends us{constructor(r,n){var i,o,a,s,l,u,c,d,h,v,p;super(),e(this,"kBucketSize",void 0),e(this,"kb",void 0),e(this,"network",void 0),e(this,"closestPeerTagger",void 0),e(this,"log",void 0),e(this,"components",void 0),e(this,"running",void 0),e(this,"pingNewContactTimeout",void 0),e(this,"pingNewContactQueue",void 0),e(this,"pingOldContactTimeout",void 0),e(this,"pingOldContactQueue",void 0),e(this,"populateFromDatastoreOnStart",void 0),e(this,"populateFromDatastoreLimit",void 0),e(this,"protocol",void 0),e(this,"peerTagName",void 0),e(this,"peerTagValue",void 0),e(this,"metrics",void 0),this.components=r,this.log=r.logger.forComponent("".concat(n.logPrefix,":routing-table")),this.kBucketSize=null!==(i=n.kBucketSize)&&void 0!==i?i:XM,this.running=!1,this.protocol=n.protocol,this.network=n.network,this.peerTagName=null!==(o=n.peerTagName)&&void 0!==o?o:rU,this.peerTagValue=null!==(a=n.peerTagValue)&&void 0!==a?a:1,this.pingOldContacts=this.pingOldContacts.bind(this),this.verifyNewContact=this.verifyNewContact.bind(this),this.peerAdded=this.peerAdded.bind(this),this.peerRemoved=this.peerRemoved.bind(this),this.populateFromDatastoreOnStart=null===(s=n.populateFromDatastoreOnStart)||void 0===s||s,this.populateFromDatastoreLimit=null!==(l=n.populateFromDatastoreLimit)&&void 0!==l?l:1e3,this.pingOldContactQueue=new bv({concurrency:null!==(u=n.pingOldContactConcurrency)&&void 0!==u?u:20,metricName:"".concat(n.metricsPrefix,"_ping_old_contact_queue"),metrics:this.components.metrics,maxSize:null!==(c=n.pingOldContactMaxQueueSize)&&void 0!==c?c:100}),this.pingOldContactTimeout=new PM(t(t({},null!==(d=n.pingOldContactTimeout)&&void 0!==d?d:{}),{},{metrics:this.components.metrics,metricName:"".concat(n.metricsPrefix,"_routing_table_ping_old_contact_time_milliseconds")})),this.pingNewContactQueue=new bv({concurrency:null!==(h=n.pingNewContactConcurrency)&&void 0!==h?h:20,metricName:"".concat(n.metricsPrefix,"_ping_new_contact_queue"),metrics:this.components.metrics,maxSize:null!==(v=n.pingNewContactMaxQueueSize)&&void 0!==v?v:100}),this.pingNewContactTimeout=new PM(t(t({},null!==(p=n.pingNewContactTimeout)&&void 0!==p?p:{}),{},{metrics:this.components.metrics,metricName:"".concat(n.metricsPrefix,"_routing_table_ping_new_contact_time_milliseconds")})),this.kb=new $M({kBucketSize:n.kBucketSize,prefixLength:n.prefixLength,splitThreshold:n.splitThreshold,numberOfOldContactsToPing:n.numberOfOldContactsToPing,lastPingThreshold:n.lastPingThreshold,ping:this.pingOldContacts,verify:this.verifyNewContact,onAdd:this.peerAdded,onRemove:this.peerRemoved}),this.closestPeerTagger=new JM(this.components,{logPrefix:n.logPrefix,routingTable:this,peerSetSize:n.closestPeerSetSize,refreshInterval:n.closestPeerSetRefreshInterval,closeTagName:n.closeTagName,closeTagValue:n.closeTagValue}),null!=this.components.metrics&&(this.metrics={routingTableSize:this.components.metrics.registerMetric("".concat(n.metricsPrefix,"_routing_table_size")),routingTableKadBucketTotal:this.components.metrics.registerMetric("".concat(n.metricsPrefix,"_routing_table_kad_bucket_total")),routingTableKadBucketAverageOccupancy:this.components.metrics.registerMetric("".concat(n.metricsPrefix,"_routing_table_kad_bucket_average_occupancy")),routingTableKadBucketMinOccupancy:this.components.metrics.registerMetric("".concat(n.metricsPrefix,"_routing_table_kad_bucket_min_occupancy")),routingTableKadBucketMaxOccupancy:this.components.metrics.registerMetric("".concat(n.metricsPrefix,"_routing_table_kad_bucket_max_occupancy")),routingTableKadBucketMaxDepth:this.components.metrics.registerMetric("".concat(n.metricsPrefix,"_routing_table_kad_bucket_max_depth")),kadBucketEvents:this.components.metrics.registerCounterGroup("".concat(n.metricsPrefix,"_kad_bucket_events_total"))})}isStarted(){return this.running}start(){var e=this;return r((function*(){e.running||(e.running=!0,yield ds(e.closestPeerTagger),yield e.kb.addSelfPeer(e.components.peerId))}))()}afterStart(){var e=this;return r((function*(){Promise.resolve().then(r((function*(){if(e.populateFromDatastoreOnStart){var t=0;for(var r of yield e.components.peerStore.all({filters:[t=>t.protocols.includes(e.protocol)&&t.tags.has(rU)],limit:e.populateFromDatastoreLimit})){if(!e.running)return;try{yield e.add(r.id),t++}catch(t){e.log("failed to add peer %p to routing table, removing kad-dht peer tags - %e"),yield e.components.peerStore.merge(r.id,{tags:{[e.peerTagName]:void 0}})}}e.log("added %d peer store peers to the routing table",t)}}))).catch((t=>{e.log.error("error adding peer store peers to the routing table %e",t)}))}))()}stop(){var e=this;return r((function*(){e.running=!1,yield vs(e.closestPeerTagger),e.pingOldContactQueue.abort(),e.pingNewContactQueue.abort()}))()}peerAdded(e,t){var n=this;return r((function*(){var t;n.components.peerId.equals(e.peerId)||(yield n.components.peerStore.merge(e.peerId,{tags:{[n.peerTagName]:{value:n.peerTagValue}}})),n.updateMetrics(),null===(t=n.metrics)||void 0===t||t.kadBucketEvents.increment({peer_added:!0}),n.safeDispatchEvent("peer:add",{detail:e.peerId})}))()}peerRemoved(e,t){var n=this;return r((function*(){var t;n.components.peerId.equals(e.peerId)||(yield n.components.peerStore.merge(e.peerId,{tags:{[n.peerTagName]:void 0}})),n.updateMetrics(),null===(t=n.metrics)||void 0===t||t.kadBucketEvents.increment({peer_removed:!0}),n.safeDispatchEvent("peer:remove",{detail:e.peerId})}))()}pingOldContacts(e,t){var n=this;return l((function*(){if(n.running){var i=[],o=function*(e){var o;if(null==n.kb.get(e.kadId))return n.log("asked to ping contact %p that was not in routing table",e.peerId),1;null===(o=n.metrics)||void 0===o||o.kadBucketEvents.increment({ping_old_contact:!0}),i.push(r((function*(){var i=n.pingOldContactQueue.find(e.peerId);if(null!=i)return n.log("asked to ping contact %p was already being pinged",e.peerId),(yield i.join(t))?void 0:e;var o=yield n.pingOldContactQueue.add(function(){var t=r((function*(t){var r=n.pingOldContactTimeout.getTimeoutSignal(),i=Dh([r,null==t?void 0:t.signal]);try{return yield n.pingContact(e,t)}catch(e){var o;return null===(o=n.metrics)||void 0===o||o.kadBucketEvents.increment({ping_old_contact_error:!0}),!0}finally{n.pingOldContactTimeout.cleanUp(r),i.clear()}}));return function(e){return t.apply(this,arguments)}}(),{peerId:e.peerId,signal:null==t?void 0:t.signal});return o?void 0:e})))};for(var a of e)yield*o(a);var l,c=!1,d=!1;try{for(var h,v=s(xL(i));c=!(h=yield u(v.next())).done;c=!1){var p=h.value;null!=p&&(yield p)}}catch(e){d=!0,l=e}finally{try{c&&null!=v.return&&(yield u(v.return()))}finally{if(d)throw l}}}}))()}verifyNewContact(e,t){var n=this;return r((function*(){var i=n.pingNewContactTimeout.getTimeoutSignal(),o=Dh([i,null==t?void 0:t.signal]);try{var a=n.pingNewContactQueue.find(e.peerId);return null!=a?(n.log("joining existing ping to add new peer %p to routing table",e.peerId),yield a.join({signal:o})):yield n.pingNewContactQueue.add(function(){var t=r((function*(t){var r;return null===(r=n.metrics)||void 0===r||r.kadBucketEvents.increment({ping_new_contact:!0}),n.log("pinging new peer %p before adding to routing table",e.peerId),n.pingContact(e,t)}));return function(e){return t.apply(this,arguments)}}(),{peerId:e.peerId,signal:o})}catch(t){var s;return n.log.trace("tried to add peer %p but they were not online",e.peerId),null===(s=n.metrics)||void 0===s||s.kadBucketEvents.increment({ping_new_contact_error:!0}),!1}finally{n.pingNewContactTimeout.cleanUp(i),o.clear()}}))()}pingContact(e,t){var n=this;return r((function*(){try{n.log("pinging contact %p",e.peerId);var r,i=!1,o=!1;try{for(var a,l=s(n.network.sendRequest(e.peerId,{type:ML.PING},t));i=!(a=yield l.next()).done;i=!1){var u=a.value;if(u.type===yU.PEER_RESPONSE)return u.messageType===ML.PING&&(n.log("contact %p ping ok",e.peerId),n.safeDispatchEvent("peer:ping",{detail:e.peerId}),!0)}}catch(e){o=!0,r=e}finally{try{i&&null!=l.return&&(yield l.return())}finally{if(o)throw r}}return!1}catch(t){return n.log("error pinging old contact %p - %e",e.peerId,t),!1}}))()}get size(){return null==this.kb?0:this.kb.count()}find(e){var t=this;return r((function*(){var r,n=yield gM(e);return null===(r=t.kb.get(n))||void 0===r?void 0:r.peerId}))()}closestPeer(e){var t=this.closestPeers(e,1);if(t.length>0)return t[0]}closestPeers(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.kBucketSize;return null==this.kb?[]:[...this.kb.closest(e,t)]}add(e,t){var n=this;return r((function*(){if(null==n.kb)throw new Error("RoutingTable is not started");yield n.kb.add(e,t)}))()}remove(e){var t=this;return r((function*(){if(null==t.kb)throw new Error("RoutingTable is not started");var r=yield gM(e);yield t.kb.remove(r)}))()}updateMetrics(){if(null!=this.metrics&&null!=this.kb){var e=0,t=0,r=0,n=20,i=0;!function o(a){if(ZM(a))return a.depth>r&&(r=a.depth),t++,e+=a.peers.length,a.peers.length<n&&(n=a.peers.length),void(a.peers.length>i&&(i=a.peers.length));o(a.left),o(a.right)}(this.kb.root),this.metrics.routingTableSize.update(e),this.metrics.routingTableKadBucketTotal.update(t),this.metrics.routingTableKadBucketAverageOccupancy.update(Math.round(e/t)),this.metrics.routingTableKadBucketMinOccupancy.update(n),this.metrics.routingTableKadBucketMaxOccupancy.update(i),this.metrics.routingTableKadBucketMaxDepth.update(r)}}}var oU=[77591,22417,43971,28421,740,29829,71467,228973,196661,78537,27689,36431,44415,14362,19456,106025,96308,2882,49509,21149,87173,131409,75844,23676,121838,30291,17492,2953,7564,110620,129477,127283,53113,72417,165166,109690,21200,102125,24049,71504,90342,25307,72039,26812,26715,32264,133800,71161,88956,171987,51779,24425,16671,30251,186294,247761,14202,2121,8465,35024,4876,85917,169730,3638,256836,96184,943,18678,6583,52907,35807,112254,214097,18796,11595,9243,23554,887,268203,382004,24590,111335,11625,16619,29039,102425,69006,97976,92362,32552,63717,41433,128974,137630,59943,10019,13986,35430,33665,108037,43799,43280,38195,29078,58629,18265,14425,46832,235538,40830,77881,110717,58937,3463,325358,51300,47623,117252,19007,10170,20540,91237,294813,4951,79841,56232,36270,128547,69209,66275,100156,32063,73531,34439,80937,28892,44466,88595,216307,32583,49620,16605,82127,45807,21630,78726,20235,40163,111007,96926,5567,72083,21665,58844,39419,179767,48328,42662,51550,5251,37811,49608,81056,50854,55513,20922,18891,197409,164656,32593,71449,220474,58919,85682,67854,13758,35066,3565,61905,214793,119572,141419,21504,10302,27354,67003,46131,32668,15165,64871,34450,17821,2757,11452,34189,5160,12257,85523,560,53385,65887,119549,135620,312353,115979,122356,10867,193231,124537,54783,90675,120791,4715,142253,50943,17271,43358,25331,4917,120566,34580,12878,33786,160528,32523,4869,301307,104817,81491,23276,8832,97911,31265,52065,7998,49622,9715,43998,34091,84587,20664,69041,29419,53205,10838,58288,116145,6185,5154,141795,35924,21307,144738,43730,12085,8279,10002,119,133779,199668,72938,31768,39176,67875,38453,9700,44144,4121,116048,41733,12868,82669,92308,128,34262,11332,7712,90764,36141,13553,71312,77470,117314,96549,49135,23602,54468,28605,6327,62308,17171,67531,21319,14105,894,107722,46157,8503,51069,100472,45138,15246,14577,35609,191464,1757,13364,161349,32067,91705,81144,52339,5408,91066,21983,14157,100545,4372,26630,129112,1423,29676,213626,4397,88436,99190,6877,49958,26122,114348,60661,29818,293118,50042,179738,16400,163423,89627,31040,43973,36638,45952,5153,1894,109322,1898,134021,12402,112077,68309,190269,69866,31938,107383,11522,105232,11248,14868,39852,71707,186525,16530,38162,106212,11700,5130,16608,26998,59586,108399,230033,43683,48135,82179,2073,5015,196684,189293,16378,23452,8301,35640,11632,214551,29240,57644,33137,91949,55157,52384,117313,5090,17717,89668,49363,82238,241035,66216,29066,184088,97206,62820,26595,4241,135635,173672,8202,459,71355,146294,29587,3008,135385,141203,14803,6634,45094,69362,50925,546,51884,62011,83296,234584,44515,56050,89476,87751,19373,12691,149923,19794,13833,35846,87557,58339,2884,19145,25647,12224,11024,77338,64608,122297,53025,7205,36189,36294,170779,21750,7739,173883,75192,35664,224240,113121,30181,26267,27036,117827,92015,106516,55628,203549,67949,60462,60844,35911,20457,1820,920,19773,8738,73173,181993,38521,98254,76257,46008,92796,5384,26868,151566,22124,2411,15919,186872,180021,28099,152961,78811,80237,62352,102653,74259,184890,16792,123702,224945,29940,19512,75283,14059,112691,92811,233329,20411,138569,53341,109802,50600,134528,66747,5529,166531,31578,64732,67189,1596,126357,967,167999,206598,109752,119431,207825,78791,91938,10301,27311,24233,252343,28831,32812,66002,112267,90895,8786,8095,16824,22866,21813,60507,174833,19549,130985,117051,52110,6938,81923,123864,38061,919,18680,53534,46739,112893,161529,85429,26761,11900,81121,91968,15390,217947,56524,1713,6654,37089,85630,138866,61850,16491,75577,16884,98296,73523,6140,44645,6062,36366,29844,57946,37932,42472,5266,20834,19309,33753,127182,134259,35810,41805,45878,312001,14881,47757,49251,120050,44252,3708,25856,107864,120347,1228,36550,41682,34496,47025,8393,173365,246526,12894,161607,35670,90785,126572,2095,124731,157033,58694,554,12786,9642,4817,16136,47864,174698,66992,4639,69284,10625,40710,27763,51738,30404,264105,137904,109882,52487,42824,57514,2740,10479,146799,107390,16586,88038,174951,9410,16185,44158,5568,40658,46108,12763,97385,26175,108859,664,230732,67470,46663,14395,50750,141320,93140,15361,47997,55784,6791,307840,118569,107326,18056,58281,260415,54691,8790,73332,45633,7511,45674,143373,14031,11799,94491,35646,96544,14560,26049,32983,25791,83814,42094,231370,63955,139212,2359,169908,3108,183486,105867,28197,32941,124968,26402,88267,149768,23053,3078,19091,52924,25383,19209,111548,97361,3959,24880,235061,9099,24921,161254,151405,20508,7159,34381,20133,11434,74036,19974,34769,36585,1076,22454,17354,38727,235160,111547,96454,117448,156940,91330,37299,7310,26915,117060,51369,22620,61861,322264,106850,111694,15091,2624,40345,300446,177064,1707,27389,54792,327783,132669,183543,59003,17744,20603,151134,106923,53084,71803,279424,319816,11579,21946,16728,38274,72711,5085,83391,88646,40159,25027,34680,10752,12988,54126,30365,18338,100445,230674,44874,84974,143877,123253,139372,28082,91477,144002,13096,219729,46016,50029,42377,14601,6660,58244,58978,23918,88206,113611,64452,17541,41032,10942,12021,49189,10978,40175,37156,10947,71709,106894,112538,57007,137486,150608,152719,40615,7746,279716,13101,19524,28708,40578,72320,1096,182051,94527,51275,22833,45164,81917,77519,48508,5421,140302,37845,149830,5587,27579,5357,428725,248187,6326,206760,39814,32585,89923,44341,288753,284443,96368,31201,94189,119504,20359,52073,103216,179,27934,32801,96035,34111,34309,101326,18198,20704,210266,37643,27880,141873,106e3,19414,56614,167714,66483,107885,86602,4379,20796,75467,4987,5017,118857,26003,34308,114428,29198,6686,29697,73632,3739,69795,16798,41504,7207,30722,21436,36735,28067,28545,3239,11221,36031,41889,100010,19247,317673,29495,174554,6424,129725,53845,94986,7955,59676,2604,191497,19735,102214,62954,23844,11872,179525,261436,34492,428,78404,142035,16747,17246,27578,37021,33672,57944,26056,135760,2369,61674,122066,31327,19374,157065,40553,130982,69619,71290,38855,72100,92903,95940,51422,165999,65713,57873,50726,7288,20272,2081,42326,22624,81120,57914,79352,19447,1684,72302,11774,302559,161481,96396,13692,414988,3721,79066,56627,46883,21150,11747,12184,5856,113458,176117,84416,52079,27933,3354,59765,141359,2212,216309,2555,23458,196722,142463,45701,44548,28798,19418,215,29916,9396,10574,114226,84475,13520,18694,34056,4524,90302,62930,13539,19407,77209,7728,38088,9535,2263,23875,183945,17750,26274,67172,10585,28042,22199,7478,51331,66030,26774,192929,31434,25850,50197,52926,178158,4679,181256,70184,229600,9959,105594,72158,73974,2726,35085,78087,23284,35568,51713,155676,5401,27254,11966,17569,223253,71993,103357,111477,55722,30504,26034,46774,35392,36285,214814,41143,163465,1051,16094,81044,6636,76489,179102,20712,39178,35683,125177,54219,30617,52994,25324,50123,2543,87529,58995,10688,125199,12388,60158,125481,131646,7642,133350,65874,3438,97277,101450,10075,56344,116821,50778,60547,98016,106135,13859,14255,16300,77373,173521,8285,45932,37426,4054,114295,55947,7703,39114,52,51119,128135,19714,60715,9554,50492,88180,2823,118271,52993,122625,97919,23859,37895,25040,33614,32102,20431,3577,9275,15686,43031,157741,110358,1884,40291,125391,13736,5008,64881,87336,77381,70711,43032,49155,118587,70494,4318,10168,30126,12580,10524,280104,104001,145413,2862,84140,6603,106005,13566,12780,11251,42830,571,179910,82443,13146,469,42714,32591,265217,424024,92553,54721,134100,6007,15242,114681,59030,16718,85465,200214,85982,55174,165013,23493,56964,82529,109150,32706,27568,82442,5350,14976,13165,44890,60021,21343,33978,17264,4655,22328,27819,75730,16567,55483,14510,17926,45827,150609,3704,7385,272531,161543,76904,122163,52405,2039,19165,41623,14423,228354,3369,176360,85491,7122,35789,303724,4465,13628,2233,55311,118771,20713,10006,221519,45115,71021,35650,29775,7337,10864,20665,21142,1746,15080,1624,32449,10905,105743,229797,7701,3940,22997,178467,57208,389057,39683,59403,63344,63125,54847,69691,18336,56448,3362,37202,18282,29648,138224,35867,10495,5911,28814,26653,31514,176702,26550,45621,11734,4525,40543,73944,121080,27858,155561,14887,44670,30742,8796,107455,113472,56369,75581,183777,240095,133699,153299,8768,160464,26058,49078,103971,21875,71486,44888,17156,9678,89541,123019,102337,3972,83930,21245,87852,109660,287918,183019,686,10100,39177,283941,11274,24736,26793,26214,25995,77011,141580,4070,23742,46285,46632,30700,26669,19056,35951,115575,174034,56097,35463,87425,24575,44245,38701,82317,85922,281616,100333,147697,61503,7730,84330,8530,59917,61597,17173,9092,32658,90288,193136,39023,20381,56654,31132,7779,1919,1375,117128,30819,11169,40938,23935,115201,101155,151034,4835,11231,74550,89388,59951,91704,107312,167882,115062,12732,72738,88703,464019,158267,57995,60496,737,14371,123867,4174,243339,159946,7568,16025,134556,110916,38103,191,80226,88794,29688,27230,10454,76308,57647,77409,113483,66864,14745,19808,12023,46583,84805,16015,17102,2231,20611,3547,95740,250131,34559,108894,8498,15853,159169,148920,20942,2813,93160,45188,210613,45531,52587,149062,39782,28194,57849,60965,84954,89766,84453,100927,16501,27658,165311,103841,54192,207341,19558,20084,319622,5672,205467,98462,61849,36279,13609,147177,24726,165015,209489,59591,31157,6551,117580,75060,141146,277310,21072,22023,106474,63041,137443,122965,68371,5383,42146,98961,113467,30863,23794,4843,99630,30392,82679,13699,241612,33601,93146,24319,18643,32155,95669,40440,15333,34089,67799,142144,58245,38633,114531,117400,77861,188726,5507,2568,8853,10987,107222,2663,2421,11530,13345,30075,41785,118661,104786,17459,12490,16281,71936,193555,17431,5944,71758,26485,77317,20803,367167,158,7362,93430,11735,172445,46002,11532,54482,930,62911,2235,23004,179236,4764,101859,208113,22477,55163,95579,14098,67320,162556,90709,156949,3826,57492,4025,34092,87442,104565,6718,186015,28214,14209,10039,107186,233912,58877,81637,55265,39828,6194,145813,50831,105849,4974,88319,122296,10272,197216,95714,51540,72418,23324,91555,8743,140452,250249,51666,34124,7229,38592,129641,78169,174242,22464,149964,51450,14034,10026,95376,26190,120062,14401,8700,265,31386,143573,7203,229889,61567,4227,140981,2466,72052,10787,10062,30958,6099,38471,30103,23202,208101,70847,467,58934,32271,32984,36637,24107,30771,17109,73353,13650,2098,157040,67366,66904,106018,265380,107238,18535,44025,32681,144983,62505,91295,56120,3082,77508,10322,63023,36700,81885,224127,16721,45023,239261,111272,13852,7866,149243,204199,32309,22084,42029,38316,126644,104973,14406,43454,67322,61310,15789,40285,24026,181047,6301,70927,23319,115823,27248,66693,115875,278566,63007,146844,56841,59007,87368,180001,22370,42114,80605,12022,10374,308,25079,14689,12618,63368,7936,264973,212291,136713,95999,105801,18965,32075,48700,52230,35119,96912,32992,8586,16606,101333,101812,14969,39930,759,193090,27387,42914,12937,5058,62646,64528,38624,25743,37502,3716,4435,30352,178687,26461,132611,42002,138442,35833,59582,16345,8048,60319,49349,309,47800,49739,90482,26405,34470,63786,32479,85028,39866,47846,11649,23934,29466,2816,42864,31828,7410,74885,49632,47629,111801,90749,19536,18767,105764,59606,21223,10746,76298,22220,39408,7190,79654,64856,11602,82156,272765,17079,70089,245473,51813,184407,384678,1576,122249,5064,27481,6188,25790,74361,27541,318284,45430,31488,620,93579,45723,192118,22670,51913,4162,70244,35966,26397,16199,50899,209613,121702,287507,2993,36101,132229,67345,33062,76295,118628,78705,52316,34375,107083,107454,44863,127561,33964,3073,154010,190914,55967,39074,6272,31047,5550,41123,26154,98638,47110,19998,148091,50229,31329,59900,195442,19106,61347,73497,70015,682,45850,25776,38022,148951,6288,37411,232526,109277,27286,32342,9262,5220,16651,23175,46740,129438,78614,121925,66914,88710,127952,5563,21500,34521,10739,14863,191006,62956,17359,16749,67027,56284,69134,43301,35039,58883,54466,60823,404451,75743,59856,86979,7923,34273,83785,32142,7693,268986,197428,282681,17049,22346,22990,92245,107180,3357,37104,96724,49153,7683,31197,43267,82231,164276,23696,20848,188364,22309,24821,158707,1018,22514,70922,27792,45589,59709,10765,736,35218,63479,51987,24275,63588,55361,92929,81964,4658,20122,12330,44058,13065,311456,72224,8337,211229,38979,22590,138478,52757,32595,133600,8838,31549,94412,43391,90056,1585,94802,127271,6223,31889,137038,132910,2165,57616,230152,6080,10748,36737,74579,134062,50525,180532,119270,34556,76155,82394,52595,29258,31435,87820,67996,26943,183878,38007,2410,13526,180297,69856,3503,187396,167700,7838,16701,9199,56267,3661,37407,65994,23767,5708,62508,221700,67088,86978,46776,84434,32088,5612,9149,88244,21685,95151,46750,189612,2979,506311,2594,3628,40074,105039,78243,28523,6651,38058,71999,30992,12764,68261,108991,6165,26450,61961,13400,22426,7490,60890,109623,2070,12958,50355,67979,257096,7213,42578,52121,35716,65461,7516,124758,39268,302,64712,14977,1467,219452,2840,34229,11121,21602,19270,63574,8024,1532,17331,79839,78885,52029,180767,57957,6069,91265,61380,55767,8927,32881,287603,22149,35029,68876,6428,199567,46926,13412,104132,21434,366616,45060,110046,81924,128910,45886,52821,130416,29416,77342,21762,67329,121432,79924,11724,38625,81006,102033,28338,13326,3250,82056,82526,38212,21112,12382,111495,3263,7414,86274,93490,40844,30224,45212,24019,48411,71367,24941,76729,57776,3769,38114,202019,197745,31953,237533,33270,201580,255648,100798,44741,32241,98468,106931,10085,15090,170358,33154,66787,18819,69760,25061,234005,82660,6295,131975,16874,9076,4094,25005,17740,40908,19533,220019,44330,99792,50040,19619,13950,55228,24423,31253,95308,103177,184795,28590,82285,5059,3210,75525,49894,70007,56178,10580,36051,139681,21617,98736,3555,106306,164189,37352,63915,47824,24883,145530,61904,28444,11483,19837,145446,30420,112972,85939,11835,191233,2262,20705,58630,1753,148334,1197,144714,6887,11223,107667,60879,77914,4151,57417,81594,96681,169430,1784,20444,95138,254041,27038,596,7117,72808,13759,3353,126776,21074,55322,27081,36942,39547,139830,179275,4453,713,8722,71399,19204,25785,22794,23923,104114,11291,25458,102309,88396,75288,230440,206396,104551,58447,130857,37247,94734,31548,176529,226077,65159,20104,10096,66881,94191,237909,27109,37404,1520,27421,25220,113003,23423,24884,50585,6286,231877,150800,11789,3226,90004,60642,5053,202400,61442,132531,175329,57138,30116,103847,9973,75367,16452,32360,59119,21246,10191,164804,23305,61051,37348,154530,13214,5468,50403,66754,130976,50559,80515,14436,155492,84017,5472,43107,41240,2890,90431,70188,382,76234,48040,50211,281038,237007,32115,142178,1536,22761,96429,1811,31243,1679,49143,55209,17402,235054,61494,7462,77030,34925,87609,78002,9499,9027,73289,201078,101379,63544,27666,5469,10642,30029,49816,132979,95620,58086,351930,116300,2110,2043,30845,6154,11279,16727,4122,2277,27281,4971,3650,39060,61970,65951,39674,75686,38151,11370,130809,177895,32665,63725,122267,7857,39618,118483,44792,157755,178624,136994,24260,41308,22471,12404,21707,12486,30473,52781,50246,20247,39065,909,56825,103158,128603,31542,1089,41935,32744,12428,37963,84420,33134,72921,208449,42622,168151,127335,147107,46699,38216,12591,94342,85814,31423,24944,2605,87542,67473,192551,4496,56321,91819,17630,6300,256183,114569,202090,33209,35289,34897,24967,40520,43470,5344,10199,34810,14283,10381,10017,62923,49924,23233,64539,13051,35686,19698,11570,135555,120868,44924,87065,52318,52335,47586,140906,245885,109834,78668,9065,46990,25258,72022,61243,40838,4545,146387,10537,11557,17470,36930,68104,46711,24264,79401,81043,18225,120488,24746,84338,81652,28266,13776,21878,46973,1047,230465,73357,95777,24973,210160,62210,58404,110633,169651,6937,41870,9909,26822,191062,76553,27519,96256,239070,2478,205678,67955,58532,20601,50120,19148,78501,195724,110740,8249,109665,27446,30568,57631,31425,49752,32820,65504,50079,3663,102256,219898,23849,211315,14645,4359,91767,9528,12449,49366,7941,49763,107848,8930,27086,50686,9744,10447,81935,39513,46514,1670,29229,6172,22312,137280,97759,9806,14445,22976,56458,73391,34983,93760,174219,52573,33149,59747,2429,136277,75123,165263,91040,7446,57632,48633,97140,246081,84766,151684,79918,93268,120346,54059,54875,77858,32996,103590,45276,11968,19600,25849,17159,132907,42828,16817,4913,99462,103303,27395,5737,74184,20749,21160,14377,77062,131403,158735,10999,27799,77785,9320,34366,51593,61070,33746,47048,29268,36675,30262,53297,9832,82e3,20188,122292,39917,7331,18160,68301,185935,134830,15031,4935,10004,165845,185534,46923,30109,44134,122631,18874,22903,112790,26561,18549,348902,82871,140345,255565,135390,63556,103747,145055,179600,145662,296111,61661,211987,23952,52342,126343,48450,32919,44277,82185,9591,62139,205363,376969,394874,108461,18040,120885,14798,39863,16571,16794,58271,81025,55206,14640,118656,6361,44092,85970,6262,153863,108244,180200,72264,79947,38044,10050,5735,61221,80712,5471,115689,11391,11661,184257,20010,60116,30320,19327,134598,45455,27542,18004,125092,452272,1549,91523,46567,180063,156026,2608,11174,58848,37788,65907,80194,30490,5786,40775,119519,106241,11323,156297,8425,61495,2617,29675,2425,59886,112582,49142,59618,4863,50597,86710,50650,168632,27693,85641,83643,18993,25768,84284,28090,93592,36627,312804,43381,9887,9402,100931,97165,3311,173330,66805,28935,4963,184460,3201,78102,19126,21607,37496,24938,22615,16153,32862,134792,153318,61120,6067,2812,12826,12792,23825,37559,64662,202250,102694,155488,85881,149193,46233,65383,15521,106982,11358,176786,25752,39717,34208,24510,32464,77742,39371,72028,138229,60688,71386,102834,132477,2208,11548,63670,271279,28351,30338,38620,32491,99845,143885,152266,13252,2825,178663,108097,1775,78201,14897,113573,163346,62292,171129,22183,96598,38733,64971,166776,117445,9968,146393,44677,74867,20908,97328,12761,25656,26785,9148,112344,26115,99176,110121,22437,49547,6180,79320,5835,31392,43328,33377,75870,119860,69497,80273,7325,155219,43167,111173,28347,20222,3763,71752,55041,47252,14618,28088,15012,97805,194698,54636,2036,41349,6173,96604,61530,51859,43782,13361,24334,22668,24792,7070,23441,16789,3209,36211,208475,26242,32880,122181,182407,21444,31060,88459,29929,77907,12716,10934,97005,20599,31690,8403,58445,30303,22700,10336,86731,103115,337709,72556,46788,112566,47684,67089,53548,36874,56487,41387,125985,26893,40071,106683,73712,18787,40105,72992,67246,137276,50802,36790,70328,138827,22466,39263,183295,29858,50975,9322,57397,10654,24364,30383,55799,41600,23584,127295,296610,129078,143558,244131,86397,36049,1085,80677,3820,108139,5476,34767,24683,7758,13060,7239,131671,250593,59556,103392,29810,4188,252323,39404,116877,7651,43600,40338,13554,157253,39196,25978,144387,61211,234,50104,6129,10449,93777,9240,356378,274148,4439,72970,3724,147770,78680,62570,115877,40027,40547,36817,224392,64609,34795,165027,67440,2477,37206,23431,50754,164797,46018,94995,170982,27051,7957,22767,3674,27900,56419,18930,60701,41302,2692,84749,339721,61996,111094,80221,50129,1045,8153,62945,19202,8250,37208,37418,32560,79477,41106,88569,33963,36693,5892,30570,1581,66471,49647,11922,160717,29442,5643,114865,82962,95982,132098,22633,22838,94726,54556,28566,205039,162340,33216,16849,35847,221339,94851,26533,71469,1805,3804,12935,45483,71020,36310,65381,192960,34240,35165,59773,1248,46954,155332,96864,4246,388800,16129,57133,74592,44807,442014,38203,42574,80818,91592,26377,36424,65760,977,77387,22628,147610,28018,30561,98454,6969,119628,63648,18170,36854,26601,64018,22027,37279,51395,152934,21153,9430,58760,194742,5330,55115,34158,28917,174111,13171,122326,1526,43896,66094,25325,4234,148354,11450,275,18999,112191,44365,22723,68409,8733,57746,96565,75007,14196,108844,29475,88599,177563,100792,106156,86323,93726,14248,135341,194131,40126,47099,14779,8272,39597,95983,171398,65882,28052,10393,47213,40689,22120,72212,106829,34964,109146,753,648,21660,30047,17527,181025,5619,145357,4085,216883,9359,186951,24779,53931,24545,36197,223296,62628,168101,4243,107313,30321,26642,13049,51059,31027,107912,807,73550,26551,84369,122422,165872,49754,74213,234264,33151,52014,33100,87183,22365,52500,40013,23302,5652,72723,21404,26107,48434,587,94049,168493,96418,32871,70860,31709,25128,443,71597,166253,15670,70994,26341,133675,28280,75491,54756,47955,56028,26182,11952,113272,472197,64640,110753,17919,337,50642,22576,142,87371,53391,93210,126694,15285,19642,85667,14148,1506,42092,52962,33243,11970,20734,135843,57044,58880,13002,219134,22876,64754,232519,4257,43120,321573,24799,64526,124728,52579,81472,70831,276848,17403,74359,23021,182101,74597,23744,148267,12055,7976,5349,11772,67540,167347,65318,18720,127832,108238,22828,90233,9987,259080,118185,73209,79270,13775,90100,137742,90799,70569,15699,19961,9087,67475,57872,39731,8810,134897,131868,146849,19898,3334,2281,167061,91073,60356,467742,74712,188,53179,137679,92769,29241,9537,132595,80119,1041,88962,5976,40171,44911,102859,139059,104558,98987,47761,19272,71472,113864,175377,73338,10857,23402,23758,1591,139864,5644,4076,118760,16427,134198,18853,20291,100849,37423,22038,36677,19071,195521,57445,11069,31869,55718,66882,148490,44,41296,75242,49704,166810,9906,20943,122258,49112,105667,15969,10344,6408,187694,21399,72742,58970,14867,14376,81889,41856,23225,15042,56993,16074,131389,74276,72407,53875,383108,53597,37363,68993,44854,122548,430927,198279,38430,80409,12245,2981,628,2818,17760,37437,238229,7968,46892,2200,3730,34190,65983,37959,112291,87850,70827,6522,20750,73913,111621,41652,19587,2780,58668,25916,85259,18200,168962,95781,42445,102050,7776,57662,103313,47742,96358,41964,66174,100396,29069,204735,19679,27978,7479,40264,22534,61183,36081,107436,58223,14680,23002,101311,24716,124108,12908,5646,31750,40380,14215,232799,102772,14122,96775,61398,50917,12096,149880,67833,598749,124194,155871,49216,790,14677,65319,56917,7440,145744,95701,12206,49405,129269,76199,45732,9767,11058,9047,210885,11051,7392,26307,2130,8132,147526,20802,232698,115660,50060,59789,57344,107623,80343,112676,23291,9866,160971,34032,118291,15719,59730,164911,28975,2659,58046,78480,21854,66209,53863,109085,116045,29021,46481,107552,22130,18764,70254,31272,11300,52460,43933,84738,20721,53869,190840,79673,105300,7561,321817,66924,13940,33281,101046,183181,32176,71878,5678,62924,79535,56646,40303,19559,27703,93042,73368,42187,3670,37376,46440,7023,36816,109628,20680,5940,276440,275233,170848,112093,136996,14984,20226,111441,77693,112960,48577,39370,55707,50314,123404,26570,54281,61372,123391,4857,35928,246740,132507,106646,44241,7196,92258,9825,37688,51197,303141,5590,15476,132986,10955,85782,34486,26696,7991,28813,18858,39546,11703,11365,38185,5716,93555,11925,40121,60002,6985,10976,171384,3887,43394,13337,56346,6381,252336,39573,75042,53711,1028,31781,44295,95925,131713,7214,68125,43571,70954,213234,1628,8760,13391,65485,17320,56038,1710,25248,60803,57399,19839,3870,326,281556,50945,72400,21460,316244,75619,56246,98775,481,13513,55765,50427,7388,123519,32929,57908,27124,61316,101097,57467,30228,48792,10788,20402,37318,50526,155730,34456,158065,145305,17832,43733,64052,4506,35072,205355,177028,184004,187081,68616,35938,83703,10367,36892,93186,260137,51934,89970,4985,23445,26755,21558,7948,78741,23376,124405,85594,68596,57536,49351,12619,56593,132668,99924,109728,71844,71935,196018,65464,17617,14987,89701,143773,33997,8687,22701,33258,2914,4436,72108,85610,9671,49067,2327,82988,1361,1672,44033,35777,30269,24057,10605,82236,616,15793,13919,47249,112086,116698,9484,80207,90574,33304,68624,93127,56101,42210,160929,4827,38995,38095,4701,125119,5027,33680,9236,231236,14135,87837,23318,70261,78893,30151,81482,14332,1084,74256,27532,46644,79185,3148,62615,6981,55672,31668,36825,1849,14536,37446,14738,23779,43058,162749,72199,1168,21346,5592,85932,85302,9668,18351,57135,150360,2080,228015,77953,34670,119302,151751,31009,106725,84265,45214,59289,74178,113071,263206,111009,4021,44449,188119,192629,123592,392506,292847,114487,12831,205858,9852,20780,79648,75767,357014,97721,18166,21005,67950,33226,204009,16536,2987,11335,66717,144910,47950,17262,55060,15063,2934,51038,26775,178497,66008,3427,49433,128592,20036,157553,63861,3089,23015,51210,28696,35933,49942,71135,231518,99620,17248,21835,176536,20676,16944,38700,165831,233253,295625,36723,13023,52745,10907,19423,67972,125868,95473,82875,1183,108455,52685,33417,64095,21433,52438,33191,127809,44505,211823,7810,2752,95548,162031,7185,91196,47563,61721,33359,17897,23682,42806,178101,22874,49707,199897,75419,82456,8618,11171,79712,116847,18783,44190,46564,5346,59046,95032,7893,14916,3214,26800,24172,121453,34362,10250,17408,18888,4840,68696,22831,13162,36005,32512,14800,62357,41723,45046,27247,37486,5372,2564,34261,298500,66509,133920,89138,31305,117697,19097,108304,81386,84106,23802,46411,63304,946,51417,41777,41041,19501,115864,60743,294354,37955,94165,18116,1156,17937,20645,57114,90804,58042,48643,92288,9861,2557,88546,61333,101008,12853,5148,87856,4152,144503,73841,18718,9789,147565,10846,42085,12789,30223,8993,56352,67203,2448,28215,6052,23540,126319,75933,36689,80235,23231,23561,21383,38800,77548,102798,21234,31468,158608,46188,63960,191679,8051,67014,11185,170078,42186,28827,34777,41930,212079,12421,34750,24111,110344,73918,45171,70826,141949,40063,23979,24254,37309,26724,27179,24718,83648,54938,14591,17425,29525,102675,48975,48654,12316,8929,60640,41709,50168,63264,89812,50716,48632,38755,138583,160123,55579,71829,24230,233277,46322,39650,166388,34718,24108,98252,7031,106695,62498,18258,35062,217827,78731,34824,33354,19520,60852,2432,60224,8587,2836,62955,702,20227,42285,40560,95592,62486,11094,53035,143291,18842,46177,77994,1770,9657,107422,172915,32655,128716,25886,25164,156740,119928,165875,85817,11007,89110,33956,12652,65156,180266,8494,36889,19958,20955,96,1264,118288,135769,44754,86671,5632,19026,168220,289120,33569,93821,66144,70635,7687,5642,2714,55445,56636,71545,184182,93133,7332,37389,12643,52315,22729,11014,158742,17050,152889,50178,34601,41945,52136,9948,26914,63548,95721,115951,40759,8960,158258,38938,49232,48325,42234,81523,253019,66128,40978,20048,238048,38760,62928,122560,118532,43687,137472,163689,26680,9878,17448,51035,16211,60834,36749,29178,14241,59868,150086,2305,26477,42422,34342,165341,83279,33894,14257,29928,12743,13957,125571,89134,66712,10952,16507,147839,30146,7249,16565,45399,39874,114565,215780,31990,230881,171477,102,196546,44538,10880,84948,281705,86651,10617,31395,2342,453658,43569,60561,132901,21845,17727,58556,258242,22262,58728,4008,77997,11806,37431,30599,81375,109137,185787,114085,217292,97453,169085,30593,60212,11544,102056,65580,2384,91655,4855,95725,7295,157994,16228,20669,53276,141590,105246,17334,25440,76067,17967,39321,38911,11362,28559,63807,21627,26468,85816,40120,1025,15234,58319,69516,66512,124548,75845,78873,22137,46681,51242,85683,32909,76747,35555,43396,101465,1765,73094,1077,2962,39028,66777,57831,42048,15828,13962,36041,63657,52412,5242,58846,2141,5506,219012,134451,3936,182230,17558,17153,152237,22621,49377,170216,35257,68233,65374,6510,11126,212151,7184,2480,22517,3437,33073,30156,16557,3768,55067,86829,91e3,12350,148650,66017,79424,70885,49066,28250,21369,51213,34533,11510,3258,18176,18465,84413,6315,36411,163765,4346,356,107618,598,13727,285026,162695,8749,14583,7132,63521,184253,32378,25991,5604,30961,53675,4874,84693,5086,34811,26978,56564,7904,33519,51221,113942,69253,6664,125563,22055,220680,102008,742,51930,19494,176108,44424,35123,13025,75685,11759,74335,22250,181453,131147,16984,132115,154311,11991,76452,52609,85351,196,30969,9198,74919,2529,56838,71779,29187,116304,3504,62330,41190,86153,28393,254926,104228,105189,13264,84359,3574,12415,8534,57147,10175,188174,59504,60932,66318,16407,107921,17638,99103,49278,28403,39786,145865,8462,3558,43406,142271,29139,21989,36552,93955,72365,7176,13556,106185,37957,321774,17782,129017,51154,27938,24952,1935,39366,2791,33489,41582,56078,24558,9311,5449,218786,27808,190429,68013,36020,86003,29735,3404,87348,119357,115714,2324,86796,81973,40992,43376,93621,28784,16808,36367,2517,2909,191926,24978,55303,53308,205724,60068,3098,21375,64784,23949,26579,63121,12319,80145,39967,97861,6757,70143,67642,37082,34698,69140,122883,46151,62187,80934,429,19437,135071,137885,222647,13331,154065,327,61778,74257,40116,37493,14855,85079,237641,42342,102164,199965,71204,4662,29368,5042,113914,122214,8955,13149,102503,43173,5659,163787,69003,307084,63392,171080,21390,81918,86666,36622,24126,28887,5736,28054,207170,163428,79891,346467,95363,38980,111806,80828,9200,19288,294896,114468,87405,111715,141705,7015,72754,68463,48738,243147,33397,101210,37051,98801,82847,20397,4940,185559,18716,54718,83491,11725,40803,1128,12128,23060,5174,7745,67007,46701,1571,27807,180186,256996,18975,16837,7877,212758,250379,15440,87954,57755,24719,124057,83461,258,50864,8874,29038,71289,31627,15429,9005,4061,113851,107716,82819,13651,79656,117851,17539,111446,12938,39724,190787,4352,15402,21070,62708,8539,23777,73853,13552,38810,86117,16285,56400,1718,75342,142863,29033,378,110113,180321,32586,23606,26393,160984,207987,23783,8406,16904,24596,47274,11693,46539,60524,78595,48423,31718,20170,9009,146268,15183,191060,172765,1349,138436,37365,10970,40509,225817,20021,70394,152138,21541,66559,66544,89352,2725,17258,91345,7313,3815,115868,8660,40362,4071,103524,39388,118275,21950,6549,38226,32754,209574,29201,43495,18028,20296,40597,18370,47520,202450,24134,2219,8195,69545,38041,136934,46374,19041,159811,84865,58620,846,98749,13569,30714,97246,32186,4479,27355,92973,35214,151491,75963,37631,1561,27200,238083,23182,60756,12291,25766,39355,102333,87362,65741,59906,19538,201575,48772,102938,24438,292580,39964,66366,9004,61379,50548,37622,38732,28379,68180,76622,17488,69849,5963,7219,48143,43413,55358,540,58691,29506,19245,52193,48621,5518,13048,118625,44755,191081,42061,89197,2259,60665,66994,71210,51232,3585,142096,55024,7892,8345,58653,463307,65658,64319,137941,136323,53499,12746,43492,6978,95163,29925,60175,5128,7352,41463,184756,121146,20473,18426,4598,5309,54580,14277,121151,10691,56711,43880,63409,76682,11830,172218,264898,32632,66536,81062,31649,25788,92774,60222,11100,63159,9432,224657,25240,53613,152,138620,163829,2397,85345,12501,37507,64932,38575,43522,65789,80198,78796,35226,3851,108891,73311,3060,28391,93671,39663,46142,30982,66041,37281,68157,26553,71872,81142,211527,39747,118119,22695,2859,11066,20232,168911,7933,197005,17066,111071,44434,133994,120798,12766,227798,45756,132852,29917,36076,55352,65281,129800,41958,18944,84678,18580,168093,132621,39997,54092,27740,32354,3770,114118,103242,43918,15899,18574,145944,3190,123469,219903,24169,100571,62403,16776,92779,14535,17168,16475,14304,37231,1712,28218,242754,61688,28980,1318,51359,222657,99200,67989,31772,23932,35351,201251,49041,27306,19128,40135,3986,77333,19649,120683,151927,21081,7076,78375,77501,101599,8011,89585,96715,58179,5378,102138,106793,26051,217276,4197,16297,27014,46721,13322,22806,5278,29629,70632,9647,71519,58818,40603,128530,8903,36770,56900,31483,26935,43845,34265,34920,87658,6114,84767,64250,47318,50720,19264,162514,33357,13117,6705,46696,75032,71054,87004,42035,69138,11903,99854,102328,19611,34525,69312,6431,49842,101600,133178,108751,41829,89939,225664,48916,99556,9195,130387,5960,36857,116724,53518,94002,39077,53996,6945,22261,64291,8314,152785,57588,16522,9091,5048,87671,35441,39509,1945,12423,158923,178413,37549,14095,1475,73188,62878,4819,24012,68534,42606,4010,120809,57497,59564,101758,103718,32701,80116,12345,95834,46918,21468,53213,15665,31200,3867,5140,96013,250744,21016,10069,13968,35449,180829,27683,39704,59956,22893,3115,26293,32785,75934,62445,141162,62720,2018,83638,19949,114012,95006,3330,99829,130935,309272,9565,55874,121727,37017,23586,319858,40970,27602,8625,112329,61060,100088,118525,25922,16232,1907,60671,51583,44553,80993,5262,94679,8676,940,20736,11823,3020,16476,12340,152600,97416,3703,25744,66826,16245,16876,46446,84798,74227,176020,45192,61955,75496,23946,23626,40372,26036,6149,11822,30582,16541,41914,82385,232823,40921,80773,14930,3631,7517,39619,4348,36180,126106,138939,62611,1477,113512,47321,25052,14546,118881,29060,23589,128322,36795,18401,137921,104699,267929,36194,172791,18113,4766,188215,30083,332586,94089,5805,77909,22194,68234,154976,43220,40660,70001,184893,138095,11128,103010,22663,5108,212615,8485,5565,49222,54614,26530,42639,16319,55062,152662,105595,21114,22216,10294,68158,10436,86950,7206,62115,3977,3657,59874,456,118617,18156,106663,112229,80992,17442,8217,55551,5133,34344,251927,51153,39364,201321,7816,66803,23057,156724,145664,14276,95705,979,2796,6875,13429,212525,50602,26276,28284,3424,19465,52397,46963,31420,51399,206476,92317,48851,637,100820,83349,10317,60227,21972,6908,282439,32857,224767,95629,83882,42106,87338,69757,29840,68709,37665,45244,114577,49188,175943,54009,186746,106158,70168,3358,234002,50555,9221,129338,9562,20118,32923,78479,118280,65752,4977,10474,102174,60947,129006,10570,83451,8598,8078,159367,123785,80438,16742,5905,5281,181513,42402,6977,163136,93179,42191,14968,50421,112401,105440,33456,57347,121611,4221,94954,36517,24046,27796,6255,33394,72990,135408,116627,1233,57874,25654,95419,68156,401399,313338,55208,45573,93124,119251,47200,38196,11909,130667,45391,73904,64964,167846,4137,115606,52036,62214,7969,160925,7187,1132,134835,40309,73195,64494,80472,444841,61111,26500,45323,40743,53625,52797,22659,15631,29739,36706,28841,39147,102836,26794,10536,14845,87305,45874,12241,127587,83833,57183,79722,30844,41304,84655,20825,92500,3722,25655,27811,10157,81634,31362,34088,92487,70123,22190,185100,72658,139035,192523,88241,2078,230490,44528,85638,100198,22088,29982,291233,241062,13865,4445,137791,37835,107218,31726,19718,38234,72528,23046,19177,66695,5109,17251,28077,5617,21554,47839,72425,133825,1486,73065,181275,141508,21768,62971,63082,2512,34200,9904,120309,6392,91243,68416,268253,41199,116757,138551,185526,41246,28986,4093,19057,17295,4148,245766,122360,35356,112075,20301,75441,10998,7977,19769,62922,937,63547,100196,26427,157820,20983,236696,22935,8140,90315,156004,47204,140973,7726,45097,52725,22636,23436,257282,105247,522,88389,216031,202204,46812,211666,19693,68828,81691,45925,11256,30292,372,5236,167826,88328,232776,151611,5360,82104,18841,80393,25465,18285,20320,72377,31730,33160,45803,38715,27705,37379,24163,18360,103586,4015,32305,269494,91252,20080,36567,54650,7797,57073,12650,31164,42209,6375,261663,105528,81661,106002,2800,5375,17247,43151,4442,15727,194619,100855,144898,62320,78465,39929,16454,1967,28311,61363,17219,9395,8745,121445,76939,80385,162380,22009,54191,44248,16299,122830,48151,74429,78291,64755,14238,44966,2511,17712,67954,93583,829,105899,49935,84750,11591,33185,85447,42717,27409,208542,28965,62052,52525,5597,25694,65594,16343,63224,276188,12475,9331,127507,38522,57287,24128,133161,79723,105548,133695,48917,27558,43278,46520,13778,141954,110785,83366,17715,46317,105763,66298,147013,41086,94180,16478,220447,44611,730,19722,78975,117889,125643,26254,16574,18480,65006,15806,38549,246418,46052,36056,8440,34984,30170,3163,59800,4458,115442,4283,41970,33507,104078,1653,22,121158,276486,3655,6338,24048,133421,23641,2161,24422,36006,8086,10675,181474,12307,29514,59143,14729,52509,87128,122470,19446,80852,33314,24573,119864,14237,9652,57779,6612,51851,15284,98871,90581,124466,156831,21190,22015,71380,161906,87247,69201,18392,17908,108470,72962,40719,14338,17911,95260,43339,20610,78916,20710,72451,11315,31448,17263,58853,178878,48111,116002,45497,80506,82605,85880,36300,121755,25215,36118,301929,88728,405223,276136,553,34704,212438,49970,78329,922,20711,25036,257130,38295,145369,18128,15385,30829,55656,48345,8012,3561,28004,122041,192900,58338,112508,41085,29976,87040,47117,23905,4336,92061,138880,97407,42083,172121,6256,25192,172671,5,93568,1420,12677,31605,56743,40620,6015,78415,231077,31298,80026,13902,19048,24924,170586,32955,176119,87859,36731,6773,27711,24658,26475,115216,133207,93250,95820,88522,8317,5714,124047,55219,86860,19677,23961,22928,162209,8904,225992,359835,56084,96201,29392,96558,86071,93643,55114,13347,8183,95129,82012,2017,123336,34219,115554,157159,47747,101684,41008,18735,193781,104151,226906,7552,179874,124113,31159,21162,44010,14771,51268,166128,31382,73124,77438,92830,205709,12113,1292,38937,13114,1334,2118,15597,69581,14449,21934,76618,48728,67038,14967,51495,24243,87736,147249,26720,11119,46063,43749,5843,44147,152629,133428,65703,14269,45604,57982,28672,55616,45957,8438,95433,37698,220862,132034,39456,61870,4161,26501,73560,56418,9845,4654,20916,10456,88920,119358,9015,65931,96507,48029,38534,21676,109081,43078,34943,25089,6131,28766,23665,5477,10255,16695,67,45778,42443,42770,29534,23733,100513,62617,42630,48746,14191,43753,50295,26007,8792,57243,43119,54725,164253,58250,112304,131796,25165,4651,3188,24831,47748,3705,19540,13211,102095,5593,18699,23666,32005,117571,33541,60584,74573,86311,99443,25172,27222,168938,7143,11853,53560,18834,19960,86522,28217,53266,117700,72989,34323,18721,66450,34346,74056,47217,202002,46269,9429,68582,75458,37823,82843,96652,32549,145144,27958,19820,158086,31955,201406,135379,31207,192545,12950,51704,9094,248263,76147,64028,110009,79407,89345,99284,223492,47966,26848,15359,201137,2861,110507,71231,72297,31851,118777,71039,151051,240855,16333,50766,14727,7939,4149,80908,418780,88378,59276,1327,7284,38576,79814,65820,42199,84860,49574,62596,12396,70598,40117,8648,7994,16836,7630,14047,359699,106878,525,29037,28064,13380,11675,50669,74216,103539,180314,27449,56299,172344,19274,7301,246099,32043,19422,36506,129317,6806,30140,4614,46639,66926,932,86600,6322,27847,233103,10541,39025,34887,3517,12972,26220,2031,66561,115015,48658,47596,12714,33845,3893,16165,35237,89983,14769,11962,147224,47018,29977,27979,5552,82338,86023,131368,1218,24853,237840,132193,15455,40873,3668,65351,53388,15229,59889,272245,47934,11858,34347,18038,90853,86981,300602,19343,114181,29362,84921,6095,106059,79472,38015,1206,48741,6208,8e4,21916,17423,6002,108083,24479,34931,56661,9511,26995,100694,163853,35997,81254,58321,18919,171890,86877,91341,74503,70477,53412,7027,59281,39892,131302,5864,15947,61301,67466,162369,47956,27874,35624,282324,21270,111847,102548,41482,30955,116737,28264,8592,55458,22301,75090,29821,30697,51709,3041,19208,8038,24634,30467,87509,126428,19389,18814,152686,20701,83474,45832,80891,105808,11378,153223,120770,98186,150633,49838,9141,12755,30962,5260,74490,21256,31678,65062,33326,289838,187831,20595,89768,2805,58535,10844,70085,12090,2451,138068,98544,24461,4511,6754,41684,28203,3383,65355,82833,30161,83924,234361,128424,28921,222594,33975,125491,34069,11508,67464,144226,41850,98703,34371,7901,21254,38398,65651,23549,53883,213340,123269,12028,71764,177701,28758,2623,68395,11549,15232,68603,9660,63116,36079,57093,31198,20475,48467,89984,35619,186847,107469,31389,43631,73867,41949,68841,114250,1605,30564,63403,17588,27680,99533,12641,70325,50428,73426,78379,11855,91651,72081,91720,60198,15743,12065,83398,140046,6761,46598,45900,5068,886,62448,148968,37347,19405,9680,15819,43496,63370,75667,163700,37639,3633,22774,34341,183131,134335,37200,23915,7054,14194,12970,26438,13350,285521,25594,8219,104410,91039,168804,138480,149734,15907,33818,61132,60082,4622,110187,56736,13551,73571,3945,73463,65498,17758,263266,17593,2710,27585,54469,38200,45367,63754,28881,3473,12791,98287,31895,65787,4463,94536,24951,36332,59901,28803,52130,86403,7668,181822,74831,18977,9850,177206,145485,109798,7292,31421,26280,77211,58511,12507,127004,11113,147,8729,56208,43066,79926,129937,31345,83947,39915,46146,98763,42566,1337,13192,18323,105163,80570,117753,16555,72883,11077,159438,40764,70933,83329,26066,12276,72059,21655,173836,126713,69454,153482,91585,70644,102558,110483,6764,127864,190133,3961,101798,20945,71138,82402,90884,69669,44753,923,16939,59700,164258,25969,27082,31399,43846,6306,246093,51342,6153,151581,202801,182731,56475,162188,89426,141356,14355,121815,27536,28023,65257,77523,106668,127314,24947,12790,38796,169698,23555,10725,44573,183083,42088,62716,43265,105958,32050,44067,50118,1668,3874,6243,318411,16599,1691,94999,52378,28671,216728,123258,2059,34969,69225,5913,136280,171443,141515,91662,22175,135282,80020,92270,1663,4808,4482,3495,34691,5226,109830,108512,17342,107488,11606,123190,100247,29666,146527,113014,15794,30894,13224,39585,243192,22351,9903,7836,47699,11078,25468,122291,48821,26780,122679,75521,81450,630,4895,92900,55074,74293,17441,3563,111657,103102,51613,12318,52370,36191,68245,34269,40445,41354,122901,168604,182500,62012,42557,11259,24428,115113,86345,12362,3909,78430,86852,134602,20459,47853,93879,22577,7659,3688,38555,13349,17381,56715,91639,12493,10895,92438,3142,37057,28928,2004,36427,32268,34222,209974,10432,67436,41989,173518,107930,27079,62729,30908,55558,5828,45031,14902,53546,8204,144263,60255,14520,88212,86582,109589,69356,8064,47449,8505,66558,16886,4844,52817,111260,215129,12941,91118,650,20770,6273,73089,40618,62790,2873,35002,14023,97208,19386,102646,36993,143736,135457,35385,113601,17893,32627,84439,100619,56016,6581,57264,172160,45452,111710,203627,70131,24100,322787,1996,35665,70078,22358,90922,83658,4097,63200,58499,14542,99153,52159,6615,12414,63415,31986,16823,1579,65405,137809,8841,16898,48082,259,33014,42375,12260,179850,73667,91389,98882,29532,17311,326251,41092,5928,20742,44964,48019,43505,9317,49265,6643,192712,48424,163487,19861,20113,70848,31928,105333,23685,78563,14638,54755,7158,24142,44018,20774,125255,20331,24280,10163,1285,2336,39851,4299,117269,46714,63816,87779,159624,11731,9971,990,137317,108831,50994,74554,162680,23640,131597,146962,170620,34829,91205,21184,1913,63616,18427,93136,156592,17519,67565,115882,138220,78622,88535,18115,2711,33554,109492,54298,971,24914,25863,36363,45715,27099,194995,14299,178181,111488,72395,322385,157719,130787,11897,81843,83999,11369,49280,118604,40922,61332,110343,53407,75639,40582,300440,54722,25637,13694,48248,48278,194521,56203,52779,48783,72627,10953,376,16733,280238,26351,230789,15132,25168,137270,3588,63704,73376,94031,74284,19443,159557,9697,39901,13351,119050,15406,146455,3460,29556,75195,37673,102524,92329,47289,98413,15311,100684,56345,7116,95480,11590,7200,167,23610,58426,17730,136656,27944,53151,2701,8824,103124,3017,90744,113588,53216,79736,65940,26931,498,29568,80540,143543,21292,1740,59268,16561,180816,42323,50174,40890,52866,10703,57169,4700,17191,4424,93511,49698,166650,26972,48631,165169,82879,69326,202970,4007,2376,231325,139592,22119,62851,37504,68816,58345,67398,186643,43331,277416,53749,15746,23102,17432,4793,151138,48822,54265,48203,198688,14305,54287,2291,18018,113378,123260,7180,97549,87027,120085,2920,76080,8190,102005,5641,64580,14955,59802,54028,58884,19367,81779,412567,85957,97053,103637,78871,29364,27637,141728,4767,30686,112738,130146,42745,12730,105040,14844,232,210944,36581,152317,135543,29744,3129,55647,58149,46319,27265,17499,28005,59948,7170,34138,5702,293047,110892,408,91760,218674,18469,46095,81403,14389,4610,35672,73060,11006,74848,104820,118143,190357,20043,105358,141735,5115,27093,45924,123073,52599,29433,9616,238350,78610,24851,58858,26769,31969,24613,18294,4982,32735,39639,143563,112073,202205,12567,4873,88601,44897,81503,101648,81362,34662,85277,17574,48173,21435,221188,40215,39576,80786,26544,64668,81841,10731,37733,247986,149188,127703,495,18382,54388,72446,43071,30974,198723,89608,41360,190,33045,8386,31658,19992,237838,119015,137622,50890,100913,6460,116233,267230,26621,104129,65114,14190,41542,14888,85962,23342,23041,26453,43725,71809,45186,4770,46452,53894,56616,221286,18973,9038,109299,55365,19366,26863,18808,60909,69353,41738,83463,12100,68561,72860,3980,13796,49340,12332,31311,27418,4255,53430,18976,45523,510,14224,30477,26581,4530,3651,101663,139840,22709,150861,31996,63923,120623,262522,3076,10528,2929,14672,130238,18087,9816,121894,100308,25085,55111,14565,18952,53293,2042,369988,23674,61789,133529,28783,108293,35477,47119,36448,71049,40015,33055,78598,198442,1833,159937,40654,77444,189245,113153,8621,18599,38553,35223,166072,2375,11659,21786,89523,6032,12116,63046,159398,18454,3678,32521,47626,11411,103527,38896,42946,15696,26370,10185,8413,37080,165583,4331,63555,14907,72220,50056,6623,62236,36565,49783,10049,17503,100581,55951,146244,24724,9626,17969,25524,109300,173965,99994,101056,46459,43647,53737,277968,8347,123521,74858,33829,44762,77574,877,81377,222525,123532,30602,43881,53145,2973,16284,81940,61281,127044,63620,9875,14756,114829,19032,9202,52759,119141,23928,120551,19607,3599,33401,76821,73233,117430,39968,36539,7071,5446,121735,194059,15206,45283,6706,15603,65615,1207,165723,92275,34773,104447,8396,32353,205240,164323,13600,60555,79205,25532,22907,33410,57480,107111,69630,32137,47832,70913,33161,20321,2371,117348,10714,86246,1625,11763,17900,268,78457,99175,97940,101092,86660,32221,14041,128504,125080,53744,124263,31017,13897,403,31859,21964,5633,111630,5547,77329,17961,18241,84995,25984,12983,67491,62168,47262,5241,297,51191,7351,8967,147212,82060,16821,782,11033,82431,62957,5026,43459,77963,203477,53528,6247,191852,87774,74164,215654,13467,1522,219964,28589,244104,16242,117821,67725,72570,156792,17186,15979,26990,44128,193014,35276,57125,16212,166451,68017,6905,77608,16364,53777,75921,76426,37975,26203,269296,64099,84122,12077,38533,830,4407,20139,963,43028,38902,42911,37503,83343,85045,16979,1165,60835,137387,58380,86990,110066,134540,56331,193845,81238,17922,163093,38744,110641,12502,56404,34862,26865,125964,12965,111648,25547,7771,27196,136980,9555,29551,107158,57885,18831,37705,35505,101742,13970,102109,62548,124657,23328,11124,89592,146376,248050,6241,22033,18337,80685,29898,11908,216623,67721,106162,146610,21377,15085,91552,42041,62560,122532,125336,102365,121537,142559,29693,223919,11515,110495,18776,22494,5895,185059,103592,229351,51220,100102,37027,257855,29359,54123,36066,106493,12244,79258,32002,432,56205,94836,90182,6726,14762,29391,48938,26864,38083,60364,3310,60192,14766,205567,57504,110760,22649,24666,46333,21517,3430,13135,28873,27052,158809,11597,20529,6695,23138,22960,37137,45574,6545,305877,43423,26153,24769,59844,14501,10430,134352,56169,13213,103432,49523,35181,13435,12408,129475,64620,230854,77390,51990,15653,83248,33466,44571,117828,51481,2187,10559,68019,18021,54895,48247,18354,33737,4554,108595,37288,39767,116707,9175,3726,108877,21616,83684,49862,1938,8543,276466,20134,108498,48770,102254,31914,131520,185291,100559,51890,209,19526,76471,50544,71814,99351,8172,198526,28816,20419,9109,98389,136777,76479,75596,30635,165417,48216,120220,25955,211071,39314,24308,32164,2559,146280,43403,9233,17947,90585,1786,86920,125662,2457,64741,32152,32918,122882,78538,44001,31723,56426,23375,103172,88177,145697,52506,49319,68016,31664,41488,18486,110400,7030,28241,986,109199,19900,42147,56864,65287,49183,7858,24e3,30453,840,16673,25907,68916,89927,6309,158335,36407,199737,130464,13137,59603,201778,195292,21015,42466,179062,172561,89492,11075,180407,31868,72493,20998,60217,9865,19530,39274,130266,54539,21623,12535,13505,40641,73375,4087,85633,2153,3117,70680,55788,92096,47509,98493,37490,271936,151475,3032,16171,96642,34106,78425,125761,19591,3366,19316,54508,24183,50786,194248,91528,33253,34622,108355,41741,705,3814,3883,108929,13203,67831,10142,59754,68208,29128,84820,56880,38794,24972,48571,40821,40476,18137,164254,24064,236309,79181,11282,395,39169,2013,51587,28551,9645,701,109513,115899,113566,12762,62045,58322,103726,41343,40866,244102,143816,2490,70346,40973,52618,15412,30720,104315,38917,42027,93676,17513,107418,20706,123890,13399,97727,24044,87962,65606,44250,98044,65276,74790,101473,19350,91570,1326,87790,172042,7577,100813,86896,85891,41512,108130,27794,14875,71431,12835,156250,58135,3759,22476,42176,115873,34686,56523,73643,108505,51491,20838,12721,32863,45700,29496,13700,34294,55360,29206,155942,123812,7706,163234,203,132720,49358,144431,8130,175788,35818,3270,76832,25710,54095,97274,28779,94621,74396,19092,128242,58067,20885,14670,93255,15107,63291,23654,126900,129421,59294,262659,9798,3251,67344,28600,44629,50672,29072,26999,31526,23183,49175,165843,175455,17282,175411,32022,45989,30298,90690,78118,83156,23749,35636,31317,7069,80381,94561,133756,14960,97404,6138,41065,78041,32843,16601,34123,9559,146529,123377,96395,54441,42012,84257,123541,10745,22139,106459,11720,150883,172651,154996,110538,4728,53447,25704,2009,71152,119354,21166,66604,1429,216162,8637,122250,63520,27180,29172,36124,276428,107787,77184,4680,14952,104903,24418,14793,51561,52931,8371,26342,48526,7118,92066,67280,40653,8847,34597,105438,14198,50163,61188,146286,50315,41205,170829,161496,585,197359,95056,1687,365794,91349,48507,5804,49263,5146,104902,96365,117343,132222,46084,96919,16875,8073,262381,79982,52663,13928,16056,153908,15145,109256,132308,18763,24904,167644,13618,40750,18686,147124,114709,150038,52849,2938,12568,48617,8778,5459,44202,44591,74914,17183,248689,13878,7822,80060,23116,194037,18487,2067,7798,43077,33678,244028,31320,74273,2794,19466,8218,36280,183997,48124,19416,29656,19280,98734,7715,18311,30701,133602,150307,126956,7378,2933,79903,13178,12593,86571,26604,92446,13574,44205,65699,427599,21118,8245,14407,27877,47936,33542,7916,26460,117762,21596,37818,2249,127359,209394,60044,47677,308089,36791,154971,31417,6998,150042,174360,12255,43009,29335,48739,3912,101398,53340,2580,146939,151295,45360,125275,15273,45383,27456,48761,23314,8750,60801,85823,104759,27894,123685,66968,39480,26917,55290,83305,2696,98390,57569,145853,340733,4919,20024,52268,30884,7413,203685,70989,112855,4129,50536,349518,68205,332641,159581,135361,236026,37563,176404,64899,6578,122033,63871,1850,85234,82089,66124,74145,121098,107351,12687,36881,117334,13136,14698,85933,93866,18047,32620,310,15094,46e3,88451,23632,36645,27940,87618,80520,58892,20976,27702,140090,96075,67841,103292,238964,87778,107338,17019,83427,67522,7302,8261,47570,116787,8730,80484,61772,174422,56005,131193,52875,14588,28471,59817,9586,15720,158155,51307,109734,15196,11025,59331,3884,52626,102602,84797,25158,27314,4437,20488,76214,189248,35023,114952,157376,2827,62439,102878,129749,36405,10329,109339,108633,36662,1254,13267,5470,87105,58004,15397,10434,159667,21864,52022,179464,3013,32147,31496,116832,18494,105502,129227,107267,50033,13481,9954,24267,22141,16257,116154,36185,950,115685,11305,176708,2048,178671,112573,287867,162328,497663,95170,50979,193861,50987,30368,136257,31830,46549,15119,169876,23788,17462,249887,57377,1949,35448,14791,43769,210091,3783,34612,282103,88380,245190,5457,20491,98908,11402,86899,117916,16028,162584,60644,320177,156096,31065,55876,22e3,77655,9992,23397,13757,317623,63978,215255,2443,17648,93231,27388,104529,93807,55505,140477,12046,112040,70887,40152,94365,112353,25063,114679,266061,71248,119555,15589,2244,617,14129,211431,70110,100652,7777,4383,85911,89221,21010,120615,58357,86405,37554,41647,18,15143,69662,60491,14714,186134,148344,42347,5410,168175,44535,42449,343894,129417,99682,20659,27272,140483,63455,222159,17536,13722,42637,62324,11976,114691,148109,2283,32057,182393,4295,147364,33705,2075,44303,30274,28331,63740,69740,29148,10346,44862,33716,73937,153333,12930,38784,247159,2515,41053,20256,83368,256189,54639,115240,5096,24661,175419,153552,26516,141,138176,63885,34115,47222,55709,2765,28479,38875,236608,12229,22921,77291,54426,45388,2860,57787,114579,295139,105782,17826,71066,19119,54364,69385,16568,12323,28057,33346,34919,124763,155533,101386,31644,8627,49001,303600,29868,63213,9103,77280,71333,9696,138789,37059,24823,5057,21352,32368,114208,56803,19424,10445,58514,8661,209508,26187,171838,10460,63454,14016,122504,41328,21329,46618,32493,38225,7855,31763,7945,29876,8734,6438,24205,97490,139977,130740,47323,33195,85390,57194,13813,60600,21313,96251,7699,27584,170521,139271,1363,4402,336738,129223,84983,69150,13147,3590,163929,207225,155260,55916,20288,4503,8398,98490,11773,27512,37113,84976,86558,28365,11756,116005,182148,13733,115313,47644,67208,85069,9347,14995,226141,14704,101835,41159,35314,13113,63526,214039,29978,50446,83339,17440,129441,72522,118641,97816,24907,73844,15717,118884,167255,96509,162793,30847,36849,51297,78974,77793,10427,1873,2972,9999,35074,28190,64297,146836,46298,60038,163007,108919,61219,2403,75022,127339,4233,110389,69022,9833,128097,88016,79390,222936,22570,94657,28462,56956,38803,81536,30474,152794,19566,16481,147408,74574,81895,20731,1918,1366,76367,187321,54494,24366,21690,61696,33283,107477,77499,31112,414383,74362,18463,218441,120929,59848,258629,201924,69269,454,19989,13054,59894,3623,58908,20681,35723,78523,102680,38988,184112,108087,50944,132704,52966,21699,18860,96349,201411,82697,85395,95658,5093,6427,177894,44191,32755,26961,155739,6249,31310,81030,26574,84311,120155,86730,113535,7424,48888,13516,45747,98098,20077,183995,81945,43210,26704,40420,75831,45648,11180,6855,57927,65528,124096,34851,2598,156633,107572,127352,38169,123845,60142,62722,105584,232364,23211,68120,1601,22169,89299,747,258039,80572,7258,152249,11862,101204,8834,121434,33761,19175,133142,46343,40178,48723,3589,41977,30210,38868,62257,10087,82658,87827,90646,16415,47552,351723,28298,72225,91146,272760,1701,11295,1652,109651,300747,51863,198800,29446,11794,32345,37538,22356,33102,37590,113544,37970,11478,179743,25454,103417,59905,221970,105196,145604,7817,164809,102360,16974,75840,255333,56902,6659,1954,645,59400,67769,7689,18675,5215,13793,20536,27852,3387,29523,259718,16860,94625,43143,29245,15848,233581,22685,63631,78557,22836,133302,84513,1348,51826,47129,98836,58284,1830,1749,94642,10933,6145,12506,10975,13879,103781,144434,10268,28409,32346,52968,121567,107374,77268,23686,35097,10501,155275,15303,47136,21102,168741,55332,90385,15996,84817,681,137803,25054,142275,6163,38175,8056,124296,240642,65621,4934,178205,16101,62803,60964,18230,100622,76465,44689,14545,9543,47514,16852,93380,28048,12047,107106,37575,101485,77047,57326,34819,96137,76916,6469,46264,115983,75768,87668,69942,13027,165,8373,114231,26434,52844,42799,182044,23580,146254,38081,43236,33883,146220,382894,14606,46035,36481,166621,35417,95382,2957,59384,60428,36358,66343,75378,22267,22950,83528,17577,56474,25285,4619,179691,75355,95836,53295,34588,171410,4487,14679,84208,44015,18562,109133,54101,11531,86052,174479,303157,28095,9953,35642,14564,39802,16145,77606,117406,53038,121117,53624,22062,1212,7632,127157,237292,189087,10478,127345,102515,181997,86752,87623,10966,121602,68783,68681,83042,114380,138349,191305,67176,50085,39016,1427,42384,1412,67118,122616,72389,25260,2237,13576,137346,19938,20304,2191,68759,5373,61364,238507,75814,23931,69565,38993,131741,38364,12528,87762,5679,129853,5310,186831,32653,90338,260176,389531,108118,26843,43985,50175,30563,25106,56965,18130,140428,4542,165503,117991,24219,229605,1819,129663,1240,3797,76093,18398,71339,51919,93043,27175,47060,216257,6483,35051,1217,16512,80798,129064,13225,69339,8548,237079,72298,2575,34280,51379,117910,55671,53345,247552,29486,39328,140821,34681,57045,60177,5004,90269,78522,2479,322607,48474,61296,13057,31558,4678,59271,6699,27044,31988,35944,12503,83480,4389,136508,3781,114121,70279,4488,155829,42214,2898,68191,75695,305850,45041,74344,106509,30087,17429,93292,12477,290,23080,114802,35714,18751,26554,105424,17775,2144,2412,100610,65192,113975,52975,180272,135050,129815,76238,106483,21440,63186,4260,46189,9711,28249,4169,23429,23390,8324,141585,63809,67668,38457,38063,39226,59972,1189,203916,62368,14403,16949,61767,85801,1739,40147,35049,76757,33124,62102,15780,103593,103009,53484,22952,67973,114645,6566,5245,50462,7601,8288,3513,194571,80276,1908,54592,5124,58571,2513,6800,273997,193904,1119,17991,117245,2508,129156,82366,26278,71465,63341,56943,39662,106116,94966,156875,9736,2204,122308,94418,27134,1280,24539,49022,45314,3764,50904,46424,30699,28087,293839,9400,33646,40165,822,147499,50263,116179,29085,11863,31314,5578,17797,5104,12454,1604,15342,219206,10232,67800,94261,25872,13565,90339,78971,75377,26649,41184,47695,11514,35369,20767,14227,41953,309396,148270,147938,33074,14453,27499,109019,39018,25738,240196,158931,52820,8612,95853,21524,137010,84901,70869,70021,116794,48404,38771,6732,1070,70990,187297,49140,5238,576,3564,253975,16027,16483,2811,37775,19034,25259,4053,2e3,70083,95774,19713,33431,92703,91314,42381,288770,48194,95985,3991,77418,13406,241328,245086,56533,35275,62725,9246,51924,70181,95331,16163,31410,79016,39312,120878,119371,275987,80124,27712,9186,220,23598,146167,85209,68238,282190,57048,31273,30555,80913,17594,75779,59160,135002,101219,189377,29225,96735,60126,62522,104e3,27620,86814,17240,147533,11001,5425,43682,410,49460,87270,69480,46315,59448,1816,76201,9431,11788,87960,29063,65539,47347,11678,33846,7008,196704,9895,6753,8633,120892,59970,572824,115934,6646,202559,892,48351,37611,251282,57823,67263,57750,26527,34485,90747,7685,88370,6144,64182,1709,41969,21458,62327,181657,49247,225330,122600,114574,107124,85361,111833,63243,71420,15655,191178,72430,18063,51425,54002,12364,53225,86557,18193,97580,41232,138398,67821,128724,8944,233212,101353,52099,42127,14006,120107,32789,32132,3498,18123,33758,56058,5779,128760,59888,98869,18445,84702,51911,13234,218379,20093,39031,8074,70195,20708,23462,24355,131384,60189,26390,10403,41060,7140,10781,49410,42261,87202,82566,41663,43105,60276,2768,5733,74176,28329,2297,145430,131632,83615,122915,105441,655,224102,5284,136426,67763,16294,188511,32538,61049,27893,3394,13951,159099,28542,17930,145360,9492,190122,32285,78855,26440,13570,58648,73908,4239,124561,2444,74172,53131,11468,10794,73566,11623,35343,64710,30481,4163,10328,38309,29901,10538,154377,76132,92405,24839,11679,3465,13449,11637,7824,2337,57754,1260,14458,41118,19878,38661,13416,159180,37074,163164,54137,28627,52134,184900,8520,40385,29546,30502,22386,66527,107458,6850,24022,47983,30603,35083,8934,304066,39500,9,28261,33026,77251,9374,44833,116312,34990,29236,63563,125639,135405,165398,159055,55690,88141,69643,236964,31983,25572,20436,36746,60896,31850,16179,11828,5888,3043,66368,9750,31167,7915,53111,36430,1333,64344,93659,20061,60596,180191,51630,6792,30244,43509,101058,22409,420,44210,109783,43223,27030,72477,72831,32679,29235,7675,47556,12258,39907,149412,84926,118247,24692,71717,105038,86009,45941,41189,89453,29856,52543,30627,226798,67303,59230,67415,34408,1367,99685,16867,128419,52147,4111,125381,117881,16173,44093,102224,31575,23234,24870,83790,127407,239098,3200,994,1255,100903,242275,117266,55116,38205,16140,29662,11307,40414,208793,123355,56470,4862,75600,30119,58218,70828,24075,26974,7802,192353,4851,5475,78720,66596,3409,28573,64396,30381,30690,59859,88256,5406,99945,103064,34463,37727,24238,86643,60088,4057,23741,5967,162904,38240,28356,93858,25510,122879,6897,3278,7057,11971,4400,35461,211413,21395,59615,39471,87233,55795,128426,3051,22470,41950,14705,3974,180108,80476,78442,204996,91987,15634,67610,139015,142373,35611,51134,10387,4353,153456,57749,181039,14183,68447,151532,21107,36452,20551,3186,46247,46383,129666,88736,140662,146243,2066,8360,7978,64818,106963,17896,47801,10723,114821,223295,74192,3293,3393,16987,74064,11277,91622,4270,29828,27951,387869,103235,1374,61988,120083,477,145892,128378,11779,211263,61354,18221,17869,46530,83061,108538,157981,90608,67199,95080,49064,195814,12302,66307,10348,231346,160732,112859,63633,146558,21271,31037,198802,47622,12862,95710,3910,77850,73961,85585,34752,61e3,4082,24595,103679,71107,8208,79568,150019,16615,24961,139857,32664,197366,4559,54735,32696,4126,162019,75698,13916,70108,159638,19834,9349,24675,175560,49643,18206,52459,27992,10809,88865,401975,133172,29e3,34558,30915,3658,25834,42430,36562,125265,18182,10155,40149,97082,208980,19575,60853,90529,66545,9600,789,46420,2317,88593,55595,98980,115302,5742,169155,1073,177901,3472,11189,63711,78643,65472,50459,127979,93,42202,67053,21720,157650,11145,141378,42033,22824,85705,79114,35584,15974,1510,54172,28562,12451,104226,19190,97151,73024,20948,5151,81741,21499,29006,84183,198074,54003,45120,170125,26240,35177,28389,64863,79974,60778,176915,232183,45342,2038,80253,41564,40703,32689,5430,100689,5366,23007,134279,14266,26712,73993,24934,64242,52113,102887,61801,46415,201049,54251,62133,122757,164883,30815,139966,2319,30842,766,13362,10287,134518,86111,81665,82440,28333,43019,18963,8804,161944,23439,102144,101145,80029,39052,248708,30350,117340,11878,128467,974,138625,63961,5237,74778,61834,67040,43814,13690,65947,33809,232476,115258,181745,28824,94013,9510,10246,93722,81976,7217,114383,3493,16014,69045,72692,12145,80981,9507,6692,1620,60820,330444,35474,33962,4797,7053,295463,46445,27026,12491,77988,49524,35675,90947,29114,166705,101385,133782,32704,6186,84595,176031,185623,45966,151302,63069,1699,107491,947,15458,74452,196212,6046,10498,12163,10239,35191,243951,9277,9090,29539,54460,22820,26514,112549,60372,51753,48756,21812,70861,260326,41,44222,10441,16961,48148,138771,216194,5914,52153,53400,212036,56519,26245,10117,45888,15294,138019,90913,26368,43842,42111,23348,6082,194845,161089,156206,51546,11647,30759,302912,262094,8635,78876,26535,35283,54183,31183,85484,147873,12989,5197,6356,72894,65347,20150,27370,73787,1493,45918,12366,190217,20724,13858,10981,67449,81213,7553,14115,72242,271517,11842,48310,88743,143726,22177,3290,243231,58452,62937,12592,1654,40066,33477,13751,9921,128442,15868,7106,75236,83773,10775,36938,10482,170465,17368,17469,161508,32752,98340,800,19824,264456,3901,87319,2867,26782,9630,113102,185815,24197,44584,86366,40224,3636,140916,31731,267731,9567,53678,72984,29389,27963,17106,50282,284911,60170,8322,12608,23374,89652,5268,39044,229766,8869,151350,31436,177342,12269,183212,120418,116270,2843,78888,69192,7865,184099,1086,129897,18383,70508,20242,18508,229924,124569,35749,50589,55626,9884,83115,40971,30671,18135,14452,38861,17844,201826,5549,26413,17189,13561,38539,10679,143331,3314,36785,171194,49685,187713,67506,4618,104039,17060,195080,50648,33159,19238,67559,134840,28599,157523,17130,38064,117398,94355,31918,13575,34538,40326,13997,3494,348283,62481,26862,3603,104426,244363,153709,112487,304612,199674,41239,35545,54869,293005,28223,26277,26899,4533,18518,15492,38587,80488,70485,160395,263,60162,11382,222152,4696,250751,51921,182609,10707,48463,46243,1227,49111,111564,46502,33342,56846,68541,63559,858,139927,16654,229375,76759,26478,33205,95828,23399,92945,2637,35630,28470,143992,50214,14174,21456,166191,65665,1711,21594,78019,97599,111701,36,147151,110246,189022,43021,30397,40757,131935,42065,73335,48039,26596,28984,15102,2361,7421,202167,69744,43766,52826,3642,83304,33873,75140,63169,192389,36551,92748,13039,123959,233220,21738,84447,77230,20228,187852,19095,25799,92136,108774,29237,53947,2299,118106,2687,8830,42331,202924,33667,2023,73763,30704,19363,19779,16737,35629,48081,24068,101013,162338,291912,13749,24745,328289,167679,70086,48299,23306,16732,17801,43322,54589,3586,63653,43624,53474,925,109177,251316,43805,13082,19511,86565,142182,92461,17117,101033,103319,64589,4022,4351,235897,5352,82705,107142,46391,156084,5860,61365,10558,13045,7717,18357,33922,12590,33065,6928,46993,783,46937,67846,8952,26295,6107,119656,18799,17458,50747,4229,179559,112727,118080,20683,41464,125468,51560,49749,44231,7359,35339,62988,136487,67015,5208,29150,24956,105186,48858,6143,18097,6972,16404,73489,58742,97196,36357,164616,5834,32267,13746,147733,15113,132091,34127,106298,39729,106426,22294,9780,15602,36213,71502,42808,66802,599,60755,5851,39120,67363,108623,126368,72770,91263,32486,30596,151717,7951,52002,43103,11768,68942,40901,39344,24037,127500,116890,48403,16926,86750,17745,48648,159545,34460,58419,5634,114317,67865,31462,23352,24010,98185,125708,69686,68337,13610,26271,70691,2980,4768,27225,102402,75453,28106,8104,6931,1176,6274,6475,112635,22498,6176,238686,26832,28893,90319,14441,15682,15087,39517,45270,109134,104440,45965,47645,81772,7876,52683,87720,12898,4505,185665,2769,113401,15664,57592,105229,137381,97059,119268,6876,43309,33886,128363,35476,144249,67013,143587,83367,25703,91436,59347,53236,2289,16519,19844,46309,58558,99834,23313,218816,231303,36388,51333,183535,109792,139277,54306,90139,18235,8275,32710,37677,82464,86025,92204,88842,117723,37570,128723,234242,76350,73795,34896,148247,58424,11105,11744,45746,63372,17118,49772,199520,81902,38004,22911,33752,3125,1995,53792,4689,26909,108150,146062,69674,41811,161444,84855,8999,28561,16731,93937,3189,21967,24890,22943,1356,145300,51569,28802,517,118679,31703,40607,48098,108854,25003,10233,73969,177495,5248,24516,215347,146192,48712,60626,69188,40735,5866,586,101541,6509,47590,52129,5969,222045,110933,25733,24223,65339,62812,2414,155418,35819,16022,78423,43138,20995,128255,240673,46745,236093,72176,57085,97841,61248,107,36068,193177,105427,55726,215229,20446,47228,100420,87091,14429,121708,23605,21157,187721,21880,2997,203976,99166,95068,25877,7724,98925,83401,4829,13182,18229,13718,239662,38653,116505,153497,30589,89029,38962,181302,43853,78872,180301,4786,248240,7401,106136,112590,77745,19731,60880,77789,125748,135487,5975,48627,34084,12419,215770,47557,254582,10364,106495,21856,67539,88981,38805,21428,48732,42316,12149,16078,52808,25327,51322,33850,51147,12253,122354,46077,56483,254553,115417,81834,150991,94662,86668,7381,12841,100650,18218,15741,22372,68294,50705,15535,84660,61887,22553,72299,31361,24824,17743,46820,64288,31582,77006,111674,116384,30760,80920,86149,77192,51979,79691,60342,122805,103800,240873,160744,233114,78962,54920,8608,3484,316104,72548,24337,5088,230040,21926,10172,36838,26,86221,83458,102176,12062,17571,41929,41170,28428,68239,41750,103930,2634,18313,53019,34825,97837,63115,24606,73157,152474,14715,91439,37033,109806,140259,30668,174760,380,135597,95673,136073,65073,134249,13829,17279,122305,4420,46444,10237,64848,203623,70728,10349,182885,65075,24519,25783,40318,34139,22222,63394,55266,102764,41422,20126,65100,90408,53640,35128,48932,11192,38935,96839,34782,39492,19396,41332,6250,5511,19492,51304,25936,104466,54099,73771,86115,5080,7669,30891,111700,13931,25276,72289,135447,14820,258641,25265,31005,281179,75286,393,95359,14623,13584,6680,101227,80173,44933,76666,54542,13244,39348,458,25379,109451,134348,81143,6959,65554,12027,51311,8716,57589,140731,28467,23316,17272,30458,25980,55229,77197,83798,28302,114784,7428,34548,26241,14712,39336,103304,18928,54080,12870,334,87722,15208,16895,142098,114262,39820,83913,57817,28682,7721,14900,108672,11250,62246,42849,415188,1724,26555,24549,25505,26443,107450,145899,61035,43528,6901,60726,65906,267741,21338,147590,42079,18924,73017,135236,15393,5206,4026,84185,1531,5988,113890,82647,303391,7386,69844,71611,189865,76523,31877,13315,19314,198575,32821,1928,67641,25913,104475,103489,3297,70391,18406,15446,113347,19295,93790,27856,1792,167471,116449,8541,4408,41757,63233,25765,86680,64501,27034,24816,34975,6079,4486,49693,36229,16917,21581,62426,27862,11612,54284,35702,194034,355,24277,48262,87411,70504,310164,118018,12516,47559,43502,57433,107139,9290,66533,80863,14634,34312,91725,28606,21342,67241,72355,43244,375789,37402,174015,105070,8342,44167,67494,1890,16365,11723,271002,1865,47918,8350,45564,27742,25110,125803,8553,49504,81925,62211,4534,15491,19011,80373,206920,667,102405,128623,245524,5553,113309,192739,65766,19567,22832,261958,29679,21293,71134,20962,105123,24721,860,21752,33448,18372,157167,94822,35770,173224,232737,75729,28937,46828,28062,25453,5207,140366,36665,30652,6169,67920,150458,92040,23186,184604,92330,20891,176492,49427,27828,38305,42495,143982,49560,25503,90043,29747,65328,47830,12932,11068,77721,9003,25213,94205,140426,46090,89945,138173,192691,33329,112232,129905,35709,27514,1841,19957,31411,127476,53572,17497,173549,55063,175135,19841,69314,5192,237921,117660,150697,4060,273045,50414,98940,65348,153665,164423,58804,156695,48994,213928,86036,28608,8355,39574,34540,16927,135680,18374,151587,10830,53805,16878,16623,4282,48030,8537,14986,46102,13062,72897,72,33050,108227,39451,45935,651,113320,40535,95176,57450,48843,5003,19019,10407,211163,3848,1068,4988,32091,30095,41692,15099,43602,107434,50744,7627,171349,16313,150832,352665,207750,33937,38256,51091,156e3,87889,90663,84175,24908,114900,50365,31494,83829,5398,169342,47521,54818,18935,8356,43094,41212,174536,10082,92550,6678,60614,23355,69721,14796,34149,128830,58187,3179,208,40325,28399,225029,401412,51150,31580,207268,6657,10993,69818,64282,289845,23308,12961,38447,6681,52944,31855,2572,47646,120728,179148,37240,45196,218274,4816,3695,21961,50084,35209,18073,51452,27004,6100,33941,1377,84831,171214,85,141510,9078,99227,32610,6417,11718,49868,65579,87902,73018,49062,46280,61742,21512,40862,107733,15941,29168,157765,144919,14487,5767,158014,140070,7241,573,71584,16921,223566,40331,179473,35081,47926,140885,41508,52104,59180,42310,32811,29048,123517,102413,80208,10104,14746,12649,153641,126022,37965,113017,4171,83,142592,2809,6362,50416,71323,116894,260776,16204,1524,5760,30351,12658,20703,54403,36083,45408,74772,4946,14485,50759,111222,10890,2195,167147,92962,130534,16283,177256,35016,15472,210156,151187,73922,117691,43250,52051,37392,24811,24358,30830,5775,818,21969,1476,127322,151783,58392,31021,106913,65215,89407,90802,28531,11690,20234,95249,44602,37256,18707,11928,5161,4410,26571,51903,49768,22008,25252,65780,209499,68769,203726,13249,137363,48845,86823,6658,5674,31881,1083,1823,108676,34518,166752,13791,14287,91576,91429,8665,11529,26401,16191,91972,30964,5254,28486,54697,79613,66520,18447,22870,45203,194466,22822,51703,12278,76716,44595,73455,33546,12235,144843,36154,51247,11116,33040,3180,225753,60864,1972,28469,12891,28879,10338,144157,56294,353058,38302,41447,87532,110616,27065,168438,6557,1213,50804,144643,24817,2390,136531,38174,247513,16190,4059,122791,131994,137430,39506,57650,16305,5188,54309,106128,20628,88071,67394,395446,250285,66176,91254,1399,114196,43915,60230,44853,27206,106353,43013,18733,345105,226453,51202,16607,57106,117175,35492,10476,89598,127439,15187,39624,13688,61570,10615,31111,59370,6238,175252,32143,224492,41388,95408,34384,148238,78307,38959,9340,160091,61443,15737,11216,41244,170,38299,102443,113097,26382,14027,33707,3957,76300,66160,19431,18900,6952,1717,108656,82206,188021,257335,27295,43999,41210,31777,46956,57457,12657,11489,15697,48060,204748,53583,82422,284790,30503,137341,8120,19615,220311,15991,10217,63424,9808,67431,70976,98221,4491,15177,28535,144789,751,13230,2394,1504,33977,132104,30316,22230,931,97193,185240,24826,22687,174322,15307,22988,1390,188745,180325,29580,59068,74903,18994,29195,79,15436,7622,38462,11566,138710,44828,45774,37768,99236,68137,84083,19282,22698,17134,74807,126662,173497,46248,16938,119735,3212,28292,213652,49013,9975,32180,45660,86250,4801,68788,95490,77482,113751,11994,44624,94452,46839,128497,100316,5798,58588,73184,202987,65417,37790,88524,1606,43156,97964,105717,34947,11203,100060,37742,130074,93653,107799,94311,196106,41347,8035,10780,16390,27883,118236,167395,1979,25006,19375,31628,18916,144723,78502,114047,103107,86492,107686,5844,20934,206963,23556,22591,16562,146333,20167,10471,117434,33085,2863,9740,36669,41849,37271,22790,18209,28979,8231,12952,54408,21731,25130,45208,55748,138120,75826,414,29593,9925,292865,25999,683,123149,7036,92159,86055,61827,103680,23176,54918,58466,57578,13305,5709,86479,16697,31064,17660,200919,10770,49793,33423,32370,52047,16488,62555,6459,8426,83493,7763,59725,82812,18628,67760,79405,68557,9612,7673,28102,56517,69620,171797,32458,29541,15870,81109,32080,207644,71495,21202,11039,91036,61230,2810,130800,32260,4613,60590,37112,75214,33979,126402,155062,30642,63875,12810,194463,82799,47664,16725,36685,43367,61099,449,172150,102867,21691,301838,36745,7130,18671,57316,34852,38034,54182,35578,65900,99486,19771,3456,2658,16914,99866,28390,28109,8262,21147,34353,20006,4228,137085,1675,203023,283196,198286,214375,163329,290603,152574,40471,83506,30068,14730,23177,131539,34759,27668,32178,71896,104799,116305,85430,119262,42860,25160,8911,23428,49437,105322,6519,16203,6349,74711,1230,38045,8540,75165,44736,25909,51026,317034,4984,32281,91312,27060,44431,17817,45363,155937,239085,35697,59784,91993,29531,126740,213757,76560,167776,285273,24262,8237,65030,41160,74437,48804,118916,13159,37842,1031,75349,1478,11655,108777,23435,277425,101734,67469,70231,124711,43532,28514,65526,54956,1e3,21882,17728,25302,40952,52214,149632,1999,2111,3259,63362,89961,220561,39777,26335,9063,10572,12416,34551,34623,38604,24723,5947,15588,69927,66252,119177,69173,46629,28714,70715,212408,20521,406913,74380,11716,50659,50862,37009,88460,130101,7210,53853,538,65120,151950,55806,163748,52837,13153,21100,16674,64536,6091,138201,44837,58547,3723,163,2177,32288,85454,34033,8497,14282,25742,10535,10741,79559,117493,243787,49337,100718,79495,40139,42956,7551,55433,15421,31509,23034,45081,547,61176,53434,328001,8470,36263,30145,4519,74173,53935,11845,73774,60211,78025,3,4102,73782,109293,315332,48412,26683,13714,6865,20128,18490,104141,325,39470,171970,115860,15707,7268,73301,74336,31370,2368,111827,107757,136231,142844,97138,96638,84053,38691,23801,1588,10573,122098,77039,240,186135,146101,11996,18143,112963,46171,155836,348769,47795,121213,116266,132515,3344,144804,31286,99187,255838,129694,35894,48779,55235,148582,71967,65282,15174,13920,47080,6147,108242,157593,125025,7136,1286,28957,127956,28402,98813,20805,7532,109417,40610,5041,32958,15142,18408,108596,33543,50517,27748,80114,233434,91447,487,37094,100048,30541,43477,10639,89862,155868,37667,8726,60684,237903,73408,99589,12190,38739,97348,3914,13594,2680,149016,13907,30171,28343,23530,115225,61104,35821,147679,14337,4297,244282,24085,326976,56428,7851,21303,131620,71446,83253,68692,111870,5224,15813,38197,49026,45057,13660,3306,76345,40671,27905,91072,996,68527,62085,91351,122634,55109,168209,2024,27560,112707,17352,8306,167115,169921,166958,5031,46020,11844,67284,19130,76185,6920,32849,5450,14610,22451,21002,17392,31872,66682,84796,13709,40210,59898,12029,8719,53564,21462,91884,21647,88379,194428,12754,37797,132826,160016,22567,54383,53186,77611,31107,8339,4694,19185,90355,23597,17222,140675,28442,23668,55977,9128,61555,28774,155229,17658,9390,24379,69357,15752,127381,239631,62460,93181,55913,45133,140155,18676,25249,33164,29581,82837,67223,22362,29975,7317,52813,1943,29613,20012,207130,49617,49651,5636,15334,36313,29226,28084,95247,72072,19e3,224932,15811,114,32127,38097,37508,88507,37225,27359,91626,12193,69279,20608,11055,88156,92808,2152,57259,55275,72789,24475,104414,1708,9882,3818,48661,66897,1631,34806,227930,85815,87753,18321,250664,72733,25107,206797,50891,8082,196411,92596,96764,152823,65514,22819,387277,62176,51225,40329,15563,189,3659,73670,64357,51793,275136,33482,86653,74615,67058,11318,125720,15388,22388,8267,1730,102663,170910,40784,7144,85373,13040,7088,94309,583,44224,140424,77439,18496,164026,36578,4722,9151,5824,63365,26510,35199,40500,79277,32495,44614,35233,9566,203293,152144,7097,2330,183480,98629,13423,330887,44130,68600,30939,97829,31012,345465,56747,94879,4939,160027,149761,99423,46099,32251,15332,8761,96094,128555,5763,235318,222223,55729,30241,55420,201746,3987,81382,8259,49325,23287,7719,24633,251100,92311,18591,110533,64759,170260,393860,7175,21144,132887,3593,75346,101277,91109,16387,259187,11627,57459,173829,44694,55780,49797,89192,120443,62622,3904,14814,23887,1027,112258,64955,99800,11132,66353,36202,48624,18158,88481,96882,43059,11040,2455,7077,21651,181159,99126,100434,61388,68186,19161,110468,120052,8819,55324,41494,7014,37689,3618,87729,92615,207943,9823,128657,12587,15857,6379,67628,51216,71775,157617,63244,1503,3864,218754,110864,5769,21492,7243,1192,87921,85529,31512,18537,42698,35350,73510,84474,34301,8991,21013,35034,566,38832,19838,35586,37216,39413,55006,12178,59742,856,84563,6900,25632,17437,49786,30723,13847,70845,4044,7843,23944,235976,55530,48942,6518,20939,73769,192653,52936,95207,23895,132542,142982,22632,87452,48042,54018,178468,10728,26230,23559,363,81269,142012,5718,346258,31456,84333,246476,51018,66692,101804,120570,39962,30373,70593,2864,60541,19425,54209,104092,7201,31545,48018,25865,15442,46257,40443,8328,6451,111782,47527,97754,33046,470,245116,31095,39,91934,87208,73470,36708,36521,12801,70624,36272,8892,79768,12427,55454,103756,5908,52390,62962,22720,141138,94634,41689,128402,126390,6628,106394,35527,134394,82727,254651,194502,148064,89549,3202,28359,957,21954,27906,49840,142747,8307,24206,48978,1186,71728,133038,71474,91306,6333,110959,74600,70387,18983,62609,56057,22970,1147,135850,1321,28834,3578,59715,102227,32827,81415,99952,55636,257598,390,22702,35701,85872,402916,39216,189795,14929,19467,10112,144422,61514,5279,63421,134686,41436,8424,51925,10598,132295,124416,4604,194739,210929,57866,31829,51626,50007,9976,91878,61906,56168,81906,60918,61859,40017,23059,16887,40927,62064,12785,32893,32913,21782,93965,20169,44387,79084,38463,11457,93950,27127,157050,2697,337088,5116,54128,48255,33279,8821,27352,25515,124022,65710,28906,38557,33390,1722,104435,72215,38551,12094,30978,25113,6671,37355,175109,42862,98024,65406,221276,59624,118012,64637,78760,86697,21426,1639,40350,12584,67193,84144,31396,7863,143011,69629,63112,9454,28666,65798,46372,134721,6314,51402,30837,151922,2847,38676,38008,92823,136245,17540,5504,109295,205242,37606,5211,214892,1586,20670,208711,137743,19328,40652,16995,20023,14657,154919,34422,12996,13918,38221,47690,16398,2959,37680,89122,6721,198469,91876,172043,83898,101992,26084,94570,3635,76958,22853,76497,38266,176590,168403,44464,142840,79180,184594,1984,41806,83147,11985,6546,366068,59732,24533,271505,8736,39084,222992,93429,28962,58985,86665,8432,30028,14548,32439,54424,165029,55175,27458,69046,121277,46168,33732,20661,24581,135574,123110,37556,79260,72611,16957,12939,46162,58238,44907,72936,253758,41324,32518,96480,11949,124438,65280,43256,34107,53533,43531,37037,28366,45970,32741,173438,6121,194202,62969,26355,30314,58370,28455,1848,50519,82830,90393,21761,295490,10936,256940,133568,44050,20269,4089,27457,21610,219460,36743,14821,101388,52005,13124,30979,140816,167362,26054,18458,60789,34917,40447,26606,33422,9066,3452,83614,5761,20263,137238,25038,91310,101,52322,74548,42572,38084,214054,186568,31802,17665,30620,141936,37730,14420,4265,187218,49640,188208,51441,55388,96452,66659,40869,42039,60967,221027,19234,178581,29105,96050,9165,196118,157335,3738,40354,117436,2965,34136,59659,15570,50843,230035,31444,71260,43886,18316,5387,38500,168508,17406,32174,8828,103373,143806,90367,3560,18719,122310,16508,26719,2541,105429,6645,37998,73190,10591,235916,49737,87112,233941,53188,32193,79154,4544,52905,126477,7580,63501,57314,3216,31337,6541,103083,60846,49,9756,15481,1355,43840,14319,13743,27486,10222,73114,230718,418644,16706,6674,279748,23058,45273,295831,86306,2743,5535,88773,21829,35253,120938,31153,3169,16839,42847,8751,80974,33942,36867,35514,16485,26474,77775,56877,5391,48346,3882,108713,31403,27804,55248,26235,43821,136104,40118,175507,28034,203908,18732,1788,34030,106427,36958,54359,7251,44936,15356,69139,455,157915,22173,140291,50348,43275,82066,49621,54952,15216,36226,96695,66855,6936,1987,8227,196087,4631,68827,99004,47541,110265,17953,147605,110242,58520,31312,38724,329975,642,3155,34497,75937,6207,73843,6120,17249,51429,117746,3218,910,68961,319671,14938,29555,34700,1649,66673,72268,9655,76800,153087,6941,210168,27130,35398,1780,73242,3135,56689,19556,165307,8765,35967,121458,13333,70453,17350,117253,22265,13340,44265,39869,441,3742,135025,23581,33309,16543,17731,13291,157637,283005,21408,101360,63887,52312,83873,5338,233779,23759,186949,34531,177320,38069,156465,91004,19353,59852,68160,14891,1338,1072,29823,1950,28901,81407,313445,73038,84807,162348,240257,37162,138934,16111,58013,41253,102951,16457,96056,19541,56402,67217,41638,94381,89674,29481,37456,80815,151579,13937,13683,132537,19699,134545,67020,29816,222341,141235,427578,48868,129557,233342,23077,87871,16213,18728,16184,9469,37913,19680,2798,171356,178328,13216,50049,72690,71904,124644,55455,7504,29052,41036,266546,19899,30391,188755,8659,59469,16,104298,112943,53865,76203,138226,68857,139953,14125,107625,119795,173133,4398,50273,48808,54390,16466,122086,31835,67035,50971,48859,7508,46427,66477,73021,84615,39985,83076,46779,201569,53336,36443,60865,168164,143810,51393,25548,169307,32896,24485,38424,21837,29087,275813,51674,6714,64883,46169,187369,55186,76192,12852,12018,62134,31067,118303,16542,12125,10579,4928,26291,43854,7091,10946,253716,109062,39283,17261,113012,258512,47764,125126,32646,55892,80279,201623,149872,3192,385,1208,48750,5376,58738,22335,5427,82416,47811,32435,143086,38930,94128,59975,156037,37977,38224,62485,7698,50405,71027,16462,21559,136153,34131,107506,162069,63703,3101,215029,40407,4178,3774,9187,80019,17880,97926,67579,2600,18405,8351,47924,86638,70820,92206,86453,29610,42241,119200,3198,15466,67813,57863,35454,4779,99518,4649,104641,144269,33730,38073,65864,6838,109456,193298,154007,5623,45741,30846,182578,25573,157224,1543,58575,138703,146140,44971,49356,18275,59064,20300,13122,11848,24453,11973,9797,86843,2919,25530,49210,1130,161220,76788,75373,85604,34926,36014,17777,17255,51533,11676,92226,51845,119859,21525,5936,18507,28050,1140,31418,14857,34207,47859,10750,36382,32079,106909,59426,87757,38393,110042,15965,97104,33757,35344,97993,53979,33651,45407,41884,82515,173089,7177,58371,35365,47543,51927,35587,10670,23544,29306,84233,39976,76076,62097,9007,8668,28119,78281,120790,19835,143020,54968,18670,64959,20649,34469,42570,33001,136570,87796,120044,1106,58700,63951,127623,12805,83057,40212,31773,49850,7361,54336,347524,101314,23751,19569,48791,29174,49369,20467,7465,75842,38281,623,112457,60210,28849,51003,94720,6426,90047,85560,43761,3579,85105,34607,90410,118528,7224,42907,111163,18168,6960,161135,191298,5247,100584,127552,171568,20121,91173,12636,54615,20199,63730,98105,2396,40387,14438,125012,4765,33235,12865,45299,37728,82098,77872,114037,59253,19675,24838,398016,102561,11446,17069,57508,178277,65836,99941,26114,2585,271882,136866,50126,11027,155648,118367,14585,8910,123015,335383,40434,41016,53021,14439,87098,176860,201543,121888,2358,9286,5739,22666,54270,37884,169381,33984,93859,16124,89364,72207,51639,76366,99029,65812,2198,12147,174891,194289,6986,30252,88822,21284,11445,288337,160821,33034,100869,43852,25761,52882,1144,103809,1924,84458,86079,43411,13542,139276,18141,34978,41298,7276,26481,173800,33210,17951,142652,33616,33677,2210,19941,98568,2486,192414,80136,12058,235883,50963,249638,29572,27221,47034,6124,72107,63346,97620,158513,299699,40388,23235,37176,224244,198386,121323,67992,23827,63170,17838,106622,158590,26807,5345,23489,91891,55474,74834,37981,13058,5977,72552,34706,26828,145172,19904,21367,34043,960,77092,91381,4733,47446,7680,41697,5170,16960,14741,46101,13656,473,51842,37433,11103,11551,121951,13191,97536,165932,50397,51628,129028,9069,44885,6590,59195,47045,32940,225472,90345,21833,13303,29407,96615,141951,5198,6028,18395,7181,3861,14966,156358,167182,36529,55253,25942,173153,30959,27261,50691,150176,162201,38467,48462,80602,42163,118482,168,108756,26011,17166,54149,456538,22512,91374,13816,90358,131615,18132,226707,1824,28139,26860,42253,93877,77351,65575,8980,80574,22020,27948,40422,91324,76376,13528,39281,91685,82215,122541,144066,1983,193851,17283,26320,2739,194978,4790,26845,42627,61300,65815,174612,55133,4200,191130,79771,158321,52280,166796,221620,62461,11278,4067,88152,83409,31717,121367,13522,47325,37945,10406,174348,249321,154101,64912,29938,51775,17220,15776,166138,78890,84425,54121,42861,16368,24572,291647,10197,32073,22651,11677,97509,26952,35787,18424,41910,71614,94977,72318,41594,70024,275419,37702,60199,7335,39107,61315,18271,18394,33768,87884,104277,123724,7277,56288,71981,189803,49320,3352,6798,14240,8954,69220,94433,57372,28620,68863,193727,85575,42309,41667,67689,42081,22543,44824,12719,28540,114236,101553,27638,27296,4300,5353,4663,19379,94098,3758,95888,95144,80344,87320,28447,259518,12718,71391,152731,37063,24132,31911,104896,15672,103782,1521,4945,72541,23717,122632,15619,87175,206120,29428,189780,61416,28350,44457,972,1175,47233,198738,95789,41907,21953,97034,59341,22864,53713,16873,32971,20693,20954,31336,21477,16169,38370,16412,9019,3841,24599,21938,17085,6484,81198,76413,5849,72514,12320,65247,276175,37234,59796,52642,16312,57349,198507,94148,46134,18958,125552,1747,18725,151873,14901,5490,68287,29470,3689,64794,40814,26018,25692,54450,2703,88278,124886,173087,174e3,24159,179477,24276,46004,201876,209202,445,52876,31948,30206,157610,39180,18439,44124,50469,5774,96278,222758,200216,50290,45486,20435,46986,46276,140133,142326,15569,13363,47522,92583,2182,7135,16853,22998,30272,4952,63263,35623,39096,53789,44864,20053,110392,124213,4630,16087,28221,127787,25839,77481,44693,13464,113146,6983,27069,55717,50102,4760,7107,26186,66507,59145,36032,104182,71328,29425,64317,50781,47465,94298,69706,74899,22754,120756,25108,93077,56834,73286,39928,16218,41699,176763,7555,70819,50083,26895,23315,26014,16773,123079,41712,5719,31516,90427,158540,85051,183128,40864,27505,55392,9058,45224,96857,30901,136622,96557,56304,120061,11501,151448,5773,89743,7769,86069,2935,18471,41628,10114,33660,110170,49479,26745,92846,33221,26731,18795,87076,8550,2100,29972,120289,3077,72490,33784,2630,208722,50861,63483,79029,6419,39467,14302,45286,64207,9686,67513,44170,1050,77246,59266,17055,53801,7150,11111,42432,4278,94579,362117,36175,42902,41933,39002,98489,22913,74161,84773,57036,17556,162288,74485,178760,93867,73635,128860,50362,261,67455,80001,46080,35662,4368,25247,19230,74393,22588,1822,27682,235324,13798,85998,13194,235067,23514,71669,147632,23191,134748,214683,105101,1518,25489,247114,7380,54842,26922,3971,26361,20844,68642,170517,77339,123255,8963,77818,150998,48466,36806,2732,23261,11741,236162,18243,126216,28690,50546,16385,92760,197383,246558,201295,88255,67588,71687,176076,172653,169058,33906,63747,24835,157621,43338,30050,46152,132741,2770,51371,94835,6614,15112,11749,56936,1250,19027,399017,58036,100215,23388,55815,308768,124152,94803,9521,64186,8971,28,30427,62163,7616,103838,35079,29203,131235,7743,17389,10882,37420,61460,228512,85363,41581,131077,62822,119647,10130,54445,26925,19968,29016,24446,74028,24176,61448,67185,9254,8563,119129,9771,99184,37716,39514,10532,221512,258753,218630,55980,23394,32141,61924,66749,32411,3741,36475,26678,77010,44946,91203,128749,116953,20476,49625,53116,13735,102335,29376,51946,83407,67892,59212,34685,21083,1546,112982,32972,74397,1078,190545,16082,86140,58591,89611,101531,10061,105104,76319,20035,17551,52611,169061,190842,100780,23907,90413,115619,9675,34710,193435,49443,129734,11183,258877,16318,136182,126808,44635,27304,192375,2599,125648,47051,12091,23814,721,58800,40137,66726,97930,60877,74487,7942,54326,9841,41428,13762,8211,85383,6950,99177,79806,201786,296464,124087,13144,29741,41721,47634,55088,254286,106408,17041,99064,12942,64086,45233,14005,2612,55827,255,7984,13980,38574,12776,46654,73499,249951,2101,26676,25996,132326,116415,119062,50449,31033,23038,11589,179252,20007,14860,129270,21143,17796,144715,60106,70758,69842,34674,282133,44014,16774,57268,38528,24053,46373,201667,28327,471023,51889,102667,21193,114909,84132,69317,96723,67969,16134,68145,15058,28765,32035,2524,101089,98664,25045,76571,14957,86040,118506,262428,154764,81573,39681,283900,73287,127825,544,80448,52347,38512,175971,15180,45467,33086,46552,48894,81107,43213,36672,54025,76703,8053,7608,13299,56619,20752,238099,54164,105133,1444,32942,953,37564,8e3,66316,119463,106817,404,13667,149108,128597,31267,10269,49836,106150,1484,52330,76965,160486,171648,38456,31263,22424,37738,66245,67467,143369,60471,75610,20895,115528,86070,60854,40796,49347,18989,15030,11371,37578,15779,79867,10187,86462,46402,155626,93200,40229,7090,57547,108053,99598,11088,47505,41218,206017,2173,20988,30219,22919,80563,57566,42369,93141,41675,2407,182519,120495,27154,16702,29456,14349,7958,16688,117177,140375,42467,261919,74916,153569,10836,34742,49526,7621,105997,12212,2270,392377,7755,17959,25086,232152,138791,33847,13860,35316,5811,1344,71259,50452,207539,92635,50359,5821,33674,30255,2086,2587,96264,17543,42,6029,9580,43007,139248,82831,12917,29607,25786,51467,42137,85161,100698,31561,88989,121990,278500,3602,109344,37982,15279,116442,28936,30880,87894,58079,128661,126731,67392,28051,146885,4861,16216,97344,42827,147561,153948,22684,21335,47685,1853,43349,15185,59642,10229,25520,187921,108972,5579,98037,24945,6697,19193,63734,137934,75056,89740,19767,224268,56138,63643,151661,39313,70618,84031,89723,84074,13703,85626,35460,8867,64845,3439,57906,99776,63968,49270,81130,34356,16210,23547,36446,34090,140028,72439,2221,22163,57058,363492,113754,18913,95451,48663,54464,54037,176097,68425,3023,34906,29482,117389,341780,80431,58330,16753,92616,60907,94846,147486,4498,48646,7773,46801,7778,18946,464978,47558,33223,177444,7328,15626,63337,94700,11743,9351,255024,39098,16447,42647,96230,39769,58840,10068,63439,35800,65843,58823,413844,9156,51258,7434,61791,85018,6872,3692,28096,7121,33024,6009,75532,31997,192535,9661,3304,9547,14753,31987,25314,55689,15896,20430,39472,31340,99744,25398,115569,54883,28719,205423,23071,57855,64638,149867,25671,82403,37616,20668,39989,77996,74948,140555,175248,64810,36515,46595,4958,248773,24045,28728,136673,168704,20804,114833,100325,27135,21205,96151,153134,45992,7093,13992,76047,1980,19432,145001,75159,87462,17710,1013,45556,34297,144882,20648,26061,11319,129567,108555,18872,464580,33386,22717,65948,167189,5603,135042,79542,8801,202632,18114,91882,5973,5239,67315,4431,60916,47819,71693,32597,32606,18183,45072,80329,76385,24749,51305,40314,156514,14693,130345,13168,66214,18029,12858,34801,27628,14544,10823,40522,40185,33739,148694,23548,9923,61012,28859,17933,19442,34364,99849,164107,141167,30629,21054,6744,36491,8096,42474,41706,155060,30650,10600,163442,1143,96655,61390,52359,7559,51568,64256,203854,4467,22453,14504,436398,7878,6980,8293,63610,293747,16167,35763,19627,147603,15419,18032,110744,51346,33681,54571,40472,48615,39073,21604,13754,173027,92560,11083,47299,63062,11813,52007,29883,9734,139722,15953,1550,20651,13616,49306,16113,90089,92326,7584,30712,72424,164858,6831,152871,55746,197721,34167,196442,6022,112107,55215,7538,123381,4920,43539,77165,8939,50392,34192,20225,79762,22505,58667,40770,29788,97180,82835,4568,8579,13273,363569,35898,49983,436,36598,3237,131691,62418,35591,8101,4073,379438,65218,76072,33887,2968,27573,212619,288680,68278,72851,150504,217896,6913,121339,22017,35340,51072,43616,75043,31437,10833,81487,4364,22968,41454,106687,85446,19863,109625,149241,524,141850,214404,54376,657,237023,9401,108137,53800,32474,49712,53334,126876,27337,45552,177696,8269,15036,12097,42240,2328,125374,119295,99715,2500,19624,39441,27220,102691,60957,94543,39101,18566,67362,13975,78230,25017,34017,239007,90027,39351,41681,35354,43822,1043,916,58587,141983,94818,38799,75459,41114,67432,16195,36606,59568,22272,126769,31424,68659,12287,134302,257977,5756,207285,95637,47248,117689,19583,77451,22373,12200,54993,117118,34244,29386,34562,53819,71267,64172,77665,49368,7716,59301,25749,45426,194789,17297,2650,1766,32501,45198,20403,20984,6600,14171,94604,19037,5402,29896,9938,59935,109708,88081,145182,44844,39167,352626,164173,35374,45982,6122,154,73419,220487,53834,53601,17992,8609,229321,5610,68098,66815,71012,95069,140968,27396,8957,134489,24656,86659,56598,134852,17316,123838,255436,6613,41610,138033,81452,32023,32396,123687,63398,8693,29712,30407,19296,121188,3551,36099,20032,111948,56624,16547,27453,35916,15378,52039,56849,13489,22214,73177,53097,277349,2157,14029,187886,10260,141743,246460,91880,50869,3788,49486,133566,54950,33120,129337,53768,18333,9525,26902,312251,10297,9020,70759,16647,112432,59260,84609,9818,82766,73569,468,46001,75780,55028,52106,11498,43645,108069,17150,17753,29417,16705,31799,9606,289,122254,115975,8620,6133,255357,56908,14456,133464,43554,79224,11247,29630,160,12756,25464,65960,350428,62521,321796,100359,67358,35169,46172,113128,48988,88868,31094,33266,6847,60887,98188,49659,69117,92977,220228,13947,80181,35103,62170,97351,13475,2440,199768,19498,36597,46971,25234,67806,62881,84717,73648,181966,10488,94149,21550,26655,63436,48375,14405,165650,9621,24439,28043,42735,4490,29963,56674,45373,1934,262446,50855,67098,26898,5261,52696,40644,33900,9440,180286,87162,22940,19704,26936,69769,10254,101759,27406,12243,48e3,73926,113215,54935,5726,192787,4312,106216,9366,11550,52949,23457,212271,277152,133895,108374,6191,96477,29980,218916,58024,54696,40853,91124,65894,91170,65908,252552,6793,29212,15389,44516,122515,52617,35058,9017,103536,39510,49136,19242,130652,662077,74699,47024,31422,8517,73351,24399,13867,128360,4810,4434,61779,111983,61036,17798,110240,59722,102960,39688,10001,23803,23039,176498,56659,44814,134295,17188,77577,74466,226175,102472,154333,63900,111747,18062,41171,79669,32773,408933,42562,28931,30907,107388,43487,2946,240310,23938,24354,319,184983,7927,6488,1422,10790,68809,68209,64775,4361,202,17123,59634,51200,44391,18188,17843,2619,74278,3230,9540,47187,21702,36274,56894,43907,16310,34790,16866,6150,5561,13587,107545,108873,126867,86986,28640,33427,19017,5762,80637,17430,46903,2047,131055,25958,13558,5444,47152,13900,44563,122857,45348,70863,39593,54332,38068,33637,318,40310,143467,18502,24520,11377,62013,28942,27246,28269,83545,17999,59015,90707,30065,15161,34720,1263,37008,2012,6060,98575,92933,5721,299,199555,24578,29223,2985,743,115825,109523,136657,47454,26378,53586,3733,174945,93340,244456,5693,37386,28782,89767,27545,23573,18798,136425,34320,84778,20041,48453,38215,7477,71958,40621,8773,5874,187927,105965,51100,43533,18083,8443,10180,43597,2003,183999,69689,12216,129696,146188,62389,34044,68410,12765,43273,26949,266807,3345,34477,79197,5688,47539,213110,21634,22257,50092,32222,42346,39530,63668,98,134978,74022,5152,59088,174145,37220,9934,9545,118937,5724,87240,19875,15784,40143,23263,87513,181654,285152,37881,263241,4966,43934,10433,186657,6470,74416,225854,25908,142677,246262,32280,6192,75890,45546,143264,135305,29742,47013,77787,11732,126658,8763,37950,21806,57557,113464,89465,108995,164574,23894,22996,23169,15369,23117,17642,130607,40503,36239,280990,44666,9981,40427,147487,26869,168452,32886,32991,46798,240839,15111,70502,65697,88548,44145,28701,48767,31139,206777,35659,181164,166262,14554,171445,31786,66523,76607,17956,6507,31279,90476,116611,167918,6560,1243,115324,80128,41867,55897,187323,37069,32596,189444,145931,13390,105530,65709,26805,6999,55714,41300,22915,68951,22138,21120,22264,10058,19945,33635,56123,99085,10032,5818,6016,46649,57476,35264,94413,112522,262288,93686,83038,14341,23204,28807,66084,77987,6101,126673,7133,38126,5923,122091,170240,97772,46874,215746,43948,41622,3272,55596,8332,146411,251315,13533,8561,81521,115449,48616,175175,2063,186556,3036,134537,75772,29728,82360,22973,186559,86348,89100,38388,82297,45610,2613,87082,9986,177812,57884,23591,47485,42543,33582,44713,74439,257444,252451,31825,35631,38540,33066,5147,13973,4343,51830,70378,22827,26448,95560,36896,241741,48067,203953,298860,61620,20450,3220,67272,6586,107662,100160,108684,6929,57226,4762,7457,1320,40404,77204,99309,62750,208653,59977,44e3,74315,34332,5819,172217,64904,114077,18147,84012,1791,98456,90930,21446,116669,103938,7422,85140,59713,5768,326211,16239,75411,13229,29398,10758,236107,1539,112472,95979,152154,151294,306,21196,38146,10700,6891,84282,109646,56492,40539,6589,119491,51354,30685,140209,136906,29622,73617,49553,70525,51671,166869,139616,74395,37439,49595,45678,11959,33211,86560,52434,9282,62690,112155,130810,5243,108261,99970,265613,72551,80049,6391,33365,90721,66737,69872,87011,1860,9032,112544,60905,37371,89015,140351,19076,850,373531,2802,36725,218795,72062,28990,16550,24614,7815,6187,26336,33373,32162,42791,73555,32062,23386,10244,56392,49442,27076,136262,12412,14883,1134,33675,97153,199281,15608,100152,74072,47942,254301,36451,16026,10687,65067,56708,254030,30290,50490,13864,57941,259331,35588,23485,43486,24869,21620,92971,22072,88645,1048,182050,13343,32452,14825,19509,3325,216938,45740,99716,189082,53740,78245,25609,24311,176777,47340,308354,40669,66085,14102,125339,9225,128709,97207,1271,200933,78439,113451,88975,18324,46521,11819,18570,141756,72512,170020,52754,63550,118515,103073,93330,32736,50499,14722,31600,68452,398867,29316,172786,18417,104924,2606,5670,84818,16288,67106,59580,82929,607401,291,85829,359,15897,35830,50696,65630,52672,22115,356968,29895,40837,231192,34024,38957,26722,406,23335,124952,72068,68804,13268,147101,164740,276569,162596,66943,11569,26654,66358,4777,23229,102127,5848,978,2921,59666,5371,28212,90108,42938,39320,2499,4271,108792,33510,125072,71653,65239,38250,66357,38577,13964,86251,35708,50755,36010,29448,12209,3844,38222,206337,100876,67827,137088,14167,252225,84163,195270,1306,5703,54198,779,46802,22028,51124,86759,70560,113164,35685,162145,45471,34561,422,2611,6464,47486,19223,38246,9191,18331,89942,243642,212364,15893,17518,22617,6409,30046,126182,59716,36560,104428,18846,26592,19458,50793,147333,30826,1388,27647,10922,14495,33545,19269,135828,39727,41601,46931,233379,49169,131130,182112,16276,82381,118209,142445,128310,19672,28740,82907,33436,3118,102206,28723,24819,41937,38854,5157,3881,111491,1142,9776,421673,152241,29309,14961,87854,6054,15424,3796,82656,54996,2108,55367,239450,154525,9643,118103,106041,64601,68549,48707,30266,25772,18740,9462,229669,91798,112152,191327,14493,72828,8175,66636,236474,25817,87351,129027,76653,20422,22983,71240,27846,44661,12399,46158,77704,53101,35032,11072,17300,109294,33638,24408,1895,11241,760,17584,82479,125877,63150,141075,34259,23274,81698,15732,43577,48340,91584,14688,16379,24481,150280,96420,262050,48635,43727,61819,56268,72003,88178,17281,79912,13218,122519,125295,166396,11811,2171,118930,67746,17636,178278,174656,95661,173039,83845,79689,17473,98555,127696,203415,54730,22925,232239,9309,12136,175026,20740,180188,10747,39816,314017,266131,10040,175732,112550,220651,31974,37393,888,23008,86799,4303,64905,148467,75337,251,3284,370102,50264,9835,5438,23655,4481,29851,329,12855,7162,64931,78141,12804,42372,296771,83547,18624,34874,86271,3360,48665,77735,88767,11463,63527,28889,22258,29140,194315,113924,25499,6406,31334,1845,4802,49184,43455,35469,127594,92970,61038,115005,38840,87761,106838,8811,20572,55637,11162,96721,132425,108925,2948,125457,36356,3502,75270,27622,127192,2561,123095,49394,61155,16897,110064,9699,89448,53356,19628,220310,21622,83036,9885,112214,6087,26713,17901,161912,91492,3440,68594,9266,92238,8087,6866,150194,72175,80701,13459,31836,43243,239700,95846,44749,50647,21945,230538,120612,132371,244604,5193,105637,34661,41341,68775,85393,1874,8771,33718,49672,77403,595452,99507,6490,58895,128742,7704,39239,73217,43816,62824,37804,199976,22361,80005,87514,94832,14089,4574,139975,59142,75523,100268,43906,53442,15152,2547,186002,17011,19513,204282,3343,60568,128318,119250,4298,51871,41336,71759,21921,45074,98169,145889,99427,11350,1237,5520,28799,7803,53702,21026,136352,38293,128690,12158,90132,44600,10184,26957,39459,126025,78904,82999,59373,39301,150198,120529,153042,20177,50089,14764,271571,30530,123161,38975,101562,22941,5648,124654,109243,69817,71675,49162,106884,21241,107795,30258,16572,188262,141456,7688,60718,8271,11044,32440,104608,103419,236109,93156,43293,128929,42107,67180,25201,115254,185488,130954,72813,167547,20537,39969,38432,22582,184022,1139,27199,5655,17767,97412,122606,209377,27070,35871,326617,188954,42680,73512,80911,22629,3011,95021,315242,157737,383,41821,41808,19335,27950,15674,25677,110950,35375,76835,59108,57370,35262,16569,160415,37706,78086,32041,49691,137143,9782,172080,50148,77917,6323,10110,69172,17711,21795,59511,76184,135114,31046,132319,59105,157578,20549,80778,57649,158421,65143,4575,72235,21899,10797,92745,34035,106079,80159,4508,78304,25350,75457,46458,32937,25623,47,8531,104751,84953,8138,36508,187199,66310,115274,13253,32461,38536,1916,42007,187160,35055,26325,84394,35963,94216,45590,97782];class aU{constructor(t,r){e(this,"log",void 0),e(this,"peerRouting",void 0),e(this,"routingTable",void 0),e(this,"refreshInterval",void 0),e(this,"refreshQueryTimeout",void 0),e(this,"commonPrefixLengthRefreshedAt",void 0),e(this,"refreshTimeoutId",void 0);var{peerRouting:n,routingTable:i,refreshInterval:o,refreshQueryTimeout:a,logPrefix:s}=r;this.log=t.logger.forComponent("".concat(s,":routing-table:refresh")),this.peerRouting=n,this.routingTable=i,this.refreshInterval=null!=o?o:3e5,this.refreshQueryTimeout=null!=a?a:3e4,this.commonPrefixLengthRefreshedAt=[],this.refreshTable=this.refreshTable.bind(this)}afterStart(){var e=this;return r((function*(){e.log("refreshing routing table every ".concat(e.refreshInterval,"ms")),e.refreshTable(!0)}))()}stop(){var e=this;return r((function*(){null!=e.refreshTimeoutId&&clearTimeout(e.refreshTimeoutId)}))()}refreshTable(){var e=this,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.log("refreshing routing table");var n=this._maxCommonPrefix(),i=this._getTrackedCommonPrefixLengthsForRefresh(n);this.log("max common prefix length ".concat(n)),this.log("tracked CPLs [ ".concat(i.map((e=>e.toISOString())).join(", ")," ]")),Promise.all(i.map(function(){var o=r((function*(r,o){try{if(yield e._refreshCommonPrefixLength(o,r,t),0===e._numPeersForCpl(n))for(var a=Math.min(2*(o+1),i.length-1),s=o+1;s<a+1;s++)try{yield e._refreshCommonPrefixLength(s,r,t)}catch(t){e.log.error(t)}}catch(t){e.log.error(t)}}));return function(e,t){return o.apply(this,arguments)}}())).catch((e=>{this.log.error(e)})).then((()=>{this.refreshTimeoutId=setTimeout(this.refreshTable,this.refreshInterval),null!=this.refreshTimeoutId.unref&&this.refreshTimeoutId.unref()})).catch((e=>{this.log.error(e)}))}_refreshCommonPrefixLength(e,t,n){var i=this;return r((function*(){if(!n&&t.getTime()>Date.now()-i.refreshInterval)i.log("not running refresh for cpl %s as time since last refresh not above interval",e);else{var r=yield i._generateRandomPeerId(e);i.log("starting refreshing cpl %s with key %p (routing table size was %s)",e,r,i.routingTable.size);var o=AbortSignal.timeout(i.refreshQueryTimeout),a=yield WM(i.peerRouting.getClosestPeers(r.toMultihash().bytes,{signal:o}));i.log("found ".concat(a," peers that were close to imaginary peer %p"),r),i.log("finished refreshing cpl %s with key %p (routing table size is now %s)",e,r,i.routingTable.size)}}))()}_getTrackedCommonPrefixLengthsForRefresh(e){e>15&&(e=15);for(var t=[],r=0;r<=e;r++){var n;t[r]=null!==(n=this.commonPrefixLengthRefreshedAt[r])&&void 0!==n?n:new Date}return t}_generateRandomPeerId(e){var t=this;return r((function*(){if(null==t.routingTable.kb)throw new Error("Routing table not started");if(null==t.routingTable.kb.localPeer)throw new Error("Local peer not set");var r=Zl(2),n=(r[1]<<8)+r[0];return zu(He(yield t._makePeerId(t.routingTable.kb.localPeer.kadId,n,e)))}))()}_makePeerId(e,t,n){return r((function*(){if(n>15)throw new Error("Cannot generate peer ID for common prefix length greater than ".concat(15));var r=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(0,!1),i=65535<<16-(n+1),o=oU[(r^32768>>n)&i|t&~i],a=new ArrayBuffer(34),s=new DataView(a,0,a.byteLength);return s.setUint8(0,$e.code),s.setUint8(1,32),s.setUint32(2,o,!1),new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}))()}_maxCommonPrefix(){var e=0;for(var t of this._prefixLengths())t>e&&(e=t);return e}_numPeersForCpl(e){var t=0;for(var r of this._prefixLengths())r===e&&t++;return t}*_prefixLengths(){var e;if(null!=(null===(e=this.routingTable.kb)||void 0===e?void 0:e.localPeer))for(var{kadId:t}of this.routingTable.kb.toIterable()){var r=pI(this.routingTable.kb.localPeer.kadId,t),n=0;for(var i of r){if(0!==i)break;n++}yield n}}}class sU{constructor(t,r){e(this,"peerId",void 0),e(this,"providers",void 0),e(this,"peerStore",void 0),e(this,"log",void 0),this.log=t.logger.forComponent("".concat(r.logPrefix,":rpc:handlers:add-provider")),this.peerId=t.peerId,this.providers=r.providers,this.peerStore=t.peerStore}handle(e,t){var n=this;return r((function*(){if(null==t.key||0===t.key.length)throw new Ja("Missing key");var i;try{i=it.decode(t.key)}catch(e){throw new Ja("Invalid CID")}null!=t.providers&&0!==t.providers.length||n.log.error("no providers found in message"),n.log("%p asked us, %p to store provider record for for %c",e,n.peerId,i),yield Promise.all(t.providers.map(function(){var t=r((function*(t){var r=zu(He(t.id)),o=t.multiaddrs.map((e=>Ir(e)));e.equals(r)?t.multiaddrs.length<1?n.log("no valid addresses for provider %p. Ignore",e):(n.log.trace("received provider %p for %s (addrs %s)",e,i,o),yield n.providers.addProvider(i,r),yield n.peerStore.merge(r,{multiaddrs:o})):n.log("invalid provider peer %p from %p",t.id,e)}));return function(e){return t.apply(this,arguments)}}()))}))()}}class lU{constructor(t,r){e(this,"peerRouting",void 0),e(this,"peerInfoMapper",void 0),e(this,"peerId",void 0),e(this,"addressManager",void 0),e(this,"log",void 0);var{peerRouting:n,logPrefix:i}=r;this.log=t.logger.forComponent("".concat(i,":rpc:handlers:find-node")),this.peerId=t.peerId,this.addressManager=t.addressManager,this.peerRouting=n,this.peerInfoMapper=r.peerInfoMapper}handle(e,t){var n=this;return r((function*(){if(n.log("incoming request from %p for peers closer to %b",e,t.key),null==t.key)throw new Ja("Invalid FIND_NODE message received - key was missing");var r=yield n.peerRouting.getCloserPeersOffline(t.key,e);Et(n.peerId.toMultihash().bytes,t.key)&&r.push({id:n.peerId,multiaddrs:n.addressManager.getAddresses().map((e=>e.decapsulateCode(Tr("p2p").code)))});var i={type:ML.FIND_NODE,clusterLevel:t.clusterLevel,closer:r.map(n.peerInfoMapper).filter((e=>{var{multiaddrs:t}=e;return t.length})).map((e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map((e=>e.bytes))}))),providers:[]};return 0===i.closer.length&&n.log("could not find any peers closer to %b than %p",t.key,e),i}))()}}class uU{constructor(t,r){e(this,"peerId",void 0),e(this,"peerRouting",void 0),e(this,"providers",void 0),e(this,"peerStore",void 0),e(this,"peerInfoMapper",void 0),e(this,"log",void 0);var{peerRouting:n,providers:i,logPrefix:o}=r;this.log=t.logger.forComponent("".concat(o,":rpc:handlers:get-providers")),this.peerId=t.peerId,this.peerStore=t.peerStore,this.peerRouting=n,this.providers=i,this.peerInfoMapper=r.peerInfoMapper}handle(e,t){var n=this;return r((function*(){if(null==t.key)throw new Ja("Invalid GET_PROVIDERS message received - key was missing");var i;try{i=it.decode(t.key)}catch(e){throw new Ja("Invalid CID")}n.log("%p asking for providers for %s",e,i);var[o,a]=yield Promise.all([gc(Pc(yield n.providers.getProviders(i),function(){var e=r((function*(e){var t=yield n.peerStore.get(e),r={id:t.id,multiaddrs:t.addresses.map((e=>{var{multiaddr:t}=e;return t}))};return r}));return function(t){return e.apply(this,arguments)}}())),n.peerRouting.getCloserPeersOffline(t.key,n.peerId)]),s={type:ML.GET_PROVIDERS,key:t.key,clusterLevel:t.clusterLevel,closer:a.map(n.peerInfoMapper).filter((e=>{var{id:t,multiaddrs:r}=e;return r.length>0})).map((e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map((e=>e.bytes))}))),providers:o.map(n.peerInfoMapper).filter((e=>{var{id:t,multiaddrs:r}=e;return r.length>0})).map((e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map((e=>e.bytes))})))};return n.log("got %s providers %s closerPeers",s.providers.length,s.closer.length),s}))()}_getAddresses(e){return r((function*(){return[]}))()}}class cU{constructor(t,r){e(this,"peerStore",void 0),e(this,"datastore",void 0),e(this,"peerRouting",void 0),e(this,"log",void 0),e(this,"datastorePrefix",void 0),this.log=t.logger.forComponent("".concat(r.logPrefix,":rpc:handlers:get-value")),this.datastorePrefix="".concat(r.datastorePrefix,"/record"),this.peerStore=t.peerStore,this.datastore=t.datastore,this.peerRouting=r.peerRouting}handle(e,t){var n=this;return r((function*(){var r=t.key;if(n.log("%p asked for key %b",e,r),null==r||0===r.length)throw new Ja("Invalid key");var i={type:ML.GET_VALUE,key:r,clusterLevel:t.clusterLevel,closer:[],providers:[]};if(function(e){return"/pk/"===gt(e.subarray(0,4))}(r)){n.log("is public key");var o,a=function(e){return zu(He(e.subarray(4)))}(r);try{var s=yield n.peerStore.get(a);if(null==s.id.publicKey)throw new Ha("No public key found in key book");o=Au(s.id.publicKey)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=o)return n.log("returning found public key"),i.record=new YL(r,o,new Date).serialize(),i}var[l,u]=yield Promise.all([n._checkLocalDatastore(r),n.peerRouting.getCloserPeersOffline(r,e)]);return null!=l&&(n.log("had record for %b in local datastore",r),i.record=l.serialize()),u.length>0&&(n.log("had %s closer peers in routing table",u.length),i.closer=u.map((e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map((e=>e.bytes))})))),i}))()}_checkLocalDatastore(e){var t=this;return r((function*(){t.log("checkLocalDatastore looking for %b",e);var r,n=mM(t.datastorePrefix,e);try{r=yield t.datastore.get(n)}catch(e){if("NotFoundError"===e.name)return;throw e}var i=YL.deserialize(r);if(!(null==i.timeReceived||Date.now()-i.timeReceived.getTime()>HL))return i;yield t.datastore.delete(n)}))()}}class dU{constructor(t,r){e(this,"log",void 0),this.log=t.logger.forComponent("".concat(r.logPrefix,":rpc:handlers:ping"))}handle(e,t){var n=this;return r((function*(){return n.log("ping from %p",e),t}))()}}class hU{constructor(t,r){e(this,"components",void 0),e(this,"validators",void 0),e(this,"log",void 0),e(this,"datastorePrefix",void 0);var{validators:n}=r;this.components=t,this.log=t.logger.forComponent("".concat(r.logPrefix,":rpc:handlers:put-value")),this.datastorePrefix="".concat(r.datastorePrefix,"/record"),this.validators=n}handle(e,t){var n=this;return r((function*(){var r=t.key;if(n.log("%p asked us to store value for key %b",e,r),null==t.record){var i="Empty record from: ".concat(e.toString());throw n.log.error(i),new Ja(i)}try{var o=YL.deserialize(t.record);yield lM(n.validators,o),o.timeReceived=new Date;var a=mM(n.datastorePrefix,o.key);yield n.components.datastore.put(a,o.serialize().subarray()),n.log("put record for %b into datastore under key %k",r,a)}catch(e){n.log("did not put record for key %b into datastore %o",r,e)}return t}))()}}class vU{constructor(t,r){var n,i;e(this,"handlers",void 0),e(this,"routingTable",void 0),e(this,"log",void 0),e(this,"metrics",void 0),this.metrics={operations:null===(n=t.metrics)||void 0===n?void 0:n.registerCounterGroup("".concat(r.metricsPrefix,"_inbound_rpc_requests_total")),errors:null===(i=t.metrics)||void 0===i?void 0:i.registerCounterGroup("".concat(r.metricsPrefix,"_inbound_rpc_errors_total"))},this.log=t.logger.forComponent("".concat(r.logPrefix,":rpc")),this.routingTable=r.routingTable,this.handlers={[ML.GET_VALUE.toString()]:new cU(t,r),[ML.PUT_VALUE.toString()]:new hU(t,r),[ML.FIND_NODE.toString()]:new lU(t,r),[ML.ADD_PROVIDER.toString()]:new sU(t,r),[ML.GET_PROVIDERS.toString()]:new uU(t,r),[ML.PING.toString()]:new dU(t,r)}}handleMessage(e,t){var n=this;return r((function*(){var r=n.handlers[t.type];if(null!=r)try{var i;return null===(i=n.metrics.operations)||void 0===i||i.increment({[t.type]:!0}),yield r.handle(e,t)}catch(e){var o;null===(o=n.metrics.errors)||void 0===o||o.increment({[t.type]:!0})}else n.log.error("no handler found for message type: ".concat(t.type))}))()}onIncomingStream(e){var t=this,n="unknown";Promise.resolve().then(r((function*(){var{stream:r,connection:i}=e,o=i.remotePeer,a=t;yield qc(r,(e=>Cp(e)),function(){var e=l((function*(e){var t,r=!1,i=!1;try{for(var l,c=s(e);r=!(l=yield u(c.next())).done;r=!1){var d=l.value,h=VL.decode(d);n=h.type,a.log("incoming %s from %p",h.type,o);var v=yield u(a.handleMessage(o,h));null!=v&&(yield VL.encode(v))}}catch(e){i=!0,t=e}finally{try{r&&null!=c.return&&(yield u(c.return()))}finally{if(i)throw t}}}));return function(t){return e.apply(this,arguments)}}(),(e=>xp(e)),r)}))).catch((t=>{this.log.error("error handling %s RPC message from %p - %e",n,e.connection.remotePeer,t)}))}}class pU extends us{constructor(t,r){super(),e(this,"log",void 0),e(this,"components",void 0),e(this,"protocol",void 0),e(this,"running",void 0),e(this,"registrarId",void 0);var{protocol:n,logPrefix:i}=r;this.components=t,this.log=t.logger.forComponent("".concat(i,":topology-listener")),this.running=!1,this.protocol=n}isStarted(){return this.running}start(){var e=this;return r((function*(){e.running||(e.running=!0,e.registrarId=yield e.components.registrar.register(e.protocol,{onConnect:t=>{e.log("observed peer %p with protocol %s",t,e.protocol),e.dispatchEvent(new CustomEvent("peer",{detail:t}))}}))}))()}stop(){var e=this;return r((function*(){e.running=!1,null!=e.registrarId&&(e.components.registrar.unregister(e.registrarId),e.registrarId=void 0)}))()}}class fU{constructor(t){e(this,"dht",void 0),this.dht=t}provide(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};yield vc(n.dht.provide(e,r))}))()}cancelReprovide(e){var t=this;return r((function*(){yield t.dht.cancelReprovide(e)}))()}findProviders(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var n,i=!1,o=!1;try{for(var a,l=s(t.dht.findProviders(e,r));i=!(a=yield u(l.next())).done;i=!1){var d=a.value;"PROVIDER"===d.name&&(yield*c(s(d.providers),u))}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}()})).apply(this,arguments)}put(e,t,n){var i=this;return r((function*(){yield vc(i.dht.put(e,t,n))}))()}get(e,t){var n=this;return r((function*(){var r,i=!1,o=!1;try{for(var a,l=s(n.dht.get(e,t));i=!(a=yield l.next()).done;i=!1){var u=a.value;if("VALUE"===u.name)return u.value}}catch(e){o=!0,r=e}finally{try{i&&null!=l.return&&(yield l.return())}finally{if(o)throw r}}throw new Ha("Could not find value for key")}))()}}class gU{constructor(t){e(this,"dht",void 0),this.dht=t}findPeer(e){var t=arguments,n=this;return r((function*(){var r,i=t.length>1&&void 0!==t[1]?t[1]:{},o=!1,a=!1;try{for(var l,u=s(n.dht.findPeer(e,i));o=!(l=yield u.next()).done;o=!1){var c=l.value;if("FINAL_PEER"===c.name)return c.peer}}catch(e){a=!0,r=e}finally{try{o&&null!=u.return&&(yield u.return())}finally{if(a)throw r}}throw new Ha("Peer not found")}))()}getClosestPeers(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var n,i=!1,o=!1;try{for(var a,l=s(t.dht.getClosestPeers(e,r));i=!(a=yield u(l.next())).done;i=!1){var c=a.value;"FINAL_PEER"===c.name&&(yield c.peer)}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}()})).apply(this,arguments)}}var yU;class mU extends us{constructor(n){var i,o,a,s,l,u,c,d,h,v,p,f,g,y,m=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),y=this,e(this,"protocol",void 0),e(this,"routingTable",void 0),e(this,"providers",void 0),e(this,"network",void 0),e(this,"peerRouting",void 0),e(this,"components",void 0),e(this,"log",void 0),e(this,"running",void 0),e(this,"kBucketSize",void 0),e(this,"clientMode",void 0),e(this,"validators",void 0),e(this,"selectors",void 0),e(this,"queryManager",void 0),e(this,"contentFetching",void 0),e(this,"contentRouting",void 0),e(this,"routingTableRefresh",void 0),e(this,"rpc",void 0),e(this,"topologyListener",void 0),e(this,"querySelf",void 0),e(this,"maxInboundStreams",void 0),e(this,"maxOutboundStreams",void 0),e(this,"dhtContentRouting",void 0),e(this,"dhtPeerRouting",void 0),e(this,"peerInfoMapper",void 0),e(this,"reprovider",void 0),e(this,Symbol.toStringTag,"@libp2p/kad-dht"),e(this,fs,["@libp2p/content-routing","@libp2p/peer-routing","@libp2p/peer-discovery"]),e(this,gs,["@libp2p/identify"]);var w=null!==(i=m.logPrefix)&&void 0!==i?i:"libp2p:kad-dht",b=null!==(o=m.datastorePrefix)&&void 0!==o?o:"/dht",S=null!==(a=m.metricsPrefix)&&void 0!==a?a:"libp2p_kad_dht",E={queries:null===(s=n.metrics)||void 0===s?void 0:s.registerMetricGroup("".concat(S,"_operations_total"),{label:"operation"}),errors:null===(l=n.metrics)||void 0===l?void 0:l.registerCounterGroup("".concat(S,"_operation_errors_total"),{label:"operation"}),queryTime:null===(u=n.metrics)||void 0===u?void 0:u.registerMetricGroup("".concat(S,"_operation_time_seconds"),{label:"operation"}),errorTime:null===(c=n.metrics)||void 0===c?void 0:c.registerMetricGroup("".concat(S,"_operation_error_time_seconds"),{label:"operation"})};this.running=!1,this.components=n,this.log=n.logger.forComponent(w),this.protocol=null!==(d=m.protocol)&&void 0!==d?d:"/ipfs/kad/1.0.0",this.kBucketSize=null!==(h=m.kBucketSize)&&void 0!==h?h:20,this.clientMode=null===(v=m.clientMode)||void 0===v||v,this.maxInboundStreams=null!==(p=m.maxInboundStreams)&&void 0!==p?p:32,this.maxOutboundStreams=null!==(f=m.maxOutboundStreams)&&void 0!==f?f:64,this.peerInfoMapper=null!==(g=m.peerInfoMapper)&&void 0!==g?g:vM;var k=zB();this.providers=new qM(n,t(t({},m.providers),{},{logPrefix:w,datastorePrefix:b,lock:k})),this.validators=t(t({},dM),m.validators),this.selectors=t(t({},sM),m.selectors),this.network=new FM(n,{protocol:this.protocol,logPrefix:w,metricsPrefix:S}),this.routingTable=new iU(n,{kBucketSize:m.kBucketSize,pingOldContactTimeout:m.pingOldContactTimeout,pingOldContactConcurrency:m.pingOldContactConcurrency,pingOldContactMaxQueueSize:m.pingOldContactMaxQueueSize,pingNewContactTimeout:m.pingNewContactTimeout,pingNewContactConcurrency:m.pingNewContactConcurrency,pingNewContactMaxQueueSize:m.pingNewContactMaxQueueSize,protocol:this.protocol,logPrefix:w,metricsPrefix:S,prefixLength:m.prefixLength,splitThreshold:m.kBucketSplitThreshold,network:this.network});var x=_c();!0===m.allowQueryWithZeroPeers&&x.resolve(),this.queryManager=new KM(n,{disjointPaths:Math.ceil(this.kBucketSize/2),logPrefix:w,metricsPrefix:S,initialQuerySelfHasRun:x,routingTable:this.routingTable}),this.peerRouting=new VM(n,{routingTable:this.routingTable,network:this.network,validators:this.validators,queryManager:this.queryManager,logPrefix:w}),this.contentFetching=new AM(n,{validators:this.validators,selectors:this.selectors,peerRouting:this.peerRouting,queryManager:this.queryManager,network:this.network,logPrefix:w,datastorePrefix:b}),this.contentRouting=new IM(n,{network:this.network,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,providers:this.providers,logPrefix:w}),this.routingTableRefresh=new aU(n,{peerRouting:this.peerRouting,routingTable:this.routingTable,logPrefix:w}),this.rpc=new vU(n,{routingTable:this.routingTable,providers:this.providers,peerRouting:this.peerRouting,validators:this.validators,logPrefix:w,metricsPrefix:S,datastorePrefix:b,peerInfoMapper:this.peerInfoMapper}),this.topologyListener=new pU(n,{protocol:this.protocol,logPrefix:w}),this.querySelf=new QM(n,{peerRouting:this.peerRouting,interval:m.querySelfInterval,initialInterval:m.initialQuerySelfInterval,logPrefix:w,initialQuerySelfHasRun:x,routingTable:this.routingTable,operationMetrics:E}),this.reprovider=new YM(n,t(t({},m.reprovide),{},{logPrefix:w,metricsPrefix:S,datastorePrefix:b,contentRouting:this.contentRouting,lock:k,operationMetrics:E})),this.network.addEventListener("peer",(e=>{var t=e.detail;this.onPeerConnect(t).catch((e=>{this.log.error("could not add %p to routing table",t.id,e)})),this.dispatchEvent(new CustomEvent("peer",{detail:t}))})),this.topologyListener.addEventListener("peer",(e=>{var t=e.detail;Promise.resolve().then(r((function*(){var e=yield y.components.peerStore.get(t),r={id:t,multiaddrs:e.addresses.map((e=>{var{multiaddr:t}=e;return t})),protocols:e.protocols};yield y.onPeerConnect(r)}))).catch((e=>{this.log.error("could not add %p to routing table - %e",t,e)}))})),this.dhtPeerRouting=new gU(this),this.dhtContentRouting=new fU(this),null==m.clientMode&&n.events.addEventListener("self:peer:update",(e=>{this.log("received update of self-peer info"),Promise.resolve().then(r((function*(){var t=e.detail.peer.addresses.some((e=>{var{multiaddr:t}=e;return function(e){var t=e.stringTuples();for(var r of t)if(290===r[0])return!1;if(54===t[0][0]||55===t[0][0]||56===t[0][0])return!0;if(4===t[0][0]||41===t[0][0]){var n=hD("".concat(t[0][1]));return null==n||!n}return!1}(t)})),r=y.getMode();t&&"client"===r?yield y.setMode("server"):"server"!==r||t||(yield y.setMode("client"))}))).catch((e=>{this.log.error("error setting dht server mode",e)}))})),this.get=kM(this.get.bind(this),E,"GET_VALUE"),this.findProviders=kM(this.findProviders.bind(this),E,"FIND_PROVIDERS"),this.findPeer=kM(this.findPeer.bind(this),E,"FIND_PEER"),this.getClosestPeers=kM(this.getClosestPeers.bind(this),E,"GET_CLOSEST_PEERS"),this.provide=kM(this.provide.bind(this),E,"PROVIDE"),this.put=kM(this.put.bind(this),E,"PUT_VALUE")}get[ka](){return this.dhtContentRouting}get[Ta](){return this.dhtPeerRouting}get[xa](){return this}onPeerConnect(e){var t=this;return r((function*(){if(t.log.trace("peer %p connected",e.id),0!==(e=t.peerInfoMapper(e)).multiaddrs.length)try{yield t.routingTable.add(e.id)}catch(r){t.log.error("could not add %p to routing table",e.id,r)}else t.log.trace("ignoring %p as there were no valid addresses in %s after filtering",e.id,e.multiaddrs.map((e=>e.toString())))}))()}isStarted(){return this.running}getMode(){return this.clientMode?"client":"server"}setMode(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]&&t[1];e!==n.getMode()||r?(yield n.components.registrar.unhandle(n.protocol),e!==n.getMode()||r?"client"===e?(n.log("enabling client mode while in %s mode",n.getMode()),n.clientMode=!0):(n.log("enabling server mode while in %s mode",n.getMode()),n.clientMode=!1,yield n.components.registrar.handle(n.protocol,n.rpc.onIncomingStream.bind(n.rpc),{maxInboundStreams:n.maxInboundStreams,maxOutboundStreams:n.maxOutboundStreams})):n.log("already in %s mode",e)):n.log("already in %s mode",e)}))()}start(){var e=this;return r((function*(){e.running||(e.running=!0,yield e.setMode(e.clientMode?"client":"server",!0),yield ds(e.routingTable,e.queryManager,e.network,e.topologyListener,e.routingTableRefresh,e.reprovider),yield ds(e.querySelf))}))()}stop(){var e=this;return r((function*(){e.running=!1,yield vs(e.querySelf,e.queryManager,e.network,e.routingTable,e.routingTableRefresh,e.topologyListener,e.reprovider)}))()}put(e,t){var r=this;return l((function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){yield*c(s(r.contentFetching.put(e,t,n)))}()})).apply(this,arguments)}get(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(t.contentFetching.get(e,r)))}()})).apply(this,arguments)}provide(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(t.contentRouting.provide(e,t.components.addressManager.getAddresses(),r)))}()})).apply(this,arguments)}cancelReprovide(e){var t=this;return r((function*(){yield t.providers.removeProvider(e,t.components.peerId)}))()}findProviders(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(t.contentRouting.findProviders(e,r)))}()})).apply(this,arguments)}findPeer(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(t.peerRouting.findPeer(e,r)))}()})).apply(this,arguments)}getClosestPeers(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(t.peerRouting.getClosestPeers(e,r)))}()})).apply(this,arguments)}refreshRoutingTable(){var e=this;return r((function*(){e.routingTableRefresh.refreshTable(!0)}))()}}function wU(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new mU(t,e)}function bU(e){if("object"!=typeof e||null===e)return!1;var t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)}!function(e){e[e.SEND_QUERY=0]="SEND_QUERY",e[e.PEER_RESPONSE=1]="PEER_RESPONSE",e[e.FINAL_PEER=2]="FINAL_PEER",e[e.QUERY_ERROR=3]="QUERY_ERROR",e[e.PROVIDER=4]="PROVIDER",e[e.VALUE=5]="VALUE",e[e.ADD_PEER=6]="ADD_PEER",e[e.DIAL_PEER=7]="DIAL_PEER"}(yU||(yU={}));var{hasOwnProperty:SU}=Object.prototype,{propertyIsEnumerable:EU}=Object,kU=(e,t,r)=>{Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})},xU={concatArrays:!1,ignoreUndefined:!1},AU=e=>{var t=[];for(var r in e)SU.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);for(var i of n)EU.call(e,i)&&t.push(i)}return t};function CU(e){return Array.isArray(e)?(r=(t=e).slice(0,0),AU(t).forEach((e=>{kU(r,e,CU(t[e]))})),r):bU(e)?function(e){var t=null===Object.getPrototypeOf(e)?Object.create(null):{};return AU(e).forEach((r=>{kU(t,r,CU(e[r]))})),t}(e):e;var t,r}var IU,TU,PU,_U,BU,NU,DU,RU,OU=(e,t,r,n)=>(r.forEach((r=>{void 0===t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?kU(e,r,MU(e[r],t[r],n)):kU(e,r,CU(t[r])))})),e),LU=(e,t,r)=>{var n=e.slice(0,0),i=0;return[e,t].forEach((t=>{for(var o=[],a=0;a<t.length;a++)SU.call(t,a)&&(o.push(String(a)),kU(n,i++,t===e?t[a]:CU(t[a])));n=OU(n,t,AU(t).filter((e=>!o.includes(e))),r)})),n};function MU(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?LU(e,t,r):bU(t)&&bU(e)?OU(e,t,AU(t),r):CU(t)}function UU(){for(var e=MU(CU(xU),undefined!==this&&this||{},xU),t={_:{}},r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];for(var o of n)if(void 0!==o){if(!bU(o))throw new TypeError("`"+o+"` is not an Option Object");t=MU(t,{_:o},e)}return t._}function FU(){if(TU)return IU;function e(e){return e>=55296&&e<=56319}function t(e){return e>=56320&&e<=57343}return TU=1,IU=function(r,n,i){if("string"!=typeof n)throw new Error("Input must be string");for(var o,a,s=n.length,l=0,u=0;u<s;u+=1){if(o=n.charCodeAt(u),a=n[u],e(o)&&t(n.charCodeAt(u+1))&&(a+=n[u+=1]),(l+=r(a))===i)return n.slice(0,u+1);if(l>i)return n.slice(0,u-a.length+1)}return n},IU}function zU(){if(NU)return BU;NU=1;var e=FU(),t=function(){if(_U)return PU;function e(e){return e>=55296&&e<=56319}function t(e){return e>=56320&&e<=57343}return _U=1,PU=function(r){if("string"!=typeof r)throw new Error("Input must be string");for(var n=r.length,i=0,o=null,a=null,s=0;s<n;s++)t(o=r.charCodeAt(s))?null!=a&&e(a)?i+=1:i+=3:o<=127?i+=1:o>=128&&o<=2047?i+=2:o>=2048&&o<=65535&&(i+=3),a=o;return i},PU}();return BU=e.bind(null,t)}var jU=function(){if(RU)return DU;RU=1;var e=zU(),t=/[\/\?<>\\:\*\|"]/g,r=/[\x00-\x1f\x80-\x9f]/g,n=/^\.+$/,i=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,o=/[\. ]+$/;function a(a,s){if("string"!=typeof a)throw new Error("Input must be string");var l=a.replace(t,s).replace(r,s).replace(n,s).replace(i,s).replace(o,s);return e(l,255)}return DU=function(e,t){var r=t&&t.replacement||"",n=a(e,r);return""===r?n:a(n,"")},DU}(),VU=a(jU),qU={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function HU(e){var t="AES-GCM",n=16,i=12,o="SHA-256",a=16,s=32767,l=tu.get();function u(){return(u=r((function*(e,r){var u,c=l.getRandomValues(new Uint8Array(a)),d=l.getRandomValues(new Uint8Array(i)),h={name:t,iv:d};if("string"==typeof r&&(r=xt(r)),0===r.length){u=yield l.subtle.importKey("jwk",qU,{name:"AES-GCM"},!0,["encrypt"]);try{var v={name:"PBKDF2",salt:c,iterations:s,hash:{name:o}},p=yield l.subtle.importKey("raw",r,{name:"PBKDF2"},!1,["deriveKey"]);u=yield l.subtle.deriveKey(v,p,{name:t,length:n},!0,["encrypt"])}catch(e){u=yield l.subtle.importKey("jwk",qU,{name:"AES-GCM"},!0,["encrypt"])}}else{var f={name:"PBKDF2",salt:c,iterations:s,hash:{name:o}},g=yield l.subtle.importKey("raw",r,{name:"PBKDF2"},!1,["deriveKey"]);u=yield l.subtle.deriveKey(f,g,{name:t,length:n},!0,["encrypt"])}var y=yield l.subtle.encrypt(h,u,e);return zt([c,h.iv,new Uint8Array(y)])}))).apply(this,arguments)}function c(){return(c=r((function*(e,r){var u,c=e.subarray(0,a),d=e.subarray(a,a+i),h=e.subarray(a+i),v={name:t,iv:d};if("string"==typeof r&&(r=xt(r)),0===r.length)try{var p={name:"PBKDF2",salt:c,iterations:s,hash:{name:o}},f=yield l.subtle.importKey("raw",r,{name:"PBKDF2"},!1,["deriveKey"]);u=yield l.subtle.deriveKey(p,f,{name:t,length:n},!0,["decrypt"])}catch(e){u=yield l.subtle.importKey("jwk",qU,{name:"AES-GCM"},!0,["decrypt"])}else{var g={name:"PBKDF2",salt:c,iterations:s,hash:{name:o}},y=yield l.subtle.importKey("raw",r,{name:"PBKDF2"},!1,["deriveKey"]);u=yield l.subtle.deriveKey(g,y,{name:t,length:n},!0,["decrypt"])}var m=yield l.subtle.decrypt(v,u,h);return new Uint8Array(m)}))).apply(this,arguments)}n*=8;var d={encrypt:function(e,t){return u.apply(this,arguments)},decrypt:function(e,t){return c.apply(this,arguments)}};return d}var KU=1e4;function WU(e,t){return GU.apply(this,arguments)}function GU(){return(GU=r((function*(e,t){var r=HU(),n=yield r.encrypt(e,t);return se.encode(n)}))).apply(this,arguments)}function QU(e,t,r){return YU.apply(this,arguments)}function YU(){return YU=r((function*(e,t,r){if("RSA"===e.type)return function(e,t){return XU.apply(this,arguments)}(e,t,r);if("Ed25519"===e.type)return function(e,t){return JU.apply(this,arguments)}(e,t,r);if("secp256k1"===e.type)return function(e,t){return ZU.apply(this,arguments)}(e,t,r);if("ECDSA"===e.type)return function(e,t){return $U.apply(this,arguments)}(e,t,r);throw new as})),YU.apply(this,arguments)}function JU(){return JU=r((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"libp2p-key";if("libp2p-key"===r)return WU(Tu(e),t);throw new Ra("export format '".concat(r,"' is not supported"))})),JU.apply(this,arguments)}function ZU(){return ZU=r((function*(e,t){if("libp2p-key"===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:"libp2p-key"))return WU(Tu(e),t);throw new Ra("Export format is not supported")})),ZU.apply(this,arguments)}function $U(){return $U=r((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"libp2p-key";if("libp2p-key"===r)return WU(Tu(e),t);throw new Ra("export format '".concat(r,"' is not supported"))})),$U.apply(this,arguments)}function XU(){return XU=r((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"pkcs-8";if("pkcs-8"===r)return function(e,t){return eF.apply(this,arguments)}(e,t);if("libp2p-key"===r)return WU(Tu(e),t);throw new Ra("Export format is not supported")})),XU.apply(this,arguments)}function eF(){return(eF=r((function*(e,t){var r=tu.get(),n=new Rg({value:[new Cg({value:0}),new Rg({value:[new _g({value:"1.2.840.113549.1.1.1"}),new ag]}),new dg({valueHex:e.raw})]}).toBER(),i=new Uint8Array(n,0,n.byteLength),o=Zl(16),a=yield na(ea,t,o,{c:KU,dkLen:32}),s=Zl(16),l=yield r.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),u=yield r.subtle.encrypt({name:"AES-CBC",iv:s},l,i),c=new Rg({value:[new dg({valueHex:o}),new Cg({value:KU}),new Cg({value:32}),new Rg({value:[new _g({value:"1.2.840.113549.2.11"}),new ag]})]}),d=new Rg({value:[new _g({value:"1.2.840.113549.1.5.13"}),new Rg({value:[new Rg({value:[new _g({value:"1.2.840.113549.1.5.12"}),c]}),new Rg({value:[new _g({value:"2.16.840.1.101.3.4.1.42"}),new dg({valueHex:s})]})]})]}),h=new Rg({value:[d,new dg({valueHex:u})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...gt(new Uint8Array(h,0,h.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}))).apply(this,arguments)}function tF(e,t){return rF.apply(this,arguments)}function rF(){return rF=r((function*(e,t){try{var r=yield function(e,t){return nF.apply(this,arguments)}(e,t);return Cu(r)}catch(e){}if(!e.includes("BEGIN"))throw new Ra("Encrypted key was not a libp2p-key or a PEM file");return function(e,t){return iF.apply(this,arguments)}(e,t)})),rF.apply(this,arguments)}function nF(){return(nF=r((function*(e,t){var r=se.decode(e);return HU().decrypt(r,t)}))).apply(this,arguments)}function iF(){return(iF=r((function*(e,t){var r,n=tu.get();if(e.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){var i=xt(e.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:o}=eg(i),{iv:a,salt:s,iterations:l,keySize:u,cipherText:c}=function(e){var t=e.valueBlock.value[0];if("OBJECT IDENTIFIER : 1.2.840.113549.1.5.13"!==t.valueBlock.value[0].toString())throw new Ra("Only pkcs5PBES2 encrypted private keys are supported");var r=t.valueBlock.value[1].valueBlock.value[0];if("OBJECT IDENTIFIER : 1.2.840.113549.1.5.12"!==r.valueBlock.value[0].toString())throw new Ra("Only pkcs5PBKDF2 key derivation functions are supported");var n=r.valueBlock.value[1],i=aF(n.valueBlock.value[0].getValue()),o=KU,a=32;if(3===n.valueBlock.value.length)o=Number(n.valueBlock.value[1].toBigInt()),a=Number(n.valueBlock.value[2].toBigInt());else if(2===n.valueBlock.value.length)throw new Ra("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key");var s=t.valueBlock.value[1].valueBlock.value[1],l=s.valueBlock.value[0].toString();if("OBJECT IDENTIFIER : 1.2.840.113549.3.7"===l);else if("OBJECT IDENTIFIER : 1.3.14.3.2.7"===l);else if("OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"===l);else if("OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"===l);else if("OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42"!==l)throw new Ra("Only AES-CBC encryption schemes are supported");var u=aF(s.valueBlock.value[1].getValue());return{cipherText:aF(e.valueBlock.value[1].getValue()),salt:i,iterations:o,keySize:a,iv:u}}(o),d=yield na(ea,t,s,{c:l,dkLen:u}),h=yield n.subtle.importKey("raw",d,"AES-CBC",!1,["decrypt"]),v=aF(yield n.subtle.decrypt({name:"AES-CBC",iv:a},h,c)),{result:p}=eg(v);r=oF(p)}else{if(!e.includes("-----BEGIN PRIVATE KEY-----"))throw new Ra("Could not parse private key from PEM data");var f=xt(e.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:g}=eg(f);r=oF(g)}var y=Iu(r);if("RSA"!==y.type)throw new Ra("Could not parse RSA private key from PEM data");return y}))).apply(this,arguments)}function oF(e){return aF(e.valueBlock.value[2].getValue())}function aF(e){return new Uint8Array(e,0,e.byteLength)}var sF,lF="/info/",uF=new WeakMap,cF=14,dF=16,hF=1e3,vF={dek:{keyLength:64,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function pF(e){return null!=e&&("string"==typeof e&&(e===VU(e.trim())&&e.length>0))}function fF(){return gF.apply(this,arguments)}function gF(){return gF=r((function*(){var e=800*Math.random()+200;yield new Promise((t=>setTimeout(t,e)))})),gF.apply(this,arguments)}function yF(e){return new hc("/pkcs8/"+e)}function mF(e){return new hc(lF+e)}function wF(){return(wF=r((function*(e){var t=Tu(e),r=yield $e.digest(t);return ie.encode(r.bytes).substring(1)}))).apply(this,arguments)}class bF{constructor(t,r){var n,i,o,a,s,l,u,c,d,h;if(e(this,"components",void 0),e(this,"init",void 0),e(this,"log",void 0),e(this,"self",void 0),e(this,Symbol.toStringTag,"@libp2p/keychain"),e(this,fs,["@libp2p/keychain"]),this.components=t,this.log=t.logger.forComponent("libp2p:keychain"),this.init=UU(vF,r),this.self=null!==(n=r.selfKey)&&void 0!==n?n:"self",null!=this.init.pass&&(null===(i=this.init.pass)||void 0===i?void 0:i.length)<20)throw new Error("pass must be least 20 characters");if(null!=(null===(o=this.init.dek)||void 0===o?void 0:o.keyLength)&&this.init.dek.keyLength<cF)throw new Error("dek.keyLength must be least ".concat(cF," bytes"));if(null!=(null===(a=this.init.dek)||void 0===a||null===(a=a.salt)||void 0===a?void 0:a.length)&&this.init.dek.salt.length<dF)throw new Error("dek.saltLength must be least ".concat(dF," bytes"));if(null!=(null===(s=this.init.dek)||void 0===s?void 0:s.iterationCount)&&this.init.dek.iterationCount<hF)throw new Error("dek.iterationCount must be least ".concat(hF));var v=null!=this.init.pass&&null!=(null===(l=this.init.dek)||void 0===l?void 0:l.salt)?lc(this.init.pass,null===(u=this.init.dek)||void 0===u?void 0:u.salt,null===(c=this.init.dek)||void 0===c?void 0:c.iterationCount,null===(d=this.init.dek)||void 0===d?void 0:d.keyLength,null===(h=this.init.dek)||void 0===h?void 0:h.hash):"";uF.set(this,{dek:v})}static generateOptions(){var e=Object.assign({},vF),t=3*Math.ceil(dF/3);return e.dek.salt=gt(Zl(t),"base64"),e}static get options(){return vF}findKeyByName(e){var t=this;return r((function*(){if(!pF(e))throw yield fF(),new Ra("Invalid key name '".concat(e,"'"));var r=mF(e);try{var n=yield t.components.datastore.get(r);return JSON.parse(gt(n))}catch(r){throw yield fF(),t.log.error(r),new Ha("Key '".concat(e,"' does not exist."))}}))()}findKeyById(e){var t=this;return r((function*(){try{var r,n={prefix:lF},i=!1,o=!1;try{for(var a,l=s(t.components.datastore.query(n));i=!(a=yield l.next()).done;i=!1){var u=a.value,c=JSON.parse(gt(u.value));if(c.id===e)return c}}catch(e){o=!0,r=e}finally{try{i&&null!=l.return&&(yield l.return())}finally{if(o)throw r}}throw new Ra("Key with id '".concat(e,"' does not exist."))}catch(e){throw yield fF(),e}}))()}importKey(e,t){var n=this;return r((function*(){if(!pF(e))throw yield fF(),new Ra("Invalid key name '".concat(e,"'"));if(null==t)throw yield fF(),new Ra("Key is required");var r,i,o=yF(e);if(yield n.components.datastore.has(o))throw yield fF(),new Ra("Key '".concat(e,"' already exists"));try{r=yield function(e){return wF.apply(this,arguments)}(t);var a=uF.get(n);if(null==a)throw new Ra("dek missing");var s=a.dek;i=yield QU(t,s,"RSA"===t.type?"pkcs-8":"libp2p-key")}catch(e){throw yield fF(),e}var l={name:e,id:r},u=n.components.datastore.batch();return u.put(o,xt(i)),u.put(mF(e),xt(JSON.stringify(l))),yield u.commit(),l}))()}exportKey(e){var t=this;return r((function*(){if(!pF(e))throw yield fF(),new Ra("Invalid key name '".concat(e,"'"));var r=yF(e);try{var n=gt(yield t.components.datastore.get(r)),i=uF.get(t);if(null==i)throw new Ra("dek missing");var o=i.dek;return yield tF(n,o)}catch(e){throw yield fF(),e}}))()}removeKey(e){var t=this;return r((function*(){if(!pF(e)||e===t.self)throw yield fF(),new Ra("Invalid key name '".concat(e,"'"));var r=yF(e),n=yield t.findKeyByName(e),i=t.components.datastore.batch();return i.delete(r),i.delete(mF(e)),yield i.commit(),n}))()}listKeys(){var e=this;return r((function*(){var t,r={prefix:lF},n=[],i=!1,o=!1;try{for(var a,l=s(e.components.datastore.query(r));i=!(a=yield l.next()).done;i=!1){var u=a.value;n.push(JSON.parse(gt(u.value)))}}catch(e){o=!0,t=e}finally{try{i&&null!=l.return&&(yield l.return())}finally{if(o)throw t}}return n}))()}renameKey(e,t){var n=this;return r((function*(){if(!pF(e)||e===n.self)throw yield fF(),new Ra("Invalid old key name '".concat(e,"'"));if(!pF(t)||t===n.self)throw yield fF(),new Ra("Invalid new key name '".concat(t,"'"));var r=yF(e),i=yF(t),o=mF(e),a=mF(t);if(yield n.components.datastore.has(i))throw yield fF(),new Ra("Key '".concat(t,"' already exists"));try{var s=yield n.components.datastore.get(r),l=yield n.components.datastore.get(o),u=JSON.parse(gt(l));u.name=t;var c=n.components.datastore.batch();return c.put(i,s),c.put(a,xt(JSON.stringify(u))),c.delete(r),c.delete(o),yield c.commit(),u}catch(e){throw yield fF(),e}}))()}rotateKeychainPass(e,t){var n=this;return r((function*(){var r,i,o,a;if("string"!=typeof e)throw yield fF(),new Ra("Invalid old pass type '".concat(typeof e,"'"));if("string"!=typeof t)throw yield fF(),new Ra("Invalid new pass type '".concat(typeof t,"'"));if(t.length<20)throw yield fF(),new Ra("Invalid pass length ".concat(t.length));n.log("recreating keychain");var s=uF.get(n);if(null==s)throw new Ra("dek missing");var l=s.dek;n.init.pass=t;var u=null!=t&&null!=(null===(r=n.init.dek)||void 0===r?void 0:r.salt)?lc(t,n.init.dek.salt,null===(i=n.init.dek)||void 0===i?void 0:i.iterationCount,null===(o=n.init.dek)||void 0===o?void 0:o.keyLength,null===(a=n.init.dek)||void 0===a?void 0:a.hash):"";uF.set(n,{dek:u});var c=yield n.listKeys();for(var d of c){var h=gt(yield n.components.datastore.get(yF(d.name))),v=yield tF(h,l),p=u.toString(),f=yield QU(v,p,"RSA"===v.type?"pkcs-8":"libp2p-key"),g=n.components.datastore.batch(),y={name:d.name,id:d.id};g.put(yF(d.name),xt(f)),g.put(mF(d.name),xt(JSON.stringify(y))),yield g.commit()}n.log("keychain reconstructed")}))()}}function SF(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new bF(t,e)}class EF{constructor(){var t,r,n,i,o,a,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e(this,"memoryStorage",void 0),e(this,"points",void 0),e(this,"duration",void 0),e(this,"blockDuration",void 0),e(this,"execEvenly",void 0),e(this,"execEvenlyMinDelayMs",void 0),e(this,"keyPrefix",void 0),this.points=null!==(t=s.points)&&void 0!==t?t:4,this.duration=null!==(r=s.duration)&&void 0!==r?r:1,this.blockDuration=null!==(n=s.blockDuration)&&void 0!==n?n:0,this.execEvenly=null!==(i=s.execEvenly)&&void 0!==i&&i,this.execEvenlyMinDelayMs=null!==(o=s.execEvenlyMinDelayMs)&&void 0!==o?o:1e3*this.duration/this.points,this.keyPrefix=null!==(a=s.keyPrefix)&&void 0!==a?a:"rlflx",this.memoryStorage=new kF}consume(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:1,i=t.length>2&&void 0!==t[2]?t[2]:{},o=n.getKey(e),a=n._getKeySecDuration(i),s=n.memoryStorage.incrby(o,r,a);if(s.remainingPoints=Math.max(n.points-s.consumedPoints,0),s.consumedPoints>n.points)throw n.blockDuration>0&&s.consumedPoints<=n.points+r&&(s=n.memoryStorage.set(o,s.consumedPoints,n.blockDuration)),new fv("Rate limit exceeded",s);if(n.execEvenly&&s.msBeforeNext>0&&!s.isFirstInDuration){var l=Math.ceil(s.msBeforeNext/(s.remainingPoints+2));l<n.execEvenlyMinDelayMs&&(l=s.consumedPoints*n.execEvenlyMinDelayMs),yield vL(l)}return s}))()}penalty(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=this.getKey(e),i=this._getKeySecDuration(r),o=this.memoryStorage.incrby(n,t,i);return o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o}reward(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=this.getKey(e),i=this._getKeySecDuration(r),o=this.memoryStorage.incrby(n,-t,i);return o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o}block(e,t){var 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){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,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){var 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!=(null==e?void 0:e.customDuration)&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?"".concat(this.keyPrefix,":").concat(e):e}parseKey(e){return e.substring(this.keyPrefix.length)}}class kF{constructor(){e(this,"storage",void 0),this.storage=new Map}incrby(e,t,r){var n=this.storage.get(e);if(null!=n){var i=null!=n.expiresAt?n.expiresAt.getTime()-(new Date).getTime():-1;return null==n.expiresAt||i>0?(n.value+=t,{remainingPoints:0,msBeforeNext:i,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,r)}return this.set(e,t,r)}set(e,t,r){var n=1e3*r,i=this.storage.get(e);null!=i&&clearTimeout(i.timeoutId);var o={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,o),n>0&&(o.timeoutId=setTimeout((()=>{this.storage.delete(e)}),n),null!=o.timeoutId.unref&&o.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:o.value,isFirstInDuration:!0}}get(e){var 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){var t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}}!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"}(sF||(sF={}));var xF=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),AF=Object.freeze({NEW_STREAM:sF.NEW_STREAM,MESSAGE:sF.MESSAGE_INITIATOR,CLOSE:sF.CLOSE_INITIATOR,RESET:sF.RESET_INITIATOR}),CF=Object.freeze({MESSAGE:sF.MESSAGE_RECEIVER,CLOSE:sF.CLOSE_RECEIVER,RESET:sF.RESET_RECEIVER}),IF=1<<20;class TF{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:IF,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4194304;e(this,"_buffer",void 0),e(this,"_headerInfo",void 0),e(this,"_maxMessageSize",void 0),e(this,"_maxUnprocessedMessageQueueSize",void 0),this._buffer=new bs,this._headerInfo=null,this._maxMessageSize=t,this._maxUnprocessedMessageQueueSize=r}write(e){if(null==e||0===e.length)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw new Ja("Unprocessed message queue size too large!");for(var t=[];0!==this._buffer.length;){if(null==this._headerInfo)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(e){if("InvalidMessageError"===e.name)throw e;break}var{id:r,type:n,length:i,offset:o}=this._headerInfo;if(this._buffer.length-o<i)break;var a={id:r,type:n};n!==sF.NEW_STREAM&&n!==sF.MESSAGE_INITIATOR&&n!==sF.MESSAGE_RECEIVER||(a.data=this._buffer.sublist(o,o+i)),t.push(a),this._buffer.consume(o+i),this._headerInfo=null}return t}_decodeHeader(e){var{value:t,offset:r}=BF(e),{value:n,offset:i}=BF(e,r),o=7&t;if(null==xF[o])throw new Error("Invalid type received: ".concat(o));if(n>this._maxMessageSize)throw new Ja("Message size too large");return{id:t>>3,type:o,offset:r+i,length:n}}}var PF=128,_F=127;function BF(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=0,i=0,o=r,a=e.length;do{if(o>=a||i>49)throw r=0,new RangeError("Could not decode varint");t=e.get(o++),n+=i<28?(t&_F)<<i:(t&_F)*Math.pow(2,i),i+=7}while(t>=PF);return{value:n,offset:r=o-r}}var NF=10240;var DF=new class{constructor(){e(this,"_pool",void 0),e(this,"_poolOffset",void 0),this._pool=dt(NF),this._poolOffset=0}write(e,t){var r=this._pool,n=this._poolOffset;Ut(e.id<<3|e.type,r,n),n+=Ot(e.id<<3|e.type),e.type!==sF.NEW_STREAM&&e.type!==sF.MESSAGE_INITIATOR&&e.type!==sF.MESSAGE_RECEIVER||null==e.data?(Ut(0,r,n),n+=Ot(0)):(Ut(e.data.length,r,n),n+=Ot(e.data.length));var i=r.subarray(this._poolOffset,n);NF-n<100?(this._pool=dt(NF),this._poolOffset=0):this._poolOffset=n,t.append(i),e.type!==sF.NEW_STREAM&&e.type!==sF.MESSAGE_INITIATOR&&e.type!==sF.MESSAGE_RECEIVER||null==e.data||t.append(e.data)}};function RF(){return RF=l((function*(e){var t,r=!1,n=!1;try{for(var i,o=s(e);r=!(i=yield u(o.next())).done;r=!1){var a=i.value,l=new bs;DF.write(a,l),yield l}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw t}}})),RF.apply(this,arguments)}class OF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Stream input buffer error"),this.name="StreamInputBufferError"}}class LF extends pp{constructor(t){super(t),e(this,"name",void 0),e(this,"streamId",void 0),e(this,"send",void 0),e(this,"types",void 0),e(this,"maxDataSize",void 0),this.types="outbound"===t.direction?AF:CF,this.send=t.send,this.name=t.name,this.streamId=t.streamId,this.maxDataSize=t.maxDataSize}sendNewStream(){var e=this;return r((function*(){yield e.send({id:e.streamId,type:AF.NEW_STREAM,data:new bs(xt(e.name))})}))()}sendData(e){var t=this;return r((function*(){for(e=e.sublist();e.byteLength>0;){var r=Math.min(e.byteLength,t.maxDataSize);yield t.send({id:t.streamId,type:t.types.MESSAGE,data:e.sublist(0,r)}),e.consume(r)}}))()}sendReset(){var e=this;return r((function*(){yield e.send({id:e.streamId,type:e.types.RESET})}))()}sendCloseWrite(){var e=this;return r((function*(){yield e.send({id:e.streamId,type:e.types.CLOSE})}))()}sendCloseRead(){return r((function*(){}))()}}function MF(e){var r=t(t({},e),{},{type:"".concat(xF[e.type]," (").concat(e.type,")")});return e.type===sF.NEW_STREAM&&(r.data=gt(e.data instanceof Uint8Array?e.data:e.data.subarray())),e.type!==sF.MESSAGE_INITIATOR&&e.type!==sF.MESSAGE_RECEIVER||(r.data=gt(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),r}class UF{constructor(t,r){var n,i;e(this,"protocol","/mplex/6.7.0"),e(this,"sink",void 0),e(this,"source",void 0),e(this,"log",void 0),e(this,"_streamId",void 0),e(this,"_streams",void 0),e(this,"_init",void 0),e(this,"_source",void 0),e(this,"closeController",void 0),e(this,"rateLimiter",void 0),e(this,"closeTimeout",void 0),e(this,"logger",void 0),r=null!=r?r:{},this.log=t.logger.forComponent("libp2p:mplex"),this.logger=t.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=r,this.closeTimeout=null!==(n=r.closeTimeout)&&void 0!==n?n:500,this.sink=this._createSink(),this._source=Rc({objectMode:!0,onEnd:()=>{for(var e of this._streams.initiators.values())e.destroy();for(var t of this._streams.receivers.values())t.destroy()}}),this.source=qc(this._source,(e=>function(e){return RF.apply(this,arguments)}(e))),this.closeController=new AbortController,this.rateLimiter=new EF({points:null!==(i=r.disconnectThreshold)&&void 0!==i?i:5,duration:1})}get streams(){var e=[];for(var t of this._streams.initiators.values())e.push(t);for(var r of this._streams.receivers.values())e.push(r);return e}newStream(e){if(this.closeController.signal.aborted)throw new ja("Muxer already closed");var t=this._streamId++;e=null==e?t.toString():e.toString();var r=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:r})}close(e){var t=this;return r((function*(){var n;if(!t.closeController.signal.aborted){var i=null!==(n=null==e?void 0:e.signal)&&void 0!==n?n:AbortSignal.timeout(t.closeTimeout);try{yield Promise.all(t.streams.map(function(){var e=r((function*(e){return e.close({signal:i})}));return function(t){return e.apply(this,arguments)}}())),t._source.end(),yield t._source.onEmpty({signal:i}),t.closeController.abort()}catch(e){t.abort(e)}}}))()}abort(e){this.closeController.signal.aborted||(this.streams.forEach((t=>{t.abort(e)})),this.closeController.abort(e))}_newReceiverStream(e){var{id:t,name:r}=e,n=this._streams.receivers;return this._newStream({id:t,name:r,type:"receiver",registry:n})}_newStream(e){var t,n=this,{id:i,name:o,type:a,registry:s}=e;if(this.log("new %s stream %s",a,i),"initiator"===a&&this._streams.initiators.size===(null!==(t=this._init.maxOutboundStreams)&&void 0!==t?t:1024))throw new os("Too many outbound streams open");if(s.has(i))throw new Error("".concat(a," stream ").concat(i," already exists!"));var l=function(){var e=r((function*(e){n.log.enabled&&n.log.trace("%s stream %s send",a,i,MF(e)),n._source.push(e)}));return function(t){return e.apply(this,arguments)}}(),u=function(e){var{id:t,name:r,send:n,onEnd:i,type:o="initiator",maxMsgSize:a=IF}=e;return new LF({id:"initiator"===o?"i".concat(t):"r".concat(t),streamId:t,name:"".concat(null!=r?r:t),direction:"initiator"===o?"outbound":"inbound",maxDataSize:a,onEnd:i,send:n,log:e.logger.forComponent("libp2p:mplex:stream:".concat(o,":").concat(t))})}({id:i,name:o,send:l,type:a,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",a,i,u.protocol),s.delete(i),null!=this._init.onStreamEnd&&this._init.onStreamEnd(u)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return s.set(i,u),u}_createSink(){var e=this,t=function(){var t=r((function*(t){var r=()=>{hp(t,e.log)};e.closeController.signal.addEventListener("abort",r);try{var n,i=new TF(e._init.maxMsgSize,e._init.maxUnprocessedMessageQueueSize),o=!1,a=!1;try{for(var l,u=s(t);o=!(l=yield u.next()).done;o=!1){var c=l.value;for(var d of i.write(c))yield e._handleIncoming(d)}}catch(e){a=!0,n=e}finally{try{o&&null!=u.return&&(yield u.return())}finally{if(a)throw n}}e._source.end()}catch(t){e.log("error in sink",t),e._source.end(t)}finally{e.closeController.signal.removeEventListener("abort",r)}}));return function(e){return t.apply(this,arguments)}}();return t}_handleIncoming(e){var t=this;return r((function*(){var r,{id:n,type:i}=e;if(t.log.enabled&&t.log.trace("incoming message",MF(e)),e.type!==sF.NEW_STREAM){var o=(1&~i?t._streams.receivers:t._streams.initiators).get(n);if(null!=o){var a=null!==(r=t._init.maxStreamBufferSize)&&void 0!==r?r:4194304;try{switch(i){case sF.MESSAGE_INITIATOR:case sF.MESSAGE_RECEIVER:if(o.sourceReadableLength()>a)throw t._source.push({id:e.id,type:i===sF.MESSAGE_INITIATOR?sF.RESET_RECEIVER:sF.RESET_INITIATOR}),new OF("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers");o.sourcePush(e.data);break;case sF.CLOSE_INITIATOR:case sF.CLOSE_RECEIVER:o.remoteCloseWrite();break;case sF.RESET_INITIATOR:case sF.RESET_RECEIVER:o.reset();break;default:t.log("unknown message type %s",i)}}catch(e){t.log.error("error while processing message",e),o.abort(e)}}else{t.log("missing stream %s for message type %s",n,xF[i]);try{yield t.rateLimiter.consume("missing-stream",1)}catch(e){return t.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),void t.abort(new Error("Too many messages for missing streams"))}}}else{var s;if(t._streams.receivers.size===(null!==(s=t._init.maxInboundStreams)&&void 0!==s?s:1024)){t.log("too many inbound streams open"),t._source.push({id:n,type:sF.RESET_RECEIVER});try{yield t.rateLimiter.consume("new-stream",1)}catch(e){return t.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),void t.abort(new Error("Too many open streams"))}return}var l=t._newReceiverStream({id:n,name:gt(e.data instanceof Uint8Array?e.data:e.data.subarray())});null!=t._init.onIncomingStream&&t._init.onIncomingStream(l)}}))()}}class FF{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"protocol","/mplex/6.7.0"),e(this,"_init",void 0),e(this,"components",void 0),e(this,Symbol.toStringTag,"@libp2p/mplex"),e(this,fs,["@libp2p/stream-multiplexing"]),this.components=t,this._init=r}createStreamMuxer(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new UF(this.components,t(t({},e),this._init))}}function zF(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new FF(t,e)}class jF{constructor(t){var r,n,i,o,a,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"protocol",void 0),e(this,"components",void 0),e(this,"started",void 0),e(this,"timeout",void 0),e(this,"maxInboundStreams",void 0),e(this,"maxOutboundStreams",void 0),e(this,"runOnLimitedConnection",void 0),e(this,"log",void 0),e(this,Symbol.toStringTag,"@libp2p/ping"),e(this,fs,["@libp2p/ping"]),this.components=t,this.log=t.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol="/".concat(null!==(r=s.protocolPrefix)&&void 0!==r?r:"ipfs","/").concat("ping","/").concat("1.0.0"),this.timeout=null!==(n=s.timeout)&&void 0!==n?n:1e4,this.maxInboundStreams=null!==(i=s.maxInboundStreams)&&void 0!==i?i:2,this.maxOutboundStreams=null!==(o=s.maxOutboundStreams)&&void 0!==o?o:1,this.runOnLimitedConnection=null===(a=s.runOnLimitedConnection)||void 0===a||a,this.handleMessage=this.handleMessage.bind(this)}start(){var e=this;return r((function*(){yield e.components.registrar.handle(e.protocol,e.handleMessage,{maxInboundStreams:e.maxInboundStreams,maxOutboundStreams:e.maxOutboundStreams,runOnLimitedConnection:e.runOnLimitedConnection}),e.started=!0}))()}stop(){var e=this;return r((function*(){yield e.components.registrar.unhandle(e.protocol),e.started=!1}))()}isStarted(){return this.started}handleMessage(e){var t=this;this.log("incoming ping from %p",e.connection.remotePeer);var{stream:n}=e,i=Date.now(),o=kd(n),a=!1;Promise.resolve().then(r((function*(){for(;;){var e=AbortSignal.timeout(t.timeout);e.addEventListener("abort",(()=>{null==n||n.abort(new $a("ping timeout"))}));var r=yield o.read({bytes:32,signal:e});yield o.write(r,{signal:e}),a=!0}}))).catch((t=>{a&&"UnexpectedEOFError"===t.name&&"ready"!==n.readStatus||(this.log.error("incoming ping from %p failed with error - %e",e.connection.remotePeer,t),null==n||n.abort(t))})).finally((()=>{var t=Date.now()-i;this.log("incoming ping from %p complete in %dms",e.connection.remotePeer,t);var r=AbortSignal.timeout(this.timeout);n.close({signal:r}).catch((t=>{this.log.error("error closing ping stream from %p - %e",e.connection.remotePeer,t),null==n||n.abort(t)}))}))}ping(e){var n=arguments,i=this;return r((function*(){var r=n.length>1&&void 0!==n[1]?n[1]:{};i.log("pinging %p",e);var o,a=Date.now(),s=Zl(32),l=yield i.components.connectionManager.openConnection(e,r);if(null==r.signal){var u=AbortSignal.timeout(i.timeout);r=t(t({},r),{},{signal:u})}try{var c=kd(o=yield l.newStream(i.protocol,t(t({},r),{},{runOnLimitedConnection:i.runOnLimitedConnection}))),[,d]=yield Promise.all([c.write(s,r),c.read(t(t({},r),{},{bytes:32}))]),h=Date.now()-a;if(!Et(s,d.subarray()))throw new Za("Received wrong ping ack after ".concat(h,"ms"));return i.log("ping %p complete in %dms",l.remotePeer,h),h}catch(e){var v;throw i.log.error("error while pinging %p",l.remotePeer,e),null===(v=o)||void 0===v||v.abort(e),e}finally{null!=o&&(yield o.close(r))}}))()}}function VF(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new jF(t,e)}var qF,HF,KF=function(){var e=r((function*(e){if(e.readyState>=2)throw new Error("socket closed");1!==e.readyState&&(yield new Promise(((t,r)=>{function n(){e.removeEventListener("open",i),e.removeEventListener("error",o)}function i(){n(),t()}function o(t){var i;n(),r(null!==(i=t.error)&&void 0!==i?i:new Error("connect ECONNREFUSED ".concat(e.url)))}e.addEventListener("open",i),e.addEventListener("error",o)})))}));return function(t){return e.apply(this,arguments)}}(),WF=(e,t)=>{(t=null!=t?t:{}).closeOnEnd=!1!==t.closeOnEnd;var n=function(){var n=r((function*(r){var n,i=!1,o=!1;try{for(var a,l=s(r);i=!(a=yield l.next()).done;i=!1){var u=a.value;try{yield KF(e)}catch(e){if("socket closed"===e.message)break;throw e}if(e.readyState===e.CLOSING||e.readyState===e.CLOSED)break;e.send(u)}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield l.return())}finally{if(o)throw n}}null!=t.closeOnEnd&&e.readyState<=1&&(yield new Promise(((t,r)=>{e.addEventListener("close",(e=>{if(e.wasClean||1006===e.code)t();else{var n=Object.assign(new Error("ws error"),{event:e});r(n)}})),setTimeout((()=>{e.close()}))})))}));return function(e){return n.apply(this,arguments)}}();return n},GF={},QF={};var YF=function(){if(HF)return GF;HF=1,Object.defineProperty(GF,"__esModule",{value:!0});var e=function(){if(qF)return QF;qF=1,Object.defineProperty(QF,"__esModule",{value:!0});class e{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(!this.isStopped){var t={value:e,done:!1};if(this.pullQueue.length){var r=this.pullQueue.shift();r&&r.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)}}stop(){if(!this.isStopped){for(var e of(this.isStopped=!0,this.remove(),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(var t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{var r=Promise.reject(e);r.catch((()=>{})),this.pushQueue.push(r)}}remove(){Promise.resolve().then((()=>{this.removeCallback&&this.removeCallback()}))}[Symbol.asyncIterator](){return{next:e=>{var 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 t{constructor(t){var{highWaterMark:r=100,lowWaterMark:n=1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=new e;i.highWaterMark=r,i.lowWaterMark=n,i.removeCallback=t({push:e=>i.push(e),stop:()=>i.stop(),fail:e=>i.fail(e),on:(e,t)=>{i.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}}return QF.EventIterator=t,QF.default=t,QF}();return GF.EventIterator=e.EventIterator,GF.subscribe=function(t,r,n){return new e.EventIterator((e=>{var{push:n}=e;return this.addEventListener(t,n,r),()=>this.removeEventListener(t,n,r)}),n)},GF.default=e.EventIterator,GF}();function JF(e){var t;return e instanceof ArrayBuffer||"ArrayBuffer"===(null==e||null===(t=e.constructor)||void 0===t?void 0:t.name)&&"number"==typeof(null==e?void 0:e.byteLength)}var ZF=e=>{e.binaryType="arraybuffer";var t,n=function(){var n=r((function*(){yield new Promise(((r,n)=>{if(o)r();else if(null==t){var i=t=>{e.removeEventListener("open",a),e.removeEventListener("error",s),t()},a=()=>{i(r)},s=t=>{i((()=>{var r;n(null!==(r=t.error)&&void 0!==r?r:new Error("connect ECONNREFUSED ".concat(e.url)))}))};e.addEventListener("open",a),e.addEventListener("error",s)}else n(t)}))}));return function(){return n.apply(this,arguments)}}(),i=l((function*(){var t=new YF.EventIterator((t=>{var{push:r,stop:n,fail:i}=t,o=e=>{var t=null;"string"==typeof e.data&&(t=xt(e.data)),JF(e.data)&&(t=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(t=e.data),null!=t&&r(t)},a=e=>{var t;i(null!==(t=e.error)&&void 0!==t?t:new Error("Socket error"))};return e.addEventListener("message",o),e.addEventListener("error",a),e.addEventListener("close",n),()=>{e.removeEventListener("message",o),e.removeEventListener("error",a),e.removeEventListener("close",n)}}),{highWaterMark:1/0});yield u(n());var r,i=!1,o=!1;try{for(var a,l=s(t);i=!(a=yield u(l.next())).done;i=!1){var c=a.value;yield JF(c)?new Uint8Array(c):c}}catch(e){o=!0,r=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw r}}}))(),o=1===e.readyState;return e.addEventListener("open",(()=>{o=!0,t=null})),e.addEventListener("close",(()=>{o=!1,t=null})),e.addEventListener("error",(r=>{var n;o||(t=null!==(n=r.error)&&void 0!==n?n:new Error("connect ECONNREFUSED ".concat(e.url)))})),Object.assign(i,{connected:n})},$F=(e,t)=>{t=null!=t?t:{};var n=ZF(e),i=t.remoteAddress,o=t.remotePort;if(null!=e.url)try{var a=new URL(e.url);i=a.hostname,o=parseInt(a.port,10)}catch(e){}if(null==i||null==o)throw new Error("Remote connection did not have address and/or port");var s,l,u={sink:WF(e,t),source:n,connected:(l=r((function*(){yield n.connected()})),function(){return l.apply(this,arguments)}),close:(s=r((function*(){e.readyState!==e.CONNECTING&&e.readyState!==e.OPEN||(yield new Promise((t=>{e.addEventListener("close",(()=>{t()})),e.close()})))})),function(){return s.apply(this,arguments)}),destroy:()=>{null!=e.terminate?e.terminate():e.close()},remoteAddress:i,remotePort:o,socket:e};return u},XF=WebSocket,ez={"http:":"ws:","https:":"wss:"};function tz(e,t){t=null!=t?t:{};var r=((e,t)=>{var r;if(e.startsWith("//")&&(e="".concat(null!==(r=null==t?void 0:t.protocol)&&void 0!==r?r:"ws:").concat(e)),e.startsWith("/")&&null!=t){var n,i=null!==(n=t.protocol)&&void 0!==n?n:"ws:",o=t.host,a=null!=t.port&&!0!==(null==o?void 0:o.endsWith(":".concat(t.port)))?":".concat(t.port):"";e="".concat(i,"//").concat(o).concat(a).concat(e)}var s=new URL(e);for(var[l,u]of Object.entries(ez))s.protocol===l&&(s.protocol=u);return s})(e,"undefined"==typeof window?void 0:window.location),n=new XF(r.toString(),t.websocket);return $F(n,t)}class rz{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"log",void 0),e(this,"init",void 0),e(this,"logger",void 0),e(this,"metrics",void 0),e(this,"components",void 0),e(this,_a,!0),e(this,Symbol.toStringTag,"@libp2p/websockets"),e(this,fs,["@libp2p/transport"]),this.log=t.logger.forComponent("libp2p:websockets"),this.logger=t.logger,this.components=t,this.init=r,null!=t.metrics&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}dial(e,n){var i=this;return r((function*(){var o;i.log("dialing %s",e),n=null!=n?n:{};var a=function(e,n,i){var o,a=i.logger.forComponent("libp2p:websockets:maconn"),c=i.metrics,d=null!==(o=i.metricPrefix)&&void 0!==o?o:"",h={log:a,sink:t=>r((function*(){try{yield e.sink(l((function*(){var e,r=!1,n=!1;try{for(var i,o=s(t);r=!(i=yield u(o.next())).done;r=!1){var a=i.value;a instanceof Uint8Array?yield a:yield a.subarray()}}catch(t){n=!0,e=t}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw e}}}))())}catch(e){"aborted"!==e.type&&a.error(e)}}))(),source:e.source,remoteAddr:n,timeline:{open:Date.now()},close(){var n=arguments,i=this;return r((function*(){var r,o=n.length>0&&void 0!==n[0]?n[0]:{},s=Date.now();if(null==o.signal){var l=AbortSignal.timeout(500);o=t(t({},o),{},{signal:l})}var u=()=>{var{host:e,port:t}=h.remoteAddr.toOptions();a("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-s),i.abort(new Ba("Socket close timeout"))};null===(r=o.signal)||void 0===r||r.addEventListener("abort",u);try{yield e.close()}catch(e){a.error("error closing WebSocket gracefully",e),i.abort(e)}finally{var c;null===(c=o.signal)||void 0===c||c.removeEventListener("abort",u),h.timeline.close=Date.now()}}))()},abort(t){var{host:r,port:n}=h.remoteAddr.toOptions();a("timeout closing stream to %s:%s due to error",r,n,t),e.destroy(),h.timeline.close=Date.now(),null==c||c.increment({["".concat(d,"error")]:!0})}};return e.socket.addEventListener("close",(()=>{null==c||c.increment({["".concat(d,"close")]:!0}),null==h.timeline.close&&(h.timeline.close=Date.now())}),{once:!0}),h}(yield i._connect(e,n),e,{logger:i.logger,metrics:null===(o=i.metrics)||void 0===o?void 0:o.dialerEvents});i.log("new outbound connection %s",a.remoteAddr);var c=yield n.upgrader.upgradeOutbound(a,n);return i.log("outbound connection %s upgraded",a.remoteAddr),c}))()}_connect(e,t){var n=this;return r((function*(){var r,i;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted();var o=e.toOptions();n.log("dialing %s:%s",o.host,o.port);var a=_c(),s=tz(bD(e),n.init);s.socket.addEventListener("error",(()=>{var t,r=new za("Could not connect to ".concat(e.toString()));n.log.error("connection error:",r),null===(t=n.metrics)||void 0===t||t.dialerEvents.increment({error:!0}),a.reject(r)}));try{var l;null===(l=t.onProgress)||void 0===l||l.call(t,new cv("websockets:open-connection")),yield Lc(Promise.race([s.connected(),a.promise]),t.signal)}catch(e){var u,c;if(null!==(u=t.signal)&&void 0!==u&&u.aborted)null===(c=n.metrics)||void 0===c||c.dialerEvents.increment({abort:!0});throw s.close().catch((e=>{n.log.error("error closing raw socket",e)})),e}return n.log("connected %s",e),null===(i=n.metrics)||void 0===i||i.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),t(t({},this.init),e))}listenFilter(e){var t,r;return e=Array.isArray(e)?e:[e],null!=(null===(t=this.init)||void 0===t?void 0:t.filter)?null===(r=this.init)||void 0===r?void 0:r.filter(e):function(e){return e.filter((e=>Eh.exactMatch(e)||bh.exactMatch(e)))}(e)}dialFilter(e){return this.listenFilter(e)}}function nz(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new rz(t,e)}function iz(e,t){var r=t.map(((e,t)=>({record:rR(e),index:t})));return r.sort(((e,t)=>{var r=e.record.sequence,n=t.record.sequence;if(r>n)return-1;if(r<n)return 1;if(e.record.validityType===VD.ValidityType.EOL&&t.record.validityType===VD.ValidityType.EOL){var i=HD.fromString(e.record.validity).toDate(),o=HD.fromString(t.record.validity).toDate();if(i.getTime()>o.getTime())return-1;if(i.getTime()<o.getTime())return 1}return 0})),r[0].index}var oz="2.8.8",az="js-libp2p";function sz(e,t){return"".concat(null!=e?e:az,"/").concat(null!=t?t:oz," browser/").concat(globalThis.navigator.userAgent)}var lz={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function uz(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r="".concat("helia","/").concat("5.3.0"," ").concat(sz());return{privateKey:t.privateKey,dns:t.dns,nodeInfo:{userAgent:r},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[Lv(),GI(),WI(),nz()],connectionEncrypters:[DI()],streamMuxers:[xO(),zF()],peerDiscovery:[(e=lz,t=>new uL(t,e))],services:{autoNAT:_O(),dcutr:EL(),delegatedRouting:()=>function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new xR(new URL(e),t)}("https://delegated-ipfs.dev",{filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}),dht:wU({clientMode:!0,validators:{ipns:uR},selectors:{ipns:iz}}),identify:DL(),identifyPush:RL(),keychain:SF(t.keychain),ping:VF()}}}function cz(){return cz=r((function*(e){var t,r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=null!==(t=i.selfKey)&&void 0!==t?t:"self",a=SF(i)({datastore:e,logger:cd()});(yield e.has(new hc("/pkcs8/".concat(o))))?r=yield a.exportKey(o):(r=yield bu(null!==(n=i.keyType)&&void 0!==n?n:"Ed25519"),yield a.importKey(o,r));return r})),cz.apply(this,arguments)}var dz=-1,hz={},vz={};[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,dz,"ip6zone"],[43,8,"ipcidr"],[53,dz,"dns",!0],[54,dz,"dns4",!0],[55,dz,"dns6",!0],[56,dz,"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,dz,"unix",!1,!0],[421,dz,"ipfs"],[421,dz,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,dz,"garlic64"],[448,0,"tls"],[449,dz,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,dz,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,dz,"http-path"],[777,dz,"memory"]].forEach((e=>{var t=function(e,t,r,n,i){return{code:e,size:t,name:r,resolvable:Boolean(n),path:Boolean(i)}}(...e);vz[t.code]=t,hz[t.name]=t}));var{code:pz}=function(e){if(null!=hz[e])return hz[e];throw new Error("no protocol with name: ".concat(e))}("dnsaddr");class fz extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Max recursive depth reached"),this.name="RecursionLimitError"}}var gz=function(){var e=r((function*(e){var r,n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=null!==(r=o.maxRecursiveDepth)&&void 0!==r?r:32;if(0===a)throw new fz("Max recursive depth reached");var[,s]=null!==(n=e.stringTuples().find((e=>{var[t]=e;return t===pz})))&&void 0!==n?n:[],l=null!==(i=null==o?void 0:o.dns)&&void 0!==i?i:oP(),u=yield l.query("_dnsaddr.".concat(s),{signal:null==o?void 0:o.signal,types:[iP.TXT]}),c=e.getPeerId(),d=[];for(var h of u.Answer){var v=h.data.replace(/["']/g,"").trim().split("=")[1];if(null!=v&&(null==c||v.includes(c))){var p=Ir(v);if(v.startsWith("/dnsaddr")){var f=yield p.resolve(t(t({},o),{},{maxRecursiveDepth:a-1}));d.push(...f.map((e=>e.toString())))}else d.push(p.toString())}}return d}));return function(t){return e.apply(this,arguments)}}(),yz={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:gz}},transportManager:{faultTolerance:Ia.FATAL_ALL}};function mz(){return mz=r((function*(e){var t,r=UU(yz,e);if(null===r.connectionProtector&&null!=(null===(t=globalThis.process)||void 0===t||null===(t=t.env)||void 0===t?void 0:t.LIBP2P_FORCE_PNET))throw new Ra("Private network is enforced, but no protector was provided");return r})),mz.apply(this,arguments)}var wz,bz,Sz;function Ez(e,t){if(null!=e.publicKey||null==t.publicKey)return e;var r;"RSA"===e.type&&(r=He(ie.decode("z".concat(e))));return Uu(Eu(t.publicKey,r))}function kz(e,t,r){return xz(e,wz.decode(t),r)}function xz(e,r,n){var i,o=new Map,a=BigInt(Date.now());for(var[s,l]of r.tags.entries())null!=l.expiry&&l.expiry<a||o.set(s,l);return t(t({},r),{},{id:Ez(e,r),addresses:r.addresses.filter((e=>{var{observed:t}=e;return null!=t&&t>Date.now()-n})).map((e=>{var{multiaddr:t,isCertified:r}=e;return{multiaddr:Ir(t),isCertified:null!=r&&r}})),metadata:r.metadata,peerRecordEnvelope:null!==(i=r.peerRecordEnvelope)&&void 0!==i?i:void 0,tags:o})}function Az(e,t){return c=e.addresses,d=t.addresses,Iz(c,d,((e,t)=>e.isCertified===t.isCertified&&!!Et(e.multiaddr,t.multiaddr)))&&(l=e.protocols,u=t.protocols,Iz(l,u,((e,t)=>e===t)))&&(a=e.publicKey,s=t.publicKey,Cz(a,s))&&(i=e.peerRecordEnvelope,o=t.peerRecordEnvelope,Cz(i,o))&&(r=e.metadata,n=t.metadata,Tz(r,n,((e,t)=>Et(e,t))))&&function(e,t){return Tz(e,t,((e,t)=>e.value===t.value&&e.expiry===t.expiry))}(e.tags,t.tags);var r,n,i,o,a,s,l,u,c,d}function Cz(e,t){return null==e&&null==t||null!=e&&null!=t&&Et(e,t)}function Iz(e,t,r){if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!r(e[n],t[n]))return!1;return!0}function Tz(e,t,r){if(e.size!==t.size)return!1;for(var[n,i]of e.entries()){var o=t.get(n);if(null==o)return!1;if(!r(i,o))return!1}return!0}!function(e){var t;!function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!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()}),(function(e,t){for(var r={key:"",value:ct(0)},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.key=e.string();break;case 2:r.value=e.bytes();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&(t.uint32(18),Sz.codec().encode(e.value,t)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={key:""},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.key=e.string();break;case 2:var a;n.value=Sz.codec().decode(e,e.uint32(),{limits:null===(a=r.limits)||void 0===a?void 0:a.value});break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==t&&(t=Ql((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==n.lengthDelimited&&r.fork(),null!=t.addresses)for(var i of t.addresses)r.uint32(10),bz.codec().encode(i,r);if(null!=t.protocols)for(var o of t.protocols)r.uint32(18),r.string(o);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(var[a,s]of t.metadata.entries())r.uint32(50),e.Peer$metadataEntry.codec().encode({key:a,value:s},r);if(null!=t.tags&&0!==t.tags.size)for(var[l,u]of t.tags.entries())r.uint32(58),e.Peer$tagsEntry.codec().encode({key:l,value:u},r);null!=t.updated&&(r.uint32(64),r.uint64Number(t.updated)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={addresses:[],protocols:[],metadata:new Map,tags:new Map},o=null==r?t.len:t.pos+r;t.pos<o;){var a=t.uint32();switch(a>>>3){case 1:var s,l;if(null!=(null===(s=n.limits)||void 0===s?void 0:s.addresses)&&i.addresses.length===n.limits.addresses)throw new Yl('Decode error - map field "addresses" had too many elements');i.addresses.push(bz.codec().decode(t,t.uint32(),{limits:null===(l=n.limits)||void 0===l?void 0:l.addresses$}));break;case 2:var u;if(null!=(null===(u=n.limits)||void 0===u?void 0:u.protocols)&&i.protocols.length===n.limits.protocols)throw new Yl('Decode error - map field "protocols" had too many elements');i.protocols.push(t.string());break;case 4:i.publicKey=t.bytes();break;case 5:i.peerRecordEnvelope=t.bytes();break;case 6:var c;if(null!=(null===(c=n.limits)||void 0===c?void 0:c.metadata)&&i.metadata.size===n.limits.metadata)throw new Jl('Decode error - map field "metadata" had too many elements');var d=e.Peer$metadataEntry.codec().decode(t,t.uint32());i.metadata.set(d.key,d.value);break;case 7:var h,v;if(null!=(null===(h=n.limits)||void 0===h?void 0:h.tags)&&i.tags.size===n.limits.tags)throw new Jl('Decode error - map field "tags" had too many elements');var p=e.Peer$tagsEntry.codec().decode(t,t.uint32(),{limits:{value:null===(v=n.limits)||void 0===v?void 0:v.tags$value}});i.tags.set(p.key,p.value);break;case 8:i.updated=t.uint64Number();break;default:t.skipType(7&a)}}return i}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(wz||(wz={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!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()}),(function(e,t){for(var r={multiaddr:ct(0)},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.multiaddr=e.bytes();break;case 2:r.isCertified=e.bool();break;case 3:r.observed=e.uint64Number();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(bz||(bz={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!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()}),(function(e,t){for(var r={value:0},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.value=e.uint32();break;case 2:r.expiry=e.uint64();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=(t,r)=>kl(t,e.codec(),r)}(Sz||(Sz={}));var Pz="/peers/";function _z(e){if(!Ca(e)||null==e.type)throw new Ra("Invalid PeerId");var t=e.toCID().toString();return new hc("".concat(Pz).concat(t))}function Bz(e,t,r,n){return Nz.apply(this,arguments)}function Nz(){return Nz=r((function*(e,t,r,n){var i=new Map;for(var o of r){var a;if(null!=o){if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=Ir(o.multiaddr)),!Cr(o.multiaddr))throw new Ra("Multiaddr was invalid");if(yield t(e,o.multiaddr)){var s=null!==(a=o.isCertified)&&void 0!==a&&a,l=o.multiaddr.toString(),u=i.get(l);null!=u?o.isCertified=u.isCertified||s:i.set(l,{multiaddr:o.multiaddr,isCertified:s})}}}return[...i.values()].sort(((e,t)=>e.multiaddr.toString().localeCompare(t.multiaddr.toString()))).map((t=>{var{isCertified:r,multiaddr:n}=t,i=n.getPeerId();return e.equals(i)&&(n=n.decapsulate(Ir("/p2p/".concat(e)))),{isCertified:r,multiaddr:n.bytes}}))})),Nz.apply(this,arguments)}function Dz(e,t,r,n){return Rz.apply(this,arguments)}function Rz(){return Rz=r((function*(e,t,n,i){var o,a,s,l,u,c,d;if(null==t)throw new Ra("Invalid PeerData");if(null!=t.publicKey&&null!=e.publicKey&&!t.publicKey.equals(e.publicKey))throw new Ra("publicKey bytes do not match peer id publicKey bytes");var h=null===(o=i.existingPeer)||void 0===o?void 0:o.peer;if(null!=h&&!e.equals(h.id))throw new Ra("peer id did not match existing peer id");var v,p=null!==(a=null==h?void 0:h.addresses)&&void 0!==a?a:[],f=new Set(null!==(s=null==h?void 0:h.protocols)&&void 0!==s?s:[]),g=null!==(l=null==h?void 0:h.metadata)&&void 0!==l?l:new Map,y=null!==(u=null==h?void 0:h.tags)&&void 0!==u?u:new Map,m=null==h?void 0:h.peerRecordEnvelope;if("patch"===n){if(null==t.multiaddrs&&null==t.addresses||(p=[],null!=t.multiaddrs&&p.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&p.push(...t.addresses)),null!=t.protocols&&(f=new Set(t.protocols)),null!=t.metadata)g=Oz(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:Lz});if(null!=t.tags)y=Oz(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:Mz,map:Uz});null!=t.peerRecordEnvelope&&(m=t.peerRecordEnvelope)}if("merge"===n){if(null!=t.multiaddrs&&p.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&p.push(...t.addresses),null!=t.protocols&&(f=new Set([...f,...t.protocols])),null!=t.metadata){var w=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(var[b,S]of w)null==S?g.delete(b):g.set(b,S);g=Oz([...g.entries()],{validate:Lz})}if(null!=t.tags){var E=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),k=new Map(y);for(var[x,A]of E)null==A?k.delete(x):k.set(x,A);y=Oz([...k.entries()],{validate:Mz,map:Uz})}null!=t.peerRecordEnvelope&&(m=t.peerRecordEnvelope)}null!=(null==h?void 0:h.id.publicKey)?v=Au(h.id.publicKey):null!=t.publicKey?v=Au(t.publicKey):null!=e.publicKey&&(v=Au(e.publicKey));var C={addresses:yield Bz(e,null!==(c=i.addressFilter)&&void 0!==c?c:r((function*(){return!0})),p,null===(d=i.existingPeer)||void 0===d?void 0:d.peerPB.addresses),protocols:[...f.values()].sort(((e,t)=>e.localeCompare(t))),metadata:g,tags:y,publicKey:v,peerRecordEnvelope:m};return C.addresses.forEach((e=>{var t,r;e.observed=null!==(t=null===(r=i.existingPeer)||void 0===r||null===(r=r.peerPB.addresses)||void 0===r||null===(r=r.find((e=>Et(e.multiaddr,e.multiaddr))))||void 0===r?void 0:r.observed)&&void 0!==t?t:Date.now()})),"RSA"!==e.type&&delete C.publicKey,C})),Rz.apply(this,arguments)}function Oz(e,t){var r=new Map;for(var[n,i]of e)null!=i&&t.validate(n,i);for(var[o,a]of e.sort(((e,t)=>{var[r]=e,[n]=t;return r.localeCompare(n)}))){var s,l;if(null!=a)r.set(o,null!==(s=null===(l=t.map)||void 0===l?void 0:l.call(t,o,a))&&void 0!==s?s:a)}return r}function Lz(e,t){if("string"!=typeof e)throw new Ra("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new Ra("Metadata value must be a Uint8Array")}function Mz(e,t){if("string"!=typeof e)throw new Ra("Tag name must be a string");if(null!=t.value){if(parseInt("".concat(t.value),10)!==t.value)throw new Ra("Tag value must be an integer");if(t.value<0||t.value>100)throw new Ra("Tag value must be between 0-100")}if(null!=t.ttl){if(parseInt("".concat(t.ttl),10)!==t.ttl)throw new Ra("Tag ttl must be an integer");if(t.ttl<0)throw new Ra("Tag ttl must be between greater than 0")}}function Uz(e,t){var r,n;return null!=t.expiry&&(n=t.expiry),null!=t.ttl&&(n=BigInt(Date.now()+Number(t.ttl))),{value:null!==(r=t.value)&&void 0!==r?r:0,expiry:n}}function Fz(e){var t=e.toString().split("/")[2];return ju(it.parse(t,K))}function zz(e,t,r){return kz(Fz(e),t,r)}var jz=new WeakSet;class Vz{constructor(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};d(this,jz),e(this,"peerId",void 0),e(this,"datastore",void 0),e(this,"lock",void 0),e(this,"addressFilter",void 0),e(this,"log",void 0),e(this,"maxAddressAge",void 0),e(this,"maxPeerAge",void 0),this.log=t.logger.forComponent("libp2p:peer-store"),this.peerId=t.peerId,this.datastore=t.datastore,this.addressFilter=i.addressFilter,this.lock=zB({name:"peer-store",singleProcess:!0}),this.maxAddressAge=null!==(r=i.maxAddressAge)&&void 0!==r?r:36e5,this.maxPeerAge=null!==(n=i.maxPeerAge)&&void 0!==n?n:216e5}has(e){var t=this;return r((function*(){try{return yield t.load(e),!0}catch(e){if("NotFoundError"!==e.name)throw e}return!1}))()}delete(e){var t=this;return r((function*(){t.peerId.equals(e)||(yield t.datastore.delete(_z(e)))}))()}load(e){var t=this;return r((function*(){var r=_z(e),n=yield t.datastore.get(r),i=wz.decode(n);if(h(jz,t,Gz).call(t,e,i))throw yield t.datastore.delete(r),new Ha;return xz(e,i,t.peerId.equals(e)?1/0:t.maxAddressAge)}))()}save(e,t){var n=this;return r((function*(){var r=yield h(jz,n,qz).call(n,e),i=yield Dz(e,t,"patch",{addressFilter:n.addressFilter});return h(jz,n,Kz).call(n,e,i,r)}))()}patch(e,t){var n=this;return r((function*(){var r=yield h(jz,n,qz).call(n,e),i=yield Dz(e,t,"patch",{addressFilter:n.addressFilter,existingPeer:r});return h(jz,n,Kz).call(n,e,i,r)}))()}merge(e,t){var n=this;return r((function*(){var r=yield h(jz,n,qz).call(n,e),i=yield Dz(e,t,"merge",{addressFilter:n.addressFilter,existingPeer:r});return h(jz,n,Kz).call(n,e,i,r)}))()}all(e){var t=this;return l((function*(){var r,n=!1,i=!1;try{for(var o,a=s(t.datastore.query(function(e,t){var r,n;return{prefix:Pz,filters:(null!==(r=e.filters)&&void 0!==r?r:[]).map((e=>r=>{var{key:n,value:i}=r;return e(zz(n,i,t))})),orders:(null!==(n=e.orders)&&void 0!==n?n:[]).map((e=>(r,n)=>e(zz(r.key,r.value,t),zz(n.key,n.value,t))))}}(null!=e?e:{},t.maxAddressAge)));n=!(o=yield u(a.next())).done;n=!1){var{key:l,value:c}=o.value,d=Fz(l);if(!d.equals(t.peerId)){var v=wz.decode(c);h(jz,t,Gz).call(t,d,v)?yield u(t.datastore.delete(l)):yield xz(d,v,t.peerId.equals(d)?1/0:t.maxAddressAge)}}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield u(a.return()))}finally{if(i)throw r}}}))()}}function qz(e){return Hz.apply(this,arguments)}function Hz(){return Hz=r((function*(e){try{var t=_z(e),r=yield this.datastore.get(t),n=wz.decode(r);if(h(jz,this,Gz).call(this,e,n))throw yield this.datastore.delete(t),new Ha;return{peerPB:n,peer:kz(e,r,this.maxAddressAge)}}catch(e){"NotFoundError"!==e.name&&this.log.error("invalid peer data found in peer store - %e",e)}})),Hz.apply(this,arguments)}function Kz(e,t,r){return Wz.apply(this,arguments)}function Wz(){return Wz=r((function*(e,t,r){t.updated=Date.now();var n=wz.encode(t);return yield this.datastore.put(_z(e),n),{peer:kz(e,n,this.maxAddressAge),previous:null==r?void 0:r.peer,updated:null==r||!Az(t,r.peerPB)}})),Wz.apply(this,arguments)}function Gz(e,t){if(null==t.updated)return!0;if(this.peerId.equals(e))return!1;var r=t.updated<Date.now()-this.maxPeerAge,n=Date.now()-this.maxAddressAge,i=t.addresses.filter((e=>null!=e.observed&&e.observed>n));return r&&0===i.length}var Qz=new WeakSet;class Yz{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};d(this,Qz),e(this,"store",void 0),e(this,"events",void 0),e(this,"peerId",void 0),e(this,"log",void 0),e(this,Symbol.toStringTag,"@libp2p/peer-store"),this.log=t.logger.forComponent("libp2p:peer-store"),this.events=t.events,this.peerId=t.peerId,this.store=new Vz(t,r)}forEach(e,t){var n=this;return r((function*(){n.log.trace("forEach await read lock");var r=yield n.store.lock.readLock();n.log.trace("forEach got read lock");try{var i,o=!1,a=!1;try{for(var l,u=s(n.store.all(t));o=!(l=yield u.next()).done;o=!1){var c=l.value;e(c)}}catch(e){a=!0,i=e}finally{try{o&&null!=u.return&&(yield u.return())}finally{if(a)throw i}}}finally{n.log.trace("forEach release read lock"),r()}}))()}all(e){var t=this;return r((function*(){t.log.trace("all await read lock");var r=yield t.store.lock.readLock();t.log.trace("all got read lock");try{return yield gc(t.store.all(e))}finally{t.log.trace("all release read lock"),r()}}))()}delete(e){var t=this;return r((function*(){t.log.trace("delete await write lock");var r=yield t.store.lock.writeLock();t.log.trace("delete got write lock");try{yield t.store.delete(e)}finally{t.log.trace("delete release write lock"),r()}}))()}has(e){var t=this;return r((function*(){t.log.trace("has await read lock");var r=yield t.store.lock.readLock();t.log.trace("has got read lock");try{return yield t.store.has(e)}finally{t.log.trace("has release read lock"),r()}}))()}get(e){var t=this;return r((function*(){t.log.trace("get await read lock");var r=yield t.store.lock.readLock();t.log.trace("get got read lock");try{return yield t.store.load(e)}finally{t.log.trace("get release read lock"),r()}}))()}getInfo(e){var t=this;return r((function*(){var r=yield t.get(e);return{id:r.id,multiaddrs:r.addresses.map((e=>{var{multiaddr:t}=e;return t}))}}))()}save(e,t){var n=this;return r((function*(){n.log.trace("save await write lock");var r=yield n.store.lock.writeLock();n.log.trace("save got write lock");try{var i=yield n.store.save(e,t);return h(Qz,n,Jz).call(n,e,i),i.peer}finally{n.log.trace("save release write lock"),r()}}))()}patch(e,t){var n=this;return r((function*(){n.log.trace("patch await write lock");var r=yield n.store.lock.writeLock();n.log.trace("patch got write lock");try{var i=yield n.store.patch(e,t);return h(Qz,n,Jz).call(n,e,i),i.peer}finally{n.log.trace("patch release write lock"),r()}}))()}merge(e,t){var n=this;return r((function*(){n.log.trace("merge await write lock");var r=yield n.store.lock.writeLock();n.log.trace("merge got write lock");try{var i=yield n.store.merge(e,t);return h(Qz,n,Jz).call(n,e,i),i.peer}finally{n.log.trace("merge release write lock"),r()}}))()}consumePeerRecord(e,t){var n=this;return r((function*(){var r,i=yield gd.openAndCertify(e,Sd.DOMAIN),o=ju(i.publicKey.toCID());if(!1===(null==t?void 0:t.equals(o)))return n.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,o),!1;var a,s=Sd.createFromProtobuf(i.payload);try{a=yield n.get(o)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=(null===(r=a)||void 0===r?void 0:r.peerRecordEnvelope)){var l=yield gd.createFromProtobuf(a.peerRecordEnvelope),u=Sd.createFromProtobuf(l.payload);if(u.seqNumber>=s.seqNumber)return n.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",u.seqNumber,s.seqNumber),!1}return yield n.patch(s.peerId,{peerRecordEnvelope:e,addresses:s.multiaddrs.map((e=>({isCertified:!0,multiaddr:e})))}),!0}))()}}function Jz(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}var Zz=864e13;class $z{constructor(t){e(this,"log",void 0),e(this,"mappings",void 0),this.log=t.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=new Map}has(e){var t=this.findHost(e);for(var r of this.mappings.values())if(r.domain===t)return!0;return!1}add(e,t){t.forEach((t=>{this.log("add DNS mapping %s to %s",t,e);var r=!0===hD(t);this.mappings.set(t,{domain:e,verified:r,expires:r?Zz-Date.now():0,lastVerified:r?Zz-Date.now():void 0})}))}remove(e){var t=this.findHost(e),r=!1;for(var[n,i]of this.mappings.entries())i.domain===t&&(this.log("removing %s to %s DNS mapping %e",n,i.domain,new Error("where")),this.mappings.delete(n),r=r||i.verified);return r}getAll(e){for(var t=[],r=0;r<e.length;r++){var n=e[r].multiaddr.stringTuples(),i=n[0][1];if(null!=i)for(var[o,a]of this.mappings.entries()){if(i===o)this.maybeAddSNITuple(n,a.domain)&&(e.splice(r,1),r--,t.push({multiaddr:Ir("/".concat(n.map((e=>[Tr(e[0]).name,e[1]].join("/"))).join("/"))),verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNITuple(e,t){for(var r=0;r<e.length;r++){var n;if(448===e[r][0]&&449!==(null===(n=e[r+1])||void 0===n?void 0:n[0]))return e.splice(r+1,0,[449,t]),!0}return!1}confirm(e,t){var r=this.findHost(e),n=!1;for(var[i,o]of this.mappings.entries())o.domain===r&&(this.log("marking %s to %s DNS mapping as verified",i,o.domain),n=o.verified,o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now());return n}unconfirm(e,t){var r=this.findHost(e),n=!1;for(var[i,o]of this.mappings.entries())o.domain===r&&(this.log("removing verification of %s to %s DNS mapping",i,o.domain),n=n||o.verified,o.verified=!1,o.expires=Date.now()+t);return n}findHost(e){for(var 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 Xz{constructor(t){e(this,"log",void 0),e(this,"mappings",void 0),this.log=t.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=new Map}has(e){var t=e.stringTuples();for(var r of this.mappings.values())for(var n of r)if(n.externalIp===t[0][1])return!0;return!1}add(e,t,r){var n,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:t,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"tcp",a="".concat(e,"-").concat(t,"-").concat(o),s=null!==(n=this.mappings.get(a))&&void 0!==n?n:[],l={internalIp:e,internalPort:t,externalIp:r,externalPort:i,externalFamily:Wt(r)?4:6,protocol:o,verified:!1,expires:0};s.push(l),this.mappings.set(a,s)}remove(e){var t,r,n=e.stringTuples(),i=null!==(t=n[0][1])&&void 0!==t?t:"",o=6===n[1][0]?"tcp":"udp",a=parseInt(null!==(r=n[1][1])&&void 0!==r?r:"0"),s=!1;for(var[l,u]of this.mappings.entries()){for(var c=0;c<u.length;c++){var d=u[c];d.externalIp===i&&d.externalPort===a&&d.protocol===o&&(this.log("removing %s:%s to %s:%s %s IP mapping",d.externalIp,d.externalPort,i,a,o),s=s||d.verified,u.splice(c,1),c--)}0===u.length&&this.mappings.delete(l)}return s}getAll(e){var t=[];for(var{multiaddr:r}of e){var n=r.stringTuples(),i=void 0;if(4!==n[0][0]&&41!==n[0][0]||6!==n[1][0]?4!==n[0][0]&&41!==n[0][0]||273!==n[1][0]||(i="".concat(n[0][1],"-").concat(n[1][1],"-udp")):i="".concat(n[0][1],"-").concat(n[1][1],"-tcp"),null!=i){var o=this.mappings.get(i);if(null!=o)for(var a of o)n[0][0]=4===a.externalFamily?4:41,n[0][1]=a.externalIp,n[1][1]="".concat(a.externalPort),t.push({multiaddr:Ir("/".concat(n.map((e=>[Tr(e[0]).name,e[1]].join("/"))).join("/"))),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}}return t}confirm(e,t){var r=e.stringTuples()[0][1],n=!1;for(var i of this.mappings.values())for(var o of i)o.externalIp===r&&(this.log("marking %s to %s IP mapping as verified",o.internalIp,o.externalIp),n=o.verified,o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now());return n}unconfirm(e,t){var r,n,i=e.stringTuples(),o=null!==(r=i[0][1])&&void 0!==r?r:"",a=6===i[1][0]?"tcp":"udp",s=parseInt(null!==(n=i[1][1])&&void 0!==n?n:"0"),l=!1;for(var u of this.mappings.values())for(var c=0;c<u.length;c++){var d=u[c];d.externalIp===o&&d.externalPort===s&&d.protocol===a&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",d.externalIp,d.externalPort,o,s,a),l=l||d.verified,d.verified=!1,d.expires=Date.now()+t)}return l}}var ej=10;class tj{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"log",void 0),e(this,"addresses",void 0),e(this,"maxObservedAddresses",void 0),this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=null!==(r=n.maxObservedAddresses)&&void 0!==r?r:ej}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(var t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(IO(e)||function(e){try{var[[t,r]]=e.stringTuples();if(null==r)return!1;if(4===t)return r.startsWith("169.254.");if(41===t)return r.toLowerCase().startsWith("fe80")}catch(e){}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=>{var[t,r]=e;return{multiaddr:Ir(t),verified:r.verified,type:"observed",expires:r.expires,lastVerified:r.lastVerified}}))}remove(e){var t,r,n=null!==(t=null===(r=this.addresses.get(e.toString()))||void 0===r?void 0:r.verified)&&void 0!==t&&t;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),n}confirm(e,t){var r,n=e.toString(),i=null!==(r=this.addresses.get(n))&&void 0!==r?r:{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},o=i.verified;return i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,i),o}}var rj=[4,41,53,54,55,56];function nj(e){try{var[[t]]=e.stringTuples();return rj.includes(t)}catch(e){}return!1}var ij=10;class oj{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"log",void 0),e(this,"addresses",void 0),e(this,"maxObservedAddresses",void 0),this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=null!==(r=n.maxObservedAddresses)&&void 0!==r?r:ij}get(e,t){if(IO(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};var r=this.toKey(e),n=this.addresses.get(r);return null==n&&(n={verified:!nj(e),expires:0},this.addresses.set(r,n)),{multiaddr:e,verified:n.verified,type:"transport",expires:n.expires,lastVerified:n.lastVerified}}has(e){var t=this.toKey(e);return this.addresses.has(t)}remove(e){var t,r,n=this.toKey(e),i=null!==(t=null===(r=this.addresses.get(n))||void 0===r?void 0:r.verified)&&void 0!==t&&t;return this.log("removing observed address %a",e),this.addresses.delete(n),i}confirm(e,t){var r,n=this.toKey(e),i=null!==(r=this.addresses.get(n))&&void 0!==r?r:{verified:!1,expires:0,lastVerified:0},o=i.verified;return i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now(),this.addresses.set(n,i),o}unconfirm(e,t){var r,n=this.toKey(e),i=null!==(r=this.addresses.get(n))&&void 0!==r?r:{verified:!1,expires:0},o=i.verified;return i.verified=!1,i.expires=Date.now()+t,this.addresses.set(n,i),o}toKey(e){if(nj(e)){var t=e.toOptions();return"".concat(t.host,"-").concat(t.port,"-").concat(t.transport)}return e.toString()}}var aj,sj={addressVerificationTTL:6e5,addressVerificationRetry:3e5},lj=e=>e;function uj(e,t){var r=e.getPeerId();null!=r&&(Mu(r).equals(t)&&(e=e.decapsulate(Ir("/p2p/".concat(t.toString())))));return e}class cj{constructor(t){var r,n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"log",void 0),e(this,"components",void 0),e(this,"listen",void 0),e(this,"announce",void 0),e(this,"appendAnnounce",void 0),e(this,"announceFilter",void 0),e(this,"observed",void 0),e(this,"dnsMappings",void 0),e(this,"ipMappings",void 0),e(this,"transportAddresses",void 0),e(this,"observedAddressFilter",void 0),e(this,"addressVerificationTTL",void 0),e(this,"addressVerificationRetry",void 0),e(this,Symbol.toStringTag,"@libp2p/address-manager");var{listen:a=[],announce:s=[],appendAnnounce:l=[]}=o;this.components=t,this.log=t.logger.forComponent("libp2p:address-manager"),this.listen=a.map((e=>e.toString())),this.announce=new Set(s.map((e=>e.toString()))),this.appendAnnounce=new Set(l.map((e=>e.toString()))),this.observed=new tj(t,o),this.dnsMappings=new $z(t,o),this.ipMappings=new Xz(t,o),this.transportAddresses=new oj(t,o),this.announceFilter=null!==(r=o.announceFilter)&&void 0!==r?r:lj,this.observedAddressFilter=rv(1024),this.addressVerificationTTL=null!==(n=o.addressVerificationTTL)&&void 0!==n?n:sj.addressVerificationTTL,this.addressVerificationRetry=null!==(i=o.addressVerificationRetry)&&void 0!==i?i:sj.addressVerificationRetry,this._updatePeerStoreAddresses=pv(this._updatePeerStoreAddresses.bind(this),1e3),t.events.addEventListener("transport:listening",(()=>{this._updatePeerStoreAddresses()})),t.events.addEventListener("transport:close",(()=>{this._updatePeerStoreAddresses()}))}_updatePeerStoreAddresses(){var e=this.getAddresses().map((e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate("/p2p/".concat(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=>Ir(e)))}getAnnounceAddrs(){return Array.from(this.announce).map((e=>Ir(e)))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map((e=>Ir(e)))}getObservedAddrs(){return this.observed.getAll().map((e=>e.multiaddr))}addObservedAddr(e){var t=e.stringTuples(),r="".concat(t[0][1],":").concat(t[1][1]);this.observedAddressFilter.has(r)||(this.observedAddressFilter.add(r),e=uj(e,this.components.peerId),this.ipMappings.has(e)||this.dnsMappings.has(e)||this.observed.add(e))}confirmObservedAddr(e,t){e=uj(e,this.components.peerId);var r,n,i,o,a,s=!0;("transport"===(null==t?void 0:t.type)||this.transportAddresses.has(e))&&(!this.transportAddresses.confirm(e,null!==(r=null==t?void 0:t.ttl)&&void 0!==r?r:this.addressVerificationTTL)&&s&&(s=!1));("dns-mapping"===(null==t?void 0:t.type)||this.dnsMappings.has(e))&&(!this.dnsMappings.confirm(e,null!==(n=null==t?void 0:t.ttl)&&void 0!==n?n:this.addressVerificationTTL)&&s&&(s=!1));("ip-mapping"===(null==t?void 0:t.type)||this.ipMappings.has(e))&&(!this.ipMappings.confirm(e,null!==(i=null==t?void 0:t.ttl)&&void 0!==i?i:this.addressVerificationTTL)&&s&&(s=!1));("observed"===(null==t?void 0:t.type)||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,null!==(o=null==t?void 0:t.ttl)&&void 0!==o?o:this.addressVerificationTTL),s=!1):!this.observed.confirm(e,null!==(a=null==t?void 0:t.ttl)&&void 0!==a?a:this.addressVerificationTTL)&&s&&(s=!1));s||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){var r,n,i;(e=uj(e,this.components.peerId),this.observed.has(e)&&this.observed.remove(e),this.transportAddresses.has(e))&&this.transportAddresses.unconfirm(e,null!==(r=null==t?void 0:t.ttl)&&void 0!==r?r:this.addressVerificationRetry);this.dnsMappings.has(e)&&this.dnsMappings.unconfirm(e,null!==(n=null==t?void 0:t.ttl)&&void 0!==n?n:this.addressVerificationRetry);this.ipMappings.has(e)&&this.ipMappings.unconfirm(e,null!==(i=null==t?void 0:t.ttl)&&void 0!==i?i:this.addressVerificationRetry)}getAddresses(){var e=new Set,t=this.getAddressesWithMetadata().filter((t=>{if(!t.verified)return!1;var r=t.multiaddr.toString();return!e.has(r)&&(e.add(r),!0)})).map((e=>e.multiaddr));return this.announceFilter(t.map((e=>{var t,r=Ir(e);return!0===(null===(t=r.protos().pop())||void 0===t?void 0:t.path)||r.getPeerId()===this.components.peerId.toString()?r:r.encapsulate("/p2p/".concat(this.components.peerId.toString()))})))}getAddressesWithMetadata(){var 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()})));var t=[];t=t.concat(this.components.transportManager.getAddrs().map((e=>this.transportAddresses.get(e,this.addressVerificationTTL))));var 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=(t=t.concat(this.observed.getAll())).concat(this.ipMappings.getAll(t))).concat(this.dnsMappings.getAll(t))}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(Ir("/dns/".concat(e)))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:t,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"tcp";this.ipMappings.add(e,t,r,n,i),this.observed.removePrefixed("/ip".concat(Wt(r)?4:6,"/").concat(r,"/").concat(i,"/").concat(n))}removePublicAddressMapping(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:t,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"tcp";this.ipMappings.remove(Ir("/ip".concat(Wt(r)?4:6,"/").concat(r,"/").concat(i,"/").concat(n)))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){var t=this;if(this.ipMappings.has(e))return!1;var r=e.toOptions();if(6===r.family||"127.0.0.1"===r.host||!0===hD(r.host))return!1;var n,i=this.components.transportManager.getListeners(),o=[e=>bh.exactMatch(e)||Eh.exactMatch(e),e=>vh.exactMatch(e),e=>yh.exactMatch(e)],a=function(n){if(!n(e))return 0;var o=i.filter((e=>e.getAddrs().filter((e=>4===e.toOptions().family&&n(e))).length>0));if(1!==o.length)return 0;var a=o[0].getAddrs().filter((e=>"127.0.0.1"!==e.toOptions().host)).pop();if(null==a)return 0;var s=a.toOptions();return t.observed.remove(e),t.ipMappings.add(s.host,s.port,r.host,r.port,r.transport),{v:!0}};for(var s of o)if(0!==(n=a(s))&&n)return n.v;return!1}}!function(e){e.NOT_STARTED_YET="The libp2p node is not started yet",e.NOT_FOUND="Not found"}(aj||(aj={}));class dj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Missing service"),this.name="MissingServiceError"}}class hj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unmet service dependencies"),this.name="UnmetServiceDependenciesError"}}class vj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No content routers available"),this.name="NoContentRoutersError"}}class pj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No peer routers available"),this.name="NoPeerRoutersError"}}class fj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Should not try to find self"),this.name="QueriedForSelfError"}}class gj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unhandled protocol error"),this.name="UnhandledProtocolError"}}class yj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Duplicate protocol handler error"),this.name="DuplicateProtocolHandlerError"}}class mj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Dial denied error"),this.name="DialDeniedError"}}class wj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No transport was configured to listen on this address"),this.name="UnsupportedListenAddressError"}}class bj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Configured listen addresses could not be listened on"),this.name="UnsupportedListenAddressesError"}}class Sj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No valid addresses"),this.name="NoValidAddressesError"}}class Ej extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Connection intercepted"),this.name="ConnectionInterceptedError"}}class kj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Connection denied"),this.name="ConnectionDeniedError"}}class xj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Stream is not multiplexed"),this.name="MuxerUnavailableError"}}class Aj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Encryption failed"),this.name="EncryptionFailedError"}}class Cj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Transport unavailable"),this.name="TransportUnavailableError"}}class Ij{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(var[r,n]of(e(this,"components",{}),e(this,"_started",!1),this.components={},Object.entries(t)))this.components[r]=n;null==this.components.logger&&(this.components.logger=cd())}isStarted(){return this._started}_invokeStartableMethod(e){var t=this;return r((function*(){yield Promise.all(Object.values(t.components).filter((e=>cs(e))).map(function(){var t=r((function*(t){var r;yield null===(r=t[e])||void 0===r?void 0:r.call(t)}));return function(e){return t.apply(this,arguments)}}()))}))()}beforeStart(){var e=this;return r((function*(){yield e._invokeStartableMethod("beforeStart")}))()}start(){var e=this;return r((function*(){yield e._invokeStartableMethod("start"),e._started=!0}))()}afterStart(){var e=this;return r((function*(){yield e._invokeStartableMethod("afterStart")}))()}beforeStop(){var e=this;return r((function*(){yield e._invokeStartableMethod("beforeStop")}))()}stop(){var e=this;return r((function*(){yield e._invokeStartableMethod("stop"),e._started=!1}))()}afterStop(){var e=this;return r((function*(){yield e._invokeStartableMethod("afterStop")}))()}}var Tj=["metrics","connectionProtector","dns"],Pj=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function _j(e){return Array.isArray(null==e?void 0:e[fs])?e[fs]:[]}function Bj(e){return Array.isArray(null==e?void 0:e[gs])?e[gs]:[]}function Nj(e){var t,r;return null!==(t=null!==(r=null==e?void 0:e[Symbol.toStringTag])&&void 0!==r?r:null==e?void 0:e.toString())&&void 0!==t?t:"unknown"}function Dj(){var e,n,i,o,a,s,l,u,c,d=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t({denyDialPeer:(c=r((function*(){return!1})),function(){return c.apply(this,arguments)}),denyDialMultiaddr:(u=r((function*(e){if(bh.matches(e))return!1;var t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&Boolean(hD("".concat(t[0][1])))})),function(e){return u.apply(this,arguments)}),denyInboundConnection:(l=r((function*(){return!1})),function(){return l.apply(this,arguments)}),denyOutboundConnection:(s=r((function*(){return!1})),function(){return s.apply(this,arguments)}),denyInboundEncryptedConnection:(a=r((function*(){return!1})),function(){return a.apply(this,arguments)}),denyOutboundEncryptedConnection:(o=r((function*(){return!1})),function(){return o.apply(this,arguments)}),denyInboundUpgradedConnection:(i=r((function*(){return!1})),function(){return i.apply(this,arguments)}),denyOutboundUpgradedConnection:(n=r((function*(){return!1})),function(){return n.apply(this,arguments)}),filterMultiaddrForPeer:(e=r((function*(){return!0})),function(){return e.apply(this,arguments)})},d)}function Rj(e){if(Ca(e))return{peerId:e,multiaddrs:[]};var t,r=Array.isArray(e)?e:[e];if(r.length>0){var n=r[0].getPeerId();t=null==n?void 0:Mu(n),r.forEach((e=>{if(!Cr(e))throw new Wa("Invalid multiaddr");var r=e.getPeerId();if(null==r){if(null!=t)throw new Ra("Multiaddrs must all have the same peer id or have no peer id")}else{var n,i=Mu(r);if(!0!==(null===(n=t)||void 0===n?void 0:n.equals(i)))throw new Ra("Multiaddrs must all have the same peer id or have no peer id")}}))}return r=r.filter((e=>!Zd.exactMatch(e))),{peerId:t,multiaddrs:r}}var Oj=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];function Lj(){return Lj=r((function*(e,t){var r,n,i,o=null!==(r=null==e||null===(n=e.streams)||void 0===n?void 0:n.map((e=>e.protocol)))&&void 0!==r?r:[],a=null!==(i=null==t?void 0:t.closableProtocols)&&void 0!==i?i:Oj;if(!(o.filter((e=>null!=e&&!a.includes(e))).length>0))try{yield null==e?void 0:e.close(t)}catch(t){null==e||e.abort(t)}})),Lj.apply(this,arguments)}var Mj="last-dial-failure",Uj="last-dial-success";function Fj(){return Fj=r((function*(e,t){var r=!1;for(var n of xr.keys())if(r=e.protoNames().includes(n))break;if(!r)return[e];var i=yield e.resolve(t);return t.log("resolved %s to",e,i.map((e=>e.toString()))),i})),Fj.apply(this,arguments)}function zj(e){try{var t;if(!(t="string"==typeof e?Ir(e):e).protoNames().includes("ipcidr")){var r=t.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(r)}return function(e){var 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 kr(r,t)}(t)}catch(t){throw new Error("Can't convert to IpNet, Invalid multiaddr format: ".concat(e))}}var jj=100;class Vj{constructor(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"maxConnections",void 0),e(this,"connectionManager",void 0),e(this,"peerStore",void 0),e(this,"allow",void 0),e(this,"events",void 0),e(this,"log",void 0),this.maxConnections=null!==(r=i.maxConnections)&&void 0!==r?r:jj,this.allow=(null!==(n=i.allow)&&void 0!==n?n:[]).map((e=>zj(e))),this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.log=t.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)}))}_maybePruneConnections(){var e=this;return r((function*(){var t=e.connectionManager.getConnections(),n=t.length;if(e.log("checking max connections limit %d/%d",n,e.maxConnections),!(n<=e.maxConnections)){var i=new qh;for(var o of t){var a=o.remotePeer;if(!i.has(a)){i.set(a,0);try{var s=yield e.peerStore.get(a);i.set(a,[...s.tags.values()].reduce(((e,t)=>e+t.value),0))}catch(t){"NotFoundError"!==t.name&&e.log.error("error loading peer tags",t)}}}var l=e.sortConnections(t,i),u=Math.max(n-e.maxConnections,0),c=[],d=function*(t){if(e.log("too many connections open - closing a connection to %p",t.remotePeer),e.allow.some((e=>e.contains(t.remoteAddr.nodeAddress().address)))||c.push(t),c.length===u)return 1};for(var h of l)if(yield*d(h))break;yield Promise.all(c.map(function(){var e=r((function*(e){yield function(e,t){return Lj.apply(this,arguments)}(e,{signal:AbortSignal.timeout(1e3)})}));return function(t){return e.apply(this,arguments)}}())),e.events.safeDispatchEvent("connection:prune",{detail:c})}}))()}sortConnections(e,t){return e.sort(((e,t)=>{var 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)=>{var n,i,o=null!==(n=t.get(e.remotePeer))&&void 0!==n?n:0,a=null!==(i=t.get(r.remotePeer))&&void 0!==i?i:0;return o>a?1:o<a?-1:0}))}}class qj extends wv{constructor(){super(t(t({},arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),{},{sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0}))}}function Hj(e){if(!CO(e))return!1;var t,{address:r}=e.nodeAddress();return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t=r)||/^::1$/.test(t)}function Kj(e,t){var r=vh.exactMatch(e.multiaddr),n=vh.exactMatch(t.multiaddr);if(r&&!n)return-1;if(!r&&n)return 1;var i=Eh.exactMatch(e.multiaddr),o=Eh.exactMatch(t.multiaddr);if(i&&!o)return-1;if(!i&&o)return 1;var a=bh.exactMatch(e.multiaddr),s=bh.exactMatch(t.multiaddr);if(a&&!s)return-1;if(!a&&s)return 1;var l=_h.exactMatch(e.multiaddr),u=_h.exactMatch(t.multiaddr);if(l&&!u)return-1;if(!l&&u)return 1;var c=xh.exactMatch(e.multiaddr),d=xh.exactMatch(t.multiaddr);if(c&&!d)return-1;if(!c&&d)return 1;var h=Ch.exactMatch(e.multiaddr),v=Ch.exactMatch(t.multiaddr);return h&&!v?-1:!h&&v?1:0}function Wj(e,t){var r=Hj(e.multiaddr),n=Hj(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function Gj(e,t){var r=IO(e.multiaddr),n=IO(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function Qj(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function Yj(e,t){var r=Ph.exactMatch(e.multiaddr),n=Ph.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}var Jj=50,Zj=500,$j=25,Xj=1e4;class eV{constructor(t){var r,n,i,o,a,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};for(var[l,u]of(e(this,"queue",void 0),e(this,"components",void 0),e(this,"addressSorter",void 0),e(this,"maxPeerAddrsToDial",void 0),e(this,"maxDialQueueLength",void 0),e(this,"dialTimeout",void 0),e(this,"shutDownController",void 0),e(this,"connections",void 0),e(this,"log",void 0),this.addressSorter=s.addressSorter,this.maxPeerAddrsToDial=null!==(r=s.maxPeerAddrsToDial)&&void 0!==r?r:$j,this.maxDialQueueLength=null!==(n=s.maxDialQueueLength)&&void 0!==n?n:Zj,this.dialTimeout=null!==(i=s.dialTimeout)&&void 0!==i?i:Xj,this.connections=null!==(o=s.connections)&&void 0!==o?o:new qh,this.log=t.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=t,this.shutDownController=new AbortController,this.shutDownController.signal,Object.entries(null!==(c=s.resolvers)&&void 0!==c?c:{}))){var c;xr.set(l,u)}this.queue=new qj({concurrency:null!==(a=s.maxParallelDials)&&void 0!==a?a:Jj,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("error",(e=>{var t;(null===(t=e.detail)||void 0===t?void 0:t.name)!==Ba.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()}dial(e){var t=arguments,n=this;return r((function*(){var i,o,a,s,l=t.length>1&&void 0!==t[1]?t[1]:{},{peerId:u,multiaddrs:c}=Rj(e),d=Array.from(n.connections.values()).flat().find((e=>!0!==l.force&&(!!e.remotePeer.equals(u)||c.find((t=>t.equals(e.remoteAddr))))));if("open"===(null==d?void 0:d.status))return n.log("already connected to %a",d.remoteAddr),null===(s=l.onProgress)||void 0===s||s.call(l,new cv("dial-queue:already-connected")),d;var h=n.queue.queue.find((e=>{if(!0===(null==u?void 0:u.equals(e.options.peerId)))return!0;var t=e.options.multiaddrs;if(null==t)return!1;for(var r of c)if(t.has(r.toString()))return!0;return!1}));if(null!=h){var v;for(var p of(n.log("joining existing dial target for %p",u),c))h.options.multiaddrs.add(p.toString());return null===(v=l.onProgress)||void 0===v||v.call(l,new cv("dial-queue:already-in-dial-queue")),h.join(l)}if(n.queue.size>=n.maxDialQueueLength)throw new ts("Dial queue is full");return n.log("creating dial target for %p",u,c.map((e=>e.toString()))),null===(i=l.onProgress)||void 0===i||i.call(l,new cv("dial-queue:add-to-dial-queue")),n.queue.add(function(){var e=r((function*(e){var t;null===(t=e.onProgress)||void 0===t||t.call(e,new cv("dial-queue:start-dial"));var r=Dh([n.shutDownController.signal,e.signal]);try{return yield n.dialPeer(e,r)}finally{r.clear()}}));return function(t){return e.apply(this,arguments)}}(),{peerId:u,priority:null!==(o=l.priority)&&void 0!==o?o:yV,multiaddrs:new Set(c.map((e=>e.toString()))),signal:null!==(a=l.signal)&&void 0!==a?a:AbortSignal.timeout(n.dialTimeout),onProgress:l.onProgress})}))()}dialPeer(e,n){var i=this;return r((function*(){var r=e.peerId,o=e.multiaddrs,a=new Set,s=0===e.multiaddrs.size,l=0,u=0,c=[];for(i.log("starting dial to %p",r);s||o.size>0;){var d;u++,s=!1;var h=[],v=new Set(e.multiaddrs);o.clear(),i.log("calculating addrs to dial %p from %s",r,[...v]);var p=yield i.calculateMultiaddrs(r,v,t(t({},e),{},{signal:n}));for(var f of p)a.has(f.multiaddr.toString())?i.log.trace("skipping previously failed multiaddr %a while dialing %p",f.multiaddr,r):h.push(f);for(var g of(i.log("%s dial to %p with %s",1===u?"starting":"continuing",r,h.map((e=>e.multiaddr.toString()))),null==e||null===(d=e.onProgress)||void 0===d||d.call(e,new cv("dial-queue:calculated-addresses",h)),h)){if(l===i.maxPeerAddrsToDial)throw i.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",l,e.peerId),new ts("Peer had more than maxPeerAddrsToDial");l++;try{var y=yield i.components.transportManager.dial(g.multiaddr,t(t({},e),{},{signal:n}));i.log("dial to %a succeeded",g.multiaddr);try{yield i.components.peerStore.merge(y.remotePeer,{multiaddrs:[y.remoteAddr],metadata:{[Uj]:xt(Date.now().toString())}})}catch(e){i.log.error("could not update last dial failure key for %p",r,e)}return y}catch(e){if(i.log.error("dial failed to %a",g.multiaddr,e),a.add(g.multiaddr.toString()),null!=r)try{yield i.components.peerStore.merge(r,{metadata:{[Mj]:xt(Date.now().toString())}})}catch(e){i.log.error("could not update last dial failure key for %p",r,e)}if(n.aborted)throw new $a(e.message);c.push(e)}}}if(1===c.length)throw c[0];throw new AggregateError(c,"All multiaddr dials failed")}))()}calculateMultiaddrs(e){var n=arguments,i=this;return r((function*(){var o=n.length>1&&void 0!==n[1]?n[1]:new Set,a=n.length>2&&void 0!==n[2]?n[2]:{},s=[...o].map((e=>({multiaddr:Ir(e),isCertified:!1})));if(null!=e){var l,u;if(i.components.peerId.equals(e))throw new ts("Tried to dial self");if(!0===(yield null===(l=(u=i.components.connectionGater).denyDialPeer)||void 0===l?void 0:l.call(u,e)))throw new mj("The dial request is blocked by gater.allowDialPeer");if(0===s.length){i.log("loading multiaddrs for %p",e);try{var c=yield i.components.peerStore.get(e);s.push(...c.addresses),i.log("loaded multiaddrs for %p",e,s.map((e=>{var{multiaddr:t}=e;return t.toString()})))}catch(e){if("NotFoundError"!==e.name)throw e}}if(0===s.length){i.log("looking up multiaddrs for %p in the peer routing",e);try{var d=yield i.components.peerRouting.findPeer(e,a);i.log("found multiaddrs for %p in the peer routing",e,s.map((e=>{var{multiaddr:t}=e;return t.toString()}))),s.push(...d.multiaddrs.map((e=>({multiaddr:e,isCertified:!1}))))}catch(t){"NoPeerRoutersError"===t.name?i.log("no peer routers configured",e):i.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,t)}}}var h=(yield Promise.all(s.map(function(){var e=r((function*(e){var r=yield function(e,t){return Fj.apply(this,arguments)}(e.multiaddr,t(t({dns:i.components.dns},a),{},{log:i.log}));return 1===r.length&&r[0].equals(e.multiaddr)?e:r.map((e=>({multiaddr:e,isCertified:!1})))}));return function(t){return e.apply(this,arguments)}}()))).flat();if(null!=e){var v="/p2p/".concat(e.toString());h=h.map((e=>{var t=e.multiaddr.protos().pop();return!0===(null==t?void 0:t.path)?e:null==e.multiaddr.getPeerId()?{multiaddr:e.multiaddr.encapsulate(v),isCertified:e.isCertified}:e}))}var p=h.filter((t=>{if(null==i.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;var r=t.multiaddr.getPeerId();return null==e||null==r||e.equals(r)})),f=new Map;for(var g of p){var y=g.multiaddr.toString(),m=f.get(y);null==m?f.set(y,g):m.isCertified=m.isCertified||g.isCertified||!1}var w=[...f.values()];if(0===w.length)throw new Sj("The dial request has no valid addresses");var b=[];for(var S of w)null!=i.components.connectionGater.denyDialMultiaddr&&(yield i.components.connectionGater.denyDialMultiaddr(S.multiaddr))||b.push(S);var E=null==i.addressSorter?b.sort(Kj).sort(Qj).sort(Yj).sort(Gj).sort(Wj):b.sort(i.addressSorter);if(0===E.length)throw new mj("The connection gater denied all addresses in the dial request");return i.log.trace("addresses for %p before filtering",null!=e?e:"unknown peer",h.map((e=>{var{multiaddr:t}=e;return t.toString()}))),i.log.trace("addresses for %p after filtering",null!=e?e:"unknown peer",E.map((e=>{var{multiaddr:t}=e;return t.toString()}))),E}))()}isDialable(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};Array.isArray(e)||(e=[e]);try{var i=yield n.calculateMultiaddrs(void 0,new Set(e.map((e=>e.toString()))),r);return!1!==r.runOnLimitedConnection||null!=i.find((e=>!Ph.matches(e.multiaddr)))}catch(e){n.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}))()}}var tV,rV,nV,iV,oV,aV={};function sV(){return nV||(nV=1,e=aV,t=function(){if(rV)return tV;function e(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))}return rV=1,tV=e,e.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},e.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},e.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},e.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)},e.prototype.try=function(e){this.attempt(e)},e.prototype.start=function(e){this.attempt(e)},e.prototype.start=e.prototype.try,e.prototype.errors=function(){return this._errors},e.prototype.attempts=function(){return this._attempts},e.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 i=this._errors[n],o=i.message,a=(e[o]||0)+1;e[o]=a,a>=r&&(t=i,r=a)}return t},tV}(),e.operation=function(r){var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.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=[],i=0;i<t.retries;i++)n.push(this.createTimeout(i,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(i,t)),n.sort((function(e,t){return e-t})),n},e.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 n=Math.min(n,t.maxTimeout)},e.wrap=function(t,r,n){if(r instanceof Array&&(n=r,r=null),!n)for(var i in n=[],t)"function"==typeof t[i]&&n.push(i);for(var o=0;o<n.length;o++){var a=n[o],s=t[a];t[a]=function(n){var i=e.operation(r),o=Array.prototype.slice.call(arguments,1),a=o.pop();o.push((function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),a.apply(this,arguments))})),i.attempt((function(){n.apply(t,o)}))}.bind(t,s),t[a].options=r}}),aV;var e,t}var lV=a(oV?iV:(oV=1,iV=sV())),uV=Object.prototype.toString,cV=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"]);function dV(e){var t;return!(!e||(t=e,"[object Error]"!==uV.call(t))||"TypeError"!==e.name||"string"!=typeof e.message)&&("Load failed"===e.message?void 0===e.stack:cV.has(e.message))}class hV 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}}var vV=(e,t,r)=>{var n=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=n,e};function pV(){return pV=r((function*(e,n){return new Promise(((i,o)=>{var a,s,l,u,c,d;null!==(s=(a=n=t({},n)).onFailedAttempt)&&void 0!==s||(a.onFailedAttempt=()=>{}),null!==(u=(l=n).shouldRetry)&&void 0!==u||(l.shouldRetry=()=>!0),null!==(d=(c=n).retries)&&void 0!==d||(c.retries=10);var h=lV.operation(n),v=()=>{var e;h.stop(),o(null===(e=n.signal)||void 0===e?void 0:e.reason)};n.signal&&!n.signal.aborted&&n.signal.addEventListener("abort",v,{once:!0});var p=()=>{var e;null===(e=n.signal)||void 0===e||e.removeEventListener("abort",v),h.stop()};h.attempt(function(){var t=r((function*(t){try{var r=yield e(t);p(),i(r)}catch(e){try{if(!(e instanceof Error))throw new TypeError('Non-error was thrown: "'.concat(e,'". You should only throw errors.'));if(e instanceof hV)throw e.originalError;if(e instanceof TypeError&&!dV(e))throw e;if(vV(e,t,n),(yield n.shouldRetry(e))||(h.stop(),o(e)),yield n.onFailedAttempt(e),!h.retry(e))throw h.mainError()}catch(e){vV(e,t,n),p(),o(e)}}}));return function(e){return t.apply(this,arguments)}}())}))})),pV.apply(this,arguments)}class fV{constructor(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"log",void 0),e(this,"queue",void 0),e(this,"started",void 0),e(this,"peerStore",void 0),e(this,"retries",void 0),e(this,"retryInterval",void 0),e(this,"backoffFactor",void 0),e(this,"connectionManager",void 0),e(this,"events",void 0),this.log=t.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.queue=new bv({concurrency:null!==(r=i.maxParallelReconnects)&&void 0!==r?r:5,metricName:"libp2p_reconnect_queue",metrics:t.metrics}),this.started=!1,this.retries=null!==(n=i.retries)&&void 0!==n?n:5,this.backoffFactor=i.backoffFactor,this.retryInterval=i.retryInterval,this.events=t.events,t.events.addEventListener("peer:disconnect",(e=>{this.maybeReconnect(e.detail).catch((t=>{this.log.error("failed to maybe reconnect to %p - %e",e.detail,t)}))}))}maybeReconnect(e){var t=this;return r((function*(){if(t.started){var n=yield t.peerStore.get(e);gV(n)&&(t.queue.has(e)||t.queue.add(function(){var n=r((function*(n){yield function(e,t){return pV.apply(this,arguments)}(function(){var i=r((function*(r){if(t.started)try{yield t.connectionManager.openConnection(e,{signal:null==n?void 0:n.signal})}catch(n){throw t.log("reconnecting to %p attempt %d of %d failed - %e",e,r,t.retries,n),n}}));return function(e){return i.apply(this,arguments)}}(),{signal:null==n?void 0:n.signal,retries:t.retries,factor:t.backoffFactor,minTimeout:t.retryInterval})}));return function(e){return n.apply(this,arguments)}}(),{peerId:e}).catch(function(){var i=r((function*(r){t.log.error("failed to reconnect to %p - %e",e,r);var i={};[...n.tags.keys()].forEach((e=>{e.startsWith(Pa)&&(i[e]=void 0)})),yield t.peerStore.merge(e,{tags:i}),t.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}));return function(e){return i.apply(this,arguments)}}()).catch(function(){var n=r((function*(r){t.log.error("failed to remove keep-alive tag from %p - %e",e,r)}));return function(e){return n.apply(this,arguments)}}()))}}))()}start(){this.started=!0}afterStart(){var e=this;return r((function*(){Promise.resolve().then(r((function*(){var t=yield e.peerStore.all({filters:[e=>gV(e)]});yield Promise.all(t.map(function(){var t=r((function*(t){yield e.connectionManager.openConnection(t.id).catch((t=>{e.log.error(t)}))}));return function(e){return t.apply(this,arguments)}}()))}))).catch((t=>{e.log.error(t)}))}))()}stop(){this.started=!1,this.queue.abort()}}function gV(e){for(var t of e.tags.keys())if(t.startsWith(Pa))return!0;return!1}var yV=50,mV=100,wV=5,bV=10;class SV{constructor(t){var r,n,i,o,a,s,l,u,c,d,h,v=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e(this,"started",void 0),e(this,"connections",void 0),e(this,"allow",void 0),e(this,"deny",void 0),e(this,"maxIncomingPendingConnections",void 0),e(this,"incomingPendingConnections",void 0),e(this,"outboundPendingConnections",void 0),e(this,"maxConnections",void 0),e(this,"dialQueue",void 0),e(this,"reconnectQueue",void 0),e(this,"connectionPruner",void 0),e(this,"inboundConnectionRateLimiter",void 0),e(this,"peerStore",void 0),e(this,"metrics",void 0),e(this,"events",void 0),e(this,"log",void 0),e(this,"peerId",void 0),e(this,Symbol.toStringTag,"@libp2p/connection-manager"),this.maxConnections=null!==(r=v.maxConnections)&&void 0!==r?r:mV,this.maxConnections<1)throw new Ra("Connection Manager maxConnections must be greater than 0");this.connections=new qh,this.started=!1,this.peerId=t.peerId,this.peerStore=t.peerStore,this.metrics=t.metrics,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(null!==(n=v.allow)&&void 0!==n?n:[]).map((e=>zj(e))),this.deny=(null!==(i=v.deny)&&void 0!==i?i:[]).map((e=>zj(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=null!==(o=v.maxIncomingPendingConnections)&&void 0!==o?o:bV,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new EF({points:null!==(a=v.inboundConnectionThreshold)&&void 0!==a?a:wV,duration:1}),this.connectionPruner=new Vj({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{maxConnections:this.maxConnections,allow:null===(s=v.allow)||void 0===s?void 0:s.map((e=>Ir(e)))}),this.dialQueue=new eV(t,{addressSorter:v.addressSorter,maxParallelDials:null!==(l=v.maxParallelDials)&&void 0!==l?l:50,maxDialQueueLength:null!==(u=v.maxDialQueueLength)&&void 0!==u?u:500,maxPeerAddrsToDial:null!==(c=v.maxPeerAddrsToDial)&&void 0!==c?c:25,dialTimeout:null!==(d=v.dialTimeout)&&void 0!==d?d:1e4,resolvers:null!==(h=v.resolvers)&&void 0!==h?h:{dnsaddr:gz},connections:this.connections}),this.reconnectQueue=new fV({events:t.events,peerStore:t.peerStore,logger:t.logger,connectionManager:this},{retries:v.reconnectRetries,retryInterval:v.reconnectRetryInterval,backoffFactor:v.reconnectBackoffFactor,maxParallelReconnects:v.maxParallelReconnects})}start(){var e=this;return r((function*(){var t,r,n;null===(t=e.metrics)||void 0===t||t.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{var t={inbound:0,"inbound pending":e.incomingPendingConnections,outbound:0,"outbound pending":e.outboundPendingConnections};for(var r of e.connections.values())for(var n of r)t[n.direction]++;return t}}),null===(r=e.metrics)||void 0===r||r.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{var t={};for(var r of e.connections.values())for(var n of r)for(var i of n.streams){var o,a,s="".concat(i.direction," ").concat(null!==(o=i.protocol)&&void 0!==o?o:"unnegotiated");t[s]=(null!==(a=t[s])&&void 0!==a?a:0)+1}return t}}),null===(n=e.metrics)||void 0===n||n.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{var t={};for(var r of e.connections.values())for(var n of r){var i={};for(var o of n.streams){var a,s,l="".concat(o.direction," ").concat(null!==(a=o.protocol)&&void 0!==a?a:"unnegotiated");i[l]=(null!==(s=i[l])&&void 0!==s?s:0)+1}for(var[u,c]of Object.entries(i)){var d;t[u]=null!==(d=t[u])&&void 0!==d?d:[],t[u].push(c)}}var h={};for(var[v,p]of Object.entries(t)){p=p.sort(((e,t)=>e-t));var f=Math.floor(.9*p.length);h[v]=p[f]}return h}}),e.events.addEventListener("connection:open",e.onConnect),e.events.addEventListener("connection:close",e.onDisconnect),yield ds(e.dialQueue,e.reconnectQueue,e.connectionPruner),e.started=!0,e.log("started")}))()}stop(){var e=this;return r((function*(){e.events.removeEventListener("connection:open",e.onConnect),e.events.removeEventListener("connection:close",e.onDisconnect),yield vs(e.reconnectQueue,e.dialQueue,e.connectionPruner);var t=[];for(var n of e.connections.values()){var i=function*(n){t.push(r((function*(){try{yield n.close()}catch(t){e.log.error(t)}}))())};for(var o of n)yield*i(o)}e.log("closing %d connections",t.length),yield Promise.all(t),e.connections.clear(),e.log("stopped")}))()}getMaxConnections(){return this.maxConnections}onConnect(e){this._onConnect(e).catch((e=>{this.log.error(e)}))}_onConnect(e){var t=this;return r((function*(){var r,{detail:n}=e;if(t.started){if("open"===n.status){var i=n.remotePeer,o=!t.connections.has(i),a=null!==(r=t.connections.get(i))&&void 0!==r?r:[];a.push(n),t.connections.set(i,a),null!=i.publicKey&&"RSA"===i.type&&(yield t.peerStore.patch(i,{publicKey:i.publicKey})),o&&t.events.safeDispatchEvent("peer:connect",{detail:n.remotePeer})}}else yield n.close()}))()}onDisconnect(e){var t,{detail:r}=e,n=r.remotePeer,i=(null!==(t=this.connections.get(n))&&void 0!==t?t:[]).filter((e=>e.id!==r.id));this.connections.set(n,i),0===i.length&&(this.log("onDisconnect remove all connections for peer %p",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:r.remotePeer}))}getConnections(e){var t;if(null!=e)return null!==(t=this.connections.get(e))&&void 0!==t?t:[];var r=[];for(var n of this.connections.values())r=r.concat(n);return r}getConnectionsMap(){return this.connections}openConnection(e){var n=arguments,i=this;return r((function*(){var r=n.length>1&&void 0!==n[1]?n[1]:{};if(!i.started)throw new Xa("Not started");i.outboundPendingConnections++;try{var o,a;null===(o=r.signal)||void 0===o||o.throwIfAborted();var{peerId:s}=Rj(e);if(i.peerId.equals(s))throw new Ka("Can not dial self");if(null!=s&&!0!==r.force){i.log("dial %p",s);var l,u=i.getConnections(s).find((e=>null==e.limits));if(null!=u)return i.log("had an existing non-limited connection to %p",s),null===(l=r.onProgress)||void 0===l||l.call(r,new cv("dial-queue:already-connected")),u}var c=yield i.dialQueue.dial(e,t(t({},r),{},{priority:null!==(a=r.priority)&&void 0!==a?a:yV}));if("open"!==c.status)throw new Fa("Remote closed connection during opening");var d=i.connections.get(c.remotePeer);null==d&&(d=[],i.connections.set(c.remotePeer,d));var h=!1;for(var v of d)if(v.id===c.id&&(h=!0),!0!==r.force&&v.id!==c.id&&v.remoteAddr.equals(c.remoteAddr))return c.abort(new Wa("Duplicate multiaddr connection")),v;return h||d.push(c),c}finally{i.outboundPendingConnections--}}))()}closeConnections(e){var t=arguments,n=this;return r((function*(){var i,o=t.length>1&&void 0!==t[1]?t[1]:{},a=null!==(i=n.connections.get(e))&&void 0!==i?i:[];yield Promise.all(a.map(function(){var e=r((function*(e){try{yield e.close(o)}catch(t){e.abort(t)}}));return function(t){return e.apply(this,arguments)}}()))}))()}acceptIncomingConnection(e){var t=this;return r((function*(){if(t.deny.some((t=>t.contains(e.remoteAddr.nodeAddress().address))))return t.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(t.allow.some((t=>t.contains(e.remoteAddr.nodeAddress().address))))return t.incomingPendingConnections++,!0;if(t.incomingPendingConnections===t.maxIncomingPendingConnections)return t.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){var r=e.remoteAddr.nodeAddress().address;try{yield t.inboundConnectionRateLimiter.consume(r,1)}catch(n){return t.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,r),!1}}return t.getConnections().length<t.maxConnections?(t.incomingPendingConnections++,!0):(t.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}))()}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){var 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=>Ir(e)))})))}isDialable(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};return n.dialQueue.isDialable(e,r)}))()}}class EV{constructor(r){var n,i,o,a,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"protocol",void 0),e(this,"components",void 0),e(this,"log",void 0),e(this,"heartbeatInterval",void 0),e(this,"pingIntervalMs",void 0),e(this,"abortController",void 0),e(this,"timeout",void 0),e(this,"abortConnectionOnPingFailure",void 0),e(this,Symbol.toStringTag,"@libp2p/connection-monitor"),e(this,fs,["@libp2p/connection-monitor"]),this.components=r,this.protocol="/".concat(null!==(n=s.protocolPrefix)&&void 0!==n?n:"ipfs","/").concat("ping","/").concat("1.0.0"),this.log=r.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=null!==(i=s.pingInterval)&&void 0!==i?i:1e4,this.abortConnectionOnPingFailure=null===(o=s.abortConnectionOnPingFailure)||void 0===o||o,this.timeout=new PM(t(t({},null!==(a=s.pingTimeout)&&void 0!==a?a:{}),{},{metrics:r.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"}))}start(){var e=this;this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval((()=>{this.components.connectionManager.getConnections().forEach((t=>{Promise.resolve().then(r((function*(){var r=Date.now();try{var n,i=e.timeout.getTimeoutSignal({signal:null===(n=e.abortController)||void 0===n?void 0:n.signal}),o=kd(yield t.newStream(e.protocol,{signal:i,runOnLimitedConnection:!0}));r=Date.now(),yield Promise.all([o.write(Zl(32),{signal:i}),o.read({bytes:32,signal:i})]),t.rtt=Date.now()-r,yield o.unwrap().close({signal:i})}catch(e){if("UnsupportedProtocolError"!==e.name)throw e;t.rtt=(Date.now()-r)/2}}))).catch((e=>{this.log.error("error during heartbeat",e),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),t.abort(e)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")}))}))}),this.pingIntervalMs)}stop(){var e;null===(e=this.abortController)||void 0===e||e.abort(),null!=this.heartbeatInterval&&clearInterval(this.heartbeatInterval)}}class kV{constructor(r,n){var i,o,a,s,l,u,c,d,h,v,p;e(this,"routers",void 0),e(this,"started",void 0),e(this,"components",void 0),e(this,Symbol.toStringTag,"@libp2p/content-routing"),this.routers=null!==(i=n.routers)&&void 0!==i?i:[],this.started=!1,this.components=r,this.findProviders=null!==(o=null===(a=r.metrics)||void 0===a?void 0:a.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:(e,r)=>{var[n]=e;return t(t({},r),{},{cid:n.toString()})},getAttributesFromYieldedValue:(e,r)=>t(t({},r),{},{providers:[...Array.isArray(r.providers)?r.providers:[],e.id.toString()]})}))&&void 0!==o?o:this.findProviders,this.provide=null!==(s=null===(l=r.metrics)||void 0===l?void 0:l.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:(e,r)=>{var[n]=e;return t(t({},r),{},{cid:n.toString()})}}))&&void 0!==s?s:this.provide,this.cancelReprovide=null!==(u=null===(c=r.metrics)||void 0===c?void 0:c.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:(e,r)=>{var[n]=e;return t(t({},r),{},{cid:n.toString()})}}))&&void 0!==u?u:this.cancelReprovide,this.put=null!==(d=null===(h=r.metrics)||void 0===h?void 0:h.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:e=>{var[t]=e;return{key:gt(t,"base36")}}}))&&void 0!==d?d:this.put,this.get=null!==(v=null===(p=r.metrics)||void 0===p?void 0:p.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:e=>{var[t]=e;return{key:gt(t,"base36")}}}))&&void 0!==v?v:this.get}isStarted(){return this.started}start(){var e=this;return r((function*(){e.started=!0}))()}stop(){var e=this;return r((function*(){e.started=!1}))()}findProviders(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(0===t.routers.length)throw new vj("No content routers available");var n,i=t,o=new Hh,a=!1,l=!1;try{for(var c,d=s(Vc(...i.routers.filter((e=>e.findProviders instanceof Function)).map((t=>t.findProviders(e,r)))));a=!(c=yield u(d.next())).done;a=!1){var h=c.value;null!=h&&(h.multiaddrs.length>0&&(yield u(t.components.peerStore.merge(h.id,{multiaddrs:h.multiaddrs}))),o.has(h.id)||(o.add(h.id),yield h))}}catch(e){l=!0,n=e}finally{try{a&&null!=d.return&&(yield u(d.return()))}finally{if(l)throw n}}}()})).apply(this,arguments)}provide(e){var t=arguments,n=this;return r((function*(){var i=t.length>1&&void 0!==t[1]?t[1]:{};if(0===n.routers.length)throw new vj("No content routers available");yield Promise.all(n.routers.filter((e=>e.provide instanceof Function)).map(function(){var t=r((function*(t){yield t.provide(e,i)}));return function(e){return t.apply(this,arguments)}}()))}))()}cancelReprovide(e){var t=arguments,n=this;return r((function*(){var i=t.length>1&&void 0!==t[1]?t[1]:{};if(0===n.routers.length)throw new vj("No content routers available");yield Promise.all(n.routers.filter((e=>e.cancelReprovide instanceof Function)).map(function(){var t=r((function*(t){yield t.cancelReprovide(e,i)}));return function(e){return t.apply(this,arguments)}}()))}))()}put(e,t,n){var i=this;return r((function*(){if(!i.isStarted())throw new Xa;yield Promise.all(i.routers.filter((e=>e.put instanceof Function)).map(function(){var i=r((function*(r){yield r.put(e,t,n)}));return function(e){return i.apply(this,arguments)}}()))}))()}get(e,t){var n=this;return r((function*(){if(!n.isStarted())throw new Xa;return Promise.any(n.routers.filter((e=>e.get instanceof Function)).map(function(){var n=r((function*(r){return r.get(e,t)}));return function(e){return n.apply(this,arguments)}}()))}))()}}class xV{constructor(r){var n,i,o,a,s,l=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"log",void 0),e(this,"peerId",void 0),e(this,"peerStore",void 0),e(this,"routers",void 0),e(this,Symbol.toStringTag,"@libp2p/peer-routing"),this.log=r.logger.forComponent("libp2p:peer-routing"),this.peerId=r.peerId,this.peerStore=r.peerStore,this.routers=null!==(n=l.routers)&&void 0!==n?n:[],this.findPeer=null!==(i=null===(o=r.metrics)||void 0===o?void 0:o.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:(e,r)=>{var[n]=e;return t(t({},r),{},{peer:n.toString()})}}))&&void 0!==i?i:this.findPeer,this.getClosestPeers=null!==(a=null===(s=r.metrics)||void 0===s?void 0:s.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:(e,r)=>{var[n]=e;return t(t({},r),{},{key:gt(n,"base36")})},getAttributesFromYieldedValue:(e,r)=>t(t({},r),{},{peers:[...Array.isArray(r.peers)?r.peers:[],e.id.toString()]})}))&&void 0!==a?a:this.getClosestPeers}findPeer(e,t){var n=this;return r((function*(){if(0===n.routers.length)throw new pj("No peer routers available");if(e.toString()===n.peerId.toString())throw new fj("Should not try to find self");var r,i=n,o=Vc(...n.routers.filter((e=>e.findPeer instanceof Function)).map((r=>l((function*(){try{yield yield u(r.findPeer(e,t))}catch(e){i.log.error(e)}}))()))),a=!1,c=!1;try{for(var d,h=s(o);a=!(d=yield h.next()).done;a=!1){var v=d.value;if(null!=v)return v.multiaddrs.length>0&&(yield n.peerStore.merge(v.id,{multiaddrs:v.multiaddrs})),v}}catch(e){c=!0,r=e}finally{try{a&&null!=h.return&&(yield h.return())}finally{if(c)throw r}}throw new Ha}))()}getClosestPeers(e){var n=this;return l((function(e){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(0===n.routers.length)throw new pj("No peer routers available");var o,a=n,c=rv(1024),d=!1,h=!1;try{for(var v,p=s(xL(l((function*(){var n,o=Vc(...a.routers.filter((e=>e.getClosestPeers instanceof Function)).map((t=>t.getClosestPeers(e,i)))),l=!1,c=!1;try{for(var d,h=function*(){var e=d.value;yield r((function*(){if(0===e.multiaddrs.length)try{e=yield a.findPeer(e.id,t(t({},i),{},{useCache:!1}))}catch(e){return void a.log.error("could not find peer multiaddrs",e)}return e}))},v=s(o);l=!(d=yield u(v.next())).done;l=!1)yield*h()}catch(e){c=!0,n=e}finally{try{l&&null!=v.return&&(yield u(v.return()))}finally{if(c)throw n}}}))()));d=!(v=yield u(p.next())).done;d=!1){var f=v.value;null!=f&&(f.multiaddrs.length>0&&(yield u(n.peerStore.merge(f.id,{multiaddrs:f.multiaddrs}))),c.has(f.id.toMultihash().bytes)||(c.add(f.id.toMultihash().bytes),yield f))}}catch(e){h=!0,o=e}finally{try{d&&null!=p.return&&(yield u(p.return()))}finally{if(h)throw o}}}()})).apply(this,arguments)}}class AV extends us{constructor(t){super(),e(this,"peerRouting",void 0),e(this,"log",void 0),e(this,"walking",void 0),e(this,"walkers",void 0),e(this,"shutdownController",void 0),e(this,"walkController",void 0),e(this,"needNext",void 0),e(this,Symbol.toStringTag,"@libp2p/random-walk"),this.log=t.logger.forComponent("libp2p:random-walk"),this.peerRouting=t.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}walk(e){var t=this;return l((function*(){t.walking||t.startWalk(),t.walkers++;var r=Dh([t.shutdownController.signal,null==e?void 0:e.signal]);try{for(;;){var n;null===(n=t.needNext)||void 0===n||n.resolve(),t.needNext=_c();var i=yield u(hv(t,"walk:peer",r,{errorEvent:"walk:error"}));yield i.detail}}finally{var o;if(r.clear(),t.walkers--,0===t.walkers)null===(o=t.walkController)||void 0===o||o.abort(),t.walkController=void 0}}))()}startWalk(){var e=this;this.walking=!0,this.walkController=new AbortController,this.walkController.signal;var t=Dh([this.walkController.signal,this.shutdownController.signal]),n=Date.now(),i=0;Promise.resolve().then(r((function*(){for(e.log("start walk");e.walkers>0;)try{var r,n=Zl(32),o=Date.now(),a=!1,l=!1;try{for(var u,c=s(e.peerRouting.getClosestPeers(n,{signal:t}));a=!(u=yield c.next()).done;a=!1){var d=u.value;t.aborted&&e.log("aborting walk"),t.throwIfAborted(),e.log("found peer %p after %dms for %d walkers",d.id,Date.now()-o,e.walkers),i++,e.safeDispatchEvent("walk:peer",{detail:d}),1===e.walkers&&null!=e.needNext&&(e.log("wait for need next"),yield Lc(e.needNext.promise,t)),o=Date.now()}}catch(e){l=!0,r=e}finally{try{a&&null!=c.return&&(yield c.return())}finally{if(l)throw r}}e.log("walk iteration for %b and %d walkers finished, found %d peers",n,e.walkers,i)}catch(t){e.log.error("random walk errored",t),e.safeDispatchEvent("walk:error",{detail:t})}e.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",i,Date.now()-n),this.walking=!1}))}}class CV{constructor(t){e(this,"log",void 0),e(this,"topologies",void 0),e(this,"handlers",void 0),e(this,"components",void 0),e(this,Symbol.toStringTag,"@libp2p/registrar"),this.log=t.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=t,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)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){var t=this.handlers.get(e);if(null==t)throw new gj("No handler registered for protocol ".concat(e));return t}getTopologies(e){var t=this.topologies.get(e);return null==t?[]:[...t.values()]}handle(e,t,n){var i=this;return r((function*(){if(i.handlers.has(e)&&!0!==(null==n?void 0:n.force))throw new yj("Handler already registered for protocol ".concat(e));var r=UU.bind({ignoreUndefined:!0})({maxInboundStreams:32,maxOutboundStreams:64},n);i.handlers.set(e,{handler:t,options:r}),yield i.components.peerStore.merge(i.components.peerId,{protocols:[e]})}))()}unhandle(e){var t=this;return r((function*(){(Array.isArray(e)?e:[e]).forEach((e=>{t.handlers.delete(e)})),yield t.components.peerStore.patch(t.components.peerId,{protocols:t.getProtocols()})}))()}register(e,t){var n=this;return r((function*(){if(null==t)throw new Ra("invalid topology");var r="".concat((1e9*Math.random()).toString(36)).concat(Date.now()),i=n.topologies.get(e);return null==i&&(i=new Map,n.topologies.set(e,i)),i.set(r,t),r}))()}unregister(e){for(var[t,r]of this.topologies.entries())r.has(e)&&(r.delete(e),0===r.size&&this.topologies.delete(t))}_onDisconnect(e){var t=e.detail;this.components.peerStore.get(t).then((e=>{for(var r of e.protocols){var n=this.topologies.get(r);if(null!=n)for(var i of n.values()){var o,a,s;!1!==(null===(o=i.filter)||void 0===o?void 0:o.has(t))&&(null===(a=i.filter)||void 0===a||a.remove(t),null===(s=i.onDisconnect)||void 0===s||s.call(i,t))}}})).catch((e=>{"NotFoundError"!==e.name&&this.log.error("could not inform topologies of disconnecting peer %p",t,e)}))}_onPeerUpdate(e){var t,{peer:r,previous:n}=e.detail,i=(null!==(t=null==n?void 0:n.protocols)&&void 0!==t?t:[]).filter((e=>!r.protocols.includes(e)));for(var o of i){var a=this.topologies.get(o);if(null!=a)for(var s of a.values()){var l,u,c;!1!==(null===(l=s.filter)||void 0===l?void 0:l.has(r.id))&&(null===(u=s.filter)||void 0===u||u.remove(r.id),null===(c=s.onDisconnect)||void 0===c||c.call(s,r.id))}}}_onPeerIdentify(e){var t=e.detail.protocols,r=e.detail.connection,n=e.detail.peerId;for(var i of t){var o=this.topologies.get(i);if(null!=o)for(var a of o.values()){var s,l,u;null!=r.limits&&!0!==a.notifyOnLimitedConnection||!0!==(null===(s=a.filter)||void 0===s?void 0:s.has(n))&&(null===(l=a.filter)||void 0===l||l.add(n),null===(u=a.onConnect)||void 0===u||u.call(a,n,r))}}}}class IV{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"log",void 0),e(this,"components",void 0),e(this,"transports",void 0),e(this,"listeners",void 0),e(this,"faultTolerance",void 0),e(this,"started",void 0),e(this,Symbol.toStringTag,"@libp2p/transport-manager"),this.log=t.logger.forComponent("libp2p:transports"),this.components=t,this.started=!1,this.transports=new Map,this.listeners=tD({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=null!==(r=n.faultTolerance)&&void 0!==r?r:Ia.FATAL_ALL}add(e){var t=e[Symbol.toStringTag];if(null==t)throw new Ra("Transport must have a valid tag");if(this.transports.has(t))throw new Ra("There is already a transport with the tag ".concat(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}afterStart(){var e=this;return r((function*(){var t=e.components.addressManager.getListenAddrs();yield e.listen(t)}))()}stop(){var e=this;return r((function*(){var t=[];for(var[r,n]of e.listeners)for(e.log("closing listeners for %s",r);n.length>0;){var i=n.pop();null!=i&&t.push(i.close())}for(var o of(yield Promise.all(t),e.log("all listeners closed"),e.listeners.keys()))e.listeners.set(o,[]);e.started=!1}))()}dial(e,n){var i=this;return r((function*(){var r,o=i.dialTransportForMultiaddr(e);if(null==o)throw new Cj("No transport available for address ".concat(String(e)));return null==n||null===(r=n.onProgress)||void 0===r||r.call(n,new cv("transport-manager:selected-transport",o[Symbol.toStringTag])),o.dial(e,t(t({},n),{},{upgrader:i.components.upgrader}))}))()}getAddrs(){var e=[];for(var t of this.listeners.values())for(var 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(var t of this.transports.values()){if(t.dialFilter([e]).length>0)return t}}listenTransportForMultiaddr(e){for(var t of this.transports.values()){if(t.listenFilter([e]).length>0)return t}}listen(e){var t=this;return r((function*(){if(!t.isStarted())throw new Xa("Not started");if(null!=e&&0!==e.length){var r={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach((e=>{r.errors.set(e.toString(),new wj)}));var n=[],i=function*(i){var o=a.listenFilter(e),s=function*(e){var o;t.log("creating listener for %s on %a",i,e);var s=a.createListener({upgrader:t.components.upgrader}),l=null!==(o=t.listeners.get(i))&&void 0!==o?o:[];null==l&&(l=[],t.listeners.set(i,l)),l.push(s),s.addEventListener("listening",(()=>{t.components.events.safeDispatchEvent("transport:listening",{detail:s})})),s.addEventListener("close",(()=>{var e=l.findIndex((e=>e===s));l.splice(e,1),t.components.events.safeDispatchEvent("transport:close",{detail:s})})),lh.matches(e)?r.ipv4.attempts++:uh.matches(e)&&r.ipv6.attempts++,n.push(s.listen(e).then((()=>{r.errors.delete(e.toString()),lh.matches(e)&&r.ipv4.success++,uh.matches(e)&&r.ipv6.success++}),(n=>{throw t.log.error("transport %s could not listen on address %a - %e",i,e,n),r.errors.set(e.toString(),n),n})))};for(var l of o)yield*s(l)};for(var[o,a]of t.transports.entries())yield*i(o);var s=yield Promise.allSettled(n);if(!(s.length>0&&s.every((e=>"fulfilled"===e.status))))if(t.ipv6Unsupported(r))t.log("all IPv4 addresses succeed but all IPv6 failed");else{if(t.faultTolerance!==Ia.NO_FATAL)throw new bj("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".concat([...r.errors.entries()].map((e=>{var t,[r,n]=e;return"\n ".concat(r,": ").concat("".concat(null!==(t=n.stack)&&void 0!==t?t:n).split("\n").join("\n "),"\n")})).join("")));t.log("failed to listen on any address but fault tolerance allows this")}}else t.log("no addresses were provided for listening, this node is dial only")}))()}ipv6Unsupported(e){if(0===e.ipv4.attempts||0===e.ipv6.attempts)return!1;var t=e.ipv4.attempts===e.ipv4.success,r=0===e.ipv6.success;return t&&r}remove(e){var t=this;return r((function*(){var r,n=null!==(r=t.listeners.get(e))&&void 0!==r?r:[];t.log.trace("removing transport %s",e);var i=[];for(t.log.trace("closing listeners for %s",e);n.length>0;){var o=n.pop();null!=o&&i.push(o.close())}yield Promise.all(i),t.transports.delete(e),t.listeners.delete(e)}))()}removeAll(){var e=this;return r((function*(){var t=[];for(var r of e.transports.keys())t.push(e.remove(r));yield Promise.all(t)}))()}}var TV="/multistream/1.0.0",PV=1024,_V=xt("\n");function BV(e,t,r){return NV.apply(this,arguments)}function NV(){return NV=r((function*(e,t,r){yield e.write(t,r)})),NV.apply(this,arguments)}function DV(){return DV=r((function*(e,t,r){yield e.writeV(t,r)})),DV.apply(this,arguments)}function RV(){return RV=r((function*(e,t){var r=yield e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==_V[0])throw t.log.error("Invalid mss message - missing newline",r),new Ja("Missing newline");return r.sublist(0,-1)})),RV.apply(this,arguments)}function OV(e,t){return LV.apply(this,arguments)}function LV(){return LV=r((function*(e,t){var r=yield function(e,t){return RV.apply(this,arguments)}(e,t);return gt(r.subarray())})),LV.apply(this,arguments)}function MV(e,t,r){return UV.apply(this,arguments)}function UV(){return UV=r((function*(e,n,i){if(1===(n=Array.isArray(n)?[...n]:[n]).length&&!1===i.negotiateFully)return function(e,n,i){var o=e.sink.bind(e),a=e.source,d=!1,h=!1,v=_c(),p=!1,f=!1,g=_c(),y=!1,m=!1,w=_c(),b=Id({sink:o,source:a},t(t({},i),{},{maxDataLength:PV}));function S(){return E.apply(this,arguments)}function E(){return(E=r((function*(){if(h)return i.log.trace("optimistic: already negotiating %s stream",n),void(yield v.promise);h=!0;try{p||(i.log.trace("optimistic: doing send protocol for %s stream",n),yield k()),y||(i.log.trace("optimistic: doing read protocol for %s stream",n),yield A())}finally{h=!1,d=!0,v.resolve()}}))).apply(this,arguments)}function k(){return x.apply(this,arguments)}function x(){return(x=r((function*(){if(f)yield g.promise;else{f=!0;try{i.log.trace('optimistic: write ["%s", "%s", data] in source',TV,n),yield b.writeV([xt("".concat(TV,"\n")),xt("".concat(n,"\n"))]),i.log.trace('optimistic: wrote ["%s", "%s", data] in source',TV,n)}finally{p=!0,f=!1,g.resolve()}}}))).apply(this,arguments)}function A(){return C.apply(this,arguments)}function C(){return C=r((function*(){if(m)yield w.promise;else{m=!0;try{i.log.trace("optimistic: reading multistream select header");var e=yield OV(b,i);if(i.log.trace('optimistic: read multistream select header "%s"',e),e===TV&&(e=yield OV(b,i)),i.log.trace('optimistic: read protocol "%s", expecting "%s"',e,n),e!==n)throw new Ya("protocol selection failed")}finally{y=!0,m=!1,w.resolve()}}})),C.apply(this,arguments)}if(e.sink=function(){var e=r((function*(e){var{sink:t}=b.unwrap();yield t(l((function*(){var t,r=!1,o=!1,a=!1;try{for(var l,c=s(e);o=!(l=yield u(c.next())).done;o=!1){var d=l.value;if(f&&(yield u(g.promise)),p)yield d;else{f=!0,i.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',TV,n,d.byteLength);var h="".concat(n,"\n");yield new bs(Uint8Array.from([19]),xt("".concat(TV,"\n")),Ut(h.length),xt(h),d).subarray(),i.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',TV,n,d.byteLength),p=!0,f=!1,g.resolve(),S().catch((e=>{i.log.error("could not finish optimistic protocol negotiation of %s",n,e)}))}r=!0}}catch(e){a=!0,t=e}finally{try{o&&null!=c.return&&(yield u(c.return()))}finally{if(a)throw t}}r||(yield u(S()))}))())}));return function(t){return e.apply(this,arguments)}}(),e.source=l((function*(){yield u(S()),i.log.trace('optimistic: reading data from "%s" stream',n),yield*c(s(b.unwrap().source))}))(),null!=e.closeRead){var I=e.closeRead.bind(e);e.closeRead=function(){var e=r((function*(e){d||(yield S().catch((e=>{i.log.error("could not negotiate protocol before close read",e)}))),yield I(e)}));return function(t){return e.apply(this,arguments)}}()}if(null!=e.closeWrite){var T=e.closeWrite.bind(e);e.closeWrite=function(){var e=r((function*(e){d||(yield S().catch((e=>{i.log.error("could not negotiate protocol before close write",e)}))),yield T(e)}));return function(t){return e.apply(this,arguments)}}()}if(null!=e.close){var P=e.close.bind(e);e.close=function(){var e=r((function*(e){var t=[];f&&t.push(g.promise),m&&t.push(w.promise),t.length>0?yield Lc(Promise.all(t),null==e?void 0:e.signal):(d=!0,h=!1,v.resolve()),yield P(e)}));return function(t){return e.apply(this,arguments)}}()}return{stream:e,protocol:n}}(e,n[0],i);var o=Id(e,t(t({},i),{},{maxDataLength:PV})),a=n.shift();if(null==a)throw new Error("At least one protocol must be specified");i.log.trace('select: write ["%s", "%s"]',TV,a);var d=xt("".concat(TV,"\n")),h=xt("".concat(a,"\n"));yield function(e,t,r){return DV.apply(this,arguments)}(o,[d,h],i),i.log.trace("select: reading multistream-select header");var v=yield OV(o,i);if(i.log.trace('select: read "%s"',v),v===TV&&(i.log.trace("select: reading protocol response"),v=yield OV(o,i),i.log.trace('select: read "%s"',v)),v===a)return{stream:o.unwrap(),protocol:a};for(var p of n){i.log.trace('select: write "%s"',p),yield BV(o,xt("".concat(p,"\n")),i),i.log.trace("select: reading protocol response");var f=yield OV(o,i);if(i.log.trace('select: read "%s" for "%s"',f,p),f===p)return{stream:o.unwrap(),protocol:p}}throw new Ya("protocol selection failed")})),UV.apply(this,arguments)}function FV(e,t,r){return zV.apply(this,arguments)}function zV(){return zV=r((function*(e,r,n){r=Array.isArray(r)?r:[r],n.log.trace("handle: available protocols %s",r);for(var i=Id(e,t(t({},n),{},{maxDataLength:PV,maxLengthLength:2}));;){n.log.trace("handle: reading incoming string");var o=yield OV(i,n);if(n.log.trace('handle: read "%s"',o),o!==TV){if(r.includes(o))return n.log.trace('handle: respond with "%s" for "%s"',o,o),yield BV(i,xt("".concat(o,"\n")),n),n.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:i.unwrap(),protocol:o};if("ls"!==o)n.log.trace('handle: respond with "na" for "%s"',o),yield BV(i,xt("na\n"),n),n.log('handle: responded with "na" for "%s"',o);else{var a=new bs(...r.map((e=>xp.single(xt("".concat(e,"\n"))))),xt("\n"));n.log.trace('handle: respond with "%s" for %s',r,o),yield BV(i,a,n),n.log.trace('handle: responded with "%s" for %s',r,o)}}else n.log.trace('handle: respond with "%s" for "%s"',TV,o),yield BV(i,xt("".concat(TV,"\n")),n),n.log.trace('handle: responded with "%s" for "%s"',TV,o)}})),zV.apply(this,arguments)}class jV{constructor(t){e(this,"id",void 0),e(this,"remoteAddr",void 0),e(this,"remotePeer",void 0),e(this,"direction",void 0),e(this,"timeline",void 0),e(this,"multiplexer",void 0),e(this,"encryption",void 0),e(this,"status",void 0),e(this,"limits",void 0),e(this,"log",void 0),e(this,"tags",void 0),e(this,"_newStream",void 0),e(this,"_close",void 0),e(this,"_abort",void 0),e(this,"_getStreams",void 0),e(this,Symbol.toStringTag,"Connection"),e(this,Ea,!0);var{remoteAddr:r,remotePeer:n,newStream:i,close:o,abort:a,getStreams:s}=t;this.id="".concat(parseInt(String(1e9*Math.random())).toString(36)).concat(Date.now()),this.remoteAddr=r,this.remotePeer=n,this.direction=t.direction,this.status="open",this.timeline=t.timeline,this.multiplexer=t.multiplexer,this.encryption=t.encryption,this.limits=t.limits,this.log=t.logger.forComponent("libp2p:connection:".concat(this.direction,":").concat(this.id)),null==this.remoteAddr.getPeerId()&&(this.remoteAddr=this.remoteAddr.encapsulate("/p2p/".concat(this.remotePeer))),this._newStream=i,this._close=o,this._abort=a,this._getStreams=s,this.tags=[]}get streams(){return this._getStreams()}newStream(e,t){var n=this;return r((function*(){if("closing"===n.status)throw new Ua("the connection is being closed");if("closed"===n.status)throw new Fa("the connection is closed");if(Array.isArray(e)||(e=[e]),null!=n.limits&&!0!==(null==t?void 0:t.runOnLimitedConnection))throw new ns("Cannot open protocol stream on limited connection");var r=yield n._newStream(e,t);return r.direction="outbound",r}))()}close(){var e=arguments,n=this;return r((function*(){var r=e.length>0&&void 0!==e[0]?e[0]:{};if("closed"!==n.status&&"closing"!==n.status){if(n.log("closing connection to %a",n.remoteAddr),n.status="closing",null==r.signal){var i=AbortSignal.timeout(500);r=t(t({},r),{},{signal:i})}try{n.log.trace("closing underlying transport"),yield n._close(r),n.log.trace("updating timeline with close time"),n.status="closed",n.timeline.close=Date.now()}catch(e){n.log.error("error encountered during graceful close of connection to %a",n.remoteAddr,e),n.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 VV(e,t,r){var n=0;return r.streams.forEach((r=>{r.direction===t&&r.protocol===e&&n++})),n}class qV{constructor(t,r){var n,i,o,a,s;e(this,"components",void 0),e(this,"connectionEncrypters",void 0),e(this,"streamMuxers",void 0),e(this,"inboundUpgradeTimeout",void 0),e(this,"inboundStreamProtocolNegotiationTimeout",void 0),e(this,"outboundStreamProtocolNegotiationTimeout",void 0),e(this,"events",void 0),e(this,"metrics",void 0),e(this,Symbol.toStringTag,"@libp2p/upgrader"),this.components=t,this.connectionEncrypters=new Map,r.connectionEncrypters.forEach((e=>{this.connectionEncrypters.set(e.protocol,e)})),this.streamMuxers=new Map,r.streamMuxers.forEach((e=>{this.streamMuxers.set(e.protocol,e)})),this.inboundUpgradeTimeout=null!==(n=r.inboundUpgradeTimeout)&&void 0!==n?n:1e4,this.inboundStreamProtocolNegotiationTimeout=null!==(i=r.inboundStreamProtocolNegotiationTimeout)&&void 0!==i?i:1e4,this.outboundStreamProtocolNegotiationTimeout=null!==(o=r.outboundStreamProtocolNegotiationTimeout)&&void 0!==o?o:1e4,this.events=t.events,this.metrics={dials:null===(a=t.metrics)||void 0===a?void 0:a.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:null===(s=t.metrics)||void 0===s?void 0:s.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}shouldBlockConnection(e){var t=arguments,n=this;return r((function*(){var r=n.components.connectionGater[e];if(null!=r){for(var i=t.length,o=new Array(i>1?i-1:0),a=1;a<i;a++)o[a-1]=t[a];if(!0===(yield r.apply(n.components.connectionGater,o)))throw new Ej("The multiaddr connection is blocked by gater.".concat(e))}}))()}createInboundAbortSignal(e){return Dh([AbortSignal.timeout(this.inboundUpgradeTimeout),e])}upgradeInbound(e,n){var i=this;return r((function*(){var r=!1,o=i.createInboundAbortSignal(n.signal);try{var a;if(null===(a=i.metrics.dials)||void 0===a||a.increment({inbound:!0}),!(r=yield i.components.connectionManager.acceptIncomingConnection(e)))throw new kj("Connection denied");yield i.shouldBlockConnection("denyInboundConnection",e),yield i._performUpgrade(e,"inbound",t(t({},n),{},{signal:o}))}catch(e){var s;throw null===(s=i.metrics.errors)||void 0===s||s.increment({inbound:!0}),e}finally{o.clear(),r&&i.components.connectionManager.afterUpgradeInbound()}}))()}upgradeOutbound(e,t){var n=this;return r((function*(){try{var r;null===(r=n.metrics.dials)||void 0===r||r.increment({outbound:!0});var i,o=e.remoteAddr.getPeerId();null!=o&&(i=Mu(o),yield n.shouldBlockConnection("denyOutboundConnection",i,e));var a="outbound";return!1===t.initiator&&(a="inbound"),yield n._performUpgrade(e,a,t)}catch(e){var s;throw null===(s=n.metrics.errors)||void 0===s||s.increment({outbound:!0}),e}}))()}_performUpgrade(e,n,i){var o=this;return r((function*(){var r,a,s,l,u,c;null===(r=o.components.metrics)||void 0===r||r.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",n);var d=e;if(!0!==(null==i?void 0:i.skipProtection)){var h=o.components.connectionProtector;null!=h&&(e.log("protecting the %s connection",n),d=yield h.protect(e,i))}try{if(a=d,!0!==(null==i?void 0:i.skipEncryption)){var v;null==i||null===(v=i.onProgress)||void 0===v||v.call(i,new cv("upgrader:encrypt-".concat(n,"-connection"))),({conn:a,remotePeer:s,protocol:c,streamMuxer:u}=yield"inbound"===n?o._encryptInbound(d,i):o._encryptOutbound(d,i));var p=t(t({},d),a);yield o.shouldBlockConnection("inbound"===n?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,p)}else{var f=e.remoteAddr.getPeerId();if(null==f)throw new Wa("".concat(n," connection that skipped encryption must have a peer id"));var g=Mu(f);c="native",s=g}if(s.equals(o.components.peerId)){var y=new Ka("Can not dial self");throw e.abort(y),y}if(l=a,null!=(null==i?void 0:i.muxerFactory))u=i.muxerFactory;else if(null==u&&o.streamMuxers.size>0){var m;null==i||null===(m=i.onProgress)||void 0===m||m.call(i,new cv("upgrader:multiplex-".concat(n,"-connection")));var w=yield"inbound"===n?o._multiplexInbound(t(t({},d),a),o.streamMuxers,i):o._multiplexOutbound(t(t({},d),a),o.streamMuxers,i);u=w.muxerFactory,l=w.stream}}catch(y){throw e.log.error("failed to upgrade inbound connection %s %a - %e","inbound"===n?"from":"to",e.remoteAddr,y),y}return yield o.shouldBlockConnection("inbound"===n?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e),e.log("successfully upgraded %s connection",n),o._createConnection({cryptoProtocol:c,direction:n,maConn:e,upgradedConn:l,muxerFactory:u,remotePeer:s,limits:null==i?void 0:i.limits})}))()}_createConnection(e){var n,i,o,a,s=this,{cryptoProtocol:l,direction:u,maConn:c,upgradedConn:d,remotePeer:h,muxerFactory:v,limits:p}=e;null!=v&&(i=v.createStreamMuxer({direction:u,onIncomingStream:e=>{null!=a&&Promise.resolve().then(r((function*(){var t,r=s.components.registrar.getProtocols(),n=AbortSignal.timeout(s.inboundStreamProtocolNegotiationTimeout),{stream:i,protocol:o}=yield FV(e,r,{signal:n,log:e.log,yieldBytes:!1});if(null!=a){a.log("incoming stream opened on %s",o);var l=function(e,t){try{var{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return 32}(o,s.components.registrar);if(VV(o,"inbound",a)===l){var u=new is('Too many inbound protocol streams for protocol "'.concat(o,'" - limit ').concat(l));throw e.abort(u),u}e.source=i.source,e.sink=i.sink,e.protocol=o,null!=i.closeWrite&&(e.closeWrite=i.closeWrite),null!=i.closeRead&&(e.closeRead=i.closeRead),null!=i.close&&(e.close=i.close),yield s.components.peerStore.merge(h,{protocols:[o]}),null===(t=s.components.metrics)||void 0===t||t.trackProtocolStream(e,a),s._onStream({connection:a,stream:e,protocol:o})}}))).catch(function(){var t=r((function*(t){a.log.error("error handling incoming stream id %s - %e",e.id,t),null==e.timeline.close&&(yield e.close())}));return function(e){return t.apply(this,arguments)}}())}}),o=function(){var n=r((function*(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null==i)throw new xj("Connection is not multiplexed");a.log.trace("starting new stream for protocols %s",r);var o=yield i.newStream();a.log.trace("started new stream %s for protocols %s",o.id,r);try{var l;if(null==n.signal){o.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",r);var c=AbortSignal.timeout(s.outboundStreamProtocolNegotiationTimeout);n=t(t({},n),{},{signal:c})}o.log.trace("selecting protocol from protocols %s",r);var{stream:d,protocol:v}=yield MV(o,r,t(t({},n),{},{log:o.log,yieldBytes:!0}));o.log.trace("selected protocol %s",v);var p=function(e,t){var r,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{var{options:i}=t.getHandler(e);if(null!=i.maxOutboundStreams)return i.maxOutboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return null!==(r=n.maxOutboundStreams)&&void 0!==r?r:64}(v,s.components.registrar,n),f=VV(v,"outbound",a);if(f>=p){var g=new os('Too many outbound protocol streams for protocol "'.concat(v,'" - ').concat(f,"/").concat(p));throw o.abort(g),g}return yield s.components.peerStore.merge(h,{protocols:[v]}),o.source=d.source,o.sink=d.sink,o.protocol=v,null!=d.closeWrite&&(o.closeWrite=d.closeWrite),null!=d.closeRead&&(o.closeRead=d.closeRead),null!=d.close&&(o.close=d.close),null===(l=s.components.metrics)||void 0===l||l.trackProtocolStream(o,a),o}catch(g){throw a.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e","inbound"===u?"from":"to",e.maConn.remoteAddr,r,g),null==o.timeline.close&&o.abort(g),g}}));return function(e){return n.apply(this,arguments)}}(),Promise.all([i.sink(d.source),d.sink(i.source)]).catch((e=>{a.log.error("error piping data through muxer - %e",e)})));var f=c.timeline;c.timeline=new Proxy(f,{set:function(){return"close"===(arguments.length<=1?void 0:arguments[1])&&null!=(arguments.length<=2?void 0:arguments[2])&&null==f.close&&r((function*(){try{"open"===a.status&&(yield a.close())}catch(e){a.log.error("error closing connection after timeline close %e",e)}finally{s.events.safeDispatchEvent("connection:close",{detail:a})}}))().catch((e=>{a.log.error("error thrown while dispatching connection:close event %e",e)})),Reflect.set(...arguments)}}),c.timeline.upgraded=Date.now();var g,y;return g={remoteAddr:c.remoteAddr,remotePeer:h,status:"open",direction:u,timeline:c.timeline,multiplexer:null===(n=i)||void 0===n?void 0:n.protocol,encryption:l,limits:p,logger:this.components.logger,newStream:null!=o?o:()=>{throw new xj("Connection is not multiplexed")},getStreams:()=>{var e,t;return null!==(e=null===(t=i)||void 0===t?void 0:t.streams)&&void 0!==e?e:[]},close:(y=r((function*(e){var t;yield null===(t=i)||void 0===t?void 0:t.close(e),yield c.close(e)})),function(e){return y.apply(this,arguments)}),abort:e=>{var t;c.abort(e),null===(t=i)||void 0===t||t.abort(e)}},a=new jV(g),this.events.safeDispatchEvent("connection:open",{detail:a}),a.__maConnTimeline=f,a}_onStream(e){var{connection:t,stream:r,protocol:n}=e,{handler:i,options:o}=this.components.registrar.getHandler(n);if(null!=t.limits&&!0!==o.runOnLimitedConnection)throw new ns("Cannot open protocol stream on limited connection");i({connection:t,stream:r})}_encryptInbound(e,n){var i=this;return r((function*(){var r=Array.from(i.connectionEncrypters.keys());try{var{stream:o,protocol:a}=yield FV(e,r,t(t({},n),{},{log:e.log})),s=i.connectionEncrypters.get(a);if(null==s)throw new Aj("no crypto module found for ".concat(a));return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,a),t(t({},yield s.secureInbound(o,n)),{},{protocol:a})}catch(t){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,t),new Aj(t.message)}}))()}_encryptOutbound(e,n){var i=this;return r((function*(){var r=Array.from(i.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",r);var{stream:o,protocol:a}=yield MV(e,r,t(t({},n),{},{log:e.log,yieldBytes:!0})),s=i.connectionEncrypters.get(a);if(null==s)throw new Aj("no crypto module found for ".concat(a));return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,a),t(t({},yield s.secureOutbound(o,n)),{},{protocol:a})}catch(t){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,t),new Aj(t.message)}}))()}_multiplexOutbound(e,n,i){return r((function*(){var r=Array.from(n.keys());e.log("outbound selecting muxer %s",r);try{e.log.trace("selecting stream muxer from %s",r);var{stream:o,protocol:a}=yield MV(e,r,t(t({},i),{},{log:e.log,yieldBytes:!0}));return e.log("selected %s as muxer protocol",a),{stream:o,muxerFactory:n.get(a)}}catch(t){throw e.log.error("error multiplexing outbound connection",t),new xj(String(t))}}))()}_multiplexInbound(e,n,i){return r((function*(){var r=Array.from(n.keys());e.log("inbound handling muxers %s",r);try{var{stream:o,protocol:a}=yield FV(e,r,t(t({},i),{},{log:e.log}));return{stream:o,muxerFactory:n.get(a)}}catch(t){throw e.log.error("error multiplexing inbound connection",t),new xj(String(t))}}))()}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}}var HV=new WeakSet;class KV extends us{constructor(r){var n,i,o,a,s,l,u,c,v,p,f,g,y,m,w,b,S,E,k,x,A,C;super(),d(this,HV),e(this,"peerId",void 0),e(this,"peerStore",void 0),e(this,"contentRouting",void 0),e(this,"peerRouting",void 0),e(this,"metrics",void 0),e(this,"services",void 0),e(this,"logger",void 0),e(this,"status",void 0),e(this,"components",void 0),e(this,"log",void 0),this.status="stopped";var I=new us,T=I.dispatchEvent.bind(I);I.dispatchEvent=e=>{var t=T(e),r=this.dispatchEvent(new CustomEvent(e.type,{detail:e.detail}));return t||r},this.peerId=r.peerId,this.logger=null!==(n=r.logger)&&void 0!==n?n:cd(),this.log=this.logger.forComponent("libp2p"),this.services={};var P=null!==(i=null===(o=r.nodeInfo)||void 0===o?void 0:o.name)&&void 0!==i?i:az,_=null!==(a=null===(s=r.nodeInfo)||void 0===s?void 0:s.version)&&void 0!==a?a:oz,B=this.components=function(){var e=new Ij(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{});return new Proxy(e,{get(t,r,n){if("string"==typeof r&&!Pj.includes(r)){var i=e.components[r];if(null==i&&!Tj.includes(r))throw new dj("".concat(r," not set"));return i}return Reflect.get(t,r,n)},set:(t,r,n)=>("string"==typeof r?e.components[r]=n:Reflect.set(t,r,n),!0)})}({peerId:r.peerId,privateKey:r.privateKey,nodeInfo:{name:P,version:_,userAgent:null!==(l=null===(u=r.nodeInfo)||void 0===u?void 0:u.userAgent)&&void 0!==l?l:sz(P,_)},logger:this.logger,events:I,datastore:null!==(c=r.datastore)&&void 0!==c?c:new Tc,connectionGater:Dj(r.connectionGater),dns:r.dns});this.peerStore=this.configureComponent("peerStore",function(e){return new Yz(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}(B,t({addressFilter:this.components.connectionGater.filterMultiaddrForPeer},r.peerStore))),null!=r.metrics&&(this.metrics=this.configureComponent("metrics",r.metrics(this.components))),B.events.addEventListener("peer:update",(e=>{if(null==e.detail.previous){var t={id:e.detail.peer.id,multiaddrs:e.detail.peer.addresses.map((e=>e.multiaddr))};B.events.safeDispatchEvent("peer:discovery",{detail:t})}})),null!=r.connectionProtector&&this.configureComponent("connectionProtector",r.connectionProtector(B)),this.components.upgrader=new qV(this.components,{connectionEncrypters:(null!==(v=r.connectionEncrypters)&&void 0!==v?v:[]).map(((e,t)=>this.configureComponent("connection-encryption-".concat(t),e(this.components)))),streamMuxers:(null!==(p=r.streamMuxers)&&void 0!==p?p:[]).map(((e,t)=>this.configureComponent("stream-muxers-".concat(t),e(this.components)))),inboundUpgradeTimeout:null===(f=r.connectionManager)||void 0===f?void 0:f.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:null!==(g=null===(y=r.connectionManager)||void 0===y?void 0:y.inboundStreamProtocolNegotiationTimeout)&&void 0!==g?g:null===(m=r.connectionManager)||void 0===m?void 0:m.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:null!==(w=null===(b=r.connectionManager)||void 0===b?void 0:b.outboundStreamProtocolNegotiationTimeout)&&void 0!==w?w:null===(S=r.connectionManager)||void 0===S?void 0:S.protocolNegotiationTimeout}),this.configureComponent("transportManager",new IV(this.components,r.transportManager)),this.configureComponent("connectionManager",new SV(this.components,r.connectionManager)),!1!==(null===(E=r.connectionMonitor)||void 0===E?void 0:E.enabled)&&this.configureComponent("connectionMonitor",new EV(this.components,r.connectionMonitor)),this.configureComponent("registrar",new CV(this.components)),this.configureComponent("addressManager",new cj(this.components,r.addresses));var N=(null!==(k=r.peerRouters)&&void 0!==k?k:[]).map(((e,t)=>this.configureComponent("peer-router-".concat(t),e(this.components))));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new xV(this.components,{routers:N}));var D=(null!==(x=r.contentRouters)&&void 0!==x?x:[]).map(((e,t)=>this.configureComponent("content-router-".concat(t),e(this.components))));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new kV(this.components,{routers:D})),this.configureComponent("randomWalk",new AV(this.components)),(null!==(A=r.peerDiscovery)&&void 0!==A?A:[]).forEach(((e,t)=>{this.configureComponent("peer-discovery-".concat(t),e(this.components)).addEventListener("peer",(e=>{h(HV,this,WV).call(this,e)}))})),null===(C=r.transports)||void 0===C||C.forEach(((e,t)=>{this.components.transportManager.add(this.configureComponent("transport-".concat(t),e(this.components)))})),null!=r.services)for(var R of Object.keys(r.services)){var O,L,M=(0,r.services[R])(this.components);if(null!=M){if(this.services[R]=M,this.configureComponent(R,M),null!=M[ka]&&(this.log("registering service %s for content routing",R),D.push(M[ka])),null!=M[Ta]&&(this.log("registering service %s for peer routing",R),N.push(M[Ta])),null!=M[xa])this.log("registering service %s for peer discovery",R),null===(O=(L=M[xa]).addEventListener)||void 0===O||O.call(L,"peer",(e=>{h(HV,this,WV).call(this,e)}))}else this.log.error("service factory %s returned null or undefined instance",R)}!function(e){var t={};for(var r of Object.values(e.components))for(var n of _j(r))t[n]=!0;for(var i of Object.values(e.components))for(var o of Bj(i))if(!0!==t[o])throw new hj('Service "'.concat(Nj(i),'" required capability "').concat(o,'" but it was not provided by any component, you may need to add additional configuration when creating your node.'))}(B)}configureComponent(e,t){return null==t&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}start(){var e=this;return r((function*(){if("stopped"===e.status){e.status="starting",e.log("libp2p is starting");try{var t,r,n,i;yield null===(t=(r=e.components).beforeStart)||void 0===t?void 0:t.call(r),yield e.components.start(),yield null===(n=(i=e.components).afterStart)||void 0===n?void 0:n.call(i),e.status="started",e.safeDispatchEvent("start",{detail:e}),e.log("libp2p has started")}catch(t){throw e.log.error("An error occurred starting libp2p",t),e.status="started",yield e.stop(),t}}}))()}stop(){var e=this;return r((function*(){var t,r,n,i;"started"===e.status&&(e.log("libp2p is stopping"),e.status="stopping",yield null===(t=(r=e.components).beforeStop)||void 0===t?void 0:t.call(r),yield e.components.stop(),yield null===(n=(i=e.components).afterStop)||void 0===n?void 0:n.call(i),e.status="stopped",e.safeDispatchEvent("stop",{detail:e}),e.log("libp2p has stopped"))}))()}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){var e=new Hh;for(var t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}dial(e){var n=arguments,i=this;return r((function*(){var r=n.length>1&&void 0!==n[1]?n[1]:{};return i.components.connectionManager.openConnection(e,t({priority:75},r))}))()}dialProtocol(e,t){var n=arguments,i=this;return r((function*(){var r=n.length>2&&void 0!==n[2]?n[2]:{};if(null==t)throw new Ra("no protocols were provided to open a stream");if(0===(t=Array.isArray(t)?t:[t]).length)throw new Ra("no protocols were provided to open a stream");return(yield i.dial(e,r)).newStream(t,r)}))()}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}hangUp(e){var t=arguments,n=this;return r((function*(){var r,i=t.length>1&&void 0!==t[1]?t[1]:{};Cr(e)&&(e=Mu(null!==(r=e.getPeerId())&&void 0!==r?r:""));yield n.components.connectionManager.closeConnections(e,i)}))()}getPublicKey(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};if(n.log("getPublicKey %p",e),null!=e.publicKey)return e.publicKey;try{var i=yield n.peerStore.get(e);if(null!=i.id.publicKey)return i.id.publicKey}catch(e){if("NotFoundError"!==e.name)throw e}var o=zt([xt("/pk/"),e.toMultihash().bytes]),a=Eu(yield n.contentRouting.get(o,r));return yield n.peerStore.patch(e,{publicKey:a}),a}))()}handle(e,t,n){var i=this;return r((function*(){Array.isArray(e)||(e=[e]),yield Promise.all(e.map(function(){var e=r((function*(e){yield i.components.registrar.handle(e,t,n)}));return function(t){return e.apply(this,arguments)}}()))}))()}unhandle(e){var t=this;return r((function*(){Array.isArray(e)||(e=[e]),yield Promise.all(e.map(function(){var e=r((function*(e){yield t.components.registrar.unhandle(e)}));return function(t){return e.apply(this,arguments)}}()))}))()}register(e,t){var n=this;return r((function*(){return n.components.registrar.register(e,t)}))()}unregister(e){this.components.registrar.unregister(e)}isDialable(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};return n.components.connectionManager.isDialable(e,r)}))()}}function WV(e){var{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 GV(){return QV.apply(this,arguments)}function QV(){return QV=r((function*(){var e,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};null!==(e=r.privateKey)&&void 0!==e||(r.privateKey=yield bu("Ed25519"));var n=new KV(t(t({},yield function(e){return mz.apply(this,arguments)}(r)),{},{peerId:Fu(r.privateKey)}));return!1!==r.start&&(yield n.start()),n})),QV.apply(this,arguments)}function YV(){return YV=r((function*(e){var r,n,i=null!==(r=e.libp2p)&&void 0!==r?r:{};null==i.privateKey&&null!=e.datastore&&(i.privateKey=yield function(e){return cz.apply(this,arguments)}(e.datastore,e.keychain));var o=uz(i);return o.datastore=null!==(n=o.datastore)&&void 0!==n?n:e.datastore,yield GV(t(t(t({},o),i),{},{start:!1}))})),YV.apply(this,arguments)}function JV(){return ZV.apply(this,arguments)}function ZV(){return ZV=r((function*(){var e,r,n,i,o,a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},s=null!==(e=a.datastore)&&void 0!==e?e:new Tc,l=null!==(r=a.blockstore)&&void 0!==r?r:new pd;o=function(e){if(null==e)return!1;return["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"].every((t=>"function"==typeof e[t]))}(a.libp2p)?a.libp2p:yield function(e){return YV.apply(this,arguments)}(t(t({},a),{},{libp2p:t(t({dns:a.dns},a.libp2p),{},{start:void 0}),datastore:s}));var u=new tO(t(t({},a),{},{libp2p:o,datastore:s,blockstore:l,blockBrokers:null!==(n=a.blockBrokers)&&void 0!==n?n:[LD(),aD()],routers:null!==(i=a.routers)&&void 0!==i?i:[eO(o),$R()],metrics:o.metrics}));return!1!==a.start&&(yield u.start()),u})),ZV.apply(this,arguments)}function $V(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return t=Number(t),null!=e[Symbol.asyncIterator]?l((function*(){var r=[];if(t<1&&(t=1),t!==Math.round(t))throw new Error("Batch size must be an integer");var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var c=a.value;for(r.push(c);r.length>=t;)yield r.slice(0,t),r=r.slice(t)}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}for(;r.length>0;)yield r.slice(0,t),r=r.slice(t)}))():function*(){var r=[];if(t<1&&(t=1),t!==Math.round(t))throw new Error("Batch size must be an integer");for(var n of e)for(r.push(n);r.length>=t;)yield r.slice(0,t),r=r.slice(t);for(;r.length>0;)yield r.slice(0,t),r=r.slice(t)}()}function XV(e){return eq.apply(this,arguments)}function eq(){return eq=l((function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return function*(){var n,i=!1,o=!1;try{for(var a,l=s($V(e,t));i=!(a=yield u(l.next())).done;i=!1)for(var c=a.value.map(function(){var e=r((function*(e){return e().then((e=>({ok:!0,value:e})),(e=>({ok:!1,err:e})))}));return function(t){return e.apply(this,arguments)}}()),d=0;d<c.length;d++){var h=yield u(c[d]);if(!h.ok)throw h.err;yield h.value}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}()})),eq.apply(this,arguments)}var tq,rq,nq,iq=function(){var e,t=null!==(e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).chunkSize)&&void 0!==e?e:262144;return function(){var e=l((function*(e){var r,n=new bs,i=0,o=!1,a=!1,l=!1;try{for(var c,d=s(e);a=!(c=yield u(d.next())).done;a=!1){var h=c.value;for(n.append(h),i+=h.length;i>=t;)if(yield n.slice(0,t),o=!0,t===n.length)n=new bs,i=0;else{var v=new bs;v.append(n.sublist(t)),n=v,i-=t}}}catch(e){l=!0,r=e}finally{try{a&&null!=d.return&&(yield u(d.return()))}finally{if(l)throw r}}(!o||i>0)&&(yield n.subarray(0,i))}));return function(t){return e.apply(this,arguments)}}()};class oq extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid type"),e(this,"name",oq.name),e(this,"code",oq.code)}}e(oq,"name","InvalidTypeError"),e(oq,"code","ERR_INVALID_TYPE"),function(e){var t,r,n;(t=e.DataType||(e.DataType={})).Raw="Raw",t.Directory="Directory",t.File="File",t.Metadata="Metadata",t.Symlink="Symlink",t.HAMTShard="HAMTShard",function(e){e[e.Raw=0]="Raw",e[e.Directory=1]="Directory",e[e.File=2]="File",e[e.Metadata=3]="Metadata",e[e.Symlink=4]="Symlink",e[e.HAMTShard=5]="HAMTShard"}(r||(r={})),function(e){e.codec=()=>Gl(r)}(e.DataType||(e.DataType={})),e.codec=()=>(null==n&&(n=Ql((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==n.lengthDelimited&&r.fork(),null!=t.Type&&(r.uint32(8),e.DataType.codec().encode(t.Type,r)),null!=t.Data&&(r.uint32(18),r.bytes(t.Data)),null!=t.filesize&&(r.uint32(24),r.uint64(t.filesize)),null!=t.blocksizes)for(var i of t.blocksizes)r.uint32(32),r.uint64(i);null!=t.hashType&&(r.uint32(40),r.uint64(t.hashType)),null!=t.fanout&&(r.uint32(48),r.uint64(t.fanout)),null!=t.mode&&(r.uint32(56),r.uint32(t.mode)),null!=t.mtime&&(r.uint32(66),rq.codec().encode(t.mtime,r)),!1!==n.lengthDelimited&&r.ldelim()}),((t,r)=>{for(var n={blocksizes:[]},i=null==r?t.len:t.pos+r;t.pos<i;){var o=t.uint32();switch(o>>>3){case 1:n.Type=e.DataType.codec().decode(t);break;case 2:n.Data=t.bytes();break;case 3:n.filesize=t.uint64();break;case 4:n.blocksizes.push(t.uint64());break;case 5:n.hashType=t.uint64();break;case 6:n.fanout=t.uint64();break;case 7:n.mode=t.uint32();break;case 8:n.mtime=rq.codec().decode(t,t.uint32());break;default:t.skipType(7&o)}}return n}))),n),e.encode=t=>Kl(t,e.codec()),e.decode=t=>kl(t,e.codec())}(tq||(tq={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.Seconds&&(t.uint32(8),t.int64(e.Seconds)),null!=e.FractionalNanoseconds&&(t.uint32(21),t.fixed32(e.FractionalNanoseconds)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{for(var r={},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.Seconds=e.int64();break;case 2:r.FractionalNanoseconds=e.fixed32();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=t=>kl(t,e.codec())}(rq||(rq={})),function(e){var t;e.codec=()=>(null==t&&(t=Ql((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.MimeType&&(t.uint32(10),t.string(e.MimeType)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{for(var r={},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();if(i>>>3==1)r.MimeType=e.string();else e.skipType(7&i)}return r}))),t),e.encode=t=>Kl(t,e.codec()),e.decode=t=>kl(t,e.codec())}(nq||(nq={}));var aq={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},sq=["directory","hamt-sharded-directory"],lq=parseInt("0644",8),uq=parseInt("0755",8);let cq=class t{static unmarshal(e){var r,n,i=tq.decode(e),o=new t({type:aq[null!=i.Type?i.Type.toString():"File"],data:i.Data,blockSizes:i.blocksizes,mode:i.mode,mtime:null!=i.mtime?{secs:null!==(r=i.mtime.Seconds)&&void 0!==r?r:0n,nsecs:i.mtime.FractionalNanoseconds}:void 0,fanout:i.fanout});return o._originalMode=null!==(n=i.mode)&&void 0!==n?n:0,o}constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{type:"file"};e(this,"type",void 0),e(this,"data",void 0),e(this,"blockSizes",void 0),e(this,"hashType",void 0),e(this,"fanout",void 0),e(this,"mtime",void 0),e(this,"_mode",void 0),e(this,"_originalMode",void 0);var{type:r,data:n,blockSizes:i,hashType:o,fanout:a,mtime:s,mode:l}=t;if(null!=r&&!Object.values(aq).includes(r))throw new oq("Type: "+r+" is not valid");this.type=null!=r?r:"file",this.data=n,this.hashType=o,this.fanout=a,this.blockSizes=null!=i?i:[],this._originalMode=0,this.mode=l,this.mtime=s}set mode(e){this._mode=null==e?this.isDirectory()?uq:lq:4095&e}get mode(){return this._mode}isDirectory(){return sq.includes(this.type)}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0n;var e=0n;return this.blockSizes.forEach((t=>{e+=t})),null!=this.data&&(e+=BigInt(this.data.length)),e}marshal(){var e;switch(this.type){case"raw":e=tq.DataType.Raw;break;case"directory":e=tq.DataType.Directory;break;case"file":e=tq.DataType.File;break;case"metadata":e=tq.DataType.Metadata;break;case"symlink":e=tq.DataType.Symlink;break;case"hamt-sharded-directory":e=tq.DataType.HAMTShard;break;default:throw new oq("Type: ".concat(e," is not valid"))}var t,r,n,i=this.data;(null!=this.data&&0!==this.data.length||(i=void 0),null!=this.mode)&&((t=4294963200&this._originalMode|(null!==(r=this.mode)&&void 0!==r?r:0))!==lq||this.isDirectory()||(t=void 0),t===uq&&this.isDirectory()&&(t=void 0));return null!=this.mtime&&(n={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),tq.encode({Type:e,Data:i,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:t,mtime:n})}};var dq=function(){var e=r((function*(e,t,r){null==r.codec&&(r.codec=zN);var n=yield $e.digest(e),i=it.create(r.cidVersion,r.codec.code,n);return yield t.put(i,e,r),i}));return function(t,r,n){return e.apply(this,arguments)}}();function hq(e){return function(){var t=l((function*(t,n){var i,o=0n,a=!1,l=!1;try{for(var c,d=function*(){var i=c.value;yield r((function*(){var r,a,s={codec:zN,cidVersion:e.cidVersion,onProgress:e.onProgress};e.rawLeaves?(s.codec=Ee,s.cidVersion=1):(a=new cq({type:e.leafType,data:i}),i=UN({Data:a.marshal(),Links:[]}));var l=yield dq(i,n,s);return o+=BigInt(i.byteLength),null===(r=e.onProgress)||void 0===r||r.call(e,new cv("unixfs:importer:progress:file:write",{bytesWritten:o,cid:l,path:t.path})),{cid:l,unixfs:a,size:BigInt(i.length),block:i}}))},h=s(t.content);a=!(c=yield u(h.next())).done;a=!1)yield*d()}catch(e){l=!0,i=e}finally{try{a&&null!=h.return&&(yield u(h.return()))}finally{if(l)throw i}}}));return function(e,r){return t.apply(this,arguments)}}()}let vq=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid parameters"),e(this,"name",t.name),e(this,"code",t.code)}};e(vq,"name","InvalidParametersError"),e(vq,"code","ERR_INVALID_PARAMS");class pq extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid avg chunk size"),e(this,"name",pq.name),e(this,"code",pq.code)}}e(pq,"name","InvalidAvgChunkSizeError"),e(pq,"code","ERR_INVALID_AVG_CHUNK_SIZE");class fq extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid chunk size"),e(this,"name",fq.name),e(this,"code",fq.code)}}e(fq,"name","InvalidChunkSizeError"),e(fq,"code","ERR_INVALID_CHUNK_SIZE");class gq extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid min chunk size"),e(this,"name",gq.name),e(this,"code",gq.code)}}e(gq,"name","InvalidMinChunkSizeError"),e(gq,"code","ERR_INVALID_MIN_CHUNK_SIZE");class yq extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid content"),e(this,"name",yq.name),e(this,"code",yq.code)}}e(yq,"name","InvalidContentError"),e(yq,"code","ERR_INVALID_CONTENT");var mq=function(){var e=r((function*(e,t,r){var n=new cq({type:"directory",mtime:e.mtime,mode:e.mode}),i=UN(ON({Data:n.marshal()}));return{cid:yield dq(i,t,r),path:e.path,unixfs:n,size:BigInt(i.length),originalPath:e.originalPath,block:i}}));return function(t,r,n){return e.apply(this,arguments)}}();function wq(){return wq=l((function*(e,r,n){var i,o,a=-1,l=!1,c=!1;try{for(var d,h=s(XV(n.bufferImporter(e,r),n.blockWriteConcurrency));l=!(d=yield u(h.next())).done;l=!1){var v=d.value;0!==++a?(1===a&&null!=i&&(yield t(t({},i),{},{block:void 0,single:void 0}),i=void 0),yield t(t({},v),{},{block:void 0})):i=t(t({},v),{},{single:!0})}}catch(e){c=!0,o=e}finally{try{l&&null!=h.return&&(yield u(h.return()))}finally{if(c)throw o}}null!=i&&(yield i)})),wq.apply(this,arguments)}function bq(e){return!0===e.single}var Sq=(e,n,i)=>{var o=function(){var o=r((function*(r){var o;if(1===r.length&&bq(r[0])&&i.reduceSingleLeafToSelf){var a,s=r[0],l=s.block;return!bq(s)||void 0===e.mtime&&void 0===e.mode||(s.unixfs=new cq({type:"file",mtime:e.mtime,mode:e.mode,data:s.block}),l={Data:s.unixfs.marshal(),Links:[]},s.block=UN(ON(l)),s.cid=yield dq(s.block,n,t(t({},i),{},{cidVersion:i.cidVersion})),s.size=BigInt(s.block.length)),null===(a=i.onProgress)||void 0===a||a.call(i,new cv("unixfs:importer:progress:file:layout",{cid:s.cid,path:s.originalPath})),{cid:s.cid,path:e.path,unixfs:s.unixfs,size:s.size,originalPath:s.originalPath}}var u=new cq({type:"file",mtime:e.mtime,mode:e.mode}),c=r.filter((e=>{var t;return e.cid.code===Se&&e.size>0||(null!=e.unixfs&&null==e.unixfs.data&&e.unixfs.fileSize()>0n||Boolean(null===(t=e.unixfs)||void 0===t||null===(t=t.data)||void 0===t?void 0:t.length))})).map((e=>{var t,r,n;if(e.cid.code===Se)return u.addBlockSize(e.size),{Name:"",Tsize:Number(e.size),Hash:e.cid};null==(null===(t=e.unixfs)||void 0===t?void 0:t.data)?u.addBlockSize(null!==(r=null===(n=e.unixfs)||void 0===n?void 0:n.fileSize())&&void 0!==r?r:0n):u.addBlockSize(BigInt(e.unixfs.data.length));return{Name:"",Tsize:Number(e.size),Hash:e.cid}})),d={Data:u.marshal(),Links:c},h=UN(ON(d)),v=yield dq(h,n,i);return null===(o=i.onProgress)||void 0===o||o.call(i,new cv("unixfs:importer:progress:file:layout",{cid:v,path:e.originalPath})),{cid:v,path:e.path,unixfs:u,size:BigInt(h.length+d.Links.reduce(((e,t)=>{var r;return e+(null!==(r=t.Tsize)&&void 0!==r?r:0)}),0)),originalPath:e.originalPath,block:h}}));return function(e){return o.apply(this,arguments)}}();return o},Eq=function(){var e=r((function*(e,t,r){return r.layout(function(e,t,r){return wq.apply(this,arguments)}(e,t,r),Sq(e,t,r))}));return function(t,r,n){return e.apply(this,arguments)}}();function kq(e){try{if(e instanceof Uint8Array)return l((function*(){yield e}))();if(t=e,Symbol.iterator in t)return l((function*(){yield*c(s(e),u)}))();if(function(e){return Symbol.asyncIterator in e}(e))return e}catch(e){throw new yq("Content was invalid")}var t;throw new yq("Content was invalid")}var xq=()=>function(){var e=l((function*(e){var t,r=!1,n=!1;try{for(var i,o=s(e);r=!(i=yield u(o.next())).done;r=!1){var a=i.value;if(void 0===a.length)throw new yq("Content was invalid");if("string"==typeof a||a instanceof String)yield xt(a.toString());else if(Array.isArray(a))yield Uint8Array.from(a);else{if(!(a instanceof Uint8Array))throw new yq("Content was invalid");yield a}}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw t}}}));return function(t){return e.apply(this,arguments)}}();function Aq(e){var t,n=null!==(t=null==e?void 0:e.maxChildrenPerNode)&&void 0!==t?t:174;return function(){var e=r((function*(e,r){var i,o=[],a=!1,l=!1;try{for(var u,c=s($V(e,n));a=!(u=yield c.next()).done;a=!1){var d=u.value;o.push(yield r(d))}}catch(e){l=!0,i=e}finally{try{a&&null!=c.return&&(yield c.return())}finally{if(l)throw i}}return o.length>1?t(o,r):o[0]}));function t(t,r){return e.apply(this,arguments)}return t}()}let Cq=class{constructor(t,r){e(this,"options",void 0),e(this,"root",void 0),e(this,"dir",void 0),e(this,"path",void 0),e(this,"dirty",void 0),e(this,"flat",void 0),e(this,"parent",void 0),e(this,"parentKey",void 0),e(this,"unixfs",void 0),e(this,"mode",void 0),e(this,"mtime",void 0),e(this,"cid",void 0),e(this,"size",void 0),e(this,"nodeSize",void 0),this.options=null!=r?r:{},this.root=t.root,this.dir=t.dir,this.path=t.path,this.dirty=t.dirty,this.flat=t.flat,this.parent=t.parent,this.parentKey=t.parentKey,this.unixfs=t.unixfs,this.mode=t.mode,this.mtime=t.mtime}};var Iq=it.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),Tq=it.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");class Pq extends Cq{constructor(t,r){super(t,r),e(this,"_children",void 0),this._children=new Map}put(e,t){var n=this;return r((function*(){n.cid=void 0,n.size=void 0,n.nodeSize=void 0,n._children.set(e,t)}))()}get(e){var t=this;return r((function*(){return Promise.resolve(t._children.get(e))}))()}childCount(){return this._children.size}directChildrenCount(){return this.childCount()}onlyChild(){return this._children.values().next().value}eachChildSeries(){var e=this;return l((function*(){for(var[t,r]of e._children.entries())yield{key:t,child:r}}))()}estimateNodeSize(){if(void 0!==this.nodeSize)return this.nodeSize;for(var[e,t]of(this.nodeSize=0,this._children.entries()))null!=t.size&&null!=t.cid&&(this.nodeSize+=e.length+(1===this.options.cidVersion?Tq.bytes.byteLength:Iq.bytes.byteLength));return this.nodeSize}flush(e){var t=this;return l((function*(){var r=[];for(var[n,i]of t._children.entries()){var o=i;if(i instanceof Cq){var a,l=!1,c=!1;try{for(var d,h=s(i.flush(e));l=!(d=yield u(h.next())).done;l=!1){var v=d.value;o=v,yield v}}catch(e){c=!0,a=e}finally{try{l&&null!=h.return&&(yield u(h.return()))}finally{if(c)throw a}}}null!=o.size&&null!=o.cid&&r.push({Name:n,Tsize:Number(o.size),Hash:o.cid})}var p=new cq({type:"directory",mtime:t.mtime,mode:t.mode}),f={Data:p.marshal(),Links:r},g=UN(ON(f)),y=yield u(dq(g,e,t.options)),m=g.length+f.Links.reduce(((e,t)=>{var r;return e+(null!==(r=t.Tsize)&&void 0!==r?r:0)}),0);t.cid=y,t.size=m,yield{cid:y,unixfs:p,path:t.path,size:BigInt(m)}}))()}}var _q,Bq,Nq,Dq={exports:{}};var Rq=Nq?Bq:(Nq=1,_q||(_q=1,function(e,t){!function(r,n){var i={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function o(e){if(!Array.isArray(e)&&!ArrayBuffer.isView(e))return!1;for(var t=0;t<e.length;t++)if(!Number.isInteger(e[t])||e[t]<0||e[t]>255)return!1;return!0}function a(e,t){return(65535&e)*t+(((e>>>16)*t&65535)<<16)}function s(e,t){return e<<t|e>>>32-t}function l(e){return e=a(e^=e>>>16,2246822507),(e=a(e^=e>>>13,3266489909))^e>>>16}function u(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]+t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]+t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]+t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]+t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function c(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]*t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]*t[3],r[1]+=r[2]>>>16,r[2]&=65535,r[2]+=e[3]*t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]*t[3],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[2]*t[2],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[3]*t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]*t[3]+e[1]*t[2]+e[2]*t[1]+e[3]*t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function d(e,t){return 32==(t%=64)?[e[1],e[0]]:t<32?[e[0]<<t|e[1]>>>32-t,e[1]<<t|e[0]>>>32-t]:(t-=32,[e[1]<<t|e[0]>>>32-t,e[0]<<t|e[1]>>>32-t])}function h(e,t){return 0==(t%=64)?e:t<32?[e[0]<<t|e[1]>>>32-t,e[1]<<t]:[e[1]<<t-32,0]}function v(e,t){return[e[0]^t[0],e[1]^t[1]]}function p(e){return e=v(e,[0,e[0]>>>1]),e=v(e=c(e,[4283543511,3981806797]),[0,e[0]>>>1]),v(e=c(e,[3301882366,444984403]),[0,e[0]>>>1])}i.x86.hash32=function(e,t){if(i.inputValidation&&!o(e))return n;t=t||0;for(var r=e.length%4,u=e.length-r,c=t,d=0,h=3432918353,v=461845907,p=0;p<u;p+=4)d=a(d=e[p]|e[p+1]<<8|e[p+2]<<16|e[p+3]<<24,h),d=a(d=s(d,15),v),c=a(c=s(c^=d,13),5)+3864292196;switch(d=0,r){case 3:d^=e[p+2]<<16;case 2:d^=e[p+1]<<8;case 1:d=a(d^=e[p],h),c^=d=a(d=s(d,15),v)}return(c=l(c^=e.length))>>>0},i.x86.hash128=function(e,t){if(i.inputValidation&&!o(e))return n;t=t||0;for(var r=e.length%16,u=e.length-r,c=t,d=t,h=t,v=t,p=0,f=0,g=0,y=0,m=597399067,w=2869860233,b=951274213,S=2716044179,E=0;E<u;E+=16)p=e[E]|e[E+1]<<8|e[E+2]<<16|e[E+3]<<24,f=e[E+4]|e[E+5]<<8|e[E+6]<<16|e[E+7]<<24,g=e[E+8]|e[E+9]<<8|e[E+10]<<16|e[E+11]<<24,y=e[E+12]|e[E+13]<<8|e[E+14]<<16|e[E+15]<<24,p=s(p=a(p,m),15),c=s(c^=p=a(p,w),19),c=a(c+=d,5)+1444728091,f=s(f=a(f,w),16),d=s(d^=f=a(f,b),17),d=a(d+=h,5)+197830471,g=s(g=a(g,b),17),h=s(h^=g=a(g,S),15),h=a(h+=v,5)+2530024501,y=s(y=a(y,S),18),v=s(v^=y=a(y,m),13),v=a(v+=c,5)+850148119;switch(p=0,f=0,g=0,y=0,r){case 15:y^=e[E+14]<<16;case 14:y^=e[E+13]<<8;case 13:y=a(y^=e[E+12],S),v^=y=a(y=s(y,18),m);case 12:g^=e[E+11]<<24;case 11:g^=e[E+10]<<16;case 10:g^=e[E+9]<<8;case 9:g=a(g^=e[E+8],b),h^=g=a(g=s(g,17),S);case 8:f^=e[E+7]<<24;case 7:f^=e[E+6]<<16;case 6:f^=e[E+5]<<8;case 5:f=a(f^=e[E+4],w),d^=f=a(f=s(f,16),b);case 4:p^=e[E+3]<<24;case 3:p^=e[E+2]<<16;case 2:p^=e[E+1]<<8;case 1:p=a(p^=e[E],m),c^=p=a(p=s(p,15),w)}return c^=e.length,c+=d^=e.length,c+=h^=e.length,d+=c+=v^=e.length,h+=c,v+=c,c=l(c),c+=d=l(d),c+=h=l(h),d+=c+=v=l(v),h+=c,v+=c,("00000000"+(c>>>0).toString(16)).slice(-8)+("00000000"+(d>>>0).toString(16)).slice(-8)+("00000000"+(h>>>0).toString(16)).slice(-8)+("00000000"+(v>>>0).toString(16)).slice(-8)},i.x64.hash128=function(e,t){if(i.inputValidation&&!o(e))return n;t=t||0;for(var r=e.length%16,a=e.length-r,s=[0,t],l=[0,t],f=[0,0],g=[0,0],y=[2277735313,289559509],m=[1291169091,658871167],w=0;w<a;w+=16)f=[e[w+4]|e[w+5]<<8|e[w+6]<<16|e[w+7]<<24,e[w]|e[w+1]<<8|e[w+2]<<16|e[w+3]<<24],g=[e[w+12]|e[w+13]<<8|e[w+14]<<16|e[w+15]<<24,e[w+8]|e[w+9]<<8|e[w+10]<<16|e[w+11]<<24],f=d(f=c(f,y),31),s=u(s=d(s=v(s,f=c(f,m)),27),l),s=u(c(s,[0,5]),[0,1390208809]),g=d(g=c(g,m),33),l=u(l=d(l=v(l,g=c(g,y)),31),s),l=u(c(l,[0,5]),[0,944331445]);switch(f=[0,0],g=[0,0],r){case 15:g=v(g,h([0,e[w+14]],48));case 14:g=v(g,h([0,e[w+13]],40));case 13:g=v(g,h([0,e[w+12]],32));case 12:g=v(g,h([0,e[w+11]],24));case 11:g=v(g,h([0,e[w+10]],16));case 10:g=v(g,h([0,e[w+9]],8));case 9:g=c(g=v(g,[0,e[w+8]]),m),l=v(l,g=c(g=d(g,33),y));case 8:f=v(f,h([0,e[w+7]],56));case 7:f=v(f,h([0,e[w+6]],48));case 6:f=v(f,h([0,e[w+5]],40));case 5:f=v(f,h([0,e[w+4]],32));case 4:f=v(f,h([0,e[w+3]],24));case 3:f=v(f,h([0,e[w+2]],16));case 2:f=v(f,h([0,e[w+1]],8));case 1:f=c(f=v(f,[0,e[w]]),y),s=v(s,f=c(f=d(f,31),m))}return s=u(s=v(s,[0,e.length]),l=v(l,[0,e.length])),l=u(l,s),s=u(s=p(s),l=p(l)),l=u(l,s),("00000000"+(s[0]>>>0).toString(16)).slice(-8)+("00000000"+(s[1]>>>0).toString(16)).slice(-8)+("00000000"+(l[0]>>>0).toString(16)).slice(-8)+("00000000"+(l[1]>>>0).toString(16)).slice(-8)},e.exports&&(t=e.exports=i),t.murmurHash3=i}()}(Dq,Dq.exports)),Bq=Dq.exports),Oq=a(Rq);Ye({name:"murmur3-32",code:35,encode:e=>function(e){for(var t=new Array(4),r=0;r<4;r++)t[r]=255&e,e>>=8;return new Uint8Array(t)}(Oq.x86.hash32(e))});var Lq,Mq,Uq=Ye({name:"murmur3-128",code:34,encode:e=>S(Oq.x64.hash128(e))});Ye({name:"murmur3-x64-64",code:34,encode:e=>S(Oq.x64.hash128(e)).subarray(0,8)});var Fq=function(){if(Mq)return Lq;function e(e,r){return e+t(r)}function t(e){var t=e;return 16843009*((t=(858993459&(t-=t>>1&1431655765))+(t>>2&858993459))+(t>>4)&252645135)>>24}function r(e,t){return e[0]-t[0]}function n(e){return e[1]}return Mq=1,Lq=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(e,t){var r=this._internalPositionFor(e,!1);if(void 0===t)-1!==r&&(this._unsetInternalPos(r),this._unsetBit(e),this._changedLength=!0,this._changedData=!0);else{var n=!1;-1===r?(r=this._data.length,this._setBit(e),this._changedData=!0):n=!0,this._setInternalPos(r,e,t,n),this._changedLength=!0}}unset(e){this.set(e,void 0)}get(e){this._sortData();var t=this._internalPositionFor(e,!0);if(-1!==t)return this._data[t][1]}push(e){return this.set(this.length,e),this.length}get length(){if(this._sortData(),this._changedLength){var e=this._data[this._data.length-1];this._length=e?e[0]+1:0,this._changedLength=!1}return this._length}forEach(e){for(var t=0;t<this.length;)e(this.get(t),t,this),t++}map(e){for(var t=0,r=new Array(this.length);t<this.length;)r[t]=e(this.get(t),t,this),t++;return r}reduce(e,t){for(var r=0,n=t;r<this.length;){n=e(n,this.get(r),r),r++}return n}find(e){for(var t,r,n=0;n<this.length&&!t;)t=e(r=this.get(n)),n++;return t?r:void 0}_internalPositionFor(r,n){var i=this._bytePosFor(r,n);if(i>=this._bitArrays.length)return-1;var o=this._bitArrays[i],a=r-7*i;return(o&1<<a)>0?this._bitArrays.slice(0,i).reduce(e,0)+t(o&~(4294967295<<a+1))-1:-1}_bytePosFor(e,t){for(var r=Math.floor(e/7),n=r+1;!t&&this._bitArrays.length<n;)this._bitArrays.push(0);return r}_setBit(e){var t=this._bytePosFor(e,!1);this._bitArrays[t]|=1<<e-7*t}_unsetBit(e){var t=this._bytePosFor(e,!1);this._bitArrays[t]&=~(1<<e-7*t)}_setInternalPos(e,t,r,n){var i=this._data,o=[t,r];if(n)this._sortData(),i[e]=o;else{if(i.length)if(i[i.length-1][0]>=t)i.push(o);else if(i[0][0]<=t)i.unshift(o);else{var a=Math.round(i.length/2);this._data=i.slice(0,a).concat(o).concat(i.slice(a))}else this._data.push(o);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(r),this._changedData=!1}bitField(){for(var e,t=[],r=8,n=0,i=0,o=this._bitArrays.slice();o.length||n;){0===n&&(e=o.shift(),n=7);var a=Math.min(n,r);i|=(e&~(255<<a))<<8-r,e>>>=a,n-=a,(r-=a)&&(n||o.length)||(t.push(i),i=0,r=8)}for(var s=t.length-1;s>0;s--){if(0!==t[s])break;t.pop()}return t}compactArray(){return this._sortData(),this._data.map(n)}},Lq}(),zq=a(Fq);class jq{constructor(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;e(this,"_options",void 0),e(this,"_popCount",void 0),e(this,"_parent",void 0),e(this,"_posAtParent",void 0),e(this,"_children",void 0),e(this,"key",void 0),this._options=t,this._popCount=0,this._parent=r,this._posAtParent=n,this._children=new zq,this.key=null}put(e,t){var n=this;return r((function*(){var r=yield n._findNewBucketAndPos(e);r.bucket._putAt(r,e,t)}))()}get(e){var t=this;return r((function*(){var r=yield t._findChild(e);if(null!=r)return r.value}))()}del(e){var t=this;return r((function*(){var r=yield t._findPlace(e),n=r.bucket._at(r.pos);null!=n&&n.key===e&&r.bucket._delAt(r.pos)}))()}leafCount(){return this._children.compactArray().reduce(((e,t)=>t instanceof jq?e+t.leafCount():e+1),0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){var e=this._children.compactArray();for(var t of e)t instanceof jq?yield*t.eachLeafSeries():yield t}serialize(e,t){return t(this._children.reduce(((r,n,i)=>(null!=n&&(n instanceof jq?r.push(n.serialize(e,t)):r.push(e(n,i))),r)),[]))}asyncTransform(e,t){var n=this;return r((function*(){return Kq(n,e,t)}))()}toJSON(){return this.serialize(qq,Hq)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}_findChild(e){var t=this;return r((function*(){var r=yield t._findPlace(e),n=r.bucket._at(r.pos);if(!(n instanceof jq))return null!=n&&n.key===e?n:void 0}))()}_findPlace(e){var t=this;return r((function*(){var r=t._options.hash("string"==typeof e?xt(e):e),n=yield r.take(t._options.bits),i=t._children.get(n);return i instanceof jq?i._findPlace(r):{bucket:t,pos:n,hash:r,existingChild:i}}))()}_findNewBucketAndPos(e){var t=this;return r((function*(){var r=yield t._findPlace(e);if(null!=r.existingChild&&r.existingChild.key!==e){var n=new jq(t._options,r.bucket,r.pos);r.bucket._putObjectAt(r.pos,n);var i=yield n._findPlace(r.existingChild.hash);return i.bucket._putAt(i,r.existingChild.key,r.existingChild.value),n._findNewBucketAndPos(r.hash)}return r}))()}_putAt(e,t,r){this._putObjectAt(e.pos,{key:t,value:r,hash:e.hash})}_putObjectAt(e,t){null==this._children.get(e)&&this._popCount++,this._children.set(e,t)}_delAt(e){if(-1===e)throw new Error("Invalid position");null!=this._children.get(e)&&this._popCount--,this._children.unset(e),this._level()}_level(){if(null!=this._parent&&this._popCount<=1)if(1===this._popCount){var e=this._children.find(Vq);if(null!=e&&!(e instanceof jq)){var t=e.hash;t.untake(this._options.bits);var r={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(r,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}}function Vq(e){return Boolean(e)}function qq(e,t){return e.key}function Hq(e){return e}function Kq(e,t,r){return Wq.apply(this,arguments)}function Wq(){return(Wq=r((function*(e,t,r){var n=[];for(var i of e._children.compactArray())if(i instanceof jq)yield Kq(i,t,r);else{var o=yield t(i);n.push({bitField:e._children.bitField(),children:o})}return r(n)}))).apply(this,arguments)}var Gq=[255,254,252,248,240,224,192,128],Qq=[1,3,7,15,31,63,127,255];let Yq=class{constructor(t){e(this,"_value",void 0),e(this,"_currentBytePos",void 0),e(this,"_currentBitPos",void 0),this._value=t,this._currentBytePos=t.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+8*this._currentBytePos}totalBits(){return 8*this._value.length}take(e){for(var t=e,r=0;t>0&&this._haveBits();){var n=this._value[this._currentBytePos],i=this._currentBitPos+1,o=Math.min(i,t);r=(r<<o)+Jq(n,i-o,o),t-=o,this._currentBitPos-=o,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return r}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function Jq(e,t,r){var n=function(e,t){return Gq[e]&Qq[Math.min(t+e-1,7)]}(t,r);return(e&n)>>>t}function Zq(e){return function(t){return t instanceof $q?t:new $q(t,e)}}let $q=class{constructor(t,r){if(e(this,"_value",void 0),e(this,"_hashFn",void 0),e(this,"_depth",void 0),e(this,"_availableBits",void 0),e(this,"_currentBufferIndex",void 0),e(this,"_buffers",void 0),!(t instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=t,this._hashFn=r,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}take(e){var t=this;return r((function*(){for(var r=e;t._availableBits<r;)yield t._produceMoreBits();for(var n=0;r>0;){var i=t._buffers[t._currentBufferIndex],o=Math.min(i.availableBits(),r);n=(n<<o)+i.take(o),r-=o,t._availableBits-=o,0===i.availableBits()&&t._currentBufferIndex++}return n}))()}untake(e){for(var t=e;t>0;){var r=this._buffers[this._currentBufferIndex],n=Math.min(r.totalBits()-r.availableBits(),t);r.untake(n),t-=n,this._availableBits+=n,this._currentBufferIndex>0&&r.totalBits()===r.availableBits()&&(this._depth--,this._currentBufferIndex--)}}_produceMoreBits(){var e=this;return r((function*(){e._depth++;var t=e._depth>0?zt([e._value,Uint8Array.from([e._depth])]):e._value,r=yield e._hashFn(t),n=new Yq(r);e._buffers.push(n),e._availableBits+=n.availableBits()}))()}};function Xq(e){var t;if(null==e||null==e.hashFn)throw new Error("please define an options.hashFn");var r={bits:null!==(t=e.bits)&&void 0!==t?t:8,hash:Zq(e.hashFn)};return new jq(r)}function eH(e){return tH.apply(this,arguments)}function tH(){return tH=r((function*(e){return(yield Uq.encode(e)).slice(0,8).reverse()})),tH.apply(this,arguments)}var rH=BigInt(34);let nH=class extends Cq{constructor(t,r){var n;super(t,r),e(this,"_bucket",void 0),this._bucket=Xq({hashFn:eH,bits:null!==(n=r.shardFanoutBits)&&void 0!==n?n:8})}put(e,t){var n=this;return r((function*(){n.cid=void 0,n.size=void 0,n.nodeSize=void 0,yield n._bucket.put(e,t)}))()}get(e){var t=this;return r((function*(){return t._bucket.get(e)}))()}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}eachChildSeries(){var e=this;return l((function*(){var t,r=!1,n=!1;try{for(var i,o=s(e._bucket.eachLeafSeries());r=!(i=yield u(o.next())).done;r=!1){var{key:a,value:l}=i.value;yield{key:a,child:l}}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw t}}}))()}estimateNodeSize(){return void 0!==this.nodeSize||(this.nodeSize=aH(this._bucket,this,this.options)),this.nodeSize}flush(e){var r=this;return l((function*(){var n,i=!1,o=!1;try{for(var a,l=s(iH(r._bucket,e,r,r.options));i=!(a=yield u(l.next())).done;i=!1){var c=a.value;yield t(t({},c),{},{path:r.path})}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}))()}};function iH(e,t,r,n){return oH.apply(this,arguments)}function oH(){return oH=l((function*(e,t,r,n){for(var i=e._children,o=(e.tableSize()-1).toString(16).length,a=[],l=0n,c=0;c<i.length;c++){var d=i.get(c);if(null!=d){var h=c.toString(16).toUpperCase().padStart(o,"0");if(d instanceof jq){var v,p=void 0,f=!1,g=!1;try{for(var y,m=s(iH(d,t,null,n));f=!(y=yield u(m.next())).done;f=!1){p=y.value}}catch(e){g=!0,v=e}finally{try{f&&null!=m.return&&(yield u(m.return()))}finally{if(g)throw v}}if(null==p)throw new Error("Could not flush sharded directory, no subshard found");a.push({Name:h,Tsize:Number(p.size),Hash:p.cid}),l+=p.size}else if("function"==typeof d.value.flush){var w,b=d.value,S=void 0,E=!1,k=!1;try{for(var x,A=s(b.flush(t));E=!(x=yield u(A.next())).done;E=!1){S=x.value,yield S}}catch(e){k=!0,w=e}finally{try{E&&null!=A.return&&(yield u(A.return()))}finally{if(k)throw w}}if(null==S)throw new Error("Did not flush dir");var C=h+d.key;a.push({Name:C,Tsize:Number(S.size),Hash:S.cid}),l+=S.size}else{var I=d.value;if(null==I.cid)continue;var T=h+d.key,P=I.size;a.push({Name:T,Tsize:Number(P),Hash:I.cid}),l+=BigInt(null!=P?P:0)}}}var _=Uint8Array.from(i.bitField().reverse()),B=new cq({type:"hamt-sharded-directory",data:_,fanout:BigInt(e.tableSize()),hashType:rH,mtime:null==r?void 0:r.mtime,mode:null==r?void 0:r.mode}),N=UN(ON({Data:B.marshal(),Links:a})),D=yield u(dq(N,t,n)),R=BigInt(N.byteLength)+l;yield{cid:D,unixfs:B,size:R}})),oH.apply(this,arguments)}function aH(e,t,r){for(var n=e._children,i=(e.tableSize()-1).toString(16).length,o=[],a=0;a<n.length;a++){var s=n.get(a);if(null!=s){var l=a.toString(16).toUpperCase().padStart(i,"0");if(s instanceof jq){var u=aH(s,null,r);o.push({Name:l,Tsize:Number(u),Hash:0===r.cidVersion?Iq:Tq})}else if("function"==typeof s.value.flush){var c=s.value.nodeSize();o.push({Name:l+s.key,Tsize:Number(c),Hash:0===r.cidVersion?Iq:Tq})}else{var d=s.value;if(null==d.cid)continue;var h=l+s.key,v=d.size;o.push({Name:h,Tsize:Number(v),Hash:d.cid})}}}var p=Uint8Array.from(n.bitField().reverse());return UN(ON({Data:new cq({type:"hamt-sharded-directory",data:p,fanout:BigInt(e.tableSize()),hashType:rH,mtime:null==t?void 0:t.mtime,mode:null==t?void 0:t.mode}).marshal(),Links:o})).length}function sH(e,t,r,n){return lH.apply(this,arguments)}function lH(){return lH=r((function*(e,t,r,n){var i=t;t instanceof Pq&&t.estimateNodeSize()>r&&(i=yield function(e,t){return uH.apply(this,arguments)}(t,n));var o=i.parent;if(null!=o){if(i!==t){if(null!=e&&(e.parent=i),null==i.parentKey)throw new Error("No parent key found");yield o.put(i.parentKey,i)}return sH(i,o,r,n)}return i})),lH.apply(this,arguments)}function uH(){return uH=r((function*(e,t){var r,n=new nH({root:e.root,dir:!0,parent:e.parent,parentKey:e.parentKey,path:e.path,dirty:e.dirty,flat:!1,mtime:e.mtime,mode:e.mode},t),i=!1,o=!1;try{for(var a,l=s(e.eachChildSeries());i=!(a=yield l.next()).done;i=!1){var{key:u,child:c}=a.value;yield n.put(u,c)}}catch(e){o=!0,r=e}finally{try{i&&null!=l.return&&(yield l.return())}finally{if(o)throw r}}return n})),uH.apply(this,arguments)}function cH(e,t,r){return dH.apply(this,arguments)}function dH(){return dH=r((function*(e,t,r){for(var n,i=function(){return(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").split(/(?<!\\)\//).filter(Boolean)}(null!==(n=e.path)&&void 0!==n?n:""),o=i.length-1,a=t,s="",l=0;l<i.length;l++){var u=i[l];s+="".concat(""!==s?"/":"").concat(u);var c=l===o;if(a.dirty=!0,a.cid=void 0,a.size=void 0,c)yield a.put(u,e),t=yield sH(null,a,r.shardSplitThresholdBytes,r);else{var d,h,v=yield a.get(u);if(null==v||!(v instanceof Cq))v=new Pq({root:!1,dir:!0,parent:a,parentKey:u,path:s,dirty:!0,flat:!0,mtime:null===(d=v)||void 0===d||null===(d=d.unixfs)||void 0===d?void 0:d.mtime,mode:null===(h=v)||void 0===h||null===(h=h.unixfs)||void 0===h?void 0:h.mode},r);yield a.put(u,v),a=v}}return t})),dH.apply(this,arguments)}function hH(e,t){return vH.apply(this,arguments)}function vH(){return vH=l((function*(e,t){var r;e instanceof Cq?yield*c(s(e.flush(t))):!0===(null===(r=e.unixfs)||void 0===r?void 0:r.isDirectory())&&(yield e)})),vH.apply(this,arguments)}function pH(e,t){return fH.apply(this,arguments)}function fH(){return fH=l((function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(i,o,a,d,h,v,p,f,g,y,m,w,b,S,E){var k;k=Symbol.asyncIterator in e||Symbol.iterator in e?e:[e];var x,A=null!==(i=n.wrapWithDirectory)&&void 0!==i&&i,C=null!==(o=n.shardSplitThresholdBytes)&&void 0!==o?o:262144,I=null!==(a=n.shardFanoutBits)&&void 0!==a?a:8,T=null!==(d=n.cidVersion)&&void 0!==d?d:1,P=null===(h=n.rawLeaves)||void 0===h||h,_=null!==(v=n.leafType)&&void 0!==v?v:"file",B=null!==(p=n.fileImportConcurrency)&&void 0!==p?p:50,N=null!==(f=n.blockWriteConcurrency)&&void 0!==f?f:10,D=null===(g=n.reduceSingleLeafToSelf)||void 0===g||g,R=null!==(y=n.chunker)&&void 0!==y?y:iq(),O=null!==(m=n.chunkValidator)&&void 0!==m?m:xq(),L=null!==(w=n.dagBuilder)&&void 0!==w?w:function(e){return function(){var t=l((function*(t,n){var i,o=!1,a=!1;try{for(var c,d=function*(){var t,i=c.value;if(null!=i.path&&(t=i.path,i.path=i.path.split("/").filter((e=>null!=e&&"."!==e)).join("/")),function(e){return null!=e.content}(i)){var o={path:i.path,mtime:i.mtime,mode:i.mode,content:l((function*(){var t,r=0n,n=!1,o=!1;try{for(var a,l=s(e.chunker(e.chunkValidator(kq(i.content))));n=!(a=yield u(l.next())).done;n=!1){var c,d=a.value,h=BigInt(d.byteLength);r+=h,null===(c=e.onProgress)||void 0===c||c.call(e,new cv("unixfs:importer:progress:file:read",{bytesRead:r,chunkSize:h,path:i.path})),yield d}}catch(e){o=!0,t=e}finally{try{n&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw t}}}))(),originalPath:t};yield r((function*(){return Eq(o,n,e)}))}else{if(null==i.path)throw new Error("Import candidate must have content or path or both");var a={path:i.path,mtime:i.mtime,mode:i.mode,originalPath:t};yield r((function*(){return mq(a,n,e)}))}},h=s(t);o=!(c=yield u(h.next())).done;o=!1)yield*d()}catch(e){a=!0,i=e}finally{try{o&&null!=h.return&&(yield u(h.return()))}finally{if(a)throw i}}}));return function(e,r){return t.apply(this,arguments)}}()}({chunker:R,chunkValidator:O,wrapWithDirectory:A,layout:null!==(b=n.layout)&&void 0!==b?b:Aq(),bufferImporter:null!==(S=n.bufferImporter)&&void 0!==S?S:hq({cidVersion:T,rawLeaves:P,leafType:_,onProgress:n.onProgress}),blockWriteConcurrency:N,reduceSingleLeafToSelf:D,cidVersion:T,onProgress:n.onProgress}),M=null!==(E=n.treeBuilder)&&void 0!==E?E:function(e){return function(){var t=l((function*(t,r){var n,i,o=new Pq({root:!0,dir:!0,path:"",dirty:!0,flat:!0},e),a=!1,l=!1,d=!1;try{for(var h,v=s(t);l=!(h=yield u(v.next())).done;l=!1){var p,f,g=h.value;if(null!=g){var y="".concat(null!==(p=g.originalPath)&&void 0!==p?p:"").split("/")[0];null!=y&&""!==y&&(null==n?(n=y,a=!0):n!==y&&(a=!1)),o=yield u(cH(g,o,e)),!0!==(null===(f=g.unixfs)||void 0===f?void 0:f.isDirectory())&&(yield g)}}}catch(e){d=!0,i=e}finally{try{l&&null!=v.return&&(yield u(v.return()))}finally{if(d)throw i}}if(e.wrapWithDirectory||a&&o.childCount()>1)yield*c(s(hH(o,r)));else{var m,w=!1,b=!1;try{for(var S,E=s(o.eachChildSeries());w=!(S=yield u(E.next())).done;w=!1){var k=S.value;null!=k&&(yield*c(s(hH(k.child,r)),u))}}catch(e){b=!0,m=e}finally{try{w&&null!=E.return&&(yield u(E.return()))}finally{if(b)throw m}}}}));return function(e,r){return t.apply(this,arguments)}}()}({wrapWithDirectory:A,shardSplitThresholdBytes:C,shardFanoutBits:I,cidVersion:T,onProgress:n.onProgress}),U=!1,F=!1;try{for(var z,j=s(M(XV(L(k,t),B),t));U=!(z=yield u(j.next())).done;U=!1){var V=z.value;yield{cid:V.cid,path:V.path,unixfs:V.unixfs,size:V.size}}}catch(e){F=!0,x=e}finally{try{U&&null!=j.return&&(yield u(j.return()))}finally{if(F)throw x}}}()})),fH.apply(this,arguments)}function gH(e,t){return yH.apply(this,arguments)}function yH(){return yH=r((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=yield gR(pH([e],t,r));if(null==n)throw new vq("Nothing imported");return n})),yH.apply(this,arguments)}function mH(){return mH=r((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=yield gR(pH([e],t,r));if(null==n)throw new vq("Nothing imported");return n})),mH.apply(this,arguments)}function wH(){return wH=r((function*(e,t){return gH({content:e},t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})})),wH.apply(this,arguments)}function bH(){return bH=r((function*(e,t){return gH({content:e},t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})})),bH.apply(this,arguments)}var SH={cidVersion:1,rawLeaves:!0,layout:Aq({maxChildrenPerNode:1024}),chunker:iq({chunkSize:1048576})};function EH(){return EH=l((function(e,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){yield*c(s(pH(e,r,t(t({},SH),n))))}()})),EH.apply(this,arguments)}function kH(){return kH=r((function*(e,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{cid:i}=yield function(e,t){return wH.apply(this,arguments)}(e,r,t(t({},SH),n));return i})),kH.apply(this,arguments)}function xH(){return xH=r((function*(e,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{cid:i}=yield function(e,t){return bH.apply(this,arguments)}(e,r,t(t({},SH),n));return i})),xH.apply(this,arguments)}function AH(){return AH=r((function*(e,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{cid:i}=yield gH(e,r,t(t({},SH),n));return i})),AH.apply(this,arguments)}function CH(){return CH=r((function*(e,r){var n,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{cid:o}=yield function(e,t){return mH.apply(this,arguments)}(t(t({},e),{},{path:null!==(n=e.path)&&void 0!==n?n:"-"}),r,t(t({},SH),i));return o})),CH.apply(this,arguments)}function IH(e){if(null!=e[Symbol.asyncIterator])return r((function*(){var t,r,n=!1,i=!1;try{for(var o,a=s(e);n=!(o=yield a.next()).done;n=!1){t=o.value}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield a.return())}finally{if(i)throw r}}return t}))();var t;for(var n of e)t=n;return t}class TH extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Bad path"),e(this,"name",TH.name),e(this,"code",TH.code)}}e(TH,"name","BadPathError"),e(TH,"code","ERR_BAD_PATH");class PH extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not found"),e(this,"name",PH.name),e(this,"code",PH.code)}}e(PH,"name","NotFoundError"),e(PH,"code","ERR_NOT_FOUND");class _H extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No resolver"),e(this,"name",_H.name),e(this,"code",_H.code)}}e(_H,"name","NoResolverError"),e(_H,"code","ERR_NO_RESOLVER");let BH=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not UnixFS"),e(this,"name",t.name),e(this,"code",t.code)}};e(BH,"name","NotUnixFSError"),e(BH,"code","ERR_NOT_UNIXFS");class NH extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Over read"),e(this,"name",NH.name),e(this,"code",NH.code)}}e(NH,"name","OverReadError"),e(NH,"code","ERR_OVER_READ");class DH extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Under read"),e(this,"name",DH.name),e(this,"code",DH.code)}}e(DH,"name","UnderReadError"),e(DH,"code","ERR_UNDER_READ");class RH extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No Property found"),e(this,"name",RH.name),e(this,"code",RH.code)}}e(RH,"name","NoPropError"),e(RH,"code","ERR_NO_PROP");let OH=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid parameters"),e(this,"name",t.name),e(this,"code",t.code)}};function LH(e,t,r,n,i,o,a){for(var s,u=e,c=i;o.length>0;){var d=o[0];if(!(d in u))throw new RH("No property named ".concat(d," found in node ").concat(r));o.shift(),c="".concat(c,"/").concat(d);var h=it.asCID(u[d]);if(null!=h)return{entry:{type:"object",name:n,path:i,cid:r,node:t,depth:a,size:BigInt(t.length),content:function(){var t=l((function*(){yield e}));return function(){return t.apply(this,arguments)}}()},next:{cid:h,name:d,path:c,toResolve:o}};u=u[d]}return{entry:{type:"object",name:n,path:i,cid:r,node:t,depth:a,size:BigInt(t.length),content:(s=l((function*(){yield e})),function(){return s.apply(this,arguments)})}}}e(OH,"name","InvalidParametersError"),e(OH,"code","ERR_INVALID_PARAMS");var MH=function(){var e=r((function*(e,t,r,n,i,o,a,s){var l=yield a.get(e,s);return LH($B(l),l,e,t,r,n,o)}));return function(t,r,n,i,o,a,s,l){return e.apply(this,arguments)}}(),UH=function(){var e=r((function*(e,t,r,n,i,o,a,s){var l=yield a.get(e,s);return LH(cN(l),l,e,t,r,n,o)}));return function(t,r,n,i,o,a,s,l){return e.apply(this,arguments)}}();function FH(e,t,r,n){var i=BigInt(e.length),o=BigInt(t+i);return r>=o||n<t?new Uint8Array(0):(n>=t&&n<o&&(e=e.subarray(0,Number(n-t))),r>=t&&r<o&&(e=e.subarray(Number(r-t))),e)}var zH=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e,n=BigInt(e),i=BigInt(null!=t?t:0),o=BigInt(r);if(o!==n&&(o=i+o),o>n&&(o=n),i<0n)throw new OH("Offset must be greater than or equal to 0");if(i>n)throw new OH("Offset must be less than the file size");if(o<0n)throw new OH("Length must be greater than or equal to 0");if(o>n)throw new OH("Length must be less than the file size");return{start:i,end:o}},jH=e=>{function t(){return t=l((function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(r){var{start:n,end:i}=zH(e.length,t.offset,t.length),o=FH(e,0n,n,i);null===(r=t.onProgress)||void 0===r||r.call(t,new cv("unixfs:exporter:progress:identity",{bytesRead:BigInt(o.byteLength),totalBytes:i-n,fileSize:BigInt(e.byteLength)})),yield o}()})),t.apply(this,arguments)}return function(){return t.apply(this,arguments)}},VH=function(){var e=r((function*(e,t,r,n,i,o,a,s){if(n.length>0)throw new PH("No link named ".concat(r," found in raw node ").concat(e));var l=He(e.multihash.bytes);return{entry:{type:"identity",name:t,path:r,cid:e,content:jH(l.digest),depth:o,size:BigInt(l.digest.length),node:l.digest}}}));return function(t,r,n,i,o,a,s,l){return e.apply(this,arguments)}}(),qH=function(){var e=r((function*(e,t,r,n,i,o,a,s){var l=yield a.get(e,s);return LH(we(l),l,e,t,r,n,o)}));return function(t,r,n,i,o,a,s,l){return e.apply(this,arguments)}}(),HH=e=>{function t(){return t=l((function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(r){var{start:n,end:i}=zH(e.length,t.offset,t.length),o=FH(e,0n,n,i);null===(r=t.onProgress)||void 0===r||r.call(t,new cv("unixfs:exporter:progress:raw",{bytesRead:BigInt(o.byteLength),totalBytes:i-n,fileSize:BigInt(e.byteLength)})),yield o}()})),t.apply(this,arguments)}return function(){return t.apply(this,arguments)}},KH=function(){var e=r((function*(e,t,r,n,i,o,a,s){if(n.length>0)throw new PH("No link named ".concat(r," found in raw node ").concat(e));var l=yield a.get(e,s);return{entry:{type:"raw",name:t,path:r,cid:e,content:HH(l),depth:o,size:BigInt(l.length),node:l}}}));return function(t,r,n,i,o,a,s,l){return e.apply(this,arguments)}}(),WH=function(){var e=r((function*(e){return(yield Uq.encode(e)).slice(0,8).reverse()}));return function(t){return e.apply(this,arguments)}}(),GH=function(){var e=r((function*(e,t,n){var i=(t.tableSize()-1).toString(16).length;yield Promise.all(e.map(function(){var e=r((function*(e){if(null==e.Name)throw new Error("Unexpected Link without a Name");if(e.Name.length!==i)yield n.put(e.Name.substring(2),!0);else{var r=parseInt(e.Name,16);t._putObjectAt(r,new jq({hash:n._options.hash,bits:n._options.bits},t,r))}}));return function(t){return e.apply(this,arguments)}}()))}));return function(t,r,n){return e.apply(this,arguments)}}(),QH=(e,t)=>e.toString(16).toUpperCase().padStart(t,"0").substring(0,t),YH=function(){var e=r((function*(e,t,r,n,i){if(null==n){if(null==e.Data)throw new BH("no data in PBNode");var o;try{o=cq.unmarshal(e.Data)}catch(e){throw new BH(e.message)}if("hamt-sharded-directory"!==o.type)throw new BH("not a HAMT");if(null==o.fanout)throw new BH("missing fanout");var a=Xq({hashFn:WH,bits:Math.log2(Number(o.fanout))});n={rootBucket:a,hamtDepth:1,lastBucket:a}}var s=(n.lastBucket.tableSize()-1).toString(16).length;yield GH(e.Links,n.lastBucket,n.rootBucket);var l=yield n.rootBucket._findNewBucketAndPos(t),u=QH(l.pos,s),c=(e=>{for(var t=e.bucket,r=[];null!=t._parent;)r.push(t),t=t._parent;return r.push(t),r.reverse()})(l);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],u=QH(n.lastBucket._posAtParent,s));var d=e.Links.find((e=>{if(null==e.Name)return!1;var r=e.Name.substring(0,s),n=e.Name.substring(s);return r===u&&(""===n||n===t)}));if(null!=d)return null!=d.Name&&d.Name.substring(s)===t?d.Hash:(n.hamtDepth++,e=FN(yield r.get(d.Hash,i)),YH(e,t,r,n,i))}));return function(t,r,n,i,o){return e.apply(this,arguments)}}();function JH(e,t,r,n,i,o,a){return ZH.apply(this,arguments)}function ZH(){return ZH=r((function*(e,n,i,o,a,l,u){if(n instanceof Uint8Array){var c=FH(n,o,a,l);i.push(c)}else{if(null==n.Data)throw new BH("no data in PBNode");var d;try{d=cq.unmarshal(n.Data)}catch(e){throw new BH(e.message)}if(null!=d.data){var h=FH(d.data,o,a,l);i.push(h),o+=BigInt(h.byteLength)}var v=[];if(n.Links.length!==d.blockSizes.length)throw new BH("Inconsistent block sizes and dag links");for(var p=0;p<n.Links.length;p++){var f=n.Links[p],g=o,y=g+d.blockSizes[p];if((a>=g&&a<y||l>=g&&l<=y||a<g&&l>y)&&v.push({link:f,blockStart:o}),(o=y)>l)break}yield qc(v,(n=>Pc(n,(n=>r((function*(){var r=yield e.get(n.link.Hash,u);return t(t({},n),{},{block:r})}))))),(e=>xL(e,{ordered:!0,concurrency:u.blockReadConcurrency})),function(){var t=r((function*(t){var n,o=!1,c=!1;try{for(var d,h,v=function*(){var t,{link:n,block:o,blockStart:s}=h.value;switch(n.Hash.code){case MN:t=FN(o);break;case Se:t=o;break;default:return i.end(new BH("Unsupported codec: ".concat(n.Hash.code))),{v:void 0}}var c=new OT({concurrency:1});c.on("error",(e=>{i.end(e)})),c.add(r((function*(){var r;null===(r=u.onProgress)||void 0===r||r.call(u,new cv("unixfs:exporter:walk:file",{cid:n.Hash})),yield JH(e,t,i,s,a,l,u)}))),yield c.onIdle()},p=s(t);o=!(h=yield p.next()).done;o=!1)if(d=yield*v())return d.v}catch(e){c=!0,n=e}finally{try{o&&null!=p.return&&(yield p.return())}finally{if(c)throw n}}}));return function(e){return t.apply(this,arguments)}}()),o>=l&&i.end()}})),ZH.apply(this,arguments)}var $H=(e,t,r,n,i,o,a)=>{function c(){return c=l((function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(i){var o=r.fileSize();if(void 0===o)throw new Error("File was a directory");var{start:l,end:c}=zH(o,n.offset,n.length);if(0n!==c){var d=0n,h=c-l,v=Rc();null===(i=n.onProgress)||void 0===i||i.call(n,new cv("unixfs:exporter:walk:file",{cid:e})),JH(a,t,v,0n,l,c,n).catch((e=>{v.end(e)}));var p,f=!1,g=!1;try{for(var y,m=s(v);f=!(y=yield u(m.next())).done;f=!1){var w,b=y.value;if(null!=b){if((d+=BigInt(b.byteLength))>h)throw v.end(),new NH("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");d===h&&v.end(),null===(w=n.onProgress)||void 0===w||w.call(n,new cv("unixfs:exporter:progress:unixfs:file",{bytesRead:d,totalBytes:h,fileSize:o})),yield b}}}catch(e){g=!0,p=e}finally{try{f&&null!=m.return&&(yield u(m.return()))}finally{if(g)throw p}}if(d<h)throw new DH("Traversed entire DAG but did not read enough bytes")}}()})),c.apply(this,arguments)}return function(){return c.apply(this,arguments)}};function XH(e,t,r,n,i,o){return eK.apply(this,arguments)}function eK(){return eK=l((function*(e,t,n,i,o,a){var l,d=e.Links;if(null==e.Data)throw new BH("no data in PBNode");try{l=cq.unmarshal(e.Data)}catch(e){throw new BH(e.message)}if(null==l.fanout)throw new BH("missing fanout");var h,v=(l.fanout-1n).toString(16).length,p=qc(d,(s=>Pc(s,(s=>r((function*(){var r=null!=s.Name?s.Name.substring(v):null;if(null!=r&&""!==r){var l=yield n(s.Hash,r,"".concat(t,"/").concat(r),[],i+1,o,a);return{entries:null==l.entry?[]:[l.entry]}}var u,c=yield o.get(s.Hash,a);return e=FN(c),null===(u=a.onProgress)||void 0===u||u.call(a,new cv("unixfs:exporter:walk:hamt-sharded-directory",{cid:s.Hash})),{entries:XH(e,t,n,i,o,a)}}))))),(e=>xL(e,{ordered:!0,concurrency:a.blockReadConcurrency}))),f=!1,g=!1;try{for(var y,m=s(p);f=!(y=yield u(m.next())).done;f=!1){var{entries:w}=y.value;yield*c(s(w),u)}}catch(e){g=!0,h=e}finally{try{f&&null!=m.return&&(yield u(m.return()))}finally{if(g)throw h}}})),eK.apply(this,arguments)}var tK,rK,nK,iK,oK={raw:$H,file:$H,directory:(e,t,n,i,o,a,u)=>{function d(){return d=l((function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(l,d,h){var v=null!==(l=n.offset)&&void 0!==l?l:0,p=null!==(d=n.length)&&void 0!==d?d:t.Links.length,f=t.Links.slice(v,p);null===(h=n.onProgress)||void 0===h||h.call(n,new cv("unixfs:exporter:walk:directory",{cid:e})),yield*c(s(qc(f,(e=>Pc(e,(e=>r((function*(){var t,r=null!==(t=e.Name)&&void 0!==t?t:"",s="".concat(i,"/").concat(r);return(yield o(e.Hash,r,s,[],a+1,u,n)).entry}))))),(e=>xL(e,{ordered:!0,concurrency:n.blockReadConcurrency})),(e=>fc(e,(e=>null!=e))))))}()})),d.apply(this,arguments)}return function(){return d.apply(this,arguments)}},"hamt-sharded-directory":(e,t,r,n,i,o,a)=>function(){var r,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return null===(r=s.onProgress)||void 0===r||r.call(s,new cv("unixfs:exporter:walk:hamt-sharded-directory",{cid:e})),XH(t,n,i,o,a,s)},metadata:(e,t,r,n,i,o,a)=>()=>[],symlink:(e,t,r,n,i,o,a)=>()=>[]},aK=function(){var e=r((function*(e,t,r,n,i,o,a,s){var l,u,c=FN(yield a.get(e,s));if(null==t&&(t=e.toString()),null==c.Data)throw new BH("no data in PBNode");try{l=cq.unmarshal(c.Data)}catch(e){throw new BH(e.message)}if(null==r&&(r=t),n.length>0){var d,h;if(h="hamt-sharded-directory"===(null===(d=l)||void 0===d?void 0:d.type)?yield YH(c,n[0],a):((e,t)=>{var r=e.Links.find((e=>e.Name===t));return null==r?void 0:r.Hash})(c,n[0]),null==h)throw new PH("file does not exist");var v=n.shift();u={cid:h,toResolve:n,name:null!=v?v:"",path:"".concat(r,"/").concat(v)}}var p=oK[l.type](e,c,l,r,i,o,a);if(null==p)throw new PH("could not find content exporter");return l.isDirectory()?{entry:{type:"directory",name:t,path:r,cid:e,content:p,unixfs:l,depth:o,node:c,size:l.fileSize()},next:u}:{entry:{type:"file",name:t,path:r,cid:e,content:p,unixfs:l,depth:o,node:c,size:l.fileSize()},next:u}}));return function(t,r,n,i,o,a,s,l){return e.apply(this,arguments)}}(),sK={[MN]:aK,[Se]:KH,[JB]:MH,[lN]:UH,[Ge.code]:VH,[me]:qH},lK=function(){var e=r((function*(e,t,r,n,i,o,a){var s=sK[e.code];if(null==s)throw new _H("No resolver for code ".concat(e.code));return s(e,t,r,n,lK,i,o,a)}));return function(t,r,n,i,o,a,s){return e.apply(this,arguments)}}(),uK=e=>{if(e instanceof Uint8Array)return{cid:it.decode(e),toResolve:[]};var t=it.asCID(e);if(null!=t)return{cid:t,toResolve:[]};if("string"==typeof e){0===e.indexOf("/ipfs/")&&(e=e.substring(6));var r=function(){var e;return(null!==(e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").trim().match(/([^\\^/]|\\\/)+/g))&&void 0!==e?e:[]).filter(Boolean)}(e);return{cid:it.parse(r[0]),toResolve:r.slice(1)}}throw new TH("Unknown path type ".concat(e))};function cK(e,t){return dK.apply(this,arguments)}function dK(){return dK=l((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){for(var{cid:n,toResolve:i}=uK(e),o=n.toString(),a=o,s=i.length;;){var l=yield u(lK(n,o,a,i,s,t,r));if(null==l.entry&&null==l.next)throw new PH("Could not resolve ".concat(e));if(null!=l.entry&&(yield l.entry),null==l.next)return;i=l.next.toResolve,n=l.next.cid,o=l.next.name,a=l.next.path}}()})),dK.apply(this,arguments)}function hK(e,t){return vK.apply(this,arguments)}function vK(){return vK=r((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=yield IH(cK(e,t,r));if(null==n)throw new PH("Could not resolve ".concat(e));return n})),vK.apply(this,arguments)}function pK(e,t){return fK.apply(this,arguments)}function fK(){return fK=l((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var n=yield u(hK(e,t,r));if(null!=n&&(yield n,"directory"===n.type)){var i,o=!1,a=!1;try{for(var d,h=s(p(n,r));o=!(d=yield u(h.next())).done;o=!1){var v=d.value;yield v}}catch(e){a=!0,i=e}finally{try{o&&null!=h.return&&(yield u(h.return()))}finally{if(a)throw i}}}function p(e,t){return f.apply(this,arguments)}function f(){return f=l((function*(e,t){var r,n=!1,i=!1;try{for(var o,a=s(e.content(t));n=!(o=yield u(a.next())).done;n=!1){var l=o.value;(yield l,l instanceof Uint8Array)||"directory"===l.type&&(yield*c(s(p(l,t)),u))}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield u(a.return()))}finally{if(i)throw r}}})),f.apply(this,arguments)}}()})),fK.apply(this,arguments)}var gK=function(){if(iK)return nK;iK=1;var e=rK?tK:(rK=1,tK=e=>{if("[object Object]"!==Object.prototype.toString.call(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}),{hasOwnProperty:t}=Object.prototype,{propertyIsEnumerable:r}=Object,n=(e,t,r)=>Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}),i=nK,o={concatArrays:!1,ignoreUndefined:!1},a=e=>{var n=[];for(var i in e)t.call(e,i)&&n.push(i);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(var a of o)r.call(e,a)&&n.push(a)}return n};function s(t){return Array.isArray(t)?(i=(r=t).slice(0,0),a(r).forEach((e=>{n(i,e,s(r[e]))})),i):e(t)?function(e){var t=null===Object.getPrototypeOf(e)?Object.create(null):{};return a(e).forEach((r=>{n(t,r,s(e[r]))})),t}(t):t;var r,i}var l=(e,t,r,i)=>(r.forEach((r=>{void 0===t[r]&&i.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?n(e,r,c(e[r],t[r],i)):n(e,r,s(t[r])))})),e),u=(e,r,i)=>{var o=e.slice(0,0),u=0;return[e,r].forEach((r=>{for(var c=[],d=0;d<r.length;d++)t.call(r,d)&&(c.push(String(d)),n(o,u++,r===e?r[d]:s(r[d])));o=l(o,r,a(r).filter((e=>!c.includes(e))),i)})),o};function c(t,r,n){return n.concatArrays&&Array.isArray(t)&&Array.isArray(r)?u(t,r,n):e(r)&&e(t)?l(t,r,a(r),n):s(r)}return nK=function(){for(var t=c(s(o),this!==i&&this||{},o),r={_:{}},n=arguments.length,a=new Array(n),l=0;l<n;l++)a[l]=arguments[l];for(var u of a)if(void 0!==u){if(!e(u))throw new TypeError("`"+u+"` is not an Option Object");r=c(r,{_:u},t)}return r._},nK}(),yK=a(gK);class mK extends Error{constructor(t,r,n){super(t),e(this,"name",void 0),e(this,"code",void 0),this.name=r,this.code=n}}class wK extends mK{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"not a Unixfs node","NotUnixFSError","ERR_NOT_UNIXFS")}}class bK extends mK{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"invalid PBNode","InvalidPBNodeError","ERR_INVALID_PB_NODE")}}class SK extends mK{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"unknown error","InvalidPBNodeError","ERR_UNKNOWN_ERROR")}}class EK extends mK{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"path already exists","AlreadyExistsError","ERR_ALREADY_EXISTS")}}class kK extends mK{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"path does not exist","DoesNotExistError","ERR_DOES_NOT_EXIST")}}class xK extends mK{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no content","NoContentError","ERR_NO_CONTENT")}}class AK extends mK{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"not a file","NotAFileError","ERR_NOT_A_FILE")}}class CK extends mK{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"not a directory","NotADirectoryError","ERR_NOT_A_DIRECTORY")}}class IK extends mK{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"invalid parameters","InvalidParametersError","ERR_INVALID_PARAMETERS")}}function TK(e){return function(t){return t instanceof PK?t:new PK(t,e)}}class PK{constructor(t,r){if(e(this,"_value",void 0),e(this,"_hashFn",void 0),e(this,"_depth",void 0),e(this,"_availableBits",void 0),e(this,"_currentBufferIndex",void 0),e(this,"_buffers",void 0),!(t instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=t,this._hashFn=r,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}take(e){var t=this;return r((function*(){for(var r=e;t._availableBits<r;)yield t._produceMoreBits();for(var n=0;r>0;){var i=t._buffers[t._currentBufferIndex],o=Math.min(i.availableBits(),r);n=(n<<o)+i.take(o),r-=o,t._availableBits-=o,0===i.availableBits()&&t._currentBufferIndex++}return n}))()}untake(e){for(var t=e;t>0;){var r=this._buffers[this._currentBufferIndex],n=Math.min(r.totalBits()-r.availableBits(),t);r.untake(n),t-=n,this._availableBits+=n,this._currentBufferIndex>0&&r.totalBits()===r.availableBits()&&(this._depth--,this._currentBufferIndex--)}}_produceMoreBits(){var e=this;return r((function*(){e._depth++;var t=e._depth>0?zt([e._value,Uint8Array.from([e._depth])]):e._value,r=yield e._hashFn(t),n=new NK(r);e._buffers.push(n),e._availableBits+=n.availableBits()}))()}}var _K=[255,254,252,248,240,224,192,128],BK=[1,3,7,15,31,63,127,255];class NK{constructor(t){e(this,"_value",void 0),e(this,"_currentBytePos",void 0),e(this,"_currentBitPos",void 0),this._value=t,this._currentBytePos=t.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+8*this._currentBytePos}totalBits(){return 8*this._value.length}take(e){for(var t=e,r=0;t>0&&this._haveBits();){var n=this._value[this._currentBytePos],i=this._currentBitPos+1,o=Math.min(i,t);r=(r<<o)+DK(n,i-o,o),t-=o,this._currentBitPos-=o,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return r}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}}function DK(e,t,r){var n=function(e,t){return _K[e]&BK[Math.min(t+e-1,7)]}(t,r);return(e&n)>>>t}var RK=BigInt(Uq.code);function OK(e){return LK.apply(this,arguments)}function LK(){return LK=r((function*(e){return(yield Uq.encode(e)).subarray(0,8).reverse()})),LK.apply(this,arguments)}var MK=function(){var e=r((function*(e,r,n){null==n.codec&&(n.codec=zN);var i=yield $e.digest(e),o=it.create(n.cidVersion,n.codec.code,i);return yield r.put(o,e,t(t({},n),{},{signal:n.signal})),o}));return function(t,r,n){return e.apply(this,arguments)}}();class UK{constructor(t,r){e(this,"options",void 0),e(this,"root",void 0),e(this,"dir",void 0),e(this,"path",void 0),e(this,"dirty",void 0),e(this,"flat",void 0),e(this,"parent",void 0),e(this,"parentKey",void 0),e(this,"unixfs",void 0),e(this,"mode",void 0),e(this,"mtime",void 0),e(this,"cid",void 0),e(this,"size",void 0),e(this,"nodeSize",void 0),this.options=null!=r?r:{},this.root=t.root,this.dir=t.dir,this.path=t.path,this.dirty=t.dirty,this.flat=t.flat,this.parent=t.parent,this.parentKey=t.parentKey,this.unixfs=t.unixfs,this.mode=t.mode,this.mtime=t.mtime}}class FK extends UK{constructor(t,r){super(t,r),e(this,"_bucket",void 0),this._bucket=Xq({hashFn:OK,bits:8})}put(e,t){var n=this;return r((function*(){n.cid=void 0,n.size=void 0,n.nodeSize=void 0,yield n._bucket.put(e,t)}))()}get(e){var t=this;return r((function*(){return t._bucket.get(e)}))()}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}eachChildSeries(){var e=this;return l((function*(){var t,r=!1,n=!1;try{for(var i,o=s(e._bucket.eachLeafSeries());r=!(i=yield u(o.next())).done;r=!1){var{key:a,value:l}=i.value;yield{key:a,child:l}}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw t}}}))()}estimateNodeSize(){return void 0!==this.nodeSize||(this.nodeSize=VK(this._bucket,this,this.options)),this.nodeSize}flush(e){var r=this;return l((function*(){var n,i=!1,o=!1;try{for(var a,l=s(zK(r._bucket,e,r,r.options));i=!(a=yield u(l.next())).done;i=!1){var c=a.value;yield t(t({},c),{},{path:r.path})}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}))()}}function zK(e,t,r,n){return jK.apply(this,arguments)}function jK(){return jK=l((function*(e,t,r,n){for(var i=e._children,o=[],a=0n,l=0;l<i.length;l++){var c=i.get(l);if(null!=c){var d=l.toString(16).toUpperCase().padStart(2,"0");if(c instanceof jq){var h,v=void 0,p=!1,f=!1;try{for(var g,y=s(zK(c,t,null,n));p=!(g=yield u(y.next())).done;p=!1){v=g.value}}catch(e){f=!0,h=e}finally{try{p&&null!=y.return&&(yield u(y.return()))}finally{if(f)throw h}}if(null==v)throw new Error("Could not flush sharded directory, no sub-shard found");o.push({Name:d,Tsize:Number(v.size),Hash:v.cid}),a+=v.size}else if("function"==typeof c.value.flush){var m,w=c.value,b=void 0,S=!1,E=!1;try{for(var k,x=s(w.flush(t));S=!(k=yield u(x.next())).done;S=!1){b=k.value,yield b}}catch(e){E=!0,m=e}finally{try{S&&null!=x.return&&(yield u(x.return()))}finally{if(E)throw m}}if(null==b)throw new Error("Did not flush dir");var A=d+c.key;o.push({Name:A,Tsize:Number(b.size),Hash:b.cid}),a+=b.size}else{var C=c.value;if(null==C.cid)continue;var I=d+c.key,T=C.size;o.push({Name:I,Tsize:Number(T),Hash:C.cid}),a+=BigInt(null!=T?T:0)}}}var P=Uint8Array.from(i.bitField().reverse()),_=new cq({type:"hamt-sharded-directory",data:P,fanout:BigInt(e.tableSize()),hashType:RK,mtime:null==r?void 0:r.mtime,mode:null==r?void 0:r.mode}),B=UN(ON({Data:_.marshal(),Links:o})),N=yield u(MK(B,t,n)),D=BigInt(B.byteLength)+a;yield{cid:N,unixfs:_,size:D}})),jK.apply(this,arguments)}function VK(e,t,r){for(var n=e._children,i=[],o=0;o<n.length;o++){var a=n.get(o);if(null!=a){var s=o.toString(16).toUpperCase().padStart(2,"0");if(a instanceof jq){var l=VK(a,null,r);i.push({Name:s,Tsize:Number(l),Hash:0===r.cidVersion?qK:HK})}else if("function"==typeof a.value.flush){var u=a.value.nodeSize();i.push({Name:s+a.key,Tsize:Number(u),Hash:0===r.cidVersion?qK:HK})}else{var c=a.value;if(null==c.cid)continue;var d=s+a.key,h=c.size;i.push({Name:d,Tsize:Number(h),Hash:c.cid})}}}var v=Uint8Array.from(n.bitField().reverse());return UN(ON({Data:new cq({type:"hamt-sharded-directory",data:v,fanout:BigInt(e.tableSize()),hashType:RK,mtime:null==t?void 0:t.mtime,mode:null==t?void 0:t.mode}).marshal(),Links:i})).length}var qK=it.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),HK=it.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi"),KK=dd("helia:unixfs:commands:utils:hamt-utils"),WK=e=>e.toString(16).toUpperCase().padStart(2,"0").substring(0,2),GK=function(){var e=r((function*(e,t,r){for(var n=new FK({root:!0,dir:!0,parent:void 0,parentKey:void 0,path:"",dirty:!0,flat:!1,mtime:r.mtime,mode:r.mode},r),i=0;i<t.length;i++)yield n._bucket.put(t[i].name,{size:t[i].size,cid:t[i].cid});var o=yield IH(n.flush(e));if(null==o)throw new Error("Flushing shard yielded no result");return o}));return function(t,r,n){return e.apply(this,arguments)}}(),QK=function(){var e=r((function*(e,t,r){var n,i,o,a=cq.unmarshal(null!==(n=e[0].node.Data)&&void 0!==n?n:new Uint8Array(0)),s=BigInt(Math.pow(2,8));e.reverse();for(var l=function*(){var n=u===e.length-1,l=e[u],c=Uint8Array.from(l.children.bitField().reverse()),d=new cq({type:"hamt-sharded-directory",data:c,fanout:s,hashType:RK});n&&(d.mtime=a.mtime,d.mode=a.mode);var h=UN(ON(o={Data:d.marshal(),Links:l.node.Links}));if(i=yield MK(h,t,r),!n){var v=e[u+1];if(null==v)throw new Error("Was not operating on shard root but also had no parent?");KK("updating link in parent sub-shard with prefix %s",v.prefix),v.node.Links=v.node.Links.filter((e=>e.Name!==v.prefix)),v.node.Links.push({Name:v.prefix,Hash:i,Tsize:l.node.Links.reduce(((e,t)=>{var r;return e+(null!==(r=t.Tsize)&&void 0!==r?r:0)}),h.byteLength)})}},u=0;u<e.length;u++)yield*l();if(null==i||null==o)throw new Error("Noting persisted");return{cid:i,node:o}}));return function(t,r,n){return e.apply(this,arguments)}}(),YK=function(){var e=r((function*(e,t,r,n){for(var i=TK(OK)(xt(t)),o=[];;){var a,s=FN(yield r.get(e,n)),l=new zq,u=yield i.take(8),c=WK(u);o.push({prefix:c,children:l,node:s});var d=void 0;for(var h of s.Links){var v,p=null!==(v=h.Name)&&void 0!==v?v:"";if(p.length<2)throw new Error("Invalid HAMT - link name was too short");var f=parseInt(p.substring(0,2),16);l.set(f,!0),p.startsWith(c)&&(d=h)}if(null==d){KK("no link found with prefix %s for %s",c,t);break}var g=null!==(a=d.Name)&&void 0!==a?a:"";if(g.length<2)throw new Error("Invalid HAMT - link name was too short");if(2!==g.length)break;e=d.Hash,KK("descend into sub-shard with prefix %s",g)}return{path:o,hash:i}}));return function(t,r,n,i){return e.apply(this,arguments)}}();function JK(e,t,r,n){return ZK.apply(this,arguments)}function ZK(){return ZK=r((function*(e,t,r,n){if(null==e.Data)throw new Error("DagPB node had no data");var i,o=cq.unmarshal(e.Data);if("directory"===o.type)i=function(e){var t=0;for(var r of e.Links){var n;t+=(null!==(n=r.Name)&&void 0!==n?n:"").length,t+=1===r.Hash.version?HK.bytes.byteLength:qK.bytes.byteLength}return t}(e);else{if("hamt-sharded-directory"!==o.type)throw new Error("Can only estimate the size of directories or shards");i=yield $K(e,0,r,t,n)}return i>r})),ZK.apply(this,arguments)}function $K(e,t,r,n,i){return XK.apply(this,arguments)}function XK(){return XK=r((function*(e,t,r,n,i){if(t>r)return r;if(null==e.Data)return t;if(!cq.unmarshal(e.Data).isDirectory())return t;for(var o of e.Links){var a,s=null!==(a=o.Name)&&void 0!==a?a:"";if(t+=(s=s.substring(2)).length,t+=o.Hash.bytes.byteLength,o.Hash.code===MN){var l=FN(yield n.get(o.Hash,i));t+=(yield $K(l,t,r,n,i))}}return t})),XK.apply(this,arguments)}var eW=dd("helia:unixfs:components:utils:add-link");function tW(e,t,r,n){return rW.apply(this,arguments)}function rW(){return rW=r((function*(e,t,r,n){if(null==e.node.Data)throw new IK("Invalid parent passed to addLink");if("hamt-sharded-directory"===cq.unmarshal(e.node.Data).type)return eW("adding link to sharded directory"),oW(e,t,r,n);eW("adding ".concat(t.Name," (").concat(t.Hash,") to regular directory"));var i=yield iW(e,t,r,n);if(yield JK(i.node,r,n.shardSplitThresholdBytes,n)){eW("converting directory to sharded directory");var o=yield nW(i,r);i.cid=o.cid,i.node=FN(yield r.get(o.cid,n))}return i})),rW.apply(this,arguments)}var nW=function(){var e=r((function*(e,t){if(null==e.node.Data)throw new IK("Invalid parent passed to convertToShardedDirectory");var r=cq.unmarshal(e.node.Data),n=yield GK(t,e.node.Links.map((e=>{var t,r;return{name:null!==(t=e.Name)&&void 0!==t?t:"",size:BigInt(null!==(r=e.Tsize)&&void 0!==r?r:0),cid:e.Hash}})),{mode:r.mode,mtime:r.mtime,cidVersion:e.cid.version});return eW("converted directory to sharded directory ".concat(n.cid)),n}));return function(t,r){return e.apply(this,arguments)}}(),iW=function(){var e=r((function*(e,t,r,n){var i=e.node.Links.filter((e=>{var r=e.Name===t.Name;if(r&&!n.allowOverwriting)throw new EK;return!r}));if(i.push(t),null==e.node.Data)throw new bK("Parent node with no data passed to addToDirectory");var o,a=cq.unmarshal(e.node.Data);if(null!=a.mtime){var s=Date.now(),l=Math.floor(s/1e3);a.mtime={secs:BigInt(l),nsecs:1e3*(s-1e3*l)},o=a.marshal()}else o=e.node.Data;e.node=ON({Data:o,Links:i});var u=UN(e.node),c=yield $e.digest(u),d=it.create(e.cid.version,MN,c);return yield r.put(d,u),{node:e.node,cid:d}}));return function(t,r,n,i){return e.apply(this,arguments)}}(),oW=function(){var e=r((function*(e,t,r,n){var{path:i,hash:o}=yield YK(e.cid,t.Name,r,n),a=i[i.length-1];if(null==a)throw new Error("Invalid HAMT, could not generate path");var s=a.prefix,l=parseInt(s,16);eW("next prefix for %s is %s",t.Name,s);var u,c="".concat(s).concat(t.Name),d=a.node.Links.find((e=>{var t;return(null!==(t=e.Name)&&void 0!==t?t:"").startsWith(s)}));if(null!=d)if(eW("link %s was present in shard",c),d.Name===c){if(!n.allowOverwriting)throw new EK;eW("overwriting %s in sub-shard",t.Name),a.node.Links=a.node.Links.filter((e=>e.Name!==c)),a.node.Links.push({Name:c,Hash:t.Hash,Tsize:t.Tsize})}else{if(2===(null===(u=d.Name)||void 0===u?void 0:u.length))throw new Error("Existing link was sub-shard?!");var h;eW("prefix %s already exists, creating new sub-shard",s);for(var v=a.node.Links.findIndex((e=>{var t;return null===(t=e.Name)||void 0===t?void 0:t.startsWith(s)})),p=a.node.Links.splice(v,1)[0],f=(null!==(h=p.Name)&&void 0!==h?h:"").substring(2),g=TK(OK)(xt(f)),y=0;y<i.length;y++)yield g.take(8);for(;;){var m=yield g.take(8),w=WK(m);p.Name="".concat(w).concat(f);var b=yield o.take(8),S=WK(b);if(w!==S){var E=new zq;E.set(b,!0),E.set(m,!0),i.push({prefix:s,children:E,node:{Links:[p,{Name:"".concat(S).concat(t.Name),Hash:t.Hash,Tsize:t.Tsize}]}});break}var k=new zq;k.set(b,!0),i.push({prefix:S,children:k,node:{Links:[]}})}}else eW("link %s was not present in sub-shard",c),t.Name=c,a.node.Links.push(t),a.children.set(l,!0),eW("adding %s to existing sub-shard",c);return QK(i,r,n)}));return function(t,r,n,i){return e.apply(this,arguments)}}();function aW(e,t){return sW.apply(this,arguments)}function sW(){return sW=r((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=yield hK(e,t,r);if("directory"!==n.type)throw new CK("".concat(e.toString()," was not a UnixFS directory"));return{cid:e,node:n.node}})),sW.apply(this,arguments)}function lW(e,t,r,n){return uW.apply(this,arguments)}function uW(){return uW=r((function*(e,t,r,n){var i,o,a=yield hK(e,r,n);if("directory"!==a.type&&"file"!==a.type&&"raw"!==a.type)throw new wK("".concat(e.toString()," was not a UnixFS node"));return{Name:t,Tsize:a.node instanceof Uint8Array?a.node.byteLength:(i=a.node,o=i.Links.reduce(((e,t)=>{var r;return e+(null!==(r=t.Tsize)&&void 0!==r?r:0)}),0),UN(i).byteLength+o),Hash:e}})),uW.apply(this,arguments)}var cW=dd("helia:unixfs:components:utils:resolve");function dW(e,t,r,n){return hW.apply(this,arguments)}function hW(){return hW=r((function*(e,t,r,n){if(null==t||""===t)return{cid:e};var i="/ipfs/".concat(e).concat(null==t?"":"/".concat(t)),o=yield gc(cK(i,r,n));if(0===o.length)throw new kK("Could not find path in directory");return cW("resolved %s to %c",t,e),{cid:o[o.length-1].cid,path:t,segments:o}})),hW.apply(this,arguments)}function vW(e,t,r,n){return pW.apply(this,arguments)}function pW(){return pW=r((function*(e,r,n,i){if(null==r.segments||0===r.segments.length)return e;var o=r.segments.pop();if(null==o)throw new Error("Insufficient segments");for(var a of(o.cid=e,r.segments.reverse(),r.segments)){var[s,l]=yield Promise.all([aW(a.cid,n,i),lW(o.cid,o.name,n,i)]);e=(yield tW(s,l,n,t(t({},i),{},{allowOverwriting:!0,cidVersion:e.version}))).cid,a.cid=e,o=a}return e})),pW.apply(this,arguments)}var fW=yK.bind({ignoreUndefined:!0}),gW={};function yW(){return yW=l((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var n=fW(gW,r),i=yield u(dW(e,n.path,t,n)),o=yield u(hK(i.cid,t,n));if("file"!==o.type&&"raw"!==o.type)throw new AK;if(null==o.content)throw new xK;yield*c(s(o.content(n)))}()})),yW.apply(this,arguments)}var mW=262144,wW=yK.bind({ignoreUndefined:!0}),bW=dd("helia:unixfs:chmod"),SW={recursive:!1,shardSplitThresholdBytes:mW};function EW(){return EW=r((function*(e,n,i){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},a=wW(SW,o),c=yield dW(e,a.path,i,o);if(bW("chmod %c %d",c.cid,n),a.recursive){var d=yield qc(l((function*(){var e,t=!1,r=!1;try{for(var a,l=s(pK(c.cid,i,o));t=!(a=yield u(l.next())).done;t=!1){var d=a.value,h=void 0,v=[];if("raw"===d.type)h=new cq({type:"file",data:d.node});else{if("file"!==d.type&&"directory"!==d.type)throw new wK;h=d.unixfs,v=d.node.Links}h.mode=n;var p={Data:h.marshal(),Links:v};yield{path:d.path,content:p}}}catch(t){r=!0,e=t}finally{try{t&&null!=l.return&&(yield u(l.return()))}finally{if(r)throw e}}})),(n=>{return pH(n,i,t(t({},a),{},{dagBuilder:(o=l((function*(n,i){var o,l=!1,c=!1;try{for(var d,h=function*(){var n=d.value;yield r((function*(){var r=n.content,o=UN(r),s=yield MK(o,i,t(t({},a),{},{cidVersion:e.version}));if(null==r.Data)throw new bK("".concat(s," had no data"));var l=cq.unmarshal(r.Data);return{cid:s,size:BigInt(o.length),path:n.path,unixfs:l}}))},v=s(n);l=!(d=yield u(v.next())).done;l=!1)yield*h()}catch(e){c=!0,o=e}finally{try{l&&null!=v.return&&(yield u(v.return()))}finally{if(c)throw o}}})),function(e,t){return o.apply(this,arguments)})}));var o}),function(){var e=r((function*(e){return IH(e)}));return function(t){return e.apply(this,arguments)}}());if(null==d)throw new SK("Could not chmod ".concat(c.cid.toString()));return vW(d.cid,c,i,a)}var h,v=yield i.get(c.cid,o),p=[];if(c.cid.code===Se)h=new cq({type:"file",data:v});else{var f=FN(v);if(null==f.Data)throw new bK("".concat(c.cid.toString()," had no data"));p=f.Links,h=cq.unmarshal(f.Data)}h.mode=n;var g=UN({Data:h.marshal(),Links:p}),y=yield $e.digest(g),m=it.create(c.cid.version,MN,y);return yield i.put(m,g),vW(m,c,i,a)})),EW.apply(this,arguments)}var kW=yK.bind({ignoreUndefined:!0}),xW=dd("helia:unixfs:cp"),AW={force:!1,shardSplitThresholdBytes:mW};function CW(){return CW=r((function*(e,r,n,i){var o=kW(AW,arguments.length>4&&void 0!==arguments[4]?arguments[4]:{});if(n.includes("/"))throw new IK("Name must not have slashes");var[a,s]=yield Promise.all([aW(r,i,o),lW(e,n,i,o)]);return xW('Adding %c as "%s" to %c',e,n,r),(yield tW(a,s,i,t({allowOverwriting:o.force,cidVersion:r.version},o))).cid})),CW.apply(this,arguments)}var IW=yK.bind({ignoreUndefined:!0}),TW={};function PW(){return PW=l((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var n=IW(TW,r),i=yield u(dW(e,n.path,t,n)),o=yield u(hK(i.cid,t));if("file"!==o.type&&"raw"!==o.type){if(null==o.content)throw new xK;if("directory"!==o.type)throw new CK;yield*c(s(o.content({offset:r.offset,length:r.length})))}else yield o}()})),PW.apply(this,arguments)}var _W=yK.bind({ignoreUndefined:!0}),BW=dd("helia:unixfs:mkdir"),NW={cidVersion:1,force:!1,shardSplitThresholdBytes:mW};function DW(){return DW=r((function*(e,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},o=_W(NW,i);if(r.includes("/"))throw new IK("Path must not have slashes");if("directory"!==(yield hK(e,n,i)).type)throw new CK("".concat(e.toString()," was not a UnixFS directory"));BW("creating %s",r);var a=UN({Data:new cq({type:"directory",mode:o.mode,mtime:o.mtime}).marshal(),Links:[]}),s=yield $e.digest(a),l=it.create(o.cidVersion,MN,s);yield n.put(l,a);var[u,c]=yield Promise.all([aW(e,n,o),lW(l,r,n,o)]);return BW("adding empty dir called %s to %c",r,e),(yield tW(u,c,n,t(t({},o),{},{allowOverwriting:o.force}))).cid})),DW.apply(this,arguments)}var RW=dd("helia:unixfs:utils:remove-link");function OW(){return OW=r((function*(e,t,r,n){if(null==e.node.Data)throw new bK("Parent node had no data");if("hamt-sharded-directory"===cq.unmarshal(e.node.Data).type){RW("removing ".concat(t," from sharded directory"));var i=yield MW(e,t,r,n);return(yield JK(i.node,r,n.shardSplitThresholdBytes,n))?i:(RW("converting shard to flat directory %c",e.cid),UW(i,r,n))}return RW("removing link ".concat(t," regular directory")),LW(e,t,r,n)})),OW.apply(this,arguments)}var LW=function(){var e=r((function*(e,r,n,i){e.node.Links=e.node.Links.filter((e=>e.Name!==r));var o=UN(e.node),a=yield MK(o,n,t(t({},i),{},{cidVersion:e.cid.version}));return RW("Updated regular directory ".concat(a)),{node:e.node,cid:a}}));return function(t,r,n,i){return e.apply(this,arguments)}}(),MW=function(){var e=r((function*(e,t,r,n){var{path:i}=yield YK(e.cid,t,r,n),o=i[i.length-1];if(null==o)throw new Error("Invalid HAMT, could not generate path");var a=o.node.Links.filter((e=>{var r;return(null!==(r=e.Name)&&void 0!==r?r:"").substring(2)===t})).map((e=>e.Name)).pop();if(null==a)throw new Error("File not found");var s=a.substring(0,2),l=parseInt(s,16);if(o.node.Links=o.node.Links.filter((e=>e.Name!==a)),o.children.unset(l),1===o.node.Links.length)for(var u=function*(){var e;if(1===i.length)return 0;var t=i[i.length-1];if(null==t||t.node.Links.length>1)return 0;i.pop();var r=i[i.length-1];if(null==r)return 0;var n=t.node.Links[0];r.node.Links=r.node.Links.filter((e=>{var t;return!(null!==(t=e.Name)&&void 0!==t?t:"").startsWith(r.prefix)})),r.node.Links.push({Hash:n.Hash,Name:"".concat(r.prefix).concat((null!==(e=n.Name)&&void 0!==e?e:"").substring(2)),Tsize:n.Tsize})};0!==(yield*u()););return QK(i,r,n)}));return function(t,r,n,i){return e.apply(this,arguments)}}(),UW=function(){var e=r((function*(e,t,r){if(null==e.node.Data)throw new IK("Invalid parent passed to convertToFlatDirectory");var n={Links:[]},i=yield hK(e.cid,t);if("directory"!==i.type)throw new Error("Unexpected node type");var o,a=!1,l=!1;try{for(var u,c=s(i.content());a=!(u=yield c.next()).done;a=!1){var d=u.value,h=0;h=d.node instanceof Uint8Array?d.node.byteLength:UN(d.node).length,n.Links.push({Hash:d.cid,Name:d.name,Tsize:h})}}catch(e){l=!0,o=e}finally{try{a&&null!=c.return&&(yield c.return())}finally{if(l)throw o}}var v=cq.unmarshal(e.node.Data);n.Data=new cq({type:"directory",mode:v.mode,mtime:v.mtime}).marshal();var p=UN(ON(n));return{cid:yield MK(p,t,{codec:zN,cidVersion:e.cid.version,signal:r.signal}),node:n}}));return function(t,r,n){return e.apply(this,arguments)}}(),FW=yK.bind({ignoreUndefined:!0}),zW=dd("helia:unixfs:rm"),jW={shardSplitThresholdBytes:mW};function VW(){return VW=r((function*(e,r,n){var i=FW(jW,arguments.length>3&&void 0!==arguments[3]?arguments[3]:{});if(r.includes("/"))throw new IK("Name must not have slashes");var o=yield aW(e,n,i);zW("Removing %s from %c",r,e);var a=yield function(e,t,r,n){return OW.apply(this,arguments)}(o,r,n,t(t({},i),{},{cidVersion:e.version}));return a.cid})),VW.apply(this,arguments)}var qW=yK.bind({ignoreUndefined:!0}),HW=dd("helia:unixfs:stat"),KW={};function WW(){return WW=r((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=qW(KW,r),i=yield dW(e,r.path,t,n);HW("stat %c",i.cid);var o=yield hK(i.cid,t,n);if("file"!==o.type&&"directory"!==o.type&&"raw"!==o.type)throw new wK;var a,s,l,u=0n,c=0n,d=0n,h=0n,v=0,p=o.type;if("raw"===o.type&&(u=BigInt(o.node.byteLength),c=BigInt(o.node.byteLength),d=BigInt(o.node.byteLength),h=BigInt(o.node.byteLength),v=1),"directory"===o.type&&(u=0n,d=0n,h=c=BigInt(o.unixfs.marshal().byteLength),v=1,a=o.unixfs.mode,s=o.unixfs.mtime,l=o.unixfs),"file"===o.type){var f,g,y=yield GW(i.cid,t,n);u=o.unixfs.fileSize(),c=BigInt((null!==(f=null===(g=o.node.Data)||void 0===g?void 0:g.byteLength)&&void 0!==f?f:0)+o.node.Links.reduce(((e,t)=>{var r;return e+(null!==(r=t.Tsize)&&void 0!==r?r:0)}),0)),d=BigInt(y.localFileSize),h=BigInt(y.localDagSize),v=y.blocks,a=o.unixfs.mode,s=o.unixfs.mtime,l=o.unixfs}return{cid:i.cid,mode:a,mtime:s,fileSize:u,dagSize:c,localFileSize:d,localDagSize:h,blocks:v,type:p,unixfs:l}})),WW.apply(this,arguments)}function GW(e,t,r){return QW.apply(this,arguments)}function QW(){return QW=r((function*(e,t,r){var n={localFileSize:0,localDagSize:0,blocks:0};if(yield t.has(e,r)){var i=yield t.get(e,r);if(n.blocks++,n.localDagSize+=i.byteLength,e.code===Se)n.localFileSize+=i.byteLength;else{if(e.code!==MN)throw new SK("".concat(e.toString()," was neither DAG_PB nor RAW"));var o=FN(i);if(o.Links.length>0)for(var a of o.Links){var s=yield GW(a.Hash,t,r);n.localFileSize+=s.localFileSize,n.localDagSize+=s.localDagSize,n.blocks+=s.blocks}else{var l;if(null==o.Data)throw new bK("PBNode ".concat(e.toString()," had no data"));var u=cq.unmarshal(o.Data);if(null==u.data)throw new bK("UnixFS node ".concat(e.toString()," had no data"));n.localFileSize+=null!==(l=u.data.byteLength)&&void 0!==l?l:0}}}return n})),QW.apply(this,arguments)}var YW=yK.bind({ignoreUndefined:!0}),JW=dd("helia:unixfs:touch"),ZW={recursive:!1,shardSplitThresholdBytes:mW};function $W(){return $W=r((function*(e,n){var i,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=YW(ZW,o),c=yield dW(e,a.path,n,a),d=null!==(i=a.mtime)&&void 0!==i?i:{secs:BigInt(Math.round(Date.now()/1e3)),nsecs:0};if(JW("touch %c %o",c.cid,d),a.recursive){var h=yield qc(l((function*(){var e,t=!1,r=!1;try{for(var i,o=s(pK(c.cid,n));t=!(i=yield u(o.next())).done;t=!1){var a=i.value,l=void 0,h=void 0;if("raw"===a.type)l=new cq({data:a.node}),h=[];else{if("file"!==a.type&&"directory"!==a.type)throw new wK;l=a.unixfs,h=a.node.Links}l.mtime=d;var v={Data:l.marshal(),Links:h};yield{path:a.path,content:v}}}catch(t){r=!0,e=t}finally{try{t&&null!=o.return&&(yield u(o.return()))}finally{if(r)throw e}}})),(i=>{return pH(i,n,t(t({},a),{},{dagBuilder:(o=l((function*(n,i){var o,l=!1,c=!1;try{for(var d,h=function*(){var n=d.value;yield r((function*(){var r=n.content,o=UN(r),s=yield MK(o,i,t(t({},a),{},{cidVersion:e.version}));if(null==r.Data)throw new bK("".concat(s," had no data"));var l=cq.unmarshal(r.Data);return{cid:s,size:BigInt(o.length),path:n.path,unixfs:l}}))},v=s(n);l=!(d=yield u(v.next())).done;l=!1)yield*h()}catch(e){c=!0,o=e}finally{try{l&&null!=v.return&&(yield u(v.return()))}finally{if(c)throw o}}})),function(e,t){return o.apply(this,arguments)})}));var o}),function(){var e=r((function*(e){return IH(e)}));return function(t){return e.apply(this,arguments)}}());if(null==h)throw new SK("Could not chmod ".concat(c.cid.toString()));return vW(h.cid,c,n,a)}var v,p=yield n.get(c.cid,o),f=[];if(c.cid.code===Se)v=new cq({data:p});else{var g=FN(p);if(f=g.Links,null==g.Data)throw new bK("".concat(c.cid.toString()," had no data"));v=cq.unmarshal(g.Data)}v.mtime=d;var y=UN({Data:v.marshal(),Links:f}),m=yield $e.digest(y),w=it.create(c.cid.version,MN,m);return yield n.put(w,y),vW(w,c,n,a)})),$W.apply(this,arguments)}class XW{constructor(t){e(this,"components",void 0),this.components=t}addAll(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(function(e,t){return EH.apply(this,arguments)}(e,t.components.blockstore,r)))}()})).apply(this,arguments)}addBytes(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};return function(e,t){return kH.apply(this,arguments)}(e,n.components.blockstore,r)}))()}addByteStream(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};return function(e,t){return xH.apply(this,arguments)}(e,n.components.blockstore,r)}))()}addFile(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};return function(e,t){return AH.apply(this,arguments)}(e,n.components.blockstore,r)}))()}addDirectory(){var e=arguments,t=this;return r((function*(){var r=e.length>1&&void 0!==e[1]?e[1]:{};return function(e,t){return CH.apply(this,arguments)}(e.length>0&&void 0!==e[0]?e[0]:{},t.components.blockstore,r)}))()}cat(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(function(e,t){return yW.apply(this,arguments)}(e,t.components.blockstore,r)))}()})).apply(this,arguments)}chmod(e,t){var n=arguments,i=this;return r((function*(){var r=n.length>2&&void 0!==n[2]?n[2]:{};return function(e,t,r){return EW.apply(this,arguments)}(e,t,i.components.blockstore,r)}))()}cp(e,t,n){var i=arguments,o=this;return r((function*(){var r=i.length>3&&void 0!==i[3]?i[3]:{};return function(e,t,r,n){return CW.apply(this,arguments)}(e,t,n,o.components.blockstore,r)}))()}ls(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(function(e,t){return PW.apply(this,arguments)}(e,t.components.blockstore,r)))}()})).apply(this,arguments)}mkdir(e,t){var n=arguments,i=this;return r((function*(){var r=n.length>2&&void 0!==n[2]?n[2]:{};return function(e,t,r){return DW.apply(this,arguments)}(e,t,i.components.blockstore,r)}))()}rm(e,t){var n=arguments,i=this;return r((function*(){var r=n.length>2&&void 0!==n[2]?n[2]:{};return function(e,t,r){return VW.apply(this,arguments)}(e,t,i.components.blockstore,r)}))()}stat(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};return function(e,t){return WW.apply(this,arguments)}(e,n.components.blockstore,r)}))()}touch(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};return function(e,t){return $W.apply(this,arguments)}(e,n.components.blockstore,r)}))()}}function eG(e){return new XW(e)}class tG{constructor(t){e(this,"components",void 0),this.components=t}add(e){var t=arguments,n=this;return r((function*(){var r,i=t.length>1&&void 0!==t[1]?t[1]:{},o=ZB(e),a=yield(null!==(r=i.hasher)&&void 0!==r?r:$e).digest(o),s=it.createV1(JB,a);return yield n.components.blockstore.put(s,o,i),s}))()}get(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{},i=yield n.components.blockstore.get(e,r);return $B(i)}))()}}function rG(e){return new tG(e)}export{Cc as $,To as A,ya as B,fa as C,ca as D,la as E,wa as F,va as G,ln as H,ma as I,ha as J,ba as K,Iu as L,Zo as M,K as N,Wr as O,en as P,it as Q,Ge as R,ie as S,Ir as T,gi as U,wc as V,bc as W,Lc as X,Ec as Y,kc as Z,pa as _,Lr as a,Ot as a$,xc as a0,fc as a1,yc as a2,hc as a3,vd as a4,W as a5,Se as a6,He as a7,Rc as a8,qc as a9,ea as aA,Mu as aB,Eu as aC,Cu as aD,Tu as aE,Au as aF,zu as aG,zt as aH,eG as aI,gt as aJ,li as aK,ku as aL,Uu as aM,Fu as aN,Sa as aO,Cr as aP,fI as aQ,ut as aR,yt as aS,At as aT,jt as aU,kt as aV,ZB as aW,$e as aX,JB as aY,$B as aZ,Ft as a_,bu as aa,GV as ab,JV as ac,Ar as ad,bs as ae,aD as af,VF as ag,RL as ah,DL as ai,EL as aj,_O as ak,xO as al,DI as am,WI as an,Lv as ao,GI as ap,dn as aq,na as ar,Jn as as,Yn as at,Mr as au,sn as av,$n as aw,ac as ax,Fi as ay,nn as az,_r as b,Tr as b0,xv as b1,YB as b2,rG as b3,cn as c,Dr as d,Br as e,wn as f,qr as g,Rr as h,On as i,In as j,Dn as k,xn as l,kn as m,Cn as n,An as o,Rn as p,bn as q,Tn as r,Vr as s,on as t,Or as u,un as v,Pn as w,_n as x,Bn as y,Nn as z};