web-dc-api 0.1.3 โ 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/helia-core-DFjEGetI.js +1 -0
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/polkadot-api-Bfjyuh3w.js +1 -0
- package/dist/dc.min.js +1 -1
- package/dist/esm/chunks/helia-core-CLvijavP.js +1 -0
- package/dist/esm/chunks/polkadot-api-Ci6ZT5H7.js +1 -0
- package/dist/esm/index.js +1 -1
- package/lib/common/define.ts +1 -1
- package/lib/implements/threaddb/net/define.ts +19 -8
- package/lib/implements/threaddb/net/grpcClient.ts +12 -4
- package/lib/implements/threaddb/net/net.ts +0 -1
- package/package.json +2 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var e=require("./babel-tools-BoLJtxtW.js"),t=new Uint8Array(0);function r(e){var r=e.match(/../g);return null!=r?new Uint8Array(r.map((e=>parseInt(e,16)))):t}function n(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 i=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),c=Math.log(s)/Math.log(256),u=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)*c+1>>>0,a=new Uint8Array(o);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var d=0,h=o-1;(0!==u||d<i)&&-1!==h;h--,d++)u+=s*a[h]>>>0,a[h]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");i=d,t++}if(" "!==e[t]){for(var p=o-i;p!==o&&0===a[p];)p++;for(var f=new Uint8Array(n+(o-p)),v=n;p!==o;)f[v++]=a[p++];return f}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,i=0,o=t.length;i!==o&&0===t[i];)i++,r++;for(var a=(o-i)*u+1>>>0,c=new Uint8Array(a);i!==o;){for(var d=t[i],h=0,p=a-1;(0!==d||h<n)&&-1!==p;p--,h++)d+=256*c[p]>>>0,c[p]=d%s>>>0,d=d/s>>>0;if(0!==d)throw new Error("Non-zero carry");n=h,i++}for(var f=a-n;f!==a&&0===c[f];)f++;for(var v=l.repeat(r);f<a;++f)v+=e.charAt(c[f]);return v},decodeUnsafe:d,decode:function(e){var r=d(e);if(r)return r;throw new Error("Non-".concat(t," character"))}}},o=i;let a=class{constructor(t,r,n){e._defineProperty(this,"name",void 0),e._defineProperty(this,"prefix",void 0),e._defineProperty(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")}},s=class{constructor(t,r,n){e._defineProperty(this,"name",void 0),e._defineProperty(this,"prefix",void 0),e._defineProperty(this,"baseDecode",void 0),e._defineProperty(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 c(this,e)}};class l{constructor(t){e._defineProperty(this,"decoders",void 0),this.decoders=t}or(e){return c(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 c(t,r){var n,i;return new l(e._objectSpread2(e._objectSpread2({},null!==(n=t.decoders)&&void 0!==n?n:{[t.prefix]:t}),null!==(i=r.decoders)&&void 0!==i?i:{[r.prefix]:r}))}class u{constructor(t,r,n,i){e._defineProperty(this,"name",void 0),e._defineProperty(this,"prefix",void 0),e._defineProperty(this,"baseEncode",void 0),e._defineProperty(this,"baseDecode",void 0),e._defineProperty(this,"encoder",void 0),e._defineProperty(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 s(t,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function d(e){var{name:t,prefix:r,encode:n,decode:i}=e;return new u(t,r,n,i)}function h(e){var{name:t,prefix:r,alphabet:i}=e,{encode:a,decode:s}=o(i,t);return d({prefix:r,name:t,encode:a,decode:e=>n(s(e))})}function p(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 d({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,c=0;c<i;++c){var u=t[e[c]];if(void 0===u)throw new SyntaxError("Non-".concat(n," character"));s=s<<r|u,(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 f=h({prefix:"9",name:"base10",alphabet:"0123456789"}),v=Object.freeze({__proto__:null,base10:f}),y=p({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),g=p({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),m=Object.freeze({__proto__:null,base16:y,base16upper:g}),w=p({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),b=Object.freeze({__proto__:null,base2:w}),_=Array.from("๐๐ชโ๐ฐ๐๐๐๐๐๐๐๐๐๐๐๐๐โ๐ป๐ฅ๐พ๐ฟ๐โค๐๐คฃ๐๐๐๐ญ๐๐๐
๐๐๐ฅ๐ฅฐ๐๐๐๐ข๐ค๐๐๐ช๐โบ๐๐ค๐๐๐๐๐น๐คฆ๐๐โโจ๐คท๐ฑ๐๐ธ๐๐๐๐๐๐๐๐๐คฉ๐๐๐ค๐๐ฏ๐๐๐ถ๐๐คญโฃ๐๐๐๐ช๐๐ฅ๐๐๐ฉ๐ก๐คช๐๐ฅณ๐ฅ๐คค๐๐๐ณโ๐๐๐ด๐๐ฌ๐๐๐ท๐ป๐โญโ
๐ฅบ๐๐๐ค๐ฆโ๐ฃ๐๐โน๐๐๐ โ๐๐บ๐๐ป๐๐๐๐๐น๐ฃ๐ซ๐๐๐ต๐ค๐๐ด๐ค๐ผ๐ซโฝ๐คโ๐๐คซ๐๐ฎ๐๐ป๐๐ถ๐๐ฒ๐ฟ๐งก๐โก๐๐โโ๐๐ฐ๐คจ๐ถ๐ค๐ถ๐ฐ๐๐ข๐ค๐๐จ๐จ๐คฌโ๐๐บ๐ค๐๐๐ฑ๐๐ถ๐ฅดโถโกโ๐๐ธโฌ๐จ๐๐ฆ๐ท๐บโ ๐
๐๐ต๐๐คฒ๐ค ๐คง๐๐ต๐
๐ง๐พ๐๐๐ค๐๐คฏ๐ทโ๐ง๐ฏ๐๐๐ค๐๐โ๐ด๐ฃ๐ธ๐๐๐ฅ๐คข๐
๐ก๐ฉ๐๐ธ๐ป๐ค๐คฎ๐ผ๐ฅต๐ฉ๐๐๐ผ๐๐ฃ๐ฅ"),S=_.reduce(((e,t,r)=>(e[r]=t,e)),[]),P=_.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 E=d({prefix:"๐",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+=S[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=P[n];if(null==i)throw new Error("Non-base256emoji character: ".concat(r));t.push(i)}return new Uint8Array(t)}}),A=Object.freeze({__proto__:null,base256emoji:E}),k=p({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),x=p({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),T=p({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),I=p({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),C=p({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),B=p({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),N=p({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),D=p({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),G=p({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),R=Object.freeze({__proto__:null,base32:k,base32hex:C,base32hexpad:N,base32hexpadupper:D,base32hexupper:B,base32pad:T,base32padupper:I,base32upper:x,base32z:G}),O=h({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),L=h({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),M=Object.freeze({__proto__:null,base36:O,base36upper:L}),j=h({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),F=h({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),U=Object.freeze({__proto__:null,base58btc:j,base58flickr:F}),z=p({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),V=p({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),q=p({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),H=p({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),K=Object.freeze({__proto__:null,base64:z,base64pad:V,base64url:q,base64urlpad:H}),W=p({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Q=Object.freeze({__proto__:null,base8:W}),Y=d({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)}),J=Object.freeze({__proto__:null,identity:Y}),Z=new TextEncoder,$=new TextDecoder,X=512;function ee(e){return JSON.parse($.decode(e))}var te=Object.freeze({__proto__:null,code:512,decode:ee,encode:function(e){return Z.encode(JSON.stringify(e))},name:"json"}),re=85;var ne=Object.freeze({__proto__:null,code:re,decode:function(e){return n(e)},encode:function(e){return n(e)},name:"raw"}),ie=function e(t,r,n){r=r||[];var i=n=n||0;for(;t>=se;)r[n++]=255&t|oe,t/=128;for(;t&ae;)r[n++]=255&t|oe,t>>>=7;return r[n]=0|t,e.bytes=n-i+1,r},oe=128,ae=-128,se=Math.pow(2,31);var le=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&ue)<<o:(n&ue)*Math.pow(2,o),o+=7}while(n>=ce);return e.bytes=a-r,i},ce=128,ue=127;var de=Math.pow(2,7),he=Math.pow(2,14),pe=Math.pow(2,21),fe=Math.pow(2,28),ve=Math.pow(2,35),ye=Math.pow(2,42),ge=Math.pow(2,49),me=Math.pow(2,56),we=Math.pow(2,63),be={encode:ie,decode:le,encodingLength:function(e){return e<de?1:e<he?2:e<pe?3:e<fe?4:e<ve?5:e<ye?6:e<ge?7:e<me?8:e<we?9:10}};function _e(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return[be.decode(e,t),be.decode.bytes]}function Se(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return be.encode(e,t,r),t}function Pe(e){return be.encodingLength(e)}function Ee(e,t){var r=t.byteLength,n=Pe(e),i=n+Pe(r),o=new Uint8Array(i+r);return Se(e,o,0),Se(r,o,n),o.set(t,i),new ke(e,r,t,o)}function Ae(e){var t=n(e),[r,i]=_e(t),[o,a]=_e(t.subarray(i)),s=t.subarray(i+a);if(s.byteLength!==o)throw new Error("Incorrect length");return new ke(r,o,s,t)}class ke{constructor(t,r,n,i){e._defineProperty(this,"code",void 0),e._defineProperty(this,"size",void 0),e._defineProperty(this,"digest",void 0),e._defineProperty(this,"bytes",void 0),this.code=t,this.size=r,this.digest=n,this.bytes=i}}var xe=n;var Te={code:0,name:"identity",encode:xe,digest:function(e){return Ee(0,xe(e))}},Ie=Object.freeze({__proto__:null,identity:Te});function Ce(e){var{name:t,code:r,encode:n}=e;return new Be(t,r,n)}class Be{constructor(t,r,n){e._defineProperty(this,"name",void 0),e._defineProperty(this,"code",void 0),e._defineProperty(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?Ee(this.code,t):t.then((e=>Ee(this.code,e)))}throw Error("Unknown type, must be binary type")}}function Ne(t){return function(){var r=e._asyncToGenerator((function*(e){return new Uint8Array(yield crypto.subtle.digest(t,e))}));return function(e){return r.apply(this,arguments)}}()}var De=Ce({name:"sha2-256",code:18,encode:Ne("SHA-256")}),Ge=Ce({name:"sha2-512",code:19,encode:Ne("SHA-512")}),Re=Object.freeze({__proto__:null,sha256:De,sha512:Ge});function Oe(e,t){var{bytes:r,version:n}=e;return 0===n?function(e,t,r){var{prefix:n}=r;if(n!==j.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,Me(e),null!=t?t:j.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,Me(e),null!=t?t:k.encoder)}var Le=new WeakMap;function Me(e){var t=Le.get(e);if(null==t){var r=new Map;return Le.set(e,r),r}return t}class je{constructor(t,r,n,i){e._defineProperty(this,"code",void 0),e._defineProperty(this,"version",void 0),e._defineProperty(this,"multihash",void 0),e._defineProperty(this,"bytes",void 0),e._defineProperty(this,"/",void 0),e._defineProperty(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!==Fe)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ue)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return je.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=Ee(e,t);return je.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 je.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 Oe(this,e)}toJSON(){return{"/":Oe(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 je)return t;if(null!=t["/"]&&t["/"]===t.bytes||t.asCID===t){var{version:r,code:n,multihash:i,bytes:o}=t;return new je(r,n,i,null!=o?o:ze(r,n,i.bytes))}if(!0===t[Ve]){var{version:a,multihash:s,code:l}=t,c=Ae(s);return je.create(a,l,c)}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!==Fe)throw new Error("Version 0 CID must use dag-pb (code: ".concat(Fe,") block encoding"));return new je(e,t,r,r.bytes);case 1:var n=ze(e,t,r.bytes);return new je(e,t,r,n);default:throw new Error("Invalid version")}}static createV0(e){return je.create(0,Fe,e)}static createV1(e,t){return je.create(1,e,t)}static decode(e){var[t,r]=je.decodeFirst(e);if(0!==r.length)throw new Error("Incorrect length");return t}static decodeFirst(e){var t=je.inspectBytes(e),r=t.size-t.multihashSize,i=n(e.subarray(r,r+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");var o=i.subarray(t.multihashSize-t.digestSize),a=new ke(t.multihashCode,t.digestSize,o,i);return[0===t.version?je.createV0(a):je.createV1(t.codec,a),e.subarray(t.size)]}static inspectBytes(e){var t=0,r=()=>{var[r,n]=_e(e.subarray(t));return t+=n,r},n=r(),i=Fe;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:j;return[j.prefix,r.decode("".concat(j.prefix).concat(e))];case j.prefix:var n=null!=t?t:j;return[j.prefix,n.decode(e)];case k.prefix:var i=null!=t?t:k;return[k.prefix,i.decode(e)];case O.prefix:var o=null!=t?t:O;return[O.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=je.decode(n);if(0===i.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return Me(i).set(r,e),i}}var Fe=112,Ue=18;function ze(e,t,r){var n=Pe(e),i=n+Pe(t),o=new Uint8Array(i+r.byteLength);return Se(e,o,0),Se(t,o,n),o.set(r,i),o}var Ve=Symbol.for("@ipld/js-cid/CID"),qe=e._objectSpread2(e._objectSpread2(e._objectSpread2(e._objectSpread2(e._objectSpread2(e._objectSpread2(e._objectSpread2(e._objectSpread2(e._objectSpread2(e._objectSpread2({},J),b),Q),v),m),R),M),U),K),A);function He(){return new Uint8Array(arguments.length>0&&void 0!==arguments[0]?arguments[0]:0)}function Ke(){return new Uint8Array(arguments.length>0&&void 0!==arguments[0]?arguments[0]:0)}function We(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}e._objectSpread2(e._objectSpread2({},Re),Ie);var Qe=We("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Ye=We("ascii","a",(e=>{for(var t="a",r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t}),(e=>{for(var t=Ke((e=e.substring(1)).length),r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t})),Je=e._objectSpread2({utf8:Qe,"utf-8":Qe,hex:qe.base16,latin1:Ye,ascii:Ye,binary:Ye},qe);function Ze(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8",r=Je[t];if(null==r)throw new Error('Unsupported encoding "'.concat(t,'"'));return r.encoder.encode(e).substring(1)}let $e=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidMultiaddrError")}};e._defineProperty($e,"name","InvalidMultiaddrError");class Xe extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","ValidationError")}}e._defineProperty(Xe,"name","ValidationError");let et=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidParametersError")}};e._defineProperty(et,"name","InvalidParametersError");class tt extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","UnknownProtocolError")}}function rt(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}function nt(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8",r=Je[t];if(null==r)throw new Error('Unsupported encoding "'.concat(t,'"'));return r.decoder.decode("".concat(r.prefix).concat(e))}e._defineProperty(tt,"name","UnknownProtocolError");var it=Math.pow(2,7),ot=Math.pow(2,14),at=Math.pow(2,21),st=Math.pow(2,28),lt=Math.pow(2,35),ct=Math.pow(2,42),ut=Math.pow(2,49),dt=128,ht=127;function pt(e){if(e<it)return 1;if(e<ot)return 2;if(e<at)return 3;if(e<st)return 4;if(e<lt)return 5;if(e<ct)return 6;if(e<ut)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ft(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;switch(pt(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 vt(e,t){var r=e[t],n=0;if(n+=r&ht,r<dt)return n;if(n+=((r=e[t+1])&ht)<<7,r<dt)return n;if(n+=((r=e[t+2])&ht)<<14,r<dt)return n;if(n+=((r=e[t+3])&ht)<<21,r<dt)return n;if(n+=((r=e[t+4])&ht)*st,r<dt)return n;if(n+=((r=e[t+5])&ht)*lt,r<dt)return n;if(n+=((r=e[t+6])&ht)*ct,r<dt)return n;if(n+=((r=e[t+7])&ht)*ut,r<dt)return n;throw new RangeError("Could not decode varint")}function yt(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return null==t&&(t=Ke(pt(e))),t instanceof Uint8Array?ft(e,t,r):function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;switch(pt(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 gt(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return e instanceof Uint8Array?vt(e,t):function(e,t){var r=e.get(t),n=0;if(n+=r&ht,r<dt)return n;if(n+=((r=e.get(t+1))&ht)<<7,r<dt)return n;if(n+=((r=e.get(t+2))&ht)<<14,r<dt)return n;if(n+=((r=e.get(t+3))&ht)<<21,r<dt)return n;if(n+=((r=e.get(t+4))&ht)*st,r<dt)return n;if(n+=((r=e.get(t+5))&ht)*lt,r<dt)return n;if(n+=((r=e.get(t+6))&ht)*ct,r<dt)return n;if(n+=((r=e.get(t+7))&ht)*ut,r<dt)return n;throw new RangeError("Could not decode varint")}(e,t)}function mt(e,t){null==t&&(t=e.reduce(((e,t)=>e+t.length),0));var r=Ke(t),n=0;for(var i of e)r.set(i,n),n+=i.length;return r}var wt=new class{constructor(){e._defineProperty(this,"index",0),e._defineProperty(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 c=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===c)break;if(i*=e,(i+=c)>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 bt(e){if(!(e.length>15))return wt.new(e).parseWith((()=>wt.readIPv4Addr()))}function _t(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return wt.new(e).parseWith((()=>wt.readIPv6Addr()))}function St(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45)){var r=wt.new(e).parseWith((()=>wt.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 Pt(e){return Boolean(bt(e))}function Et(e){return Boolean(_t(e))}function At(e){return t=>Ze(t,e)}function kt(e){return t=>nt(t,e)}function xt(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function Tt(e){var t=new ArrayBuffer(2);return new DataView(t).setUint16(0,"string"==typeof e?parseInt(e):e),new Uint8Array(t)}function It(e){var t=e.subarray(0,e.length-2),r=e.subarray(e.length-2),n=Ze(t,"base32"),i=xt(r);return"".concat(n,":").concat(i)}var Ct=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 $e("Invalid byte value in IP address");t[r]=n})),t};var Bt,Nt=Object.values(qe).map((e=>e.decoder)),Dt=(Bt=Nt[0].or(Nt[1]),Nt.slice(2).forEach((e=>Bt=Bt.or(e))),Bt);var Gt,Rt=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 Xe("Value must be an integer")}),(function(e){if(e<0)throw new Xe("Value must be a positive integer, or zero")}),(Gt=65535,e=>{if(e>Gt)throw new Xe("Value must be smaller than or equal to ".concat(Gt))})),Ot=-1;var Lt=new class{constructor(){e._defineProperty(this,"protocolsByCode",new Map),e._defineProperty(this,"protocolsByName",new Map)}getProtocol(e){var t;if(null==(t="string"==typeof e?this.protocolsByName.get(e):this.protocolsByCode.get(e)))throw new tt("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)})))}},Mt=[{code:4,name:"ip4",size:32,valueToBytes:Ct,bytesToValue:function(e){if(4!==e.byteLength)throw new $e("IPv4 address was incorrect length");for(var t=[],r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},validate:e=>{if(!Pt(e))throw new Xe('Invalid IPv4 address "'.concat(e,'"'))}},{code:6,name:"tcp",size:16,valueToBytes:Tt,bytesToValue:xt,validate:Rt},{code:273,name:"udp",size:16,valueToBytes:Tt,bytesToValue:xt,validate:Rt},{code:33,name:"dccp",size:16,valueToBytes:Tt,bytesToValue:xt,validate:Rt},{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;Pt(n[t])&&(i=Ct(n[t]),n[t]=Ze(i.subarray(0,2),"base16")),null!=i&&++t<8&&n.splice(t,0,Ze(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 $e("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 $e("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 $e('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 $e('Invalid IPv6 address "'.concat(e,'"'))}},validate:e=>{if(!Et(e))throw new Xe('Invalid IPv6 address "'.concat(e,'"'))}},{code:42,name:"ip6zone",size:Ot},{code:43,name:"ipcidr",size:8,bytesToValue:At("base10"),valueToBytes:kt("base10")},{code:53,name:"dns",size:Ot,resolvable:!0},{code:54,name:"dns4",size:Ot,resolvable:!0},{code:55,name:"dns6",size:Ot,resolvable:!0},{code:56,name:"dnsaddr",size:Ot,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Tt,bytesToValue:xt,validate:Rt},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Ot,path:!0,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:Ot,bytesToValue:At("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?kt("base58btc")(e):je.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:It,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=nt(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=Tt(n);return mt([r,i],r.length+i.length)}},{code:445,name:"onion3",size:296,bytesToValue:It,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=Tt(n);return mt([r,i],r.length+i.length)}},{code:446,name:"garlic64",size:Ot},{code:447,name:"garlic32",size:Ot},{code:448,name:"tls"},{code:449,name:"sni",size:Ot},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Ot,bytesToValue:function(e){return t=>e.encoder.encode(t)}(q),valueToBytes:function(e){return Dt.decode(e)}},{code:480,name:"http"},{code:481,name:"http-path",size:Ot,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:Ot}];function jt(e,t,r){return null==e.size||0===e.size?0:e.size>0?e.size/8:gt(t,r)}Mt.forEach((e=>{Lt.addProtocol(e)}));var Ft=Symbol.for("nodejs.util.inspect.custom"),Ut=Symbol.for("@multiformats/multiaddr"),zt=[53,54,55,56];class Vt extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No available resolver"),this.name="NoAvailableResolverError"}}function qt(e){if(null==e&&(e="/"),rr(e))return e.getComponents();if(e instanceof Uint8Array)return function(e){for(var t=[],r=0;r<e.length;){var n=gt(e,r),i=Lt.getProtocol(n),o=pt(n),a=jt(i,e,r+o),s=0;a>0&&i.size===Ot&&(s=pt(a));var l=o+s+a,c={code:n,name:i.name,bytes:e.subarray(r,r+l)};if(a>0){var u,d,h=r+o+s,p=e.subarray(h,h+a);c.value=null!==(u=null===(d=i.bytesToValue)||void 0===d?void 0:d.call(i,p))&&void 0!==u?u:Ze(p)}t.push(c),r+=l}return t}(e);if("string"==typeof e)return""===(e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""))&&(e="/"),function(e){if("/"!==e.charAt(0))throw new $e('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=Lt.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 $e("Component ".concat(i," was missing value"));r="value"}else if("value"===r){var c={code:l.code,name:l.name};if(null!=l.size&&0!==l.size){var u,d;if(""===n)throw new $e("Component ".concat(i," was missing value"));c.value=null!==(u=null===(d=l.stringToValue)||void 0===d?void 0:d.call(l,n))&&void 0!==u?u:n}t.push(c),n="",i="",r="protocol"}}}if(""!==i&&""!==n)throw new $e("Incomplete multiaddr");return t}(e);if(Array.isArray(e))return e;throw new $e("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Ht=new WeakMap,Kt=new WeakMap,Wt=new WeakMap;class Qt{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/",r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,Ut,!0),e._classPrivateFieldInitSpec(this,Ht,void 0),e._classPrivateFieldInitSpec(this,Kt,void 0),e._classPrivateFieldInitSpec(this,Wt,void 0),e._classPrivateFieldSet2(Ht,this,qt(t)),!1!==r.validate&&function(e){e.getComponents().forEach((e=>{var t,r=Lt.getProtocol(e.code);null!=e.value&&(null===(t=r.validate)||void 0===t||t.call(r,e.value))}))}(this)}get bytes(){return null==e._classPrivateFieldGet2(Wt,this)&&e._classPrivateFieldSet2(Wt,this,function(e){var t=0,r=[];for(var n of e){if(null==n.bytes){var i,o,a=Lt.getProtocol(n.code),s=pt(n.code),l=void 0,c=0,u=0;null!=n.value&&(c=(l=null!==(i=null===(o=a.valueToBytes)||void 0===o?void 0:o.call(a,n.value))&&void 0!==i?i:nt(n.value)).byteLength,a.size===Ot&&(u=pt(c)));var d=new Uint8Array(s+u+c),h=0;ft(n.code,d,h),h+=s,null!=l&&(a.size===Ot&&(ft(c,d,h),h+=u),d.set(l,h)),n.bytes=d}r.push(n.bytes),t+=n.bytes.byteLength}return mt(r,t)}(e._classPrivateFieldGet2(Ht,this))),e._classPrivateFieldGet2(Wt,this)}toString(){var t;return null==e._classPrivateFieldGet2(Kt,this)&&e._classPrivateFieldSet2(Kt,this,(t=e._classPrivateFieldGet2(Ht,this),"/".concat(t.flatMap((e=>{var t,r;if(null==e.value)return e.name;var n=Lt.getProtocol(e.code);if(null==n)throw new $e("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("/")))),e._classPrivateFieldGet2(Kt,this)}toJSON(){return this.toString()}toOptions(){var t,r,n,i,o="";for(var{code:a,name:s,value:l}of e._classPrivateFieldGet2(Ht,this))42===a&&(o="%".concat(null!=l?l:"")),zt.includes(a)&&(r="tcp",i=443,n="".concat(null!=l?l:"").concat(o),t=55===a?6:4),6!==a&&273!==a||(r="tcp"===s?"tcp":"udp",i=parseInt(null!=l?l:"")),4!==a&&41!==a||(r="tcp",n="".concat(null!=l?l:"").concat(o),t=41===a?6:4);if(null==t||null==r||null==n||null==i)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:r,port:i}}getComponents(){return[...e._classPrivateFieldGet2(Ht,this)]}protos(){return e._classPrivateFieldGet2(Ht,this).map((e=>{var t,{code:r,value:n}=e,i=Lt.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 e._classPrivateFieldGet2(Ht,this).map((e=>{var{code:t}=e;return t}))}protoNames(){return e._classPrivateFieldGet2(Ht,this).map((e=>{var{name:t}=e;return t}))}tuples(){return e._classPrivateFieldGet2(Ht,this).map((e=>{var{code:t,value:r}=e;if(null==r)return[t];var n,i,o=Lt.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:nt(r));return a}))}stringTuples(){return e._classPrivateFieldGet2(Ht,this).map((e=>{var{code:t,value:r}=e;return null==r?[t]:[t,r]}))}encapsulate(t){var r=new Qt(t);return new Qt([...e._classPrivateFieldGet2(Ht,this),...r.getComponents()],{validate:!1})}decapsulate(e){var t=e.toString(),r=this.toString(),n=r.lastIndexOf(t);if(n<0)throw new et("Address ".concat(this.toString()," does not contain subaddress: ").concat(e.toString()));return new Qt(r.slice(0,n),{validate:!1})}decapsulateCode(t){for(var r,n=e._classPrivateFieldGet2(Ht,this).length-1;n>-1;n--)if(e._classPrivateFieldGet2(Ht,this)[n].code===t){r=n;break}return new Qt(e._classPrivateFieldGet2(Ht,this).slice(0,r),{validate:!1})}getPeerId(){try{var t=[];e._classPrivateFieldGet2(Ht,this).forEach((e=>{var{code:r,value:n}=e;421===r&&t.push([r,n]),290===r&&(t=[])}));var r=t.pop();if(null!=(null==r?void 0:r[1])){var n=r[1];return"Q"===n[0]||"1"===n[0]?Ze(j.decode("z".concat(n)),"base58btc"):Ze(je.parse(n).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){for(var t of e._classPrivateFieldGet2(Ht,this)){var r;if(Lt.getProtocol(t.code).path)return null!==(r=t.value)&&void 0!==r?r:null}return null}equals(e){return rt(this.bytes,e.bytes)}resolve(t){var r=this;return e._asyncToGenerator((function*(){var e=r.protos().find((e=>e.resolvable));if(null==e)return[r];var n=tr.get(e.name);if(null==n)throw new Vt("no available resolver for ".concat(e.name));return(yield n(r,t)).map((e=>nr(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===e._classPrivateFieldGet2(Ht,this).length&&((4===e._classPrivateFieldGet2(Ht,this)[0].code||41===e._classPrivateFieldGet2(Ht,this)[0].code)&&(6===e._classPrivateFieldGet2(Ht,this)[1].code||273===e._classPrivateFieldGet2(Ht,this)[1].code))}[Ft](){return"Multiaddr(".concat(this.toString(),")")}}var Yt=4,Jt=16,Zt=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function $t(e,t){t.length===Jt&&e.length===Yt&&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===Yt&&e.length===Jt&&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,Zt,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 Xt(e,t){if(t!==8*Yt&&t!==8*Jt)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 er{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=Yt,i=bt(t);if(null==i&&(n=Jt,null==(i=_t(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=Xt(o,8*n);return{network:$t(i,a),mask:a}}(e));else{var r=St(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=St(t);if(null==i)throw new Error("Failed to parse mask");this.mask=i}else this.mask=Xt(n,8*r.length);this.network=$t(r,this.mask)}}contains(e){return function(e,t){if("string"==typeof t&&(t=St(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 Yt:return e.join(".");case Jt: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 tr=new Map;function rr(e){return Boolean(null==e?void 0:e[Ut])}function nr(e){return new Qt(e)}function ir(e){var t,r=Lt.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 or="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function ar(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function sr(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 lr(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");ar(e.outputLen),ar(e.blockLen)}function cr(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 ur(e,t){sr(e);var r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function dr(){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 hr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function pr(e,t){return e<<32-t|e>>>t}function fr(e,t){return e<<t|e>>>32-t>>>0}var vr=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function yr(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}var gr=vr?e=>e:e=>yr(e);var mr=vr?e=>e:function(e){for(var t=0;t<e.length;t++)e[t]=yr(e[t]);return e},wr=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),br=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));var _r=48,Sr=57,Pr=65,Er=70,Ar=97,kr=102;function xr(e){return e>=_r&&e<=Sr?e-_r:e>=Pr&&e<=Er?e-(Pr-10):e>=Ar&&e<=kr?e-(Ar-10):void 0}var Tr=function(){var t=e._asyncToGenerator((function*(){}));return function(){return t.apply(this,arguments)}}();function Ir(){return Ir=e._asyncToGenerator((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 Tr(),n+=o)}})),Ir.apply(this,arguments)}function Cr(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function Br(e){return"string"==typeof e&&(e=Cr(e)),sr(e),e}function Nr(e){return"string"==typeof e&&(e=Cr(e)),sr(e),e}function Dr(){for(var e=0,t=0;t<arguments.length;t++){var r=t<0||arguments.length<=t?void 0:arguments[t];sr(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 Gr{}function Rr(e){var t=t=>e().update(Br(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Or(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:32;if(or&&"function"==typeof or.getRandomValues)return or.getRandomValues(new Uint8Array(e));if(or&&"function"==typeof or.randomBytes)return Uint8Array.from(or.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Lr(e,t,r){return e&t^~e&r}function Mr(e,t,r){return e&t^e&r^t&r}class jr extends Gr{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=hr(this.buffer)}update(e){cr(this),sr(e=Br(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=hr(e);n<=i-o;o+=n)this.process(s,o)}return this.length+=e.length,this.roundClean(),this}digestInto(e){cr(this),ur(e,this),this.finished=!0;var{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,dr(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,c=n?0:4;e.setUint32(t+l,a,n),e.setUint32(t+c,s,n)}(r,n-8,BigInt(8*this.length),i),this.process(r,0);var s=hr(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");var c=l/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(var d=0;d<c;d++)s.setUint32(4*d,u[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 Fr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ur=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),zr=BigInt(2**32-1),Vr=BigInt(32);function qr(e){return arguments.length>1&&void 0!==arguments[1]&&arguments[1]?{h:Number(e&zr),l:Number(e>>Vr&zr)}:{h:0|Number(e>>Vr&zr),l:0|Number(e&zr)}}function Hr(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}=qr(e[o],t);[n[o],i[o]]=[a,s]}return[n,i]}var Kr=(e,t,r)=>e>>>r,Wr=(e,t,r)=>e<<32-r|t>>>r,Qr=(e,t,r)=>e>>>r|t<<32-r,Yr=(e,t,r)=>e<<32-r|t>>>r,Jr=(e,t,r)=>e<<64-r|t>>>r-32,Zr=(e,t,r)=>e>>>r-32|t<<64-r;function $r(e,t,r,n){var i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:0|i}}var Xr=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),en=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,tn=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),rn=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,nn=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),on=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,an=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]),sn=new Uint32Array(64);class ln extends jr{constructor(){super(64,arguments.length>0&&void 0!==arguments[0]?arguments[0]:32,8,!1),this.A=0|Fr[0],this.B=0|Fr[1],this.C=0|Fr[2],this.D=0|Fr[3],this.E=0|Fr[4],this.F=0|Fr[5],this.G=0|Fr[6],this.H=0|Fr[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)sn[r]=e.getUint32(t,!1);for(var n=16;n<64;n++){var i=sn[n-15],o=sn[n-2],a=pr(i,7)^pr(i,18)^i>>>3,s=pr(o,17)^pr(o,19)^o>>>10;sn[n]=s+sn[n-7]+a+sn[n-16]|0}for(var{A:l,B:c,C:u,D:d,E:h,F:p,G:f,H:v}=this,y=0;y<64;y++){var g=v+(pr(h,6)^pr(h,11)^pr(h,25))+Lr(h,p,f)+an[y]+sn[y]|0,m=(pr(l,2)^pr(l,13)^pr(l,22))+Mr(l,c,u)|0;v=f,f=p,p=h,h=d+g|0,d=u,u=c,c=l,l=g+m|0}l=l+this.A|0,c=c+this.B|0,u=u+this.C|0,d=d+this.D|0,h=h+this.E|0,p=p+this.F|0,f=f+this.G|0,v=v+this.H|0,this.set(l,c,u,d,h,p,f,v)}roundClean(){dr(sn)}destroy(){this.set(0,0,0,0,0,0,0,0),dr(this.buffer)}}var cn=(()=>Hr(["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)))))(),un=(()=>cn[0])(),dn=(()=>cn[1])(),hn=new Uint32Array(80),pn=new Uint32Array(80);class fn extends jr{constructor(){super(128,arguments.length>0&&void 0!==arguments[0]?arguments[0]:64,16,!1),this.Ah=0|Ur[0],this.Al=0|Ur[1],this.Bh=0|Ur[2],this.Bl=0|Ur[3],this.Ch=0|Ur[4],this.Cl=0|Ur[5],this.Dh=0|Ur[6],this.Dl=0|Ur[7],this.Eh=0|Ur[8],this.El=0|Ur[9],this.Fh=0|Ur[10],this.Fl=0|Ur[11],this.Gh=0|Ur[12],this.Gl=0|Ur[13],this.Hh=0|Ur[14],this.Hl=0|Ur[15]}get(){var{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:o,Dh:a,Dl:s,Eh:l,El:c,Fh:u,Fl:d,Gh:h,Gl:p,Hh:f,Hl:v}=this;return[e,t,r,n,i,o,a,s,l,c,u,d,h,p,f,v]}set(e,t,r,n,i,o,a,s,l,c,u,d,h,p,f,v){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|c,this.Fh=0|u,this.Fl=0|d,this.Gh=0|h,this.Gl=0|p,this.Hh=0|f,this.Hl=0|v}process(e,t){for(var r=0;r<16;r++,t+=4)hn[r]=e.getUint32(t),pn[r]=e.getUint32(t+=4);for(var n=16;n<80;n++){var i=0|hn[n-15],o=0|pn[n-15],a=Qr(i,o,1)^Qr(i,o,8)^Kr(i,0,7),s=Yr(i,o,1)^Yr(i,o,8)^Wr(i,o,7),l=0|hn[n-2],c=0|pn[n-2],u=Qr(l,c,19)^Jr(l,c,61)^Kr(l,0,6),d=Yr(l,c,19)^Zr(l,c,61)^Wr(l,c,6),h=tn(s,d,pn[n-7],pn[n-16]),p=rn(h,a,u,hn[n-7],hn[n-16]);hn[n]=0|p,pn[n]=0|h}for(var{Ah:f,Al:v,Bh:y,Bl:g,Ch:m,Cl:w,Dh:b,Dl:_,Eh:S,El:P,Fh:E,Fl:A,Gh:k,Gl:x,Hh:T,Hl:I}=this,C=0;C<80;C++){var B=Qr(S,P,14)^Qr(S,P,18)^Jr(S,P,41),N=Yr(S,P,14)^Yr(S,P,18)^Zr(S,P,41),D=S&E^~S&k,G=nn(I,N,P&A^~P&x,dn[C],pn[C]),R=on(G,T,B,D,un[C],hn[C]),O=0|G,L=Qr(f,v,28)^Jr(f,v,34)^Jr(f,v,39),M=Yr(f,v,28)^Zr(f,v,34)^Zr(f,v,39),j=f&y^f&m^y&m,F=v&g^v&w^g&w;T=0|k,I=0|x,k=0|E,x=0|A,E=0|S,A=0|P,({h:S,l:P}=$r(0|b,0|_,0|R,0|O)),b=0|m,_=0|w,m=0|y,w=0|g,y=0|f,g=0|v;var U=Xr(O,M,F);f=en(U,R,L,j),v=0|U}({h:f,l:v}=$r(0|this.Ah,0|this.Al,0|f,0|v)),({h:y,l:g}=$r(0|this.Bh,0|this.Bl,0|y,0|g)),({h:m,l:w}=$r(0|this.Ch,0|this.Cl,0|m,0|w)),({h:b,l:_}=$r(0|this.Dh,0|this.Dl,0|b,0|_)),({h:S,l:P}=$r(0|this.Eh,0|this.El,0|S,0|P)),({h:E,l:A}=$r(0|this.Fh,0|this.Fl,0|E,0|A)),({h:k,l:x}=$r(0|this.Gh,0|this.Gl,0|k,0|x)),({h:T,l:I}=$r(0|this.Hh,0|this.Hl,0|T,0|I)),this.set(f,v,y,g,m,w,b,_,S,P,E,A,k,x,T,I)}roundClean(){dr(hn,pn)}destroy(){dr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}var vn=Rr((()=>new ln)),yn=Rr((()=>new fn));class gn extends Gr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,lr(e);var r=Br(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),dr(i)}update(e){return cr(this),this.iHash.update(e),this}digestInto(e){cr(this),sr(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 mn=(e,t,r)=>new gn(e,t).update(r).digest();mn.create=(e,t)=>new gn(e,t);var wn=BigInt(0),bn=BigInt(1);function _n(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Sn(e){if(!_n(e))throw new Error("Uint8Array expected")}function Pn(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}function En(e){var t=e.toString(16);return 1&t.length?"0"+t:t}function An(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?wn:BigInt("0x"+e)}var kn="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,xn=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Tn(e){if(Sn(e),kn)return e.toHex();for(var t="",r=0;r<e.length;r++)t+=xn[e[r]];return t}var In=48,Cn=57,Bn=65,Nn=70,Dn=97,Gn=102;function Rn(e){return e>=In&&e<=Cn?e-In:e>=Bn&&e<=Nn?e-(Bn-10):e>=Dn&&e<=Gn?e-(Dn-10):void 0}function On(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(kn)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=Rn(e.charCodeAt(o)),s=Rn(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 Ln(e){return An(Tn(e))}function Mn(e){return Sn(e),An(Tn(Uint8Array.from(e).reverse()))}function jn(e,t){return On(e.toString(16).padStart(2*t,"0"))}function Fn(e,t){return jn(e,t).reverse()}function Un(e,t,r){var n;if("string"==typeof t)try{n=On(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!_n(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 zn(){for(var e=0,t=0;t<arguments.length;t++){var r=t<0||arguments.length<=t?void 0:arguments[t];Sn(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 Vn=e=>"bigint"==typeof e&&wn<=e;function qn(e,t,r){return Vn(e)&&Vn(t)&&Vn(r)&&t<=e&&e<r}function Hn(e,t,r,n){if(!qn(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}var Kn=e=>(bn<<BigInt(e))-bn,Wn=e=>new Uint8Array(e),Qn=e=>Uint8Array.from(e);var Yn={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||_n(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 Jn(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=(t,r,n)=>{var i=Yn[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 Zn(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 $n=BigInt(0),Xn=BigInt(1),ei=BigInt(2),ti=BigInt(3),ri=BigInt(4),ni=BigInt(5),ii=BigInt(8);function oi(e,t){var r=e%t;return r>=$n?r:t+r}function ai(e,t,r){for(var n=e;t-- >$n;)n*=n,n%=r;return n}function si(e,t){if(e===$n)throw new Error("invert: expected non-zero number");if(t<=$n)throw new Error("invert: expected positive modulus, got "+t);for(var r=oi(e,t),n=t,i=$n,o=Xn;r!==$n;){var a=n%r,s=i-o*(n/r);n=r,r=a,i=o,o=s}if(n!==Xn)throw new Error("invert: does not exist");return oi(i,t)}function li(e,t){var r=(e.ORDER+Xn)/ri,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function ci(e,t){var r=(e.ORDER-ni)/ii,n=e.mul(t,ei),i=e.pow(n,r),o=e.mul(t,i),a=e.mul(e.mul(o,ei),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 ui(e){return e%ri===ti?li:e%ii===ni?ci:function(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");for(var t=e-Xn,r=0;t%ei===$n;)t/=ei,r++;for(var n=ei,i=vi(e);1===pi(i,n);)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===r)return li;var o=i.pow(n,t),a=(t+Xn)/ei;return function(e,n){if(e.is0(n))return n;if(1!==pi(e,n))throw new Error("Cannot find square root");for(var i=r,s=e.mul(e.ONE,o),l=e.pow(n,t),c=e.pow(n,a);!e.eql(l,e.ONE);){if(e.is0(l))return e.ZERO;for(var u=1,d=e.sqr(l);!e.eql(d,e.ONE);)if(u++,d=e.sqr(d),u===i)throw new Error("Cannot find square root");var h=Xn<<BigInt(i-u-1),p=e.pow(s,h);i=u,s=e.sqr(p),l=e.mul(l,s),c=e.mul(c,p)}return c}}(e)}var di=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hi(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 pi(e,t){var r=(e.ORDER-Xn)/ei,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 fi(e,t){void 0!==t&&ar(t);var r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function vi(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<=$n)throw new Error("invalid field: expected ORDER > 0, got "+e);var i,{nBitLength:o,nByteLength:a}=fi(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:Kn(o),ZERO:$n,ONE:Xn,create:t=>oi(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return $n<=t&&t<e},is0:e=>e===$n,isOdd:e=>(e&Xn)===Xn,neg:t=>oi(-t,e),eql:(e,t)=>e===t,sqr:t=>oi(t*t,e),add:(t,r)=>oi(t+r,e),sub:(t,r)=>oi(t-r,e),mul:(t,r)=>oi(t*r,e),pow:(e,t)=>function(e,t,r){if(r<$n)throw new Error("invalid exponent, negatives unsupported");if(r===$n)return e.ONE;if(r===Xn)return t;for(var n=e.ONE,i=t;r>$n;)r&Xn&&(n=e.mul(n,i)),i=e.sqr(i),r>>=Xn;return n}(s,e,t),div:(t,r)=>oi(t*si(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>si(t,e),sqrt:n.sqrt||(t=>(i||(i=ui(e)),i(s,t))),toBytes:e=>r?Fn(e,a):jn(e,a),fromBytes:e=>{if(e.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+e.length);return r?Mn(e):Ln(e)},invertBatch:e=>hi(s,e),cmov:(e,t,r)=>r?t:e});return Object.freeze(s)}function yi(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 gi(e){var t=yi(e);return t+Math.ceil(t/2)}var mi=BigInt(0),wi=BigInt(1);function bi(e,t){var r=t.negate();return e?r:t}function _i(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Si(e,t){_i(e,t);var r=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Kn(e),maxNumber:r,shiftBy:BigInt(e)}}function Pi(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+=wi);var c=t*n;return{nextN:l,offset:c+Math.abs(s)-1,isZero:0===s,isNeg:s<0,isNegF:t%2!=0,offsetF:c}}var Ei=new WeakMap,Ai=new WeakMap;function ki(e){return Ai.get(e)||1}function xi(e,t){return{constTimeNegate:bi,hasPrecomputes:e=>1!==ki(e),unsafeLadder(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.ZERO,i=t;r>mi;)r&wi&&(n=n.add(i)),i=i.double(),r>>=wi;return n},precomputeWindow(e,r){for(var{windows:n,windowSize:i}=Si(r,t),o=[],a=e,s=a,l=0;l<n;l++){s=a,o.push(s);for(var c=1;c<i;c++)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=Si(r,t),l=0;l<s.windows;l++){var{nextN:c,offset:u,isZero:d,isNeg:h,isNegF:p,offsetF:f}=Pi(i,l,s);i=c,d?a=a.add(bi(p,n[f])):o=o.add(bi(h,n[u]))}return{p:o,f:a}},wNAFUnsafe(r,n,i){for(var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e.ZERO,a=Si(r,t),s=0;s<a.windows&&i!==mi;s++){var{nextN:l,offset:c,isZero:u,isNeg:d}=Pi(i,s,a);if(i=l,!u){var h=n[c];o=o.add(d?h.negate():h)}}return o},getPrecomputes(e,t,r){var n=Ei.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&Ei.set(t,r(n))),n},wNAFCached(e,t,r){var n=ki(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)},wNAFCachedUnsafe(e,t,r,n){var i=ki(e);return 1===i?this.unsafeLadder(e,t,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),t,n)},setWindowSize(e,r){_i(r,t),Ai.set(e,r),Ei.delete(e)}}}function Ti(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>wn;e>>=bn,t+=1);return t}(BigInt(i)),l=1;s>12?l=s-3:s>4?l=s-2:s>0&&(l=2);for(var c=Kn(l),u=new Array(Number(c)+1).fill(a),d=a,h=Math.floor((t.BITS-1)/l)*l;h>=0;h-=l){u.fill(a);for(var p=0;p<o;p++){var f=n[p],v=Number(f>>BigInt(h)&c);u[v]=u[v].add(r[p])}for(var y=a,g=u.length-1,m=a;g>0;g--)m=m.add(u[g]),y=y.add(m);if(d=d.add(y),0!==h)for(var w=0;w<l;w++)d=d.double()}return d}function Ii(t){var r,n;return r=t.Fp,n=di.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"}),Jn(r,n),Jn(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze(e._objectSpread2(e._objectSpread2(e._objectSpread2({},fi(t.n,t.nBitLength)),t),{p:t.Fp.ORDER}))}function Ci(e){void 0!==e.lowS&&Pn("lowS",e.lowS),void 0!==e.prehash&&Pn("prehash",e.prehash)}class Bi extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"")}}var Ni={Err:Bi,_tlv:{encode:(e,t)=>{var{Err:r}=Ni;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=En(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");var o=n>127?En(i.length/2|128):"";return En(e)+o+i+t},decode(e,t){var{Err:r}=Ni,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 c=t.subarray(n,n+o);if(c.length!==o)throw new r("tlv.decode: wrong value length");return{v:c,l:t.subarray(n+o)}}},_int:{encode(e){var{Err:t}=Ni;if(e<Gi)throw new t("integer: negative integers are not allowed");var r=En(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}=Ni;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 Ln(e)}},toSig(e){var{Err:t,_int:r,_tlv:n}=Ni,i=Un("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:c,l:u}=n.decode(2,l);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(s),s:r.decode(c)}},hexFromSig(e){var{_tlv:t,_int:r}=Ni,n=t.encode(2,r.encode(e.r))+t.encode(2,r.encode(e.s));return t.encode(48,n)}};function Di(e,t){return Tn(jn(e,t))}var Gi=BigInt(0),Ri=BigInt(1);BigInt(2);var Oi=BigInt(3),Li=BigInt(4);function Mi(t){var r=function(t){var r=Ii(t);Jn(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(e._objectSpread2({},r))}(t),{Fp:n}=r,i=vi(r.n,r.nBitLength),o=r.toBytes||((e,t,r)=>{var i=t.toAffine();return zn(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 c=n.mul(n.pow(r.a,Oi),Li),u=n.mul(n.sqr(r.b),BigInt(27));if(n.is0(n.add(c,u)))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(_n(e)&&(e=Tn(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:Ln(Un("private key",e,i))}catch(t){throw new Error("invalid private key, expected hex or "+i+" bytes, got "+typeof e)}return o&&(t=oi(t,a)),Hn("private key",t,Ri,a),t}function h(e){if(!(e instanceof v))throw new Error("ProjectivePoint expected")}var p=Zn(((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),c=n.mul(o,t);if(a)return{x:n.ZERO,y:n.ZERO};if(!n.eql(c,n.ONE))throw new Error("invZ was invalid");return{x:s,y:l}})),f=Zn((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 v{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 v)throw new Error("projective point not allowed");var i=e=>n.eql(e,n.ZERO);return i(t)&&i(r)?v.ZERO:new v(t,r,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){var t=hi(n,e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(v.fromAffine)}static fromHex(e){var t=v.fromAffine(a(Un("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return v.BASE.multiply(d(e))}static msm(e,t){return Ti(v,i,e,t)}_setWindowSize(e){m.setWindowSize(this,e)}assertValidity(){f(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)),c=n.eql(n.mul(r,s),n.mul(a,i));return l&&c}negate(){return new v(this.px,n.neg(this.py),this.pz)}double(){var{a:e,b:t}=r,i=n.mul(t,Oi),{px:o,py:a,pz:s}=this,l=n.ZERO,c=n.ZERO,u=n.ZERO,d=n.mul(o,o),h=n.mul(a,a),p=n.mul(s,s),f=n.mul(o,a);return f=n.add(f,f),u=n.mul(o,s),u=n.add(u,u),l=n.mul(e,u),c=n.mul(i,p),c=n.add(l,c),l=n.sub(h,c),c=n.add(h,c),c=n.mul(l,c),l=n.mul(f,l),u=n.mul(i,u),p=n.mul(e,p),f=n.sub(d,p),f=n.mul(e,f),f=n.add(f,u),u=n.add(d,d),d=n.add(u,d),d=n.add(d,p),d=n.mul(d,f),c=n.add(c,d),p=n.mul(a,s),p=n.add(p,p),d=n.mul(p,f),l=n.sub(l,d),u=n.mul(p,h),u=n.add(u,u),u=n.add(u,u),new v(l,c,u)}add(e){h(e);var{px:t,py:i,pz:o}=this,{px:a,py:s,pz:l}=e,c=n.ZERO,u=n.ZERO,d=n.ZERO,p=r.a,f=n.mul(r.b,Oi),y=n.mul(t,a),g=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(y,g),w=n.sub(w,b),b=n.add(t,o);var _=n.add(a,l);return b=n.mul(b,_),_=n.add(y,m),b=n.sub(b,_),_=n.add(i,o),c=n.add(s,l),_=n.mul(_,c),c=n.add(g,m),_=n.sub(_,c),d=n.mul(p,b),c=n.mul(f,m),d=n.add(c,d),c=n.sub(g,d),d=n.add(g,d),u=n.mul(c,d),g=n.add(y,y),g=n.add(g,y),m=n.mul(p,m),b=n.mul(f,b),g=n.add(g,m),m=n.sub(y,m),m=n.mul(p,m),b=n.add(b,m),y=n.mul(g,b),u=n.add(u,y),y=n.mul(_,b),c=n.mul(w,c),c=n.sub(c,y),y=n.mul(w,g),d=n.mul(_,d),d=n.add(d,y),new v(c,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(v.ZERO)}wNAF(e){return m.wNAFCached(this,e,v.normalizeZ)}multiplyUnsafe(e){var{endo:t,n:i}=r;Hn("scalar",e,Gi,i);var o=v.ZERO;if(e===Gi)return o;if(this.is0()||e===Ri)return this;if(!t||m.hasPrecomputes(this))return m.wNAFCachedUnsafe(this,e,v.normalizeZ);for(var{k1neg:a,k1:s,k2neg:l,k2:c}=t.splitScalar(e),u=o,d=o,h=this;s>Gi||c>Gi;)s&Ri&&(u=u.add(h)),c&Ri&&(d=d.add(h)),h=h.double(),s>>=Ri,c>>=Ri;return a&&(u=u.negate()),l&&(d=d.negate()),d=new v(n.mul(d.px,t.beta),d.py,d.pz),u.add(d)}multiply(e){var t,i,{endo:o,n:a}=r;if(Hn("scalar",e,Ri,a),o){var{k1neg:s,k1:l,k2neg:c,k2:u}=o.splitScalar(e),{p:d,f:h}=this.wNAF(l),{p:p,f:f}=this.wNAF(u);d=m.constTimeNegate(s,d),p=m.constTimeNegate(c,p),p=new v(n.mul(p.px,o.beta),p.py,p.pz),t=d.add(p),i=h.add(f)}else{var{p:y,f:g}=this.wNAF(e);t=y,i=g}return v.normalizeZ([t,i])[0]}multiplyAndAddUnsafe(e,t,r){var n=v.BASE,i=(e,t)=>t!==Gi&&t!==Ri&&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 p(this,e)}isTorsionFree(){var{h:e,isTorsionFree:t}=r;if(e===Ri)return!0;if(t)return t(v,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){var{h:e,clearCofactor:t}=r;return e===Ri?this:t?t(v,this):this.multiplyUnsafe(r.h)}toRawBytes(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return Pn("isCompressed",e),this.assertValidity(),o(v,this,e)}toHex(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return Pn("isCompressed",e),Tn(this.toRawBytes(e))}}v.BASE=new v(r.Gx,r.Gy,n.ONE),v.ZERO=new v(n.ZERO,n.ONE,n.ZERO);var{endo:y,nBitLength:g}=r,m=xi(v,y?Math.ceil(g/2):g);return{CURVE:r,ProjectivePoint:v,normPrivateKeyToScalar:d,weierstrassEquation:s,isWithinCurveOrder:function(e){return qn(e,Ri,r.n)}}}function ji(t){var r,n=(Jn(r=Ii(t),{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze(e._objectSpread2({lowS:!0},r))),{Fp:i,n:o,nByteLength:a,nBitLength:s}=n,l=i.BYTES+1,c=2*i.BYTES+1;function u(e){return oi(e,o)}function d(e){return si(e,o)}var{ProjectivePoint:h,normPrivateKeyToScalar:p,weierstrassEquation:f,isWithinCurveOrder:v}=Mi(e._objectSpread2(e._objectSpread2({},n),{},{toBytes(e,t,r){var n=t.toAffine(),o=i.toBytes(n.x),a=zn;return Pn("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===c&&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 "+c+", got "+t)}var o=Ln(n);if(!qn(o,Ri,i.ORDER))throw new Error("Point is not on curve");var a,s=f(o);try{a=i.sqrt(s)}catch(e){var u=e instanceof Error?": "+e.message:"";throw new Error("Point is not on curve"+u)}return!(1&~r)!==((a&Ri)===Ri)&&(a=i.neg(a)),{x:o,y:a}}}));function y(e){return e>o>>Ri}var g=(e,t,r)=>Ln(e.slice(t,r));class m{constructor(e,t,r){Hn("r",e,Ri,o),Hn("s",t,Ri,o),this.r=e,this.s=t,null!=r&&(this.recovery=r),Object.freeze(this)}static fromCompact(e){var t=a;return e=Un("compactSignature",e,2*t),new m(g(e,0,t),g(e,t,2*t))}static fromDER(e){var{r:t,s:r}=Ni.toSig(Un("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=S(Un("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",c=h.fromHex(l+Di(s,i.BYTES)),p=d(s),f=u(-a*p),v=u(r*p),y=h.BASE.multiplyAndAddUnsafe(c,f,v);if(!y)throw new Error("point at infinify");return y.assertValidity(),y}hasHighS(){return y(this.s)}normalizeS(){return this.hasHighS()?new m(this.r,u(-this.s),this.recovery):this}toDERRawBytes(){return On(this.toDERHex())}toDERHex(){return Ni.hexFromSig(this)}toCompactRawBytes(){return On(this.toCompactHex())}toCompactHex(){var e=a;return Di(this.r,e)+Di(this.s,e)}}var w={isValidPrivateKey(e){try{return p(e),!0}catch(e){return!1}},normPrivateKeyToScalar:p,randomPrivateKey:()=>{var e=gi(n.n);return function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=e.length,i=yi(t),o=gi(t);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);var a=oi(r?Mn(e):Ln(e),t-Xn)+Xn;return r?Fn(a,i):jn(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=Un("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 _=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");var t=Ln(e),r=8*e.length-s;return r>0?t>>BigInt(r):t},S=n.bits2int_modN||function(e){return u(_(e))},P=Kn(s);function E(e){return Hn("num < 2^"+s,e,Gi,P),jn(e,a)}function A(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:k;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:c}=r;null==s&&(s=!0),e=Un("msgHash",e),Ci(r),l&&(e=Un("prehashed msgHash",o(e)));var f=S(e),g=p(t),w=[E(g),E(f)];if(null!=c&&!1!==c){var b=!0===c?a(i.BYTES):c;w.push(Un("extraEntropy",b))}var P=zn(...w),A=f;return{seed:P,k2sig:function(e){var t=_(e);if(v(t)){var r=d(t),n=h.BASE.multiply(t).toAffine(),i=u(n.x);if(i!==Gi){var o=u(r*u(A+i*g));if(o!==Gi){var a=(n.x===i?0:2)|Number(n.y&Ri),l=o;return s&&y(o)&&(l=function(e){return y(e)?u(-e):e}(o),a^=1),new m(i,l,a)}}}}}}var k={lowS:n.lowS,prehash:!1},x={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(p(e)).toRawBytes(r)},sign:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:k,{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=Wn(e),i=Wn(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]:Wn(0);i=s(Qn([0]),e),n=s(),0!==e.length&&(i=s(Qn([1]),e),n=s())},c=()=>{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 zn(...r)};return(e,t)=>{a(),l(e);for(var r=void 0;!(r=t(c()));)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]:x,a=e;t=Un("msgHash",t),r=Un("publicKey",r);var{lowS:s,prehash:l,format:c}=o;if(Ci(o),"strict"in o)throw new Error("options.strict was renamed to lowS");if(void 0!==c&&"compact"!==c&&"der"!==c)throw new Error("format must be compact or der");var p="string"==typeof a||_n(a),f=!p&&!c&&"object"==typeof a&&null!==a&&"bigint"==typeof a.r&&"bigint"==typeof a.s;if(!p&&!f)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");var v,y=void 0;try{if(f&&(y=new m(a.r,a.s)),p){try{"compact"!==c&&(y=m.fromDER(a))}catch(e){if(!(e instanceof Ni.Err))throw e}y||"der"===c||(y=m.fromCompact(a))}v=h.fromHex(r)}catch(e){return!1}if(!y)return!1;if(s&&y.hasHighS())return!1;l&&(t=n.hash(t));var{r:g,s:w}=y,b=S(t),_=d(w),P=u(b*_),E=u(g*_),A=null===(i=h.BASE.multiplyAndAddUnsafe(v,P,E))||void 0===i?void 0:i.toAffine();return!!A&&u(A.x)===g},ProjectivePoint:h,Signature:m,utils:w}}var Fi=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Ui=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),zi=BigInt(0),Vi=BigInt(1),qi=BigInt(2),Hi=(e,t)=>(e+t/qi)/t;var Ki=vi(Fi,void 0,void 0,{sqrt:function(e){var t=Fi,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),a=BigInt(23),s=BigInt(44),l=BigInt(88),c=e*e*e%t,u=c*c*e%t,d=ai(u,r,t)*u%t,h=ai(d,r,t)*u%t,p=ai(h,qi,t)*c%t,f=ai(p,i,t)*p%t,v=ai(f,o,t)*f%t,y=ai(v,s,t)*v%t,g=ai(y,l,t)*y%t,m=ai(g,s,t)*v%t,w=ai(m,r,t)*u%t,b=ai(w,a,t)*f%t,_=ai(b,n,t)*c%t,S=ai(_,qi,t);if(!Ki.eql(Ki.sqr(S),e))throw new Error("Cannot find square root");return S}}),Wi=function(t,r){var n=r=>ji(e._objectSpread2(e._objectSpread2({},t),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 mn(e,t,Dr(...n))},randomBytes:Or}}(r)));return e._objectSpread2(e._objectSpread2({},n(r)),{},{create:n})}({a:zi,b:BigInt(7),Fp:Ki,n:Ui,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{var t=Ui,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Vi*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,a=BigInt("0x100000000000000000000000000000000"),s=Hi(o*e,t),l=Hi(-n*e,t),c=oi(e-s*r-l*i,t),u=oi(-s*n-l*o,t),d=c>a,h=u>a;if(d&&(c=t-c),h&&(u=t-u),c>a||u>a)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:d,k1:c,k2neg:h,k2:u}}}},vn),Qi=BigInt(0),Yi=BigInt(1),Ji=BigInt(2),Zi=BigInt(8),$i={zip215:!0};function Xi(t){var r,n,i=(n=Ii(r=t),Jn(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze(e._objectSpread2({},n))),{Fp:o,n:a,prehash:s,hash:l,randomBytes:c,nByteLength:u,h:d}=i,h=Ji<<BigInt(8*u)-Yi,p=o.create,f=vi(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 v=i.uvRatio||((e,t)=>{try{return{isValid:!0,value:o.sqrt(e*o.inv(t))}}catch(e){return{isValid:!1,value:Qi}}}),y=i.adjustScalarBytes||(e=>e),g=i.domain||((e,t,r)=>{if(Pn("phflag",r),t.length||r)throw new Error("Contexts/pre-hash are not supported");return e});function m(e,t){Hn("coordinate "+e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2]?Yi:Qi,h)}function w(e){if(!(e instanceof S))throw new Error("ExtendedPoint expected")}var b=Zn(((e,t)=>{var{ex:r,ey:n,ez:i}=e,a=e.is0();null==t&&(t=a?Zi:o.inv(i));var s=p(r*t),l=p(n*t),c=p(i*t);if(a)return{x:Qi,y:Yi};if(c!==Yi)throw new Error("invZ was invalid");return{x:s,y:l}})),_=Zn((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=p(n*n),c=p(o*o),u=p(a*a),d=p(u*u),h=p(l*t);if(p(u*p(h+c))!==p(d+p(r*p(l*c))))throw new Error("bad point: equation left != right (1)");if(p(n*o)!==p(a*s))throw new Error("bad point: equation left != right (2)");return!0}));class S{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 S)throw new Error("extended point not allowed");var{x:t,y:r}=e||{};return m("x",t),m("y",r),new S(t,r,Yi,p(t*r))}static normalizeZ(e){var t=hi(o,e.map((e=>e.ez)));return e.map(((e,r)=>e.toAffine(t[r]))).map(S.fromAffine)}static msm(e,t){return Ti(S,f,e,t)}_setWindowSize(e){A.setWindowSize(this,e)}assertValidity(){_(this)}equals(e){w(e);var{ex:t,ey:r,ez:n}=this,{ex:i,ey:o,ez:a}=e,s=p(t*a),l=p(i*n),c=p(r*a),u=p(o*n);return s===l&&c===u}is0(){return this.equals(S.ZERO)}negate(){return new S(p(-this.ex),this.ey,this.ez,p(-this.et))}double(){var{a:e}=i,{ex:t,ey:r,ez:n}=this,o=p(t*t),a=p(r*r),s=p(Ji*p(n*n)),l=p(e*o),c=t+r,u=p(p(c*c)-o-a),d=l+a,h=d-s,f=l-a,v=p(u*h),y=p(d*f),g=p(u*f),m=p(h*d);return new S(v,y,m,g)}add(e){w(e);var{a:t,d:r}=i,{ex:n,ey:o,ez:a,et:s}=this,{ex:l,ey:c,ez:u,et:d}=e,h=p(n*l),f=p(o*c),v=p(s*r*d),y=p(a*u),g=p((n+o)*(l+c)-h-f),m=y-v,b=y+v,_=p(f-t*h),P=p(g*m),E=p(b*_),A=p(g*_),k=p(m*b);return new S(P,E,k,A)}subtract(e){return this.add(e.negate())}wNAF(e){return A.wNAFCached(this,e,S.normalizeZ)}multiply(e){var t=e;Hn("scalar",t,Yi,a);var{p:r,f:n}=this.wNAF(t);return S.normalizeZ([r,n])[0]}multiplyUnsafe(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:S.ZERO,r=e;return Hn("scalar",r,Qi,a),r===Qi?E:this.is0()||r===Yi?this:A.wNAFCachedUnsafe(this,r,S.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===Yi?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=Un("pointHex",e,a),Pn("zip215",t);var s=e.slice(),l=e[a-1];s[a-1]=-129&l;var c=Mn(s),u=t?h:o.ORDER;Hn("pointHex.y",c,Qi,u);var d=p(c*c),f=p(d-Yi),y=p(r*d-n),{isValid:g,value:m}=v(f,y);if(!g)throw new Error("Point.fromHex: invalid y coordinate");var w=(m&Yi)===Yi,b=!!(128&l);if(!t&&m===Qi&&b)throw new Error("Point.fromHex: x=0 and x_0=1");return b!==w&&(m=p(-m)),S.fromAffine({x:m,y:c})}static fromPrivateKey(e){var{scalar:t}=T(e);return P.multiply(t)}toRawBytes(){var{x:e,y:t}=this.toAffine(),r=Fn(t,o.BYTES);return r[r.length-1]|=e&Yi?128:0,r}toHex(){return Tn(this.toRawBytes())}}S.BASE=new S(i.Gx,i.Gy,Yi,p(i.Gx*i.Gy)),S.ZERO=new S(Qi,Yi,Yi,Qi);var{BASE:P,ZERO:E}=S,A=xi(S,8*u);function k(e){return oi(e,a)}function x(e){return k(Mn(e))}function T(e){var t=o.BYTES;e=Un("private key",e,t);var r=Un("hashed private key",l(e),2*t),n=y(r.slice(0,t));return{head:n,prefix:r.slice(t,2*t),scalar:x(n)}}function I(e){var{head:t,prefix:r,scalar:n}=T(e),i=P.multiply(n),o=i.toRawBytes();return{head:t,prefix:r,scalar:n,point:i,pointBytes:o}}function C(){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=zn(...r);return x(l(g(i,Un("context",e),!!s)))}var B=$i;P._setWindowSize(8);var N={getExtendedPublicKey:I,randomPrivateKey:()=>c(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]:S.BASE;return t._setWindowSize(e),t.multiply(BigInt(3)),t}};return{CURVE:i,getPublicKey:function(e){return I(e).pointBytes},sign:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e=Un("message",e),s&&(e=s(e));var{prefix:n,scalar:i,pointBytes:l}=I(t),c=C(r.context,n,e),u=P.multiply(c).toRawBytes(),d=k(c+C(r.context,u,l,e)*i);return Hn("signature.s",d,Qi,a),Un("result",zn(u,Fn(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=Un("signature",e,2*l),t=Un("message",t),r=Un("publicKey",r,l),void 0!==a&&Pn("zip215",a),s&&(t=s(t));var c,u,d,h=Mn(e.slice(l,2*l));try{c=S.fromHex(r,a),u=S.fromHex(e.slice(0,l),a),d=P.multiplyUnsafe(h)}catch(e){return!1}if(!a&&c.isSmallOrder())return!1;var p=C(i,u.toRawBytes(),c.toRawBytes(),t);return u.add(c.multiplyUnsafe(p)).subtract(d).clearCofactor().equals(S.ZERO)},ExtendedPoint:S,utils:N}}var eo=BigInt(0),to=BigInt(1),ro=BigInt(2);function no(t){var r,n=(Jn(r=t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze(e._objectSpread2({},r))),{P:i,type:o,adjustScalarBytes:a,powPminus2:s}=n,l="x25519"===o;if(!l&&"x448"!==o)throw new Error("invalid type");var c=l?255:448,u=l?32:56,d=l?BigInt(9):BigInt(5),h=l?BigInt(121665):BigInt(39081),p=l?ro**BigInt(254):ro**BigInt(447),f=l?BigInt(8)*ro**BigInt(251)-to:BigInt(4)*ro**BigInt(445)-to,v=p+f+to,y=e=>oi(e,i),g=m(d);function m(e){return Fn(y(e),u)}function w(e,t){var r=function(e,t){Hn("u",e,eo,i),Hn("scalar",t,p,v);for(var r=t,n=e,o=to,a=eo,l=e,u=to,d=eo,f=BigInt(c-1);f>=eo;f--){var g=r>>f&to;d^=g,({x_2:o,x_3:l}=_(d,o,l)),({x_2:a,x_3:u}=_(d,a,u)),d=g;var m=o+a,w=y(m*m),b=o-a,S=y(b*b),P=w-S,E=l+u,A=y((l-u)*m),k=y(E*b),x=A+k,T=A-k;l=y(x*x),u=y(n*y(T*T)),o=y(w*S),a=y(P*(w+y(h*P)))}({x_2:o,x_3:l}=_(d,o,l)),({x_2:a,x_3:u}=_(d,a,u));var I=s(a);return y(o*I)}(function(e){var t=Un("u coordinate",e,u);return l&&(t[31]&=127),y(Mn(t))}(t),function(e){return Mn(a(Un("scalar",e,u)))}(e));if(r===eo)throw new Error("invalid private or public key received");return m(r)}function b(e){return w(e,g)}function _(e,t,r){var n=y(e*(t-r));return{x_2:t=y(t-n),x_3:r=y(r+n)}}return{scalarMult:w,scalarMultBase:b,getSharedSecret:(e,t)=>w(e,t),getPublicKey:e=>b(e),utils:{randomPrivateKey:()=>n.randomBytes(u)},GuBytes:g.slice()}}var io=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),oo=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);var ao=BigInt(1),so=BigInt(2),lo=BigInt(3),co=BigInt(5),uo=BigInt(8);function ho(e){var t=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),o=io,a=e*e%o*e%o,s=ai(a,so,o)*a%o,l=ai(s,ao,o)*e%o,c=ai(l,co,o)*l%o,u=ai(c,t,o)*c%o,d=ai(u,r,o)*u%o,h=ai(d,n,o)*d%o,p=ai(h,i,o)*h%o,f=ai(p,i,o)*h%o,v=ai(f,t,o)*c%o;return{pow_p_5_8:ai(v,so,o)*e%o,b2:a}}function po(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function fo(e,t){var r=io,n=oi(t*t*t,r),i=oi(n*n*t,r),o=oi(e*n*ho(e*i).pow_p_5_8,r),a=oi(t*o*o,r),s=o,l=oi(o*oo,r),c=a===e,u=a===oi(-e,r),d=a===oi(-e*oo,r);return c&&(o=s),(u||d)&&(o=l),(oi(o,r)&Xn)===Xn&&(o=oi(-o,r)),{isValid:c||u,value:o}}var vo=(()=>vi(io,void 0,!0))(),yo=(()=>({a:vo.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:vo,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:uo,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:yn,randomBytes:Or,adjustScalarBytes:po,uvRatio:fo}))(),go=(()=>Xi(yo))(),mo=(()=>no({P:io,type:"x25519",powPminus2:e=>{var t=io,{pow_p_5_8:r,b2:n}=ho(e);return oi(ai(r,lo,t)*n,t)},adjustScalarBytes:po,randomBytes:Or}))(),wo=vn,bo=yn;function _o(e,t,r,n){lr(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(ar(o),ar(a),ar(s),o<1)throw new Error("iterations (c) should be >= 1");var l=Nr(t),c=Nr(r),u=new Uint8Array(a),d=mn.create(e,l),h=d._cloneInto().update(c);return{c:o,dkLen:a,asyncTick:s,DK:u,PRF:d,PRFSalt:h}}function So(e,t,r,n,i){return e.destroy(),t.destroy(),n&&n.destroy(),dr(i),r}function Po(e,t,r,n){return Eo.apply(this,arguments)}function Eo(){return Eo=e._asyncToGenerator((function*(e,t,r,n){for(var i,{c:o,dkLen:a,asyncTick:s,DK:l,PRF:c,PRFSalt:u}=_o(e,t,r,n),d=new Uint8Array(4),h=hr(d),p=new Uint8Array(c.outputLen),f=function*(){var e=l.subarray(y,y+c.outputLen);h.setInt32(0,v,!1),(i=u._cloneInto(i)).update(d).digestInto(p),e.set(p.subarray(0,e.length)),yield function(e,t,r){return Ir.apply(this,arguments)}(o-1,s,(()=>{c._cloneInto(i).update(p).digestInto(p);for(var t=0;t<e.length;t++)e[t]^=p[t]}))},v=1,y=0;y<a;v++,y+=c.outputLen)yield*f();return So(c,u,l,i,p)})),Eo.apply(this,arguments)}var Ao,ko={exports:{}};var xo=(Ao||(Ao=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,c,u=this._events[s],d=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),d){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,i),!0;case 5:return u.fn.call(u.context,t,n,i,o),!0;case 6:return u.fn.call(u.context,t,n,i,o,a),!0}for(c=1,l=new Array(d-1);c<d;c++)l[c-1]=arguments[c];u.fn.apply(u.context,l)}else{var h,p=u.length;for(c=0;c<p;c++)switch(u[c].once&&this.removeListener(e,u[c].fn,void 0,!0),d){case 1:u[c].fn.call(u[c].context);break;case 2:u[c].fn.call(u[c].context,t);break;case 3:u[c].fn.call(u[c].context,t,n);break;case 4:u[c].fn.call(u[c].context,t,n,i);break;default:if(!l)for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];u[c].fn.apply(u[c].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,c=[],u=s.length;l<u;l++)(s[l].fn!==t||i&&!s[l].once||n&&s[l].context!==n)&&c.push(s[l]);c.length?this._events[o]=1===c.length?c[0]:c: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}(ko)),ko.exports),To=e.getDefaultExportFromCjs(xo),Io=function(e,t){return Io=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])},Io(e,t)};function Co(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}Io(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function Bo(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 No(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 Do(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 Go(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 Ro(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 Oo(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(Ro(arguments[t]));return e}function Lo(e){return this instanceof Lo?(this.v=e,this):new Lo(e)}"function"==typeof SuppressedError&&SuppressedError;var Mo=Symbol.for("@libp2p/connection"),jo=Symbol.for("@libp2p/content-routing"),Fo=Symbol.for("@libp2p/peer-discovery"),Uo=Symbol.for("@libp2p/peer-id");function zo(e){return Boolean(null==e?void 0:e[Uo])}var Vo,qo=Symbol.for("@libp2p/peer-routing"),Ho="keep-alive",Ko=Symbol.for("@libp2p/transport");!function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"}(Vo||(Vo={}));let Wo=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The operation was aborted"),this.name="AbortError"}};e._defineProperty(Wo,"name","AbortError");class Qo extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unexpected Peer"),this.name="UnexpectedPeerError"}}e._defineProperty(Qo,"name","UnexpectedPeerError");let Yo=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid crypto exchange"),this.name="InvalidCryptoExchangeError"}};e._defineProperty(Yo,"name","InvalidCryptoExchangeError");let Jo=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid parameters"),this.name="InvalidParametersError"}};e._defineProperty(Jo,"name","InvalidParametersError");class Zo extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid public key"),this.name="InvalidPublicKeyError"}}e._defineProperty(Zo,"name","InvalidPublicKeyError");class $o extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid private key"),this.name="InvalidPrivateKeyError"}}e._defineProperty($o,"name","InvalidPrivateKeyError");class Xo extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unsupported operation"),this.name="UnsupportedOperationError"}}e._defineProperty(Xo,"name","UnsupportedOperationError");class ea extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The connection is closing"),this.name="ConnectionClosingError"}}e._defineProperty(ea,"name","ConnectionClosingError");class ta extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The connection is closed"),this.name="ConnectionClosedError"}}e._defineProperty(ta,"name","ConnectionClosedError");class ra extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Connection failed"),this.name="ConnectionFailedError"}}e._defineProperty(ra,"name","ConnectionFailedError");class na extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The muxer is closed"),this.name="MuxerClosedError"}}e._defineProperty(na,"name","MuxerClosedError");class ia extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The stream has been reset"),this.name="StreamResetError"}}e._defineProperty(ia,"name","StreamResetError");class oa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The stream is in an invalid state"),this.name="StreamStateError"}}e._defineProperty(oa,"name","StreamStateError");let aa=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not found"),this.name="NotFoundError"}};e._defineProperty(aa,"name","NotFoundError");class sa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid PeerID"),this.name="InvalidPeerIdError"}}e._defineProperty(sa,"name","InvalidPeerIdError");class la extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid multiaddr"),this.name="InvalidMultiaddrError"}}e._defineProperty(la,"name","InvalidMultiaddrError");class ca extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid CID"),this.name="InvalidCIDError"}}e._defineProperty(ca,"name","InvalidCIDError");class ua extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid Multihash"),this.name="InvalidMultihashError"}}e._defineProperty(ua,"name","InvalidMultihashError");class da extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unsupported protocol error"),this.name="UnsupportedProtocolError"}}e._defineProperty(da,"name","UnsupportedProtocolError");class ha extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid message"),this.name="InvalidMessageError"}}e._defineProperty(ha,"name","InvalidMessageError");class pa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Protocol error"),this.name="ProtocolError"}}e._defineProperty(pa,"name","ProtocolError");let fa=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Timed out"),this.name="TimeoutError"}};e._defineProperty(fa,"name","TimeoutError");class va extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not started"),this.name="NotStartedError"}}e._defineProperty(va,"name","NotStartedError");class ya extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Already started"),this.name="AlreadyStartedError"}}e._defineProperty(ya,"name","AlreadyStartedError");class ga extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Dial error"),this.name="DialError"}}e._defineProperty(ga,"name","DialError");class ma extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Listen error"),this.name="ListenError"}}e._defineProperty(ma,"name","ListenError");class wa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Limited connection"),this.name="LimitedConnectionError"}}e._defineProperty(wa,"name","LimitedConnectionError");class ba extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Too many inbound protocol streams"),this.name="TooManyInboundProtocolStreamsError"}}e._defineProperty(ba,"name","TooManyInboundProtocolStreamsError");class _a extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Too many outbound protocol streams"),this.name="TooManyOutboundProtocolStreamsError"}}e._defineProperty(_a,"name","TooManyOutboundProtocolStreamsError");class Sa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unsupported key type"),this.name="UnsupportedKeyTypeError"}}e._defineProperty(Sa,"name","UnsupportedKeyTypeError");class Pa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not implemented"),this.name="NotImplementedError"}}e._defineProperty(Pa,"name","NotImplementedError");var Ea=new WeakMap;let Aa=class extends EventTarget{constructor(){super(),e._classPrivateFieldInitSpec(this,Ea,new Map)}listenerCount(t){var r=e._classPrivateFieldGet2(Ea,this).get(t);return null==r?0:r.length}addEventListener(t,r,n){var i;super.addEventListener(t,r,n);var o=e._classPrivateFieldGet2(Ea,this).get(t);null==o&&(o=[],e._classPrivateFieldGet2(Ea,this).set(t,o)),o.push({callback:r,once:null!==(i=!0!==n&&!1!==n&&(null==n?void 0:n.once))&&void 0!==i&&i})}removeEventListener(t,r,n){super.removeEventListener(t.toString(),null!=r?r:null,n);var i=e._classPrivateFieldGet2(Ea,this).get(t);null!=i&&(i=i.filter((e=>{var{callback:t}=e;return t!==r})),e._classPrivateFieldGet2(Ea,this).set(t,i))}dispatchEvent(t){var r=super.dispatchEvent(t),n=e._classPrivateFieldGet2(Ea,this).get(t.type);return null==n||(n=n.filter((e=>{var{once:t}=e;return!t})),e._classPrivateFieldGet2(Ea,this).set(t.type,n)),r}safeDispatchEvent(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.dispatchEvent(new CustomEvent(e,t))}};function ka(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}function xa(){return Ta.apply(this,arguments)}function Ta(){return Ta=e._asyncToGenerator((function*(){for(var t=[],r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];for(var o of n)ka(o)&&t.push(o);yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){null!=e.beforeStart&&(yield e.beforeStart())}));return function(e){return t.apply(this,arguments)}}())),yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){yield e.start()}));return function(e){return t.apply(this,arguments)}}())),yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){null!=e.afterStart&&(yield e.afterStart())}));return function(e){return t.apply(this,arguments)}}()))})),Ta.apply(this,arguments)}function Ia(){return Ca.apply(this,arguments)}function Ca(){return Ca=e._asyncToGenerator((function*(){for(var t=[],r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];for(var o of n)ka(o)&&t.push(o);yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){null!=e.beforeStop&&(yield e.beforeStop())}));return function(e){return t.apply(this,arguments)}}())),yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){yield e.stop()}));return function(e){return t.apply(this,arguments)}}())),yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){null!=e.afterStop&&(yield e.afterStop())}));return function(e){return t.apply(this,arguments)}}()))})),Ca.apply(this,arguments)}var Ba=Symbol.for("@libp2p/service-capabilities"),Na=Symbol.for("@libp2p/service-dependencies"),Da=Symbol.for("@achingbrain/uint8arraylist");function Ga(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 Ra(e){return Boolean(null==e?void 0:e[Da])}class Oa{constructor(){e._defineProperty(this,"bufs",void 0),e._defineProperty(this,"length",void 0),e._defineProperty(this,Da,!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(!Ra(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(!Ra(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=Ga(this.bufs,e);return t.buf[t.index]}set(e,t){var r=Ga(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(!Ra(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 mt(r,n)}subarray(e,t){var{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:mt(r,n)}sublist(e,t){var{bufs:r,length:n}=this._subList(e,t),i=new Oa;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,c=t>a&&t<=s;if(l&&c){if(e===a&&t===s){r.push(o);break}var u=e-a;r.push(o.subarray(u,u+(t-e)));break}if(l){if(0===e){r.push(o);continue}r.push(o.subarray(e-a))}else{if(c){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(!(Ra(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,c=this.byteLength-r.byteLength,u=r.byteLength-1,d=t;d<=c;d+=s){s=0;for(var h=u;h>=0;h--){var p=this.get(d+h);if(r[h]!==p){s=Math.max(1,h-l[p]);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=Ke(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=He(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=He(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=He(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=Ke(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=He(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=He(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=He(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=He(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=He(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 Oa))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(var t=0;t<this.bufs.length;t++)if(!rt(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){var r=new Oa;return r.bufs=e,null==t&&(t=e.reduce(((e,t)=>e+t.byteLength),0)),r.length=t,r}}var La=parseInt("11111",2),Ma=parseInt("10000000",2),ja=parseInt("01111111",2),Fa={0:Va,1:Va,2:function(e,t){for(var r=za(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=za(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=za(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=za(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 c=e[t.offset];if(t.offset++,l.push(127&c),c<128){l.reverse();for(var u=0,d=0;d<l.length;d++)u+=l[d]<<7*d;s+=".".concat(u),l=[]}}return s},16:Va,22:Va,48:Va};function Ua(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{offset:0},r=e[t.offset]&La;if(t.offset++,null!=Fa[r])return Fa[r](e,t);throw new Error("No decoder for tag "+r)}function za(e,t){var r=0;if((e[t.offset]&Ma)===Ma){var n=e[t.offset]&ja,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 Va(e,t){za(e,t);for(var r=[];!(t.offset>=e.byteLength);){var n=Ua(e,t);if(null===n)break;r.push(n)}return r}function qa(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 Oa,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 Oa(Uint8Array.from([t.byteLength|Ma]),t)}function Ha(e){var t=new Oa;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new Oa(Uint8Array.from([2]),qa(t),t)}function Ka(e){var t=Uint8Array.from([0]),r=new Oa(t,e);return new Oa(Uint8Array.from([3]),qa(r),r)}function Wa(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48,r=new Oa;for(var n of e)r.append(n);return new Oa(Uint8Array.from([t]),qa(r),r)}var Qa="1.2.840.10045.3.1.7",Ya="1.3.132.0.34",Ja="1.3.132.0.35";function Za(){return Za=e._asyncToGenerator((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)}})),Za.apply(this,arguments)}function $a(){return($a=e._asyncToGenerator((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 Xa(){return Xa=e._asyncToGenerator((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())})),Xa.apply(this,arguments)}var es=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),ts=Uint8Array.from([6,5,43,129,4,0,34]),rs=Uint8Array.from([6,5,43,129,4,0,35]),ns={ext:!0,kty:"EC",crv:"P-256"},is={ext:!0,kty:"EC",crv:"P-384"},os={ext:!0,kty:"EC",crv:"P-521"},as=32,ss=48,ls=66;function cs(t){var r,n,i=t[1],o=Ze(i,"base64url"),a=t[2][1][0];if(i.byteLength===as)return r=Ze(a.subarray(1,33),"base64url"),n=Ze(a.subarray(33),"base64url"),new vs(e._objectSpread2(e._objectSpread2({},ns),{},{key_ops:["sign"],d:o,x:r,y:n}));if(i.byteLength===ss)return r=Ze(a.subarray(1,49),"base64url"),n=Ze(a.subarray(49),"base64url"),new vs(e._objectSpread2(e._objectSpread2({},is),{},{key_ops:["sign"],d:o,x:r,y:n}));if(i.byteLength===ls)return r=Ze(a.subarray(1,67),"base64url"),n=Ze(a.subarray(67),"base64url"),new vs(e._objectSpread2(e._objectSpread2({},os),{},{key_ops:["sign"],d:o,x:r,y:n}));throw new Jo("Private key length was wrong length, got ".concat(i.byteLength,", expected 32, 48 or 66"))}function us(e){return ds(Ua(e))}function ds(t){var r,n,i=t[1][1][0];if(65===i.byteLength)return r=Ze(i.subarray(1,33),"base64url"),n=Ze(i.subarray(33),"base64url"),new fs(e._objectSpread2(e._objectSpread2({},ns),{},{key_ops:["verify"],x:r,y:n}));if(97===i.byteLength)return r=Ze(i.subarray(1,49),"base64url"),n=Ze(i.subarray(49),"base64url"),new fs(e._objectSpread2(e._objectSpread2({},is),{},{key_ops:["verify"],x:r,y:n}));if(133===i.byteLength)return r=Ze(i.subarray(1,67),"base64url"),n=Ze(i.subarray(67),"base64url"),new fs(e._objectSpread2(e._objectSpread2({},os),{},{key_ops:["verify"],x:r,y:n}));throw new Jo("coordinates were wrong length, got ".concat(i.byteLength,", expected 65, 97 or 133"))}function hs(e){if("P-256"===e)return es;if("P-384"===e)return ts;if("P-521"===e)return rs;throw new Jo("Invalid curve ".concat(e))}function ps(){return ps=e._asyncToGenerator((function*(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"P-256",t=yield function(){return Za.apply(this,arguments)}(e);return new vs(t.privateKey)})),ps.apply(this,arguments)}class fs{constructor(t){e._defineProperty(this,"type","ECDSA"),e._defineProperty(this,"jwk",void 0),e._defineProperty(this,"_raw",void 0),this.jwk=t}get raw(){return null==this._raw&&(this._raw=function(e){var t,r;return Wa([Ha(Uint8Array.from([1])),Wa([hs(e.crv)],160),Wa([Ka(new Oa(Uint8Array.from([4]),nt(null!==(t=e.x)&&void 0!==t?t:"","base64url"),nt(null!==(r=e.y)&&void 0!==r?r:"","base64url")))],161)]).subarray()}(this.jwk)),this._raw}toMultihash(){return Te.digest(Fl(this))}toCID(){return je.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rt(this.raw,e.raw)}verify(t,r){var n=this;return e._asyncToGenerator((function*(){return function(e,t,r){return Xa.apply(this,arguments)}(n.jwk,r,t)}))()}}class vs{constructor(t){e._defineProperty(this,"type","ECDSA"),e._defineProperty(this,"jwk",void 0),e._defineProperty(this,"publicKey",void 0),e._defineProperty(this,"_raw",void 0),this.jwk=t,this.publicKey=new fs({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,Wa([Ha(Uint8Array.from([1])),(i=nt(null!==(t=e.d)&&void 0!==t?t:"","base64url"),new Oa(Uint8Array.from([4]),qa(i),i)),Wa([hs(e.crv)],160),Wa([Ka(new Oa(Uint8Array.from([4]),nt(null!==(r=e.x)&&void 0!==r?r:"","base64url"),nt(null!==(n=e.y)&&void 0!==n?n:"","base64url")))],161)]).subarray())),this._raw}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rt(this.raw,e.raw)}sign(t){var r=this;return e._asyncToGenerator((function*(){return function(e,t){return $a.apply(this,arguments)}(r.jwk,t)}))()}}var ys=64;function gs(){var e=go.utils.randomPrivateKey(),t=go.getPublicKey(e),r=function(e,t){for(var r=new Uint8Array(ys),n=0;n<32;n++)r[n]=e[n],r[32+n]=t[n];return r}(e,t);return{privateKey:r,publicKey:t}}class ms{constructor(t){e._defineProperty(this,"type","Ed25519"),e._defineProperty(this,"raw",void 0),this.raw=Ps(t,32)}toMultihash(){return Te.digest(Fl(this))}toCID(){return je.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rt(this.raw,e.raw)}verify(e,t){return function(e,t,r){return go.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this.raw,t,e)}}class ws{constructor(t,r){e._defineProperty(this,"type","Ed25519"),e._defineProperty(this,"raw",void 0),e._defineProperty(this,"publicKey",void 0),this.raw=Ps(t,ys),this.publicKey=new ms(r)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rt(this.raw,e.raw)}sign(e){return t=this.raw,r=e,n=t.subarray(0,32),go.sign(r instanceof Uint8Array?r:r.subarray(),n);var t,r,n}}function bs(e){if(e.length>ys){var t=(e=Ps(e,96)).subarray(0,ys),r=e.subarray(ys,e.length);return new ws(t,r)}var n=(e=Ps(e,ys)).subarray(0,ys),i=e.subarray(32);return new ws(n,i)}function _s(e){return e=Ps(e,32),new ms(e)}function Ss(){return Ss=e._asyncToGenerator((function*(){var{privateKey:e,publicKey:t}=gs();return new ws(e,t)})),Ss.apply(this,arguments)}function Ps(e,t){if((e=Uint8Array.from(null!=e?e:[])).length!==t)throw new Jo("Key must be a Uint8Array of length ".concat(t,", got ").concat(e.length));return e}var Es=new Float32Array([-0]),As=new Uint8Array(Es.buffer);function ks(e,t,r){Es[0]=e,t[r]=As[0],t[r+1]=As[1],t[r+2]=As[2],t[r+3]=As[3]}var xs=new Float64Array([-0]),Ts=new Uint8Array(xs.buffer);function Is(e,t,r){xs[0]=e,t[r]=Ts[0],t[r+1]=Ts[1],t[r+2]=Ts[2],t[r+3]=Ts[3],t[r+4]=Ts[4],t[r+5]=Ts[5],t[r+6]=Ts[6],t[r+7]=Ts[7]}var Cs=BigInt(Number.MAX_SAFE_INTEGER),Bs=BigInt(Number.MIN_SAFE_INTEGER);class Ns{constructor(t,r){e._defineProperty(this,"lo",void 0),e._defineProperty(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 Ds;if(e<Cs&&e>Bs)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>Gs&&(n=0n,++r>Gs&&(r=0n))),new Ns(Number(n),Number(r))}static fromNumber(e){if(0===e)return Ds;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 Ns(r,n)}static from(e){return"number"==typeof e?Ns.fromNumber(e):"bigint"==typeof e?Ns.fromBigInt(e):"string"==typeof e?Ns.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new Ns(e.low>>>0,e.high>>>0):Ds}}var Ds=new Ns(0,0);Ds.toBigInt=function(){return 0n},Ds.zzEncode=Ds.zzDecode=function(){return this},Ds.length=function(){return 1};var Gs=4294967296n;function Rs(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 Os(e,t){return RangeError("index out of range: ".concat(e.pos," + ").concat(null!=t?t:1," > ").concat(e.len))}function Ls(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class Ms{constructor(t){e._defineProperty(this,"buf",void 0),e._defineProperty(this,"pos",void 0),e._defineProperty(this,"len",void 0),e._defineProperty(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,Os(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 Os(this,4);return Ls(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Os(this,4);return 0|Ls(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Os(this,4);var e=function(e,t){return As[0]=e[t],As[1]=e[t+1],As[2]=e[t+2],As[3]=e[t+3],Es[0]}(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Os(this,4);var e=function(e,t){return Ts[0]=e[t],Ts[1]=e[t+1],Ts[2]=e[t+2],Ts[3]=e[t+3],Ts[4]=e[t+4],Ts[5]=e[t+5],Ts[6]=e[t+6],Ts[7]=e[t+7],xs[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 Os(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 Os(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Os(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 Ns(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Os(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 Os(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 Os(this,8);var e=Ls(this.buf,this.pos+=4),t=Ls(this.buf,this.pos+=4);return new Ns(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=vt(this.buf,this.pos);return this.pos+=pt(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 js(e,t,r){var n=function(e){return new Ms(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(n,void 0,r)}class Fs{constructor(t,r,n){e._defineProperty(this,"fn",void 0),e._defineProperty(this,"len",void 0),e._defineProperty(this,"next",void 0),e._defineProperty(this,"val",void 0),this.fn=t,this.len=r,this.next=void 0,this.val=n}}function Us(){}class zs{constructor(t){e._defineProperty(this,"head",void 0),e._defineProperty(this,"tail",void 0),e._defineProperty(this,"len",void 0),e._defineProperty(this,"next",void 0),this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}}var Vs,qs,Hs,Ks,Ws,Qs,Ys,Js,Zs=(Hs=qs=8192,function(e){if(e<1||e>4096)return Ke(e);Hs+e>qs&&(Vs=Ke(qs),Hs=0);var t=Vs.subarray(Hs,Hs+=e);return 7&Hs&&(Hs=1+(7|Hs)),t});class $s{constructor(){e._defineProperty(this,"len",void 0),e._defineProperty(this,"head",void 0),e._defineProperty(this,"tail",void 0),e._defineProperty(this,"states",void 0),this.len=0,this.head=new Fs(Us,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new Fs(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new tl((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(rl,10,Ns.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){var t=Ns.fromBigInt(e);return this._push(rl,t.length(),t)}uint64Number(e){return this._push(ft,pt(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=Ns.fromBigInt(e).zzEncode();return this._push(rl,t.length(),t)}sint64Number(e){var t=Ns.fromNumber(e).zzEncode();return this._push(rl,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Xs,1,e?1:0)}fixed32(e){return this._push(nl,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){var t=Ns.fromBigInt(e);return this._push(nl,4,t.lo)._push(nl,4,t.hi)}fixed64Number(e){var t=Ns.fromNumber(e);return this._push(nl,4,t.lo)._push(nl,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(ks,4,e)}double(e){return this._push(Is,8,e)}bytes(e){var t=e.length>>>0;return 0===t?this._push(Xs,1,0):this.uint32(t)._push(il,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(Rs,t,e):this._push(Xs,1,0)}fork(){return this.states=new zs(this),this.head=this.tail=new Fs(Us,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 Fs(Us,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?Ke(e):Zs(e)),n=0;null!=t;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}}function Xs(e,t,r){t[r]=255&e}function el(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class tl extends Fs{constructor(t,r){super(el,t,r),e._defineProperty(this,"next",void 0),this.next=void 0}}function rl(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 nl(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 il(e,t,r){t.set(e,r)}function ol(e,t,r){t.set(e,r)}function al(e,t,r){e.length<40?Rs(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set(nt(e),r)}function sl(e,t){var r=new $s;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}function ll(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function cl(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return ll("enum",Ks.VARINT,(function(e,r){var n=t(e);r.int32(n)}),(function(e){return t(e.int32())}))}function ul(e,t){return ll("message",Ks.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&($s.prototype.bytes=function(e){var t=e.length>>>0;return this.uint32(t),t>0&&this._push(ol,t,e),this},$s.prototype.string=function(e){var t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(al,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"}(Ks||(Ks={}));class dl extends Error{constructor(){super(...arguments),e._defineProperty(this,"code","ERR_MAX_LENGTH"),e._defineProperty(this,"name","MaxLengthError")}}class hl extends Error{constructor(){super(...arguments),e._defineProperty(this,"code","ERR_MAX_SIZE"),e._defineProperty(this,"name","MaxSizeError")}}function pl(e){if(isNaN(e)||e<=0)throw new Jo("random bytes length must be a Number bigger than 0");return Or(e)}!function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"}(Ws||(Ws={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"}(Qs||(Qs={})),function(e){e.codec=()=>cl(Qs)}(Ws||(Ws={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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),Ws.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=Ws.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(Ys||(Ys={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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),Ws.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=Ws.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(Js||(Js={}));class fl extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"An error occurred while signing a message"),this.name="SigningError"}}class vl extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"An error occurred while verifying a message"),this.name="VerificationError"}}class yl extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Missing Web Crypto API"),this.name="WebCryptoMissingError"}}var gl={get(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:globalThis).crypto;if(null==(null==e?void 0:e.subtle))throw new yl("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 ml=class{constructor(t,r){e._defineProperty(this,"type","RSA"),e._defineProperty(this,"jwk",void 0),e._defineProperty(this,"_raw",void 0),e._defineProperty(this,"_multihash",void 0),this.jwk=t,this._multihash=r}get raw(){return null==this._raw&&(this._raw=Sl(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return je.createV1(114,this._multihash)}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rt(this.raw,e.raw)}verify(e,t){return function(e,t,r){return Tl.apply(this,arguments)}(this.jwk,t,e)}},wl=class{constructor(t,r){e._defineProperty(this,"type","RSA"),e._defineProperty(this,"jwk",void 0),e._defineProperty(this,"_raw",void 0),e._defineProperty(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 Jo("JWK was missing components");return Wa([Ha(Uint8Array.from([0])),Ha(nt(e.n,"base64url")),Ha(nt(e.e,"base64url")),Ha(nt(e.d,"base64url")),Ha(nt(e.p,"base64url")),Ha(nt(e.q,"base64url")),Ha(nt(e.dp,"base64url")),Ha(nt(e.dq,"base64url")),Ha(nt(e.qi,"base64url"))]).subarray()}(this.jwk)),this._raw}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rt(this.raw,e.raw)}sign(e){return function(e,t){return xl.apply(this,arguments)}(this.jwk,e)}};var bl=8192,_l=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Sl(e){if(null==e.n||null==e.e)throw new Jo("JWK was missing components");return Wa([_l,Ka(Wa([Ha(nt(e.n,"base64url")),Ha(nt(e.e,"base64url"))]))]).subarray()}function Pl(e){var t=function(e){return{n:Ze(e[1],"base64url"),e:Ze(e[2],"base64url"),d:Ze(e[3],"base64url"),p:Ze(e[4],"base64url"),q:Ze(e[5],"base64url"),dp:Ze(e[6],"base64url"),dq:Ze(e[7],"base64url"),qi:Ze(e[8],"base64url"),kty:"RSA"}}(e);return function(e){if(function(e){if("RSA"!==e.kty)throw new Jo("invalid key type");if(null==e.n)throw new Jo("invalid key modulus");var t=nt(e.n,"base64url");return 8*t.length}(e)>bl)throw new Jo("Key size is too large");var t=function(e){if(null==e)throw new Jo("Missing key parameter");return{privateKey:e,publicKey:{kty:e.kty,n:e.n,e:e.e}}}(e),r=wo(Ys.encode({Type:Ws.RSA,Data:Sl(t.publicKey)})),n=Ee(18,r);return new wl(t.privateKey,new ml(t.publicKey,n))}(t)}function El(e,t,r){var n=function(e){var t=Ua(e[1],{offset:0});return{kty:"RSA",n:Ze(t[0],"base64url"),e:Ze(t[1],"base64url")}}(e);null==r&&(r=Ee(18,wo(Ys.encode({Type:Ws.RSA,Data:t}))));return new ml(n,r)}function Al(){return Al=e._asyncToGenerator((function*(e){if(e>bl)throw new Jo("Key size is too large");var t=yield function(e){return kl.apply(this,arguments)}(e),r=Ee(18,wo(Ys.encode({Type:Ws.RSA,Data:Sl(t.publicKey)})));return new wl(t.privateKey,new ml(t.publicKey,r))})),Al.apply(this,arguments)}function kl(){return kl=e._asyncToGenerator((function*(e){var t=yield gl.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 Il.apply(this,arguments)}(t);return{privateKey:r[0],publicKey:r[1]}})),kl.apply(this,arguments)}function xl(){return(xl=e._asyncToGenerator((function*(e,t){var r=yield gl.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=yield gl.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 Tl(){return Tl=e._asyncToGenerator((function*(e,t,r){var n=yield gl.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return gl.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())})),Tl.apply(this,arguments)}function Il(){return Il=e._asyncToGenerator((function*(e){if(null==e.privateKey||null==e.publicKey)throw new Jo("Private and public key are required");return Promise.all([gl.get().subtle.exportKey("jwk",e.privateKey),gl.get().subtle.exportKey("jwk",e.publicKey)])})),Il.apply(this,arguments)}function Cl(e){return null!=e&&("function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally)}class Bl{constructor(t){e._defineProperty(this,"type","secp256k1"),e._defineProperty(this,"raw",void 0),e._defineProperty(this,"_key",void 0),this._key=function(e){try{return Wi.ProjectivePoint.fromHex(e),e}catch(e){throw new Zo(String(e))}}(t),this.raw=function(e){var t=Wi.ProjectivePoint.fromHex(e).toRawBytes(!0);return t}(this._key)}toMultihash(){return Te.digest(Fl(this))}toCID(){return je.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rt(this.raw,e.raw)}verify(e,t){return function(e,t,r){var n=De.digest(r instanceof Uint8Array?r:r.subarray());if(Cl(n))return n.then((r=>{var{digest:n}=r;return Wi.verify(t,n,e)})).catch((e=>{throw new vl(String(e))}));try{return Wi.verify(t,n.digest,e)}catch(e){throw new vl(String(e))}}(this._key,t,e)}}class Nl{constructor(t,r){e._defineProperty(this,"type","secp256k1"),e._defineProperty(this,"raw",void 0),e._defineProperty(this,"publicKey",void 0),this.raw=function(e){try{return Wi.getPublicKey(e,!0),e}catch(e){throw new $o(String(e))}}(t),this.publicKey=new Bl(null!=r?r:function(e){try{return Wi.getPublicKey(e,!0)}catch(e){throw new $o(String(e))}}(t))}equals(e){return null!=e&&e.raw instanceof Uint8Array&&rt(this.raw,e.raw)}sign(e){return function(e,t){var r=De.digest(t instanceof Uint8Array?t:t.subarray());if(Cl(r))return r.then((t=>{var{digest:r}=t;return Wi.sign(r,e).toDERRawBytes()})).catch((e=>{throw new fl(String(e))}));try{return Wi.sign(r.digest,e).toDERRawBytes()}catch(e){throw new fl(String(e))}}(this.raw,e)}}function Dl(e){return new Nl(e)}function Gl(e){return new Bl(e)}function Rl(){return(Rl=e._asyncToGenerator((function*(){var e=Wi.utils.randomPrivateKey();return new Nl(e)}))).apply(this,arguments)}function Ol(e,t){return Ll.apply(this,arguments)}function Ll(){return Ll=e._asyncToGenerator((function*(e,t){if("Ed25519"===e)return function(){return Ss.apply(this,arguments)}();if("secp256k1"===e)return function(){return Rl.apply(this,arguments)}();if("RSA"===e)return function(e){return Al.apply(this,arguments)}(function(e){if(null==e)return 2048;return parseInt(e,10)}(t));if("ECDSA"===e)return function(){return ps.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 Jo("Unsupported curve, should be P-256, P-384 or P-521")}(t));throw new Sa})),Ll.apply(this,arguments)}function Ml(e,t){var{Type:r,Data:n}=Ys.decode(e),i=null!=n?n:new Uint8Array;switch(r){case Ws.RSA:return function(e,t){if(e.byteLength>=1062)throw new Zo("Key size is too large");return El(Ua(e,{offset:0}),e,t)}(i,t);case Ws.Ed25519:return _s(i);case Ws.secp256k1:return Gl(i);case Ws.ECDSA:return us(i);default:throw new Sa}}function jl(e){var{Type:t,Data:r}=Ys.decode(e.digest),n=null!=r?r:new Uint8Array;switch(t){case Ws.Ed25519:return _s(n);case Ws.secp256k1:return Gl(n);case Ws.ECDSA:return us(n);default:throw new Sa}}function Fl(e){return Ys.encode({Type:Ws[e.type],Data:e.raw})}function Ul(e){var t,r=Js.decode(e),n=null!==(t=r.Data)&&void 0!==t?t:new Uint8Array;switch(r.Type){case Ws.RSA:return Pl(Ua(n));case Ws.Ed25519:return bs(n);case Ws.secp256k1:return Dl(n);case Ws.ECDSA:return function(e){return cs(Ua(e))}(n);default:throw new Sa}}function zl(e){var t;if(e.byteLength===ys)return bs(e);if(32===e.byteLength)return Dl(e);var r=Ua(e),n=null===(t=r[2])||void 0===t?void 0:t[0];if(n===Qa||n===Ya||n===Ja)return cs(r);if(r.length>8)return Pl(r);throw new Jo("Could not extract private key from raw bytes")}function Vl(e){return Js.encode({Type:Ws[e.type],Data:e.raw})}function ql(e){return Hl.apply(this,arguments)}function Hl(){return(Hl=e._asyncToGenerator((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 Jo("Only RSA and ECDSA keys are supported")}))).apply(this,arguments)}var Kl=Symbol.for("nodejs.util.inspect.custom");class Wl{constructor(t){e._defineProperty(this,"type",void 0),e._defineProperty(this,"multihash",void 0),e._defineProperty(this,"publicKey",void 0),e._defineProperty(this,"string",void 0),e._defineProperty(this,Uo,!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=j.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return je.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){var t;if(null==e)return!1;if(e instanceof Uint8Array)return rt(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 rt(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Kl](){return"PeerId(".concat(this.toString(),")")}}class Ql extends Wl{constructor(t){super(e._objectSpread2(e._objectSpread2({},t),{},{type:"RSA"})),e._defineProperty(this,"type","RSA"),e._defineProperty(this,"publicKey",void 0),this.publicKey=t.publicKey}}class Yl extends Wl{constructor(t){super(e._objectSpread2(e._objectSpread2({},t),{},{type:"Ed25519"})),e._defineProperty(this,"type","Ed25519"),e._defineProperty(this,"publicKey",void 0),this.publicKey=t.publicKey}}class Jl extends Wl{constructor(t){super(e._objectSpread2(e._objectSpread2({},t),{},{type:"secp256k1"})),e._defineProperty(this,"type","secp256k1"),e._defineProperty(this,"publicKey",void 0),this.publicKey=t.publicKey}}class Zl{constructor(t){e._defineProperty(this,"type","url"),e._defineProperty(this,"multihash",void 0),e._defineProperty(this,"publicKey",void 0),e._defineProperty(this,"url",void 0),e._defineProperty(this,Uo,!0),this.url=t.toString(),this.multihash=Te.digest(nt(this.url))}[Kl](){return"PeerId(".concat(this.url,")")}toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return je.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=Ze(e)),e.toString()===this.toString())}}function $l(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 rc(je.parse(e));throw new Jo('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return tc(Ae(j.decode("z".concat(e))))}function Xl(e){if("Ed25519"===e.type)return new Yl({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new Jl({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new Ql({multihash:e.toCID().multihash,publicKey:e});throw new Sa}function ec(e){return Xl(e.publicKey)}function tc(e){if(function(e){return e.code===De.code}(e))return new Ql({multihash:e});if(function(e){return e.code===Te.code}(e))try{var t=jl(e);if("Ed25519"===t.type)return new Yl({multihash:e,publicKey:t});if("secp256k1"===t.type)return new Jl({multihash:e,publicKey:t})}catch(t){var r=Ze(e.digest);return new Zl(new URL(r))}throw new ua("Supplied PeerID Multihash is invalid")}function rc(e){if(null==(null==e?void 0:e.multihash)||null==e.version||1===e.version&&114!==e.code&&2336!==e.code)throw new ca("Supplied PeerID CID is invalid");if(2336===e.code){var t=Ze(e.multihash.digest);return new Zl(new URL(t))}return tc(e.multihash)}var nc=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),ic=new Uint32Array(80);class oc extends jr{constructor(){super(64,20,8,!1),this.A=0|nc[0],this.B=0|nc[1],this.C=0|nc[2],this.D=0|nc[3],this.E=0|nc[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)ic[r]=e.getUint32(t,!1);for(var n=16;n<80;n++)ic[n]=fr(ic[n-3]^ic[n-8]^ic[n-14]^ic[n-16],1);for(var{A:i,B:o,C:a,D:s,E:l}=this,c=0;c<80;c++){var u=void 0,d=void 0;c<20?(u=Lr(o,a,s),d=1518500249):c<40?(u=o^a^s,d=1859775393):c<60?(u=Mr(o,a,s),d=2400959708):(u=o^a^s,d=3395469782);var h=fr(i,5)+u+l+d+ic[c]|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(){dr(ic)}destroy(){this.set(0,0,0,0,0),dr(this.buffer)}}var ac=Rr((()=>new oc)),sc=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),lc=(()=>Uint8Array.from(new Array(16).fill(0).map(((e,t)=>t))))(),cc=(()=>lc.map((e=>(9*e+5)%16)))(),uc=(()=>{for(var e=[[lc],[cc]],t=0;t<4;t++)for(var r of e)r.push(r[t].map((e=>sc[e])));return e})(),dc=(()=>uc[0])(),hc=(()=>uc[1])(),pc=[[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))),fc=dc.map(((e,t)=>e.map((e=>pc[t][e])))),vc=hc.map(((e,t)=>e.map((e=>pc[t][e])))),yc=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),gc=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function mc(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 wc=new Uint32Array(16);class bc extends jr{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)wc[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,c=0|this.h3,u=c,d=0|this.h4,h=d,p=0;p<5;p++){for(var f=4-p,v=yc[p],y=gc[p],g=dc[p],m=hc[p],w=fc[p],b=vc[p],_=0;_<16;_++){var S=fr(n+mc(p,o,s,c)+wc[g[_]]+v,w[_])+d|0;n=d,d=c,c=0|fr(s,10),s=o,o=S}for(var P=0;P<16;P++){var E=fr(i+mc(f,a,l,u)+wc[m[P]]+y,b[P])+h|0;i=h,h=u,u=0|fr(l,10),l=a,a=E}}this.set(this.h1+s+u|0,this.h2+c+h|0,this.h3+d+i|0,this.h4+n+a|0,this.h0+o+l|0)}roundClean(){dr(wc)}destroy(){this.destroyed=!0,dr(this.buffer),this.set(0,0,0,0,0)}}var _c=Rr((()=>new bc)),Sc={sha1:ac,"sha2-256":wo,"sha2-512":bo};function Pc(e,t,r,n,i){if("sha1"!==i&&"sha2-256"!==i&&"sha2-512"!==i){var o=Object.keys(Sc).join(" / ");throw new Jo("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:c}=_o(e,t,r,n),u=new Uint8Array(4),d=hr(u),h=new Uint8Array(l.outputLen),p=1,f=0;f<a;p++,f+=l.outputLen){var v=s.subarray(f,f+l.outputLen);d.setInt32(0,p,!1),(i=c._cloneInto(i)).update(u).digestInto(h),v.set(h.subarray(0,v.length));for(var y=1;y<o;y++){l._cloneInto(i).update(h).digestInto(h);for(var g=0;g<v.length;g++)v[g]^=h[g]}}return So(l,c,s,i,h)}(Sc[i],e,t,{c:r,dkLen:n});return z.encode(a).substring(1)}var Ec="/",Ac=(new TextEncoder).encode(Ec),kc=Ac[0];class xc{constructor(t,r){if(e._defineProperty(this,"_buf",void 0),"string"==typeof t)this._buf=nt(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]!==kc)throw new Error("Invalid key")}toString(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"utf8";return Ze(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return"Key(".concat(this.toString(),")")}static withNamespaces(e){return new xc(e.join(Ec))}static random(){return new xc(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new xc(e):"function"==typeof e.uint8Array?new xc(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=Ac),this._buf[0]!==kc){var e=new Uint8Array(this._buf.byteLength+1);e.fill(kc,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===kc;)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 xc.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){var e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ec).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 xc(this.toString()+":"+e)}path(){var e=this.parent().toString();return e.endsWith(Ec)||(e+=Ec),e+=this.type(),new xc(e)}parent(){var e=this.list();return 1===e.length?new xc(Ec):new xc(e.slice(0,-1).join(Ec))}child(e){return this.toString()===Ec?e:e.toString()===Ec?this:new xc(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 xc.withNamespaces([...this.namespaces(),...(n=t.map((e=>e.namespaces())),[].concat(...n))]);var n}}function Tc(t){if(null!=t[Symbol.asyncIterator])return e._asyncToGenerator((function*(){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t);n=!(o=yield a.next()).done;n=!1)o.value}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield a.return())}finally{if(i)throw r}}}))();for(var r of t);}function Ic(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 Cc(t,r){var n=0;if(null!=t[Symbol.asyncIterator])return e._wrapAsyncGenerator((function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;(yield e._awaitAsyncGenerator(r(c,n++)))&&(yield c)}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}))();var i=Ic(t),{value:o,done:a}=i.next();if(!0===a)return function*(){}();var s=r(o,n++);if("function"==typeof s.then)return e._wrapAsyncGenerator((function*(){for(var t of((yield e._awaitAsyncGenerator(s))&&(yield o),i))(yield e._awaitAsyncGenerator(r(t,n++)))&&(yield t)}))();var l=r;return function*(){for(var e of(!0===s&&(yield o),i))l(e,n++)&&(yield e)}()}function Bc(t){if(null!=t[Symbol.asyncIterator])return e._asyncToGenerator((function*(){var r,n=[],i=!1,o=!1;try{for(var a,s=e._asyncIterator(t);i=!(a=yield s.next()).done;i=!1){var l=a.value;n.push(l)}}catch(e){o=!0,r=e}finally{try{i&&null!=s.return&&(yield s.return())}finally{if(o)throw r}}return n}))();var r=[];for(var n of t)r.push(n);return r}function Nc(t,r){return null!=t[Symbol.asyncIterator]?e._wrapAsyncGenerator((function*(){var n=yield e._awaitAsyncGenerator(Bc(t));yield*e._asyncGeneratorDelegate(e._asyncIterator(n.sort(r)))}))():function*(){var e=Bc(t);yield*e.sort(r)}()}function Dc(t,r){return null!=t[Symbol.asyncIterator]?e._wrapAsyncGenerator((function*(){var n=0;if(!(r<1)){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;if(yield c,++n===r)return}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}}))():function*(){var e=0;if(!(r<1))for(var n of t)if(yield n,++e===r)return}()}class Gc{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(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var{key:c,value:u}=s.value;yield e._awaitAsyncGenerator(r.put(c,u,n)),yield c}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}()})).apply(this,arguments)}getMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;yield{key:c,value:yield e._awaitAsyncGenerator(r.get(c,n))}}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}()})).apply(this,arguments)}deleteMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;yield e._awaitAsyncGenerator(r.delete(c,n)),yield c}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}()})).apply(this,arguments)}batch(){var t,r=this,n=[],i=[];return{put(e,t){n.push({key:e,value:t})},delete(e){i.push(e)},commit:(t=e._asyncToGenerator((function*(e){yield Tc(r.putMany(n,e)),n=[],yield Tc(r.deleteMany(i,e)),i=[]})),function(e){return t.apply(this,arguments)})}}_all(t,r){return e._wrapAsyncGenerator((function*(){throw new Error("._all is not implemented")}))()}_allKeys(t,r){return e._wrapAsyncGenerator((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=Cc(r,(e=>e.key.toString().startsWith(n)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>Cc(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>Nc(e,t)),r)),null!=e.offset){var i=0,o=e.offset;r=Cc(r,(()=>i++>=o))}return null!=e.limit&&(r=Dc(r,e.limit)),r}queryKeys(e,t){var r=this._allKeys(e,t);if(null!=e.prefix){var n=e.prefix;r=Cc(r,(e=>e.toString().startsWith(n)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>Cc(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>Nc(e,t)),r)),null!=e.offset){var i=e.offset,o=0;r=Cc(r,(()=>o++>=i))}return null!=e.limit&&(r=Dc(r,e.limit)),r}}class Rc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Open failed"),e._defineProperty(this,"name",Rc.name),e._defineProperty(this,"code",Rc.code)}}e._defineProperty(Rc,"name","OpenFailedError"),e._defineProperty(Rc,"code","ERR_OPEN_FAILED");class Oc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Close failed"),e._defineProperty(this,"name",Oc.name),e._defineProperty(this,"code",Oc.code)}}e._defineProperty(Oc,"name","CloseFailedError"),e._defineProperty(Oc,"code","ERR_CLOSE_FAILED");class Lc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Put failed"),e._defineProperty(this,"name",Lc.name),e._defineProperty(this,"code",Lc.code)}}e._defineProperty(Lc,"name","PutFailedError"),e._defineProperty(Lc,"code","ERR_PUT_FAILED");class Mc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Get failed"),e._defineProperty(this,"name",Mc.name),e._defineProperty(this,"code",Mc.code)}}e._defineProperty(Mc,"name","GetFailedError"),e._defineProperty(Mc,"code","ERR_GET_FAILED");class jc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Delete failed"),e._defineProperty(this,"name",jc.name),e._defineProperty(this,"code",jc.code)}}e._defineProperty(jc,"name","DeleteFailedError"),e._defineProperty(jc,"code","ERR_DELETE_FAILED");class Fc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Has failed"),e._defineProperty(this,"name",Fc.name),e._defineProperty(this,"code",Fc.code)}}e._defineProperty(Fc,"name","HasFailedError"),e._defineProperty(Fc,"code","ERR_HAS_FAILED");let Uc=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not Found"),e._defineProperty(this,"name",t.name),e._defineProperty(this,"code",t.code)}};e._defineProperty(Uc,"name","NotFoundError"),e._defineProperty(Uc,"code","ERR_NOT_FOUND");let zc=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Aborted"),e._defineProperty(this,"name",t.name),e._defineProperty(this,"code",t.code)}};e._defineProperty(zc,"name","AbortError"),e._defineProperty(zc,"code","ERR_ABORTED");class Vc extends Gc{constructor(){super(),e._defineProperty(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 Uc;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 xc(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 xc(n),null==t||null===(i=t.signal)||void 0===i||i.throwIfAborted()}}}function qc(t,r){var n=0;if(null!=t[Symbol.asyncIterator])return e._wrapAsyncGenerator((function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;yield r(c,n++)}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}))();var i=Ic(t),{value:o,done:a}=i.next();if(!0===a)return function*(){}();var s=r(o,n++);if("function"==typeof s.then)return e._wrapAsyncGenerator((function*(){for(var t of(yield yield e._awaitAsyncGenerator(s),i))yield r(t,n++)}))();var l=r;return function*(){for(var e of(yield s,i))yield l(e,n++)}()}function Hc(){var e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}class Kc{constructor(t){if(e._defineProperty(this,"buffer",void 0),e._defineProperty(this,"mask",void 0),e._defineProperty(this,"top",void 0),e._defineProperty(this,"btm",void 0),e._defineProperty(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 Wc{constructor(){var t,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e._defineProperty(this,"size",void 0),e._defineProperty(this,"hwm",void 0),e._defineProperty(this,"head",void 0),e._defineProperty(this,"tail",void 0),this.hwm=null!==(t=r.splitLimit)&&void 0!==t?t:16,this.head=new Kc(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 Kc(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 Qc=class extends Error{constructor(t,r){super(null!=t?t:"The operation was aborted"),e._defineProperty(this,"type",void 0),e._defineProperty(this,"code",void 0),this.type="aborted",this.code=null!=r?r:"ABORT_ERR"}};function Yc(){return function(t,r){r=null!=r?r:{};var n,i,o,a=r.onEnd,s=new Wc,l=Hc(),c=function(){var r=e._asyncToGenerator((function*(){try{return s.isEmpty()?o?{done:!0}:yield new Promise(((e,r)=>{i=o=>{i=null,s.push(o);try{e(t(s))}catch(e){r(e)}return n}})):t(s)}finally{s.isEmpty()&&queueMicrotask((()=>{l.resolve(),l=Hc()}))}}));return function(){return r.apply(this,arguments)}}(),u=e=>null!=i?i(e):(s.push(e),n),d=e=>(s=new Wc,null!=i?i({error:e}):(s.push({error:e}),n)),h=e=>{var t;if(o)return n;if(!0!==(null===(t=r)||void 0===t?void 0:t.objectMode)&&null==(null==e?void 0:e.byteLength))throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:e})},p=e=>o?n:(o=!0,null!=e?d(e):u({done:!0})),f=()=>(s=new Wc,p(),{done:!0}),v=e=>(p(e),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:c,return:f,throw:v,push:h,end:p,get readableLength(){return s.size},onEmpty:function(){var t=e._asyncToGenerator((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 Qc)},t.addEventListener("abort",n)})));try{yield Promise.race([l.promise,r])}finally{null!=n&&null!=t&&(null==t||t.removeEventListener("abort",n))}}}));function r(e){return t.apply(this,arguments)}return r}()},null==a)return n;var y=n;return n={[Symbol.asyncIterator](){return this},next:()=>y.next(),throw:e=>(y.throw(e),null!=a&&(a(e),a=void 0),{done:!0}),return:()=>(y.return(),null!=a&&(a(),a=void 0),{done:!0}),push:h,end:e=>(y.end(e),null!=a&&(a(e),a=void 0),n),get readableLength(){return y.readableLength},onEmpty:e=>y.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 Jc=class extends Error{constructor(t,r,n){super(null!=t?t:"The operation was aborted"),e._defineProperty(this,"type",void 0),e._defineProperty(this,"code",void 0),this.type="aborted",this.name=null!=n?n:"AbortError",this.code=null!=r?r:"ABORT_ERR"}};function Zc(e,t,r){return $c.apply(this,arguments)}function $c(){return($c=e._asyncToGenerator((function*(e,t,r){if(null==t)return e;if(t.aborted)return e.catch((()=>{})),Promise.reject(new Jc(null==r?void 0:r.errorMessage,null==r?void 0:r.errorCode,null==r?void 0:r.errorName));var n,i=new Jc(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 Xc=class{constructor(){e._defineProperty(this,"readNext",void 0),e._defineProperty(this,"haveNext",void 0),e._defineProperty(this,"ended",void 0),e._defineProperty(this,"nextResult",void 0),e._defineProperty(this,"error",void 0),this.ended=!1,this.readNext=Hc(),this.haveNext=Hc()}[Symbol.asyncIterator](){return this}next(){var t=this;return e._asyncToGenerator((function*(){if(null==t.nextResult&&(yield t.haveNext.promise),null==t.nextResult)throw new Error("HaveNext promise resolved but nextResult was undefined");var e=t.nextResult;return t.nextResult=void 0,t.readNext.resolve(),t.readNext=Hc(),e}))()}throw(t){var r=this;return e._asyncToGenerator((function*(){return r.ended=!0,r.error=t,null!=t&&(r.haveNext.promise.catch((()=>{})),r.haveNext.reject(t)),{done:!0,value:void 0}}))()}return(){var t=this;return e._asyncToGenerator((function*(){var e={done:!0,value:void 0};return t.ended=!0,t.nextResult=e,t.haveNext.resolve(),e}))()}push(t,r){var n=this;return e._asyncToGenerator((function*(){yield n._push(t,r)}))()}end(t,r){var n=this;return e._asyncToGenerator((function*(){null!=t?yield n.throw(t):yield n._push(void 0,r)}))()}_push(t,r){var n=this;return e._asyncToGenerator((function*(){var e;if(null!=t&&n.ended)throw null!==(e=n.error)&&void 0!==e?e:new Error("Cannot push value onto an ended pushable");for(;null!=n.nextResult;)yield n.readNext.promise;null!=t?n.nextResult={done:!1,value:t}:(n.ended=!0,n.nextResult={done:!0,value:void 0}),n.haveNext.resolve(),n.haveNext=Hc(),yield Zc(n.readNext.promise,null==r?void 0:r.signal,r)}))()}};function eu(){return new Xc}function tu(){return tu=e._asyncToGenerator((function*(t,r,n){try{yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(t){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield l.next()).done;o=!1){var c=s.value;yield r.push(c,{signal:n}),n.throwIfAborted()}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield l.return())}finally{if(a)throw i}}}));return function(e){return t.apply(this,arguments)}}())),yield r.end(void 0,{signal:n})}catch(e){yield r.end(e,{signal:n}).catch((()=>{}))}})),tu.apply(this,arguments)}function ru(){return ru=e._wrapAsyncGenerator((function*(t){var r=new AbortController,n=eu();(function(e,t,r){return tu.apply(this,arguments)})(t,n,r.signal).catch((()=>{}));try{yield*e._asyncGeneratorDelegate(e._asyncIterator(n),e._awaitAsyncGenerator)}finally{r.abort()}})),ru.apply(this,arguments)}function nu(){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 ru.apply(this,arguments)}(r)}function iu(e){if(null==e)throw new Error("Empty pipeline");if(lu(e)){var t=e;e=()=>t.source}else if(su(e)||au(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&&lu(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++)lu(a[s])&&(a[s]=cu(a[s]));return ou(...a)}var ou=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},au=e=>null!=(null==e?void 0:e[Symbol.asyncIterator]),su=e=>null!=(null==e?void 0:e[Symbol.iterator]),lu=e=>null!=e&&(null!=e.sink&&null!=e.source),cu=t=>r=>{var n=t.sink(r);if(null!=(null==n?void 0:n.then)){var i,o=Yc({objectMode:!0});n.then((()=>{o.end()}),(e=>{o.end(e)}));var a=t.source;if(au(a))i=function(){var t=e._wrapAsyncGenerator((function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(a)),o.end()}));return function(){return t.apply(this,arguments)}}();else{if(!su(a))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");i=function*(){yield*a,o.end()}}return nu(o,i())}return t.source};new xc("SHARDING");var uu,du,hu=1e3,pu=60*hu,fu=60*pu,vu=24*fu,yu=7*vu,gu=365.25*vu;function mu(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*gu;case"weeks":case"week":case"w":return r*yu;case"days":case"day":case"d":return r*vu;case"hours":case"hour":case"hrs":case"hr":case"h":return r*fu;case"minutes":case"minute":case"mins":case"min":case"m":return r*pu;case"seconds":case"second":case"secs":case"sec":case"s":return r*hu;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>=vu)return wu(e,t,vu,"day");if(t>=fu)return wu(e,t,fu,"hour");if(t>=pu)return wu(e,t,pu,"minute");if(t>=hu)return wu(e,t,hu,"second");return"".concat(e," ms")}(e):function(e){var t=Math.abs(e);if(t>=vu)return"".concat(Math.round(e/vu),"d");if(t>=fu)return"".concat(Math.round(e/fu),"h");if(t>=pu)return"".concat(Math.round(e/pu),"m");if(t>=hu)return"".concat(Math.round(e/hu),"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 wu(e,t,r,n){var i=t>=1.5*r;return"".concat(Math.round(e/r)," ").concat(n).concat(i?"s":"")}var bu=function(){try{return localStorage}catch(e){}}();var _u=null!==(uu=null!==(du=console.debug)&&void 0!==du?du:console.log)&&void 0!==uu?uu:()=>{};var Su,Pu,Eu=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 c=0;r[0]=r[0].replace(/%([a-zA-Z%])/g,((e,n)=>{if("%%"===e)return"%";c++;var i=t.formatters[n];if("function"==typeof i){var a=r[c];e=i.call(o,a),r.splice(c,1),c--}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=mu,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 ":" ")+"+"+mu(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==bu||bu.setItem("debug",e):null==bu||bu.removeItem("debug")}catch(e){}},load:function(){var e;try{e=null==bu?void 0:bu.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:bu,log:_u});function Au(){return{forComponent:e=>ku(e)}}function ku(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 Eu.enabled("".concat(e,":trace"))&&null!=Eu.names.map((e=>e.toString())).find((e=>e.includes(":trace")))&&(t=Eu("".concat(e,":trace"))),Object.assign(Eu(e),{error:Eu("".concat(e,":error")),trace:t})}function xu(e){if(null!=e&&0!==(e=e.trim()).length)return e}Eu.formatters.b=e=>null==e?"undefined":j.baseEncode(e),Eu.formatters.t=e=>null==e?"undefined":k.baseEncode(e),Eu.formatters.m=e=>null==e?"undefined":z.baseEncode(e),Eu.formatters.p=e=>null==e?"undefined":e.toString(),Eu.formatters.c=e=>null==e?"undefined":e.toString(),Eu.formatters.k=e=>null==e?"undefined":e.toString(),Eu.formatters.a=e=>null==e?"undefined":e.toString(),Eu.formatters.e=e=>{var t,r;return null==e?"undefined":null!==(t=null!==(r=xu(e.stack))&&void 0!==r?r:xu(e.message))&&void 0!==t?t:e.toString()},ku("datastore:core:tiered");class Tu{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(t,r){var n=this;return e._wrapAsyncGenerator((function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var{cid:c,block:u}=s.value;yield e._awaitAsyncGenerator(n.put(c,u,r)),yield c}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}))()}get(e,t){return Promise.reject(new Error(".get is not implemented"))}getMany(t,r){var n=this;return e._wrapAsyncGenerator((function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;yield{cid:c,block:yield e._awaitAsyncGenerator(n.get(c,r))}}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}))()}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}deleteMany(t,r){var n=this;return e._wrapAsyncGenerator((function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;yield e._awaitAsyncGenerator(n.delete(c,r)),yield c}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}))()}getAll(t){return e._wrapAsyncGenerator((function*(){throw new Error(".getAll is not implemented")}))()}}class Iu extends Tu{constructor(){super(),e._defineProperty(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 Uc;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(t,r){var n=this;return e._asyncToGenerator((function*(){var e;null==r||null===(e=r.signal)||void 0===e||e.throwIfAborted(),n.data.delete(k.encode(t.multihash.bytes))}))()}getAll(t){var r=this;return e._wrapAsyncGenerator((function*(){var e;for(var[n,i]of(null==t||null===(e=t.signal)||void 0===e||e.throwIfAborted(),r.data.entries())){var o;yield{cid:je.createV1(re,Ae(k.decode(n))),block:i},null==t||null===(o=t.signal)||void 0===o||o.throwIfAborted()}}))()}}ku("blockstore:core:tiered"),function(e){var t;e.codec=()=>(null==t&&(t=ul((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:He(0),payloadType:He(0),payload:He(0),signature:He(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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(Su||(Su={}));class Cu extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid signature"),this.name="InvalidSignatureError"}}class Bu{constructor(t){e._defineProperty(this,"publicKey",void 0),e._defineProperty(this,"payloadType",void 0),e._defineProperty(this,"payload",void 0),e._defineProperty(this,"signature",void 0),e._defineProperty(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=Su.encode({publicKey:Fl(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return null!=e&&rt(this.marshal(),e.marshal())}validate(t){var r=this;return e._asyncToGenerator((function*(){var e=Nu(t,r.payloadType,r.payload);return r.publicKey.verify(e.subarray(),r.signature)}))()}}Pu=Bu,e._defineProperty(Bu,"createFromProtobuf",function(){var t=e._asyncToGenerator((function*(e){var t=Su.decode(e),r=Ml(t.publicKey);return new Pu({publicKey:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})}));return function(e){return t.apply(this,arguments)}}()),e._defineProperty(Bu,"seal",function(){var t=e._asyncToGenerator((function*(e,t){if(null==t)throw new Error("Missing private key");var r=e.domain,n=e.codec,i=e.marshal(),o=Nu(r,n,i),a=yield t.sign(o.subarray());return new Pu({publicKey:t.publicKey,payloadType:n,payload:i,signature:a})}));return function(e,r){return t.apply(this,arguments)}}()),e._defineProperty(Bu,"openAndCertify",function(){var t=e._asyncToGenerator((function*(e,t){var r=yield Pu.createFromProtobuf(e);if(!(yield r.validate(t)))throw new Cu("Envelope signature is not valid for the given domain");return r}));return function(e,r){return t.apply(this,arguments)}}());var Nu=(e,t,r)=>{var n=nt(e),i=yt(n.byteLength),o=yt(t.length),a=yt(r.length);return new Oa(i,n,o,t,a,r)};var Du,Gu,Ru=Uint8Array.from([3,1]);!function(e){var t;!function(e){var t;e.codec=()=>(null==t&&(t=ul((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:He(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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==t&&(t=ul((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:He(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 dl('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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(Du||(Du={}));class Ou{constructor(t){e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"multiaddrs",void 0),e._defineProperty(this,"seqNumber",void 0),e._defineProperty(this,"domain",Ou.DOMAIN),e._defineProperty(this,"codec",Ou.CODEC),e._defineProperty(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=Du.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 Ou&&(!!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)))}}Gu=Ou,e._defineProperty(Ou,"createFromProtobuf",(e=>{var t,r=Du.decode(e),n=tc(Ae(r.peerId)),i=(null!==(t=r.addresses)&&void 0!==t?t:[]).map((e=>nr(e.multiaddr))),o=r.seq;return new Gu({peerId:n,multiaddrs:i,seqNumber:o})})),e._defineProperty(Ou,"DOMAIN","libp2p-peer-record"),e._defineProperty(Ou,"CODEC",Ru);let Lu=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","UnexpectedEOFError"),e._defineProperty(this,"code","ERR_UNEXPECTED_EOF")}};function Mu(t,r){var n=eu();t.sink(n).catch(function(){var t=e._asyncToGenerator((function*(e){yield n.end(e)}));return function(e){return t.apply(this,arguments)}}()),t.sink=function(){var t=e._asyncToGenerator((function*(t){var r,i=!1,o=!1;try{for(var a,s=e._asyncIterator(t);i=!(a=yield s.next()).done;i=!1){var l=a.value;yield n.push(l)}}catch(e){o=!0,r=e}finally{try{i&&null!=s.return&&(yield s.return())}finally{if(o)throw r}}yield n.end()}));return function(e){return t.apply(this,arguments)}}();var i=t.source;null!=t.source[Symbol.iterator]?i=t.source[Symbol.iterator]():null!=t.source[Symbol.asyncIterator]&&(i=t.source[Symbol.asyncIterator]());var o,a=new Oa,s={read:function(){var t=e._asyncToGenerator((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 Zc(i.next(),null==e?void 0:e.signal);return!0===r?null:n}for(;a.byteLength<e.bytes;){var{value:o,done:s}=yield Zc(i.next(),null==e?void 0:e.signal);if(!0===s)throw new Lu("unexpected end of input");a.append(o)}var l=a.sublist(0,e.bytes);return a.consume(e.bytes),l}));return function(e){return t.apply(this,arguments)}}(),write:(o=e._asyncToGenerator((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 n=t.source;t.source=e._wrapAsyncGenerator((function*(){!1===(null==r?void 0:r.yieldBytes)?yield a:yield*e._asyncGeneratorDelegate(e._asyncIterator(a)),yield*e._asyncGeneratorDelegate(e._asyncIterator(n))}))()}return t}};return s}let ju=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidMessageLengthError"),e._defineProperty(this,"code","ERR_INVALID_MSG_LENGTH")}},Fu=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidDataLengthError"),e._defineProperty(this,"code","ERR_MSG_DATA_TOO_LONG")}},Uu=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidDataLengthLengthError"),e._defineProperty(this,"code","ERR_MSG_LENGTH_TOO_LONG")}};function zu(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=Mu(t,i);null!=i.maxDataLength&&null==i.maxLengthLength&&(i.maxLengthLength=pt(i.maxDataLength));var a,s=null!==(r=null==i?void 0:i.lengthDecoder)&&void 0!==r?r:gt,l=null!==(n=null==i?void 0:i.lengthEncoder)&&void 0!==n?n:yt,c={read:function(){var t=e._asyncToGenerator((function*(t){for(var r=-1,n=new Oa;;){n.append(yield o.read(e._objectSpread2(e._objectSpread2({},t),{},{bytes:1})));try{r=s(n)}catch(e){if(e instanceof RangeError)continue;throw e}if(r<0)throw new ju("Invalid message length");if(null!=(null==i?void 0:i.maxLengthLength)&&n.byteLength>i.maxLengthLength)throw new Uu("message length length too long");if(r>-1)break}if(null!=(null==i?void 0:i.maxDataLength)&&r>i.maxDataLength)throw new Fu("message length too long");return o.read(e._objectSpread2(e._objectSpread2({},t),{},{bytes:r}))}));return function(e){return t.apply(this,arguments)}}(),write:function(){var t=e._asyncToGenerator((function*(e,t){yield o.write(new Oa(l(e.byteLength),e),t)}));return function(e,r){return t.apply(this,arguments)}}(),writeV:(a=e._asyncToGenerator((function*(e,t){var r=new Oa(...e.flatMap((e=>[l(e.byteLength),e])));yield o.write(r,t)})),function(e,t){return a.apply(this,arguments)}),unwrap:()=>o.unwrap()};return c}function Vu(t,r){var n,i=zu(t,r),o={read:function(){var t=e._asyncToGenerator((function*(e,t){var r=yield i.read(t);return e.decode(r)}));return function(e,r){return t.apply(this,arguments)}}(),write:function(){var t=e._asyncToGenerator((function*(e,t,r){yield i.write(t.encode(e),r)}));return function(e,r,n){return t.apply(this,arguments)}}(),writeV:(n=e._asyncToGenerator((function*(e,t,r){yield i.writeV(e.map((e=>t.encode(e))),r)})),function(e,t,r){return n.apply(this,arguments)}),pb:t=>{return{read:(i=e._asyncToGenerator((function*(e){return o.read(t,e)})),function(e){return i.apply(this,arguments)}),write:(n=e._asyncToGenerator((function*(e,r){return o.write(e,t,r)})),function(e,t){return n.apply(this,arguments)}),writeV:(r=e._asyncToGenerator((function*(e,r){return o.writeV(e,t,r)})),function(e,t){return r.apply(this,arguments)}),unwrap:()=>o};var r,n,i},unwrap:()=>i.unwrap()};return o}var qu="".concat(Ho,"-circuit-relay");BigInt(1<<17);var Hu,Ku,Wu,Qu,Yu,Ju,Zu,$u,Xu,ed="/libp2p/circuit/relay/0.2.0/hop",td="/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=()=>cl(t)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=ul((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),Wu.codec().encode(t.peer,r)),null!=t.reservation&&(r.uint32(26),Qu.codec().encode(t.reservation,r)),null!=t.limit&&(r.uint32(34),Yu.codec().encode(t.limit,r)),null!=t.status&&(r.uint32(40),Ju.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=Wu.codec().decode(t,t.uint32(),{limits:null===(s=n.limits)||void 0===s?void 0:s.peer});break;case 3:var l;i.reservation=Qu.codec().decode(t,t.uint32(),{limits:null===(l=n.limits)||void 0===l?void 0:l.reservation});break;case 4:var c;i.limit=Yu.codec().decode(t,t.uint32(),{limits:null===(c=n.limits)||void 0===c?void 0:c.limit});break;case 5:i.status=Ju.codec().decode(t);break;default:t.skipType(7&a)}}return i}))),r),e.encode=t=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(Hu||(Hu={})),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=()=>cl(t)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=ul((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),Wu.codec().encode(t.peer,r)),null!=t.limit&&(r.uint32(26),Yu.codec().encode(t.limit,r)),null!=t.status&&(r.uint32(32),Ju.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=Wu.codec().decode(t,t.uint32(),{limits:null===(s=n.limits)||void 0===s?void 0:s.peer});break;case 3:var l;i.limit=Yu.codec().decode(t,t.uint32(),{limits:null===(l=n.limits)||void 0===l?void 0:l.limit});break;case 4:i.status=Ju.codec().decode(t);break;default:t.skipType(7&a)}}return i}))),r),e.encode=t=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(Ku||(Ku={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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:He(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 dl('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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(Wu||(Wu={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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),Xu.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 dl('Decode error - map field "addrs" had too many elements');n.addrs.push(e.bytes());break;case 3:var s;n.voucher=Xu.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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(Qu||(Qu={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(Yu||(Yu={})),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"}(Ju||(Ju={})),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"}(Zu||(Zu={})),function(e){e.codec=()=>cl(Zu)}(Ju||(Ju={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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:He(0),peer:He(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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}($u||($u={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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),$u.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:He(0),payloadType:He(0),signature:He(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=$u.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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(Xu||(Xu={}));var rd=e=>({match:t=>!(t.length<1)&&(!!e(t[0])&&t.slice(1)),pattern:"fn"}),nd=e=>({match:t=>rd((t=>t===e)).match(t),pattern:e}),id=()=>({match:e=>rd((e=>"string"==typeof e)).match(e),pattern:"{string}"}),od=()=>({match:e=>rd((e=>!isNaN(parseInt(e)))).match(e),pattern:"{number}"}),ad=()=>({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{j.decode("z".concat(e[1]))}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),sd=()=>({match:e=>{if(e.length<2)return!1;if("certhash"!==e[0])return!1;try{q.decode(e[1])}catch(e){return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),ld=e=>({match:t=>{var r=e.match(t);return!1===r?t:r},pattern:"optional(".concat(e.pattern,")")}),cd=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(", "),")")}},ud=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 dd(){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 hd=dd(ad()),pd=ud(nd("dns4"),id()),fd=ud(nd("dns6"),id()),vd=ud(nd("dnsaddr"),id()),yd=ud(nd("dns"),id());dd(pd,ld(ad())),dd(fd,ld(ad())),dd(vd,ld(ad()));var gd=dd(cd(yd,vd,pd,fd),ld(ad())),md=ud(nd("ip4"),rd(Pt)),wd=ud(nd("ip6"),rd(Et)),bd=cd(md,wd),_d=cd(bd,yd,pd,fd,vd),Sd=dd(cd(bd,ud(cd(yd,vd,pd,fd),ld(ad())))),Pd=dd(md),Ed=dd(wd),Ad=dd(bd),kd=ud(_d,nd("tcp"),od()),xd=ud(_d,nd("udp"),od()),Td=dd(ud(kd,ld(ad())));dd(xd);var Id=ud(xd,nd("quic"),ld(ad())),Cd=ud(xd,nd("quic-v1"),ld(ad())),Bd=cd(Id,Cd);dd(Id);var Nd=dd(Cd),Dd=cd(_d,kd,xd,Id,Cd),Gd=cd(ud(Dd,nd("ws"),ld(ad()))),Rd=dd(Gd),Od=cd(ud(Dd,nd("wss"),ld(ad())),ud(Dd,nd("tls"),ld(ud(nd("sni"),id())),nd("ws"),ld(ad()))),Ld=dd(Od),Md=ud(xd,nd("webrtc-direct"),ld(sd()),ld(sd()),ld(ad())),jd=dd(Md),Fd=ud(Cd,nd("webtransport"),ld(sd()),ld(sd()),ld(ad())),Ud=dd(Fd),zd=cd(Gd,Od,ud(kd,ld(ad())),ud(Bd,ld(ad())),ud(_d,ld(ad())),Md,Fd,ad()),Vd=dd(zd),qd=dd(ud(zd,nd("p2p-circuit"),ad())),Hd=dd(cd(ud(zd,nd("p2p-circuit"),nd("webrtc"),ld(ad())),ud(zd,nd("webrtc"),ld(ad())),ud(nd("webrtc"),ld(ad())))),Kd=dd(cd(ud(_d,nd("tcp"),od(),nd("http"),ld(ad())),ud(_d,nd("http"),ld(ad())))),Wd=dd(cd(ud(_d,nd("tcp"),cd(ud(nd("443"),nd("http")),ud(od(),nd("https")),ud(od(),nd("tls"),nd("http"))),ld(ad())),ud(_d,nd("tls"),nd("http"),ld(ad())),ud(_d,nd("https"),ld(ad()))));function Qd(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}dd(cd(ud(nd("memory"),id(),ld(ad()))));class Yd extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","HadEnoughRelaysError")}}e._defineProperty(Yd,"name","HadEnoughRelaysError");class Jd extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","DoubleRelayError")}}e._defineProperty(Jd,"name","DoubleRelayError");class Zd extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","RelayQueueFullError")}}function $d(e){var t=e*BigInt(1e3),r=(new Date).getTime();return Number(t-BigInt(r))}e._defineProperty(Zd,"name","RelayQueueFullError");class Xd{constructor(t){e._defineProperty(this,"expires",void 0),e._defineProperty(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 eh=dd(ud(Vd.matchers[0],nd("p2p-circuit"))),th=dd(nd("p2p-circuit"));function rh(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 nh(e){return tc(Ae(j.decode("z".concat(e))))}class ih{constructor(t){if(e._defineProperty(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 rh(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 rh(this.map.values(),(e=>e.key))}values(){return rh(this.map.values(),(e=>e.value))}get size(){return this.map.size}}class oh{constructor(t){if(e._defineProperty(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 rh(this.set.entries(),(e=>{var t=nh(e[0]);return[t,t]}))}forEach(e){this.set.forEach((t=>{var r=nh(t);e(r,r,this)}))}has(e){return this.set.has(e.toString())}values(){return rh(this.set.values(),(e=>nh(e)))}intersection(e){var t=new oh;for(var r of e)this.has(r)&&t.add(r);return t}difference(e){var t=new oh;for(var r of this)e.has(r)||t.add(r);return t}union(e){var t=new oh;for(var r of e)t.add(r);for(var n of this)t.add(n);return t}}var ah={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},sh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},lh=new globalThis.TextEncoder;function ch(e){var{size:t=32,utf8Buffer:r}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!ah[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=ah[t],i=sh[t],o=e;o.length>0;){var a=lh.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=lh.encode(e)}return function(e,t){for(var r=ah[t],n=sh[t],i=0;i<e.length;i++)n^=BigInt(e[i]),n=BigInt.asUintN(t,n*r);return n}(e,t)}var uh={hash:e=>Number(ch(e,{size:32})),hashV:(e,t)=>function(e){var t=e.toString(16);t.length%2==1&&(t="0".concat(t));return nt(t,"base16")}(uh.hash(e,t))};class dh{constructor(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:2;if(e._defineProperty(this,"fp",void 0),e._defineProperty(this,"h",void 0),e._defineProperty(this,"seed",void 0),i>64)throw new TypeError("Invalid Fingerprint Size");for(var o=r.hashV(t,n),a=He(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&&rt(this.fp,e.fp)}}function hh(e,t){return Math.floor(Math.random()*(t-e))+e}let ph=class{constructor(t){e._defineProperty(this,"contents",void 0),this.contents=new Array(t).fill(null)}has(e){if(!(e instanceof dh))throw new TypeError("Invalid Fingerprint");return this.contents.some((t=>e.equals(t)))}add(e){if(!(e instanceof dh))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 dh))throw new TypeError("Invalid Fingerprint");var t=hh(0,this.contents.length-1),r=this.contents[t];return this.contents[t]=e,r}remove(e){if(!(e instanceof dh))throw new TypeError("Invalid Fingerprint");var t=this.contents.findIndex((t=>e.equals(t)));return t>-1&&(this.contents[t]=null,!0)}};class fh{constructor(t){var r,n,i,o;e._defineProperty(this,"bucketSize",void 0),e._defineProperty(this,"filterSize",void 0),e._defineProperty(this,"fingerprintSize",void 0),e._defineProperty(this,"buckets",void 0),e._defineProperty(this,"count",void 0),e._defineProperty(this,"hash",void 0),e._defineProperty(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:uh,this.seed=null!==(o=t.seed)&&void 0!==o?o:hh(0,Math.pow(2,10))}add(e){"string"==typeof e&&(e=nt(e));var t=new dh(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 ph(this.bucketSize)),null==this.buckets[n]&&(this.buckets[n]=new ph(this.bucketSize)),this.buckets[r].add(t)||this.buckets[n].add(t))return this.count++,!0;var i=[r,n],o=i[hh(0,i.length-1)];null==this.buckets[o]&&(this.buckets[o]=new ph(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 ph(this.bucketSize)),this.buckets[o].add(s)))return this.count++,!0}return!1}has(e){var t,r,n,i;"string"==typeof e&&(e=nt(e));var o=new dh(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=nt(e));var o=new dh(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,c=null!==(n=null===(i=this.buckets[l])||void 0===i?void 0:i.remove(o))&&void 0!==n&&n;return c&&this.count--,c}get reliable(){return Math.floor(this.count/this.filterSize*100)<=90}}var vh={1:.5,2:.84,4:.95,8:.98};class yh{constructor(t){var r,n,i,o,a,s;e._defineProperty(this,"filterSize",void 0),e._defineProperty(this,"bucketSize",void 0),e._defineProperty(this,"fingerprintSize",void 0),e._defineProperty(this,"scale",void 0),e._defineProperty(this,"filterSeries",void 0),e._defineProperty(this,"hash",void 0),e._defineProperty(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:uh,this.seed=null!==(s=t.seed)&&void 0!==s?s:hh(0,Math.pow(2,10)),this.filterSeries=[new fh({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=nt(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 fh({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=nt(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=nt(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 gh(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:.001,n=arguments.length>2?arguments[2]:void 0;return new yh(e._objectSpread2(e._objectSpread2({},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=vh[r];return{filterSize:Math.round(e/n),bucketSize:r,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*r)),64)}}(t,r)),null!=n?n:{}))}class mh{constructor(t,r){e._defineProperty(this,"filter",void 0),this.filter=gh(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 wh(e){return new mh(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:.001)}class bh extends ih{constructor(t){super(),e._defineProperty(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 _h(e){var{name:t,metrics:r}=e;return null!=r?new bh({name:t,metrics:r}):new ih}function Sh(e){return null!=(null==e?void 0:e.then)}function Ph(t,r){var n=0;if(null!=t[Symbol.asyncIterator])return e._wrapAsyncGenerator((function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value,u=r(c,n++);Sh(u)&&(yield e._awaitAsyncGenerator(u)),yield c}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}))();var i=Ic(t),{value:o,done:a}=i.next();if(!0===a)return function*(){}();var s=r(o,n++);if("function"==typeof(null==s?void 0:s.then))return e._wrapAsyncGenerator((function*(){for(var t of(yield o,i)){var a=r(t,n++);Sh(a)&&(yield e._awaitAsyncGenerator(a)),yield t}}))();var l=r;return function*(){for(var e of(yield o,i))l(e,n++),yield e}()}function Eh(t){var{stream:r,remoteAddr:n,logger:i,onDataRead:o,onDataWrite:a}=t,s=i.forComponent("libp2p:stream:converter"),l=!1,c=!1,u=r.close.bind(r);r.close=function(){var t=e._asyncToGenerator((function*(e){yield u(e),f(!0)}));return function(e){return t.apply(this,arguments)}}();var d=r.abort.bind(r);r.abort=e=>{d(e),f(!0)};var h=r.sink.bind(r);r.sink=function(){var t=e._asyncToGenerator((function*(e){try{yield h(iu(e,(e=>Ph(e,(e=>null==a?void 0:a(e))))))}catch(e){"aborted"!==e.type&&s.error("%s error in sink",n,e)}finally{c=!0,f()}}));return function(e){return t.apply(this,arguments)}}();var p={log:s,sink:r.sink,source:e._wrapAsyncGenerator((function*(){try{var t,n=!1,i=!1;try{for(var a,s=e._asyncIterator(r.source);n=!(a=yield e._awaitAsyncGenerator(s.next())).done;n=!1){var c=a.value;null==o||o(c),yield c}}catch(e){i=!0,t=e}finally{try{n&&null!=s.return&&(yield e._awaitAsyncGenerator(s.return()))}finally{if(i)throw t}}}finally{l=!0,f()}}))(),remoteAddr:n,timeline:{open:Date.now(),close:void 0},close:r.close,abort:r.abort};function f(e){!0===e&&(l=!0,c=!0),l&&c&&null==p.timeline.close&&(p.timeline.close=Date.now())}return p}class Ah extends Event{constructor(t,r){super(t),e._defineProperty(this,"type",void 0),e._defineProperty(this,"detail",void 0),this.type=t,this.detail=r}}let kh=class extends Error{constructor(t,r){super(null!=t?t:"The operation was aborted"),e._defineProperty(this,"type",void 0),e._defineProperty(this,"code",void 0),this.type="aborted",this.name="AbortError",this.code=null!=r?r:"ABORT_ERR"}};function xh(e,t,r,n){return Th.apply(this,arguments)}function Th(){return Th=e._asyncToGenerator((function*(e,t,r,n){var i=new kh(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",u),e.removeEventListener(t,l),null!=(null==n?void 0:n.errorEvent)&&e.removeEventListener(n.errorEvent,c)}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)},c=e=>{s(),a(e.detail)},u=()=>{s(),a(i)};null==r||r.addEventListener("abort",u),e.addEventListener(t,l),null!=(null==n?void 0:n.errorEvent)&&e.addEventListener(n.errorEvent,c)}))})),Th.apply(this,arguments)}function Ih(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 Ch 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._defineProperty(this,"remainingPoints",void 0),e._defineProperty(this,"msBeforeNext",void 0),e._defineProperty(this,"consumedPoints",void 0),e._defineProperty(this,"isFirstInDuration",void 0),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}}let Bh=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The queue was full"),this.name="QueueFullError"}};e._defineProperty(Bh,"name","QueueFullError");let Nh=class{constructor(t){var r;e._defineProperty(this,"deferred",void 0),e._defineProperty(this,"signal",void 0),this.signal=t,this.deferred=Hc(),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 Wo)}cleanup(){var e;null===(e=this.signal)||void 0===e||e.removeEventListener("abort",this.onAbort)}};let Dh=class{constructor(t,r){e._defineProperty(this,"id",void 0),e._defineProperty(this,"fn",void 0),e._defineProperty(this,"options",void 0),e._defineProperty(this,"recipients",void 0),e._defineProperty(this,"status",void 0),e._defineProperty(this,"timeline",void 0),e._defineProperty(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 Wo),this.cleanup())}join(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e,n=t.length>0&&void 0!==t[0]?t[0]:{},i=new Nh(n.signal);return r.recipients.push(i),null===(e=n.signal)||void 0===e||e.addEventListener("abort",r.onAbort),i.deferred.promise}))()}run(){var t=this;return e._asyncToGenerator((function*(){t.status="running",t.timeline.started=Date.now();try{var r;t.controller.signal.throwIfAborted();var n=yield Zc(t.fn(e._objectSpread2(e._objectSpread2({},null!==(r=t.options)&&void 0!==r?r:{}),{},{signal:t.controller.signal})),t.controller.signal);t.recipients.forEach((e=>{e.deferred.resolve(n)})),t.status="complete"}catch(e){t.recipients.forEach((t=>{t.deferred.reject(e)})),t.status="errored"}finally{t.timeline.finished=Date.now(),t.cleanup()}}))()}cleanup(){this.recipients.forEach((e=>{var t;e.cleanup(),null===(t=e.signal)||void 0===t||t.removeEventListener("abort",this.onAbort)}))}},Gh=class extends Aa{constructor(){var t,r,n,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(super(),e._defineProperty(this,"concurrency",void 0),e._defineProperty(this,"maxSize",void 0),e._defineProperty(this,"queue",void 0),e._defineProperty(this,"pending",void 0),e._defineProperty(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=Ih(this.emitEmpty.bind(this),1),this.emitIdle=Ih(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(t,r){var n=this;return e._asyncToGenerator((function*(){var e;if(null==r||null===(e=r.signal)||void 0===e||e.throwIfAborted(),n.size===n.maxSize)throw new Bh;var i=new Dh(t,r);return n.enqueue(i),n.safeDispatchEvent("add"),n.tryToStartAnother(),i.join(r).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 Wo)})),this.clear()}onEmpty(t){var r=this;return e._asyncToGenerator((function*(){0!==r.size&&(yield xh(r,"empty",null==t?void 0:t.signal))}))()}onSizeLessThan(t,r){var n=this;return e._asyncToGenerator((function*(){n.size<t||(yield xh(n,"next",null==r?void 0:r.signal,{filter:()=>n.size<t}))}))()}onIdle(t){var r=this;return e._asyncToGenerator((function*(){0===r.pending&&0===r.size||(yield xh(r,"idle",null==t?void 0:t.signal))}))()}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}toGenerator(t){var r=this;return e._wrapAsyncGenerator((function*(){var n,i;null==t||null===(n=t.signal)||void 0===n||n.throwIfAborted();var o=Yc({objectMode:!0}),a=e=>{null!=e?r.abort():r.clear(),o.end(e)},s=e=>{null!=e.detail&&o.push(e.detail)},l=e=>{a(e.detail)},c=()=>{a()},u=()=>{a(new Wo("Queue aborted"))};r.addEventListener("completed",s),r.addEventListener("error",l),r.addEventListener("idle",c),null==t||null===(i=t.signal)||void 0===i||i.addEventListener("abort",u);try{yield*e._asyncGeneratorDelegate(e._asyncIterator(o),e._awaitAsyncGenerator)}finally{var d;r.removeEventListener("completed",s),r.removeEventListener("error",l),r.removeEventListener("idle",c),null==t||null===(d=t.signal)||void 0===d||d.removeEventListener("abort",u),a()}}))()}};class Rh extends Gh{has(e){return null!=this.find(e)}find(e){return this.queue.find((t=>e.equals(t.options.peerId)))}}class Oh extends Aa{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"registrar",void 0),e._defineProperty(this,"connectionManager",void 0),e._defineProperty(this,"randomWalk",void 0),e._defineProperty(this,"started",void 0),e._defineProperty(this,"running",void 0),e._defineProperty(this,"topologyId",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"discoveryController",void 0),e._defineProperty(this,"filter",void 0),e._defineProperty(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 t=this;return e._asyncToGenerator((function*(){t.topologyId=yield t.registrar.register(ed,{filter:t.filter,onConnect:e=>{var r,n;t.log.trace("discovered relay %p queue (length: %d, active %d)",e,null===(r=t.queue)||void 0===r?void 0:r.size,null===(n=t.queue)||void 0===n?void 0:n.running),t.safeDispatchEvent("relay:discover",{detail:e})}}),t.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 t=this;this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,Promise.resolve().then(e._asyncToGenerator((function*(){t.log("searching peer store for relays");var r=yield t.peerStore.all({filters:[e=>e.protocols.includes(ed)],orders:[()=>Math.random()<.5?1:-1,(e,t)=>{var r=Lh(e),n=Lh(t);return r>n?-1:n>r?1:0}]});for(var n of r)t.log.trace("found relay peer %p in peer store",n.id),t.safeDispatchEvent("relay:discover",{detail:n.id});t.log("found %d relay peers in peer store",r.length);var i=t.queue=new Rh({concurrency:5});t.log("start random walk");var o,a=!1,s=!1;try{for(var l,c=function*(){var r,n=l.value;return t.log.trace("found random peer %p",n.id),i.has(n.id)?(t.log.trace("random peer %p was already in queue",n.id),0):(null===(r=t.connectionManager.getConnections(n.id))||void 0===r?void 0:r.length)>0?(t.log.trace("random peer %p was already connected",n.id),0):(yield t.connectionManager.isDialable(n.multiaddrs))?(i.queued>10&&(t.log.trace("wait for space in queue for %p",n.id),yield i.onSizeLessThan(10,{signal:t.discoveryController.signal})),t.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,i.size,i.running),void i.add(e._asyncToGenerator((function*(){var e=Qd([t.discoveryController.signal,AbortSignal.timeout(5e3)]);try{yield t.connectionManager.openConnection(n.id,{signal:e})}finally{e.clear()}})),{peerId:n.id,signal:t.discoveryController.signal}).catch((e=>{t.log.error("error opening connection to random peer %p",n.id,e)}))):(t.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map((e=>e.toString()))),0)},u=e._asyncIterator(t.randomWalk.walk({signal:t.discoveryController.signal}));a=!(l=yield u.next()).done;a=!1)yield*c()}catch(e){s=!0,o=e}finally{try{a&&null!=u.return&&(yield u.return())}finally{if(s)throw o}}t.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 Lh(e){var t=e.metadata.get("last-dial-success");return null==t?0:new Date(Ze(t)).getTime()}class Mh extends Aa{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),e._defineProperty(this,"connectionManager",void 0),e._defineProperty(this,"addressManager",void 0),e._defineProperty(this,"reservationStore",void 0),e._defineProperty(this,"listeningAddrs",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"listenTimeout",void 0),e._defineProperty(this,"reservationId",void 0),e._defineProperty(this,"relay",void 0),e._defineProperty(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._defineProperty(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(t){var r=this;return e._asyncToGenerator((function*(){if(th.exactMatch(t))r.log("searching for circuit relay servers"),r.reservationId=r.reservationStore.reserveRelay();else{if(!eh.exactMatch(t))throw new ma('Could not listen on p2p-circuit address "'.concat(t,'"'));r.log("listen on specific relay server %a",t);var e=AbortSignal.timeout(r.listenTimeout),n=t.decapsulate("/p2p-circuit"),i=yield r.connectionManager.openConnection(n,{signal:e});if(!r.reservationStore.hasReservation(i.remotePeer)){r.log("making reservation on peer %p",i.remotePeer);var o=yield r.reservationStore.addRelay(i.remotePeer,"configured");r.addedRelay(o)}}}))()}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}close(){var t=this;return e._asyncToGenerator((function*(){t.reservationStore.cancelReservations(),t.listeningAddrs=[],t.reservationStore.removeEventListener("relay:removed",t._onRemoveRelayPeer),queueMicrotask((()=>{t.safeDispatchEvent("close")}))}))()}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map((e=>nr(e).encapsulate("/p2p-circuit"))),this.listeningAddrs.forEach((e=>{this.addressManager.confirmObservedAddr(e,{type:"transport"})})),queueMicrotask((()=>{this.safeDispatchEvent("listening")}))}}var jh=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},Fh=new WeakSet;class Uh extends Aa{constructor(t,r){var n,i,o;super(),e._classPrivateMethodInitSpec(this,Fh),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"connectionManager",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"events",void 0),e._defineProperty(this,"reserveQueue",void 0),e._defineProperty(this,"reservations",void 0),e._defineProperty(this,"pendingReservations",void 0),e._defineProperty(this,"maxReservationQueueLength",void 0),e._defineProperty(this,"reservationCompletionTimeout",void 0),e._defineProperty(this,"started",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(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 ih,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=gh(100),this.reserveQueue=new Rh({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",(t=>{null!=[...this.reservations.values()].find((e=>e.connection===t.detail.id))&&e._assertClassBrand(Fh,this,qh).call(this,t.detail.remotePeer).catch((e=>{this.log("could not remove relay %p - %e",t.detail,e)}))}))}isStarted(){return this.started}start(){this.started=!0}afterStart(){var t=this;Promise.resolve().then(e._asyncToGenerator((function*(){var r=yield t.peerStore.all({filters:[e=>e.tags.has(qu)]});t.log("removing tag from %d old relays",r.length),yield Promise.all(r.map(function(){var r=e._asyncToGenerator((function*(e){yield t.peerStore.merge(e.id,{tags:{[qu]:void 0}})}));return function(e){return r.apply(this,arguments)}}())),t.log("redialing %d old relays",r.length),yield Promise.all(r.map(function(){var r=e._asyncToGenerator((function*(e){return t.addRelay(e.id,"discovered")}));return function(e){return r.apply(this,arguments)}}())),e._assertClassBrand(Fh,t,Kh).call(t)}))).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 t=jh();return this.pendingReservations.push(t),e._assertClassBrand(Fh,this,Kh).call(this),t}addRelay(t,r){var n=this;return e._asyncToGenerator((function*(){if(n.peerId.equals(t))throw n.log.trace("not trying to use self as relay"),new ma("Cannot use self as relay");if(n.reserveQueue.size>n.maxReservationQueueLength)throw new Zd("The reservation queue is full");var i=n.reserveQueue.find(t);if(null!=i)return n.log.trace("potential relay peer %p is already in the reservation queue",t),i.join();if(n.relayFilter.has(t.toMultihash().bytes))throw new ma("The relay was previously invalid");return n.log.trace("try to reserve relay slot with %p",t),n.reserveQueue.add(e._asyncToGenerator((function*(){var i=Date.now();try{var o=n.reservations.get(t);if(null!=o){var a=n.connectionManager.getConnections(t),s=!1;if(0===a.length&&n.log("already have relay reservation with %p but we are no longer connected",t),a.map((e=>e.id)).includes(o.connection)&&(n.log("already have relay reservation with %p and the original connection is still open",t),s=!0),s&&$d(o.reservation.expire)>6e5)return n.log("already have relay reservation with %p but we are still connected and it does not expire soon",t),{relay:t,details:o};yield e._assertClassBrand(Fh,n,qh).call(n,t)}if("discovered"===r&&0===n.pendingReservations.length)throw new Yd("Not making reservation on discovered relay because we do not need any more relays");var l=AbortSignal.timeout(n.reservationCompletionTimeout),c=yield n.connectionManager.openConnection(t,{signal:l});if(qd.matches(c.remoteAddr))throw new Jd("not creating reservation over relayed connection");var u=yield e._assertClassBrand(Fh,n,zh).call(n,c,{signal:l}),d=$d(u.expire);n.log("created reservation on relay peer %p, expiry date is %s",t,new Date(Date.now()+d).toString());var h,p=Math.min(Math.max(d-3e5,3e4),Math.pow(2,31)-1),f=setTimeout((()=>{n.log("refresh reservation to relay %p",t),n.addRelay(t,r).catch(function(){var r=e._asyncToGenerator((function*(r){n.log.error("could not refresh reservation to relay %p - %e",t,r),yield e._assertClassBrand(Fh,n,qh).call(n,t)}));return function(e){return r.apply(this,arguments)}}()).catch((e=>{n.log.error("could not remove expired reservation to relay %p - %e",t,e)}))}),p);if("discovered"===r){var v=n.pendingReservations.pop();if(null==v)throw new Yd("Made reservation on relay but did not need any more discovered relays");h={timeout:f,reservation:u,type:r,connection:c.id,id:v}}else h={timeout:f,reservation:u,type:r,connection:c.id};n.reservations.set(t,h),yield n.peerStore.merge(t,{tags:{[qu]:{value:1,ttl:d}}}),e._assertClassBrand(Fh,n,Kh).call(n);var y={relay:t,details:h};return n.safeDispatchEvent("relay:created-reservation",{detail:y}),y}catch(o){throw"discovered"===r&&"HadEnoughRelaysError"===o.name||n.log.error("could not reserve slot on %p after %dms - %e",t,Date.now()-i,o),"DialError"!==o.name&&"UnsupportedProtocolError"!==o.name||n.relayFilter.add(t.toMultihash().bytes),e._assertClassBrand(Fh,n,qh).call(n,t).catch((e=>{n.log.error("could not remove reservation on %p after reserving slot failed - %e",t,e)})),o}})),{peerId:t})}))()}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 zh(e,t){return Vh.apply(this,arguments)}function Vh(){return Vh=e._asyncToGenerator((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(ed,t),a=Vu(o).pb(Hu);this.log.trace("send RESERVE to %p",e.remotePeer),yield a.write({type:Hu.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===Ju.OK&&null!=i.reservation){var s=new Set;for(var l of(s.add(e.remoteAddr.toString()),i.reservation.addrs)){var c=nr(l);null==c.getPeerId()&&(c=c.encapsulate("/p2p/".concat(e.remotePeer))),c=nr(c.toString().replace("/p2p/".concat(e.remotePeer,"/p2p/").concat(e.remotePeer),"/p2p/".concat(e.remotePeer))),s.add(c.toString())}return i.reservation.addrs=[...s].map((e=>nr(e).bytes)),i.reservation}var u="reservation failed with status ".concat(null!==(n=i.status)&&void 0!==n?n:"undefined");throw this.log.error(u),new Error(u)})),Vh.apply(this,arguments)}function qh(e){return Hh.apply(this,arguments)}function Hh(){return Hh=e._asyncToGenerator((function*(t){var r=this.reservations.get(t);null!=r&&(this.log("removing relay reservation with %p from local store",t),clearTimeout(r.timeout),this.reservations.delete(t),"discovered"===r.type&&this.pendingReservations.push(r.id),yield this.peerStore.merge(t,{tags:{[qu]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:t,details:r}}),e._assertClassBrand(Fh,this,Kh).call(this))})),Hh.apply(this,arguments)}function Kh(){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=gh(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}var Wh,Qh=300,Yh=300;class Jh{constructor(t){var r,n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"discovery",void 0),e._defineProperty(this,"registrar",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"connectionManager",void 0),e._defineProperty(this,"transportManager",void 0),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"upgrader",void 0),e._defineProperty(this,"addressManager",void 0),e._defineProperty(this,"connectionGater",void 0),e._defineProperty(this,"reservationStore",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"maxInboundStopStreams",void 0),e._defineProperty(this,"maxOutboundStopStreams",void 0),e._defineProperty(this,"started",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"shutdownController",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/circuit-relay-v2-transport"),e._defineProperty(this,Ba,["@libp2p/transport","@libp2p/circuit-relay-v2-transport"]),e._defineProperty(this,Ko,!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:Qh,this.maxOutboundStopStreams=null!==(n=o.maxOutboundStopStreams)&&void 0!==n?n:Yh,this.shutdownController=new AbortController,this.discovery=new Oh(t,{filter:null!==(i=o.discoveryFilter)&&void 0!==i?i:wh(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 Uh(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[Na](){return null!=this.discovery?["@libp2p/identify"]:[]}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){t.shutdownController=new AbortController,t.shutdownController.signal,yield t.registrar.handle(td,(e=>{var r=t.upgrader.createInboundAbortSignal(t.shutdownController.signal);t.onStop(e,r).catch((r=>{t.log.error("error while handling STOP protocol",r),e.stream.abort(r)})).finally((()=>{r.clear()}))}),{maxInboundStreams:t.maxInboundStopStreams,maxOutboundStreams:t.maxOutboundStopStreams,runOnLimitedConnection:!0}),yield xa(t.discovery,t.reservationStore),t.started=!0}))()}stop(){var t=this;return e._asyncToGenerator((function*(){t.shutdownController.abort(),yield Ia(t.discovery,t.reservationStore),yield t.registrar.unhandle(td),t.started=!1}))()}dial(t,r){var n=this;return e._asyncToGenerator((function*(){if(1!==t.protoCodes().filter((e=>290===e)).length){var i="Invalid circuit relay address";throw n.log.error(i,t),new ga(i)}var o=t.toString().split("/p2p-circuit"),a=nr(o[0]),s=nr(o[o.length-1]),l=a.getPeerId(),c=s.getPeerId();if(null==l||null==c){var u="ircuit relay dial to ".concat(t.toString()," failed as address did not have both relay and destination PeerIDs");throw n.log.error("c".concat(u)),new ga("C".concat(u))}var d,h,p,f=$l(l),v=$l(c),y=n.connectionManager.getConnections(f)[0];null==y?(yield n.peerStore.merge(f,{multiaddrs:[a]}),null===(d=r.onProgress)||void 0===d||d.call(r,new Ah("circuit-relay:open-connection")),y=yield n.connectionManager.openConnection(f,r)):null===(h=r.onProgress)||void 0===h||h.call(r,new Ah("circuit-relay:reuse-connection"));try{var g,m,w;null===(g=r.onProgress)||void 0===g||g.call(r,new Ah("circuit-relay:open-hop-stream"));var b=Vu(p=yield y.newStream(ed,r)),_=b.pb(Hu);null===(m=r.onProgress)||void 0===m||m.call(r,new Ah("circuit-relay:write-connect-message")),yield _.write({type:Hu.Type.CONNECT,peer:{id:v.toMultihash().bytes,addrs:[nr(s).bytes]}},r),null===(w=r.onProgress)||void 0===w||w.call(r,new Ah("circuit-relay:read-connect-response"));var S,P,E=yield _.read(r);if(E.status!==Ju.OK)throw new ha("failed to connect via relay with status ".concat(null!==(S=null==E||null===(P=E.status)||void 0===P?void 0:P.toString())&&void 0!==S?S:"undefined"));var A=new Xd(E.limit),k=Eh({stream:b.unwrap(),remoteAddr:t,localAddr:a.encapsulate("/p2p-circuit/p2p/".concat(n.peerId.toString())),logger:n.logger,onDataRead:A.onData,onDataWrite:A.onData});return n.log("new outbound relayed connection %a",k.remoteAddr),yield n.upgrader.upgradeOutbound(k,e._objectSpread2(e._objectSpread2({},r),{},{limits:A.getLimits()}))}catch(e){var x;throw n.log.error("circuit relay dial to destination %p via relay %p failed",v,f,e),null===(x=p)||void 0===x||x.abort(e),e}}))()}createListener(e){return function(e){return new Mh(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=>eh.exactMatch(e)||th.exactMatch(e)))}dialFilter(e){return(e=Array.isArray(e)?e:[e]).filter((e=>qd.exactMatch(e)))}onStop(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i,{connection:o,stream:a}=t;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=Vu(a).pb(Ku),l=yield s.read({signal:r});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:Ku.Type.STATUS,status:Ju.MALFORMED_MESSAGE},{signal:r}),void(yield a.close());if(l.type!==Ku.Type.CONNECT)return n.log.error("invalid stop connect request via peer %p",o.remotePeer),yield s.write({type:Ku.Type.STATUS,status:Ju.UNEXPECTED_MESSAGE},{signal:r}),void(yield a.close());if(!(e=>{if(null==e.peer)return!1;try{e.peer.addrs.forEach(nr)}catch(e){return!1}return!0})(l))return n.log.error("invalid stop connect request via peer %p",o.remotePeer),yield s.write({type:Ku.Type.STATUS,status:Ju.MALFORMED_MESSAGE},{signal:r}),void(yield a.close({signal:r}));var c=tc(Ae(l.peer.id));if(!0===(yield null===(e=(i=n.connectionGater).denyInboundRelayedConnection)||void 0===e?void 0:e.call(i,o.remotePeer,c)))return n.log.error("connection gater denied inbound relayed connection from %p",o.remotePeer),yield s.write({type:Ku.Type.STATUS,status:Ju.PERMISSION_DENIED},{signal:r}),void(yield a.close({signal:r}));n.log.trace("sending success response to %p",o.remotePeer),yield s.write({type:Ku.Type.STATUS,status:Ju.OK},{signal:r});var u=new Xd(l.limit),d=o.remoteAddr.encapsulate("/p2p-circuit/p2p/".concat(c.toString()));n.addressManager.getAddresses()[0];var h=Eh({stream:s.unwrap().unwrap(),remoteAddr:d,logger:n.logger,onDataRead:u.onData,onDataWrite:u.onData});n.log("new inbound relayed connection %a",h.remoteAddr),yield n.upgrader.upgradeInbound(h,{limits:u.getLimits(),signal:r}),n.log("%s connection %a upgraded","inbound",h.remoteAddr)}))()}}function Zh(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new Jh(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=()=>cl(t)}(e.Flag||(e.Flag={})),e.codec=()=>(null==r&&(r=ul((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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(Wh||(Wh={}));var $h=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],Xh=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),ep=16384;var tp=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ep,t=pt(e-pt(e)),r=1+pt(Object.keys(Wh.Flag).length-1);return t+r+1+pt(e-t-r-1)}(),rp="/webrtc",np="/webrtc-signaling/0.0.1",ip=864e5,op=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))},ap=function(e,t,r){this.name=e,this.version=t,this.os=r,this.type="browser"},sp=function(t){this.version=t,this.type="node",this.name="node",this.os=e.process.platform},lp=function(e,t,r,n){this.name=e,this.version=t,this.os=r,this.bot=n,this.type="bot-device"},cp=function(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null},up=function(){this.type="react-native",this.name="react-native",this.version=null,this.os=null},dp=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,hp=[["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/]],pp=[["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 fp extends Error{constructor(e){super(e),this.name="TimeoutError"}}let vp=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}};var yp=e=>void 0===globalThis.DOMException?new vp(e):new DOMException(e),gp=e=>{var t=void 0===e.reason?yp("This operation was aborted."):e.reason;return t instanceof Error?t:yp(t)};function mp(t,r){var n,i,{milliseconds:o,fallback:a,message:s,customTimers:l={setTimeout:setTimeout,clearTimeout:clearTimeout}}=r,c=new Promise(((c,u)=>{if("number"!=typeof o||1!==Math.sign(o))throw new TypeError("Expected `milliseconds` to be a positive number, got `".concat(o,"`"));if(r.signal){var{signal:d}=r;d.aborted&&u(gp(d)),i=()=>{u(gp(d))},d.addEventListener("abort",i,{once:!0})}if(o!==Number.POSITIVE_INFINITY){var h=new fp;n=l.setTimeout.call(void 0,(()=>{if(a)try{c(a())}catch(e){u(e)}else"function"==typeof t.cancel&&t.cancel(),!1===s?c():s instanceof Error?u(s):(h.message=null!=s?s:"Promise timed out after ".concat(o," milliseconds"),u(h))}),o),e._asyncToGenerator((function*(){try{c(yield t)}catch(e){u(e)}}))()}else t.then(c,u)})),u=c.finally((()=>{u.clear(),i&&r.signal&&r.signal.removeEventListener("abort",i)}));return u.clear=()=>{l.clearTimeout.call(void 0,n),n=void 0},u}var wp="undefined"==typeof document&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product?new up:"undefined"!=typeof navigator?function(e){var t=function(e){return""!==e&&hp.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 cp;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length<3&&(i=op(op([],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=pp.length;t<r;t++){var n=pp[t],i=n[0];if(n[1].exec(e))return i}return null}(e),s=dp.exec(e);return s&&s[1]?new lp(r,o,a,s[1]):new ap(r,o,a)}(navigator.userAgent):void 0!==e.process&&e.process.version?new sp(e.process.version.slice(1)):null,bp=null!=wp&&"firefox"===wp.name,_p=function(){var t=e._wrapAsyncGenerator((function*(){}));return function(){return t.apply(this,arguments)}}(),Sp=function(){var t=e._asyncToGenerator((function*(e){}));return function(e){return t.apply(this,arguments)}}();function Pp(e){return Ep.apply(this,arguments)}function Ep(){return(Ep=e._asyncToGenerator((function*(e){var t;return"function"==typeof(e=null!=e?e:{})&&(e=yield e()),e.iceServers=null!==(t=e.iceServers)&&void 0!==t?t:$h.map((e=>({urls:[e]}))),e}))).apply(this,arguments)}class Ap{constructor(t,r){e._defineProperty(this,"log",void 0),e._defineProperty(this,"peerConnection",void 0),e._defineProperty(this,"remoteAddr",void 0),e._defineProperty(this,"timeline",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"source",_p()),e._defineProperty(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(t){var r=this;return e._asyncToGenerator((function*(){var e;r.log.trace("closing connection"),r.peerConnection.close(),r.timeline.close=Date.now(),null===(e=r.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 kp(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 xp(e,t){var r,n,i,o=null===(r=(n=kp(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 Tp(e){return null!=e&&("function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally)}class Ip{constructor(t){var r,n;e._defineProperty(this,"id",void 0),e._defineProperty(this,"direction",void 0),e._defineProperty(this,"timeline",void 0),e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"metadata",void 0),e._defineProperty(this,"source",void 0),e._defineProperty(this,"status",void 0),e._defineProperty(this,"readStatus",void 0),e._defineProperty(this,"writeStatus",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"sinkController",void 0),e._defineProperty(this,"sinkEnd",void 0),e._defineProperty(this,"closed",void 0),e._defineProperty(this,"endErr",void 0),e._defineProperty(this,"streamSource",void 0),e._defineProperty(this,"onEnd",void 0),e._defineProperty(this,"onCloseRead",void 0),e._defineProperty(this,"onCloseWrite",void 0),e._defineProperty(this,"onReset",void 0),e._defineProperty(this,"onAbort",void 0),e._defineProperty(this,"sendCloseWriteTimeout",void 0),e._defineProperty(this,"sendingData",void 0),this.sinkController=new AbortController,this.sinkEnd=Hc(),this.closed=Hc(),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=Yc({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(t){var r=this;return e._asyncToGenerator((function*(){if("ready"!==r.writeStatus)throw new oa('writable end state is "'.concat(r.writeStatus,'" not "ready"'));try{r.writeStatus="writing";var n={signal:r.sinkController.signal};if("outbound"===r.direction){var i=r.sendNewStream(n);Tp(i)&&(yield i)}var o=()=>{xp(t,r.log)};try{r.sinkController.signal.addEventListener("abort",o),r.log.trace("sink reading from source");var a,s=!1,l=!1;try{for(var c,u=e._asyncIterator(t);s=!(c=yield u.next()).done;s=!1){var d=c.value;d=d instanceof Uint8Array?new Oa(d):d;var h=r.sendData(d,n);Tp(h)&&(r.sendingData=Hc(),yield h,r.sendingData.resolve(),r.sendingData=void 0)}}catch(e){l=!0,a=e}finally{try{s&&null!=u.return&&(yield u.return())}finally{if(l)throw a}}}finally{r.sinkController.signal.removeEventListener("abort",o)}r.log.trace('sink finished reading from source, write status is "%s"',r.writeStatus),"writing"===r.writeStatus&&(r.writeStatus="closing",r.log.trace("send close write to remote"),yield r.sendCloseWrite({signal:AbortSignal.timeout(r.sendCloseWriteTimeout)}),r.writeStatus="closed"),r.onSinkEnd()}catch(e){throw r.log.trace("sink ended with error, calling abort with error",e),r.abort(e),e}finally{r.log.trace("resolve sink end"),r.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(t){var r=this;return e._asyncToGenerator((function*(){"open"===r.status&&(r.log.trace("closing gracefully"),r.status="closing",yield Zc(Promise.all([r.closeWrite(t),r.closeRead(t),r.closed.promise]),null==t?void 0:t.signal),r.status="closed",r.log.trace("closed gracefully"))}))()}closeRead(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e=t.length>0&&void 0!==t[0]?t[0]:{};if("closing"!==r.readStatus&&"closed"!==r.readStatus){r.log.trace('closing readable end of stream with starting read status "%s"',r.readStatus);var n=r.readStatus;r.readStatus="closing","reset"!==r.status&&"aborted"!==r.status&&null==r.timeline.closeRead&&(r.log.trace("send close read to remote"),yield r.sendCloseRead(e)),"ready"===n&&(r.log.trace("ending internal source queue with %d queued bytes",r.streamSource.readableLength),r.streamSource.end()),r.log.trace("closed readable end of stream")}}))()}closeWrite(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e=t.length>0&&void 0!==t[0]?t[0]:{};"closing"!==r.writeStatus&&"closed"!==r.writeStatus&&(r.log.trace('closing writable end of stream with starting write status "%s"',r.writeStatus),"ready"===r.writeStatus&&(r.log.trace("sink was never sunk, sink an empty array"),yield Zc(r.sink([]),e.signal)),"writing"===r.writeStatus&&(null!=r.sendingData&&(yield Zc(r.sendingData.promise,e.signal)),r.log.trace("aborting source passed to .sink"),r.sinkController.abort(),yield Zc(r.sinkEnd.promise,e.signal)),r.writeStatus="closed",r.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();Tp(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 ia("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 Cp=4194304;let Bp=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidMessageLengthError"),e._defineProperty(this,"code","ERR_INVALID_MSG_LENGTH")}},Np=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidDataLengthError"),e._defineProperty(this,"code","ERR_MSG_DATA_TOO_LONG")}},Dp=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidDataLengthLengthError"),e._defineProperty(this,"code","ERR_MSG_LENGTH_TOO_LONG")}},Gp=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","UnexpectedEOFError"),e._defineProperty(this,"code","ERR_UNEXPECTED_EOF")}};function Rp(e){return null!=e[Symbol.asyncIterator]}function Op(e,t){if(e.byteLength>t)throw new Np("Message length too long")}var Lp,Mp=e=>{var t=pt(e),r=Ke(t);return yt(e,r),Mp.bytes=t,r};function jp(t,r){var n,i,o,a=null!==(n=(r=null!=r?r:{}).lengthEncoder)&&void 0!==n?n:Mp,s=null!==(i=null===(o=r)||void 0===o?void 0:o.maxDataLength)&&void 0!==i?i:Cp;function*l(e){Op(e,s);var t=a(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return Rp(t)?e._wrapAsyncGenerator((function*(){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t);n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var s=o.value;yield*e._asyncGeneratorDelegate(e._asyncIterator(l(s)),e._awaitAsyncGenerator)}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw r}}}))():function*(){for(var e of t)yield*l(e)}()}Mp.bytes=0,jp.single=(e,t)=>{var r,n,i,o=null!==(r=(t=null!=t?t:{}).lengthEncoder)&&void 0!==r?r:Mp;return Op(e,null!==(n=null===(i=t)||void 0===i?void 0:i.maxDataLength)&&void 0!==n?n:Cp),new Oa(o(e.byteLength),e)},function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(Lp||(Lp={}));var Fp=e=>{var t=gt(e);return Fp.bytes=pt(t),t};function Up(t,r){var n,i,o,a=new Oa,s=Lp.LENGTH,l=-1,c=null!==(n=null==r?void 0:r.lengthDecoder)&&void 0!==n?n:Fp,u=null!==(i=null==r?void 0:r.maxLengthLength)&&void 0!==i?i:8,d=null!==(o=null==r?void 0:r.maxDataLength)&&void 0!==o?o:Cp;function*h(){for(;a.byteLength>0;){if(s===Lp.LENGTH)try{if((l=c(a))<0)throw new Bp("Invalid message length");if(l>d)throw new Np("Message length too long");var e=c.bytes;a.consume(e),null!=(null==r?void 0:r.onLength)&&r.onLength(l),s=Lp.DATA}catch(e){if(e instanceof RangeError){if(a.byteLength>u)throw new Dp("Message length length too long");break}throw e}if(s===Lp.DATA){if(a.byteLength<l)break;var t=a.sublist(0,l);a.consume(l),null!=(null==r?void 0:r.onData)&&r.onData(t),yield t,s=Lp.LENGTH}}}return Rp(t)?e._wrapAsyncGenerator((function*(){var r,n=!1,i=!1;try{for(var o,s=e._asyncIterator(t);n=!(o=yield e._awaitAsyncGenerator(s.next())).done;n=!1){var l=o.value;a.append(l),yield*e._asyncGeneratorDelegate(e._asyncIterator(h()),e._awaitAsyncGenerator)}}catch(e){i=!0,r=e}finally{try{n&&null!=s.return&&(yield e._awaitAsyncGenerator(s.return()))}finally{if(i)throw r}}if(a.byteLength>0)throw new Gp("Unexpected end of input")}))():function*(){for(var e of t)a.append(e),yield*h();if(a.byteLength>0)throw new Gp("Unexpected end of input")}()}Fp.bytes=0,Up.fromReader=(t,r)=>{var n=1;return Up(e._wrapAsyncGenerator((function*(){for(;;)try{var{done:r,value:i}=yield e._awaitAsyncGenerator(t.next(n));if(!0===r)return;null!=i&&(yield i)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{n=1}}))(),e._objectSpread2(e._objectSpread2({},null!=r?r:{}),{},{onLength:e=>{n=e}}))};class zp extends Ip{constructor(t){var r,n,i,o,a,s,l=t.onEnd;switch(t.onEnd=t=>{this.log.trace('readable and writeable ends closed with status "%s"',this.status),Promise.resolve(e._asyncToGenerator((function*(){if(null==r.timeline.abort&&null===r.timeline.reset)try{yield mp(r.receiveFinAck.promise,{milliseconds:r.finAckTimeout})}catch(e){r.log.error("error receiving FIN_ACK",e)}}))).then((()=>{this.incomingData.end(),null==l||l(t)})).catch((e=>{this.log.error("error ending stream",e)})).finally((()=>{this.channel.close()}))},super(t),r=this,e._defineProperty(this,"channel",void 0),e._defineProperty(this,"incomingData",void 0),e._defineProperty(this,"maxBufferedAmount",void 0),e._defineProperty(this,"bufferedAmountLowEventTimeout",void 0),e._defineProperty(this,"maxMessageSize",void 0),e._defineProperty(this,"receiveFinAck",void 0),e._defineProperty(this,"finAckTimeout",void 0),e._defineProperty(this,"openTimeout",void 0),e._defineProperty(this,"closeController",void 0),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=Yc(),this.bufferedAmountLowEventTimeout=null!==(n=t.bufferedAmountLowEventTimeout)&&void 0!==n?n:3e4,this.maxBufferedAmount=null!==(i=t.maxBufferedAmount)&&void 0!==i?i:2097152,this.maxMessageSize=(null!==(o=t.maxMessageSize)&&void 0!==o?o:ep)-tp,this.receiveFinAck=Hc(),this.finAckTimeout=null!==(a=t.closeTimeout)&&void 0!==a?a:5e3,this.openTimeout=null!==(s=t.openTimeout)&&void 0!==s?s: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 oa("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 t=e._asyncToGenerator((function*(e){var{data:t}=e;null!==t&&0!==t.byteLength&&r.incomingData.push(new Uint8Array(t,0,t.byteLength))}));return function(e){return t.apply(this,arguments)}}();var c=this;Promise.resolve().then(e._asyncToGenerator((function*(){var t,n=!1,i=!1;try{for(var o,a=e._asyncIterator(Up(r.incomingData));n=!(o=yield a.next()).done;n=!1){var s=o.value,l=c.processIncomingProtobuf(s);null!=l&&c.sourcePush(new Oa(l))}}catch(e){i=!0,t=e}finally{try{n&&null!=a.return&&(yield a.return())}finally{if(i)throw t}}}))).catch((e=>{this.log.error("error processing incoming data channel messages",e)}))}sendNewStream(){}_sendMessage(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=!(r.length>1&&void 0!==r[1])||r[1];if("closed"===n.channel.readyState||"closing"===n.channel.readyState)throw new oa("Invalid datachannel state - ".concat(n.channel.readyState));if("open"!==n.channel.readyState){var i=AbortSignal.timeout(n.openTimeout),o=Qd([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 xh(n.channel,"open",o)}finally{o.clear()}n.log('channel state is now "%s", sending data',n.channel.readyState)}if(e&&n.channel.bufferedAmount>n.maxBufferedAmount){var a=AbortSignal.timeout(n.bufferedAmountLowEventTimeout),s=Qd([n.closeController.signal,a]);try{n.log('channel buffer is %d, wait for "bufferedamountlow" event',n.channel.bufferedAmount),yield xh(n.channel,"bufferedamountlow",s)}catch(e){if(a.aborted)throw new fa("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(t.subarray())}catch(e){n.log.error("error while sending message",e)}}))()}sendData(t){var r=this;return e._asyncToGenerator((function*(){var e=t.byteLength;for(t=t.sublist();t.byteLength>0;){var n=Math.min(t.byteLength,r.maxMessageSize),i=t.subarray(0,n),o=Wh.encode({message:i}),a=jp.single(o);r.log.trace("sending %d/%d bytes on channel",i.byteLength,e),yield r._sendMessage(a),t.consume(n)}r.log.trace('finished sending data, channel state "%s"',r.channel.readyState)}))()}sendReset(){var t=this;return e._asyncToGenerator((function*(){try{yield t._sendFlag(Wh.Flag.RESET)}catch(e){t.log.error("failed to send reset - %e",e)}finally{t.channel.close()}}))()}sendCloseWrite(t){var r=this;return e._asyncToGenerator((function*(){if("open"===r.channel.readyState){if(yield r._sendFlag(Wh.Flag.FIN)){r.log.trace("awaiting FIN_ACK");try{yield Zc(r.receiveFinAck.promise,null==t?void 0:t.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorName:"FinAckNotReceivedError"})}catch(e){r.log.error("failed to await FIN_ACK",e)}}else r.log.trace("sending FIN failed, not awaiting FIN_ACK");r.receiveFinAck.resolve()}else r.receiveFinAck.resolve()}))()}sendCloseRead(){var t=this;return e._asyncToGenerator((function*(){"open"===t.channel.readyState&&(yield t._sendFlag(Wh.Flag.STOP_SENDING))}))()}processIncomingProtobuf(e){var t=Wh.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===Wh.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Wh.Flag.FIN_ACK).catch((e=>{this.log.error("error sending FIN_ACK immediately",e)}))),t.flag===Wh.Flag.RESET&&this.reset(),t.flag===Wh.Flag.STOP_SENDING&&this.remoteCloseRead(),t.flag===Wh.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),"ready"===this.readStatus)return t.message}_sendFlag(t){var r=this;return e._asyncToGenerator((function*(){if("open"!==r.channel.readyState)return r.log.trace('not sending flag %s because channel is "%s" and not "open"',t.toString(),r.channel.readyState),!1;r.log.trace("sending flag %s",t.toString());var e=Wh.encode({flag:t}),n=jp.single(e);try{return yield r._sendMessage(n,!1),!0}catch(e){r.log.error("could not send flag %s - %e",t.toString(),e)}return!1}))()}}function Vp(t){var{channel:r,direction:n,handshake:i}=t;return new zp(e._objectSpread2({id:"".concat(r.id),log:t.logger.forComponent("libp2p:webrtc:stream:".concat(!0===i?"handshake":n,":").concat(r.id))},t))}class qp{constructor(t,r){var n,i;e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"peerConnection",void 0),e._defineProperty(this,"bufferedStreams",[]),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"dataChannelOptions",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"log",void 0),this.components=t,this.peerConnection=r.peerConnection,this.metrics=r.metrics,this.protocol=null!==(n=r.protocol)&&void 0!==n?n:rp,this.dataChannelOptions=null!==(i=r.dataChannelOptions)&&void 0!==i?i:{},this.log=t.logger.forComponent("libp2p:webrtc:muxerfactory"),this.peerConnection.ondatachannel=r=>{var{channel:n}=r;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=Vp(e._objectSpread2({channel:n,direction:"inbound",onEnd:e=>{i.onEnd(e)},logger:t.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(t){return new Kp(this.components,e._objectSpread2(e._objectSpread2({},t),{},{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol}))}}var Hp=new WeakSet;class Kp{constructor(t,r){var n,i;e._classPrivateMethodInitSpec(this,Hp),e._defineProperty(this,"init",void 0),e._defineProperty(this,"streams",void 0),e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"peerConnection",void 0),e._defineProperty(this,"dataChannelOptions",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"source",_p()),e._defineProperty(this,"sink",Sp),this.init=r,this.log=t.logger.forComponent("libp2p:webrtc:muxer"),this.logger=t.logger,this.streams=r.streams.map((e=>e.stream)),this.peerConnection=r.peerConnection,this.protocol=null!==(n=r.protocol)&&void 0!==n?n:rp,this.metrics=r.metrics,this.dataChannelOptions=null!==(i=r.dataChannelOptions)&&void 0!==i?i:{},this.peerConnection.ondatachannel=t=>{var n,i,{channel:o}=t;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=Vp(e._objectSpread2({channel:o,direction:"inbound",onEnd:()=>{e._assertClassBrand(Hp,this,Wp).call(this,s,o),this.log("incoming channel %s ended",a)},logger:this.logger},this.dataChannelOptions));this.streams.push(s),null===(n=this.metrics)||void 0===n||n.increment({incoming_stream:!0}),null==r||null===(i=r.onIncomingStream)||void 0===i||i.call(r,s)},this.init.streams.length>0&&queueMicrotask((()=>{this.init.streams.forEach((t=>{var r,n,i;t.onEnd=()=>{this.log("incoming early channel %s ended with state %s",t.channel.id,t.channel.readyState),e._assertClassBrand(Hp,this,Wp).call(this,t.stream,t.channel)},null===(r=this.metrics)||void 0===r||r.increment({incoming_stream:!0}),null===(n=this.init)||void 0===n||null===(i=n.onIncomingStream)||void 0===i||i.call(n,t.stream)}))}))}close(t){var r=this;return e._asyncToGenerator((function*(){try{yield Promise.all(r.streams.map(function(){var r=e._asyncToGenerator((function*(e){return e.close(t)}));return function(e){return r.apply(this,arguments)}}()))}catch(e){r.abort(e)}}))()}abort(e){for(var t of this.streams)t.abort(e)}newStream(){var t,r=this.peerConnection.createDataChannel(""),n=r.id;this.log.trace("opened outgoing datachannel with channel id %s",n);var i=Vp(e._objectSpread2({channel:r,direction:"outbound",onEnd:()=>{e._assertClassBrand(Hp,this,Wp).call(this,i,r),this.log("outgoing channel %s ended",n)},logger:this.logger},this.dataChannelOptions));return this.streams.push(i),null===(t=this.metrics)||void 0===t||t.increment({outgoing_stream:!0}),i}}function Wp(t,r){var n,i,o;this.log.trace("stream %s %s %s onEnd",t.direction,t.id,t.protocol),function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3e4,i=arguments.length>3?arguments[3]:void 0;"open"===t.readyState&&Promise.resolve().then(e._asyncToGenerator((function*(){if(t.bufferedAmount>0){i.log("%s drain channel with %d buffered bytes",r,t.bufferedAmount);var e=Hc(),o=!1;t.bufferedAmountLowThreshold=0;var a=()=>{o||(i.log("%s drain channel closed before drain",r),e.resolve())};t.addEventListener("close",a,{once:!0}),t.addEventListener("bufferedamountlow",(()=>{o=!0,t.removeEventListener("close",a),e.resolve()})),yield mp(e.promise,{milliseconds:n})}}))).then(e._asyncToGenerator((function*(){"open"===t.readyState&&t.close()}))).catch((e=>{i.log.error("error closing outbound stream",e)}))}(r,"".concat(t.direction," ").concat(t.id," ").concat(t.protocol),this.dataChannelOptions.drainTimeout,{log:this.log}),this.streams=this.streams.filter((e=>e.id!==t.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,t)}var Qp,Yp=globalThis.RTCPeerConnection,Jp=globalThis.RTCSessionDescription,Zp=globalThis.RTCIceCandidate;class $p extends Error{constructor(e){super("WebRTC transport error: ".concat(e)),this.name="WebRTCTransportError"}}class Xp extends $p{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SDP handshake failed"),this.name="SDPHandshakeFailedError"}}class ef extends $p{constructor(e,t){super('Invalid fingerprint "'.concat(e,'" within ').concat(t)),this.name="WebRTC/InvalidFingerprintError"}}class tf extends $p{constructor(e){super("A method (".concat(e,") was called though it has been intentionally left unimplemented.")),this.name="WebRTC/UnimplementedError"}}class rf extends $p{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=()=>cl(t)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=ul((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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(Qp||(Qp={}));var nf=function(){var t=e._asyncToGenerator((function*(e,t,r){try{var n=Hc();for(!function(e,t){e[bp?"oniceconnectionstatechange":"onconnectionstatechange"]=r=>{switch(of(e)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new ra("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!==Qp.Type.ICE_CANDIDATE)throw new ha("ICE candidate message expected");var s=JSON.parse(null!==(i=o.data)&&void 0!==i?i:"null");if(""!==s&&null!==s){var l=new Zp(s);r.log.trace("%s received new ICE candidate %o",r.direction,s);try{var c;null===(c=r.onProgress)||void 0===c||c.call(r,new Ah("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 u;null===(u=r.onProgress)||void 0===u||u.call(r,new Ah("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"!==of(e))throw t}}));return function(e,r,n){return t.apply(this,arguments)}}();function of(e){return bp?e.iceConnectionState:e.connectionState}function af(){return af=e._asyncToGenerator((function*(e){var{rtcConfiguration:t,dataChannel:r,signal:n,metrics:i,multiaddr:o,connectionManager:a,transportManager:s,log:l,logger:c,onProgress:u}=e,{baseAddr:d}=function(e){var t=e.toString().split("/webrtc/");if(2!==t.length)throw new Jo("webrtc protocol was not present in multiaddr");if(!t[0].includes("/p2p-circuit"))throw new Jo("p2p-circuit protocol was not present in multiaddr");var r=nr(t[0]),n=nr("/"+t[1]).getPeerId();if(null==n)throw new Jo("destination peer id was missing");var i=r.protos().pop();if(void 0===i)throw new Jo("invalid multiaddr");"p2p"!==i.name&&(r=r.encapsulate("/p2p/".concat(n)));return{baseAddr:r,peerId:$l(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 Jo("Relay peer was missing");var p,f=a.getConnections($l(h)),v=!1;0===f.length?(null==u||u(new Ah("webrtc:dial-relay")),p=yield s.dial(d,{signal:n,onProgress:u}),v=!0):(null==u||u(new Ah("webrtc:reuse-relay-connection")),p=f[0]);try{null==u||u(new Ah("webrtc:open-signaling-stream"));var y=yield p.newStream(np,{signal:n,runOnLimitedConnection:!0}),g=Vu(y).pb(Qp),m=new Yp(t),w=new qp({logger:c},{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),g.write({type:Qp.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 _=yield m.createOffer().catch((e=>{throw l.error("could not execute createOffer",e),new Xp("Failed to set createOffer")}));l.trace("initiator send SDP offer %s",_.sdp),null==u||u(new Ah("webrtc:send-sdp-offer")),yield g.write({type:Qp.Type.SDP_OFFER,data:_.sdp},{signal:n}),yield m.setLocalDescription(_).catch((e=>{throw l.error("could not execute setLocalDescription",e),new Xp("Failed to set localDescription")})),null==u||u(new Ah("webrtc:read-sdp-answer")),l.trace("initiator read SDP answer");var S=yield g.read({signal:n});if(S.type!==Qp.Type.SDP_ANSWER)throw new Xp("Remote should send an SDP answer");l.trace("initiator received SDP answer %s",S.data);var P=new Jp({type:"answer",sdp:S.data});return yield m.setRemoteDescription(P).catch((e=>{throw l.error("could not execute setRemoteDescription",e),new Xp("Failed to set remoteDescription")})),l.trace("initiator read candidates until connected"),null==u||u(new Ah("webrtc:read-ice-candidates")),yield nf(m,g,{direction:"initiator",signal:n,log:l,onProgress:u}),l.trace("initiator connected, closing init channel"),b.close(),null==u||u(new Ah("webrtc:close-signaling-stream")),l.trace("closing signaling channel"),yield y.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(),y.abort(e),e}finally{m.onicecandidate=null,m.onicecandidateerror=null}}finally{if(v)try{yield p.close({signal:n})}catch(e){p.abort(e)}}})),af.apply(this,arguments)}var sf=dd(Vd.matchers[0],nd("p2p-circuit"));class lf extends Aa{constructor(t,r){super(),e._defineProperty(this,"transportManager",void 0),e._defineProperty(this,"shutdownController",void 0),e._defineProperty(this,"events",void 0),this.transportManager=t.transportManager,this.events=t.events,this.shutdownController=r.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}listen(){var t=this;return e._asyncToGenerator((function*(){t.events.addEventListener("transport:listening",t.onTransportListening)}))()}onTransportListening(e){e.detail.getAddrs().filter((e=>sf.exactMatch(e))).map((e=>e.encapsulate("/webrtc"))).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter((e=>!(e instanceof lf))).map((e=>e.getAddrs().filter((e=>sf.exactMatch(e))).map((e=>e.encapsulate("/webrtc"))))).flat()}updateAnnounceAddrs(){}close(){var t=this;return e._asyncToGenerator((function*(){t.events.removeEventListener("transport:listening",t.onTransportListening),t.shutdownController.abort(),queueMicrotask((()=>{t.safeDispatchEvent("close")}))}))()}}function cf(){return cf=e._asyncToGenerator((function*(e){var{peerConnection:t,stream:r,signal:n,connection:i,log:o}=e;o.trace("new inbound signaling stream");var a=Vu(r).pb(Qp);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:Qp.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!==Qp.Type.SDP_OFFER)throw new Xp("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 c=new Jp({type:"offer",sdp:l.data});yield t.setRemoteDescription(c).catch((e=>{throw o.error("could not execute setRemoteDescription",e),new Xp("Failed to set remoteDescription")}));var u=yield t.createAnswer().catch((e=>{throw o.error("could not execute createAnswer",e),new Xp("Failed to create answer")}));o.trace("recipient send SDP answer %s",u.sdp),yield a.write({type:Qp.Type.SDP_ANSWER,data:u.sdp},{signal:n}),yield t.setLocalDescription(u).catch((e=>{throw o.error("could not execute setLocalDescription",e),new Xp("Failed to set localDescription")})),o.trace("recipient read candidates until connected"),yield nf(t,a,{direction:"recipient",signal:n,log:o})}catch(e){if("connected"!==of(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=nr("/webrtc/p2p/".concat(i.remoteAddr.getPeerId()));return o.trace("recipient connected to remote address %s",d),{remoteAddress:d}})),cf.apply(this,arguments)}class uf{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"components",void 0),e._defineProperty(this,"init",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"_started",!1),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"shutdownController",void 0),e._defineProperty(this,Ko,!0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/webrtc"),e._defineProperty(this,Ba,["@libp2p/transport"]),e._defineProperty(this,Na,["@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 t=this;return e._asyncToGenerator((function*(){yield t.components.registrar.handle(np,(e=>{var r=t.components.upgrader.createInboundAbortSignal(t.shutdownController.signal);t._onProtocol(e,r).catch((r=>{t.log.error("failed to handle incoming connect from %p",e.connection.remotePeer,r)})).finally((()=>{r.clear()}))}),{runOnLimitedConnection:!0}),t._started=!0}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield t.components.registrar.unhandle(np),t._started=!1}))()}createListener(e){return new lf(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(Hd.exactMatch)}dialFilter(e){return this.listenFilter(e)}dial(t,r){var n=this;return e._asyncToGenerator((function*(){var e;n.log.trace("dialing address: %a",t);var{remoteAddress:i,peerConnection:o,muxerFactory:a}=yield function(e){return af.apply(this,arguments)}({rtcConfiguration:yield Pp(n.init.rtcConfiguration),dataChannel:n.init.dataChannel,multiaddr:t,dataChannelOptions:n.init.dataChannel,signal:r.signal,connectionManager:n.components.connectionManager,transportManager:n.components.transportManager,log:n.log,logger:n.components.logger,onProgress:r.onProgress}),s=new Ap(n.components,{peerConnection:o,timeline:{open:Date.now()},remoteAddr:i,metrics:null===(e=n.metrics)||void 0===e?void 0:e.dialerEvents}),l=yield r.upgrader.upgradeOutbound(s,{skipProtection:!0,skipEncryption:!0,muxerFactory:a,onProgress:r.onProgress,signal:r.signal});return n._closeOnShutdown(o,s),l}))()}_onProtocol(t,r){var n=this;return e._asyncToGenerator((function*(){var{connection:e,stream:i}=t,o=new Yp(yield Pp(n.init.rtcConfiguration)),a=new qp(n.components,{peerConnection:o,dataChannelOptions:n.init.dataChannel});try{var s,{remoteAddress:l}=yield function(e){return cf.apply(this,arguments)}({peerConnection:o,connection:e,stream:i,signal:r,log:n.log});yield i.close({signal:r});var c=new Ap(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(c,{skipEncryption:!0,skipProtection:!0,muxerFactory:a,signal:r}),n._closeOnShutdown(o,c)}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 df,hf={};!function(){return df||(df=1,function(t){!function(){var r="object"==typeof globalThis?globalThis:"object"==typeof e.commonjsGlobal?e.commonjsGlobal:"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){}}(),n=i(t);function i(e,t){return function(r,n){Object.defineProperty(e,r,{configurable:!0,writable:!0,value:n}),t&&t(r,n)}}void 0!==r.Reflect&&(n=i(r.Reflect,n)),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,c={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]}},u=Object.getPrototypeOf(Function),d="function"==typeof Map&&"function"==typeof Map.prototype.entries?Map:le(),h="function"==typeof Set&&"function"==typeof Set.prototype.entries?Set:ce(),p="function"==typeof WeakMap?WeakMap:ue(),f=n?Symbol.for("@reflect-metadata:registry"):void 0,v=ie(),y=oe(v);function g(e,t,r,n){if(L(r)){if(!K(e))throw new TypeError;if(!Q(t))throw new TypeError;return x(e,t)}if(!K(e))throw new TypeError;if(!F(t))throw new TypeError;if(!F(n)&&!L(n)&&!M(n))throw new TypeError;return M(n)&&(n=void 0),T(e,t,r=H(r),n)}function m(e,t){function r(r,n){if(!F(r))throw new TypeError;if(!L(n)&&!Y(n))throw new TypeError;D(e,t,r,n)}return r}function w(e,t,r,n){if(!F(r))throw new TypeError;return L(n)||(n=H(n)),D(e,t,r,n)}function b(e,t,r){if(!F(t))throw new TypeError;return L(r)||(r=H(r)),I(e,t,r)}function _(e,t,r){if(!F(t))throw new TypeError;return L(r)||(r=H(r)),C(e,t,r)}function S(e,t,r){if(!F(t))throw new TypeError;return L(r)||(r=H(r)),B(e,t,r)}function P(e,t,r){if(!F(t))throw new TypeError;return L(r)||(r=H(r)),N(e,t,r)}function E(e,t){if(!F(e))throw new TypeError;return L(t)||(t=H(t)),G(e,t)}function A(e,t){if(!F(e))throw new TypeError;return L(t)||(t=H(t)),R(e,t)}function k(e,t,r){if(!F(t))throw new TypeError;if(L(r)||(r=H(r)),!F(t))throw new TypeError;L(r)||(r=H(r));var n=se(t,r,!1);return!L(n)&&n.OrdinaryDeleteMetadata(e,t,r)}function x(e,t){for(var r=e.length-1;r>=0;--r){var n=(0,e[r])(t);if(!L(n)&&!M(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(!L(o)&&!M(o)){if(!F(o))throw new TypeError;n=o}}return n}function I(e,t,r){if(C(e,t,r))return!0;var n=re(t);return!M(n)&&I(e,n,r)}function C(e,t,r){var n=se(t,r,!1);return!L(n)&&V(n.OrdinaryHasOwnMetadata(e,t,r))}function B(e,t,r){if(C(e,t,r))return N(e,t,r);var n=re(t);return M(n)?void 0:B(e,n,r)}function N(e,t,r){var n=se(t,r,!1);if(!L(n))return n.OrdinaryGetOwnMetadata(e,t,r)}function D(e,t,r,n){se(r,n,!0).OrdinaryDefineOwnMetadata(e,t,r,n)}function G(e,t){var r=R(e,t),n=re(e);if(null===n)return r;var i=G(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 c=l[s];o.has(c)||(o.add(c),a.push(c))}for(var u=0,d=i;u<d.length;u++){c=d[u];o.has(c)||(o.add(c),a.push(c))}return a}function R(e,t){var r=se(e,t,!1);return r?r.OrdinaryOwnMetadataKeys(e,t):[]}function O(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 L(e){return void 0===e}function M(e){return null===e}function j(e){return"symbol"==typeof e}function F(e){return"object"==typeof e?null!==e:"function"==typeof e}function U(e,t){switch(O(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(F(o))throw new TypeError;return o}return z(e)}function z(e,t){var r,n,i=e.toString;if(W(i)&&!F(n=i.call(e)))return n;if(W(r=e.valueOf)&&!F(n=r.call(e)))return n;throw new TypeError}function V(e){return!!e}function q(e){return""+e}function H(e){var t=U(e);return j(t)?t:q(t)}function K(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function W(e){return"function"==typeof e}function Q(e){return"function"==typeof e}function Y(e){switch(O(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(!W(r))throw new TypeError;return r}}function $(e){var t=Z(e,o);if(!W(t))throw new TypeError;var r=t.call(e);if(!F(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===u)return t;if(t!==u)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;L(f)||void 0===t.Reflect||f in t.Reflect||"function"!=typeof t.Reflect.defineMetadata||(e=ae(t.Reflect));var o=new p,a={registerProvider:s,getProvider:c,setProvider:v};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 L(r):r=t;break;case r===t:break;case L(n):n=t;break;case n===t:break;default:void 0===i&&(i=new h),i.add(t)}}function l(t,o){if(!L(r)){if(r.isProviderFor(t,o))return r;if(!L(n)){if(n.isProviderFor(t,o))return r;if(!L(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(!L(e)&&e.isProviderFor(t,o))return e}function c(e,t){var r,n=o.get(e);return L(n)||(r=n.get(t)),L(r)?(L(r=l(e,t))||(L(n)&&(n=new d,o.set(e,n)),n.set(t,r)),r):r}function u(e){if(L(e))throw new TypeError;return r===e||n===e||!L(i)&&i.has(e)}function v(e,t,r){if(!u(r))throw new Error("Metadata provider not registered.");var n=c(e,t);if(n!==r){if(!L(n))return!1;var i=o.get(e);L(i)&&(i=new d,o.set(e,i)),i.set(t,r)}return!0}}function ie(){var e;return!L(f)&&F(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[f]),L(e)&&(e=ne()),!L(f)&&F(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,f,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}function oe(e){var t=new p,r={isProviderFor:function(e,r){var n=t.get(e);return!L(n)&&n.has(r)},OrdinaryDefineOwnMetadata:a,OrdinaryHasOwnMetadata:i,OrdinaryGetOwnMetadata:o,OrdinaryOwnMetadataKeys:s,OrdinaryDeleteMetadata:l};return v.registerProvider(r),r;function n(n,i,o){var a=t.get(n),s=!1;if(L(a)){if(!o)return;a=new d,t.set(n,a),s=!0}var l=a.get(i);if(L(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!L(i)&&V(i.has(e))}function o(e,t,r){var i=n(t,r,!1);if(!L(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(L(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(L(o))return!1;if(!o.delete(e))return!1;if(0===o.size){var a=t.get(r);L(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 p;return{isProviderFor:function(e,t){var r=a.get(e);return!(L(r)||!r.has(t))||!!i(e,t).length&&(L(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=v.getProvider(e,t);if(!L(n))return n;if(r){if(v.setProvider(e,t,y))return y;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 ce(){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 ue(){var e=16,t=c.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&&c.has(t,this._key)},e.prototype.get=function(e){var t=o(e,!1);return void 0!==t?c.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(c.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:c.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",g),e("metadata",m),e("defineMetadata",w),e("hasMetadata",b),e("hasOwnMetadata",_),e("getMetadata",S),e("getOwnMetadata",P),e("getMetadataKeys",E),e("getOwnMetadataKeys",A),e("deleteMetadata",k)}(n,r),void 0===r.Reflect&&(r.Reflect=t)}()}(t||(t={}))),hf;var t}();var pf,ff={};var vf=function(){if(pf)return ff;pf=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 c=this.toUint8Array(l);a.set(c,s),s+=c.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",ff.BufferSourceConverter=e,ff.Convert=s,ff.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},ff.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},ff.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},ff}();function yf(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 gf(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),c=a-1;c>=0;c--){var u=Math.pow(2,c*t);l[i-c-1]=Math.floor(n/u),n-=l[i-c-1]*u}return s}o*=Math.pow(2,t)}return new ArrayBuffer(0)}function mf(){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 wf(){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=yf(i,8),s=new ArrayBuffer(this.valueHex.byteLength),l=new Uint8Array(s),c=0;c<this.valueHex.byteLength;c++)l[c]=e[c];return l[0]&=127,yf(l,8)-a}function bf(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 _f=["name","optional","primitiveSchema"],Sf=["value"],Pf=["isHexOnly"],Ef=["value","isIndefiniteForm"],Af=["value"],kf=["isConstructed"],xf=["idBlock","lenBlock"],Tf=["unusedBits","isConstructed"],If=["idBlock","lenBlock"],Cf=["value"],Bf=["valueDec","isFirstSid"],Nf=["value"],Df=["valueDec"],Gf=["value"],Rf=["value","valueDate"],Of=["value"],Lf=["value","local"];function Mf(){if("undefined"==typeof BigInt)throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function jf(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 Ff(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 Uf{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return jf(this.items)}}var zf=[new Uint8Array([1])],Vf="0123456789",qf="name",Hf="valueHexView",Kf="",Wf=new ArrayBuffer(0),Qf=new Uint8Array(0),Yf="EndOfContent",Jf="OCTET STRING",Zf="BIT STRING";function $f(t){var r;return r=class extends t{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?vf.BufferSourceConverter.toUint8Array(t.valueHex):Qf}fromBER(e,t,r){var n=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!Ff(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",Wf)}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{isHexOnly:this.isHexOnly,valueHex:vf.Convert.ToHex(this.valueHexView)})}},r.NAME="hexBlock",r}class Xf{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=Kf,warnings:r=[],valueBeforeDecode:n=Qf}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=vf.BufferSourceConverter.toUint8Array(n)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:vf.Convert.ToHex(this.valueBeforeDecodeView)}}}Xf.NAME="baseBlock";class ev extends Xf{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'")}}ev.NAME="valueBlock";class tv extends($f(Xf)){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?vf.BufferSourceConverter.toUint8Array(i.valueHex):Qf,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",Wf}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=gf(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 c=new Uint8Array(this.valueHexView.byteLength+1);if(c[0]=31|t,!e){for(var u=this.valueHexView,d=0;d<u.length-1;d++)c[d+1]=128|u[d];c[this.valueHexView.byteLength]=u[u.length-1]}return c.buffer}fromBER(e,t,r){var n=vf.BufferSourceConverter.toUint8Array(e);if(!Ff(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 c=new Uint8Array(l),u=0;u<s.length;u++)c[u]=s[u];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=yf(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 e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed})}}tv.NAME="identificationBlock";class rv extends Xf{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=vf.BufferSourceConverter.toUint8Array(e);if(!Ff(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=yf(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=gf(this.length,8);if(n.byteLength>127)return this.error="Too big length",Wf;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 e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length})}}rv.NAME="lengthBlock";var nv,iv,ov,av,sv,lv={};class cv extends Xf{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{name:r=Kf,optional:n=!1,primitiveSchema:i}=t,o=e._objectWithoutProperties(t,_f),a=arguments.length>1?arguments[1]:void 0;super(o),this.name=r,this.optional=n,i&&(this.primitiveSchema=i),this.idBlock=new tv(o),this.lenBlock=new rv(o),this.valueBlock=a?new a(o):new ev(o)}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 Uf;t||uv(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?Wf:r.final()}toJSON(){var t=e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional});return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(){return"ascii"===(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"ascii")?this.onAsciiEncoding():vf.Convert.ToHex(this.toBER())}onAsciiEncoding(){var e=this.constructor.NAME,t=vf.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 uv(e){var t;if(e instanceof lv.Constructed)for(var r of e.valueBlock.value)uv(r)&&(e.lenBlock.isIndefiniteForm=!0);return!!(null===(t=e.lenBlock)||void 0===t?void 0:t.isIndefiniteForm)}cv.NAME="BaseBlock";class dv extends cv{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:r=Kf}=t;super(e._objectWithoutProperties(t,Sf),arguments.length>1?arguments[1]:void 0),r&&this.fromString(r)}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,"'")}}dv.NAME="BaseStringBlock";class hv extends($f(ev)){constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{isHexOnly:r=!0}=t;super(e._objectWithoutProperties(t,Pf)),this.isHexOnly=r}}hv.NAME="PrimitiveValueBlock";class pv extends cv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},hv),this.idBlock.isConstructed=!1}}function fv(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 cv({},ev),o=new Xf;if(!Ff(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=cv;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=lv.EndOfContent;break;case 1:s=lv.Boolean;break;case 2:s=lv.Integer;break;case 3:s=lv.BitString;break;case 4:s=lv.OctetString;break;case 5:s=lv.Null;break;case 6:s=lv.ObjectIdentifier;break;case 10:s=lv.Enumerated;break;case 12:s=lv.Utf8String;break;case 13:s=lv.RelativeObjectIdentifier;break;case 14:s=lv.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:s=lv.Sequence;break;case 17:s=lv.Set;break;case 18:s=lv.NumericString;break;case 19:s=lv.PrintableString;break;case 20:s=lv.TeletexString;break;case 21:s=lv.VideotexString;break;case 22:s=lv.IA5String;break;case 23:s=lv.UTCTime;break;case 24:s=lv.GeneralizedTime;break;case 25:s=lv.GraphicString;break;case 26:s=lv.VisibleString;break;case 27:s=lv.GeneralString;break;case 28:s=lv.UniversalString;break;case 29:s=lv.CharacterString;break;case 30:s=lv.BmpString;break;case 31:s=lv.DATE;break;case 32:s=lv.TimeOfDay;break;case 33:s=lv.DateTime;break;case 34:s=lv.Duration;break;default:var l=i.idBlock.isConstructed?new lv.Constructed:new lv.Primitive;l.idBlock=i.idBlock,l.lenBlock=i.lenBlock,l.warnings=i.warnings,i=l}}else s=i.idBlock.isConstructed?lv.Constructed:lv.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 vv(e){if(!e.byteLength){var t=new cv({},ev);return t.error="Input buffer has zero length",{offset:-1,result:t}}return fv(vf.BufferSourceConverter.toUint8Array(e).slice(),0,e.byteLength)}function yv(e,t){return e?1:t}nv=pv,lv.Primitive=nv,pv.NAME="PRIMITIVE";class gv extends ev{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:r=[],isIndefiniteForm:n=!1}=t;super(e._objectWithoutProperties(t,Ef)),this.value=r,this.isIndefiniteForm=n}fromBER(e,t,r){var n=vf.BufferSourceConverter.toUint8Array(e);if(!Ff(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;yv(this.isIndefiniteForm,r)>0;){var o=fv(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===Yf)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Yf?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){for(var r=t||new Uf,n=0;n<this.value.length;n++)this.value[n].toBER(e,r);return t?Wf:r.final()}toJSON(){var t=e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{isIndefiniteForm:this.isIndefiniteForm,value:[]});for(var r of this.value)t.value.push(r.toJSON());return t}}gv.NAME="ConstructedValueBlock";class mv extends cv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},gv),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," :")}}iv=mv,lv.Constructed=iv,mv.NAME="CONSTRUCTED";class wv extends ev{fromBER(e,t,r){return t}toBER(e){return Wf}}wv.override="EndOfContentValueBlock";class bv extends cv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},wv),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}ov=bv,lv.EndOfContent=ov,bv.NAME=Yf;class _v extends cv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},ev),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)}}av=_v,lv.Null=av,_v.NAME="NULL";class Sv extends($f(ev)){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 t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:r}=t,n=e._objectWithoutProperties(t,Af);super(n),n.valueHex?this.valueHexView=vf.BufferSourceConverter.toUint8Array(n.valueHex):this.valueHexView=new Uint8Array(1),r&&(this.value=r)}fromBER(e,t,r){var n=vf.BufferSourceConverter.toUint8Array(e);return Ff(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,wf.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{value:this.value})}}Sv.NAME="BooleanValueBlock";let Pv=class extends cv{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},Sv),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.getValue)}};sv=Pv,lv.Boolean=sv,Pv.NAME="BOOLEAN";class Ev extends($f(gv)){constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{isConstructed:r=!1}=t;super(e._objectWithoutProperties(t,kf)),this.isConstructed=r}fromBER(e,t,r){var n=0;if(this.isConstructed){if(this.isHexOnly=!1,-1===(n=gv.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===Yf){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(o!==Jf)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?gv.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{isConstructed:this.isConstructed})}}var Av;Ev.NAME="OctetStringValueBlock";let kv=class extends cv{constructor(){var t,r,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{idBlock:i={},lenBlock:o={}}=n,a=e._objectWithoutProperties(n,xf);null!==(t=a.isConstructed)&&void 0!==t||(a.isConstructed=!!(null===(r=a.value)||void 0===r?void 0:r.length)),super(e._objectSpread2({idBlock:e._objectSpread2({isConstructed:a.isConstructed},i),lenBlock:e._objectSpread2(e._objectSpread2({},o),{},{isIndefiniteForm:!!a.isIndefiniteForm})},a),Ev),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=fv(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 mv.prototype.onAsciiEncoding.call(this);var e=this.constructor.NAME,t=vf.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 Av&&e.push(t.valueBlock.valueHexView);return vf.BufferSourceConverter.concat(e)}};Av=kv,lv.OctetString=Av,kv.NAME=Jf;class xv extends($f(gv)){constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{unusedBits:r=0,isConstructed:n=!1}=t;super(e._objectWithoutProperties(t,Tf)),this.unusedBits=r,this.isConstructed=n,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,r){if(!r)return t;var n=-1;if(this.isConstructed){if(-1===(n=gv.prototype.fromBER.call(this,e,t,r)))return n;for(var i of this.value){var o=i.constructor.NAME;if(o===Yf){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(o!==Zf)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=vf.BufferSourceConverter.toUint8Array(e);if(!Ff(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 c=l.subarray(1);try{if(c.byteLength){var u=fv(c,0,c.byteLength);-1!==u.offset&&u.offset===r-1&&(this.value=[u.result])}}catch(e){}}return this.valueHexView=l.subarray(1),this.blockLength=l.length,t+r}toBER(e,t){if(this.isConstructed)return gv.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Wf;var r=new Uint8Array(this.valueHexView.length+1);return r[0]=this.unusedBits,r.set(this.valueHexView,1),r.buffer}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{unusedBits:this.unusedBits,isConstructed:this.isConstructed})}}var Tv;xv.NAME="BitStringValueBlock";let Iv=class extends cv{constructor(){var t,r,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{idBlock:i={},lenBlock:o={}}=n,a=e._objectWithoutProperties(n,If);null!==(t=a.isConstructed)&&void 0!==t||(a.isConstructed=!!(null===(r=a.value)||void 0===r?void 0:r.length)),super(e._objectSpread2({idBlock:e._objectSpread2({isConstructed:a.isConstructed},i),lenBlock:e._objectSpread2(e._objectSpread2({},o),{},{isIndefiniteForm:!!a.isIndefiniteForm})},a),xv),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 mv.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 Cv,Bv,Nv,Dv,Gv,Rv,Ov;function Lv(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,c=0,u=0,d=l<a?a:l;d>=0;d--,u++){if(!0==u<s.length)c=o[a-u]+s[l-u]+r[0];else c=o[a-u]+r[0];if(r[0]=c/10,!0==u>=o.length)o=mf(new Uint8Array([c%10]),o);else o[a-u]=c%10}return r[0]>0&&(o=mf(r,o)),o}function Mv(e){if(e>=zf.length)for(var t=zf.length;t<=e;t++){for(var r=new Uint8Array([0]),n=zf[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=mf(r,n)),zf.push(n)}return zf[e]}function jv(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),c=l.length-1,u=0,d=c;d>=0;d--,u++)if(!0==(r=a[s-u]-l[c-u]-n)<0)n=1,a[s-u]=r+10;else n=0,a[s-u]=r;if(n>0)for(var h=s-c+1;h>=0;h--,u++){if(!((r=a[s-u]-n)<0)){n=0,a[s-u]=r;break}n=1,a[s-u]=r+10}return a.slice()}Tv=Iv,lv.BitString=Tv,Iv.NAME=Zf;class Fv extends($f(ev)){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=wf.call(this)))}constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:r}=t,n=e._objectWithoutProperties(t,Cf);super(n),this._valueDec=0,n.valueHex&&this.setValueHex(),void 0!==r&&(this.valueDec=r)}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=gf(r-t,8,n);return new Uint8Array(i)[0]|=128,i}var o=gf(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 c=0;c<s.byteLength;c++)a[c+1]=l[c];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 e._objectSpread2(e._objectSpread2({},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=jv(Mv(n),r),o="-";else r=Lv(r,Mv(n));n++,e>>=1}}for(var c=0;c<r.length;c++)r[c]&&(a=!0),a&&(o+=Vf.charAt(r[c]));return!1===a&&(o+=Vf.charAt(0)),o}}Cv=Fv,Fv.NAME="IntegerValueBlock",Object.defineProperty(Cv.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class Uv extends cv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},Fv),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Mf(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Mf();var t=BigInt(e),r=new Uf,n=t.toString(16).replace(/^-/,""),i=new Uint8Array(vf.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(vf.Convert.ToHex(o)))+t,s=vf.BufferSourceConverter.toUint8Array(vf.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 Bv({valueHex:r.final()})}convertToDER(){var e=new Bv({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Bv({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.valueBlock.toString())}}Bv=Uv,lv.Integer=Bv,Uv.NAME="INTEGER";class zv extends Uv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}Nv=zv,lv.Enumerated=Nv,zv.NAME="ENUMERATED";class Vv extends($f(ev)){constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{valueDec:r=-1,isFirstSid:n=!1}=t;super(e._objectWithoutProperties(t,Bf)),this.valueDec=r,this.isFirstSid=n}fromBER(e,t,r){if(!r)return t;var n=vf.BufferSourceConverter.toUint8Array(e);if(!Ff(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=yf(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Mf();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=gf(this.valueDec,7);if(0===i.byteLength)return this.error="Error during encoding SID value",Wf;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=vf.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 e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{valueDec:this.valueDec,isFirstSid:this.isFirstSid})}}Vv.NAME="sidBlock";class qv extends ev{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:r=Kf}=t;super(e._objectWithoutProperties(t,Nf)),this.value=[],r&&this.fromString(r)}fromBER(e,t,r){for(var n=t;r>0;){var i=new Vv;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,Wf;t.push(n)}return jf(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 Vv;if(n>Number.MAX_SAFE_INTEGER){Mf();var c=BigInt(n);l.valueBigInt=c}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 t=e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{value:this.toString(),sidArray:[]}),r=0;r<this.value.length;r++)t.sidArray.push(this.value[r].toJSON());return t}}qv.NAME="ObjectIdentifierValueBlock";class Hv extends cv{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},qv),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.valueBlock.toString()||"empty")}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{value:this.getValue()})}}Dv=Hv,lv.ObjectIdentifier=Dv,Hv.NAME="OBJECT IDENTIFIER";class Kv extends($f(Xf)){constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{valueDec:r=0}=t;super(e._objectWithoutProperties(t,Df)),this.valueDec=r}fromBER(e,t,r){if(0===r)return t;var n=vf.BufferSourceConverter.toUint8Array(e);if(!Ff(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=yf(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=gf(this.valueDec,7);if(0===i.byteLength)return this.error="Error during encoding SID value",Wf;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?vf.Convert.ToHex(this.valueHexView):this.valueDec.toString()}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{valueDec:this.valueDec})}}Kv.NAME="relativeSidBlock";class Wv extends ev{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:r=Kf}=t;super(e._objectWithoutProperties(t,Gf)),this.value=[],r&&this.fromString(r)}fromBER(e,t,r){for(var n=t;r>0;){var i=new Kv;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,Wf;r.push(i)}return jf(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 Kv;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 t=e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{value:this.toString(),sidArray:[]}),r=0;r<this.value.length;r++)t.sidArray.push(this.value[r].toJSON());return t}}Wv.NAME="RelativeObjectIdentifierValueBlock";class Qv extends cv{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},Wv),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.valueBlock.toString()||"empty")}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{value:this.getValue()})}}Gv=Qv,lv.RelativeObjectIdentifier=Gv,Qv.NAME="RelativeObjectIdentifier";class Yv extends mv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}Rv=Yv,lv.Sequence=Rv,Yv.NAME="SEQUENCE";let Jv=class extends mv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Ov=Jv,lv.Set=Ov,Jv.NAME="SET";class Zv extends($f(ev)){constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(e._extends({},(e._objectDestructuringEmpty(t),t))),this.isHexOnly=!0,this.value=Kf}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{value:this.value})}}Zv.NAME="StringValueBlock";class $v extends Zv{}$v.NAME="SimpleStringValueBlock";class Xv extends dv{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(e._extends({},(e._objectDestructuringEmpty(t),t)),$v)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,vf.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}}Xv.NAME="SIMPLE STRING";class ey extends Xv{fromBuffer(e){this.valueBlock.valueHexView=vf.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=vf.Convert.ToUtf8String(e)}catch(t){this.warnings.push('Error during "decodeURIComponent": '.concat(t,", using raw string")),this.valueBlock.value=vf.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(vf.Convert.FromUtf8String(e)),this.valueBlock.value=e}}var ty,ry,ny,iy,oy,ay,sy,ly,cy,uy,dy,hy,py,fy,vy,yy,gy,my,wy;ey.NAME="Utf8StringValueBlock";class by extends ey{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}ty=by,lv.Utf8String=ty,by.NAME="UTF8String";class _y extends Xv{fromBuffer(e){this.valueBlock.value=vf.Convert.ToUtf16String(e),this.valueBlock.valueHexView=vf.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(vf.Convert.FromUtf16String(e))}}_y.NAME="BmpStringValueBlock";class Sy extends _y{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(e._extends({},(e._objectDestructuringEmpty(t),t))),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}ry=Sy,lv.BmpString=ry,Sy.NAME="BMPString";class Py extends Xv{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=gf(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}}Py.NAME="UniversalStringValueBlock";class Ey extends Py{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(e._extends({},(e._objectDestructuringEmpty(t),t))),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}ny=Ey,lv.UniversalString=ny,Ey.NAME="UniversalString";class Ay extends Xv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}iy=Ay,lv.NumericString=iy,Ay.NAME="NumericString";class ky extends Xv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}oy=ky,lv.PrintableString=oy,ky.NAME="PrintableString";class xy extends Xv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}ay=xy,lv.TeletexString=ay,xy.NAME="TeletexString";class Ty extends Xv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}sy=Ty,lv.VideotexString=sy,Ty.NAME="VideotexString";class Iy extends Xv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}ly=Iy,lv.IA5String=ly,Iy.NAME="IA5String";class Cy extends Xv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}cy=Cy,lv.GraphicString=cy,Cy.NAME="GraphicString";class By extends Xv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}uy=By,lv.VisibleString=uy,By.NAME="VisibleString";class Ny extends Xv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}dy=Ny,lv.GeneralString=dy,Ny.NAME="GeneralString";class Dy extends Xv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}hy=Dy,lv.CharacterString=hy,Dy.NAME="CharacterString";class Gy extends By{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:r,valueDate:n}=t;if(super(e._objectWithoutProperties(t,Rf)),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,r){this.fromString(r),this.valueBlock.valueHexView=new Uint8Array(r.length);for(var i=0;i<r.length;i++)this.valueBlock.valueHexView[i]=r.charCodeAt(i)}n&&(this.fromDate(n),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,vf.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]=bf(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=bf(this.month,2),t[2]=bf(this.day,2),t[3]=bf(this.hour,2),t[4]=bf(this.minute,2),t[5]=bf(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.toDate().toISOString())}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second})}}py=Gy,lv.UTCTime=py,Gy.NAME="UTCTime";class Ry extends Gy{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 c=1,u=n.indexOf("+"),d="";if(-1===u&&(u=n.indexOf("-"),c=-1),-1!==u){if(d=n.substring(u+1),n=n.substring(0,u),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=c*h,4===d.length){if(h=parseInt(d.substring(2,4),10),isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");s=c*h}}}var p=n.indexOf(".");if(-1===p&&(p=n.indexOf(",")),-1!==p){var f=new Number("0".concat(n.substring(p)));if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");o=f.valueOf(),i=n.substring(0,p)}else i=n;switch(!0){case 8===i.length:if(t=/(\d{4})(\d{2})(\d{2})/gi,-1!==p)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!==p){var v=60*o;this.minute=Math.floor(v),v=60*(v-this.minute),this.second=Math.floor(v),v=1e3*(v-this.second),this.millisecond=Math.floor(v)}break;case 12===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==p){var y=60*o;this.second=Math.floor(y),y=1e3*(y-this.second),this.millisecond=Math.floor(y)}break;case 14===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==p){var g=1e3*o;this.millisecond=Math.floor(g)}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(bf(this.year,4)),t.push(bf(this.month,2)),t.push(bf(this.day,2)),t.push(bf(this.hour,2)),t.push(bf(this.minute,2)),t.push(bf(this.second,2)),0!==this.millisecond&&(t.push("."),t.push(bf(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{millisecond:this.millisecond})}}fy=Ry,lv.GeneralizedTime=fy,Ry.NAME="GeneralizedTime";class Oy extends by{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}vy=Oy,lv.DATE=vy,Oy.NAME="DATE";class Ly extends by{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}yy=Ly,lv.TimeOfDay=yy,Ly.NAME="TimeOfDay";class My extends by{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}gy=My,lv.DateTime=gy,My.NAME="DateTime";class jy extends by{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}my=jy,lv.Duration=my,jy.NAME="Duration";class Fy extends by{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}wy=Fy,lv.TIME=wy,Fy.NAME="TIME";class Uy{constructor(){var{name:e=Kf,optional:t=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.name=e,this.optional=t}}class zy extends Uy{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:r=[]}=t;super(e._objectWithoutProperties(t,Of)),this.value=r}}class Vy extends Uy{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:r=new Uy,local:n=!1}=t;super(e._objectWithoutProperties(t,Lf)),this.value=r,this.local=n}}function qy(e,t,r){if(r instanceof zy){for(var n of r.value){if(qy(e,t,n).verified)return{verified:!0,result:e}}var i={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(qf)&&(i.name=r.name),i}if(r instanceof Uy)return r.hasOwnProperty(qf)&&(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(Hf 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,Kf),r.name&&(e[r.name]=t)),r instanceof lv.Constructed){var c=0,u={verified:!1,result:{error:"Unknown error"}},d=r.valueBlock.value.length;if(d>0&&r.valueBlock.value[0]instanceof Vy&&(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,p=0;p<r.valueBlock.value.length;p++)h=h&&(r.valueBlock.value[p].optional||!1);return h?{verified:!0,result:e}:(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Kf),r.name&&delete e[r.name]),e.error="Inconsistent object length",{verified:!1,result:e})}for(var f=0;f<d;f++)if(f-c>=t.valueBlock.value.length){if(!1===r.valueBlock.value[f].optional){var v={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,Kf),r.name&&(delete e[r.name],v.name=r.name)),v}}else if(r.valueBlock.value[0]instanceof Vy){if(!1===(u=qy(e,t.valueBlock.value[f],r.valueBlock.value[0].value)).verified){if(!r.valueBlock.value[0].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Kf),r.name&&delete e[r.name]),u;c++}if(qf in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){var y={};void 0===(y="local"in r.valueBlock.value[0]&&r.valueBlock.value[0].local?t:e)[r.valueBlock.value[0].name]&&(y[r.valueBlock.value[0].name]=[]),y[r.valueBlock.value[0].name].push(t.valueBlock.value[f])}}else if(!1===(u=qy(e,t.valueBlock.value[f-c],r.valueBlock.value[f])).verified){if(!r.valueBlock.value[f].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Kf),r.name&&delete e[r.name]),u;c++}if(!1===u.verified){var g={verified:!1,result:e};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Kf),r.name&&(delete e[r.name],g.name=r.name)),g}return{verified:!0,result:e}}if(r.primitiveSchema&&Hf in t.valueBlock){var m=fv(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,Kf),r.name&&(delete e[r.name],w.name=r.name)),w}return qy(e,m.result,r.primitiveSchema)}return{verified:!0,result:e}}var Hy,Ky,Wy=Object.freeze({__proto__:null,Any:Uy,BaseBlock:cv,BaseStringBlock:dv,BitString:Iv,BmpString:Sy,Boolean:Pv,CharacterString:Dy,Choice:zy,Constructed:mv,DATE:Oy,DateTime:My,Duration:jy,EndOfContent:bv,Enumerated:zv,GeneralString:Ny,GeneralizedTime:Ry,GraphicString:Cy,HexBlock:$f,IA5String:Iy,Integer:Uv,Null:_v,NumericString:Ay,ObjectIdentifier:Hv,OctetString:kv,Primitive:pv,PrintableString:ky,RawData:class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=vf.BufferSourceConverter.toUint8Array(e)}constructor(){var{data:e=Qf}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.dataView=vf.BufferSourceConverter.toUint8Array(e)}fromBER(e,t,r){var n=t+r;return this.dataView=vf.BufferSourceConverter.toUint8Array(e).subarray(t,n),n}toBER(e){return this.dataView.slice().buffer}},RelativeObjectIdentifier:Qv,Repeated:Vy,Sequence:Yv,Set:Jv,TIME:Fy,TeletexString:xy,TimeOfDay:Ly,UTCTime:Gy,UniversalString:Ey,Utf8String:by,ValueBlock:ev,VideotexString:Ty,ViewWriter:Uf,VisibleString:By,compareSchema:qy,fromBER:vv,verifySchema:function(e,t){if(t instanceof Object==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};var r=fv(vf.BufferSourceConverter.toUint8Array(e));return-1===r.offset?{verified:!1,result:r.result}:qy(r.result,r.result,t)}});!function(e){e[e.Sequence=0]="Sequence",e[e.Set=1]="Set",e[e.Choice=2]="Choice"}(Hy||(Hy={})),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"}(Ky||(Ky={}));class Qy{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(!vf.BufferSourceConverter.isBufferSource(e))throw TypeError("Unsupported type of 'params' argument for BitString");this.unusedBits=t,this.value=vf.BufferSourceConverter.toArrayBuffer(e)}}fromASN(e){if(!(e instanceof Iv))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 Iv({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new Iv({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 Yy{get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){"number"==typeof e?this.buffer=new ArrayBuffer(e):vf.BufferSourceConverter.isBufferSource(e)?this.buffer=vf.BufferSourceConverter.toArrayBuffer(e):Array.isArray(e)?this.buffer=new Uint8Array(e):this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof kv))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=e.valueBlock.valueHex,this}toASN(){return new kv({valueHex:this.buffer})}toSchema(e){return new kv({name:e})}}var Jy={fromASN:e=>e instanceof _v?null:e.valueBeforeDecodeView,toASN:e=>{if(null===e)return new _v;var t=vv(e);if(t.result.error)throw new Error(t.result.error);return t.result}},Zy={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new Uv({value:+e})},$y={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new zv({value:e})},Xy={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new Uv({valueHex:e})},eg={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new Iv({valueHex:e})},tg={fromASN:e=>e.valueBlock.toString(),toASN:e=>new Hv({value:e})},rg={fromASN:e=>e.valueBlock.value,toASN:e=>new Pv({value:e})},ng={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new kv({valueHex:e})},ig={fromASN:e=>new Yy(e.getValue()),toASN:e=>e.toASN()};function og(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}var ag=og(by),sg=og(Sy),lg=og(Ey),cg=og(Ay),ug=og(ky),dg=og(xy),hg=og(Ty),pg=og(Iy),fg=og(Cy),vg=og(By),yg=og(Ny),gg=og(Dy),mg={fromASN:e=>e.toDate(),toASN:e=>new Gy({valueDate:e})},wg={fromASN:e=>e.toDate(),toASN:e=>new Ry({valueDate:e})},bg={fromASN:()=>null,toASN:()=>new _v};function _g(e){switch(e){case Ky.Any:return Jy;case Ky.BitString:return eg;case Ky.BmpString:return sg;case Ky.Boolean:return rg;case Ky.CharacterString:return gg;case Ky.Enumerated:return $y;case Ky.GeneralString:return yg;case Ky.GeneralizedTime:return wg;case Ky.GraphicString:return fg;case Ky.IA5String:return pg;case Ky.Integer:return Zy;case Ky.Null:return bg;case Ky.NumericString:return cg;case Ky.ObjectIdentifier:return tg;case Ky.OctetString:return ng;case Ky.PrintableString:return ug;case Ky.TeletexString:return dg;case Ky.UTCTime:return mg;case Ky.UniversalString:return lg;case Ky.Utf8String:return ag;case Ky.VideotexString:return hg;case Ky.VisibleString:return vg;default:return null}}function Sg(e){return"function"==typeof e&&e.prototype?!(!e.prototype.toASN||!e.prototype.fromASN)||Sg(e.prototype):!!(e&&"object"==typeof e&&"toASN"in e&&"fromASN"in e)}function Pg(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||Pg(r)}return!1}function Eg(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 Ag,kg,xg,Tg=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:Hy.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=Ky[o.type],c=Wy[l];if(!c)throw new Error("Cannot get ASN1 class by name '".concat(l,"'"));s=new c({name:a})}else if(Sg(o.type)){s=(new o.type).toSchema(a)}else if(o.optional){this.get(o.type).type===Hy.Choice?s=new Uy({name:a}):(s=this.create(o.type,!1)).name=a}else s=new Uy({name:a});var u=!!o.optional||void 0!==o.defaultValue;if(o.repeated)s.name="",s=new("set"===o.repeated?Jv:Yv)({name:"",value:[new Vy({name:a,value:s})]});if(null!==o.context&&void 0!==o.context)if(o.implicit)if("number"==typeof o.type||Sg(o.type)){var d=o.repeated?mv:pv;n.push(new d({name:a,optional:u,idBlock:{tagClass:3,tagNumber:o.context}}))}else{this.cache(o.type);var h=!!o.repeated,p=h?s:this.get(o.type,!0).schema;p="valueBlock"in p?p.valueBlock.value:p.value,n.push(new mv({name:h?"":a,optional:u,idBlock:{tagClass:3,tagNumber:o.context},value:p}))}else n.push(new mv({optional:u,idBlock:{tagClass:3,tagNumber:o.context},value:[s]}));else s.optional=u,n.push(s)}switch(r.type){case Hy.Sequence:return new Yv({value:n,name:""});case Hy.Set:return new Jv({value:n,name:""});case Hy.Choice:return new zy({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}},Ig=e=>t=>{var r;Tg.has(t)?r=Tg.get(t):(r=Tg.createDefault(t),Tg.set(t,r)),Object.assign(r,e)},Cg=e=>(t,r)=>{var n;Tg.has(t.constructor)?n=Tg.get(t.constructor):(n=Tg.createDefault(t.constructor),Tg.set(t.constructor,n));var i=Object.assign({},e);if("number"==typeof i.type&&!i.converter){var o=_g(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 Bg extends Error{constructor(){super(...arguments),this.schemas=[]}}class Ng{static parse(e,t){var r=vv(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(Sg(t))return(new t).fromASN(e);var i=Tg.get(t);Tg.cache(t);var o=i.schema;if(e.constructor===mv&&i.type!==Hy.Choice)for(var a in o=new mv({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:i.schema.valueBlock.value}),i.items)delete e[a];var s=qy({},e,o);if(!s.verified)throw new Bg("Data does not match to ".concat(t.name," ASN1 schema. ").concat(s.result.error));var l=new t;if(Pg(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 c=i.itemType;if("number"==typeof c){var u=_g(c);if(!u)throw new Error("Cannot get default converter for array item of ".concat(t.name," ASN1 schema"));return t.from(e.valueBlock.value,(e=>u.fromASN(e)))}return t.from(e.valueBlock.value,(e=>this.fromASN(e,c)))}var d=function(){var e=s.result[h];if(!e)return 1;var t=i.items[h],o=t.type;if("number"==typeof o||Sg(o)){var a=null!==(r=t.converter)&&void 0!==r?r:Sg(o)?new o:null;if(!a)throw new Error("Converter is empty");if(t.repeated)if(t.implicit){var c=new("sequence"===t.repeated?Yv:Jv);c.valueBlock=e.valueBlock;var u=vv(c.toBER(!1));if(-1===u.offset)throw new Error("Cannot parse the child item. ".concat(u.result.error));if(!("value"in u.result.valueBlock)||!Array.isArray(u.result.valueBlock.value))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");var d=u.result.valueBlock.value;l[h]=Array.from(d,(e=>a.fromASN(e)))}else l[h]=Array.from(e,(e=>a.fromASN(e)));else{var p=e;if(t.implicit){var f;if(Sg(o))f=(new o).toSchema("");else{var v=Ky[o],y=Wy[v];if(!y)throw new Error("Cannot get '".concat(v,"' class from asn1js module"));f=new y}f.valueBlock=p.valueBlock,p=vv(f.toBER(!1)).result}l[h]=a.fromASN(p)}}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 Bg&&e.schemas.push(t.name),e}}}class Dg{static serialize(e){return e instanceof cv?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(t){if(t&&"object"==typeof t&&Sg(t))return t.toASN();if(!t||"object"!=typeof t)throw new TypeError("Parameter 1 should be type of Object.");var r=t.constructor,n=Tg.get(r);Tg.cache(r);var i,o=[];if(n.itemType){if(!Array.isArray(t))throw new TypeError("Parameter 1 should be type of Array.");if("number"==typeof n.itemType){var a=_g(n.itemType);if(!a)throw new Error("Cannot get default converter for array item of ".concat(r.name," ASN1 schema"));o=t.map((e=>a.toASN(e)))}else o=t.map((e=>this.toAsnItem({type:n.itemType},"[]",r,e)))}else for(var s in n.items){var l=n.items[s],c=t[s];if(!(void 0===c||l.defaultValue===c||"object"==typeof l.defaultValue&&"object"==typeof c&&Eg(this.serialize(l.defaultValue),this.serialize(c)))){var u=Dg.toAsnItem(l,s,r,c);if("number"==typeof l.context)if(l.implicit)if(l.repeated||"number"!=typeof l.type&&!Sg(l.type))o.push(new mv({optional:l.optional,idBlock:{tagClass:3,tagNumber:l.context},value:u.valueBlock.value}));else{var d={};d.valueHex=u instanceof _v?u.valueBeforeDecodeView:u.valueBlock.toBER(),o.push(new pv(e._objectSpread2({optional:l.optional,idBlock:{tagClass:3,tagNumber:l.context}},d)))}else o.push(new mv({optional:l.optional,idBlock:{tagClass:3,tagNumber:l.context},value:[u]}));else l.repeated?o=o.concat(u):o.push(u)}}switch(n.type){case Hy.Sequence:i=new Yv({value:o});break;case Hy.Set:i=new Jv({value:o});break;case Hy.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(Ky[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?Yv:Jv)({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?Yv:Jv)({value:s})}else i=this.toASN(n);return i}}class Gg 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 Rg{static serialize(e){return Dg.serialize(e)}static parse(e,t){return Ng.parse(e,t)}static toString(e){var t=vv(vf.BufferSourceConverter.isBufferSource(e)?vf.BufferSourceConverter.toArrayBuffer(e):Rg.serialize(e));if(-1===t.offset)throw new Error("Cannot decode ASN.1 data. ".concat(t.result.error));return t.result.toString()}}class Og{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(vf.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 Lg=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||""}};Bo([Cg({type:Ky.TeletexString})],Lg.prototype,"teletexString",void 0),Bo([Cg({type:Ky.PrintableString})],Lg.prototype,"printableString",void 0),Bo([Cg({type:Ky.UniversalString})],Lg.prototype,"universalString",void 0),Bo([Cg({type:Ky.Utf8String})],Lg.prototype,"utf8String",void 0),Bo([Cg({type:Ky.BmpString})],Lg.prototype,"bmpString",void 0),Lg=Bo([Ig({type:Hy.Choice})],Lg);var Mg=class extends Lg{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?vf.Convert.ToHex(this.anyValue):super.toString())}};Bo([Cg({type:Ky.IA5String})],Mg.prototype,"ia5String",void 0),Bo([Cg({type:Ky.Any})],Mg.prototype,"anyValue",void 0),Mg=Bo([Ig({type:Hy.Choice})],Mg);class jg{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.type="",this.value=new Mg,Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier})],jg.prototype,"type",void 0),Bo([Cg({type:Mg})],jg.prototype,"value",void 0);var Fg=Ag=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,Ag.prototype)}};Fg=Ag=Bo([Ig({type:Hy.Set,itemType:jg})],Fg);var Ug=kg=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,kg.prototype)}};Ug=kg=Bo([Ig({type:Hy.Sequence,itemType:Fg})],Ug);var zg=xg=class extends Ug{constructor(e){super(e),Object.setPrototypeOf(this,xg.prototype)}};zg=xg=Bo([Ig({type:Hy.Sequence})],zg);var Vg={fromASN:e=>Og.toString(ng.fromASN(e)),toASN:e=>ng.toASN(Og.fromString(e))};class qg{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.typeId="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier})],qg.prototype,"typeId",void 0),Bo([Cg({type:Ky.Any,context:0})],qg.prototype,"value",void 0);class Hg{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.partyName=new Lg,Object.assign(this,e)}}Bo([Cg({type:Lg,optional:!0,context:0,implicit:!0})],Hg.prototype,"nameAssigner",void 0),Bo([Cg({type:Lg,context:1,implicit:!0})],Hg.prototype,"partyName",void 0);var Kg=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Bo([Cg({type:qg,context:0,implicit:!0})],Kg.prototype,"otherName",void 0),Bo([Cg({type:Ky.IA5String,context:1,implicit:!0})],Kg.prototype,"rfc822Name",void 0),Bo([Cg({type:Ky.IA5String,context:2,implicit:!0})],Kg.prototype,"dNSName",void 0),Bo([Cg({type:Ky.Any,context:3,implicit:!0})],Kg.prototype,"x400Address",void 0),Bo([Cg({type:zg,context:4,implicit:!1})],Kg.prototype,"directoryName",void 0),Bo([Cg({type:Hg,context:5})],Kg.prototype,"ediPartyName",void 0),Bo([Cg({type:Ky.IA5String,context:6,implicit:!0})],Kg.prototype,"uniformResourceIdentifier",void 0),Bo([Cg({type:Ky.OctetString,context:7,implicit:!0,converter:Vg})],Kg.prototype,"iPAddress",void 0),Bo([Cg({type:Ky.ObjectIdentifier,context:8,implicit:!0})],Kg.prototype,"registeredID",void 0),Kg=Bo([Ig({type:Hy.Choice})],Kg);var Wg,Qg="1.3.6.1.5.5.7",Yg="".concat(Qg,".1"),Jg="".concat(Qg,".3"),Zg="".concat(Qg,".48"),$g="".concat(Zg,".1"),Xg="".concat(Zg,".2"),em="".concat(Zg,".3"),tm="".concat(Zg,".5"),rm="2.5.29",nm="".concat(Yg,".1");class im{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.accessMethod="",this.accessLocation=new Kg,Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier})],im.prototype,"accessMethod",void 0),Bo([Cg({type:Kg})],im.prototype,"accessLocation",void 0);var om=Wg=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,Wg.prototype)}};om=Wg=Bo([Ig({type:Hy.Sequence,itemType:im})],om);var am="".concat(rm,".35");class sm extends Yy{}class lm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e&&Object.assign(this,e)}}Bo([Cg({type:sm,context:0,optional:!0,implicit:!0})],lm.prototype,"keyIdentifier",void 0),Bo([Cg({type:Kg,context:1,optional:!0,implicit:!0,repeated:"sequence"})],lm.prototype,"authorityCertIssuer",void 0),Bo([Cg({type:Ky.Integer,context:2,optional:!0,implicit:!0,converter:Xy})],lm.prototype,"authorityCertSerialNumber",void 0);var cm,um="".concat(rm,".19");class dm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.cA=!1,Object.assign(this,e)}}Bo([Cg({type:Ky.Boolean,defaultValue:!1})],dm.prototype,"cA",void 0),Bo([Cg({type:Ky.Integer,optional:!0})],dm.prototype,"pathLenConstraint",void 0);var hm,pm=cm=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,cm.prototype)}};pm=cm=Bo([Ig({type:Hy.Sequence,itemType:Kg})],pm);var fm,vm=hm=class extends pm{constructor(e){super(e),Object.setPrototypeOf(this,hm.prototype)}};vm=hm=Bo([Ig({type:Hy.Sequence})],vm);var ym="".concat(rm,".32"),gm=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||""}};Bo([Cg({type:Ky.IA5String})],gm.prototype,"ia5String",void 0),Bo([Cg({type:Ky.VisibleString})],gm.prototype,"visibleString",void 0),Bo([Cg({type:Ky.BmpString})],gm.prototype,"bmpString",void 0),Bo([Cg({type:Ky.Utf8String})],gm.prototype,"utf8String",void 0),gm=Bo([Ig({type:Hy.Choice})],gm);class mm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.organization=new gm,this.noticeNumbers=[],Object.assign(this,e)}}Bo([Cg({type:gm})],mm.prototype,"organization",void 0),Bo([Cg({type:Ky.Integer,repeated:"sequence"})],mm.prototype,"noticeNumbers",void 0);class wm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Bo([Cg({type:mm,optional:!0})],wm.prototype,"noticeRef",void 0),Bo([Cg({type:gm,optional:!0})],wm.prototype,"explicitText",void 0);var bm=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Bo([Cg({type:Ky.IA5String})],bm.prototype,"cPSuri",void 0),Bo([Cg({type:wm})],bm.prototype,"userNotice",void 0),bm=Bo([Ig({type:Hy.Choice})],bm);class _m{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.policyQualifierId="",this.qualifier=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier})],_m.prototype,"policyQualifierId",void 0),Bo([Cg({type:Ky.Any})],_m.prototype,"qualifier",void 0);class Sm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.policyIdentifier="",Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier})],Sm.prototype,"policyIdentifier",void 0),Bo([Cg({type:_m,repeated:"sequence",optional:!0})],Sm.prototype,"policyQualifiers",void 0);var Pm=fm=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,fm.prototype)}};Pm=fm=Bo([Ig({type:Hy.Sequence,itemType:Sm})],Pm);var Em=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.value=e}};Bo([Cg({type:Ky.Integer})],Em.prototype,"value",void 0),Em=Bo([Ig({type:Hy.Choice})],Em);var Am,km=class extends Em{};km=Bo([Ig({type:Hy.Choice})],km);var xm,Tm="".concat(rm,".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"}(xm||(xm={}));class Im extends Qy{toJSON(){var e=[],t=this.toNumber();return t&xm.aACompromise&&e.push("aACompromise"),t&xm.affiliationChanged&&e.push("affiliationChanged"),t&xm.cACompromise&&e.push("cACompromise"),t&xm.certificateHold&&e.push("certificateHold"),t&xm.cessationOfOperation&&e.push("cessationOfOperation"),t&xm.keyCompromise&&e.push("keyCompromise"),t&xm.privilegeWithdrawn&&e.push("privilegeWithdrawn"),t&xm.superseded&&e.push("superseded"),t&xm.unused&&e.push("unused"),e}toString(){return"[".concat(this.toJSON().join(", "),"]")}}var Cm=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Bo([Cg({type:Kg,context:0,repeated:"sequence",implicit:!0})],Cm.prototype,"fullName",void 0),Bo([Cg({type:Fg,context:1,implicit:!0})],Cm.prototype,"nameRelativeToCRLIssuer",void 0),Cm=Bo([Ig({type:Hy.Choice})],Cm);class Bm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Bo([Cg({type:Cm,context:0,optional:!0})],Bm.prototype,"distributionPoint",void 0),Bo([Cg({type:Im,context:1,optional:!0,implicit:!0})],Bm.prototype,"reasons",void 0),Bo([Cg({type:Kg,context:2,optional:!0,repeated:"sequence",implicit:!0})],Bm.prototype,"cRLIssuer",void 0);var Nm,Dm=Am=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,Am.prototype)}};Dm=Am=Bo([Ig({type:Hy.Sequence,itemType:Bm})],Dm);var Gm,Rm=Nm=class extends Dm{constructor(e){super(e),Object.setPrototypeOf(this,Nm.prototype)}};Rm=Nm=Bo([Ig({type:Hy.Sequence,itemType:Bm})],Rm);class Om{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.onlyContainsUserCerts=Om.ONLY,this.onlyContainsCACerts=Om.ONLY,this.indirectCRL=Om.ONLY,this.onlyContainsAttributeCerts=Om.ONLY,Object.assign(this,e)}}Om.ONLY=!1,Bo([Cg({type:Cm,context:0,optional:!0})],Om.prototype,"distributionPoint",void 0),Bo([Cg({type:Ky.Boolean,context:1,defaultValue:Om.ONLY,implicit:!0})],Om.prototype,"onlyContainsUserCerts",void 0),Bo([Cg({type:Ky.Boolean,context:2,defaultValue:Om.ONLY,implicit:!0})],Om.prototype,"onlyContainsCACerts",void 0),Bo([Cg({type:Im,context:3,optional:!0,implicit:!0})],Om.prototype,"onlySomeReasons",void 0),Bo([Cg({type:Ky.Boolean,context:4,defaultValue:Om.ONLY,implicit:!0})],Om.prototype,"indirectCRL",void 0),Bo([Cg({type:Ky.Boolean,context:5,defaultValue:Om.ONLY,implicit:!0})],Om.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"}(Gm||(Gm={}));var Lm,Mm=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Gm.unspecified;this.reason=Gm.unspecified,this.reason=e}toJSON(){return Gm[this.reason]}toString(){return this.toJSON()}};Bo([Cg({type:Ky.Enumerated})],Mm.prototype,"reason",void 0),Mm=Bo([Ig({type:Hy.Choice})],Mm);var jm="".concat(rm,".37"),Fm=Lm=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,Lm.prototype)}};Fm=Lm=Bo([Ig({type:Hy.Sequence,itemType:Ky.ObjectIdentifier})],Fm);var Um="".concat(Jg,".1"),zm="".concat(Jg,".2"),Vm="".concat(Jg,".3"),qm="".concat(Jg,".4"),Hm="".concat(Jg,".8"),Km="".concat(Jg,".9"),Wm=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new ArrayBuffer(0);this.value=e}};Bo([Cg({type:Ky.Integer,converter:Xy})],Wm.prototype,"value",void 0),Wm=Bo([Ig({type:Hy.Choice})],Wm);var Qm,Ym=class{constructor(e){this.value=new Date,e&&(this.value=e)}};Bo([Cg({type:Ky.GeneralizedTime})],Ym.prototype,"value",void 0),Ym=Bo([Ig({type:Hy.Choice})],Ym);var Jm=Qm=class extends pm{constructor(e){super(e),Object.setPrototypeOf(this,Qm.prototype)}};Jm=Qm=Bo([Ig({type:Hy.Sequence})],Jm);var Zm,$m,Xm="".concat(rm,".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"}(Zm||(Zm={}));class ew extends Qy{toJSON(){var e=this.toNumber(),t=[];return e&Zm.cRLSign&&t.push("crlSign"),e&Zm.dataEncipherment&&t.push("dataEncipherment"),e&Zm.decipherOnly&&t.push("decipherOnly"),e&Zm.digitalSignature&&t.push("digitalSignature"),e&Zm.encipherOnly&&t.push("encipherOnly"),e&Zm.keyAgreement&&t.push("keyAgreement"),e&Zm.keyCertSign&&t.push("keyCertSign"),e&Zm.keyEncipherment&&t.push("keyEncipherment"),e&Zm.nonRepudiation&&t.push("nonRepudiation"),t}toString(){return"[".concat(this.toJSON().join(", "),"]")}}class tw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.base=new Kg,this.minimum=0,Object.assign(this,e)}}Bo([Cg({type:Kg})],tw.prototype,"base",void 0),Bo([Cg({type:Ky.Integer,context:0,defaultValue:0,implicit:!0})],tw.prototype,"minimum",void 0),Bo([Cg({type:Ky.Integer,context:1,optional:!0,implicit:!0})],tw.prototype,"maximum",void 0);var rw,nw=$m=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,$m.prototype)}};nw=$m=Bo([Ig({type:Hy.Sequence,itemType:tw})],nw);class iw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Bo([Cg({type:nw,context:0,optional:!0,implicit:!0})],iw.prototype,"permittedSubtrees",void 0),Bo([Cg({type:nw,context:1,optional:!0,implicit:!0})],iw.prototype,"excludedSubtrees",void 0);class ow{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Bo([Cg({type:Ky.Integer,context:0,implicit:!0,optional:!0,converter:Xy})],ow.prototype,"requireExplicitPolicy",void 0),Bo([Cg({type:Ky.Integer,context:1,implicit:!0,optional:!0,converter:Xy})],ow.prototype,"inhibitPolicyMapping",void 0);class aw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.issuerDomainPolicy="",this.subjectDomainPolicy="",Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier})],aw.prototype,"issuerDomainPolicy",void 0),Bo([Cg({type:Ky.ObjectIdentifier})],aw.prototype,"subjectDomainPolicy",void 0);var sw,lw=rw=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,rw.prototype)}};lw=rw=Bo([Ig({type:Hy.Sequence,itemType:aw})],lw);var cw="".concat(rm,".17"),uw=sw=class extends pm{constructor(e){super(e),Object.setPrototypeOf(this,sw.prototype)}};uw=sw=Bo([Ig({type:Hy.Sequence})],uw);let dw=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.type="",this.values=[],Object.assign(this,e)}};var hw;Bo([Cg({type:Ky.ObjectIdentifier})],dw.prototype,"type",void 0),Bo([Cg({type:Ky.Any,repeated:"set"})],dw.prototype,"values",void 0);var pw=hw=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,hw.prototype)}};pw=hw=Bo([Ig({type:Hy.Sequence,itemType:dw})],pw);var fw,vw,yw="".concat(rm,".14");class gw extends sm{}class mw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Bo([Cg({type:Ky.GeneralizedTime,context:0,implicit:!0,optional:!0})],mw.prototype,"notBefore",void 0),Bo([Cg({type:Ky.GeneralizedTime,context:1,implicit:!0,optional:!0})],mw.prototype,"notAfter",void 0),function(e){e[e.keyUpdateAllowed=1]="keyUpdateAllowed",e[e.newExtensions=2]="newExtensions",e[e.pKIXCertificate=4]="pKIXCertificate"}(fw||(fw={}));class ww extends Qy{toJSON(){var e=[],t=this.toNumber();return t&fw.pKIXCertificate&&e.push("pKIXCertificate"),t&fw.newExtensions&&e.push("newExtensions"),t&fw.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return"[".concat(this.toJSON().join(", "),"]")}}class bw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.entrustVers="",this.entrustInfoFlags=new ww,Object.assign(this,e)}}Bo([Cg({type:Ky.GeneralString})],bw.prototype,"entrustVers",void 0),Bo([Cg({type:ww})],bw.prototype,"entrustInfoFlags",void 0);var _w=vw=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,vw.prototype)}};_w=vw=Bo([Ig({type:Hy.Sequence,itemType:im})],_w);class Sw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.algorithm="",Object.assign(this,e)}isEqual(e){return e instanceof Sw&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&vf.isEqual(e.parameters,this.parameters)||e.parameters===this.parameters)}}Bo([Cg({type:Ky.ObjectIdentifier})],Sw.prototype,"algorithm",void 0),Bo([Cg({type:Ky.Any,optional:!0})],Sw.prototype,"parameters",void 0);class Pw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.algorithm=new Sw,this.subjectPublicKey=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:Sw})],Pw.prototype,"algorithm",void 0),Bo([Cg({type:Ky.BitString})],Pw.prototype,"subjectPublicKey",void 0);var Ew,Aw=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}};Bo([Cg({type:Ky.UTCTime})],Aw.prototype,"utcTime",void 0),Bo([Cg({type:Ky.GeneralizedTime})],Aw.prototype,"generalTime",void 0),Aw=Bo([Ig({type:Hy.Choice})],Aw);class kw{constructor(e){this.notBefore=new Aw(new Date),this.notAfter=new Aw(new Date),e&&(this.notBefore=new Aw(e.notBefore),this.notAfter=new Aw(e.notAfter))}}Bo([Cg({type:Aw})],kw.prototype,"notBefore",void 0),Bo([Cg({type:Aw})],kw.prototype,"notAfter",void 0);let xw=class e{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.extnID="",this.critical=e.CRITICAL,this.extnValue=new Yy,Object.assign(this,t)}};xw.CRITICAL=!1,Bo([Cg({type:Ky.ObjectIdentifier})],xw.prototype,"extnID",void 0),Bo([Cg({type:Ky.Boolean,defaultValue:xw.CRITICAL})],xw.prototype,"critical",void 0),Bo([Cg({type:Yy})],xw.prototype,"extnValue",void 0);var Tw,Iw=Ew=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,Ew.prototype)}};Iw=Ew=Bo([Ig({type:Hy.Sequence,itemType:xw})],Iw),function(e){e[e.v1=0]="v1",e[e.v2=1]="v2",e[e.v3=2]="v3"}(Tw||(Tw={}));class Cw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Tw.v1,this.serialNumber=new ArrayBuffer(0),this.signature=new Sw,this.issuer=new zg,this.validity=new kw,this.subject=new zg,this.subjectPublicKeyInfo=new Pw,Object.assign(this,e)}}Bo([Cg({type:Ky.Integer,context:0,defaultValue:Tw.v1})],Cw.prototype,"version",void 0),Bo([Cg({type:Ky.Integer,converter:Xy})],Cw.prototype,"serialNumber",void 0),Bo([Cg({type:Sw})],Cw.prototype,"signature",void 0),Bo([Cg({type:zg})],Cw.prototype,"issuer",void 0),Bo([Cg({type:kw})],Cw.prototype,"validity",void 0),Bo([Cg({type:zg})],Cw.prototype,"subject",void 0),Bo([Cg({type:Pw})],Cw.prototype,"subjectPublicKeyInfo",void 0),Bo([Cg({type:Ky.BitString,context:1,implicit:!0,optional:!0})],Cw.prototype,"issuerUniqueID",void 0),Bo([Cg({type:Ky.BitString,context:2,implicit:!0,optional:!0})],Cw.prototype,"subjectUniqueID",void 0),Bo([Cg({type:Iw,context:3,optional:!0})],Cw.prototype,"extensions",void 0);class Bw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.tbsCertificate=new Cw,this.signatureAlgorithm=new Sw,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:Cw})],Bw.prototype,"tbsCertificate",void 0),Bo([Cg({type:Sw})],Bw.prototype,"signatureAlgorithm",void 0),Bo([Cg({type:Ky.BitString})],Bw.prototype,"signatureValue",void 0);class Nw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.userCertificate=new ArrayBuffer(0),this.revocationDate=new Aw,Object.assign(this,e)}}Bo([Cg({type:Ky.Integer,converter:Xy})],Nw.prototype,"userCertificate",void 0),Bo([Cg({type:Aw})],Nw.prototype,"revocationDate",void 0),Bo([Cg({type:xw,optional:!0,repeated:"sequence"})],Nw.prototype,"crlEntryExtensions",void 0);class Dw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.signature=new Sw,this.issuer=new zg,this.thisUpdate=new Aw,Object.assign(this,e)}}Bo([Cg({type:Ky.Integer,optional:!0})],Dw.prototype,"version",void 0),Bo([Cg({type:Sw})],Dw.prototype,"signature",void 0),Bo([Cg({type:zg})],Dw.prototype,"issuer",void 0),Bo([Cg({type:Aw})],Dw.prototype,"thisUpdate",void 0),Bo([Cg({type:Aw,optional:!0})],Dw.prototype,"nextUpdate",void 0),Bo([Cg({type:Nw,repeated:"sequence",optional:!0})],Dw.prototype,"revokedCertificates",void 0),Bo([Cg({type:xw,optional:!0,context:0,repeated:"sequence"})],Dw.prototype,"crlExtensions",void 0);class Gw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.tbsCertList=new Dw,this.signatureAlgorithm=new Sw,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:Dw})],Gw.prototype,"tbsCertList",void 0),Bo([Cg({type:Sw})],Gw.prototype,"signatureAlgorithm",void 0),Bo([Cg({type:Ky.BitString})],Gw.prototype,"signature",void 0);class Rw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.issuer=new zg,this.serialNumber=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:zg})],Rw.prototype,"issuer",void 0),Bo([Cg({type:Ky.Integer,converter:Xy})],Rw.prototype,"serialNumber",void 0);var Ow,Lw=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Bo([Cg({type:gw,context:0,implicit:!0})],Lw.prototype,"subjectKeyIdentifier",void 0),Bo([Cg({type:Rw})],Lw.prototype,"issuerAndSerialNumber",void 0),Lw=Bo([Ig({type:Hy.Choice})],Lw),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"}(Ow||(Ow={}));var Mw=class extends Sw{};Mw=Bo([Ig({type:Hy.Sequence})],Mw);var jw=class extends Sw{};jw=Bo([Ig({type:Hy.Sequence})],jw);var Fw=class extends Sw{};Fw=Bo([Ig({type:Hy.Sequence})],Fw);var Uw=class extends Sw{};Uw=Bo([Ig({type:Hy.Sequence})],Uw);var zw=class extends Sw{};zw=Bo([Ig({type:Hy.Sequence})],zw);var Vw=class extends Sw{};Vw=Bo([Ig({type:Hy.Sequence})],Vw);let qw=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.attrType="",this.attrValues=[],Object.assign(this,e)}};var Hw;Bo([Cg({type:Ky.ObjectIdentifier})],qw.prototype,"attrType",void 0),Bo([Cg({type:Ky.Any,repeated:"set"})],qw.prototype,"attrValues",void 0);class Kw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Ow.v0,this.sid=new Lw,this.digestAlgorithm=new Mw,this.signatureAlgorithm=new jw,this.signature=new Yy,Object.assign(this,e)}}Bo([Cg({type:Ky.Integer})],Kw.prototype,"version",void 0),Bo([Cg({type:Lw})],Kw.prototype,"sid",void 0),Bo([Cg({type:Mw})],Kw.prototype,"digestAlgorithm",void 0),Bo([Cg({type:qw,repeated:"set",context:0,implicit:!0,optional:!0})],Kw.prototype,"signedAttrs",void 0),Bo([Cg({type:jw})],Kw.prototype,"signatureAlgorithm",void 0),Bo([Cg({type:Yy})],Kw.prototype,"signature",void 0),Bo([Cg({type:qw,repeated:"set",context:1,implicit:!0,optional:!0})],Kw.prototype,"unsignedAttrs",void 0);var Ww=Hw=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,Hw.prototype)}};Ww=Hw=Bo([Ig({type:Hy.Set,itemType:Kw})],Ww);var Qw=class extends Aw{};Qw=Bo([Ig({type:Hy.Choice})],Qw);var Yw,Jw=class extends Kw{};Jw=Bo([Ig({type:Hy.Sequence})],Jw);class Zw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.acIssuer=new Kg,this.acSerial=0,this.attrs=[],Object.assign(this,e)}}Bo([Cg({type:Kg})],Zw.prototype,"acIssuer",void 0),Bo([Cg({type:Ky.Integer})],Zw.prototype,"acSerial",void 0),Bo([Cg({type:dw,repeated:"sequence"})],Zw.prototype,"attrs",void 0);var $w,Xw=Yw=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,Yw.prototype)}};Xw=Yw=Bo([Ig({type:Hy.Sequence,itemType:Ky.ObjectIdentifier})],Xw);class eb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.permitUnSpecified=!0,Object.assign(this,e)}}Bo([Cg({type:Ky.Integer,optional:!0})],eb.prototype,"pathLenConstraint",void 0),Bo([Cg({type:Xw,implicit:!0,context:0,optional:!0})],eb.prototype,"permittedAttrs",void 0),Bo([Cg({type:Xw,implicit:!0,context:1,optional:!0})],eb.prototype,"excludedAttrs",void 0),Bo([Cg({type:Ky.Boolean,defaultValue:!0})],eb.prototype,"permitUnSpecified",void 0);class tb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.issuer=new pm,this.serial=new ArrayBuffer(0),this.issuerUID=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:pm})],tb.prototype,"issuer",void 0),Bo([Cg({type:Ky.Integer,converter:Xy})],tb.prototype,"serial",void 0),Bo([Cg({type:Ky.BitString,optional:!0})],tb.prototype,"issuerUID",void 0),function(e){e[e.publicKey=0]="publicKey",e[e.publicKeyCert=1]="publicKeyCert",e[e.otherObjectTypes=2]="otherObjectTypes"}($w||($w={}));class rb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.digestedObjectType=$w.publicKey,this.digestAlgorithm=new Sw,this.objectDigest=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:Ky.Enumerated})],rb.prototype,"digestedObjectType",void 0),Bo([Cg({type:Ky.ObjectIdentifier,optional:!0})],rb.prototype,"otherObjectTypeID",void 0),Bo([Cg({type:Sw})],rb.prototype,"digestAlgorithm",void 0),Bo([Cg({type:Ky.BitString})],rb.prototype,"objectDigest",void 0);class nb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Bo([Cg({type:pm,optional:!0})],nb.prototype,"issuerName",void 0),Bo([Cg({type:tb,context:0,implicit:!0,optional:!0})],nb.prototype,"baseCertificateID",void 0),Bo([Cg({type:rb,context:1,implicit:!0,optional:!0})],nb.prototype,"objectDigestInfo",void 0);var ib,ob,ab,sb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Bo([Cg({type:Kg,repeated:"sequence"})],sb.prototype,"v1Form",void 0),Bo([Cg({type:nb,context:0,implicit:!0})],sb.prototype,"v2Form",void 0),sb=Bo([Ig({type:Hy.Choice})],sb);class lb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.notBeforeTime=new Date,this.notAfterTime=new Date,Object.assign(this,e)}}Bo([Cg({type:Ky.GeneralizedTime})],lb.prototype,"notBeforeTime",void 0),Bo([Cg({type:Ky.GeneralizedTime})],lb.prototype,"notAfterTime",void 0);class cb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Bo([Cg({type:tb,implicit:!0,context:0,optional:!0})],cb.prototype,"baseCertificateID",void 0),Bo([Cg({type:pm,implicit:!0,context:1,optional:!0})],cb.prototype,"entityName",void 0),Bo([Cg({type:rb,implicit:!0,context:2,optional:!0})],cb.prototype,"objectDigestInfo",void 0),function(e){e[e.v2=1]="v2"}(ib||(ib={}));class ub{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=ib.v2,this.holder=new cb,this.issuer=new sb,this.signature=new Sw,this.serialNumber=new ArrayBuffer(0),this.attrCertValidityPeriod=new lb,this.attributes=[],Object.assign(this,e)}}Bo([Cg({type:Ky.Integer})],ub.prototype,"version",void 0),Bo([Cg({type:cb})],ub.prototype,"holder",void 0),Bo([Cg({type:sb})],ub.prototype,"issuer",void 0),Bo([Cg({type:Sw})],ub.prototype,"signature",void 0),Bo([Cg({type:Ky.Integer,converter:Xy})],ub.prototype,"serialNumber",void 0),Bo([Cg({type:lb})],ub.prototype,"attrCertValidityPeriod",void 0),Bo([Cg({type:dw,repeated:"sequence"})],ub.prototype,"attributes",void 0),Bo([Cg({type:Ky.BitString,optional:!0})],ub.prototype,"issuerUniqueID",void 0),Bo([Cg({type:Iw,optional:!0})],ub.prototype,"extensions",void 0);class db{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.acinfo=new ub,this.signatureAlgorithm=new Sw,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:ub})],db.prototype,"acinfo",void 0),Bo([Cg({type:Sw})],db.prototype,"signatureAlgorithm",void 0),Bo([Cg({type:Ky.BitString})],db.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"}(ob||(ob={}));class hb extends Qy{}class pb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.type="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier,implicit:!0,context:0})],pb.prototype,"type",void 0),Bo([Cg({type:Ky.Any,implicit:!0,context:1})],pb.prototype,"value",void 0);class fb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.policyId="",this.classList=new hb(ob.unclassified),Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier})],fb.prototype,"policyId",void 0),Bo([Cg({type:hb,defaultValue:new hb(ob.unclassified)})],fb.prototype,"classList",void 0),Bo([Cg({type:pb,repeated:"set"})],fb.prototype,"securityCategories",void 0);class vb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Bo([Cg({type:Yy})],vb.prototype,"cotets",void 0),Bo([Cg({type:Ky.ObjectIdentifier})],vb.prototype,"oid",void 0),Bo([Cg({type:Ky.Utf8String})],vb.prototype,"string",void 0);class yb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.values=[],Object.assign(this,e)}}Bo([Cg({type:pm,implicit:!0,context:0,optional:!0})],yb.prototype,"policyAuthority",void 0),Bo([Cg({type:vb,repeated:"sequence"})],yb.prototype,"values",void 0);class gb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.targetCertificate=new tb,Object.assign(this,e)}}Bo([Cg({type:tb})],gb.prototype,"targetCertificate",void 0),Bo([Cg({type:Kg,optional:!0})],gb.prototype,"targetName",void 0),Bo([Cg({type:rb,optional:!0})],gb.prototype,"certDigestInfo",void 0);var mb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Bo([Cg({type:Kg,context:0,implicit:!0})],mb.prototype,"targetName",void 0),Bo([Cg({type:Kg,context:1,implicit:!0})],mb.prototype,"targetGroup",void 0),Bo([Cg({type:gb,context:2,implicit:!0})],mb.prototype,"targetCert",void 0),mb=Bo([Ig({type:Hy.Choice})],mb);var wb,bb=ab=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,ab.prototype)}};bb=ab=Bo([Ig({type:Hy.Sequence,itemType:mb})],bb);var _b,Sb=wb=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,wb.prototype)}};Sb=wb=Bo([Ig({type:Hy.Sequence,itemType:bb})],Sb);class Pb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Bo([Cg({type:pm,implicit:!0,context:0,optional:!0})],Pb.prototype,"roleAuthority",void 0),Bo([Cg({type:Kg,implicit:!0,context:1})],Pb.prototype,"roleName",void 0);class Eb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.service=new Kg,this.ident=new Kg,Object.assign(this,e)}}Bo([Cg({type:Kg})],Eb.prototype,"service",void 0),Bo([Cg({type:Kg})],Eb.prototype,"ident",void 0),Bo([Cg({type:Yy,optional:!0})],Eb.prototype,"authInfo",void 0);class Ab{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.otherCertFormat="",this.otherCert=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier})],Ab.prototype,"otherCertFormat",void 0),Bo([Cg({type:Ky.Any})],Ab.prototype,"otherCert",void 0);var kb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Bo([Cg({type:Bw})],kb.prototype,"certificate",void 0),Bo([Cg({type:db,context:2,implicit:!0})],kb.prototype,"v2AttrCert",void 0),Bo([Cg({type:Ab,context:3,implicit:!0})],kb.prototype,"other",void 0),kb=Bo([Ig({type:Hy.Choice})],kb);var xb=_b=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,_b.prototype)}};xb=_b=Bo([Ig({type:Hy.Set,itemType:kb})],xb);class Tb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.contentType="",this.content=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier})],Tb.prototype,"contentType",void 0),Bo([Cg({type:Ky.Any,context:0})],Tb.prototype,"content",void 0);var Ib=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Bo([Cg({type:Yy})],Ib.prototype,"single",void 0),Bo([Cg({type:Ky.Any})],Ib.prototype,"any",void 0),Ib=Bo([Ig({type:Hy.Choice})],Ib);class Cb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.eContentType="",Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier})],Cb.prototype,"eContentType",void 0),Bo([Cg({type:Ib,context:0,optional:!0})],Cb.prototype,"eContent",void 0);var Bb,Nb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Bo([Cg({type:Yy,context:0,implicit:!0,optional:!0})],Nb.prototype,"value",void 0),Bo([Cg({type:Yy,converter:ig,context:0,implicit:!0,optional:!0,repeated:"sequence"})],Nb.prototype,"constructedValue",void 0),Nb=Bo([Ig({type:Hy.Choice})],Nb);class Db{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.contentType="",this.contentEncryptionAlgorithm=new Uw,Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier})],Db.prototype,"contentType",void 0),Bo([Cg({type:Uw})],Db.prototype,"contentEncryptionAlgorithm",void 0),Bo([Cg({type:Nb,optional:!0})],Db.prototype,"encryptedContent",void 0);class Gb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.keyAttrId="",Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier})],Gb.prototype,"keyAttrId",void 0),Bo([Cg({type:Ky.Any,optional:!0})],Gb.prototype,"keyAttr",void 0);class Rb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.subjectKeyIdentifier=new gw,Object.assign(this,e)}}Bo([Cg({type:gw})],Rb.prototype,"subjectKeyIdentifier",void 0),Bo([Cg({type:Ky.GeneralizedTime,optional:!0})],Rb.prototype,"date",void 0),Bo([Cg({type:Gb,optional:!0})],Rb.prototype,"other",void 0);var Ob=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Bo([Cg({type:Rb,context:0,implicit:!0,optional:!0})],Ob.prototype,"rKeyId",void 0),Bo([Cg({type:Rw,optional:!0})],Ob.prototype,"issuerAndSerialNumber",void 0),Ob=Bo([Ig({type:Hy.Choice})],Ob);class Lb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.rid=new Ob,this.encryptedKey=new Yy,Object.assign(this,e)}}Bo([Cg({type:Ob})],Lb.prototype,"rid",void 0),Bo([Cg({type:Yy})],Lb.prototype,"encryptedKey",void 0);var Mb=Bb=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,Bb.prototype)}};Mb=Bb=Bo([Ig({type:Hy.Sequence,itemType:Lb})],Mb);class jb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.algorithm=new Sw,this.publicKey=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:Sw})],jb.prototype,"algorithm",void 0),Bo([Cg({type:Ky.BitString})],jb.prototype,"publicKey",void 0);var Fb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Bo([Cg({type:gw,context:0,implicit:!0,optional:!0})],Fb.prototype,"subjectKeyIdentifier",void 0),Bo([Cg({type:jb,context:1,implicit:!0,optional:!0})],Fb.prototype,"originatorKey",void 0),Bo([Cg({type:Rw,optional:!0})],Fb.prototype,"issuerAndSerialNumber",void 0),Fb=Bo([Ig({type:Hy.Choice})],Fb);class Ub{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Ow.v3,this.originator=new Fb,this.keyEncryptionAlgorithm=new Fw,this.recipientEncryptedKeys=new Mb,Object.assign(this,e)}}Bo([Cg({type:Ky.Integer})],Ub.prototype,"version",void 0),Bo([Cg({type:Fb,context:0})],Ub.prototype,"originator",void 0),Bo([Cg({type:Yy,context:1,optional:!0})],Ub.prototype,"ukm",void 0),Bo([Cg({type:Fw})],Ub.prototype,"keyEncryptionAlgorithm",void 0),Bo([Cg({type:Mb})],Ub.prototype,"recipientEncryptedKeys",void 0);var zb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Bo([Cg({type:gw,context:0,implicit:!0})],zb.prototype,"subjectKeyIdentifier",void 0),Bo([Cg({type:Rw})],zb.prototype,"issuerAndSerialNumber",void 0),zb=Bo([Ig({type:Hy.Choice})],zb);class Vb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Ow.v0,this.rid=new zb,this.keyEncryptionAlgorithm=new Fw,this.encryptedKey=new Yy,Object.assign(this,e)}}Bo([Cg({type:Ky.Integer})],Vb.prototype,"version",void 0),Bo([Cg({type:zb})],Vb.prototype,"rid",void 0),Bo([Cg({type:Fw})],Vb.prototype,"keyEncryptionAlgorithm",void 0),Bo([Cg({type:Yy})],Vb.prototype,"encryptedKey",void 0);class qb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.keyIdentifier=new Yy,Object.assign(this,e)}}Bo([Cg({type:Yy})],qb.prototype,"keyIdentifier",void 0),Bo([Cg({type:Ky.GeneralizedTime,optional:!0})],qb.prototype,"date",void 0),Bo([Cg({type:Gb,optional:!0})],qb.prototype,"other",void 0);class Hb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Ow.v4,this.kekid=new qb,this.keyEncryptionAlgorithm=new Fw,this.encryptedKey=new Yy,Object.assign(this,e)}}Bo([Cg({type:Ky.Integer})],Hb.prototype,"version",void 0),Bo([Cg({type:qb})],Hb.prototype,"kekid",void 0),Bo([Cg({type:Fw})],Hb.prototype,"keyEncryptionAlgorithm",void 0),Bo([Cg({type:Yy})],Hb.prototype,"encryptedKey",void 0);class Kb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Ow.v0,this.keyEncryptionAlgorithm=new Fw,this.encryptedKey=new Yy,Object.assign(this,e)}}Bo([Cg({type:Ky.Integer})],Kb.prototype,"version",void 0),Bo([Cg({type:Vw,context:0,optional:!0})],Kb.prototype,"keyDerivationAlgorithm",void 0),Bo([Cg({type:Fw})],Kb.prototype,"keyEncryptionAlgorithm",void 0),Bo([Cg({type:Yy})],Kb.prototype,"encryptedKey",void 0);class Wb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.oriType="",this.oriValue=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier})],Wb.prototype,"oriType",void 0),Bo([Cg({type:Ky.Any})],Wb.prototype,"oriValue",void 0);var Qb,Yb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Bo([Cg({type:Vb,optional:!0})],Yb.prototype,"ktri",void 0),Bo([Cg({type:Ub,context:1,implicit:!0,optional:!0})],Yb.prototype,"kari",void 0),Bo([Cg({type:Hb,context:2,implicit:!0,optional:!0})],Yb.prototype,"kekri",void 0),Bo([Cg({type:Kb,context:3,implicit:!0,optional:!0})],Yb.prototype,"pwri",void 0),Bo([Cg({type:Wb,context:4,implicit:!0,optional:!0})],Yb.prototype,"ori",void 0),Yb=Bo([Ig({type:Hy.Choice})],Yb);var Jb,Zb=Qb=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,Qb.prototype)}};Zb=Qb=Bo([Ig({type:Hy.Set,itemType:Yb})],Zb);class $b{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.otherRevInfoFormat="",this.otherRevInfo=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier})],$b.prototype,"otherRevInfoFormat",void 0),Bo([Cg({type:Ky.Any})],$b.prototype,"otherRevInfo",void 0);var Xb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.other=new $b,Object.assign(this,e)}};Bo([Cg({type:$b,context:1,implicit:!0})],Xb.prototype,"other",void 0),Xb=Bo([Ig({type:Hy.Choice})],Xb);var e_,t_=Jb=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,Jb.prototype)}};t_=Jb=Bo([Ig({type:Hy.Set,itemType:Xb})],t_);class r_{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Bo([Cg({type:xb,context:0,implicit:!0,optional:!0})],r_.prototype,"certs",void 0),Bo([Cg({type:t_,context:1,implicit:!0,optional:!0})],r_.prototype,"crls",void 0);var n_=e_=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,e_.prototype)}};n_=e_=Bo([Ig({type:Hy.Set,itemType:qw})],n_);class i_{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Ow.v0,this.recipientInfos=new Zb,this.encryptedContentInfo=new Db,Object.assign(this,e)}}Bo([Cg({type:Ky.Integer})],i_.prototype,"version",void 0),Bo([Cg({type:r_,context:0,implicit:!0,optional:!0})],i_.prototype,"originatorInfo",void 0),Bo([Cg({type:Zb})],i_.prototype,"recipientInfos",void 0),Bo([Cg({type:Db})],i_.prototype,"encryptedContentInfo",void 0),Bo([Cg({type:n_,context:1,implicit:!0,optional:!0})],i_.prototype,"unprotectedAttrs",void 0);var o_,a_="1.2.840.113549.1.7.2",s_=o_=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,o_.prototype)}};s_=o_=Bo([Ig({type:Hy.Set,itemType:Mw})],s_);class l_{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Ow.v0,this.digestAlgorithms=new s_,this.encapContentInfo=new Cb,this.signerInfos=new Ww,Object.assign(this,e)}}Bo([Cg({type:Ky.Integer})],l_.prototype,"version",void 0),Bo([Cg({type:s_})],l_.prototype,"digestAlgorithms",void 0),Bo([Cg({type:Cb})],l_.prototype,"encapContentInfo",void 0),Bo([Cg({type:xb,context:0,implicit:!0,optional:!0})],l_.prototype,"certificates",void 0),Bo([Cg({type:t_,context:1,implicit:!0,optional:!0})],l_.prototype,"crls",void 0),Bo([Cg({type:Ww})],l_.prototype,"signerInfos",void 0);var c_="1.2.840.10045.2.1",u_="1.2.840.10045.4.1",d_="1.2.840.10045.4.3.1",h_="1.2.840.10045.4.3.2",p_="1.2.840.10045.4.3.3",f_="1.2.840.10045.4.3.4",v_="1.2.840.10045.3.1.7",y_="1.3.132.0.34",g_="1.3.132.0.35";function m_(e){return new Sw({algorithm:e})}var w_=m_(u_);m_(d_);var b_=m_(h_),__=m_(p_),S_=m_(f_),P_=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Bo([Cg({type:Ky.ObjectIdentifier})],P_.prototype,"fieldType",void 0),Bo([Cg({type:Ky.Any})],P_.prototype,"parameters",void 0),P_=Bo([Ig({type:Hy.Sequence})],P_);var E_,A_=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Bo([Cg({type:Ky.OctetString})],A_.prototype,"a",void 0),Bo([Cg({type:Ky.OctetString})],A_.prototype,"b",void 0),Bo([Cg({type:Ky.BitString,optional:!0})],A_.prototype,"seed",void 0),A_=Bo([Ig({type:Hy.Sequence})],A_),function(e){e[e.ecpVer1=1]="ecpVer1"}(E_||(E_={}));var k_=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=E_.ecpVer1,Object.assign(this,e)}};Bo([Cg({type:Ky.Integer})],k_.prototype,"version",void 0),Bo([Cg({type:P_})],k_.prototype,"fieldID",void 0),Bo([Cg({type:A_})],k_.prototype,"curve",void 0),Bo([Cg({type:class extends Yy{}})],k_.prototype,"base",void 0),Bo([Cg({type:Ky.Integer,converter:Xy})],k_.prototype,"order",void 0),Bo([Cg({type:Ky.Integer,optional:!0})],k_.prototype,"cofactor",void 0),k_=Bo([Ig({type:Hy.Sequence})],k_);var x_=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Bo([Cg({type:Ky.ObjectIdentifier})],x_.prototype,"namedCurve",void 0),Bo([Cg({type:Ky.Null})],x_.prototype,"implicitCurve",void 0),Bo([Cg({type:k_})],x_.prototype,"specifiedCurve",void 0),x_=Bo([Ig({type:Hy.Choice})],x_);class T_{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=1,this.privateKey=new Yy,Object.assign(this,e)}}Bo([Cg({type:Ky.Integer})],T_.prototype,"version",void 0),Bo([Cg({type:Yy})],T_.prototype,"privateKey",void 0),Bo([Cg({type:x_,context:0,optional:!0})],T_.prototype,"parameters",void 0),Bo([Cg({type:Ky.BitString,context:1,optional:!0})],T_.prototype,"publicKey",void 0);class I_{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)}}Bo([Cg({type:Ky.Integer,converter:Xy})],I_.prototype,"r",void 0),Bo([Cg({type:Ky.Integer,converter:Xy})],I_.prototype,"s",void 0);var C_="1.2.840.113549.1.1",B_="".concat(C_,".1"),N_="".concat(C_,".7"),D_="".concat(C_,".9"),G_="".concat(C_,".10"),R_="".concat(C_,".2"),O_="".concat(C_,".4"),L_="".concat(C_,".5"),M_="".concat(C_,".14"),j_="".concat(C_,".11"),F_="".concat(C_,".12"),U_="".concat(C_,".13"),z_="".concat(C_,".15"),V_="".concat(C_,".16"),q_="1.3.14.3.2.26",H_="2.16.840.1.101.3.4.2.4",K_="2.16.840.1.101.3.4.2.1",W_="2.16.840.1.101.3.4.2.2",Q_="2.16.840.1.101.3.4.2.3",Y_="".concat(C_,".8");function J_(e){return new Sw({algorithm:e,parameters:null})}J_("1.2.840.113549.2.2"),J_("1.2.840.113549.2.5");var Z_=J_(q_);J_(H_),J_(K_),J_(W_),J_(Q_),J_("2.16.840.1.101.3.4.2.5"),J_("2.16.840.1.101.3.4.2.6");var $_,X_=new Sw({algorithm:Y_,parameters:Rg.serialize(Z_)}),eS=new Sw({algorithm:D_,parameters:Rg.serialize(ng.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});J_(B_),J_(R_),J_(O_),J_(L_),J_(z_),J_(V_),J_(F_),J_(U_),J_(z_),J_(V_);class tS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.hashAlgorithm=new Sw(Z_),this.maskGenAlgorithm=new Sw({algorithm:Y_,parameters:Rg.serialize(Z_)}),this.pSourceAlgorithm=new Sw(eS),Object.assign(this,e)}}Bo([Cg({type:Sw,context:0,defaultValue:Z_})],tS.prototype,"hashAlgorithm",void 0),Bo([Cg({type:Sw,context:1,defaultValue:X_})],tS.prototype,"maskGenAlgorithm",void 0),Bo([Cg({type:Sw,context:2,defaultValue:eS})],tS.prototype,"pSourceAlgorithm",void 0),new Sw({algorithm:N_,parameters:Rg.serialize(new tS)});class rS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.hashAlgorithm=new Sw(Z_),this.maskGenAlgorithm=new Sw({algorithm:Y_,parameters:Rg.serialize(Z_)}),this.saltLength=20,this.trailerField=1,Object.assign(this,e)}}Bo([Cg({type:Sw,context:0,defaultValue:Z_})],rS.prototype,"hashAlgorithm",void 0),Bo([Cg({type:Sw,context:1,defaultValue:X_})],rS.prototype,"maskGenAlgorithm",void 0),Bo([Cg({type:Ky.Integer,context:2,defaultValue:20})],rS.prototype,"saltLength",void 0),Bo([Cg({type:Ky.Integer,context:3,defaultValue:1})],rS.prototype,"trailerField",void 0),new Sw({algorithm:G_,parameters:Rg.serialize(new rS)});class nS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.digestAlgorithm=new Sw,this.digest=new Yy,Object.assign(this,e)}}Bo([Cg({type:Sw})],nS.prototype,"digestAlgorithm",void 0),Bo([Cg({type:Yy})],nS.prototype,"digest",void 0);class iS{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)}}Bo([Cg({type:Ky.Integer,converter:Xy})],iS.prototype,"prime",void 0),Bo([Cg({type:Ky.Integer,converter:Xy})],iS.prototype,"exponent",void 0),Bo([Cg({type:Ky.Integer,converter:Xy})],iS.prototype,"coefficient",void 0);var oS,aS=$_=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,$_.prototype)}};aS=$_=Bo([Ig({type:Hy.Sequence,itemType:iS})],aS);class sS{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)}}Bo([Cg({type:Ky.Integer})],sS.prototype,"version",void 0),Bo([Cg({type:Ky.Integer,converter:Xy})],sS.prototype,"modulus",void 0),Bo([Cg({type:Ky.Integer,converter:Xy})],sS.prototype,"publicExponent",void 0),Bo([Cg({type:Ky.Integer,converter:Xy})],sS.prototype,"privateExponent",void 0),Bo([Cg({type:Ky.Integer,converter:Xy})],sS.prototype,"prime1",void 0),Bo([Cg({type:Ky.Integer,converter:Xy})],sS.prototype,"prime2",void 0),Bo([Cg({type:Ky.Integer,converter:Xy})],sS.prototype,"exponent1",void 0),Bo([Cg({type:Ky.Integer,converter:Xy})],sS.prototype,"exponent2",void 0),Bo([Cg({type:Ky.Integer,converter:Xy})],sS.prototype,"coefficient",void 0),Bo([Cg({type:aS,optional:!0})],sS.prototype,"otherPrimeInfos",void 0);class lS{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)}}Bo([Cg({type:Ky.Integer,converter:Xy})],lS.prototype,"modulus",void 0),Bo([Cg({type:Ky.Integer,converter:Xy})],lS.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"}(oS||(oS={}));var cS=oS;function uS(e){return!!e.useClass}function dS(e){return!!e.useFactory}var hS=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,Oo(t))}})),t},e}();function pS(e){return"string"==typeof e||"symbol"==typeof e}function fS(e){return"object"==typeof e&&"token"in e&&"transform"in e}function vS(e){return!!e.useToken}function yS(e){return null!=e.useValue}var gS=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}(),mS=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Co(t,e),t}(gS),wS=function(){this.scopedResolutions=new Map};function bS(e,t,r){var n,i,o=Ro(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=" "),Oo([n],r.message.split("\n").map((function(e){return i+e}))).join("\n")}var _S,SS=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Co(t,e),t}(gS),PS=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Co(t,e),t}(gS),ES=function(){this.preResolution=new SS,this.postResolution=new PS},AS=new Map,kS=function(){function e(e){this.parent=e,this._registry=new mS,this.interceptors=new ES,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,r){var n;if(void 0===r&&(r={lifecycle:cS.Transient}),this.ensureNotDisposed(),n=function(e){return uS(e)||yS(e)||vS(e)||dS(e)}(t)?t:{useClass:t},vS(n))for(var i=[e],o=n;null!=o;){var a=o.useToken;if(i.includes(a))throw new Error("Token registration cycle detected! "+Oo(i,[a]).join(" -> "));i.push(a);var s=this._registry.get(a);o=s&&vS(s.provider)?s.provider:null}if((r.lifecycle===cS.Singleton||r.lifecycle==cS.ContainerScoped||r.lifecycle==cS.ResolutionScoped)&&(yS(n)||dS(n)))throw new Error('Cannot use lifecycle "'+cS[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(),pS(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(),pS(e)){if(pS(t))return this.register(e,{useToken:t},{lifecycle:cS.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:cS.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var r=e;return t&&!pS(t)&&(r=t),this.register(e,{useClass:r},{lifecycle:cS.Singleton})},e.prototype.resolve=function(e,t,r){void 0===t&&(t=new wS),void 0===r&&(r=!1),this.ensureNotDisposed();var n=this.getRegistration(e);if(!n&&pS(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 hS}(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=Go(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=Go(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===cS.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var r,n=e.options.lifecycle===cS.Singleton,i=e.options.lifecycle===cS.ContainerScoped,o=n||i;return r=yS(e.provider)?e.provider.useValue:vS(e.provider)?o?e.instance||(e.instance=this.resolve(e.provider.useToken,t)):this.resolve(e.provider.useToken,t):uS(e.provider)?o?e.instance||(e.instance=this.construct(e.provider.useClass,t)):this.construct(e.provider.useClass,t):dS(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t),e.options.lifecycle===cS.ResolutionScoped&&t.scopedResolutions.set(e,r),r},e.prototype.resolveAll=function(e,t,r){var n=this;void 0===t&&(t=new wS),void 0===r&&(r=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&pS(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=Go(this._registry.entries()),n=r.next();!n.done;n=r.next()){var i=Ro(n.value,2),o=i[0],a=i[1];this._registry.setAll(o,a.filter((function(e){return!yS(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=Go(this._registry.entries()),o=i.next();!o.done;o=i.next()){var a=Ro(o.value,2),s=a[0],l=a[1];l.some((function(e){return e.options.lifecycle===cS.ContainerScoped}))&&n._registry.setAll(s,l.map((function(e){return e.options.lifecycle===cS.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 No(this,void 0,void 0,(function(){var e;return Do(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 hS)return e.createProxy((function(e){return r.resolve(e,t)}));var n,i=function(){var n=AS.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,Oo([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?fS(n)?n.multiple?(o=r.resolve(n.transform)).transform.apply(o,Oo([r.resolveAll(n.token,new wS,n.isOptional)],n.transformArgs)):(a=r.resolve(n.transform)).transform.apply(a,Oo([r.resolve(n.token,e,n.isOptional)],n.transformArgs)):n.multiple?r.resolveAll(n.token,new wS,n.isOptional):r.resolve(n.token,e,n.isOptional):fS(n)?(s=r.resolve(n.transform,e)).transform.apply(s,Oo([r.resolve(n.token,e)],n.transformArgs)):r.resolve(n,e)}catch(e){throw new Error(bS(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}(),xS=new kS;function TS(e){return function(e){AS.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 IS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.attrId="",this.attrValues=[],Object.assign(e)}}Bo([Cg({type:Ky.ObjectIdentifier})],IS.prototype,"attrId",void 0),Bo([Cg({type:Ky.Any,repeated:"set"})],IS.prototype,"attrValues",void 0);var CS,BS=_S=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,_S.prototype)}};BS=_S=Bo([Ig({type:Hy.Sequence,itemType:IS})],BS);var NS=CS=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,CS.prototype)}};NS=CS=Bo([Ig({type:Hy.Sequence,itemType:Tb})],NS);class DS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.certId="",this.certValue=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier})],DS.prototype,"certId",void 0),Bo([Cg({type:Ky.Any,context:0})],DS.prototype,"certValue",void 0);class GS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.crlId="",this.crltValue=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier})],GS.prototype,"crlId",void 0),Bo([Cg({type:Ky.Any,context:0})],GS.prototype,"crltValue",void 0);class RS extends Yy{}let OS=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.encryptionAlgorithm=new Sw,this.encryptedData=new RS,Object.assign(this,e)}};var LS,MS;Bo([Cg({type:Sw})],OS.prototype,"encryptionAlgorithm",void 0),Bo([Cg({type:RS})],OS.prototype,"encryptedData",void 0),function(e){e[e.v1=0]="v1"}(MS||(MS={}));class jS extends Yy{}var FS=LS=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,LS.prototype)}};FS=LS=Bo([Ig({type:Hy.Sequence,itemType:dw})],FS);class US{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=MS.v1,this.privateKeyAlgorithm=new Sw,this.privateKey=new jS,Object.assign(this,e)}}Bo([Cg({type:Ky.Integer})],US.prototype,"version",void 0),Bo([Cg({type:Sw})],US.prototype,"privateKeyAlgorithm",void 0),Bo([Cg({type:jS})],US.prototype,"privateKey",void 0),Bo([Cg({type:FS,implicit:!0,context:0,optional:!0})],US.prototype,"attributes",void 0);var zS=class extends US{};zS=Bo([Ig({type:Hy.Sequence})],zS);var VS,qS=class extends OS{};qS=Bo([Ig({type:Hy.Sequence})],qS);class HS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.secretTypeId="",this.secretValue=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier})],HS.prototype,"secretTypeId",void 0),Bo([Cg({type:Ky.Any,context:0})],HS.prototype,"secretValue",void 0);class KS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.mac=new nS,this.macSalt=new Yy,this.iterations=1,Object.assign(this,e)}}Bo([Cg({type:nS})],KS.prototype,"mac",void 0),Bo([Cg({type:Yy})],KS.prototype,"macSalt",void 0),Bo([Cg({type:Ky.Integer,defaultValue:1})],KS.prototype,"iterations",void 0);class WS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=3,this.authSafe=new Tb,this.macData=new KS,Object.assign(this,e)}}Bo([Cg({type:Ky.Integer})],WS.prototype,"version",void 0),Bo([Cg({type:Tb})],WS.prototype,"authSafe",void 0),Bo([Cg({type:KS,optional:!0})],WS.prototype,"macData",void 0);class QS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.bagId="",this.bagValue=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:Ky.ObjectIdentifier})],QS.prototype,"bagId",void 0),Bo([Cg({type:Ky.Any,context:0})],QS.prototype,"bagValue",void 0),Bo([Cg({type:IS,repeated:"set",optional:!0})],QS.prototype,"bagAttributes",void 0);var YS,JS,ZS,$S=VS=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,VS.prototype)}};$S=VS=Bo([Ig({type:Hy.Sequence,itemType:QS})],$S);var XS="1.2.840.113549.1.9",eP="".concat(XS,".7"),tP="".concat(XS,".14"),rP=class extends Lg{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{})}toString(){return this.ia5String||super.toString()}};Bo([Cg({type:Ky.IA5String})],rP.prototype,"ia5String",void 0),rP=Bo([Ig({type:Hy.Choice})],rP);var nP=class extends Tb{};nP=Bo([Ig({type:Hy.Sequence})],nP);var iP=class extends WS{};iP=Bo([Ig({type:Hy.Sequence})],iP);var oP=class extends OS{};oP=Bo([Ig({type:Hy.Sequence})],oP);var aP=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.value=e}toString(){return this.value}};Bo([Cg({type:Ky.IA5String})],aP.prototype,"value",void 0),aP=Bo([Ig({type:Hy.Choice})],aP);var sP=class extends rP{};sP=Bo([Ig({type:Hy.Choice})],sP);var lP=class extends Lg{};lP=Bo([Ig({type:Hy.Choice})],lP);var cP=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Date;this.value=e}};Bo([Cg({type:Ky.GeneralizedTime})],cP.prototype,"value",void 0),cP=Bo([Ig({type:Hy.Choice})],cP);var uP=class extends Lg{};uP=Bo([Ig({type:Hy.Choice})],uP);var dP=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"M";this.value=e}toString(){return this.value}};Bo([Cg({type:Ky.PrintableString})],dP.prototype,"value",void 0),dP=Bo([Ig({type:Hy.Choice})],dP);var hP=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.value=e}toString(){return this.value}};Bo([Cg({type:Ky.PrintableString})],hP.prototype,"value",void 0),hP=Bo([Ig({type:Hy.Choice})],hP);var pP=class extends hP{};pP=Bo([Ig({type:Hy.Choice})],pP);var fP=class extends Lg{};fP=Bo([Ig({type:Hy.Choice})],fP);var vP=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.value=e}toString(){return this.value}};Bo([Cg({type:Ky.ObjectIdentifier})],vP.prototype,"value",void 0),vP=Bo([Ig({type:Hy.Choice})],vP);var yP=class extends Aw{};yP=Bo([Ig({type:Hy.Choice})],yP);var gP=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.value=e}toString(){return this.value.toString()}};Bo([Cg({type:Ky.Integer})],gP.prototype,"value",void 0),gP=Bo([Ig({type:Hy.Choice})],gP);var mP=class extends Kw{};mP=Bo([Ig({type:Hy.Sequence})],mP);var wP=class extends Lg{};wP=Bo([Ig({type:Hy.Choice})],wP);var bP=YS=class extends Iw{constructor(e){super(e),Object.setPrototypeOf(this,YS.prototype)}};bP=YS=Bo([Ig({type:Hy.Sequence})],bP);var _P=JS=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,JS.prototype)}};_P=JS=Bo([Ig({type:Hy.Set,itemType:qw})],_P);var SP=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.value=e}toString(){return this.value}};Bo([Cg({type:Ky.BmpString})],SP.prototype,"value",void 0),SP=Bo([Ig({type:Hy.Choice})],SP);var PP=class extends Sw{};PP=Bo([Ig({type:Hy.Sequence})],PP);var EP,AP=ZS=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,ZS.prototype)}};AP=ZS=Bo([Ig({type:Hy.Sequence,itemType:PP})],AP);var kP=EP=class extends Gg{constructor(e){super(e),Object.setPrototypeOf(this,EP.prototype)}};kP=EP=Bo([Ig({type:Hy.Sequence,itemType:dw})],kP);class xP{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=0,this.subject=new zg,this.subjectPKInfo=new Pw,this.attributes=new kP,Object.assign(this,e)}}Bo([Cg({type:Ky.Integer})],xP.prototype,"version",void 0),Bo([Cg({type:zg})],xP.prototype,"subject",void 0),Bo([Cg({type:Pw})],xP.prototype,"subjectPKInfo",void 0),Bo([Cg({type:kP,implicit:!0,context:0})],xP.prototype,"attributes",void 0);class TP{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.certificationRequestInfo=new xP,this.signatureAlgorithm=new Sw,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}Bo([Cg({type:xP})],TP.prototype,"certificationRequestInfo",void 0),Bo([Cg({type:Sw})],TP.prototype,"signatureAlgorithm",void 0),Bo([Cg({type:Ky.BitString})],TP.prototype,"signature",void 0);var IP="crypto.algorithm";var CP,BP="crypto.algorithmProvider";xS.registerSingleton(BP,class{getAlgorithms(){return xS.resolveAll(IP)}toAsnAlgorithm(t){for(var r of(e._objectSpread2({},t),this.getAlgorithms())){var n=r.toAsnAlgorithm(t);if(n)return n}if(/^[0-9.]+$/.test(t.name)){var i=new Sw({algorithm:t.name});if("parameters"in t){var o=t;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 NP="1.3.36.3.3.2.8.1.1",DP="".concat(NP,".1"),GP="".concat(NP,".2"),RP="".concat(NP,".3"),OP="".concat(NP,".4"),LP="".concat(NP,".5"),MP="".concat(NP,".6"),jP="".concat(NP,".7"),FP="".concat(NP,".8"),UP="".concat(NP,".9"),zP="".concat(NP,".10"),VP="".concat(NP,".11"),qP="".concat(NP,".12"),HP="".concat(NP,".13"),KP="".concat(NP,".14"),WP="brainpoolP160r1",QP="brainpoolP160t1",YP="brainpoolP192r1",JP="brainpoolP192t1",ZP="brainpoolP224r1",$P="brainpoolP224t1",XP="brainpoolP256r1",eE="brainpoolP256t1",tE="brainpoolP320r1",rE="brainpoolP320t1",nE="brainpoolP384r1",iE="brainpoolP384t1",oE="brainpoolP512r1",aE="brainpoolP512t1",sE="ECDSA",lE=CP=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===sE.toLowerCase())if("hash"in e)switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return w_;case"sha-256":return b_;case"sha-384":return __;case"sha-512":return S_}else if("namedCurve"in e){var t="";switch(e.namedCurve){case"P-256":t=v_;break;case"K-256":t=CP.SECP256K1;break;case"P-384":t=y_;break;case"P-521":t=g_;break;case WP:t=DP;break;case QP:t=GP;break;case YP:t=RP;break;case JP:t=OP;break;case ZP:t=LP;break;case $P:t=MP;break;case XP:t=jP;break;case eE:t=FP;break;case tE:t=UP;break;case rE:t=zP;break;case nE:t=VP;break;case iE:t=qP;break;case oE:t=HP;break;case aE:t=KP}if(t)return new Sw({algorithm:c_,parameters:Rg.serialize(new x_({namedCurve:t}))})}return null}toWebAlgorithm(e){switch(e.algorithm){case u_:return{name:sE,hash:{name:"SHA-1"}};case h_:return{name:sE,hash:{name:"SHA-256"}};case p_:return{name:sE,hash:{name:"SHA-384"}};case f_:return{name:sE,hash:{name:"SHA-512"}};case c_:if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(Rg.parse(e.parameters,x_).namedCurve){case v_:return{name:sE,namedCurve:"P-256"};case CP.SECP256K1:return{name:sE,namedCurve:"K-256"};case y_:return{name:sE,namedCurve:"P-384"};case g_:return{name:sE,namedCurve:"P-521"};case DP:return{name:sE,namedCurve:WP};case GP:return{name:sE,namedCurve:QP};case RP:return{name:sE,namedCurve:YP};case OP:return{name:sE,namedCurve:JP};case LP:return{name:sE,namedCurve:ZP};case MP:return{name:sE,namedCurve:$P};case jP:return{name:sE,namedCurve:XP};case FP:return{name:sE,namedCurve:eE};case UP:return{name:sE,namedCurve:tE};case zP:return{name:sE,namedCurve:rE};case VP:return{name:sE,namedCurve:nE};case qP:return{name:sE,namedCurve:iE};case HP:return{name:sE,namedCurve:oE};case KP:return{name:sE,namedCurve:aE}}}return null}};lE.SECP256K1="1.3.132.0.10",lE=CP=Bo([TS()],lE),xS.registerSingleton(IP,lE);var cE,uE=Symbol("name"),dE=Symbol("value");class hE{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[uE]=e,this[dE]=r,t)this[n]=t[n]}}hE.NAME=uE,hE.VALUE=dE;class pE{static toString(e){var t=this.items[e];return t||e}}pE.items={[q_]:"sha1",[H_]:"sha224",[K_]:"sha256",[W_]:"sha384",[Q_]:"sha512",[B_]:"rsaEncryption",[L_]:"sha1WithRSAEncryption",[M_]:"sha224WithRSAEncryption",[j_]:"sha256WithRSAEncryption",[F_]:"sha384WithRSAEncryption",[U_]:"sha512WithRSAEncryption",[c_]:"ecPublicKey",[u_]:"ecdsaWithSHA1",[d_]:"ecdsaWithSHA224",[h_]:"ecdsaWithSHA256",[p_]:"ecdsaWithSHA384",[f_]:"ecdsaWithSHA512",[Um]:"TLS WWW server authentication",[zm]:"TLS WWW client authentication",[Vm]:"Code Signing",[qm]:"E-mail Protection",[Hm]:"Time Stamping",[Km]:"OCSP Signing",[a_]:"Signed Data"};class fE{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[hE.VALUE];for(var a in o&&(i=" ".concat(o)),r.push("".concat(n).concat(e[hE.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 c of s)c[hE.NAME]=a,r.push(...this.serializeObj(c,t));else if(s instanceof hE)s[hE.NAME]=a,r.push(...this.serializeObj(s,t));else if(vf.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 u=s.toTextObject();u[hE.NAME]=a,r.push(...this.serializeObj(u,t))}}return r}static serializeBufferSource(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=this.pad(t),n=vf.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)}}fE.oidSerializer=pE,fE.algorithmSerializer=class{static toTextObject(e){var t=new hE("Algorithm Identifier",{},pE.toString(e.algorithm));if(e.parameters)if(e.algorithm===c_){var r=(new lE).toWebAlgorithm(e);r&&"namedCurve"in r?t["Named Curve"]=r.namedCurve:t.Parameters=e.parameters}else t.Parameters=e.parameters;return t}};class vE{constructor(){if(1===arguments.length){var e=arguments.length<=0?void 0:arguments[0];this.rawData=Rg.serialize(e),this.onInit(e)}else{var t=Rg.parse(arguments.length<=0?void 0:arguments[0],arguments.length<=1?void 0:arguments[1]);this.rawData=vf.BufferSourceConverter.toArrayBuffer(arguments.length<=0?void 0:arguments[0]),this.onInit(t)}}equal(e){return e instanceof vE&&vf.isEqual(e.rawData,this.rawData)}toString(){switch(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"text"){case"asn":return Rg.toString(this.rawData);case"text":return fE.serialize(this.toTextObject());case"hex":return vf.Convert.ToHex(this.rawData);case"base64":return vf.Convert.ToBase64(this.rawData);case"base64url":return vf.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 hE(this.getTextName(),{},e)}}vE.NAME="ASN";class yE extends vE{constructor(){super(vf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])?vf.BufferSourceConverter.toArrayBuffer(arguments.length<=0?void 0:arguments[0]):Rg.serialize(new xw({extnID:arguments.length<=0?void 0:arguments[0],critical:arguments.length<=1?void 0:arguments[1],extnValue:new Yy(vf.BufferSourceConverter.toArrayBuffer(arguments.length<=2?void 0:arguments[2]))})),xw)}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[hE.NAME]===yE.NAME&&(e[hE.NAME]=pE.toString(this.type)),e}}class gE{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[cE]="CryptoProvider","undefined"!=typeof self&&"undefined"!=typeof crypto?this.set(gE.DEFAULT,crypto):"undefined"!=typeof global&&global.crypto&&global.crypto.subtle&&this.set(gE.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]:gE.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(gE.DEFAULT,e);return this}}cE=Symbol.toStringTag,gE.DEFAULT="default";var mE=new gE,wE=/^[0-2](?:\.[1-9][0-9]*)+$/;class bE{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(wE).test(t)?e:this.get(e);var t}register(e,t){this.items[e]=t,this.items[t]=e}}var _E=new bE;function SE(e,t){return"\\".concat(vf.Convert.ToHex(vf.Convert.FromUtf8String(t)).toUpperCase())}_E.register("CN","2.5.4.3"),_E.register("L","2.5.4.7"),_E.register("ST","2.5.4.8"),_E.register("O","2.5.4.10"),_E.register("OU","2.5.4.11"),_E.register("C","2.5.4.6"),_E.register("DC","0.9.2342.19200300.100.1.25"),_E.register("E","1.2.840.113549.1.9.1"),_E.register("G","2.5.4.42"),_E.register("I","2.5.4.43"),_E.register("SN","2.5.4.4"),_E.register("T","2.5.4.12");class PE{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 bE,this.asn=new zg,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 zg?this.asn=e:vf.BufferSourceConverter.isBufferSource(e)?this.asn=Rg.parse(e,zg):this.asn=this.fromJSON(e)}getField(e){var t=this.extraNames.findId(e)||_E.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)||_E.get(e)}toString(){return this.asn.map((e=>e.map((e=>{var t=this.getName(e.type)||e.type,r=e.value.anyValue?"#".concat(vf.Convert.ToHex(e.value.anyValue)):e.value.toString().replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,SE);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(vf.Convert.ToHex(i.value.anyValue)):i.value.toString())}t.push(n)}return t}fromString(e){for(var t=new zg,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 c=this.createAttribute(o,a);"+"===i?t[t.length-1].push(c):t.push(new Fg([c])),i=l}return t}fromJSON(e){var t=new zg;for(var r of e){var n=new Fg;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 jg({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=vf.Convert.FromHex(t.slice(1));else{var i=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=i:PE.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 Rg.serialize(this.asn)}getThumbprint(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e,n,i="SHA-1";return t.length>=1&&!(null===(e=t.length<=0?void 0:t[0])||void 0===e?void 0:e.subtle)?(i=(t.length<=0?void 0:t[0])||i,n=(t.length<=1?void 0:t[1])||mE.get()):n=(t.length<=0?void 0:t[0])||mE.get(),yield n.subtle.digest(i,r.toArrayBuffer())}))()}}var EE="Cannot initialize GeneralName from ASN.1 data.",AE="".concat(EE," Unsupported string format in use."),kE="".concat(EE," Value doesn't match to GUID regular expression."),xE=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,TE="1.3.6.1.4.1.311.25.1",IE="1.3.6.1.4.1.311.20.2.3",CE="dns",BE="dn",NE="email",DE="ip",GE="url",RE="guid",OE="upn",LE="id";class ME extends vE{constructor(){var e;if(2===arguments.length)switch(arguments.length<=0?void 0:arguments[0]){case BE:var t=new PE(arguments.length<=1?void 0:arguments[1]).toArrayBuffer(),r=Rg.parse(t,zg);e=new Kg({directoryName:r});break;case CE:e=new Kg({dNSName:arguments.length<=1?void 0:arguments[1]});break;case NE:e=new Kg({rfc822Name:arguments.length<=1?void 0:arguments[1]});break;case RE:var n=new RegExp(xE,"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?vf.Convert.ToHex(new Uint8Array(vf.Convert.FromHex(e)).reverse()):e)).join("");e=new Kg({otherName:new qg({typeId:TE,value:Rg.serialize(new Yy(vf.Convert.FromHex(i)))})});break;case DE:e=new Kg({iPAddress:arguments.length<=1?void 0:arguments[1]});break;case LE:e=new Kg({registeredID:arguments.length<=1?void 0:arguments[1]});break;case OE:e=new Kg({otherName:new qg({typeId:IE,value:Rg.serialize(ag.toASN(arguments.length<=1?void 0:arguments[1]))})});break;case GE:e=new Kg({uniformResourceIdentifier:arguments.length<=1?void 0:arguments[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else e=vf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])?Rg.parse(arguments.length<=0?void 0:arguments[0],Kg):arguments.length<=0?void 0:arguments[0];super(e)}onInit(e){if(null!=e.dNSName)this.type=CE,this.value=e.dNSName;else if(null!=e.rfc822Name)this.type=NE,this.value=e.rfc822Name;else if(null!=e.iPAddress)this.type=DE,this.value=e.iPAddress;else if(null!=e.uniformResourceIdentifier)this.type=GE,this.value=e.uniformResourceIdentifier;else if(null!=e.registeredID)this.type=LE,this.value=e.registeredID;else if(null!=e.directoryName)this.type=BE,this.value=new PE(e.directoryName).toString();else{if(null==e.otherName)throw new Error(AE);if(e.otherName.typeId===TE){this.type=RE;var t=Rg.parse(e.otherName.value,Yy),r=new RegExp(xE,"i").exec(vf.Convert.ToHex(t));if(!r)throw new Error(kE);this.value=r.slice(1).map(((e,t)=>t<3?vf.Convert.ToHex(new Uint8Array(vf.Convert.FromHex(e)).reverse()):e)).join("-")}else{if(e.otherName.typeId!==IE)throw new Error(AE);this.type=OE,this.value=Rg.parse(e.otherName.value,Lg).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){var e;switch(this.type){case BE:case CE:case RE:case DE:case LE:case OE:case GE:e=this.type.toUpperCase();break;case NE:e="Email";break;default:throw new Error("Unsupported GeneralName type")}var t=this.value;return this.type===LE&&(t=pE.toString(t)),new hE(e,void 0,t)}}class jE extends vE{constructor(e){var t;if(e instanceof pm)t=e;else if(Array.isArray(e)){var r=[];for(var n of e)if(n instanceof Kg)r.push(n);else{var i=Rg.parse(new ME(n.type,n.value).rawData,Kg);r.push(i)}t=new pm(r)}else{if(!vf.BufferSourceConverter.isBufferSource(e))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");t=Rg.parse(e,pm)}super(t)}onInit(e){var t=[];for(var r of e){var n=null;try{n=new ME(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[hE.NAME]];Array.isArray(n)||(n=[],e[r[hE.NAME]]=n),n.push(r)}return e}}jE.NAME="GeneralNames";var FE,UE,zE="-{5}",VE="\\n",qE="[^".concat(VE,"]+"),HE="".concat(zE,"BEGIN (").concat(qE,"(?=").concat(zE,"))").concat(zE),KE="".concat(zE,"END \\1").concat(zE),WE="\\n",QE="[^:".concat(VE,"]+"),YE="(?:[^".concat(VE,"]+").concat(WE,"(?: +[^").concat(VE,"]+").concat(WE,")*)"),JE="(?:".concat("[a-zA-Z0-9=+/]+").concat(WE,")+"),ZE="".concat(HE).concat(WE,"(?:((?:").concat(QE,": ").concat(YE,")+))?").concat(WE,"?(").concat(JE,")").concat(KE);class $E{static isPem(e){return"string"==typeof e&&new RegExp(ZE,"g").test(e)}static decodeWithHeaders(e){e=e.replace(/\r/g,"");for(var t=new RegExp(ZE,"g"),r=[],n=null;n=t.exec(e);){var i=n[3].replace(new RegExp("[".concat(VE,"]+"),"g"),""),o={type:n[1],headers:[],rawData:vf.Convert.FromBase64(i)},a=n[2];if(a){var s=a.split(new RegExp(WE,"g")),l=null;for(var c of s){var[u,d]=c.split(/:(.*)/);if(void 0===d){if(!l)throw new Error("Cannot parse PEM string. Incorrect header value");l.value+=u.trim()}else l&&o.headers.push(l),l={key:u,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(!vf.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:vf.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:vf.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=vf.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")}}$E.CertificateTag="CERTIFICATE",$E.CrlTag="CRL",$E.CertificateRequestTag="CERTIFICATE REQUEST",$E.PublicKeyTag="PUBLIC KEY",$E.PrivateKeyTag="PRIVATE KEY";class XE extends vE{static isAsnEncoded(e){return vf.BufferSourceConverter.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e){if($E.isPem(e))return $E.decode(e)[0];if(vf.Convert.isHex(e))return vf.Convert.FromHex(e);if(vf.Convert.isBase64(e))return vf.Convert.FromBase64(e);if(vf.Convert.isBase64Url(e))return vf.Convert.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}var t=vf.Convert.ToBinary(e);return $E.isPem(t)?$E.decode(t)[0]:vf.Convert.isHex(t)?vf.Convert.FromHex(t):vf.Convert.isBase64(t)?vf.Convert.FromBase64(t):vf.Convert.isBase64Url(t)?vf.Convert.FromBase64Url(t):vf.BufferSourceConverter.toArrayBuffer(e)}constructor(){XE.isAsnEncoded(arguments.length<=0?void 0:arguments[0])?super(XE.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?$E.encode(this.rawData,this.tag):super.toString(e)}}class eA extends XE{static create(t){var r=arguments;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:mE.get();if(t instanceof eA)return t;if(gE.isCryptoKey(t)){if("public"!==t.type)throw new TypeError("Public key is required");var n=yield e.subtle.exportKey("spki",t);return new eA(n)}if(t.publicKey)return t.publicKey;if(vf.BufferSourceConverter.isBufferSource(t))return new eA(t);throw new TypeError("Unsupported PublicKeyType")}))()}constructor(e){XE.isAsnEncoded(e)?super(e,Pw):super(e),this.tag=$E.PublicKeyTag}export(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var n,i=["verify"],o=e._objectSpread2({hash:"SHA-256"},r.algorithm);t.length>1?(o=(t.length<=0?void 0:t[0])||o,i=(t.length<=1?void 0:t[1])||i,n=(t.length<=2?void 0:t[2])||mE.get()):n=(t.length<=0?void 0:t[0])||mE.get();var a=r.rawData,s=Rg.parse(r.rawData,Pw);return s.algorithm.algorithm===G_&&(a=function(e,t){return e.algorithm=new Sw({algorithm:B_,parameters:null}),t=Rg.serialize(e),t}(s,a)),n.subtle.importKey("spki",a,o,!0,i)}))()}onInit(e){var t=xS.resolve(BP),r=this.algorithm=t.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===B_){var n=Rg.parse(e.subjectPublicKey,lS),i=vf.BufferSourceConverter.toUint8Array(n.modulus);r.publicExponent=vf.BufferSourceConverter.toUint8Array(n.publicExponent),r.modulusLength=(i[0]?i:i.slice(1)).byteLength<<3}}getThumbprint(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e,n,i="SHA-1";return t.length>=1&&!(null===(e=t.length<=0?void 0:t[0])||void 0===e?void 0:e.subtle)?(i=(t.length<=0?void 0:t[0])||i,n=(t.length<=1?void 0:t[1])||mE.get()):n=(t.length<=0?void 0:t[0])||mE.get(),yield n.subtle.digest(i,r.rawData)}))()}getKeyIdentifier(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e,n="SHA-1";1===t.length?"string"==typeof(t.length<=0?void 0:t[0])?(n=t.length<=0?void 0:t[0],e=mE.get()):e=t.length<=0?void 0:t[0]:2===t.length?(n=t.length<=0?void 0:t[0],e=t.length<=1?void 0:t[1]):e=mE.get();var i=Rg.parse(r.rawData,Pw);return yield e.subtle.digest(n,i.subjectPublicKey)}))()}toTextObject(){var e=this.toTextObjectEmpty(),t=Rg.parse(this.rawData,Pw);if(e.Algorithm=fE.serializeAlgorithm(t.algorithm),t.algorithm.algorithm===c_)e["EC Point"]=t.subjectPublicKey;else e["Raw Data"]=t.subjectPublicKey;return e}}class tA extends yE{static create(t){var r=arguments;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]&&r[1],n=r.length>2&&void 0!==r[2]?r[2]:mE.get();if("name"in t&&"serialNumber"in t)return new tA(t,e);var i=yield eA.create(t,n),o=yield i.getKeyIdentifier(n);return new tA(vf.Convert.ToHex(o),e)}))()}constructor(){if(vf.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 lm({keyIdentifier:new sm(vf.Convert.FromHex(arguments.length<=0?void 0:arguments[0]))});super(am,arguments.length<=1?void 0:arguments[1],Rg.serialize(e))}else{var t=arguments.length<=0?void 0:arguments[0],r=t.name instanceof jE?Rg.parse(t.name.rawData,pm):t.name,n=new lm({authorityCertIssuer:r,authorityCertSerialNumber:vf.Convert.FromHex(t.serialNumber)});super(am,arguments.length<=1?void 0:arguments[1],Rg.serialize(n))}}onInit(e){super.onInit(e);var t=Rg.parse(e.extnValue,lm);t.keyIdentifier&&(this.keyId=vf.Convert.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?vf.Convert.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){var e=this.toTextObjectWithoutValue(),t=Rg.parse(this.value,lm);return t.authorityCertIssuer&&(e["Authority Issuer"]=new jE(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}}tA.NAME="Authority Key Identifier";class rA extends yE{constructor(){if(vf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var e=Rg.parse(this.value,dm);this.ca=e.cA,this.pathLength=e.pathLenConstraint}else{var t=new dm({cA:arguments.length<=0?void 0:arguments[0],pathLenConstraint:arguments.length<=1?void 0:arguments[1]});super(um,arguments.length<=2?void 0:arguments[2],Rg.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}}rA.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"}(FE||(FE={}));class nA extends yE{constructor(){if(vf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var e=Rg.parse(this.value,Fm);this.usages=e.map((e=>e))}else{var t=new Fm(arguments.length<=0?void 0:arguments[0]);super(jm,arguments.length<=1?void 0:arguments[1],Rg.serialize(t)),this.usages=arguments.length<=0?void 0:arguments[0]}}toTextObject(){var e=this.toTextObjectWithoutValue();return e[""]=this.usages.map((e=>pE.toString(e))).join(", "),e}}nA.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"}(UE||(UE={}));class iA extends yE{constructor(){if(vf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var e=Rg.parse(this.value,ew);this.usages=e.toNumber()}else{var t=new ew(arguments.length<=0?void 0:arguments[0]);super(Xm,arguments.length<=1?void 0:arguments[1],Rg.serialize(t)),this.usages=arguments.length<=0?void 0:arguments[0]}}toTextObject(){var e=this.toTextObjectWithoutValue(),t=Rg.parse(this.value,ew);return e[""]=t.toJSON().join(", "),e}}iA.NAME="Key Usages";class oA extends yE{static create(t){var r=arguments;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]&&r[1],n=r.length>2&&void 0!==r[2]?r[2]:mE.get(),i=yield eA.create(t,n),o=yield i.getKeyIdentifier(n);return new oA(vf.Convert.ToHex(o),e)}))()}constructor(){if(vf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var e=Rg.parse(this.value,gw);this.keyId=vf.Convert.ToHex(e)}else{var t="string"==typeof(arguments.length<=0?void 0:arguments[0])?vf.Convert.FromHex(arguments.length<=0?void 0:arguments[0]):arguments.length<=0?void 0:arguments[0],r=new gw(t);super(yw,arguments.length<=1?void 0:arguments[1],Rg.serialize(r)),this.keyId=vf.Convert.ToHex(t)}}toTextObject(){var e=this.toTextObjectWithoutValue(),t=Rg.parse(this.value,gw);return e[""]=t,e}}oA.NAME="Subject Key Identifier";class aA extends yE{constructor(){vf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])?super(arguments.length<=0?void 0:arguments[0]):super(cw,arguments.length<=1?void 0:arguments[1],new jE((arguments.length<=0?void 0:arguments[0])||[]).rawData)}onInit(e){super.onInit(e);var t=Rg.parse(e.extnValue,uw);this.names=new jE(t)}toTextObject(){var e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(var r in t)e[r]=t[r];return e}}aA.NAME="Subject Alternative Name";class sA{static register(e,t){this.items.set(e,t)}static create(e){var t=new yE(e),r=this.items.get(t.type);return r?new r(e):t}}sA.items=new Map;class lA extends yE{constructor(){var e;if(vf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var t=Rg.parse(this.value,Pm);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 Pm(r.map((e=>new Sm({policyIdentifier:e}))));super(ym,n,Rg.serialize(i)),this.policies=r}}toTextObject(){var e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map((e=>new hE("",{},pE.toString(e)))),e}}lA.NAME="Certificate Policies",sA.register(ym,lA);class cA extends yE{constructor(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];if(vf.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 Bm({distributionPoint:new Cm({fullName:[new Kg({uniformResourceIdentifier:e})]})}))),o=new Dm(i);super(Tm,r[1],Rg.serialize(o))}else{var a=new Dm(r[0]);super(Tm,r[1],Rg.serialize(a))}null!==(e=this.distributionPoints)&&void 0!==e||(this.distributionPoints=[])}onInit(e){super.onInit(e);var t=Rg.parse(e.extnValue,Dm);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 ME(e).toString())).join(", ")),e.reasons&&(r.Reasons=e.reasons.toString()),e.cRLIssuer&&(r["CRL Issuer"]=e.cRLIssuer.map((e=>e.toString())).join(", ")),r})),e}}cA.NAME="CRL Distribution Points";class uA extends yE{constructor(){var e,t,r,n;if(vf.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 om){var i=new om(arguments.length<=0?void 0:arguments[0]);super(nm,arguments.length<=1?void 0:arguments[1],Rg.serialize(i))}else{var o=arguments.length<=0?void 0:arguments[0],a=new om;hA(a,o,$g,"ocsp"),hA(a,o,Xg,"caIssuers"),hA(a,o,em,"timeStamping"),hA(a,o,tm,"caRepository"),super(nm,arguments.length<=1?void 0:arguments[1],Rg.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=[],Rg.parse(e.extnValue,om).forEach((e=>{switch(e.accessMethod){case $g:this.ocsp.push(new ME(e.accessLocation));break;case Xg:this.caIssuers.push(new ME(e.accessLocation));break;case em:this.timeStamping.push(new ME(e.accessLocation));break;case tm:this.caRepository.push(new ME(e.accessLocation))}}))}toTextObject(){var e=this.toTextObjectWithoutValue();return this.ocsp.length&&dA(e,"OCSP",this.ocsp),this.caIssuers.length&&dA(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&dA(e,"Time Stamping",this.timeStamping),this.caRepository.length&&dA(e,"CA Repository",this.caRepository),e}}function dA(e,t,r){if(1===r.length)e[t]=r[0].toTextObject();else{var n=new hE("");r.forEach(((e,t)=>{var r=e.toTextObject(),i="".concat(r[hE.NAME]," ").concat(t+1),o=n[i];Array.isArray(o)||(o=[],n[i]=o),o.push(r)})),e[t]=n}}function hA(e,t,r,n){var i=t[n];i&&(Array.isArray(i)?i:[i]).forEach((t=>{"string"==typeof t&&(t=new ME("url",t)),e.push(new im({accessMethod:r,accessLocation:Rg.parse(t.rawData,Kg)}))}))}uA.NAME="Authority Info Access";class pA extends vE{constructor(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];if(vf.BufferSourceConverter.isBufferSource(r[0]))e=vf.BufferSourceConverter.toArrayBuffer(r[0]);else{var i=r[0],o=Array.isArray(r[1])?r[1].map((e=>vf.BufferSourceConverter.toArrayBuffer(e))):[];e=Rg.serialize(new dw({type:i,values:o}))}super(e,dw)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){var e=this.toTextObjectWithoutValue();return e.Value=this.values.map((e=>new hE("",{"":e}))),e}toTextObjectWithoutValue(){var e=this.toTextObjectEmpty();return e[hE.NAME]===pA.NAME&&(e[hE.NAME]=pE.toString(this.type)),e}}pA.NAME="Attribute";class fA extends pA{constructor(){var e;if(vf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0]))super(arguments.length<=0?void 0:arguments[0]);else{var t=new wP({printableString:arguments.length<=0?void 0:arguments[0]});super(eP,[Rg.serialize(t)])}null!==(e=this.password)&&void 0!==e||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){var t=Rg.parse(this.values[0],wP);this.password=t.toString()}}toTextObject(){var e=this.toTextObjectWithoutValue();return e[hE.VALUE]=this.password,e}}fA.NAME="Challenge Password";class vA extends pA{constructor(){var e;if(vf.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 Iw;for(var n of t)r.push(Rg.parse(n.rawData,xw));super(tP,[Rg.serialize(r)])}null!==(e=this.items)&&void 0!==e||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){var t=Rg.parse(this.values[0],Iw);this.items=t.map((e=>sA.create(Rg.serialize(e))))}}toTextObject(){var e=this.toTextObjectWithoutValue(),t=this.items.map((e=>e.toTextObject()));for(var r of t)e[r[hE.NAME]]=r;return e}}vA.NAME="Extensions";class yA{static register(e,t){this.items.set(e,t)}static create(e){var t=new pA(e),r=this.items.get(t.type);return r?new r(e):t}}yA.items=new Map;var gA,mA="crypto.signatureFormatter";var wA=gA=class{static createPssParams(e,t){var r=gA.getHashAlgorithm(e);return r?new rS({hashAlgorithm:r,maskGenAlgorithm:new Sw({algorithm:Y_,parameters:Rg.serialize(r)}),saltLength:t}):null}static getHashAlgorithm(e){var t=xS.resolve(BP);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 Sw({algorithm:B_,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 Sw({algorithm:L_,parameters:null});case"sha-256":return new Sw({algorithm:j_,parameters:null});case"sha-384":return new Sw({algorithm:F_,parameters:null});case"sha-512":return new Sw({algorithm:U_,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=gA.createPssParams(e.hash,e.saltLength);if(!r)throw new Error("Cannot create PSS parameters");return new Sw({algorithm:G_,parameters:Rg.serialize(r)})}return new Sw({algorithm:G_,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case B_:return{name:"RSASSA-PKCS1-v1_5"};case L_:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case j_:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case F_:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case U_:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case G_:if(e.parameters){var t=Rg.parse(e.parameters,rS);return{name:"RSA-PSS",hash:xS.resolve(BP).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:"RSA-PSS"}}return null}};wA=gA=Bo([TS()],wA),xS.registerSingleton(IP,wA);var bA=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new Sw({algorithm:q_});case"sha-256":return new Sw({algorithm:K_});case"sha-384":return new Sw({algorithm:W_});case"sha-512":return new Sw({algorithm:Q_})}return null}toWebAlgorithm(e){switch(e.algorithm){case q_:return{name:"SHA-1"};case K_:return{name:"SHA-256"};case W_:return{name:"SHA-384"};case Q_:return{name:"SHA-512"}}return null}};bA=Bo([TS()],bA),xS.registerSingleton(IP,bA);class _A{addPadding(e,t){var r=vf.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=vf.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=_A.namedCurveSize.get(r)||_A.defaultNamedCurveSize,i=new I_,o=vf.BufferSourceConverter.toUint8Array(t);return i.r=this.removePadding(o.slice(0,n),!0),i.s=this.removePadding(o.slice(n,n+n),!0),Rg.serialize(i)}return null}toWebSignature(e,t){if("ECDSA"===e.name){var r=Rg.parse(t,I_),n=e.namedCurve,i=_A.namedCurveSize.get(n)||_A.defaultNamedCurveSize,o=this.addPadding(i,this.removePadding(r.r)),a=this.addPadding(i,this.removePadding(r.s));return vf.combine(o,a)}return null}}_A.namedCurveSize=new Map,_A.defaultNamedCurveSize=32;var SA,PA,EA="1.3.101.110",AA="1.3.101.111",kA="1.3.101.112",xA="1.3.101.113",TA=class{toAsnAlgorithm(e){var t=null;switch(e.name.toLowerCase()){case"ed25519":t=kA;break;case"x25519":t=EA;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=kA;break;case"ed448":t=xA}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=EA;break;case"x448":t=AA}}return t?new Sw({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case kA:return{name:"Ed25519"};case xA:return{name:"EdDSA",namedCurve:"Ed448"};case EA:return{name:"X25519"};case AA:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};TA=Bo([TS()],TA),xS.registerSingleton(IP,TA);(class extends XE{constructor(e){XE.isAsnEncoded(e)?super(e,TP):super(e),this.tag=$E.CertificateRequestTag}onInit(e){this.tbs=Rg.serialize(e.certificationRequestInfo),this.publicKey=new eA(e.certificationRequestInfo.subjectPKInfo);var t=xS.resolve(BP);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map((e=>yA.create(Rg.serialize(e))));var r=this.getAttribute(tP);this.extensions=[],r instanceof vA&&(this.extensions=r.items),this.subjectName=new PE(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 t=arguments,r=this;return e._asyncToGenerator((function*(){var n=t.length>0&&void 0!==t[0]?t[0]:mE.get(),i=e._objectSpread2(e._objectSpread2({},r.publicKey.algorithm),r.signatureAlgorithm),o=yield r.publicKey.export(i,["verify"],n),a=xS.resolveAll(mA).reverse(),s=null;for(var l of a)if(s=l.toWebSignature(i,r.signature))break;if(!s)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return yield n.subtle.verify(r.signatureAlgorithm,o,s,r.tbs)}))()}toTextObject(){var e=this.toTextObjectEmpty(),t=Rg.parse(this.rawData,TP),r=t.certificationRequestInfo,n=new hE("",{Version:"".concat(Tw[r.version]," (").concat(r.version,")"),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){var i=new hE("");for(var o of this.attributes){var a=o.toTextObject();i[a[hE.NAME]]=a}n.Attributes=i}return e.Data=n,e.Signature=new hE("",{Algorithm:fE.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}).NAME="PKCS#10 Certificate Request";class IA extends XE{constructor(e){XE.isAsnEncoded(e)?super(e,Bw):super(e),this.tag=$E.CertificateTag}onInit(e){var t=e.tbsCertificate;this.tbs=Rg.serialize(t),this.serialNumber=vf.Convert.ToHex(t.serialNumber),this.subjectName=new PE(t.subject),this.subject=new PE(t.subject).toString(),this.issuerName=new PE(t.issuer),this.issuer=this.issuerName.toString();var r=xS.resolve(BP);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=>sA.create(Rg.serialize(e))))),this.publicKey=new eA(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 t=arguments,r=this;return e._asyncToGenerator((function*(){var n,i,o=t.length>0&&void 0!==t[0]?t[0]:{},a=t.length>1&&void 0!==t[1]?t[1]:mE.get(),s=o.publicKey;try{if(s)if("publicKey"in s)n=e._objectSpread2(e._objectSpread2({},s.publicKey.algorithm),r.signatureAlgorithm),i=yield s.publicKey.export(n,["verify"],a);else if(s instanceof eA)n=e._objectSpread2(e._objectSpread2({},s.algorithm),r.signatureAlgorithm),i=yield s.export(n,["verify"],a);else if(vf.BufferSourceConverter.isBufferSource(s)){var l=new eA(s);n=e._objectSpread2(e._objectSpread2({},l.algorithm),r.signatureAlgorithm),i=yield l.export(n,["verify"],a)}else n=e._objectSpread2(e._objectSpread2({},s.algorithm),r.signatureAlgorithm),i=s;else n=e._objectSpread2(e._objectSpread2({},r.publicKey.algorithm),r.signatureAlgorithm),i=yield r.publicKey.export(n,["verify"],a)}catch(e){return!1}var c=xS.resolveAll(mA).reverse(),u=null;for(var d of c)if(u=d.toWebSignature(n,r.signature))break;if(!u)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");var h=yield a.subtle.verify(r.signatureAlgorithm,i,u,r.tbs);if(o.signatureOnly)return h;var p=(o.date||new Date).getTime();return h&&r.notBefore.getTime()<p&&p<r.notAfter.getTime()}))()}getThumbprint(){var t=arguments,r=this;return e._asyncToGenerator((function*(){for(var e,n="SHA-1",i=t.length,o=new Array(i),a=0;a<i;a++)o[a]=t[a];return o[0]&&(o[0].subtle?e=o[0]:(n=o[0]||n,e=o[1])),null!=e||(e=mE.get()),yield e.subtle.digest(n,r.rawData)}))()}isSelfSigned(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e=t.length>0&&void 0!==t[0]?t[0]:mE.get();return r.subject===r.issuer&&(yield r.verify({signatureOnly:!0},e))}))()}toTextObject(){var e=this.toTextObjectEmpty(),t=Rg.parse(this.rawData,Bw),r=t.tbsCertificate,n=new hE("",{Version:"".concat(Tw[r.version]," (").concat(r.version,")"),"Serial Number":r.serialNumber,"Signature Algorithm":fE.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new hE("",{"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 hE("");for(var o of this.extensions){var a=o.toTextObject();i[a[hE.NAME]]=a}n.Extensions=i}return e.Data=n,e.Signature=new hE("",{Algorithm:fE.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}}IA.NAME="Certificate";class CA{static createSelfSigned(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:mE.get();if(!t.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!t.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return n.create({serialNumber:t.serialNumber,subject:t.name,issuer:t.name,notBefore:t.notBefore,notAfter:t.notAfter,publicKey:t.keys.publicKey,signingKey:t.keys.privateKey,signingAlgorithm:t.signingAlgorithm,extensions:t.extensions},e)}))()}static create(t){var r=arguments;return e._asyncToGenerator((function*(){var n,i,o=r.length>1&&void 0!==r[1]?r[1]:mE.get();i=t.publicKey instanceof eA?t.publicKey.rawData:"publicKey"in t.publicKey?t.publicKey.publicKey.rawData:vf.BufferSourceConverter.isBufferSource(t.publicKey)?t.publicKey:yield o.subtle.exportKey("spki",t.publicKey);var a=t.serialNumber?vf.BufferSourceConverter.toUint8Array(vf.Convert.FromHex(t.serialNumber)):o.getRandomValues(new Uint8Array(16));a[0]>127&&(a[0]&=127),a.length>1&&0===a[0]&&(a[1]|=128);var s=t.notBefore||new Date,l=t.notAfter||new Date(s.getTime()+31536e6),c=new Bw({tbsCertificate:new Cw({version:Tw.v3,serialNumber:a,validity:new kw({notBefore:s,notAfter:l}),extensions:new Iw((null===(n=t.extensions)||void 0===n?void 0:n.map((e=>Rg.parse(e.rawData,xw))))||[]),subjectPublicKeyInfo:Rg.parse(i,Pw)})});if(t.subject){var u=t.subject instanceof PE?t.subject:new PE(t.subject);c.tbsCertificate.subject=Rg.parse(u.toArrayBuffer(),zg)}if(t.issuer){var d=t.issuer instanceof PE?t.issuer:new PE(t.issuer);c.tbsCertificate.issuer=Rg.parse(d.toArrayBuffer(),zg)}var h={hash:"SHA-256"},p="signingKey"in t?e._objectSpread2(e._objectSpread2(e._objectSpread2({},h),t.signingAlgorithm),t.signingKey.algorithm):e._objectSpread2(e._objectSpread2({},h),t.signingAlgorithm),f=xS.resolve(BP);c.tbsCertificate.signature=c.signatureAlgorithm=f.toAsnAlgorithm(p);var v=Rg.serialize(c.tbsCertificate),y="signingKey"in t?yield o.subtle.sign(p,t.signingKey,v):t.signature,g=xS.resolveAll(mA).reverse(),m=null;for(var w of g)if(m=w.toAsnSignature(p,y))break;if(!m)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return c.signatureValue=m,new IA(Rg.serialize(c))}))()}}!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"}(SA||(SA={})),sA.register(um,rA),sA.register(jm,nA),sA.register(Xm,iA),sA.register(yw,oA),sA.register(am,tA),sA.register(cw,aA),sA.register(Tm,cA),sA.register(nm,uA),yA.register(eP,fA),yA.register(tP,vA),xS.registerSingleton(mA,class{toAsnSignature(e,t){return vf.BufferSourceConverter.toArrayBuffer(t)}toWebSignature(e,t){return vf.BufferSourceConverter.toArrayBuffer(t)}}),xS.registerSingleton(mA,_A),_A.namedCurveSize.set("P-256",32),_A.namedCurveSize.set("K-256",32),_A.namedCurveSize.set("P-384",48),_A.namedCurveSize.set("P-521",66);class BA extends Aa{listen(){return e._asyncToGenerator((function*(){throw new tf("WebRTCTransport.createListener")}))()}getAddrs(){return[]}updateAnnounceAddrs(){}close(){return e._asyncToGenerator((function*(){}))()}}function NA(){var t,r=Hc(),n=!1;return{sink:(t=e._asyncToGenerator((function*(e){if(n)throw new Error("already piped");n=!0,r.resolve(e)})),function(e){return t.apply(this,arguments)}),source:e._wrapAsyncGenerator((function*(){var t=yield e._awaitAsyncGenerator(r.promise);yield*e._asyncGeneratorDelegate(e._asyncIterator(t))}))()}}var DA=65535,GA=Boolean(null===(PA=globalThis.process)||void 0===PA||null===(PA=PA.env)||void 0===PA?void 0:PA.DUMP_SESSION_KEYS);function RA(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function OA(e){if("boolean"!=typeof e)throw new Error("boolean expected, not ".concat(e))}function LA(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function MA(e){if(!RA(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 jA(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 FA(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function UA(){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 zA=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function VA(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(!RA(e))throw new Error("Uint8Array expected, got "+typeof e);e=QA(e)}return e}var qA=(e,t)=>{function r(r){if(MA(r),!zA)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?MA(a):MA(a,e.nonceLength)}var s=e.tagLength;s&&void 0!==i[1]&&MA(i[1]);var l=t(r,...i),c=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");MA(t)}},u=!1;return{encrypt(e,t){if(u)throw new Error("cannot encrypt() twice with same key + nonce");return u=!0,MA(e),c(l.encrypt.length,t),l.encrypt(e,t)},decrypt(e,t){if(MA(e),s&&e.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return c(l.decrypt.length,t),l.decrypt(e,t)}}}return Object.assign(r,e),r};function HA(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 KA(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 WA(e,t,r){OA(r);var n,i=new Uint8Array(16),o=(n=i,new DataView(n.buffer,n.byteOffset,n.byteLength));return KA(o,0,BigInt(t),r),KA(o,8,BigInt(e),r),i}function QA(e){return Uint8Array.from(e)}var YA=e=>Uint8Array.from(e.split("").map((e=>e.charCodeAt(0)))),JA=YA("expand 16-byte k"),ZA=YA("expand 32-byte k"),$A=FA(JA),XA=FA(ZA);function ek(e,t){return e<<t|e>>>32-t}function tk(e){return e.byteOffset%4==0}var rk=2**32-1,nk=new Uint32Array;function ik(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 LA(i),LA(a),OA(o),OA(r),function(t,s,l,c){var u=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0;MA(t),MA(s),MA(l);var d=l.length;if(void 0===c&&(c=new Uint8Array(d)),MA(c),LA(u),u<0||u>=rk)throw new Error("arx: counter overflow");if(c.length<d)throw new Error("arx: output (".concat(c.length,") is shorter than data (").concat(d,")"));var h,p,f=[],v=t.length;if(32===v)f.push(h=QA(t)),p=XA;else{if(16!==v||!r)throw new Error("arx: invalid 32-byte key, got length=".concat(v));(h=new Uint8Array(32)).set(t),h.set(t,16),p=$A,f.push(h)}tk(s)||f.push(s=QA(s));var y=FA(h);if(n){if(24!==s.length)throw new Error("arx: extended nonce must be 24 bytes");n(p,y,FA(s.subarray(0,16)),y),s=s.subarray(16)}var g=16-i;if(g!==s.length)throw new Error("arx: nonce must be ".concat(g," or 16 bytes"));if(12!==g){var m=new Uint8Array(12);m.set(s,o?0:12-s.length),s=m,f.push(s)}var w=FA(s);return function(e,t,r,n,i,o,a,s){for(var l=i.length,c=new Uint8Array(64),u=FA(c),d=tk(i)&&tk(o),h=d?FA(i):nk,p=d?FA(o):nk,f=0;f<l;a++){if(e(t,r,n,u,a,s),a>=rk)throw new Error("arx: counter overflow");var v=Math.min(64,l-f);if(d&&64===v){var y=f/4;if(f%4!=0)throw new Error("arx: invalid block position");for(var g,m=0;m<16;m++)p[g=y+m]=h[g]^u[m];f+=64}else{for(var w,b=0;b<v;b++)o[w=f+b]=i[w]^c[b];f+=v}}}(e,p,y,w,l,c,u,a),UA(...f),c}}var ok=(e,t)=>255&e[t++]|(255&e[t++])<<8;class ak{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,MA(e=VA(e),32);var t=ok(e,0),r=ok(e,2),n=ok(e,4),i=ok(e,6),o=ok(e,8),a=ok(e,10),s=ok(e,12),l=ok(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 c=0;c<8;c++)this.pad[c]=ok(e,16+2*c)}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],c=i[4],u=i[5],d=i[6],h=i[7],p=i[8],f=i[9],v=ok(e,t+0),y=ok(e,t+2),g=ok(e,t+4),m=ok(e,t+6),w=ok(e,t+8),b=ok(e,t+10),_=ok(e,t+12),S=ok(e,t+14),P=n[0]+(8191&v),E=n[1]+(8191&(v>>>13|y<<3)),A=n[2]+(8191&(y>>>10|g<<6)),k=n[3]+(8191&(g>>>7|m<<9)),x=n[4]+(8191&(m>>>4|w<<12)),T=n[5]+(w>>>1&8191),I=n[6]+(8191&(w>>>14|b<<2)),C=n[7]+(8191&(b>>>11|_<<5)),B=n[8]+(8191&(_>>>8|S<<8)),N=n[9]+(S>>>5|r),D=0,G=D+P*o+E*(5*f)+A*(5*p)+k*(5*h)+x*(5*d);D=G>>>13,G&=8191;var R=(D+=(G+=T*(5*u)+I*(5*c)+C*(5*l)+B*(5*s)+N*(5*a))>>>13)+P*a+E*o+A*(5*f)+k*(5*p)+x*(5*h);D=R>>>13,R&=8191,D+=(R+=T*(5*d)+I*(5*u)+C*(5*c)+B*(5*l)+N*(5*s))>>>13,R&=8191;var O=D+P*s+E*a+A*o+k*(5*f)+x*(5*p);D=O>>>13,O&=8191,D+=(O+=T*(5*h)+I*(5*d)+C*(5*u)+B*(5*c)+N*(5*l))>>>13,O&=8191;var L=D+P*l+E*s+A*a+k*o+x*(5*f);D=L>>>13,L&=8191,D+=(L+=T*(5*p)+I*(5*h)+C*(5*d)+B*(5*u)+N*(5*c))>>>13,L&=8191;var M=D+P*c+E*l+A*s+k*a+x*o;D=M>>>13,M&=8191,D+=(M+=T*(5*f)+I*(5*p)+C*(5*h)+B*(5*d)+N*(5*u))>>>13,M&=8191;var j=D+P*u+E*c+A*l+k*s+x*a;D=j>>>13,j&=8191,D+=(j+=T*o+I*(5*f)+C*(5*p)+B*(5*h)+N*(5*d))>>>13,j&=8191;var F=D+P*d+E*u+A*c+k*l+x*s;D=F>>>13,F&=8191,D+=(F+=T*a+I*o+C*(5*f)+B*(5*p)+N*(5*h))>>>13,F&=8191;var U=D+P*h+E*d+A*u+k*c+x*l;D=U>>>13,U&=8191,D+=(U+=T*s+I*a+C*o+B*(5*f)+N*(5*p))>>>13,U&=8191;var z=D+P*p+E*h+A*d+k*u+x*c;D=z>>>13,z&=8191,D+=(z+=T*l+I*s+C*a+B*o+N*(5*f))>>>13,z&=8191;var V=D+P*f+E*p+A*h+k*d+x*u;D=V>>>13,V&=8191,D+=(V+=T*c+I*l+C*s+B*a+N*o)>>>13,V&=8191,G=8191&(D=(D=(D<<2)+D|0)+(G&=8191)|0),R+=D>>>=13,n[0]=G,n[1]=R,n[2]=O,n[3]=L,n[4]=M,n[5]=j,n[6]=F,n[7]=U,n[8]=z,n[9]=V}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 c=e[0]+t[0];e[0]=65535&c;for(var u=1;u<8;u++)c=(e[u]+t[u]|0)+(c>>>16)|0,e[u]=65535&c;UA(r)}update(e){jA(this),MA(e=VA(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(){UA(this.h,this.r,this.buffer,this.pad)}digestInto(e){jA(this),function(e,t){MA(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 sk,lk,ck,uk=(lk=(e,t)=>sk(t).update(VA(e)).digest(),ck=(sk=e=>new ak(e))(new Uint8Array(32)),lk.outputLen=ck.outputLen,lk.blockLen=ck.blockLen,lk.create=e=>sk(e),lk);function dk(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],c=e[3],u=t[0],d=t[1],h=t[2],p=t[3],f=t[4],v=t[5],y=t[6],g=t[7],m=i,w=r[0],b=r[1],_=r[2],S=a,P=s,E=l,A=c,k=u,x=d,T=h,I=p,C=f,B=v,N=y,D=g,G=m,R=w,O=b,L=_,M=0;M<o;M+=2)G=ek(G^(S=S+k|0),16),k=ek(k^(C=C+G|0),12),G=ek(G^(S=S+k|0),8),k=ek(k^(C=C+G|0),7),R=ek(R^(P=P+x|0),16),x=ek(x^(B=B+R|0),12),R=ek(R^(P=P+x|0),8),x=ek(x^(B=B+R|0),7),O=ek(O^(E=E+T|0),16),T=ek(T^(N=N+O|0),12),O=ek(O^(E=E+T|0),8),T=ek(T^(N=N+O|0),7),L=ek(L^(A=A+I|0),16),I=ek(I^(D=D+L|0),12),L=ek(L^(A=A+I|0),8),I=ek(I^(D=D+L|0),7),L=ek(L^(S=S+x|0),16),x=ek(x^(N=N+L|0),12),L=ek(L^(S=S+x|0),8),x=ek(x^(N=N+L|0),7),G=ek(G^(P=P+T|0),16),T=ek(T^(D=D+G|0),12),G=ek(G^(P=P+T|0),8),T=ek(T^(D=D+G|0),7),R=ek(R^(E=E+I|0),16),I=ek(I^(C=C+R|0),12),R=ek(R^(E=E+I|0),8),I=ek(I^(C=C+R|0),7),O=ek(O^(A=A+k|0),16),k=ek(k^(B=B+O|0),12),O=ek(O^(A=A+k|0),8),k=ek(k^(B=B+O|0),7);var j=0;n[j++]=a+S|0,n[j++]=s+P|0,n[j++]=l+E|0,n[j++]=c+A|0,n[j++]=u+k|0,n[j++]=d+x|0,n[j++]=h+T|0,n[j++]=p+I|0,n[j++]=f+C|0,n[j++]=v+B|0,n[j++]=y+N|0,n[j++]=g+D|0,n[j++]=m+G|0,n[j++]=w+R|0,n[j++]=b+O|0,n[j++]=_+L|0}var hk=ik(dk,{counterRight:!1,counterLength:4,allowShortKeys:!1}),pk=new Uint8Array(16),fk=(e,t)=>{e.update(t);var r=t.length%16;r&&e.update(pk.subarray(r))},vk=new Uint8Array(32);function yk(e,t,r,n,i){var o=e(t,r,vk),a=uk.create(o);i&&fk(a,i),fk(a,n);var s=WA(n.length,i?i.length:0,!0);a.update(s);var l=a.digest();return UA(o,s),l}var gk,mk=qA({blockSize:64,nonceLength:12,tagLength:16},(gk=hk,(e,t,r)=>{var n=16;return{encrypt(i,o){var a=i.length;(o=HA(a+n,o,!1)).set(i);var s=o.subarray(0,-16);gk(e,t,s,s,1);var l=yk(gk,e,t,s,r);return o.set(l,a),UA(l),o},decrypt(i,o){o=HA(i.length-n,o,!1);var a=i.subarray(0,-16),s=i.subarray(-16),l=yk(gk,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)),gk(e,t,o,o,1),UA(l),o}}}));var wk=Uint8Array.from([0]),bk=Uint8Array.of();var _k={hashSHA256:e=>wo(e.subarray()),getHKDF(e,t){var r=function(e,t,r){return lr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),mn(e,Br(r),Br(t))}(wo,t,e),n=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:32;lr(e),ar(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=bk);for(var a=new Uint8Array(o*i),s=mn.create(e,t),l=s._cloneInto(),c=new Uint8Array(s.outputLen),u=0;u<o;u++)wk[0]=u+1,l.update(0===u?bk:c).update(r).update(wk).digestInto(c),a.set(c,i*u),s._cloneInto(l);return s.destroy(),l.destroy(),dr(c,wk),a.slice(0,n)}(wo,r,void 0,96),i=n;return[i.subarray(0,32),i.subarray(32,64),i.subarray(64,96)]},generateX25519KeyPair(){var e=mo.utils.randomPrivateKey();return{publicKey:mo.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:mo.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>mo.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>mk(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,i)=>mk(n,t,r).decrypt(e.subarray(),i)},Sk=_k;var Pk=e=>{var t=Ke(2);return t[0]=e>>8,t[1]=e,t};Pk.bytes=2;var Ek=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 Ak(e,t){t.enabled&&GA&&(e?(t("LOCAL_STATIC_PUBLIC_KEY ".concat(Ze(e.publicKey,"hex"))),t("LOCAL_STATIC_PRIVATE_KEY ".concat(Ze(e.privateKey,"hex")))):t("Missing local static keys."))}function kk(e,t){t.enabled&&GA&&(e?(t("LOCAL_PUBLIC_EPHEMERAL_KEY ".concat(Ze(e.publicKey,"hex"))),t("LOCAL_PRIVATE_EPHEMERAL_KEY ".concat(Ze(e.privateKey,"hex")))):t("Missing local ephemeral keys."))}function xk(e,t){t.enabled&&GA&&t(e?"REMOTE_EPHEMERAL_PUBLIC_KEY ".concat(Ze(e.subarray(),"hex")):"Missing remote ephemeral keys.")}function Tk(e,t,r){r.enabled&&GA&&(r("CIPHER_STATE_1 ".concat(e.n.getUint64()," ").concat(e.k&&Ze(e.k,"hex"))),r("CIPHER_STATE_2 ".concat(t.n.getUint64()," ").concat(t.k&&Ze(t.k,"hex"))))}function Ik(e,t){if(e.length!==t.length)throw new Error("Inputs should have the same length");for(var r=Ke(e.length),n=0;n<e.length;n++)r[n]=e[n]^t[n];return r}Ek.bytes=2;class Ck extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid crypto exchange"),e._defineProperty(this,"code",void 0),this.code=Ck.code}}e._defineProperty(Ck,"code","ERR_INVALID_CRYPTO_EXCHANGE");class Bk{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;e._defineProperty(this,"n",void 0),e._defineProperty(this,"bytes",void 0),e._defineProperty(this,"view",void 0),this.n=t,this.bytes=He(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 Nk,Dk,Gk=He(0);class Rk{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._defineProperty(this,"k",void 0),e._defineProperty(this,"n",void 0),e._defineProperty(this,"crypto",void 0),this.crypto=t,this.k=r,this.n=new Bk(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 Ok{constructor(t,r){e._defineProperty(this,"cs",void 0),e._defineProperty(this,"ck",void 0),e._defineProperty(this,"h",void 0),e._defineProperty(this,"crypto",void 0),this.crypto=t;var n=nt(r,"utf-8");this.h=function(e,t){if(t.length<=32){var r=He(32);return r.set(t),r}return e.hash(t)}(t,n),this.ck=this.h,this.cs=new Rk(t)}mixKey(e){var[t,r]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new Rk(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new Oa(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,Gk);return[new Rk(this.crypto,e),new Rk(this.crypto,t)]}}class Lk{constructor(t){e._defineProperty(this,"ss",void 0),e._defineProperty(this,"s",void 0),e._defineProperty(this,"e",void 0),e._defineProperty(this,"rs",void 0),e._defineProperty(this,"re",void 0),e._defineProperty(this,"initiator",void 0),e._defineProperty(this,"crypto",void 0);var{crypto:r,protocolName:n,prologue:i,initiator:o,s:a,e:s,rs:l,re:c}=t;this.crypto=r,this.ss=new Ok(r,n),this.ss.mixHash(i),this.initiator=o,this.s=a,this.e=s,this.rs=l,this.re=c}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 Mk extends Lk{writeMessageA(e){return new Oa(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){var t=this.writeE();this.writeEE();var r=this.writeS();return this.writeES(),new Oa(t,r,this.ss.encryptAndHash(e))}writeMessageC(e){var t=this.writeS();return this.writeSE(),new Oa(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(e){throw new Ck("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 Ck("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 Ck("handshake stage 2 validation fail: ".concat(e.message))}}}function jk(e,t,r){return Fk.apply(this,arguments)}function Fk(){return(Fk=e._asyncToGenerator((function*(e,t,r){var n=yield e.sign(Vk(t));return Dk.encode({identityKey:Fl(e.publicKey),identitySig:n,extensions:r})}))).apply(this,arguments)}function Uk(e,t,r){return zk.apply(this,arguments)}function zk(){return zk=e._asyncToGenerator((function*(e,t,r){try{var n=Dk.decode(e),i=Ml(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=Vk(t);if(!(yield i.verify(o,n.identitySig)))throw new Error("Invalid payload signature");return n}catch(e){throw new Qo(e.message)}})),zk.apply(this,arguments)}function Vk(e){var t=nt("noise-libp2p-static-key:");return e instanceof Uint8Array?mt([t,e],t.length+e.length):(e.prepend(t),e)}function qk(){return qk=e._asyncToGenerator((function*(e,t){var{log:r,connection:n,crypto:i,privateKey:o,prologue:a,s:s,remoteIdentityKey:l,extensions:c}=e,u=yield jk(o,s.publicKey,c),d=new Mk({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:a,s:s});Ak(d.s,r),r.trace("Stage 0 - Initiator starting to send first message."),yield n.write(d.writeMessageA(Gk),t),r.trace("Stage 0 - Initiator finished sending first message."),kk(d.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");var h,p,f=d.readMessageB(yield n.read(t));r.trace("Stage 1 - Initiator received the message."),xk(d.re,r),h=d.rs,(p=r).enabled&&GA&&p(h?"REMOTE_STATIC_PUBLIC_KEY ".concat(Ze(h.subarray(),"hex")):"Missing remote static public key."),r.trace("Initiator going to check remote's signature...");var v=yield Uk(f,d.rs,l);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),yield n.write(d.writeMessageC(u),t),r.trace("Stage 2 - Initiator sent message with signed payload.");var[y,g]=d.ss.split();return Tk(y,g,r),{payload:v,encrypt:e=>y.encryptWithAd(Gk,e),decrypt:(e,t)=>g.decryptWithAd(Gk,e,t)}})),qk.apply(this,arguments)}function Hk(){return Hk=e._asyncToGenerator((function*(e,t){var{log:r,connection:n,crypto:i,privateKey:o,prologue:a,s:s,remoteIdentityKey:l,extensions:c}=e,u=yield jk(o,s.publicKey,c),d=new Mk({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:a,s:s});Ak(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."),xk(d.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),yield n.write(d.writeMessageB(u),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),kk(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 p=yield Uk(h,d.rs,l),[f,v]=d.ss.split();return Tk(f,v,r),{payload:p,encrypt:e=>v.encryptWithAd(Gk,e),decrypt:(e,t)=>f.decryptWithAd(Gk,e,t)}})),Hk.apply(this,arguments)}!function(e){var t;e.codec=()=>(null==t&&(t=ul((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 dl('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 dl('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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(Nk||(Nk={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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),Nk.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:He(0),identitySig:He(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=Nk.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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(Dk||(Dk={}));class Kk{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"protocol","/noise"),e._defineProperty(this,"crypto",void 0),e._defineProperty(this,"prologue",void 0),e._defineProperty(this,"staticKey",void 0),e._defineProperty(this,"extensions",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,Symbol.toStringTag,"@chainsafe/libp2p-noise"),e._defineProperty(this,Ba,["@libp2p/connection-encryption","@chainsafe/libp2p-noise"]);var{staticNoiseKey:n,extensions:i,crypto:o,prologueBytes:a}=r,{metrics:s}=t;this.components=t;var l=null!=o?o:Sk;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}}(l),this.extensions=e._objectSpread2({webtransportCerthashes:[]},i),this.metrics=s?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"})}}(s):void 0,this.staticKey=n?l.generateX25519KeyPairFromSeed(n):l.generateX25519KeyPair(),this.prologue=null!=a?a:He(0)}secureOutbound(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i,o=zu(t,{lengthEncoder:Pk,lengthDecoder:Ek,maxDataLength:DA}),a=yield n.performHandshakeInitiator(o,n.components.privateKey,null==r||null===(e=r.remotePeer)||void 0===e?void 0:e.publicKey,r),s=yield n.createSecureConnection(o,a);t.source=s.source,t.sink=s.sink;var l=Ml(a.payload.identityKey);return{conn:t,remoteExtensions:a.payload.extensions,remotePeer:Xl(l),streamMuxer:!0===(null==r?void 0:r.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 Yo("Early muxer negotiation was requested but the initiator and responder had no common muxers")}}secureInbound(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i,o=zu(t,{lengthEncoder:Pk,lengthDecoder:Ek,maxDataLength:DA}),a=yield n.performHandshakeResponder(o,n.components.privateKey,null==r||null===(e=r.remotePeer)||void 0===e?void 0:e.publicKey,r),s=yield n.createSecureConnection(o,a);t.source=s.source,t.sink=s.sink;var l=Ml(a.payload.identityKey);return{conn:t,remoteExtensions:a.payload.extensions,remotePeer:Xl(l),streamMuxer:!0===(null==r?void 0:r.skipStreamMuxerNegotiation)?void 0:n.getStreamMuxer(null===(i=a.payload.extensions)||void 0===i?void 0:i.streamMuxers)}}))()}performHandshakeInitiator(t,r,n,i){var o=this;return e._asyncToGenerator((function*(){var a,s=!0===(null==i?void 0:i.skipStreamMuxerNegotiation)?[]:[...o.components.upgrader.getStreamMuxers().keys()];try{var l;a=yield function(e,t){return qk.apply(this,arguments)}({connection:t,privateKey:r,remoteIdentityKey:n,log:o.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:o.crypto,prologue:o.prologue,s:o.staticKey,extensions:e._objectSpread2({streamMuxers:s,webtransportCerthashes:[]},o.extensions)},i),null===(l=o.metrics)||void 0===l||l.xxHandshakeSuccesses.increment()}catch(e){var c;throw null===(c=o.metrics)||void 0===c||c.xxHandshakeErrors.increment(),e}return a}))()}performHandshakeResponder(t,r,n,i){var o=this;return e._asyncToGenerator((function*(){var a,s=!0===(null==i?void 0:i.skipStreamMuxerNegotiation)?[]:[...o.components.upgrader.getStreamMuxers().keys()];try{var l;a=yield function(e,t){return Hk.apply(this,arguments)}({connection:t,privateKey:r,remoteIdentityKey:n,log:o.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:o.crypto,prologue:o.prologue,s:o.staticKey,extensions:e._objectSpread2({streamMuxers:s,webtransportCerthashes:[]},o.extensions)},i),null===(l=o.metrics)||void 0===l||l.xxHandshakeSuccesses.increment()}catch(e){var c;throw null===(c=o.metrics)||void 0===c||c.xxHandshakeErrors.increment(),e}return a}))()}createSecureConnection(t,r){var n=this;return e._asyncToGenerator((function*(){var i,o,[a,s]=(i=NA(),o=NA(),[{source:i.source,sink:o.sink},{source:o.source,sink:i.sink}]),l=t.unwrap();return yield iu(a,function(t,r){return function(){var n=e._wrapAsyncGenerator((function*(n){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(n);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1)for(var c=s.value,u=0;u<c.length;u+=65519){var d=u+65519;d>c.length&&(d=c.length);var h=void 0;h=c instanceof Uint8Array?t.encrypt(c.subarray(u,d)):t.encrypt(c.sublist(u,d)),null==r||r.encryptedPackets.increment(),yield new Oa(Pk(h.byteLength),h)}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}));return function(e){return n.apply(this,arguments)}}()}(r,n.metrics),l,(e=>Up(e,{lengthDecoder:Ek})),function(t,r){return function(){var n=e._wrapAsyncGenerator((function*(n){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(n);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1)for(var c=s.value,u=0;u<c.length;u+=DA){var d=u+DA;if(d>c.length&&(d=c.length),d-16<u)throw new Error("Invalid chunk");var h=c.sublist(u,d),p=c.subarray(u,d-16);try{var f=t.decrypt(h,p);null==r||r.decryptedPackets.increment(),yield f}catch(e){throw null==r||r.decryptErrors.increment(),e}}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}));return function(e){return n.apply(this,arguments)}}()}(r,n.metrics),a),s}))()}}function Wk(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new Kk(t,e)}var Qk=Object.values(qe).map((e=>e.decoder)).reduce(((e,t)=>e.or(t))),Yk=e._wrapRegExp(/^a=fingerprint:(?:\w+-[0-9]+)\s((:?[0-9a-fA-F]{2})+)$/m,{fingerprint:1});function Jk(e){var t=e.stringTuples().filter((e=>466===e[0])).map((e=>e[1]))[0];if(void 0===t||""===t)throw new Jo("Couldn't find a certhash component of multiaddr: ".concat(e.toString()));return t}function Zk(e){var t=function(e){return Ae(Qk.decode(e))}(Jk(e)),r=function(e){switch(e){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new rf(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 ef(n,e.toString());return"".concat(r," ").concat(i.join(":").toUpperCase())}function $k(e,t){if(void 0===e.sdp)throw new Jo("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 Xk=nt("libp2p-webrtc-noise:");var ex=bp?"iceconnectionstatechange":"connectionstatechange";function tx(){return tx=e._asyncToGenerator((function*(t,r,n){var i=t.createDataChannel("",{negotiated:!0,id:0});try{var o,a,s;if("client"===n.role){n.log.trace("client creating local offer");var l=yield t.createOffer();n.log.trace("client created local offer %s",l.sdp);var c=$k(l,r);n.log.trace("client setting local offer %s",c.sdp),yield t.setLocalDescription(c);var u=function(e,t){var{host:r,port:n,family:i}=e.toOptions(),o=Zk(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(ep,"\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",u.sdp),yield t.setRemoteDescription(u)}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(ep,"\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 t.setRemoteDescription(d),n.log.trace("server creating local answer");var h=yield t.createAnswer();n.log.trace("server created local answer");var p=$k(h,r);n.log.trace("server setting local description %s",h.sdp),yield t.setLocalDescription(p)}if("open"!==i.readyState&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,i.readyState),yield xh(i,"open",n.signal)),n.log.trace("%s handshake channel opened",n.role),"server"===n.role){var f,v,y=null!==(f=null===(v=t.remoteFingerprint())||void 0===v?void 0:v.value)&&void 0!==f?f:"";n.remoteAddr=n.remoteAddr.encapsulate(function(e){var t=e.split(":").map((e=>parseInt(e,16))),r=Uint8Array.from(t),n=Ee(De.code,r);return nr("/certhash/".concat(q.encode(n.bytes)))}(y))}var g=function(e){var t;if(null!=e){var r=e.match(Yk);return null==r||null===(t=r.groups)||void 0===t?void 0:t.fingerprint}}(null===(o=t.localDescription)||void 0===o?void 0:o.sdp);if(null==g)throw new $p("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=nt(e.trim().toLowerCase().replaceAll(":",""),"hex"),i=Ee(De.code,n),o=Qk.decode(Jk(t)),a=Xk.byteLength+i.bytes.byteLength+o.byteLength;return mt("server"===r?[Xk,o,i.bytes]:[Xk,i.bytes,o],a)}(g,n.remoteAddr,n.role),w=Wk({prologueBytes:m})(n),b=Vp(e._objectSpread2({channel:i,direction:"outbound",handshake:!0,logger:n.logger},null!==(a=n.dataChannel)&&void 0!==a?a:{})),_=new Ap(n,{peerConnection:t,remoteAddr:n.remoteAddr,timeline:{open:Date.now()},metrics:n.events});t.addEventListener(ex,(()=>{switch(t.connectionState){case"failed":case"disconnected":case"closed":_.close().catch((e=>{n.log.error("error closing connection",e),_.abort(e)}))}})),null===(s=n.events)||void 0===s||s.increment({peer_connection:!0});var S=new qp(n,{peerConnection:t,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(_,{skipProtection:!0,skipEncryption:!0,muxerFactory:S,signal:n.signal});n.log.trace("%s secure outbound",n.role);var P=yield w.secureOutbound(b,{remotePeer:n.remotePeerId,signal:n.signal,skipStreamMuxerNegotiation:!0});_.remoteAddr=_.remoteAddr.encapsulate("/p2p/".concat(P.remotePeer)),n.log.trace("%s upgrade inbound",n.role),yield n.upgrader.upgradeInbound(_,{skipProtection:!0,skipEncryption:!0,muxerFactory:S,signal:n.signal})}catch(e){throw i.close(),e}})),tx.apply(this,arguments)}function rx(){return(rx=e._asyncToGenerator((function*(t,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(e._objectSpread2(e._objectSpread2({},null!=o?o:{}),{},{certificates:[i]}))}))).apply(this,arguments)}function nx(e){return ix.apply(this,arguments)}function ix(){return(ix=e._asyncToGenerator((function*(e){var t=yield ql(e),r=yield crypto.subtle.exportKey("pkcs8",t.privateKey);return["-----BEGIN PRIVATE KEY-----",...Ze(new Uint8Array(r),"base64pad").split(/(.{64})/).filter(Boolean),"-----END PRIVATE KEY-----"].join("\n")}))).apply(this,arguments)}class ox{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e._defineProperty(this,"log",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"init",void 0),e._defineProperty(this,"certificate",void 0),e._defineProperty(this,"privateKey",void 0),e._defineProperty(this,"emitter",void 0),e._defineProperty(this,"renewCertificateTask",void 0),e._defineProperty(this,Ko,!0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/webrtc-direct"),e._defineProperty(this,Ba,["@libp2p/transport"]),this.log=t.logger.forComponent("libp2p:webrtc-direct"),this.components=t,this.init=r,this.emitter=new Aa,null!=r.certificateLifespan&&null!=r.certificateRenewalThreshold&&r.certificateRenewalThreshold>=r.certificateLifespan)throw new Jo("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 t=this;return e._asyncToGenerator((function*(){t.certificate=yield t.getCertificate()}))()}stop(){var t=this;return e._asyncToGenerator((function*(){null!=t.renewCertificateTask&&clearTimeout(t.renewCertificateTask),t.certificate=void 0}))()}dial(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i;n.log("dial %a",t),r.signal.throwIfAborted();var o=t.getPeerId();null!=o&&(i=$l(o));var a=function(){return"libp2p+webrtc+v1/"+[...Array(arguments.length>0&&void 0!==arguments[0]?arguments[0]:32)].map((()=>Xh.at(Math.floor(Math.random()*Xh.length)))).join("")}(),s=yield function(e,t,r,n){return rx.apply(this,arguments)}("client",a,"function"==typeof n.init.rtcConfiguration?yield n.init.rtcConfiguration():null!==(e=n.init.rtcConfiguration)&&void 0!==e?e:{});try{var l;return yield function(e,t,r){return tx.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:r.signal,remoteAddr:t,dataChannel:n.init.dataChannel,upgrader:r.upgrader,peerId:n.components.peerId,remotePeerId:i,privateKey:n.components.privateKey})}catch(e){throw s.close(),e}}))()}createListener(t){if(null==this.certificate)throw new va;return new BA(this.components,e._objectSpread2(e._objectSpread2(e._objectSpread2({},this.init),t),{},{certificate:this.certificate,emitter:this.emitter}))}listenFilter(e){return e.filter(jd.exactMatch)}dialFilter(e){return this.listenFilter(e)}getCertificate(t){var r=this;return e._asyncToGenerator((function*(){if(function(e){if(null==e)return!1;return"string"==typeof e.privateKey&&"string"==typeof e.pem&&"string"==typeof e.certhash}(r.init.certificate))return r.log("using provided TLS certificate"),r.init.certificate;var e=yield r.loadOrCreatePrivateKey(),{pem:n,certhash:i}=yield r.loadOrCreateCertificate(e,t);return{privateKey:yield nx(e),pem:n,certhash:i}}))()}loadOrCreatePrivateKey(){var t=this;return e._asyncToGenerator((function*(){var e;if(null!=t.privateKey)return t.privateKey;var r=null!==(e=t.init.certificateKeychainName)&&void 0!==e?e:"webrtc-direct-certificate-private-key",n=t.getKeychain();try{if(null==n)throw t.log("no keychain configured - not checking for stored private key"),new aa;t.log.trace("checking for stored private key"),t.privateKey=yield n.exportKey(r)}catch(e){if("NotFoundError"!==e.name)throw e;t.log.trace("generating private key"),t.privateKey=yield Ol("ECDSA","P-256"),null!=n?(t.log.trace("storing private key"),yield n.importKey(r,t.privateKey)):t.log("no keychain configured - not storing private key")}return t.privateKey}))()}loadOrCreateCertificate(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i,o;if(null!=n.certificate&&!0!==r)return n.certificate;var a=new xc(null!==(e=n.init.certificateDatastoreKey)&&void 0!==e?e:"/libp2p/webrtc-direct/certificate"),s=yield ql(t);try{if(!0===r)throw n.log.trace("forcing renewal of TLS certificate"),new aa;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:ip)-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:q.encode((yield De.digest(new Uint8Array(o.rawData))).bytes)}}))()}loadCertificate(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i=yield n.components.datastore.get(t),o=new IA(i),a=o.notAfter.getTime()-(null!==(e=n.init.certificateRenewalThreshold)&&void 0!==e?e:ip);if(Date.now()>a)throw n.log("stored TLS certificate has expired"),new aa;n.log("loaded certificate, expires in %d ms",a);var s=yield o.publicKey.export(crypto),l=yield crypto.subtle.exportKey("raw",s),c=yield crypto.subtle.exportKey("raw",r.publicKey);if(!rt(new Uint8Array(l,0,l.byteLength),new Uint8Array(c,0,c.byteLength)))throw n.log("stored TLS certificate public key did not match public key from private key"),new aa;return n.log("loaded certificate, expiry time is %o",a),o}))()}createCertificate(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i=new Date,o=new Date(Date.now()+(null!==(e=n.init.certificateLifespan)&&void 0!==e?e:12096e5));i.setMilliseconds(0),o.setMilliseconds(0);var a=yield CA.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:r,extensions:[new rA(!1,void 0,!0)]},crypto);return null!=n.getKeychain()?(n.log.trace("storing TLS certificate"),yield n.components.datastore.put(t,nt(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 ax(e){return t=>new ox(t,e)}function sx(e){return t=>new uf(t,e)}var lx,cx,ux,dx,hx,px,fx,vx,yx,gx="/ipfs/bitswap/1.2.0",mx=4194304,wx=mx;!function(e){e.WantBlock="WantBlock",e.WantHave="WantHave"}(lx||(lx={})),function(e){e[e.WantBlock=0]="WantBlock",e[e.WantHave=1]="WantHave"}(cx||(cx={})),function(e){e.codec=()=>cl(cx)}(lx||(lx={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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),lx.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:He(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=lx.codec().decode(e);break;case 5:r.sendDontHave=e.bool();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(ux||(ux={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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),ux.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 dl('Decode error - map field "entries" had too many elements');n.entries.push(ux.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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(dx||(dx={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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:He(0),data:He(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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(hx||(hx={})),function(e){e.HaveBlock="HaveBlock",e.DoNotHaveBlock="DoNotHaveBlock"}(px||(px={})),function(e){e[e.HaveBlock=0]="HaveBlock",e[e.DoNotHaveBlock=1]="DoNotHaveBlock"}(fx||(fx={})),function(e){e.codec=()=>cl(fx)}(px||(px={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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!==fx[e.type]&&(t.uint32(16),px.codec().encode(e.type,t)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={cid:He(0),type:px.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=px.codec().decode(e);break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(vx||(vx={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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),dx.codec().encode(e.wantlist,t)),null!=e.blocks)for(var n of e.blocks)t.uint32(26),hx.codec().encode(n,t);if(null!=e.blockPresences)for(var i of e.blockPresences)t.uint32(34),vx.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=dx.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 dl('Decode error - map field "blocks" had too many elements');n.blocks.push(hx.codec().decode(e,e.uint32(),{limits:null===(l=r.limits)||void 0===l?void 0:l.blocks$}));break;case 4:var c,u;if(null!=(null===(c=r.limits)||void 0===c?void 0:c.blockPresences)&&n.blockPresences.length===r.limits.blockPresences)throw new dl('Decode error - map field "blockPresences" had too many elements');n.blockPresences.push(vx.codec().decode(e,e.uint32(),{limits:null===(u=r.limits)||void 0===u?void 0:u.blockPresences$}));break;case 5:n.pendingBytes=e.int32();break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(yx||(yx={}));class bx extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Block too large"),this.name="BlockTooLargeError"}}e._defineProperty(bx,"name","BlockTooLargeError");function _x(e,t,r,n,i,o){for(var a=0,s=!1,l=r;l<e.length;l++){var c=e[l],u=o(c);if(u>4193664)throw new bx("Cannot send block as after encoding it is over the max message size");var d=i+u;if(d>n){s=!0;break}t.push(c),a++,i=d}return{hasMore:s,added:a,newSize:i}}function Sx(e){return Ax(3,hx.encode(e))}function Px(e){return Ax(4,vx.encode(e))}function Ex(e){return Ax(1,ux.encode(e))}function Ax(e,t){return pt(e)+pt(t.byteLength)+t.byteLength}let kx=class extends Aa{constructor(t){var r,n,i,o,a,s,l,c,u,d,h,p=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),e._defineProperty(this,"log",void 0),e._defineProperty(this,"libp2p",void 0),e._defineProperty(this,"routing",void 0),e._defineProperty(this,"protocols",void 0),e._defineProperty(this,"running",void 0),e._defineProperty(this,"maxInboundStreams",void 0),e._defineProperty(this,"maxOutboundStreams",void 0),e._defineProperty(this,"messageReceiveTimeout",void 0),e._defineProperty(this,"registrarIds",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"sendQueue",void 0),e._defineProperty(this,"runOnLimitedConnections",void 0),e._defineProperty(this,"maxOutgoingMessageSize",void 0),e._defineProperty(this,"maxIncomingMessageSize",void 0),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=null!==(r=p.protocols)&&void 0!==r?r:[gx],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=null!==(n=p.maxInboundStreams)&&void 0!==n?n:1024,this.maxOutboundStreams=null!==(i=p.maxOutboundStreams)&&void 0!==i?i:1024,this.messageReceiveTimeout=null!==(o=p.messageReceiveTimeout)&&void 0!==o?o:5e3,this.runOnLimitedConnections=null!==(a=p.runOnLimitedConnections)&&void 0!==a&&a,this.maxIncomingMessageSize=null!==(s=p.maxIncomingMessageSize)&&void 0!==s?s:mx,this.maxOutgoingMessageSize=null!==(l=null!==(c=p.maxOutgoingMessageSize)&&void 0!==c?c:p.maxIncomingMessageSize)&&void 0!==l?l:wx,this.metrics={blocksSent:null===(u=t.metrics)||void 0===u?void 0:u.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 Rh({concurrency:null!==(h=p.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 t=this;return e._asyncToGenerator((function*(){if(!t.running){t.running=!0,yield t.libp2p.handle(t.protocols,t._onStream,{maxInboundStreams:t.maxInboundStreams,maxOutboundStreams:t.maxOutboundStreams,runOnLimitedConnection:t.runOnLimitedConnections});var e={onConnect:e=>{t.safeDispatchEvent("peer:connected",{detail:e})},onDisconnect:e=>{t.safeDispatchEvent("peer:disconnected",{detail:e})}};for(var r of(t.registrarIds=[],t.protocols))t.registrarIds.push(yield t.libp2p.register(r,e));t.libp2p.getConnections().forEach((e=>{t.safeDispatchEvent("peer:connected",{detail:e.remotePeer})}))}}))()}stop(){var t=this;return e._asyncToGenerator((function*(){if(t.running=!1,yield t.libp2p.unhandle(t.protocols),null!=t.registrarIds){for(var e of t.registrarIds)t.libp2p.unregister(e);t.registrarIds=[]}}))()}_onStream(t){var r=this;if(this.running){var{stream:n,connection:i}=t;Promise.resolve().then(e._asyncToGenerator((function*(){r.log("incoming new bitswap %s stream from %p",n.protocol,i.remotePeer);var t=()=>{"open"===n.status?n.abort(new fa("Incoming Bitswap stream timed out after ".concat(r.messageReceiveTimeout,"ms"))):r.log("stream aborted with status %s",n.status)},o=AbortSignal.timeout(r.messageReceiveTimeout);o.addEventListener("abort",t),yield n.closeWrite(),yield iu(n,(e=>Up(e,{maxDataLength:r.maxIncomingMessageSize})),function(){var a=e._asyncToGenerator((function*(a){var s,l=!1,c=!1;try{for(var u,d=e._asyncIterator(a);l=!(u=yield d.next()).done;l=!1){var h=u.value;try{var p=yx.decode(h);r.log("incoming new bitswap %s message from %p on stream",n.protocol,i.remotePeer,n.id),r.safeDispatchEvent("bitswap:message",{detail:{peer:i.remotePeer,message:p}}),o.removeEventListener("abort",t),(o=AbortSignal.timeout(r.messageReceiveTimeout)).addEventListener("abort",t)}catch(e){r.log.error("error reading incoming bitswap message from %p on stream",i.remotePeer,n.id,e),n.abort(e);break}}}catch(e){c=!0,s=e}finally{try{l&&null!=d.return&&(yield d.return())}finally{if(c)throw s}}}));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(t,r){var n=this;return e._wrapAsyncGenerator((function*(){var i;null==r||null===(i=r.onProgress)||void 0===i||i.call(r,new Ah("bitswap:network:find-providers",t));var o,a=!1,s=!1;try{for(var l,c=e._asyncIterator(n.routing.findProviders(t,r));a=!(l=yield e._awaitAsyncGenerator(c.next())).done;a=!1){var u=l.value;(yield e._awaitAsyncGenerator(n.libp2p.isDialable(u.multiaddrs,{runOnLimitedConnection:n.runOnLimitedConnections})))&&(yield u)}}catch(e){s=!0,o=e}finally{try{a&&null!=c.return&&(yield e._awaitAsyncGenerator(c.return()))}finally{if(s)throw o}}}))()}findAndConnect(t,r){var n=this;return e._asyncToGenerator((function*(){var i;null!=(null==r?void 0:r.providers)&&(yield Promise.all(r.providers.map(function(){var t=e._asyncToGenerator((function*(e){return n.connectTo(e).catch((e=>{n.log.error("could not connect to supplied provider - %e",e)}))}));return function(e){return t.apply(this,arguments)}}()))),yield Tc(qc(Dc(n.findProviders(t,r),null!==(i=null==r?void 0:r.maxProviders)&&void 0!==i?i:3),function(){var t=e._asyncToGenerator((function*(e){return n.connectTo(e.id,r)}));return function(e){return t.apply(this,arguments)}}())).catch((e=>{n.log.error(e)}))}))()}sendMessage(t,r,n){var i=this;return e._asyncToGenerator((function*(){if(!i.running)throw new Error("network isn't running");var o=i.sendQueue.queue.find((e=>t.equals(e.options.peerId)&&"queued"===e.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,c]of t.blockPresences.entries())e.blockPresences.set(l,c);for(var[u,d]of t.blocks.entries())e.blocks.set(u,d);return t.full&&!e.full&&(e.full=!0),e}(o.options.message,r),void(yield o.join({signal:null==n?void 0:n.signal}));yield i.sendQueue.add(function(){var r=e._asyncToGenerator((function*(e){var r,n=null==e?void 0:e.message;if(null==n)throw new Jo("No message to send");i.log("sendMessage to %p",t),null==e||null===(r=e.onProgress)||void 0===r||r.call(e,new Ah("bitswap:network:send-wantlist",t));var o=yield i.libp2p.dialProtocol(t,gx,e);yield o.closeRead();try{yield iu(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 c,u={wantlist:{full:null!==(c=e.full)&&void 0!==c&&c,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},d=yx.encode(u).byteLength,{added:h,hasMore:p,newSize:f}=_x(i,u.blocks,s,t,d,Sx);s+=h,d=f;var v=p;({added:h,hasMore:p,newSize:f}=_x(n,u.blockPresences,a,t,d,Px)),a+=h,d=f;var y=p;if(({added:h,hasMore:p,newSize:f}=_x(r,u.wantlist.entries,o,t,d,Ex)),o+=h,d=f,(l=!v&&!y&&!p)||(u.wantlist.full=!1),yield yx.encode(u),l)break}}(n,i.maxOutgoingMessageSize),(e=>jp(e)),o),yield o.close(e)}catch(r){var a;null==e||null===(a=e.onProgress)||void 0===a||a.call(e,new Ah("bitswap:network:send-wantlist:error",{peer:t,error:r})),i.log.error("error sending message to %p",t,r),o.abort(r)}i._updateSentStats(n.blocks)}));return function(e){return r.apply(this,arguments)}}(),{peerId:t,signal:null==n?void 0:n.signal,message:r})}))()}connectTo(t,r){var n=this;return e._asyncToGenerator((function*(){var e;if(!n.running)throw new va("Network isn't running");null==r||null===(e=r.onProgress)||void 0===e||e.call(r,new Ah("bitswap:network:dial",t));var[i]=yield Promise.all([n.libp2p.dial(t,r),xh(n.libp2p,"peer:identify",null==r?void 0:r.signal,{filter:e=>{if(!e.detail.peerId.equals(t))return!1;if(e.detail.protocols.includes(gx))return!0;throw new da("".concat(t," did not support ").concat(gx))}})]);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 xx{constructor(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];e._defineProperty(this,"full",void 0),e._defineProperty(this,"pendingBytes",void 0),e._defineProperty(this,"wantlist",void 0),e._defineProperty(this,"blocks",void 0),e._defineProperty(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=z.encode(e.multihash.bytes);this.wantlist.set(r,t)}addBlockPresence(e,t){var r=z.encode(e.multihash.bytes);this.blockPresences.set(r,t)}addBlock(e,t){var r=z.encode(e.multihash.bytes);this.blocks.set(r,t)}}function Tx(e){return function(e){var t=new Uint8Array(e.reduce(((e,t)=>e+pt(t)),0)),r=0;for(var n of e)t=yt(n,t,r),r+=pt(n);return t}([e.version,e.code,e.multihash.code,e.multihash.digest.byteLength])}class Ix{constructor(t,r){var n;e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"blockstore",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"wants",void 0),e._defineProperty(this,"exchangeCount",void 0),e._defineProperty(this,"bytesSent",void 0),e._defineProperty(this,"bytesReceived",void 0),e._defineProperty(this,"lastExchange",void 0),e._defineProperty(this,"maxSizeReplaceHasWithBlock",void 0),e._defineProperty(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(t){var r=this;return e._asyncToGenerator((function*(){var e=new xx,n=new Set;for(var[i,o]of r.wants.entries())try{var a=yield r.blockstore.get(o.cid,t);o.wantType===lx.WantHave?a.byteLength<r.maxSizeReplaceHasWithBlock?(r.log("sending have and block for %c",o.cid),n.add(i),e.addBlock(o.cid,{data:a,prefix:Tx(o.cid)})):(r.log("sending have for %c",o.cid),e.addBlockPresence(o.cid,{cid:o.cid.bytes,type:px.HaveBlock})):(r.log("sending block for %c",o.cid),n.add(i),e.addBlock(o.cid,{data:a,prefix:Tx(o.cid)}))}catch(t){if("NotFoundError"!==t.name)throw t;if(r.log("do not have block for %c",o.cid),!o.sendDontHave)continue;if(!0===o.sentDoNotHave)continue;o.sentDoNotHave=!0,e.addBlockPresence(o.cid,{cid:o.cid.bytes,type:px.DoNotHaveBlock})}if(e.blocks.size>0||e.blockPresences.size>0)for(var s of(r.log("sending message"),yield r.network.sendMessage(r.peerId,e,t),r.log("sent message"),r.sentBytes([...e.blocks.values()].reduce(((e,t)=>e+t.data.byteLength),0)),n))r.wants.delete(s)}))()}}class Cx{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"blockstore",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"ledgerMap",void 0),e._defineProperty(this,"maxSizeReplaceHasWithBlock",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(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=_h({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(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i,o=n.ledgerMap.get(t);if(null==o&&(o=new Ix({peerId:t,blockstore:n.blockstore,network:n.network,logger:n.logger},{maxSizeReplaceHasWithBlock:n.maxSizeReplaceHasWithBlock}),n.ledgerMap.set(t,o)),o.receivedBytes(null!==(e=null===(i=r.blocks)||void 0===i?void 0:i.reduce(((e,t)=>e+t.data.byteLength),0))&&void 0!==e?e:0),null!=r.wantlist)for(var a of(!0===r.wantlist.full&&o.wants.clear(),r.wantlist.entries)){var s,l,c=je.decode(a.cid),u=Ze(c.multihash.bytes,"base64");if(!0===a.cancel)n.log("peer %p cancelled want of block for %c",t,c),o.wants.delete(u);else a.wantType===lx.WantHave?n.log("peer %p wanted block presence for %c",t,c):n.log("peer %p wanted block for %c",t,c),o.wants.set(u,{cid:c,priority:a.priority,wantType:null!==(s=a.wantType)&&void 0!==s?s:lx.WantBlock,sendDontHave:null!==(l=a.sendDontHave)&&void 0!==l&&l})}n.log("send blocks to peer"),yield o.sendBlocksToPeer()}))()}receivedBlock(t,r){var n=this;return e._asyncToGenerator((function*(){var i=Ze(t.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 t=e._asyncToGenerator((function*(e){return e.sendBlocksToPeer(r)}));return function(e){return t.apply(this,arguments)}}()))}))()}peerDisconnected(e){this.ledgerMap.delete(e)}}var Bx=new WeakMap;let Nx=class{constructor(){e._classPrivateFieldInitSpec(this,Bx,[])}enqueue(t,r){var n={priority:(r=e._objectSpread2({priority:0},r)).priority,id:r.id,run:t};if(0===this.size||e._classPrivateFieldGet2(Bx,this)[this.size-1].priority>=r.priority)e._classPrivateFieldGet2(Bx,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}(e._classPrivateFieldGet2(Bx,this),n,((e,t)=>t.priority-e.priority));e._classPrivateFieldGet2(Bx,this).splice(i,0,n)}}setPriority(t,r){var n=e._classPrivateFieldGet2(Bx,this).findIndex((e=>e.id===t));if(-1===n)throw new ReferenceError('No promise function with the id "'.concat(t,'" exists in the queue.'));var[i]=e._classPrivateFieldGet2(Bx,this).splice(n,1);this.enqueue(i.run,{priority:r,id:t})}dequeue(){var t=e._classPrivateFieldGet2(Bx,this).shift();return null==t?void 0:t.run}filter(t){return e._classPrivateFieldGet2(Bx,this).filter((e=>e.priority===t.priority)).map((e=>e.run))}get size(){return e._classPrivateFieldGet2(Bx,this).length}};var Dx=new WeakMap,Gx=new WeakMap,Rx=new WeakMap,Ox=new WeakMap,Lx=new WeakMap,Mx=new WeakMap,jx=new WeakMap,Fx=new WeakMap,Ux=new WeakMap,zx=new WeakMap,Vx=new WeakMap,qx=new WeakMap,Hx=new WeakMap,Kx=new WeakMap,Wx=new WeakMap,Qx=new WeakSet;class Yx extends To{constructor(t){var r,n,i,o;if(super(),e._classPrivateMethodInitSpec(this,Qx),e._classPrivateFieldInitSpec(this,Dx,void 0),e._classPrivateFieldInitSpec(this,Gx,void 0),e._classPrivateFieldInitSpec(this,Rx,0),e._classPrivateFieldInitSpec(this,Ox,void 0),e._classPrivateFieldInitSpec(this,Lx,void 0),e._classPrivateFieldInitSpec(this,Mx,0),e._classPrivateFieldInitSpec(this,jx,void 0),e._classPrivateFieldInitSpec(this,Fx,void 0),e._classPrivateFieldInitSpec(this,Ux,void 0),e._classPrivateFieldInitSpec(this,zx,void 0),e._classPrivateFieldInitSpec(this,Vx,0),e._classPrivateFieldInitSpec(this,qx,void 0),e._classPrivateFieldInitSpec(this,Hx,void 0),e._classPrivateFieldInitSpec(this,Kx,void 0),e._classPrivateFieldInitSpec(this,Wx,1n),e._defineProperty(this,"timeout",void 0),!("number"==typeof(t=e._objectSpread2({carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Nx},t)).intervalCap&&t.intervalCap>=1))throw new TypeError("Expected `intervalCap` to be a number from 1 and up, got `".concat(null!==(r=null===(n=t.intervalCap)||void 0===n?void 0:n.toString())&&void 0!==r?r:"","` (").concat(typeof t.intervalCap,")"));if(void 0===t.interval||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError("Expected `interval` to be a finite number >= 0, got `".concat(null!==(i=null===(o=t.interval)||void 0===o?void 0:o.toString())&&void 0!==i?i:"","` (").concat(typeof t.interval,")"));e._classPrivateFieldSet2(Dx,this,t.carryoverConcurrencyCount),e._classPrivateFieldSet2(Gx,this,t.intervalCap===Number.POSITIVE_INFINITY||0===t.interval),e._classPrivateFieldSet2(Ox,this,t.intervalCap),e._classPrivateFieldSet2(Lx,this,t.interval),e._classPrivateFieldSet2(Ux,this,new t.queueClass),e._classPrivateFieldSet2(zx,this,t.queueClass),this.concurrency=t.concurrency,this.timeout=t.timeout,e._classPrivateFieldSet2(Kx,this,!0===t.throwOnTimeout),e._classPrivateFieldSet2(Hx,this,!1===t.autoStart)}get concurrency(){return e._classPrivateFieldGet2(qx,this)}set concurrency(t){if(!("number"==typeof t&&t>=1))throw new TypeError("Expected `concurrency` to be a number from 1 and up, got `".concat(t,"` (").concat(typeof t,")"));e._classPrivateFieldSet2(qx,this,t),e._assertClassBrand(Qx,this,iT).call(this)}setPriority(t,r){e._classPrivateFieldGet2(Ux,this).setPriority(t,r)}add(t){return e._asyncToGenerator((function*(){var r,n,i,o,a=arguments,s=this,l=a.length>1&&void 0!==a[1]?a[1]:{};return null!==(n=(r=l).id)&&void 0!==n||(r.id=(e._classPrivateFieldSet2(Wx,s,(i=e._classPrivateFieldGet2(Wx,s),o=i++,i)),o).toString()),l=e._objectSpread2({timeout:s.timeout,throwOnTimeout:e._classPrivateFieldGet2(Kx,s)},l),new Promise(((r,n)=>{e._classPrivateFieldGet2(Ux,s).enqueue(e._asyncToGenerator((function*(){var i,o;e._classPrivateFieldSet2(Vx,s,(i=e._classPrivateFieldGet2(Vx,s),++i)),e._classPrivateFieldSet2(Rx,s,(o=e._classPrivateFieldGet2(Rx,s),++o));try{var a;null===(a=l.signal)||void 0===a||a.throwIfAborted();var c=t({signal:l.signal});l.timeout&&(c=mp(Promise.resolve(c),{milliseconds:l.timeout})),l.signal&&(c=Promise.race([c,e._assertClassBrand(Qx,s,oT).call(s,l.signal)]));var u=yield c;r(u),s.emit("completed",u)}catch(e){if(e instanceof fp&&!l.throwOnTimeout)return void r();n(e),s.emit("error",e)}finally{e._assertClassBrand(Qx,s,$x).call(s)}})),l),s.emit("add"),e._assertClassBrand(Qx,s,tT).call(s)}))}))()}addAll(t,r){var n=this;return e._asyncToGenerator((function*(){return Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){return n.add(e,r)}));return function(e){return t.apply(this,arguments)}}()))}))()}start(){return e._classPrivateFieldGet2(Hx,this)?(e._classPrivateFieldSet2(Hx,this,!1),e._assertClassBrand(Qx,this,iT).call(this),this):this}pause(){e._classPrivateFieldSet2(Hx,this,!0)}clear(){e._classPrivateFieldSet2(Ux,this,new(e._classPrivateFieldGet2(zx,this)))}onEmpty(){var t=this;return e._asyncToGenerator((function*(){0!==e._classPrivateFieldGet2(Ux,t).size&&(yield e._assertClassBrand(Qx,t,sT).call(t,"empty"))}))()}onSizeLessThan(t){var r=this;return e._asyncToGenerator((function*(){e._classPrivateFieldGet2(Ux,r).size<t||(yield e._assertClassBrand(Qx,r,sT).call(r,"next",(()=>e._classPrivateFieldGet2(Ux,r).size<t)))}))()}onIdle(){var t=this;return e._asyncToGenerator((function*(){0===e._classPrivateFieldGet2(Vx,t)&&0===e._classPrivateFieldGet2(Ux,t).size||(yield e._assertClassBrand(Qx,t,sT).call(t,"idle"))}))()}get size(){return e._classPrivateFieldGet2(Ux,this).size}sizeBy(t){return e._classPrivateFieldGet2(Ux,this).filter(t).length}get pending(){return e._classPrivateFieldGet2(Vx,this)}get isPaused(){return e._classPrivateFieldGet2(Hx,this)}}function Jx(t){return e._classPrivateFieldGet2(Gx,t)||e._classPrivateFieldGet2(Rx,t)<e._classPrivateFieldGet2(Ox,t)}function Zx(t){return e._classPrivateFieldGet2(Vx,t)<e._classPrivateFieldGet2(qx,t)}function $x(){var t;e._classPrivateFieldSet2(Vx,this,(t=e._classPrivateFieldGet2(Vx,this),--t)),e._assertClassBrand(Qx,this,tT).call(this),this.emit("next")}function Xx(){e._assertClassBrand(Qx,this,nT).call(this),e._assertClassBrand(Qx,this,rT).call(this),e._classPrivateFieldSet2(Fx,this,void 0)}function eT(t){var r=Date.now();if(void 0===e._classPrivateFieldGet2(jx,t)){var n=e._classPrivateFieldGet2(Mx,t)-r;if(!(n<0))return void 0===e._classPrivateFieldGet2(Fx,t)&&e._classPrivateFieldSet2(Fx,t,setTimeout((()=>{e._assertClassBrand(Qx,t,Xx).call(t)}),n)),!0;e._classPrivateFieldSet2(Rx,t,e._classPrivateFieldGet2(Dx,t)?e._classPrivateFieldGet2(Vx,t):0)}return!1}function tT(){if(0===e._classPrivateFieldGet2(Ux,this).size)return e._classPrivateFieldGet2(jx,this)&&clearInterval(e._classPrivateFieldGet2(jx,this)),e._classPrivateFieldSet2(jx,this,void 0),this.emit("empty"),0===e._classPrivateFieldGet2(Vx,this)&&this.emit("idle"),!1;if(!e._classPrivateFieldGet2(Hx,this)){var t=!e._classPrivateGetter(Qx,this,eT);if(e._classPrivateGetter(Qx,this,Jx)&&e._classPrivateGetter(Qx,this,Zx)){var r=e._classPrivateFieldGet2(Ux,this).dequeue();return!!r&&(this.emit("active"),r(),t&&e._assertClassBrand(Qx,this,rT).call(this),!0)}}return!1}function rT(){e._classPrivateFieldGet2(Gx,this)||void 0!==e._classPrivateFieldGet2(jx,this)||(e._classPrivateFieldSet2(jx,this,setInterval((()=>{e._assertClassBrand(Qx,this,nT).call(this)}),e._classPrivateFieldGet2(Lx,this))),e._classPrivateFieldSet2(Mx,this,Date.now()+e._classPrivateFieldGet2(Lx,this)))}function nT(){0===e._classPrivateFieldGet2(Rx,this)&&0===e._classPrivateFieldGet2(Vx,this)&&e._classPrivateFieldGet2(jx,this)&&(clearInterval(e._classPrivateFieldGet2(jx,this)),e._classPrivateFieldSet2(jx,this,void 0)),e._classPrivateFieldSet2(Rx,this,e._classPrivateFieldGet2(Dx,this)?e._classPrivateFieldGet2(Vx,this):0),e._assertClassBrand(Qx,this,iT).call(this)}function iT(){for(;e._assertClassBrand(Qx,this,tT).call(this););}function oT(e){return aT.apply(this,arguments)}function aT(){return(aT=e._asyncToGenerator((function*(e){return new Promise(((t,r)=>{e.addEventListener("abort",(()=>{r(e.reason)}),{once:!0})}))}))).apply(this,arguments)}function sT(e,t){return lT.apply(this,arguments)}function lT(){return lT=e._asyncToGenerator((function*(e,t){return new Promise((r=>{var n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)}))})),lT.apply(this,arguments)}function cT(e){var t=[mT.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function uT(e){var t,r,n,i,o,a,s,l,c,u,d,h,p,f,v;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!==(c=e.AD)&&void 0!==c?c:e.flag_ad)&&void 0!==l&&l,CD:null!==(u=null!==(d=e.CD)&&void 0!==d?d:e.flag_cd)&&void 0!==u&&u,Question:(null!==(h=null!==(p=e.Question)&&void 0!==p?p:e.questions)&&void 0!==h?h:[]).map((e=>({name:e.name,type:mT[e.type]}))),Answer:(null!==(f=null!==(v=e.Answer)&&void 0!==v?v:e.answers)&&void 0!==f?f:[]).map((e=>{var t,r;return{name:e.name,type:mT[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?Ze(e.data):e.data}}))}}var dT,hT;function pT(t){var r,n=new Yx({concurrency:null!==(r=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).queryConcurrency)&&void 0!==r?r:4});return function(){var r=e._asyncToGenerator((function*(r){var i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=new URLSearchParams;a.set("name",r),cT(o.types).forEach((e=>{a.append("type",mT[e])})),null===(i=o.onProgress)||void 0===i||i.call(o,new Ah("dns:query",{detail:r}));var s=yield n.add(e._asyncToGenerator((function*(){var e,r=yield fetch("".concat(t,"?").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=uT(yield r.json());return null===(e=o.onProgress)||void 0===e||e.call(o,new Ah("dns:response",{detail:n})),n})),{signal:o.signal});if(null==s)throw new Error("No DNS response received");return s}));return function(e){return r.apply(this,arguments)}}()}var fT=(hT||(hT=1,dT=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)}}}),dT),vT=e.getDefaultExportFromCjs(fT);class yT{constructor(t){e._defineProperty(this,"lru",void 0),this.lru=vT(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 uT({answers:n})}getAnswers(t,r){var n="".concat(t.toLowerCase(),"-").concat(r),i=this.lru.get(n);if(null!=i){var o=i.filter((e=>e.expires>Date.now())).map((t=>{var{expires:r,value:n}=t;return e._objectSpread2(e._objectSpread2({},n),{},{TTL:Math.round((r-Date.now())/1e3),type:mT[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 gT=class{constructor(t){var r,n,i;e._defineProperty(this,"resolvers",void 0),e._defineProperty(this,"cache",void 0),this.resolvers={},this.cache=(i=null!==(r=t.cacheSize)&&void 0!==r?r:1e3,new yT(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["."]=[pT("https://cloudflare-dns.com/dns-query"),pT("https://dns.google/resolve")])}query(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i,o,a=r.length>1&&void 0!==r[1]?r[1]:{},s=cT(a.types),l=!1!==a.cached?n.cache.get(t,s):void 0;if(null!=l)return null===(o=a.onProgress)||void 0===o||o.call(a,new Ah("dns:cache",{detail:l})),l;var c="".concat(t.split(".").pop(),"."),u=(null!==(i=n.resolvers[c])&&void 0!==i?i:n.resolvers["."]).sort((()=>Math.random()>.5?-1:1)),d=[];for(var h of u){var p;if(!0===(null===(p=a.signal)||void 0===p?void 0:p.aborted))break;try{var f=yield h(t,e._objectSpread2(e._objectSpread2({},a),{},{types:s}));for(var v of f.Answer)n.cache.add(t,v);return f}catch(e){var y;d.push(e),null===(y=a.onProgress)||void 0===y||y.call(a,new Ah("dns:error",{detail:e}))}}if(1===d.length)throw d[0];throw new AggregateError(d,"DNS lookup of ".concat(t," ").concat(s," failed"))}))()}};var mT;function wT(){return new gT(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"}(mT||(mT={}));var bT=["string","number","bigint","symbol"],_T=["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 ST(e){if(null===e)return"null";if(void 0===e)return"undefined";if(!0===e||!1===e)return"boolean";var t=typeof e;if(bT.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(_T.includes(t))return t;return}(e);return r||"Object"}class PT{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}}PT.uint=new PT(0,"uint",!0),PT.negint=new PT(1,"negint",!0),PT.bytes=new PT(2,"bytes",!0),PT.string=new PT(3,"string",!0),PT.array=new PT(4,"array",!1),PT.map=new PT(5,"map",!1),PT.tag=new PT(6,"tag",!1),PT.float=new PT(7,"float",!0),PT.false=new PT(7,"false",!0),PT.true=new PT(7,"true",!0),PT.null=new PT(7,"null",!0),PT.undefined=new PT(7,"undefined",!0),PT.break=new PT(7,"break",!0);class ET{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 AT=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&"function"==typeof globalThis.Buffer.isBuffer,kT=new TextDecoder,xT=new TextEncoder;function TT(e){return AT&&globalThis.Buffer.isBuffer(e)}function IT(e){return e instanceof Uint8Array?TT(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e:Uint8Array.from(e)}var CT=AT?(e,t,r)=>r-t>64?globalThis.Buffer.from(e.subarray(t,r)).toString("utf8"):LT(e,t,r):(e,t,r)=>r-t>64?kT.decode(e.subarray(t,r)):LT(e,t,r),BT=AT?e=>e.length>64?globalThis.Buffer.from(e):OT(e):e=>e.length>64?xT.encode(e):OT(e),NT=e=>Uint8Array.from(e),DT=AT?(e,t,r)=>TT(e)?new Uint8Array(e.subarray(t,r)):e.slice(t,r):(e,t,r)=>e.slice(t,r),GT=AT?(e,t)=>(e=e.map((e=>e instanceof Uint8Array?e:globalThis.Buffer.from(e))),IT(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},RT=AT?e=>globalThis.Buffer.allocUnsafe(e):e=>new Uint8Array(e);function OT(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 LT(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,c=void 0,u=void 0;switch(a){case 1:i<128&&(o=i);break;case 2:128==(192&(s=e[t+1]))&&(u=(31&i)<<6|63&s)>127&&(o=u);break;case 3:s=e[t+1],l=e[t+2],128==(192&s)&&128==(192&l)&&(u=(15&i)<<12|(63&s)<<6|63&l)>2047&&(u<55296||u>57343)&&(o=u);break;case 4:s=e[t+1],l=e[t+2],c=e[t+3],128==(192&s)&&128==(192&l)&&128==(192&c)&&(u=(15&i)<<18|(63&s)<<12|(63&l)<<6|63&c)>65535&&u<1114112&&(o=u)}}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 jT(n)}var MT=4096;function jT(e){var t=e.length;if(t<=MT)return String.fromCharCode.apply(String,e);for(var r="",n=0;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=MT));return r}class FT{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=RT(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=DT(r,0,this.cursor)}else e=GT(this.chunks,this.cursor);return t&&this.reset(),e}}var UT="CBOR decode error:",zT="CBOR encode error:";function VT(e,t,r){if(e.length-t<r)throw new Error("".concat(UT," not enough data for type"))}var qT=[24,256,65536,4294967296,BigInt("18446744073709551616")];function HT(e,t,r){VT(e,t,1);var n=e[t];if(!0===r.strict&&n<qT[0])throw new Error("".concat(UT," integer encoded in more bytes than necessary (strict decode)"));return n}function KT(e,t,r){VT(e,t,2);var n=e[t]<<8|e[t+1];if(!0===r.strict&&n<qT[1])throw new Error("".concat(UT," integer encoded in more bytes than necessary (strict decode)"));return n}function WT(e,t,r){VT(e,t,4);var n=16777216*e[t]+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];if(!0===r.strict&&n<qT[2])throw new Error("".concat(UT," integer encoded in more bytes than necessary (strict decode)"));return n}function QT(e,t,r){VT(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<qT[3])throw new Error("".concat(UT," 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(UT," integers outside of the safe integer range are not supported"))}function YT(e,t){return JT(e,0,t.value)}function JT(e,t,r){if(r<qT[0]){var n=Number(r);e.push([t|n])}else if(r<qT[1]){var i=Number(r);e.push([24|t,i])}else if(r<qT[2]){var o=Number(r);e.push([25|t,o>>>8,255&o])}else if(r<qT[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<qT[4]))throw new Error("".concat(UT," encountered BigInt larger than allowable range"));var l=[27|t,0,0,0,0,0,0,0],c=Number(s&BigInt(4294967295)),u=Number(s>>BigInt(32)&BigInt(4294967295));l[8]=255&c,c>>=8,l[7]=255&c,c>>=8,l[6]=255&c,c>>=8,l[5]=255&c,l[4]=255&u,u>>=8,l[3]=255&u,u>>=8,l[2]=255&u,u>>=8,l[1]=255&u,e.push(l)}}YT.encodedSize=function(e){return JT.encodedSize(e.value)},JT.encodedSize=function(e){return e<qT[0]?1:e<qT[1]?2:e<qT[2]?3:e<qT[3]?5:9},YT.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};var ZT=BigInt(-1),$T=BigInt(1);function XT(e,t){var r=t.value,n="bigint"==typeof r?r*ZT-$T:-1*r-1;JT(e,t.type.majorEncoded,n)}function eI(e,t,r,n){VT(e,t,r+n);var i=DT(e,t+r,t+r+n);return new ET(PT.bytes,i,r+n)}function tI(e,t,r,n){return eI(e,t,1,r)}function rI(e){return void 0===e.encodedBytes&&(e.encodedBytes=e.type===PT.string?BT(e.value):e.value),e.encodedBytes}function nI(e,t){var r=rI(t);JT(e,t.type.majorEncoded,r.length),e.push(r)}function iI(e,t,r,n,i){var o=r+n;VT(e,t,o);var a=new ET(PT.string,CT(e,t+r,t+o),o);return!0===i.retainStringBytes&&(a.byteValue=DT(e,t+r,t+o)),a}function oI(e,t,r,n){return iI(e,t,1,r,n)}XT.encodedSize=function(e){var t=e.value,r="bigint"==typeof t?t*ZT-$T:-1*t-1;return r<qT[0]?1:r<qT[1]?2:r<qT[2]?3:r<qT[3]?5:9},XT.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0},nI.encodedSize=function(e){var t=rI(e);return JT.encodedSize(t.length)+t.length},nI.compareTokens=function(e,t){return r=rI(e),n=rI(t),r.length<n.length?-1:r.length>n.length?1:function(e,t){if(TT(e)&&TT(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 aI=nI;function sI(e,t,r,n){return new ET(PT.array,n,r)}function lI(e,t,r,n){return sI(0,0,1,r)}function cI(e,t){JT(e,PT.array.majorEncoded,t.value)}function uI(e,t,r,n){return new ET(PT.map,n,r)}function dI(e,t,r,n){return uI(0,0,1,r)}function hI(e,t){JT(e,PT.map.majorEncoded,t.value)}function pI(e,t,r,n){return new ET(PT.tag,r,1)}function fI(e,t){JT(e,PT.tag.majorEncoded,t.value)}cI.compareTokens=YT.compareTokens,cI.encodedSize=function(e){return JT.encodedSize(e.value)},hI.compareTokens=YT.compareTokens,hI.encodedSize=function(e){return JT.encodedSize(e.value)},fI.compareTokens=YT.compareTokens,fI.encodedSize=function(e){return JT.encodedSize(e.value)};function vI(e,t,r){if(r){if(!1===r.allowNaN&&Number.isNaN(e))throw new Error("".concat(UT," NaN values are not supported"));if(!1===r.allowInfinity&&(e===1/0||e===-1/0))throw new Error("".concat(UT," Infinity values are not supported"))}return new ET(PT.float,e,t)}function yI(e,t,r){var n,i=t.value;if(!1===i)e.push([20|PT.float.majorEncoded]);else if(!0===i)e.push([21|PT.float.majorEncoded]);else if(null===i)e.push([22|PT.float.majorEncoded]);else if(void 0===i)e.push([23|PT.float.majorEncoded]);else{var o=!1;r&&!0===r.float64||(bI(i),i===_I(wI,1)||Number.isNaN(i)?(wI[0]=249,e.push(wI.slice(0,3)),o=!0):(SI(i),i===PI(wI,1)&&(wI[0]=250,e.push(wI.slice(0,5)),o=!0))),o||(n=i,mI.setFloat64(0,n,!1),EI(wI,1),wI[0]=251,e.push(wI.slice(0,9)))}}yI.encodedSize=function(e,t){var r=e.value;if(!1===r||!0===r||null==r)return 1;if(!t||!0!==t.float64){bI(r);var n=_I(wI,1);if(r===n||Number.isNaN(r))return 3;if(SI(r),r===(n=PI(wI,1)))return 5}return 9};var gI=new ArrayBuffer(9),mI=new DataView(gI,1),wI=new Uint8Array(gI,0);function bI(e){if(e===1/0)mI.setUint16(0,31744,!1);else if(e===-1/0)mI.setUint16(0,64512,!1);else if(Number.isNaN(e))mI.setUint16(0,32256,!1);else{mI.setFloat32(0,e);var t=mI.getUint32(0),r=(2139095040&t)>>23,n=8388607&t;if(255===r)mI.setUint16(0,31744,!1);else if(0===r)mI.setUint16(0,(2147483648&e)>>16|n>>13,!1);else{var i=r-127;i<-24?mI.setUint16(0,0):i<-14?mI.setUint16(0,(2147483648&t)>>16|1<<24+i,!1):mI.setUint16(0,(2147483648&t)>>16|i+15<<10|n>>13,!1)}}}function _I(e,t){if(e.length-t<2)throw new Error("".concat(UT," 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 SI(e){mI.setFloat32(0,e,!1)}function PI(e,t){if(e.length-t<4)throw new Error("".concat(UT," not enough data for float32"));var r=(e.byteOffset||0)+t;return new DataView(e.buffer,r,4).getFloat32(0,!1)}function EI(e,t){if(e.length-t<8)throw new Error("".concat(UT," not enough data for float64"));var r=(e.byteOffset||0)+t;return new DataView(e.buffer,r,8).getFloat64(0,!1)}function AI(e,t,r){throw new Error("".concat(UT," encountered invalid minor (").concat(r,") for major ").concat(e[t]>>>5))}function kI(e){return()=>{throw new Error("".concat(UT," ").concat(e))}}yI.compareTokens=YT.compareTokens;for(var xI=[],TI=0;TI<=23;TI++)xI[TI]=AI;xI[24]=function(e,t,r,n){return new ET(PT.uint,HT(e,t+1,n),2)},xI[25]=function(e,t,r,n){return new ET(PT.uint,KT(e,t+1,n),3)},xI[26]=function(e,t,r,n){return new ET(PT.uint,WT(e,t+1,n),5)},xI[27]=function(e,t,r,n){return new ET(PT.uint,QT(e,t+1,n),9)},xI[28]=AI,xI[29]=AI,xI[30]=AI,xI[31]=AI;for(var II=32;II<=55;II++)xI[II]=AI;xI[56]=function(e,t,r,n){return new ET(PT.negint,-1-HT(e,t+1,n),2)},xI[57]=function(e,t,r,n){return new ET(PT.negint,-1-KT(e,t+1,n),3)},xI[58]=function(e,t,r,n){return new ET(PT.negint,-1-WT(e,t+1,n),5)},xI[59]=function(e,t,r,n){var i=QT(e,t+1,n);if("bigint"!=typeof i){var o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new ET(PT.negint,o,9)}if(!0!==n.allowBigInt)throw new Error("".concat(UT," integers outside of the safe integer range are not supported"));return new ET(PT.negint,ZT-BigInt(i),9)},xI[60]=AI,xI[61]=AI,xI[62]=AI,xI[63]=AI;for(var CI=64;CI<=87;CI++)xI[CI]=tI;xI[88]=function(e,t,r,n){return eI(e,t,2,HT(e,t+1,n))},xI[89]=function(e,t,r,n){return eI(e,t,3,KT(e,t+1,n))},xI[90]=function(e,t,r,n){return eI(e,t,5,WT(e,t+1,n))},xI[91]=function(e,t,r,n){var i=QT(e,t+1,n);if("bigint"==typeof i)throw new Error("".concat(UT," 64-bit integer bytes lengths not supported"));return eI(e,t,9,i)},xI[92]=AI,xI[93]=AI,xI[94]=AI,xI[95]=kI("indefinite length bytes/strings are not supported");for(var BI=96;BI<=119;BI++)xI[BI]=oI;xI[120]=function(e,t,r,n){return iI(e,t,2,HT(e,t+1,n),n)},xI[121]=function(e,t,r,n){return iI(e,t,3,KT(e,t+1,n),n)},xI[122]=function(e,t,r,n){return iI(e,t,5,WT(e,t+1,n),n)},xI[123]=function(e,t,r,n){var i=QT(e,t+1,n);if("bigint"==typeof i)throw new Error("".concat(UT," 64-bit integer string lengths not supported"));return iI(e,t,9,i,n)},xI[124]=AI,xI[125]=AI,xI[126]=AI,xI[127]=kI("indefinite length bytes/strings are not supported");for(var NI=128;NI<=151;NI++)xI[NI]=lI;xI[152]=function(e,t,r,n){return sI(0,0,2,HT(e,t+1,n))},xI[153]=function(e,t,r,n){return sI(0,0,3,KT(e,t+1,n))},xI[154]=function(e,t,r,n){return sI(0,0,5,WT(e,t+1,n))},xI[155]=function(e,t,r,n){var i=QT(e,t+1,n);if("bigint"==typeof i)throw new Error("".concat(UT," 64-bit integer array lengths not supported"));return sI(0,0,9,i)},xI[156]=AI,xI[157]=AI,xI[158]=AI,xI[159]=function(e,t,r,n){if(!1===n.allowIndefinite)throw new Error("".concat(UT," indefinite length items not allowed"));return sI(0,0,1,1/0)};for(var DI=160;DI<=183;DI++)xI[DI]=dI;xI[184]=function(e,t,r,n){return uI(0,0,2,HT(e,t+1,n))},xI[185]=function(e,t,r,n){return uI(0,0,3,KT(e,t+1,n))},xI[186]=function(e,t,r,n){return uI(0,0,5,WT(e,t+1,n))},xI[187]=function(e,t,r,n){var i=QT(e,t+1,n);if("bigint"==typeof i)throw new Error("".concat(UT," 64-bit integer map lengths not supported"));return uI(0,0,9,i)},xI[188]=AI,xI[189]=AI,xI[190]=AI,xI[191]=function(e,t,r,n){if(!1===n.allowIndefinite)throw new Error("".concat(UT," indefinite length items not allowed"));return uI(0,0,1,1/0)};for(var GI=192;GI<=215;GI++)xI[GI]=pI;xI[216]=function(e,t,r,n){return new ET(PT.tag,HT(e,t+1,n),2)},xI[217]=function(e,t,r,n){return new ET(PT.tag,KT(e,t+1,n),3)},xI[218]=function(e,t,r,n){return new ET(PT.tag,WT(e,t+1,n),5)},xI[219]=function(e,t,r,n){return new ET(PT.tag,QT(e,t+1,n),9)},xI[220]=AI,xI[221]=AI,xI[222]=AI,xI[223]=AI;for(var RI=224;RI<=243;RI++)xI[RI]=kI("simple values are not supported");xI[244]=AI,xI[245]=AI,xI[246]=AI,xI[247]=function(e,t,r,n){if(!1===n.allowUndefined)throw new Error("".concat(UT," undefined values are not supported"));return!0===n.coerceUndefinedToNull?new ET(PT.null,null,1):new ET(PT.undefined,void 0,1)},xI[248]=kI("simple values are not supported"),xI[249]=function(e,t,r,n){return vI(_I(e,t+1),3,n)},xI[250]=function(e,t,r,n){return vI(PI(e,t+1),5,n)},xI[251]=function(e,t,r,n){return vI(EI(e,t+1),9,n)},xI[252]=AI,xI[253]=AI,xI[254]=AI,xI[255]=function(e,t,r,n){if(!1===n.allowIndefinite)throw new Error("".concat(UT," indefinite length items not allowed"));return new ET(PT.break,void 0,1)};for(var OI=[],LI=0;LI<24;LI++)OI[LI]=new ET(PT.uint,LI,1);for(var MI=-1;MI>=-24;MI--)OI[31-MI]=new ET(PT.negint,MI,1);OI[64]=new ET(PT.bytes,new Uint8Array(0),1),OI[96]=new ET(PT.string,"",1),OI[128]=new ET(PT.array,0,1),OI[160]=new ET(PT.map,0,1),OI[244]=new ET(PT.false,!1,1),OI[245]=new ET(PT.true,!0,1),OI[246]=new ET(PT.null,null,1);var jI={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=UI[i].compareTokens(r,n);return o},quickEncodeToken:function(e){switch(e.type){case PT.false:return NT([244]);case PT.true:return NT([245]);case PT.null:return NT([246]);case PT.bytes:return e.value.length?void 0:NT([64]);case PT.string:return""===e.value?NT([96]):void 0;case PT.array:return 0===e.value?NT([128]):void 0;case PT.map:return 0===e.value?NT([160]):void 0;case PT.uint:return e.value<24?NT([Number(e.value)]):void 0;case PT.negint:if(e.value>=-24)return NT([31-Number(e.value)])}}};var FI,UI=((FI=[])[PT.uint.major]=YT,FI[PT.negint.major]=XT,FI[PT.bytes.major]=nI,FI[PT.string.major]=aI,FI[PT.array.major]=cI,FI[PT.map.major]=hI,FI[PT.tag.major]=fI,FI[PT.float.major]=yI,FI),zI=new FT;class VI{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(zT," object contains circular references"));return new VI(t,e)}}var qI={null:new ET(PT.null,null),undefined:new ET(PT.undefined,void 0),true:new ET(PT.true,!0),false:new ET(PT.false,!1),emptyArray:new ET(PT.array,0),emptyMap:new ET(PT.map,0)},HI={number:(e,t,r,n)=>Number.isInteger(e)&&Number.isSafeInteger(e)?new ET(e>=0?PT.uint:PT.negint,e):new ET(PT.float,e),bigint:(e,t,r,n)=>e>=BigInt(0)?new ET(PT.uint,e):new ET(PT.negint,e),Uint8Array:(e,t,r,n)=>new ET(PT.bytes,e),string:(e,t,r,n)=>new ET(PT.string,e),boolean:(e,t,r,n)=>e?qI.true:qI.false,null:(e,t,r,n)=>qI.null,undefined:(e,t,r,n)=>qI.undefined,ArrayBuffer:(e,t,r,n)=>new ET(PT.bytes,new Uint8Array(e)),DataView:(e,t,r,n)=>new ET(PT.bytes,new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),Array(e,t,r,n){if(!e.length)return!0===r.addBreakTokens?[qI.emptyArray,new ET(PT.break)]:qI.emptyArray;n=VI.createCheck(n,e);var i=[],o=0;for(var a of e)i[o++]=WI(a,r,n);return r.addBreakTokens?[new ET(PT.array,e.length),i,new ET(PT.break)]:[new ET(PT.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?[qI.emptyMap,new ET(PT.break)]:qI.emptyMap;n=VI.createCheck(n,e);var s=[],l=0;for(var c of o)s[l++]=[WI(c,r,n),WI(i?e.get(c):e[c],r,n)];return function(e,t){t.mapSorter&&e.sort(t.mapSorter)}(s,r),r.addBreakTokens?[new ET(PT.map,a),s,new ET(PT.break)]:[new ET(PT.map,a),s]}};for(var KI of(HI.Map=HI.Object,HI.Buffer=HI.Uint8Array,"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" ")))HI["".concat(KI,"Array")]=HI.DataView;function WI(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0,n=ST(e),i=t&&t.typeEncoders&&t.typeEncoders[n]||HI[n];if("function"==typeof i){var o=i(e,n,t,r);if(null!=o)return o}var a=HI[n];if(!a)throw new Error("".concat(zT," unsupported type: ").concat(n));return a(e,n,t,r)}function QI(e,t,r,n){if(Array.isArray(t))for(var i of t)QI(e,i,r,n);else r[t.type.major](e,t,n)}function YI(e,t,r){var n=WI(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 FT(a);if(o(s,n,r),1!==s.chunks.length)throw new Error("Unexpected error: pre-calculated length for ".concat(n," was wrong"));return IT(s.chunks[0])}}return zI.reset(),QI(zI,n,t,r),zI.toBytes(!0)}function JI(e,t){return t=Object.assign({},jI,t),YI(e,UI,t)}var ZI={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0};class $I{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=OI[e];if(void 0===t){var r=xI[e];if(!r)throw new Error("".concat(UT," 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 XI=Symbol.for("DONE"),eC=Symbol.for("BREAK");function tC(e,t){if(e.done())return XI;var r=e.next();if(r.type===PT.break)return eC;if(r.type.terminal)return r.value;if(r.type===PT.array)return function(e,t,r){for(var n=[],i=0;i<e.value;i++){var o=tC(t,r);if(o===eC){if(e.value===1/0)break;throw new Error("".concat(UT," got unexpected break to lengthed array"))}if(o===XI)throw new Error("".concat(UT," found array but not enough entries (got ").concat(i,", expected ").concat(e.value,")"));n[i]=o}return n}(r,e,t);if(r.type===PT.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=tC(t,r);if(s===eC){if(e.value===1/0)break;throw new Error("".concat(UT," got unexpected break to lengthed map"))}if(s===XI)throw new Error("".concat(UT," 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(UT," 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(UT,' found repeat map key "').concat(s,'"'));var l=tC(t,r);if(l===XI)throw new Error("".concat(UT," 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===PT.tag){if(t.tags&&"function"==typeof t.tags[r.value]){var n=tC(e,t);return t.tags[r.value](n)}throw new Error("".concat(UT," tag not supported (").concat(r.value,")"))}throw new Error("unsupported")}function rC(e,t){var[r,n]=function(e,t){if(!(e instanceof Uint8Array))throw new Error("".concat(UT," data to decode must be a Uint8Array"));var r=(t=Object.assign({},ZI,t)).tokenizer||new $I(e,t),n=tC(r,t);if(n===XI)throw new Error("".concat(UT," did not find any content to decode"));if(n===eC)throw new Error("".concat(UT," got unexpected break"));return[n,e.subarray(r.pos())]}(e,t);if(n.length>0)throw new Error("".concat(UT," too many terminals, data makes no sense"));return r}function nC(){var{enumerable:e=!0,configurable:t=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{enumerable:e,configurable:t,writable:!1}}function*iC(e,t){if(null!=t&&"object"==typeof t)if(Array.isArray(t))for(var[r,n]of t.entries()){var i=[...e,r],o=je.asCID(n);null!=o?yield[i.join("/"),o]:"object"==typeof n&&(yield*oC(n,i))}else{var a=je.asCID(t);null!=a?yield[e.join("/"),a]:yield*oC(t,e)}}function*oC(e,t){if(!(null==e||e instanceof Uint8Array)){var r=je.asCID(e);for(var[n,i]of(null!=r&&(yield[t.join("/"),r]),Object.entries(e))){var o=[...t,n];yield*iC(o,i)}}}function*aC(e,t){if(Array.isArray(t))for(var[r,n]of t.entries()){var i=[...e,r];yield i.join("/"),"object"==typeof n&&null==je.asCID(n)&&(yield*sC(n,i))}else yield*sC(t,e)}function*sC(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!=je.asCID(n)||(yield*aC(i,n))}}class lC{constructor(t){var{cid:r,bytes:n,value:i}=t;if(e._defineProperty(this,"cid",void 0),e._defineProperty(this,"bytes",void 0),e._defineProperty(this,"value",void 0),e._defineProperty(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:nC(),bytes:nC(),value:nC(),asBlock:nC()})}links(){return oC(this.value,[])}tree(){return sC(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=je.asCID(r);if(null!=o)return{value:o,remaining:t.slice(n+1).join("/")}}return{value:r}}(this.value,e.split("/").filter(Boolean))}}var cC="/pin/",uC="/pinned-block/",dC=O;function hC(e){return 0===e.version&&(e=e.toV1()),new xc("".concat(cC).concat(e.toString(dC)))}var pC=new WeakSet;class fC{constructor(t,r,n){e._classPrivateMethodInitSpec(this,pC),e._defineProperty(this,"datastore",void 0),e._defineProperty(this,"blockstore",void 0),e._defineProperty(this,"getCodec",void 0),this.datastore=t,this.blockstore=r,this.getCodec=n}add(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(i,o){var a=hC(t);if(yield e._awaitAsyncGenerator(r.datastore.has(a)))throw new Error("Already pinned");var s=Math.round(null!==(i=n.depth)&&void 0!==i?i:1/0);if(s<0)throw new Error("Depth must be greater than or equal to 0");var l,c=new Gh({concurrency:1}),u=!1,d=!1;try{for(var h,p=e._asyncIterator(e._assertClassBrand(pC,r,vC).call(r,t,c,e._objectSpread2(e._objectSpread2({},n),{},{depth:s})));u=!(h=yield e._awaitAsyncGenerator(p.next())).done;u=!1){var f=h.value;yield e._awaitAsyncGenerator(e._assertClassBrand(pC,r,yC).call(r,f,(e=>null==e.pinnedBy.find((e=>rt(e,t.bytes)))&&(e.pinCount++,e.pinnedBy.push(t.bytes),!0)),n)),yield f}}catch(e){d=!0,l=e}finally{try{u&&null!=p.return&&(yield e._awaitAsyncGenerator(p.return()))}finally{if(d)throw l}}var v={depth:s,metadata:null!==(o=n.metadata)&&void 0!==o?o:{}};yield e._awaitAsyncGenerator(r.datastore.put(a,JI(v),n))}()})).apply(this,arguments)}rm(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var i=hC(t),o=rC(yield e._awaitAsyncGenerator(r.datastore.get(i,n)));yield e._awaitAsyncGenerator(r.datastore.delete(i,n));var a,s=new Gh({concurrency:1}),l=!1,c=!1;try{for(var u,d=e._asyncIterator(e._assertClassBrand(pC,r,vC).call(r,t,s,e._objectSpread2(e._objectSpread2({},n),{},{depth:o.depth})));l=!(u=yield e._awaitAsyncGenerator(d.next())).done;l=!1){var h=u.value;yield e._awaitAsyncGenerator(e._assertClassBrand(pC,r,yC).call(r,h,(e=>(e.pinCount--,e.pinnedBy=e.pinnedBy.filter((e=>rt(e,t.bytes))),!0)),e._objectSpread2(e._objectSpread2({},n),{},{depth:o.depth}))),yield h}}catch(e){c=!0,a=e}finally{try{l&&null!=d.return&&(yield e._awaitAsyncGenerator(d.return()))}finally{if(c)throw a}}}()})).apply(this,arguments)}ls(){var t=this;return e._wrapAsyncGenerator((function(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var n,i=!1,o=!1;try{for(var a,s=e._asyncIterator(t.datastore.query({prefix:cC+(null!=r.cid?"".concat(r.cid.toString(O)):"")},r));i=!(a=yield e._awaitAsyncGenerator(s.next())).done;i=!1){var{key:l,value:c}=a.value,u=je.parse(l.toString().substring(5),O),d=rC(c);yield e._objectSpread2({cid:u},d)}}catch(e){o=!0,n=e}finally{try{i&&null!=s.return&&(yield e._awaitAsyncGenerator(s.return()))}finally{if(o)throw n}}}()})).apply(this,arguments)}isPinned(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{},i=new xc("".concat(uC).concat(dC.encode(t.multihash.bytes)));return n.datastore.has(i,e)}))()}get(t,r){var n=this;return e._asyncToGenerator((function*(){var e=hC(t);return rC(yield n.datastore.get(e,r))}))()}setMetadata(t,r,n){var i=this;return e._asyncToGenerator((function*(){var e=hC(t),o=rC(yield i.datastore.get(e,n));o.metadata=null!=r?r:{},yield i.datastore.put(e,JI(o),n)}))()}}function vC(t,r,n){var i=this;return e._wrapAsyncGenerator((function*(){if(-1!==n.depth){var o=yield e._awaitAsyncGenerator(i.getCodec(t.code)),a=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 lC({cid:r,bytes:t,value:o})}({bytes:yield e._awaitAsyncGenerator(i.blockstore.get(t,n)),cid:t,codec:o});yield t;var s=function*(t){yield*e._asyncGeneratorDelegate(e._asyncIterator(yield e._awaitAsyncGenerator(r.add(e._asyncToGenerator((function*(){return e._assertClassBrand(pC,i,vC).call(i,t,r,e._objectSpread2(e._objectSpread2({},n),{},{depth:n.depth-1}))}))))))};for(var[,l]of a.links())yield*s(l)}}))()}function yC(e,t,r){return gC.apply(this,arguments)}function gC(){return gC=e._asyncToGenerator((function*(e,t,r){var n,i=new xc("".concat(uC).concat(dC.encode(e.multihash.bytes))),o={pinCount:0,pinnedBy:[]};try{o=rC(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,JI(o),r),null===(n=r.onProgress)||void 0===n||n.call(r,new Ah("helia:pin:add",e))))})),gC.apply(this,arguments)}class mC extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Insufficient providers found"),this.name="InsufficientProvidersError"}}e._defineProperty(mC,"name","InsufficientProvidersError");class wC extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No routers available"),this.name="NoRoutersAvailableError"}}e._defineProperty(wC,"name","NoRoutersAvailableError");class bC extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unknown hash algorithm"),this.name="UnknownHashAlgorithmError"}}e._defineProperty(bC,"name","UnknownHashAlgorithmError");class _C extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unknown codec"),this.name="UnknownCodecError"}}e._defineProperty(_C,"name","UnknownCodecError");class SC{constructor(t,r){var n,i,o,a,s,l,c,u,d,h,p,f,v,y,g,m;e._defineProperty(this,"log",void 0),e._defineProperty(this,"routers",void 0),e._defineProperty(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!==(c=null===(u=t.metrics)||void 0===u?void 0:u.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1}))&&void 0!==c?c: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!==(p=null===(f=t.metrics)||void 0===f?void 0:f.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1}))&&void 0!==p?p:this.get,this.findPeer=null!==(v=null===(y=t.metrics)||void 0===y?void 0:y.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1}))&&void 0!==v?v:this.findPeer,this.getClosestPeers=null!==(g=null===(m=t.metrics)||void 0===m?void 0:m.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1}))&&void 0!==g?g:this.getClosestPeers}start(){var t=this;return e._asyncToGenerator((function*(){yield xa(...t.routers)}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield Ia(...t.routers)}))()}findProviders(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(0===r.routers.length)throw new wC("No content routers available");var i=new Rh({concurrency:r.providerLookupConcurrency});i.addEventListener("error",(()=>{}));var o,a=!1,s=!1;try{for(var l,c=function*(){var t=l.value;if(null==t)return 0;if(0===t.multiaddrs.length){if(null!=i.find(t.id))return 0;i.add(e._asyncToGenerator((function*(){try{var e=yield r.findPeer(t.id,n);return 0===e.multiaddrs.length?null:e}catch(e){return r.log.error("could not load multiaddrs for peer %p",t.id,e),null}})),{peerId:t.id,signal:n.signal}).catch((e=>{r.log.error("could not load multiaddrs for peer %p",t.id,e)}))}yield t},u=e._asyncIterator(nu(i.toGenerator(),...PC(r.routers,"findProviders").map((e=>e.findProviders(t,n)))));a=!(l=yield e._awaitAsyncGenerator(u.next())).done;a=!1)yield*c()}catch(e){s=!0,o=e}finally{try{a&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(s)throw o}}}()})).apply(this,arguments)}provide(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{};if(0===n.routers.length)throw new wC("No content routers available");yield Promise.all(PC(n.routers,"provide").map(function(){var r=e._asyncToGenerator((function*(e){yield e.provide(t,i)}));return function(e){return r.apply(this,arguments)}}()))}))()}cancelReprovide(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{};yield Promise.all(PC(n.routers,"cancelReprovide").map(function(){var r=e._asyncToGenerator((function*(e){yield e.cancelReprovide(t,i)}));return function(e){return r.apply(this,arguments)}}()))}))()}put(t,r,n){var i=this;return e._asyncToGenerator((function*(){yield Promise.all(PC(i.routers,"put").map(function(){var i=e._asyncToGenerator((function*(e){yield e.put(t,r,n)}));return function(e){return i.apply(this,arguments)}}()))}))()}get(t,r){var n=this;return e._asyncToGenerator((function*(){return Promise.any(PC(n.routers,"get").map(function(){var n=e._asyncToGenerator((function*(e){return e.get(t,r)}));return function(e){return n.apply(this,arguments)}}()))}))()}findPeer(t,r){var n=this;return e._asyncToGenerator((function*(){if(0===n.routers.length)throw new wC("No peer routers available");var i,o=n,a=nu(...PC(n.routers,"findPeer").map((n=>e._wrapAsyncGenerator((function*(){try{yield yield e._awaitAsyncGenerator(n.findPeer(t,r))}catch(e){o.log.error(e)}}))()))),s=!1,l=!1;try{for(var c,u=e._asyncIterator(a);s=!(c=yield u.next()).done;s=!1){var d=c.value;if(null!=d)return d}}catch(e){l=!0,i=e}finally{try{s&&null!=u.return&&(yield u.return())}finally{if(l)throw i}}throw new aa("Could not find peer in routing")}))()}getClosestPeers(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(0===r.routers.length)throw new wC("No peer routers available");var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(nu(...PC(r.routers,"getClosestPeers").map((e=>e.getClosestPeers(t,n)))));o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;null!=c&&(yield c)}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}()})).apply(this,arguments)}}function PC(e,t){return e.filter((e=>null!=e[t]))}let EC=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 AC=new WeakMap;class kC extends EventTarget{constructor(){super(),e._classPrivateFieldInitSpec(this,AC,new Map)}listenerCount(t){var r=e._classPrivateFieldGet2(AC,this).get(t);return null==r?0:r.length}addEventListener(t,r,n){var i;super.addEventListener(t,r,n);var o=e._classPrivateFieldGet2(AC,this).get(t);null==o&&(o=[],e._classPrivateFieldGet2(AC,this).set(t,o)),o.push({callback:r,once:null!==(i=!0!==n&&!1!==n&&(null==n?void 0:n.once))&&void 0!==i&&i})}removeEventListener(t,r,n){super.removeEventListener(t.toString(),null!=r?r:null,n);var i=e._classPrivateFieldGet2(AC,this).get(t);null!=i&&(i=i.filter((e=>{var{callback:t}=e;return t!==r})),e._classPrivateFieldGet2(AC,this).set(t,i))}dispatchEvent(t){var r=super.dispatchEvent(t),n=e._classPrivateFieldGet2(AC,this).get(t.type);return null==n||(n=n.filter((e=>{var{once:t}=e;return!t})),e._classPrivateFieldGet2(AC,this).set(t.type,n)),r}safeDispatchEvent(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.dispatchEvent(new CustomEvent(e,t))}}class xC extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The queue was full"),this.name="QueueFullError"}}e._defineProperty(xC,"name","QueueFullError");class TC{constructor(t){var r;e._defineProperty(this,"deferred",void 0),e._defineProperty(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 EC)}cleanup(){var e;null===(e=this.signal)||void 0===e||e.removeEventListener("abort",this.onAbort)}}class IC{constructor(t,r){e._defineProperty(this,"id",void 0),e._defineProperty(this,"fn",void 0),e._defineProperty(this,"options",void 0),e._defineProperty(this,"recipients",void 0),e._defineProperty(this,"status",void 0),e._defineProperty(this,"timeline",void 0),e._defineProperty(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 EC),this.cleanup())}join(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e,n=t.length>0&&void 0!==t[0]?t[0]:{},i=new TC(n.signal);return r.recipients.push(i),null===(e=n.signal)||void 0===e||e.addEventListener("abort",r.onAbort),i.deferred.promise}))()}run(){var t=this;return e._asyncToGenerator((function*(){t.status="running",t.timeline.started=Date.now();try{var r;t.controller.signal.throwIfAborted();var n=yield Zc(t.fn(e._objectSpread2(e._objectSpread2({},null!==(r=t.options)&&void 0!==r?r:{}),{},{signal:t.controller.signal})),t.controller.signal);t.recipients.forEach((e=>{e.deferred.resolve(n)})),t.status="complete"}catch(e){t.recipients.forEach((t=>{t.deferred.reject(e)})),t.status="errored"}finally{t.timeline.finished=Date.now(),t.cleanup()}}))()}cleanup(){this.recipients.forEach((e=>{var t;e.cleanup(),null===(t=e.signal)||void 0===t||t.removeEventListener("abort",this.onAbort)}))}}function CC(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 BC extends kC{constructor(){var t,r,n,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),e._defineProperty(this,"concurrency",void 0),e._defineProperty(this,"maxSize",void 0),e._defineProperty(this,"queue",void 0),e._defineProperty(this,"pending",void 0),e._defineProperty(this,"sort",void 0),e._defineProperty(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=CC(this.emitEmpty.bind(this),1),this.emitIdle=CC(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(t,r){var n=this;return e._asyncToGenerator((function*(){var e;if(null==r||null===(e=r.signal)||void 0===e||e.throwIfAborted(),n.size===n.maxSize)throw new xC;var i=new IC(t,r);return n.enqueue(i),n.safeDispatchEvent("add"),n.autoStart&&n.tryToStartAnother(),i.join(r).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 EC)})),this.clear()}onEmpty(t){var r=this;return e._asyncToGenerator((function*(){0!==r.size&&(yield xh(r,"empty",null==t?void 0:t.signal))}))()}onSizeLessThan(t,r){var n=this;return e._asyncToGenerator((function*(){n.size<t||(yield xh(n,"next",null==r?void 0:r.signal,{filter:()=>n.size<t}))}))()}onIdle(t){var r=this;return e._asyncToGenerator((function*(){0===r.pending&&0===r.size||(yield xh(r,"idle",null==t?void 0:t.signal))}))()}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}toGenerator(t){var r=this;return e._wrapAsyncGenerator((function*(){var n,i;null==t||null===(n=t.signal)||void 0===n||n.throwIfAborted();var o=Yc({objectMode:!0}),a=e=>{null!=e?r.abort():r.clear(),o.end(e)},s=e=>{null!=e.detail&&o.push(e.detail.result)},l=e=>{a(e.detail.error)},c=()=>{a()},u=()=>{a(new EC("Queue aborted"))};r.addEventListener("success",s),r.addEventListener("failure",l),r.addEventListener("idle",c),null==t||null===(i=t.signal)||void 0===i||i.addEventListener("abort",u);try{yield*e._asyncGeneratorDelegate(e._asyncIterator(o),e._awaitAsyncGenerator)}finally{var d;r.removeEventListener("success",s),r.removeEventListener("failure",l),r.removeEventListener("idle",c),null==t||null===(d=t.signal)||void 0===d||d.removeEventListener("abort",u),a()}}))()}}var NC="lock:worker:request-read",DC="lock:worker:abort-read-request",GC="lock:worker:release-read",RC="lock:master:grant-read",OC="lock:master:error-read",LC="lock:worker:request-write",MC="lock:worker:abort-write-request",jC="lock:worker:release-write",FC="lock:master:grant-write",UC="lock:master:error-write",zC="lock:worker:finalize",VC="mortice",qC={singleProcess:!1},HC=(t,r,n,i,o,a,s,l,c)=>u=>{if(null!=u.data){var d,h={type:u.data.type,name:u.data.name,identifier:u.data.identifier};h.type===o&&t.safeDispatchEvent(n,{detail:{name:h.name,identifier:h.identifier,handler:(d=e._asyncToGenerator((function*(){r.postMessage({type:c,name:h.name,identifier:h.identifier}),yield new Promise((e=>{var t=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&&(r.removeEventListener("message",t),e())}};r.addEventListener("message",t)}))})),function(){return d.apply(this,arguments)}),onError:e=>{r.postMessage({type:s,name:h.name,identifier:h.identifier,error:{message:e.message,name:e.name,stack:e.stack}})}}}),h.type===a&&t.safeDispatchEvent(i,{detail:{name:h.name,identifier:h.identifier}}),h.type===zC&&t.safeDispatchEvent("finalizeRequest",{detail:{name:h.name}})}};class KC{constructor(t){e._defineProperty(this,"name",void 0),e._defineProperty(this,"channel",void 0),this.name=t,this.channel=new BroadcastChannel(VC)}readLock(e){return this.sendRequest(NC,DC,RC,OC,GC,e)}writeLock(e){return this.sendRequest(LC,MC,FC,UC,jC,e)}finalize(){this.channel.postMessage({type:zC,name:this.name}),this.channel.close()}sendRequest(t,r,n,i,o,a){var s=this;return e._asyncToGenerator((function*(){var e;null==a||null===(e=a.signal)||void 0===e||e.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:t,identifier:l,name:s.name}),new Promise(((e,t)=>{var c,u=()=>{s.channel.postMessage({type:r,identifier:l,name:s.name})};null==a||null===(c=a.signal)||void 0===c||c.addEventListener("abort",u,{once:!0});var d=r=>{var c,h;if((null===(c=r.data)||void 0===c?void 0:c.identifier)===l){var p;if((null===(h=r.data)||void 0===h?void 0:h.type)===n)s.channel.removeEventListener("message",d),null==a||null===(p=a.signal)||void 0===p||p.removeEventListener("abort",u),e((()=>{s.channel.postMessage({type:o,identifier:l,name:s.name})}));if(r.data.type===i){var f;s.channel.removeEventListener("message",d),null==a||null===(f=a.signal)||void 0===f||f.removeEventListener("abort",u);var v=new Error;null!=r.data.error&&(v.message=r.data.error.message,v.name=r.data.error.name,v.stack=r.data.error.stack),t(v)}}};s.channel.addEventListener("message",d)}))}))()}}var WC,QC=new Map;function YC(e){return"function"==typeof(null==e?void 0:e.readLock)&&"function"==typeof(null==e?void 0:e.writeLock)}function JC(t){if(null==WC&&(WC=(e=>{if(e=Object.assign({},qC,e),Boolean(globalThis.document)||e.singleProcess){var t=new BroadcastChannel(VC),r=new kC;return t.addEventListener("message",HC(r,t,"requestReadLock","abortReadLockRequest",NC,DC,OC,GC,RC)),t.addEventListener("message",HC(r,t,"requestWriteLock","abortWriteLockRequest",LC,MC,UC,jC,FC)),r}return new KC(e.name)})(t),!YC(WC))){var r=WC;r.addEventListener("requestReadLock",(t=>{var n=t.detail.name,i=t.detail.identifier,o=QC.get(n);if(null!=o){var a=new AbortController,s=e=>{e.detail.name===n&&e.detail.identifier===i&&a.abort()};r.addEventListener("abortReadLockRequest",s),o.readLock({signal:a.signal}).then(function(){var r=e._asyncToGenerator((function*(e){yield t.detail.handler().finally((()=>{e()}))}));return function(e){return r.apply(this,arguments)}}()).catch((e=>{t.detail.onError(e)})).finally((()=>{r.removeEventListener("abortReadLockRequest",s)}))}})),r.addEventListener("requestWriteLock",(t=>{var n=t.detail.name,i=t.detail.identifier,o=QC.get(n);if(null!=o){var a=new AbortController,s=e=>{e.detail.name===n&&e.detail.identifier===i&&a.abort()};r.addEventListener("abortWriteLockRequest",s),o.writeLock({signal:a.signal}).then(function(){var r=e._asyncToGenerator((function*(e){yield t.detail.handler().finally((()=>{e()}))}));return function(e){return r.apply(this,arguments)}}()).catch((e=>{t.detail.onError(e)})).finally((()=>{r.removeEventListener("abortWriteLockRequest",s)}))}})),r.addEventListener("finalizeRequest",(e=>{var t=e.detail.name,r=QC.get(t);null!=r&&r.finalize()}))}return WC}function ZC(e,t){return $C.apply(this,arguments)}function $C(){return $C=e._asyncToGenerator((function*(t,r){var n,i,o,a=new Promise(((e,t)=>{i=e,o=t})),s=()=>{o(new EC)};return null==r||null===(n=r.signal)||void 0===n||n.addEventListener("abort",s,{once:!0}),t.add(e._asyncToGenerator((function*(){yield new Promise((e=>{i((()=>{var t;null==r||null===(t=r.signal)||void 0===t||t.removeEventListener("abort",s),e()}))}))})),{signal:null==r?void 0:r.signal}).catch((e=>{o(e)})),a})),$C.apply(this,arguments)}var XC={name:"lock",concurrency:1/0,singleProcess:!1};function eB(t){var r=Object.assign({},XC,t);return((t,r)=>{var n=QC.get(t);if(null!=n)return n;var i=JC(r);if(YC(i))return n=i,QC.set(t,n),n;var o,a=new BC({concurrency:1});return n={readLock:t=>e._asyncToGenerator((function*(){if(null!=o)return ZC(o,t);var n=o=new BC({concurrency:r.concurrency,autoStart:!1}),i=ZC(o,t);return a.add(e._asyncToGenerator((function*(){n.start(),yield n.onIdle().then((()=>{o===n&&(o=null)}))}))),i}))(),writeLock:t=>e._asyncToGenerator((function*(){return o=null,ZC(a,t)}))(),finalize:()=>{QC.delete(t)},queue:a},QC.set(t,n),n})(r.name,r)}class tB{constructor(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e._defineProperty(this,"lock",void 0),e._defineProperty(this,"child",void 0),e._defineProperty(this,"pins",void 0),e._defineProperty(this,"started",void 0),this.child=t,this.pins=r,this.lock=eB({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){yield xa(t.child),t.started=!0}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield Ia(t.child),t.started=!1}))()}unwrap(){return this.child}put(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var e,o=n.length>2&&void 0!==n[2]?n[2]:{};null==o||null===(e=o.signal)||void 0===e||e.throwIfAborted();var a=yield i.lock.readLock();try{return yield i.child.put(t,r,o)}finally{a()}}))()}putMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(i){null==n||null===(i=n.signal)||void 0===i||i.throwIfAborted();var o=yield e._awaitAsyncGenerator(r.lock.readLock());try{yield*e._asyncGeneratorDelegate(e._asyncIterator(r.child.putMany(t,n)),e._awaitAsyncGenerator)}finally{o()}}()})).apply(this,arguments)}get(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e,i=r.length>1&&void 0!==r[1]?r[1]:{};null==i||null===(e=i.signal)||void 0===e||e.throwIfAborted();var o=yield n.lock.readLock();try{return yield n.child.get(t,i)}finally{o()}}))()}getMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(i){null==n||null===(i=n.signal)||void 0===i||i.throwIfAborted();var o=yield e._awaitAsyncGenerator(r.lock.readLock());try{yield*e._asyncGeneratorDelegate(e._asyncIterator(r.child.getMany(t,n)),e._awaitAsyncGenerator)}finally{o()}}()})).apply(this,arguments)}delete(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e,i=r.length>1&&void 0!==r[1]?r[1]:{};null==i||null===(e=i.signal)||void 0===e||e.throwIfAborted();var o=yield n.lock.writeLock();try{if(yield n.pins.isPinned(t))throw new Error("CID was pinned");yield n.child.delete(t,i)}finally{o()}}))()}deleteMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(i){null==n||null===(i=n.signal)||void 0===i||i.throwIfAborted();var o=yield e._awaitAsyncGenerator(r.lock.writeLock());try{var a=r;yield*e._asyncGeneratorDelegate(e._asyncIterator(r.child.deleteMany(e._wrapAsyncGenerator((function*(){var r,n=!1,i=!1;try{for(var o,s=e._asyncIterator(t);n=!(o=yield e._awaitAsyncGenerator(s.next())).done;n=!1){var l=o.value;if(yield e._awaitAsyncGenerator(a.pins.isPinned(l)))throw new Error("CID was pinned");yield l}}catch(e){i=!0,r=e}finally{try{n&&null!=s.return&&(yield e._awaitAsyncGenerator(s.return()))}finally{if(i)throw r}}}))(),n)),e._awaitAsyncGenerator)}finally{o()}}()})).apply(this,arguments)}has(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e,i=r.length>1&&void 0!==r[1]?r[1]:{};null==i||null===(e=i.signal)||void 0===e||e.throwIfAborted();var o=yield n.lock.readLock();try{return yield n.child.has(t,i)}finally{o()}}))()}getAll(){var t=this;return e._wrapAsyncGenerator((function(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(n){null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted();var i=yield e._awaitAsyncGenerator(t.lock.readLock());try{yield*e._asyncGeneratorDelegate(e._asyncIterator(t.child.getAll(r)),e._awaitAsyncGenerator)}finally{i()}}()})).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 rB=new xc("/version");function nB(){return(nB=e._asyncToGenerator((function*(e){if(yield e.has(rB)){var t=Ze(yield e.get(rB));if(1!==parseInt(t,10))throw new Error("Unknown datastore version, a datastore migration may be required")}else yield e.put(rB,nt("".concat(1)))}))).apply(this,arguments)}function iB(e){return e instanceof ArrayBuffer?new Uint8Array(e,0,e.byteLength):e}var oB={float64:!0,typeEncoders:{Object:function(e){if(e.asCID!==e&&e["/"]!==e.bytes)return null;var t=je.asCID(e);if(!t)return null;var r=new Uint8Array(t.bytes.byteLength+1);return r.set(t.bytes,1),[new ET(PT.tag,42),new ET(PT.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}}},aB=e._objectSpread2(e._objectSpread2({},oB),{},{typeEncoders:e._objectSpread2({},oB.typeEncoders)});var sB={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};sB.tags[42]=function(e){if(0!==e[0])throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return je.decode(e.subarray(1))};var lB=e._objectSpread2(e._objectSpread2({},sB),{},{tags:sB.tags.slice()}),cB="dag-cbor",uB=113,dB=e=>JI(e,oB),hB=e=>rC(iB(e),sB),pB=Object.freeze({__proto__:null,code:uB,decode:hB,decodeOptions:lB,encode:dB,encodeOptions:aB,name:cB,toByteView:iB});class fB extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){var t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===PT.array&&(t.elements++,1!==t.elements&&e.push([44])),t.type===PT.map&&(t.elements++,1!==t.elements&&(t.elements%2==1?e.push([44]):e.push([58]))))}[PT.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)}[PT.negint.major](e,t){this[PT.uint.major](e,t)}[PT.bytes.major](e,t){throw new Error("".concat(zT," unsupported type: Uint8Array"))}[PT.string.major](e,t){this.prefix(e);var r=BT(JSON.stringify(t.value));e.push(r.length>32?IT(r):r)}[PT.array.major](e,t){this.prefix(e),this.inRecursive.push({type:PT.array,elements:0}),e.push([91])}[PT.map.major](e,t){this.prefix(e),this.inRecursive.push({type:PT.map,elements:0}),e.push([123])}[PT.tag.major](e,t){}[PT.float.major](e,t){if("break"===t.type.name){var r=this.inRecursive.pop();if(r){if(r.type===PT.array)e.push([93]);else{if(r.type!==PT.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(zT," 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 vB={addBreakTokens:!0,mapSorter:function(e,t){if(Array.isArray(e[0])||Array.isArray(t[0]))throw new Error("".concat(zT," complex map keys are not supported"));var r=e[0],n=t[0];if(r.type!==PT.string||n.type!==PT.string)throw new Error("".concat(zT," non-string map keys are not supported"));if(r<n)return-1;if(r>n)return 1;throw new Error("".concat(zT," unexpected duplicate map keys, this is not supported"))}};class yB{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(UT," 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(UT," 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 ET(PT.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(UT," unexpected token at position ").concat(this._pos));if(!this.done()&&46===this.ch()){if(r)throw new Error("".concat(UT," 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 ET(PT.float,o,this._pos-e):!0!==this.options.allowBigInt||Number.isSafeInteger(o)?new ET(o>=0?PT.uint:PT.negint,o,this._pos-e):new ET(o>=0?PT.uint:PT.negint,BigInt(i),this._pos-e)}parseString(){if(34!==this.ch())throw new Error("".concat(UT," 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 ET(PT.string,n,t)}}for(var i=this._pos,o=[],a=()=>{if(this._pos+4>=this.data.length)throw new Error("".concat(UT," 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(UT," 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(UT," 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(),c=void 0;switch(l){case 92:if(this._pos++,this.done())throw new Error("".concat(UT," unexpected string termination at position ").concat(this._pos));switch(c=this.ch(),this._pos++,c){case 34:case 39:case 92:case 47:o.push(c);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(UT," unexpected string escape character at position ").concat(this._pos))}break;case 34:return this._pos++,new ET(PT.string,jT(o),this._pos-i);default:if(l<32)throw new Error("".concat(UT," invalid control character at position ").concat(this._pos));l<128?(o.push(l),this._pos++):s()}}throw new Error("".concat(UT," unexpected end of string at position ").concat(this._pos))}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new ET(PT.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new ET(PT.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new ET(PT.null,null,4);case 102:return this.expect([102,97,108,115,101]),new ET(PT.false,!1,5);case 116:return this.expect([116,114,117,101]),new ET(PT.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(UT," 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 ET(PT.break,void 0,1);if(44!==this.ch())throw new Error("".concat(UT," 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 ET(PT.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 ET(PT.break,void 0,1);if(44!==this.ch())throw new Error("".concat(UT," 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 ET(PT.break,void 0,1);var e=this.parseString();if(this.skipWhitespace(),58!==this.ch())throw new Error("".concat(UT," 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(UT," unexpected parse state at position ").concat(this._pos,"; this shouldn't happen"))}}}function gB(e){var t=z.encode(e).slice(1);return[new ET(PT.map,1/0,1),new ET(PT.string,"/",1),new ET(PT.map,1/0,1),new ET(PT.string,"bytes",5),new ET(PT.string,t,t.length),new ET(PT.break,void 0,1),new ET(PT.break,void 0,1)]}function mB(e){return gB(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}var wB={typeEncoders:{Object:function(e){if(e.asCID!==e&&e["/"]!==e.bytes)return null;var t=je.asCID(e);if(!t)return null;var r=t.toString();return[new ET(PT.map,1/0,1),new ET(PT.string,"/",1),new ET(PT.string,r,r.length),new ET(PT.break,void 0,1)]},Buffer:gB,Uint8Array:gB,Int8Array:mB,Uint16Array:mB,Int16Array:mB,Uint32Array:mB,Int32Array:mB,Float32Array:mB,Float64Array:mB,Uint8ClampedArray:mB,BigInt64Array:mB,BigUint64Array:mB,DataView:mB,ArrayBuffer:function(e){return gB(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 bB extends yB{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===PT.map){var t=this._next();if(t.type===PT.string&&"/"===t.value){var r=this._next();if(r.type===PT.string){if(this._next().type!==PT.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(r),new ET(PT.tag,42,0)}if(r.type===PT.map){var n=this._next();if(n.type===PT.string&&"bytes"===n.value){var i=this._next();if(i.type===PT.string){for(var o=0;o<2;o++){if(this._next().type!==PT.break)throw new Error("Invalid encoded Bytes form")}var a=z.decode("m".concat(i.value));return new ET(PT.bytes,a,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(r)}this.tokenBuffer.push(t)}return e}}var _B={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};_B.tags[42]=je.parse;var SB=297,PB=e=>function(e,t){return t=Object.assign({},vB,t),YI(e,new fB,t)}(e,wB),EB=e=>{var t=function(e){return e instanceof ArrayBuffer?new Uint8Array(e,0,e.byteLength):e}(e);return function(e,t){return rC(e,t=Object.assign({tokenizer:new yB(e,t)},t))}(t,Object.assign(_B,{tokenizer:new bB(t,_B)}))},AB=e=>kB.decode(PB(e)),kB=new TextDecoder,xB=new TextEncoder,TB=Object.freeze({__proto__:null,code:297,decode:EB,encode:PB,format:AB,name:"dag-json",parse:e=>EB(xB.encode(e)),stringify:AB}),IB=new TextDecoder;function CB(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 BB(e,t){var r;[r,t]=CB(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 NB(e,t){var r;return[r,t]=CB(e,t),[7&r,r>>3,t]}function DB(e){for(var t={},r=e.length,n=0;n<r;){var i=void 0,o=void 0;if([i,o,n]=NB(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]=BB(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]=BB(e,n),t.Name=IB.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]=CB(e,n)}}if(n>r)throw new Error("protobuf: (PBLink) unexpected end of data");return t}var GB=new TextEncoder,RB=2**32,OB=2**31;function LB(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=FB(t,r,e.Tsize)-1]=24}if("string"==typeof e.Name){var n=GB.encode(e.Name);r-=n.length,t.set(n,r),t[r=FB(t,r,n.length)-1]=18}return e.Hash&&(r-=e.Hash.length,t.set(e.Hash,r),t[r=FB(t,r,e.Hash.length)-1]=10),t.length-r}function MB(e){var t=function(e){var t=0;if(e.Data){var r=e.Data.length;t+=1+r+UB(r)}if(e.Links)for(var n of e.Links){var i=jB(n);t+=1+i+UB(i)}return t}(e),r=new Uint8Array(t),n=t;if(e.Data&&(n-=e.Data.length,r.set(e.Data,n),r[n=FB(r,n,e.Data.length)-1]=10),e.Links)for(var i=e.Links.length-1;i>=0;i--){var o=LB(e.Links[i],r.subarray(0,n));r[n=FB(r,n-=o,o)-1]=18}return r}function jB(e){var t=0;if(e.Hash){var r=e.Hash.length;t+=1+r+UB(r)}if("string"==typeof e.Name){var n=GB.encode(e.Name).length;t+=1+n+UB(n)}return"number"==typeof e.Tsize&&(t+=1+UB(e.Tsize)),t}function FB(e,t,r){for(var n=t-=UB(r);r>=OB;)e[t++]=127&r|128,r/=128;for(;r>=128;)e[t++]=127&r|128,r>>>=7;return e[t]=r,n}function UB(e){return e%2==0&&e++,Math.floor((function(e){var t=0;e>=RB&&(e=Math.floor(e/RB),t=32);e>=65536&&(e>>>=16,t+=16);e>=256&&(e>>>=8,t+=8);return t+zB[e]}(e)+6)/7)}var zB=[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],VB=["Data","Links"],qB=["Hash","Name","Tsize"],HB=new TextEncoder;function KB(e,t){if(e===t)return 0;for(var r=e.Name?HB.encode(e.Name):[],n=t.Name?HB.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 WB(e,t){return!Object.keys(e).some((e=>!t.includes(e)))}function QB(e){if("object"==typeof e.asCID){var t=je.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=je.asCID(e.Hash);try{n||("string"==typeof e.Hash?n=je.parse(e.Hash):e.Hash instanceof Uint8Array&&(n=je.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 YB(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=HB.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(QB),t.Links.sort(KB)}else t.Links=[];return t}function JB(e){if(!e||"object"!=typeof e||Array.isArray(e)||e instanceof Uint8Array||e["/"]&&e["/"]===e.bytes)throw new TypeError("Invalid DAG-PB form");if(!WB(e,VB))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(!WB(r,qB))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===KB(r,e.Links[t-1]))throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}var ZB=112;function $B(e){JB(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),MB(t)}function XB(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]=NB(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]=BB(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]=BB(e,r),n.push(DB(l))}}if(r>t)throw new Error("protobuf: (PBNode) unexpected end of data");var c={};return o&&(c.Data=o),c.Links=n||[],c}(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=je.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 eN=Object.freeze({__proto__:null,code:ZB,createLink:function(e,t,r){return QB({Hash:r,Name:e,Tsize:t})},createNode:function(e){return YB({Data:e,Links:arguments.length>1&&void 0!==arguments[1]?arguments[1]:[]})},decode:XB,encode:$B,name:"dag-pb",prepare:YB,validate:JB});function tN(e){return null!=(null==e?void 0:e.then)}class rN extends Tu{constructor(t){super(),e._defineProperty(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 Uc;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 nN{constructor(t){e._defineProperty(this,"child",void 0),e._defineProperty(this,"getHasher",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"components",void 0),this.log=t.logger.forComponent("helia:networked-storage"),this.logger=t.logger,this.components=t,this.child=new rN(t.blockstore),this.getHasher=t.getHasher}put(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var o,a,s,l=n.length>2&&void 0!==n[2]?n[2]:{};return(yield i.child.has(t,l))?(null===(s=l.onProgress)||void 0===s||s.call(l,new Ah("blocks:put:duplicate",t)),t):(null===(o=l.onProgress)||void 0===o||o.call(l,new Ah("blocks:put:providers:notify",t)),yield Promise.all(i.components.blockBrokers.map(function(){var n=e._asyncToGenerator((function*(e){var n;return null===(n=e.announce)||void 0===n?void 0:n.call(e,t,r,l)}));return function(e){return n.apply(this,arguments)}}())),null===(a=l.onProgress)||void 0===a||a.call(l,new Ah("blocks:put:blockstore:put",t)),i.child.put(t,r,l))}))()}putMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(i){var o=Cc(t,function(){var t=e._asyncToGenerator((function*(e){var t,{cid:i}=e,o=yield r.child.has(i,n);o&&(null===(t=n.onProgress)||void 0===t||t.call(n,new Ah("blocks:put-many:duplicate",i)));return!o}));return function(e){return t.apply(this,arguments)}}()),a=Ph(o,function(){var t=e._asyncToGenerator((function*(t){var i,{cid:o,block:a}=t;null===(i=n.onProgress)||void 0===i||i.call(n,new Ah("blocks:put-many:providers:notify",o)),yield Promise.all(r.components.blockBrokers.map(function(){var t=e._asyncToGenerator((function*(e){var t;return null===(t=e.announce)||void 0===t?void 0:t.call(e,o,a,n)}));return function(e){return t.apply(this,arguments)}}()))}));return function(e){return t.apply(this,arguments)}}());null===(i=n.onProgress)||void 0===i||i.call(n,new Ah("blocks:put-many:blockstore:put-many")),yield*e._asyncGeneratorDelegate(e._asyncIterator(r.child.putMany(a,n)))}()})).apply(this,arguments)}get(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i,o=r.length>1&&void 0!==r[1]?r[1]:{};if(!0!==o.offline&&!(yield n.child.has(t,o))){var a,s,l,c=yield n.getHasher(t.multihash.code);null===(a=o.onProgress)||void 0===a||a.call(o,new Ah("blocks:get:providers:get",t));var u=yield lN(t,n.components.blockBrokers,c,e._objectSpread2(e._objectSpread2({},o),{},{log:n.log}));return null===(s=o.onProgress)||void 0===s||s.call(o,new Ah("blocks:get:blockstore:put",t)),yield n.child.put(t,u,o),null===(l=o.onProgress)||void 0===l||l.call(o,new Ah("blocks:get:providers:notify",t)),yield Promise.all(n.components.blockBrokers.map(function(){var r=e._asyncToGenerator((function*(e){var r;return null===(r=e.announce)||void 0===r?void 0:r.call(e,t,u,o)}));return function(e){return r.apply(this,arguments)}}())),u}return null===(i=o.onProgress)||void 0===i||i.call(o,new Ah("blocks:get:blockstore:get",t)),n.child.get(t,o)}))()}getMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(i){null===(i=n.onProgress)||void 0===i||i.call(n,new Ah("blocks:get-many:blockstore:get-many")),yield*e._asyncGeneratorDelegate(e._asyncIterator(r.child.getMany(Ph(t,function(){var t=e._asyncToGenerator((function*(t){if(!0!==n.offline&&!(yield r.child.has(t,n))){var i,o,a,s=yield r.getHasher(t.multihash.code);null===(i=n.onProgress)||void 0===i||i.call(n,new Ah("blocks:get-many:providers:get",t));var l=yield lN(t,r.components.blockBrokers,s,e._objectSpread2(e._objectSpread2({},n),{},{log:r.log}));null===(o=n.onProgress)||void 0===o||o.call(n,new Ah("blocks:get-many:blockstore:put",t)),yield r.child.put(t,l,n),null===(a=n.onProgress)||void 0===a||a.call(n,new Ah("blocks:get-many:providers:notify",t)),yield Promise.all(r.components.blockBrokers.map(function(){var r=e._asyncToGenerator((function*(e){var r;return null===(r=e.announce)||void 0===r?void 0:r.call(e,t,l,n)}));return function(e){return r.apply(this,arguments)}}()))}}));return function(e){return t.apply(this,arguments)}}()))))}()})).apply(this,arguments)}delete(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e,i=r.length>1&&void 0!==r[1]?r[1]:{};null===(e=i.onProgress)||void 0===e||e.call(i,new Ah("blocks:delete:blockstore:delete",t)),yield n.child.delete(t,i)}))()}deleteMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(i){null===(i=n.onProgress)||void 0===i||i.call(n,new Ah("blocks:delete-many:blockstore:delete-many")),yield*e._asyncGeneratorDelegate(e._asyncIterator(r.child.deleteMany(e._wrapAsyncGenerator((function*(){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t);n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var s=o.value;yield s}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw r}}}))(),n)))}()})).apply(this,arguments)}has(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};return n.child.has(t,e)}))()}getAll(){var t=this;return e._wrapAsyncGenerator((function(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(n){null===(n=r.onProgress)||void 0===n||n.call(r,new Ah("blocks:get-all:blockstore:get-many")),yield*e._asyncGeneratorDelegate(e._asyncIterator(t.child.getAll(r)))}()})).apply(this,arguments)}}class iN extends nN{constructor(t){super(t),e._defineProperty(this,"started",void 0),this.started=!1}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){yield xa(t.child,...t.components.blockBrokers),t.started=!0}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield Ia(t.child,...t.components.blockBrokers),t.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 oN({blockstore:this.child,blockBrokers:r,getHasher:this.getHasher,logger:this.logger},{root:e})}}class oN extends nN{constructor(t,r){super(t),e._defineProperty(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(t,r){var n=arguments,i=()=>super.put,o=this;return e._asyncToGenerator((function*(){var a=n.length>2&&void 0!==n[2]?n[2]:{},s=Qd([o.closeController.signal,a.signal]);try{return yield i().call(o,t,r,e._objectSpread2(e._objectSpread2({},a),{},{signal:s}))}finally{s.clear()}}))()}putMany(t){var r=()=>super.putMany,n=this;return e._wrapAsyncGenerator((function(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var o=Qd([n.closeController.signal,i.signal]);try{yield*e._asyncGeneratorDelegate(e._asyncIterator(r().call(n,t,e._objectSpread2(e._objectSpread2({},i),{},{signal:o}))),e._awaitAsyncGenerator)}finally{o.clear()}}()})).apply(this,arguments)}get(t){var r=arguments,n=()=>super.get,i=this;return e._asyncToGenerator((function*(){var o=r.length>1&&void 0!==r[1]?r[1]:{},a=Qd([i.closeController.signal,o.signal]);try{return yield n().call(i,t,e._objectSpread2(e._objectSpread2({},o),{},{signal:a}))}finally{a.clear()}}))()}getMany(t){var r=()=>super.getMany,n=this;return e._wrapAsyncGenerator((function(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var o=Qd([n.closeController.signal,i.signal]);try{yield*e._asyncGeneratorDelegate(e._asyncIterator(r().call(n,t,e._objectSpread2(e._objectSpread2({},i),{},{signal:o}))),e._awaitAsyncGenerator)}finally{o.clear()}}()})).apply(this,arguments)}delete(t){var r=arguments,n=()=>super.delete,i=this;return e._asyncToGenerator((function*(){var o=r.length>1&&void 0!==r[1]?r[1]:{},a=Qd([i.closeController.signal,o.signal]);try{yield n().call(i,t,e._objectSpread2(e._objectSpread2({},o),{},{signal:a}))}finally{a.clear()}}))()}deleteMany(t){var r=()=>super.deleteMany,n=this;return e._wrapAsyncGenerator((function(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var o=Qd([n.closeController.signal,i.signal]);try{yield*e._asyncGeneratorDelegate(e._asyncIterator(r().call(n,t,e._objectSpread2(e._objectSpread2({},i),{},{signal:o}))),e._awaitAsyncGenerator)}finally{o.clear()}}()})).apply(this,arguments)}has(t){var r=arguments,n=()=>super.has,i=this;return e._asyncToGenerator((function*(){var o=r.length>1&&void 0!==r[1]?r[1]:{},a=Qd([i.closeController.signal,o.signal]);try{return yield n().call(i,t,e._objectSpread2(e._objectSpread2({},o),{},{signal:a}))}finally{a.clear()}}))()}getAll(){var t=()=>super.getAll,r=this;return e._wrapAsyncGenerator((function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i=Qd([r.closeController.signal,n.signal]);try{yield*e._asyncGeneratorDelegate(e._asyncIterator(t().call(r,e._objectSpread2(e._objectSpread2({},n),{},{signal:i}))),e._awaitAsyncGenerator)}finally{i.clear()}}()})).apply(this,arguments)}}function aN(e){return"function"==typeof e.retrieve}var sN=(t,r)=>{if(null==r)throw new Jo("No hasher configured for multihash code 0x".concat(t.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=e._asyncToGenerator((function*(e){var n=r.digest(e);if(!rt((tN(n)?yield n:n).digest,t.multihash.digest))throw new ua("Hash of downloaded block did not match multihash from passed CID")}));return function(e){return n.apply(this,arguments)}}()};function lN(e,t,r,n){return cN.apply(this,arguments)}function cN(){return cN=e._asyncToGenerator((function*(t,r,n,i){var o=sN(t,n),a=new AbortController,s=Qd([a.signal,i.signal]);a.signal;var l=[];for(var c of r)aN(c)&&l.push(c);try{return yield Promise.any(l.map(function(){var r=e._asyncToGenerator((function*(r){try{var n=!1,a=yield r.retrieve(t,e._objectSpread2(e._objectSpread2({},i),{},{signal:s,validateFn:(l=e._asyncToGenerator((function*(e){yield o(e),n=!0})),function(e){return l.apply(this,arguments)})}));return n||(yield o(a)),a}catch(e){throw i.log.error("could not retrieve verified block for %c",t,e),e}var l}));return function(e){return r.apply(this,arguments)}}()))}finally{a.abort(),s.clear()}})),cN.apply(this,arguments)}class uN extends Aa{constructor(t,r){var n,i,o;super(),e._defineProperty(this,"initialPeerSearchComplete",void 0),e._defineProperty(this,"requests",void 0),e._defineProperty(this,"name",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"minProviders",void 0),e._defineProperty(this,"maxProviders",void 0),e._defineProperty(this,"providers",void 0),e._defineProperty(this,"evictionFilter",void 0),e._defineProperty(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=gh(this.maxProviders),this.initialProviders=null!==(o=r.providers)&&void 0!==o?o:[]}retrieve(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i,o=r.length>1&&void 0!==r[1]?r[1]:{},a=z.encode(t.multihash.bytes),s=n.requests.get(a);if(null!=s)return n.log("join existing request for %c",t),s;var l=Hc();if(n.requests.set(a,l.promise),0===n.providers.length){var c=!1;null==n.initialPeerSearchComplete&&(c=!0,n.log=n.logger.forComponent("".concat(n.name,":").concat(t)),n.initialPeerSearchComplete=n.findProviders(t,n.minProviders,o)),yield n.initialPeerSearchComplete,c&&n.log("found initial session peers for %c",t)}var u=!1,d=new Gh({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=>{u=!0,l.resolve(e.detail.result)})),d.addEventListener("idle",(()=>{var r;u||!0===(null===(r=o.signal)||void 0===r?void 0:r.aborted)?n.log.trace("session idle, found block"):Promise.resolve().then(e._asyncToGenerator((function*(){n.log("no session peers had block for for %c, finding new providers",t);for(var e=0;e<n.minProviders&&0!==n.providers.length;e++){var r=n.providers[Math.floor(Math.random()*n.providers.length)];n.evict(r)}yield n.findProviders(t,n.minProviders,o),n.log("found new providers re-retrieving %c",t),n.requests.delete(a),l.resolve(yield n.retrieve(t,o))}))).catch((e=>{n.log.error("could not find new providers for %c",t,e),l.reject(e)}))}));var h=r=>{d.add(e._asyncToGenerator((function*(){return n.queryProvider(t,r.detail,o)})),{provider:r.detail}).catch((e=>{var r;!0!==(null===(r=o.signal)||void 0===r?void 0:r.aborted)&&n.log.error("error retrieving session block for %c",t,e)}))};n.addEventListener("provider",h),Promise.all([...n.providers].map(function(){var r=e._asyncToGenerator((function*(r){return d.add(e._asyncToGenerator((function*(){return n.queryProvider(t,r,o)})),{provider:r})}));return function(e){return r.apply(this,arguments)}}())).catch((e=>{var r;!0!==(null===(r=o.signal)||void 0===r?void 0:r.aborted)&&n.log.error("error retrieving session block for %c",t,e)}));var p=()=>{var e,t;l.reject(new Wo(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",p);try{return yield l.promise}finally{var f;n.removeEventListener("provider",h),null===(f=o.signal)||void 0===f||f.removeEventListener("abort",p),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(t,r,n){var i=this;return e._asyncToGenerator((function*(){var o=Hc(),a=0;return Promise.resolve().then(e._asyncToGenerator((function*(){if(i.log("finding %d-%d new provider(s) for %c",r,i.maxProviders,t),i.initialProviders.length>0)for(;a<r&&i.initialProviders.length>0;){var s,l=i.initialProviders.pop();if(null==l)break;var c=yield i.convertToProvider(l,n);if(!0===(null===(s=n.signal)||void 0===s?void 0:s.aborted))break;if(null!=c&&(!i.hasProvider(c)&&(i.log("found %d/%d new providers",a,i.maxProviders),i.providers.push(c),i.safeDispatchEvent("provider",{detail:c}),++a===r&&(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 u,d=!1,h=!1;try{for(var p,f=e._asyncIterator(i.findNewProviders(t,n));d=!(p=yield f.next()).done;d=!1){var v,y=p.value;if(a===i.maxProviders||!0===(null===(v=n.signal)||void 0===v?void 0:v.aborted))break;if(!i.hasProvider(y)&&(i.log("found %d/%d new providers",a,i.maxProviders),i.providers.push(y),i.safeDispatchEvent("provider",{detail:y}),++a===r&&(i.log("session is ready"),o.resolve()),i.providers.length===i.maxProviders)){i.log("found max session peers",a);break}}}catch(e){h=!0,u=e}finally{try{d&&null!=f.return&&(yield f.return())}finally{if(h)throw u}}}if(i.log("found %d/%d new session peers",a,i.maxProviders),a<r)throw new mC("Found ".concat(a," of ").concat(r," ").concat(i.name," providers for ").concat(t))}))).catch((e=>{var r;i.log.error("error searching routing for potential session peers for %c",t,null!==(r=e.errors)&&void 0!==r?r:e),o.reject(e)})),o.promise}))()}}class dN{constructor(t){var r,n,i,o,a;e._defineProperty(this,"blockstore",void 0),e._defineProperty(this,"datastore",void 0),e._defineProperty(this,"pins",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"routing",void 0),e._defineProperty(this,"getCodec",void 0),e._defineProperty(this,"getHasher",void 0),e._defineProperty(this,"dns",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"log",void 0),this.logger=null!==(r=t.logger)&&void 0!==r?r:Au(),this.log=this.logger.forComponent("helia"),this.getHasher=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],r=arguments.length>1?arguments[1]:void 0,n={[De.code]:De,[Ge.code]:Ge,[Te.code]:Te};return t.forEach((e=>{n[e.code]=e})),function(){var t=e._asyncToGenerator((function*(e){var t=n[e];if(null==t&&null!=r){var i=r(e);t=tN(i)?yield i:i,n[t.code]=t}if(null!=t)return t;throw new bC("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(e){return t.apply(this,arguments)}}()}(t.hashers,t.loadHasher),this.getCodec=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],r=arguments.length>1?arguments[1]:void 0,n={[ZB]:eN,[re]:ne,[uB]:pB,[SB]:TB,[X]:te};return t.forEach((e=>{n[e.code]=e})),function(){var t=e._asyncToGenerator((function*(e){var t=n[e];if(null==t&&null!=r){var i=r(e);t=tN(i)?yield i:i,n[t.code]=t}if(null!=t)return t;throw new _C("Could not load codec for ".concat(e))}));return function(e){return t.apply(this,arguments)}}()}(t.codecs,t.loadCodec),this.dns=null!==(n=t.dns)&&void 0!==n?n:wT(),this.metrics=t.metrics;var s=e._objectSpread2({blockstore:t.blockstore,datastore:t.datastore,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics},null!==(i=t.components)&&void 0!==i?i:{});this.routing=s.routing=new SC(s,{routers:(null!==(o=t.routers)&&void 0!==o?o:[]).flatMap((e=>{var t=[e];return null!=e[jo]&&t.push(e[jo]),null!=e[qo]&&t.push(e[qo]),t})),providerLookupConcurrency:t.providerLookupConcurrency});var l=new iN(s);this.pins=new fC(t.datastore,l,this.getCodec),this.blockstore=new tB(l,this.pins,{holdGcLock:null===(a=t.holdGcLock)||void 0===a||a}),this.datastore=t.datastore,s.blockBrokers=t.blockBrokers.map((e=>e(s)))}start(){var t=this;return e._asyncToGenerator((function*(){yield function(e){return nB.apply(this,arguments)}(t.datastore),yield xa(t.blockstore,t.datastore,t.routing)}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield Ia(t.blockstore,t.datastore,t.routing)}))()}gc(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var n=t.length>0&&void 0!==t[0]?t[0]:{},i=yield r.blockstore.lock.writeLock();try{var o=r,a=r.blockstore.unwrap();r.log("gc start"),yield Tc(a.deleteMany(e._wrapAsyncGenerator((function*(){var t,r=!1,i=!1;try{for(var s,l=e._asyncIterator(a.getAll());r=!(s=yield e._awaitAsyncGenerator(l.next())).done;r=!1){var{cid:c}=s.value;try{var u;if(yield e._awaitAsyncGenerator(o.pins.isPinned(c,n)))continue;yield c,null===(u=n.onProgress)||void 0===u||u.call(n,new Ah("helia:gc:deleted",c))}catch(e){var d;o.log.error("Error during gc",e),null===(d=n.onProgress)||void 0===d||d.call(n,new Ah("helia:gc:error",e))}}}catch(e){i=!0,t=e}finally{try{r&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(i)throw t}}}))()))}finally{i()}r.log("gc finished")}))()}}class hN extends uN{constructor(t,r){super(t,e._objectSpread2(e._objectSpread2({},r),{},{name:"helia:bitswap:session"})),e._defineProperty(this,"wantList",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"libp2p",void 0),this.wantList=t.wantList,this.network=t.network,this.libp2p=t.libp2p}queryProvider(t,r,n){var i=this;return e._asyncToGenerator((function*(){i.log("sending WANT-BLOCK for %c to %p",t,r);var e=yield i.wantList.wantSessionBlock(t,r,n);if(i.log("%p %s %c",r,e.has?"has":"does not have",t),e.has&&null!=e.block)return e.block;throw new Error("Provider did not have block")}))()}findNewProviders(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(r.network.findProviders(t,n));o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;yield c.id}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}()})).apply(this,arguments)}toEvictionKey(e){return e.toMultihash().bytes}equals(e,t){return e.equals(t)}convertToProvider(t,r){var n=this;return e._asyncToGenerator((function*(){return zo(t)?t:(yield n.libp2p.dial(t,r)).remotePeer}))()}}class pN{constructor(t){var r,n,i,o;e._defineProperty(this,"blocksReceived",void 0),e._defineProperty(this,"duplicateBlocksReceived",void 0),e._defineProperty(this,"dataReceived",void 0),e._defineProperty(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 fN extends Map{constructor(t){super(),e._defineProperty(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 vN(e){var{name:t,metrics:r}=e;return null!=r?new fN({name:t,metrics:r}):new Map}function yN(e){if(!(e instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");for(var t=[];e.length>0;){var r=gt(e);t.push(r),e=e.slice(pt(r))}return t}class gN extends Aa{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),e._defineProperty(this,"peers",void 0),e._defineProperty(this,"wants",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"sendMessagesDelay",void 0),e._defineProperty(this,"sendMessagesTimeout",void 0),e._defineProperty(this,"hashLoader",void 0),e._defineProperty(this,"sendingMessages",void 0),this.peers=_h({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=vN({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(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i,o=Ze(t.multihash.bytes,"base64"),a=n.wants.get(o);null==a&&(a={cid:t,priority:null!==(e=r.priority)&&void 0!==e?e:1,wantType:null!==(i=r.wantType)&&void 0!==i?i:lx.WantBlock,cancel:!1,sendDontHave:!0},n.wants.set(o,a));a.wantType===lx.WantHave&&r.wantType===lx.WantBlock&&(a.wantType=lx.WantBlock),yield n.sendMessagesDebounced();try{if(r.wantType===lx.WantBlock){var s=yield xh(n,"block",null==r?void 0:r.signal,{filter:e=>rt(t.multihash.digest,e.detail.cid.multihash.digest),errorMessage:"Want was aborted"});return s.detail}return(yield xh(n,"presence",null==r?void 0:r.signal,{filter:e=>rt(t.multihash.digest,e.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{var l;!0===(null===(l=r.signal)||void 0===l?void 0:l.aborted)&&(n.log("want for %c was aborted, cancelling want",t),a.cancel=!0,yield n.sendMessagesDebounced())}}))()}sendMessagesDebounced(){var t=this;return e._asyncToGenerator((function*(){var e;yield null===(e=t.sendingMessages)||void 0===e?void 0:e.promise,clearTimeout(t.sendMessagesTimeout),t.sendMessagesTimeout=setTimeout((()=>{t.sendMessages().catch((e=>{t.log("error sending messages to peers",e)}))}),t.sendMessagesDelay)}))()}sendMessages(){var t=this;return e._asyncToGenerator((function*(){for(var[r,n]of(t.sendingMessages=Hc(),yield Promise.all([...t.peers.entries()].map(function(){var r=e._asyncToGenerator((function*(e){var[r,n]=e,i=new Set,o=new xx;for(var[a,s]of t.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 t.network.sendMessage(r,o),i))n.add(l)}catch(e){t.log.error("error sending full wantlist to new peer",e)}}));return function(e){return r.apply(this,arguments)}}())).catch((e=>{t.log.error("error sending messages",e)})),t.wants))if(n.cancel)for(var i of(t.wants.delete(r),t.peers.values()))i.delete(r);t.sendingMessages.resolve()}))()}has(e){var t=Ze(e.multihash.bytes,"base64");return this.wants.has(t)}wantSessionPresence(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var e=n.length>2&&void 0!==n[2]?n[2]:{},o=new xx;return o.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:lx.WantHave,priority:1}),yield i.network.sendMessage(r,o),(yield xh(i,"presence",e.signal,{filter:e=>r.equals(e.detail.sender)&&rt(t.multihash.digest,e.detail.cid.multihash.digest)})).detail}))()}wantBlock(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{};return n.addEntry(t,e._objectSpread2(e._objectSpread2({},i),{},{wantType:lx.WantBlock}))}))()}wantSessionBlock(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var e=n.length>2&&void 0!==n[2]?n[2]:{},o=new xx;return o.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:lx.WantBlock,priority:1}),yield i.network.sendMessage(r,o),(yield xh(i,"presence",e.signal,{filter:e=>r.equals(e.detail.sender)&&rt(t.multihash.digest,e.detail.cid.multihash.digest)})).detail}))()}receivedBlock(t,r){var n=this;return e._asyncToGenerator((function*(){var e=Ze(t.multihash.bytes,"base64"),r=n.wants.get(e);null!=r&&(r.cancel=!0,yield n.sendMessagesDebounced())}))()}receiveMessage(t,r){var n=this;return e._asyncToGenerator((function*(){n.log("received message from %p with %d blocks",t,r.blocks.length);var e=!1;for(var i of r.blocks){var o;if(null!=i.prefix&&null!=i.data){var a=yN(i.prefix),s=a[0],l=a[1],c=a[2],u=c===De.code?De:yield null===(o=n.hashLoader)||void 0===o?void 0:o.getHasher(c);if(null!=u){var d=u.digest(i.data);null!=d.then&&(d=yield d);var h=je.create(0===s?0:1,l,d);n.log("received block from %p for %c",t,h),n.safeDispatchEvent("block",{detail:{sender:t,cid:h,block:i.data}}),n.safeDispatchEvent("presence",{detail:{sender:t,cid:h,has:!0,block:i.data}});var p=Ze(h.multihash.bytes,"base64"),f=n.wants.get(p);null!=f&&(f.cancel=!0,e=!0)}else n.log.error("unknown hash algorithm",c)}}for(var{cid:v,type:y}of r.blockPresences){var g=je.decode(v);n.log("received %s from %p for %c",y,t,g),n.safeDispatchEvent("presence",{detail:{sender:t,cid:g,has:y===px.HaveBlock}})}e&&(yield n.sendMessagesDebounced())}))()}peerConnected(t){var r=this;return e._asyncToGenerator((function*(){var e=new Set,n=new xx(!0);for(var[i,o]of r.wants.entries())o.cancel||(e.add(i),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:lx.WantBlock,cancel:!1,sendDontHave:!1}));if(0!==n.wantlist.size)try{yield r.network.sendMessage(t,n),r.peers.set(t,e)}catch(e){r.log.error("error sending full wantlist to new peer %p",t,e)}else r.peers.set(t,e)}))()}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}}class mN{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"log",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"stats",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"blockstore",void 0),e._defineProperty(this,"peerWantLists",void 0),e._defineProperty(this,"wantList",void 0),e._defineProperty(this,"libp2p",void 0),this.logger=t.logger,this.log=t.logger.forComponent("helia:bitswap"),this.blockstore=t.blockstore,this.libp2p=t.libp2p,this.stats=new pN(t),this.network=new kx(t,r),this.peerWantLists=new Cx(e._objectSpread2(e._objectSpread2({},t),{},{network:this.network}),r),this.wantList=new gN(e._objectSpread2(e._objectSpread2({},t),{},{network:this.network}),r)}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 hN(e,t)}want(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{},o=new AbortController,a=Qd([o.signal,i.signal]);o.signal,n.network.findAndConnect(t,e._objectSpread2(e._objectSpread2({},i),{},{signal:a})).catch((e=>{o.signal.aborted||n.log.error("error during finding and connect for cid %c",t,e)}));try{return(yield n.wantList.wantBlock(t,e._objectSpread2(e._objectSpread2({},i),{},{signal:a}))).block}finally{o.abort(),a.clear()}}))()}notify(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var e=n.length>2&&void 0!==n[2]?n[2]:{};yield Promise.all([i.peerWantLists.receivedBlock(t,e),i.wantList.receivedBlock(t,e)])}))()}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 t=this;return e._asyncToGenerator((function*(){t.wantList.start(),yield t.network.start()}))()}stop(){var t=this;return e._asyncToGenerator((function*(){t.wantList.stop(),yield t.network.stop()}))()}}class wN{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"bitswap",void 0),e._defineProperty(this,"started",void 0);var n,{getHasher:i}=t;this.bitswap=function(e){return new mN(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}(t,e._objectSpread2({hashLoader:{getHasher:(n=e._asyncToGenerator((function*(e){return i(e)})),function(e){return n.apply(this,arguments)})}},r)),this.started=!1}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){yield t.bitswap.start(),t.started=!0}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield t.bitswap.stop(),t.started=!1}))()}announce(t,r,n){var i=this;return e._asyncToGenerator((function*(){yield i.bitswap.notify(t,r,n)}))()}retrieve(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};return n.bitswap.want(t,e)}))()}createSession(t){var r,n,i=this,o=this.bitswap.createSession(t);return{announce:(n=e._asyncToGenerator((function*(e,t,r){yield i.bitswap.notify(e,t,r)})),function(e,t,r){return n.apply(this,arguments)}),retrieve:(r=e._asyncToGenerator((function*(e,t){return o.retrieve(e,t)})),function(e,t){return r.apply(this,arguments)})}}}function bN(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new wN(t,e)}var _N,SN={};var PN=(_N||(_N=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,c;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")),c=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===c)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}(),SN.ip2long=a,SN.long2ip=s,SN.Netmask=e}.call(SN)),SN),EN=["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 PN.Netmask(e)));function AN(e){for(var t of EN)if(t.contains(e))return!0;return!1}function kN(e){return Pt(e)?AN(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 AN("".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 AN(t[t.length-1])}(e):Et(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 xN=[ir("tcp").code,ir("dns").code,ir("dnsaddr").code,ir("dns4").code,ir("dns6").code];function TN(e){var t;return null===(t=CN("sni",e))||void 0===t?void 0:t[1]}function IN(e){var t,r=null===(t=CN("tcp",e))||void 0===t?void 0:t[1];return null==r?"":":".concat(r)}function CN(e,t){var r;try{r=ir(e).code}catch(e){return}for(var[n,i]of t)if(n===r&&null!=i)return[n,i]}function BN(e){return e.some((e=>{var[t,r]=e;return t===ir("tls").code}))}function NN(e,t,r){var n=DN[ir(e).name];if(null==n)throw new Error("Can't interpret protocol ".concat(ir(e).name));var i=n(t,r);return e===ir("ip6").code?"[".concat(i,"]"):i}var DN={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(NN(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(NN(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(NN(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(NN(n[0],null!==(r=n[1])&&void 0!==r?r:"",t))},http:(e,t)=>{var r,n=BN(t),i=TN(t),o=IN(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=NN(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=NN(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 NN(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 NN(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=NN(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=BN(t),i=TN(t),o=IN(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=NN(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=NN(n[0],null!==(r=n[1])&&void 0!==r?r:"",t);return i=i.replace("tcp://",""),"wss://".concat(i)}};function GN(e,t){var r,n=nr(e).stringTuples(),i=n.pop();if(null==i)throw new Error("Unexpected end of multiaddr");var o=ir(i[0]),a=DN[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 xN.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 RN=new WeakMap,ON=new WeakMap,LN=new WeakMap,MN=new WeakMap,jN=new WeakMap,FN=new WeakSet;class UN{constructor(t,r){var{logger:n,transformRequestInit:i}=r;e._classPrivateMethodInitSpec(this,FN),e._defineProperty(this,"url",void 0),e._classPrivateFieldInitSpec(this,RN,0),e._classPrivateFieldInitSpec(this,ON,0),e._classPrivateFieldInitSpec(this,LN,0),e._classPrivateFieldInitSpec(this,MN,0),e._classPrivateFieldInitSpec(this,jN,new Map),e._defineProperty(this,"log",void 0),e._defineProperty(this,"transformRequestInit",void 0),this.url=t instanceof URL?t:new URL(t),this.transformRequestInit=i,this.log=n.forComponent("helia:trustless-gateway-block-broker:".concat(this.url.hostname))}getRawBlock(t,r){var n=this;return e._asyncToGenerator((function*(){var i=new URL(n.url.toString());if(i.pathname="/ipfs/".concat(t.toString()),i.search="?format=raw",!0===(null==r?void 0:r.aborted))throw new Error("Signal to fetch raw block for CID ".concat(t," from gateway ").concat(n.url," was aborted prior to fetch"));var o=e._assertClassBrand(FN,n,zN).call(n,t),a=new AbortController,s=()=>{a.abort()};null==r||r.addEventListener("abort",s);try{var l=e._classPrivateFieldGet2(jN,n).get(o);if(null==l){var c;e._classPrivateFieldSet2(RN,n,(c=e._classPrivateFieldGet2(RN,n),c++,c));var u={signal:a.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},d=null!=n.transformRequestInit?yield n.transformRequestInit(u):u;l=fetch(i.toString(),d).then(function(){var r=e._asyncToGenerator((function*(r){var o,a;if(n.log("GET %s %d",i,r.status),!r.ok)throw e._classPrivateFieldSet2(ON,n,(a=e._classPrivateFieldGet2(ON,n),a++,a)),new Error("unable to fetch raw block for CID ".concat(t," from gateway ").concat(n.url));return e._classPrivateFieldSet2(MN,n,(o=e._classPrivateFieldGet2(MN,n),o++,o)),new Uint8Array(yield r.arrayBuffer())}));return function(e){return r.apply(this,arguments)}}()),e._classPrivateFieldGet2(jN,n).set(o,l)}return yield l}catch(i){var h;if(!0===(null==r?void 0:r.aborted))throw new Error("fetching raw block for CID ".concat(t," from gateway ").concat(n.url," was aborted"));throw e._classPrivateFieldSet2(ON,n,(h=e._classPrivateFieldGet2(ON,n),++h)),new Error("unable to fetch raw block for CID ".concat(t))}finally{null==r||r.removeEventListener("abort",s),e._classPrivateFieldGet2(jN,n).delete(o)}}))()}reliability(){return 0===e._classPrivateFieldGet2(RN,this)?1:e._classPrivateFieldGet2(LN,this)>0?-1/0:e._classPrivateFieldGet2(MN,this)/(e._classPrivateFieldGet2(RN,this)+3*e._classPrivateFieldGet2(ON,this))}incrementInvalidBlocks(){var t;e._classPrivateFieldSet2(LN,this,(t=e._classPrivateFieldGet2(LN,this),++t))}getStats(){return{attempts:e._classPrivateFieldGet2(RN,this),errors:e._classPrivateFieldGet2(ON,this),invalidBlocks:e._classPrivateFieldGet2(LN,this),successes:e._classPrivateFieldGet2(MN,this),pendingResponses:e._classPrivateFieldGet2(jN,this).size}}}function zN(e){var t=e.multihash.bytes;return z.encode(t)}function VN(e,t,r){return e.filter((e=>{if(Wd.matches(e)||t&&Kd.matches(e))return!!r||(!!gd.matches(e)||!1===kN(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 qN(e,t,r,n,i){return HN.apply(this,arguments)}function HN(){return HN=e._wrapAsyncGenerator((function(t,r,n,i,o){var a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};return function*(){var s,l=!1,c=!1;try{for(var u,d=e._asyncIterator(r.findProviders(t,a));l=!(u=yield e._awaitAsyncGenerator(d.next())).done;l=!1){var h=VN(u.value.multiaddrs,i,o);if(0!==h.length){var p=GN(h[0]);yield new UN(p,{logger:n,transformRequestInit:a.transformRequestInit})}}}catch(e){c=!0,s=e}finally{try{l&&null!=d.return&&(yield e._awaitAsyncGenerator(d.return()))}finally{if(c)throw s}}}()})),HN.apply(this,arguments)}class KN extends uN{constructor(t,r){var n,i;super(t,e._objectSpread2(e._objectSpread2({},r),{},{name:"helia:trustless-gateway:session"})),e._defineProperty(this,"routing",void 0),e._defineProperty(this,"allowInsecure",void 0),e._defineProperty(this,"allowLocal",void 0),e._defineProperty(this,"transformRequestInit",void 0),this.routing=t.routing,this.allowInsecure=null!==(n=r.allowInsecure)&&void 0!==n?n:QN,this.allowLocal=null!==(i=r.allowLocal)&&void 0!==i?i:YN,this.transformRequestInit=r.transformRequestInit}queryProvider(t,r,n){var i=this;return e._asyncToGenerator((function*(){var e;i.log("fetching BLOCK for %c from %s",t,r.url);var o=yield r.getRawBlock(t,n.signal);return i.log.trace("got block for %c from %s",t,r.url),yield null===(e=n.validateFn)||void 0===e?void 0:e.call(n,o),o}))()}findNewProviders(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(qN(t,r.routing,r.logger,r.allowInsecure,r.allowLocal,e._objectSpread2(e._objectSpread2({},n),{},{transformRequestInit:r.transformRequestInit}))))}()})).apply(this,arguments)}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}}class WN{constructor(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"allowInsecure",void 0),e._defineProperty(this,"allowLocal",void 0),e._defineProperty(this,"transformRequestInit",void 0),e._defineProperty(this,"routing",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(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:QN,this.allowLocal=null!==(n=i.allowLocal)&&void 0!==n?n:YN,this.transformRequestInit=i.transformRequestInit}retrieve(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i,o=r.length>1&&void 0!==r[1]?r[1]:{},a=[],s=!1,l=!1;try{for(var c,u=e._asyncIterator(qN(t,n.routing,n.logger,n.allowInsecure,n.allowLocal,e._objectSpread2(e._objectSpread2({},o),{},{transformRequestInit:n.transformRequestInit})));s=!(c=yield u.next()).done;s=!1){var d=c.value;n.log("getting block for %c from %s",t,d.url);try{var h=yield d.getRawBlock(t,o.signal);n.log.trace("got block for %c from %s",t,d.url);try{var p;yield null===(p=o.validateFn)||void 0===p?void 0:p.call(o,h)}catch(e){n.log.error("failed to validate block for %c from %s",t,d.url,e);continue}return h}catch(e){var f;if(n.log.error("failed to get block for %c from %s",t,d.url,e),e instanceof Error?a.push(e):a.push(new Error("Unable to fetch raw block for CID ".concat(t," from gateway ").concat(d.url))),!0===(null===(f=o.signal)||void 0===f?void 0:f.aborted)){n.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,d.url);break}}}}catch(e){l=!0,i=e}finally{try{s&&null!=u.return&&(yield u.return())}finally{if(l)throw i}}throw a.length>0?new AggregateError(a,"Unable to fetch raw block for CID ".concat(t," from any gateway")):new Error("Unable to fetch raw block for CID ".concat(t," from any gateway"))}))()}createSession(){var t,r,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t={logger:this.logger,routing:this.routing},r=e._objectSpread2(e._objectSpread2({},n),{},{allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit}),new KN(t,r)}}var QN=!1,YN=!1;function JN(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new WN(t,e)}function ZN(e){return $N.apply(this,arguments)}function $N(){return $N=e._wrapAsyncGenerator((function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var n=t.getReader();try{for(;;){var i=yield e._awaitAsyncGenerator(n.read());if(i.done)return;yield i.value}}finally{!0!==r.preventCancel&&(yield e._awaitAsyncGenerator(n.cancel())),n.releaseLock()}}()})),$N.apply(this,arguments)}var XN,eD={exports:{}};var tD,rD,nD=(XN||(XN=1,tD=eD,function(){tD.exports=v;var e=86400,t=3200,r=146097*t/400,n=e*r,i=1e3*n,o=864e13,a=4294967296,s=1e6,l="000000000",c=Math.trunc||function(e){var t=e-e%1;return 0==t&&(e<0||0===e&&1/e!=1/0)?-0:t},u=v.prototype,d=(v.fromDate=function(e){return new v(+e)},v.fromInt64BE=b(0,1,2,3,0,4),v.fromInt64LE=b(3,2,1,0,4,0),v.fromString=function(e){var t,r=new v;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 y(r)},v.fromTimeT=function(e){return m(e,0)},u.year=0,u.time=0,u.nano=0,u.addNano=function(e){return this.nano+=+e||0,this},u.getNano=function(){var e=y(this);return(e.time%1e3*s+ +e.nano+1e9)%1e9},u.getTimeT=function(){var n=y(this),i=Math.floor(n.time/1e3);return(n=n.year)&&(i+=n*r*e/t),i},u.getYear=function(){return this.toDate().getUTCFullYear()+this.year},u.toDate=function(){return g(y(this).time)},u.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},u.toString=function(e){var t=this,r=t.toDate(),n={H:function(){return S(r.getUTCHours())},L:function(){return P(r.getUTCMilliseconds(),3)},M:function(){return S(r.getUTCMinutes())},N:function(){return P(t.getNano(),9)},S:function(){return S(r.getUTCSeconds())},Y:function(){var e=t.getYear();return 999999<e?"+"+e:9999<e?"+"+P(e,6):0<=e?P(e,4):-999999<=e?"-"+P(-e,6):e},a:function(){return p[r.getUTCDay()]},b:function(){return h[r.getUTCMonth()]},d:function(){return S(r.getUTCDate())},e:function(){return function(e){return(9<e?"":" ")+(0|e)}(r.getUTCDate())},m:function(){return S(r.getUTCMonth()+1)}};return function e(t){return t.replace(/%./g,(function(t){var r=t[1],i=f[r];return r=n[r],i?e(i):r?r():t}))}(e||d)},u.writeInt64BE=w(0,1,2,3,0,4),u.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"],p=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],f={"%":"%",F:"%Y-%m-%d",n:"\n",R:"%H:%M",T:"%H:%M:%S",t:"\t",X:"%T",Z:"GMT",z:"+0000"};return v;function v(e,t,r){var n=this;if(!(n instanceof v))return new v(e,t,r);n.time=+e||0,n.nano=+t||0,n.year=+r||0,y(n)}function y(e){var r,n,a,l=e.year,u=e.time,d=e.nano,h=((d<0||s<=d)&&(d-=(n=Math.floor(d/s))*s,u+=n,n=1),l%t);return(u<-o||o<u||h)&&((r=c(u/i))&&(l+=r*t,u-=r*i),(a=g(u)).setUTCFullYear(h+a.getUTCFullYear()),a=(u=+a)+(r=c((l-=h)/t))*i,r&&-o<=a&&a<=o&&(l-=r*t,u=a),n=1),n&&(e.year=l,e.time=u,e.nano=d),e}function g(e){var t=new Date(0);return t.setTime(e),t}function m(e,r){e=+e||0;var i=c((r=(0|r)*a)/n)+c(e/n);return(e=c((r=r%n+e%n)/n))&&(i+=e,r-=e*n),new v(1e3*r,0,i*t)}function w(n,i,o,s,l,u){return function(n,i){var o=y(this);_(n=n||new Array(8),i|=0);var s=Math.floor(o.time/1e3),h=(o=o.year*(r*e/t),c(o/a)+c(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+u,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){_(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 _(e,t){if(null==(e=e&&e.length))throw new TypeError("Invalid Buffer");if(e<t+8)throw new RangeError("Out of range")}function S(e){return(9<e?"":"0")+(0|e)}function P(e,t){return(l+(0|e)).substr(-t)}}()),eD.exports),iD=e.getDefaultExportFromCjs(nD);class oD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Record signature creation failed"),this.name="SignatureCreationError"}}e._defineProperty(oD,"name","SignatureCreationError");class aD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Record signature verification failed"),this.name="SignatureVerificationError"}}e._defineProperty(aD,"name","SignatureVerificationError");class sD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Record has expired"),this.name="RecordExpiredError"}}e._defineProperty(sD,"name","RecordExpiredError");class lD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The validity type is unsupported"),this.name="UnsupportedValidityError"}}e._defineProperty(lD,"name","UnsupportedValidityError");class cD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The record is too large"),this.name="RecordTooLargeError"}}e._defineProperty(cD,"name","RecordTooLargeError");class uD 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._defineProperty(uD,"name","InvalidValueError");class dD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid record data"),this.name="InvalidRecordDataError"}}e._defineProperty(dD,"name","InvalidRecordDataError");class hD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid embedded public key"),this.name="InvalidEmbeddedPublicKeyError"}}e._defineProperty(hD,"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=()=>cl(t)}(e.ValidityType||(e.ValidityType={})),e.codec=()=>(null==r&&(r=ul((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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(rD||(rD={}));var pD=ku("ipns:utils"),fD=nt("/ipns/");function vD(e){return"signatureV1"in e?rD.encode({value:nt(e.value),signatureV1:e.signatureV1,validityType:e.validityType,validity:nt(e.validity),sequence:e.sequence,ttl:e.ttl,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data}):rD.encode({pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data})}function yD(e){var t=rD.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 aD("Missing data or signatureV2");var r=wD(t.data),n=function(e){var t=Ze(e).trim();if(t.startsWith("/"))return t;try{return"/ipfs/".concat(je.decode(e).toV1().toString())}catch(e){}try{return"/ipfs/".concat(je.parse(t).toV1().toString())}catch(e){}throw new uD("Value must be a valid content path starting with /")}(r.Value),i=Ze(r.Validity);if(null!=t.value&&null!=t.signatureV1)return function(e){var t,r;if(null==e.data)throw new dD("Record data is missing");var n=wD(e.data);if(!rt(n.Value,null!==(t=e.value)&&void 0!==t?t:new Uint8Array(0)))throw new aD('Field "value" did not match between protobuf and CBOR');if(!rt(n.Validity,null!==(r=e.validity)&&void 0!==r?r:new Uint8Array(0)))throw new aD('Field "validity" did not match between protobuf and CBOR');if(n.ValidityType!==e.validityType)throw new aD('Field "validityType" did not match between protobuf and CBOR');if(n.Sequence!==e.sequence)throw new aD('Field "sequence" did not match between protobuf and CBOR');if(n.TTL!==e.ttl)throw new aD('Field "ttl" did not match between protobuf and CBOR')}(t),{value:n,validityType:rD.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:rD.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 gD(e){return mt([fD,e.bytes])}function mD(e){var t=Ae(e.slice(fD.length));if(!bD(t,0)&&!bD(t,18))throw new ua("Multihash in IPNS key was not identity or sha2-256");return t}function wD(e){var t=rC(e);if(0!==t.ValidityType)throw new lD("The validity type is unsupported");return t.ValidityType=rD.ValidityType.EOL,Number.isInteger(t.Sequence)&&(t.Sequence=BigInt(t.Sequence)),Number.isInteger(t.TTL)&&(t.TTL=BigInt(t.TTL)),t}function bD(e,t){return e.code===t}var _D=ku("ipns:validator"),SD=function(){var t=e._asyncToGenerator((function*(e,t){var r,n,i=yD(t);try{var o=(n=i.data,mt([nt("ipns-signature:"),n]));r=yield e.verify(o,i.signatureV2)}catch(e){r=!1}if(!r)throw _D.error("record signature verification failed"),new aD("Record signature verification failed");if(i.validityType===rD.ValidityType.EOL){if(iD.fromString(i.validity).toDate().getTime()<Date.now())throw _D.error("record has expired"),new sD("record has expired")}else if(null!=i.validityType)throw _D.error("the validity type is unsupported"),new lD("The validity type is unsupported");_D("ipns record for %s is valid",i.value)}));return function(e,r){return t.apply(this,arguments)}}();function PD(e,t){return ED.apply(this,arguments)}function ED(){return(ED=e._asyncToGenerator((function*(e,t){var r;if(t.byteLength>10240)throw new cD("The record is too large");var n,i=mD(e);bD(i,0)&&(n=jl(i));var o=null!==(r=function(e){var t;if(null!=e.pubKey)try{t=Ml(e.pubKey)}catch(e){throw pD.error(e),e}if(null!=t)return t}(yD(t)))&&void 0!==r?r:n;if(null==o)throw new hD("Could not extract public key from IPNS record or routing key");if(!rt(gD(o.toMultihash()),e))throw new hD("Embedded public key did not match routing key");yield SD(o,t)}))).apply(this,arguments)}let AD=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidMessageLengthError"),e._defineProperty(this,"code","ERR_INVALID_MESSAGE_LENGTH")}};function kD(e){return xD.apply(this,arguments)}function xD(){return xD=e._wrapAsyncGenerator((function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var n,i=/\r?\n/,o=new TextDecoder("utf8"),a="",s=!1,l=!1;try{for(var c,u=e._asyncIterator(t);s=!(c=yield e._awaitAsyncGenerator(u.next())).done;s=!1){var d,h,p=c.value;if("string"==typeof p&&(p=(new TextEncoder).encode(p)),Ra(p)&&(p=p.subarray()),(a+=o.decode(p,{stream:!0})).length>(null!==(d=null==r?void 0:r.maxMessageLength)&&void 0!==d?d:a.length))throw new AD("Incoming message too long");var f=a.split(i);a=null!==(h=f.pop())&&void 0!==h?h:"";for(var v=0;v<f.length;v++)yield JSON.parse(f[v])}}catch(e){l=!0,n=e}finally{try{s&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(l)throw n}}""!==(a+=o.decode())&&(yield JSON.parse(a))}()})),xD.apply(this,arguments)}class TD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid request"),this.name="InvalidRequestError"}}e._defineProperty(TD,"name","InvalidRequestError");class ID extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Bad response"),this.name="BadResponseError"}}function CD(t){if(null!=t[Symbol.asyncIterator])return e._asyncToGenerator((function*(){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t);n=!(o=yield a.next()).done;n=!1){return o.value}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield a.return())}finally{if(i)throw r}}}))();for(var r of t)return r}e._defineProperty(ID,"name","BadResponseError");var BD=nt("/ipns/");function ND(e){return rt(e.subarray(0,BD.byteLength),BD)}class DD{constructor(t){e._defineProperty(this,"client",void 0),this.client=t}findProviders(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(qc(r.client.getProviders(t,n),(e=>{var t;return{id:e.ID,multiaddrs:null!==(t=e.Addrs)&&void 0!==t?t:[]}}))))}()})).apply(this,arguments)}provide(){return e._asyncToGenerator((function*(){}))()}cancelReprovide(){return e._asyncToGenerator((function*(){}))()}put(t,r,n){var i=this;return e._asyncToGenerator((function*(){if(ND(t)){var e=mD(t),o=je.createV1(114,e),a=yD(r);yield i.client.putIPNS(o,a,n)}}))()}get(t,r){var n=this;return e._asyncToGenerator((function*(){if(!ND(t))throw new aa("Not found");var e=mD(t),i=je.createV1(114,e);try{return vD(yield n.client.getIPNS(i,r))}catch(e){if("BadResponseError"===e.name)throw new aa("Not found");throw e}}))()}}class GD{constructor(t){e._defineProperty(this,"client",void 0),this.client=t}findPeer(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e,i=r.length>1&&void 0!==r[1]?r[1]:{},o=yield CD(n.client.getPeers(t,i));if(null!=o)return{id:o.ID,multiaddrs:null!==(e=o.Addrs)&&void 0!==e?e:[]};throw new aa("Not found")}))()}getClosestPeers(t){return e._wrapAsyncGenerator((function(e){return function*(){}()})).apply(this,arguments)}}var RD=ku("delegated-routing-v1-http-api-client"),OD={concurrentRequests:4,timeout:3e4,cacheTTL:3e5,cacheName:"delegated-routing-v1-cache"},LD=new WeakSet;class MD{constructor(t){var r,n,i,o,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._classPrivateMethodInitSpec(this,LD),e._defineProperty(this,"started",void 0),e._defineProperty(this,"httpQueue",void 0),e._defineProperty(this,"shutDownController",void 0),e._defineProperty(this,"clientUrl",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"contentRouting",void 0),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"filterAddrs",void 0),e._defineProperty(this,"filterProtocols",void 0),e._defineProperty(this,"inFlightRequests",void 0),e._defineProperty(this,"cacheName",void 0),e._defineProperty(this,"cache",void 0),e._defineProperty(this,"cacheTTL",void 0),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new Yx({concurrency:null!==(r=a.concurrentRequests)&&void 0!==r?r:OD.concurrentRequests}),this.inFlightRequests=new Map,this.clientUrl=t instanceof URL?t:new URL(t),this.timeout=null!==(n=a.timeout)&&void 0!==n?n:OD.timeout,this.filterAddrs=a.filterAddrs,this.filterProtocols=a.filterProtocols,this.contentRouting=new DD(this),this.peerRouting=new GD(this),this.cacheName=null!==(i=a.cacheName)&&void 0!==i?i:OD.cacheName,this.cacheTTL=null!==(o=a.cacheTTL)&&void 0!==o?o:OD.cacheTTL}get[jo](){return this.contentRouting}get[qo](){return this.peerRouting}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){var e;t.started||(t.started=!0,t.cacheTTL>0&&(t.cache=yield null===(e=globalThis.caches)||void 0===e?void 0:e.open(t.cacheName),null!=t.cache&&RD("cache enabled with ttl %d",t.cacheTTL)))}))()}stop(){var t=this;return e._asyncToGenerator((function*(){var e;t.httpQueue.clear(),t.shutDownController.abort(),yield null===(e=globalThis.caches)||void 0===e?void 0:e.delete(t.cacheName),t.started=!1}))()}getProviders(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){RD("getProviders starts: %c",t);var i=AbortSignal.timeout(r.timeout),o=Qd([r.shutDownController.signal,i,n.signal]),a=Hc(),s=Hc();r.httpQueue.add(e._asyncToGenerator((function*(){return a.resolve(),s.promise})));try{yield e._awaitAsyncGenerator(a.promise);var l=new URL("".concat(r.clientUrl,"routing/v1/providers/").concat(t.toString()));e._assertClassBrand(LD,r,FD).call(r,l,n.filterAddrs,n.filterProtocols);var c={headers:{Accept:"application/x-ndjson"},signal:o},u=yield e._awaitAsyncGenerator(e._assertClassBrand(LD,r,UD).call(r,l.toString(),c));if(null==u)throw new ID("No response received");if(!u.ok){if(404===u.status)throw new aa("No matching records found");if(422===u.status)throw new TD("Request does not conform to schema or semantic constraints");throw new ID("Unexpected status code: ".concat(u.status))}if(null==u.body)throw new ID("Routing response had no body");var d=u.headers.get("Content-Type");if(null==d)throw new ID("No Content-Type header received");if(null!=d&&d.startsWith("application/json")){var h=yield e._awaitAsyncGenerator(u.json());for(var p of h.Providers){var f=e._assertClassBrand(LD,r,jD).call(r,p);null!=f&&(yield f)}}else{if(!d.includes("application/x-ndjson"))throw new ID("Unsupported Content-Type: ".concat(d));var v,y=!1,g=!1;try{for(var m,w=e._asyncIterator(kD(ZN(u.body)));y=!(m=yield e._awaitAsyncGenerator(w.next())).done;y=!1){var b=m.value,_=e._assertClassBrand(LD,r,jD).call(r,b);null!=_&&(yield _)}}catch(e){g=!0,v=e}finally{try{y&&null!=w.return&&(yield e._awaitAsyncGenerator(w.return()))}finally{if(g)throw v}}}}finally{o.clear(),s.resolve(),RD("getProviders finished: %c",t)}}()})).apply(this,arguments)}getPeers(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){RD("getPeers starts: %c",t);var i=AbortSignal.timeout(r.timeout),o=Qd([r.shutDownController.signal,i,n.signal]),a=Hc(),s=Hc();r.httpQueue.add(e._asyncToGenerator((function*(){return a.resolve(),s.promise})));try{yield e._awaitAsyncGenerator(a.promise);var l=new URL("".concat(r.clientUrl,"routing/v1/peers/").concat(t.toCID().toString()));e._assertClassBrand(LD,r,FD).call(r,l,n.filterAddrs,n.filterProtocols);var c={headers:{Accept:"application/x-ndjson"},signal:o},u=yield e._awaitAsyncGenerator(e._assertClassBrand(LD,r,UD).call(r,l.toString(),c));if(404===u.status)throw new aa("No matching records found");if(422===u.status)throw new TD("Request does not conform to schema or semantic constraints");if(null==u.body)throw new ID("Routing response had no body");if("application/json"===u.headers.get("Content-Type")){var d=yield e._awaitAsyncGenerator(u.json());for(var h of d.Peers){var p=e._assertClassBrand(LD,r,jD).call(r,h);null!=p&&(yield p)}}else{var f,v=!1,y=!1;try{for(var g,m=e._asyncIterator(kD(ZN(u.body)));v=!(g=yield e._awaitAsyncGenerator(m.next())).done;v=!1){var w=g.value,b=e._assertClassBrand(LD,r,jD).call(r,w);null!=b&&(yield b)}}catch(e){y=!0,f=e}finally{try{v&&null!=m.return&&(yield e._awaitAsyncGenerator(m.return()))}finally{if(y)throw f}}}}catch(e){RD.error("getPeers errored:",e)}finally{o.clear(),s.resolve(),RD("getPeers finished: %c",t)}}()})).apply(this,arguments)}getIPNS(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{};RD("getIPNS starts: %s",t);var o=AbortSignal.timeout(n.timeout),a=Qd([n.shutDownController.signal,o,i.signal]),s=Hc(),l=Hc();n.httpQueue.add(e._asyncToGenerator((function*(){return s.resolve(),l.promise})));var c="".concat(n.clientUrl,"routing/v1/ipns/").concat(t);try{yield s.promise;var u={headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:a},d=yield e._assertClassBrand(LD,n,UD).call(n,c,u);if(RD("getIPNS GET %s %d",c,d.status),404===d.status)throw new aa("No matching records found");if(422===d.status)throw new TD("Request does not conform to schema or semantic constraints");if(null==d.body)throw new ID("GET ipns response had no body");var h=yield d.arrayBuffer(),p=new Uint8Array(h,0,h.byteLength);return!1!==i.validate&&(yield PD(gD(t.multihash),p)),yD(p)}catch(e){throw RD.error("getIPNS GET %s error:",c,e),e}finally{a.clear(),l.resolve(),RD("getIPNS finished: %s",t)}}))()}putIPNS(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var o=n.length>2&&void 0!==n[2]?n[2]:{};RD("putIPNS starts: %c",t);var a=AbortSignal.timeout(i.timeout),s=Qd([i.shutDownController.signal,a,o.signal]),l=Hc(),c=Hc();i.httpQueue.add(e._asyncToGenerator((function*(){return l.resolve(),c.promise})));var u="".concat(i.clientUrl,"routing/v1/ipns/").concat(t);try{yield l.promise;var d={method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:vD(r),signal:s},h=yield e._assertClassBrand(LD,i,UD).call(i,u,d);if(RD("putIPNS PUT %s %d",u,h.status),200!==h.status)throw new ID("PUT ipns response had status other than 200")}catch(e){throw RD.error("putIPNS PUT %s error:",u,e.stack),e}finally{s.clear(),c.resolve(),RD("putIPNS finished: %c",t)}}))()}}function jD(t){try{var r,n,i=[],o=null!==(r=null===(n=t.Addrs)||void 0===n?void 0:n.map(nr))&&void 0!==r?r:[];return null!=t.Protocols&&i.push(...t.Protocols),null!=t.Protocol&&(i.push(t.Protocol),delete t.Protocol),e._objectSpread2(e._objectSpread2({},t),{},{Schema:"peer",ID:$l(t.ID),Addrs:o,Protocols:i})}catch(e){RD.error("could not conform record to peer schema",e)}}function FD(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,c,u=null!==(s=null!==(l=null==r?void 0:r.join(","))&&void 0!==l?l:null===(c=this.filterProtocols)||void 0===c?void 0:c.join(","))&&void 0!==s?s:"";""!==u&&e.searchParams.set("filter-protocols",u)}}function UD(e,t){return zD.apply(this,arguments)}function zD(){return zD=e._asyncToGenerator((function*(t,r){var n,i=this,o=null!==(n=r.method)&&void 0!==n?n:"GET",a="".concat(o,"-").concat(t);if("GET"===o){var s,l=yield null===(s=this.cache)||void 0===s?void 0:s.match(t);if(null!=l){var c,u;if(parseInt(null!==(c=l.headers.get("x-cache-expires"))&&void 0!==c?c:"0",10)>Date.now())return RD("returning cached response for %s",a),l;yield null===(u=this.cache)||void 0===u?void 0:u.delete(t)}}var d=this.inFlightRequests.get(a);if(null!=d){var h=yield d;return RD("deduplicating outgoing request for %s",a),h.clone()}var p=fetch(t,r).then(function(){var r=e._asyncToGenerator((function*(e){if(null!=i.cache&&e.ok&&"GET"===o){var r=Date.now()+i.cacheTTL,n=new Headers(e.headers);n.set("x-cache-expires",r.toString());var a=new Response(e.clone().body,{status:e.status,statusText:e.statusText,headers:n});yield i.cache.put(t,a)}return e}));return function(e){return r.apply(this,arguments)}}()).finally((()=>{this.inFlightRequests.delete(a)}));return this.inFlightRequests.set(a,p),yield p})),zD.apply(this,arguments)}var VD="[a-fA-F\\d:]",qD=e=>e&&e.includeBoundaries?"(?:(?<=\\s|^)(?=".concat(VD,")|(?<=").concat(VD,")(?=\\s|$))"):"",HD="(?: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}",KD="[a-fA-F\\d]{1,4}",WD="\n(?:\n(?:".concat(KD,":){7}(?:").concat(KD,"|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:").concat(KD,":){6}(?:").concat(HD,"|:").concat(KD,"|:)| // 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(KD,":){5}(?::").concat(HD,"|(?::").concat(KD,"){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(KD,":){4}(?:(?::").concat(KD,"){0,1}:").concat(HD,"|(?::").concat(KD,"){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(KD,":){3}(?:(?::").concat(KD,"){0,2}:").concat(HD,"|(?::").concat(KD,"){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(KD,":){2}(?:(?::").concat(KD,"){0,3}:").concat(HD,"|(?::").concat(KD,"){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(KD,":){1}(?:(?::").concat(KD,"){0,4}:").concat(HD,"|(?::").concat(KD,"){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::").concat(KD,"){0,5}:").concat(HD,"|(?::").concat(KD,"){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(),QD=new RegExp("(?:^".concat(HD,"$)|(?:^").concat(WD,"$)")),YD=new RegExp("^".concat(HD,"$")),JD=new RegExp("^".concat(WD,"$")),ZD=e=>e&&e.exact?QD:new RegExp("(?:".concat(qD(e)).concat(HD).concat(qD(e),")|(?:").concat(qD(e)).concat(WD).concat(qD(e),")"),"g");ZD.v4=e=>e&&e.exact?YD:new RegExp("".concat(qD(e)).concat(HD).concat(qD(e)),"g"),ZD.v6=e=>e&&e.exact?JD:new RegExp("".concat(qD(e)).concat(WD).concat(qD(e)),"g");var{toString:$D}=Object.prototype;var XD={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function eG(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t=e,"[object RegExp]"!==$D.call(t))throw new TypeError("Expected a RegExp instance");var n=Object.keys(XD).map((t=>("boolean"==typeof r[t]?r[t]:e[t])?XD[t]:"")).join(""),i=new RegExp(r.source||e.source,n);return i.lastIndex="number"==typeof r.lastIndex?r.lastIndex:e.lastIndex,i}function tG(e,t){var r,n,{timeout:i}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{return(r=()=>eG(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 rG={timeout:400};function nG(e){return!(e.length>45)&&tG(ZD.v6({exact:!0}),e,rG)}var iG={http:"80",https:"443",ws:"80",wss:"443"},oG=["http","https","ws","wss"];function aG(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(":");oG.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==iG[e])return;return iG[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=[sG(o,n),lG(a,i),cG(i)];return null!=s&&l.push(function(e){if(null==e||""===e)return;return["http-path",encodeURIComponent(e)]}(s)),nr("/"+l.filter((e=>Boolean(e))).reduce(((e,t)=>e.concat(t)),[]).join("/"))}function sG(e,t){if(null!=e&&""!==e){if(function(e){return!(e.length>15)&&tG(ZD.v4({exact:!0}),e,rG)}(e))return["ip4",e];if(nG(e))return["ip6",e];if("["===e[0]){var r=e.substring(1,e.length-1);if(nG(r))return["ip6",r]}return[t,e]}}function lG(e,t){if(null!=e&&""!==e)return"udp"===t?["udp",e]:["tcp",e]}function cG(e){if(null==e.match(/^tcp$|^udp$/))return"https"===e?["/tls/http"]:"wss"===e?["/tls/ws"]:[e]}var uG=["https://trustless-gateway.link","https://4everland.io"];class dG{constructor(){var t,r,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e._defineProperty(this,"gateways",void 0),e._defineProperty(this,"shuffle",void 0),this.gateways=(null!==(t=n.gateways)&&void 0!==t?t:uG).map((e=>function(e){return e=e.toString(),{id:rc(je.createV1(2336,Te.digest(nt(e)))),multiaddrs:[aG(e)]}}(e))),this.shuffle=null===(r=n.shuffle)||void 0===r||r}findProviders(t,r){var n=this;return e._wrapAsyncGenerator((function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator((n.shuffle?n.gateways.toSorted((()=>Math.random()>.5?1:-1)):n.gateways).map((t=>e._objectSpread2(e._objectSpread2({},t),{},{protocols:["transport-ipfs-gateway-http"]})))))}))()}}function hG(){return new dG(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{})}class pG{constructor(t){e._defineProperty(this,"libp2p",void 0),this.libp2p=t}provide(t,r){var n=this;return e._asyncToGenerator((function*(){yield n.libp2p.contentRouting.provide(t,r)}))()}cancelReprovide(t,r){var n=this;return e._asyncToGenerator((function*(){yield n.libp2p.contentRouting.cancelReprovide(t,r)}))()}findProviders(t,r){var n=this;return e._wrapAsyncGenerator((function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(n.libp2p.contentRouting.findProviders(t,r)))}))()}put(t,r,n){var i=this;return e._asyncToGenerator((function*(){yield i.libp2p.contentRouting.put(t,r,n)}))()}get(t,r){var n=this;return e._asyncToGenerator((function*(){return n.libp2p.contentRouting.get(t,r)}))()}findPeer(t,r){var n=this;return e._asyncToGenerator((function*(){return n.libp2p.peerRouting.findPeer(t,r)}))()}getClosestPeers(t,r){var n=this;return e._wrapAsyncGenerator((function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(n.libp2p.peerRouting.getClosestPeers(t,r)))}))()}}function fG(e){return new pG(e)}class vG extends dN{constructor(t){super(e._objectSpread2(e._objectSpread2({},t),{},{components:{libp2p:t.libp2p}})),e._defineProperty(this,"libp2p",void 0),this.libp2p=t.libp2p}start(){var t=()=>super.start,r=this;return e._asyncToGenerator((function*(){yield t().call(r),yield r.libp2p.start()}))()}stop(){var t=()=>super.stop,r=this;return e._asyncToGenerator((function*(){yield t().call(r),yield r.libp2p.stop()}))()}}class yG extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The frame was invalid"),this.name="InvalidFrameError"}}e._defineProperty(yG,"name","InvalidFrameError");class gG extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unrequested ping error"),this.name="UnrequestedPingError"}}e._defineProperty(gG,"name","UnrequestedPingError");class mG extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unrequested ping error"),this.name="NotMatchingPingError"}}e._defineProperty(mG,"name","NotMatchingPingError");class wG extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid state"),this.name="InvalidStateError"}}e._defineProperty(wG,"name","InvalidStateError");class bG extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Strean already exists"),this.name="StreamAlreadyExistsError"}}e._defineProperty(bG,"name","StreamAlreadyExistsError");class _G extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Decode invalid version"),this.name="DecodeInvalidVersionError"}}e._defineProperty(_G,"name","DecodeInvalidVersionError");class SG extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Both clients"),this.name="BothClientsError"}}e._defineProperty(SG,"name","BothClientsError");class PG extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Receive window exceeded"),this.name="ReceiveWindowExceededError"}}e._defineProperty(PG,"name","ReceiveWindowExceededError");var EG,AG,kG=new Set([yG.name,gG.name,mG.name,bG.name,_G.name,SG.name,PG.name]),xG=262144,TG={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,initialStreamWindowSize:xG,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"}(EG||(EG={})),function(e){e[e.SYN=1]="SYN",e[e.ACK=2]="ACK",e[e.FIN=4]="FIN",e[e.RST=8]="RST"}(AG||(AG={})),Object.values(AG).filter((e=>"string"!=typeof e));var IG;!function(e){e[e.NormalTermination=0]="NormalTermination",e[e.ProtocolError=1]="ProtocolError",e[e.InternalError=2]="InternalError"}(IG||(IG={}));var CG=2**24;let BG=class{constructor(t){e._defineProperty(this,"source",void 0),e._defineProperty(this,"buffer",void 0),e._defineProperty(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 Oa,this.frameInProgress=!1}emitFrames(){var t=this;return e._wrapAsyncGenerator((function*(){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t.source);n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var s=o.value;for(t.buffer.append(s);;){var l=t.readHeader();if(void 0===l)break;var{type:c,length:u}=l;c===EG.Data?(t.frameInProgress=!0,yield{header:l,readData:t.readBytes.bind(t,u)}):yield{header:l}}}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw r}}}))()}readHeader(){if(this.frameInProgress)throw new wG("decoding frame already in progress");if(!(this.buffer.length<12)){var e=function(e){if(0!==e[0])throw new yG("Invalid frame version");return{type:e[1],flag:(e[2]<<8)+e[3],streamID:e[4]*CG+(e[5]<<16)+(e[6]<<8)+e[7],length:e[8]*CG+(e[9]<<16)+(e[10]<<8)+e[11]}}(this.buffer.subarray(0,12));return this.buffer.consume(12),e}}readBytes(t){var r=this;return e._asyncToGenerator((function*(){if(r.buffer.length<t){var n,i=!1,o=!1;try{for(var a,s=e._asyncIterator(r.source);i=!(a=yield s.next()).done;i=!1){var l=a.value;if(r.buffer.append(l),r.buffer.length>=t)break}}catch(e){o=!0,n=e}finally{try{i&&null!=s.return&&(yield s.return())}finally{if(o)throw n}}}var c=r.buffer.sublist(0,t);return r.buffer.consume(t),r.frameInProgress=!1,c}))()}};function NG(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 DG;!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"}(DG||(DG={}));class GG extends Ip{constructor(t){super(e._objectSpread2(e._objectSpread2({},t),{},{onEnd:e=>{var r;this.state=DG.Finished,null===(r=t.onEnd)||void 0===r||r.call(t,e)}})),e._defineProperty(this,"name",void 0),e._defineProperty(this,"state",void 0),e._defineProperty(this,"config",void 0),e._defineProperty(this,"_id",void 0),e._defineProperty(this,"sendWindowCapacity",void 0),e._defineProperty(this,"sendWindowCapacityUpdate",void 0),e._defineProperty(this,"recvWindow",void 0),e._defineProperty(this,"recvWindowCapacity",void 0),e._defineProperty(this,"epochStart",void 0),e._defineProperty(this,"getRTT",void 0),e._defineProperty(this,"sendFrame",void 0),this.config=t.config,this._id=parseInt(t.id,10),this.name=t.name,this.state=t.state,this.sendWindowCapacity=xG,this.recvWindow=this.config.initialStreamWindowSize,this.recvWindowCapacity=this.recvWindow,this.epochStart=Date.now(),this.getRTT=t.getRTT,this.sendFrame=t.sendFrame,this.source=Ph(this.source,(()=>{this.sendWindowUpdate()}))}sendNewStream(){return e._asyncToGenerator((function*(){}))()}sendData(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};for(t=t.sublist();0!==t.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(e),"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,t.length),s=n.getSendFlags();n.sendFrame({type:EG.Data,flag:s,streamID:n._id,length:a},t.sublist(0,a)),n.sendWindowCapacity-=a,t.consume(a)}}))()}sendReset(){var t=this;return e._asyncToGenerator((function*(){t.sendFrame({type:EG.WindowUpdate,flag:AG.RST,streamID:t._id,length:0})}))()}sendCloseWrite(){var t=this;return e._asyncToGenerator((function*(){var e=t.getSendFlags()|AG.FIN;t.sendFrame({type:EG.WindowUpdate,flag:e,streamID:t._id,length:0})}))()}sendCloseRead(){return e._asyncToGenerator((function*(){}))()}waitForSendWindowCapacity(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e,n=t.length>0&&void 0!==t[0]?t[0]:{};if(!(r.sendWindowCapacity>0)){var i,o,a=()=>{"open"===r.status||"closing"===r.status?o(new Wo("Stream aborted")):i()};null===(e=n.signal)||void 0===e||e.addEventListener("abort",a);try{yield new Promise(((e,t)=>{r.sendWindowCapacityUpdate=()=>{e()},o=t,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(t,r){var n=this;return e._asyncToGenerator((function*(){var e;if(null===(e=n.log)||void 0===e||e.trace("stream received data id=%s",n._id),n.processFlags(t.flag),n.recvWindowCapacity<t.length)throw new PG("Receive window exceeded");var i=yield r();n.recvWindowCapacity-=t.length,n.sourcePush(i)}))()}processFlags(e){(e&AG.ACK)===AG.ACK&&this.state===DG.SYNSent&&(this.state=DG.Established),(e&AG.FIN)===AG.FIN&&this.remoteCloseWrite(),(e&AG.RST)===AG.RST&&this.reset()}getSendFlags(){switch(this.state){case DG.Init:return this.state=DG.SYNSent,AG.SYN;case DG.SYNReceived:return this.state=DG.Established,AG.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:EG.WindowUpdate,flag:e,streamID:this._id,length:n})}}}var RG="/yamux/1.0.0";class OG{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"protocol",RG),e._defineProperty(this,"_components",void 0),e._defineProperty(this,"_init",void 0),e._defineProperty(this,Symbol.toStringTag,"@chainsafe/libp2p-yamux"),e._defineProperty(this,Ba,["@libp2p/stream-multiplexing"]),this._components=t,this._init=r}createStreamMuxer(t){return new LG(this._components,e._objectSpread2(e._objectSpread2({},this._init),t))}}class LG{constructor(t,r){var n,i=this;e._defineProperty(this,"protocol",RG),e._defineProperty(this,"source",void 0),e._defineProperty(this,"sink",void 0),e._defineProperty(this,"config",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"closeController",void 0),e._defineProperty(this,"nextStreamID",void 0),e._defineProperty(this,"_streams",void 0),e._defineProperty(this,"nextPingID",void 0),e._defineProperty(this,"activePing",void 0),e._defineProperty(this,"rtt",void 0),e._defineProperty(this,"client",void 0),e._defineProperty(this,"localGoAway",void 0),e._defineProperty(this,"remoteGoAway",void 0),e._defineProperty(this,"numInboundStreams",void 0),e._defineProperty(this,"numOutboundStreams",void 0),e._defineProperty(this,"onIncomingStream",void 0),e._defineProperty(this,"onStreamEnd",void 0),this.client="outbound"===r.direction,this.config=e._objectSpread2(e._objectSpread2({},TG),r),this.logger=t.logger,this.log=this.logger.forComponent("libp2p:yamux"),function(e){if(e.keepAliveInterval<=0)throw new Jo("keep-alive interval must be positive");if(e.maxInboundStreams<0)throw new Jo("max inbound streams must be larger or equal 0");if(e.maxOutboundStreams<0)throw new Jo("max outbound streams must be larger or equal 0");if(e.initialStreamWindowSize<xG)throw new Jo("InitialStreamWindowSize must be larger or equal 256 kB");if(e.maxStreamWindowSize<e.initialStreamWindowSize)throw new Jo("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(e.maxStreamWindowSize>2**32-1)throw new Jo("MaxStreamWindowSize must be less than equal MAX_UINT32");if(e.maxMessageSize<1024)throw new Jo("MaxMessageSize must be greater than a kilobyte")}(this.config),this.closeController=new AbortController,this.closeController.signal,this.onIncomingStream=r.onIncomingStream,this.onStreamEnd=r.onStreamEnd,this._streams=new Map,this.source=Yc({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 t=e._asyncToGenerator((function*(t){var r,n,o,a=()=>{var e,r=kp(t);if(null!=r.return){var n=r.return();null!=(e=n)&&"function"==typeof e.then&&n.catch((e=>{var t;null===(t=i.log)||void 0===t||t.call(i,"could not cause sink source to return",e)}))}};try{var s=new BG(t);try{i.closeController.signal.addEventListener("abort",a);var l,c=!1,u=!1;try{for(var d,h=e._asyncIterator(s.emitFrames());c=!(d=yield h.next()).done;c=!1){var p=d.value;yield i.handleFrame(p.header,p.readData)}}catch(e){u=!0,l=e}finally{try{c&&null!=h.return&&(yield h.return())}finally{if(u)throw l}}}finally{i.closeController.signal.removeEventListener("abort",a)}n=IG.NormalTermination}catch(e){var f,v;if(kG.has(e.name))null===(f=i.log)||void 0===f||f.error("protocol error in sink",e),n=IG.ProtocolError;else null===(v=i.log)||void 0===v||v.error("internal error in sink",e),n=IG.InternalError;o=e}null===(r=i.log)||void 0===r||r.trace("muxer sink ended"),null!=o?i.abort(o,n):yield i.close({reason:n})}));return function(e){return t.apply(this,arguments)}}(),this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,null===(n=this.log)||void 0===n||n.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 na("Muxer closed remotely");if(void 0!==this.localGoAway)throw new na("Muxer closed locally");var r=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.config.maxOutboundStreams)throw new _a("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,DG.Init,"outbound");return this._streams.set(r,n),this.numOutboundStreams++,n.sendWindowUpdate(),n}ping(){var t=this;return e._asyncToGenerator((function*(){if(void 0!==t.remoteGoAway)throw new na("Muxer closed remotely");if(void 0!==t.localGoAway)throw new na("Muxer closed locally");if(void 0===t.activePing){var e=()=>{};t.activePing={id:t.nextPingID++,promise:new Promise(((r,n)=>{var i=()=>{n(new na("Muxer closed locally"))};t.closeController.signal.addEventListener("abort",i,{once:!0}),e=()=>{t.closeController.signal.removeEventListener("abort",i),r()}})),resolve:e};var r=Date.now();t.sendPing(t.activePing.id);try{yield t.activePing.promise}finally{delete t.activePing}var n=Date.now();t.rtt=n-r}else yield t.activePing.promise;return t.rtt}))()}getRTT(){return this.rtt}close(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var n,i,o,a=t.length>0&&void 0!==t[0]?t[0]:{};if(!r.closeController.signal.aborted){var s=null!==(n=null===(i=a)||void 0===i?void 0:i.reason)&&void 0!==n?n:IG.NormalTermination;if(null===(o=r.log)||void 0===o||o.trace("muxer close reason=%s",s),null==a.signal){var l=AbortSignal.timeout(500);a=e._objectSpread2(e._objectSpread2({},a),{},{signal:l})}try{yield Promise.all([...r._streams.values()].map(function(){var t=e._asyncToGenerator((function*(e){return e.close(a)}));return function(e){return t.apply(this,arguments)}}())),r.sendGoAway(s),r._closeMuxer()}catch(e){r.abort(e)}}}))()}abort(e,t){var r;if(!this.closeController.signal.aborted){for(var n of(t=null!=t?t:IG.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 Jo("Stream already exists with that id");var i=new GG({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 t=this;return e._asyncToGenerator((function*(){var e,r=new Promise(((e,r)=>{t.closeController.signal.addEventListener("abort",r,{once:!0})}));null===(e=t.log)||void 0===e||e.trace("muxer keepalive enabled interval=%s",t.config.keepAliveInterval);for(var n,i=function*(){var e;try{yield Promise.race([r,new Promise((r=>{e=setTimeout(r,t.config.keepAliveInterval)}))]),t.ping().catch((e=>{var r;return null===(r=t.log)||void 0===r?void 0:r.error("ping error: %s",e)}))}catch(t){return clearInterval(e),{v:void 0}}};;)if(n=yield*i())return n.v}))()}handleFrame(t,r){var n=this;return e._asyncToGenerator((function*(){var e,{streamID:i,type:o,length:a}=t;if(null===(e=n.log)||void 0===e||e.trace("received frame %o",t),0===i)switch(o){case EG.Ping:return void n.handlePing(t);case EG.GoAway:return void n.handleGoAway(a);default:throw new yG("Invalid frame type")}else switch(t.type){case EG.Data:case EG.WindowUpdate:return void(yield n.handleStreamMessage(t,r));default:throw new yG("Invalid frame type")}}))()}handlePing(e){if(e.flag===AG.SYN){var t;null===(t=this.log)||void 0===t||t.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,AG.ACK)}else{if(e.flag!==AG.ACK)throw new yG("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 gG("ping not requested");if(this.activePing.id!==e)throw new mG("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=IG[e])&&void 0!==r?r:"unknown"),this.remoteGoAway=e,this._streams.values()))n.reset();this._closeMuxer()}handleStreamMessage(t,r){var n=this;return e._asyncToGenerator((function*(){var{streamID:e,flag:i,type:o}=t;(i&AG.SYN)===AG.SYN&&n.incomingStream(e);var a=n._streams.get(e);if(void 0!==a)switch(o){case EG.WindowUpdate:return void a.handleWindowUpdate(t);case EG.Data:if(void 0===r)throw new Error("unreachable");return void(yield a.handleData(t,r));default:throw new Error("unreachable")}else if(o===EG.Data){var s;if(null===(s=n.log)||void 0===s||s.call(n,"discarding data for stream id=%s",e),void 0===r)throw new Error("unreachable");yield r()}else{var l;null===(l=n.log)||void 0===l||l.trace("frame for missing stream id=%s",e)}}))()}incomingStream(e){var t,r;if(this.client!==(e%2==0))throw new Jo("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:EG.WindowUpdate,flag:AG.RST,streamID:e,length:0});var i=this._newStream(e,void 0,DG.SYNReceived,"inbound");this.numInboundStreams++,this._streams.set(e,i),null===(r=this.onIncomingStream)||void 0===r||r.call(this,i)}else this.sendFrame({type:EG.WindowUpdate,flag:AG.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===EG.Data){if(void 0===t)throw new yG("Invalid frame");this.source.push(new Oa(NG(e),t))}else this.source.push(NG(e))}sendPing(e){var t,r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:AG.SYN;n===AG.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:EG.Ping,flag:n,streamID:0,length:e})}sendGoAway(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:IG.NormalTermination;null===(e=this.log)||void 0===e||e.call(this,"sending GoAway reason=%s",IG[t]),this.localGoAway=t,this.sendFrame({type:EG.GoAway,flag:0,streamID:0,length:t})}}function MG(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new OG(t,e)}function jG(e){try{var[[t,r]]=e.stringTuples();if(null==r)return!1;if(41===t)return n=r,new er("2000::/3").contains(n)}catch(e){}var n;return!1}function FG(e){try{var[[t]]=e.stringTuples();return 4===t||41===t}catch(e){}return!1}function UG(e){try{var t;if(!FG(e))return!1;var[[,r]]=e.stringTuples();return null!=r&&(null!==(t=kN(r))&&void 0!==t&&t)}catch(e){}return!0}var zG;!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=()=>cl(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=()=>cl(n)}(e.ResponseStatus||(e.ResponseStatus={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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 dl('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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(e.PeerInfo||(e.PeerInfo={})),function(t){var r;t.codec=()=>(null==r&&(r=ul((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=>sl(e,t.codec()),t.decode=(e,r)=>js(e,t.codec(),r)}(e.Dial||(e.Dial={})),function(t){var r;t.codec=()=>(null==r&&(r=ul((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=>sl(e,t.codec()),t.decode=(e,r)=>js(e,t.codec(),r)}(e.DialResponse||(e.DialResponse={})),e.codec=()=>(null==i&&(i=ul((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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(zG||(zG={}));class VG{constructor(t,r){var n,i,o,a,s,l;e._defineProperty(this,"components",void 0),e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"maxInboundStreams",void 0),e._defineProperty(this,"maxOutboundStreams",void 0),e._defineProperty(this,"maxMessageSize",void 0),e._defineProperty(this,"started",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"topologyId",void 0),e._defineProperty(this,"dialResults",void 0),e._defineProperty(this,"findPeers",void 0),e._defineProperty(this,"addressFilter",void 0),e._defineProperty(this,"connectionThreshold",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/autonat"),e._defineProperty(this,Ba,["@libp2p/autonat"]),this.components=t,this.log=t.logger.forComponent("libp2p:auto-nat"),this.started=!1,this.protocol="/".concat(null!==(n=r.protocolPrefix)&&void 0!==n?n:"libp2p","/").concat("autonat","/").concat("1.0.0"),this.timeout=null!==(i=r.timeout)&&void 0!==i?i:3e4,this.maxInboundStreams=null!==(o=r.maxInboundStreams)&&void 0!==o?o:2,this.maxOutboundStreams=null!==(a=r.maxOutboundStreams)&&void 0!==a?a:20,this.connectionThreshold=null!==(s=r.connectionThreshold)&&void 0!==s?s:80,this.maxMessageSize=null!==(l=r.maxMessageSize)&&void 0!==l?l:8192,this.dialResults=new Map,this.findPeers=function(t,r,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 c=Qd([o.signal,AbortSignal.timeout(n.timeout)]);l.signal=c}Promise.resolve().then(e._asyncToGenerator((function*(){yield t(l)}))).catch((()=>{})).finally((()=>{o.signal.aborted||(i=setTimeout(a,r))}))}var s=!1;return{setInterval:e=>{r!==e&&(r=e,null!=i&&(clearTimeout(i),i=setTimeout(a,r)))},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,r))},stop:()=>{var e;clearTimeout(i),null===(e=o)||void 0===e||e.abort(),s=!1}}}(this.findRandomPeers.bind(this),6e4),this.addressFilter=gh(1024)}get[Na](){return["@libp2p/identify"]}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){t.started||(yield t.components.registrar.handle(t.protocol,(e=>{t.handleIncomingAutonatStream(e).catch((e=>{t.log.error("error handling incoming autonat stream - %e",e)}))}),{maxInboundStreams:t.maxInboundStreams,maxOutboundStreams:t.maxOutboundStreams}),t.topologyId=yield t.components.registrar.register(t.protocol,{onConnect:(e,r)=>{t.verifyExternalAddresses(r).catch((e=>{t.log.error("could not verify addresses - %e",e)}))}}),t.findPeers.start(),t.started=!0)}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield t.components.registrar.unhandle(t.protocol),null!=t.topologyId&&(yield t.components.registrar.unhandle(t.topologyId)),t.dialResults.clear(),t.findPeers.stop(),t.started=!1}))()}allAddressesAreVerified(){return this.components.addressManager.getAddressesWithMetadata().every((e=>e.expires>Date.now()||e.verified))}findRandomPeers(t){var r=this;return e._asyncToGenerator((function*(){if(!r.allAddressesAreVerified()){var n=Qd([AbortSignal.timeout(1e4),null==t?void 0:t.signal]);try{r.log("starting random walk to find peers to run AutoNAT");var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(r.components.randomWalk.walk({signal:n}));o=!(s=yield l.next()).done;o=!1){var c=s.value;if(yield r.components.connectionManager.isDialable(c.multiaddrs)){try{r.log.trace("dial random peer %p",c.id),yield r.components.connectionManager.openConnection(c.multiaddrs,{signal:n})}catch(e){}if(r.allAddressesAreVerified())return void r.log("stopping random walk, all addresses are verified");if(!r.hasConnectionCapacity())return void r.log("stopping random walk, too close to max connections")}else r.log.trace("random peer %p was not dialable %s",c.id,c.multiaddrs.map((e=>e.toString())).join(", "))}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield l.return())}finally{if(a)throw i}}}catch(e){}}}))()}handleIncomingAutonatStream(t){var r=this;return e._asyncToGenerator((function*(){var e=AbortSignal.timeout(r.timeout),n=Vu(t.stream,{maxDataLength:r.maxMessageSize}).pb(zG);try{var i=yield n.read({signal:e}),o=yield r.handleAutonatMessage(i,t.connection,{signal:e});yield n.write(o,{signal:e}),yield n.unwrap().unwrap().close({signal:e})}catch(e){r.log.error("error handling incoming autonat stream - %e",e),t.stream.abort(e)}}))()}handleAutonatMessage(t,r,n){var i=this;return e._asyncToGenerator((function*(){var e,o=i.components.addressManager.getAddresses().map((e=>e.toOptions().host)),a=t.dial;if(null==a)return i.log.error("dial was missing from message"),{type:zG.MessageType.DIAL_RESPONSE,dialResponse:{status:zG.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:zG.MessageType.DIAL_RESPONSE,dialResponse:{status:zG.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}};try{var l=Ae(s.id);e=tc(l)}catch(e){return i.log.error("invalid PeerId - %e",e),{type:zG.MessageType.DIAL_RESPONSE,dialResponse:{status:zG.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}}}if(i.log("incoming request from %p",e),!r.remotePeer.equals(e))return i.log("target peer %p did not equal sending peer %p",e,r.remotePeer),{type:zG.MessageType.DIAL_RESPONSE,dialResponse:{status:zG.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}};var c=s.addrs.map((e=>nr(e))).filter((e=>{var t=e.toOptions();return!UG(e)&&(t.host!==r.remoteAddr.toOptions().host?(i.log.trace("not dialing %a - target host did not match remote host %a",e,r.remoteAddr),!1):!o.includes(t.host)&&(null!=i.components.transportManager.dialTransportForMultiaddr(e)||(i.log.trace("not dialing %a - transport unsupported",e),!1)))})).map((t=>(null==t.getPeerId()&&(t=t.encapsulate("/p2p/".concat(e.toString()))),t)));if(0===c.length)return i.log("refused to dial all multiaddrs for %p from message",e),{type:zG.MessageType.DIAL_RESPONSE,dialResponse:{status:zG.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}};i.log("dial multiaddrs %s for peer %p",c.map((e=>e.toString())).join(", "),e);var u="",d=c[0];for(var h of c){var p=void 0;d=h;try{if(!(p=yield i.components.connectionManager.openConnection(h,n)).remoteAddr.equals(h))throw i.log.error("tried to dial %a but dialed %a",h,p.remoteAddr),new Error("Unexpected remote address");return i.log("successfully dialed %p via %a",e,h),{type:zG.MessageType.DIAL_RESPONSE,dialResponse:{status:zG.ResponseStatus.OK,addr:p.remoteAddr.decapsulateCode(ir("p2p").code).bytes}}}catch(t){i.log.error("could not dial %p - %e",e,t),u=t.message}finally{null!=p&&(yield p.close())}}return{type:zG.MessageType.DIAL_RESPONSE,dialResponse:{status:zG.ResponseStatus.E_DIAL_ERROR,statusText:u,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(!jG(e.multiaddr))return!1}return!UG(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 oh,queue:new Rh({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(t){var r=this;return e._asyncToGenerator((function*(){if(r.isStarted()){r.removeOutdatedMultiaddrResults();var n=(yield r.components.peerStore.get(t.remotePeer)).addresses.some((e=>{var{multiaddr:t}=e;return 6===t.toOptions().family})),i=r.getNetworkSegment(t.remoteAddr),o=r.getFirstUnverifiedMultiaddr(i,n);null!=o?r.hasConnectionCapacity()?o.queue.add(function(){var n=e._asyncToGenerator((function*(e){yield r.askPeerToVerify(t,i,e)}));return function(e){return n.apply(this,arguments)}}(),{peerId:t.remotePeer,multiaddr:o.multiaddr}).catch((e=>{null==(null==o?void 0:o.result)&&r.log.error("error from %p verifying address %a - %e",t.remotePeer,null==o?void 0:o.multiaddr,e)})):null!=o.lastVerified?(r.log("automatically re-verifying %a because we are too close to the connection limit",o.multiaddr),r.confirmAddress(o)):r.log("skipping verifying %a because we are too close to the connection limit",o.multiaddr):r.log.trace("no unverified public addresses found for peer %p to verify, not requesting verification",t.remotePeer)}}))()}askPeerToVerify(t,r,n){var i=this;return e._asyncToGenerator((function*(){var e=i.dialResults.get(n.multiaddr.toString());if(null!=e){var o=AbortSignal.timeout(i.timeout);i.log.trace("asking %p to verify multiaddr %s",t.remotePeer,n.multiaddr);var a=yield t.newStream(i.protocol,{signal:o});try{var s=Vu(a).pb(zG),[,l]=yield Promise.all([s.write({type:zG.MessageType.DIAL,dial:{peer:{id:i.components.peerId.toMultihash().bytes,addrs:[n.multiaddr.bytes]}}},{signal:o}),s.read({signal:o})]);if(l.type!==zG.MessageType.DIAL_RESPONSE||null==l.dialResponse)return void i.log("invalid autonat response from %p - %j",t.remotePeer,l);var c=l.dialResponse.status;if(i.log.trace("autonat response from %p for %a is %s",t.remotePeer,n.multiaddr,c),c!==zG.ResponseStatus.OK&&c!==zG.ResponseStatus.E_DIAL_ERROR)return;if(null==(e=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(e.networkSegments.includes(r))return void i.log.trace("%a results included network segment %s",n.multiaddr,r);if(null!=e.result)return void i.log.trace("already resolved result for %a, ignoring response from",n.multiaddr,t.remotePeer);if(e.verifyingPeers.has(t.remotePeer))return void i.log.trace("peer %p has already verified %a, ignoring response",t.remotePeer,n.multiaddr);if(e.verifyingPeers.add(t.remotePeer),e.networkSegments.push(r),c===zG.ResponseStatus.OK){if(e.success++,"observed"!==e.type)return void i.confirmAddress(e)}else c===zG.ResponseStatus.E_DIAL_ERROR&&e.failure++;i.log("%a success %d failure %d",e.multiaddr,e.success,e.failure),4===e.success&&i.confirmAddress(e),8===e.failure&&i.unconfirmAddress(e)}finally{try{yield a.close({signal:o})}catch(e){a.abort(e)}}}else i.log("%a was verified while %p was queued",n.multiaddr,t.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 qG(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new VG(t,e)}var HG=SR("dns4"),KG=SR("dns6"),WG=SR("dnsaddr"),QG=_R(SR("dns"),WG,HG,KG),YG=_R(SR("ip4"),SR("ip6")),JG=_R(bR(YG,SR("tcp")),bR(QG,SR("tcp"))),ZG=bR(YG,SR("udp")),$G=bR(ZG,SR("utp")),XG=bR(ZG,SR("quic")),eR=bR(ZG,SR("quic-v1")),tR=_R(bR(JG,SR("ws")),bR(QG,SR("ws"))),rR=_R(bR(tR,SR("p2p")),tR),nR=_R(bR(JG,SR("wss")),bR(QG,SR("wss")),bR(JG,SR("tls"),SR("ws")),bR(QG,SR("tls"),SR("ws"))),iR=_R(bR(nR,SR("p2p")),nR),oR=_R(bR(JG,SR("http")),bR(YG,SR("http")),bR(QG,SR("http"))),aR=_R(bR(JG,SR("https")),bR(YG,SR("https")),bR(QG,SR("https"))),sR=bR(ZG,SR("webrtc-direct"),SR("certhash")),lR=_R(bR(sR,SR("p2p")),sR),cR=bR(eR,SR("webtransport"),SR("certhash"),SR("certhash")),uR=_R(bR(cR,SR("p2p")),cR),dR=_R(bR(rR,SR("p2p-webrtc-star"),SR("p2p")),bR(iR,SR("p2p-webrtc-star"),SR("p2p")),bR(rR,SR("p2p-webrtc-star")),bR(iR,SR("p2p-webrtc-star")));_R(bR(rR,SR("p2p-websocket-star"),SR("p2p")),bR(iR,SR("p2p-websocket-star"),SR("p2p")),bR(rR,SR("p2p-websocket-star")),bR(iR,SR("p2p-websocket-star")));var hR=_R(bR(oR,SR("p2p-webrtc-direct"),SR("p2p")),bR(aR,SR("p2p-webrtc-direct"),SR("p2p")),bR(oR,SR("p2p-webrtc-direct")),bR(aR,SR("p2p-webrtc-direct"))),pR=_R(tR,nR,oR,aR,dR,hR,JG,$G,XG,QG,lR,uR);_R(bR(pR,SR("p2p-stardust"),SR("p2p")),bR(pR,SR("p2p-stardust")));var fR=_R(bR(pR,SR("p2p")),dR,hR,lR,uR,SR("p2p")),vR=_R(bR(fR,SR("p2p-circuit"),fR),bR(fR,SR("p2p-circuit")),bR(SR("p2p-circuit"),fR),bR(pR,SR("p2p-circuit")),bR(SR("p2p-circuit"),pR),SR("p2p-circuit")),yR=()=>_R(bR(vR,yR),vR),gR=yR(),mR=_R(bR(gR,fR,gR),bR(fR,gR),bR(gR,fR),gR,fR);function wR(e){return function(t){var r;try{r=nr(t)}catch(e){return!1}var n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function bR(){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:wR(n),partialMatch:n}}function _R(){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:wR(n),partialMatch:n}}function SR(e){var t=e;return{toString:function(){return t},matches:function(e){var r;try{r=nr(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}}}_R(bR(gR,SR("webrtc"),SR("p2p")),bR(gR,SR("webrtc")),bR(pR,SR("webrtc"),SR("p2p")),bR(pR,SR("webrtc")),SR("webrtc"));class PR extends Aa{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._defineProperty(this,"log",void 0),e._defineProperty(this,"timer",void 0),e._defineProperty(this,"list",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"_init",void 0),e._defineProperty(this,Fo,this),e._defineProperty(this,Symbol.toStringTag,"@libp2p/bootstrap"),e._defineProperty(this,Ba,["@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(mR.matches(i)){var o=nr(i),a=o.getPeerId();if(null!=a){var s={id:$l(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 t=this;return e._asyncToGenerator((function*(){if(null!=t.timer){var e,r=function*(e){var r,n;if(yield t.components.peerStore.merge(e.id,{tags:{[null!==(r=t._init.tagName)&&void 0!==r?r:"bootstrap"]:{value:null!==(n=t._init.tagValue)&&void 0!==n?n:50,ttl:t._init.tagTTL}},multiaddrs:e.multiaddrs}),null==t.timer)return{v:void 0};t.safeDispatchEvent("peer",{detail:e}),t.components.connectionManager.openConnection(e.id).catch((r=>{t.log.error("could not dial bootstrap peer %p",e.id,r)}))};for(var n of t.list)if(e=yield*r(n))return e.v}}))()}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}}e._defineProperty(PR,"tag","bootstrap");var ER=()=>{var e=new Error("Delay aborted");return e.name="AbortError",e},AR=new WeakMap;var kR,xR=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(ER());var l=null!=e?e:clearTimeout,c=()=>{l(n),o(ER())},u=new Promise(((e,l)=>{i=()=>{s&&s.removeEventListener("abort",c),e(a)},o=l,n=(null!=t?t:setTimeout)(i,r)}));return s&&s.addEventListener("abort",c,{once:!0}),AR.set(u,(()=>{l(n),n=null,i()})),u}}();function TR(e,t){return!qd.matches(e)&&(null!=t.dialTransportForMultiaddr(e)&&(!!gd.matches(e)||!!Ad.matches(e)&&!1===kN(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=()=>cl(t)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=ul((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 dl('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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(kR||(kR={}));var IR=5e3,CR=3,BR=1,NR=1;class DR{constructor(t,r){var n,i,o,a;e._defineProperty(this,"started",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"retries",void 0),e._defineProperty(this,"maxInboundStreams",void 0),e._defineProperty(this,"maxOutboundStreams",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"registrar",void 0),e._defineProperty(this,"connectionManager",void 0),e._defineProperty(this,"addressManager",void 0),e._defineProperty(this,"transportManager",void 0),e._defineProperty(this,"topologyId",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/dcutr"),e._defineProperty(this,Na,["@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:IR,this.retries=null!==(i=r.retries)&&void 0!==i?i:CR,this.maxInboundStreams=null!==(o=r.maxInboundStreams)&&void 0!==o?o:BR,this.maxOutboundStreams=null!==(a=r.maxOutboundStreams)&&void 0!==a?a:NR}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){t.started||(t.topologyId=yield t.registrar.register(RR,{notifyOnLimitedConnection:!0,onConnect:(e,r)=>{qd.exactMatch(r.remoteAddr)&&"inbound"===r.direction&&t.upgradeInbound(r).catch((e=>{t.log.error("error during outgoing DCUtR attempt",e)}))}}),yield t.registrar.handle(RR,(e=>{t.handleIncomingUpgrade(e.stream,e.connection).catch((r=>{t.log.error("error during incoming DCUtR attempt",r),e.stream.abort(r)}))}),{maxInboundStreams:t.maxInboundStreams,maxOutboundStreams:t.maxOutboundStreams,runOnLimitedConnection:!0}),t.started=!0)}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield t.registrar.unhandle(RR),null!=t.topologyId&&t.registrar.unregister(t.topologyId),t.started=!1}))()}upgradeInbound(t){var r=this;return e._asyncToGenerator((function*(){if(!(yield r.attemptUnilateralConnectionUpgrade(t)))for(var e,n=0;n<r.retries;n++){var i={signal:AbortSignal.timeout(r.timeout)};try{var o=Vu(e=yield t.newStream([RR],{signal:i.signal,runOnLimitedConnection:!0}),{maxDataLength:4096}).pb(kR);r.log("B sending connect to %p",t.remotePeer);var a=Date.now();yield o.write({type:kR.Type.CONNECT,observedAddresses:r.addressManager.getAddresses().map((e=>e.bytes))},i),r.log("B receiving connect from %p",t.remotePeer);var s=yield o.read(i);if(s.type!==kR.Type.CONNECT)throw r.log("A sent wrong message type"),new ha("DCUtR message type was incorrect");var l=r.getDialableMultiaddrs(s.observedAddresses);if(0===l.length)throw r.log("A did not have any dialable multiaddrs"),new ha("DCUtR connect message had no multiaddrs");var c=Date.now()-a;r.log("A sending sync, rtt %dms",c),yield o.write({type:kR.Type.SYNC,observedAddresses:[]},i),r.log("A waiting for half RTT"),yield xR(c/2),r.log("B dialing",l);var u=yield r.connectionManager.openConnection(l,{signal:i.signal,priority:100,force:!0,initiator:!1});r.log("DCUtR to %p succeeded to address %a, closing relayed connection",t.remotePeer,u.remoteAddr),yield t.close(i);break}catch(t){var d;if(r.log.error("error while attempting DCUtR on attempt %d of %d",n+1,r.retries,t),null===(d=e)||void 0===d||d.abort(t),n===r.retries)throw t}finally{null!=e&&(yield e.close(i))}}}))()}attemptUnilateralConnectionUpgrade(t){var r=this;return e._asyncToGenerator((function*(){var e=(yield r.peerStore.get(t.remotePeer)).addresses.map((e=>{var r=e.multiaddr;return null==r.getPeerId()?r.encapsulate("/p2p/".concat(t.remotePeer)):r})).filter((e=>TR(e,r.transportManager)));if(e.length>0){var n=AbortSignal.timeout(r.timeout);try{r.log("attempting unilateral connection upgrade to %a",e);var i=yield r.connectionManager.openConnection(e,{signal:n,force:!0});if(qd.exactMatch(i.remoteAddr))throw new Error("Could not open a new, non-limited, connection");return r.log("unilateral connection upgrade to %p succeeded via %a, closing relayed connection",t.remotePeer,i.remoteAddr),yield t.close({signal:n}),!0}catch(n){r.log.error("unilateral connection upgrade to %p on addresses %a failed",t.remotePeer,e,n)}}else r.log("peer %p has no public addresses, not attempting unilateral connection upgrade",t.remotePeer);return!1}))()}handleIncomingUpgrade(t,r){var n=this;return e._asyncToGenerator((function*(){var e={signal:AbortSignal.timeout(n.timeout)};try{var i=Vu(t,{maxDataLength:4096}).pb(kR);n.log("A receiving connect");var o=yield i.read(e);if(o.type!==kR.Type.CONNECT)throw n.log("B sent wrong message type"),new ha("DCUtR message type was incorrect");if(0===o.observedAddresses.length)throw n.log("B sent no multiaddrs"),new ha("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 ha("DCUtR connect message had no dialable multiaddrs");if(n.log("A sending connect"),yield i.write({type:kR.Type.CONNECT,observedAddresses:n.addressManager.getAddresses().map((e=>e.bytes))}),n.log("A receiving sync"),(yield i.read(e)).type!==kR.Type.SYNC)throw new ha("DCUtR message type was incorrect");n.log("A dialing",a);var s=yield n.connectionManager.openConnection(a,{signal:e.signal,priority:100,force:!0});n.log("DCUtR to %p succeeded via %a, closing relayed connection",r.remotePeer,s.remoteAddr),yield r.close(e)}catch(e){n.log.error("incoming DCUtR from %p failed",r.remotePeer,e),t.abort(e)}finally{yield t.close(e)}}))()}getDialableMultiaddrs(e){var t=[];for(var r of e)if(null!=r&&0!==r.length)try{var n=nr(r);if(!TR(n,this.transportManager))continue;t.push(n)}catch(e){}return t}}var GR,RR="/libp2p/dcutr";function OR(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new DR(t,e)}var LR=null!==(GR=globalThis.CustomEvent)&&void 0!==GR?GR:Event;function MR(e){return jR.apply(this,arguments)}function jR(){return jR=e._wrapAsyncGenerator((function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(n,i){var o=null!==(n=r.concurrency)&&void 0!==n?n:1/0;o<1&&(o=1/0);var a,s=null!==(i=r.ordered)&&void 0!==i&&i,l=new EventTarget,c=[],u=Hc(),d=Hc(),h=!1,p=!1;function f(){var e;return s?null===(e=c[0])||void 0===e?void 0:e.done:Boolean(c.find((e=>e.done)))}function*v(){for(;c.length>0&&c[0].done;){var e=c[0];if(c.shift(),!e.ok)throw p=!0,u.resolve(),e.err;yield e.value,u.resolve()}}function*y(){for(;f();)for(var e=0;e<c.length;e++)if(c[e].done){var t=c[e];if(c.splice(e,1),e--,!t.ok)throw p=!0,u.resolve(),t.err;yield t.value,u.resolve()}}for(l.addEventListener("task-complete",(()=>{d.resolve()})),Promise.resolve().then(e._asyncToGenerator((function*(){try{var r,n=!1,i=!1;try{for(var s,d=function*(){var e=s.value;if(c.length===o&&(u=Hc(),yield u.promise),p)return 1;var t={done:!1};c.push(t),e().then((e=>{t.done=!0,t.ok=!0,t.value=e,l.dispatchEvent(new LR("task-complete"))}),(e=>{t.done=!0,t.err=e,l.dispatchEvent(new LR("task-complete"))}))},f=e._asyncIterator(t);(n=!(s=yield f.next()).done)&&!(yield*d());n=!1);}catch(e){i=!0,r=e}finally{try{n&&null!=f.return&&(yield f.return())}finally{if(i)throw r}}h=!0,l.dispatchEvent(new LR("task-complete"))}catch(e){a=e,l.dispatchEvent(new LR("task-complete"))}})));;){if(f()||(d=Hc(),yield e._awaitAsyncGenerator(d.promise)),null!=a)throw a;if(s?yield*e._asyncGeneratorDelegate(e._asyncIterator(v())):yield*e._asyncGeneratorDelegate(e._asyncIterator(y())),null!=a)throw a;if(h&&0===c.length)break}}()})),jR.apply(this,arguments)}var FR;!function(e){var t;e.codec=()=>(null==t&&(t=ul((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 dl('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 dl('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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(FR||(FR={}));var UR={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:8192,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnLimitedConnection:!0,concurrency:32};function zR(e,t,r,n,i){return VR.apply(this,arguments)}function VR(){return VR=e._asyncToGenerator((function*(e,t,r,n,i){if(r("received identify from %p",n.remotePeer),null==i)throw new ha("message was null or undefined");var o,a={};if(i.listenAddrs.length>0&&(a.addresses=i.listenAddrs.map((e=>({isCertified:!1,multiaddr:nr(e)})))),i.protocols.length>0&&(a.protocols=i.protocols),null!=i.publicKey){var s=Ml(i.publicKey);if(!Xl(s).equals(n.remotePeer))throw new ha("public key did not match remote PeerId");a.publicKey=s}if(null!=i.signedPeerRecord){r.trace("received signedPeerRecord from %p",n.remotePeer);var l,c=i.signedPeerRecord,u=yield Bu.openAndCertify(c,Ou.DOMAIN),d=Ou.createFromProtobuf(u.payload),h=rc(u.publicKey.toCID());if(!d.peerId.equals(h))throw new ha("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(d.peerId))throw new ha("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 p=yield Bu.createFromProtobuf(l.peerRecordEnvelope),f=Ou.createFromProtobuf(p.payload);f.seqNumber>=d.seqNumber&&(r("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,d.seqNumber),d=f,c=l.peerRecordEnvelope)}a.peerRecordEnvelope=c,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 v={};null!=i.agentVersion&&(v.AgentVersion=nt(i.agentVersion)),null!=i.protocolVersion&&(v.ProtocolVersion=nt(i.protocolVersion)),r.trace("merging %p metadata",n.remotePeer,v),yield e.merge(n.remotePeer,{metadata:v})}var y={peerId:n.remotePeer,protocolVersion:i.protocolVersion,agentVersion:i.agentVersion,publicKey:i.publicKey,listenAddrs:i.listenAddrs.map((e=>nr(e))),observedAddr:null==i.observedAddr?void 0:nr(i.observedAddr),protocols:i.protocols,signedPeerRecord:o,connection:n};return t.safeDispatchEvent("peer:identify",{detail:y}),y})),VR.apply(this,arguments)}class qR{constructor(t,r){var n,i,o,a,s,l,c,u,d;e._defineProperty(this,"host",void 0),e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"started",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"privateKey",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"registrar",void 0),e._defineProperty(this,"addressManager",void 0),e._defineProperty(this,"maxInboundStreams",void 0),e._defineProperty(this,"maxOutboundStreams",void 0),e._defineProperty(this,"maxMessageSize",void 0),e._defineProperty(this,"maxObservedAddresses",void 0),e._defineProperty(this,"events",void 0),e._defineProperty(this,"runOnLimitedConnection",void 0),e._defineProperty(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:UR.timeout,this.maxInboundStreams=null!==(i=r.maxInboundStreams)&&void 0!==i?i:UR.maxInboundStreams,this.maxOutboundStreams=null!==(o=r.maxOutboundStreams)&&void 0!==o?o:UR.maxOutboundStreams,this.maxMessageSize=null!==(a=r.maxMessageSize)&&void 0!==a?a:UR.maxMessageSize,this.maxObservedAddresses=null!==(s=r.maxObservedAddresses)&&void 0!==s?s:UR.maxObservedAddresses,this.runOnLimitedConnection=null!==(l=r.runOnLimitedConnection)&&void 0!==l?l:UR.runOnLimitedConnection,this.host={protocolVersion:"".concat(null!==(c=r.protocolPrefix)&&void 0!==c?c:UR.protocolPrefix,"/").concat("0.1.0"),agentVersion:(u=t.nodeInfo,d=r.agentVersion,null!=d?d:u.userAgent)}}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){t.started||(yield t.peerStore.merge(t.peerId,{metadata:{AgentVersion:nt(t.host.agentVersion),ProtocolVersion:nt(t.host.protocolVersion)}}),yield t.registrar.handle(t.protocol,(e=>{t.handleProtocol(e).catch((e=>{t.log.error(e)}))}),{maxInboundStreams:t.maxInboundStreams,maxOutboundStreams:t.maxOutboundStreams,runOnLimitedConnection:t.runOnLimitedConnection}),t.started=!0)}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield t.registrar.unhandle(t.protocol),t.started=!1}))()}}class HR extends qR{constructor(t){var r,n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(t,e._objectSpread2(e._objectSpread2({},o),{},{protocol:"/".concat(null!==(r=o.protocolPrefix)&&void 0!==r?r:UR.protocolPrefix,"/").concat("id/push","/").concat("1.0.0"),log:t.logger.forComponent("libp2p:identify-push")})),e._defineProperty(this,"connectionManager",void 0),e._defineProperty(this,"concurrency",void 0),e._defineProperty(this,Ba,["@libp2p/identify-push"]),this.connectionManager=t.connectionManager,this.concurrency=null!==(n=o.concurrency)&&void 0!==n?n:UR.concurrency,(null!==(i=o.runOnSelfUpdate)&&void 0!==i?i:UR.runOnSelfUpdate)&&t.events.addEventListener("self:peer:update",(e=>{this.push().catch((e=>{this.log.error(e)}))}))}push(){var t=this;return e._asyncToGenerator((function*(){var r,n;if(t.isStarted()){var i=t.addressManager.getAddresses().map((e=>e.decapsulateCode(ir("p2p").code))),o=new Ou({peerId:t.peerId,multiaddrs:i}),a=yield Bu.seal(o,t.privateKey),s=t.registrar.getProtocols(),l=yield t.peerStore.get(t.peerId),c=Ze(null!==(r=l.metadata.get("AgentVersion"))&&void 0!==r?r:nt(t.host.agentVersion)),u=Ze(null!==(n=l.metadata.get("ProtocolVersion"))&&void 0!==n?n:nt(t.host.protocolVersion)),d=t;yield Tc(MR(function(){return h.apply(this,arguments)}(),{concurrency:t.concurrency}))}function h(){return(h=e._wrapAsyncGenerator((function*(){var t=function*(t){if(!(yield e._awaitAsyncGenerator(d.peerStore.get(t.remotePeer))).protocols.includes(d.protocol))return 1;yield e._asyncToGenerator((function*(){var e,r=AbortSignal.timeout(d.timeout);try{var n=Vu(e=yield t.newStream(d.protocol,{signal:r,runOnLimitedConnection:d.runOnLimitedConnection}),{maxDataLength:d.maxMessageSize}).pb(FR);yield n.write({listenAddrs:i.map((e=>e.bytes)),signedPeerRecord:a.marshal(),protocols:s,agentVersion:c,protocolVersion:u},{signal:r}),yield e.close({signal:r})}catch(t){var o;d.log.error("could not push identify update to peer",t),null===(o=e)||void 0===o||o.abort(t)}}))};for(var r of d.connectionManager.getConnections())yield*t(r)}))).apply(this,arguments)}}))()}handleProtocol(t){var r=this;return e._asyncToGenerator((function*(){var{connection:e,stream:n}=t;try{if(r.peerId.equals(e.remotePeer))throw new Error("received push from ourselves?");var i={signal:AbortSignal.timeout(r.timeout)},o=Vu(n,{maxDataLength:r.maxMessageSize}).pb(FR),a=yield o.read(i);yield n.close(i),yield zR(r.peerStore,r.events,r.log,e,a)}catch(e){return r.log.error("received invalid message",e),void n.abort(e)}r.log.trace("handled push from %p",e.remotePeer)}))()}}class KR extends qR{constructor(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(t,e._objectSpread2(e._objectSpread2({},i),{},{protocol:"/".concat(null!==(r=i.protocolPrefix)&&void 0!==r?r:UR.protocolPrefix,"/").concat("id","/").concat("1.0.0"),log:t.logger.forComponent("libp2p:identify")})),e._defineProperty(this,Ba,["@libp2p/identify"]),(null!==(n=i.runOnConnectionOpen)&&void 0!==n?n:UR.runOnConnectionOpen)&&t.events.addEventListener("connection:open",(e=>{var t=e.detail;this.identify(t).catch((e=>{e.name!==da.name&&this.log.error("error during identify trigged by connection:open",e)}))}))}_identify(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i,o=r.length>1&&void 0!==r[1]?r[1]:{};if(null==o.signal){var a=AbortSignal.timeout(n.timeout);o=e._objectSpread2(e._objectSpread2({},o),{},{signal:a})}try{var s=Vu(i=yield t.newStream(n.protocol,e._objectSpread2(e._objectSpread2({},o),{},{runOnLimitedConnection:n.runOnLimitedConnection})),{maxDataLength:n.maxMessageSize}).pb(FR),l=yield s.read(o);return yield i.close(o),l}catch(e){var c;throw null===(c=i)||void 0===c||c.abort(e),e}}))()}identify(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{},i=yield n._identify(t,e),{publicKey:o,protocols:a,observedAddr:s}=i;if(null==o)throw new ha("public key was missing from identify message");var l=rc(Ml(o).toCID());if(!t.remotePeer.equals(l))throw new ha("identified peer does not match the expected peer");if(n.peerId.equals(l))throw new ha("identified peer is our own peer id?");return n.maybeAddObservedAddress(s),n.log("identify completed for peer %p and protocols %o",l,a),zR(n.peerStore,n.events,n.log,t,i)}))()}maybeAddObservedAddress(e){var t=function(e){if(null!=e&&e.length>0)try{return nr(e)}catch(e){}}(e);null!=t&&(this.log.trace("our observed address was %a",t),UG(t)?this.log.trace("our observed address was private"):41!==t.stringTuples()[0][0]||jG(t)?Td.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(t){var r=this;return e._asyncToGenerator((function*(){var{connection:e,stream:n}=t,i=AbortSignal.timeout(r.timeout);try{var o=yield r.peerStore.get(r.peerId),a=r.addressManager.getAddresses().map((e=>e.decapsulateCode(ir("p2p").code))),s=o.peerRecordEnvelope;if(a.length>0&&null==s){var l=new Ou({peerId:r.peerId,multiaddrs:a});s=(yield Bu.seal(l,r.privateKey)).marshal().subarray()}var c=e.remoteAddr.bytes;Sd.matches(e.remoteAddr)||(c=void 0);var u=Vu(n).pb(FR);yield u.write({protocolVersion:r.host.protocolVersion,agentVersion:r.host.agentVersion,publicKey:Fl(r.privateKey.publicKey),listenAddrs:a.map((e=>e.bytes)),signedPeerRecord:s,observedAddr:c,protocols:o.protocols},{signal:i}),yield n.close({signal:i})}catch(e){r.log.error("could not respond to identify request",e),n.abort(e)}}))()}}function WR(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new KR(t,e)}function QR(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new HR(t,e)}var YR,JR,ZR,$R,XR,eO,tO,rO,nO=36e5,iO=36*nO,oO=48*nO,aO=nO,sO="".concat(Ho,"-kad-dht");function lO(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=ul((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:He(0),value:He(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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(YR||(YR={}));class cO{constructor(t,r,n){if(e._defineProperty(this,"key",void 0),e._defineProperty(this,"value",void 0),e._defineProperty(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 YR.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:lO(this.timeReceived)}}static deserialize(e){var t=YR.decode(e);return new cO(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),c=parseInt(r[7].slice(0,-6),10);return new Date(Date.UTC(n,i,o,a,s,l,c))}(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 cO(e.key,e.value,t)}}class uO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Query error"),this.name="QueryError"}}class dO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Query aborted"),this.name="QueryAbortedError"}}class hO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid record"),this.name="InvalidRecordError"}}class pO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No selector function configured for prefix"),this.name="MissingSelectorError"}}function fO(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e._objectSpread2(e._objectSpread2({},t),{},{name:"SEND_QUERY",type:0,messageName:t.type,messageType:t.type});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:send-query",{detail:i})),i}function vO(t){var r,n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=e._objectSpread2(e._objectSpread2({},t),{},{name:"PEER_RESPONSE",type:1,messageName:t.messageType,closer:null!==(r=t.closer)&&void 0!==r?r:[],providers:null!==(n=t.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 yO(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e._objectSpread2(e._objectSpread2({},t),{},{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 gO(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e._objectSpread2(e._objectSpread2({},t),{},{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 mO(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e._objectSpread2(e._objectSpread2({},t),{},{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 wO(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e._objectSpread2(e._objectSpread2({},t),{},{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 bO(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e._objectSpread2(e._objectSpread2({},t),{},{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=ul((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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(JR||(JR={})),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"}(ZR||(ZR={})),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"}($R||($R={})),function(e){e.codec=()=>cl($R)}(ZR||(ZR={})),function(e){e.NOT_CONNECTED="NOT_CONNECTED",e.CONNECTED="CONNECTED",e.CAN_CONNECT="CAN_CONNECT",e.CANNOT_CONNECT="CANNOT_CONNECT"}(XR||(XR={})),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"}(eO||(eO={})),function(e){e.codec=()=>cl(eO)}(XR||(XR={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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),XR.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:He(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 dl('Decode error - map field "multiaddrs" had too many elements');n.multiaddrs.push(e.bytes());break;case 3:n.connection=XR.codec().decode(e);break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(tO||(tO={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.type&&0!==$R[e.type]&&(t.uint32(8),ZR.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),tO.codec().encode(n,t);if(null!=e.providers)for(var i of e.providers)t.uint32(74),tO.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:ZR.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=ZR.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 dl('Decode error - map field "closer" had too many elements');n.closer.push(tO.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.closer$}));break;case 9:var l,c;if(null!=(null===(l=r.limits)||void 0===l?void 0:l.providers)&&n.providers.length===r.limits.providers)throw new dl('Decode error - map field "providers" had too many elements');n.providers.push(tO.codec().decode(e,e.uint32(),{limits:null===(c=r.limits)||void 0===c?void 0:c.providers$}));break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(rO||(rO={}));var _O={pk:function(e,t){return 0}};function SO(e,t){return PO.apply(this,arguments)}function PO(){return PO=e._asyncToGenerator((function*(e,t){var r=t.key,n=Ze(r).split("/");if(!(n.length<3)){var i=e[n[1].toString()];if(null==i)throw new Jo('No validator available for key type "'.concat(n[1],'"'));yield i(r,t.value)}})),PO.apply(this,arguments)}var EO=function(){var t=e._asyncToGenerator((function*(e,t){if(!(e instanceof Uint8Array))throw new Jo('"key" must be a Uint8Array');if(e.byteLength<5)throw new Jo("Invalid public key record");if("/pk/"!==Ze(e.subarray(0,4)))throw new Jo("key was not prefixed with /pk/");var r=Ml(t);if(!rt(e.slice(4),r.toMultihash().bytes))throw new Jo("public key does not match passed in key")}));return function(e,r){return t.apply(this,arguments)}}(),AO={pk:EO},kO=nt("/pk/");function xO(t){return e._objectSpread2(e._objectSpread2({},t),{},{multiaddrs:t.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=kN(r);return null==n||!n}))})}function TO(e){return IO.apply(this,arguments)}function IO(){return IO=e._asyncToGenerator((function*(e){return(yield De.digest(e)).digest})),IO.apply(this,arguments)}function CO(e){return BO.apply(this,arguments)}function BO(){return BO=e._asyncToGenerator((function*(e){return TO(e.toMultihash().bytes)})),BO.apply(this,arguments)}function NO(e,t){return new xc("".concat(e,"/").concat(Ze(t,"base32")),!1)}function DO(e,t){var r=new Date;return new cO(e,t,r).serialize()}function GO(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:je.createV1(re,Ae(nt(n,"base32"))),peerId:$l(r)}}function RO(e,t,r){var n=[e,"string"==typeof t?t:Ze(t.multihash.bytes,"base32")];return null!=r&&n.push(r.toString()),new xc(n.join("/"))}function OO(e){return new Date(gt(e))}function LO(t,r,n){return e._wrapAsyncGenerator((function*(){var i,o,a=null===(i=r.queryTime)||void 0===i?void 0:i.timer(n),s=null===(o=r.errorTime)||void 0===o?void 0:o.timer(n),l=!1;try{var c;null===(c=r.queries)||void 0===c||c.increment({[n]:!0}),yield*e._asyncGeneratorDelegate(e._asyncIterator(t(...arguments)),e._awaitAsyncGenerator)}catch(e){var u;throw l=!0,null==s||s(),null===(u=r.errors)||void 0===u||u.increment({[n]:!0}),e}finally{var d;null===(d=r.queries)||void 0===d||d.decrement({[n]:!0}),l||null==a||a()}}))}function MO(t,r,n){return e._asyncToGenerator((function*(){var e,i,o=null==r||null===(e=r.queryTime)||void 0===e?void 0:e.timer(n),a=null==r||null===(i=r.errorTime)||void 0===i?void 0:i.timer(n),s=!1;try{var l;return null===(l=r.queries)||void 0===l||l.increment({[n]:!0}),yield t(...arguments)}catch(e){var c;throw s=!0,null==a||a(),null===(c=r.errors)||void 0===c||c.increment({[n]:!0}),e}finally{var u;null===(u=r.queries)||void 0===u||u.decrement({[n]:!0}),s||null==o||o()}}))}class jO{constructor(t,r){var n,i,o,a;e._defineProperty(this,"log",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"validators",void 0),e._defineProperty(this,"selectors",void 0),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"queryManager",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"datastorePrefix",void 0);var{validators:s,selectors:l,peerRouting:c,queryManager:u,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=c,this.queryManager=u,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(t){var r=this;return e._asyncToGenerator((function*(){r.log("getLocal %b",t);var e=NO(r.datastorePrefix,t);r.log("fetching record for key %k",e);var n=yield r.components.datastore.get(e);r.log("found %k in local datastore",e);var i=cO.deserialize(n);return yield SO(r.validators,i),i}))()}sendCorrectionRecord(t,r,n){var i=this;return e._wrapAsyncGenerator((function(t,r,n){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return function*(){i.log("sendCorrection for %b",t);var a=DO(t,n);for(var{value:s,from:l}of r)if(rt(s,n))i.log("record was ok");else if(i.components.peerId.equals(l))try{var c=NO(i.datastorePrefix,t);i.log("Storing corrected record for key ".concat(c.toString())),yield e._awaitAsyncGenerator(i.components.datastore.put(c,a.subarray()))}catch(e){i.log.error("Failed error correcting self",e)}else{var u,d=!1,h={type:ZR.PUT_VALUE,key:t,record:a},p=!1,f=!1;try{for(var v,y=e._asyncIterator(i.network.sendRequest(l,h,o));p=!(v=yield e._awaitAsyncGenerator(y.next())).done;p=!1){var g=v.value;"PEER_RESPONSE"===g.name&&null!=g.record&&rt(g.record.value,cO.deserialize(a).value)&&(d=!0),yield g}}catch(e){f=!0,u=e}finally{try{p&&null!=y.return&&(yield e._awaitAsyncGenerator(y.return()))}finally{if(f)throw u}}d||(yield gO({from:l,error:new uO("Value not put correctly")},o)),i.log.error("Failed error correcting entry")}}()})).apply(this,arguments)}put(t,r){var n=this;return e._wrapAsyncGenerator((function(t,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){n.log("put key %b value %b",t,r);var o=DO(t,r),a=NO(n.datastorePrefix,t);n.log("storing record for key ".concat(a.toString())),yield e._awaitAsyncGenerator(n.components.datastore.put(a,o.subarray())),yield*e._asyncGeneratorDelegate(e._asyncIterator(iu(n.peerRouting.getClosestPeers(t,e._objectSpread2(e._objectSpread2({},i),{},{signal:i.signal})),(r=>qc(r,(r=>e._asyncToGenerator((function*(){if("FINAL_PEER"!==r.name)return[r];var a=[],s={type:ZR.PUT_VALUE,key:t,record:o};n.log("send put to %p",r.peer.id);var l,c=!1,u=!1;try{for(var d,h=e._asyncIterator(n.network.sendRequest(r.peer.id,s,i));c=!(d=yield h.next()).done;c=!1){var p=d.value;(a.push(p),"PEER_RESPONSE"===p.name)&&(null!=p.record&&rt(p.record.value,cO.deserialize(o).value)||a.push(gO({from:r.peer.id,error:new uO("Value not put correctly")},i)))}}catch(e){u=!0,l=e}finally{try{c&&null!=h.return&&(yield h.return())}finally{if(u)throw l}}return a}))))),(e=>MR(e,{ordered:!1,concurrency:3})),function(){var t=e._wrapAsyncGenerator((function*(t){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t);n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var s=o.value;yield*e._asyncGeneratorDelegate(e._asyncIterator(s),e._awaitAsyncGenerator)}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw r}}}));return function(e){return t.apply(this,arguments)}}())))}()})).apply(this,arguments)}get(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){r.log("get %b",t);var i,o=[],a=!1,s=!1;try{for(var l,c=e._asyncIterator(r.getMany(t,n));a=!(l=yield e._awaitAsyncGenerator(c.next())).done;a=!1){var u=l.value;"VALUE"===u.name&&o.push(u),yield u}}catch(e){s=!0,i=e}finally{try{a&&null!=c.return&&(yield e._awaitAsyncGenerator(c.return()))}finally{if(s)throw i}}if(0!==o.length){var d=o.map((e=>e.value)),h=0;try{h=function(e,t,r){if(0===r.length)throw new Jo("No records given");var n=Ze(t).split("/");if(n.length<3)throw new Jo("Record key does not have a selector function");var i=e[n[1].toString()];if(null==i)throw new pO('No selector function configured for key type "'.concat(n[1],'"'));return 1===r.length?0:i(t,r)}(r.selectors,t,d)}catch(e){if("InvalidParametersError"!==e.name)throw e}var p=d[h];if(r.log("GetValue %b %b",t,p),null==p)throw new aa("Best value was not found");yield*e._asyncGeneratorDelegate(e._asyncIterator(r.sendCorrectionRecord(t,o,p,n))),yield o[h]}}()})).apply(this,arguments)}getMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){r.log("getMany values for %b",t);try{var i=yield e._awaitAsyncGenerator(r.getLocal(t));yield wO({value:i.value,from:r.components.peerId},n)}catch(e){r.log("error getting local value for %b",t,e)}var o=r,a=function(){var r=e._wrapAsyncGenerator((function(r){var{peer:i,signal:a}=r;return function*(){var r,s=!1,l=!1;try{for(var c,u=e._asyncIterator(o.peerRouting.getValueOrPeers(i,t,e._objectSpread2(e._objectSpread2({},n),{},{signal:a})));s=!(c=yield e._awaitAsyncGenerator(u.next())).done;s=!1){var d=c.value;yield d,"PEER_RESPONSE"===d.name&&null!=d.record&&(yield wO({from:i,value:d.record.value},n))}}catch(e){l=!0,r=e}finally{try{s&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(l)throw r}}}()}));return function(e){return r.apply(this,arguments)}}();yield*e._asyncGeneratorDelegate(e._asyncIterator(r.queryManager.run(t,a,n)))}()})).apply(this,arguments)}}function FO(e){var t;if(null==e.id)throw new Error("Invalid peer in message");return{id:tc(Ae(e.id)),multiaddrs:(null!==(t=e.multiaddrs)&&void 0!==t?t:[]).map((e=>nr(e)))}}class UO{constructor(t,r){var n,i,o,a;e._defineProperty(this,"log",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"queryManager",void 0),e._defineProperty(this,"routingTable",void 0),e._defineProperty(this,"providers",void 0);var{network:s,peerRouting:l,queryManager:c,routingTable:u,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=c,this.routingTable=u,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(t,r){var n=this;return e._wrapAsyncGenerator((function(t,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){n.log("provide %s",t);var o=t.multihash.bytes;yield e._awaitAsyncGenerator(n.providers.addProvider(t,n.components.peerId));var a,s,l,c,u={type:ZR.ADD_PROVIDER,key:o,providers:[(a={id:n.components.peerId,multiaddrs:r},c={id:a.id.toMultihash().bytes,multiaddrs:(null!==(l=a.multiaddrs)&&void 0!==l?l:[]).map((e=>e.bytes)),connection:s},c)]},d=0;yield*e._asyncGeneratorDelegate(e._asyncIterator(iu(n.peerRouting.getClosestPeers(o,i),(r=>qc(r,(r=>(r=>e._asyncToGenerator((function*(){if("FINAL_PEER"!==r.name)return[r];var o=[];n.log("putProvider %s to %p",t,r.peer.id);try{n.log("sending provider record for %s to %p",t,r.peer.id);var a,s=!1,l=!1;try{for(var c,h=e._asyncIterator(n.network.sendMessage(r.peer.id,u,i));s=!(c=yield h.next()).done;s=!1){var p=c.value;"PEER_RESPONSE"===p.name&&(n.log("sent provider record for %s to %p",t,r.peer.id),d++),o.push(p)}}catch(e){l=!0,a=e}finally{try{s&&null!=h.return&&(yield h.return())}finally{if(l)throw a}}}catch(e){n.log.error("error sending provide record to peer %p",r.peer.id,e),o.push(gO({from:r.peer.id,error:e},i))}return o})))(r)))),(e=>MR(e,{ordered:!1,concurrency:3})),function(){var t=e._wrapAsyncGenerator((function*(t){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t);n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var s=o.value;yield*e._asyncGeneratorDelegate(e._asyncIterator(s),e._awaitAsyncGenerator)}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw r}}}));return function(e){return t.apply(this,arguments)}}()))),n.log("sent provider records to %d peers",d)}()})).apply(this,arguments)}findProviders(t,r){var n=this;return e._wrapAsyncGenerator((function*(){var i=n.routingTable.kBucketSize,o=0,a=t.multihash.bytes,s=n;n.log("findProviders %c",t);var l=yield e._awaitAsyncGenerator(n.providers.getProviders(t));if(l.length>0){var c=[];for(var u of l.slice(0,i))try{var d=yield e._awaitAsyncGenerator(n.components.peerStore.get(u));c.push({id:u,multiaddrs:d.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",u)}if(yield vO({from:n.components.peerId,messageType:ZR.GET_PROVIDERS,providers:c},r),yield mO({from:n.components.peerId,providers:c},r),(o+=c.length)>=i)return}var h,p=function(){var t=e._wrapAsyncGenerator((function(t){var{peer:n,signal:i}=t;return function*(){var t={type:ZR.GET_PROVIDERS,key:a};yield*e._asyncGeneratorDelegate(e._asyncIterator(s.network.sendRequest(n,t,e._objectSpread2(e._objectSpread2({},r),{},{signal:i}))))}()}));return function(e){return t.apply(this,arguments)}}(),f=new oh(l),v=!1,y=!1;try{for(var g,m=e._asyncIterator(n.queryManager.run(a,p,r));v=!(g=yield e._awaitAsyncGenerator(m.next())).done;v=!1){var w=g.value;if(yield w,"PEER_RESPONSE"===w.name){n.log("Found %d provider entries for %c and %d closer peers",w.providers.length,t,w.closer.length);var b=[];for(var _ of w.providers)f.has(_.id)||(f.add(_.id),b.push(_));if(b.length>0&&(yield mO({from:w.from,providers:b},r),(o+=b.length)>=i))return}}}catch(e){y=!0,h=e}finally{try{v&&null!=m.return&&(yield e._awaitAsyncGenerator(m.return()))}finally{if(y)throw h}}}))()}}class zO{constructor(t){e._defineProperty(this,"movingAverage",void 0),e._defineProperty(this,"variance",void 0),e._defineProperty(this,"deviation",void 0),e._defineProperty(this,"forecast",void 0),e._defineProperty(this,"timeSpan",void 0),e._defineProperty(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 VO{constructor(){var t,r,n,i,o,a,s,l=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e._defineProperty(this,"success",void 0),e._defineProperty(this,"failure",void 0),e._defineProperty(this,"next",void 0),e._defineProperty(this,"metric",void 0),e._defineProperty(this,"timeoutMultiplier",void 0),e._defineProperty(this,"failureMultiplier",void 0),e._defineProperty(this,"minTimeout",void 0),this.success=new zO(null!==(t=l.interval)&&void 0!==t?t:5e3),this.failure=new zO(null!==(r=l.interval)&&void 0!==r?r:5e3),this.next=new zO(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=Qd([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 qO{constructor(){e._defineProperty(this,"readNext",void 0),e._defineProperty(this,"haveNext",void 0),e._defineProperty(this,"ended",void 0),e._defineProperty(this,"nextResult",void 0),this.ended=!1,this.readNext=Hc(),this.haveNext=Hc()}[Symbol.asyncIterator](){return this}next(){var t=this;return e._asyncToGenerator((function*(){if(null==t.nextResult&&(yield t.haveNext.promise),null==t.nextResult)throw new Error("HaveNext promise resolved but nextResult was undefined");var e=t.nextResult;return t.nextResult=void 0,t.readNext.resolve(),t.readNext=Hc(),e}))()}throw(t){var r=this;return e._asyncToGenerator((function*(){return r.ended=!0,null!=t&&(r.haveNext.promise.catch((()=>{})),r.haveNext.reject(t)),{done:!0,value:void 0}}))()}return(){var t=this;return e._asyncToGenerator((function*(){var e={done:!0,value:void 0};return t.ended=!0,t.nextResult=e,t.haveNext.resolve(),e}))()}push(t,r){var n=this;return e._asyncToGenerator((function*(){yield n._push(t,r)}))()}end(t,r){var n=this;return e._asyncToGenerator((function*(){null!=t?yield n.throw(t):yield n._push(void 0,r)}))()}_push(t,r){var n=this;return e._asyncToGenerator((function*(){if(null!=t&&n.ended)throw new Error("Cannot push value onto an ended pushable");for(;null!=n.nextResult;)yield n.readNext.promise;null!=t?n.nextResult={done:!1,value:t}:(n.ended=!0,n.nextResult={done:!0,value:void 0}),n.haveNext.resolve(),n.haveNext=Hc(),yield Zc(n.readNext.promise,null==r?void 0:r.signal,r)}))()}}class HO extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","UnexpectedEOFError"),e._defineProperty(this,"code","ERR_UNEXPECTED_EOF")}}class KO extends Error{constructor(t,r){super(t),e._defineProperty(this,"code",void 0),this.code=r}}let WO=class extends KO{constructor(t){super(t,"ABORT_ERR"),e._defineProperty(this,"type",void 0),this.type="aborted",this.name="AbortError"}};function QO(t,r){var n=new qO;t.sink(n).catch(function(){var t=e._asyncToGenerator((function*(e){yield n.end(e)}));return function(e){return t.apply(this,arguments)}}()),t.sink=function(){var t=e._asyncToGenerator((function*(t){var r,i=!1,o=!1;try{for(var a,s=e._asyncIterator(t);i=!(a=yield s.next()).done;i=!1){var l=a.value;yield n.push(l)}}catch(e){o=!0,r=e}finally{try{i&&null!=s.return&&(yield s.return())}finally{if(o)throw r}}yield n.end()}));return function(e){return t.apply(this,arguments)}}();var i=t.source;null!=t.source[Symbol.iterator]?i=t.source[Symbol.iterator]():null!=t.source[Symbol.asyncIterator]&&(i=t.source[Symbol.asyncIterator]());var o,a=new Oa,s={read:function(){var t=e._asyncToGenerator((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 WO("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 Oa:l}for(;a.byteLength<e;){var{value:c,done:u}=yield Promise.race([i.next(),o]);if(!0===u)throw new HO("unexpected end of input");a.append(c)}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(e,r){return t.apply(this,arguments)}}(),write:(o=e._asyncToGenerator((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 n=t.source;t.source=e._wrapAsyncGenerator((function*(){!1===(null==r?void 0:r.yieldBytes)?yield a:yield*e._asyncGeneratorDelegate(e._asyncIterator(a)),yield*e._asyncGeneratorDelegate(e._asyncIterator(n))}))()}return t}};return s}class YO extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidMessageLengthError"),e._defineProperty(this,"code","ERR_INVALID_MSG_LENGTH")}}class JO extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidDataLengthError"),e._defineProperty(this,"code","ERR_MSG_DATA_TOO_LONG")}}class ZO extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidDataLengthLengthError"),e._defineProperty(this,"code","ERR_MSG_LENGTH_TOO_LONG")}}function $O(t,r){var n,i=function(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=QO(t,i);null!=i.maxDataLength&&null==i.maxLengthLength&&(i.maxLengthLength=pt(i.maxDataLength));var a,s=null!==(r=null==i?void 0:i.lengthDecoder)&&void 0!==r?r:gt,l=null!==(n=null==i?void 0:i.lengthEncoder)&&void 0!==n?n:yt,c={read:function(){var t=e._asyncToGenerator((function*(e){for(var t=-1,r=new Oa;;){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 YO("Invalid message length");if(null!=(null==i?void 0:i.maxLengthLength)&&r.byteLength>i.maxLengthLength)throw new ZO("message length length too long");if(t>-1)break}if(null!=(null==i?void 0:i.maxDataLength)&&t>i.maxDataLength)throw new JO("message length too long");return o.read(t,e)}));return function(e){return t.apply(this,arguments)}}(),write:function(){var t=e._asyncToGenerator((function*(e,t){yield o.write(new Oa(l(e.byteLength),e),t)}));return function(e,r){return t.apply(this,arguments)}}(),writeV:(a=e._asyncToGenerator((function*(e,t){var r=new Oa(...e.flatMap((e=>[l(e.byteLength),e])));yield o.write(r,t)})),function(e,t){return a.apply(this,arguments)}),unwrap:()=>o.unwrap()};return c}(t,r),o={read:function(){var t=e._asyncToGenerator((function*(e,t){var r=yield i.read(t);return e.decode(r)}));return function(e,r){return t.apply(this,arguments)}}(),write:function(){var t=e._asyncToGenerator((function*(e,t,r){yield i.write(t.encode(e),r)}));return function(e,r,n){return t.apply(this,arguments)}}(),writeV:(n=e._asyncToGenerator((function*(e,t,r){yield i.writeV(e.map((e=>t.encode(e))),r)})),function(e,t,r){return n.apply(this,arguments)}),pb:t=>{return{read:(i=e._asyncToGenerator((function*(e){return o.read(t,e)})),function(e){return i.apply(this,arguments)}),write:(n=e._asyncToGenerator((function*(e,r){return o.write(e,t,r)})),function(e,t){return n.apply(this,arguments)}),writeV:(r=e._asyncToGenerator((function*(e,r){return o.writeV(e,t,r)})),function(e,t){return r.apply(this,arguments)}),unwrap:()=>o};var r,n,i},unwrap:()=>i.unwrap()};return o}class XO extends Aa{constructor(t,r){var n,i,o,a,s,l,c;super(),e._defineProperty(this,"log",void 0),e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"running",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"metrics",void 0),this.components=t,this.log=t.logger.forComponent("".concat(r.logPrefix,":network")),this.running=!1,this.protocol=r.protocol,this.timeout=new VO(e._objectSpread2(e._objectSpread2({},null!==(n=r.timeout)&&void 0!==n?n:{}),{},{metrics:t.metrics,metricName:"".concat(r.metricsPrefix,"_network_message_send_times_milliseconds")})),this.metrics={operations:null===(i=t.metrics)||void 0===i?void 0:i.registerCounterGroup("".concat(r.metricsPrefix,"_outbound_rpc_requests_total")),errors:null===(o=t.metrics)||void 0===o?void 0:o.registerCounterGroup("".concat(r.metricsPrefix,"_outbound_rpc_errors_total"))},this.sendRequest=null!==(a=null===(s=t.metrics)||void 0===s?void 0:s.traceFunction("libp2p.kadDHT.sendRequest",this.sendRequest.bind(this),{optionsIndex:2,getAttributesFromArgs(t,r){var[n,i]=t;return e._objectSpread2(e._objectSpread2({},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!==a?a:this.sendRequest,this.sendMessage=null!==(l=null===(c=t.metrics)||void 0===c?void 0:c.traceFunction("libp2p.kadDHT.sendMessage",this.sendMessage.bind(this),{optionsIndex:2,getAttributesFromArgs(t,r){var[n,i]=t;return e._objectSpread2(e._objectSpread2({},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!==l?l:this.sendMessage}start(){var t=this;return e._asyncToGenerator((function*(){t.running||(t.running=!0)}))()}stop(){var t=this;return e._asyncToGenerator((function*(){t.running=!1}))()}isStarted(){return this.running}sendRequest(t,r){var n=this;return e._wrapAsyncGenerator((function(t,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 Jo("Message type was missing");n.log("sending %s to %p",r.type,t),yield bO({peer:t},i),yield fO({to:t,type:a},i);var s=n.timeout.getTimeoutSignal(i);i=e._objectSpread2(e._objectSpread2({},i),{},{signal:s});try{var l;null===(l=n.metrics.operations)||void 0===l||l.increment({[a]:!0});var c=yield e._awaitAsyncGenerator(n.components.connectionManager.openConnection(t,i));o=yield e._awaitAsyncGenerator(c.newStream(n.protocol,i));var u=yield e._awaitAsyncGenerator(n._writeReadMessage(o,r,i));o.close(i).catch((e=>{var r;n.log.error("error closing stream to %p",t,e),null===(r=o)||void 0===r||r.abort(e)})),yield vO({from:t,messageType:u.type,closer:u.closer.map(FO),providers:u.providers.map(FO),record:null==u.record?void 0:cO.deserialize(u.record)},i)}catch(e){var d,h,p;null===(d=n.metrics.errors)||void 0===d||d.increment({[a]:!0}),null===(h=o)||void 0===h||h.abort(e),!0!==(null===(p=i.signal)||void 0===p?void 0:p.aborted)&&n.log.error("could not send %s to %p - %e",r.type,t,e),yield gO({from:t,error:e},i)}finally{n.timeout.cleanUp(s)}}}()})).apply(this,arguments)}sendMessage(t,r){var n=this;return e._wrapAsyncGenerator((function(t,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 Jo("Message type was missing");n.log("sending %s to %p",r.type,t),yield bO({peer:t},i),yield fO({to:t,type:a},i);var s=n.timeout.getTimeoutSignal(i);i=e._objectSpread2(e._objectSpread2({},i),{},{signal:s});try{var l;null===(l=n.metrics.operations)||void 0===l||l.increment({[a]:!0});var c=yield e._awaitAsyncGenerator(n.components.connectionManager.openConnection(t,i));o=yield e._awaitAsyncGenerator(c.newStream(n.protocol,i)),yield e._awaitAsyncGenerator(n._writeMessage(o,r,i)),o.close(i).catch((e=>{var r;n.log.error("error closing stream to %p",t,e),null===(r=o)||void 0===r||r.abort(e)})),yield vO({from:t,messageType:a},i)}catch(e){var u,d;null===(u=n.metrics.errors)||void 0===u||u.increment({[a]:!0}),null===(d=o)||void 0===d||d.abort(e),yield gO({from:t,error:e},i)}finally{n.timeout.cleanUp(s)}}}()})).apply(this,arguments)}_writeMessage(t,r,n){return e._asyncToGenerator((function*(){var e=$O(t);yield e.write(r,rO,n)}))()}_writeReadMessage(t,r,n){var i=this;return e._asyncToGenerator((function*(){var e=$O(t);yield e.write(r,rO,n);var o=yield e.read(rO,n);return o.closer.forEach((e=>{i.safeDispatchEvent("peer",{detail:FO(e)})})),o.providers.forEach((e=>{i.safeDispatchEvent("peer",{detail:FO(e)})})),o}))()}}function eL(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 tL{constructor(t,r){e._defineProperty(this,"originDhtKey",void 0),e._defineProperty(this,"capacity",void 0),e._defineProperty(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(t){var r=this;return e._asyncToGenerator((function*(){var e=yield CO(t.id);r.addWithKadId(t,e)}))()}addWithKadId(e,t){if(null==this.peerDistances.find((t=>t.peer.id.equals(e.id)))){for(var r={peer:e,distance:Ik(this.originDhtKey,t)},n=!1,i=0;i<this.peerDistances.length;i++){var o=eL(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(t){var r=this;return e._asyncToGenerator((function*(){return 0===r.length||-1===eL(Ik(yield CO(t),r.originDhtKey),r.peerDistances[r.peerDistances.length-1].distance)}))()}anyCloser(t){var r=this;return e._asyncToGenerator((function*(){return 0!==t.length&&Promise.any(t.map(function(){var t=e._asyncToGenerator((function*(e){return r.isCloser(e)}));return function(e){return t.apply(this,arguments)}}()))}))()}}class rL{constructor(t,r){var n,i,o,a;e._defineProperty(this,"log",void 0),e._defineProperty(this,"routingTable",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"validators",void 0),e._defineProperty(this,"queryManager",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(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(t){var r=this;return e._asyncToGenerator((function*(){var e,n=yield r.routingTable.find(t);if(null!=n){r.log("findPeerLocal found %p in routing table",t);try{e=yield r.peerStore.get(n)}catch(e){if("NotFoundError"!==e.name)throw e}}if(null==e)try{e=yield r.peerStore.get(t)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=e)return r.log("findPeerLocal found %p in peer store",t),{id:e.id,multiaddrs:e.addresses.map((e=>e.multiaddr))}}))()}_getValueSingle(t,r){var n=this;return e._wrapAsyncGenerator((function(t,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var o={type:ZR.GET_VALUE,key:r};yield*e._asyncGeneratorDelegate(e._asyncIterator(n.network.sendRequest(t,o,i)))}()})).apply(this,arguments)}getPublicKeyFromNode(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var i,o=function(e){return mt([kO,e.toMultihash().bytes])}(t),a=!1,s=!1;try{for(var l,c=e._asyncIterator(r._getValueSingle(t,o,n));a=!(l=yield e._awaitAsyncGenerator(c.next())).done;a=!1){var u=l.value;if(yield u,"PEER_RESPONSE"===u.name&&null!=u.record){var d=Xl(Ml(u.record.value));if(!d.equals(t))throw new Zo("public key does not match id");if(null==d.publicKey)throw new Zo("public key missing");yield wO({from:t,value:u.record.value},n)}}}catch(e){s=!0,i=e}finally{try{a&&null!=c.return&&(yield e._awaitAsyncGenerator(c.return()))}finally{if(s)throw i}}throw new uO("Node not responding with its public key: ".concat(t.toString()))}()})).apply(this,arguments)}findPeer(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(r.log("findPeer %p",t),!1!==n.useCache){var i=yield e._awaitAsyncGenerator(r.findPeerLocal(t));if(null!=i)return r.log("found local"),void(yield yO({from:r.peerId,peer:i},n))}var o=!1;if(!1!==n.useNetwork){var a,s=r,l=function(){var r=e._wrapAsyncGenerator((function(r){var{peer:i,signal:o}=r;return function*(){var r,a={type:ZR.FIND_NODE,key:t.toMultihash().bytes},l=!1,c=!1;try{for(var u,d=e._asyncIterator(s.network.sendRequest(i,a,e._objectSpread2(e._objectSpread2({},n),{},{signal:o})));l=!(u=yield e._awaitAsyncGenerator(d.next())).done;l=!1){var h=u.value;if(yield h,"PEER_RESPONSE"===h.name){var p=h.closer.find((e=>e.id.equals(t)));null!=p&&(yield yO({from:h.from,peer:p},n))}}}catch(e){c=!0,r=e}finally{try{l&&null!=d.return&&(yield e._awaitAsyncGenerator(d.return()))}finally{if(c)throw r}}}()}));return function(e){return r.apply(this,arguments)}}(),c=!1,u=!1;try{for(var d,h=e._asyncIterator(r.queryManager.run(t.toMultihash().bytes,l,n));c=!(d=yield e._awaitAsyncGenerator(h.next())).done;c=!1){var p=d.value;"FINAL_PEER"===p.name&&(o=!0),yield p}}catch(e){u=!0,a=e}finally{try{c&&null!=h.return&&(yield e._awaitAsyncGenerator(h.return()))}finally{if(u)throw a}}}o||(yield gO({from:r.peerId,error:new aa("Not found")},n))}()})).apply(this,arguments)}getClosestPeers(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){r.log("getClosestPeers to %b",t);var i=yield e._awaitAsyncGenerator(TO(t)),o=r.routingTable.closestPeers(i),a=r,s=new tL(i,r.routingTable.kBucketSize);yield e._awaitAsyncGenerator(Promise.all(o.map(function(){var t=e._asyncToGenerator((function*(e){yield s.add({id:e,multiaddrs:[]})}));return function(e){return t.apply(this,arguments)}}())));var l,c=function(){var r=e._wrapAsyncGenerator((function(r){var{peer:i,signal:o}=r;return function*(){a.log("closerPeersSingle %s from %p",Ze(t,"base32"),i);var r={type:ZR.FIND_NODE,key:t};yield*e._asyncGeneratorDelegate(e._asyncIterator(a.network.sendRequest(i,r,e._objectSpread2(e._objectSpread2({},n),{},{signal:o}))))}()}));return function(e){return r.apply(this,arguments)}}(),u=!1,d=!1;try{for(var h,p=e._asyncIterator(r.queryManager.run(t,c,n));u=!(h=yield e._awaitAsyncGenerator(p.next())).done;u=!1){var f=h.value;"PEER_RESPONSE"===f.name&&(yield e._awaitAsyncGenerator(Promise.all(f.closer.map(function(){var t=e._asyncToGenerator((function*(e){yield s.add(e)}));return function(e){return t.apply(this,arguments)}}())))),yield f}}catch(e){d=!0,l=e}finally{try{u&&null!=p.return&&(yield e._awaitAsyncGenerator(p.return()))}finally{if(d)throw l}}for(var v of(r.log("found %d peers close to %b",s.length,t),s.peers))yield yO({from:r.peerId,peer:v},n)}()})).apply(this,arguments)}getValueOrPeers(t,r){var n=this;return e._wrapAsyncGenerator((function(t,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var o,a=!1,s=!1;try{for(var l,c=e._asyncIterator(n._getValueSingle(t,r,i));a=!(l=yield e._awaitAsyncGenerator(c.next())).done;a=!1){var u=l.value;if("PEER_RESPONSE"===u.name&&null!=u.record)try{yield e._awaitAsyncGenerator(n._verifyRecordOnline(u.record))}catch(e){var d="invalid record received, discarded";n.log(d),yield gO({from:u.from,error:new uO(d)},i);continue}yield u}}catch(e){s=!0,o=e}finally{try{a&&null!=c.return&&(yield e._awaitAsyncGenerator(c.return()))}finally{if(s)throw o}}}()})).apply(this,arguments)}_verifyRecordOnline(t){var r=this;return e._asyncToGenerator((function*(){if(null==t.timeReceived)throw new hO("invalid record received");yield SO(r.validators,new cO(t.key,t.value,t.timeReceived))}))()}getCloserPeersOffline(t,r){var n=this;return e._asyncToGenerator((function*(){var e=[];try{var i=tc(Ae(t)),o=yield n.peerStore.get(i);e.push({id:o.id,multiaddrs:o.addresses.map((e=>{var{multiaddr:t}=e;return t}))})}catch(e){}var a=yield TO(t),s=n.routingTable.closestPeers(a),l=Ik(yield CO(r),a);for(var c of s){if(-1===eL(Ik(yield CO(c),a),l))try{var u=yield n.peerStore.get(c);e.push({id:c,multiaddrs:u.addresses.map((e=>{var{multiaddr:t}=e;return t}))})}catch(e){if("NotFoundError"!==e.name)throw e}}return e.length>0?n.log("getCloserPeersOffline found %d peer(s) closer to %b than %p",e.length,t,r):n.log("getCloserPeersOffline could not find peer closer to %b than %p with %d peers in the routing table",t,r,n.routingTable.size),e}))()}}class nL{constructor(t,r){e._defineProperty(this,"log",void 0),e._defineProperty(this,"datastore",void 0),e._defineProperty(this,"datastorePrefix",void 0),e._defineProperty(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(t,r){var n=this;return e._asyncToGenerator((function*(){var e=yield n.lock.readLock();try{n.log("%p provides %s",r,t),yield n.writeProviderEntry(t,r)}finally{e()}}))()}removeProvider(t,r){var n=this;return e._asyncToGenerator((function*(){var e=yield n.lock.writeLock();try{var i=RO(n.datastorePrefix,t,r);n.log("%p no longer provides %s",r,t),yield n.datastore.delete(i)}finally{e()}}))()}getProviders(t){var r=this;return e._asyncToGenerator((function*(){var e=yield r.lock.readLock();try{r.log("get providers for %c",t);var n=yield r.loadProviders(t);return r.log("got %d providers for %c",n.size,t),[...n.keys()]}finally{e()}}))()}writeProviderEntry(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var e=n.length>2&&void 0!==n[2]?n[2]:new Date,o=RO(i.datastorePrefix,t,r),a=yt(e.getTime());yield i.datastore.put(o,a)}))()}loadProviders(t){var r=this;return e._asyncToGenerator((function*(){var n,i=new ih,o=RO(r.datastorePrefix,t),a=!1,s=!1;try{for(var l,c=e._asyncIterator(r.datastore.query({prefix:o.toString()}));a=!(l=yield c.next()).done;a=!1){var u=l.value,{peerId:d}=GO(u.key);i.set(d,OO(u.value))}}catch(e){s=!0,n=e}finally{try{a&&null!=c.return&&(yield c.return())}finally{if(s)throw n}}return i}))()}}function iL(){return iL=e._wrapAsyncGenerator((function*(t){var{key:r,startingPeer:n,ourPeerId:i,signal:o,query:a,alpha:s,pathIndex:l,numPaths:c,queryFuncTimeout:u,log:d,peersSeen:h,connectionManager:p}=t,f=new Gh({concurrency:s,sort:(e,t)=>eL(e.options.distance,t.options.distance)}),v=yield e._awaitAsyncGenerator(TO(r));!function n(s,y){if(null!=s){h.add(s);var g=Ik(y,v);f.add(e._asyncToGenerator((function*(){var y=[o];null!=u&&y.push(AbortSignal.timeout(u));var m=Qd(y);try{var w,b=!1,_=!1;try{for(var S,P=e._asyncIterator(a(e._objectSpread2(e._objectSpread2({},t),{},{key:r,peer:s,signal:m,pathIndex:l,numPaths:c})));b=!(S=yield P.next()).done;b=!1){var E=S.value;if(m.aborted)return;if("PEER_RESPONSE"===E.name)for(var A of E.closer)if(h.has(A.id))d.trace("already seen %p in query",A.id);else if(i.equals(A.id))d("not querying ourselves");else if(yield p.isDialable(A.multiaddrs)){var k=yield CO(A.id);-1===eL(Ik(k,v),g)?(d.trace("querying closer peer %p",A.id),n(A.id,k)):d.trace("skipping %p as they are not closer to %b than %p",A.id,r,s)}else d("not querying undialable peer");f.safeDispatchEvent("completed",{detail:E})}}catch(e){_=!0,w=e}finally{try{b&&null!=P.return&&(yield P.return())}finally{if(_)throw w}}}catch(e){if(!o.aborted)return gO({from:s,error:e},t)}finally{m.clear()}})),{distance:g}).catch((e=>{d.error(e)}))}}(n,yield e._awaitAsyncGenerator(CO(n)));try{var y,g=!1,m=!1;try{for(var w,b=e._asyncIterator(f.toGenerator({signal:o}));g=!(w=yield e._awaitAsyncGenerator(b.next())).done;g=!1){var _=w.value;null!=_&&(yield _)}}catch(e){m=!0,y=e}finally{try{g&&null!=b.return&&(yield e._awaitAsyncGenerator(b.return()))}finally{if(m)throw y}}}catch(e){if(o.aborted)throw new dO("Query aborted");throw e}})),iL.apply(this,arguments)}class oL{constructor(t,r){var n,i;e._defineProperty(this,"disjointPaths",void 0),e._defineProperty(this,"alpha",void 0),e._defineProperty(this,"shutDownController",void 0),e._defineProperty(this,"running",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"connectionManager",void 0),e._defineProperty(this,"routingTable",void 0),e._defineProperty(this,"initialQuerySelfHasRun",void 0),e._defineProperty(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 t=this;return e._asyncToGenerator((function*(){t.running||(t.running=!0,t.shutDownController=new AbortController,t.shutDownController.signal)}))()}stop(){var t=this;return e._asyncToGenerator((function*(){t.running=!1,t.shutDownController.abort()}))()}run(t,r){var n=this;return e._wrapAsyncGenerator((function(t,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=e._objectSpread2(e._objectSpread2({},i),{},{signal:o})}var a=new AbortController,s=Qd([n.shutDownController.signal,a.signal,i.signal]);a.signal;var l=n.logger.forComponent("".concat(n.logPrefix,":query:")+Ze(t,"base58btc")),c=!1;try{!0!==i.isSelfQuery&&null!=n.initialQuerySelfHasRun&&(l("waiting for initial query-self query before continuing"),yield e._awaitAsyncGenerator(Zc(n.initialQuerySelfHasRun.promise,s)),n.initialQuerySelfHasRun=void 0),l("query:start");var u=yield e._awaitAsyncGenerator(TO(t)),d=n.routingTable.closestPeers(u),h=d.slice(0,Math.min(n.disjointPaths,d.length));if(0===d.length)return void l.error("Running query with no peers");var p,f=new oh,v=h.map(((o,a)=>function(e){return iL.apply(this,arguments)}(e._objectSpread2(e._objectSpread2({},i),{},{key:t,startingPeer:o,ourPeerId:n.peerId,signal:s,query:r,pathIndex:a,numPaths:h.length,alpha:n.alpha,queryFuncTimeout:i.queryFuncTimeout,log:l,peersSeen:f,onProgress:i.onProgress,connectionManager:n.connectionManager})))),y=!1,g=!1;try{for(var m,w=e._asyncIterator(nu(...v));y=!(m=yield e._awaitAsyncGenerator(w.next())).done;y=!1){var b=m.value;if("QUERY_ERROR"===b.name&&l.error("query error",b.error),"PEER_RESPONSE"===b.name)for(var _ of[...b.closer,...b.providers])(yield e._awaitAsyncGenerator(n.connectionManager.isDialable(_.multiaddrs)))&&(yield e._awaitAsyncGenerator(n.routingTable.add(_.id)));yield b}}catch(e){g=!0,p=e}finally{try{y&&null!=w.return&&(yield e._awaitAsyncGenerator(w.return()))}finally{if(g)throw p}}c=!0}catch(e){if(n.running||"QueryAbortedError"!==e.name)throw e}finally{c||(l("query exited early"),a.abort()),s.clear(),l("query:done")}}()})).apply(this,arguments)}}function aL(t){if(null!=t[Symbol.asyncIterator])return e._asyncToGenerator((function*(){var r,n=0,i=!1,o=!1;try{for(var a,s=e._asyncIterator(t);i=!(a=yield s.next()).done;i=!1){a.value;n++}}catch(e){o=!0,r=e}finally{try{i&&null!=s.return&&(yield s.return())}finally{if(o)throw r}}return n}))();var r=0;for(var n of t)r++;return r}function sL(t,r,n){var i,o=new Promise(((o,a)=>{var s;if(!((n=e._objectSpread2({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(),c=[],{addListener:u,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)}})(t),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)||(c.push(a),n.count===c.length&&(i(),o(c)))},p=e=>{i(),a(e)};for(var f of(i=()=>{for(var e of l)d(e,h);for(var t of n.rejectionEvents)d(t,p)},l))u(f,h);for(var v of n.rejectionEvents)u(v,p);n.signal&&n.signal.addEventListener("abort",(()=>{p(n.signal.reason)}),{once:!0}),n.resolveImmediately&&o(c)}));if(o.cancel=i,"number"==typeof n.timeout){var a=mp(o,{milliseconds:n.timeout});return a.cancel=i,a}return o}class lL{constructor(t,r){var n,i,o,a;e._defineProperty(this,"log",void 0),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"routingTable",void 0),e._defineProperty(this,"count",void 0),e._defineProperty(this,"interval",void 0),e._defineProperty(this,"initialInterval",void 0),e._defineProperty(this,"queryTimeout",void 0),e._defineProperty(this,"running",void 0),e._defineProperty(this,"timeoutId",void 0),e._defineProperty(this,"controller",void 0),e._defineProperty(this,"initialQuerySelfHasRun",void 0),e._defineProperty(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=MO(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 t=this;return e._asyncToGenerator((function*(){if(t.running){if(null!=t.querySelfPromise)return t.log("joining existing self query"),t.querySelfPromise.promise;if(t.querySelfPromise=Hc(),t.running){t.controller=new AbortController;var r=[t.controller.signal];if(null==t.initialQuerySelfHasRun){var n=AbortSignal.timeout(t.queryTimeout);r.push(n)}var i=Qd(r);t.controller.signal;try{0===t.routingTable.size&&(t.log("routing table was empty, waiting for some peers before running query"),yield function(t,r,n){"function"==typeof n&&(n={filter:n});var i=sL(t,r,n=e._objectSpread2(e._objectSpread2({},n),{},{count:1,resolveImmediately:!1})),o=i.then((e=>e[0]));return o.cancel=i.cancel,o}(t.routingTable,"peer:add",{signal:i,filter:e=>!t.peerId.equals(e.detail)}),t.log("routing table has peers, continuing with query")),t.log("run self-query, look for %d peers timing out after %dms",t.count,t.queryTimeout);var o=Date.now(),a=yield iu(t.peerRouting.getClosestPeers(t.peerId.toMultihash().bytes,{signal:i,isSelfQuery:!0}),(e=>Dc(e,t.count)),function(){var t=e._asyncToGenerator((function*(e){return aL(e)}));return function(e){return t.apply(this,arguments)}}());t.log("self-query found %d peers in %dms",a,Date.now()-o)}catch(e){t.log.error("self-query error",e)}finally{i.clear(),null!=t.initialQuerySelfHasRun&&(t.initialQuerySelfHasRun.resolve(),t.initialQuerySelfHasRun=void 0)}}t.querySelfPromise.resolve(),t.querySelfPromise=void 0,t.running&&(t.timeoutId=setTimeout((()=>{t.querySelf().catch((e=>{t.log.error("error running self-query",e)}))}),t.interval))}else t.log("skip self-query because we are not started")}))()}}class cL extends Aa{constructor(t,r){var n,i,o,a,s,l;super(),e._defineProperty(this,"log",void 0),e._defineProperty(this,"reprovideQueue",void 0),e._defineProperty(this,"maxQueueSize",void 0),e._defineProperty(this,"datastore",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"reprovideTimeout",void 0),e._defineProperty(this,"running",void 0),e._defineProperty(this,"shutdownController",void 0),e._defineProperty(this,"reprovideThreshold",void 0),e._defineProperty(this,"contentRouting",void 0),e._defineProperty(this,"datastorePrefix",void 0),e._defineProperty(this,"addressManager",void 0),e._defineProperty(this,"validity",void 0),e._defineProperty(this,"interval",void 0),e._defineProperty(this,"lock",void 0),e._defineProperty(this,"peerId",void 0),this.log=t.logger.forComponent("".concat(r.logPrefix,":reprovider")),this.peerId=t.peerId,this.reprovideQueue=new Gh({concurrency:null!==(n=r.concurrency)&&void 0!==n?n:10,metrics:t.metrics,metricName:"".concat(r.metricsPrefix,"_reprovide_queue")}),this.reprovideTimeout=new VO(e._objectSpread2(e._objectSpread2({},null!==(i=r.timeout)&&void 0!==i?i:{}),{},{metrics:t.metrics,metricName:"".concat(r.metricsPrefix,"_reprovide_timeout_milliseconds")})),this.datastore=t.datastore,this.addressManager=t.addressManager,this.datastorePrefix="".concat(r.datastorePrefix,"/provider"),this.reprovideThreshold=null!==(o=r.threshold)&&void 0!==o?o:864e5,this.maxQueueSize=null!==(a=r.maxQueueSize)&&void 0!==a?a:16384,this.validity=null!==(s=r.validity)&&void 0!==s?s:oO,this.interval=null!==(l=r.interval)&&void 0!==l?l:aO,this.contentRouting=r.contentRouting,this.lock=r.lock,this.running=!1,this.reprovide=MO(this.reprovide.bind(this),r.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 t=this;return e._asyncToGenerator((function*(){var r=yield t.lock.writeLock();try{t.safeDispatchEvent("reprovide:start");var n,i=!1,o=!1;try{for(var a,s=function*(){var e=a.value;try{var{cid:r,peerId:n}=GO(e.key),i=OO(e.value).getTime(),o=i+t.validity,s=Date.now(),l=s>o;t.log.trace("comparing: %d < %d = %s %s",i,s-t.validity,l,l?"(expired)":""),l&&(yield t.datastore.delete(e.key)),t.peerId.equals(n)&&s-o<t.reprovideThreshold&&t.queueReprovide(r).catch((e=>{t.log.error("could not reprovide %c - %e",r,e)}))}catch(r){t.log.error("error processing datastore key %s - %e",e.key,r.message)}},l=e._asyncIterator(t.datastore.query({prefix:t.datastorePrefix}));i=!(a=yield l.next()).done;i=!1)yield*s()}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield l.return())}finally{if(o)throw n}}t.log("reprovide/cleanup successful")}finally{r(),t.safeDispatchEvent("reprovide:end"),t.running&&(t.timeout=setTimeout((()=>{t.cleanUp().catch((e=>{t.log.error("error running re-provide - %e",e)}))}),t.interval))}}))()}queueReprovide(t){var r=this;return e._asyncToGenerator((function*(){var n;if(r.running){r.log.trace("waiting for queue capacity before adding %c to re-provide queue",t),yield r.reprovideQueue.onSizeLessThan(r.maxQueueSize);var i=r.reprovideQueue.queue.find((e=>e.options.cid.equals(t)));if(null!=i)return r.log.trace("not adding %c to re-provide queue - already in queue",t),i.join();r.log.trace("adding %c to re-provide queue",t),r.reprovideQueue.add(function(){var n=e._asyncToGenerator((function*(e){var n;if(null===(n=e.signal)||void 0===n||n.throwIfAborted(),r.running){r.log.trace("re-providing %c",t);var i=r.reprovideTimeout.getTimeoutSignal(e);try{yield r.reprovide(e.cid,e)}finally{r.reprovideTimeout.cleanUp(i)}r.log.trace("re-provided %c",t)}}));return function(e){return n.apply(this,arguments)}}(),{signal:null===(n=r.shutdownController)||void 0===n?void 0:n.signal,cid:t}).catch((e=>{r.log.error("could not re-provide key %c - %e",t,e)}))}}))()}reprovide(t,r){var n=this;return e._asyncToGenerator((function*(){yield Tc(n.contentRouting.provide(t,n.addressManager.getAddresses(),r))}))()}}class uL{constructor(t,r){var n,i,o,a;e._defineProperty(this,"routingTable",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"closestPeers",void 0),e._defineProperty(this,"newPeers",void 0),e._defineProperty(this,"refreshInterval",void 0),e._defineProperty(this,"peerSetSize",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"closeTagName",void 0),e._defineProperty(this,"closeTagValue",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(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 oh,this.onPeerPing=this.onPeerPing.bind(this),this.running=!1}start(){var t=this;return e._asyncToGenerator((function*(){if(!t.running){t.running=!0;var e=yield CO(t.components.peerId);t.newPeers=new tL(e,t.peerSetSize),t.routingTable.addEventListener("peer:ping",t.onPeerPing),t.timeout=setInterval((()=>{t.updatePeerTags().catch((e=>{t.log.error("error updating peer tags - %e",e)}))}),t.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 t=this;return e._asyncToGenerator((function*(){var r,n=new oh(null===(r=t.newPeers)||void 0===r?void 0:r.peers.map((e=>e.id))),i=n.difference(t.closestPeers),o=t.closestPeers.difference(n);t.closestPeers=n,yield Promise.all([...[...i].map(function(){var r=e._asyncToGenerator((function*(e){yield t.components.peerStore.merge(e,{tags:{[t.closeTagName]:{value:t.closeTagValue},[sO]:{value:1}}})}));return function(e){return r.apply(this,arguments)}}()),...[...o].map(function(){var r=e._asyncToGenerator((function*(e){yield t.components.peerStore.merge(e,{tags:{[t.closeTagName]:void 0,[sO]:void 0}})}));return function(e){return r.apply(this,arguments)}}())])}))()}}function dL(e){return Array.isArray(null==e?void 0:e.peers)}class hL{constructor(t){var r,n,i,o,a;e._defineProperty(this,"root",void 0),e._defineProperty(this,"localPeer",void 0),e._defineProperty(this,"prefixLength",void 0),e._defineProperty(this,"splitThreshold",void 0),e._defineProperty(this,"kBucketSize",void 0),e._defineProperty(this,"numberOfNodesToPing",void 0),e._defineProperty(this,"lastPingThreshold",void 0),e._defineProperty(this,"ping",void 0),e._defineProperty(this,"verify",void 0),e._defineProperty(this,"onAdd",void 0),e._defineProperty(this,"onRemove",void 0),e._defineProperty(this,"onMove",void 0),e._defineProperty(this,"addingPeerMap",void 0),this.prefixLength=null!==(r=t.prefixLength)&&void 0!==r?r:fL,this.kBucketSize=null!==(n=t.kBucketSize)&&void 0!==n?n:pL,this.splitThreshold=null!==(i=t.splitThreshold)&&void 0!==i?i:this.kBucketSize,this.numberOfNodesToPing=null!==(o=t.numberOfOldContactsToPing)&&void 0!==o?o:vL,this.lastPingThreshold=null!==(a=t.lastPingThreshold)&&void 0!==a?a:gL,this.ping=t.ping,this.verify=t.verify,this.onAdd=t.onAdd,this.onRemove=t.onRemove,this.addingPeerMap=new ih,this.root={prefix:"",depth:0,peers:[]}}addSelfPeer(t){var r=this;return e._asyncToGenerator((function*(){r.localPeer={peerId:t,kadId:yield CO(t),lastPing:Date.now()}}))()}add(t,r){var n=this;return e._asyncToGenerator((function*(){var e={peerId:t,kadId:yield CO(t),lastPing:0},i=n.addingPeerMap.get(t);if(null!=i)return i;try{var o=n._add(e,r);n.addingPeerMap.set(t,o),yield o}finally{n.addingPeerMap.delete(t)}}))()}_add(t,r){var n=this;return e._asyncToGenerator((function*(){var i=n._determineBucket(t.kadId);if(!(n._indexOf(i,t.kadId)>-1)){if(i.peers.length===n.splitThreshold&&i.depth<n.prefixLength)return yield n._split(i),void(yield n._add(t,r));var o;if(i.peers.length<n.kBucketSize)return function(e,t){return e.lastPing<Date.now()-t}(t,n.lastPingThreshold)?void((yield n.verify(t,r))&&(t.lastPing=Date.now(),yield n._add(t,r))):(i.peers.push(t),void(yield null===(o=n.onAdd)||void 0===o?void 0:o.call(n,t,i)));var a,s=i.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,c=!1,u=!1;try{for(var d,h=e._asyncIterator(n.ping(s,r));c=!(d=yield h.next()).done;c=!1){var p=d.value;l=!0,yield n.remove(p.kadId)}}catch(e){u=!0,a=e}finally{try{c&&null!=h.return&&(yield h.return())}finally{if(u)throw a}}l&&(yield n._add(t,r))}}))()}closest(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.kBucketSize;return function*(){var n=new tL(e,r);for(var i of t.toIterable())n.addWithKadId({id:i.peerId,multiaddrs:[]},i.kadId);yield*qc(n.peers,(e=>e.id))}()}count(){return function e(t){if(dL(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(t){var r=this;return e._asyncToGenerator((function*(){var e=r._determineBucket(t),n=r._indexOf(e,t);if(n>-1){var i,o=e.peers.splice(n,1)[0];yield null===(i=r.onRemove)||void 0===i?void 0:i.call(r,o,e)}}))()}*toIterable(){yield*function*e(t){dL(t)?yield*t.peers:(yield*e(t.left),yield*e(t.right))}(this.root)}distance(e,t){return BigInt("0x"+Ze(Ik(e,t),"base16"))}_determineBucket(e){var t=Ze(e,"base2");return function e(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return dL(r)?r:e("0"===t[n]?r.left:r.right,n+1)}(this.root)}_indexOf(e,t){return e.peers.findIndex((e=>rt(e.kadId,t)))}_split(t){var r=this;return e._asyncToGenerator((function*(){var e={prefix:"0",depth:t.depth+1,peers:[]},n={prefix:"1",depth:t.depth+1,peers:[]};for(var i of t.peers){var o,a;if("0"===Ze(i.kadId,"base2")[t.depth])e.peers.push(i),yield null===(o=r.onMove)||void 0===o?void 0:o.call(r,i,t,e);else n.peers.push(i),yield null===(a=r.onMove)||void 0===a?void 0:a.call(r,i,t,n)}!function(e,t,r){delete e.peers,e.left=t,e.right=r,""===e.prefix&&(delete e.depth,delete e.prefix)}(t,e,n)}))()}}var pL=20,fL=6,vL=3,yL="kad-peer",gL=6e5;class mL extends Aa{constructor(t,r){var n,i,o,a,s,l,c,u,d,h,p;super(),e._defineProperty(this,"kBucketSize",void 0),e._defineProperty(this,"kb",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"closestPeerTagger",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"running",void 0),e._defineProperty(this,"pingNewContactTimeout",void 0),e._defineProperty(this,"pingNewContactQueue",void 0),e._defineProperty(this,"pingOldContactTimeout",void 0),e._defineProperty(this,"pingOldContactQueue",void 0),e._defineProperty(this,"populateFromDatastoreOnStart",void 0),e._defineProperty(this,"populateFromDatastoreLimit",void 0),e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"peerTagName",void 0),e._defineProperty(this,"peerTagValue",void 0),e._defineProperty(this,"metrics",void 0),this.components=t,this.log=t.logger.forComponent("".concat(r.logPrefix,":routing-table")),this.kBucketSize=null!==(n=r.kBucketSize)&&void 0!==n?n:pL,this.running=!1,this.protocol=r.protocol,this.network=r.network,this.peerTagName=null!==(i=r.peerTagName)&&void 0!==i?i:yL,this.peerTagValue=null!==(o=r.peerTagValue)&&void 0!==o?o: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===(a=r.populateFromDatastoreOnStart)||void 0===a||a,this.populateFromDatastoreLimit=null!==(s=r.populateFromDatastoreLimit)&&void 0!==s?s:1e3,this.pingOldContactQueue=new Rh({concurrency:null!==(l=r.pingOldContactConcurrency)&&void 0!==l?l:20,metricName:"".concat(r.metricsPrefix,"_ping_old_contact_queue"),metrics:this.components.metrics,maxSize:null!==(c=r.pingOldContactMaxQueueSize)&&void 0!==c?c:100}),this.pingOldContactTimeout=new VO(e._objectSpread2(e._objectSpread2({},null!==(u=r.pingOldContactTimeout)&&void 0!==u?u:{}),{},{metrics:this.components.metrics,metricName:"".concat(r.metricsPrefix,"_routing_table_ping_old_contact_time_milliseconds")})),this.pingNewContactQueue=new Rh({concurrency:null!==(d=r.pingNewContactConcurrency)&&void 0!==d?d:20,metricName:"".concat(r.metricsPrefix,"_ping_new_contact_queue"),metrics:this.components.metrics,maxSize:null!==(h=r.pingNewContactMaxQueueSize)&&void 0!==h?h:100}),this.pingNewContactTimeout=new VO(e._objectSpread2(e._objectSpread2({},null!==(p=r.pingNewContactTimeout)&&void 0!==p?p:{}),{},{metrics:this.components.metrics,metricName:"".concat(r.metricsPrefix,"_routing_table_ping_new_contact_time_milliseconds")})),this.kb=new hL({kBucketSize:r.kBucketSize,prefixLength:r.prefixLength,splitThreshold:r.splitThreshold,numberOfOldContactsToPing:r.numberOfOldContactsToPing,lastPingThreshold:r.lastPingThreshold,ping:this.pingOldContacts,verify:this.verifyNewContact,onAdd:this.peerAdded,onRemove:this.peerRemoved}),this.closestPeerTagger=new uL(this.components,{logPrefix:r.logPrefix,routingTable:this,peerSetSize:r.closestPeerSetSize,refreshInterval:r.closestPeerSetRefreshInterval,closeTagName:r.closeTagName,closeTagValue:r.closeTagValue}),null!=this.components.metrics&&(this.metrics={routingTableSize:this.components.metrics.registerMetric("".concat(r.metricsPrefix,"_routing_table_size")),routingTableKadBucketTotal:this.components.metrics.registerMetric("".concat(r.metricsPrefix,"_routing_table_kad_bucket_total")),routingTableKadBucketAverageOccupancy:this.components.metrics.registerMetric("".concat(r.metricsPrefix,"_routing_table_kad_bucket_average_occupancy")),routingTableKadBucketMinOccupancy:this.components.metrics.registerMetric("".concat(r.metricsPrefix,"_routing_table_kad_bucket_min_occupancy")),routingTableKadBucketMaxOccupancy:this.components.metrics.registerMetric("".concat(r.metricsPrefix,"_routing_table_kad_bucket_max_occupancy")),routingTableKadBucketMaxDepth:this.components.metrics.registerMetric("".concat(r.metricsPrefix,"_routing_table_kad_bucket_max_depth")),kadBucketEvents:this.components.metrics.registerCounterGroup("".concat(r.metricsPrefix,"_kad_bucket_events_total"))})}isStarted(){return this.running}start(){var t=this;return e._asyncToGenerator((function*(){t.running||(t.running=!0,yield xa(t.closestPeerTagger),yield t.kb.addSelfPeer(t.components.peerId))}))()}afterStart(){var t=this;return e._asyncToGenerator((function*(){Promise.resolve().then(e._asyncToGenerator((function*(){if(t.populateFromDatastoreOnStart){var e=0;for(var r of yield t.components.peerStore.all({filters:[e=>e.protocols.includes(t.protocol)&&e.tags.has(yL)],limit:t.populateFromDatastoreLimit})){if(!t.running)return;try{yield t.add(r.id),e++}catch(e){t.log("failed to add peer %p to routing table, removing kad-dht peer tags - %e"),yield t.components.peerStore.merge(r.id,{tags:{[t.peerTagName]:void 0}})}}t.log("added %d peer store peers to the routing table",e)}}))).catch((e=>{t.log.error("error adding peer store peers to the routing table %e",e)}))}))()}stop(){var t=this;return e._asyncToGenerator((function*(){t.running=!1,yield Ia(t.closestPeerTagger),t.pingOldContactQueue.abort(),t.pingNewContactQueue.abort()}))()}peerAdded(t,r){var n=this;return e._asyncToGenerator((function*(){var e;n.components.peerId.equals(t.peerId)||(yield n.components.peerStore.merge(t.peerId,{tags:{[n.peerTagName]:{value:n.peerTagValue}}})),n.updateMetrics(),null===(e=n.metrics)||void 0===e||e.kadBucketEvents.increment({peer_added:!0}),n.safeDispatchEvent("peer:add",{detail:t.peerId})}))()}peerRemoved(t,r){var n=this;return e._asyncToGenerator((function*(){var e;n.components.peerId.equals(t.peerId)||(yield n.components.peerStore.merge(t.peerId,{tags:{[n.peerTagName]:void 0}})),n.updateMetrics(),null===(e=n.metrics)||void 0===e||e.kadBucketEvents.increment({peer_removed:!0}),n.safeDispatchEvent("peer:remove",{detail:t.peerId})}))()}pingOldContacts(t,r){var n=this;return e._wrapAsyncGenerator((function*(){if(n.running){var i=[],o=function*(t){var o;if(null==n.kb.get(t.kadId))return n.log("asked to ping contact %p that was not in routing table",t.peerId),1;null===(o=n.metrics)||void 0===o||o.kadBucketEvents.increment({ping_old_contact:!0}),i.push(e._asyncToGenerator((function*(){var i=n.pingOldContactQueue.find(t.peerId);if(null!=i)return n.log("asked to ping contact %p was already being pinged",t.peerId),(yield i.join(r))?void 0:t;var o=yield n.pingOldContactQueue.add(function(){var r=e._asyncToGenerator((function*(e){var r=n.pingOldContactTimeout.getTimeoutSignal(),i=Qd([r,null==e?void 0:e.signal]);try{return yield n.pingContact(t,e)}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 r.apply(this,arguments)}}(),{peerId:t.peerId,signal:null==r?void 0:r.signal});return o?void 0:t})))};for(var a of t)yield*o(a);var s,l=!1,c=!1;try{for(var u,d=e._asyncIterator(MR(i));l=!(u=yield e._awaitAsyncGenerator(d.next())).done;l=!1){var h=u.value;null!=h&&(yield h)}}catch(e){c=!0,s=e}finally{try{l&&null!=d.return&&(yield e._awaitAsyncGenerator(d.return()))}finally{if(c)throw s}}}}))()}verifyNewContact(t,r){var n=this;return e._asyncToGenerator((function*(){var i=n.pingNewContactTimeout.getTimeoutSignal(),o=Qd([i,null==r?void 0:r.signal]);try{var a=n.pingNewContactQueue.find(t.peerId);return null!=a?(n.log("joining existing ping to add new peer %p to routing table",t.peerId),yield a.join({signal:o})):yield n.pingNewContactQueue.add(function(){var r=e._asyncToGenerator((function*(e){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",t.peerId),n.pingContact(t,e)}));return function(e){return r.apply(this,arguments)}}(),{peerId:t.peerId,signal:o})}catch(e){var s;return n.log.trace("tried to add peer %p but they were not online",t.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(t,r){var n=this;return e._asyncToGenerator((function*(){try{n.log("pinging contact %p",t.peerId);var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(n.network.sendRequest(t.peerId,{type:ZR.PING},r));o=!(s=yield l.next()).done;o=!1){var c=s.value;if(c.type===BL.PEER_RESPONSE)return c.messageType===ZR.PING&&(n.log("contact %p ping ok",t.peerId),n.safeDispatchEvent("peer:ping",{detail:t.peerId}),!0)}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield l.return())}finally{if(a)throw i}}return!1}catch(e){return n.log("error pinging old contact %p - %e",t.peerId,e),!1}}))()}get size(){return null==this.kb?0:this.kb.count()}find(t){var r=this;return e._asyncToGenerator((function*(){var e,n=yield CO(t);return null===(e=r.kb.get(n))||void 0===e?void 0:e.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(t,r){var n=this;return e._asyncToGenerator((function*(){if(null==n.kb)throw new Error("RoutingTable is not started");yield n.kb.add(t,r)}))()}remove(t){var r=this;return e._asyncToGenerator((function*(){if(null==r.kb)throw new Error("RoutingTable is not started");var e=yield CO(t);yield r.kb.remove(e)}))()}updateMetrics(){if(null!=this.metrics&&null!=this.kb){var e=0,t=0,r=0,n=20,i=0;!function o(a){if(dL(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 wL=[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 bL{constructor(t,r){e._defineProperty(this,"log",void 0),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"routingTable",void 0),e._defineProperty(this,"refreshInterval",void 0),e._defineProperty(this,"refreshQueryTimeout",void 0),e._defineProperty(this,"commonPrefixLengthRefreshedAt",void 0),e._defineProperty(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 t=this;return e._asyncToGenerator((function*(){t.log("refreshing routing table every ".concat(t.refreshInterval,"ms")),t.refreshTable(!0)}))()}stop(){var t=this;return e._asyncToGenerator((function*(){null!=t.refreshTimeoutId&&clearTimeout(t.refreshTimeoutId)}))()}refreshTable(){var t=this,r=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=e._asyncToGenerator((function*(e,o){try{if(yield t._refreshCommonPrefixLength(o,e,r),0===t._numPeersForCpl(n))for(var a=Math.min(2*(o+1),i.length-1),s=o+1;s<a+1;s++)try{yield t._refreshCommonPrefixLength(s,e,r)}catch(e){t.log.error(e)}}catch(e){t.log.error(e)}}));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(t,r,n){var i=this;return e._asyncToGenerator((function*(){if(!n&&r.getTime()>Date.now()-i.refreshInterval)i.log("not running refresh for cpl %s as time since last refresh not above interval",t);else{var e=yield i._generateRandomPeerId(t);i.log("starting refreshing cpl %s with key %p (routing table size was %s)",t,e,i.routingTable.size);var o=AbortSignal.timeout(i.refreshQueryTimeout),a=yield aL(i.peerRouting.getClosestPeers(e.toMultihash().bytes,{signal:o}));i.log("found ".concat(a," peers that were close to imaginary peer %p"),e),i.log("finished refreshing cpl %s with key %p (routing table size is now %s)",t,e,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(t){var r=this;return e._asyncToGenerator((function*(){if(null==r.routingTable.kb)throw new Error("Routing table not started");if(null==r.routingTable.kb.localPeer)throw new Error("Local peer not set");var e=pl(2),n=(e[1]<<8)+e[0];return tc(Ae(yield r._makePeerId(r.routingTable.kb.localPeer.kadId,n,t)))}))()}_makePeerId(t,r,n){return e._asyncToGenerator((function*(){if(n>15)throw new Error("Cannot generate peer ID for common prefix length greater than ".concat(15));var e=new DataView(t.buffer,t.byteOffset,t.byteLength).getUint16(0,!1),i=65535<<16-(n+1),o=wL[(e^32768>>n)&i|r&~i],a=new ArrayBuffer(34),s=new DataView(a,0,a.byteLength);return s.setUint8(0,De.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=Ik(this.routingTable.kb.localPeer.kadId,t),n=0;for(var i of r){if(0!==i)break;n++}yield n}}}class _L{constructor(t,r){e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"providers",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(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(t,r){var n=this;return e._asyncToGenerator((function*(){if(null==r.key||0===r.key.length)throw new ha("Missing key");var i;try{i=je.decode(r.key)}catch(e){throw new ha("Invalid CID")}null!=r.providers&&0!==r.providers.length||n.log.error("no providers found in message"),n.log("%p asked us, %p to store provider record for for %c",t,n.peerId,i),yield Promise.all(r.providers.map(function(){var r=e._asyncToGenerator((function*(e){var r=tc(Ae(e.id)),o=e.multiaddrs.map((e=>nr(e)));t.equals(r)?e.multiaddrs.length<1?n.log("no valid addresses for provider %p. Ignore",t):(n.log.trace("received provider %p for %s (addrs %s)",t,i,o),yield n.providers.addProvider(i,r),yield n.peerStore.merge(r,{multiaddrs:o})):n.log("invalid provider peer %p from %p",e.id,t)}));return function(e){return r.apply(this,arguments)}}()))}))()}}class SL{constructor(t,r){e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"peerInfoMapper",void 0),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"addressManager",void 0),e._defineProperty(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(t,r){var n=this;return e._asyncToGenerator((function*(){if(n.log("incoming request from %p for peers closer to %b",t,r.key),null==r.key)throw new ha("Invalid FIND_NODE message received - key was missing");var e=yield n.peerRouting.getCloserPeersOffline(r.key,t);rt(n.peerId.toMultihash().bytes,r.key)&&e.push({id:n.peerId,multiaddrs:n.addressManager.getAddresses().map((e=>e.decapsulateCode(ir("p2p").code)))});var i={type:ZR.FIND_NODE,clusterLevel:r.clusterLevel,closer:e.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",r.key,t),i}))()}}class PL{constructor(t,r){e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"providers",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"peerInfoMapper",void 0),e._defineProperty(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(t,r){var n=this;return e._asyncToGenerator((function*(){if(null==r.key)throw new ha("Invalid GET_PROVIDERS message received - key was missing");var i;try{i=je.decode(r.key)}catch(e){throw new ha("Invalid CID")}n.log("%p asking for providers for %s",t,i);var[o,a]=yield Promise.all([Bc(qc(yield n.providers.getProviders(i),function(){var t=e._asyncToGenerator((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(e){return t.apply(this,arguments)}}())),n.peerRouting.getCloserPeersOffline(r.key,n.peerId)]),s={type:ZR.GET_PROVIDERS,key:r.key,clusterLevel:r.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(t){return e._asyncToGenerator((function*(){return[]}))()}}class EL{constructor(t,r){e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"datastore",void 0),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(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(t,r){var n=this;return e._asyncToGenerator((function*(){var e=r.key;if(n.log("%p asked for key %b",t,e),null==e||0===e.length)throw new ha("Invalid key");var i={type:ZR.GET_VALUE,key:e,clusterLevel:r.clusterLevel,closer:[],providers:[]};if(function(e){return"/pk/"===Ze(e.subarray(0,4))}(e)){n.log("is public key");var o,a=function(e){return tc(Ae(e.subarray(4)))}(e);try{var s=yield n.peerStore.get(a);if(null==s.id.publicKey)throw new aa("No public key found in key book");o=Fl(s.id.publicKey)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=o)return n.log("returning found public key"),i.record=new cO(e,o,new Date).serialize(),i}var[l,c]=yield Promise.all([n._checkLocalDatastore(e),n.peerRouting.getCloserPeersOffline(e,t)]);return null!=l&&(n.log("had record for %b in local datastore",e),i.record=l.serialize()),c.length>0&&(n.log("had %s closer peers in routing table",c.length),i.closer=c.map((e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map((e=>e.bytes))})))),i}))()}_checkLocalDatastore(t){var r=this;return e._asyncToGenerator((function*(){r.log("checkLocalDatastore looking for %b",t);var e,n=NO(r.datastorePrefix,t);try{e=yield r.datastore.get(n)}catch(e){if("NotFoundError"===e.name)return;throw e}var i=cO.deserialize(e);if(!(null==i.timeReceived||Date.now()-i.timeReceived.getTime()>iO))return i;yield r.datastore.delete(n)}))()}}class AL{constructor(t,r){e._defineProperty(this,"log",void 0),this.log=t.logger.forComponent("".concat(r.logPrefix,":rpc:handlers:ping"))}handle(t,r){var n=this;return e._asyncToGenerator((function*(){return n.log("ping from %p",t),r}))()}}class kL{constructor(t,r){e._defineProperty(this,"components",void 0),e._defineProperty(this,"validators",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(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(t,r){var n=this;return e._asyncToGenerator((function*(){var e=r.key;if(n.log("%p asked us to store value for key %b",t,e),null==r.record){var i="Empty record from: ".concat(t.toString());throw n.log.error(i),new ha(i)}try{var o=cO.deserialize(r.record);yield SO(n.validators,o),o.timeReceived=new Date;var a=NO(n.datastorePrefix,o.key);yield n.components.datastore.put(a,o.serialize().subarray()),n.log("put record for %b into datastore under key %k",e,a)}catch(t){n.log("did not put record for key %b into datastore %o",e,t)}return r}))()}}class xL{constructor(t,r){var n,i;e._defineProperty(this,"handlers",void 0),e._defineProperty(this,"routingTable",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(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={[ZR.GET_VALUE.toString()]:new EL(t,r),[ZR.PUT_VALUE.toString()]:new kL(t,r),[ZR.FIND_NODE.toString()]:new SL(t,r),[ZR.ADD_PROVIDER.toString()]:new _L(t,r),[ZR.GET_PROVIDERS.toString()]:new PL(t,r),[ZR.PING.toString()]:new AL(t,r)}}handleMessage(t,r){var n=this;return e._asyncToGenerator((function*(){var e=n.handlers[r.type];if(null!=e)try{var i;return null===(i=n.metrics.operations)||void 0===i||i.increment({[r.type]:!0}),yield e.handle(t,r)}catch(e){var o;null===(o=n.metrics.errors)||void 0===o||o.increment({[r.type]:!0})}else n.log.error("no handler found for message type: ".concat(r.type))}))()}onIncomingStream(t){var r=this,n="unknown";Promise.resolve().then(e._asyncToGenerator((function*(){var{stream:i,connection:o}=t,a=o.remotePeer,s=r;yield iu(i,(e=>Up(e)),function(){var t=e._wrapAsyncGenerator((function*(t){var r,i=!1,o=!1;try{for(var l,c=e._asyncIterator(t);i=!(l=yield e._awaitAsyncGenerator(c.next())).done;i=!1){var u=l.value,d=rO.decode(u);n=d.type,s.log("incoming %s from %p",d.type,a);var h=yield e._awaitAsyncGenerator(s.handleMessage(a,d));null!=h&&(yield rO.encode(h))}}catch(e){o=!0,r=e}finally{try{i&&null!=c.return&&(yield e._awaitAsyncGenerator(c.return()))}finally{if(o)throw r}}}));return function(e){return t.apply(this,arguments)}}(),(e=>jp(e)),i)}))).catch((e=>{this.log.error("error handling %s RPC message from %p - %e",n,t.connection.remotePeer,e)}))}}class TL extends Aa{constructor(t,r){super(),e._defineProperty(this,"log",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"running",void 0),e._defineProperty(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 t=this;return e._asyncToGenerator((function*(){t.running||(t.running=!0,t.registrarId=yield t.components.registrar.register(t.protocol,{onConnect:e=>{t.log("observed peer %p with protocol %s",e,t.protocol),t.dispatchEvent(new CustomEvent("peer",{detail:e}))}}))}))()}stop(){var t=this;return e._asyncToGenerator((function*(){t.running=!1,null!=t.registrarId&&(t.components.registrar.unregister(t.registrarId),t.registrarId=void 0)}))()}}class IL{constructor(t){e._defineProperty(this,"dht",void 0),this.dht=t}provide(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};yield Tc(n.dht.provide(t,e))}))()}cancelReprovide(t){var r=this;return e._asyncToGenerator((function*(){yield r.dht.cancelReprovide(t)}))()}findProviders(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(r.dht.findProviders(t,n));o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;"PROVIDER"===c.name&&(yield*e._asyncGeneratorDelegate(e._asyncIterator(c.providers),e._awaitAsyncGenerator))}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}()})).apply(this,arguments)}put(t,r,n){var i=this;return e._asyncToGenerator((function*(){yield Tc(i.dht.put(t,r,n))}))()}get(t,r){var n=this;return e._asyncToGenerator((function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(n.dht.get(t,r));o=!(s=yield l.next()).done;o=!1){var c=s.value;if("VALUE"===c.name)return c.value}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield l.return())}finally{if(a)throw i}}throw new aa("Could not find value for key")}))()}}class CL{constructor(t){e._defineProperty(this,"dht",void 0),this.dht=t}findPeer(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i,o=r.length>1&&void 0!==r[1]?r[1]:{},a=!1,s=!1;try{for(var l,c=e._asyncIterator(n.dht.findPeer(t,o));a=!(l=yield c.next()).done;a=!1){var u=l.value;if("FINAL_PEER"===u.name)return u.peer}}catch(e){s=!0,i=e}finally{try{a&&null!=c.return&&(yield c.return())}finally{if(s)throw i}}throw new aa("Peer not found")}))()}getClosestPeers(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(r.dht.getClosestPeers(t,n));o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;"FINAL_PEER"===c.name&&(yield c.peer)}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}()})).apply(this,arguments)}}var BL;class NL extends Aa{constructor(t){var r,n,i,o,a,s,l,c,u,d,h,p,f,v,y=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),v=this,e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"routingTable",void 0),e._defineProperty(this,"providers",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"running",void 0),e._defineProperty(this,"kBucketSize",void 0),e._defineProperty(this,"clientMode",void 0),e._defineProperty(this,"validators",void 0),e._defineProperty(this,"selectors",void 0),e._defineProperty(this,"queryManager",void 0),e._defineProperty(this,"contentFetching",void 0),e._defineProperty(this,"contentRouting",void 0),e._defineProperty(this,"routingTableRefresh",void 0),e._defineProperty(this,"rpc",void 0),e._defineProperty(this,"topologyListener",void 0),e._defineProperty(this,"querySelf",void 0),e._defineProperty(this,"maxInboundStreams",void 0),e._defineProperty(this,"maxOutboundStreams",void 0),e._defineProperty(this,"dhtContentRouting",void 0),e._defineProperty(this,"dhtPeerRouting",void 0),e._defineProperty(this,"peerInfoMapper",void 0),e._defineProperty(this,"reprovider",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/kad-dht"),e._defineProperty(this,Ba,["@libp2p/content-routing","@libp2p/peer-routing","@libp2p/peer-discovery"]),e._defineProperty(this,Na,["@libp2p/identify"]);var g=null!==(r=y.logPrefix)&&void 0!==r?r:"libp2p:kad-dht",m=null!==(n=y.datastorePrefix)&&void 0!==n?n:"/dht",w=null!==(i=y.metricsPrefix)&&void 0!==i?i:"libp2p_kad_dht",b={queries:null===(o=t.metrics)||void 0===o?void 0:o.registerMetricGroup("".concat(w,"_operations_total"),{label:"operation"}),errors:null===(a=t.metrics)||void 0===a?void 0:a.registerCounterGroup("".concat(w,"_operation_errors_total"),{label:"operation"}),queryTime:null===(s=t.metrics)||void 0===s?void 0:s.registerMetricGroup("".concat(w,"_operation_time_seconds"),{label:"operation"}),errorTime:null===(l=t.metrics)||void 0===l?void 0:l.registerMetricGroup("".concat(w,"_operation_error_time_seconds"),{label:"operation"})};this.running=!1,this.components=t,this.log=t.logger.forComponent(g),this.protocol=null!==(c=y.protocol)&&void 0!==c?c:"/ipfs/kad/1.0.0",this.kBucketSize=null!==(u=y.kBucketSize)&&void 0!==u?u:20,this.clientMode=null===(d=y.clientMode)||void 0===d||d,this.maxInboundStreams=null!==(h=y.maxInboundStreams)&&void 0!==h?h:32,this.maxOutboundStreams=null!==(p=y.maxOutboundStreams)&&void 0!==p?p:64,this.peerInfoMapper=null!==(f=y.peerInfoMapper)&&void 0!==f?f:xO;var _=eB();this.providers=new nL(t,e._objectSpread2(e._objectSpread2({},y.providers),{},{logPrefix:g,datastorePrefix:m,lock:_})),this.validators=e._objectSpread2(e._objectSpread2({},AO),y.validators),this.selectors=e._objectSpread2(e._objectSpread2({},_O),y.selectors),this.network=new XO(t,{protocol:this.protocol,logPrefix:g,metricsPrefix:w}),this.routingTable=new mL(t,{kBucketSize:y.kBucketSize,pingOldContactTimeout:y.pingOldContactTimeout,pingOldContactConcurrency:y.pingOldContactConcurrency,pingOldContactMaxQueueSize:y.pingOldContactMaxQueueSize,pingNewContactTimeout:y.pingNewContactTimeout,pingNewContactConcurrency:y.pingNewContactConcurrency,pingNewContactMaxQueueSize:y.pingNewContactMaxQueueSize,protocol:this.protocol,logPrefix:g,metricsPrefix:w,prefixLength:y.prefixLength,splitThreshold:y.kBucketSplitThreshold,network:this.network});var S=Hc();!0===y.allowQueryWithZeroPeers&&S.resolve(),this.queryManager=new oL(t,{disjointPaths:Math.ceil(this.kBucketSize/2),logPrefix:g,metricsPrefix:w,initialQuerySelfHasRun:S,routingTable:this.routingTable}),this.peerRouting=new rL(t,{routingTable:this.routingTable,network:this.network,validators:this.validators,queryManager:this.queryManager,logPrefix:g}),this.contentFetching=new jO(t,{validators:this.validators,selectors:this.selectors,peerRouting:this.peerRouting,queryManager:this.queryManager,network:this.network,logPrefix:g,datastorePrefix:m}),this.contentRouting=new UO(t,{network:this.network,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,providers:this.providers,logPrefix:g}),this.routingTableRefresh=new bL(t,{peerRouting:this.peerRouting,routingTable:this.routingTable,logPrefix:g}),this.rpc=new xL(t,{routingTable:this.routingTable,providers:this.providers,peerRouting:this.peerRouting,validators:this.validators,logPrefix:g,metricsPrefix:w,datastorePrefix:m,peerInfoMapper:this.peerInfoMapper}),this.topologyListener=new TL(t,{protocol:this.protocol,logPrefix:g}),this.querySelf=new lL(t,{peerRouting:this.peerRouting,interval:y.querySelfInterval,initialInterval:y.initialQuerySelfInterval,logPrefix:g,initialQuerySelfHasRun:S,routingTable:this.routingTable,operationMetrics:b}),this.reprovider=new cL(t,e._objectSpread2(e._objectSpread2({},y.reprovide),{},{logPrefix:g,metricsPrefix:w,datastorePrefix:m,contentRouting:this.contentRouting,lock:_,operationMetrics:b})),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",(t=>{var r=t.detail;Promise.resolve().then(e._asyncToGenerator((function*(){var e=yield v.components.peerStore.get(r),t={id:r,multiaddrs:e.addresses.map((e=>{var{multiaddr:t}=e;return t})),protocols:e.protocols};yield v.onPeerConnect(t)}))).catch((e=>{this.log.error("could not add %p to routing table - %e",r,e)}))})),this.dhtPeerRouting=new CL(this),this.dhtContentRouting=new IL(this),null==y.clientMode&&t.events.addEventListener("self:peer:update",(t=>{this.log("received update of self-peer info"),Promise.resolve().then(e._asyncToGenerator((function*(){var e=t.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=kN("".concat(t[0][1]));return null==n||!n}return!1}(t)})),r=v.getMode();e&&"client"===r?yield v.setMode("server"):"server"!==r||e||(yield v.setMode("client"))}))).catch((e=>{this.log.error("error setting dht server mode",e)}))})),this.get=LO(this.get.bind(this),b,"GET_VALUE"),this.findProviders=LO(this.findProviders.bind(this),b,"FIND_PROVIDERS"),this.findPeer=LO(this.findPeer.bind(this),b,"FIND_PEER"),this.getClosestPeers=LO(this.getClosestPeers.bind(this),b,"GET_CLOSEST_PEERS"),this.provide=LO(this.provide.bind(this),b,"PROVIDE"),this.put=LO(this.put.bind(this),b,"PUT_VALUE")}get[jo](){return this.dhtContentRouting}get[qo](){return this.dhtPeerRouting}get[Fo](){return this}onPeerConnect(t){var r=this;return e._asyncToGenerator((function*(){if(r.log.trace("peer %p connected",t.id),0!==(t=r.peerInfoMapper(t)).multiaddrs.length)try{yield r.routingTable.add(t.id)}catch(e){r.log.error("could not add %p to routing table",t.id,e)}else r.log.trace("ignoring %p as there were no valid addresses in %s after filtering",t.id,t.multiaddrs.map((e=>e.toString())))}))()}isStarted(){return this.running}getMode(){return this.clientMode?"client":"server"}setMode(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]&&r[1];t!==n.getMode()||e?(yield n.components.registrar.unhandle(n.protocol),t!==n.getMode()||e?"client"===t?(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",t)):n.log("already in %s mode",t)}))()}start(){var t=this;return e._asyncToGenerator((function*(){t.running||(t.running=!0,yield t.setMode(t.clientMode?"client":"server",!0),yield xa(t.routingTable,t.queryManager,t.network,t.topologyListener,t.routingTableRefresh,t.reprovider),yield xa(t.querySelf))}))()}stop(){var t=this;return e._asyncToGenerator((function*(){t.running=!1,yield Ia(t.querySelf,t.queryManager,t.network,t.routingTable,t.routingTableRefresh,t.topologyListener,t.reprovider)}))()}put(t,r){var n=this;return e._wrapAsyncGenerator((function(t,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(n.contentFetching.put(t,r,i)))}()})).apply(this,arguments)}get(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(r.contentFetching.get(t,n)))}()})).apply(this,arguments)}provide(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(r.contentRouting.provide(t,r.components.addressManager.getAddresses(),n)))}()})).apply(this,arguments)}cancelReprovide(t){var r=this;return e._asyncToGenerator((function*(){yield r.providers.removeProvider(t,r.components.peerId)}))()}findProviders(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(r.contentRouting.findProviders(t,n)))}()})).apply(this,arguments)}findPeer(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(r.peerRouting.findPeer(t,n)))}()})).apply(this,arguments)}getClosestPeers(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(r.peerRouting.getClosestPeers(t,n)))}()})).apply(this,arguments)}refreshRoutingTable(){var t=this;return e._asyncToGenerator((function*(){t.routingTableRefresh.refreshTable(!0)}))()}}function DL(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new NL(t,e)}function GL(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"}(BL||(BL={}));var{hasOwnProperty:RL}=Object.prototype,{propertyIsEnumerable:OL}=Object,LL=(e,t,r)=>{Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})},ML={concatArrays:!1,ignoreUndefined:!1},jL=e=>{var t=[];for(var r in e)RL.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);for(var i of n)OL.call(e,i)&&t.push(i)}return t};function FL(e){return Array.isArray(e)?(r=(t=e).slice(0,0),jL(t).forEach((e=>{LL(r,e,FL(t[e]))})),r):GL(e)?function(e){var t=null===Object.getPrototypeOf(e)?Object.create(null):{};return jL(e).forEach((r=>{LL(t,r,FL(e[r]))})),t}(e):e;var t,r}var UL,zL,VL,qL,HL,KL,WL,QL,YL=(e,t,r,n)=>(r.forEach((r=>{void 0===t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?LL(e,r,ZL(e[r],t[r],n)):LL(e,r,FL(t[r])))})),e),JL=(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++)RL.call(t,a)&&(o.push(String(a)),LL(n,i++,t===e?t[a]:FL(t[a])));n=YL(n,t,jL(t).filter((e=>!o.includes(e))),r)})),n};function ZL(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?JL(e,t,r):GL(t)&&GL(e)?YL(e,t,jL(t),r):FL(t)}function $L(){for(var e=ZL(FL(ML),undefined!==this&&this||{},ML),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(!GL(o))throw new TypeError("`"+o+"` is not an Option Object");t=ZL(t,{_:o},e)}return t._}function XL(){if(zL)return UL;function e(e){return e>=55296&&e<=56319}function t(e){return e>=56320&&e<=57343}return zL=1,UL=function(r,n,i){if("string"!=typeof n)throw new Error("Input must be string");for(var o,a,s=n.length,l=0,c=0;c<s;c+=1){if(o=n.charCodeAt(c),a=n[c],e(o)&&t(n.charCodeAt(c+1))&&(a+=n[c+=1]),(l+=r(a))===i)return n.slice(0,c+1);if(l>i)return n.slice(0,c-a.length+1)}return n},UL}function eM(){if(KL)return HL;KL=1;var e=XL(),t=function(){if(qL)return VL;function e(e){return e>=55296&&e<=56319}function t(e){return e>=56320&&e<=57343}return qL=1,VL=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},VL}();return HL=e.bind(null,t)}var tM=function(){if(QL)return WL;QL=1;var e=eM(),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 WL=function(e,t){var r=t&&t.replacement||"",n=a(e,r);return""===r?n:a(n,"")},WL}(),rM=e.getDefaultExportFromCjs(tM),nM={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function iM(t){var r="AES-GCM",n=16,i=12,o="SHA-256",a=16,s=32767,l=gl.get();function c(){return(c=e._asyncToGenerator((function*(e,t){var c,u=l.getRandomValues(new Uint8Array(a)),d=l.getRandomValues(new Uint8Array(i)),h={name:r,iv:d};if("string"==typeof t&&(t=nt(t)),0===t.length){c=yield l.subtle.importKey("jwk",nM,{name:"AES-GCM"},!0,["encrypt"]);try{var p={name:"PBKDF2",salt:u,iterations:s,hash:{name:o}},f=yield l.subtle.importKey("raw",t,{name:"PBKDF2"},!1,["deriveKey"]);c=yield l.subtle.deriveKey(p,f,{name:r,length:n},!0,["encrypt"])}catch(e){c=yield l.subtle.importKey("jwk",nM,{name:"AES-GCM"},!0,["encrypt"])}}else{var v={name:"PBKDF2",salt:u,iterations:s,hash:{name:o}},y=yield l.subtle.importKey("raw",t,{name:"PBKDF2"},!1,["deriveKey"]);c=yield l.subtle.deriveKey(v,y,{name:r,length:n},!0,["encrypt"])}var g=yield l.subtle.encrypt(h,c,e);return mt([u,h.iv,new Uint8Array(g)])}))).apply(this,arguments)}function u(){return(u=e._asyncToGenerator((function*(e,t){var c,u=e.subarray(0,a),d=e.subarray(a,a+i),h=e.subarray(a+i),p={name:r,iv:d};if("string"==typeof t&&(t=nt(t)),0===t.length)try{var f={name:"PBKDF2",salt:u,iterations:s,hash:{name:o}},v=yield l.subtle.importKey("raw",t,{name:"PBKDF2"},!1,["deriveKey"]);c=yield l.subtle.deriveKey(f,v,{name:r,length:n},!0,["decrypt"])}catch(e){c=yield l.subtle.importKey("jwk",nM,{name:"AES-GCM"},!0,["decrypt"])}else{var y={name:"PBKDF2",salt:u,iterations:s,hash:{name:o}},g=yield l.subtle.importKey("raw",t,{name:"PBKDF2"},!1,["deriveKey"]);c=yield l.subtle.deriveKey(y,g,{name:r,length:n},!0,["decrypt"])}var m=yield l.subtle.decrypt(p,c,h);return new Uint8Array(m)}))).apply(this,arguments)}n*=8;var d={encrypt:function(e,t){return c.apply(this,arguments)},decrypt:function(e,t){return u.apply(this,arguments)}};return d}var oM=1e4;function aM(e,t){return sM.apply(this,arguments)}function sM(){return(sM=e._asyncToGenerator((function*(e,t){var r=iM(),n=yield r.encrypt(e,t);return z.encode(n)}))).apply(this,arguments)}function lM(e,t,r){return cM.apply(this,arguments)}function cM(){return cM=e._asyncToGenerator((function*(e,t,r){if("RSA"===e.type)return function(e,t){return pM.apply(this,arguments)}(e,t,r);if("Ed25519"===e.type)return function(e,t){return uM.apply(this,arguments)}(e,t,r);if("secp256k1"===e.type)return function(e,t){return dM.apply(this,arguments)}(e,t,r);if("ECDSA"===e.type)return function(e,t){return hM.apply(this,arguments)}(e,t,r);throw new Sa})),cM.apply(this,arguments)}function uM(){return uM=e._asyncToGenerator((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"libp2p-key";if("libp2p-key"===r)return aM(Vl(e),t);throw new Jo("export format '".concat(r,"' is not supported"))})),uM.apply(this,arguments)}function dM(){return dM=e._asyncToGenerator((function*(e,t){if("libp2p-key"===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:"libp2p-key"))return aM(Vl(e),t);throw new Jo("Export format is not supported")})),dM.apply(this,arguments)}function hM(){return hM=e._asyncToGenerator((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"libp2p-key";if("libp2p-key"===r)return aM(Vl(e),t);throw new Jo("export format '".concat(r,"' is not supported"))})),hM.apply(this,arguments)}function pM(){return pM=e._asyncToGenerator((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 fM.apply(this,arguments)}(e,t);if("libp2p-key"===r)return aM(Vl(e),t);throw new Jo("Export format is not supported")})),pM.apply(this,arguments)}function fM(){return(fM=e._asyncToGenerator((function*(e,t){var r=gl.get(),n=new Yv({value:[new Uv({value:0}),new Yv({value:[new Hv({value:"1.2.840.113549.1.1.1"}),new _v]}),new kv({valueHex:e.raw})]}).toBER(),i=new Uint8Array(n,0,n.byteLength),o=pl(16),a=yield Po(bo,t,o,{c:oM,dkLen:32}),s=pl(16),l=yield r.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),c=yield r.subtle.encrypt({name:"AES-CBC",iv:s},l,i),u=new Yv({value:[new kv({valueHex:o}),new Uv({value:oM}),new Uv({value:32}),new Yv({value:[new Hv({value:"1.2.840.113549.2.11"}),new _v]})]}),d=new Yv({value:[new Hv({value:"1.2.840.113549.1.5.13"}),new Yv({value:[new Yv({value:[new Hv({value:"1.2.840.113549.1.5.12"}),u]}),new Yv({value:[new Hv({value:"2.16.840.1.101.3.4.1.42"}),new kv({valueHex:s})]})]})]}),h=new Yv({value:[d,new kv({valueHex:c})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...Ze(new Uint8Array(h,0,h.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}))).apply(this,arguments)}function vM(e,t){return yM.apply(this,arguments)}function yM(){return yM=e._asyncToGenerator((function*(e,t){try{var r=yield function(e,t){return gM.apply(this,arguments)}(e,t);return Ul(r)}catch(e){}if(!e.includes("BEGIN"))throw new Jo("Encrypted key was not a libp2p-key or a PEM file");return function(e,t){return mM.apply(this,arguments)}(e,t)})),yM.apply(this,arguments)}function gM(){return(gM=e._asyncToGenerator((function*(e,t){var r=z.decode(e);return iM().decrypt(r,t)}))).apply(this,arguments)}function mM(){return(mM=e._asyncToGenerator((function*(e,t){var r,n=gl.get();if(e.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){var i=nt(e.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:o}=vv(i),{iv:a,salt:s,iterations:l,keySize:c,cipherText:u}=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 Jo("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 Jo("Only pkcs5PBKDF2 key derivation functions are supported");var n=r.valueBlock.value[1],i=bM(n.valueBlock.value[0].getValue()),o=oM,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 Jo("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 Jo("Only AES-CBC encryption schemes are supported");var c=bM(s.valueBlock.value[1].getValue());return{cipherText:bM(e.valueBlock.value[1].getValue()),salt:i,iterations:o,keySize:a,iv:c}}(o),d=yield Po(bo,t,s,{c:l,dkLen:c}),h=yield n.subtle.importKey("raw",d,"AES-CBC",!1,["decrypt"]),p=bM(yield n.subtle.decrypt({name:"AES-CBC",iv:a},h,u)),{result:f}=vv(p);r=wM(f)}else{if(!e.includes("-----BEGIN PRIVATE KEY-----"))throw new Jo("Could not parse private key from PEM data");var v=nt(e.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:y}=vv(v);r=wM(y)}var g=zl(r);if("RSA"!==g.type)throw new Jo("Could not parse RSA private key from PEM data");return g}))).apply(this,arguments)}function wM(e){return bM(e.valueBlock.value[2].getValue())}function bM(e){return new Uint8Array(e,0,e.byteLength)}var _M,SM="/info/",PM=new WeakMap,EM=14,AM=16,kM=1e3,xM={dek:{keyLength:64,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function TM(e){return null!=e&&("string"==typeof e&&(e===rM(e.trim())&&e.length>0))}function IM(){return CM.apply(this,arguments)}function CM(){return CM=e._asyncToGenerator((function*(){var e=800*Math.random()+200;yield new Promise((t=>setTimeout(t,e)))})),CM.apply(this,arguments)}function BM(e){return new xc("/pkcs8/"+e)}function NM(e){return new xc(SM+e)}function DM(){return(DM=e._asyncToGenerator((function*(e){var t=Vl(e),r=yield De.digest(t);return j.encode(r.bytes).substring(1)}))).apply(this,arguments)}class GM{constructor(t,r){var n,i,o,a,s,l,c,u,d,h;if(e._defineProperty(this,"components",void 0),e._defineProperty(this,"init",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"self",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/keychain"),e._defineProperty(this,Ba,["@libp2p/keychain"]),this.components=t,this.log=t.logger.forComponent("libp2p:keychain"),this.init=$L(xM,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<EM)throw new Error("dek.keyLength must be least ".concat(EM," 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<AM)throw new Error("dek.saltLength must be least ".concat(AM," bytes"));if(null!=(null===(s=this.init.dek)||void 0===s?void 0:s.iterationCount)&&this.init.dek.iterationCount<kM)throw new Error("dek.iterationCount must be least ".concat(kM));var p=null!=this.init.pass&&null!=(null===(l=this.init.dek)||void 0===l?void 0:l.salt)?Pc(this.init.pass,null===(c=this.init.dek)||void 0===c?void 0:c.salt,null===(u=this.init.dek)||void 0===u?void 0:u.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):"";PM.set(this,{dek:p})}static generateOptions(){var e=Object.assign({},xM),t=3*Math.ceil(AM/3);return e.dek.salt=Ze(pl(t),"base64"),e}static get options(){return xM}findKeyByName(t){var r=this;return e._asyncToGenerator((function*(){if(!TM(t))throw yield IM(),new Jo("Invalid key name '".concat(t,"'"));var e=NM(t);try{var n=yield r.components.datastore.get(e);return JSON.parse(Ze(n))}catch(e){throw yield IM(),r.log.error(e),new aa("Key '".concat(t,"' does not exist."))}}))()}findKeyById(t){var r=this;return e._asyncToGenerator((function*(){try{var n,i={prefix:SM},o=!1,a=!1;try{for(var s,l=e._asyncIterator(r.components.datastore.query(i));o=!(s=yield l.next()).done;o=!1){var c=s.value,u=JSON.parse(Ze(c.value));if(u.id===t)return u}}catch(e){a=!0,n=e}finally{try{o&&null!=l.return&&(yield l.return())}finally{if(a)throw n}}throw new Jo("Key with id '".concat(t,"' does not exist."))}catch(e){throw yield IM(),e}}))()}importKey(t,r){var n=this;return e._asyncToGenerator((function*(){if(!TM(t))throw yield IM(),new Jo("Invalid key name '".concat(t,"'"));if(null==r)throw yield IM(),new Jo("Key is required");var e,i,o=BM(t);if(yield n.components.datastore.has(o))throw yield IM(),new Jo("Key '".concat(t,"' already exists"));try{e=yield function(e){return DM.apply(this,arguments)}(r);var a=PM.get(n);if(null==a)throw new Jo("dek missing");var s=a.dek;i=yield lM(r,s,"RSA"===r.type?"pkcs-8":"libp2p-key")}catch(e){throw yield IM(),e}var l={name:t,id:e},c=n.components.datastore.batch();return c.put(o,nt(i)),c.put(NM(t),nt(JSON.stringify(l))),yield c.commit(),l}))()}exportKey(t){var r=this;return e._asyncToGenerator((function*(){if(!TM(t))throw yield IM(),new Jo("Invalid key name '".concat(t,"'"));var e=BM(t);try{var n=Ze(yield r.components.datastore.get(e)),i=PM.get(r);if(null==i)throw new Jo("dek missing");var o=i.dek;return yield vM(n,o)}catch(e){throw yield IM(),e}}))()}removeKey(t){var r=this;return e._asyncToGenerator((function*(){if(!TM(t)||t===r.self)throw yield IM(),new Jo("Invalid key name '".concat(t,"'"));var e=BM(t),n=yield r.findKeyByName(t),i=r.components.datastore.batch();return i.delete(e),i.delete(NM(t)),yield i.commit(),n}))()}listKeys(){var t=this;return e._asyncToGenerator((function*(){var r,n={prefix:SM},i=[],o=!1,a=!1;try{for(var s,l=e._asyncIterator(t.components.datastore.query(n));o=!(s=yield l.next()).done;o=!1){var c=s.value;i.push(JSON.parse(Ze(c.value)))}}catch(e){a=!0,r=e}finally{try{o&&null!=l.return&&(yield l.return())}finally{if(a)throw r}}return i}))()}renameKey(t,r){var n=this;return e._asyncToGenerator((function*(){if(!TM(t)||t===n.self)throw yield IM(),new Jo("Invalid old key name '".concat(t,"'"));if(!TM(r)||r===n.self)throw yield IM(),new Jo("Invalid new key name '".concat(r,"'"));var e=BM(t),i=BM(r),o=NM(t),a=NM(r);if(yield n.components.datastore.has(i))throw yield IM(),new Jo("Key '".concat(r,"' already exists"));try{var s=yield n.components.datastore.get(e),l=yield n.components.datastore.get(o),c=JSON.parse(Ze(l));c.name=r;var u=n.components.datastore.batch();return u.put(i,s),u.put(a,nt(JSON.stringify(c))),u.delete(e),u.delete(o),yield u.commit(),c}catch(e){throw yield IM(),e}}))()}rotateKeychainPass(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i,o,a;if("string"!=typeof t)throw yield IM(),new Jo("Invalid old pass type '".concat(typeof t,"'"));if("string"!=typeof r)throw yield IM(),new Jo("Invalid new pass type '".concat(typeof r,"'"));if(r.length<20)throw yield IM(),new Jo("Invalid pass length ".concat(r.length));n.log("recreating keychain");var s=PM.get(n);if(null==s)throw new Jo("dek missing");var l=s.dek;n.init.pass=r;var c=null!=r&&null!=(null===(e=n.init.dek)||void 0===e?void 0:e.salt)?Pc(r,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):"";PM.set(n,{dek:c});var u=yield n.listKeys();for(var d of u){var h=Ze(yield n.components.datastore.get(BM(d.name))),p=yield vM(h,l),f=c.toString(),v=yield lM(p,f,"RSA"===p.type?"pkcs-8":"libp2p-key"),y=n.components.datastore.batch(),g={name:d.name,id:d.id};y.put(BM(d.name),nt(v)),y.put(NM(d.name),nt(JSON.stringify(g))),yield y.commit()}n.log("keychain reconstructed")}))()}}function RM(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new GM(t,e)}class OM{constructor(){var t,r,n,i,o,a,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e._defineProperty(this,"memoryStorage",void 0),e._defineProperty(this,"points",void 0),e._defineProperty(this,"duration",void 0),e._defineProperty(this,"blockDuration",void 0),e._defineProperty(this,"execEvenly",void 0),e._defineProperty(this,"execEvenlyMinDelayMs",void 0),e._defineProperty(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 LM}consume(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:1,i=r.length>2&&void 0!==r[2]?r[2]:{},o=n.getKey(t),a=n._getKeySecDuration(i),s=n.memoryStorage.incrby(o,e,a);if(s.remainingPoints=Math.max(n.points-s.consumedPoints,0),s.consumedPoints>n.points)throw n.blockDuration>0&&s.consumedPoints<=n.points+e&&(s=n.memoryStorage.set(o,s.consumedPoints,n.blockDuration)),new Ch("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 xR(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 LM{constructor(){e._defineProperty(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"}(_M||(_M={}));var MM=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),jM=Object.freeze({NEW_STREAM:_M.NEW_STREAM,MESSAGE:_M.MESSAGE_INITIATOR,CLOSE:_M.CLOSE_INITIATOR,RESET:_M.RESET_INITIATOR}),FM=Object.freeze({MESSAGE:_M.MESSAGE_RECEIVER,CLOSE:_M.CLOSE_RECEIVER,RESET:_M.RESET_RECEIVER}),UM=1<<20;class zM{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:UM,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4194304;e._defineProperty(this,"_buffer",void 0),e._defineProperty(this,"_headerInfo",void 0),e._defineProperty(this,"_maxMessageSize",void 0),e._defineProperty(this,"_maxUnprocessedMessageQueueSize",void 0),this._buffer=new Oa,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 ha("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!==_M.NEW_STREAM&&n!==_M.MESSAGE_INITIATOR&&n!==_M.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}=HM(e),{value:n,offset:i}=HM(e,r),o=7&t;if(null==MM[o])throw new Error("Invalid type received: ".concat(o));if(n>this._maxMessageSize)throw new ha("Message size too large");return{id:t>>3,type:o,offset:r+i,length:n}}}var VM=128,qM=127;function HM(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&qM)<<i:(t&qM)*Math.pow(2,i),i+=7}while(t>=VM);return{value:n,offset:r=o-r}}var KM=10240;var WM=new class{constructor(){e._defineProperty(this,"_pool",void 0),e._defineProperty(this,"_poolOffset",void 0),this._pool=Ke(KM),this._poolOffset=0}write(e,t){var r=this._pool,n=this._poolOffset;yt(e.id<<3|e.type,r,n),n+=pt(e.id<<3|e.type),e.type!==_M.NEW_STREAM&&e.type!==_M.MESSAGE_INITIATOR&&e.type!==_M.MESSAGE_RECEIVER||null==e.data?(yt(0,r,n),n+=pt(0)):(yt(e.data.length,r,n),n+=pt(e.data.length));var i=r.subarray(this._poolOffset,n);KM-n<100?(this._pool=Ke(KM),this._poolOffset=0):this._poolOffset=n,t.append(i),e.type!==_M.NEW_STREAM&&e.type!==_M.MESSAGE_INITIATOR&&e.type!==_M.MESSAGE_RECEIVER||null==e.data||t.append(e.data)}};function QM(){return QM=e._wrapAsyncGenerator((function*(t){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t);n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var s=o.value,l=new Oa;WM.write(s,l),yield l}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw r}}})),QM.apply(this,arguments)}class YM extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Stream input buffer error"),this.name="StreamInputBufferError"}}class JM extends Ip{constructor(t){super(t),e._defineProperty(this,"name",void 0),e._defineProperty(this,"streamId",void 0),e._defineProperty(this,"send",void 0),e._defineProperty(this,"types",void 0),e._defineProperty(this,"maxDataSize",void 0),this.types="outbound"===t.direction?jM:FM,this.send=t.send,this.name=t.name,this.streamId=t.streamId,this.maxDataSize=t.maxDataSize}sendNewStream(){var t=this;return e._asyncToGenerator((function*(){yield t.send({id:t.streamId,type:jM.NEW_STREAM,data:new Oa(nt(t.name))})}))()}sendData(t){var r=this;return e._asyncToGenerator((function*(){for(t=t.sublist();t.byteLength>0;){var e=Math.min(t.byteLength,r.maxDataSize);yield r.send({id:r.streamId,type:r.types.MESSAGE,data:t.sublist(0,e)}),t.consume(e)}}))()}sendReset(){var t=this;return e._asyncToGenerator((function*(){yield t.send({id:t.streamId,type:t.types.RESET})}))()}sendCloseWrite(){var t=this;return e._asyncToGenerator((function*(){yield t.send({id:t.streamId,type:t.types.CLOSE})}))()}sendCloseRead(){return e._asyncToGenerator((function*(){}))()}}function ZM(t){var r=e._objectSpread2(e._objectSpread2({},t),{},{type:"".concat(MM[t.type]," (").concat(t.type,")")});return t.type===_M.NEW_STREAM&&(r.data=Ze(t.data instanceof Uint8Array?t.data:t.data.subarray())),t.type!==_M.MESSAGE_INITIATOR&&t.type!==_M.MESSAGE_RECEIVER||(r.data=Ze(t.data instanceof Uint8Array?t.data:t.data.subarray(),"base16")),r}class $M{constructor(t,r){var n,i;e._defineProperty(this,"protocol","/mplex/6.7.0"),e._defineProperty(this,"sink",void 0),e._defineProperty(this,"source",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"_streamId",void 0),e._defineProperty(this,"_streams",void 0),e._defineProperty(this,"_init",void 0),e._defineProperty(this,"_source",void 0),e._defineProperty(this,"closeController",void 0),e._defineProperty(this,"rateLimiter",void 0),e._defineProperty(this,"closeTimeout",void 0),e._defineProperty(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=Yc({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=iu(this._source,(e=>function(e){return QM.apply(this,arguments)}(e))),this.closeController=new AbortController,this.rateLimiter=new OM({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 na("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(t){var r=this;return e._asyncToGenerator((function*(){var n;if(!r.closeController.signal.aborted){var i=null!==(n=null==t?void 0:t.signal)&&void 0!==n?n:AbortSignal.timeout(r.closeTimeout);try{yield Promise.all(r.streams.map(function(){var t=e._asyncToGenerator((function*(e){return e.close({signal:i})}));return function(e){return t.apply(this,arguments)}}())),r._source.end(),yield r._source.onEmpty({signal:i}),r.closeController.abort()}catch(e){r.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(t){var r,n=this,{id:i,name:o,type:a,registry:s}=t;if(this.log("new %s stream %s",a,i),"initiator"===a&&this._streams.initiators.size===(null!==(r=this._init.maxOutboundStreams)&&void 0!==r?r:1024))throw new _a("Too many outbound streams open");if(s.has(i))throw new Error("".concat(a," stream ").concat(i," already exists!"));var l=function(){var t=e._asyncToGenerator((function*(e){n.log.enabled&&n.log.trace("%s stream %s send",a,i,ZM(e)),n._source.push(e)}));return function(e){return t.apply(this,arguments)}}(),c=function(e){var{id:t,name:r,send:n,onEnd:i,type:o="initiator",maxMsgSize:a=UM}=e;return new JM({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,c.protocol),s.delete(i),null!=this._init.onStreamEnd&&this._init.onStreamEnd(c)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return s.set(i,c),c}_createSink(){var t=this,r=function(){var r=e._asyncToGenerator((function*(r){var n=()=>{xp(r,t.log)};t.closeController.signal.addEventListener("abort",n);try{var i,o=new zM(t._init.maxMsgSize,t._init.maxUnprocessedMessageQueueSize),a=!1,s=!1;try{for(var l,c=e._asyncIterator(r);a=!(l=yield c.next()).done;a=!1){var u=l.value;for(var d of o.write(u))yield t._handleIncoming(d)}}catch(e){s=!0,i=e}finally{try{a&&null!=c.return&&(yield c.return())}finally{if(s)throw i}}t._source.end()}catch(e){t.log("error in sink",e),t._source.end(e)}finally{t.closeController.signal.removeEventListener("abort",n)}}));return function(e){return r.apply(this,arguments)}}();return r}_handleIncoming(t){var r=this;return e._asyncToGenerator((function*(){var e,{id:n,type:i}=t;if(r.log.enabled&&r.log.trace("incoming message",ZM(t)),t.type!==_M.NEW_STREAM){var o=(1&~i?r._streams.receivers:r._streams.initiators).get(n);if(null!=o){var a=null!==(e=r._init.maxStreamBufferSize)&&void 0!==e?e:4194304;try{switch(i){case _M.MESSAGE_INITIATOR:case _M.MESSAGE_RECEIVER:if(o.sourceReadableLength()>a)throw r._source.push({id:t.id,type:i===_M.MESSAGE_INITIATOR?_M.RESET_RECEIVER:_M.RESET_INITIATOR}),new YM("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers");o.sourcePush(t.data);break;case _M.CLOSE_INITIATOR:case _M.CLOSE_RECEIVER:o.remoteCloseWrite();break;case _M.RESET_INITIATOR:case _M.RESET_RECEIVER:o.reset();break;default:r.log("unknown message type %s",i)}}catch(e){r.log.error("error while processing message",e),o.abort(e)}}else{r.log("missing stream %s for message type %s",n,MM[i]);try{yield r.rateLimiter.consume("missing-stream",1)}catch(e){return r.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),void r.abort(new Error("Too many messages for missing streams"))}}}else{var s;if(r._streams.receivers.size===(null!==(s=r._init.maxInboundStreams)&&void 0!==s?s:1024)){r.log("too many inbound streams open"),r._source.push({id:n,type:_M.RESET_RECEIVER});try{yield r.rateLimiter.consume("new-stream",1)}catch(e){return r.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),void r.abort(new Error("Too many open streams"))}return}var l=r._newReceiverStream({id:n,name:Ze(t.data instanceof Uint8Array?t.data:t.data.subarray())});null!=r._init.onIncomingStream&&r._init.onIncomingStream(l)}}))()}}class XM{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"protocol","/mplex/6.7.0"),e._defineProperty(this,"_init",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/mplex"),e._defineProperty(this,Ba,["@libp2p/stream-multiplexing"]),this.components=t,this._init=r}createStreamMuxer(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new $M(this.components,e._objectSpread2(e._objectSpread2({},t),this._init))}}function ej(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new XM(t,e)}class tj{constructor(t){var r,n,i,o,a,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"started",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"maxInboundStreams",void 0),e._defineProperty(this,"maxOutboundStreams",void 0),e._defineProperty(this,"runOnLimitedConnection",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/ping"),e._defineProperty(this,Ba,["@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 t=this;return e._asyncToGenerator((function*(){yield t.components.registrar.handle(t.protocol,t.handleMessage,{maxInboundStreams:t.maxInboundStreams,maxOutboundStreams:t.maxOutboundStreams,runOnLimitedConnection:t.runOnLimitedConnection}),t.started=!0}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield t.components.registrar.unhandle(t.protocol),t.started=!1}))()}isStarted(){return this.started}handleMessage(t){var r=this;this.log("incoming ping from %p",t.connection.remotePeer);var{stream:n}=t,i=Date.now(),o=Mu(n),a=!1;Promise.resolve().then(e._asyncToGenerator((function*(){for(;;){var e=AbortSignal.timeout(r.timeout);e.addEventListener("abort",(()=>{null==n||n.abort(new fa("ping timeout"))}));var t=yield o.read({bytes:32,signal:e});yield o.write(t,{signal:e}),a=!0}}))).catch((e=>{a&&"UnexpectedEOFError"===e.name&&"ready"!==n.readStatus||(this.log.error("incoming ping from %p failed with error - %e",t.connection.remotePeer,e),null==n||n.abort(e))})).finally((()=>{var e=Date.now()-i;this.log("incoming ping from %p complete in %dms",t.connection.remotePeer,e);var r=AbortSignal.timeout(this.timeout);n.close({signal:r}).catch((e=>{this.log.error("error closing ping stream from %p - %e",t.connection.remotePeer,e),null==n||n.abort(e)}))}))}ping(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{};n.log("pinging %p",t);var o,a=Date.now(),s=pl(32),l=yield n.components.connectionManager.openConnection(t,i);if(null==i.signal){var c=AbortSignal.timeout(n.timeout);i=e._objectSpread2(e._objectSpread2({},i),{},{signal:c})}try{var u=Mu(o=yield l.newStream(n.protocol,e._objectSpread2(e._objectSpread2({},i),{},{runOnLimitedConnection:n.runOnLimitedConnection}))),[,d]=yield Promise.all([u.write(s,i),u.read(e._objectSpread2(e._objectSpread2({},i),{},{bytes:32}))]),h=Date.now()-a;if(!rt(s,d.subarray()))throw new pa("Received wrong ping ack after ".concat(h,"ms"));return n.log("ping %p complete in %dms",l.remotePeer,h),h}catch(e){var p;throw n.log.error("error while pinging %p",l.remotePeer,e),null===(p=o)||void 0===p||p.abort(e),e}finally{null!=o&&(yield o.close(i))}}))()}}function rj(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new tj(t,e)}var nj,ij,oj=function(){var t=e._asyncToGenerator((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(e){return t.apply(this,arguments)}}(),aj=(t,r)=>{(r=null!=r?r:{}).closeOnEnd=!1!==r.closeOnEnd;var n=function(){var n=e._asyncToGenerator((function*(n){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(n);o=!(s=yield l.next()).done;o=!1){var c=s.value;try{yield oj(t)}catch(e){if("socket closed"===e.message)break;throw e}if(t.readyState===t.CLOSING||t.readyState===t.CLOSED)break;t.send(c)}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield l.return())}finally{if(a)throw i}}null!=r.closeOnEnd&&t.readyState<=1&&(yield new Promise(((e,r)=>{t.addEventListener("close",(t=>{if(t.wasClean||1006===t.code)e();else{var n=Object.assign(new Error("ws error"),{event:t});r(n)}})),setTimeout((()=>{t.close()}))})))}));return function(e){return n.apply(this,arguments)}}();return n},sj={},lj={};var cj=function(){if(ij)return sj;ij=1,Object.defineProperty(sj,"__esModule",{value:!0});var e=function(){if(nj)return lj;nj=1,Object.defineProperty(lj,"__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 lj.EventIterator=t,lj.default=t,lj}();return sj.EventIterator=e.EventIterator,sj.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)},sj.default=e.EventIterator,sj}();function uj(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 dj=t=>{t.binaryType="arraybuffer";var r,n=function(){var n=e._asyncToGenerator((function*(){yield new Promise(((e,n)=>{if(o)e();else if(null==r){var i=e=>{t.removeEventListener("open",a),t.removeEventListener("error",s),e()},a=()=>{i(e)},s=e=>{i((()=>{var r;n(null!==(r=e.error)&&void 0!==r?r:new Error("connect ECONNREFUSED ".concat(t.url)))}))};t.addEventListener("open",a),t.addEventListener("error",s)}else n(r)}))}));return function(){return n.apply(this,arguments)}}(),i=e._wrapAsyncGenerator((function*(){var r=new cj.EventIterator((e=>{var{push:r,stop:n,fail:i}=e,o=e=>{var t=null;"string"==typeof e.data&&(t=nt(e.data)),uj(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 t.addEventListener("message",o),t.addEventListener("error",a),t.addEventListener("close",n),()=>{t.removeEventListener("message",o),t.removeEventListener("error",a),t.removeEventListener("close",n)}}),{highWaterMark:1/0});yield e._awaitAsyncGenerator(n());var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(r);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;yield uj(c)?new Uint8Array(c):c}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}))(),o=1===t.readyState;return t.addEventListener("open",(()=>{o=!0,r=null})),t.addEventListener("close",(()=>{o=!1,r=null})),t.addEventListener("error",(e=>{var n;o||(r=null!==(n=e.error)&&void 0!==n?n:new Error("connect ECONNREFUSED ".concat(t.url)))})),Object.assign(i,{connected:n})},hj=(t,r)=>{r=null!=r?r:{};var n=dj(t),i=r.remoteAddress,o=r.remotePort;if(null!=t.url)try{var a=new URL(t.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,c={sink:aj(t,r),source:n,connected:(l=e._asyncToGenerator((function*(){yield n.connected()})),function(){return l.apply(this,arguments)}),close:(s=e._asyncToGenerator((function*(){t.readyState!==t.CONNECTING&&t.readyState!==t.OPEN||(yield new Promise((e=>{t.addEventListener("close",(()=>{e()})),t.close()})))})),function(){return s.apply(this,arguments)}),destroy:()=>{null!=t.terminate?t.terminate():t.close()},remoteAddress:i,remotePort:o,socket:t};return c},pj=WebSocket,fj={"http:":"ws:","https:":"wss:"};function vj(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,c]of Object.entries(fj))s.protocol===l&&(s.protocol=c);return s})(e,"undefined"==typeof window?void 0:window.location),n=new pj(r.toString(),t.websocket);return hj(n,t)}class yj{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"log",void 0),e._defineProperty(this,"init",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,Ko,!0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/websockets"),e._defineProperty(this,Ba,["@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(t,r){var n=this;return e._asyncToGenerator((function*(){var i;n.log("dialing %s",t),r=null!=r?r:{};var o=function(t,r,n){var i,o=n.logger.forComponent("libp2p:websockets:maconn"),a=n.metrics,s=null!==(i=n.metricPrefix)&&void 0!==i?i:"",l={log:o,sink:r=>e._asyncToGenerator((function*(){try{yield t.sink(e._wrapAsyncGenerator((function*(){var t,n=!1,i=!1;try{for(var o,a=e._asyncIterator(r);n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var s=o.value;s instanceof Uint8Array?yield s:yield s.subarray()}}catch(e){i=!0,t=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw t}}}))())}catch(e){"aborted"!==e.type&&o.error(e)}}))(),source:t.source,remoteAddr:r,timeline:{open:Date.now()},close(){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i,a=r.length>0&&void 0!==r[0]?r[0]:{},s=Date.now();if(null==a.signal){var c=AbortSignal.timeout(500);a=e._objectSpread2(e._objectSpread2({},a),{},{signal:c})}var u=()=>{var{host:e,port:t}=l.remoteAddr.toOptions();o("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-s),n.abort(new Wo("Socket close timeout"))};null===(i=a.signal)||void 0===i||i.addEventListener("abort",u);try{yield t.close()}catch(e){o.error("error closing WebSocket gracefully",e),n.abort(e)}finally{var d;null===(d=a.signal)||void 0===d||d.removeEventListener("abort",u),l.timeline.close=Date.now()}}))()},abort(e){var{host:r,port:n}=l.remoteAddr.toOptions();o("timeout closing stream to %s:%s due to error",r,n,e),t.destroy(),l.timeline.close=Date.now(),null==a||a.increment({["".concat(s,"error")]:!0})}};return t.socket.addEventListener("close",(()=>{null==a||a.increment({["".concat(s,"close")]:!0}),null==l.timeline.close&&(l.timeline.close=Date.now())}),{once:!0}),l}(yield n._connect(t,r),t,{logger:n.logger,metrics:null===(i=n.metrics)||void 0===i?void 0:i.dialerEvents});n.log("new outbound connection %s",o.remoteAddr);var a=yield r.upgrader.upgradeOutbound(o,r);return n.log("outbound connection %s upgraded",o.remoteAddr),a}))()}_connect(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i;null==r||null===(e=r.signal)||void 0===e||e.throwIfAborted();var o=t.toOptions();n.log("dialing %s:%s",o.host,o.port);var a=Hc(),s=vj(GN(t),n.init);s.socket.addEventListener("error",(()=>{var e,r=new ra("Could not connect to ".concat(t.toString()));n.log.error("connection error:",r),null===(e=n.metrics)||void 0===e||e.dialerEvents.increment({error:!0}),a.reject(r)}));try{var l;null===(l=r.onProgress)||void 0===l||l.call(r,new Ah("websockets:open-connection")),yield Zc(Promise.race([s.connected(),a.promise]),r.signal)}catch(e){var c,u;if(null!==(c=r.signal)&&void 0!==c&&c.aborted)null===(u=n.metrics)||void 0===u||u.dialerEvents.increment({abort:!0});throw s.close().catch((e=>{n.log.error("error closing raw socket",e)})),e}return n.log("connected %s",t),null===(i=n.metrics)||void 0===i||i.dialerEvents.increment({connect:!0}),s}))()}createListener(t){return function(){throw new Error("WebSocket Servers can not be created in the browser!")}((this.logger,this.components.events,this.components.metrics),e._objectSpread2(e._objectSpread2({},this.init),t))}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=>Ld.exactMatch(e)||Rd.exactMatch(e)))}(e)}dialFilter(e){return this.listenFilter(e)}}function gj(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new yj(t,e)}function mj(e,t){var r=t.map(((e,t)=>({record:yD(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===rD.ValidityType.EOL&&t.record.validityType===rD.ValidityType.EOL){var i=iD.fromString(e.record.validity).toDate(),o=iD.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 wj="2.8.8",bj="js-libp2p";function _j(e,t){return"".concat(null!=e?e:bj,"/").concat(null!=t?t:wj," browser/").concat(globalThis.navigator.userAgent)}var Sj={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 Pj(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r="".concat("helia","/").concat("5.3.0"," ").concat(_j());return{privateKey:t.privateKey,dns:t.dns,nodeInfo:{userAgent:r},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[Zh(),sx(),ax(),gj()],connectionEncrypters:[Wk()],streamMuxers:[MG(),ej()],peerDiscovery:[(e=Sj,t=>new PR(t,e))],services:{autoNAT:qG(),dcutr:OR(),delegatedRouting:()=>function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new MD(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:DL({clientMode:!0,validators:{ipns:PD},selectors:{ipns:mj}}),identify:WR(),identifyPush:QR(),keychain:RM(t.keychain),ping:rj()}}}function Ej(){return Ej=e._asyncToGenerator((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=RM(i)({datastore:e,logger:Au()});(yield e.has(new xc("/pkcs8/".concat(o))))?r=yield a.exportKey(o):(r=yield Ol(null!==(n=i.keyType)&&void 0!==n?n:"Ed25519"),yield a.importKey(o,r));return r})),Ej.apply(this,arguments)}var Aj=-1,kj={},xj={};[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,Aj,"ip6zone"],[43,8,"ipcidr"],[53,Aj,"dns",!0],[54,Aj,"dns4",!0],[55,Aj,"dns6",!0],[56,Aj,"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,Aj,"unix",!1,!0],[421,Aj,"ipfs"],[421,Aj,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,Aj,"garlic64"],[448,0,"tls"],[449,Aj,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,Aj,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,Aj,"http-path"],[777,Aj,"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);xj[t.code]=t,kj[t.name]=t}));var{code:Tj}=function(e){if(null!=kj[e])return kj[e];throw new Error("no protocol with name: ".concat(e))}("dnsaddr");class Ij extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Max recursive depth reached"),this.name="RecursionLimitError"}}var Cj=function(){var t=e._asyncToGenerator((function*(t){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 Ij("Max recursive depth reached");var[,s]=null!==(n=t.stringTuples().find((e=>{var[t]=e;return t===Tj})))&&void 0!==n?n:[],l=null!==(i=null==o?void 0:o.dns)&&void 0!==i?i:wT(),c=yield l.query("_dnsaddr.".concat(s),{signal:null==o?void 0:o.signal,types:[mT.TXT]}),u=t.getPeerId(),d=[];for(var h of c.Answer){var p=h.data.replace(/["']/g,"").trim().split("=")[1];if(null!=p&&(null==u||p.includes(u))){var f=nr(p);if(p.startsWith("/dnsaddr")){var v=yield f.resolve(e._objectSpread2(e._objectSpread2({},o),{},{maxRecursiveDepth:a-1}));d.push(...v.map((e=>e.toString())))}else d.push(f.toString())}}return d}));return function(e){return t.apply(this,arguments)}}(),Bj={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:Cj}},transportManager:{faultTolerance:Vo.FATAL_ALL}};function Nj(){return Nj=e._asyncToGenerator((function*(e){var t,r=$L(Bj,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 Jo("Private network is enforced, but no protector was provided");return r})),Nj.apply(this,arguments)}var Dj,Gj,Rj;function Oj(e,t){if(null!=e.publicKey||null==t.publicKey)return e;var r;"RSA"===e.type&&(r=Ae(j.decode("z".concat(e))));return Xl(Ml(t.publicKey,r))}function Lj(e,t,r){return Mj(e,Dj.decode(t),r)}function Mj(t,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 e._objectSpread2(e._objectSpread2({},r),{},{id:Oj(t,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:nr(t),isCertified:null!=r&&r}})),metadata:r.metadata,peerRecordEnvelope:null!==(i=r.peerRecordEnvelope)&&void 0!==i?i:void 0,tags:o})}function jj(e,t){return u=e.addresses,d=t.addresses,Uj(u,d,((e,t)=>e.isCertified===t.isCertified&&!!rt(e.multiaddr,t.multiaddr)))&&(l=e.protocols,c=t.protocols,Uj(l,c,((e,t)=>e===t)))&&(a=e.publicKey,s=t.publicKey,Fj(a,s))&&(i=e.peerRecordEnvelope,o=t.peerRecordEnvelope,Fj(i,o))&&(r=e.metadata,n=t.metadata,zj(r,n,((e,t)=>rt(e,t))))&&function(e,t){return zj(e,t,((e,t)=>e.value===t.value&&e.expiry===t.expiry))}(e.tags,t.tags);var r,n,i,o,a,s,l,c,u,d}function Fj(e,t){return null==e&&null==t||null!=e&&null!=t&&rt(e,t)}function Uj(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 zj(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=ul((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:He(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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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),Rj.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=Rj.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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==t&&(t=ul((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),Gj.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,c]of t.tags.entries())r.uint32(58),e.Peer$tagsEntry.codec().encode({key:l,value:c},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 dl('Decode error - map field "addresses" had too many elements');i.addresses.push(Gj.codec().decode(t,t.uint32(),{limits:null===(l=n.limits)||void 0===l?void 0:l.addresses$}));break;case 2:var c;if(null!=(null===(c=n.limits)||void 0===c?void 0:c.protocols)&&i.protocols.length===n.limits.protocols)throw new dl('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 u;if(null!=(null===(u=n.limits)||void 0===u?void 0:u.metadata)&&i.metadata.size===n.limits.metadata)throw new hl('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,p;if(null!=(null===(h=n.limits)||void 0===h?void 0:h.tags)&&i.tags.size===n.limits.tags)throw new hl('Decode error - map field "tags" had too many elements');var f=e.Peer$tagsEntry.codec().decode(t,t.uint32(),{limits:{value:null===(p=n.limits)||void 0===p?void 0:p.tags$value}});i.tags.set(f.key,f.value);break;case 8:i.updated=t.uint64Number();break;default:t.skipType(7&a)}}return i}))),t),e.encode=t=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(Dj||(Dj={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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:He(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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(Gj||(Gj={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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=>sl(t,e.codec()),e.decode=(t,r)=>js(t,e.codec(),r)}(Rj||(Rj={}));var Vj="/peers/";function qj(e){if(!zo(e)||null==e.type)throw new Jo("Invalid PeerId");var t=e.toCID().toString();return new xc("".concat(Vj).concat(t))}function Hj(e,t,r,n){return Kj.apply(this,arguments)}function Kj(){return Kj=e._asyncToGenerator((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=nr(o.multiaddr)),!rr(o.multiaddr))throw new Jo("Multiaddr was invalid");if(yield t(e,o.multiaddr)){var s=null!==(a=o.isCertified)&&void 0!==a&&a,l=o.multiaddr.toString(),c=i.get(l);null!=c?o.isCertified=c.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(nr("/p2p/".concat(e)))),{isCertified:r,multiaddr:n.bytes}}))})),Kj.apply(this,arguments)}function Wj(e,t,r,n){return Qj.apply(this,arguments)}function Qj(){return Qj=e._asyncToGenerator((function*(t,r,n,i){var o,a,s,l,c,u,d;if(null==r)throw new Jo("Invalid PeerData");if(null!=r.publicKey&&null!=t.publicKey&&!r.publicKey.equals(t.publicKey))throw new Jo("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&&!t.equals(h.id))throw new Jo("peer id did not match existing peer id");var p,f=null!==(a=null==h?void 0:h.addresses)&&void 0!==a?a:[],v=new Set(null!==(s=null==h?void 0:h.protocols)&&void 0!==s?s:[]),y=null!==(l=null==h?void 0:h.metadata)&&void 0!==l?l:new Map,g=null!==(c=null==h?void 0:h.tags)&&void 0!==c?c:new Map,m=null==h?void 0:h.peerRecordEnvelope;if("patch"===n){if(null==r.multiaddrs&&null==r.addresses||(f=[],null!=r.multiaddrs&&f.push(...r.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=r.addresses&&f.push(...r.addresses)),null!=r.protocols&&(v=new Set(r.protocols)),null!=r.metadata)y=Yj(r.metadata instanceof Map?[...r.metadata.entries()]:Object.entries(r.metadata),{validate:Jj});if(null!=r.tags)g=Yj(r.tags instanceof Map?[...r.tags.entries()]:Object.entries(r.tags),{validate:Zj,map:$j});null!=r.peerRecordEnvelope&&(m=r.peerRecordEnvelope)}if("merge"===n){if(null!=r.multiaddrs&&f.push(...r.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=r.addresses&&f.push(...r.addresses),null!=r.protocols&&(v=new Set([...v,...r.protocols])),null!=r.metadata){var w=r.metadata instanceof Map?[...r.metadata.entries()]:Object.entries(r.metadata);for(var[b,_]of w)null==_?y.delete(b):y.set(b,_);y=Yj([...y.entries()],{validate:Jj})}if(null!=r.tags){var S=r.tags instanceof Map?[...r.tags.entries()]:Object.entries(r.tags),P=new Map(g);for(var[E,A]of S)null==A?P.delete(E):P.set(E,A);g=Yj([...P.entries()],{validate:Zj,map:$j})}null!=r.peerRecordEnvelope&&(m=r.peerRecordEnvelope)}null!=(null==h?void 0:h.id.publicKey)?p=Fl(h.id.publicKey):null!=r.publicKey?p=Fl(r.publicKey):null!=t.publicKey&&(p=Fl(t.publicKey));var k={addresses:yield Hj(t,null!==(u=i.addressFilter)&&void 0!==u?u:e._asyncToGenerator((function*(){return!0})),f,null===(d=i.existingPeer)||void 0===d?void 0:d.peerPB.addresses),protocols:[...v.values()].sort(((e,t)=>e.localeCompare(t))),metadata:y,tags:g,publicKey:p,peerRecordEnvelope:m};return k.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=>rt(e.multiaddr,e.multiaddr))))||void 0===r?void 0:r.observed)&&void 0!==t?t:Date.now()})),"RSA"!==t.type&&delete k.publicKey,k})),Qj.apply(this,arguments)}function Yj(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 Jj(e,t){if("string"!=typeof e)throw new Jo("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new Jo("Metadata value must be a Uint8Array")}function Zj(e,t){if("string"!=typeof e)throw new Jo("Tag name must be a string");if(null!=t.value){if(parseInt("".concat(t.value),10)!==t.value)throw new Jo("Tag value must be an integer");if(t.value<0||t.value>100)throw new Jo("Tag value must be between 0-100")}if(null!=t.ttl){if(parseInt("".concat(t.ttl),10)!==t.ttl)throw new Jo("Tag ttl must be an integer");if(t.ttl<0)throw new Jo("Tag ttl must be between greater than 0")}}function $j(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 Xj(e){var t=e.toString().split("/")[2];return rc(je.parse(t,k))}function eF(e,t,r){return Lj(Xj(e),t,r)}var tF=new WeakSet;class rF{constructor(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._classPrivateMethodInitSpec(this,tF),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"datastore",void 0),e._defineProperty(this,"lock",void 0),e._defineProperty(this,"addressFilter",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"maxAddressAge",void 0),e._defineProperty(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=eB({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(t){var r=this;return e._asyncToGenerator((function*(){try{return yield r.load(t),!0}catch(e){if("NotFoundError"!==e.name)throw e}return!1}))()}delete(t){var r=this;return e._asyncToGenerator((function*(){r.peerId.equals(t)||(yield r.datastore.delete(qj(t)))}))()}load(t){var r=this;return e._asyncToGenerator((function*(){var n=qj(t),i=yield r.datastore.get(n),o=Dj.decode(i);if(e._assertClassBrand(tF,r,sF).call(r,t,o))throw yield r.datastore.delete(n),new aa;return Mj(t,o,r.peerId.equals(t)?1/0:r.maxAddressAge)}))()}save(t,r){var n=this;return e._asyncToGenerator((function*(){var i=yield e._assertClassBrand(tF,n,nF).call(n,t),o=yield Wj(t,r,"patch",{addressFilter:n.addressFilter});return e._assertClassBrand(tF,n,oF).call(n,t,o,i)}))()}patch(t,r){var n=this;return e._asyncToGenerator((function*(){var i=yield e._assertClassBrand(tF,n,nF).call(n,t),o=yield Wj(t,r,"patch",{addressFilter:n.addressFilter,existingPeer:i});return e._assertClassBrand(tF,n,oF).call(n,t,o,i)}))()}merge(t,r){var n=this;return e._asyncToGenerator((function*(){var i=yield e._assertClassBrand(tF,n,nF).call(n,t),o=yield Wj(t,r,"merge",{addressFilter:n.addressFilter,existingPeer:i});return e._assertClassBrand(tF,n,oF).call(n,t,o,i)}))()}all(t){var r=this;return e._wrapAsyncGenerator((function*(){var n,i=!1,o=!1;try{for(var a,s=e._asyncIterator(r.datastore.query(function(e,t){var r,n;return{prefix:Vj,filters:(null!==(r=e.filters)&&void 0!==r?r:[]).map((e=>r=>{var{key:n,value:i}=r;return e(eF(n,i,t))})),orders:(null!==(n=e.orders)&&void 0!==n?n:[]).map((e=>(r,n)=>e(eF(r.key,r.value,t),eF(n.key,n.value,t))))}}(null!=t?t:{},r.maxAddressAge)));i=!(a=yield e._awaitAsyncGenerator(s.next())).done;i=!1){var{key:l,value:c}=a.value,u=Xj(l);if(!u.equals(r.peerId)){var d=Dj.decode(c);e._assertClassBrand(tF,r,sF).call(r,u,d)?yield e._awaitAsyncGenerator(r.datastore.delete(l)):yield Mj(u,d,r.peerId.equals(u)?1/0:r.maxAddressAge)}}}catch(e){o=!0,n=e}finally{try{i&&null!=s.return&&(yield e._awaitAsyncGenerator(s.return()))}finally{if(o)throw n}}}))()}}function nF(e){return iF.apply(this,arguments)}function iF(){return iF=e._asyncToGenerator((function*(t){try{var r=qj(t),n=yield this.datastore.get(r),i=Dj.decode(n);if(e._assertClassBrand(tF,this,sF).call(this,t,i))throw yield this.datastore.delete(r),new aa;return{peerPB:i,peer:Lj(t,n,this.maxAddressAge)}}catch(e){"NotFoundError"!==e.name&&this.log.error("invalid peer data found in peer store - %e",e)}})),iF.apply(this,arguments)}function oF(e,t,r){return aF.apply(this,arguments)}function aF(){return aF=e._asyncToGenerator((function*(e,t,r){t.updated=Date.now();var n=Dj.encode(t);return yield this.datastore.put(qj(e),n),{peer:Lj(e,n,this.maxAddressAge),previous:null==r?void 0:r.peer,updated:null==r||!jj(t,r.peerPB)}})),aF.apply(this,arguments)}function sF(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 lF=new WeakSet;class cF{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._classPrivateMethodInitSpec(this,lF),e._defineProperty(this,"store",void 0),e._defineProperty(this,"events",void 0),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(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 rF(t,r)}forEach(t,r){var n=this;return e._asyncToGenerator((function*(){n.log.trace("forEach await read lock");var i=yield n.store.lock.readLock();n.log.trace("forEach got read lock");try{var o,a=!1,s=!1;try{for(var l,c=e._asyncIterator(n.store.all(r));a=!(l=yield c.next()).done;a=!1){var u=l.value;t(u)}}catch(e){s=!0,o=e}finally{try{a&&null!=c.return&&(yield c.return())}finally{if(s)throw o}}}finally{n.log.trace("forEach release read lock"),i()}}))()}all(t){var r=this;return e._asyncToGenerator((function*(){r.log.trace("all await read lock");var e=yield r.store.lock.readLock();r.log.trace("all got read lock");try{return yield Bc(r.store.all(t))}finally{r.log.trace("all release read lock"),e()}}))()}delete(t){var r=this;return e._asyncToGenerator((function*(){r.log.trace("delete await write lock");var e=yield r.store.lock.writeLock();r.log.trace("delete got write lock");try{yield r.store.delete(t)}finally{r.log.trace("delete release write lock"),e()}}))()}has(t){var r=this;return e._asyncToGenerator((function*(){r.log.trace("has await read lock");var e=yield r.store.lock.readLock();r.log.trace("has got read lock");try{return yield r.store.has(t)}finally{r.log.trace("has release read lock"),e()}}))()}get(t){var r=this;return e._asyncToGenerator((function*(){r.log.trace("get await read lock");var e=yield r.store.lock.readLock();r.log.trace("get got read lock");try{return yield r.store.load(t)}finally{r.log.trace("get release read lock"),e()}}))()}getInfo(t){var r=this;return e._asyncToGenerator((function*(){var e=yield r.get(t);return{id:e.id,multiaddrs:e.addresses.map((e=>{var{multiaddr:t}=e;return t}))}}))()}save(t,r){var n=this;return e._asyncToGenerator((function*(){n.log.trace("save await write lock");var i=yield n.store.lock.writeLock();n.log.trace("save got write lock");try{var o=yield n.store.save(t,r);return e._assertClassBrand(lF,n,uF).call(n,t,o),o.peer}finally{n.log.trace("save release write lock"),i()}}))()}patch(t,r){var n=this;return e._asyncToGenerator((function*(){n.log.trace("patch await write lock");var i=yield n.store.lock.writeLock();n.log.trace("patch got write lock");try{var o=yield n.store.patch(t,r);return e._assertClassBrand(lF,n,uF).call(n,t,o),o.peer}finally{n.log.trace("patch release write lock"),i()}}))()}merge(t,r){var n=this;return e._asyncToGenerator((function*(){n.log.trace("merge await write lock");var i=yield n.store.lock.writeLock();n.log.trace("merge got write lock");try{var o=yield n.store.merge(t,r);return e._assertClassBrand(lF,n,uF).call(n,t,o),o.peer}finally{n.log.trace("merge release write lock"),i()}}))()}consumePeerRecord(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i=yield Bu.openAndCertify(t,Ou.DOMAIN),o=rc(i.publicKey.toCID());if(!1===(null==r?void 0:r.equals(o)))return n.log("envelope peer id was not the expected peer id - expected: %p received: %p",r,o),!1;var a,s=Ou.createFromProtobuf(i.payload);try{a=yield n.get(o)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=(null===(e=a)||void 0===e?void 0:e.peerRecordEnvelope)){var l=yield Bu.createFromProtobuf(a.peerRecordEnvelope),c=Ou.createFromProtobuf(l.payload);if(c.seqNumber>=s.seqNumber)return n.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,s.seqNumber),!1}return yield n.patch(s.peerId,{peerRecordEnvelope:t,addresses:s.multiaddrs.map((e=>({isCertified:!0,multiaddr:e})))}),!0}))()}}function uF(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}var dF=864e13;class hF{constructor(t){e._defineProperty(this,"log",void 0),e._defineProperty(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===kN(t);this.mappings.set(t,{domain:e,verified:r,expires:r?dF-Date.now():0,lastVerified:r?dF-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:nr("/".concat(n.map((e=>[ir(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 pF{constructor(t){e._defineProperty(this,"log",void 0),e._defineProperty(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:Pt(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,c]of this.mappings.entries()){for(var u=0;u<c.length;u++){var d=c[u];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,c.splice(u,1),u--)}0===c.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:nr("/".concat(n.map((e=>[ir(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 c of this.mappings.values())for(var u=0;u<c.length;u++){var d=c[u];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 fF=10;class vF{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"log",void 0),e._defineProperty(this,"addresses",void 0),e._defineProperty(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:fF}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&&(UG(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:nr(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 yF=[4,41,53,54,55,56];function gF(e){try{var[[t]]=e.stringTuples();return yF.includes(t)}catch(e){}return!1}var mF=10;class wF{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"log",void 0),e._defineProperty(this,"addresses",void 0),e._defineProperty(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:mF}get(e,t){if(UG(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:!gF(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(gF(e)){var t=e.toOptions();return"".concat(t.host,"-").concat(t.port,"-").concat(t.transport)}return e.toString()}}var bF,_F={addressVerificationTTL:6e5,addressVerificationRetry:3e5},SF=e=>e;function PF(e,t){var r=e.getPeerId();null!=r&&($l(r).equals(t)&&(e=e.decapsulate(nr("/p2p/".concat(t.toString())))));return e}class EF{constructor(t){var r,n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"log",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"listen",void 0),e._defineProperty(this,"announce",void 0),e._defineProperty(this,"appendAnnounce",void 0),e._defineProperty(this,"announceFilter",void 0),e._defineProperty(this,"observed",void 0),e._defineProperty(this,"dnsMappings",void 0),e._defineProperty(this,"ipMappings",void 0),e._defineProperty(this,"transportAddresses",void 0),e._defineProperty(this,"observedAddressFilter",void 0),e._defineProperty(this,"addressVerificationTTL",void 0),e._defineProperty(this,"addressVerificationRetry",void 0),e._defineProperty(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 vF(t,o),this.dnsMappings=new hF(t,o),this.ipMappings=new pF(t,o),this.transportAddresses=new wF(t,o),this.announceFilter=null!==(r=o.announceFilter)&&void 0!==r?r:SF,this.observedAddressFilter=gh(1024),this.addressVerificationTTL=null!==(n=o.addressVerificationTTL)&&void 0!==n?n:_F.addressVerificationTTL,this.addressVerificationRetry=null!==(i=o.addressVerificationRetry)&&void 0!==i?i:_F.addressVerificationRetry,this._updatePeerStoreAddresses=Ih(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=>nr(e)))}getAnnounceAddrs(){return Array.from(this.announce).map((e=>nr(e)))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map((e=>nr(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=PF(e,this.components.peerId),this.ipMappings.has(e)||this.dnsMappings.has(e)||this.observed.add(e))}confirmObservedAddr(e,t){e=PF(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=PF(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=nr(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(nr("/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(Pt(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(nr("/ip".concat(Pt(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===kN(r.host))return!1;var n,i=this.components.transportManager.getListeners(),o=[e=>Rd.exactMatch(e)||Ld.exactMatch(e),e=>Td.exactMatch(e),e=>Nd.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"}(bF||(bF={}));class AF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Missing service"),this.name="MissingServiceError"}}class kF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unmet service dependencies"),this.name="UnmetServiceDependenciesError"}}class xF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No content routers available"),this.name="NoContentRoutersError"}}class TF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No peer routers available"),this.name="NoPeerRoutersError"}}class IF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Should not try to find self"),this.name="QueriedForSelfError"}}class CF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unhandled protocol error"),this.name="UnhandledProtocolError"}}class BF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Duplicate protocol handler error"),this.name="DuplicateProtocolHandlerError"}}class NF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Dial denied error"),this.name="DialDeniedError"}}class DF 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 GF 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 RF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No valid addresses"),this.name="NoValidAddressesError"}}class OF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Connection intercepted"),this.name="ConnectionInterceptedError"}}class LF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Connection denied"),this.name="ConnectionDeniedError"}}class MF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Stream is not multiplexed"),this.name="MuxerUnavailableError"}}class jF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Encryption failed"),this.name="EncryptionFailedError"}}class FF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Transport unavailable"),this.name="TransportUnavailableError"}}class UF{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(var[r,n]of(e._defineProperty(this,"components",{}),e._defineProperty(this,"_started",!1),this.components={},Object.entries(t)))this.components[r]=n;null==this.components.logger&&(this.components.logger=Au())}isStarted(){return this._started}_invokeStartableMethod(t){var r=this;return e._asyncToGenerator((function*(){yield Promise.all(Object.values(r.components).filter((e=>ka(e))).map(function(){var r=e._asyncToGenerator((function*(e){var r;yield null===(r=e[t])||void 0===r?void 0:r.call(e)}));return function(e){return r.apply(this,arguments)}}()))}))()}beforeStart(){var t=this;return e._asyncToGenerator((function*(){yield t._invokeStartableMethod("beforeStart")}))()}start(){var t=this;return e._asyncToGenerator((function*(){yield t._invokeStartableMethod("start"),t._started=!0}))()}afterStart(){var t=this;return e._asyncToGenerator((function*(){yield t._invokeStartableMethod("afterStart")}))()}beforeStop(){var t=this;return e._asyncToGenerator((function*(){yield t._invokeStartableMethod("beforeStop")}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield t._invokeStartableMethod("stop"),t._started=!1}))()}afterStop(){var t=this;return e._asyncToGenerator((function*(){yield t._invokeStartableMethod("afterStop")}))()}}var zF=["metrics","connectionProtector","dns"],VF=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function qF(e){return Array.isArray(null==e?void 0:e[Ba])?e[Ba]:[]}function HF(e){return Array.isArray(null==e?void 0:e[Na])?e[Na]:[]}function KF(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 WF(){var t,r,n,i,o,a,s,l,c,u=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return e._objectSpread2({denyDialPeer:(c=e._asyncToGenerator((function*(){return!1})),function(){return c.apply(this,arguments)}),denyDialMultiaddr:(l=e._asyncToGenerator((function*(e){if(Rd.matches(e))return!1;var t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&Boolean(kN("".concat(t[0][1])))})),function(e){return l.apply(this,arguments)}),denyInboundConnection:(s=e._asyncToGenerator((function*(){return!1})),function(){return s.apply(this,arguments)}),denyOutboundConnection:(a=e._asyncToGenerator((function*(){return!1})),function(){return a.apply(this,arguments)}),denyInboundEncryptedConnection:(o=e._asyncToGenerator((function*(){return!1})),function(){return o.apply(this,arguments)}),denyOutboundEncryptedConnection:(i=e._asyncToGenerator((function*(){return!1})),function(){return i.apply(this,arguments)}),denyInboundUpgradedConnection:(n=e._asyncToGenerator((function*(){return!1})),function(){return n.apply(this,arguments)}),denyOutboundUpgradedConnection:(r=e._asyncToGenerator((function*(){return!1})),function(){return r.apply(this,arguments)}),filterMultiaddrForPeer:(t=e._asyncToGenerator((function*(){return!0})),function(){return t.apply(this,arguments)})},u)}function QF(e){if(zo(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:$l(n),r.forEach((e=>{if(!rr(e))throw new la("Invalid multiaddr");var r=e.getPeerId();if(null==r){if(null!=t)throw new Jo("Multiaddrs must all have the same peer id or have no peer id")}else{var n,i=$l(r);if(!0!==(null===(n=t)||void 0===n?void 0:n.equals(i)))throw new Jo("Multiaddrs must all have the same peer id or have no peer id")}}))}return r=r.filter((e=>!hd.exactMatch(e))),{peerId:t,multiaddrs:r}}var YF=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];function JF(){return JF=e._asyncToGenerator((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:YF;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)}})),JF.apply(this,arguments)}var ZF="last-dial-failure",$F="last-dial-success";function XF(){return XF=e._asyncToGenerator((function*(e,t){var r=!1;for(var n of tr.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})),XF.apply(this,arguments)}function eU(e){try{var t;if(!(t="string"==typeof e?nr(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 er(r,t)}(t)}catch(t){throw new Error("Can't convert to IpNet, Invalid multiaddr format: ".concat(e))}}var tU=100;class rU{constructor(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"maxConnections",void 0),e._defineProperty(this,"connectionManager",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"allow",void 0),e._defineProperty(this,"events",void 0),e._defineProperty(this,"log",void 0),this.maxConnections=null!==(r=i.maxConnections)&&void 0!==r?r:tU,this.allow=(null!==(n=i.allow)&&void 0!==n?n:[]).map((e=>eU(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 t=this;return e._asyncToGenerator((function*(){var r=t.connectionManager.getConnections(),n=r.length;if(t.log("checking max connections limit %d/%d",n,t.maxConnections),!(n<=t.maxConnections)){var i=new ih;for(var o of r){var a=o.remotePeer;if(!i.has(a)){i.set(a,0);try{var s=yield t.peerStore.get(a);i.set(a,[...s.tags.values()].reduce(((e,t)=>e+t.value),0))}catch(e){"NotFoundError"!==e.name&&t.log.error("error loading peer tags",e)}}}var l=t.sortConnections(r,i),c=Math.max(n-t.maxConnections,0),u=[],d=function*(e){if(t.log("too many connections open - closing a connection to %p",e.remotePeer),t.allow.some((t=>t.contains(e.remoteAddr.nodeAddress().address)))||u.push(e),u.length===c)return 1};for(var h of l)if(yield*d(h))break;yield Promise.all(u.map(function(){var t=e._asyncToGenerator((function*(e){yield function(e,t){return JF.apply(this,arguments)}(e,{signal:AbortSignal.timeout(1e3)})}));return function(e){return t.apply(this,arguments)}}())),t.events.safeDispatchEvent("connection:prune",{detail:u})}}))()}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 nU extends Gh{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(e._objectSpread2(e._objectSpread2({},t),{},{sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0}))}}function iU(e){if(!FG(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 oU(e,t){var r=Td.exactMatch(e.multiaddr),n=Td.exactMatch(t.multiaddr);if(r&&!n)return-1;if(!r&&n)return 1;var i=Ld.exactMatch(e.multiaddr),o=Ld.exactMatch(t.multiaddr);if(i&&!o)return-1;if(!i&&o)return 1;var a=Rd.exactMatch(e.multiaddr),s=Rd.exactMatch(t.multiaddr);if(a&&!s)return-1;if(!a&&s)return 1;var l=Hd.exactMatch(e.multiaddr),c=Hd.exactMatch(t.multiaddr);if(l&&!c)return-1;if(!l&&c)return 1;var u=jd.exactMatch(e.multiaddr),d=jd.exactMatch(t.multiaddr);if(u&&!d)return-1;if(!u&&d)return 1;var h=Ud.exactMatch(e.multiaddr),p=Ud.exactMatch(t.multiaddr);return h&&!p?-1:!h&&p?1:0}function aU(e,t){var r=iU(e.multiaddr),n=iU(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function sU(e,t){var r=UG(e.multiaddr),n=UG(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function lU(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function cU(e,t){var r=qd.exactMatch(e.multiaddr),n=qd.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}var uU=50,dU=500,hU=25,pU=1e4;class fU{constructor(t){var r,n,i,o,a,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};for(var[l,c]of(e._defineProperty(this,"queue",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"addressSorter",void 0),e._defineProperty(this,"maxPeerAddrsToDial",void 0),e._defineProperty(this,"maxDialQueueLength",void 0),e._defineProperty(this,"dialTimeout",void 0),e._defineProperty(this,"shutDownController",void 0),e._defineProperty(this,"connections",void 0),e._defineProperty(this,"log",void 0),this.addressSorter=s.addressSorter,this.maxPeerAddrsToDial=null!==(r=s.maxPeerAddrsToDial)&&void 0!==r?r:hU,this.maxDialQueueLength=null!==(n=s.maxDialQueueLength)&&void 0!==n?n:dU,this.dialTimeout=null!==(i=s.dialTimeout)&&void 0!==i?i:pU,this.connections=null!==(o=s.connections)&&void 0!==o?o:new ih,this.log=t.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=t,this.shutDownController=new AbortController,this.shutDownController.signal,Object.entries(null!==(u=s.resolvers)&&void 0!==u?u:{}))){var u;tr.set(l,c)}this.queue=new nU({concurrency:null!==(a=s.maxParallelDials)&&void 0!==a?a:uU,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)!==Wo.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(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i,o,a,s,l=r.length>1&&void 0!==r[1]?r[1]:{},{peerId:c,multiaddrs:u}=QF(t),d=Array.from(n.connections.values()).flat().find((e=>!0!==l.force&&(!!e.remotePeer.equals(c)||u.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 Ah("dial-queue:already-connected")),d;var h=n.queue.queue.find((e=>{if(!0===(null==c?void 0:c.equals(e.options.peerId)))return!0;var t=e.options.multiaddrs;if(null==t)return!1;for(var r of u)if(t.has(r.toString()))return!0;return!1}));if(null!=h){var p;for(var f of(n.log("joining existing dial target for %p",c),u))h.options.multiaddrs.add(f.toString());return null===(p=l.onProgress)||void 0===p||p.call(l,new Ah("dial-queue:already-in-dial-queue")),h.join(l)}if(n.queue.size>=n.maxDialQueueLength)throw new ga("Dial queue is full");return n.log("creating dial target for %p",c,u.map((e=>e.toString()))),null===(i=l.onProgress)||void 0===i||i.call(l,new Ah("dial-queue:add-to-dial-queue")),n.queue.add(function(){var t=e._asyncToGenerator((function*(e){var t;null===(t=e.onProgress)||void 0===t||t.call(e,new Ah("dial-queue:start-dial"));var r=Qd([n.shutDownController.signal,e.signal]);try{return yield n.dialPeer(e,r)}finally{r.clear()}}));return function(e){return t.apply(this,arguments)}}(),{peerId:c,priority:null!==(o=l.priority)&&void 0!==o?o:NU,multiaddrs:new Set(u.map((e=>e.toString()))),signal:null!==(a=l.signal)&&void 0!==a?a:AbortSignal.timeout(n.dialTimeout),onProgress:l.onProgress})}))()}dialPeer(t,r){var n=this;return e._asyncToGenerator((function*(){var i=t.peerId,o=t.multiaddrs,a=new Set,s=0===t.multiaddrs.size,l=0,c=0,u=[];for(n.log("starting dial to %p",i);s||o.size>0;){var d;c++,s=!1;var h=[],p=new Set(t.multiaddrs);o.clear(),n.log("calculating addrs to dial %p from %s",i,[...p]);var f=yield n.calculateMultiaddrs(i,p,e._objectSpread2(e._objectSpread2({},t),{},{signal:r}));for(var v of f)a.has(v.multiaddr.toString())?n.log.trace("skipping previously failed multiaddr %a while dialing %p",v.multiaddr,i):h.push(v);for(var y of(n.log("%s dial to %p with %s",1===c?"starting":"continuing",i,h.map((e=>e.multiaddr.toString()))),null==t||null===(d=t.onProgress)||void 0===d||d.call(t,new Ah("dial-queue:calculated-addresses",h)),h)){if(l===n.maxPeerAddrsToDial)throw n.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",l,t.peerId),new ga("Peer had more than maxPeerAddrsToDial");l++;try{var g=yield n.components.transportManager.dial(y.multiaddr,e._objectSpread2(e._objectSpread2({},t),{},{signal:r}));n.log("dial to %a succeeded",y.multiaddr);try{yield n.components.peerStore.merge(g.remotePeer,{multiaddrs:[g.remoteAddr],metadata:{[$F]:nt(Date.now().toString())}})}catch(e){n.log.error("could not update last dial failure key for %p",i,e)}return g}catch(e){if(n.log.error("dial failed to %a",y.multiaddr,e),a.add(y.multiaddr.toString()),null!=i)try{yield n.components.peerStore.merge(i,{metadata:{[ZF]:nt(Date.now().toString())}})}catch(e){n.log.error("could not update last dial failure key for %p",i,e)}if(r.aborted)throw new fa(e.message);u.push(e)}}}if(1===u.length)throw u[0];throw new AggregateError(u,"All multiaddr dials failed")}))()}calculateMultiaddrs(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:new Set,o=r.length>2&&void 0!==r[2]?r[2]:{},a=[...i].map((e=>({multiaddr:nr(e),isCertified:!1})));if(null!=t){var s,l;if(n.components.peerId.equals(t))throw new ga("Tried to dial self");if(!0===(yield null===(s=(l=n.components.connectionGater).denyDialPeer)||void 0===s?void 0:s.call(l,t)))throw new NF("The dial request is blocked by gater.allowDialPeer");if(0===a.length){n.log("loading multiaddrs for %p",t);try{var c=yield n.components.peerStore.get(t);a.push(...c.addresses),n.log("loaded multiaddrs for %p",t,a.map((e=>{var{multiaddr:t}=e;return t.toString()})))}catch(e){if("NotFoundError"!==e.name)throw e}}if(0===a.length){n.log("looking up multiaddrs for %p in the peer routing",t);try{var u=yield n.components.peerRouting.findPeer(t,o);n.log("found multiaddrs for %p in the peer routing",t,a.map((e=>{var{multiaddr:t}=e;return t.toString()}))),a.push(...u.multiaddrs.map((e=>({multiaddr:e,isCertified:!1}))))}catch(e){"NoPeerRoutersError"===e.name?n.log("no peer routers configured",t):n.log.error("looking up multiaddrs for %p in the peer routing failed - %e",t,e)}}}var d=(yield Promise.all(a.map(function(){var t=e._asyncToGenerator((function*(t){var r=yield function(e,t){return XF.apply(this,arguments)}(t.multiaddr,e._objectSpread2(e._objectSpread2({dns:n.components.dns},o),{},{log:n.log}));return 1===r.length&&r[0].equals(t.multiaddr)?t:r.map((e=>({multiaddr:e,isCertified:!1})))}));return function(e){return t.apply(this,arguments)}}()))).flat();if(null!=t){var h="/p2p/".concat(t.toString());d=d.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(h),isCertified:e.isCertified}:e}))}var p=d.filter((e=>{if(null==n.components.transportManager.dialTransportForMultiaddr(e.multiaddr))return!1;var r=e.multiaddr.getPeerId();return null==t||null==r||t.equals(r)})),f=new Map;for(var v of p){var y=v.multiaddr.toString(),g=f.get(y);null==g?f.set(y,v):g.isCertified=g.isCertified||v.isCertified||!1}var m=[...f.values()];if(0===m.length)throw new RF("The dial request has no valid addresses");var w=[];for(var b of m)null!=n.components.connectionGater.denyDialMultiaddr&&(yield n.components.connectionGater.denyDialMultiaddr(b.multiaddr))||w.push(b);var _=null==n.addressSorter?w.sort(oU).sort(lU).sort(cU).sort(sU).sort(aU):w.sort(n.addressSorter);if(0===_.length)throw new NF("The connection gater denied all addresses in the dial request");return n.log.trace("addresses for %p before filtering",null!=t?t:"unknown peer",d.map((e=>{var{multiaddr:t}=e;return t.toString()}))),n.log.trace("addresses for %p after filtering",null!=t?t:"unknown peer",_.map((e=>{var{multiaddr:t}=e;return t.toString()}))),_}))()}isDialable(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};Array.isArray(t)||(t=[t]);try{var i=yield n.calculateMultiaddrs(void 0,new Set(t.map((e=>e.toString()))),e);return!1!==e.runOnLimitedConnection||null!=i.find((e=>!qd.matches(e.multiaddr)))}catch(e){n.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}))()}}var vU,yU,gU,mU,wU,bU={};function _U(){return gU||(gU=1,function(e){var t=function(){if(yU)return vU;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 yU=1,vU=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},vU}();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}}}(bU)),bU}var SU=wU?mU:(wU=1,mU=_U()),PU=e.getDefaultExportFromCjs(SU),EU=Object.prototype.toString,AU=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 kU(e){var t;return!(!e||(t=e,"[object Error]"!==EU.call(t))||"TypeError"!==e.name||"string"!=typeof e.message)&&("Load failed"===e.message?void 0===e.stack:AU.has(e.message))}class xU 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 TU=(e,t,r)=>{var n=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=n,e};function IU(){return IU=e._asyncToGenerator((function*(t,r){return new Promise(((n,i)=>{var o,a,s,l,c,u;null!==(a=(o=r=e._objectSpread2({},r)).onFailedAttempt)&&void 0!==a||(o.onFailedAttempt=()=>{}),null!==(l=(s=r).shouldRetry)&&void 0!==l||(s.shouldRetry=()=>!0),null!==(u=(c=r).retries)&&void 0!==u||(c.retries=10);var d=PU.operation(r),h=()=>{var e;d.stop(),i(null===(e=r.signal)||void 0===e?void 0:e.reason)};r.signal&&!r.signal.aborted&&r.signal.addEventListener("abort",h,{once:!0});var p=()=>{var e;null===(e=r.signal)||void 0===e||e.removeEventListener("abort",h),d.stop()};d.attempt(function(){var o=e._asyncToGenerator((function*(e){try{var o=yield t(e);p(),n(o)}catch(t){try{if(!(t instanceof Error))throw new TypeError('Non-error was thrown: "'.concat(t,'". You should only throw errors.'));if(t instanceof xU)throw t.originalError;if(t instanceof TypeError&&!kU(t))throw t;if(TU(t,e,r),(yield r.shouldRetry(t))||(d.stop(),i(t)),yield r.onFailedAttempt(t),!d.retry(t))throw d.mainError()}catch(t){TU(t,e,r),p(),i(t)}}}));return function(e){return o.apply(this,arguments)}}())}))})),IU.apply(this,arguments)}class CU{constructor(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"log",void 0),e._defineProperty(this,"queue",void 0),e._defineProperty(this,"started",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"retries",void 0),e._defineProperty(this,"retryInterval",void 0),e._defineProperty(this,"backoffFactor",void 0),e._defineProperty(this,"connectionManager",void 0),e._defineProperty(this,"events",void 0),this.log=t.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.queue=new Rh({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(t){var r=this;return e._asyncToGenerator((function*(){if(r.started){var n=yield r.peerStore.get(t);BU(n)&&(r.queue.has(t)||r.queue.add(function(){var n=e._asyncToGenerator((function*(n){yield function(e,t){return IU.apply(this,arguments)}(function(){var i=e._asyncToGenerator((function*(e){if(r.started)try{yield r.connectionManager.openConnection(t,{signal:null==n?void 0:n.signal})}catch(n){throw r.log("reconnecting to %p attempt %d of %d failed - %e",t,e,r.retries,n),n}}));return function(e){return i.apply(this,arguments)}}(),{signal:null==n?void 0:n.signal,retries:r.retries,factor:r.backoffFactor,minTimeout:r.retryInterval})}));return function(e){return n.apply(this,arguments)}}(),{peerId:t}).catch(function(){var i=e._asyncToGenerator((function*(e){r.log.error("failed to reconnect to %p - %e",t,e);var i={};[...n.tags.keys()].forEach((e=>{e.startsWith(Ho)&&(i[e]=void 0)})),yield r.peerStore.merge(t,{tags:i}),r.events.safeDispatchEvent("peer:reconnect-failure",{detail:t})}));return function(e){return i.apply(this,arguments)}}()).catch(function(){var n=e._asyncToGenerator((function*(e){r.log.error("failed to remove keep-alive tag from %p - %e",t,e)}));return function(e){return n.apply(this,arguments)}}()))}}))()}start(){this.started=!0}afterStart(){var t=this;return e._asyncToGenerator((function*(){Promise.resolve().then(e._asyncToGenerator((function*(){var r=yield t.peerStore.all({filters:[e=>BU(e)]});yield Promise.all(r.map(function(){var r=e._asyncToGenerator((function*(e){yield t.connectionManager.openConnection(e.id).catch((e=>{t.log.error(e)}))}));return function(e){return r.apply(this,arguments)}}()))}))).catch((e=>{t.log.error(e)}))}))()}stop(){this.started=!1,this.queue.abort()}}function BU(e){for(var t of e.tags.keys())if(t.startsWith(Ho))return!0;return!1}var NU=50,DU=100,GU=5,RU=10;class OU{constructor(t){var r,n,i,o,a,s,l,c,u,d,h,p=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e._defineProperty(this,"started",void 0),e._defineProperty(this,"connections",void 0),e._defineProperty(this,"allow",void 0),e._defineProperty(this,"deny",void 0),e._defineProperty(this,"maxIncomingPendingConnections",void 0),e._defineProperty(this,"incomingPendingConnections",void 0),e._defineProperty(this,"outboundPendingConnections",void 0),e._defineProperty(this,"maxConnections",void 0),e._defineProperty(this,"dialQueue",void 0),e._defineProperty(this,"reconnectQueue",void 0),e._defineProperty(this,"connectionPruner",void 0),e._defineProperty(this,"inboundConnectionRateLimiter",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"events",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/connection-manager"),this.maxConnections=null!==(r=p.maxConnections)&&void 0!==r?r:DU,this.maxConnections<1)throw new Jo("Connection Manager maxConnections must be greater than 0");this.connections=new ih,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=p.allow)&&void 0!==n?n:[]).map((e=>eU(e))),this.deny=(null!==(i=p.deny)&&void 0!==i?i:[]).map((e=>eU(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=null!==(o=p.maxIncomingPendingConnections)&&void 0!==o?o:RU,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new OM({points:null!==(a=p.inboundConnectionThreshold)&&void 0!==a?a:GU,duration:1}),this.connectionPruner=new rU({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{maxConnections:this.maxConnections,allow:null===(s=p.allow)||void 0===s?void 0:s.map((e=>nr(e)))}),this.dialQueue=new fU(t,{addressSorter:p.addressSorter,maxParallelDials:null!==(l=p.maxParallelDials)&&void 0!==l?l:50,maxDialQueueLength:null!==(c=p.maxDialQueueLength)&&void 0!==c?c:500,maxPeerAddrsToDial:null!==(u=p.maxPeerAddrsToDial)&&void 0!==u?u:25,dialTimeout:null!==(d=p.dialTimeout)&&void 0!==d?d:1e4,resolvers:null!==(h=p.resolvers)&&void 0!==h?h:{dnsaddr:Cj},connections:this.connections}),this.reconnectQueue=new CU({events:t.events,peerStore:t.peerStore,logger:t.logger,connectionManager:this},{retries:p.reconnectRetries,retryInterval:p.reconnectRetryInterval,backoffFactor:p.reconnectBackoffFactor,maxParallelReconnects:p.maxParallelReconnects})}start(){var t=this;return e._asyncToGenerator((function*(){var e,r,n;null===(e=t.metrics)||void 0===e||e.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{var e={inbound:0,"inbound pending":t.incomingPendingConnections,outbound:0,"outbound pending":t.outboundPendingConnections};for(var r of t.connections.values())for(var n of r)e[n.direction]++;return e}}),null===(r=t.metrics)||void 0===r||r.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{var e={};for(var r of t.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");e[s]=(null!==(a=e[s])&&void 0!==a?a:0)+1}return e}}),null===(n=t.metrics)||void 0===n||n.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{var e={};for(var r of t.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[c,u]of Object.entries(i)){var d;e[c]=null!==(d=e[c])&&void 0!==d?d:[],e[c].push(u)}}var h={};for(var[p,f]of Object.entries(e)){f=f.sort(((e,t)=>e-t));var v=Math.floor(.9*f.length);h[p]=f[v]}return h}}),t.events.addEventListener("connection:open",t.onConnect),t.events.addEventListener("connection:close",t.onDisconnect),yield xa(t.dialQueue,t.reconnectQueue,t.connectionPruner),t.started=!0,t.log("started")}))()}stop(){var t=this;return e._asyncToGenerator((function*(){t.events.removeEventListener("connection:open",t.onConnect),t.events.removeEventListener("connection:close",t.onDisconnect),yield Ia(t.reconnectQueue,t.dialQueue,t.connectionPruner);var r=[];for(var n of t.connections.values()){var i=function*(n){r.push(e._asyncToGenerator((function*(){try{yield n.close()}catch(e){t.log.error(e)}}))())};for(var o of n)yield*i(o)}t.log("closing %d connections",r.length),yield Promise.all(r),t.connections.clear(),t.log("stopped")}))()}getMaxConnections(){return this.maxConnections}onConnect(e){this._onConnect(e).catch((e=>{this.log.error(e)}))}_onConnect(t){var r=this;return e._asyncToGenerator((function*(){var e,{detail:n}=t;if(r.started){if("open"===n.status){var i=n.remotePeer,o=!r.connections.has(i),a=null!==(e=r.connections.get(i))&&void 0!==e?e:[];a.push(n),r.connections.set(i,a),null!=i.publicKey&&"RSA"===i.type&&(yield r.peerStore.patch(i,{publicKey:i.publicKey})),o&&r.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(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{};if(!n.started)throw new va("Not started");n.outboundPendingConnections++;try{var o,a;null===(o=i.signal)||void 0===o||o.throwIfAborted();var{peerId:s}=QF(t);if(n.peerId.equals(s))throw new sa("Can not dial self");if(null!=s&&!0!==i.force){n.log("dial %p",s);var l,c=n.getConnections(s).find((e=>null==e.limits));if(null!=c)return n.log("had an existing non-limited connection to %p",s),null===(l=i.onProgress)||void 0===l||l.call(i,new Ah("dial-queue:already-connected")),c}var u=yield n.dialQueue.dial(t,e._objectSpread2(e._objectSpread2({},i),{},{priority:null!==(a=i.priority)&&void 0!==a?a:NU}));if("open"!==u.status)throw new ta("Remote closed connection during opening");var d=n.connections.get(u.remotePeer);null==d&&(d=[],n.connections.set(u.remotePeer,d));var h=!1;for(var p of d)if(p.id===u.id&&(h=!0),!0!==i.force&&p.id!==u.id&&p.remoteAddr.equals(u.remoteAddr))return u.abort(new la("Duplicate multiaddr connection")),p;return h||d.push(u),u}finally{n.outboundPendingConnections--}}))()}closeConnections(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i,o=r.length>1&&void 0!==r[1]?r[1]:{},a=null!==(i=n.connections.get(t))&&void 0!==i?i:[];yield Promise.all(a.map(function(){var t=e._asyncToGenerator((function*(e){try{yield e.close(o)}catch(t){e.abort(t)}}));return function(e){return t.apply(this,arguments)}}()))}))()}acceptIncomingConnection(t){var r=this;return e._asyncToGenerator((function*(){if(r.deny.some((e=>e.contains(t.remoteAddr.nodeAddress().address))))return r.log("connection from %a refused - connection remote address was in deny list",t.remoteAddr),!1;if(r.allow.some((e=>e.contains(t.remoteAddr.nodeAddress().address))))return r.incomingPendingConnections++,!0;if(r.incomingPendingConnections===r.maxIncomingPendingConnections)return r.log("connection from %a refused - incomingPendingConnections exceeded by host",t.remoteAddr),!1;if(t.remoteAddr.isThinWaistAddress()){var e=t.remoteAddr.nodeAddress().address;try{yield r.inboundConnectionRateLimiter.consume(e,1)}catch(n){return r.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",t.remoteAddr,e),!1}}return r.getConnections().length<r.maxConnections?(r.incomingPendingConnections++,!0):(r.log("connection from %a refused - maxConnections exceeded",t.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=>nr(e)))})))}isDialable(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};return n.dialQueue.isDialable(t,e)}))()}}class LU{constructor(t){var r,n,i,o,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"heartbeatInterval",void 0),e._defineProperty(this,"pingIntervalMs",void 0),e._defineProperty(this,"abortController",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"abortConnectionOnPingFailure",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/connection-monitor"),e._defineProperty(this,Ba,["@libp2p/connection-monitor"]),this.components=t,this.protocol="/".concat(null!==(r=a.protocolPrefix)&&void 0!==r?r:"ipfs","/").concat("ping","/").concat("1.0.0"),this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=null!==(n=a.pingInterval)&&void 0!==n?n:1e4,this.abortConnectionOnPingFailure=null===(i=a.abortConnectionOnPingFailure)||void 0===i||i,this.timeout=new VO(e._objectSpread2(e._objectSpread2({},null!==(o=a.pingTimeout)&&void 0!==o?o:{}),{},{metrics:t.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"}))}start(){var t=this;this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval((()=>{this.components.connectionManager.getConnections().forEach((r=>{Promise.resolve().then(e._asyncToGenerator((function*(){var e=Date.now();try{var n,i=t.timeout.getTimeoutSignal({signal:null===(n=t.abortController)||void 0===n?void 0:n.signal}),o=Mu(yield r.newStream(t.protocol,{signal:i,runOnLimitedConnection:!0}));e=Date.now(),yield Promise.all([o.write(pl(32),{signal:i}),o.read({bytes:32,signal:i})]),r.rtt=Date.now()-e,yield o.unwrap().close({signal:i})}catch(t){if("UnsupportedProtocolError"!==t.name)throw t;r.rtt=(Date.now()-e)/2}}))).catch((e=>{this.log.error("error during heartbeat",e),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),r.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 MU{constructor(t,r){var n,i,o,a,s,l,c,u,d,h,p;e._defineProperty(this,"routers",void 0),e._defineProperty(this,"started",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/content-routing"),this.routers=null!==(n=r.routers)&&void 0!==n?n:[],this.started=!1,this.components=t,this.findProviders=null!==(i=null===(o=t.metrics)||void 0===o?void 0:o.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:(t,r)=>{var[n]=t;return e._objectSpread2(e._objectSpread2({},r),{},{cid:n.toString()})},getAttributesFromYieldedValue:(t,r)=>e._objectSpread2(e._objectSpread2({},r),{},{providers:[...Array.isArray(r.providers)?r.providers:[],t.id.toString()]})}))&&void 0!==i?i:this.findProviders,this.provide=null!==(a=null===(s=t.metrics)||void 0===s?void 0:s.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:(t,r)=>{var[n]=t;return e._objectSpread2(e._objectSpread2({},r),{},{cid:n.toString()})}}))&&void 0!==a?a:this.provide,this.cancelReprovide=null!==(l=null===(c=t.metrics)||void 0===c?void 0:c.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:(t,r)=>{var[n]=t;return e._objectSpread2(e._objectSpread2({},r),{},{cid:n.toString()})}}))&&void 0!==l?l:this.cancelReprovide,this.put=null!==(u=null===(d=t.metrics)||void 0===d?void 0:d.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:e=>{var[t]=e;return{key:Ze(t,"base36")}}}))&&void 0!==u?u:this.put,this.get=null!==(h=null===(p=t.metrics)||void 0===p?void 0:p.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:e=>{var[t]=e;return{key:Ze(t,"base36")}}}))&&void 0!==h?h:this.get}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){t.started=!0}))()}stop(){var t=this;return e._asyncToGenerator((function*(){t.started=!1}))()}findProviders(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(0===r.routers.length)throw new xF("No content routers available");var i,o=r,a=new oh,s=!1,l=!1;try{for(var c,u=e._asyncIterator(nu(...o.routers.filter((e=>e.findProviders instanceof Function)).map((e=>e.findProviders(t,n)))));s=!(c=yield e._awaitAsyncGenerator(u.next())).done;s=!1){var d=c.value;null!=d&&(d.multiaddrs.length>0&&(yield e._awaitAsyncGenerator(r.components.peerStore.merge(d.id,{multiaddrs:d.multiaddrs}))),a.has(d.id)||(a.add(d.id),yield d))}}catch(e){l=!0,i=e}finally{try{s&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(l)throw i}}}()})).apply(this,arguments)}provide(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{};if(0===n.routers.length)throw new xF("No content routers available");yield Promise.all(n.routers.filter((e=>e.provide instanceof Function)).map(function(){var r=e._asyncToGenerator((function*(e){yield e.provide(t,i)}));return function(e){return r.apply(this,arguments)}}()))}))()}cancelReprovide(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{};if(0===n.routers.length)throw new xF("No content routers available");yield Promise.all(n.routers.filter((e=>e.cancelReprovide instanceof Function)).map(function(){var r=e._asyncToGenerator((function*(e){yield e.cancelReprovide(t,i)}));return function(e){return r.apply(this,arguments)}}()))}))()}put(t,r,n){var i=this;return e._asyncToGenerator((function*(){if(!i.isStarted())throw new va;yield Promise.all(i.routers.filter((e=>e.put instanceof Function)).map(function(){var i=e._asyncToGenerator((function*(e){yield e.put(t,r,n)}));return function(e){return i.apply(this,arguments)}}()))}))()}get(t,r){var n=this;return e._asyncToGenerator((function*(){if(!n.isStarted())throw new va;return Promise.any(n.routers.filter((e=>e.get instanceof Function)).map(function(){var n=e._asyncToGenerator((function*(e){return e.get(t,r)}));return function(e){return n.apply(this,arguments)}}()))}))()}}class jU{constructor(t){var r,n,i,o,a,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"log",void 0),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"routers",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/peer-routing"),this.log=t.logger.forComponent("libp2p:peer-routing"),this.peerId=t.peerId,this.peerStore=t.peerStore,this.routers=null!==(r=s.routers)&&void 0!==r?r:[],this.findPeer=null!==(n=null===(i=t.metrics)||void 0===i?void 0:i.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:(t,r)=>{var[n]=t;return e._objectSpread2(e._objectSpread2({},r),{},{peer:n.toString()})}}))&&void 0!==n?n:this.findPeer,this.getClosestPeers=null!==(o=null===(a=t.metrics)||void 0===a?void 0:a.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:(t,r)=>{var[n]=t;return e._objectSpread2(e._objectSpread2({},r),{},{key:Ze(n,"base36")})},getAttributesFromYieldedValue:(t,r)=>e._objectSpread2(e._objectSpread2({},r),{},{peers:[...Array.isArray(r.peers)?r.peers:[],t.id.toString()]})}))&&void 0!==o?o:this.getClosestPeers}findPeer(t,r){var n=this;return e._asyncToGenerator((function*(){if(0===n.routers.length)throw new TF("No peer routers available");if(t.toString()===n.peerId.toString())throw new IF("Should not try to find self");var i,o=n,a=nu(...n.routers.filter((e=>e.findPeer instanceof Function)).map((n=>e._wrapAsyncGenerator((function*(){try{yield yield e._awaitAsyncGenerator(n.findPeer(t,r))}catch(e){o.log.error(e)}}))()))),s=!1,l=!1;try{for(var c,u=e._asyncIterator(a);s=!(c=yield u.next()).done;s=!1){var d=c.value;if(null!=d)return d.multiaddrs.length>0&&(yield n.peerStore.merge(d.id,{multiaddrs:d.multiaddrs})),d}}catch(e){l=!0,i=e}finally{try{s&&null!=u.return&&(yield u.return())}finally{if(l)throw i}}throw new aa}))()}getClosestPeers(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(0===r.routers.length)throw new TF("No peer routers available");var i,o=r,a=gh(1024),s=!1,l=!1;try{for(var c,u=e._asyncIterator(MR(e._wrapAsyncGenerator((function*(){var r,i=nu(...o.routers.filter((e=>e.getClosestPeers instanceof Function)).map((e=>e.getClosestPeers(t,n)))),a=!1,s=!1;try{for(var l,c=function*(){var t=l.value;yield e._asyncToGenerator((function*(){if(0===t.multiaddrs.length)try{t=yield o.findPeer(t.id,e._objectSpread2(e._objectSpread2({},n),{},{useCache:!1}))}catch(e){return void o.log.error("could not find peer multiaddrs",e)}return t}))},u=e._asyncIterator(i);a=!(l=yield e._awaitAsyncGenerator(u.next())).done;a=!1)yield*c()}catch(e){s=!0,r=e}finally{try{a&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(s)throw r}}}))()));s=!(c=yield e._awaitAsyncGenerator(u.next())).done;s=!1){var d=c.value;null!=d&&(d.multiaddrs.length>0&&(yield e._awaitAsyncGenerator(r.peerStore.merge(d.id,{multiaddrs:d.multiaddrs}))),a.has(d.id.toMultihash().bytes)||(a.add(d.id.toMultihash().bytes),yield d))}}catch(e){l=!0,i=e}finally{try{s&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(l)throw i}}}()})).apply(this,arguments)}}class FU extends Aa{constructor(t){super(),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"walking",void 0),e._defineProperty(this,"walkers",void 0),e._defineProperty(this,"shutdownController",void 0),e._defineProperty(this,"walkController",void 0),e._defineProperty(this,"needNext",void 0),e._defineProperty(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(t){var r=this;return e._wrapAsyncGenerator((function*(){r.walking||r.startWalk(),r.walkers++;var n=Qd([r.shutdownController.signal,null==t?void 0:t.signal]);try{for(;;){var i;null===(i=r.needNext)||void 0===i||i.resolve(),r.needNext=Hc();var o=yield e._awaitAsyncGenerator(xh(r,"walk:peer",n,{errorEvent:"walk:error"}));yield o.detail}}finally{var a;if(n.clear(),r.walkers--,0===r.walkers)null===(a=r.walkController)||void 0===a||a.abort(),r.walkController=void 0}}))()}startWalk(){var t=this;this.walking=!0,this.walkController=new AbortController,this.walkController.signal;var r=Qd([this.walkController.signal,this.shutdownController.signal]),n=Date.now(),i=0;Promise.resolve().then(e._asyncToGenerator((function*(){for(t.log("start walk");t.walkers>0;)try{var n,o=pl(32),a=Date.now(),s=!1,l=!1;try{for(var c,u=e._asyncIterator(t.peerRouting.getClosestPeers(o,{signal:r}));s=!(c=yield u.next()).done;s=!1){var d=c.value;r.aborted&&t.log("aborting walk"),r.throwIfAborted(),t.log("found peer %p after %dms for %d walkers",d.id,Date.now()-a,t.walkers),i++,t.safeDispatchEvent("walk:peer",{detail:d}),1===t.walkers&&null!=t.needNext&&(t.log("wait for need next"),yield Zc(t.needNext.promise,r)),a=Date.now()}}catch(e){l=!0,n=e}finally{try{s&&null!=u.return&&(yield u.return())}finally{if(l)throw n}}t.log("walk iteration for %b and %d walkers finished, found %d peers",o,t.walkers,i)}catch(e){t.log.error("random walk errored",e),t.safeDispatchEvent("walk:error",{detail:e})}t.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 UU{constructor(t){e._defineProperty(this,"log",void 0),e._defineProperty(this,"topologies",void 0),e._defineProperty(this,"handlers",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(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 CF("No handler registered for protocol ".concat(e));return t}getTopologies(e){var t=this.topologies.get(e);return null==t?[]:[...t.values()]}handle(t,r,n){var i=this;return e._asyncToGenerator((function*(){if(i.handlers.has(t)&&!0!==(null==n?void 0:n.force))throw new BF("Handler already registered for protocol ".concat(t));var e=$L.bind({ignoreUndefined:!0})({maxInboundStreams:32,maxOutboundStreams:64},n);i.handlers.set(t,{handler:r,options:e}),yield i.components.peerStore.merge(i.components.peerId,{protocols:[t]})}))()}unhandle(t){var r=this;return e._asyncToGenerator((function*(){(Array.isArray(t)?t:[t]).forEach((e=>{r.handlers.delete(e)})),yield r.components.peerStore.patch(r.components.peerId,{protocols:r.getProtocols()})}))()}register(t,r){var n=this;return e._asyncToGenerator((function*(){if(null==r)throw new Jo("invalid topology");var e="".concat((1e9*Math.random()).toString(36)).concat(Date.now()),i=n.topologies.get(t);return null==i&&(i=new Map,n.topologies.set(t,i)),i.set(e,r),e}))()}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,c,u;!1!==(null===(l=s.filter)||void 0===l?void 0:l.has(r.id))&&(null===(c=s.filter)||void 0===c||c.remove(r.id),null===(u=s.onDisconnect)||void 0===u||u.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,c;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===(c=a.onConnect)||void 0===c||c.call(a,n,r))}}}}class zU{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"log",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"transports",void 0),e._defineProperty(this,"listeners",void 0),e._defineProperty(this,"faultTolerance",void 0),e._defineProperty(this,"started",void 0),e._defineProperty(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=vN({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=null!==(r=n.faultTolerance)&&void 0!==r?r:Vo.FATAL_ALL}add(e){var t=e[Symbol.toStringTag];if(null==t)throw new Jo("Transport must have a valid tag");if(this.transports.has(t))throw new Jo("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 t=this;return e._asyncToGenerator((function*(){var e=t.components.addressManager.getListenAddrs();yield t.listen(e)}))()}stop(){var t=this;return e._asyncToGenerator((function*(){var e=[];for(var[r,n]of t.listeners)for(t.log("closing listeners for %s",r);n.length>0;){var i=n.pop();null!=i&&e.push(i.close())}for(var o of(yield Promise.all(e),t.log("all listeners closed"),t.listeners.keys()))t.listeners.set(o,[]);t.started=!1}))()}dial(t,r){var n=this;return e._asyncToGenerator((function*(){var i,o=n.dialTransportForMultiaddr(t);if(null==o)throw new FF("No transport available for address ".concat(String(t)));return null==r||null===(i=r.onProgress)||void 0===i||i.call(r,new Ah("transport-manager:selected-transport",o[Symbol.toStringTag])),o.dial(t,e._objectSpread2(e._objectSpread2({},r),{},{upgrader:n.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(t){var r=this;return e._asyncToGenerator((function*(){if(!r.isStarted())throw new va("Not started");if(null!=t&&0!==t.length){var e={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};t.forEach((t=>{e.errors.set(t.toString(),new DF)}));var n=[],i=function*(i){var o=a.listenFilter(t),s=function*(t){var o;r.log("creating listener for %s on %a",i,t);var s=a.createListener({upgrader:r.components.upgrader}),l=null!==(o=r.listeners.get(i))&&void 0!==o?o:[];null==l&&(l=[],r.listeners.set(i,l)),l.push(s),s.addEventListener("listening",(()=>{r.components.events.safeDispatchEvent("transport:listening",{detail:s})})),s.addEventListener("close",(()=>{var e=l.findIndex((e=>e===s));l.splice(e,1),r.components.events.safeDispatchEvent("transport:close",{detail:s})})),Pd.matches(t)?e.ipv4.attempts++:Ed.matches(t)&&e.ipv6.attempts++,n.push(s.listen(t).then((()=>{e.errors.delete(t.toString()),Pd.matches(t)&&e.ipv4.success++,Ed.matches(t)&&e.ipv6.success++}),(n=>{throw r.log.error("transport %s could not listen on address %a - %e",i,t,n),e.errors.set(t.toString(),n),n})))};for(var l of o)yield*s(l)};for(var[o,a]of r.transports.entries())yield*i(o);var s=yield Promise.allSettled(n);if(!(s.length>0&&s.every((e=>"fulfilled"===e.status))))if(r.ipv6Unsupported(e))r.log("all IPv4 addresses succeed but all IPv6 failed");else{if(r.faultTolerance!==Vo.NO_FATAL)throw new GF("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([...e.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("")));r.log("failed to listen on any address but fault tolerance allows this")}}else r.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(t){var r=this;return e._asyncToGenerator((function*(){var e,n=null!==(e=r.listeners.get(t))&&void 0!==e?e:[];r.log.trace("removing transport %s",t);var i=[];for(r.log.trace("closing listeners for %s",t);n.length>0;){var o=n.pop();null!=o&&i.push(o.close())}yield Promise.all(i),r.transports.delete(t),r.listeners.delete(t)}))()}removeAll(){var t=this;return e._asyncToGenerator((function*(){var e=[];for(var r of t.transports.keys())e.push(t.remove(r));yield Promise.all(e)}))()}}var VU="/multistream/1.0.0",qU=1024,HU=nt("\n");function KU(e,t,r){return WU.apply(this,arguments)}function WU(){return WU=e._asyncToGenerator((function*(e,t,r){yield e.write(t,r)})),WU.apply(this,arguments)}function QU(){return QU=e._asyncToGenerator((function*(e,t,r){yield e.writeV(t,r)})),QU.apply(this,arguments)}function YU(){return YU=e._asyncToGenerator((function*(e,t){var r=yield e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==HU[0])throw t.log.error("Invalid mss message - missing newline",r),new ha("Missing newline");return r.sublist(0,-1)})),YU.apply(this,arguments)}function JU(e,t){return ZU.apply(this,arguments)}function ZU(){return ZU=e._asyncToGenerator((function*(e,t){var r=yield function(e,t){return YU.apply(this,arguments)}(e,t);return Ze(r.subarray())})),ZU.apply(this,arguments)}function $U(e,t,r){return XU.apply(this,arguments)}function XU(){return XU=e._asyncToGenerator((function*(t,r,n){if(1===(r=Array.isArray(r)?[...r]:[r]).length&&!1===n.negotiateFully)return function(t,r,n){var i=t.sink.bind(t),o=t.source,a=!1,s=!1,l=Hc(),c=!1,u=!1,d=Hc(),h=!1,p=!1,f=Hc(),v=zu({sink:i,source:o},e._objectSpread2(e._objectSpread2({},n),{},{maxDataLength:qU}));function y(){return g.apply(this,arguments)}function g(){return(g=e._asyncToGenerator((function*(){if(s)return n.log.trace("optimistic: already negotiating %s stream",r),void(yield l.promise);s=!0;try{c||(n.log.trace("optimistic: doing send protocol for %s stream",r),yield m()),h||(n.log.trace("optimistic: doing read protocol for %s stream",r),yield b())}finally{s=!1,a=!0,l.resolve()}}))).apply(this,arguments)}function m(){return w.apply(this,arguments)}function w(){return(w=e._asyncToGenerator((function*(){if(u)yield d.promise;else{u=!0;try{n.log.trace('optimistic: write ["%s", "%s", data] in source',VU,r),yield v.writeV([nt("".concat(VU,"\n")),nt("".concat(r,"\n"))]),n.log.trace('optimistic: wrote ["%s", "%s", data] in source',VU,r)}finally{c=!0,u=!1,d.resolve()}}}))).apply(this,arguments)}function b(){return _.apply(this,arguments)}function _(){return _=e._asyncToGenerator((function*(){if(p)yield f.promise;else{p=!0;try{n.log.trace("optimistic: reading multistream select header");var e=yield JU(v,n);if(n.log.trace('optimistic: read multistream select header "%s"',e),e===VU&&(e=yield JU(v,n)),n.log.trace('optimistic: read protocol "%s", expecting "%s"',e,r),e!==r)throw new da("protocol selection failed")}finally{h=!0,p=!1,f.resolve()}}})),_.apply(this,arguments)}if(t.sink=function(){var t=e._asyncToGenerator((function*(t){var{sink:i}=v.unwrap();yield i(e._wrapAsyncGenerator((function*(){var i,o=!1,a=!1,s=!1;try{for(var l,h=e._asyncIterator(t);a=!(l=yield e._awaitAsyncGenerator(h.next())).done;a=!1){var p=l.value;if(u&&(yield e._awaitAsyncGenerator(d.promise)),c)yield p;else{u=!0,n.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',VU,r,p.byteLength);var f="".concat(r,"\n");yield new Oa(Uint8Array.from([19]),nt("".concat(VU,"\n")),yt(f.length),nt(f),p).subarray(),n.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',VU,r,p.byteLength),c=!0,u=!1,d.resolve(),y().catch((e=>{n.log.error("could not finish optimistic protocol negotiation of %s",r,e)}))}o=!0}}catch(e){s=!0,i=e}finally{try{a&&null!=h.return&&(yield e._awaitAsyncGenerator(h.return()))}finally{if(s)throw i}}o||(yield e._awaitAsyncGenerator(y()))}))())}));return function(e){return t.apply(this,arguments)}}(),t.source=e._wrapAsyncGenerator((function*(){yield e._awaitAsyncGenerator(y()),n.log.trace('optimistic: reading data from "%s" stream',r),yield*e._asyncGeneratorDelegate(e._asyncIterator(v.unwrap().source))}))(),null!=t.closeRead){var S=t.closeRead.bind(t);t.closeRead=function(){var t=e._asyncToGenerator((function*(e){a||(yield y().catch((e=>{n.log.error("could not negotiate protocol before close read",e)}))),yield S(e)}));return function(e){return t.apply(this,arguments)}}()}if(null!=t.closeWrite){var P=t.closeWrite.bind(t);t.closeWrite=function(){var t=e._asyncToGenerator((function*(e){a||(yield y().catch((e=>{n.log.error("could not negotiate protocol before close write",e)}))),yield P(e)}));return function(e){return t.apply(this,arguments)}}()}if(null!=t.close){var E=t.close.bind(t);t.close=function(){var t=e._asyncToGenerator((function*(e){var t=[];u&&t.push(d.promise),p&&t.push(f.promise),t.length>0?yield Zc(Promise.all(t),null==e?void 0:e.signal):(a=!0,s=!1,l.resolve()),yield E(e)}));return function(e){return t.apply(this,arguments)}}()}return{stream:t,protocol:r}}(t,r[0],n);var i=zu(t,e._objectSpread2(e._objectSpread2({},n),{},{maxDataLength:qU})),o=r.shift();if(null==o)throw new Error("At least one protocol must be specified");n.log.trace('select: write ["%s", "%s"]',VU,o);var a=nt("".concat(VU,"\n")),s=nt("".concat(o,"\n"));yield function(e,t,r){return QU.apply(this,arguments)}(i,[a,s],n),n.log.trace("select: reading multistream-select header");var l=yield JU(i,n);if(n.log.trace('select: read "%s"',l),l===VU&&(n.log.trace("select: reading protocol response"),l=yield JU(i,n),n.log.trace('select: read "%s"',l)),l===o)return{stream:i.unwrap(),protocol:o};for(var c of r){n.log.trace('select: write "%s"',c),yield KU(i,nt("".concat(c,"\n")),n),n.log.trace("select: reading protocol response");var u=yield JU(i,n);if(n.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:i.unwrap(),protocol:c}}throw new da("protocol selection failed")})),XU.apply(this,arguments)}function ez(e,t,r){return tz.apply(this,arguments)}function tz(){return tz=e._asyncToGenerator((function*(t,r,n){r=Array.isArray(r)?r:[r],n.log.trace("handle: available protocols %s",r);for(var i=zu(t,e._objectSpread2(e._objectSpread2({},n),{},{maxDataLength:qU,maxLengthLength:2}));;){n.log.trace("handle: reading incoming string");var o=yield JU(i,n);if(n.log.trace('handle: read "%s"',o),o!==VU){if(r.includes(o))return n.log.trace('handle: respond with "%s" for "%s"',o,o),yield KU(i,nt("".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 KU(i,nt("na\n"),n),n.log('handle: responded with "na" for "%s"',o);else{var a=new Oa(...r.map((e=>jp.single(nt("".concat(e,"\n"))))),nt("\n"));n.log.trace('handle: respond with "%s" for %s',r,o),yield KU(i,a,n),n.log.trace('handle: responded with "%s" for %s',r,o)}}else n.log.trace('handle: respond with "%s" for "%s"',VU,o),yield KU(i,nt("".concat(VU,"\n")),n),n.log.trace('handle: responded with "%s" for "%s"',VU,o)}})),tz.apply(this,arguments)}class rz{constructor(t){e._defineProperty(this,"id",void 0),e._defineProperty(this,"remoteAddr",void 0),e._defineProperty(this,"remotePeer",void 0),e._defineProperty(this,"direction",void 0),e._defineProperty(this,"timeline",void 0),e._defineProperty(this,"multiplexer",void 0),e._defineProperty(this,"encryption",void 0),e._defineProperty(this,"status",void 0),e._defineProperty(this,"limits",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"tags",void 0),e._defineProperty(this,"_newStream",void 0),e._defineProperty(this,"_close",void 0),e._defineProperty(this,"_abort",void 0),e._defineProperty(this,"_getStreams",void 0),e._defineProperty(this,Symbol.toStringTag,"Connection"),e._defineProperty(this,Mo,!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(t,r){var n=this;return e._asyncToGenerator((function*(){if("closing"===n.status)throw new ea("the connection is being closed");if("closed"===n.status)throw new ta("the connection is closed");if(Array.isArray(t)||(t=[t]),null!=n.limits&&!0!==(null==r?void 0:r.runOnLimitedConnection))throw new wa("Cannot open protocol stream on limited connection");var e=yield n._newStream(t,r);return e.direction="outbound",e}))()}close(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var n=t.length>0&&void 0!==t[0]?t[0]:{};if("closed"!==r.status&&"closing"!==r.status){if(r.log("closing connection to %a",r.remoteAddr),r.status="closing",null==n.signal){var i=AbortSignal.timeout(500);n=e._objectSpread2(e._objectSpread2({},n),{},{signal:i})}try{r.log.trace("closing underlying transport"),yield r._close(n),r.log.trace("updating timeline with close time"),r.status="closed",r.timeline.close=Date.now()}catch(e){r.log.error("error encountered during graceful close of connection to %a",r.remoteAddr,e),r.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 nz(e,t,r){var n=0;return r.streams.forEach((r=>{r.direction===t&&r.protocol===e&&n++})),n}class iz{constructor(t,r){var n,i,o,a,s;e._defineProperty(this,"components",void 0),e._defineProperty(this,"connectionEncrypters",void 0),e._defineProperty(this,"streamMuxers",void 0),e._defineProperty(this,"inboundUpgradeTimeout",void 0),e._defineProperty(this,"inboundStreamProtocolNegotiationTimeout",void 0),e._defineProperty(this,"outboundStreamProtocolNegotiationTimeout",void 0),e._defineProperty(this,"events",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(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(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=n.components.connectionGater[t];if(null!=e){for(var i=r.length,o=new Array(i>1?i-1:0),a=1;a<i;a++)o[a-1]=r[a];if(!0===(yield e.apply(n.components.connectionGater,o)))throw new OF("The multiaddr connection is blocked by gater.".concat(t))}}))()}createInboundAbortSignal(e){return Qd([AbortSignal.timeout(this.inboundUpgradeTimeout),e])}upgradeInbound(t,r){var n=this;return e._asyncToGenerator((function*(){var i=!1,o=n.createInboundAbortSignal(r.signal);try{var a;if(null===(a=n.metrics.dials)||void 0===a||a.increment({inbound:!0}),!(i=yield n.components.connectionManager.acceptIncomingConnection(t)))throw new LF("Connection denied");yield n.shouldBlockConnection("denyInboundConnection",t),yield n._performUpgrade(t,"inbound",e._objectSpread2(e._objectSpread2({},r),{},{signal:o}))}catch(e){var s;throw null===(s=n.metrics.errors)||void 0===s||s.increment({inbound:!0}),e}finally{o.clear(),i&&n.components.connectionManager.afterUpgradeInbound()}}))()}upgradeOutbound(t,r){var n=this;return e._asyncToGenerator((function*(){try{var e;null===(e=n.metrics.dials)||void 0===e||e.increment({outbound:!0});var i,o=t.remoteAddr.getPeerId();null!=o&&(i=$l(o),yield n.shouldBlockConnection("denyOutboundConnection",i,t));var a="outbound";return!1===r.initiator&&(a="inbound"),yield n._performUpgrade(t,a,r)}catch(e){var s;throw null===(s=n.metrics.errors)||void 0===s||s.increment({outbound:!0}),e}}))()}_performUpgrade(t,r,n){var i=this;return e._asyncToGenerator((function*(){var o,a,s,l,c,u;null===(o=i.components.metrics)||void 0===o||o.trackMultiaddrConnection(t),t.log.trace("starting the %s connection upgrade",r);var d=t;if(!0!==(null==n?void 0:n.skipProtection)){var h=i.components.connectionProtector;null!=h&&(t.log("protecting the %s connection",r),d=yield h.protect(t,n))}try{if(a=d,!0!==(null==n?void 0:n.skipEncryption)){var p;null==n||null===(p=n.onProgress)||void 0===p||p.call(n,new Ah("upgrader:encrypt-".concat(r,"-connection"))),({conn:a,remotePeer:s,protocol:u,streamMuxer:c}=yield"inbound"===r?i._encryptInbound(d,n):i._encryptOutbound(d,n));var f=e._objectSpread2(e._objectSpread2({},d),a);yield i.shouldBlockConnection("inbound"===r?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,f)}else{var v=t.remoteAddr.getPeerId();if(null==v)throw new la("".concat(r," connection that skipped encryption must have a peer id"));var y=$l(v);u="native",s=y}if(s.equals(i.components.peerId)){var g=new sa("Can not dial self");throw t.abort(g),g}if(l=a,null!=(null==n?void 0:n.muxerFactory))c=n.muxerFactory;else if(null==c&&i.streamMuxers.size>0){var m;null==n||null===(m=n.onProgress)||void 0===m||m.call(n,new Ah("upgrader:multiplex-".concat(r,"-connection")));var w=yield"inbound"===r?i._multiplexInbound(e._objectSpread2(e._objectSpread2({},d),a),i.streamMuxers,n):i._multiplexOutbound(e._objectSpread2(e._objectSpread2({},d),a),i.streamMuxers,n);c=w.muxerFactory,l=w.stream}}catch(g){throw t.log.error("failed to upgrade inbound connection %s %a - %e","inbound"===r?"from":"to",t.remoteAddr,g),g}return yield i.shouldBlockConnection("inbound"===r?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,t),t.log("successfully upgraded %s connection",r),i._createConnection({cryptoProtocol:u,direction:r,maConn:t,upgradedConn:l,muxerFactory:c,remotePeer:s,limits:null==n?void 0:n.limits})}))()}_createConnection(t){var r,n,i,o,a=this,{cryptoProtocol:s,direction:l,maConn:c,upgradedConn:u,remotePeer:d,muxerFactory:h,limits:p}=t;null!=h&&(n=h.createStreamMuxer({direction:l,onIncomingStream:t=>{null!=o&&Promise.resolve().then(e._asyncToGenerator((function*(){var e,r=a.components.registrar.getProtocols(),n=AbortSignal.timeout(a.inboundStreamProtocolNegotiationTimeout),{stream:i,protocol:s}=yield ez(t,r,{signal:n,log:t.log,yieldBytes:!1});if(null!=o){o.log("incoming stream opened on %s",s);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}(s,a.components.registrar);if(nz(s,"inbound",o)===l){var c=new ba('Too many inbound protocol streams for protocol "'.concat(s,'" - limit ').concat(l));throw t.abort(c),c}t.source=i.source,t.sink=i.sink,t.protocol=s,null!=i.closeWrite&&(t.closeWrite=i.closeWrite),null!=i.closeRead&&(t.closeRead=i.closeRead),null!=i.close&&(t.close=i.close),yield a.components.peerStore.merge(d,{protocols:[s]}),null===(e=a.components.metrics)||void 0===e||e.trackProtocolStream(t,o),a._onStream({connection:o,stream:t,protocol:s})}}))).catch(function(){var r=e._asyncToGenerator((function*(e){o.log.error("error handling incoming stream id %s - %e",t.id,e),null==t.timeline.close&&(yield t.close())}));return function(e){return r.apply(this,arguments)}}())}}),i=function(){var r=e._asyncToGenerator((function*(r){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null==n)throw new MF("Connection is not multiplexed");o.log.trace("starting new stream for protocols %s",r);var s=yield n.newStream();o.log.trace("started new stream %s for protocols %s",s.id,r);try{var c;if(null==i.signal){s.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",r);var u=AbortSignal.timeout(a.outboundStreamProtocolNegotiationTimeout);i=e._objectSpread2(e._objectSpread2({},i),{},{signal:u})}s.log.trace("selecting protocol from protocols %s",r);var{stream:h,protocol:p}=yield $U(s,r,e._objectSpread2(e._objectSpread2({},i),{},{log:s.log,yieldBytes:!0}));s.log.trace("selected protocol %s",p);var f=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}(p,a.components.registrar,i),v=nz(p,"outbound",o);if(v>=f){var y=new _a('Too many outbound protocol streams for protocol "'.concat(p,'" - ').concat(v,"/").concat(f));throw s.abort(y),y}return yield a.components.peerStore.merge(d,{protocols:[p]}),s.source=h.source,s.sink=h.sink,s.protocol=p,null!=h.closeWrite&&(s.closeWrite=h.closeWrite),null!=h.closeRead&&(s.closeRead=h.closeRead),null!=h.close&&(s.close=h.close),null===(c=a.components.metrics)||void 0===c||c.trackProtocolStream(s,o),s}catch(y){throw o.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e","inbound"===l?"from":"to",t.maConn.remoteAddr,r,y),null==s.timeline.close&&s.abort(y),y}}));return function(e){return r.apply(this,arguments)}}(),Promise.all([n.sink(u.source),u.sink(n.source)]).catch((e=>{o.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&&e._asyncToGenerator((function*(){try{"open"===o.status&&(yield o.close())}catch(e){o.log.error("error closing connection after timeline close %e",e)}finally{a.events.safeDispatchEvent("connection:close",{detail:o})}}))().catch((e=>{o.log.error("error thrown while dispatching connection:close event %e",e)})),Reflect.set(...arguments)}}),c.timeline.upgraded=Date.now();var v,y;return v={remoteAddr:c.remoteAddr,remotePeer:d,status:"open",direction:l,timeline:c.timeline,multiplexer:null===(r=n)||void 0===r?void 0:r.protocol,encryption:s,limits:p,logger:this.components.logger,newStream:null!=i?i:()=>{throw new MF("Connection is not multiplexed")},getStreams:()=>{var e,t;return null!==(e=null===(t=n)||void 0===t?void 0:t.streams)&&void 0!==e?e:[]},close:(y=e._asyncToGenerator((function*(e){var t;yield null===(t=n)||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=n)||void 0===t||t.abort(e)}},o=new rz(v),this.events.safeDispatchEvent("connection:open",{detail:o}),o.__maConnTimeline=f,o}_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 wa("Cannot open protocol stream on limited connection");i({connection:t,stream:r})}_encryptInbound(t,r){var n=this;return e._asyncToGenerator((function*(){var i=Array.from(n.connectionEncrypters.keys());try{var{stream:o,protocol:a}=yield ez(t,i,e._objectSpread2(e._objectSpread2({},r),{},{log:t.log})),s=n.connectionEncrypters.get(a);if(null==s)throw new jF("no crypto module found for ".concat(a));return t.log("encrypting inbound connection to %a using %s",t.remoteAddr,a),e._objectSpread2(e._objectSpread2({},yield s.secureInbound(o,r)),{},{protocol:a})}catch(e){throw t.log.error("encrypting inbound connection from %a failed",t.remoteAddr,e),new jF(e.message)}}))()}_encryptOutbound(t,r){var n=this;return e._asyncToGenerator((function*(){var i=Array.from(n.connectionEncrypters.keys());try{t.log.trace("selecting encrypter from %s",i);var{stream:o,protocol:a}=yield $U(t,i,e._objectSpread2(e._objectSpread2({},r),{},{log:t.log,yieldBytes:!0})),s=n.connectionEncrypters.get(a);if(null==s)throw new jF("no crypto module found for ".concat(a));return t.log("encrypting outbound connection to %a using %s",t.remoteAddr,a),e._objectSpread2(e._objectSpread2({},yield s.secureOutbound(o,r)),{},{protocol:a})}catch(e){throw t.log.error("encrypting outbound connection to %a failed",t.remoteAddr,e),new jF(e.message)}}))()}_multiplexOutbound(t,r,n){return e._asyncToGenerator((function*(){var i=Array.from(r.keys());t.log("outbound selecting muxer %s",i);try{t.log.trace("selecting stream muxer from %s",i);var{stream:o,protocol:a}=yield $U(t,i,e._objectSpread2(e._objectSpread2({},n),{},{log:t.log,yieldBytes:!0}));return t.log("selected %s as muxer protocol",a),{stream:o,muxerFactory:r.get(a)}}catch(e){throw t.log.error("error multiplexing outbound connection",e),new MF(String(e))}}))()}_multiplexInbound(t,r,n){return e._asyncToGenerator((function*(){var i=Array.from(r.keys());t.log("inbound handling muxers %s",i);try{var{stream:o,protocol:a}=yield ez(t,i,e._objectSpread2(e._objectSpread2({},n),{},{log:t.log}));return{stream:o,muxerFactory:r.get(a)}}catch(e){throw t.log.error("error multiplexing inbound connection",e),new MF(String(e))}}))()}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}}var oz=new WeakSet;class az extends Aa{constructor(t){var r,n,i,o,a,s,l,c,u,d,h,p,f,v,y,g,m,w,b,_,S,P;super(),e._classPrivateMethodInitSpec(this,oz),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"contentRouting",void 0),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"services",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"status",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"log",void 0),this.status="stopped";var E=new Aa,A=E.dispatchEvent.bind(E);E.dispatchEvent=e=>{var t=A(e),r=this.dispatchEvent(new CustomEvent(e.type,{detail:e.detail}));return t||r},this.peerId=t.peerId,this.logger=null!==(r=t.logger)&&void 0!==r?r:Au(),this.log=this.logger.forComponent("libp2p"),this.services={};var k=null!==(n=null===(i=t.nodeInfo)||void 0===i?void 0:i.name)&&void 0!==n?n:bj,x=null!==(o=null===(a=t.nodeInfo)||void 0===a?void 0:a.version)&&void 0!==o?o:wj,T=this.components=function(){var e=new UF(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{});return new Proxy(e,{get(t,r,n){if("string"==typeof r&&!VF.includes(r)){var i=e.components[r];if(null==i&&!zF.includes(r))throw new AF("".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:t.peerId,privateKey:t.privateKey,nodeInfo:{name:k,version:x,userAgent:null!==(s=null===(l=t.nodeInfo)||void 0===l?void 0:l.userAgent)&&void 0!==s?s:_j(k,x)},logger:this.logger,events:E,datastore:null!==(c=t.datastore)&&void 0!==c?c:new Vc,connectionGater:WF(t.connectionGater),dns:t.dns});this.peerStore=this.configureComponent("peerStore",function(e){return new cF(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}(T,e._objectSpread2({addressFilter:this.components.connectionGater.filterMultiaddrForPeer},t.peerStore))),null!=t.metrics&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),T.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))};T.events.safeDispatchEvent("peer:discovery",{detail:t})}})),null!=t.connectionProtector&&this.configureComponent("connectionProtector",t.connectionProtector(T)),this.components.upgrader=new iz(this.components,{connectionEncrypters:(null!==(u=t.connectionEncrypters)&&void 0!==u?u:[]).map(((e,t)=>this.configureComponent("connection-encryption-".concat(t),e(this.components)))),streamMuxers:(null!==(d=t.streamMuxers)&&void 0!==d?d:[]).map(((e,t)=>this.configureComponent("stream-muxers-".concat(t),e(this.components)))),inboundUpgradeTimeout:null===(h=t.connectionManager)||void 0===h?void 0:h.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:null!==(p=null===(f=t.connectionManager)||void 0===f?void 0:f.inboundStreamProtocolNegotiationTimeout)&&void 0!==p?p:null===(v=t.connectionManager)||void 0===v?void 0:v.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:null!==(y=null===(g=t.connectionManager)||void 0===g?void 0:g.outboundStreamProtocolNegotiationTimeout)&&void 0!==y?y:null===(m=t.connectionManager)||void 0===m?void 0:m.protocolNegotiationTimeout}),this.configureComponent("transportManager",new zU(this.components,t.transportManager)),this.configureComponent("connectionManager",new OU(this.components,t.connectionManager)),!1!==(null===(w=t.connectionMonitor)||void 0===w?void 0:w.enabled)&&this.configureComponent("connectionMonitor",new LU(this.components,t.connectionMonitor)),this.configureComponent("registrar",new UU(this.components)),this.configureComponent("addressManager",new EF(this.components,t.addresses));var I=(null!==(b=t.peerRouters)&&void 0!==b?b:[]).map(((e,t)=>this.configureComponent("peer-router-".concat(t),e(this.components))));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new jU(this.components,{routers:I}));var C=(null!==(_=t.contentRouters)&&void 0!==_?_:[]).map(((e,t)=>this.configureComponent("content-router-".concat(t),e(this.components))));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new MU(this.components,{routers:C})),this.configureComponent("randomWalk",new FU(this.components)),(null!==(S=t.peerDiscovery)&&void 0!==S?S:[]).forEach(((t,r)=>{this.configureComponent("peer-discovery-".concat(r),t(this.components)).addEventListener("peer",(t=>{e._assertClassBrand(oz,this,sz).call(this,t)}))})),null===(P=t.transports)||void 0===P||P.forEach(((e,t)=>{this.components.transportManager.add(this.configureComponent("transport-".concat(t),e(this.components)))})),null!=t.services)for(var B of Object.keys(t.services)){var N,D,G=(0,t.services[B])(this.components);if(null!=G){if(this.services[B]=G,this.configureComponent(B,G),null!=G[jo]&&(this.log("registering service %s for content routing",B),C.push(G[jo])),null!=G[qo]&&(this.log("registering service %s for peer routing",B),I.push(G[qo])),null!=G[Fo])this.log("registering service %s for peer discovery",B),null===(N=(D=G[Fo]).addEventListener)||void 0===N||N.call(D,"peer",(t=>{e._assertClassBrand(oz,this,sz).call(this,t)}))}else this.log.error("service factory %s returned null or undefined instance",B)}!function(e){var t={};for(var r of Object.values(e.components))for(var n of qF(r))t[n]=!0;for(var i of Object.values(e.components))for(var o of HF(i))if(!0!==t[o])throw new kF('Service "'.concat(KF(i),'" required capability "').concat(o,'" but it was not provided by any component, you may need to add additional configuration when creating your node.'))}(T)}configureComponent(e,t){return null==t&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}start(){var t=this;return e._asyncToGenerator((function*(){if("stopped"===t.status){t.status="starting",t.log("libp2p is starting");try{var e,r,n,i;yield null===(e=(r=t.components).beforeStart)||void 0===e?void 0:e.call(r),yield t.components.start(),yield null===(n=(i=t.components).afterStart)||void 0===n?void 0:n.call(i),t.status="started",t.safeDispatchEvent("start",{detail:t}),t.log("libp2p has started")}catch(e){throw t.log.error("An error occurred starting libp2p",e),t.status="started",yield t.stop(),e}}}))()}stop(){var t=this;return e._asyncToGenerator((function*(){var e,r,n,i;"started"===t.status&&(t.log("libp2p is stopping"),t.status="stopping",yield null===(e=(r=t.components).beforeStop)||void 0===e?void 0:e.call(r),yield t.components.stop(),yield null===(n=(i=t.components).afterStop)||void 0===n?void 0:n.call(i),t.status="stopped",t.safeDispatchEvent("stop",{detail:t}),t.log("libp2p has stopped"))}))()}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){var e=new oh;for(var t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}dial(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{};return n.components.connectionManager.openConnection(t,e._objectSpread2({priority:75},i))}))()}dialProtocol(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var e=n.length>2&&void 0!==n[2]?n[2]:{};if(null==r)throw new Jo("no protocols were provided to open a stream");if(0===(r=Array.isArray(r)?r:[r]).length)throw new Jo("no protocols were provided to open a stream");return(yield i.dial(t,e)).newStream(r,e)}))()}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}hangUp(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e,i=r.length>1&&void 0!==r[1]?r[1]:{};rr(t)&&(t=$l(null!==(e=t.getPeerId())&&void 0!==e?e:""));yield n.components.connectionManager.closeConnections(t,i)}))()}getPublicKey(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};if(n.log("getPublicKey %p",t),null!=t.publicKey)return t.publicKey;try{var i=yield n.peerStore.get(t);if(null!=i.id.publicKey)return i.id.publicKey}catch(e){if("NotFoundError"!==e.name)throw e}var o=mt([nt("/pk/"),t.toMultihash().bytes]),a=Ml(yield n.contentRouting.get(o,e));return yield n.peerStore.patch(t,{publicKey:a}),a}))()}handle(t,r,n){var i=this;return e._asyncToGenerator((function*(){Array.isArray(t)||(t=[t]),yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){yield i.components.registrar.handle(e,r,n)}));return function(e){return t.apply(this,arguments)}}()))}))()}unhandle(t){var r=this;return e._asyncToGenerator((function*(){Array.isArray(t)||(t=[t]),yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){yield r.components.registrar.unhandle(e)}));return function(e){return t.apply(this,arguments)}}()))}))()}register(t,r){var n=this;return e._asyncToGenerator((function*(){return n.components.registrar.register(t,r)}))()}unregister(e){this.components.registrar.unregister(e)}isDialable(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};return n.components.connectionManager.isDialable(t,e)}))()}}function sz(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 lz(){return cz.apply(this,arguments)}function cz(){return cz=e._asyncToGenerator((function*(){var t,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};null!==(t=r.privateKey)&&void 0!==t||(r.privateKey=yield Ol("Ed25519"));var n=new az(e._objectSpread2(e._objectSpread2({},yield function(e){return Nj.apply(this,arguments)}(r)),{},{peerId:ec(r.privateKey)}));return!1!==r.start&&(yield n.start()),n})),cz.apply(this,arguments)}function uz(){return uz=e._asyncToGenerator((function*(t){var r,n,i=null!==(r=t.libp2p)&&void 0!==r?r:{};null==i.privateKey&&null!=t.datastore&&(i.privateKey=yield function(e){return Ej.apply(this,arguments)}(t.datastore,t.keychain));var o=Pj(i);return o.datastore=null!==(n=o.datastore)&&void 0!==n?n:t.datastore,yield lz(e._objectSpread2(e._objectSpread2(e._objectSpread2({},o),i),{},{start:!1}))})),uz.apply(this,arguments)}function dz(){return dz=e._asyncToGenerator((function*(){var t,r,n,i,o,a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},s=null!==(t=a.datastore)&&void 0!==t?t:new Vc,l=null!==(r=a.blockstore)&&void 0!==r?r:new Iu;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 uz.apply(this,arguments)}(e._objectSpread2(e._objectSpread2({},a),{},{libp2p:e._objectSpread2(e._objectSpread2({dns:a.dns},a.libp2p),{},{start:void 0}),datastore:s}));var c=new vG(e._objectSpread2(e._objectSpread2({},a),{},{libp2p:o,datastore:s,blockstore:l,blockBrokers:null!==(n=a.blockBrokers)&&void 0!==n?n:[JN(),bN()],routers:null!==(i=a.routers)&&void 0!==i?i:[fG(o),hG()],metrics:o.metrics}));return!1!==a.start&&(yield c.start()),c})),dz.apply(this,arguments)}function hz(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return r=Number(r),null!=t[Symbol.asyncIterator]?e._wrapAsyncGenerator((function*(){var n=[];if(r<1&&(r=1),r!==Math.round(r))throw new Error("Batch size must be an integer");var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;for(n.push(c);n.length>=r;)yield n.slice(0,r),n=n.slice(r)}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}for(;n.length>0;)yield n.slice(0,r),n=n.slice(r)}))():function*(){var e=[];if(r<1&&(r=1),r!==Math.round(r))throw new Error("Batch size must be an integer");for(var n of t)for(e.push(n);e.length>=r;)yield e.slice(0,r),e=e.slice(r);for(;e.length>0;)yield e.slice(0,r),e=e.slice(r)}()}function pz(e){return fz.apply(this,arguments)}function fz(){return fz=e._wrapAsyncGenerator((function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return function*(){var n,i=!1,o=!1;try{for(var a,s=e._asyncIterator(hz(t,r));i=!(a=yield e._awaitAsyncGenerator(s.next())).done;i=!1)for(var l=a.value.map(function(){var t=e._asyncToGenerator((function*(e){return e().then((e=>({ok:!0,value:e})),(e=>({ok:!1,err:e})))}));return function(e){return t.apply(this,arguments)}}()),c=0;c<l.length;c++){var u=yield e._awaitAsyncGenerator(l[c]);if(!u.ok)throw u.err;yield u.value}}catch(e){o=!0,n=e}finally{try{i&&null!=s.return&&(yield e._awaitAsyncGenerator(s.return()))}finally{if(o)throw n}}}()})),fz.apply(this,arguments)}var vz,yz,gz,mz=function(){var t,r=null!==(t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).chunkSize)&&void 0!==t?t:262144;return function(){var t=e._wrapAsyncGenerator((function*(t){var n,i=new Oa,o=0,a=!1,s=!1,l=!1;try{for(var c,u=e._asyncIterator(t);s=!(c=yield e._awaitAsyncGenerator(u.next())).done;s=!1){var d=c.value;for(i.append(d),o+=d.length;o>=r;)if(yield i.slice(0,r),a=!0,r===i.length)i=new Oa,o=0;else{var h=new Oa;h.append(i.sublist(r)),i=h,o-=r}}}catch(e){l=!0,n=e}finally{try{s&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(l)throw n}}(!a||o>0)&&(yield i.subarray(0,o))}));return function(e){return t.apply(this,arguments)}}()};class wz extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid type"),e._defineProperty(this,"name",wz.name),e._defineProperty(this,"code",wz.code)}}e._defineProperty(wz,"name","InvalidTypeError"),e._defineProperty(wz,"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=()=>cl(r)}(e.DataType||(e.DataType={})),e.codec=()=>(null==n&&(n=ul((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),yz.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=yz.codec().decode(t,t.uint32());break;default:t.skipType(7&o)}}return n}))),n),e.encode=t=>sl(t,e.codec()),e.decode=t=>js(t,e.codec())}(vz||(vz={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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=>sl(t,e.codec()),e.decode=t=>js(t,e.codec())}(yz||(yz={})),function(e){var t;e.codec=()=>(null==t&&(t=ul((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=>sl(t,e.codec()),e.decode=t=>js(t,e.codec())}(gz||(gz={}));var bz={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},_z=["directory","hamt-sharded-directory"],Sz=parseInt("0644",8),Pz=parseInt("0755",8);let Ez=class t{static unmarshal(e){var r,n,i=vz.decode(e),o=new t({type:bz[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._defineProperty(this,"type",void 0),e._defineProperty(this,"data",void 0),e._defineProperty(this,"blockSizes",void 0),e._defineProperty(this,"hashType",void 0),e._defineProperty(this,"fanout",void 0),e._defineProperty(this,"mtime",void 0),e._defineProperty(this,"_mode",void 0),e._defineProperty(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(bz).includes(r))throw new wz("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()?Pz:Sz:4095&e}get mode(){return this._mode}isDirectory(){return _z.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=vz.DataType.Raw;break;case"directory":e=vz.DataType.Directory;break;case"file":e=vz.DataType.File;break;case"metadata":e=vz.DataType.Metadata;break;case"symlink":e=vz.DataType.Symlink;break;case"hamt-sharded-directory":e=vz.DataType.HAMTShard;break;default:throw new wz("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))!==Sz||this.isDirectory()||(t=void 0),t===Pz&&this.isDirectory()&&(t=void 0));return null!=this.mtime&&(n={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),vz.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 Az=function(){var t=e._asyncToGenerator((function*(e,t,r){null==r.codec&&(r.codec=eN);var n=yield De.digest(e),i=je.create(r.cidVersion,r.codec.code,n);return yield t.put(i,e,r),i}));return function(e,r,n){return t.apply(this,arguments)}}();function kz(t){return function(){var r=e._wrapAsyncGenerator((function*(r,n){var i,o=0n,a=!1,s=!1;try{for(var l,c=function*(){var i=l.value;yield e._asyncToGenerator((function*(){var e,a,s={codec:eN,cidVersion:t.cidVersion,onProgress:t.onProgress};t.rawLeaves?(s.codec=ne,s.cidVersion=1):(a=new Ez({type:t.leafType,data:i}),i=$B({Data:a.marshal(),Links:[]}));var l=yield Az(i,n,s);return o+=BigInt(i.byteLength),null===(e=t.onProgress)||void 0===e||e.call(t,new Ah("unixfs:importer:progress:file:write",{bytesWritten:o,cid:l,path:r.path})),{cid:l,unixfs:a,size:BigInt(i.length),block:i}}))},u=e._asyncIterator(r.content);a=!(l=yield e._awaitAsyncGenerator(u.next())).done;a=!1)yield*c()}catch(e){s=!0,i=e}finally{try{a&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(s)throw i}}}));return function(e,t){return r.apply(this,arguments)}}()}let xz=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid parameters"),e._defineProperty(this,"name",t.name),e._defineProperty(this,"code",t.code)}};e._defineProperty(xz,"name","InvalidParametersError"),e._defineProperty(xz,"code","ERR_INVALID_PARAMS");class Tz extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid avg chunk size"),e._defineProperty(this,"name",Tz.name),e._defineProperty(this,"code",Tz.code)}}e._defineProperty(Tz,"name","InvalidAvgChunkSizeError"),e._defineProperty(Tz,"code","ERR_INVALID_AVG_CHUNK_SIZE");class Iz extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid chunk size"),e._defineProperty(this,"name",Iz.name),e._defineProperty(this,"code",Iz.code)}}e._defineProperty(Iz,"name","InvalidChunkSizeError"),e._defineProperty(Iz,"code","ERR_INVALID_CHUNK_SIZE");class Cz extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid min chunk size"),e._defineProperty(this,"name",Cz.name),e._defineProperty(this,"code",Cz.code)}}e._defineProperty(Cz,"name","InvalidMinChunkSizeError"),e._defineProperty(Cz,"code","ERR_INVALID_MIN_CHUNK_SIZE");class Bz extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid content"),e._defineProperty(this,"name",Bz.name),e._defineProperty(this,"code",Bz.code)}}e._defineProperty(Bz,"name","InvalidContentError"),e._defineProperty(Bz,"code","ERR_INVALID_CONTENT");var Nz=function(){var t=e._asyncToGenerator((function*(e,t,r){var n=new Ez({type:"directory",mtime:e.mtime,mode:e.mode}),i=$B(YB({Data:n.marshal()}));return{cid:yield Az(i,t,r),path:e.path,unixfs:n,size:BigInt(i.length),originalPath:e.originalPath,block:i}}));return function(e,r,n){return t.apply(this,arguments)}}();function Dz(){return Dz=e._wrapAsyncGenerator((function*(t,r,n){var i,o,a=-1,s=!1,l=!1;try{for(var c,u=e._asyncIterator(pz(n.bufferImporter(t,r),n.blockWriteConcurrency));s=!(c=yield e._awaitAsyncGenerator(u.next())).done;s=!1){var d=c.value;0!==++a?(1===a&&null!=i&&(yield e._objectSpread2(e._objectSpread2({},i),{},{block:void 0,single:void 0}),i=void 0),yield e._objectSpread2(e._objectSpread2({},d),{},{block:void 0})):i=e._objectSpread2(e._objectSpread2({},d),{},{single:!0})}}catch(e){l=!0,o=e}finally{try{s&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(l)throw o}}null!=i&&(yield i)})),Dz.apply(this,arguments)}function Gz(e){return!0===e.single}var Rz=(t,r,n)=>{var i=function(){var i=e._asyncToGenerator((function*(i){var o;if(1===i.length&&Gz(i[0])&&n.reduceSingleLeafToSelf){var a,s=i[0],l=s.block;return!Gz(s)||void 0===t.mtime&&void 0===t.mode||(s.unixfs=new Ez({type:"file",mtime:t.mtime,mode:t.mode,data:s.block}),l={Data:s.unixfs.marshal(),Links:[]},s.block=$B(YB(l)),s.cid=yield Az(s.block,r,e._objectSpread2(e._objectSpread2({},n),{},{cidVersion:n.cidVersion})),s.size=BigInt(s.block.length)),null===(a=n.onProgress)||void 0===a||a.call(n,new Ah("unixfs:importer:progress:file:layout",{cid:s.cid,path:s.originalPath})),{cid:s.cid,path:t.path,unixfs:s.unixfs,size:s.size,originalPath:s.originalPath}}var c=new Ez({type:"file",mtime:t.mtime,mode:t.mode}),u=i.filter((e=>{var t;return e.cid.code===re&&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===re)return c.addBlockSize(e.size),{Name:"",Tsize:Number(e.size),Hash:e.cid};null==(null===(t=e.unixfs)||void 0===t?void 0:t.data)?c.addBlockSize(null!==(r=null===(n=e.unixfs)||void 0===n?void 0:n.fileSize())&&void 0!==r?r:0n):c.addBlockSize(BigInt(e.unixfs.data.length));return{Name:"",Tsize:Number(e.size),Hash:e.cid}})),d={Data:c.marshal(),Links:u},h=$B(YB(d)),p=yield Az(h,r,n);return null===(o=n.onProgress)||void 0===o||o.call(n,new Ah("unixfs:importer:progress:file:layout",{cid:p,path:t.originalPath})),{cid:p,path:t.path,unixfs:c,size:BigInt(h.length+d.Links.reduce(((e,t)=>{var r;return e+(null!==(r=t.Tsize)&&void 0!==r?r:0)}),0)),originalPath:t.originalPath,block:h}}));return function(e){return i.apply(this,arguments)}}();return i},Oz=function(){var t=e._asyncToGenerator((function*(e,t,r){return r.layout(function(e,t,r){return Dz.apply(this,arguments)}(e,t,r),Rz(e,t,r))}));return function(e,r,n){return t.apply(this,arguments)}}();function Lz(t){try{if(t instanceof Uint8Array)return e._wrapAsyncGenerator((function*(){yield t}))();if(r=t,Symbol.iterator in r)return e._wrapAsyncGenerator((function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(t),e._awaitAsyncGenerator)}))();if(function(e){return Symbol.asyncIterator in e}(t))return t}catch(e){throw new Bz("Content was invalid")}var r;throw new Bz("Content was invalid")}var Mz=()=>function(){var t=e._wrapAsyncGenerator((function*(t){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t);n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var s=o.value;if(void 0===s.length)throw new Bz("Content was invalid");if("string"==typeof s||s instanceof String)yield nt(s.toString());else if(Array.isArray(s))yield Uint8Array.from(s);else{if(!(s instanceof Uint8Array))throw new Bz("Content was invalid");yield s}}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw r}}}));return function(e){return t.apply(this,arguments)}}();function jz(t){var r,n=null!==(r=null==t?void 0:t.maxChildrenPerNode)&&void 0!==r?r:174;return function(){var t=e._asyncToGenerator((function*(t,i){var o,a=[],s=!1,l=!1;try{for(var c,u=e._asyncIterator(hz(t,n));s=!(c=yield u.next()).done;s=!1){var d=c.value;a.push(yield i(d))}}catch(e){l=!0,o=e}finally{try{s&&null!=u.return&&(yield u.return())}finally{if(l)throw o}}return a.length>1?r(a,i):a[0]}));function r(e,r){return t.apply(this,arguments)}return r}()}let Fz=class{constructor(t,r){e._defineProperty(this,"options",void 0),e._defineProperty(this,"root",void 0),e._defineProperty(this,"dir",void 0),e._defineProperty(this,"path",void 0),e._defineProperty(this,"dirty",void 0),e._defineProperty(this,"flat",void 0),e._defineProperty(this,"parent",void 0),e._defineProperty(this,"parentKey",void 0),e._defineProperty(this,"unixfs",void 0),e._defineProperty(this,"mode",void 0),e._defineProperty(this,"mtime",void 0),e._defineProperty(this,"cid",void 0),e._defineProperty(this,"size",void 0),e._defineProperty(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 Uz=je.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),zz=je.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");class Vz extends Fz{constructor(t,r){super(t,r),e._defineProperty(this,"_children",void 0),this._children=new Map}put(t,r){var n=this;return e._asyncToGenerator((function*(){n.cid=void 0,n.size=void 0,n.nodeSize=void 0,n._children.set(t,r)}))()}get(t){var r=this;return e._asyncToGenerator((function*(){return Promise.resolve(r._children.get(t))}))()}childCount(){return this._children.size}directChildrenCount(){return this.childCount()}onlyChild(){return this._children.values().next().value}eachChildSeries(){var t=this;return e._wrapAsyncGenerator((function*(){for(var[e,r]of t._children.entries())yield{key:e,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?zz.bytes.byteLength:Uz.bytes.byteLength));return this.nodeSize}flush(t){var r=this;return e._wrapAsyncGenerator((function*(){var n=[];for(var[i,o]of r._children.entries()){var a=o;if(o instanceof Fz){var s,l=!1,c=!1;try{for(var u,d=e._asyncIterator(o.flush(t));l=!(u=yield e._awaitAsyncGenerator(d.next())).done;l=!1){var h=u.value;a=h,yield h}}catch(e){c=!0,s=e}finally{try{l&&null!=d.return&&(yield e._awaitAsyncGenerator(d.return()))}finally{if(c)throw s}}}null!=a.size&&null!=a.cid&&n.push({Name:i,Tsize:Number(a.size),Hash:a.cid})}var p=new Ez({type:"directory",mtime:r.mtime,mode:r.mode}),f={Data:p.marshal(),Links:n},v=$B(YB(f)),y=yield e._awaitAsyncGenerator(Az(v,t,r.options)),g=v.length+f.Links.reduce(((e,t)=>{var r;return e+(null!==(r=t.Tsize)&&void 0!==r?r:0)}),0);r.cid=y,r.size=g,yield{cid:y,unixfs:p,path:r.path,size:BigInt(g)}}))()}}var qz,Hz,Kz,Wz={exports:{}};var Qz=Kz?Hz:(Kz=1,qz||(qz=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 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[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 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[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 p(e,t){return[e[0]^t[0],e[1]^t[1]]}function f(e){return e=p(e,[0,e[0]>>>1]),e=p(e=u(e,[4283543511,3981806797]),[0,e[0]>>>1]),p(e=u(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,c=e.length-r,u=t,d=0,h=3432918353,p=461845907,f=0;f<c;f+=4)d=a(d=e[f]|e[f+1]<<8|e[f+2]<<16|e[f+3]<<24,h),d=a(d=s(d,15),p),u=a(u=s(u^=d,13),5)+3864292196;switch(d=0,r){case 3:d^=e[f+2]<<16;case 2:d^=e[f+1]<<8;case 1:d=a(d^=e[f],h),u^=d=a(d=s(d,15),p)}return(u=l(u^=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,c=e.length-r,u=t,d=t,h=t,p=t,f=0,v=0,y=0,g=0,m=597399067,w=2869860233,b=951274213,_=2716044179,S=0;S<c;S+=16)f=e[S]|e[S+1]<<8|e[S+2]<<16|e[S+3]<<24,v=e[S+4]|e[S+5]<<8|e[S+6]<<16|e[S+7]<<24,y=e[S+8]|e[S+9]<<8|e[S+10]<<16|e[S+11]<<24,g=e[S+12]|e[S+13]<<8|e[S+14]<<16|e[S+15]<<24,f=s(f=a(f,m),15),u=s(u^=f=a(f,w),19),u=a(u+=d,5)+1444728091,v=s(v=a(v,w),16),d=s(d^=v=a(v,b),17),d=a(d+=h,5)+197830471,y=s(y=a(y,b),17),h=s(h^=y=a(y,_),15),h=a(h+=p,5)+2530024501,g=s(g=a(g,_),18),p=s(p^=g=a(g,m),13),p=a(p+=u,5)+850148119;switch(f=0,v=0,y=0,g=0,r){case 15:g^=e[S+14]<<16;case 14:g^=e[S+13]<<8;case 13:g=a(g^=e[S+12],_),p^=g=a(g=s(g,18),m);case 12:y^=e[S+11]<<24;case 11:y^=e[S+10]<<16;case 10:y^=e[S+9]<<8;case 9:y=a(y^=e[S+8],b),h^=y=a(y=s(y,17),_);case 8:v^=e[S+7]<<24;case 7:v^=e[S+6]<<16;case 6:v^=e[S+5]<<8;case 5:v=a(v^=e[S+4],w),d^=v=a(v=s(v,16),b);case 4:f^=e[S+3]<<24;case 3:f^=e[S+2]<<16;case 2:f^=e[S+1]<<8;case 1:f=a(f^=e[S],m),u^=f=a(f=s(f,15),w)}return u^=e.length,u+=d^=e.length,u+=h^=e.length,d+=u+=p^=e.length,h+=u,p+=u,u=l(u),u+=d=l(d),u+=h=l(h),d+=u+=p=l(p),h+=u,p+=u,("00000000"+(u>>>0).toString(16)).slice(-8)+("00000000"+(d>>>0).toString(16)).slice(-8)+("00000000"+(h>>>0).toString(16)).slice(-8)+("00000000"+(p>>>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],v=[0,0],y=[0,0],g=[2277735313,289559509],m=[1291169091,658871167],w=0;w<a;w+=16)v=[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],y=[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],v=d(v=u(v,g),31),s=c(s=d(s=p(s,v=u(v,m)),27),l),s=c(u(s,[0,5]),[0,1390208809]),y=d(y=u(y,m),33),l=c(l=d(l=p(l,y=u(y,g)),31),s),l=c(u(l,[0,5]),[0,944331445]);switch(v=[0,0],y=[0,0],r){case 15:y=p(y,h([0,e[w+14]],48));case 14:y=p(y,h([0,e[w+13]],40));case 13:y=p(y,h([0,e[w+12]],32));case 12:y=p(y,h([0,e[w+11]],24));case 11:y=p(y,h([0,e[w+10]],16));case 10:y=p(y,h([0,e[w+9]],8));case 9:y=u(y=p(y,[0,e[w+8]]),m),l=p(l,y=u(y=d(y,33),g));case 8:v=p(v,h([0,e[w+7]],56));case 7:v=p(v,h([0,e[w+6]],48));case 6:v=p(v,h([0,e[w+5]],40));case 5:v=p(v,h([0,e[w+4]],32));case 4:v=p(v,h([0,e[w+3]],24));case 3:v=p(v,h([0,e[w+2]],16));case 2:v=p(v,h([0,e[w+1]],8));case 1:v=u(v=p(v,[0,e[w]]),g),s=p(s,v=u(v=d(v,31),m))}return s=c(s=p(s,[0,e.length]),l=p(l,[0,e.length])),l=c(l,s),s=c(s=f(s),l=f(l)),l=c(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}()}(Wz,Wz.exports)),Hz=Wz.exports),Yz=e.getDefaultExportFromCjs(Qz);Ce({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)}(Yz.x86.hash32(e))});var Jz,Zz,$z=Ce({name:"murmur3-128",code:34,encode:e=>r(Yz.x64.hash128(e))});Ce({name:"murmur3-x64-64",code:34,encode:e=>r(Yz.x64.hash128(e)).subarray(0,8)});var Xz=function(){if(Zz)return Jz;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 Zz=1,Jz=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)}},Jz}(),eV=e.getDefaultExportFromCjs(Xz);class tV{constructor(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;e._defineProperty(this,"_options",void 0),e._defineProperty(this,"_popCount",void 0),e._defineProperty(this,"_parent",void 0),e._defineProperty(this,"_posAtParent",void 0),e._defineProperty(this,"_children",void 0),e._defineProperty(this,"key",void 0),this._options=t,this._popCount=0,this._parent=r,this._posAtParent=n,this._children=new eV,this.key=null}put(t,r){var n=this;return e._asyncToGenerator((function*(){var e=yield n._findNewBucketAndPos(t);e.bucket._putAt(e,t,r)}))()}get(t){var r=this;return e._asyncToGenerator((function*(){var e=yield r._findChild(t);if(null!=e)return e.value}))()}del(t){var r=this;return e._asyncToGenerator((function*(){var e=yield r._findPlace(t),n=e.bucket._at(e.pos);null!=n&&n.key===t&&e.bucket._delAt(e.pos)}))()}leafCount(){return this._children.compactArray().reduce(((e,t)=>t instanceof tV?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 tV?yield*t.eachLeafSeries():yield t}serialize(e,t){return t(this._children.reduce(((r,n,i)=>(null!=n&&(n instanceof tV?r.push(n.serialize(e,t)):r.push(e(n,i))),r)),[]))}asyncTransform(t,r){var n=this;return e._asyncToGenerator((function*(){return oV(n,t,r)}))()}toJSON(){return this.serialize(nV,iV)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}_findChild(t){var r=this;return e._asyncToGenerator((function*(){var e=yield r._findPlace(t),n=e.bucket._at(e.pos);if(!(n instanceof tV))return null!=n&&n.key===t?n:void 0}))()}_findPlace(t){var r=this;return e._asyncToGenerator((function*(){var e=r._options.hash("string"==typeof t?nt(t):t),n=yield e.take(r._options.bits),i=r._children.get(n);return i instanceof tV?i._findPlace(e):{bucket:r,pos:n,hash:e,existingChild:i}}))()}_findNewBucketAndPos(t){var r=this;return e._asyncToGenerator((function*(){var e=yield r._findPlace(t);if(null!=e.existingChild&&e.existingChild.key!==t){var n=new tV(r._options,e.bucket,e.pos);e.bucket._putObjectAt(e.pos,n);var i=yield n._findPlace(e.existingChild.hash);return i.bucket._putAt(i,e.existingChild.key,e.existingChild.value),n._findNewBucketAndPos(e.hash)}return e}))()}_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(rV);if(null!=e&&!(e instanceof tV)){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 rV(e){return Boolean(e)}function nV(e,t){return e.key}function iV(e){return e}function oV(e,t,r){return aV.apply(this,arguments)}function aV(){return(aV=e._asyncToGenerator((function*(e,t,r){var n=[];for(var i of e._children.compactArray())if(i instanceof tV)yield oV(i,t,r);else{var o=yield t(i);n.push({bitField:e._children.bitField(),children:o})}return r(n)}))).apply(this,arguments)}var sV=[255,254,252,248,240,224,192,128],lV=[1,3,7,15,31,63,127,255];let cV=class{constructor(t){e._defineProperty(this,"_value",void 0),e._defineProperty(this,"_currentBytePos",void 0),e._defineProperty(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)+uV(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 uV(e,t,r){var n=function(e,t){return sV[e]&lV[Math.min(t+e-1,7)]}(t,r);return(e&n)>>>t}function dV(e){return function(t){return t instanceof hV?t:new hV(t,e)}}let hV=class{constructor(t,r){if(e._defineProperty(this,"_value",void 0),e._defineProperty(this,"_hashFn",void 0),e._defineProperty(this,"_depth",void 0),e._defineProperty(this,"_availableBits",void 0),e._defineProperty(this,"_currentBufferIndex",void 0),e._defineProperty(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(t){var r=this;return e._asyncToGenerator((function*(){for(var e=t;r._availableBits<e;)yield r._produceMoreBits();for(var n=0;e>0;){var i=r._buffers[r._currentBufferIndex],o=Math.min(i.availableBits(),e);n=(n<<o)+i.take(o),e-=o,r._availableBits-=o,0===i.availableBits()&&r._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 t=this;return e._asyncToGenerator((function*(){t._depth++;var e=t._depth>0?mt([t._value,Uint8Array.from([t._depth])]):t._value,r=yield t._hashFn(e),n=new cV(r);t._buffers.push(n),t._availableBits+=n.availableBits()}))()}};function pV(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:dV(e.hashFn)};return new tV(r)}function fV(e){return vV.apply(this,arguments)}function vV(){return vV=e._asyncToGenerator((function*(e){return(yield $z.encode(e)).slice(0,8).reverse()})),vV.apply(this,arguments)}var yV=BigInt(34);let gV=class extends Fz{constructor(t,r){var n;super(t,r),e._defineProperty(this,"_bucket",void 0),this._bucket=pV({hashFn:fV,bits:null!==(n=r.shardFanoutBits)&&void 0!==n?n:8})}put(t,r){var n=this;return e._asyncToGenerator((function*(){n.cid=void 0,n.size=void 0,n.nodeSize=void 0,yield n._bucket.put(t,r)}))()}get(t){var r=this;return e._asyncToGenerator((function*(){return r._bucket.get(t)}))()}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}eachChildSeries(){var t=this;return e._wrapAsyncGenerator((function*(){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t._bucket.eachLeafSeries());n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var{key:s,value:l}=o.value;yield{key:s,child:l}}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw r}}}))()}estimateNodeSize(){return void 0!==this.nodeSize||(this.nodeSize=bV(this._bucket,this,this.options)),this.nodeSize}flush(t){var r=this;return e._wrapAsyncGenerator((function*(){var n,i=!1,o=!1;try{for(var a,s=e._asyncIterator(mV(r._bucket,t,r,r.options));i=!(a=yield e._awaitAsyncGenerator(s.next())).done;i=!1){var l=a.value;yield e._objectSpread2(e._objectSpread2({},l),{},{path:r.path})}}catch(e){o=!0,n=e}finally{try{i&&null!=s.return&&(yield e._awaitAsyncGenerator(s.return()))}finally{if(o)throw n}}}))()}};function mV(e,t,r,n){return wV.apply(this,arguments)}function wV(){return wV=e._wrapAsyncGenerator((function*(t,r,n,i){for(var o=t._children,a=(t.tableSize()-1).toString(16).length,s=[],l=0n,c=0;c<o.length;c++){var u=o.get(c);if(null!=u){var d=c.toString(16).toUpperCase().padStart(a,"0");if(u instanceof tV){var h,p=void 0,f=!1,v=!1;try{for(var y,g=e._asyncIterator(mV(u,r,null,i));f=!(y=yield e._awaitAsyncGenerator(g.next())).done;f=!1){p=y.value}}catch(e){v=!0,h=e}finally{try{f&&null!=g.return&&(yield e._awaitAsyncGenerator(g.return()))}finally{if(v)throw h}}if(null==p)throw new Error("Could not flush sharded directory, no subshard found");s.push({Name:d,Tsize:Number(p.size),Hash:p.cid}),l+=p.size}else if("function"==typeof u.value.flush){var m,w=u.value,b=void 0,_=!1,S=!1;try{for(var P,E=e._asyncIterator(w.flush(r));_=!(P=yield e._awaitAsyncGenerator(E.next())).done;_=!1){b=P.value,yield b}}catch(e){S=!0,m=e}finally{try{_&&null!=E.return&&(yield e._awaitAsyncGenerator(E.return()))}finally{if(S)throw m}}if(null==b)throw new Error("Did not flush dir");var A=d+u.key;s.push({Name:A,Tsize:Number(b.size),Hash:b.cid}),l+=b.size}else{var k=u.value;if(null==k.cid)continue;var x=d+u.key,T=k.size;s.push({Name:x,Tsize:Number(T),Hash:k.cid}),l+=BigInt(null!=T?T:0)}}}var I=Uint8Array.from(o.bitField().reverse()),C=new Ez({type:"hamt-sharded-directory",data:I,fanout:BigInt(t.tableSize()),hashType:yV,mtime:null==n?void 0:n.mtime,mode:null==n?void 0:n.mode}),B=$B(YB({Data:C.marshal(),Links:s})),N=yield e._awaitAsyncGenerator(Az(B,r,i)),D=BigInt(B.byteLength)+l;yield{cid:N,unixfs:C,size:D}})),wV.apply(this,arguments)}function bV(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 tV){var c=bV(s,null,r);o.push({Name:l,Tsize:Number(c),Hash:0===r.cidVersion?Uz:zz})}else if("function"==typeof s.value.flush){var u=s.value.nodeSize();o.push({Name:l+s.key,Tsize:Number(u),Hash:0===r.cidVersion?Uz:zz})}else{var d=s.value;if(null==d.cid)continue;var h=l+s.key,p=d.size;o.push({Name:h,Tsize:Number(p),Hash:d.cid})}}}var f=Uint8Array.from(n.bitField().reverse());return $B(YB({Data:new Ez({type:"hamt-sharded-directory",data:f,fanout:BigInt(e.tableSize()),hashType:yV,mtime:null==t?void 0:t.mtime,mode:null==t?void 0:t.mode}).marshal(),Links:o})).length}function _V(e,t,r,n){return SV.apply(this,arguments)}function SV(){return SV=e._asyncToGenerator((function*(e,t,r,n){var i=t;t instanceof Vz&&t.estimateNodeSize()>r&&(i=yield function(e,t){return PV.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 _V(i,o,r,n)}return i})),SV.apply(this,arguments)}function PV(){return PV=e._asyncToGenerator((function*(t,r){var n,i=new gV({root:t.root,dir:!0,parent:t.parent,parentKey:t.parentKey,path:t.path,dirty:t.dirty,flat:!1,mtime:t.mtime,mode:t.mode},r),o=!1,a=!1;try{for(var s,l=e._asyncIterator(t.eachChildSeries());o=!(s=yield l.next()).done;o=!1){var{key:c,child:u}=s.value;yield i.put(c,u)}}catch(e){a=!0,n=e}finally{try{o&&null!=l.return&&(yield l.return())}finally{if(a)throw n}}return i})),PV.apply(this,arguments)}function EV(e,t,r){return AV.apply(this,arguments)}function AV(){return AV=e._asyncToGenerator((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 c=i[l];s+="".concat(""!==s?"/":"").concat(c);var u=l===o;if(a.dirty=!0,a.cid=void 0,a.size=void 0,u)yield a.put(c,e),t=yield _V(null,a,r.shardSplitThresholdBytes,r);else{var d,h,p=yield a.get(c);if(null==p||!(p instanceof Fz))p=new Vz({root:!1,dir:!0,parent:a,parentKey:c,path:s,dirty:!0,flat:!0,mtime:null===(d=p)||void 0===d||null===(d=d.unixfs)||void 0===d?void 0:d.mtime,mode:null===(h=p)||void 0===h||null===(h=h.unixfs)||void 0===h?void 0:h.mode},r);yield a.put(c,p),a=p}}return t})),AV.apply(this,arguments)}function kV(e,t){return xV.apply(this,arguments)}function xV(){return xV=e._wrapAsyncGenerator((function*(t,r){var n;t instanceof Fz?yield*e._asyncGeneratorDelegate(e._asyncIterator(t.flush(r))):!0===(null===(n=t.unixfs)||void 0===n?void 0:n.isDirectory())&&(yield t)})),xV.apply(this,arguments)}function TV(e,t){return IV.apply(this,arguments)}function IV(){return IV=e._wrapAsyncGenerator((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(i,o,a,s,l,c,u,d,h,p,f,v,y,g,m){var w;w=Symbol.asyncIterator in t||Symbol.iterator in t?t:[t];var b,_=null!==(i=n.wrapWithDirectory)&&void 0!==i&&i,S=null!==(o=n.shardSplitThresholdBytes)&&void 0!==o?o:262144,P=null!==(a=n.shardFanoutBits)&&void 0!==a?a:8,E=null!==(s=n.cidVersion)&&void 0!==s?s:1,A=null===(l=n.rawLeaves)||void 0===l||l,k=null!==(c=n.leafType)&&void 0!==c?c:"file",x=null!==(u=n.fileImportConcurrency)&&void 0!==u?u:50,T=null!==(d=n.blockWriteConcurrency)&&void 0!==d?d:10,I=null===(h=n.reduceSingleLeafToSelf)||void 0===h||h,C=null!==(p=n.chunker)&&void 0!==p?p:mz(),B=null!==(f=n.chunkValidator)&&void 0!==f?f:Mz(),N=null!==(v=n.dagBuilder)&&void 0!==v?v:function(t){return function(){var r=e._wrapAsyncGenerator((function*(r,n){var i,o=!1,a=!1;try{for(var s,l=function*(){var r,i=s.value;if(null!=i.path&&(r=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:e._wrapAsyncGenerator((function*(){var r,n=0n,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t.chunker(t.chunkValidator(Lz(i.content))));o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c,u=s.value,d=BigInt(u.byteLength);n+=d,null===(c=t.onProgress)||void 0===c||c.call(t,new Ah("unixfs:importer:progress:file:read",{bytesRead:n,chunkSize:d,path:i.path})),yield u}}catch(e){a=!0,r=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw r}}}))(),originalPath:r};yield e._asyncToGenerator((function*(){return Oz(o,n,t)}))}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:r};yield e._asyncToGenerator((function*(){return Nz(a,n,t)}))}},c=e._asyncIterator(r);o=!(s=yield e._awaitAsyncGenerator(c.next())).done;o=!1)yield*l()}catch(e){a=!0,i=e}finally{try{o&&null!=c.return&&(yield e._awaitAsyncGenerator(c.return()))}finally{if(a)throw i}}}));return function(e,t){return r.apply(this,arguments)}}()}({chunker:C,chunkValidator:B,wrapWithDirectory:_,layout:null!==(y=n.layout)&&void 0!==y?y:jz(),bufferImporter:null!==(g=n.bufferImporter)&&void 0!==g?g:kz({cidVersion:E,rawLeaves:A,leafType:k,onProgress:n.onProgress}),blockWriteConcurrency:T,reduceSingleLeafToSelf:I,cidVersion:E,onProgress:n.onProgress}),D=null!==(m=n.treeBuilder)&&void 0!==m?m:function(t){return function(){var r=e._wrapAsyncGenerator((function*(r,n){var i,o,a=new Vz({root:!0,dir:!0,path:"",dirty:!0,flat:!0},t),s=!1,l=!1,c=!1;try{for(var u,d=e._asyncIterator(r);l=!(u=yield e._awaitAsyncGenerator(d.next())).done;l=!1){var h,p,f=u.value;if(null!=f){var v="".concat(null!==(h=f.originalPath)&&void 0!==h?h:"").split("/")[0];null!=v&&""!==v&&(null==i?(i=v,s=!0):i!==v&&(s=!1)),a=yield e._awaitAsyncGenerator(EV(f,a,t)),!0!==(null===(p=f.unixfs)||void 0===p?void 0:p.isDirectory())&&(yield f)}}}catch(e){c=!0,o=e}finally{try{l&&null!=d.return&&(yield e._awaitAsyncGenerator(d.return()))}finally{if(c)throw o}}if(t.wrapWithDirectory||s&&a.childCount()>1)yield*e._asyncGeneratorDelegate(e._asyncIterator(kV(a,n)));else{var y,g=!1,m=!1;try{for(var w,b=e._asyncIterator(a.eachChildSeries());g=!(w=yield e._awaitAsyncGenerator(b.next())).done;g=!1){var _=w.value;null!=_&&(yield*e._asyncGeneratorDelegate(e._asyncIterator(kV(_.child,n)),e._awaitAsyncGenerator))}}catch(e){m=!0,y=e}finally{try{g&&null!=b.return&&(yield e._awaitAsyncGenerator(b.return()))}finally{if(m)throw y}}}}));return function(e,t){return r.apply(this,arguments)}}()}({wrapWithDirectory:_,shardSplitThresholdBytes:S,shardFanoutBits:P,cidVersion:E,onProgress:n.onProgress}),G=!1,R=!1;try{for(var O,L=e._asyncIterator(D(pz(N(w,r),x),r));G=!(O=yield e._awaitAsyncGenerator(L.next())).done;G=!1){var M=O.value;yield{cid:M.cid,path:M.path,unixfs:M.unixfs,size:M.size}}}catch(e){R=!0,b=e}finally{try{G&&null!=L.return&&(yield e._awaitAsyncGenerator(L.return()))}finally{if(R)throw b}}}()})),IV.apply(this,arguments)}function CV(e,t){return BV.apply(this,arguments)}function BV(){return BV=e._asyncToGenerator((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=yield CD(TV([e],t,r));if(null==n)throw new xz("Nothing imported");return n})),BV.apply(this,arguments)}function NV(){return NV=e._asyncToGenerator((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=yield CD(TV([e],t,r));if(null==n)throw new xz("Nothing imported");return n})),NV.apply(this,arguments)}function DV(){return DV=e._asyncToGenerator((function*(e,t){return CV({content:e},t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})})),DV.apply(this,arguments)}function GV(){return GV=e._asyncToGenerator((function*(e,t){return CV({content:e},t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})})),GV.apply(this,arguments)}var RV={cidVersion:1,rawLeaves:!0,layout:jz({maxChildrenPerNode:1024}),chunker:mz({chunkSize:1048576})};function OV(){return OV=e._wrapAsyncGenerator((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(TV(t,r,e._objectSpread2(e._objectSpread2({},RV),n))))}()})),OV.apply(this,arguments)}function LV(){return LV=e._asyncToGenerator((function*(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{cid:i}=yield function(e,t){return DV.apply(this,arguments)}(t,r,e._objectSpread2(e._objectSpread2({},RV),n));return i})),LV.apply(this,arguments)}function MV(){return MV=e._asyncToGenerator((function*(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{cid:i}=yield function(e,t){return GV.apply(this,arguments)}(t,r,e._objectSpread2(e._objectSpread2({},RV),n));return i})),MV.apply(this,arguments)}function jV(){return jV=e._asyncToGenerator((function*(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{cid:i}=yield CV(t,r,e._objectSpread2(e._objectSpread2({},RV),n));return i})),jV.apply(this,arguments)}function FV(){return FV=e._asyncToGenerator((function*(t,r){var n,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{cid:o}=yield function(e,t){return NV.apply(this,arguments)}(e._objectSpread2(e._objectSpread2({},t),{},{path:null!==(n=t.path)&&void 0!==n?n:"-"}),r,e._objectSpread2(e._objectSpread2({},RV),i));return o})),FV.apply(this,arguments)}function UV(t){if(null!=t[Symbol.asyncIterator])return e._asyncToGenerator((function*(){var r,n,i=!1,o=!1;try{for(var a,s=e._asyncIterator(t);i=!(a=yield s.next()).done;i=!1){r=a.value}}catch(e){o=!0,n=e}finally{try{i&&null!=s.return&&(yield s.return())}finally{if(o)throw n}}return r}))();var r;for(var n of t)r=n;return r}class zV extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Bad path"),e._defineProperty(this,"name",zV.name),e._defineProperty(this,"code",zV.code)}}e._defineProperty(zV,"name","BadPathError"),e._defineProperty(zV,"code","ERR_BAD_PATH");class VV extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not found"),e._defineProperty(this,"name",VV.name),e._defineProperty(this,"code",VV.code)}}e._defineProperty(VV,"name","NotFoundError"),e._defineProperty(VV,"code","ERR_NOT_FOUND");class qV extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No resolver"),e._defineProperty(this,"name",qV.name),e._defineProperty(this,"code",qV.code)}}e._defineProperty(qV,"name","NoResolverError"),e._defineProperty(qV,"code","ERR_NO_RESOLVER");let HV=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not UnixFS"),e._defineProperty(this,"name",t.name),e._defineProperty(this,"code",t.code)}};e._defineProperty(HV,"name","NotUnixFSError"),e._defineProperty(HV,"code","ERR_NOT_UNIXFS");class KV extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Over read"),e._defineProperty(this,"name",KV.name),e._defineProperty(this,"code",KV.code)}}e._defineProperty(KV,"name","OverReadError"),e._defineProperty(KV,"code","ERR_OVER_READ");class WV extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Under read"),e._defineProperty(this,"name",WV.name),e._defineProperty(this,"code",WV.code)}}e._defineProperty(WV,"name","UnderReadError"),e._defineProperty(WV,"code","ERR_UNDER_READ");class QV extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No Property found"),e._defineProperty(this,"name",QV.name),e._defineProperty(this,"code",QV.code)}}e._defineProperty(QV,"name","NoPropError"),e._defineProperty(QV,"code","ERR_NO_PROP");let YV=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid parameters"),e._defineProperty(this,"name",t.name),e._defineProperty(this,"code",t.code)}};function JV(t,r,n,i,o,a,s){for(var l,c=t,u=o;a.length>0;){var d=a[0];if(!(d in c))throw new QV("No property named ".concat(d," found in node ").concat(n));a.shift(),u="".concat(u,"/").concat(d);var h=je.asCID(c[d]);if(null!=h)return{entry:{type:"object",name:i,path:o,cid:n,node:r,depth:s,size:BigInt(r.length),content:function(){var r=e._wrapAsyncGenerator((function*(){yield t}));return function(){return r.apply(this,arguments)}}()},next:{cid:h,name:d,path:u,toResolve:a}};c=c[d]}return{entry:{type:"object",name:i,path:o,cid:n,node:r,depth:s,size:BigInt(r.length),content:(l=e._wrapAsyncGenerator((function*(){yield t})),function(){return l.apply(this,arguments)})}}}e._defineProperty(YV,"name","InvalidParametersError"),e._defineProperty(YV,"code","ERR_INVALID_PARAMS");var ZV=function(){var t=e._asyncToGenerator((function*(e,t,r,n,i,o,a,s){var l=yield a.get(e,s);return JV(hB(l),l,e,t,r,n,o)}));return function(e,r,n,i,o,a,s,l){return t.apply(this,arguments)}}(),$V=function(){var t=e._asyncToGenerator((function*(e,t,r,n,i,o,a,s){var l=yield a.get(e,s);return JV(EB(l),l,e,t,r,n,o)}));return function(e,r,n,i,o,a,s,l){return t.apply(this,arguments)}}();function XV(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 eq=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 YV("Offset must be greater than or equal to 0");if(i>n)throw new YV("Offset must be less than the file size");if(o<0n)throw new YV("Length must be greater than or equal to 0");if(o>n)throw new YV("Length must be less than the file size");return{start:i,end:o}},tq=t=>{function r(){return r=e._wrapAsyncGenerator((function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(r){var{start:n,end:i}=eq(t.length,e.offset,e.length),o=XV(t,0n,n,i);null===(r=e.onProgress)||void 0===r||r.call(e,new Ah("unixfs:exporter:progress:identity",{bytesRead:BigInt(o.byteLength),totalBytes:i-n,fileSize:BigInt(t.byteLength)})),yield o}()})),r.apply(this,arguments)}return function(){return r.apply(this,arguments)}},rq=function(){var t=e._asyncToGenerator((function*(e,t,r,n,i,o,a,s){if(n.length>0)throw new VV("No link named ".concat(r," found in raw node ").concat(e));var l=Ae(e.multihash.bytes);return{entry:{type:"identity",name:t,path:r,cid:e,content:tq(l.digest),depth:o,size:BigInt(l.digest.length),node:l.digest}}}));return function(e,r,n,i,o,a,s,l){return t.apply(this,arguments)}}(),nq=function(){var t=e._asyncToGenerator((function*(e,t,r,n,i,o,a,s){var l=yield a.get(e,s);return JV(ee(l),l,e,t,r,n,o)}));return function(e,r,n,i,o,a,s,l){return t.apply(this,arguments)}}(),iq=t=>{function r(){return r=e._wrapAsyncGenerator((function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(r){var{start:n,end:i}=eq(t.length,e.offset,e.length),o=XV(t,0n,n,i);null===(r=e.onProgress)||void 0===r||r.call(e,new Ah("unixfs:exporter:progress:raw",{bytesRead:BigInt(o.byteLength),totalBytes:i-n,fileSize:BigInt(t.byteLength)})),yield o}()})),r.apply(this,arguments)}return function(){return r.apply(this,arguments)}},oq=function(){var t=e._asyncToGenerator((function*(e,t,r,n,i,o,a,s){if(n.length>0)throw new VV("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:iq(l),depth:o,size:BigInt(l.length),node:l}}}));return function(e,r,n,i,o,a,s,l){return t.apply(this,arguments)}}(),aq=function(){var t=e._asyncToGenerator((function*(e){return(yield $z.encode(e)).slice(0,8).reverse()}));return function(e){return t.apply(this,arguments)}}(),sq=function(){var t=e._asyncToGenerator((function*(t,r,n){var i=(r.tableSize()-1).toString(16).length;yield Promise.all(t.map(function(){var t=e._asyncToGenerator((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 t=parseInt(e.Name,16);r._putObjectAt(t,new tV({hash:n._options.hash,bits:n._options.bits},r,t))}}));return function(e){return t.apply(this,arguments)}}()))}));return function(e,r,n){return t.apply(this,arguments)}}(),lq=(e,t)=>e.toString(16).toUpperCase().padStart(t,"0").substring(0,t),cq=function(){var t=e._asyncToGenerator((function*(e,t,r,n,i){if(null==n){if(null==e.Data)throw new HV("no data in PBNode");var o;try{o=Ez.unmarshal(e.Data)}catch(e){throw new HV(e.message)}if("hamt-sharded-directory"!==o.type)throw new HV("not a HAMT");if(null==o.fanout)throw new HV("missing fanout");var a=pV({hashFn:aq,bits:Math.log2(Number(o.fanout))});n={rootBucket:a,hamtDepth:1,lastBucket:a}}var s=(n.lastBucket.tableSize()-1).toString(16).length;yield sq(e.Links,n.lastBucket,n.rootBucket);var l=yield n.rootBucket._findNewBucketAndPos(t),c=lq(l.pos,s),u=(e=>{for(var t=e.bucket,r=[];null!=t._parent;)r.push(t),t=t._parent;return r.push(t),r.reverse()})(l);u.length>n.hamtDepth&&(n.lastBucket=u[n.hamtDepth],c=lq(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===c&&(""===n||n===t)}));if(null!=d)return null!=d.Name&&d.Name.substring(s)===t?d.Hash:(n.hamtDepth++,e=XB(yield r.get(d.Hash,i)),cq(e,t,r,n,i))}));return function(e,r,n,i,o){return t.apply(this,arguments)}}();function uq(e,t,r,n,i,o,a){return dq.apply(this,arguments)}function dq(){return dq=e._asyncToGenerator((function*(t,r,n,i,o,a,s){if(r instanceof Uint8Array){var l=XV(r,i,o,a);n.push(l)}else{if(null==r.Data)throw new HV("no data in PBNode");var c;try{c=Ez.unmarshal(r.Data)}catch(e){throw new HV(e.message)}if(null!=c.data){var u=XV(c.data,i,o,a);n.push(u),i+=BigInt(u.byteLength)}var d=[];if(r.Links.length!==c.blockSizes.length)throw new HV("Inconsistent block sizes and dag links");for(var h=0;h<r.Links.length;h++){var p=r.Links[h],f=i,v=f+c.blockSizes[h];if((o>=f&&o<v||a>=f&&a<=v||o<f&&a>v)&&d.push({link:p,blockStart:i}),(i=v)>a)break}yield iu(d,(r=>qc(r,(r=>e._asyncToGenerator((function*(){var n=yield t.get(r.link.Hash,s);return e._objectSpread2(e._objectSpread2({},r),{},{block:n})}))))),(e=>MR(e,{ordered:!0,concurrency:s.blockReadConcurrency})),function(){var r=e._asyncToGenerator((function*(r){var i,l=!1,c=!1;try{for(var u,d,h=function*(){var r,{link:i,block:l,blockStart:c}=d.value;switch(i.Hash.code){case ZB:r=XB(l);break;case re:r=l;break;default:return n.end(new HV("Unsupported codec: ".concat(i.Hash.code))),{v:void 0}}var u=new Yx({concurrency:1});u.on("error",(e=>{n.end(e)})),u.add(e._asyncToGenerator((function*(){var e;null===(e=s.onProgress)||void 0===e||e.call(s,new Ah("unixfs:exporter:walk:file",{cid:i.Hash})),yield uq(t,r,n,c,o,a,s)}))),yield u.onIdle()},p=e._asyncIterator(r);l=!(d=yield p.next()).done;l=!1)if(u=yield*h())return u.v}catch(e){c=!0,i=e}finally{try{l&&null!=p.return&&(yield p.return())}finally{if(c)throw i}}}));return function(e){return r.apply(this,arguments)}}()),i>=a&&n.end()}})),dq.apply(this,arguments)}var hq=(t,r,n,i,o,a,s)=>{function l(){return l=e._wrapAsyncGenerator((function(){var i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(o){var a=n.fileSize();if(void 0===a)throw new Error("File was a directory");var{start:l,end:c}=eq(a,i.offset,i.length);if(0n!==c){var u=0n,d=c-l,h=Yc();null===(o=i.onProgress)||void 0===o||o.call(i,new Ah("unixfs:exporter:walk:file",{cid:t})),uq(s,r,h,0n,l,c,i).catch((e=>{h.end(e)}));var p,f=!1,v=!1;try{for(var y,g=e._asyncIterator(h);f=!(y=yield e._awaitAsyncGenerator(g.next())).done;f=!1){var m,w=y.value;if(null!=w){if((u+=BigInt(w.byteLength))>d)throw h.end(),new KV("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");u===d&&h.end(),null===(m=i.onProgress)||void 0===m||m.call(i,new Ah("unixfs:exporter:progress:unixfs:file",{bytesRead:u,totalBytes:d,fileSize:a})),yield w}}}catch(e){v=!0,p=e}finally{try{f&&null!=g.return&&(yield e._awaitAsyncGenerator(g.return()))}finally{if(v)throw p}}if(u<d)throw new WV("Traversed entire DAG but did not read enough bytes")}}()})),l.apply(this,arguments)}return function(){return l.apply(this,arguments)}};function pq(e,t,r,n,i,o){return fq.apply(this,arguments)}function fq(){return fq=e._wrapAsyncGenerator((function*(t,r,n,i,o,a){var s,l=t.Links;if(null==t.Data)throw new HV("no data in PBNode");try{s=Ez.unmarshal(t.Data)}catch(e){throw new HV(e.message)}if(null==s.fanout)throw new HV("missing fanout");var c,u=(s.fanout-1n).toString(16).length,d=iu(l,(s=>qc(s,(s=>e._asyncToGenerator((function*(){var e=null!=s.Name?s.Name.substring(u):null;if(null!=e&&""!==e){var l=yield n(s.Hash,e,"".concat(r,"/").concat(e),[],i+1,o,a);return{entries:null==l.entry?[]:[l.entry]}}var c,d=yield o.get(s.Hash,a);return t=XB(d),null===(c=a.onProgress)||void 0===c||c.call(a,new Ah("unixfs:exporter:walk:hamt-sharded-directory",{cid:s.Hash})),{entries:pq(t,r,n,i,o,a)}}))))),(e=>MR(e,{ordered:!0,concurrency:a.blockReadConcurrency}))),h=!1,p=!1;try{for(var f,v=e._asyncIterator(d);h=!(f=yield e._awaitAsyncGenerator(v.next())).done;h=!1){var{entries:y}=f.value;yield*e._asyncGeneratorDelegate(e._asyncIterator(y),e._awaitAsyncGenerator)}}catch(e){p=!0,c=e}finally{try{h&&null!=v.return&&(yield e._awaitAsyncGenerator(v.return()))}finally{if(p)throw c}}})),fq.apply(this,arguments)}var vq,yq,gq,mq,wq={raw:hq,file:hq,directory:(t,r,n,i,o,a,s)=>{function l(){return l=e._wrapAsyncGenerator((function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(l,c,u){var d=null!==(l=n.offset)&&void 0!==l?l:0,h=null!==(c=n.length)&&void 0!==c?c:r.Links.length,p=r.Links.slice(d,h);null===(u=n.onProgress)||void 0===u||u.call(n,new Ah("unixfs:exporter:walk:directory",{cid:t})),yield*e._asyncGeneratorDelegate(e._asyncIterator(iu(p,(t=>qc(t,(t=>e._asyncToGenerator((function*(){var e,r=null!==(e=t.Name)&&void 0!==e?e:"",l="".concat(i,"/").concat(r);return(yield o(t.Hash,r,l,[],a+1,s,n)).entry}))))),(e=>MR(e,{ordered:!0,concurrency:n.blockReadConcurrency})),(e=>Cc(e,(e=>null!=e))))))}()})),l.apply(this,arguments)}return function(){return l.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 Ah("unixfs:exporter:walk:hamt-sharded-directory",{cid:e})),pq(t,n,i,o,a,s)},metadata:(e,t,r,n,i,o,a)=>()=>[],symlink:(e,t,r,n,i,o,a)=>()=>[]},bq=function(){var t=e._asyncToGenerator((function*(e,t,r,n,i,o,a,s){var l,c,u=XB(yield a.get(e,s));if(null==t&&(t=e.toString()),null==u.Data)throw new HV("no data in PBNode");try{l=Ez.unmarshal(u.Data)}catch(e){throw new HV(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 cq(u,n[0],a):((e,t)=>{var r=e.Links.find((e=>e.Name===t));return null==r?void 0:r.Hash})(u,n[0]),null==h)throw new VV("file does not exist");var p=n.shift();c={cid:h,toResolve:n,name:null!=p?p:"",path:"".concat(r,"/").concat(p)}}var f=wq[l.type](e,u,l,r,i,o,a);if(null==f)throw new VV("could not find content exporter");return l.isDirectory()?{entry:{type:"directory",name:t,path:r,cid:e,content:f,unixfs:l,depth:o,node:u,size:l.fileSize()},next:c}:{entry:{type:"file",name:t,path:r,cid:e,content:f,unixfs:l,depth:o,node:u,size:l.fileSize()},next:c}}));return function(e,r,n,i,o,a,s,l){return t.apply(this,arguments)}}(),_q={[ZB]:bq,[re]:oq,[uB]:ZV,[SB]:$V,[Te.code]:rq,[X]:nq},Sq=function(){var t=e._asyncToGenerator((function*(e,t,r,n,i,o,a){var s=_q[e.code];if(null==s)throw new qV("No resolver for code ".concat(e.code));return s(e,t,r,n,Sq,i,o,a)}));return function(e,r,n,i,o,a,s){return t.apply(this,arguments)}}(),Pq=e=>{if(e instanceof Uint8Array)return{cid:je.decode(e),toResolve:[]};var t=je.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:je.parse(r[0]),toResolve:r.slice(1)}}throw new zV("Unknown path type ".concat(e))};function Eq(e,t){return Aq.apply(this,arguments)}function Aq(){return Aq=e._wrapAsyncGenerator((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){for(var{cid:i,toResolve:o}=Pq(t),a=i.toString(),s=a,l=o.length;;){var c=yield e._awaitAsyncGenerator(Sq(i,a,s,o,l,r,n));if(null==c.entry&&null==c.next)throw new VV("Could not resolve ".concat(t));if(null!=c.entry&&(yield c.entry),null==c.next)return;o=c.next.toResolve,i=c.next.cid,a=c.next.name,s=c.next.path}}()})),Aq.apply(this,arguments)}function kq(e,t){return xq.apply(this,arguments)}function xq(){return xq=e._asyncToGenerator((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=yield UV(Eq(e,t,r));if(null==n)throw new VV("Could not resolve ".concat(e));return n})),xq.apply(this,arguments)}function Tq(e,t){return Iq.apply(this,arguments)}function Iq(){return Iq=e._wrapAsyncGenerator((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var i=yield e._awaitAsyncGenerator(kq(t,r,n));if(null!=i&&(yield i,"directory"===i.type)){var o,a=!1,s=!1;try{for(var l,c=e._asyncIterator(d(i,n));a=!(l=yield e._awaitAsyncGenerator(c.next())).done;a=!1){var u=l.value;yield u}}catch(e){s=!0,o=e}finally{try{a&&null!=c.return&&(yield e._awaitAsyncGenerator(c.return()))}finally{if(s)throw o}}}function d(e,t){return h.apply(this,arguments)}function h(){return h=e._wrapAsyncGenerator((function*(t,r){var n,i=!1,o=!1;try{for(var a,s=e._asyncIterator(t.content(r));i=!(a=yield e._awaitAsyncGenerator(s.next())).done;i=!1){var l=a.value;(yield l,l instanceof Uint8Array)||"directory"===l.type&&(yield*e._asyncGeneratorDelegate(e._asyncIterator(d(l,r)),e._awaitAsyncGenerator))}}catch(e){o=!0,n=e}finally{try{i&&null!=s.return&&(yield e._awaitAsyncGenerator(s.return()))}finally{if(o)throw n}}})),h.apply(this,arguments)}}()})),Iq.apply(this,arguments)}var Cq=function(){if(mq)return gq;mq=1;var e=yq?vq:(yq=1,vq=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=gq,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,u(e[r],t[r],i)):n(e,r,s(t[r])))})),e),c=(e,r,i)=>{var o=e.slice(0,0),c=0;return[e,r].forEach((r=>{for(var u=[],d=0;d<r.length;d++)t.call(r,d)&&(u.push(String(d)),n(o,c++,r===e?r[d]:s(r[d])));o=l(o,r,a(r).filter((e=>!u.includes(e))),i)})),o};function u(t,r,n){return n.concatArrays&&Array.isArray(t)&&Array.isArray(r)?c(t,r,n):e(r)&&e(t)?l(t,r,a(r),n):s(r)}return gq=function(){for(var t=u(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 c of a)if(void 0!==c){if(!e(c))throw new TypeError("`"+c+"` is not an Option Object");r=u(r,{_:c},t)}return r._},gq}(),Bq=e.getDefaultExportFromCjs(Cq);class Nq extends Error{constructor(t,r,n){super(t),e._defineProperty(this,"name",void 0),e._defineProperty(this,"code",void 0),this.name=r,this.code=n}}class Dq extends Nq{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"not a Unixfs node","NotUnixFSError","ERR_NOT_UNIXFS")}}class Gq extends Nq{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"invalid PBNode","InvalidPBNodeError","ERR_INVALID_PB_NODE")}}class Rq extends Nq{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"unknown error","InvalidPBNodeError","ERR_UNKNOWN_ERROR")}}class Oq extends Nq{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"path already exists","AlreadyExistsError","ERR_ALREADY_EXISTS")}}class Lq extends Nq{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"path does not exist","DoesNotExistError","ERR_DOES_NOT_EXIST")}}class Mq extends Nq{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no content","NoContentError","ERR_NO_CONTENT")}}class jq extends Nq{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"not a file","NotAFileError","ERR_NOT_A_FILE")}}class Fq extends Nq{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"not a directory","NotADirectoryError","ERR_NOT_A_DIRECTORY")}}class Uq extends Nq{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"invalid parameters","InvalidParametersError","ERR_INVALID_PARAMETERS")}}function zq(e){return function(t){return t instanceof Vq?t:new Vq(t,e)}}class Vq{constructor(t,r){if(e._defineProperty(this,"_value",void 0),e._defineProperty(this,"_hashFn",void 0),e._defineProperty(this,"_depth",void 0),e._defineProperty(this,"_availableBits",void 0),e._defineProperty(this,"_currentBufferIndex",void 0),e._defineProperty(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(t){var r=this;return e._asyncToGenerator((function*(){for(var e=t;r._availableBits<e;)yield r._produceMoreBits();for(var n=0;e>0;){var i=r._buffers[r._currentBufferIndex],o=Math.min(i.availableBits(),e);n=(n<<o)+i.take(o),e-=o,r._availableBits-=o,0===i.availableBits()&&r._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 t=this;return e._asyncToGenerator((function*(){t._depth++;var e=t._depth>0?mt([t._value,Uint8Array.from([t._depth])]):t._value,r=yield t._hashFn(e),n=new Kq(r);t._buffers.push(n),t._availableBits+=n.availableBits()}))()}}var qq=[255,254,252,248,240,224,192,128],Hq=[1,3,7,15,31,63,127,255];class Kq{constructor(t){e._defineProperty(this,"_value",void 0),e._defineProperty(this,"_currentBytePos",void 0),e._defineProperty(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)+Wq(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 Wq(e,t,r){var n=function(e,t){return qq[e]&Hq[Math.min(t+e-1,7)]}(t,r);return(e&n)>>>t}var Qq=BigInt($z.code);function Yq(e){return Jq.apply(this,arguments)}function Jq(){return Jq=e._asyncToGenerator((function*(e){return(yield $z.encode(e)).subarray(0,8).reverse()})),Jq.apply(this,arguments)}var Zq=function(){var t=e._asyncToGenerator((function*(t,r,n){null==n.codec&&(n.codec=eN);var i=yield De.digest(t),o=je.create(n.cidVersion,n.codec.code,i);return yield r.put(o,t,e._objectSpread2(e._objectSpread2({},n),{},{signal:n.signal})),o}));return function(e,r,n){return t.apply(this,arguments)}}();class $q{constructor(t,r){e._defineProperty(this,"options",void 0),e._defineProperty(this,"root",void 0),e._defineProperty(this,"dir",void 0),e._defineProperty(this,"path",void 0),e._defineProperty(this,"dirty",void 0),e._defineProperty(this,"flat",void 0),e._defineProperty(this,"parent",void 0),e._defineProperty(this,"parentKey",void 0),e._defineProperty(this,"unixfs",void 0),e._defineProperty(this,"mode",void 0),e._defineProperty(this,"mtime",void 0),e._defineProperty(this,"cid",void 0),e._defineProperty(this,"size",void 0),e._defineProperty(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 Xq extends $q{constructor(t,r){super(t,r),e._defineProperty(this,"_bucket",void 0),this._bucket=pV({hashFn:Yq,bits:8})}put(t,r){var n=this;return e._asyncToGenerator((function*(){n.cid=void 0,n.size=void 0,n.nodeSize=void 0,yield n._bucket.put(t,r)}))()}get(t){var r=this;return e._asyncToGenerator((function*(){return r._bucket.get(t)}))()}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}eachChildSeries(){var t=this;return e._wrapAsyncGenerator((function*(){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t._bucket.eachLeafSeries());n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var{key:s,value:l}=o.value;yield{key:s,child:l}}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw r}}}))()}estimateNodeSize(){return void 0!==this.nodeSize||(this.nodeSize=rH(this._bucket,this,this.options)),this.nodeSize}flush(t){var r=this;return e._wrapAsyncGenerator((function*(){var n,i=!1,o=!1;try{for(var a,s=e._asyncIterator(eH(r._bucket,t,r,r.options));i=!(a=yield e._awaitAsyncGenerator(s.next())).done;i=!1){var l=a.value;yield e._objectSpread2(e._objectSpread2({},l),{},{path:r.path})}}catch(e){o=!0,n=e}finally{try{i&&null!=s.return&&(yield e._awaitAsyncGenerator(s.return()))}finally{if(o)throw n}}}))()}}function eH(e,t,r,n){return tH.apply(this,arguments)}function tH(){return tH=e._wrapAsyncGenerator((function*(t,r,n,i){for(var o=t._children,a=[],s=0n,l=0;l<o.length;l++){var c=o.get(l);if(null!=c){var u=l.toString(16).toUpperCase().padStart(2,"0");if(c instanceof tV){var d,h=void 0,p=!1,f=!1;try{for(var v,y=e._asyncIterator(eH(c,r,null,i));p=!(v=yield e._awaitAsyncGenerator(y.next())).done;p=!1){h=v.value}}catch(e){f=!0,d=e}finally{try{p&&null!=y.return&&(yield e._awaitAsyncGenerator(y.return()))}finally{if(f)throw d}}if(null==h)throw new Error("Could not flush sharded directory, no sub-shard found");a.push({Name:u,Tsize:Number(h.size),Hash:h.cid}),s+=h.size}else if("function"==typeof c.value.flush){var g,m=c.value,w=void 0,b=!1,_=!1;try{for(var S,P=e._asyncIterator(m.flush(r));b=!(S=yield e._awaitAsyncGenerator(P.next())).done;b=!1){w=S.value,yield w}}catch(e){_=!0,g=e}finally{try{b&&null!=P.return&&(yield e._awaitAsyncGenerator(P.return()))}finally{if(_)throw g}}if(null==w)throw new Error("Did not flush dir");var E=u+c.key;a.push({Name:E,Tsize:Number(w.size),Hash:w.cid}),s+=w.size}else{var A=c.value;if(null==A.cid)continue;var k=u+c.key,x=A.size;a.push({Name:k,Tsize:Number(x),Hash:A.cid}),s+=BigInt(null!=x?x:0)}}}var T=Uint8Array.from(o.bitField().reverse()),I=new Ez({type:"hamt-sharded-directory",data:T,fanout:BigInt(t.tableSize()),hashType:Qq,mtime:null==n?void 0:n.mtime,mode:null==n?void 0:n.mode}),C=$B(YB({Data:I.marshal(),Links:a})),B=yield e._awaitAsyncGenerator(Zq(C,r,i)),N=BigInt(C.byteLength)+s;yield{cid:B,unixfs:I,size:N}})),tH.apply(this,arguments)}function rH(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 tV){var l=rH(a,null,r);i.push({Name:s,Tsize:Number(l),Hash:0===r.cidVersion?nH:iH})}else if("function"==typeof a.value.flush){var c=a.value.nodeSize();i.push({Name:s+a.key,Tsize:Number(c),Hash:0===r.cidVersion?nH:iH})}else{var u=a.value;if(null==u.cid)continue;var d=s+a.key,h=u.size;i.push({Name:d,Tsize:Number(h),Hash:u.cid})}}}var p=Uint8Array.from(n.bitField().reverse());return $B(YB({Data:new Ez({type:"hamt-sharded-directory",data:p,fanout:BigInt(e.tableSize()),hashType:Qq,mtime:null==t?void 0:t.mtime,mode:null==t?void 0:t.mode}).marshal(),Links:i})).length}var nH=je.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),iH=je.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi"),oH=ku("helia:unixfs:commands:utils:hamt-utils"),aH=e=>e.toString(16).toUpperCase().padStart(2,"0").substring(0,2),sH=function(){var t=e._asyncToGenerator((function*(e,t,r){for(var n=new Xq({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 UV(n.flush(e));if(null==o)throw new Error("Flushing shard yielded no result");return o}));return function(e,r,n){return t.apply(this,arguments)}}(),lH=function(){var t=e._asyncToGenerator((function*(e,t,r){var n,i,o,a=Ez.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=c===e.length-1,l=e[c],u=Uint8Array.from(l.children.bitField().reverse()),d=new Ez({type:"hamt-sharded-directory",data:u,fanout:s,hashType:Qq});n&&(d.mtime=a.mtime,d.mode=a.mode);var h=$B(YB(o={Data:d.marshal(),Links:l.node.Links}));if(i=yield Zq(h,t,r),!n){var p=e[c+1];if(null==p)throw new Error("Was not operating on shard root but also had no parent?");oH("updating link in parent sub-shard with prefix %s",p.prefix),p.node.Links=p.node.Links.filter((e=>e.Name!==p.prefix)),p.node.Links.push({Name:p.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)})}},c=0;c<e.length;c++)yield*l();if(null==i||null==o)throw new Error("Noting persisted");return{cid:i,node:o}}));return function(e,r,n){return t.apply(this,arguments)}}(),cH=function(){var t=e._asyncToGenerator((function*(e,t,r,n){for(var i=zq(Yq)(nt(t)),o=[];;){var a,s=XB(yield r.get(e,n)),l=new eV,c=yield i.take(8),u=aH(c);o.push({prefix:u,children:l,node:s});var d=void 0;for(var h of s.Links){var p,f=null!==(p=h.Name)&&void 0!==p?p:"";if(f.length<2)throw new Error("Invalid HAMT - link name was too short");var v=parseInt(f.substring(0,2),16);l.set(v,!0),f.startsWith(u)&&(d=h)}if(null==d){oH("no link found with prefix %s for %s",u,t);break}var y=null!==(a=d.Name)&&void 0!==a?a:"";if(y.length<2)throw new Error("Invalid HAMT - link name was too short");if(2!==y.length)break;e=d.Hash,oH("descend into sub-shard with prefix %s",y)}return{path:o,hash:i}}));return function(e,r,n,i){return t.apply(this,arguments)}}();function uH(e,t,r,n){return dH.apply(this,arguments)}function dH(){return dH=e._asyncToGenerator((function*(e,t,r,n){if(null==e.Data)throw new Error("DagPB node had no data");var i,o=Ez.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?iH.bytes.byteLength:nH.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 hH(e,0,r,t,n)}return i>r})),dH.apply(this,arguments)}function hH(e,t,r,n,i){return pH.apply(this,arguments)}function pH(){return pH=e._asyncToGenerator((function*(e,t,r,n,i){if(t>r)return r;if(null==e.Data)return t;if(!Ez.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===ZB){var l=XB(yield n.get(o.Hash,i));t+=(yield hH(l,t,r,n,i))}}return t})),pH.apply(this,arguments)}var fH=ku("helia:unixfs:components:utils:add-link");function vH(e,t,r,n){return yH.apply(this,arguments)}function yH(){return yH=e._asyncToGenerator((function*(e,t,r,n){if(null==e.node.Data)throw new Uq("Invalid parent passed to addLink");if("hamt-sharded-directory"===Ez.unmarshal(e.node.Data).type)return fH("adding link to sharded directory"),wH(e,t,r,n);fH("adding ".concat(t.Name," (").concat(t.Hash,") to regular directory"));var i=yield mH(e,t,r,n);if(yield uH(i.node,r,n.shardSplitThresholdBytes,n)){fH("converting directory to sharded directory");var o=yield gH(i,r);i.cid=o.cid,i.node=XB(yield r.get(o.cid,n))}return i})),yH.apply(this,arguments)}var gH=function(){var t=e._asyncToGenerator((function*(e,t){if(null==e.node.Data)throw new Uq("Invalid parent passed to convertToShardedDirectory");var r=Ez.unmarshal(e.node.Data),n=yield sH(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 fH("converted directory to sharded directory ".concat(n.cid)),n}));return function(e,r){return t.apply(this,arguments)}}(),mH=function(){var t=e._asyncToGenerator((function*(e,t,r,n){var i=e.node.Links.filter((e=>{var r=e.Name===t.Name;if(r&&!n.allowOverwriting)throw new Oq;return!r}));if(i.push(t),null==e.node.Data)throw new Gq("Parent node with no data passed to addToDirectory");var o,a=Ez.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=YB({Data:o,Links:i});var c=$B(e.node),u=yield De.digest(c),d=je.create(e.cid.version,ZB,u);return yield r.put(d,c),{node:e.node,cid:d}}));return function(e,r,n,i){return t.apply(this,arguments)}}(),wH=function(){var t=e._asyncToGenerator((function*(e,t,r,n){var{path:i,hash:o}=yield cH(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);fH("next prefix for %s is %s",t.Name,s);var c,u="".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(fH("link %s was present in shard",u),d.Name===u){if(!n.allowOverwriting)throw new Oq;fH("overwriting %s in sub-shard",t.Name),a.node.Links=a.node.Links.filter((e=>e.Name!==u)),a.node.Links.push({Name:u,Hash:t.Hash,Tsize:t.Tsize})}else{if(2===(null===(c=d.Name)||void 0===c?void 0:c.length))throw new Error("Existing link was sub-shard?!");var h;fH("prefix %s already exists, creating new sub-shard",s);for(var p=a.node.Links.findIndex((e=>{var t;return null===(t=e.Name)||void 0===t?void 0:t.startsWith(s)})),f=a.node.Links.splice(p,1)[0],v=(null!==(h=f.Name)&&void 0!==h?h:"").substring(2),y=zq(Yq)(nt(v)),g=0;g<i.length;g++)yield y.take(8);for(;;){var m=yield y.take(8),w=aH(m);f.Name="".concat(w).concat(v);var b=yield o.take(8),_=aH(b);if(w!==_){var S=new eV;S.set(b,!0),S.set(m,!0),i.push({prefix:s,children:S,node:{Links:[f,{Name:"".concat(_).concat(t.Name),Hash:t.Hash,Tsize:t.Tsize}]}});break}var P=new eV;P.set(b,!0),i.push({prefix:_,children:P,node:{Links:[]}})}}else fH("link %s was not present in sub-shard",u),t.Name=u,a.node.Links.push(t),a.children.set(l,!0),fH("adding %s to existing sub-shard",u);return lH(i,r,n)}));return function(e,r,n,i){return t.apply(this,arguments)}}();function bH(e,t){return _H.apply(this,arguments)}function _H(){return _H=e._asyncToGenerator((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=yield kq(e,t,r);if("directory"!==n.type)throw new Fq("".concat(e.toString()," was not a UnixFS directory"));return{cid:e,node:n.node}})),_H.apply(this,arguments)}function SH(e,t,r,n){return PH.apply(this,arguments)}function PH(){return PH=e._asyncToGenerator((function*(e,t,r,n){var i,o,a=yield kq(e,r,n);if("directory"!==a.type&&"file"!==a.type&&"raw"!==a.type)throw new Dq("".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),$B(i).byteLength+o),Hash:e}})),PH.apply(this,arguments)}var EH=ku("helia:unixfs:components:utils:resolve");function AH(e,t,r,n){return kH.apply(this,arguments)}function kH(){return kH=e._asyncToGenerator((function*(e,t,r,n){if(null==t||""===t)return{cid:e};var i="/ipfs/".concat(e).concat(null==t?"":"/".concat(t)),o=yield Bc(Eq(i,r,n));if(0===o.length)throw new Lq("Could not find path in directory");return EH("resolved %s to %c",t,e),{cid:o[o.length-1].cid,path:t,segments:o}})),kH.apply(this,arguments)}function xH(e,t,r,n){return TH.apply(this,arguments)}function TH(){return TH=e._asyncToGenerator((function*(t,r,n,i){if(null==r.segments||0===r.segments.length)return t;var o=r.segments.pop();if(null==o)throw new Error("Insufficient segments");for(var a of(o.cid=t,r.segments.reverse(),r.segments)){var[s,l]=yield Promise.all([bH(a.cid,n,i),SH(o.cid,o.name,n,i)]);t=(yield vH(s,l,n,e._objectSpread2(e._objectSpread2({},i),{},{allowOverwriting:!0,cidVersion:t.version}))).cid,a.cid=t,o=a}return t})),TH.apply(this,arguments)}var IH=Bq.bind({ignoreUndefined:!0}),CH={};function BH(){return BH=e._wrapAsyncGenerator((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var i=IH(CH,n),o=yield e._awaitAsyncGenerator(AH(t,i.path,r,i)),a=yield e._awaitAsyncGenerator(kq(o.cid,r,i));if("file"!==a.type&&"raw"!==a.type)throw new jq;if(null==a.content)throw new Mq;yield*e._asyncGeneratorDelegate(e._asyncIterator(a.content(i)))}()})),BH.apply(this,arguments)}var NH=262144,DH=Bq.bind({ignoreUndefined:!0}),GH=ku("helia:unixfs:chmod"),RH={recursive:!1,shardSplitThresholdBytes:NH};function OH(){return OH=e._asyncToGenerator((function*(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},o=DH(RH,i),a=yield AH(t,o.path,n,i);if(GH("chmod %c %d",a.cid,r),o.recursive){var s=yield iu(e._wrapAsyncGenerator((function*(){var t,o=!1,s=!1;try{for(var l,c=e._asyncIterator(Tq(a.cid,n,i));o=!(l=yield e._awaitAsyncGenerator(c.next())).done;o=!1){var u=l.value,d=void 0,h=[];if("raw"===u.type)d=new Ez({type:"file",data:u.node});else{if("file"!==u.type&&"directory"!==u.type)throw new Dq;d=u.unixfs,h=u.node.Links}d.mode=r;var p={Data:d.marshal(),Links:h};yield{path:u.path,content:p}}}catch(e){s=!0,t=e}finally{try{o&&null!=c.return&&(yield e._awaitAsyncGenerator(c.return()))}finally{if(s)throw t}}})),(r=>{return TV(r,n,e._objectSpread2(e._objectSpread2({},o),{},{dagBuilder:(i=e._wrapAsyncGenerator((function*(r,n){var i,a=!1,s=!1;try{for(var l,c=function*(){var r=l.value;yield e._asyncToGenerator((function*(){var i=r.content,a=$B(i),s=yield Zq(a,n,e._objectSpread2(e._objectSpread2({},o),{},{cidVersion:t.version}));if(null==i.Data)throw new Gq("".concat(s," had no data"));var l=Ez.unmarshal(i.Data);return{cid:s,size:BigInt(a.length),path:r.path,unixfs:l}}))},u=e._asyncIterator(r);a=!(l=yield e._awaitAsyncGenerator(u.next())).done;a=!1)yield*c()}catch(e){s=!0,i=e}finally{try{a&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(s)throw i}}})),function(e,t){return i.apply(this,arguments)})}));var i}),function(){var t=e._asyncToGenerator((function*(e){return UV(e)}));return function(e){return t.apply(this,arguments)}}());if(null==s)throw new Rq("Could not chmod ".concat(a.cid.toString()));return xH(s.cid,a,n,o)}var l,c=yield n.get(a.cid,i),u=[];if(a.cid.code===re)l=new Ez({type:"file",data:c});else{var d=XB(c);if(null==d.Data)throw new Gq("".concat(a.cid.toString()," had no data"));u=d.Links,l=Ez.unmarshal(d.Data)}l.mode=r;var h=$B({Data:l.marshal(),Links:u}),p=yield De.digest(h),f=je.create(a.cid.version,ZB,p);return yield n.put(f,h),xH(f,a,n,o)})),OH.apply(this,arguments)}var LH=Bq.bind({ignoreUndefined:!0}),MH=ku("helia:unixfs:cp"),jH={force:!1,shardSplitThresholdBytes:NH};function FH(){return FH=e._asyncToGenerator((function*(t,r,n,i){var o=LH(jH,arguments.length>4&&void 0!==arguments[4]?arguments[4]:{});if(n.includes("/"))throw new Uq("Name must not have slashes");var[a,s]=yield Promise.all([bH(r,i,o),SH(t,n,i,o)]);return MH('Adding %c as "%s" to %c',t,n,r),(yield vH(a,s,i,e._objectSpread2({allowOverwriting:o.force,cidVersion:r.version},o))).cid})),FH.apply(this,arguments)}var UH=Bq.bind({ignoreUndefined:!0}),zH={};function VH(){return VH=e._wrapAsyncGenerator((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var i=UH(zH,n),o=yield e._awaitAsyncGenerator(AH(t,i.path,r,i)),a=yield e._awaitAsyncGenerator(kq(o.cid,r));if("file"!==a.type&&"raw"!==a.type){if(null==a.content)throw new Mq;if("directory"!==a.type)throw new Fq;yield*e._asyncGeneratorDelegate(e._asyncIterator(a.content({offset:n.offset,length:n.length})))}else yield a}()})),VH.apply(this,arguments)}var qH=Bq.bind({ignoreUndefined:!0}),HH=ku("helia:unixfs:mkdir"),KH={cidVersion:1,force:!1,shardSplitThresholdBytes:NH};function WH(){return WH=e._asyncToGenerator((function*(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},o=qH(KH,i);if(r.includes("/"))throw new Uq("Path must not have slashes");if("directory"!==(yield kq(t,n,i)).type)throw new Fq("".concat(t.toString()," was not a UnixFS directory"));HH("creating %s",r);var a=$B({Data:new Ez({type:"directory",mode:o.mode,mtime:o.mtime}).marshal(),Links:[]}),s=yield De.digest(a),l=je.create(o.cidVersion,ZB,s);yield n.put(l,a);var[c,u]=yield Promise.all([bH(t,n,o),SH(l,r,n,o)]);return HH("adding empty dir called %s to %c",r,t),(yield vH(c,u,n,e._objectSpread2(e._objectSpread2({},o),{},{allowOverwriting:o.force}))).cid})),WH.apply(this,arguments)}var QH=ku("helia:unixfs:utils:remove-link");function YH(){return YH=e._asyncToGenerator((function*(e,t,r,n){if(null==e.node.Data)throw new Gq("Parent node had no data");if("hamt-sharded-directory"===Ez.unmarshal(e.node.Data).type){QH("removing ".concat(t," from sharded directory"));var i=yield ZH(e,t,r,n);return(yield uH(i.node,r,n.shardSplitThresholdBytes,n))?i:(QH("converting shard to flat directory %c",e.cid),$H(i,r,n))}return QH("removing link ".concat(t," regular directory")),JH(e,t,r,n)})),YH.apply(this,arguments)}var JH=function(){var t=e._asyncToGenerator((function*(t,r,n,i){t.node.Links=t.node.Links.filter((e=>e.Name!==r));var o=$B(t.node),a=yield Zq(o,n,e._objectSpread2(e._objectSpread2({},i),{},{cidVersion:t.cid.version}));return QH("Updated regular directory ".concat(a)),{node:t.node,cid:a}}));return function(e,r,n,i){return t.apply(this,arguments)}}(),ZH=function(){var t=e._asyncToGenerator((function*(e,t,r,n){var{path:i}=yield cH(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 c=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*c()););return lH(i,r,n)}));return function(e,r,n,i){return t.apply(this,arguments)}}(),$H=function(){var t=e._asyncToGenerator((function*(t,r,n){if(null==t.node.Data)throw new Uq("Invalid parent passed to convertToFlatDirectory");var i={Links:[]},o=yield kq(t.cid,r);if("directory"!==o.type)throw new Error("Unexpected node type");var a,s=!1,l=!1;try{for(var c,u=e._asyncIterator(o.content());s=!(c=yield u.next()).done;s=!1){var d=c.value,h=0;h=d.node instanceof Uint8Array?d.node.byteLength:$B(d.node).length,i.Links.push({Hash:d.cid,Name:d.name,Tsize:h})}}catch(e){l=!0,a=e}finally{try{s&&null!=u.return&&(yield u.return())}finally{if(l)throw a}}var p=Ez.unmarshal(t.node.Data);i.Data=new Ez({type:"directory",mode:p.mode,mtime:p.mtime}).marshal();var f=$B(YB(i));return{cid:yield Zq(f,r,{codec:eN,cidVersion:t.cid.version,signal:n.signal}),node:i}}));return function(e,r,n){return t.apply(this,arguments)}}(),XH=Bq.bind({ignoreUndefined:!0}),eK=ku("helia:unixfs:rm"),tK={shardSplitThresholdBytes:NH};function rK(){return rK=e._asyncToGenerator((function*(t,r,n){var i=XH(tK,arguments.length>3&&void 0!==arguments[3]?arguments[3]:{});if(r.includes("/"))throw new Uq("Name must not have slashes");var o=yield bH(t,n,i);eK("Removing %s from %c",r,t);var a=yield function(e,t,r,n){return YH.apply(this,arguments)}(o,r,n,e._objectSpread2(e._objectSpread2({},i),{},{cidVersion:t.version}));return a.cid})),rK.apply(this,arguments)}var nK=Bq.bind({ignoreUndefined:!0}),iK=ku("helia:unixfs:stat"),oK={};function aK(){return aK=e._asyncToGenerator((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=nK(oK,r),i=yield AH(e,r.path,t,n);iK("stat %c",i.cid);var o=yield kq(i.cid,t,n);if("file"!==o.type&&"directory"!==o.type&&"raw"!==o.type)throw new Dq;var a,s,l,c=0n,u=0n,d=0n,h=0n,p=0,f=o.type;if("raw"===o.type&&(c=BigInt(o.node.byteLength),u=BigInt(o.node.byteLength),d=BigInt(o.node.byteLength),h=BigInt(o.node.byteLength),p=1),"directory"===o.type&&(c=0n,d=0n,h=u=BigInt(o.unixfs.marshal().byteLength),p=1,a=o.unixfs.mode,s=o.unixfs.mtime,l=o.unixfs),"file"===o.type){var v,y,g=yield sK(i.cid,t,n);c=o.unixfs.fileSize(),u=BigInt((null!==(v=null===(y=o.node.Data)||void 0===y?void 0:y.byteLength)&&void 0!==v?v:0)+o.node.Links.reduce(((e,t)=>{var r;return e+(null!==(r=t.Tsize)&&void 0!==r?r:0)}),0)),d=BigInt(g.localFileSize),h=BigInt(g.localDagSize),p=g.blocks,a=o.unixfs.mode,s=o.unixfs.mtime,l=o.unixfs}return{cid:i.cid,mode:a,mtime:s,fileSize:c,dagSize:u,localFileSize:d,localDagSize:h,blocks:p,type:f,unixfs:l}})),aK.apply(this,arguments)}function sK(e,t,r){return lK.apply(this,arguments)}function lK(){return lK=e._asyncToGenerator((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===re)n.localFileSize+=i.byteLength;else{if(e.code!==ZB)throw new Rq("".concat(e.toString()," was neither DAG_PB nor RAW"));var o=XB(i);if(o.Links.length>0)for(var a of o.Links){var s=yield sK(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 Gq("PBNode ".concat(e.toString()," had no data"));var c=Ez.unmarshal(o.Data);if(null==c.data)throw new Gq("UnixFS node ".concat(e.toString()," had no data"));n.localFileSize+=null!==(l=c.data.byteLength)&&void 0!==l?l:0}}}return n})),lK.apply(this,arguments)}var cK=Bq.bind({ignoreUndefined:!0}),uK=ku("helia:unixfs:touch"),dK={recursive:!1,shardSplitThresholdBytes:NH};function hK(){return hK=e._asyncToGenerator((function*(t,r){var n,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=cK(dK,i),a=yield AH(t,o.path,r,o),s=null!==(n=o.mtime)&&void 0!==n?n:{secs:BigInt(Math.round(Date.now()/1e3)),nsecs:0};if(uK("touch %c %o",a.cid,s),o.recursive){var l=yield iu(e._wrapAsyncGenerator((function*(){var t,n=!1,i=!1;try{for(var o,l=e._asyncIterator(Tq(a.cid,r));n=!(o=yield e._awaitAsyncGenerator(l.next())).done;n=!1){var c=o.value,u=void 0,d=void 0;if("raw"===c.type)u=new Ez({data:c.node}),d=[];else{if("file"!==c.type&&"directory"!==c.type)throw new Dq;u=c.unixfs,d=c.node.Links}u.mtime=s;var h={Data:u.marshal(),Links:d};yield{path:c.path,content:h}}}catch(e){i=!0,t=e}finally{try{n&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(i)throw t}}})),(n=>{return TV(n,r,e._objectSpread2(e._objectSpread2({},o),{},{dagBuilder:(i=e._wrapAsyncGenerator((function*(r,n){var i,a=!1,s=!1;try{for(var l,c=function*(){var r=l.value;yield e._asyncToGenerator((function*(){var i=r.content,a=$B(i),s=yield Zq(a,n,e._objectSpread2(e._objectSpread2({},o),{},{cidVersion:t.version}));if(null==i.Data)throw new Gq("".concat(s," had no data"));var l=Ez.unmarshal(i.Data);return{cid:s,size:BigInt(a.length),path:r.path,unixfs:l}}))},u=e._asyncIterator(r);a=!(l=yield e._awaitAsyncGenerator(u.next())).done;a=!1)yield*c()}catch(e){s=!0,i=e}finally{try{a&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(s)throw i}}})),function(e,t){return i.apply(this,arguments)})}));var i}),function(){var t=e._asyncToGenerator((function*(e){return UV(e)}));return function(e){return t.apply(this,arguments)}}());if(null==l)throw new Rq("Could not chmod ".concat(a.cid.toString()));return xH(l.cid,a,r,o)}var c,u=yield r.get(a.cid,i),d=[];if(a.cid.code===re)c=new Ez({data:u});else{var h=XB(u);if(d=h.Links,null==h.Data)throw new Gq("".concat(a.cid.toString()," had no data"));c=Ez.unmarshal(h.Data)}c.mtime=s;var p=$B({Data:c.marshal(),Links:d}),f=yield De.digest(p),v=je.create(a.cid.version,ZB,f);return yield r.put(v,p),xH(v,a,r,o)})),hK.apply(this,arguments)}class pK{constructor(t){e._defineProperty(this,"components",void 0),this.components=t}addAll(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(function(e,t){return OV.apply(this,arguments)}(t,r.components.blockstore,n)))}()})).apply(this,arguments)}addBytes(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};return function(e,t){return LV.apply(this,arguments)}(t,n.components.blockstore,e)}))()}addByteStream(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};return function(e,t){return MV.apply(this,arguments)}(t,n.components.blockstore,e)}))()}addFile(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};return function(e,t){return jV.apply(this,arguments)}(t,n.components.blockstore,e)}))()}addDirectory(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e=t.length>1&&void 0!==t[1]?t[1]:{};return function(e,t){return FV.apply(this,arguments)}(t.length>0&&void 0!==t[0]?t[0]:{},r.components.blockstore,e)}))()}cat(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(function(e,t){return BH.apply(this,arguments)}(t,r.components.blockstore,n)))}()})).apply(this,arguments)}chmod(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var e=n.length>2&&void 0!==n[2]?n[2]:{};return function(e,t,r){return OH.apply(this,arguments)}(t,r,i.components.blockstore,e)}))()}cp(t,r,n){var i=arguments,o=this;return e._asyncToGenerator((function*(){var e=i.length>3&&void 0!==i[3]?i[3]:{};return function(e,t,r,n){return FH.apply(this,arguments)}(t,r,n,o.components.blockstore,e)}))()}ls(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(function(e,t){return VH.apply(this,arguments)}(t,r.components.blockstore,n)))}()})).apply(this,arguments)}mkdir(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var e=n.length>2&&void 0!==n[2]?n[2]:{};return function(e,t,r){return WH.apply(this,arguments)}(t,r,i.components.blockstore,e)}))()}rm(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var e=n.length>2&&void 0!==n[2]?n[2]:{};return function(e,t,r){return rK.apply(this,arguments)}(t,r,i.components.blockstore,e)}))()}stat(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};return function(e,t){return aK.apply(this,arguments)}(t,n.components.blockstore,e)}))()}touch(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};return function(e,t){return hK.apply(this,arguments)}(t,n.components.blockstore,e)}))()}}class fK{constructor(t){e._defineProperty(this,"components",void 0),this.components=t}add(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e,i=r.length>1&&void 0!==r[1]?r[1]:{},o=dB(t),a=yield(null!==(e=i.hasher)&&void 0!==e?e:De).digest(o),s=je.createV1(uB,a);return yield n.components.blockstore.put(s,o,i),s}))()}get(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{},i=yield n.components.blockstore.get(t,e);return hB(i)}))()}}exports.BaseBlockstore=Tu,exports.BaseDatastore=Gc,exports.CID=je,exports.DeleteFailedError=jc,exports.EventEmitter=To,exports.GetFailedError=Mc,exports.Hash=Gr,exports.Key=xc,exports.NotFoundError=Uc,exports.OpenFailedError=Rc,exports.PutFailedError=Lc,exports.Uint8ArrayList=Oa,exports.__asyncGenerator=function(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,c)}})),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 Lo?Promise.resolve(r.value.v).then(l,c):u(o[0][2],r)}catch(e){u(o[0][3],e)}var r}function l(e){s("next",e)}function c(e){s("throw",e)}function u(e,t){e(t),o.shift(),o.length&&s(o[0][0],o[0][1])}},exports.__asyncValues=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=Go(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)}))}}},exports.__await=Lo,exports.__awaiter=No,exports.__classPrivateFieldGet=function(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)},exports.__extends=Co,exports.__generator=Do,exports.__read=Ro,exports.__spreadArray=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))},exports.__values=Go,exports.abytes=sr,exports.add=$r,exports.add3H=en,exports.add3L=Xr,exports.aexists=cr,exports.anumber=ar,exports.aoutput=ur,exports.autoNAT=qG,exports.base32=k,exports.base32upper=x,exports.base58btc=j,exports.bases=qe,exports.bitswap=bN,exports.bytesToHex=function(e){if(sr(e),wr)return e.toHex();for(var t="",r=0;r<e.length;r++)t+=br[e[r]];return t},exports.bytesToHex$1=Tn,exports.circuitRelayTransport=Zh,exports.clean=dr,exports.code=re,exports.code$1=uB,exports.compare=function(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},exports.concat=mt,exports.concatBytes=Dr,exports.createHasher=Rr,exports.createHelia=function(){return dz.apply(this,arguments)},exports.createLibp2p=lz,exports.createOptHasher=function(e){var t=(t,r)=>e(r).update(Br(t)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t},exports.createView=hr,exports.dagCbor=function(e){return new fK(e)},exports.dcutr=OR,exports.decode=Ae,exports.decode$1=hB,exports.decode$2=gt,exports.ed25519=go,exports.encode=dB,exports.encodingLength=pt,exports.filter=Cc,exports.fromBig=qr,exports.generateKeyPair=Ol,exports.hexToBytes=function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(wr)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},exports.hexToBytes$1=On,exports.hmac=mn,exports.identify=WR,exports.identifyPush=QR,exports.identity=Te,exports.isMultiaddr=rr,exports.isName=function(e){return!!rr(e)&&e.protos().some((e=>e.resolvable))},exports.mod=oi,exports.multiaddr=nr,exports.name=cB,exports.nanoid=jh,exports.noise=Wk,exports.pbkdf2Async=Po,exports.peerIdFromMultihash=tc,exports.peerIdFromPrivateKey=ec,exports.peerIdFromPublicKey=Xl,exports.peerIdFromString=$l,exports.ping=rj,exports.pipe=iu,exports.privateKeyFromProtobuf=Ul,exports.privateKeyFromRaw=zl,exports.privateKeyToProtobuf=Vl,exports.publicKeyFromProtobuf=Ml,exports.publicKeyFromRaw=function(e){var t,r;if(32===e.byteLength)return _s(e);if(33===e.byteLength)return Gl(e);var n=Ua(e),i=null===(t=n[1])||void 0===t?void 0:t[0];if(i===Qa||i===Ya||i===Ja)return ds(n);if("1.2.840.113549.1.1.1"===(null===(r=n[0])||void 0===r?void 0:r[0]))return El(n,e);throw new Jo("Could not extract public key from raw bytes")},exports.publicKeyToProtobuf=Fl,exports.pushable=Yc,exports.raceSignal=Zc,exports.randomBytes=Or,exports.registry=Lt,exports.ripemd160=_c,exports.rotlBH=(e,t,r)=>t<<r-32|e>>>64-r,exports.rotlBL=(e,t,r)=>e<<r-32|t>>>64-r,exports.rotlSH=(e,t,r)=>e<<r|t>>>32-r,exports.rotlSL=(e,t,r)=>t<<r|e>>>32-r,exports.rotr32H=(e,t)=>t,exports.rotr32L=(e,t)=>e,exports.rotrBH=Jr,exports.rotrBL=Zr,exports.rotrSH=Qr,exports.rotrSL=Yr,exports.secp256k1=Wi,exports.sha256=vn,exports.sha256$1=De,exports.sha512=yn,exports.sha512$1=bo,exports.sort=Nc,exports.split=Hr,exports.swap32IfBE=mr,exports.swap8IfBE=gr,exports.toBytes=Br,exports.toString=Ze,exports.u32=function(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))},exports.unixfs=function(e){return new pK(e)},exports.utf8ToBytes=Cr,exports.webRTC=sx,exports.webRTCDirect=ax,exports.yamux=MG;
|