web-dc-api 0.1.8 โ†’ 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- import{e,j as t,g as r,d as n,f as i,_ as o,k as a,l as s,m as l,n as u,o as c,c as d,b as h,p as v,q as p,h as f,r as g,s as y,t as m,u as w}from"./babel-tools-sSecqeD4.js";var b=new Uint8Array(0);function S(e){var t=e.match(/../g);return null!=t?new Uint8Array(t.map((e=>parseInt(e,16)))):b}function E(e){if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}var k=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<e.length;i++){var o=e.charAt(i),a=o.charCodeAt(0);if(255!==r[a])throw new TypeError(o+" is ambiguous");r[a]=i}var s=e.length,l=e.charAt(0),u=Math.log(s)/Math.log(256),c=Math.log(256)/Math.log(s);function d(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var n=0,i=0;e[t]===l;)n++,t++;for(var o=(e.length-t)*u+1>>>0,a=new Uint8Array(o);e[t];){var c=r[e.charCodeAt(t)];if(255===c)return;for(var d=0,h=o-1;(0!==c||d<i)&&-1!==h;h--,d++)c+=s*a[h]>>>0,a[h]=c%256>>>0,c=c/256>>>0;if(0!==c)throw new Error("Non-zero carry");i=d,t++}if(" "!==e[t]){for(var v=o-i;v!==o&&0===a[v];)v++;for(var p=new Uint8Array(n+(o-v)),f=n;v!==o;)p[f++]=a[v++];return p}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,i=0,o=t.length;i!==o&&0===t[i];)i++,r++;for(var a=(o-i)*c+1>>>0,u=new Uint8Array(a);i!==o;){for(var d=t[i],h=0,v=a-1;(0!==d||h<n)&&-1!==v;v--,h++)d+=256*u[v]>>>0,u[v]=d%s>>>0,d=d/s>>>0;if(0!==d)throw new Error("Non-zero carry");n=h,i++}for(var p=a-n;p!==a&&0===u[p];)p++;for(var f=l.repeat(r);p<a;++p)f+=e.charAt(u[p]);return f},decodeUnsafe:d,decode:function(e){var r=d(e);if(r)return r;throw new Error("Non-".concat(t," character"))}}},x=k;let A=class{constructor(t,r,n){e(this,"name",void 0),e(this,"prefix",void 0),e(this,"baseEncode",void 0),this.name=t,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return"".concat(this.prefix).concat(this.baseEncode(e));throw Error("Unknown type, must be binary type")}},C=class{constructor(t,r,n){e(this,"name",void 0),e(this,"prefix",void 0),e(this,"baseDecode",void 0),e(this,"prefixCodePoint",void 0),this.name=t,this.prefix=r;var i=r.codePointAt(0);if(void 0===i)throw new Error("Invalid prefix character");this.prefixCodePoint=i,this.baseDecode=n}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error("Unable to decode multibase string ".concat(JSON.stringify(e),", ").concat(this.name," decoder only supports inputs prefixed with ").concat(this.prefix));return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return T(this,e)}};class I{constructor(t){e(this,"decoders",void 0),this.decoders=t}or(e){return T(this,e)}decode(e){var t=e[0],r=this.decoders[t];if(null!=r)return r.decode(e);throw RangeError("Unable to decode multibase string ".concat(JSON.stringify(e),", only inputs prefixed with ").concat(Object.keys(this.decoders)," are supported"))}}function T(e,r){var n,i;return new I(t(t({},null!==(n=e.decoders)&&void 0!==n?n:{[e.prefix]:e}),null!==(i=r.decoders)&&void 0!==i?i:{[r.prefix]:r}))}class P{constructor(t,r,n,i){e(this,"name",void 0),e(this,"prefix",void 0),e(this,"baseEncode",void 0),e(this,"baseDecode",void 0),e(this,"encoder",void 0),e(this,"decoder",void 0),this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new A(t,r,n),this.decoder=new C(t,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function _(e){var{name:t,prefix:r,encode:n,decode:i}=e;return new P(t,r,n,i)}function B(e){var{name:t,prefix:r,alphabet:n}=e,{encode:i,decode:o}=x(n,t);return _({prefix:r,name:t,encode:i,decode:e=>E(o(e))})}function N(e){var{name:t,prefix:r,bitsPerChar:n,alphabet:i}=e,o=function(e){for(var t={},r=0;r<e.length;++r)t[e[r]]=r;return t}(i);return _({prefix:r,name:t,encode:e=>function(e,t,r){for(var n="="===t[t.length-1],i=(1<<r)-1,o="",a=0,s=0,l=0;l<e.length;++l)for(s=s<<8|e[l],a+=8;a>r;)o+=t[i&s>>(a-=r)];if(0!==a&&(o+=t[i&s<<r-a]),n)for(;o.length*r&7;)o+="=";return o}(e,i,n),decode:e=>function(e,t,r,n){for(var i=e.length;"="===e[i-1];)--i;for(var o=new Uint8Array(i*r/8|0),a=0,s=0,l=0,u=0;u<i;++u){var c=t[e[u]];if(void 0===c)throw new SyntaxError("Non-".concat(n," character"));s=s<<r|c,(a+=r)>=8&&(a-=8,o[l++]=255&s>>a)}if(a>=r||255&s<<8-a)throw new SyntaxError("Unexpected end of data");return o}(e,o,n,t)})}var D=B({prefix:"9",name:"base10",alphabet:"0123456789"}),R=Object.freeze({__proto__:null,base10:D}),O=N({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),L=N({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),M=Object.freeze({__proto__:null,base16:O,base16upper:L}),U=N({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),F=Object.freeze({__proto__:null,base2:U}),z=Array.from("๐Ÿš€๐Ÿชโ˜„๐Ÿ›ฐ๐ŸŒŒ๐ŸŒ‘๐ŸŒ’๐ŸŒ“๐ŸŒ”๐ŸŒ•๐ŸŒ–๐ŸŒ—๐ŸŒ˜๐ŸŒ๐ŸŒ๐ŸŒŽ๐Ÿ‰โ˜€๐Ÿ’ป๐Ÿ–ฅ๐Ÿ’พ๐Ÿ’ฟ๐Ÿ˜‚โค๐Ÿ˜๐Ÿคฃ๐Ÿ˜Š๐Ÿ™๐Ÿ’•๐Ÿ˜ญ๐Ÿ˜˜๐Ÿ‘๐Ÿ˜…๐Ÿ‘๐Ÿ˜๐Ÿ”ฅ๐Ÿฅฐ๐Ÿ’”๐Ÿ’–๐Ÿ’™๐Ÿ˜ข๐Ÿค”๐Ÿ˜†๐Ÿ™„๐Ÿ’ช๐Ÿ˜‰โ˜บ๐Ÿ‘Œ๐Ÿค—๐Ÿ’œ๐Ÿ˜”๐Ÿ˜Ž๐Ÿ˜‡๐ŸŒน๐Ÿคฆ๐ŸŽ‰๐Ÿ’žโœŒโœจ๐Ÿคท๐Ÿ˜ฑ๐Ÿ˜Œ๐ŸŒธ๐Ÿ™Œ๐Ÿ˜‹๐Ÿ’—๐Ÿ’š๐Ÿ˜๐Ÿ’›๐Ÿ™‚๐Ÿ’“๐Ÿคฉ๐Ÿ˜„๐Ÿ˜€๐Ÿ–ค๐Ÿ˜ƒ๐Ÿ’ฏ๐Ÿ™ˆ๐Ÿ‘‡๐ŸŽถ๐Ÿ˜’๐Ÿคญโฃ๐Ÿ˜œ๐Ÿ’‹๐Ÿ‘€๐Ÿ˜ช๐Ÿ˜‘๐Ÿ’ฅ๐Ÿ™‹๐Ÿ˜ž๐Ÿ˜ฉ๐Ÿ˜ก๐Ÿคช๐Ÿ‘Š๐Ÿฅณ๐Ÿ˜ฅ๐Ÿคค๐Ÿ‘‰๐Ÿ’ƒ๐Ÿ˜ณโœ‹๐Ÿ˜š๐Ÿ˜๐Ÿ˜ด๐ŸŒŸ๐Ÿ˜ฌ๐Ÿ™ƒ๐Ÿ€๐ŸŒท๐Ÿ˜ป๐Ÿ˜“โญโœ…๐Ÿฅบ๐ŸŒˆ๐Ÿ˜ˆ๐Ÿค˜๐Ÿ’ฆโœ”๐Ÿ˜ฃ๐Ÿƒ๐Ÿ’โ˜น๐ŸŽŠ๐Ÿ’˜๐Ÿ˜ โ˜๐Ÿ˜•๐ŸŒบ๐ŸŽ‚๐ŸŒป๐Ÿ˜๐Ÿ–•๐Ÿ’๐Ÿ™Š๐Ÿ˜น๐Ÿ—ฃ๐Ÿ’ซ๐Ÿ’€๐Ÿ‘‘๐ŸŽต๐Ÿคž๐Ÿ˜›๐Ÿ”ด๐Ÿ˜ค๐ŸŒผ๐Ÿ˜ซโšฝ๐Ÿค™โ˜•๐Ÿ†๐Ÿคซ๐Ÿ‘ˆ๐Ÿ˜ฎ๐Ÿ™†๐Ÿป๐Ÿƒ๐Ÿถ๐Ÿ’๐Ÿ˜ฒ๐ŸŒฟ๐Ÿงก๐ŸŽโšก๐ŸŒž๐ŸŽˆโŒโœŠ๐Ÿ‘‹๐Ÿ˜ฐ๐Ÿคจ๐Ÿ˜ถ๐Ÿค๐Ÿšถ๐Ÿ’ฐ๐Ÿ“๐Ÿ’ข๐ŸคŸ๐Ÿ™๐Ÿšจ๐Ÿ’จ๐Ÿคฌโœˆ๐ŸŽ€๐Ÿบ๐Ÿค“๐Ÿ˜™๐Ÿ’Ÿ๐ŸŒฑ๐Ÿ˜–๐Ÿ‘ถ๐Ÿฅดโ–ถโžกโ“๐Ÿ’Ž๐Ÿ’ธโฌ‡๐Ÿ˜จ๐ŸŒš๐Ÿฆ‹๐Ÿ˜ท๐Ÿ•บโš ๐Ÿ™…๐Ÿ˜Ÿ๐Ÿ˜ต๐Ÿ‘Ž๐Ÿคฒ๐Ÿค ๐Ÿคง๐Ÿ“Œ๐Ÿ”ต๐Ÿ’…๐Ÿง๐Ÿพ๐Ÿ’๐Ÿ˜—๐Ÿค‘๐ŸŒŠ๐Ÿคฏ๐Ÿทโ˜Ž๐Ÿ’ง๐Ÿ˜ฏ๐Ÿ’†๐Ÿ‘†๐ŸŽค๐Ÿ™‡๐Ÿ‘โ„๐ŸŒด๐Ÿ’ฃ๐Ÿธ๐Ÿ’Œ๐Ÿ“๐Ÿฅ€๐Ÿคข๐Ÿ‘…๐Ÿ’ก๐Ÿ’ฉ๐Ÿ‘๐Ÿ“ธ๐Ÿ‘ป๐Ÿค๐Ÿคฎ๐ŸŽผ๐Ÿฅต๐Ÿšฉ๐ŸŽ๐ŸŠ๐Ÿ‘ผ๐Ÿ’๐Ÿ“ฃ๐Ÿฅ‚"),j=z.reduce(((e,t,r)=>(e[r]=t,e)),[]),V=z.reduce(((e,t,r)=>{var n=t.codePointAt(0);if(null==n)throw new Error("Invalid character: ".concat(t));return e[n]=r,e}),[]);var q=_({prefix:"๐Ÿš€",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+=j[t]),"")},decode:function(e){var t=[];for(var r of e){var n=r.codePointAt(0);if(null==n)throw new Error("Invalid character: ".concat(r));var i=V[n];if(null==i)throw new Error("Non-base256emoji character: ".concat(r));t.push(i)}return new Uint8Array(t)}}),H=Object.freeze({__proto__:null,base256emoji:q}),K=N({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),W=N({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),G=N({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Q=N({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Y=N({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),J=N({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Z=N({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),$=N({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),X=N({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),ee=Object.freeze({__proto__:null,base32:K,base32hex:Y,base32hexpad:Z,base32hexpadupper:$,base32hexupper:J,base32pad:G,base32padupper:Q,base32upper:W,base32z:X}),te=B({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),re=B({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),ne=Object.freeze({__proto__:null,base36:te,base36upper:re}),ie=B({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),oe=B({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),ae=Object.freeze({__proto__:null,base58btc:ie,base58flickr:oe}),se=N({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),le=N({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ue=N({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ce=N({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),de=Object.freeze({__proto__:null,base64:se,base64pad:le,base64url:ue,base64urlpad:ce}),he=N({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),ve=Object.freeze({__proto__:null,base8:he}),pe=_({prefix:"\0",name:"identity",encode:e=>{return t=e,(new TextDecoder).decode(t);var t},decode:e=>function(e){return(new TextEncoder).encode(e)}(e)}),fe=Object.freeze({__proto__:null,identity:pe}),ge=new TextEncoder,ye=new TextDecoder,me=512;function we(e){return JSON.parse(ye.decode(e))}var be=Object.freeze({__proto__:null,code:512,decode:we,encode:function(e){return ge.encode(JSON.stringify(e))},name:"json"}),Se=85;var Ee=Object.freeze({__proto__:null,code:Se,decode:function(e){return E(e)},encode:function(e){return E(e)},name:"raw"}),ke=function e(t,r,n){r=r||[];var i=n=n||0;for(;t>=Ce;)r[n++]=255&t|xe,t/=128;for(;t&Ae;)r[n++]=255&t|xe,t>>>=7;return r[n]=0|t,e.bytes=n-i+1,r},xe=128,Ae=-128,Ce=Math.pow(2,31);var Ie=function e(t,r){var n,i=0,o=0,a=r=r||0,s=t.length;do{if(a>=s)throw e.bytes=0,new RangeError("Could not decode varint");n=t[a++],i+=o<28?(n&Pe)<<o:(n&Pe)*Math.pow(2,o),o+=7}while(n>=Te);return e.bytes=a-r,i},Te=128,Pe=127;var _e=Math.pow(2,7),Be=Math.pow(2,14),Ne=Math.pow(2,21),De=Math.pow(2,28),Re=Math.pow(2,35),Oe=Math.pow(2,42),Le=Math.pow(2,49),Me=Math.pow(2,56),Ue=Math.pow(2,63),Fe={encode:ke,decode:Ie,encodingLength:function(e){return e<_e?1:e<Be?2:e<Ne?3:e<De?4:e<Re?5:e<Oe?6:e<Le?7:e<Me?8:e<Ue?9:10}};function ze(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return[Fe.decode(e,t),Fe.decode.bytes]}function je(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return Fe.encode(e,t,r),t}function Ve(e){return Fe.encodingLength(e)}function qe(e,t){var r=t.byteLength,n=Ve(e),i=n+Ve(r),o=new Uint8Array(i+r);return je(e,o,0),je(r,o,n),o.set(t,i),new Ke(e,r,t,o)}function He(e){var t=E(e),[r,n]=ze(t),[i,o]=ze(t.subarray(n)),a=t.subarray(n+o);if(a.byteLength!==i)throw new Error("Incorrect length");return new Ke(r,i,a,t)}class Ke{constructor(t,r,n,i){e(this,"code",void 0),e(this,"size",void 0),e(this,"digest",void 0),e(this,"bytes",void 0),this.code=t,this.size=r,this.digest=n,this.bytes=i}}var We=E;var Ge={code:0,name:"identity",encode:We,digest:function(e){return qe(0,We(e))}},Qe=Object.freeze({__proto__:null,identity:Ge});function Ye(e){var{name:t,code:r,encode:n}=e;return new Je(t,r,n)}class Je{constructor(t,r,n){e(this,"name",void 0),e(this,"code",void 0),e(this,"encode",void 0),this.name=t,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){var t=this.encode(e);return t instanceof Uint8Array?qe(this.code,t):t.then((e=>qe(this.code,e)))}throw Error("Unknown type, must be binary type")}}function Ze(e){return function(){var t=r((function*(t){return new Uint8Array(yield crypto.subtle.digest(e,t))}));return function(e){return t.apply(this,arguments)}}()}var $e=Ye({name:"sha2-256",code:18,encode:Ze("SHA-256")}),Xe=Ye({name:"sha2-512",code:19,encode:Ze("SHA-512")}),et=Object.freeze({__proto__:null,sha256:$e,sha512:Xe});function tt(e,t){var{bytes:r,version:n}=e;return 0===n?function(e,t,r){var{prefix:n}=r;if(n!==ie.prefix)throw Error("Cannot string encode V0 in ".concat(r.name," encoding"));var i=t.get(n);if(null==i){var o=r.encode(e).slice(1);return t.set(n,o),o}return i}(r,nt(e),null!=t?t:ie.encoder):function(e,t,r){var{prefix:n}=r,i=t.get(n);if(null==i){var o=r.encode(e);return t.set(n,o),o}return i}(r,nt(e),null!=t?t:K.encoder)}var rt=new WeakMap;function nt(e){var t=rt.get(e);if(null==t){var r=new Map;return rt.set(e,r),r}return t}class it{constructor(t,r,n,i){e(this,"code",void 0),e(this,"version",void 0),e(this,"multihash",void 0),e(this,"bytes",void 0),e(this,"/",void 0),e(this,Symbol.toStringTag,"CID"),this.code=r,this.version=t,this.multihash=n,this.bytes=i,this["/"]=i}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:var{code:e,multihash:t}=this;if(e!==ot)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==at)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return it.createV0(t);default:throw Error("Can not convert CID version ".concat(this.version," to version 0. This is a bug please report"))}}toV1(){switch(this.version){case 0:var{code:e,digest:t}=this.multihash,r=qe(e,t);return it.createV1(this.code,r);case 1:return this;default:throw Error("Can not convert CID version ".concat(this.version," to version 1. This is a bug please report"))}}equals(e){return it.equals(this,e)}static equals(e,t){var r=t;return null!=r&&e.code===r.code&&e.version===r.version&&function(e,t){if(e===t)return!0;var r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&function(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(var r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}(e.bytes,r.bytes)}(e.multihash,r.multihash)}toString(e){return tt(this,e)}toJSON(){return{"/":tt(this)}}link(){return this}[Symbol.for("nodejs.util.inspect.custom")](){return"CID(".concat(this.toString(),")")}static asCID(e){if(null==e)return null;var t=e;if(t instanceof it)return t;if(null!=t["/"]&&t["/"]===t.bytes||t.asCID===t){var{version:r,code:n,multihash:i,bytes:o}=t;return new it(r,n,i,null!=o?o:st(r,n,i.bytes))}if(!0===t[lt]){var{version:a,multihash:s,code:l}=t,u=He(s);return it.create(a,l,u)}return null}static create(e,t,r){if("number"!=typeof t)throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:if(t!==ot)throw new Error("Version 0 CID must use dag-pb (code: ".concat(ot,") block encoding"));return new it(e,t,r,r.bytes);case 1:var n=st(e,t,r.bytes);return new it(e,t,r,n);default:throw new Error("Invalid version")}}static createV0(e){return it.create(0,ot,e)}static createV1(e,t){return it.create(1,e,t)}static decode(e){var[t,r]=it.decodeFirst(e);if(0!==r.length)throw new Error("Incorrect length");return t}static decodeFirst(e){var t=it.inspectBytes(e),r=t.size-t.multihashSize,n=E(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");var i=n.subarray(t.multihashSize-t.digestSize),o=new Ke(t.multihashCode,t.digestSize,i,n);return[0===t.version?it.createV0(o):it.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){var t=0,r=()=>{var[r,n]=ze(e.subarray(t));return t+=n,r},n=r(),i=ot;if(18===n?(n=0,t=0):i=r(),0!==n&&1!==n)throw new RangeError("Invalid CID version ".concat(n));var o=t,a=r(),s=r(),l=t+s;return{version:n,codec:i,multihashCode:a,digestSize:s,multihashSize:l-o,size:l}}static parse(e,t){var[r,n]=function(e,t){switch(e[0]){case"Q":var r=null!=t?t:ie;return[ie.prefix,r.decode("".concat(ie.prefix).concat(e))];case ie.prefix:var n=null!=t?t:ie;return[ie.prefix,n.decode(e)];case K.prefix:var i=null!=t?t:K;return[K.prefix,i.decode(e)];case te.prefix:var o=null!=t?t:te;return[te.prefix,o.decode(e)];default:if(null==t)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}(e,t),i=it.decode(n);if(0===i.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return nt(i).set(r,e),i}}var ot=112,at=18;function st(e,t,r){var n=Ve(e),i=n+Ve(t),o=new Uint8Array(i+r.byteLength);return je(e,o,0),je(t,o,n),o.set(r,i),o}var lt=Symbol.for("@ipld/js-cid/CID"),ut=t(t(t(t(t(t(t(t(t(t({},fe),F),ve),R),M),ee),ne),ae),de),H);function ct(){return new Uint8Array(arguments.length>0&&void 0!==arguments[0]?arguments[0]:0)}function dt(){return new Uint8Array(arguments.length>0&&void 0!==arguments[0]?arguments[0]:0)}function ht(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}t(t({},et),Qe);var vt=ht("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),pt=ht("ascii","a",(e=>{for(var t="a",r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t}),(e=>{for(var t=dt((e=e.substring(1)).length),r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t})),ft=t({utf8:vt,"utf-8":vt,hex:ut.base16,latin1:pt,ascii:pt,binary:pt},ut);function gt(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8",r=ft[t];if(null==r)throw new Error('Unsupported encoding "'.concat(t,'"'));return r.encoder.encode(e).substring(1)}let yt=class extends Error{constructor(){super(...arguments),e(this,"name","InvalidMultiaddrError")}};e(yt,"name","InvalidMultiaddrError");class mt extends Error{constructor(){super(...arguments),e(this,"name","ValidationError")}}e(mt,"name","ValidationError");let wt=class extends Error{constructor(){super(...arguments),e(this,"name","InvalidParametersError")}};e(wt,"name","InvalidParametersError");class bt extends Error{constructor(){super(...arguments),e(this,"name","UnknownProtocolError")}}function St(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 Et(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8",r=ft[t];if(null==r)throw new Error('Unsupported encoding "'.concat(t,'"'));return r.decoder.decode("".concat(r.prefix).concat(e))}e(bt,"name","UnknownProtocolError");var kt=Math.pow(2,7),xt=Math.pow(2,14),At=Math.pow(2,21),Ct=Math.pow(2,28),It=Math.pow(2,35),Tt=Math.pow(2,42),Pt=Math.pow(2,49),_t=128,Bt=127;function Nt(e){if(e<kt)return 1;if(e<xt)return 2;if(e<At)return 3;if(e<Ct)return 4;if(e<It)return 5;if(e<Tt)return 6;if(e<Pt)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Dt(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;switch(Nt(e)){case 8:t[r++]=255&e|_t,e/=128;case 7:t[r++]=255&e|_t,e/=128;case 6:t[r++]=255&e|_t,e/=128;case 5:t[r++]=255&e|_t,e/=128;case 4:t[r++]=255&e|_t,e>>>=7;case 3:t[r++]=255&e|_t,e>>>=7;case 2:t[r++]=255&e|_t,e>>>=7;case 1:t[r++]=255&e,e>>>=7;break;default:throw new Error("unreachable")}return t}function Rt(e,t){var r=e[t],n=0;if(n+=r&Bt,r<_t)return n;if(n+=((r=e[t+1])&Bt)<<7,r<_t)return n;if(n+=((r=e[t+2])&Bt)<<14,r<_t)return n;if(n+=((r=e[t+3])&Bt)<<21,r<_t)return n;if(n+=((r=e[t+4])&Bt)*Ct,r<_t)return n;if(n+=((r=e[t+5])&Bt)*It,r<_t)return n;if(n+=((r=e[t+6])&Bt)*Tt,r<_t)return n;if(n+=((r=e[t+7])&Bt)*Pt,r<_t)return n;throw new RangeError("Could not decode varint")}function Ot(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return null==t&&(t=dt(Nt(e))),t instanceof Uint8Array?Dt(e,t,r):function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;switch(Nt(e)){case 8:t.set(r++,255&e|_t),e/=128;case 7:t.set(r++,255&e|_t),e/=128;case 6:t.set(r++,255&e|_t),e/=128;case 5:t.set(r++,255&e|_t),e/=128;case 4:t.set(r++,255&e|_t),e>>>=7;case 3:t.set(r++,255&e|_t),e>>>=7;case 2:t.set(r++,255&e|_t),e>>>=7;case 1:t.set(r++,255&e),e>>>=7;break;default:throw new Error("unreachable")}return t}(e,t,r)}function Lt(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return e instanceof Uint8Array?Rt(e,t):function(e,t){var r=e.get(t),n=0;if(n+=r&Bt,r<_t)return n;if(n+=((r=e.get(t+1))&Bt)<<7,r<_t)return n;if(n+=((r=e.get(t+2))&Bt)<<14,r<_t)return n;if(n+=((r=e.get(t+3))&Bt)<<21,r<_t)return n;if(n+=((r=e.get(t+4))&Bt)*Ct,r<_t)return n;if(n+=((r=e.get(t+5))&Bt)*It,r<_t)return n;if(n+=((r=e.get(t+6))&Bt)*Tt,r<_t)return n;if(n+=((r=e.get(t+7))&Bt)*Pt,r<_t)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=dt(t),n=0;for(var i of e)r.set(i,n),n+=i.length;return r}var Ut=new class{constructor(){e(this,"index",0),e(this,"input","")}new(e){return this.index=0,this.input=e,this}readAtomically(e){var t=this.index,r=e();return void 0===r&&(this.index=t),r}parseWith(e){var t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically((()=>{var t=this.readChar();if(t===e)return t}))}readSeparator(e,t,r){return this.readAtomically((()=>{if(!(t>0&&void 0===this.readGivenChar(e)))return r()}))}readNumber(e,t,r,n){return this.readAtomically((()=>{var i=0,o=0,a=this.peekChar();if(void 0!==a){for(var s="0"===a,l=2**(8*n)-1;;){var u=this.readAtomically((()=>{var t=this.readChar();if(void 0!==t){var r=Number.parseInt(t,e);if(!Number.isNaN(r))return r}}));if(void 0===u)break;if(i*=e,(i+=u)>l)return;if(o+=1,void 0!==t&&o>t)return}return 0===o||!r&&s&&o>1?void 0:i}}))}readIPv4Addr(){return this.readAtomically((()=>{for(var e=new Uint8Array(4),t=0;t<e.length;t++){var r=this.readSeparator(".",t,(()=>this.readNumber(10,3,!1,1)));if(void 0===r)return;e[t]=r}return e}))}readIPv6Addr(){var e=e=>{for(var t=0;t<e.length/2;t++){var r=2*t;if(t<e.length-3){var n=this.readSeparator(":",t,(()=>this.readIPv4Addr()));if(void 0!==n)return e[r]=n[0],e[r+1]=n[1],e[r+2]=n[2],e[r+3]=n[3],[r+4,!0]}var i=this.readSeparator(":",t,(()=>this.readNumber(16,4,!0,2)));if(void 0===i)return[r,!1];e[r]=i>>8,e[r+1]=255&i}return[e.length,!1]};return this.readAtomically((()=>{var t=new Uint8Array(16),[r,n]=e(t);if(16===r)return t;if(!n&&void 0!==this.readGivenChar(":")&&void 0!==this.readGivenChar(":")){var i=new Uint8Array(14),o=16-(r+2),[a]=e(i.subarray(0,o));return t.set(i.subarray(0,a),16-a),t}}))}readIPAddr(){var e;return null!==(e=this.readIPv4Addr())&&void 0!==e?e:this.readIPv6Addr()}};function Ft(e){if(!(e.length>15))return Ut.new(e).parseWith((()=>Ut.readIPv4Addr()))}function zt(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return Ut.new(e).parseWith((()=>Ut.readIPv6Addr()))}function jt(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45)){var r=Ut.new(e).parseWith((()=>Ut.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 Vt(e){return Boolean(Ft(e))}function qt(e){return Boolean(zt(e))}function Ht(e){return t=>gt(t,e)}function Kt(e){return t=>Et(t,e)}function Wt(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function Gt(e){var t=new ArrayBuffer(2);return new DataView(t).setUint16(0,"string"==typeof e?parseInt(e):e),new Uint8Array(t)}function Qt(e){var t=e.subarray(0,e.length-2),r=e.subarray(e.length-2),n=gt(t,"base32"),i=Wt(r);return"".concat(n,":").concat(i)}var Yt=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 yt("Invalid byte value in IP address");t[r]=n})),t};var Jt,Zt=Object.values(ut).map((e=>e.decoder)),$t=(Jt=Zt[0].or(Zt[1]),Zt.slice(2).forEach((e=>Jt=Jt.or(e))),Jt);var Xt,er=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 mt("Value must be an integer")}),(function(e){if(e<0)throw new mt("Value must be a positive integer, or zero")}),(Xt=65535,e=>{if(e>Xt)throw new mt("Value must be smaller than or equal to ".concat(Xt))})),tr=-1;var rr=new class{constructor(){e(this,"protocolsByCode",new Map),e(this,"protocolsByName",new Map)}getProtocol(e){var t;if(null==(t="string"==typeof e?this.protocolsByName.get(e):this.protocolsByCode.get(e)))throw new bt("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)})))}},nr=[{code:4,name:"ip4",size:32,valueToBytes:Yt,bytesToValue:function(e){if(4!==e.byteLength)throw new yt("IPv4 address was incorrect length");for(var t=[],r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},validate:e=>{if(!Vt(e))throw new mt('Invalid IPv4 address "'.concat(e,'"'))}},{code:6,name:"tcp",size:16,valueToBytes:Gt,bytesToValue:Wt,validate:er},{code:273,name:"udp",size:16,valueToBytes:Gt,bytesToValue:Wt,validate:er},{code:33,name:"dccp",size:16,valueToBytes:Gt,bytesToValue:Wt,validate:er},{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;Vt(n[t])&&(i=Yt(n[t]),n[t]=gt(i.subarray(0,2),"base16")),null!=i&&++t<8&&n.splice(t,0,gt(i.subarray(2,4),"base16"))}if(""===n[0])for(;n.length<8;)n.unshift("0");else if(""===n[n.length-1])for(;n.length<8;)n.push("0");else if(n.length<8){for(t=0;t<n.length&&""!==n[t];t++);var o=[t,1];for(t=9-n.length;t>0;t--)o.push("0");n.splice.apply(n,o)}var a=new Uint8Array(r+16);for(t=0;t<n.length;t++){""===n[t]&&(n[t]="0");var s=parseInt(n[t],16);if(isNaN(s)||s<0||s>65535)throw new yt("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 yt("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 yt('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 yt('Invalid IPv6 address "'.concat(e,'"'))}},validate:e=>{if(!qt(e))throw new mt('Invalid IPv6 address "'.concat(e,'"'))}},{code:42,name:"ip6zone",size:tr},{code:43,name:"ipcidr",size:8,bytesToValue:Ht("base10"),valueToBytes:Kt("base10")},{code:53,name:"dns",size:tr,resolvable:!0},{code:54,name:"dns4",size:tr,resolvable:!0},{code:55,name:"dns6",size:tr,resolvable:!0},{code:56,name:"dnsaddr",size:tr,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Gt,bytesToValue:Wt,validate:er},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:tr,path:!0,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:tr,bytesToValue:Ht("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?Kt("base58btc")(e):it.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Qt,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=Et(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=Gt(n);return Mt([r,i],r.length+i.length)}},{code:445,name:"onion3",size:296,bytesToValue:Qt,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=Gt(n);return Mt([r,i],r.length+i.length)}},{code:446,name:"garlic64",size:tr},{code:447,name:"garlic32",size:tr},{code:448,name:"tls"},{code:449,name:"sni",size:tr},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:tr,bytesToValue:function(e){return t=>e.encoder.encode(t)}(ue),valueToBytes:function(e){return $t.decode(e)}},{code:480,name:"http"},{code:481,name:"http-path",size:tr,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:tr}];function ir(e,t,r){return null==e.size||0===e.size?0:e.size>0?e.size/8:Lt(t,r)}nr.forEach((e=>{rr.addProtocol(e)}));var or=Symbol.for("nodejs.util.inspect.custom"),ar=Symbol.for("@multiformats/multiaddr"),sr=[53,54,55,56];class lr extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No available resolver"),this.name="NoAvailableResolverError"}}function ur(e){if(null==e&&(e="/"),Er(e))return e.getComponents();if(e instanceof Uint8Array)return function(e){for(var t=[],r=0;r<e.length;){var n=Lt(e,r),i=rr.getProtocol(n),o=Nt(n),a=ir(i,e,r+o),s=0;a>0&&i.size===tr&&(s=Nt(a));var l=o+s+a,u={code:n,name:i.name,bytes:e.subarray(r,r+l)};if(a>0){var c,d,h=r+o+s,v=e.subarray(h,h+a);u.value=null!==(c=null===(d=i.bytesToValue)||void 0===d?void 0:d.call(i,v))&&void 0!==c?c:gt(v)}t.push(u),r+=l}return t}(e);if("string"==typeof e)return""===(e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""))&&(e="/"),function(e){if("/"!==e.charAt(0))throw new yt('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=rr.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 yt("Component ".concat(i," was missing value"));r="value"}else if("value"===r){var u={code:l.code,name:l.name};if(null!=l.size&&0!==l.size){var c,d;if(""===n)throw new yt("Component ".concat(i," was missing value"));u.value=null!==(c=null===(d=l.stringToValue)||void 0===d?void 0:d.call(l,n))&&void 0!==c?c:n}t.push(u),n="",i="",r="protocol"}}}if(""!==i&&""!==n)throw new yt("Incomplete multiaddr");return t}(e);if(Array.isArray(e))return e;throw new yt("Must be a string, Uint8Array, Component[], or another Multiaddr")}var cr=new WeakMap,dr=new WeakMap,hr=new WeakMap;class vr{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/",r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,ar,!0),n(this,cr,void 0),n(this,dr,void 0),n(this,hr,void 0),i(cr,this,ur(t)),!1!==r.validate&&function(e){e.getComponents().forEach((e=>{var t,r=rr.getProtocol(e.code);null!=e.value&&(null===(t=r.validate)||void 0===t||t.call(r,e.value))}))}(this)}get bytes(){return null==o(hr,this)&&i(hr,this,function(e){var t=0,r=[];for(var n of e){if(null==n.bytes){var i,o,a=rr.getProtocol(n.code),s=Nt(n.code),l=void 0,u=0,c=0;null!=n.value&&(u=(l=null!==(i=null===(o=a.valueToBytes)||void 0===o?void 0:o.call(a,n.value))&&void 0!==i?i:Et(n.value)).byteLength,a.size===tr&&(c=Nt(u)));var d=new Uint8Array(s+c+u),h=0;Dt(n.code,d,h),h+=s,null!=l&&(a.size===tr&&(Dt(u,d,h),h+=c),d.set(l,h)),n.bytes=d}r.push(n.bytes),t+=n.bytes.byteLength}return Mt(r,t)}(o(cr,this))),o(hr,this)}toString(){var e;return null==o(dr,this)&&i(dr,this,(e=o(cr,this),"/".concat(e.flatMap((e=>{var t,r;if(null==e.value)return e.name;var n=rr.getProtocol(e.code);if(null==n)throw new yt("Unknown protocol code ".concat(e.code));return[e.name,null!==(t=null===(r=n.valueToString)||void 0===r?void 0:r.call(n,e.value))&&void 0!==t?t:e.value]})).join("/")))),o(dr,this)}toJSON(){return this.toString()}toOptions(){var e,t,r,n,i="";for(var{code:a,name:s,value:l}of o(cr,this))42===a&&(i="%".concat(null!=l?l:"")),sr.includes(a)&&(t="tcp",n=443,r="".concat(null!=l?l:"").concat(i),e=55===a?6:4),6!==a&&273!==a||(t="tcp"===s?"tcp":"udp",n=parseInt(null!=l?l:"")),4!==a&&41!==a||(t="tcp",r="".concat(null!=l?l:"").concat(i),e=41===a?6:4);if(null==e||null==t||null==r||null==n)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:r,transport:t,port:n}}getComponents(){return[...o(cr,this)]}protos(){return o(cr,this).map((e=>{var t,{code:r,value:n}=e,i=rr.getProtocol(r);return{code:r,size:null!==(t=i.size)&&void 0!==t?t:0,name:i.name,resolvable:Boolean(i.resolvable),path:Boolean(i.path)}}))}protoCodes(){return o(cr,this).map((e=>{var{code:t}=e;return t}))}protoNames(){return o(cr,this).map((e=>{var{name:t}=e;return t}))}tuples(){return o(cr,this).map((e=>{var{code:t,value:r}=e;if(null==r)return[t];var n,i,o=rr.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:Et(r));return a}))}stringTuples(){return o(cr,this).map((e=>{var{code:t,value:r}=e;return null==r?[t]:[t,r]}))}encapsulate(e){var t=new vr(e);return new vr([...o(cr,this),...t.getComponents()],{validate:!1})}decapsulate(e){var t=e.toString(),r=this.toString(),n=r.lastIndexOf(t);if(n<0)throw new wt("Address ".concat(this.toString()," does not contain subaddress: ").concat(e.toString()));return new vr(r.slice(0,n),{validate:!1})}decapsulateCode(e){for(var t,r=o(cr,this).length-1;r>-1;r--)if(o(cr,this)[r].code===e){t=r;break}return new vr(o(cr,this).slice(0,t),{validate:!1})}getPeerId(){try{var e=[];o(cr,this).forEach((t=>{var{code:r,value:n}=t;421===r&&e.push([r,n]),290===r&&(e=[])}));var t=e.pop();if(null!=(null==t?void 0:t[1])){var r=t[1];return"Q"===r[0]||"1"===r[0]?gt(ie.decode("z".concat(r)),"base58btc"):gt(it.parse(r).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){for(var e of o(cr,this)){var t;if(rr.getProtocol(e.code).path)return null!==(t=e.value)&&void 0!==t?t:null}return null}equals(e){return St(this.bytes,e.bytes)}resolve(e){var t=this;return r((function*(){var r=t.protos().find((e=>e.resolvable));if(null==r)return[t];var n=br.get(r.name);if(null==n)throw new lr("no available resolver for ".concat(r.name));return(yield n(t,e)).map((e=>kr(e)))}))()}nodeAddress(){var e=this.toOptions();if("tcp"!==e.transport&&"udp"!==e.transport)throw new Error('multiaddr must have a valid format - no protocol with name: "'.concat(e.transport,'". Must have a valid transport protocol: "{tcp, udp}"'));return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(){return 2===o(cr,this).length&&((4===o(cr,this)[0].code||41===o(cr,this)[0].code)&&(6===o(cr,this)[1].code||273===o(cr,this)[1].code))}[or](){return"Multiaddr(".concat(this.toString(),")")}}var pr=4,fr=16,gr=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function yr(e,t){t.length===fr&&e.length===pr&&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===pr&&e.length===fr&&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,gr,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 mr(e,t){if(t!==8*pr&&t!==8*fr)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 wr{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=pr,i=Ft(t);if(null==i&&(n=fr,null==(i=zt(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=mr(o,8*n);return{network:yr(i,a),mask:a}}(e));else{var r=jt(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=jt(t);if(null==i)throw new Error("Failed to parse mask");this.mask=i}else this.mask=mr(n,8*r.length);this.network=yr(r,this.mask)}}contains(e){return function(e,t){if("string"==typeof t&&(t=jt(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 pr:return e.join(".");case fr: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 br=new Map;function Sr(e){return!!Er(e)&&e.protos().some((e=>e.resolvable))}function Er(e){return Boolean(null==e?void 0:e[ar])}function kr(e){return new vr(e)}function xr(e){var t,r=rr.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 Ar="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Cr(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Ir(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 Tr(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");Cr(e.outputLen),Cr(e.blockLen)}function Pr(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 _r(e,t){Ir(e);var r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Br(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Nr(){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 Dr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Rr(e,t){return e<<32-t|e>>>t}function Or(e,t){return e<<t|e>>>32-t>>>0}var Lr=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function Mr(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}var Ur=Lr?e=>e:e=>Mr(e);var Fr=Lr?e=>e:function(e){for(var t=0;t<e.length;t++)e[t]=Mr(e[t]);return e},zr=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),jr=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Vr(e){if(Ir(e),zr)return e.toHex();for(var t="",r=0;r<e.length;r++)t+=jr[e[r]];return t}var qr=48,Hr=57,Kr=65,Wr=70,Gr=97,Qr=102;function Yr(e){return e>=qr&&e<=Hr?e-qr:e>=Kr&&e<=Wr?e-(Kr-10):e>=Gr&&e<=Qr?e-(Gr-10):void 0}function Jr(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(zr)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=Yr(e.charCodeAt(o)),s=Yr(e.charCodeAt(o+1));if(void 0===a||void 0===s){var l=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+l+'" at index '+o)}n[i]=16*a+s}return n}var Zr=function(){var e=r((function*(){}));return function(){return e.apply(this,arguments)}}();function $r(){return $r=r((function*(e,t,r){for(var n=Date.now(),i=0;i<e;i++){r(i);var o=Date.now()-n;o>=0&&o<t||(yield Zr(),n+=o)}})),$r.apply(this,arguments)}function Xr(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function en(e){return"string"==typeof e&&(e=Xr(e)),Ir(e),e}function tn(e){return"string"==typeof e&&(e=Xr(e)),Ir(e),e}function rn(){for(var e=0,t=0;t<arguments.length;t++){var r=t<0||arguments.length<=t?void 0:arguments[t];Ir(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 nn{}function on(e){var t=t=>e().update(en(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function an(e){var t=(t,r)=>e(r).update(en(t)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}function sn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:32;if(Ar&&"function"==typeof Ar.getRandomValues)return Ar.getRandomValues(new Uint8Array(e));if(Ar&&"function"==typeof Ar.randomBytes)return Uint8Array.from(Ar.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function ln(e,t,r){return e&t^~e&r}function un(e,t,r){return e&t^e&r^t&r}class cn extends nn{constructor(e,t,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Dr(this.buffer)}update(e){Pr(this),Ir(e=en(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=Dr(e);n<=i-o;o+=n)this.process(s,o)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Pr(this),_r(e,this),this.finished=!0;var{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,Nr(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(r,0),o=0);for(var a=o;a<n;a++)t[a]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);var i=BigInt(32),o=BigInt(4294967295),a=Number(r>>i&o),s=Number(r&o),l=n?4:0,u=n?0:4;e.setUint32(t+l,a,n),e.setUint32(t+u,s,n)}(r,n-8,BigInt(8*this.length),i),this.process(r,0);var s=Dr(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");var u=l/4,c=this.get();if(u>c.length)throw new Error("_sha2: outputLen bigger than state");for(var d=0;d<u;d++)s.setUint32(4*d,c[d],i)}digest(){var{buffer:e,outputLen:t}=this;this.digestInto(e);var r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());var{blockLen:t,buffer:r,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}var dn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),hn=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),vn=BigInt(2**32-1),pn=BigInt(32);function fn(e){return arguments.length>1&&void 0!==arguments[1]&&arguments[1]?{h:Number(e&vn),l:Number(e>>pn&vn)}:{h:0|Number(e>>pn&vn),l:0|Number(e&vn)}}function gn(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}=fn(e[o],t);[n[o],i[o]]=[a,s]}return[n,i]}var yn=(e,t,r)=>e>>>r,mn=(e,t,r)=>e<<32-r|t>>>r,wn=(e,t,r)=>e>>>r|t<<32-r,bn=(e,t,r)=>e<<32-r|t>>>r,Sn=(e,t,r)=>e<<64-r|t>>>r-32,En=(e,t,r)=>e>>>r-32|t<<64-r,kn=(e,t)=>t,xn=(e,t)=>e,An=(e,t,r)=>e<<r|t>>>32-r,Cn=(e,t,r)=>t<<r|e>>>32-r,In=(e,t,r)=>t<<r-32|e>>>64-r,Tn=(e,t,r)=>e<<r-32|t>>>64-r;function Pn(e,t,r,n){var i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:0|i}}var _n=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Bn=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,Nn=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Dn=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,Rn=(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,Ln=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Mn=new Uint32Array(64);class Un extends cn{constructor(){super(64,arguments.length>0&&void 0!==arguments[0]?arguments[0]:32,8,!1),this.A=0|dn[0],this.B=0|dn[1],this.C=0|dn[2],this.D=0|dn[3],this.E=0|dn[4],this.F=0|dn[5],this.G=0|dn[6],this.H=0|dn[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)Mn[r]=e.getUint32(t,!1);for(var n=16;n<64;n++){var i=Mn[n-15],o=Mn[n-2],a=Rr(i,7)^Rr(i,18)^i>>>3,s=Rr(o,17)^Rr(o,19)^o>>>10;Mn[n]=s+Mn[n-7]+a+Mn[n-16]|0}for(var{A:l,B:u,C:c,D:d,E:h,F:v,G:p,H:f}=this,g=0;g<64;g++){var y=f+(Rr(h,6)^Rr(h,11)^Rr(h,25))+ln(h,v,p)+Ln[g]+Mn[g]|0,m=(Rr(l,2)^Rr(l,13)^Rr(l,22))+un(l,u,c)|0;f=p,p=v,v=h,h=d+y|0,d=c,c=u,u=l,l=y+m|0}l=l+this.A|0,u=u+this.B|0,c=c+this.C|0,d=d+this.D|0,h=h+this.E|0,v=v+this.F|0,p=p+this.G|0,f=f+this.H|0,this.set(l,u,c,d,h,v,p,f)}roundClean(){Nr(Mn)}destroy(){this.set(0,0,0,0,0,0,0,0),Nr(this.buffer)}}var Fn=(()=>gn(["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)))))(),zn=(()=>Fn[0])(),jn=(()=>Fn[1])(),Vn=new Uint32Array(80),qn=new Uint32Array(80);class Hn extends cn{constructor(){super(128,arguments.length>0&&void 0!==arguments[0]?arguments[0]:64,16,!1),this.Ah=0|hn[0],this.Al=0|hn[1],this.Bh=0|hn[2],this.Bl=0|hn[3],this.Ch=0|hn[4],this.Cl=0|hn[5],this.Dh=0|hn[6],this.Dl=0|hn[7],this.Eh=0|hn[8],this.El=0|hn[9],this.Fh=0|hn[10],this.Fl=0|hn[11],this.Gh=0|hn[12],this.Gl=0|hn[13],this.Hh=0|hn[14],this.Hl=0|hn[15]}get(){var{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:o,Dh:a,Dl:s,Eh:l,El:u,Fh:c,Fl:d,Gh:h,Gl:v,Hh:p,Hl:f}=this;return[e,t,r,n,i,o,a,s,l,u,c,d,h,v,p,f]}set(e,t,r,n,i,o,a,s,l,u,c,d,h,v,p,f){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|i,this.Cl=0|o,this.Dh=0|a,this.Dl=0|s,this.Eh=0|l,this.El=0|u,this.Fh=0|c,this.Fl=0|d,this.Gh=0|h,this.Gl=0|v,this.Hh=0|p,this.Hl=0|f}process(e,t){for(var r=0;r<16;r++,t+=4)Vn[r]=e.getUint32(t),qn[r]=e.getUint32(t+=4);for(var n=16;n<80;n++){var i=0|Vn[n-15],o=0|qn[n-15],a=wn(i,o,1)^wn(i,o,8)^yn(i,0,7),s=bn(i,o,1)^bn(i,o,8)^mn(i,o,7),l=0|Vn[n-2],u=0|qn[n-2],c=wn(l,u,19)^Sn(l,u,61)^yn(l,0,6),d=bn(l,u,19)^En(l,u,61)^mn(l,u,6),h=Nn(s,d,qn[n-7],qn[n-16]),v=Dn(h,a,c,Vn[n-7],Vn[n-16]);Vn[n]=0|v,qn[n]=0|h}for(var{Ah:p,Al:f,Bh:g,Bl:y,Ch:m,Cl:w,Dh:b,Dl:S,Eh:E,El:k,Fh:x,Fl:A,Gh:C,Gl:I,Hh:T,Hl:P}=this,_=0;_<80;_++){var B=wn(E,k,14)^wn(E,k,18)^Sn(E,k,41),N=bn(E,k,14)^bn(E,k,18)^En(E,k,41),D=E&x^~E&C,R=Rn(P,N,k&A^~k&I,jn[_],qn[_]),O=On(R,T,B,D,zn[_],Vn[_]),L=0|R,M=wn(p,f,28)^Sn(p,f,34)^Sn(p,f,39),U=bn(p,f,28)^En(p,f,34)^En(p,f,39),F=p&g^p&m^g&m,z=f&y^f&w^y&w;T=0|C,P=0|I,C=0|x,I=0|A,x=0|E,A=0|k,({h:E,l:k}=Pn(0|b,0|S,0|O,0|L)),b=0|m,S=0|w,m=0|g,w=0|y,g=0|p,y=0|f;var j=_n(L,U,z);p=Bn(j,O,M,F),f=0|j}({h:p,l:f}=Pn(0|this.Ah,0|this.Al,0|p,0|f)),({h:g,l:y}=Pn(0|this.Bh,0|this.Bl,0|g,0|y)),({h:m,l:w}=Pn(0|this.Ch,0|this.Cl,0|m,0|w)),({h:b,l:S}=Pn(0|this.Dh,0|this.Dl,0|b,0|S)),({h:E,l:k}=Pn(0|this.Eh,0|this.El,0|E,0|k)),({h:x,l:A}=Pn(0|this.Fh,0|this.Fl,0|x,0|A)),({h:C,l:I}=Pn(0|this.Gh,0|this.Gl,0|C,0|I)),({h:T,l:P}=Pn(0|this.Hh,0|this.Hl,0|T,0|P)),this.set(p,f,g,y,m,w,b,S,E,k,x,A,C,I,T,P)}roundClean(){Nr(Vn,qn)}destroy(){Nr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}var Kn=on((()=>new Un)),Wn=on((()=>new Hn));class Gn extends nn{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Tr(e);var r=en(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),Nr(i)}update(e){return Pr(this),this.iHash.update(e),this}digestInto(e){Pr(this),Ir(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 Qn=(e,t,r)=>new Gn(e,t).update(r).digest();Qn.create=(e,t)=>new Gn(e,t);var Yn=BigInt(0),Jn=BigInt(1);function Zn(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function $n(e){if(!Zn(e))throw new Error("Uint8Array expected")}function Xn(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}function ei(e){var t=e.toString(16);return 1&t.length?"0"+t:t}function ti(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Yn:BigInt("0x"+e)}var ri="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,ni=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function ii(e){if($n(e),ri)return e.toHex();for(var t="",r=0;r<e.length;r++)t+=ni[e[r]];return t}var oi=48,ai=57,si=65,li=70,ui=97,ci=102;function di(e){return e>=oi&&e<=ai?e-oi:e>=si&&e<=li?e-(si-10):e>=ui&&e<=ci?e-(ui-10):void 0}function hi(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(ri)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=di(e.charCodeAt(o)),s=di(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 vi(e){return ti(ii(e))}function pi(e){return $n(e),ti(ii(Uint8Array.from(e).reverse()))}function fi(e,t){return hi(e.toString(16).padStart(2*t,"0"))}function gi(e,t){return fi(e,t).reverse()}function yi(e,t,r){var n;if("string"==typeof t)try{n=hi(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!Zn(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 mi(){for(var e=0,t=0;t<arguments.length;t++){var r=t<0||arguments.length<=t?void 0:arguments[t];$n(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 wi=e=>"bigint"==typeof e&&Yn<=e;function bi(e,t,r){return wi(e)&&wi(t)&&wi(r)&&t<=e&&e<r}function Si(e,t,r,n){if(!bi(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}var Ei=e=>(Jn<<BigInt(e))-Jn,ki=e=>new Uint8Array(e),xi=e=>Uint8Array.from(e);var Ai={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||Zn(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 Ci(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=(t,r,n)=>{var i=Ai[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 Ii(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 Ti=BigInt(0),Pi=BigInt(1),_i=BigInt(2),Bi=BigInt(3),Ni=BigInt(4),Di=BigInt(5),Ri=BigInt(8);function Oi(e,t){var r=e%t;return r>=Ti?r:t+r}function Li(e,t,r){for(var n=e;t-- >Ti;)n*=n,n%=r;return n}function Mi(e,t){if(e===Ti)throw new Error("invert: expected non-zero number");if(t<=Ti)throw new Error("invert: expected positive modulus, got "+t);for(var r=Oi(e,t),n=t,i=Ti,o=Pi;r!==Ti;){var a=n%r,s=i-o*(n/r);n=r,r=a,i=o,o=s}if(n!==Pi)throw new Error("invert: does not exist");return Oi(i,t)}function Ui(e,t){var r=(e.ORDER+Pi)/Ni,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function Fi(e,t){var r=(e.ORDER-Di)/Ri,n=e.mul(t,_i),i=e.pow(n,r),o=e.mul(t,i),a=e.mul(e.mul(o,_i),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 zi(e){return e%Ni===Bi?Ui:e%Ri===Di?Fi:function(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");for(var t=e-Pi,r=0;t%_i===Ti;)t/=_i,r++;for(var n=_i,i=Ki(e);1===qi(i,n);)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===r)return Ui;var o=i.pow(n,t),a=(t+Pi)/_i;return function(e,n){if(e.is0(n))return n;if(1!==qi(e,n))throw new Error("Cannot find square root");for(var i=r,s=e.mul(e.ONE,o),l=e.pow(n,t),u=e.pow(n,a);!e.eql(l,e.ONE);){if(e.is0(l))return e.ZERO;for(var c=1,d=e.sqr(l);!e.eql(d,e.ONE);)if(c++,d=e.sqr(d),c===i)throw new Error("Cannot find square root");var h=Pi<<BigInt(i-c-1),v=e.pow(s,h);i=c,s=e.sqr(v),l=e.mul(l,s),u=e.mul(u,v)}return u}}(e)}var ji=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Vi(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 qi(e,t){var r=(e.ORDER-Pi)/_i,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 Hi(e,t){void 0!==t&&Cr(t);var r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function Ki(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<=Ti)throw new Error("invalid field: expected ORDER > 0, got "+e);var i,{nBitLength:o,nByteLength:a}=Hi(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:Ei(o),ZERO:Ti,ONE:Pi,create:t=>Oi(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return Ti<=t&&t<e},is0:e=>e===Ti,isOdd:e=>(e&Pi)===Pi,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<Ti)throw new Error("invalid exponent, negatives unsupported");if(r===Ti)return e.ONE;if(r===Pi)return t;for(var n=e.ONE,i=t;r>Ti;)r&Pi&&(n=e.mul(n,i)),i=e.sqr(i),r>>=Pi;return n}(s,e,t),div:(t,r)=>Oi(t*Mi(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Mi(t,e),sqrt:n.sqrt||(t=>(i||(i=zi(e)),i(s,t))),toBytes:e=>r?gi(e,a):fi(e,a),fromBytes:e=>{if(e.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+e.length);return r?pi(e):vi(e)},invertBatch:e=>Vi(s,e),cmov:(e,t,r)=>r?t:e});return Object.freeze(s)}function Wi(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=Wi(e);return t+Math.ceil(t/2)}var Qi=BigInt(0),Yi=BigInt(1);function Ji(e,t){var r=t.negate();return e?r:t}function Zi(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function $i(e,t){Zi(e,t);var r=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Ei(e),maxNumber:r,shiftBy:BigInt(e)}}function Xi(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+=Yi);var u=t*n;return{nextN:l,offset:u+Math.abs(s)-1,isZero:0===s,isNeg:s<0,isNegF:t%2!=0,offsetF:u}}var eo=new WeakMap,to=new WeakMap;function ro(e){return to.get(e)||1}function no(e,t){return{constTimeNegate:Ji,hasPrecomputes:e=>1!==ro(e),unsafeLadder(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.ZERO,i=t;r>Qi;)r&Yi&&(n=n.add(i)),i=i.double(),r>>=Yi;return n},precomputeWindow(e,r){for(var{windows:n,windowSize:i}=$i(r,t),o=[],a=e,s=a,l=0;l<n;l++){s=a,o.push(s);for(var u=1;u<i;u++)s=s.add(a),o.push(s);a=s.double()}return o},wNAF(r,n,i){for(var o=e.ZERO,a=e.BASE,s=$i(r,t),l=0;l<s.windows;l++){var{nextN:u,offset:c,isZero:d,isNeg:h,isNegF:v,offsetF:p}=Xi(i,l,s);i=u,d?a=a.add(Ji(v,n[p])):o=o.add(Ji(h,n[c]))}return{p:o,f:a}},wNAFUnsafe(r,n,i){for(var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e.ZERO,a=$i(r,t),s=0;s<a.windows&&i!==Qi;s++){var{nextN:l,offset:u,isZero:c,isNeg:d}=Xi(i,s,a);if(i=l,!c){var h=n[u];o=o.add(d?h.negate():h)}}return o},getPrecomputes(e,t,r){var n=eo.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&eo.set(t,r(n))),n},wNAFCached(e,t,r){var n=ro(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)},wNAFCachedUnsafe(e,t,r,n){var i=ro(e);return 1===i?this.unsafeLadder(e,t,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),t,n)},setWindowSize(e,r){Zi(r,t),to.set(e,r),eo.delete(e)}}}function io(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>Yn;e>>=Jn,t+=1);return t}(BigInt(i)),l=1;s>12?l=s-3:s>4?l=s-2:s>0&&(l=2);for(var u=Ei(l),c=new Array(Number(u)+1).fill(a),d=a,h=Math.floor((t.BITS-1)/l)*l;h>=0;h-=l){c.fill(a);for(var v=0;v<o;v++){var p=n[v],f=Number(p>>BigInt(h)&u);c[f]=c[f].add(r[v])}for(var g=a,y=c.length-1,m=a;y>0;y--)m=m.add(c[y]),g=g.add(m);if(d=d.add(g),0!==h)for(var w=0;w<l;w++)d=d.double()}return d}function oo(e){var r,n;return r=e.Fp,n=ji.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"}),Ci(r,n),Ci(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze(t(t(t({},Hi(e.n,e.nBitLength)),e),{p:e.Fp.ORDER}))}function ao(e){void 0!==e.lowS&&Xn("lowS",e.lowS),void 0!==e.prehash&&Xn("prehash",e.prehash)}class so extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"")}}var lo={Err:so,_tlv:{encode:(e,t)=>{var{Err:r}=lo;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=ei(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");var o=n>127?ei(i.length/2|128):"";return ei(e)+o+i+t},decode(e,t){var{Err:r}=lo,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");var i=t[n++],o=0;if(!!(128&i)){var a=127&i;if(!a)throw new r("tlv.decode(long): indefinite length not supported");if(a>4)throw new r("tlv.decode(long): byte length is too big");var s=t.subarray(n,n+a);if(s.length!==a)throw new r("tlv.decode: length bytes not complete");if(0===s[0])throw new r("tlv.decode(long): zero leftmost byte");for(var l of s)o=o<<8|l;if(n+=a,o<128)throw new r("tlv.decode(long): not minimal encoding")}else o=i;var u=t.subarray(n,n+o);if(u.length!==o)throw new r("tlv.decode: wrong value length");return{v:u,l:t.subarray(n+o)}}},_int:{encode(e){var{Err:t}=lo;if(e<co)throw new t("integer: negative integers are not allowed");var r=ei(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}=lo;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 vi(e)}},toSig(e){var{Err:t,_int:r,_tlv:n}=lo,i=yi("signature",e),{v:o,l:a}=n.decode(48,i);if(a.length)throw new t("invalid signature: left bytes after parsing");var{v:s,l:l}=n.decode(2,o),{v:u,l:c}=n.decode(2,l);if(c.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(s),s:r.decode(u)}},hexFromSig(e){var{_tlv:t,_int:r}=lo,n=t.encode(2,r.encode(e.r))+t.encode(2,r.encode(e.s));return t.encode(48,n)}};function uo(e,t){return ii(fi(e,t))}var co=BigInt(0),ho=BigInt(1);BigInt(2);var vo=BigInt(3),po=BigInt(4);function fo(e){var r=function(e){var r=oo(e);Ci(r,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});var{endo:n,Fp:i,a:o}=r;if(n){if(!i.eql(o,i.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if("object"!=typeof n||"bigint"!=typeof n.beta||"function"!=typeof n.splitScalar)throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze(t({},r))}(e),{Fp:n}=r,i=Ki(r.n,r.nBitLength),o=r.toBytes||((e,t,r)=>{var i=t.toAffine();return mi(Uint8Array.from([4]),n.toBytes(i.x),n.toBytes(i.y))}),a=r.fromBytes||(e=>{var t=e.subarray(1);return{x:n.fromBytes(t.subarray(0,n.BYTES)),y:n.fromBytes(t.subarray(n.BYTES,2*n.BYTES))}});function s(e){var{a:t,b:i}=r,o=n.sqr(e),a=n.mul(o,e);return n.add(n.add(a,n.mul(e,t)),i)}function l(e,t){var r=n.sqr(t),i=s(e);return n.eql(r,i)}if(!l(r.Gx,r.Gy))throw new Error("bad curve params: generator point");var u=n.mul(n.pow(r.a,vo),po),c=n.mul(n.sqr(r.b),BigInt(27));if(n.is0(n.add(u,c)))throw new Error("bad curve params: a or b");function d(e){var t,{allowedPrivateKeyLengths:n,nByteLength:i,wrapPrivateKey:o,n:a}=r;if(n&&"bigint"!=typeof e){if(Zn(e)&&(e=ii(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:vi(yi("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)),Si("private key",t,ho,a),t}function h(e){if(!(e instanceof f))throw new Error("ProjectivePoint expected")}var v=Ii(((e,t)=>{var{px:r,py:i,pz:o}=e;if(n.eql(o,n.ONE))return{x:r,y:i};var a=e.is0();null==t&&(t=a?n.ONE:n.inv(o));var s=n.mul(r,t),l=n.mul(i,t),u=n.mul(o,t);if(a)return{x:n.ZERO,y:n.ZERO};if(!n.eql(u,n.ONE))throw new Error("invZ was invalid");return{x:s,y:l}})),p=Ii((e=>{if(e.is0()){if(r.allowInfinityPoint&&!n.is0(e.py))return;throw new Error("bad point: ZERO")}var{x:t,y:i}=e.toAffine();if(!n.isValid(t)||!n.isValid(i))throw new Error("bad point: x or y not FE");if(!l(t,i))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0}));class f{constructor(e,t,r){if(null==e||!n.isValid(e))throw new Error("x required");if(null==t||!n.isValid(t)||n.is0(t))throw new Error("y required");if(null==r||!n.isValid(r))throw new Error("z required");this.px=e,this.py=t,this.pz=r,Object.freeze(this)}static fromAffine(e){var{x:t,y:r}=e||{};if(!e||!n.isValid(t)||!n.isValid(r))throw new Error("invalid affine point");if(e instanceof f)throw new Error("projective point not allowed");var i=e=>n.eql(e,n.ZERO);return i(t)&&i(r)?f.ZERO:new f(t,r,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){var t=Vi(n,e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(f.fromAffine)}static fromHex(e){var t=f.fromAffine(a(yi("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return f.BASE.multiply(d(e))}static msm(e,t){return io(f,i,e,t)}_setWindowSize(e){m.setWindowSize(this,e)}assertValidity(){p(this)}hasEvenY(){var{y:e}=this.toAffine();if(n.isOdd)return!n.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){h(e);var{px:t,py:r,pz:i}=this,{px:o,py:a,pz:s}=e,l=n.eql(n.mul(t,s),n.mul(o,i)),u=n.eql(n.mul(r,s),n.mul(a,i));return l&&u}negate(){return new f(this.px,n.neg(this.py),this.pz)}double(){var{a:e,b:t}=r,i=n.mul(t,vo),{px:o,py:a,pz:s}=this,l=n.ZERO,u=n.ZERO,c=n.ZERO,d=n.mul(o,o),h=n.mul(a,a),v=n.mul(s,s),p=n.mul(o,a);return p=n.add(p,p),c=n.mul(o,s),c=n.add(c,c),l=n.mul(e,c),u=n.mul(i,v),u=n.add(l,u),l=n.sub(h,u),u=n.add(h,u),u=n.mul(l,u),l=n.mul(p,l),c=n.mul(i,c),v=n.mul(e,v),p=n.sub(d,v),p=n.mul(e,p),p=n.add(p,c),c=n.add(d,d),d=n.add(c,d),d=n.add(d,v),d=n.mul(d,p),u=n.add(u,d),v=n.mul(a,s),v=n.add(v,v),d=n.mul(v,p),l=n.sub(l,d),c=n.mul(v,h),c=n.add(c,c),c=n.add(c,c),new f(l,u,c)}add(e){h(e);var{px:t,py:i,pz:o}=this,{px:a,py:s,pz:l}=e,u=n.ZERO,c=n.ZERO,d=n.ZERO,v=r.a,p=n.mul(r.b,vo),g=n.mul(t,a),y=n.mul(i,s),m=n.mul(o,l),w=n.add(t,i),b=n.add(a,s);w=n.mul(w,b),b=n.add(g,y),w=n.sub(w,b),b=n.add(t,o);var S=n.add(a,l);return b=n.mul(b,S),S=n.add(g,m),b=n.sub(b,S),S=n.add(i,o),u=n.add(s,l),S=n.mul(S,u),u=n.add(y,m),S=n.sub(S,u),d=n.mul(v,b),u=n.mul(p,m),d=n.add(u,d),u=n.sub(y,d),d=n.add(y,d),c=n.mul(u,d),y=n.add(g,g),y=n.add(y,g),m=n.mul(v,m),b=n.mul(p,b),y=n.add(y,m),m=n.sub(g,m),m=n.mul(v,m),b=n.add(b,m),g=n.mul(y,b),c=n.add(c,g),g=n.mul(S,b),u=n.mul(w,u),u=n.sub(u,g),g=n.mul(w,y),d=n.mul(S,d),d=n.add(d,g),new f(u,c,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(f.ZERO)}wNAF(e){return m.wNAFCached(this,e,f.normalizeZ)}multiplyUnsafe(e){var{endo:t,n:i}=r;Si("scalar",e,co,i);var o=f.ZERO;if(e===co)return o;if(this.is0()||e===ho)return this;if(!t||m.hasPrecomputes(this))return m.wNAFCachedUnsafe(this,e,f.normalizeZ);for(var{k1neg:a,k1:s,k2neg:l,k2:u}=t.splitScalar(e),c=o,d=o,h=this;s>co||u>co;)s&ho&&(c=c.add(h)),u&ho&&(d=d.add(h)),h=h.double(),s>>=ho,u>>=ho;return a&&(c=c.negate()),l&&(d=d.negate()),d=new f(n.mul(d.px,t.beta),d.py,d.pz),c.add(d)}multiply(e){var t,i,{endo:o,n:a}=r;if(Si("scalar",e,ho,a),o){var{k1neg:s,k1:l,k2neg:u,k2:c}=o.splitScalar(e),{p:d,f:h}=this.wNAF(l),{p:v,f:p}=this.wNAF(c);d=m.constTimeNegate(s,d),v=m.constTimeNegate(u,v),v=new f(n.mul(v.px,o.beta),v.py,v.pz),t=d.add(v),i=h.add(p)}else{var{p:g,f:y}=this.wNAF(e);t=g,i=y}return f.normalizeZ([t,i])[0]}multiplyAndAddUnsafe(e,t,r){var n=f.BASE,i=(e,t)=>t!==co&&t!==ho&&e.equals(n)?e.multiply(t):e.multiplyUnsafe(t),o=i(this,t).add(i(e,r));return o.is0()?void 0:o}toAffine(e){return v(this,e)}isTorsionFree(){var{h:e,isTorsionFree:t}=r;if(e===ho)return!0;if(t)return t(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){var{h:e,clearCofactor:t}=r;return e===ho?this:t?t(f,this):this.multiplyUnsafe(r.h)}toRawBytes(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return Xn("isCompressed",e),this.assertValidity(),o(f,this,e)}toHex(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return Xn("isCompressed",e),ii(this.toRawBytes(e))}}f.BASE=new f(r.Gx,r.Gy,n.ONE),f.ZERO=new f(n.ZERO,n.ONE,n.ZERO);var{endo:g,nBitLength:y}=r,m=no(f,g?Math.ceil(y/2):y);return{CURVE:r,ProjectivePoint:f,normPrivateKeyToScalar:d,weierstrassEquation:s,isWithinCurveOrder:function(e){return bi(e,ho,r.n)}}}function go(e){var r,n=(Ci(r=oo(e),{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze(t({lowS:!0},r))),{Fp:i,n:o,nByteLength:a,nBitLength:s}=n,l=i.BYTES+1,u=2*i.BYTES+1;function c(e){return Oi(e,o)}function d(e){return Mi(e,o)}var{ProjectivePoint:h,normPrivateKeyToScalar:v,weierstrassEquation:p,isWithinCurveOrder:f}=fo(t(t({},n),{},{toBytes(e,t,r){var n=t.toAffine(),o=i.toBytes(n.x),a=mi;return Xn("isCompressed",r),r?a(Uint8Array.from([t.hasEvenY()?2:3]),o):a(Uint8Array.from([4]),o,i.toBytes(n.y))},fromBytes(e){var t=e.length,r=e[0],n=e.subarray(1);if(t!==l||2!==r&&3!==r){if(t===u&&4===r)return{x:i.fromBytes(n.subarray(0,i.BYTES)),y:i.fromBytes(n.subarray(i.BYTES,2*i.BYTES))};throw new Error("invalid Point, expected length of "+l+", or uncompressed "+u+", got "+t)}var o=vi(n);if(!bi(o,ho,i.ORDER))throw new Error("Point is not on curve");var a,s=p(o);try{a=i.sqrt(s)}catch(e){var c=e instanceof Error?": "+e.message:"";throw new Error("Point is not on curve"+c)}return!(1&~r)!==((a&ho)===ho)&&(a=i.neg(a)),{x:o,y:a}}}));function g(e){return e>o>>ho}var y=(e,t,r)=>vi(e.slice(t,r));class m{constructor(e,t,r){Si("r",e,ho,o),Si("s",t,ho,o),this.r=e,this.s=t,null!=r&&(this.recovery=r),Object.freeze(this)}static fromCompact(e){var t=a;return e=yi("compactSignature",e,2*t),new m(y(e,0,t),y(e,t,2*t))}static fromDER(e){var{r:t,s:r}=lo.toSig(yi("DER",e));return new m(t,r)}assertValidity(){}addRecoveryBit(e){return new m(this.r,this.s,e)}recoverPublicKey(e){var{r:t,s:r,recovery:o}=this,a=E(yi("msgHash",e));if(null==o||![0,1,2,3].includes(o))throw new Error("recovery id invalid");var s=2===o||3===o?t+n.n:t;if(s>=i.ORDER)throw new Error("recovery id 2 or 3 invalid");var l=1&o?"03":"02",u=h.fromHex(l+uo(s,i.BYTES)),v=d(s),p=c(-a*v),f=c(r*v),g=h.BASE.multiplyAndAddUnsafe(u,p,f);if(!g)throw new Error("point at infinify");return g.assertValidity(),g}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new m(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return hi(this.toDERHex())}toDERHex(){return lo.hexFromSig(this)}toCompactRawBytes(){return hi(this.toCompactHex())}toCompactHex(){var e=a;return uo(this.r,e)+uo(this.s,e)}}var w={isValidPrivateKey(e){try{return v(e),!0}catch(e){return!1}},normPrivateKeyToScalar:v,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=Wi(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?pi(e):vi(e),t-Pi)+Pi;return r?gi(a,i):fi(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=yi("key",e).length,r=i.BYTES,o=r+1,s=2*r+1;return n.allowedPrivateKeyLengths||a===o?void 0:t===o||t===s}var S=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");var t=vi(e),r=8*e.length-s;return r>0?t>>BigInt(r):t},E=n.bits2int_modN||function(e){return c(S(e))},k=Ei(s);function x(e){return Si("num < 2^"+s,e,co,k),fi(e,a)}function A(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:C;if(["recovered","canonical"].some((e=>e in r)))throw new Error("sign() legacy options not supported");var{hash:o,randomBytes:a}=n,{lowS:s,prehash:l,extraEntropy:u}=r;null==s&&(s=!0),e=yi("msgHash",e),ao(r),l&&(e=yi("prehashed msgHash",o(e)));var p=E(e),y=v(t),w=[x(y),x(p)];if(null!=u&&!1!==u){var b=!0===u?a(i.BYTES):u;w.push(yi("extraEntropy",b))}var k=mi(...w),A=p;return{seed:k,k2sig:function(e){var t=S(e);if(f(t)){var r=d(t),n=h.BASE.multiply(t).toAffine(),i=c(n.x);if(i!==co){var o=c(r*c(A+i*y));if(o!==co){var a=(n.x===i?0:2)|Number(n.y&ho),l=o;return s&&g(o)&&(l=function(e){return g(e)?c(-e):e}(o),a^=1),new m(i,l,a)}}}}}}var C={lowS:n.lowS,prehash:!1},I={lowS:n.lowS,prehash:!1};return h.BASE._setWindowSize(8),{CURVE:n,getPublicKey:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return h.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(!0===b(e))throw new Error("first arg must be private key");if(!1===b(t))throw new Error("second arg must be public key");return h.fromHex(t).multiply(v(e)).toRawBytes(r)},sign:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:C,{seed:i,k2sig:o}=A(e,t,r),a=n,s=function(e,t,r){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof r)throw new Error("hmacFn must be a function");var n=ki(e),i=ki(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]:ki(0);i=s(xi([0]),e),n=s(),0!==e.length&&(i=s(xi([1]),e),n=s())},u=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");for(var e=0,r=[];e<t;){var i=(n=s()).slice();r.push(i),e+=n.length}return mi(...r)};return(e,t)=>{a(),l(e);for(var r=void 0;!(r=t(u()));)l();return a(),r}}(a.hash.outputLen,a.nByteLength,a.hmac);return s(i,o)},verify:function(e,t,r){var i,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:I,a=e;t=yi("msgHash",t),r=yi("publicKey",r);var{lowS:s,prehash:l,format:u}=o;if(ao(o),"strict"in o)throw new Error("options.strict was renamed to lowS");if(void 0!==u&&"compact"!==u&&"der"!==u)throw new Error("format must be compact or der");var v="string"==typeof a||Zn(a),p=!v&&!u&&"object"==typeof a&&null!==a&&"bigint"==typeof a.r&&"bigint"==typeof a.s;if(!v&&!p)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");var f,g=void 0;try{if(p&&(g=new m(a.r,a.s)),v){try{"compact"!==u&&(g=m.fromDER(a))}catch(e){if(!(e instanceof lo.Err))throw e}g||"der"===u||(g=m.fromCompact(a))}f=h.fromHex(r)}catch(e){return!1}if(!g)return!1;if(s&&g.hasHighS())return!1;l&&(t=n.hash(t));var{r:y,s:w}=g,b=E(t),S=d(w),k=c(b*S),x=c(y*S),A=null===(i=h.BASE.multiplyAndAddUnsafe(f,k,x))||void 0===i?void 0:i.toAffine();return!!A&&c(A.x)===y},ProjectivePoint:h,Signature:m,utils:w}}var yo=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),mo=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),wo=BigInt(0),bo=BigInt(1),So=BigInt(2),Eo=(e,t)=>(e+t/So)/t;var ko=Ki(yo,void 0,void 0,{sqrt:function(e){var t=yo,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),a=BigInt(23),s=BigInt(44),l=BigInt(88),u=e*e*e%t,c=u*u*e%t,d=Li(c,r,t)*c%t,h=Li(d,r,t)*c%t,v=Li(h,So,t)*u%t,p=Li(v,i,t)*v%t,f=Li(p,o,t)*p%t,g=Li(f,s,t)*f%t,y=Li(g,l,t)*g%t,m=Li(y,s,t)*f%t,w=Li(m,r,t)*c%t,b=Li(w,a,t)*p%t,S=Li(b,n,t)*u%t,E=Li(S,So,t);if(!ko.eql(ko.sqr(E),e))throw new Error("Cannot find square root");return E}}),xo=function(e,r){var n=r=>go(t(t({},e),function(e){return{hash:e,hmac:function(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return Qn(e,t,rn(...n))},randomBytes:sn}}(r)));return t(t({},n(r)),{},{create:n})}({a:wo,b:BigInt(7),Fp:ko,n:mo,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{var t=mo,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-bo*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,a=BigInt("0x100000000000000000000000000000000"),s=Eo(o*e,t),l=Eo(-n*e,t),u=Oi(e-s*r-l*i,t),c=Oi(-s*n-l*o,t),d=u>a,h=c>a;if(d&&(u=t-u),h&&(c=t-c),u>a||c>a)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:d,k1:u,k2neg:h,k2:c}}}},Kn),Ao=BigInt(0),Co=BigInt(1),Io=BigInt(2),To=BigInt(8),Po={zip215:!0};function _o(e){var r,n,i=(n=oo(r=e),Ci(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze(t({},n))),{Fp:o,n:a,prehash:s,hash:l,randomBytes:u,nByteLength:c,h:d}=i,h=Io<<BigInt(8*c)-Co,v=o.create,p=Ki(i.n,i.nBitLength);if(!function(e,t){var r=o.sqr(e),n=o.sqr(t),a=o.add(o.mul(i.a,r),n),s=o.add(o.ONE,o.mul(i.d,o.mul(r,n)));return o.eql(a,s)}(i.Gx,i.Gy))throw new Error("bad curve params: generator point");var f=i.uvRatio||((e,t)=>{try{return{isValid:!0,value:o.sqrt(e*o.inv(t))}}catch(e){return{isValid:!1,value:Ao}}}),g=i.adjustScalarBytes||(e=>e),y=i.domain||((e,t,r)=>{if(Xn("phflag",r),t.length||r)throw new Error("Contexts/pre-hash are not supported");return e});function m(e,t){Si("coordinate "+e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2]?Co:Ao,h)}function w(e){if(!(e instanceof E))throw new Error("ExtendedPoint expected")}var b=Ii(((e,t)=>{var{ex:r,ey:n,ez:i}=e,a=e.is0();null==t&&(t=a?To:o.inv(i));var s=v(r*t),l=v(n*t),u=v(i*t);if(a)return{x:Ao,y:Co};if(u!==Co)throw new Error("invZ was invalid");return{x:s,y:l}})),S=Ii((e=>{var{a:t,d:r}=i;if(e.is0())throw new Error("bad point: ZERO");var{ex:n,ey:o,ez:a,et:s}=e,l=v(n*n),u=v(o*o),c=v(a*a),d=v(c*c),h=v(l*t);if(v(c*v(h+u))!==v(d+v(r*v(l*u))))throw new Error("bad point: equation left != right (1)");if(v(n*o)!==v(a*s))throw new Error("bad point: equation left != right (2)");return!0}));class E{constructor(e,t,r,n){m("x",e),m("y",t),m("z",r,!0),m("t",n),this.ex=e,this.ey=t,this.ez=r,this.et=n,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof E)throw new Error("extended point not allowed");var{x:t,y:r}=e||{};return m("x",t),m("y",r),new E(t,r,Co,v(t*r))}static normalizeZ(e){var t=Vi(o,e.map((e=>e.ez)));return e.map(((e,r)=>e.toAffine(t[r]))).map(E.fromAffine)}static msm(e,t){return io(E,p,e,t)}_setWindowSize(e){A.setWindowSize(this,e)}assertValidity(){S(this)}equals(e){w(e);var{ex:t,ey:r,ez:n}=this,{ex:i,ey:o,ez:a}=e,s=v(t*a),l=v(i*n),u=v(r*a),c=v(o*n);return s===l&&u===c}is0(){return this.equals(E.ZERO)}negate(){return new E(v(-this.ex),this.ey,this.ez,v(-this.et))}double(){var{a:e}=i,{ex:t,ey:r,ez:n}=this,o=v(t*t),a=v(r*r),s=v(Io*v(n*n)),l=v(e*o),u=t+r,c=v(v(u*u)-o-a),d=l+a,h=d-s,p=l-a,f=v(c*h),g=v(d*p),y=v(c*p),m=v(h*d);return new E(f,g,m,y)}add(e){w(e);var{a:t,d:r}=i,{ex:n,ey:o,ez:a,et:s}=this,{ex:l,ey:u,ez:c,et:d}=e,h=v(n*l),p=v(o*u),f=v(s*r*d),g=v(a*c),y=v((n+o)*(l+u)-h-p),m=g-f,b=g+f,S=v(p-t*h),k=v(y*m),x=v(b*S),A=v(y*S),C=v(m*b);return new E(k,x,C,A)}subtract(e){return this.add(e.negate())}wNAF(e){return A.wNAFCached(this,e,E.normalizeZ)}multiply(e){var t=e;Si("scalar",t,Co,a);var{p:r,f:n}=this.wNAF(t);return E.normalizeZ([r,n])[0]}multiplyUnsafe(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:E.ZERO,r=e;return Si("scalar",r,Ao,a),r===Ao?x:this.is0()||r===Co?this:A.wNAFCachedUnsafe(this,r,E.normalizeZ,t)}isSmallOrder(){return this.multiplyUnsafe(d).is0()}isTorsionFree(){return A.unsafeLadder(this,a).is0()}toAffine(e){return b(this,e)}clearCofactor(){var{h:e}=i;return e===Co?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=yi("pointHex",e,a),Xn("zip215",t);var s=e.slice(),l=e[a-1];s[a-1]=-129&l;var u=pi(s),c=t?h:o.ORDER;Si("pointHex.y",u,Ao,c);var d=v(u*u),p=v(d-Co),g=v(r*d-n),{isValid:y,value:m}=f(p,g);if(!y)throw new Error("Point.fromHex: invalid y coordinate");var w=(m&Co)===Co,b=!!(128&l);if(!t&&m===Ao&&b)throw new Error("Point.fromHex: x=0 and x_0=1");return b!==w&&(m=v(-m)),E.fromAffine({x:m,y:u})}static fromPrivateKey(e){var{scalar:t}=T(e);return k.multiply(t)}toRawBytes(){var{x:e,y:t}=this.toAffine(),r=gi(t,o.BYTES);return r[r.length-1]|=e&Co?128:0,r}toHex(){return ii(this.toRawBytes())}}E.BASE=new E(i.Gx,i.Gy,Co,v(i.Gx*i.Gy)),E.ZERO=new E(Ao,Co,Co,Ao);var{BASE:k,ZERO:x}=E,A=no(E,8*c);function C(e){return Oi(e,a)}function I(e){return C(pi(e))}function T(e){var t=o.BYTES;e=yi("private key",e,t);var r=yi("hashed private key",l(e),2*t),n=g(r.slice(0,t));return{head:n,prefix:r.slice(t,2*t),scalar:I(n)}}function P(e){var{head:t,prefix:r,scalar:n}=T(e),i=k.multiply(n),o=i.toRawBytes();return{head:t,prefix:r,scalar:n,point:i,pointBytes:o}}function _(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Uint8Array.of(),t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];var i=mi(...r);return I(l(y(i,yi("context",e),!!s)))}var B=Po;k._setWindowSize(8);var N={getExtendedPublicKey:P,randomPrivateKey:()=>u(o.BYTES),precompute(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:8,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:E.BASE;return t._setWindowSize(e),t.multiply(BigInt(3)),t}};return{CURVE:i,getPublicKey:function(e){return P(e).pointBytes},sign:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e=yi("message",e),s&&(e=s(e));var{prefix:n,scalar:i,pointBytes:l}=P(t),u=_(r.context,n,e),c=k.multiply(u).toRawBytes(),d=C(u+_(r.context,c,l,e)*i);return Si("signature.s",d,Ao,a),yi("result",mi(c,gi(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=yi("signature",e,2*l),t=yi("message",t),r=yi("publicKey",r,l),void 0!==a&&Xn("zip215",a),s&&(t=s(t));var u,c,d,h=pi(e.slice(l,2*l));try{u=E.fromHex(r,a),c=E.fromHex(e.slice(0,l),a),d=k.multiplyUnsafe(h)}catch(e){return!1}if(!a&&u.isSmallOrder())return!1;var v=_(i,c.toRawBytes(),u.toRawBytes(),t);return c.add(u.multiplyUnsafe(v)).subtract(d).clearCofactor().equals(E.ZERO)},ExtendedPoint:E,utils:N}}var Bo=BigInt(0),No=BigInt(1),Do=BigInt(2);function Ro(e){var r,n=(Ci(r=e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze(t({},r))),{P:i,type:o,adjustScalarBytes:a,powPminus2:s}=n,l="x25519"===o;if(!l&&"x448"!==o)throw new Error("invalid type");var u=l?255:448,c=l?32:56,d=l?BigInt(9):BigInt(5),h=l?BigInt(121665):BigInt(39081),v=l?Do**BigInt(254):Do**BigInt(447),p=l?BigInt(8)*Do**BigInt(251)-No:BigInt(4)*Do**BigInt(445)-No,f=v+p+No,g=e=>Oi(e,i),y=m(d);function m(e){return gi(g(e),c)}function w(e,t){var r=function(e,t){Si("u",e,Bo,i),Si("scalar",t,v,f);for(var r=t,n=e,o=No,a=Bo,l=e,c=No,d=Bo,p=BigInt(u-1);p>=Bo;p--){var y=r>>p&No;d^=y,({x_2:o,x_3:l}=S(d,o,l)),({x_2:a,x_3:c}=S(d,a,c)),d=y;var m=o+a,w=g(m*m),b=o-a,E=g(b*b),k=w-E,x=l+c,A=g((l-c)*m),C=g(x*b),I=A+C,T=A-C;l=g(I*I),c=g(n*g(T*T)),o=g(w*E),a=g(k*(w+g(h*k)))}({x_2:o,x_3:l}=S(d,o,l)),({x_2:a,x_3:c}=S(d,a,c));var P=s(a);return g(o*P)}(function(e){var t=yi("u coordinate",e,c);return l&&(t[31]&=127),g(pi(t))}(t),function(e){return pi(a(yi("scalar",e,c)))}(e));if(r===Bo)throw new Error("invalid private or public key received");return m(r)}function b(e){return w(e,y)}function S(e,t,r){var n=g(e*(t-r));return{x_2:t=g(t-n),x_3:r=g(r+n)}}return{scalarMult:w,scalarMultBase:b,getSharedSecret:(e,t)=>w(e,t),getPublicKey:e=>b(e),utils:{randomPrivateKey:()=>n.randomBytes(c)},GuBytes:y.slice()}}var Oo=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Lo=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);var Mo=BigInt(1),Uo=BigInt(2),Fo=BigInt(3),zo=BigInt(5),jo=BigInt(8);function Vo(e){var t=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),o=Oo,a=e*e%o*e%o,s=Li(a,Uo,o)*a%o,l=Li(s,Mo,o)*e%o,u=Li(l,zo,o)*l%o,c=Li(u,t,o)*u%o,d=Li(c,r,o)*c%o,h=Li(d,n,o)*d%o,v=Li(h,i,o)*h%o,p=Li(v,i,o)*h%o,f=Li(p,t,o)*u%o;return{pow_p_5_8:Li(f,Uo,o)*e%o,b2:a}}function qo(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function Ho(e,t){var r=Oo,n=Oi(t*t*t,r),i=Oi(n*n*t,r),o=Oi(e*n*Vo(e*i).pow_p_5_8,r),a=Oi(t*o*o,r),s=o,l=Oi(o*Lo,r),u=a===e,c=a===Oi(-e,r),d=a===Oi(-e*Lo,r);return u&&(o=s),(c||d)&&(o=l),(Oi(o,r)&Pi)===Pi&&(o=Oi(-o,r)),{isValid:u||c,value:o}}var Ko=(()=>Ki(Oo,void 0,!0))(),Wo=(()=>({a:Ko.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ko,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:jo,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Wn,randomBytes:sn,adjustScalarBytes:qo,uvRatio:Ho}))(),Go=(()=>_o(Wo))(),Qo=(()=>Ro({P:Oo,type:"x25519",powPminus2:e=>{var t=Oo,{pow_p_5_8:r,b2:n}=Vo(e);return Oi(Li(r,Fo,t)*n,t)},adjustScalarBytes:qo,randomBytes:sn}))(),Yo=Kn,Jo=Wn;function Zo(e,t,r,n){Tr(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(Cr(o),Cr(a),Cr(s),o<1)throw new Error("iterations (c) should be >= 1");var l=tn(t),u=tn(r),c=new Uint8Array(a),d=Qn.create(e,l),h=d._cloneInto().update(u);return{c:o,dkLen:a,asyncTick:s,DK:c,PRF:d,PRFSalt:h}}function $o(e,t,r,n,i){return e.destroy(),t.destroy(),n&&n.destroy(),Nr(i),r}function Xo(e,t,r,n){return ea.apply(this,arguments)}function ea(){return ea=r((function*(e,t,r,n){for(var i,{c:o,dkLen:a,asyncTick:s,DK:l,PRF:u,PRFSalt:c}=Zo(e,t,r,n),d=new Uint8Array(4),h=Dr(d),v=new Uint8Array(u.outputLen),p=function*(){var e=l.subarray(g,g+u.outputLen);h.setInt32(0,f,!1),(i=c._cloneInto(i)).update(d).digestInto(v),e.set(v.subarray(0,e.length)),yield function(e,t,r){return $r.apply(this,arguments)}(o-1,s,(()=>{u._cloneInto(i).update(v).digestInto(v);for(var t=0;t<e.length;t++)e[t]^=v[t]}))},f=1,g=0;g<a;f++,g+=u.outputLen)yield*p();return $o(u,c,l,i,v)})),ea.apply(this,arguments)}var ta,ra={exports:{}};var na=(ta||(ta=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function o(e,t,n,o,a){if("function"!=typeof n)throw new TypeError("The listener must be a function");var s=new i(n,o||e,a),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],s]:e._events[l].push(s):(e._events[l]=s,e._eventsCount++),e}function a(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function s(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),s.prototype.eventNames=function(){var e,n,i=[];if(0===this._eventsCount)return i;for(n in e=this._events)t.call(e,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},s.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,a=new Array(o);i<o;i++)a[i]=n[i].fn;return a},s.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},s.prototype.emit=function(e,t,n,i,o,a){var s=r?r+e:e;if(!this._events[s])return!1;var l,u,c=this._events[s],d=arguments.length;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,o),!0;case 6:return c.fn.call(c.context,t,n,i,o,a),!0}for(u=1,l=new Array(d-1);u<d;u++)l[u-1]=arguments[u];c.fn.apply(c.context,l)}else{var h,v=c.length;for(u=0;u<v;u++)switch(c[u].once&&this.removeListener(e,c[u].fn,void 0,!0),d){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,t);break;case 3:c[u].fn.call(c[u].context,t,n);break;case 4:c[u].fn.call(c[u].context,t,n,i);break;default:if(!l)for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];c[u].fn.apply(c[u].context,l)}}return!0},s.prototype.on=function(e,t,r){return o(this,e,t,r,!1)},s.prototype.once=function(e,t,r){return o(this,e,t,r,!0)},s.prototype.removeListener=function(e,t,n,i){var o=r?r+e:e;if(!this._events[o])return this;if(!t)return a(this,o),this;var s=this._events[o];if(s.fn)s.fn!==t||i&&!s.once||n&&s.context!==n||a(this,o);else{for(var l=0,u=[],c=s.length;l<c;l++)(s[l].fn!==t||i&&!s[l].once||n&&s[l].context!==n)&&u.push(s[l]);u.length?this._events[o]=1===u.length?u[0]:u:a(this,o)}return this},s.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&a(this,t)):(this._events=new n,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prefixed=r,s.EventEmitter=s,e.exports=s}(ra)),ra.exports),ia=a(na),oa=function(e,t){return oa=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])},oa(e,t)};function aa(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}oa(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function sa(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 la(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 ua(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 ca(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 da(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 ha(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(da(arguments[t]));return e}function va(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i<o;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))}function pa(e){return this instanceof pa?(this.v=e,this):new pa(e)}function fa(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,i=r.apply(e,t||[]),o=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",(function(e){return function(t){return Promise.resolve(t).then(e,u)}})),n[Symbol.asyncIterator]=function(){return this},n;function a(e,t){i[e]&&(n[e]=function(t){return new Promise((function(r,n){o.push([e,t,r,n])>1||s(e,t)}))},t&&(n[e]=t(n[e])))}function s(e,t){try{(r=i[e](t)).value instanceof pa?Promise.resolve(r.value.v).then(l,u):c(o[0][2],r)}catch(e){c(o[0][3],e)}var r}function l(e){s("next",e)}function u(e){s("throw",e)}function c(e,t){e(t),o.shift(),o.length&&s(o[0][0],o[0][1])}}function ga(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=ca(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,i){(function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)})(n,i,(t=e[r](t)).done,t.value)}))}}}function ya(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)}"function"==typeof SuppressedError&&SuppressedError;var ma=Symbol.for("@libp2p/connection"),wa=Symbol.for("@libp2p/content-routing"),ba=Symbol.for("@libp2p/peer-discovery"),Sa=Symbol.for("@libp2p/peer-id");function Ea(e){return Boolean(null==e?void 0:e[Sa])}var ka,xa=Symbol.for("@libp2p/peer-routing"),Aa="keep-alive",Ca=Symbol.for("@libp2p/transport");!function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"}(ka||(ka={}));let Ia=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The operation was aborted"),this.name="AbortError"}};e(Ia,"name","AbortError");class Ta extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unexpected Peer"),this.name="UnexpectedPeerError"}}e(Ta,"name","UnexpectedPeerError");let Pa=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid crypto exchange"),this.name="InvalidCryptoExchangeError"}};e(Pa,"name","InvalidCryptoExchangeError");let _a=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid parameters"),this.name="InvalidParametersError"}};e(_a,"name","InvalidParametersError");class Ba extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid public key"),this.name="InvalidPublicKeyError"}}e(Ba,"name","InvalidPublicKeyError");class Na extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid private key"),this.name="InvalidPrivateKeyError"}}e(Na,"name","InvalidPrivateKeyError");class Da extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unsupported operation"),this.name="UnsupportedOperationError"}}e(Da,"name","UnsupportedOperationError");class Ra extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The connection is closing"),this.name="ConnectionClosingError"}}e(Ra,"name","ConnectionClosingError");class Oa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The connection is closed"),this.name="ConnectionClosedError"}}e(Oa,"name","ConnectionClosedError");class La extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Connection failed"),this.name="ConnectionFailedError"}}e(La,"name","ConnectionFailedError");class Ma extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The muxer is closed"),this.name="MuxerClosedError"}}e(Ma,"name","MuxerClosedError");class Ua extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The stream has been reset"),this.name="StreamResetError"}}e(Ua,"name","StreamResetError");class Fa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The stream is in an invalid state"),this.name="StreamStateError"}}e(Fa,"name","StreamStateError");let za=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not found"),this.name="NotFoundError"}};e(za,"name","NotFoundError");class ja extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid PeerID"),this.name="InvalidPeerIdError"}}e(ja,"name","InvalidPeerIdError");class Va extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid multiaddr"),this.name="InvalidMultiaddrError"}}e(Va,"name","InvalidMultiaddrError");class qa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid CID"),this.name="InvalidCIDError"}}e(qa,"name","InvalidCIDError");class Ha extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid Multihash"),this.name="InvalidMultihashError"}}e(Ha,"name","InvalidMultihashError");class Ka extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unsupported protocol error"),this.name="UnsupportedProtocolError"}}e(Ka,"name","UnsupportedProtocolError");class Wa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid message"),this.name="InvalidMessageError"}}e(Wa,"name","InvalidMessageError");class Ga extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Protocol error"),this.name="ProtocolError"}}e(Ga,"name","ProtocolError");let Qa=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Timed out"),this.name="TimeoutError"}};e(Qa,"name","TimeoutError");class Ya extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not started"),this.name="NotStartedError"}}e(Ya,"name","NotStartedError");class Ja extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Already started"),this.name="AlreadyStartedError"}}e(Ja,"name","AlreadyStartedError");class Za extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Dial error"),this.name="DialError"}}e(Za,"name","DialError");class $a extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Listen error"),this.name="ListenError"}}e($a,"name","ListenError");class Xa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Limited connection"),this.name="LimitedConnectionError"}}e(Xa,"name","LimitedConnectionError");class es extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Too many inbound protocol streams"),this.name="TooManyInboundProtocolStreamsError"}}e(es,"name","TooManyInboundProtocolStreamsError");class ts extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Too many outbound protocol streams"),this.name="TooManyOutboundProtocolStreamsError"}}e(ts,"name","TooManyOutboundProtocolStreamsError");class rs extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unsupported key type"),this.name="UnsupportedKeyTypeError"}}e(rs,"name","UnsupportedKeyTypeError");class ns extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not implemented"),this.name="NotImplementedError"}}e(ns,"name","NotImplementedError");var is=new WeakMap;let os=class extends EventTarget{constructor(){super(),n(this,is,new Map)}listenerCount(e){var t=o(is,this).get(e);return null==t?0:t.length}addEventListener(e,t,r){var n;super.addEventListener(e,t,r);var i=o(is,this).get(e);null==i&&(i=[],o(is,this).set(e,i)),i.push({callback:t,once:null!==(n=!0!==r&&!1!==r&&(null==r?void 0:r.once))&&void 0!==n&&n})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),null!=t?t:null,r);var n=o(is,this).get(e);null!=n&&(n=n.filter((e=>{var{callback:r}=e;return r!==t})),o(is,this).set(e,n))}dispatchEvent(e){var t=super.dispatchEvent(e),r=o(is,this).get(e.type);return null==r||(r=r.filter((e=>{var{once:t}=e;return!t})),o(is,this).set(e.type,r)),t}safeDispatchEvent(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.dispatchEvent(new CustomEvent(e,t))}};function as(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}function ss(){return ls.apply(this,arguments)}function ls(){return ls=r((function*(){for(var e=[],t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];for(var o of n)as(o)&&e.push(o);yield Promise.all(e.map(function(){var e=r((function*(e){null!=e.beforeStart&&(yield e.beforeStart())}));return function(t){return e.apply(this,arguments)}}())),yield Promise.all(e.map(function(){var e=r((function*(e){yield e.start()}));return function(t){return e.apply(this,arguments)}}())),yield Promise.all(e.map(function(){var e=r((function*(e){null!=e.afterStart&&(yield e.afterStart())}));return function(t){return e.apply(this,arguments)}}()))})),ls.apply(this,arguments)}function us(){return cs.apply(this,arguments)}function cs(){return cs=r((function*(){for(var e=[],t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];for(var o of n)as(o)&&e.push(o);yield Promise.all(e.map(function(){var e=r((function*(e){null!=e.beforeStop&&(yield e.beforeStop())}));return function(t){return e.apply(this,arguments)}}())),yield Promise.all(e.map(function(){var e=r((function*(e){yield e.stop()}));return function(t){return e.apply(this,arguments)}}())),yield Promise.all(e.map(function(){var e=r((function*(e){null!=e.afterStop&&(yield e.afterStop())}));return function(t){return e.apply(this,arguments)}}()))})),cs.apply(this,arguments)}var ds=Symbol.for("@libp2p/service-capabilities"),hs=Symbol.for("@libp2p/service-dependencies"),vs=Symbol.for("@achingbrain/uint8arraylist");function ps(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 fs(e){return Boolean(null==e?void 0:e[vs])}class gs{constructor(){e(this,"bufs",void 0),e(this,"length",void 0),e(this,vs,!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(!fs(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(!fs(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=ps(this.bufs,e);return t.buf[t.index]}set(e,t){var r=ps(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(!fs(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 gs;return i.length=n,i.bufs=[...r],i}_subList(e,t){if(e=null!=e?e:0,t=null!=t?t:this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(0===e&&t===this.length)return{bufs:this.bufs,length:this.length};for(var r=[],n=0,i=0;i<this.bufs.length;i++){var o=this.bufs[i],a=n,s=a+o.byteLength;if(n=s,!(e>=s)){var l=e>=a&&e<s,u=t>a&&t<=s;if(l&&u){if(e===a&&t===s){r.push(o);break}var c=e-a;r.push(o.subarray(c,c+(t-e)));break}if(l){if(0===e){r.push(o);continue}r.push(o.subarray(e-a))}else{if(u){if(t===s){r.push(o);break}r.push(o.subarray(0,t-a));break}r.push(o)}}}return{bufs:r,length:t-e}}indexOf(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!(fs(e)||e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');var r=e instanceof Uint8Array?e:e.subarray();if(t=Number(null!=t?t:0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;var n=r.byteLength;if(0===n)throw new TypeError("search must be at least 1 byte long");for(var i=new Int32Array(256),o=0;o<256;o++)i[o]=-1;for(var a=0;a<n;a++)i[r[a]]=a;for(var s,l=i,u=this.byteLength-r.byteLength,c=r.byteLength-1,d=t;d<=u;d+=s){s=0;for(var h=c;h>=0;h--){var v=this.get(d+h);if(r[h]!==v){s=Math.max(1,h-l[v]);break}}if(0===s)return d}return-1}getInt8(e){var t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){var r=dt(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){var r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){var n=ct(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){var r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){var n=ct(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){var r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){var n=ct(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){var t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){var r=dt(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){var r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){var n=ct(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){var r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){var n=ct(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){var r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){var n=ct(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){var r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){var n=ct(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){var r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){var n=ct(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(null==e)return!1;if(!(e instanceof gs))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(var t=0;t<this.bufs.length;t++)if(!St(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){var r=new gs;return r.bufs=e,null==t&&(t=e.reduce(((e,t)=>e+t.byteLength),0)),r.length=t,r}}var ys=parseInt("11111",2),ms=parseInt("10000000",2),ws=parseInt("01111111",2),bs={0:ks,1:ks,2:function(e,t){for(var r=Es(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=Es(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=Es(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=Es(e,t),n=t.offset+r,i=e[t.offset];t.offset++;var o=0,a=0;i<40?(o=0,a=i):i<80?(o=1,a=i-40):(o=2,a=i-80);var s="".concat(o,".").concat(a),l=[];for(;t.offset<n;){var u=e[t.offset];if(t.offset++,l.push(127&u),u<128){l.reverse();for(var c=0,d=0;d<l.length;d++)c+=l[d]<<7*d;s+=".".concat(c),l=[]}}return s},16:ks,22:ks,48:ks};function Ss(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{offset:0},r=e[t.offset]&ys;if(t.offset++,null!=bs[r])return bs[r](e,t);throw new Error("No decoder for tag "+r)}function Es(e,t){var r=0;if((e[t.offset]&ms)===ms){var n=e[t.offset]&ws,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 ks(e,t){Es(e,t);for(var r=[];!(t.offset>=e.byteLength);){var n=Ss(e,t);if(null===n)break;r.push(n)}return r}function xs(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 gs,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 gs(Uint8Array.from([t.byteLength|ms]),t)}function As(e){var t=new gs;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new gs(Uint8Array.from([2]),xs(t),t)}function Cs(e){var t=Uint8Array.from([0]),r=new gs(t,e);return new gs(Uint8Array.from([3]),xs(r),r)}function Is(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48,r=new gs;for(var n of e)r.append(n);return new gs(Uint8Array.from([t]),xs(r),r)}var Ts="1.2.840.10045.3.1.7",Ps="1.3.132.0.34",_s="1.3.132.0.35";function Bs(){return Bs=r((function*(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"P-256",t=yield crypto.subtle.generateKey({name:"ECDSA",namedCurve:e},!0,["sign","verify"]);return{publicKey:yield crypto.subtle.exportKey("jwk",t.publicKey),privateKey:yield crypto.subtle.exportKey("jwk",t.privateKey)}})),Bs.apply(this,arguments)}function Ns(){return(Ns=r((function*(e,t){var r,n=yield crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:null!==(r=e.crv)&&void 0!==r?r:"P-256"},!1,["sign"]),i=yield crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,t.subarray());return new Uint8Array(i,0,i.byteLength)}))).apply(this,arguments)}function Ds(){return Ds=r((function*(e,t,r){var n,i=yield crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:null!==(n=e.crv)&&void 0!==n?n:"P-256"},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},i,t,r.subarray())})),Ds.apply(this,arguments)}var Rs=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Os=Uint8Array.from([6,5,43,129,4,0,34]),Ls=Uint8Array.from([6,5,43,129,4,0,35]),Ms={ext:!0,kty:"EC",crv:"P-256"},Us={ext:!0,kty:"EC",crv:"P-384"},Fs={ext:!0,kty:"EC",crv:"P-521"},zs=32,js=48,Vs=66;function qs(e){var r,n,i=e[1],o=gt(i,"base64url"),a=e[2][1][0];if(i.byteLength===zs)return r=gt(a.subarray(1,33),"base64url"),n=gt(a.subarray(33),"base64url"),new Ys(t(t({},Ms),{},{key_ops:["sign"],d:o,x:r,y:n}));if(i.byteLength===js)return r=gt(a.subarray(1,49),"base64url"),n=gt(a.subarray(49),"base64url"),new Ys(t(t({},Us),{},{key_ops:["sign"],d:o,x:r,y:n}));if(i.byteLength===Vs)return r=gt(a.subarray(1,67),"base64url"),n=gt(a.subarray(67),"base64url"),new Ys(t(t({},Fs),{},{key_ops:["sign"],d:o,x:r,y:n}));throw new _a("Private key length was wrong length, got ".concat(i.byteLength,", expected 32, 48 or 66"))}function Hs(e){return Ks(Ss(e))}function Ks(e){var r,n,i=e[1][1][0];if(65===i.byteLength)return r=gt(i.subarray(1,33),"base64url"),n=gt(i.subarray(33),"base64url"),new Qs(t(t({},Ms),{},{key_ops:["verify"],x:r,y:n}));if(97===i.byteLength)return r=gt(i.subarray(1,49),"base64url"),n=gt(i.subarray(49),"base64url"),new Qs(t(t({},Us),{},{key_ops:["verify"],x:r,y:n}));if(133===i.byteLength)return r=gt(i.subarray(1,67),"base64url"),n=gt(i.subarray(67),"base64url"),new Qs(t(t({},Fs),{},{key_ops:["verify"],x:r,y:n}));throw new _a("coordinates were wrong length, got ".concat(i.byteLength,", expected 65, 97 or 133"))}function Ws(e){if("P-256"===e)return Rs;if("P-384"===e)return Os;if("P-521"===e)return Ls;throw new _a("Invalid curve ".concat(e))}function Gs(){return Gs=r((function*(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"P-256",t=yield function(){return Bs.apply(this,arguments)}(e);return new Ys(t.privateKey)})),Gs.apply(this,arguments)}class Qs{constructor(t){e(this,"type","ECDSA"),e(this,"jwk",void 0),e(this,"_raw",void 0),this.jwk=t}get raw(){return null==this._raw&&(this._raw=function(e){var t,r;return Is([As(Uint8Array.from([1])),Is([Ws(e.crv)],160),Is([Cs(new gs(Uint8Array.from([4]),Et(null!==(t=e.x)&&void 0!==t?t:"","base64url"),Et(null!==(r=e.y)&&void 0!==r?r:"","base64url")))],161)]).subarray()}(this.jwk)),this._raw}toMultihash(){return Ge.digest(Su(this))}toCID(){return it.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&St(this.raw,e.raw)}verify(e,t){var n=this;return r((function*(){return function(e,t,r){return Ds.apply(this,arguments)}(n.jwk,t,e)}))()}}class Ys{constructor(t){e(this,"type","ECDSA"),e(this,"jwk",void 0),e(this,"publicKey",void 0),e(this,"_raw",void 0),this.jwk=t,this.publicKey=new Qs({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,Is([As(Uint8Array.from([1])),(i=Et(null!==(t=e.d)&&void 0!==t?t:"","base64url"),new gs(Uint8Array.from([4]),xs(i),i)),Is([Ws(e.crv)],160),Is([Cs(new gs(Uint8Array.from([4]),Et(null!==(r=e.x)&&void 0!==r?r:"","base64url"),Et(null!==(n=e.y)&&void 0!==n?n:"","base64url")))],161)]).subarray())),this._raw}equals(e){return null!=e&&e.raw instanceof Uint8Array&&St(this.raw,e.raw)}sign(e){var t=this;return r((function*(){return function(e,t){return Ns.apply(this,arguments)}(t.jwk,e)}))()}}var Js=64;function Zs(){var e=Go.utils.randomPrivateKey(),t=Go.getPublicKey(e),r=function(e,t){for(var r=new Uint8Array(Js),n=0;n<32;n++)r[n]=e[n],r[32+n]=t[n];return r}(e,t);return{privateKey:r,publicKey:t}}class $s{constructor(t){e(this,"type","Ed25519"),e(this,"raw",void 0),this.raw=nl(t,32)}toMultihash(){return Ge.digest(Su(this))}toCID(){return it.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&St(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 Xs{constructor(t,r){e(this,"type","Ed25519"),e(this,"raw",void 0),e(this,"publicKey",void 0),this.raw=nl(t,Js),this.publicKey=new $s(r)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&St(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 el(e){if(e.length>Js){var t=(e=nl(e,96)).subarray(0,Js),r=e.subarray(Js,e.length);return new Xs(t,r)}var n=(e=nl(e,Js)).subarray(0,Js),i=e.subarray(32);return new Xs(n,i)}function tl(e){return e=nl(e,32),new $s(e)}function rl(){return rl=r((function*(){var{privateKey:e,publicKey:t}=Zs();return new Xs(e,t)})),rl.apply(this,arguments)}function nl(e,t){if((e=Uint8Array.from(null!=e?e:[])).length!==t)throw new _a("Key must be a Uint8Array of length ".concat(t,", got ").concat(e.length));return e}var il=new Float32Array([-0]),ol=new Uint8Array(il.buffer);function al(e,t,r){il[0]=e,t[r]=ol[0],t[r+1]=ol[1],t[r+2]=ol[2],t[r+3]=ol[3]}var sl=new Float64Array([-0]),ll=new Uint8Array(sl.buffer);function ul(e,t,r){sl[0]=e,t[r]=ll[0],t[r+1]=ll[1],t[r+2]=ll[2],t[r+3]=ll[3],t[r+4]=ll[4],t[r+5]=ll[5],t[r+6]=ll[6],t[r+7]=ll[7]}var cl=BigInt(Number.MAX_SAFE_INTEGER),dl=BigInt(Number.MIN_SAFE_INTEGER);class hl{constructor(t,r){e(this,"lo",void 0),e(this,"hi",void 0),this.lo=0|t,this.hi=0|r}toNumber(){if(!(arguments.length>0&&void 0!==arguments[0]&&arguments[0])&&this.hi>>>31>0){var e=1+~this.lo>>>0,t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(){if(arguments.length>0&&void 0!==arguments[0]&&arguments[0])return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){var e=1+~this.lo>>>0,t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this.toBigInt(e).toString()}zzEncode(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(0n===e)return vl;if(e<cl&&e>dl)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>pl&&(n=0n,++r>pl&&(r=0n))),new hl(Number(n),Number(r))}static fromNumber(e){if(0===e)return vl;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 hl(r,n)}static from(e){return"number"==typeof e?hl.fromNumber(e):"bigint"==typeof e?hl.fromBigInt(e):"string"==typeof e?hl.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new hl(e.low>>>0,e.high>>>0):vl}}var vl=new hl(0,0);vl.toBigInt=function(){return 0n},vl.zzEncode=vl.zzDecode=function(){return this},vl.length=function(){return 1};var pl=4294967296n;function fl(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 gl(e,t){return RangeError("index out of range: ".concat(e.pos," + ").concat(null!=t?t:1," > ").concat(e.len))}function yl(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class ml{constructor(t){e(this,"buf",void 0),e(this,"pos",void 0),e(this,"len",void 0),e(this,"_slice",Uint8Array.prototype.subarray),this.buf=t,this.pos=0,this.len=t.length}uint32(){var e=4294967295;if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,gl(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 gl(this,4);return yl(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw gl(this,4);return 0|yl(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw gl(this,4);var e=function(e,t){return ol[0]=e[t],ol[1]=e[t+1],ol[2]=e[t+2],ol[3]=e[t+3],il[0]}(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw gl(this,4);var e=function(e,t){return ll[0]=e[t],ll[1]=e[t+1],ll[2]=e[t+2],ll[3]=e[t+3],ll[4]=e[t+4],ll[5]=e[t+5],ll[6]=e[t+6],ll[7]=e[t+7],sl[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 gl(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 gl(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw gl(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 hl(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw gl(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 gl(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 gl(this,8);var e=yl(this.buf,this.pos+=4),t=yl(this.buf,this.pos+=4);return new hl(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=Rt(this.buf,this.pos);return this.pos+=Nt(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 wl(e,t,r){var n=function(e){return new ml(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(n,void 0,r)}class bl{constructor(t,r,n){e(this,"fn",void 0),e(this,"len",void 0),e(this,"next",void 0),e(this,"val",void 0),this.fn=t,this.len=r,this.next=void 0,this.val=n}}function Sl(){}class El{constructor(t){e(this,"head",void 0),e(this,"tail",void 0),e(this,"len",void 0),e(this,"next",void 0),this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}}var kl,xl,Al,Cl,Il,Tl,Pl,_l,Bl=(Al=xl=8192,function(e){if(e<1||e>4096)return dt(e);Al+e>xl&&(kl=dt(xl),Al=0);var t=kl.subarray(Al,Al+=e);return 7&Al&&(Al=1+(7|Al)),t});class Nl{constructor(){e(this,"len",void 0),e(this,"head",void 0),e(this,"tail",void 0),e(this,"states",void 0),this.len=0,this.head=new bl(Sl,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new bl(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Ol((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Ll,10,hl.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){var t=hl.fromBigInt(e);return this._push(Ll,t.length(),t)}uint64Number(e){return this._push(Dt,Nt(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=hl.fromBigInt(e).zzEncode();return this._push(Ll,t.length(),t)}sint64Number(e){var t=hl.fromNumber(e).zzEncode();return this._push(Ll,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Dl,1,e?1:0)}fixed32(e){return this._push(Ml,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){var t=hl.fromBigInt(e);return this._push(Ml,4,t.lo)._push(Ml,4,t.hi)}fixed64Number(e){var t=hl.fromNumber(e);return this._push(Ml,4,t.lo)._push(Ml,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(al,4,e)}double(e){return this._push(ul,8,e)}bytes(e){var t=e.length>>>0;return 0===t?this._push(Dl,1,0):this.uint32(t)._push(Ul,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(fl,t,e):this._push(Dl,1,0)}fork(){return this.states=new El(this),this.head=this.tail=new bl(Sl,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 bl(Sl,0,0),this.len=0),this}ldelim(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),0!==r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this}finish(){for(var e,t=this.head.next,r=(e=this.len,null!=globalThis.Buffer?dt(e):Bl(e)),n=0;null!=t;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}}function Dl(e,t,r){t[r]=255&e}function Rl(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class Ol extends bl{constructor(t,r){super(Rl,t,r),e(this,"next",void 0),this.next=void 0}}function Ll(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 Ml(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 Ul(e,t,r){t.set(e,r)}function Fl(e,t,r){t.set(e,r)}function zl(e,t,r){e.length<40?fl(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set(Et(e),r)}function jl(e,t){var r=new Nl;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}function Vl(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function ql(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Vl("enum",Cl.VARINT,(function(e,r){var n=t(e);r.int32(n)}),(function(e){return t(e.int32())}))}function Hl(e,t){return Vl("message",Cl.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(Nl.prototype.bytes=function(e){var t=e.length>>>0;return this.uint32(t),t>0&&this._push(Fl,t,e),this},Nl.prototype.string=function(e){var t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(zl,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"}(Cl||(Cl={}));class Kl extends Error{constructor(){super(...arguments),e(this,"code","ERR_MAX_LENGTH"),e(this,"name","MaxLengthError")}}class Wl extends Error{constructor(){super(...arguments),e(this,"code","ERR_MAX_SIZE"),e(this,"name","MaxSizeError")}}function Gl(e){if(isNaN(e)||e<=0)throw new _a("random bytes length must be a Number bigger than 0");return sn(e)}!function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"}(Il||(Il={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"}(Tl||(Tl={})),function(e){e.codec=()=>ql(Tl)}(Il||(Il={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((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),Il.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=Il.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(Pl||(Pl={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((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),Il.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=Il.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(_l||(_l={}));class Ql extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"An error occurred while signing a message"),this.name="SigningError"}}class Yl extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"An error occurred while verifying a message"),this.name="VerificationError"}}class Jl extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Missing Web Crypto API"),this.name="WebCryptoMissingError"}}var Zl={get(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:globalThis).crypto;if(null==(null==e?void 0:e.subtle))throw new Jl("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 $l=class{constructor(t,r){e(this,"type","RSA"),e(this,"jwk",void 0),e(this,"_raw",void 0),e(this,"_multihash",void 0),this.jwk=t,this._multihash=r}get raw(){return null==this._raw&&(this._raw=ru(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return it.createV1(114,this._multihash)}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&St(this.raw,e.raw)}verify(e,t){return function(e,t,r){return lu.apply(this,arguments)}(this.jwk,t,e)}},Xl=class{constructor(t,r){e(this,"type","RSA"),e(this,"jwk",void 0),e(this,"_raw",void 0),e(this,"publicKey",void 0),this.jwk=t,this.publicKey=r}get raw(){return null==this._raw&&(this._raw=function(e){if(null==e.n||null==e.e||null==e.d||null==e.p||null==e.q||null==e.dp||null==e.dq||null==e.qi)throw new _a("JWK was missing components");return Is([As(Uint8Array.from([0])),As(Et(e.n,"base64url")),As(Et(e.e,"base64url")),As(Et(e.d,"base64url")),As(Et(e.p,"base64url")),As(Et(e.q,"base64url")),As(Et(e.dp,"base64url")),As(Et(e.dq,"base64url")),As(Et(e.qi,"base64url"))]).subarray()}(this.jwk)),this._raw}equals(e){return null!=e&&e.raw instanceof Uint8Array&&St(this.raw,e.raw)}sign(e){return function(e,t){return su.apply(this,arguments)}(this.jwk,e)}};var eu=8192,tu=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function ru(e){if(null==e.n||null==e.e)throw new _a("JWK was missing components");return Is([tu,Cs(Is([As(Et(e.n,"base64url")),As(Et(e.e,"base64url"))]))]).subarray()}function nu(e){var t=function(e){return{n:gt(e[1],"base64url"),e:gt(e[2],"base64url"),d:gt(e[3],"base64url"),p:gt(e[4],"base64url"),q:gt(e[5],"base64url"),dp:gt(e[6],"base64url"),dq:gt(e[7],"base64url"),qi:gt(e[8],"base64url"),kty:"RSA"}}(e);return function(e){if(function(e){if("RSA"!==e.kty)throw new _a("invalid key type");if(null==e.n)throw new _a("invalid key modulus");var t=Et(e.n,"base64url");return 8*t.length}(e)>eu)throw new _a("Key size is too large");var t=function(e){if(null==e)throw new _a("Missing key parameter");return{privateKey:e,publicKey:{kty:e.kty,n:e.n,e:e.e}}}(e),r=Yo(Pl.encode({Type:Il.RSA,Data:ru(t.publicKey)})),n=qe(18,r);return new Xl(t.privateKey,new $l(t.publicKey,n))}(t)}function iu(e,t,r){var n=function(e){var t=Ss(e[1],{offset:0});return{kty:"RSA",n:gt(t[0],"base64url"),e:gt(t[1],"base64url")}}(e);null==r&&(r=qe(18,Yo(Pl.encode({Type:Il.RSA,Data:t}))));return new $l(n,r)}function ou(){return ou=r((function*(e){if(e>eu)throw new _a("Key size is too large");var t=yield function(e){return au.apply(this,arguments)}(e),r=qe(18,Yo(Pl.encode({Type:Il.RSA,Data:ru(t.publicKey)})));return new Xl(t.privateKey,new $l(t.publicKey,r))})),ou.apply(this,arguments)}function au(){return au=r((function*(e){var t=yield Zl.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 uu.apply(this,arguments)}(t);return{privateKey:r[0],publicKey:r[1]}})),au.apply(this,arguments)}function su(){return(su=r((function*(e,t){var r=yield Zl.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=yield Zl.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 lu(){return lu=r((function*(e,t,r){var n=yield Zl.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Zl.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())})),lu.apply(this,arguments)}function uu(){return uu=r((function*(e){if(null==e.privateKey||null==e.publicKey)throw new _a("Private and public key are required");return Promise.all([Zl.get().subtle.exportKey("jwk",e.privateKey),Zl.get().subtle.exportKey("jwk",e.publicKey)])})),uu.apply(this,arguments)}function cu(e){return null!=e&&("function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally)}class du{constructor(t){e(this,"type","secp256k1"),e(this,"raw",void 0),e(this,"_key",void 0),this._key=function(e){try{return xo.ProjectivePoint.fromHex(e),e}catch(e){throw new Ba(String(e))}}(t),this.raw=function(e){var t=xo.ProjectivePoint.fromHex(e).toRawBytes(!0);return t}(this._key)}toMultihash(){return Ge.digest(Su(this))}toCID(){return it.createV1(114,this.toMultihash())}toString(){return ie.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&St(this.raw,e.raw)}verify(e,t){return function(e,t,r){var n=$e.digest(r instanceof Uint8Array?r:r.subarray());if(cu(n))return n.then((r=>{var{digest:n}=r;return xo.verify(t,n,e)})).catch((e=>{throw new Yl(String(e))}));try{return xo.verify(t,n.digest,e)}catch(e){throw new Yl(String(e))}}(this._key,t,e)}}class hu{constructor(t,r){e(this,"type","secp256k1"),e(this,"raw",void 0),e(this,"publicKey",void 0),this.raw=function(e){try{return xo.getPublicKey(e,!0),e}catch(e){throw new Na(String(e))}}(t),this.publicKey=new du(null!=r?r:function(e){try{return xo.getPublicKey(e,!0)}catch(e){throw new Na(String(e))}}(t))}equals(e){return null!=e&&e.raw instanceof Uint8Array&&St(this.raw,e.raw)}sign(e){return function(e,t){var r=$e.digest(t instanceof Uint8Array?t:t.subarray());if(cu(r))return r.then((t=>{var{digest:r}=t;return xo.sign(r,e).toDERRawBytes()})).catch((e=>{throw new Ql(String(e))}));try{return xo.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Ql(String(e))}}(this.raw,e)}}function vu(e){return new hu(e)}function pu(e){return new du(e)}function fu(){return(fu=r((function*(){var e=xo.utils.randomPrivateKey();return new hu(e)}))).apply(this,arguments)}function gu(e,t){return yu.apply(this,arguments)}function yu(){return yu=r((function*(e,t){if("Ed25519"===e)return function(){return rl.apply(this,arguments)}();if("secp256k1"===e)return function(){return fu.apply(this,arguments)}();if("RSA"===e)return function(e){return ou.apply(this,arguments)}(function(e){if(null==e)return 2048;return parseInt(e,10)}(t));if("ECDSA"===e)return function(){return Gs.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 _a("Unsupported curve, should be P-256, P-384 or P-521")}(t));throw new rs})),yu.apply(this,arguments)}function mu(e,t){var{Type:r,Data:n}=Pl.decode(e),i=null!=n?n:new Uint8Array;switch(r){case Il.RSA:return function(e,t){if(e.byteLength>=1062)throw new Ba("Key size is too large");return iu(Ss(e,{offset:0}),e,t)}(i,t);case Il.Ed25519:return tl(i);case Il.secp256k1:return pu(i);case Il.ECDSA:return Hs(i);default:throw new rs}}function wu(e){var t,r;if(32===e.byteLength)return tl(e);if(33===e.byteLength)return pu(e);var n=Ss(e),i=null===(t=n[1])||void 0===t?void 0:t[0];if(i===Ts||i===Ps||i===_s)return Ks(n);if("1.2.840.113549.1.1.1"===(null===(r=n[0])||void 0===r?void 0:r[0]))return iu(n,e);throw new _a("Could not extract public key from raw bytes")}function bu(e){var{Type:t,Data:r}=Pl.decode(e.digest),n=null!=r?r:new Uint8Array;switch(t){case Il.Ed25519:return tl(n);case Il.secp256k1:return pu(n);case Il.ECDSA:return Hs(n);default:throw new rs}}function Su(e){return Pl.encode({Type:Il[e.type],Data:e.raw})}function Eu(e){var t,r=_l.decode(e),n=null!==(t=r.Data)&&void 0!==t?t:new Uint8Array;switch(r.Type){case Il.RSA:return nu(Ss(n));case Il.Ed25519:return el(n);case Il.secp256k1:return vu(n);case Il.ECDSA:return function(e){return qs(Ss(e))}(n);default:throw new rs}}function ku(e){var t;if(e.byteLength===Js)return el(e);if(32===e.byteLength)return vu(e);var r=Ss(e),n=null===(t=r[2])||void 0===t?void 0:t[0];if(n===Ts||n===Ps||n===_s)return qs(r);if(r.length>8)return nu(r);throw new _a("Could not extract private key from raw bytes")}function xu(e){return _l.encode({Type:Il[e.type],Data:e.raw})}function Au(e){return Cu.apply(this,arguments)}function Cu(){return(Cu=r((function*(e){if("RSA"===e.type)return{privateKey:yield crypto.subtle.importKey("jwk",e.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),publicKey:yield crypto.subtle.importKey("jwk",e.publicKey.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])};var t,r;if("ECDSA"===e.type)return{privateKey:yield crypto.subtle.importKey("jwk",e.jwk,{name:"ECDSA",namedCurve:null!==(t=e.jwk.crv)&&void 0!==t?t:"P-256"},!0,["sign"]),publicKey:yield crypto.subtle.importKey("jwk",e.publicKey.jwk,{name:"ECDSA",namedCurve:null!==(r=e.publicKey.jwk.crv)&&void 0!==r?r:"P-256"},!0,["verify"])};throw new _a("Only RSA and ECDSA keys are supported")}))).apply(this,arguments)}var Iu=Symbol.for("nodejs.util.inspect.custom");class Tu{constructor(t){e(this,"type",void 0),e(this,"multihash",void 0),e(this,"publicKey",void 0),e(this,"string",void 0),e(this,Sa,!0),this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return"PeerId(".concat(this.toString(),")")}toString(){return null==this.string&&(this.string=ie.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return it.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){var t;if(null==e)return!1;if(e instanceof Uint8Array)return St(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 St(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Iu](){return"PeerId(".concat(this.toString(),")")}}class Pu extends Tu{constructor(r){super(t(t({},r),{},{type:"RSA"})),e(this,"type","RSA"),e(this,"publicKey",void 0),this.publicKey=r.publicKey}}class _u extends Tu{constructor(r){super(t(t({},r),{},{type:"Ed25519"})),e(this,"type","Ed25519"),e(this,"publicKey",void 0),this.publicKey=r.publicKey}}class Bu extends Tu{constructor(r){super(t(t({},r),{},{type:"secp256k1"})),e(this,"type","secp256k1"),e(this,"publicKey",void 0),this.publicKey=r.publicKey}}class Nu{constructor(t){e(this,"type","url"),e(this,"multihash",void 0),e(this,"publicKey",void 0),e(this,"url",void 0),e(this,Sa,!0),this.url=t.toString(),this.multihash=Ge.digest(Et(this.url))}[Iu](){return"PeerId(".concat(this.url,")")}toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return it.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=gt(e)),e.toString()===this.toString())}}function Du(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 Mu(it.parse(e));throw new _a('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return Lu(He(ie.decode("z".concat(e))))}function Ru(e){if("Ed25519"===e.type)return new _u({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new Bu({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new Pu({multihash:e.toCID().multihash,publicKey:e});throw new rs}function Ou(e){return Ru(e.publicKey)}function Lu(e){if(function(e){return e.code===$e.code}(e))return new Pu({multihash:e});if(function(e){return e.code===Ge.code}(e))try{var t=bu(e);if("Ed25519"===t.type)return new _u({multihash:e,publicKey:t});if("secp256k1"===t.type)return new Bu({multihash:e,publicKey:t})}catch(t){var r=gt(e.digest);return new Nu(new URL(r))}throw new Ha("Supplied PeerID Multihash is invalid")}function Mu(e){if(null==(null==e?void 0:e.multihash)||null==e.version||1===e.version&&114!==e.code&&2336!==e.code)throw new qa("Supplied PeerID CID is invalid");if(2336===e.code){var t=gt(e.multihash.digest);return new Nu(new URL(t))}return Lu(e.multihash)}var Uu=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Fu=new Uint32Array(80);class zu extends cn{constructor(){super(64,20,8,!1),this.A=0|Uu[0],this.B=0|Uu[1],this.C=0|Uu[2],this.D=0|Uu[3],this.E=0|Uu[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)Fu[r]=e.getUint32(t,!1);for(var n=16;n<80;n++)Fu[n]=Or(Fu[n-3]^Fu[n-8]^Fu[n-14]^Fu[n-16],1);for(var{A:i,B:o,C:a,D:s,E:l}=this,u=0;u<80;u++){var c=void 0,d=void 0;u<20?(c=ln(o,a,s),d=1518500249):u<40?(c=o^a^s,d=1859775393):u<60?(c=un(o,a,s),d=2400959708):(c=o^a^s,d=3395469782);var h=Or(i,5)+c+l+d+Fu[u]|0;l=s,s=a,a=Or(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(){Nr(Fu)}destroy(){this.set(0,0,0,0,0),Nr(this.buffer)}}var ju=on((()=>new zu)),Vu=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),qu=(()=>Uint8Array.from(new Array(16).fill(0).map(((e,t)=>t))))(),Hu=(()=>qu.map((e=>(9*e+5)%16)))(),Ku=(()=>{for(var e=[[qu],[Hu]],t=0;t<4;t++)for(var r of e)r.push(r[t].map((e=>Vu[e])));return e})(),Wu=(()=>Ku[0])(),Gu=(()=>Ku[1])(),Qu=[[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))),Yu=Wu.map(((e,t)=>e.map((e=>Qu[t][e])))),Ju=Gu.map(((e,t)=>e.map((e=>Qu[t][e])))),Zu=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),$u=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function Xu(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 ec=new Uint32Array(16);class tc extends cn{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)ec[r]=e.getUint32(t,!0);for(var n=0|this.h0,i=n,o=0|this.h1,a=o,s=0|this.h2,l=s,u=0|this.h3,c=u,d=0|this.h4,h=d,v=0;v<5;v++){for(var p=4-v,f=Zu[v],g=$u[v],y=Wu[v],m=Gu[v],w=Yu[v],b=Ju[v],S=0;S<16;S++){var E=Or(n+Xu(v,o,s,u)+ec[y[S]]+f,w[S])+d|0;n=d,d=u,u=0|Or(s,10),s=o,o=E}for(var k=0;k<16;k++){var x=Or(i+Xu(p,a,l,c)+ec[m[k]]+g,b[k])+h|0;i=h,h=c,c=0|Or(l,10),l=a,a=x}}this.set(this.h1+s+c|0,this.h2+u+h|0,this.h3+d+i|0,this.h4+n+a|0,this.h0+o+l|0)}roundClean(){Nr(ec)}destroy(){this.destroyed=!0,Nr(this.buffer),this.set(0,0,0,0,0)}}var rc=on((()=>new tc)),nc={sha1:ju,"sha2-256":Yo,"sha2-512":Jo};function ic(e,t,r,n,i){if("sha1"!==i&&"sha2-256"!==i&&"sha2-512"!==i){var o=Object.keys(nc).join(" / ");throw new _a("Hash '".concat(i,"' is unknown or not supported. Must be ").concat(o))}var a=function(e,t,r,n){for(var i,{c:o,dkLen:a,DK:s,PRF:l,PRFSalt:u}=Zo(e,t,r,n),c=new Uint8Array(4),d=Dr(c),h=new Uint8Array(l.outputLen),v=1,p=0;p<a;v++,p+=l.outputLen){var f=s.subarray(p,p+l.outputLen);d.setInt32(0,v,!1),(i=u._cloneInto(i)).update(c).digestInto(h),f.set(h.subarray(0,f.length));for(var g=1;g<o;g++){l._cloneInto(i).update(h).digestInto(h);for(var y=0;y<f.length;y++)f[y]^=h[y]}}return $o(l,u,s,i,h)}(nc[i],e,t,{c:r,dkLen:n});return se.encode(a).substring(1)}var oc="/",ac=(new TextEncoder).encode(oc),sc=ac[0];class lc{constructor(t,r){if(e(this,"_buf",void 0),"string"==typeof t)this._buf=Et(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]!==sc)throw new Error("Invalid key")}toString(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"utf8";return gt(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return"Key(".concat(this.toString(),")")}static withNamespaces(e){return new lc(e.join(oc))}static random(){return new lc(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new lc(e):"function"==typeof e.uint8Array?new lc(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=ac),this._buf[0]!==sc){var e=new Uint8Array(this._buf.byteLength+1);e.fill(sc,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===sc;)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 lc.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){var e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(oc).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 lc(this.toString()+":"+e)}path(){var e=this.parent().toString();return e.endsWith(oc)||(e+=oc),e+=this.type(),new lc(e)}parent(){var e=this.list();return 1===e.length?new lc(oc):new lc(e.slice(0,-1).join(oc))}child(e){return this.toString()===oc?e:e.toString()===oc?this:new lc(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 lc.withNamespaces([...this.namespaces(),...(n=t.map((e=>e.namespaces())),[].concat(...n))]);var n}}function uc(e){if(null!=e[Symbol.asyncIterator])return r((function*(){var t,r=!1,n=!1;try{for(var i,o=s(e);r=!(i=yield o.next()).done;r=!1)i.value}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield o.return())}finally{if(n)throw t}}}))();for(var t of e);}function cc(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 dc(e,t){var r=0;if(null!=e[Symbol.asyncIterator])return l((function*(){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var c=a.value;(yield u(t(c,r++)))&&(yield c)}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}))();var n=cc(e),{value:i,done:o}=n.next();if(!0===o)return function*(){}();var a=t(i,r++);if("function"==typeof a.then)return l((function*(){for(var e of((yield u(a))&&(yield i),n))(yield u(t(e,r++)))&&(yield e)}))();var c=t;return function*(){for(var e of(!0===a&&(yield i),n))c(e,r++)&&(yield e)}()}function hc(e){if(null!=e[Symbol.asyncIterator])return r((function*(){var t,r=[],n=!1,i=!1;try{for(var o,a=s(e);n=!(o=yield a.next()).done;n=!1){var l=o.value;r.push(l)}}catch(e){i=!0,t=e}finally{try{n&&null!=a.return&&(yield a.return())}finally{if(i)throw t}}return r}))();var t=[];for(var n of e)t.push(n);return t}function vc(e,t){return null!=e[Symbol.asyncIterator]?l((function*(){var r=yield u(hc(e));yield*c(s(r.sort(t)))}))():function*(){var r=hc(e);yield*r.sort(t)}()}function pc(e,t){return null!=e[Symbol.asyncIterator]?l((function*(){var r=0;if(!(t<1)){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var c=a.value;if(yield c,++r===t)return}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}}))():function*(){var r=0;if(!(t<1))for(var n of e)if(yield n,++r===t)return}()}class fc{put(e,t,r){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}putMany(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var{key:c,value:d}=a.value;yield u(t.put(c,d,r)),yield c}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}()})).apply(this,arguments)}getMany(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var c=a.value;yield{key:c,value:yield u(t.get(c,r))}}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}()})).apply(this,arguments)}deleteMany(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var c=a.value;yield u(t.delete(c,r)),yield c}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}()})).apply(this,arguments)}batch(){var e,t=this,n=[],i=[];return{put(e,t){n.push({key:e,value:t})},delete(e){i.push(e)},commit:(e=r((function*(e){yield uc(t.putMany(n,e)),n=[],yield uc(t.deleteMany(i,e)),i=[]})),function(t){return e.apply(this,arguments)})}}_all(e,t){return l((function*(){throw new Error("._all is not implemented")}))()}_allKeys(e,t){return l((function*(){throw new Error("._allKeys is not implemented")}))()}query(e,t){var r=this._all(e,t);if(null!=e.prefix){var n=e.prefix;r=dc(r,(e=>e.key.toString().startsWith(n)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>dc(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>vc(e,t)),r)),null!=e.offset){var i=0,o=e.offset;r=dc(r,(()=>i++>=o))}return null!=e.limit&&(r=pc(r,e.limit)),r}queryKeys(e,t){var r=this._allKeys(e,t);if(null!=e.prefix){var n=e.prefix;r=dc(r,(e=>e.toString().startsWith(n)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>dc(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>vc(e,t)),r)),null!=e.offset){var i=e.offset,o=0;r=dc(r,(()=>o++>=i))}return null!=e.limit&&(r=pc(r,e.limit)),r}}class gc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Open failed"),e(this,"name",gc.name),e(this,"code",gc.code)}}e(gc,"name","OpenFailedError"),e(gc,"code","ERR_OPEN_FAILED");class yc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Close failed"),e(this,"name",yc.name),e(this,"code",yc.code)}}e(yc,"name","CloseFailedError"),e(yc,"code","ERR_CLOSE_FAILED");class mc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Put failed"),e(this,"name",mc.name),e(this,"code",mc.code)}}e(mc,"name","PutFailedError"),e(mc,"code","ERR_PUT_FAILED");class wc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Get failed"),e(this,"name",wc.name),e(this,"code",wc.code)}}e(wc,"name","GetFailedError"),e(wc,"code","ERR_GET_FAILED");class bc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Delete failed"),e(this,"name",bc.name),e(this,"code",bc.code)}}e(bc,"name","DeleteFailedError"),e(bc,"code","ERR_DELETE_FAILED");class Sc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Has failed"),e(this,"name",Sc.name),e(this,"code",Sc.code)}}e(Sc,"name","HasFailedError"),e(Sc,"code","ERR_HAS_FAILED");let Ec=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not Found"),e(this,"name",t.name),e(this,"code",t.code)}};e(Ec,"name","NotFoundError"),e(Ec,"code","ERR_NOT_FOUND");let kc=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Aborted"),e(this,"name",t.name),e(this,"code",t.code)}};e(kc,"name","AbortError"),e(kc,"code","ERR_ABORTED");class xc extends fc{constructor(){super(),e(this,"data",void 0),this.data=new Map}put(e,t,r){var n;return null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){var r;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted();var n=this.data.get(e.toString());if(null==n)throw new Ec;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 lc(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 lc(n),null==t||null===(i=t.signal)||void 0===i||i.throwIfAborted()}}}function Ac(e,t){var r=0;if(null!=e[Symbol.asyncIterator])return l((function*(){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var c=a.value;yield t(c,r++)}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}))();var n=cc(e),{value:i,done:o}=n.next();if(!0===o)return function*(){}();var a=t(i,r++);if("function"==typeof a.then)return l((function*(){for(var e of(yield yield u(a),n))yield t(e,r++)}))();var c=t;return function*(){for(var e of(yield a,n))yield c(e,r++)}()}function Cc(){var e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}class Ic{constructor(t){if(e(this,"buffer",void 0),e(this,"mask",void 0),e(this,"top",void 0),e(this,"btm",void 0),e(this,"next",void 0),!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){var e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return void 0===this.buffer[this.btm]}}class Tc{constructor(){var t,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e(this,"size",void 0),e(this,"hwm",void 0),e(this,"head",void 0),e(this,"tail",void 0),this.hwm=null!==(t=r.splitLimit)&&void 0!==t?t:16,this.head=new Ic(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 Ic(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 Pc=class extends Error{constructor(t,r){super(null!=t?t:"The operation was aborted"),e(this,"type",void 0),e(this,"code",void 0),this.type="aborted",this.code=null!=r?r:"ABORT_ERR"}};function _c(){return function(e,t){t=null!=t?t:{};var n,i,o,a=t.onEnd,s=new Tc,l=Cc(),u=function(){var t=r((function*(){try{return s.isEmpty()?o?{done:!0}:yield new Promise(((t,r)=>{i=o=>{i=null,s.push(o);try{t(e(s))}catch(e){r(e)}return n}})):e(s)}finally{s.isEmpty()&&queueMicrotask((()=>{l.resolve(),l=Cc()}))}}));return function(){return t.apply(this,arguments)}}(),c=e=>null!=i?i(e):(s.push(e),n),d=e=>(s=new Tc,null!=i?i({error:e}):(s.push({error:e}),n)),h=e=>{var r;if(o)return n;if(!0!==(null===(r=t)||void 0===r?void 0:r.objectMode)&&null==(null==e?void 0:e.byteLength))throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:e})},v=e=>o?n:(o=!0,null!=e?d(e):c({done:!0})),p=()=>(s=new Tc,v(),{done:!0}),f=e=>(v(e),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:u,return:p,throw:f,push:h,end:v,get readableLength(){return s.size},onEmpty:function(){var e=r((function*(e){var t=null==e?void 0:e.signal;if(null==t||t.throwIfAborted(),!s.isEmpty()){var r,n;null!=t&&(r=new Promise(((e,r)=>{n=()=>{r(new Pc)},t.addEventListener("abort",n)})));try{yield Promise.race([l.promise,r])}finally{null!=n&&null!=t&&(null==t||t.removeEventListener("abort",n))}}}));function t(t){return e.apply(this,arguments)}return t}()},null==a)return n;var g=n;return n={[Symbol.asyncIterator](){return this},next:()=>g.next(),throw:e=>(g.throw(e),null!=a&&(a(e),a=void 0),{done:!0}),return:()=>(g.return(),null!=a&&(a(),a=void 0),{done:!0}),push:h,end:e=>(g.end(e),null!=a&&(a(e),a=void 0),n),get readableLength(){return g.readableLength},onEmpty:e=>g.onEmpty(e)},n}((e=>{var t=e.shift();if(null==t)return{done:!0};if(null!=t.error)throw t.error;return{done:!0===t.done,value:t.value}}),arguments.length>0&&void 0!==arguments[0]?arguments[0]:{})}let Bc=class extends Error{constructor(t,r,n){super(null!=t?t:"The operation was aborted"),e(this,"type",void 0),e(this,"code",void 0),this.type="aborted",this.name=null!=n?n:"AbortError",this.code=null!=r?r:"ABORT_ERR"}};function Nc(e,t,r){return Dc.apply(this,arguments)}function Dc(){return(Dc=r((function*(e,t,r){if(null==t)return e;if(t.aborted)return e.catch((()=>{})),Promise.reject(new Bc(null==r?void 0:r.errorMessage,null==r?void 0:r.errorCode,null==r?void 0:r.errorName));var n,i=new Bc(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 Rc=class{constructor(){e(this,"readNext",void 0),e(this,"haveNext",void 0),e(this,"ended",void 0),e(this,"nextResult",void 0),e(this,"error",void 0),this.ended=!1,this.readNext=Cc(),this.haveNext=Cc()}[Symbol.asyncIterator](){return this}next(){var e=this;return r((function*(){if(null==e.nextResult&&(yield e.haveNext.promise),null==e.nextResult)throw new Error("HaveNext promise resolved but nextResult was undefined");var t=e.nextResult;return e.nextResult=void 0,e.readNext.resolve(),e.readNext=Cc(),t}))()}throw(e){var t=this;return r((function*(){return t.ended=!0,t.error=e,null!=e&&(t.haveNext.promise.catch((()=>{})),t.haveNext.reject(e)),{done:!0,value:void 0}}))()}return(){var e=this;return r((function*(){var t={done:!0,value:void 0};return e.ended=!0,e.nextResult=t,e.haveNext.resolve(),t}))()}push(e,t){var n=this;return r((function*(){yield n._push(e,t)}))()}end(e,t){var n=this;return r((function*(){null!=e?yield n.throw(e):yield n._push(void 0,t)}))()}_push(e,t){var n=this;return r((function*(){var r;if(null!=e&&n.ended)throw null!==(r=n.error)&&void 0!==r?r:new Error("Cannot push value onto an ended pushable");for(;null!=n.nextResult;)yield n.readNext.promise;null!=e?n.nextResult={done:!1,value:e}:(n.ended=!0,n.nextResult={done:!0,value:void 0}),n.haveNext.resolve(),n.haveNext=Cc(),yield Nc(n.readNext.promise,null==t?void 0:t.signal,t)}))()}};function Oc(){return new Rc}function Lc(){return Lc=r((function*(e,t,n){try{yield Promise.all(e.map(function(){var e=r((function*(e){var r,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield l.next()).done;i=!1){var u=a.value;yield t.push(u,{signal:n}),n.throwIfAborted()}}catch(e){o=!0,r=e}finally{try{i&&null!=l.return&&(yield l.return())}finally{if(o)throw r}}}));return function(t){return e.apply(this,arguments)}}())),yield t.end(void 0,{signal:n})}catch(e){yield t.end(e,{signal:n}).catch((()=>{}))}})),Lc.apply(this,arguments)}function Mc(){return Mc=l((function*(e){var t=new AbortController,r=Oc();(function(e,t,r){return Lc.apply(this,arguments)})(e,r,t.signal).catch((()=>{}));try{yield*c(s(r),u)}finally{t.abort()}})),Mc.apply(this,arguments)}function Uc(){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 Mc.apply(this,arguments)}(r)}function Fc(e){if(null==e)throw new Error("Empty pipeline");if(qc(e)){var t=e;e=()=>t.source}else if(Vc(e)||jc(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&&qc(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++)qc(a[s])&&(a[s]=Hc(a[s]));return zc(...a)}var zc=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},jc=e=>null!=(null==e?void 0:e[Symbol.asyncIterator]),Vc=e=>null!=(null==e?void 0:e[Symbol.iterator]),qc=e=>null!=e&&(null!=e.sink&&null!=e.source),Hc=e=>t=>{var r=e.sink(t);if(null!=(null==r?void 0:r.then)){var n,i=_c({objectMode:!0});r.then((()=>{i.end()}),(e=>{i.end(e)}));var o=e.source;if(jc(o))n=function(){var e=l((function*(){yield*c(s(o)),i.end()}));return function(){return e.apply(this,arguments)}}();else{if(!Vc(o))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");n=function*(){yield*o,i.end()}}return Uc(i,n())}return e.source};new lc("SHARDING");var Kc,Wc,Gc=1e3,Qc=60*Gc,Yc=60*Qc,Jc=24*Yc,Zc=7*Jc,$c=365.25*Jc;function Xc(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*$c;case"weeks":case"week":case"w":return r*Zc;case"days":case"day":case"d":return r*Jc;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Yc;case"minutes":case"minute":case"mins":case"min":case"m":return r*Qc;case"seconds":case"second":case"secs":case"sec":case"s":return r*Gc;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>=Jc)return ed(e,t,Jc,"day");if(t>=Yc)return ed(e,t,Yc,"hour");if(t>=Qc)return ed(e,t,Qc,"minute");if(t>=Gc)return ed(e,t,Gc,"second");return"".concat(e," ms")}(e):function(e){var t=Math.abs(e);if(t>=Jc)return"".concat(Math.round(e/Jc),"d");if(t>=Yc)return"".concat(Math.round(e/Yc),"h");if(t>=Qc)return"".concat(Math.round(e/Qc),"m");if(t>=Gc)return"".concat(Math.round(e/Gc),"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 ed(e,t,r,n){var i=t>=1.5*r;return"".concat(Math.round(e/r)," ").concat(n).concat(i?"s":"")}var td=function(){try{return localStorage}catch(e){}}();var rd=null!==(Kc=null!==(Wc=console.debug)&&void 0!==Wc?Wc:console.log)&&void 0!==Kc?Kc:()=>{};var nd,id,od=function(e){function t(e){var n,i,o,a=null;function s(){for(var e=arguments.length,r=new Array(e),i=0;i<e;i++)r[i]=arguments[i];if(s.enabled){var o=s,a=Number(new Date),l=a-(n||a);o.diff=l,o.prev=n,o.curr=a,n=a,r[0]=t.coerce(r[0]),"string"!=typeof r[0]&&r.unshift("%O");var u=0;r[0]=r[0].replace(/%([a-zA-Z%])/g,((e,n)=>{if("%%"===e)return"%";u++;var i=t.formatters[n];if("function"==typeof i){var a=r[u];e=i.call(o,a),r.splice(u,1),u--}return e})),t.formatArgs.call(o,r),(o.log||t.log).apply(o,r)}}return s.namespace=e,s.useColors=t.useColors(),s.color=t.selectColor(e),s.extend=r,s.destroy=t.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(i!==t.namespaces&&(i=t.namespaces,o=t.enabled(e)),o),set:e=>{a=e}}),"function"==typeof t.init&&t.init(s),s}function r(e,r){var n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){var t;return e instanceof Error?null!==(t=e.stack)&&void 0!==t?t:e.message:e},t.disable=function(){var e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){var r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];var n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r<i;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;var r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=Xc,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 ":" ")+"+"+Xc(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==td||td.setItem("debug",e):null==td||td.removeItem("debug")}catch(e){}},load:function(){var e;try{e=null==td?void 0:td.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:td,log:rd});function ad(){return{forComponent:e=>sd(e)}}function sd(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 od.enabled("".concat(e,":trace"))&&null!=od.names.map((e=>e.toString())).find((e=>e.includes(":trace")))&&(t=od("".concat(e,":trace"))),Object.assign(od(e),{error:od("".concat(e,":error")),trace:t})}function ld(e){if(null!=e&&0!==(e=e.trim()).length)return e}od.formatters.b=e=>null==e?"undefined":ie.baseEncode(e),od.formatters.t=e=>null==e?"undefined":K.baseEncode(e),od.formatters.m=e=>null==e?"undefined":se.baseEncode(e),od.formatters.p=e=>null==e?"undefined":e.toString(),od.formatters.c=e=>null==e?"undefined":e.toString(),od.formatters.k=e=>null==e?"undefined":e.toString(),od.formatters.a=e=>null==e?"undefined":e.toString(),od.formatters.e=e=>{var t,r;return null==e?"undefined":null!==(t=null!==(r=ld(e.stack))&&void 0!==r?r:ld(e.message))&&void 0!==t?t:e.toString()},sd("datastore:core:tiered");class ud{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,r){return Promise.reject(new Error(".put is not implemented"))}putMany(e,t){var r=this;return l((function*(){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var{cid:c,block:d}=a.value;yield u(r.put(c,d,t)),yield c}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}))()}get(e,t){return Promise.reject(new Error(".get is not implemented"))}getMany(e,t){var r=this;return l((function*(){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var c=a.value;yield{cid:c,block:yield u(r.get(c,t))}}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}))()}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}deleteMany(e,t){var r=this;return l((function*(){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var c=a.value;yield u(r.delete(c,t)),yield c}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}))()}getAll(e){return l((function*(){throw new Error(".getAll is not implemented")}))()}}class cd extends ud{constructor(){super(),e(this,"data",void 0),this.data=new Map}put(e,t,r){var n;return null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted(),this.data.set(K.encode(e.multihash.bytes),t),e}get(e,t){var r;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted();var n=this.data.get(K.encode(e.multihash.bytes));if(null==n)throw new Ec;return n}has(e,t){var r;return null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.data.has(K.encode(e.multihash.bytes))}delete(e,t){var n=this;return r((function*(){var r;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),n.data.delete(K.encode(e.multihash.bytes))}))()}getAll(e){var t=this;return l((function*(){var r;for(var[n,i]of(null==e||null===(r=e.signal)||void 0===r||r.throwIfAborted(),t.data.entries())){var o;yield{cid:it.createV1(Se,He(K.decode(n))),block:i},null==e||null===(o=e.signal)||void 0===o||o.throwIfAborted()}}))()}}sd("blockstore:core:tiered"),function(e){var t;e.codec=()=>(null==t&&(t=Hl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.publicKey&&e.publicKey.byteLength>0&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.payloadType&&e.payloadType.byteLength>0&&(t.uint32(18),t.bytes(e.payloadType)),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(26),t.bytes(e.payload)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={publicKey:ct(0),payloadType:ct(0),payload:ct(0),signature:ct(0)},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.publicKey=e.bytes();break;case 2:r.payloadType=e.bytes();break;case 3:r.payload=e.bytes();break;case 5:r.signature=e.bytes();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(nd||(nd={}));class dd extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid signature"),this.name="InvalidSignatureError"}}class hd{constructor(t){e(this,"publicKey",void 0),e(this,"payloadType",void 0),e(this,"payload",void 0),e(this,"signature",void 0),e(this,"marshaled",void 0);var{publicKey:r,payloadType:n,payload:i,signature:o}=t;this.publicKey=r,this.payloadType=n,this.payload=i,this.signature=o}marshal(){return null==this.marshaled&&(this.marshaled=nd.encode({publicKey:Su(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return null!=e&&St(this.marshal(),e.marshal())}validate(e){var t=this;return r((function*(){var r=vd(e,t.payloadType,t.payload);return t.publicKey.verify(r.subarray(),t.signature)}))()}}id=hd,e(hd,"createFromProtobuf",function(){var e=r((function*(e){var t=nd.decode(e),r=mu(t.publicKey);return new id({publicKey:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})}));return function(t){return e.apply(this,arguments)}}()),e(hd,"seal",function(){var e=r((function*(e,t){if(null==t)throw new Error("Missing private key");var r=e.domain,n=e.codec,i=e.marshal(),o=vd(r,n,i),a=yield t.sign(o.subarray());return new id({publicKey:t.publicKey,payloadType:n,payload:i,signature:a})}));return function(t,r){return e.apply(this,arguments)}}()),e(hd,"openAndCertify",function(){var e=r((function*(e,t){var r=yield id.createFromProtobuf(e);if(!(yield r.validate(t)))throw new dd("Envelope signature is not valid for the given domain");return r}));return function(t,r){return e.apply(this,arguments)}}());var vd=(e,t,r)=>{var n=Et(e),i=Ot(n.byteLength),o=Ot(t.length),a=Ot(r.length);return new gs(i,n,o,t,a,r)};var pd,fd,gd=Uint8Array.from([3,1]);!function(e){var t;!function(e){var t;e.codec=()=>(null==t&&(t=Hl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={multiaddr:ct(0)},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();if(i>>>3==1)r.multiaddr=e.bytes();else e.skipType(7&i)}return r}))),t),e.encode=t=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==t&&(t=Hl((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==n.lengthDelimited&&r.fork(),null!=t.peerId&&t.peerId.byteLength>0&&(r.uint32(10),r.bytes(t.peerId)),null!=t.seq&&0n!==t.seq&&(r.uint32(16),r.uint64(t.seq)),null!=t.addresses)for(var i of t.addresses)r.uint32(26),e.AddressInfo.codec().encode(i,r);!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={peerId:ct(0),seq:0n,addresses:[]},o=null==r?t.len:t.pos+r;t.pos<o;){var a=t.uint32();switch(a>>>3){case 1:i.peerId=t.bytes();break;case 2:i.seq=t.uint64();break;case 3:var s,l;if(null!=(null===(s=n.limits)||void 0===s?void 0:s.addresses)&&i.addresses.length===n.limits.addresses)throw new Kl('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=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(pd||(pd={}));class yd{constructor(t){e(this,"peerId",void 0),e(this,"multiaddrs",void 0),e(this,"seqNumber",void 0),e(this,"domain",yd.DOMAIN),e(this,"codec",yd.CODEC),e(this,"marshaled",void 0);var{peerId:r,multiaddrs:n,seqNumber:i}=t;this.peerId=r,this.multiaddrs=null!=n?n:[],this.seqNumber=null!=i?i:BigInt(Date.now())}marshal(){return null==this.marshaled&&(this.marshaled=pd.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 yd&&(!!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)))}}fd=yd,e(yd,"createFromProtobuf",(e=>{var t,r=pd.decode(e),n=Lu(He(r.peerId)),i=(null!==(t=r.addresses)&&void 0!==t?t:[]).map((e=>kr(e.multiaddr))),o=r.seq;return new fd({peerId:n,multiaddrs:i,seqNumber:o})})),e(yd,"DOMAIN","libp2p-peer-record"),e(yd,"CODEC",gd);let md=class extends Error{constructor(){super(...arguments),e(this,"name","UnexpectedEOFError"),e(this,"code","ERR_UNEXPECTED_EOF")}};function wd(e,t){var n=Oc();e.sink(n).catch(function(){var e=r((function*(e){yield n.end(e)}));return function(t){return e.apply(this,arguments)}}()),e.sink=function(){var e=r((function*(e){var t,r=!1,i=!1;try{for(var o,a=s(e);r=!(o=yield a.next()).done;r=!1){var l=o.value;yield n.push(l)}}catch(e){i=!0,t=e}finally{try{r&&null!=a.return&&(yield a.return())}finally{if(i)throw t}}yield n.end()}));return function(t){return e.apply(this,arguments)}}();var i=e.source;null!=e.source[Symbol.iterator]?i=e.source[Symbol.iterator]():null!=e.source[Symbol.asyncIterator]&&(i=e.source[Symbol.asyncIterator]());var o,a=new gs,u={read:function(){var e=r((function*(e){var t;if(null==e||null===(t=e.signal)||void 0===t||t.throwIfAborted(),null==(null==e?void 0:e.bytes)){var{done:r,value:n}=yield Nc(i.next(),null==e?void 0:e.signal);return!0===r?null:n}for(;a.byteLength<e.bytes;){var{value:o,done:s}=yield Nc(i.next(),null==e?void 0:e.signal);if(!0===s)throw new md("unexpected end of input");a.append(o)}var l=a.sublist(0,e.bytes);return a.consume(e.bytes),l}));return function(t){return e.apply(this,arguments)}}(),write:(o=r((function*(e,t){var r;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),e instanceof Uint8Array?yield n.push(e,t):yield n.push(e.subarray(),t)})),function(e,t){return o.apply(this,arguments)}),unwrap:()=>{if(a.byteLength>0){var r=e.source;e.source=l((function*(){!1===(null==t?void 0:t.yieldBytes)?yield a:yield*c(s(a)),yield*c(s(r))}))()}return e}};return u}let bd=class extends Error{constructor(){super(...arguments),e(this,"name","InvalidMessageLengthError"),e(this,"code","ERR_INVALID_MSG_LENGTH")}},Sd=class extends Error{constructor(){super(...arguments),e(this,"name","InvalidDataLengthError"),e(this,"code","ERR_MSG_DATA_TOO_LONG")}},Ed=class extends Error{constructor(){super(...arguments),e(this,"name","InvalidDataLengthLengthError"),e(this,"code","ERR_MSG_LENGTH_TOO_LONG")}};function kd(e){var n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=wd(e,o);null!=o.maxDataLength&&null==o.maxLengthLength&&(o.maxLengthLength=Nt(o.maxDataLength));var s,l=null!==(n=null==o?void 0:o.lengthDecoder)&&void 0!==n?n:Lt,u=null!==(i=null==o?void 0:o.lengthEncoder)&&void 0!==i?i:Ot,c={read:function(){var e=r((function*(e){for(var r=-1,n=new gs;;){n.append(yield a.read(t(t({},e),{},{bytes:1})));try{r=l(n)}catch(e){if(e instanceof RangeError)continue;throw e}if(r<0)throw new bd("Invalid message length");if(null!=(null==o?void 0:o.maxLengthLength)&&n.byteLength>o.maxLengthLength)throw new Ed("message length length too long");if(r>-1)break}if(null!=(null==o?void 0:o.maxDataLength)&&r>o.maxDataLength)throw new Sd("message length too long");return a.read(t(t({},e),{},{bytes:r}))}));return function(t){return e.apply(this,arguments)}}(),write:function(){var e=r((function*(e,t){yield a.write(new gs(u(e.byteLength),e),t)}));return function(t,r){return e.apply(this,arguments)}}(),writeV:(s=r((function*(e,t){var r=new gs(...e.flatMap((e=>[u(e.byteLength),e])));yield a.write(r,t)})),function(e,t){return s.apply(this,arguments)}),unwrap:()=>a.unwrap()};return c}function xd(e,t){var n,i=kd(e,t),o={read:function(){var e=r((function*(e,t){var r=yield i.read(t);return e.decode(r)}));return function(t,r){return e.apply(this,arguments)}}(),write:function(){var e=r((function*(e,t,r){yield i.write(t.encode(e),r)}));return function(t,r,n){return e.apply(this,arguments)}}(),writeV:(n=r((function*(e,t,r){yield i.writeV(e.map((e=>t.encode(e))),r)})),function(e,t,r){return n.apply(this,arguments)}),pb:e=>{return{read:(i=r((function*(t){return o.read(e,t)})),function(e){return i.apply(this,arguments)}),write:(n=r((function*(t,r){return o.write(t,e,r)})),function(e,t){return n.apply(this,arguments)}),writeV:(t=r((function*(t,r){return o.writeV(t,e,r)})),function(e,r){return t.apply(this,arguments)}),unwrap:()=>o};var t,n,i},unwrap:()=>i.unwrap()};return o}var Ad="".concat(Aa,"-circuit-relay");BigInt(1<<17);var Cd,Id,Td,Pd,_d,Bd,Nd,Dd,Rd,Od="/libp2p/circuit/relay/0.2.0/hop",Ld="/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=()=>ql(t)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=Hl((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),Td.codec().encode(t.peer,r)),null!=t.reservation&&(r.uint32(26),Pd.codec().encode(t.reservation,r)),null!=t.limit&&(r.uint32(34),_d.codec().encode(t.limit,r)),null!=t.status&&(r.uint32(40),Bd.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=Td.codec().decode(t,t.uint32(),{limits:null===(s=n.limits)||void 0===s?void 0:s.peer});break;case 3:var l;i.reservation=Pd.codec().decode(t,t.uint32(),{limits:null===(l=n.limits)||void 0===l?void 0:l.reservation});break;case 4:var u;i.limit=_d.codec().decode(t,t.uint32(),{limits:null===(u=n.limits)||void 0===u?void 0:u.limit});break;case 5:i.status=Bd.codec().decode(t);break;default:t.skipType(7&a)}}return i}))),r),e.encode=t=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(Cd||(Cd={})),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=()=>ql(t)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=Hl((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),Td.codec().encode(t.peer,r)),null!=t.limit&&(r.uint32(26),_d.codec().encode(t.limit,r)),null!=t.status&&(r.uint32(32),Bd.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=Td.codec().decode(t,t.uint32(),{limits:null===(s=n.limits)||void 0===s?void 0:s.peer});break;case 3:var l;i.limit=_d.codec().decode(t,t.uint32(),{limits:null===(l=n.limits)||void 0===l?void 0:l.limit});break;case 4:i.status=Bd.codec().decode(t);break;default:t.skipType(7&a)}}return i}))),r),e.encode=t=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(Id||(Id={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.id&&e.id.byteLength>0&&(t.uint32(10),t.bytes(e.id)),null!=e.addrs)for(var n of e.addrs)t.uint32(18),t.bytes(n);!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={id:ct(0),addrs:[]},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.id=e.bytes();break;case 2:var a;if(null!=(null===(a=r.limits)||void 0===a?void 0:a.addrs)&&n.addrs.length===r.limits.addrs)throw new Kl('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=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(Td||(Td={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((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),Rd.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 Kl('Decode error - map field "addrs" had too many elements');n.addrs.push(e.bytes());break;case 3:var s;n.voucher=Rd.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=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(Pd||(Pd={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((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=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(_d||(_d={})),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"}(Bd||(Bd={})),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"}(Nd||(Nd={})),function(e){e.codec=()=>ql(Nd)}(Bd||(Bd={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.relay&&e.relay.byteLength>0&&(t.uint32(10),t.bytes(e.relay)),null!=e.peer&&e.peer.byteLength>0&&(t.uint32(18),t.bytes(e.peer)),null!=e.expiration&&0n!==e.expiration&&(t.uint32(24),t.uint64(e.expiration)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={relay:ct(0),peer:ct(0),expiration:0n},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.relay=e.bytes();break;case 2:r.peer=e.bytes();break;case 3:r.expiration=e.uint64();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(Dd||(Dd={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((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),Dd.codec().encode(e.payload,t)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={publicKey:ct(0),payloadType:ct(0),signature:ct(0)},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.publicKey=e.bytes();break;case 2:n.payloadType=e.bytes();break;case 3:var a;n.payload=Dd.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=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(Rd||(Rd={}));var Md=e=>({match:t=>!(t.length<1)&&(!!e(t[0])&&t.slice(1)),pattern:"fn"}),Ud=e=>({match:t=>Md((t=>t===e)).match(t),pattern:e}),Fd=()=>({match:e=>Md((e=>"string"==typeof e)).match(e),pattern:"{string}"}),zd=()=>({match:e=>Md((e=>!isNaN(parseInt(e)))).match(e),pattern:"{number}"}),jd=()=>({match:e=>{if(e.length<2)return!1;if("p2p"!==e[0]&&"ipfs"!==e[0])return!1;if(!e[1].startsWith("Q")&&!e[1].startsWith("1"))return!1;try{ie.decode("z".concat(e[1]))}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),Vd=()=>({match:e=>{if(e.length<2)return!1;if("certhash"!==e[0])return!1;try{ue.decode(e[1])}catch(e){return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),qd=e=>({match:t=>{var r=e.match(t);return!1===r?t:r},pattern:"optional(".concat(e.pattern,")")}),Hd=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(", "),")")}},Kd=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 Wd(){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 Gd=Wd(jd()),Qd=Kd(Ud("dns4"),Fd()),Yd=Kd(Ud("dns6"),Fd()),Jd=Kd(Ud("dnsaddr"),Fd()),Zd=Kd(Ud("dns"),Fd());Wd(Qd,qd(jd())),Wd(Yd,qd(jd())),Wd(Jd,qd(jd()));var $d=Wd(Hd(Zd,Jd,Qd,Yd),qd(jd())),Xd=Kd(Ud("ip4"),Md(Vt)),eh=Kd(Ud("ip6"),Md(qt)),th=Hd(Xd,eh),rh=Hd(th,Zd,Qd,Yd,Jd),nh=Wd(Hd(th,Kd(Hd(Zd,Jd,Qd,Yd),qd(jd())))),ih=Wd(Xd),oh=Wd(eh),ah=Wd(th),sh=Kd(rh,Ud("tcp"),zd()),lh=Kd(rh,Ud("udp"),zd()),uh=Wd(Kd(sh,qd(jd())));Wd(lh);var ch=Kd(lh,Ud("quic"),qd(jd())),dh=Kd(lh,Ud("quic-v1"),qd(jd())),hh=Hd(ch,dh);Wd(ch);var vh=Wd(dh),ph=Hd(rh,sh,lh,ch,dh),fh=Hd(Kd(ph,Ud("ws"),qd(jd()))),gh=Wd(fh),yh=Hd(Kd(ph,Ud("wss"),qd(jd())),Kd(ph,Ud("tls"),qd(Kd(Ud("sni"),Fd())),Ud("ws"),qd(jd()))),mh=Wd(yh),wh=Kd(lh,Ud("webrtc-direct"),qd(Vd()),qd(Vd()),qd(jd())),bh=Wd(wh),Sh=Kd(dh,Ud("webtransport"),qd(Vd()),qd(Vd()),qd(jd())),Eh=Wd(Sh),kh=Hd(fh,yh,Kd(sh,qd(jd())),Kd(hh,qd(jd())),Kd(rh,qd(jd())),wh,Sh,jd()),xh=Wd(kh),Ah=Wd(Kd(kh,Ud("p2p-circuit"),jd())),Ch=Wd(Hd(Kd(kh,Ud("p2p-circuit"),Ud("webrtc"),qd(jd())),Kd(kh,Ud("webrtc"),qd(jd())),Kd(Ud("webrtc"),qd(jd())))),Ih=Wd(Hd(Kd(rh,Ud("tcp"),zd(),Ud("http"),qd(jd())),Kd(rh,Ud("http"),qd(jd())))),Th=Wd(Hd(Kd(rh,Ud("tcp"),Hd(Kd(Ud("443"),Ud("http")),Kd(zd(),Ud("https")),Kd(zd(),Ud("tls"),Ud("http"))),qd(jd())),Kd(rh,Ud("tls"),Ud("http"),qd(jd())),Kd(rh,Ud("https"),qd(jd()))));function Ph(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}Wd(Hd(Kd(Ud("memory"),Fd(),qd(jd()))));class _h extends Error{constructor(){super(...arguments),e(this,"name","HadEnoughRelaysError")}}e(_h,"name","HadEnoughRelaysError");class Bh extends Error{constructor(){super(...arguments),e(this,"name","DoubleRelayError")}}e(Bh,"name","DoubleRelayError");class Nh extends Error{constructor(){super(...arguments),e(this,"name","RelayQueueFullError")}}function Dh(e){var t=e*BigInt(1e3),r=(new Date).getTime();return Number(t-BigInt(r))}e(Nh,"name","RelayQueueFullError");class Rh{constructor(t){e(this,"expires",void 0),e(this,"bytes",void 0),null!=(null==t?void 0:t.duration)&&0!==(null==t?void 0:t.duration)&&(this.expires=Date.now()+1e3*t.duration),this.bytes=null==t?void 0:t.data,0n===this.bytes&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){null!=this.bytes&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(null!=this.expires||null!=this.bytes){var e={};if(null!=this.bytes){var t=this;Object.defineProperty(e,"bytes",{get:()=>t.bytes})}if(null!=this.expires){var r=this;Object.defineProperty(e,"seconds",{get(){var e;return Math.round(((null!==(e=r.expires)&&void 0!==e?e:0)-Date.now())/1e3)}})}return e}}}var Oh=Wd(Kd(xh.matchers[0],Ud("p2p-circuit"))),Lh=Wd(Ud("p2p-circuit"));function Mh(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 Uh(e){return Lu(He(ie.decode("z".concat(e))))}class Fh{constructor(t){if(e(this,"map",void 0),this.map=new Map,null!=t)for(var[r,n]of t.entries())this.map.set(r.toString(),{key:r,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Mh(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 Mh(this.map.values(),(e=>e.key))}values(){return Mh(this.map.values(),(e=>e.value))}get size(){return this.map.size}}class zh{constructor(t){if(e(this,"set",void 0),this.set=new Set,null!=t)for(var r of t)this.set.add(r.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Mh(this.set.entries(),(e=>{var t=Uh(e[0]);return[t,t]}))}forEach(e){this.set.forEach((t=>{var r=Uh(t);e(r,r,this)}))}has(e){return this.set.has(e.toString())}values(){return Mh(this.set.values(),(e=>Uh(e)))}intersection(e){var t=new zh;for(var r of e)this.has(r)&&t.add(r);return t}difference(e){var t=new zh;for(var r of this)e.has(r)||t.add(r);return t}union(e){var t=new zh;for(var r of e)t.add(r);for(var n of this)t.add(n);return t}}var jh={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Vh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},qh=new globalThis.TextEncoder;function Hh(e){var{size:t=32,utf8Buffer:r}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!jh[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=jh[t],i=Vh[t],o=e;o.length>0;){var a=qh.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=qh.encode(e)}return function(e,t){for(var r=jh[t],n=Vh[t],i=0;i<e.length;i++)n^=BigInt(e[i]),n=BigInt.asUintN(t,n*r);return n}(e,t)}var Kh={hash:e=>Number(Hh(e,{size:32})),hashV:(e,t)=>function(e){var t=e.toString(16);t.length%2==1&&(t="0".concat(t));return Et(t,"base16")}(Kh.hash(e,t))};class Wh{constructor(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:2;if(e(this,"fp",void 0),e(this,"h",void 0),e(this,"seed",void 0),i>64)throw new TypeError("Invalid Fingerprint Size");for(var o=r.hashV(t,n),a=ct(i),s=0;s<a.length;s++)a[s]=o[s];0===a.length&&(a[0]=7),this.fp=a,this.h=r,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return(null==e?void 0:e.fp)instanceof Uint8Array&&St(this.fp,e.fp)}}function Gh(e,t){return Math.floor(Math.random()*(t-e))+e}let Qh=class{constructor(t){e(this,"contents",void 0),this.contents=new Array(t).fill(null)}has(e){if(!(e instanceof Wh))throw new TypeError("Invalid Fingerprint");return this.contents.some((t=>e.equals(t)))}add(e){if(!(e instanceof Wh))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 Wh))throw new TypeError("Invalid Fingerprint");var t=Gh(0,this.contents.length-1),r=this.contents[t];return this.contents[t]=e,r}remove(e){if(!(e instanceof Wh))throw new TypeError("Invalid Fingerprint");var t=this.contents.findIndex((t=>e.equals(t)));return t>-1&&(this.contents[t]=null,!0)}};class Yh{constructor(t){var r,n,i,o;e(this,"bucketSize",void 0),e(this,"filterSize",void 0),e(this,"fingerprintSize",void 0),e(this,"buckets",void 0),e(this,"count",void 0),e(this,"hash",void 0),e(this,"seed",void 0),this.filterSize=t.filterSize,this.bucketSize=null!==(r=t.bucketSize)&&void 0!==r?r:4,this.fingerprintSize=null!==(n=t.fingerprintSize)&&void 0!==n?n:2,this.count=0,this.buckets=[],this.hash=null!==(i=t.hash)&&void 0!==i?i:Kh,this.seed=null!==(o=t.seed)&&void 0!==o?o:Gh(0,Math.pow(2,10))}add(e){"string"==typeof e&&(e=Et(e));var t=new Wh(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 Qh(this.bucketSize)),null==this.buckets[n]&&(this.buckets[n]=new Qh(this.bucketSize)),this.buckets[r].add(t)||this.buckets[n].add(t))return this.count++,!0;var i=[r,n],o=i[Gh(0,i.length-1)];null==this.buckets[o]&&(this.buckets[o]=new Qh(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 Qh(this.bucketSize)),this.buckets[o].add(s)))return this.count++,!0}return!1}has(e){var t,r,n,i;"string"==typeof e&&(e=Et(e));var o=new Wh(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=Et(e));var o=new Wh(e,this.hash,this.seed,this.fingerprintSize),a=this.hash.hash(e,this.seed)%this.filterSize,s=null!==(t=null===(r=this.buckets[a])||void 0===r?void 0:r.remove(o))&&void 0!==t&&t;if(s)return this.count--,s;var l=(a^o.hash())%this.filterSize,u=null!==(n=null===(i=this.buckets[l])||void 0===i?void 0:i.remove(o))&&void 0!==n&&n;return u&&this.count--,u}get reliable(){return Math.floor(this.count/this.filterSize*100)<=90}}var Jh={1:.5,2:.84,4:.95,8:.98};class Zh{constructor(t){var r,n,i,o,a,s;e(this,"filterSize",void 0),e(this,"bucketSize",void 0),e(this,"fingerprintSize",void 0),e(this,"scale",void 0),e(this,"filterSeries",void 0),e(this,"hash",void 0),e(this,"seed",void 0),this.bucketSize=null!==(r=t.bucketSize)&&void 0!==r?r:4,this.filterSize=null!==(n=t.filterSize)&&void 0!==n?n:(1<<18)/this.bucketSize,this.fingerprintSize=null!==(i=t.fingerprintSize)&&void 0!==i?i:2,this.scale=null!==(o=t.scale)&&void 0!==o?o:2,this.hash=null!==(a=t.hash)&&void 0!==a?a:Kh,this.seed=null!==(s=t.seed)&&void 0!==s?s:Gh(0,Math.pow(2,10)),this.filterSeries=[new Yh({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=Et(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 Yh({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=Et(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=Et(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 $h(e){var r=arguments.length>2?arguments[2]:void 0;return new Zh(t(t({},function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:.001,r=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:.001;return e>.002?2:e>1e-5?4:8}(t),n=Jh[r];return{filterSize:Math.round(e/n),bucketSize:r,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*r)),64)}}(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:.001)),null!=r?r:{}))}class Xh{constructor(t,r){e(this,"filter",void 0),this.filter=$h(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 ev(e){return new Xh(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:.001)}class tv extends Fh{constructor(t){super(),e(this,"metric",void 0);var{name:r,metrics:n}=t;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){var t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function rv(e){var{name:t,metrics:r}=e;return null!=r?new tv({name:t,metrics:r}):new Fh}function nv(e){return null!=(null==e?void 0:e.then)}function iv(e,t){var r=0;if(null!=e[Symbol.asyncIterator])return l((function*(){var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var c=a.value,d=t(c,r++);nv(d)&&(yield u(d)),yield c}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}))();var n=cc(e),{value:i,done:o}=n.next();if(!0===o)return function*(){}();var a=t(i,r++);if("function"==typeof(null==a?void 0:a.then))return l((function*(){for(var e of(yield i,n)){var o=t(e,r++);nv(o)&&(yield u(o)),yield e}}))();var c=t;return function*(){for(var e of(yield i,n))c(e,r++),yield e}()}function ov(e){var{stream:t,remoteAddr:n,logger:i,onDataRead:o,onDataWrite:a}=e,c=i.forComponent("libp2p:stream:converter"),d=!1,h=!1,v=t.close.bind(t);t.close=function(){var e=r((function*(e){yield v(e),y(!0)}));return function(t){return e.apply(this,arguments)}}();var p=t.abort.bind(t);t.abort=e=>{p(e),y(!0)};var f=t.sink.bind(t);t.sink=function(){var e=r((function*(e){try{yield f(Fc(e,(e=>iv(e,(e=>null==a?void 0:a(e))))))}catch(e){"aborted"!==e.type&&c.error("%s error in sink",n,e)}finally{h=!0,y()}}));return function(t){return e.apply(this,arguments)}}();var g={log:c,sink:t.sink,source:l((function*(){try{var e,r=!1,n=!1;try{for(var i,a=s(t.source);r=!(i=yield u(a.next())).done;r=!1){var l=i.value;null==o||o(l),yield l}}catch(t){n=!0,e=t}finally{try{r&&null!=a.return&&(yield u(a.return()))}finally{if(n)throw e}}}finally{d=!0,y()}}))(),remoteAddr:n,timeline:{open:Date.now(),close:void 0},close:t.close,abort:t.abort};function y(e){!0===e&&(d=!0,h=!0),d&&h&&null==g.timeline.close&&(g.timeline.close=Date.now())}return g}class av extends Event{constructor(t,r){super(t),e(this,"type",void 0),e(this,"detail",void 0),this.type=t,this.detail=r}}let sv=class extends Error{constructor(t,r){super(null!=t?t:"The operation was aborted"),e(this,"type",void 0),e(this,"code",void 0),this.type="aborted",this.name="AbortError",this.code=null!=r?r:"ABORT_ERR"}};function lv(e,t,r,n){return uv.apply(this,arguments)}function uv(){return uv=r((function*(e,t,r,n){var i=new sv(null==n?void 0:n.errorMessage,null==n?void 0:n.errorCode);return!0===(null==r?void 0:r.aborted)?Promise.reject(i):new Promise(((o,a)=>{function s(){null==r||r.removeEventListener("abort",c),e.removeEventListener(t,l),null!=(null==n?void 0:n.errorEvent)&&e.removeEventListener(n.errorEvent,u)}var l=e=>{try{var t;if(!1===(null==n||null===(t=n.filter)||void 0===t?void 0:t.call(n,e)))return}catch(e){return s(),void a(e)}s(),o(e)},u=e=>{s(),a(e.detail)},c=()=>{s(),a(i)};null==r||r.addEventListener("abort",c),e.addEventListener(t,l),null!=(null==n?void 0:n.errorEvent)&&e.addEventListener(n.errorEvent,u)}))})),uv.apply(this,arguments)}function cv(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 dv extends Error{constructor(){var t=arguments.length>1?arguments[1]:void 0;super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Rate limit exceeded"),e(this,"remainingPoints",void 0),e(this,"msBeforeNext",void 0),e(this,"consumedPoints",void 0),e(this,"isFirstInDuration",void 0),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}}let hv=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The queue was full"),this.name="QueueFullError"}};e(hv,"name","QueueFullError");let vv=class{constructor(t){var r;e(this,"deferred",void 0),e(this,"signal",void 0),this.signal=t,this.deferred=Cc(),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 Ia)}cleanup(){var e;null===(e=this.signal)||void 0===e||e.removeEventListener("abort",this.onAbort)}};let pv=class{constructor(t,r){e(this,"id",void 0),e(this,"fn",void 0),e(this,"options",void 0),e(this,"recipients",void 0),e(this,"status",void 0),e(this,"timeline",void 0),e(this,"controller",void 0),this.id="".concat(parseInt(String(1e9*Math.random()),10).toString()).concat(Date.now()),this.status="queued",this.fn=t,this.options=r,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){var e=this.recipients.reduce(((e,t)=>{var r;return e&&!0===(null===(r=t.signal)||void 0===r?void 0:r.aborted)}),!0);e&&(this.controller.abort(new Ia),this.cleanup())}join(){var e=arguments,t=this;return r((function*(){var r,n=e.length>0&&void 0!==e[0]?e[0]:{},i=new vv(n.signal);return t.recipients.push(i),null===(r=n.signal)||void 0===r||r.addEventListener("abort",t.onAbort),i.deferred.promise}))()}run(){var e=this;return r((function*(){e.status="running",e.timeline.started=Date.now();try{var r;e.controller.signal.throwIfAborted();var n=yield Nc(e.fn(t(t({},null!==(r=e.options)&&void 0!==r?r:{}),{},{signal:e.controller.signal})),e.controller.signal);e.recipients.forEach((e=>{e.deferred.resolve(n)})),e.status="complete"}catch(t){e.recipients.forEach((e=>{e.deferred.reject(t)})),e.status="errored"}finally{e.timeline.finished=Date.now(),e.cleanup()}}))()}cleanup(){this.recipients.forEach((e=>{var t;e.cleanup(),null===(t=e.signal)||void 0===t||t.removeEventListener("abort",this.onAbort)}))}},fv=class extends os{constructor(){var t,r,n,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(super(),e(this,"concurrency",void 0),e(this,"maxSize",void 0),e(this,"queue",void 0),e(this,"pending",void 0),e(this,"sort",void 0),this.concurrency=null!==(t=i.concurrency)&&void 0!==t?t:Number.POSITIVE_INFINITY,this.maxSize=null!==(r=i.maxSize)&&void 0!==r?r:Number.POSITIVE_INFINITY,this.pending=0,null!=i.metricName)&&(null===(n=i.metrics)||void 0===n||n.registerMetricGroup(i.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}));this.sort=i.sort,this.queue=[],this.emitEmpty=cv(this.emitEmpty.bind(this),1),this.emitIdle=cv(this.emitIdle.bind(this),1)}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){var e;for(var t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally((()=>{for(var t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")})),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}add(e,t){var n=this;return r((function*(){var r;if(null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),n.size===n.maxSize)throw new hv;var i=new pv(e,t);return n.enqueue(i),n.safeDispatchEvent("add"),n.tryToStartAnother(),i.join(t).then((e=>(n.safeDispatchEvent("completed",{detail:e}),n.safeDispatchEvent("success",{detail:{job:i,result:e}}),e))).catch((e=>{if("queued"===i.status)for(var t=0;t<n.queue.length;t++)if(n.queue[t]===i){n.queue.splice(t,1);break}throw n.safeDispatchEvent("error",{detail:e}),n.safeDispatchEvent("failure",{detail:{job:i,error:e}}),e}))}))()}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach((e=>{e.abort(new Ia)})),this.clear()}onEmpty(e){var t=this;return r((function*(){0!==t.size&&(yield lv(t,"empty",null==e?void 0:e.signal))}))()}onSizeLessThan(e,t){var n=this;return r((function*(){n.size<e||(yield lv(n,"next",null==t?void 0:t.signal,{filter:()=>n.size<e}))}))()}onIdle(e){var t=this;return r((function*(){0===t.pending&&0===t.size||(yield lv(t,"idle",null==e?void 0:e.signal))}))()}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}toGenerator(e){var t=this;return l((function*(){var r,n;null==e||null===(r=e.signal)||void 0===r||r.throwIfAborted();var i=_c({objectMode:!0}),o=e=>{null!=e?t.abort():t.clear(),i.end(e)},a=e=>{null!=e.detail&&i.push(e.detail)},l=e=>{o(e.detail)},d=()=>{o()},h=()=>{o(new Ia("Queue aborted"))};t.addEventListener("completed",a),t.addEventListener("error",l),t.addEventListener("idle",d),null==e||null===(n=e.signal)||void 0===n||n.addEventListener("abort",h);try{yield*c(s(i),u)}finally{var v;t.removeEventListener("completed",a),t.removeEventListener("error",l),t.removeEventListener("idle",d),null==e||null===(v=e.signal)||void 0===v||v.removeEventListener("abort",h),o()}}))()}};class gv extends fv{has(e){return null!=this.find(e)}find(e){return this.queue.find((t=>e.equals(t.options.peerId)))}}class yv extends os{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),e(this,"peerStore",void 0),e(this,"registrar",void 0),e(this,"connectionManager",void 0),e(this,"randomWalk",void 0),e(this,"started",void 0),e(this,"running",void 0),e(this,"topologyId",void 0),e(this,"log",void 0),e(this,"discoveryController",void 0),e(this,"filter",void 0),e(this,"queue",void 0),this.log=t.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.started=!1,this.running=!1,this.peerStore=t.peerStore,this.registrar=t.registrar,this.connectionManager=t.connectionManager,this.randomWalk=t.randomWalk,this.filter=r.filter,this.discoveryController=new AbortController,this.discoveryController.signal}isStarted(){return this.started}start(){var e=this;return r((function*(){e.topologyId=yield e.registrar.register(Od,{filter:e.filter,onConnect:t=>{var r,n;e.log.trace("discovered relay %p queue (length: %d, active %d)",t,null===(r=e.queue)||void 0===r?void 0:r.size,null===(n=e.queue)||void 0===n?void 0:n.running),e.safeDispatchEvent("relay:discover",{detail:t})}}),e.started=!0}))()}stop(){var e;null!=this.topologyId&&this.registrar.unregister(this.topologyId),null===(e=this.discoveryController)||void 0===e||e.abort(),this.started=!1}startDiscovery(){var e=this;this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,Promise.resolve().then(r((function*(){e.log("searching peer store for relays");var t=yield e.peerStore.all({filters:[e=>e.protocols.includes(Od)],orders:[()=>Math.random()<.5?1:-1,(e,t)=>{var r=mv(e),n=mv(t);return r>n?-1:n>r?1:0}]});for(var n of t)e.log.trace("found relay peer %p in peer store",n.id),e.safeDispatchEvent("relay:discover",{detail:n.id});e.log("found %d relay peers in peer store",t.length);var i=e.queue=new gv({concurrency:5});e.log("start random walk");var o,a=!1,l=!1;try{for(var u,c=function*(){var t,n=u.value;return e.log.trace("found random peer %p",n.id),i.has(n.id)?(e.log.trace("random peer %p was already in queue",n.id),0):(null===(t=e.connectionManager.getConnections(n.id))||void 0===t?void 0:t.length)>0?(e.log.trace("random peer %p was already connected",n.id),0):(yield e.connectionManager.isDialable(n.multiaddrs))?(i.queued>10&&(e.log.trace("wait for space in queue for %p",n.id),yield i.onSizeLessThan(10,{signal:e.discoveryController.signal})),e.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,i.size,i.running),void i.add(r((function*(){var t=Ph([e.discoveryController.signal,AbortSignal.timeout(5e3)]);try{yield e.connectionManager.openConnection(n.id,{signal:t})}finally{t.clear()}})),{peerId:n.id,signal:e.discoveryController.signal}).catch((t=>{e.log.error("error opening connection to random peer %p",n.id,t)}))):(e.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map((e=>e.toString()))),0)},d=s(e.randomWalk.walk({signal:e.discoveryController.signal}));a=!(u=yield d.next()).done;a=!1)yield*c()}catch(e){l=!0,o=e}finally{try{a&&null!=d.return&&(yield d.return())}finally{if(l)throw o}}e.log("stop random walk"),yield i.onIdle()}))).catch((e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network",e)})))}stopDiscovery(){var e;this.log("stop discovery"),this.running=!1,null===(e=this.discoveryController)||void 0===e||e.abort()}}function mv(e){var t=e.metadata.get("last-dial-success");return null==t?0:new Date(gt(t)).getTime()}class wv extends os{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),e(this,"connectionManager",void 0),e(this,"addressManager",void 0),e(this,"reservationStore",void 0),e(this,"listeningAddrs",void 0),e(this,"log",void 0),e(this,"listenTimeout",void 0),e(this,"reservationId",void 0),e(this,"relay",void 0),e(this,"_onRemoveRelayPeer",(e=>{var t,r;this.log("relay removed %p our relay %p",e.detail.relay,this.relay,null===(t=this.relay)||void 0===t?void 0:t.equals(e.detail.relay)),!0===(null===(r=this.relay)||void 0===r?void 0:r.equals(e.detail.relay))&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach((e=>{this.addressManager.removeObservedAddr(e)})),this.listeningAddrs=[],this.safeDispatchEvent("listening"))})),e(this,"_onAddRelayPeer",(e=>{var{details:t}=e.detail;"configured"!==t.type&&t.id===this.reservationId&&this.addedRelay(e.detail)})),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=t.connectionManager,this.addressManager=t.addressManager,this.reservationStore=t.reservationStore,this.listeningAddrs=[],this.listenTimeout=null!==(r=n.listenTimeout)&&void 0!==r?r:2e3,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}listen(e){var t=this;return r((function*(){if(Lh.exactMatch(e))t.log("searching for circuit relay servers"),t.reservationId=t.reservationStore.reserveRelay();else{if(!Oh.exactMatch(e))throw new $a('Could not listen on p2p-circuit address "'.concat(e,'"'));t.log("listen on specific relay server %a",e);var r=AbortSignal.timeout(t.listenTimeout),n=e.decapsulate("/p2p-circuit"),i=yield t.connectionManager.openConnection(n,{signal:r});if(!t.reservationStore.hasReservation(i.remotePeer)){t.log("making reservation on peer %p",i.remotePeer);var o=yield t.reservationStore.addRelay(i.remotePeer,"configured");t.addedRelay(o)}}}))()}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}close(){var e=this;return r((function*(){e.reservationStore.cancelReservations(),e.listeningAddrs=[],e.reservationStore.removeEventListener("relay:removed",e._onRemoveRelayPeer),queueMicrotask((()=>{e.safeDispatchEvent("close")}))}))()}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map((e=>kr(e).encapsulate("/p2p-circuit"))),this.listeningAddrs.forEach((e=>{this.addressManager.confirmObservedAddr(e,{type:"transport"})})),queueMicrotask((()=>{this.safeDispatchEvent("listening")}))}}var bv=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},Sv=new WeakSet;class Ev extends os{constructor(t,r){var n,i,o;super(),d(this,Sv),e(this,"peerId",void 0),e(this,"connectionManager",void 0),e(this,"peerStore",void 0),e(this,"events",void 0),e(this,"reserveQueue",void 0),e(this,"reservations",void 0),e(this,"pendingReservations",void 0),e(this,"maxReservationQueueLength",void 0),e(this,"reservationCompletionTimeout",void 0),e(this,"started",void 0),e(this,"log",void 0),e(this,"relayFilter",void 0),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=t.peerId,this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.reservations=new Fh,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=$h(100),this.reserveQueue=new gv({concurrency:null!==(o=null==r?void 0:r.reservationConcurrency)&&void 0!==o?o:1,metricName:"libp2p_relay_reservation_queue",metrics:t.metrics}),this.events.addEventListener("connection:close",(e=>{null!=[...this.reservations.values()].find((t=>t.connection===e.detail.id))&&h(Sv,this,Av).call(this,e.detail.remotePeer).catch((t=>{this.log("could not remove relay %p - %e",e.detail,t)}))}))}isStarted(){return this.started}start(){this.started=!0}afterStart(){var e=this;Promise.resolve().then(r((function*(){var t=yield e.peerStore.all({filters:[e=>e.tags.has(Ad)]});e.log("removing tag from %d old relays",t.length),yield Promise.all(t.map(function(){var t=r((function*(t){yield e.peerStore.merge(t.id,{tags:{[Ad]:void 0}})}));return function(e){return t.apply(this,arguments)}}())),e.log("redialing %d old relays",t.length),yield Promise.all(t.map(function(){var t=r((function*(t){return e.addRelay(t.id,"discovered")}));return function(e){return t.apply(this,arguments)}}())),h(Sv,e,Iv).call(e)}))).catch((e=>{this.log.error(e)}))}stop(){this.reserveQueue.clear(),this.reservations.forEach((e=>{var{timeout:t}=e;clearTimeout(t)})),this.reservations.clear(),this.started=!1}reserveRelay(){var e=bv();return this.pendingReservations.push(e),h(Sv,this,Iv).call(this),e}addRelay(e,t){var n=this;return r((function*(){if(n.peerId.equals(e))throw n.log.trace("not trying to use self as relay"),new $a("Cannot use self as relay");if(n.reserveQueue.size>n.maxReservationQueueLength)throw new Nh("The reservation queue is full");var i=n.reserveQueue.find(e);if(null!=i)return n.log.trace("potential relay peer %p is already in the reservation queue",e),i.join();if(n.relayFilter.has(e.toMultihash().bytes))throw new $a("The relay was previously invalid");return n.log.trace("try to reserve relay slot with %p",e),n.reserveQueue.add(r((function*(){var i=Date.now();try{var o=n.reservations.get(e);if(null!=o){var a=n.connectionManager.getConnections(e),s=!1;if(0===a.length&&n.log("already have relay reservation with %p but we are no longer connected",e),a.map((e=>e.id)).includes(o.connection)&&(n.log("already have relay reservation with %p and the original connection is still open",e),s=!0),s&&Dh(o.reservation.expire)>6e5)return n.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:o};yield h(Sv,n,Av).call(n,e)}if("discovered"===t&&0===n.pendingReservations.length)throw new _h("Not making reservation on discovered relay because we do not need any more relays");var l=AbortSignal.timeout(n.reservationCompletionTimeout),u=yield n.connectionManager.openConnection(e,{signal:l});if(Ah.matches(u.remoteAddr))throw new Bh("not creating reservation over relayed connection");var c=yield h(Sv,n,kv).call(n,u,{signal:l}),d=Dh(c.expire);n.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+d).toString());var v,p=Math.min(Math.max(d-3e5,3e4),Math.pow(2,31)-1),f=setTimeout((()=>{n.log("refresh reservation to relay %p",e),n.addRelay(e,t).catch(function(){var t=r((function*(t){n.log.error("could not refresh reservation to relay %p - %e",e,t),yield h(Sv,n,Av).call(n,e)}));return function(e){return t.apply(this,arguments)}}()).catch((t=>{n.log.error("could not remove expired reservation to relay %p - %e",e,t)}))}),p);if("discovered"===t){var g=n.pendingReservations.pop();if(null==g)throw new _h("Made reservation on relay but did not need any more discovered relays");v={timeout:f,reservation:c,type:t,connection:u.id,id:g}}else v={timeout:f,reservation:c,type:t,connection:u.id};n.reservations.set(e,v),yield n.peerStore.merge(e,{tags:{[Ad]:{value:1,ttl:d}}}),h(Sv,n,Iv).call(n);var y={relay:e,details:v};return n.safeDispatchEvent("relay:created-reservation",{detail:y}),y}catch(r){throw"discovered"===t&&"HadEnoughRelaysError"===r.name||n.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-i,r),"DialError"!==r.name&&"UnsupportedProtocolError"!==r.name||n.relayFilter.add(e.toMultihash().bytes),h(Sv,n,Av).call(n,e).catch((t=>{n.log.error("could not remove reservation on %p after reserving slot failed - %e",e,t)})),r}})),{peerId:e})}))()}hasReservation(e){return this.reservations.has(e)}getReservation(e){var t;return null===(t=this.reservations.get(e))||void 0===t?void 0:t.reservation}reservationCount(e){return null==e?this.reservations.size:[...this.reservations.values()].reduce(((t,r)=>(r.type===e&&t++,t)),0)}cancelReservations(){[...this.reservations.values()].forEach((e=>{clearTimeout(e.timeout)})),this.reservations.clear()}}function kv(e,t){return xv.apply(this,arguments)}function xv(){return xv=r((function*(e,t){var r,n;null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);var i,o=yield e.newStream(Od,t),a=xd(o).pb(Cd);this.log.trace("send RESERVE to %p",e.remotePeer),yield a.write({type:Cd.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===Bd.OK&&null!=i.reservation){var s=new Set;for(var l of(s.add(e.remoteAddr.toString()),i.reservation.addrs)){var u=kr(l);null==u.getPeerId()&&(u=u.encapsulate("/p2p/".concat(e.remotePeer))),u=kr(u.toString().replace("/p2p/".concat(e.remotePeer,"/p2p/").concat(e.remotePeer),"/p2p/".concat(e.remotePeer))),s.add(u.toString())}return i.reservation.addrs=[...s].map((e=>kr(e).bytes)),i.reservation}var c="reservation failed with status ".concat(null!==(n=i.status)&&void 0!==n?n:"undefined");throw this.log.error(c),new Error(c)})),xv.apply(this,arguments)}function Av(e){return Cv.apply(this,arguments)}function Cv(){return Cv=r((function*(e){var t=this.reservations.get(e);null!=t&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),"discovered"===t.type&&this.pendingReservations.push(t.id),yield this.peerStore.merge(e,{tags:{[Ad]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),h(Sv,this,Iv).call(this))})),Cv.apply(this,arguments)}function Iv(){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=$h(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}var Tv,Pv=300,_v=300;class Bv{constructor(t){var r,n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"discovery",void 0),e(this,"registrar",void 0),e(this,"peerStore",void 0),e(this,"connectionManager",void 0),e(this,"transportManager",void 0),e(this,"peerId",void 0),e(this,"upgrader",void 0),e(this,"addressManager",void 0),e(this,"connectionGater",void 0),e(this,"reservationStore",void 0),e(this,"logger",void 0),e(this,"maxInboundStopStreams",void 0),e(this,"maxOutboundStopStreams",void 0),e(this,"started",void 0),e(this,"log",void 0),e(this,"shutdownController",void 0),e(this,Symbol.toStringTag,"@libp2p/circuit-relay-v2-transport"),e(this,ds,["@libp2p/transport","@libp2p/circuit-relay-v2-transport"]),e(this,Ca,!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:Pv,this.maxOutboundStopStreams=null!==(n=o.maxOutboundStopStreams)&&void 0!==n?n:_v,this.shutdownController=new AbortController,this.discovery=new yv(t,{filter:null!==(i=o.discoveryFilter)&&void 0!==i?i:ev(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 Ev(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[hs](){return null!=this.discovery?["@libp2p/identify"]:[]}isStarted(){return this.started}start(){var e=this;return r((function*(){e.shutdownController=new AbortController,e.shutdownController.signal,yield e.registrar.handle(Ld,(t=>{var r=e.upgrader.createInboundAbortSignal(e.shutdownController.signal);e.onStop(t,r).catch((r=>{e.log.error("error while handling STOP protocol",r),t.stream.abort(r)})).finally((()=>{r.clear()}))}),{maxInboundStreams:e.maxInboundStopStreams,maxOutboundStreams:e.maxOutboundStopStreams,runOnLimitedConnection:!0}),yield ss(e.discovery,e.reservationStore),e.started=!0}))()}stop(){var e=this;return r((function*(){e.shutdownController.abort(),yield us(e.discovery,e.reservationStore),yield e.registrar.unhandle(Ld),e.started=!1}))()}dial(e,n){var i=this;return r((function*(){if(1!==e.protoCodes().filter((e=>290===e)).length){var r="Invalid circuit relay address";throw i.log.error(r,e),new Za(r)}var o=e.toString().split("/p2p-circuit"),a=kr(o[0]),s=kr(o[o.length-1]),l=a.getPeerId(),u=s.getPeerId();if(null==l||null==u){var c="ircuit relay dial to ".concat(e.toString()," failed as address did not have both relay and destination PeerIDs");throw i.log.error("c".concat(c)),new Za("C".concat(c))}var d,h,v,p=Du(l),f=Du(u),g=i.connectionManager.getConnections(p)[0];null==g?(yield i.peerStore.merge(p,{multiaddrs:[a]}),null===(d=n.onProgress)||void 0===d||d.call(n,new av("circuit-relay:open-connection")),g=yield i.connectionManager.openConnection(p,n)):null===(h=n.onProgress)||void 0===h||h.call(n,new av("circuit-relay:reuse-connection"));try{var y,m,w;null===(y=n.onProgress)||void 0===y||y.call(n,new av("circuit-relay:open-hop-stream"));var b=xd(v=yield g.newStream(Od,n)),S=b.pb(Cd);null===(m=n.onProgress)||void 0===m||m.call(n,new av("circuit-relay:write-connect-message")),yield S.write({type:Cd.Type.CONNECT,peer:{id:f.toMultihash().bytes,addrs:[kr(s).bytes]}},n),null===(w=n.onProgress)||void 0===w||w.call(n,new av("circuit-relay:read-connect-response"));var E,k,x=yield S.read(n);if(x.status!==Bd.OK)throw new Wa("failed to connect via relay with status ".concat(null!==(E=null==x||null===(k=x.status)||void 0===k?void 0:k.toString())&&void 0!==E?E:"undefined"));var A=new Rh(x.limit),C=ov({stream:b.unwrap(),remoteAddr:e,localAddr:a.encapsulate("/p2p-circuit/p2p/".concat(i.peerId.toString())),logger:i.logger,onDataRead:A.onData,onDataWrite:A.onData});return i.log("new outbound relayed connection %a",C.remoteAddr),yield i.upgrader.upgradeOutbound(C,t(t({},n),{},{limits:A.getLimits()}))}catch(e){var I;throw i.log.error("circuit relay dial to destination %p via relay %p failed",f,p,e),null===(I=v)||void 0===I||I.abort(e),e}}))()}createListener(e){return function(e){return new wv(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=>Oh.exactMatch(e)||Lh.exactMatch(e)))}dialFilter(e){return(e=Array.isArray(e)?e:[e]).filter((e=>Ah.exactMatch(e)))}onStop(e,t){var n=this;return r((function*(){var r,i,{connection:o,stream:a}=e;if(!n.reservationStore.hasReservation(o.remotePeer))try{n.log("dialed via relay we did not have a reservation on, start listening on that relay address"),yield n.transportManager.listen([o.remoteAddr.encapsulate("/p2p-circuit")])}catch(e){n.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on",e)}var s=xd(a).pb(Id),l=yield s.read({signal:t});if(n.log("new circuit relay v2 stop stream from %p with type %s",o.remotePeer,l.type),void 0===(null==l?void 0:l.type))return n.log.error("type was missing from circuit v2 stop protocol request from %s",o.remotePeer),yield s.write({type:Id.Type.STATUS,status:Bd.MALFORMED_MESSAGE},{signal:t}),void(yield a.close());if(l.type!==Id.Type.CONNECT)return n.log.error("invalid stop connect request via peer %p",o.remotePeer),yield s.write({type:Id.Type.STATUS,status:Bd.UNEXPECTED_MESSAGE},{signal:t}),void(yield a.close());if(!(e=>{if(null==e.peer)return!1;try{e.peer.addrs.forEach(kr)}catch(e){return!1}return!0})(l))return n.log.error("invalid stop connect request via peer %p",o.remotePeer),yield s.write({type:Id.Type.STATUS,status:Bd.MALFORMED_MESSAGE},{signal:t}),void(yield a.close({signal:t}));var u=Lu(He(l.peer.id));if(!0===(yield null===(r=(i=n.connectionGater).denyInboundRelayedConnection)||void 0===r?void 0:r.call(i,o.remotePeer,u)))return n.log.error("connection gater denied inbound relayed connection from %p",o.remotePeer),yield s.write({type:Id.Type.STATUS,status:Bd.PERMISSION_DENIED},{signal:t}),void(yield a.close({signal:t}));n.log.trace("sending success response to %p",o.remotePeer),yield s.write({type:Id.Type.STATUS,status:Bd.OK},{signal:t});var c=new Rh(l.limit),d=o.remoteAddr.encapsulate("/p2p-circuit/p2p/".concat(u.toString()));n.addressManager.getAddresses()[0];var h=ov({stream:s.unwrap().unwrap(),remoteAddr:d,logger:n.logger,onDataRead:c.onData,onDataWrite:c.onData});n.log("new inbound relayed connection %a",h.remoteAddr),yield n.upgrader.upgradeInbound(h,{limits:c.getLimits(),signal:t}),n.log("%s connection %a upgraded","inbound",h.remoteAddr)}))()}}function Nv(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new Bv(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=()=>ql(t)}(e.Flag||(e.Flag={})),e.codec=()=>(null==r&&(r=Hl((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=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(Tv||(Tv={}));var Dv=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],Rv=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Ov=16384;var Lv=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Ov,t=Nt(e-Nt(e)),r=1+Nt(Object.keys(Tv.Flag).length-1);return t+r+1+Nt(e-t-r-1)}(),Mv="/webrtc",Uv="/webrtc-signaling/0.0.1",Fv=864e5,zv=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))},jv=function(e,t,r){this.name=e,this.version=t,this.os=r,this.type="browser"},Vv=function(e){this.version=e,this.type="node",this.name="node",this.os=v.platform},qv=function(e,t,r,n){this.name=e,this.version=t,this.os=r,this.bot=n,this.type="bot-device"},Hv=function(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null},Kv=function(){this.type="react-native",this.name="react-native",this.version=null,this.os=null},Wv=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Gv=[["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/]],Qv=[["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 Yv extends Error{constructor(e){super(e),this.name="TimeoutError"}}let Jv=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}};var Zv=e=>void 0===globalThis.DOMException?new Jv(e):new DOMException(e),$v=e=>{var t=void 0===e.reason?Zv("This operation was aborted."):e.reason;return t instanceof Error?t:Zv(t)};function Xv(e,t){var n,i,{milliseconds:o,fallback:a,message:s,customTimers:l={setTimeout:setTimeout,clearTimeout:clearTimeout}}=t,u=new Promise(((u,c)=>{if("number"!=typeof o||1!==Math.sign(o))throw new TypeError("Expected `milliseconds` to be a positive number, got `".concat(o,"`"));if(t.signal){var{signal:d}=t;d.aborted&&c($v(d)),i=()=>{c($v(d))},d.addEventListener("abort",i,{once:!0})}if(o!==Number.POSITIVE_INFINITY){var h=new Yv;n=l.setTimeout.call(void 0,(()=>{if(a)try{u(a())}catch(e){c(e)}else"function"==typeof e.cancel&&e.cancel(),!1===s?u():s instanceof Error?c(s):(h.message=null!=s?s:"Promise timed out after ".concat(o," milliseconds"),c(h))}),o),r((function*(){try{u(yield e)}catch(e){c(e)}}))()}else e.then(u,c)})),c=u.finally((()=>{c.clear(),i&&t.signal&&t.signal.removeEventListener("abort",i)}));return c.clear=()=>{l.clearTimeout.call(void 0,n),n=void 0},c}var ep="undefined"==typeof document&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product?new Kv:"undefined"!=typeof navigator?function(e){var t=function(e){return""!==e&&Gv.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 Hv;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length<3&&(i=zv(zv([],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=Qv.length;t<r;t++){var n=Qv[t],i=n[0];if(n[1].exec(e))return i}return null}(e),s=Wv.exec(e);return s&&s[1]?new qv(r,o,a,s[1]):new jv(r,o,a)}(navigator.userAgent):void 0!==v&&v.version?new Vv(v.version.slice(1)):null,tp=null!=ep&&"firefox"===ep.name,rp=function(){var e=l((function*(){}));return function(){return e.apply(this,arguments)}}(),np=function(){var e=r((function*(e){}));return function(t){return e.apply(this,arguments)}}();function ip(e){return op.apply(this,arguments)}function op(){return(op=r((function*(e){var t;return"function"==typeof(e=null!=e?e:{})&&(e=yield e()),e.iceServers=null!==(t=e.iceServers)&&void 0!==t?t:Dv.map((e=>({urls:[e]}))),e}))).apply(this,arguments)}class ap{constructor(t,r){e(this,"log",void 0),e(this,"peerConnection",void 0),e(this,"remoteAddr",void 0),e(this,"timeline",void 0),e(this,"metrics",void 0),e(this,"source",rp()),e(this,"sink",np),this.log=t.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=r.remoteAddr,this.timeline=r.timeline,this.peerConnection=r.peerConnection;var n=this.peerConnection,i=n.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",n.connectionState,"initial state",i),"disconnected"!==n.connectionState&&"failed"!==n.connectionState&&"closed"!==n.connectionState||(this.timeline.close=Date.now())}}close(e){var t=this;return r((function*(){var e;t.log.trace("closing connection"),t.peerConnection.close(),t.timeline.close=Date.now(),null===(e=t.metrics)||void 0===e||e.increment({close:!0})}))()}abort(e){var t;this.log.error("closing connection due to error",e),this.peerConnection.close(),this.timeline.close=Date.now(),null===(t=this.metrics)||void 0===t||t.increment({abort:!0})}}function sp(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 lp(e,t){var r,n,i,o=null===(r=(n=sp(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 up(e){return null!=e&&("function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally)}class cp{constructor(t){var r,n;e(this,"id",void 0),e(this,"direction",void 0),e(this,"timeline",void 0),e(this,"protocol",void 0),e(this,"metadata",void 0),e(this,"source",void 0),e(this,"status",void 0),e(this,"readStatus",void 0),e(this,"writeStatus",void 0),e(this,"log",void 0),e(this,"sinkController",void 0),e(this,"sinkEnd",void 0),e(this,"closed",void 0),e(this,"endErr",void 0),e(this,"streamSource",void 0),e(this,"onEnd",void 0),e(this,"onCloseRead",void 0),e(this,"onCloseWrite",void 0),e(this,"onReset",void 0),e(this,"onAbort",void 0),e(this,"sendCloseWriteTimeout",void 0),e(this,"sendingData",void 0),this.sinkController=new AbortController,this.sinkEnd=Cc(),this.closed=Cc(),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=_c({onEnd:e=>{null!=e?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}sink(e){var t=this;return r((function*(){if("ready"!==t.writeStatus)throw new Fa('writable end state is "'.concat(t.writeStatus,'" not "ready"'));try{t.writeStatus="writing";var r={signal:t.sinkController.signal};if("outbound"===t.direction){var n=t.sendNewStream(r);up(n)&&(yield n)}var i=()=>{lp(e,t.log)};try{t.sinkController.signal.addEventListener("abort",i),t.log.trace("sink reading from source");var o,a=!1,l=!1;try{for(var u,c=s(e);a=!(u=yield c.next()).done;a=!1){var d=u.value;d=d instanceof Uint8Array?new gs(d):d;var h=t.sendData(d,r);up(h)&&(t.sendingData=Cc(),yield h,t.sendingData.resolve(),t.sendingData=void 0)}}catch(e){l=!0,o=e}finally{try{a&&null!=c.return&&(yield c.return())}finally{if(l)throw o}}}finally{t.sinkController.signal.removeEventListener("abort",i)}t.log.trace('sink finished reading from source, write status is "%s"',t.writeStatus),"writing"===t.writeStatus&&(t.writeStatus="closing",t.log.trace("send close write to remote"),yield t.sendCloseWrite({signal:AbortSignal.timeout(t.sendCloseWriteTimeout)}),t.writeStatus="closed"),t.onSinkEnd()}catch(e){throw t.log.trace("sink ended with error, calling abort with error",e),t.abort(e),e}finally{t.log.trace("resolve sink end"),t.sinkEnd.resolve()}}))()}onSourceEnd(e){var t;null==this.timeline.closeRead&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),null===(t=this.onCloseRead)||void 0===t||t.call(this),null!=this.timeline.closeWrite?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){var t;null==this.timeline.closeWrite&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),null===(t=this.onCloseWrite)||void 0===t||t.call(this),null!=this.timeline.closeRead?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}close(e){var t=this;return r((function*(){"open"===t.status&&(t.log.trace("closing gracefully"),t.status="closing",yield Nc(Promise.all([t.closeWrite(e),t.closeRead(e),t.closed.promise]),null==e?void 0:e.signal),t.status="closed",t.log.trace("closed gracefully"))}))()}closeRead(){var e=arguments,t=this;return r((function*(){var r=e.length>0&&void 0!==e[0]?e[0]:{};if("closing"!==t.readStatus&&"closed"!==t.readStatus){t.log.trace('closing readable end of stream with starting read status "%s"',t.readStatus);var n=t.readStatus;t.readStatus="closing","reset"!==t.status&&"aborted"!==t.status&&null==t.timeline.closeRead&&(t.log.trace("send close read to remote"),yield t.sendCloseRead(r)),"ready"===n&&(t.log.trace("ending internal source queue with %d queued bytes",t.streamSource.readableLength),t.streamSource.end()),t.log.trace("closed readable end of stream")}}))()}closeWrite(){var e=arguments,t=this;return r((function*(){var r=e.length>0&&void 0!==e[0]?e[0]:{};"closing"!==t.writeStatus&&"closed"!==t.writeStatus&&(t.log.trace('closing writable end of stream with starting write status "%s"',t.writeStatus),"ready"===t.writeStatus&&(t.log.trace("sink was never sunk, sink an empty array"),yield Nc(t.sink([]),r.signal)),"writing"===t.writeStatus&&(null!=t.sendingData&&(yield Nc(t.sendingData.promise,r.signal)),t.log.trace("aborting source passed to .sink"),t.sinkController.abort(),yield Nc(t.sinkEnd.promise,r.signal)),t.writeStatus="closed",t.log.trace("closed writable end of stream"))}))()}abort(e){var t;if("closed"!==this.status&&"aborted"!==this.status&&"reset"!==this.status){this.log("abort with error",e),this.log("try to send reset to remote");var r=this.sendReset();up(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 Ua("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 dp=4194304;let hp=class extends Error{constructor(){super(...arguments),e(this,"name","InvalidMessageLengthError"),e(this,"code","ERR_INVALID_MSG_LENGTH")}},vp=class extends Error{constructor(){super(...arguments),e(this,"name","InvalidDataLengthError"),e(this,"code","ERR_MSG_DATA_TOO_LONG")}},pp=class extends Error{constructor(){super(...arguments),e(this,"name","InvalidDataLengthLengthError"),e(this,"code","ERR_MSG_LENGTH_TOO_LONG")}},fp=class extends Error{constructor(){super(...arguments),e(this,"name","UnexpectedEOFError"),e(this,"code","ERR_UNEXPECTED_EOF")}};function gp(e){return null!=e[Symbol.asyncIterator]}function yp(e,t){if(e.byteLength>t)throw new vp("Message length too long")}var mp,wp=e=>{var t=Nt(e),r=dt(t);return Ot(e,r),wp.bytes=t,r};function bp(e,t){var r,n,i,o=null!==(r=(t=null!=t?t:{}).lengthEncoder)&&void 0!==r?r:wp,a=null!==(n=null===(i=t)||void 0===i?void 0:i.maxDataLength)&&void 0!==n?n:dp;function*d(e){yp(e,a);var t=o(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return gp(e)?l((function*(){var t,r=!1,n=!1;try{for(var i,o=s(e);r=!(i=yield u(o.next())).done;r=!1){var a=i.value;yield*c(s(d(a)),u)}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw t}}}))():function*(){for(var t of e)yield*d(t)}()}wp.bytes=0,bp.single=(e,t)=>{var r,n,i,o=null!==(r=(t=null!=t?t:{}).lengthEncoder)&&void 0!==r?r:wp;return yp(e,null!==(n=null===(i=t)||void 0===i?void 0:i.maxDataLength)&&void 0!==n?n:dp),new gs(o(e.byteLength),e)},function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(mp||(mp={}));var Sp=e=>{var t=Lt(e);return Sp.bytes=Nt(t),t};function Ep(e,t){var r,n,i,o=new gs,a=mp.LENGTH,d=-1,h=null!==(r=null==t?void 0:t.lengthDecoder)&&void 0!==r?r:Sp,v=null!==(n=null==t?void 0:t.maxLengthLength)&&void 0!==n?n:8,p=null!==(i=null==t?void 0:t.maxDataLength)&&void 0!==i?i:dp;function*f(){for(;o.byteLength>0;){if(a===mp.LENGTH)try{if((d=h(o))<0)throw new hp("Invalid message length");if(d>p)throw new vp("Message length too long");var e=h.bytes;o.consume(e),null!=(null==t?void 0:t.onLength)&&t.onLength(d),a=mp.DATA}catch(e){if(e instanceof RangeError){if(o.byteLength>v)throw new pp("Message length length too long");break}throw e}if(a===mp.DATA){if(o.byteLength<d)break;var r=o.sublist(0,d);o.consume(d),null!=(null==t?void 0:t.onData)&&t.onData(r),yield r,a=mp.LENGTH}}}return gp(e)?l((function*(){var t,r=!1,n=!1;try{for(var i,a=s(e);r=!(i=yield u(a.next())).done;r=!1){var l=i.value;o.append(l),yield*c(s(f()),u)}}catch(e){n=!0,t=e}finally{try{r&&null!=a.return&&(yield u(a.return()))}finally{if(n)throw t}}if(o.byteLength>0)throw new fp("Unexpected end of input")}))():function*(){for(var t of e)o.append(t),yield*f();if(o.byteLength>0)throw new fp("Unexpected end of input")}()}Sp.bytes=0,Ep.fromReader=(e,r)=>{var n=1;return Ep(l((function*(){for(;;)try{var{done:t,value:r}=yield u(e.next(n));if(!0===t)return;null!=r&&(yield r)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{n=1}}))(),t(t({},null!=r?r:{}),{},{onLength:e=>{n=e}}))};class kp extends cp{constructor(t){var n,i,o,a,l,u,c=t.onEnd;switch(t.onEnd=e=>{this.log.trace('readable and writeable ends closed with status "%s"',this.status),Promise.resolve(r((function*(){if(null==n.timeline.abort&&null===n.timeline.reset)try{yield Xv(n.receiveFinAck.promise,{milliseconds:n.finAckTimeout})}catch(e){n.log.error("error receiving FIN_ACK",e)}}))).then((()=>{this.incomingData.end(),null==c||c(e)})).catch((e=>{this.log.error("error ending stream",e)})).finally((()=>{this.channel.close()}))},super(t),n=this,e(this,"channel",void 0),e(this,"incomingData",void 0),e(this,"maxBufferedAmount",void 0),e(this,"bufferedAmountLowEventTimeout",void 0),e(this,"maxMessageSize",void 0),e(this,"receiveFinAck",void 0),e(this,"finAckTimeout",void 0),e(this,"openTimeout",void 0),e(this,"closeController",void 0),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=_c(),this.bufferedAmountLowEventTimeout=null!==(i=t.bufferedAmountLowEventTimeout)&&void 0!==i?i:3e4,this.maxBufferedAmount=null!==(o=t.maxBufferedAmount)&&void 0!==o?o:2097152,this.maxMessageSize=(null!==(a=t.maxMessageSize)&&void 0!==a?a:Ov)-Lv,this.receiveFinAck=Cc(),this.finAckTimeout=null!==(l=t.closeTimeout)&&void 0!==l?l:5e3,this.openTimeout=null!==(u=t.openTimeout)&&void 0!==u?u:5e3,this.closeController=new AbortController,this.channel.readyState){case"open":this.timeline.open=(new Date).getTime();break;case"closed":case"closing":void 0!==this.timeline.close&&0!==this.timeline.close||(this.timeline.close=Date.now());break;case"connecting":break;default:throw this.log.error("unknown datachannel state %s",this.channel.readyState),new Fa("Unknown datachannel state")}this.channel.onopen=e=>{this.timeline.open=(new Date).getTime()},this.channel.onclose=e=>{this.log.trace("received onclose event"),this.closeController.abort(),this.receiveFinAck.resolve(),this.close().catch((e=>{this.log.error("error closing stream after channel closed",e)}))},this.channel.onerror=e=>{this.log.trace("received onerror event"),this.closeController.abort();var t=e.error;this.abort(t)},this.channel.onmessage=function(){var e=r((function*(e){var{data:t}=e;null!==t&&0!==t.byteLength&&n.incomingData.push(new Uint8Array(t,0,t.byteLength))}));return function(t){return e.apply(this,arguments)}}();var d=this;Promise.resolve().then(r((function*(){var e,t=!1,r=!1;try{for(var i,o=s(Ep(n.incomingData));t=!(i=yield o.next()).done;t=!1){var a=i.value,l=d.processIncomingProtobuf(a);null!=l&&d.sourcePush(new gs(l))}}catch(t){r=!0,e=t}finally{try{t&&null!=o.return&&(yield o.return())}finally{if(r)throw e}}}))).catch((e=>{this.log.error("error processing incoming data channel messages",e)}))}sendNewStream(){}_sendMessage(e){var t=arguments,n=this;return r((function*(){var r=!(t.length>1&&void 0!==t[1])||t[1];if("closed"===n.channel.readyState||"closing"===n.channel.readyState)throw new Fa("Invalid datachannel state - ".concat(n.channel.readyState));if("open"!==n.channel.readyState){var i=AbortSignal.timeout(n.openTimeout),o=Ph([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 lv(n.channel,"open",o)}finally{o.clear()}n.log('channel state is now "%s", sending data',n.channel.readyState)}if(r&&n.channel.bufferedAmount>n.maxBufferedAmount){var a=AbortSignal.timeout(n.bufferedAmountLowEventTimeout),s=Ph([n.closeController.signal,a]);try{n.log('channel buffer is %d, wait for "bufferedamountlow" event',n.channel.bufferedAmount),yield lv(n.channel,"bufferedamountlow",s)}catch(e){if(a.aborted)throw new Qa("Timed out waiting for DataChannel buffer to clear after ".concat(n.bufferedAmountLowEventTimeout,"ms"));throw e}finally{s.clear()}}try{n.log.trace('sending message, channel state "%s"',n.channel.readyState),n.channel.send(e.subarray())}catch(e){n.log.error("error while sending message",e)}}))()}sendData(e){var t=this;return r((function*(){var r=e.byteLength;for(e=e.sublist();e.byteLength>0;){var n=Math.min(e.byteLength,t.maxMessageSize),i=e.subarray(0,n),o=Tv.encode({message:i}),a=bp.single(o);t.log.trace("sending %d/%d bytes on channel",i.byteLength,r),yield t._sendMessage(a),e.consume(n)}t.log.trace('finished sending data, channel state "%s"',t.channel.readyState)}))()}sendReset(){var e=this;return r((function*(){try{yield e._sendFlag(Tv.Flag.RESET)}catch(t){e.log.error("failed to send reset - %e",t)}finally{e.channel.close()}}))()}sendCloseWrite(e){var t=this;return r((function*(){if("open"===t.channel.readyState){if(yield t._sendFlag(Tv.Flag.FIN)){t.log.trace("awaiting FIN_ACK");try{yield Nc(t.receiveFinAck.promise,null==e?void 0:e.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorName:"FinAckNotReceivedError"})}catch(e){t.log.error("failed to await FIN_ACK",e)}}else t.log.trace("sending FIN failed, not awaiting FIN_ACK");t.receiveFinAck.resolve()}else t.receiveFinAck.resolve()}))()}sendCloseRead(){var e=this;return r((function*(){"open"===e.channel.readyState&&(yield e._sendFlag(Tv.Flag.STOP_SENDING))}))()}processIncomingProtobuf(e){var t=Tv.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===Tv.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Tv.Flag.FIN_ACK).catch((e=>{this.log.error("error sending FIN_ACK immediately",e)}))),t.flag===Tv.Flag.RESET&&this.reset(),t.flag===Tv.Flag.STOP_SENDING&&this.remoteCloseRead(),t.flag===Tv.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),"ready"===this.readStatus)return t.message}_sendFlag(e){var t=this;return r((function*(){if("open"!==t.channel.readyState)return t.log.trace('not sending flag %s because channel is "%s" and not "open"',e.toString(),t.channel.readyState),!1;t.log.trace("sending flag %s",e.toString());var r=Tv.encode({flag:e}),n=bp.single(r);try{return yield t._sendMessage(n,!1),!0}catch(r){t.log.error("could not send flag %s - %e",e.toString(),r)}return!1}))()}}function xp(e){var{channel:r,direction:n,handshake:i}=e;return new kp(t({id:"".concat(r.id),log:e.logger.forComponent("libp2p:webrtc:stream:".concat(!0===i?"handshake":n,":").concat(r.id))},e))}class Ap{constructor(r,n){var i,o;e(this,"protocol",void 0),e(this,"peerConnection",void 0),e(this,"bufferedStreams",[]),e(this,"metrics",void 0),e(this,"dataChannelOptions",void 0),e(this,"components",void 0),e(this,"log",void 0),this.components=r,this.peerConnection=n.peerConnection,this.metrics=n.metrics,this.protocol=null!==(i=n.protocol)&&void 0!==i?i:Mv,this.dataChannelOptions=null!==(o=n.dataChannelOptions)&&void 0!==o?o:{},this.log=r.logger.forComponent("libp2p:webrtc:muxerfactory"),this.peerConnection.ondatachannel=e=>{var{channel:n}=e;if(this.log.trace('incoming early datachannel with channel id %d and label "%s"',n.id),"init"===n.label)return this.log.trace("closing early init channel"),void n.close();var i={},o=xp(t({channel:n,direction:"inbound",onEnd:e=>{i.onEnd(e)},logger:r.logger},this.dataChannelOptions));i.stream=o,i.channel=n,i.onEnd=()=>{this.bufferedStreams=this.bufferedStreams.filter((e=>e.stream.id!==o.id))},this.bufferedStreams.push(i)}}createStreamMuxer(e){return new Ip(this.components,t(t({},e),{},{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol}))}}var Cp=new WeakSet;class Ip{constructor(r,n){var i,o;d(this,Cp),e(this,"init",void 0),e(this,"streams",void 0),e(this,"protocol",void 0),e(this,"log",void 0),e(this,"peerConnection",void 0),e(this,"dataChannelOptions",void 0),e(this,"metrics",void 0),e(this,"logger",void 0),e(this,"source",rp()),e(this,"sink",np),this.init=n,this.log=r.logger.forComponent("libp2p:webrtc:muxer"),this.logger=r.logger,this.streams=n.streams.map((e=>e.stream)),this.peerConnection=n.peerConnection,this.protocol=null!==(i=n.protocol)&&void 0!==i?i:Mv,this.metrics=n.metrics,this.dataChannelOptions=null!==(o=n.dataChannelOptions)&&void 0!==o?o:{},this.peerConnection.ondatachannel=e=>{var r,i,{channel:o}=e;if(this.log.trace("incoming datachannel with channel id %d",o.id),"init"===o.label)return this.log.trace("closing init channel"),void o.close();var a=o.id,s=xp(t({channel:o,direction:"inbound",onEnd:()=>{h(Cp,this,Tp).call(this,s,o),this.log("incoming channel %s ended",a)},logger:this.logger},this.dataChannelOptions));this.streams.push(s),null===(r=this.metrics)||void 0===r||r.increment({incoming_stream:!0}),null==n||null===(i=n.onIncomingStream)||void 0===i||i.call(n,s)},this.init.streams.length>0&&queueMicrotask((()=>{this.init.streams.forEach((e=>{var t,r,n;e.onEnd=()=>{this.log("incoming early channel %s ended with state %s",e.channel.id,e.channel.readyState),h(Cp,this,Tp).call(this,e.stream,e.channel)},null===(t=this.metrics)||void 0===t||t.increment({incoming_stream:!0}),null===(r=this.init)||void 0===r||null===(n=r.onIncomingStream)||void 0===n||n.call(r,e.stream)}))}))}close(e){var t=this;return r((function*(){try{yield Promise.all(t.streams.map(function(){var t=r((function*(t){return t.close(e)}));return function(e){return t.apply(this,arguments)}}()))}catch(e){t.abort(e)}}))()}abort(e){for(var t of this.streams)t.abort(e)}newStream(){var e,r=this.peerConnection.createDataChannel(""),n=r.id;this.log.trace("opened outgoing datachannel with channel id %s",n);var i=xp(t({channel:r,direction:"outbound",onEnd:()=>{h(Cp,this,Tp).call(this,i,r),this.log("outgoing channel %s ended",n)},logger:this.logger},this.dataChannelOptions));return this.streams.push(i),null===(e=this.metrics)||void 0===e||e.increment({outgoing_stream:!0}),i}}function Tp(e,t){var n,i,o;this.log.trace("stream %s %s %s onEnd",e.direction,e.id,e.protocol),function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3e4,i=arguments.length>3?arguments[3]:void 0;"open"===e.readyState&&Promise.resolve().then(r((function*(){if(e.bufferedAmount>0){i.log("%s drain channel with %d buffered bytes",t,e.bufferedAmount);var r=Cc(),o=!1;e.bufferedAmountLowThreshold=0;var a=()=>{o||(i.log("%s drain channel closed before drain",t),r.resolve())};e.addEventListener("close",a,{once:!0}),e.addEventListener("bufferedamountlow",(()=>{o=!0,e.removeEventListener("close",a),r.resolve()})),yield Xv(r.promise,{milliseconds:n})}}))).then(r((function*(){"open"===e.readyState&&e.close()}))).catch((e=>{i.log.error("error closing outbound stream",e)}))}(t,"".concat(e.direction," ").concat(e.id," ").concat(e.protocol),this.dataChannelOptions.drainTimeout,{log:this.log}),this.streams=this.streams.filter((t=>t.id!==e.id)),null===(n=this.metrics)||void 0===n||n.increment({stream_end:!0}),null===(i=this.init)||void 0===i||null===(o=i.onStreamEnd)||void 0===o||o.call(i,e)}var Pp,_p=globalThis.RTCPeerConnection,Bp=globalThis.RTCSessionDescription,Np=globalThis.RTCIceCandidate;class Dp extends Error{constructor(e){super("WebRTC transport error: ".concat(e)),this.name="WebRTCTransportError"}}class Rp extends Dp{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SDP handshake failed"),this.name="SDPHandshakeFailedError"}}class Op extends Dp{constructor(e,t){super('Invalid fingerprint "'.concat(e,'" within ').concat(t)),this.name="WebRTC/InvalidFingerprintError"}}class Lp extends Dp{constructor(e){super("A method (".concat(e,") was called though it has been intentionally left unimplemented.")),this.name="WebRTC/UnimplementedError"}}class Mp extends Dp{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=()=>ql(t)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=Hl((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=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(Pp||(Pp={}));var Up=function(){var e=r((function*(e,t,r){try{var n=Cc();for(!function(e,t){e[tp?"oniceconnectionstatechange":"onconnectionstatechange"]=r=>{switch(Fp(e)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new La("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!==Pp.Type.ICE_CANDIDATE)throw new Wa("ICE candidate message expected");var s=JSON.parse(null!==(i=o.data)&&void 0!==i?i:"null");if(""!==s&&null!==s){var l=new Np(s);r.log.trace("%s received new ICE candidate %o",r.direction,s);try{var u;null===(u=r.onProgress)||void 0===u||u.call(r,new av("webrtc:add-ice-candidate",l.candidate)),yield e.addIceCandidate(l)}catch(e){r.log.error("%s bad candidate received",r.direction,s,e)}}else{var c;null===(c=r.onProgress)||void 0===c||c.call(r,new av("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"!==Fp(e))throw t}}));return function(t,r,n){return e.apply(this,arguments)}}();function Fp(e){return tp?e.iceConnectionState:e.connectionState}function zp(){return zp=r((function*(e){var{rtcConfiguration:t,dataChannel:r,signal:n,metrics:i,multiaddr:o,connectionManager:a,transportManager:s,log:l,logger:u,onProgress:c}=e,{baseAddr:d}=function(e){var t=e.toString().split("/webrtc/");if(2!==t.length)throw new _a("webrtc protocol was not present in multiaddr");if(!t[0].includes("/p2p-circuit"))throw new _a("p2p-circuit protocol was not present in multiaddr");var r=kr(t[0]),n=kr("/"+t[1]).getPeerId();if(null==n)throw new _a("destination peer id was missing");var i=r.protos().pop();if(void 0===i)throw new _a("invalid multiaddr");"p2p"!==i.name&&(r=r.encapsulate("/p2p/".concat(n)));return{baseAddr:r,peerId:Du(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 _a("Relay peer was missing");var v,p=a.getConnections(Du(h)),f=!1;0===p.length?(null==c||c(new av("webrtc:dial-relay")),v=yield s.dial(d,{signal:n,onProgress:c}),f=!0):(null==c||c(new av("webrtc:reuse-relay-connection")),v=p[0]);try{null==c||c(new av("webrtc:open-signaling-stream"));var g=yield v.newStream(Uv,{signal:n,runOnLimitedConnection:!0}),y=xd(g).pb(Pp),m=new _p(t),w=new Ap({logger:u},{peerConnection:m,dataChannelOptions:r});try{var b=m.createDataChannel("init");m.onicecandidate=e=>{var t,{candidate:r}=e,i=JSON.stringify(null!==(t=null==r?void 0:r.toJSON())&&void 0!==t?t:null);l.trace("initiator sending ICE candidate %o",r),y.write({type:Pp.Type.ICE_CANDIDATE,data:i},{signal:n}).catch((e=>{l.error("error sending ICE candidate",e)}))},m.onicecandidateerror=e=>{l.error("initiator ICE candidate error",e)};var S=yield m.createOffer().catch((e=>{throw l.error("could not execute createOffer",e),new Rp("Failed to set createOffer")}));l.trace("initiator send SDP offer %s",S.sdp),null==c||c(new av("webrtc:send-sdp-offer")),yield y.write({type:Pp.Type.SDP_OFFER,data:S.sdp},{signal:n}),yield m.setLocalDescription(S).catch((e=>{throw l.error("could not execute setLocalDescription",e),new Rp("Failed to set localDescription")})),null==c||c(new av("webrtc:read-sdp-answer")),l.trace("initiator read SDP answer");var E=yield y.read({signal:n});if(E.type!==Pp.Type.SDP_ANSWER)throw new Rp("Remote should send an SDP answer");l.trace("initiator received SDP answer %s",E.data);var k=new Bp({type:"answer",sdp:E.data});return yield m.setRemoteDescription(k).catch((e=>{throw l.error("could not execute setRemoteDescription",e),new Rp("Failed to set remoteDescription")})),l.trace("initiator read candidates until connected"),null==c||c(new av("webrtc:read-ice-candidates")),yield Up(m,y,{direction:"initiator",signal:n,log:l,onProgress:c}),l.trace("initiator connected, closing init channel"),b.close(),null==c||c(new av("webrtc:close-signaling-stream")),l.trace("closing signaling channel"),yield g.close({signal:n}),l.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:m,muxerFactory:w}}catch(e){throw l.error("outgoing signaling error",e),m.close(),g.abort(e),e}finally{m.onicecandidate=null,m.onicecandidateerror=null}}finally{if(f)try{yield v.close({signal:n})}catch(e){v.abort(e)}}})),zp.apply(this,arguments)}var jp=Wd(xh.matchers[0],Ud("p2p-circuit"));class Vp extends os{constructor(t,r){super(),e(this,"transportManager",void 0),e(this,"shutdownController",void 0),e(this,"events",void 0),this.transportManager=t.transportManager,this.events=t.events,this.shutdownController=r.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}listen(){var e=this;return r((function*(){e.events.addEventListener("transport:listening",e.onTransportListening)}))()}onTransportListening(e){e.detail.getAddrs().filter((e=>jp.exactMatch(e))).map((e=>e.encapsulate("/webrtc"))).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter((e=>!(e instanceof Vp))).map((e=>e.getAddrs().filter((e=>jp.exactMatch(e))).map((e=>e.encapsulate("/webrtc"))))).flat()}updateAnnounceAddrs(){}close(){var e=this;return r((function*(){e.events.removeEventListener("transport:listening",e.onTransportListening),e.shutdownController.abort(),queueMicrotask((()=>{e.safeDispatchEvent("close")}))}))()}}function qp(){return qp=r((function*(e){var{peerConnection:t,stream:r,signal:n,connection:i,log:o}=e;o.trace("new inbound signaling stream");var a=xd(r).pb(Pp);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:Pp.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!==Pp.Type.SDP_OFFER)throw new Rp("expected message type SDP_OFFER, received: ".concat(null!==(s=l.type)&&void 0!==s?s:"undefined"," "));o.trace("recipient received SDP offer %s",l.data);var u=new Bp({type:"offer",sdp:l.data});yield t.setRemoteDescription(u).catch((e=>{throw o.error("could not execute setRemoteDescription",e),new Rp("Failed to set remoteDescription")}));var c=yield t.createAnswer().catch((e=>{throw o.error("could not execute createAnswer",e),new Rp("Failed to create answer")}));o.trace("recipient send SDP answer %s",c.sdp),yield a.write({type:Pp.Type.SDP_ANSWER,data:c.sdp},{signal:n}),yield t.setLocalDescription(c).catch((e=>{throw o.error("could not execute setLocalDescription",e),new Rp("Failed to set localDescription")})),o.trace("recipient read candidates until connected"),yield Up(t,a,{direction:"recipient",signal:n,log:o})}catch(e){if("connected"!==Fp(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=kr("/webrtc/p2p/".concat(i.remoteAddr.getPeerId()));return o.trace("recipient connected to remote address %s",d),{remoteAddress:d}})),qp.apply(this,arguments)}class Hp{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"components",void 0),e(this,"init",void 0),e(this,"log",void 0),e(this,"_started",!1),e(this,"metrics",void 0),e(this,"shutdownController",void 0),e(this,Ca,!0),e(this,Symbol.toStringTag,"@libp2p/webrtc"),e(this,ds,["@libp2p/transport"]),e(this,hs,["@libp2p/identify","@libp2p/circuit-relay-v2-transport"]),this.components=t,this.init=r,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,null!=t.metrics&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}isStarted(){return this._started}start(){var e=this;return r((function*(){yield e.components.registrar.handle(Uv,(t=>{var r=e.components.upgrader.createInboundAbortSignal(e.shutdownController.signal);e._onProtocol(t,r).catch((r=>{e.log.error("failed to handle incoming connect from %p",t.connection.remotePeer,r)})).finally((()=>{r.clear()}))}),{runOnLimitedConnection:!0}),e._started=!0}))()}stop(){var e=this;return r((function*(){yield e.components.registrar.unhandle(Uv),e._started=!1}))()}createListener(e){return new Vp(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(Ch.exactMatch)}dialFilter(e){return this.listenFilter(e)}dial(e,t){var n=this;return r((function*(){var r;n.log.trace("dialing address: %a",e);var{remoteAddress:i,peerConnection:o,muxerFactory:a}=yield function(e){return zp.apply(this,arguments)}({rtcConfiguration:yield ip(n.init.rtcConfiguration),dataChannel:n.init.dataChannel,multiaddr:e,dataChannelOptions:n.init.dataChannel,signal:t.signal,connectionManager:n.components.connectionManager,transportManager:n.components.transportManager,log:n.log,logger:n.components.logger,onProgress:t.onProgress}),s=new ap(n.components,{peerConnection:o,timeline:{open:Date.now()},remoteAddr:i,metrics:null===(r=n.metrics)||void 0===r?void 0:r.dialerEvents}),l=yield t.upgrader.upgradeOutbound(s,{skipProtection:!0,skipEncryption:!0,muxerFactory:a,onProgress:t.onProgress,signal:t.signal});return n._closeOnShutdown(o,s),l}))()}_onProtocol(e,t){var n=this;return r((function*(){var{connection:r,stream:i}=e,o=new _p(yield ip(n.init.rtcConfiguration)),a=new Ap(n.components,{peerConnection:o,dataChannelOptions:n.init.dataChannel});try{var s,{remoteAddress:l}=yield function(e){return qp.apply(this,arguments)}({peerConnection:o,connection:r,stream:i,signal:t,log:n.log});yield i.close({signal:t});var u=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(u,{skipEncryption:!0,skipProtection:!0,muxerFactory:a,signal:t}),n._closeOnShutdown(o,u)}catch(e){throw n.log.error("incoming signaling error",e),o.close(),i.abort(e),e}}))()}_closeOnShutdown(e,t){var r=()=>{t.close().catch((e=>{this.log.error("could not close WebRTCMultiaddrConnection",e)}))};this.shutdownController.signal.addEventListener("abort",r),e.addEventListener("close",(()=>{this.shutdownController.signal.removeEventListener("abort",r)}))}}var Kp,Wp={};!function(){return Kp||(Kp=1,function(e){!function(){var t="object"==typeof globalThis?globalThis:"object"==typeof p?p:"object"==typeof self?self:"object"==typeof this?this:function(){try{return Function("return this;")()}catch(e){}}()||function(){try{return(0,eval)("(function() { return this; })()")}catch(e){}}(),r=n(e);function n(e,t){return function(r,n){Object.defineProperty(e,r,{configurable:!0,writable:!0,value:n}),t&&t(r,n)}}void 0!==t.Reflect&&(r=n(t.Reflect,r)),function(e,t){var r=Object.prototype.hasOwnProperty,n="function"==typeof Symbol,i=n&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",o=n&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",a="function"==typeof Object.create,s={__proto__:[]}instanceof Array,l=!a&&!s,u={create:a?function(){return de(Object.create(null))}:s?function(){return de({__proto__:null})}:function(){return de({})},has:l?function(e,t){return r.call(e,t)}:function(e,t){return t in e},get:l?function(e,t){return r.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},c=Object.getPrototypeOf(Function),d="function"==typeof Map&&"function"==typeof Map.prototype.entries?Map:le(),h="function"==typeof Set&&"function"==typeof Set.prototype.entries?Set:ue(),v="function"==typeof WeakMap?WeakMap:ce(),p=n?Symbol.for("@reflect-metadata:registry"):void 0,f=ie(),g=oe(f);function y(e,t,r,n){if(M(r)){if(!W(e))throw new TypeError;if(!Q(t))throw new TypeError;return I(e,t)}if(!W(e))throw new TypeError;if(!z(t))throw new TypeError;if(!z(n)&&!M(n)&&!U(n))throw new TypeError;return U(n)&&(n=void 0),T(e,t,r=K(r),n)}function m(e,t){function r(r,n){if(!z(r))throw new TypeError;if(!M(n)&&!Y(n))throw new TypeError;D(e,t,r,n)}return r}function w(e,t,r,n){if(!z(r))throw new TypeError;return M(n)||(n=K(n)),D(e,t,r,n)}function b(e,t,r){if(!z(t))throw new TypeError;return M(r)||(r=K(r)),P(e,t,r)}function S(e,t,r){if(!z(t))throw new TypeError;return M(r)||(r=K(r)),_(e,t,r)}function E(e,t,r){if(!z(t))throw new TypeError;return M(r)||(r=K(r)),B(e,t,r)}function k(e,t,r){if(!z(t))throw new TypeError;return M(r)||(r=K(r)),N(e,t,r)}function x(e,t){if(!z(e))throw new TypeError;return M(t)||(t=K(t)),R(e,t)}function A(e,t){if(!z(e))throw new TypeError;return M(t)||(t=K(t)),O(e,t)}function C(e,t,r){if(!z(t))throw new TypeError;if(M(r)||(r=K(r)),!z(t))throw new TypeError;M(r)||(r=K(r));var n=se(t,r,!1);return!M(n)&&n.OrdinaryDeleteMetadata(e,t,r)}function I(e,t){for(var r=e.length-1;r>=0;--r){var n=(0,e[r])(t);if(!M(n)&&!U(n)){if(!Q(n))throw new TypeError;t=n}}return t}function T(e,t,r,n){for(var i=e.length-1;i>=0;--i){var o=(0,e[i])(t,r,n);if(!M(o)&&!U(o)){if(!z(o))throw new TypeError;n=o}}return n}function P(e,t,r){if(_(e,t,r))return!0;var n=re(t);return!U(n)&&P(e,n,r)}function _(e,t,r){var n=se(t,r,!1);return!M(n)&&q(n.OrdinaryHasOwnMetadata(e,t,r))}function B(e,t,r){if(_(e,t,r))return N(e,t,r);var n=re(t);return U(n)?void 0:B(e,n,r)}function N(e,t,r){var n=se(t,r,!1);if(!M(n))return n.OrdinaryGetOwnMetadata(e,t,r)}function D(e,t,r,n){se(r,n,!0).OrdinaryDefineOwnMetadata(e,t,r,n)}function R(e,t){var r=O(e,t),n=re(e);if(null===n)return r;var i=R(n,t);if(i.length<=0)return r;if(r.length<=0)return i;for(var o=new h,a=[],s=0,l=r;s<l.length;s++){var u=l[s];o.has(u)||(o.add(u),a.push(u))}for(var c=0,d=i;c<d.length;c++){u=d[c];o.has(u)||(o.add(u),a.push(u))}return a}function O(e,t){var r=se(e,t,!1);return r?r.OrdinaryOwnMetadataKeys(e,t):[]}function L(e){if(null===e)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return null===e?1:6;default:return 6}}function M(e){return void 0===e}function U(e){return null===e}function F(e){return"symbol"==typeof e}function z(e){return"object"==typeof e?null!==e:"function"==typeof e}function j(e,t){switch(L(e)){case 0:case 1:case 2:case 3:case 4:case 5:return e}var r="string",n=Z(e,i);if(void 0!==n){var o=n.call(e,r);if(z(o))throw new TypeError;return o}return V(e)}function V(e,t){var r,n,i=e.toString;if(G(i)&&!z(n=i.call(e)))return n;if(G(r=e.valueOf)&&!z(n=r.call(e)))return n;throw new TypeError}function q(e){return!!e}function H(e){return""+e}function K(e){var t=j(e);return F(t)?t:H(t)}function W(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function G(e){return"function"==typeof e}function Q(e){return"function"==typeof e}function Y(e){switch(L(e)){case 3:case 4:return!0;default:return!1}}function J(e,t){return e===t||e!=e&&t!=t}function Z(e,t){var r=e[t];if(null!=r){if(!G(r))throw new TypeError;return r}}function $(e){var t=Z(e,o);if(!G(t))throw new TypeError;var r=t.call(e);if(!z(r))throw new TypeError;return r}function X(e){return e.value}function ee(e){var t=e.next();return!t.done&&t}function te(e){var t=e.return;t&&t.call(e)}function re(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===c)return t;if(t!==c)return t;var r=e.prototype,n=r&&Object.getPrototypeOf(r);if(null==n||n===Object.prototype)return t;var i=n.constructor;return"function"!=typeof i||i===e?t:i}function ne(){var e,r,n,i;M(p)||void 0===t.Reflect||p in t.Reflect||"function"!=typeof t.Reflect.defineMetadata||(e=ae(t.Reflect));var o=new v,a={registerProvider:s,getProvider:u,setProvider:f};return a;function s(t){if(!Object.isExtensible(a))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case e===t:break;case M(r):r=t;break;case r===t:break;case M(n):n=t;break;case n===t:break;default:void 0===i&&(i=new h),i.add(t)}}function l(t,o){if(!M(r)){if(r.isProviderFor(t,o))return r;if(!M(n)){if(n.isProviderFor(t,o))return r;if(!M(i))for(var a=$(i);;){var s=ee(a);if(!s)return;var l=X(s);if(l.isProviderFor(t,o))return te(a),l}}}if(!M(e)&&e.isProviderFor(t,o))return e}function u(e,t){var r,n=o.get(e);return M(n)||(r=n.get(t)),M(r)?(M(r=l(e,t))||(M(n)&&(n=new d,o.set(e,n)),n.set(t,r)),r):r}function c(e){if(M(e))throw new TypeError;return r===e||n===e||!M(i)&&i.has(e)}function f(e,t,r){if(!c(r))throw new Error("Metadata provider not registered.");var n=u(e,t);if(n!==r){if(!M(n))return!1;var i=o.get(e);M(i)&&(i=new d,o.set(e,i)),i.set(t,r)}return!0}}function ie(){var e;return!M(p)&&z(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[p]),M(e)&&(e=ne()),!M(p)&&z(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,p,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}function oe(e){var t=new v,r={isProviderFor:function(e,r){var n=t.get(e);return!M(n)&&n.has(r)},OrdinaryDefineOwnMetadata:a,OrdinaryHasOwnMetadata:i,OrdinaryGetOwnMetadata:o,OrdinaryOwnMetadataKeys:s,OrdinaryDeleteMetadata:l};return f.registerProvider(r),r;function n(n,i,o){var a=t.get(n),s=!1;if(M(a)){if(!o)return;a=new d,t.set(n,a),s=!0}var l=a.get(i);if(M(l)){if(!o)return;if(l=new d,a.set(i,l),!e.setProvider(n,i,r))throw a.delete(i),s&&t.delete(n),new Error("Wrong provider for target.")}return l}function i(e,t,r){var i=n(t,r,!1);return!M(i)&&q(i.has(e))}function o(e,t,r){var i=n(t,r,!1);if(!M(i))return i.get(e)}function a(e,t,r,i){n(r,i,!0).set(e,t)}function s(e,t){var r=[],i=n(e,t,!1);if(M(i))return r;for(var o=$(i.keys()),a=0;;){var s=ee(o);if(!s)return r.length=a,r;var l=X(s);try{r[a]=l}catch(e){try{te(o)}finally{throw e}}a++}}function l(e,r,i){var o=n(r,i,!1);if(M(o))return!1;if(!o.delete(e))return!1;if(0===o.size){var a=t.get(r);M(a)||(a.delete(i),0===a.size&&t.delete(a))}return!0}}function ae(e){var t=e.defineMetadata,r=e.hasOwnMetadata,n=e.getOwnMetadata,i=e.getOwnMetadataKeys,o=e.deleteMetadata,a=new v;return{isProviderFor:function(e,t){var r=a.get(e);return!(M(r)||!r.has(t))||!!i(e,t).length&&(M(r)&&(r=new h,a.set(e,r)),r.add(t),!0)},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:n,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:o}}function se(e,t,r){var n=f.getProvider(e,t);if(!M(n))return n;if(r){if(f.setProvider(e,t,g))return g;throw new Error("Illegal state.")}}function le(){var e={},t=[],r=function(){function e(e,t,r){this._index=0,this._keys=e,this._values=t,this._selector=r}return e.prototype["@@iterator"]=function(){return this},e.prototype[o]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var r=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:r,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:e,done:!0}},e}(),n=function(){function t(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(t.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),t.prototype.has=function(e){return this._find(e,!1)>=0},t.prototype.get=function(e){var t=this._find(e,!1);return t>=0?this._values[t]:void 0},t.prototype.set=function(e,t){var r=this._find(e,!0);return this._values[r]=t,this},t.prototype.delete=function(t){var r=this._find(t,!1);if(r>=0){for(var n=this._keys.length,i=r+1;i<n;i++)this._keys[i-1]=this._keys[i],this._values[i-1]=this._values[i];return this._keys.length--,this._values.length--,J(t,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},t.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},t.prototype.keys=function(){return new r(this._keys,this._values,i)},t.prototype.values=function(){return new r(this._keys,this._values,a)},t.prototype.entries=function(){return new r(this._keys,this._values,s)},t.prototype["@@iterator"]=function(){return this.entries()},t.prototype[o]=function(){return this.entries()},t.prototype._find=function(e,t){if(!J(this._cacheKey,e)){this._cacheIndex=-1;for(var r=0;r<this._keys.length;r++)if(J(this._keys[r],e)){this._cacheIndex=r;break}}return this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();return n;function i(e,t){return e}function a(e,t){return t}function s(e,t){return[e,t]}}function ue(){return function(){function e(){this._map=new d}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype["@@iterator"]=function(){return this.keys()},e.prototype[o]=function(){return this.keys()},e}()}function ce(){var e=16,t=u.create(),n=i();return function(){function e(){this._key=i()}return e.prototype.has=function(e){var t=o(e,!1);return void 0!==t&&u.has(t,this._key)},e.prototype.get=function(e){var t=o(e,!1);return void 0!==t?u.get(t,this._key):void 0},e.prototype.set=function(e,t){return o(e,!0)[this._key]=t,this},e.prototype.delete=function(e){var t=o(e,!1);return void 0!==t&&delete t[this._key]},e.prototype.clear=function(){this._key=i()},e}();function i(){var e;do{e="@@WeakMap@@"+l()}while(u.has(t,e));return t[e]=!0,e}function o(e,t){if(!r.call(e,n)){if(!t)return;Object.defineProperty(e,n,{value:u.create()})}return e[n]}function a(e,t){for(var r=0;r<t;++r)e[r]=255*Math.random()|0;return e}function s(e){if("function"==typeof Uint8Array){var t=new Uint8Array(e);return"undefined"!=typeof crypto?crypto.getRandomValues(t):"undefined"!=typeof msCrypto?msCrypto.getRandomValues(t):a(t,e),t}return a(new Array(e),e)}function l(){var t=s(e);t[6]=79&t[6]|64,t[8]=191&t[8]|128;for(var r="",n=0;n<e;++n){var i=t[n];4!==n&&6!==n&&8!==n||(r+="-"),i<16&&(r+="0"),r+=i.toString(16).toLowerCase()}return r}}function de(e){return e.__=void 0,delete e.__,e}e("decorate",y),e("metadata",m),e("defineMetadata",w),e("hasMetadata",b),e("hasOwnMetadata",S),e("getMetadata",E),e("getOwnMetadata",k),e("getMetadataKeys",x),e("getOwnMetadataKeys",A),e("deleteMetadata",C)}(r,t),void 0===t.Reflect&&(t.Reflect=e)}()}(e||(e={}))),Wp;var e}();var Gp,Qp={};var Yp=function(){if(Gp)return Qp;Gp=1;class e{static isArrayBuffer(e){return"[object ArrayBuffer]"===Object.prototype.toString.call(e)}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(t,r){var n=e.toUint8Array(t),i=e.toUint8Array(r);if(n.length!==i.byteLength)return!1;for(var o=0;o<n.length;o++)if(n[o]!==i[o])return!1;return!0}static concat(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];e=!Array.isArray(r[0])||r[1]instanceof Function?Array.isArray(r[0])&&r[1]instanceof Function?r[0]:r[r.length-1]instanceof Function?r.slice(0,r.length-1):r:r[0];var i=0;for(var o of e)i+=o.byteLength;var a=new Uint8Array(i),s=0;for(var l of e){var u=this.toUint8Array(l);a.set(u,s),s+=u.length}return r[r.length-1]instanceof Function?this.toView(a,r[r.length-1]):a.buffer}}var t="string",r=/^[0-9a-f\s]+$/i,n=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,i=/^[a-zA-Z0-9-_]+$/;class o{static fromString(e){for(var t=unescape(encodeURIComponent(e)),r=new Uint8Array(t.length),n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r.buffer}static toString(t){for(var r=e.toUint8Array(t),n="",i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return decodeURIComponent(escape(n))}}class a{static toString(t){for(var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=e.toArrayBuffer(t),i=new DataView(n),o="",a=0;a<n.byteLength;a+=2){var s=i.getUint16(a,r);o+=String.fromCharCode(s)}return o}static fromString(e){for(var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=new ArrayBuffer(2*e.length),n=new DataView(r),i=0;i<e.length;i++)n.setUint16(2*i,e.charCodeAt(i),t);return r}}class s{static isHex(e){return typeof e===t&&r.test(e)}static isBase64(e){return typeof e===t&&n.test(e)}static isBase64Url(e){return typeof e===t&&i.test(e)}static ToString(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8",n=e.toUint8Array(t);switch(r.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return a.toString(n,!0);case"utf16":case"utf16be":return a.toString(n);default:throw new Error("Unknown type of encoding '".concat(r,"'"))}}static FromString(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8";if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return a.fromString(e,!0);case"utf16":case"utf16be":return a.fromString(e);default:throw new Error("Unknown type of encoding '".concat(t,"'"))}}static ToBase64(t){var r=e.toUint8Array(t);if("undefined"!=typeof btoa){var n=this.ToString(r,"binary");return btoa(n)}return Buffer.from(r).toString("base64")}static FromBase64(e){var t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!s.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return"undefined"!=typeof atob?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){var t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!s.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s.DEFAULT_UTF8_ENCODING;switch(t){case"ascii":return this.FromBinary(e);case"utf8":return o.fromString(e);case"utf16":case"utf16be":return a.fromString(e);case"utf16le":case"usc2":return a.fromString(e,!0);default:throw new Error("Unknown type of encoding '".concat(t,"'"))}}static ToUtf8String(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s.DEFAULT_UTF8_ENCODING;switch(t){case"ascii":return this.ToBinary(e);case"utf8":return o.toString(e);case"utf16":case"utf16be":return a.toString(e);case"utf16le":case"usc2":return a.toString(e,!0);default:throw new Error("Unknown type of encoding '".concat(t,"'"))}}static FromBinary(e){for(var t=e.length,r=new Uint8Array(t),n=0;n<t;n++)r[n]=e.charCodeAt(n);return r.buffer}static ToBinary(t){for(var r=e.toUint8Array(t),n="",i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return n}static ToHex(t){for(var r=e.toUint8Array(t),n="",i=r.length,o=0;o<i;o++){var a=r[o];a<16&&(n+="0"),n+=a.toString(16)}return n}static FromHex(e){var t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!s.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t="0".concat(t));for(var r=new Uint8Array(t.length/2),n=0;n<t.length;n+=2){var i=t.slice(n,n+2);r[n/2]=parseInt(i,16)}return r.buffer}static ToUtf16String(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return a.toString(e,t)}static FromUtf16String(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return a.fromString(e,t)}static Base64Padding(e){var t=4-e.length%4;if(t<4)for(var r=0;r<t;r++)e+="=";return e}static formatString(e){return(null==e?void 0:e.replace(/[\n\r\t ]/g,""))||""}}return s.DEFAULT_UTF8_ENCODING="utf8",Qp.BufferSourceConverter=e,Qp.Convert=s,Qp.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},Qp.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},Qp.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},Qp}();function Jp(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 Zp(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1,n=e,i=0,o=Math.pow(2,t),a=1;a<8;a++){if(e<o){var s=void 0;if(r<0)s=new ArrayBuffer(a),i=a;else{if(r<a)return new ArrayBuffer(0);s=new ArrayBuffer(r),i=r}for(var l=new Uint8Array(s),u=a-1;u>=0;u--){var c=Math.pow(2,u*t);l[i-u-1]=Math.floor(n/c),n-=l[i-u-1]*c}return s}o*=Math.pow(2,t)}return new ArrayBuffer(0)}function $p(){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 Xp(){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=Jp(i,8),s=new ArrayBuffer(this.valueHex.byteLength),l=new Uint8Array(s),u=0;u<this.valueHex.byteLength;u++)l[u]=e[u];return l[0]&=127,Jp(l,8)-a}function ef(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 tf=["name","optional","primitiveSchema"],rf=["value"],nf=["isHexOnly"],of=["value","isIndefiniteForm"],af=["value"],sf=["isConstructed"],lf=["idBlock","lenBlock"],uf=["unusedBits","isConstructed"],cf=["idBlock","lenBlock"],df=["value"],hf=["valueDec","isFirstSid"],vf=["value"],pf=["valueDec"],ff=["value"],gf=["value","valueDate"],yf=["value"],mf=["value","local"];function wf(){if("undefined"==typeof BigInt)throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function bf(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 Sf(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 Ef{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return bf(this.items)}}var kf=[new Uint8Array([1])],xf="0123456789",Af="name",Cf="valueHexView",If="",Tf=new ArrayBuffer(0),Pf=new Uint8Array(0),_f="EndOfContent",Bf="OCTET STRING",Nf="BIT STRING";function Df(e){var r;return r=class extends e{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(e){this.valueHexView=new Uint8Array(e)}constructor(){var e;super(...arguments);var t=(arguments.length<=0?void 0:arguments[0])||{};this.isHexOnly=null!==(e=t.isHexOnly)&&void 0!==e&&e,this.valueHexView=t.valueHex?Yp.BufferSourceConverter.toUint8Array(t.valueHex):Pf}fromBER(e,t,r){var n=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!Sf(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",Tf)}toJSON(){return t(t({},super.toJSON()),{},{isHexOnly:this.isHexOnly,valueHex:Yp.Convert.ToHex(this.valueHexView)})}},r.NAME="hexBlock",r}class Rf{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=If,warnings:r=[],valueBeforeDecode:n=Pf}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=Yp.BufferSourceConverter.toUint8Array(n)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:Yp.Convert.ToHex(this.valueBeforeDecodeView)}}}Rf.NAME="baseBlock";class Of extends Rf{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'")}}Of.NAME="valueBlock";class Lf extends(Df(Rf)){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?Yp.BufferSourceConverter.toUint8Array(i.valueHex):Pf,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",Tf}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=Zp(this.tagNumber,7),o=new Uint8Array(i),a=i.byteLength,s=new Uint8Array(a+1);if(s[0]=31|t,!e){for(var l=0;l<a-1;l++)s[l+1]=128|o[l];s[a]=o[a-1]}return s.buffer}var u=new Uint8Array(this.valueHexView.byteLength+1);if(u[0]=31|t,!e){for(var c=this.valueHexView,d=0;d<c.length-1;d++)u[d+1]=128|c[d];u[this.valueHexView.byteLength]=c[c.length-1]}return u.buffer}fromBER(e,t,r){var n=Yp.BufferSourceConverter.toUint8Array(e);if(!Sf(this,n,t,r))return-1;var i=n.subarray(t,t+r);if(0===i.length)return this.error="Zero buffer length",-1;switch(192&i[0]){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=!(32&~i[0]),this.isHexOnly=!1;var o=31&i[0];if(31!==o)this.tagNumber=o,this.blockLength=1;else{for(var a=1,s=this.valueHexView=new Uint8Array(255),l=255;128&i[a];){if(s[a-1]=127&i[a],++a>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(a===l){l+=255;for(var u=new Uint8Array(l),c=0;c<s.length;c++)u[c]=s[c];s=this.valueHexView=new Uint8Array(l)}}this.blockLength=a+1,s[a-1]=127&i[a];for(var d=new Uint8Array(a),h=0;h<a;h++)d[h]=s[h];(s=this.valueHexView=new Uint8Array(a)).set(d),this.blockLength<=9?this.tagNumber=Jp(s,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(1===this.tagClass&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return t(t({},super.toJSON()),{},{tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed})}}Lf.NAME="identificationBlock";class Mf extends Rf{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=Yp.BufferSourceConverter.toUint8Array(e);if(!Sf(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=Jp(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=Zp(this.length,8);if(n.byteLength>127)return this.error="Too big length",Tf;if(e=new ArrayBuffer(n.byteLength+1),r)return e;var i=new Uint8Array(n);(t=new Uint8Array(e))[0]=128|n.byteLength;for(var o=0;o<n.byteLength;o++)t[o+1]=i[o];return e}return e=new ArrayBuffer(1),!1===r&&((t=new Uint8Array(e))[0]=this.length),e}toJSON(){return t(t({},super.toJSON()),{},{isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length})}}Mf.NAME="lengthBlock";var Uf,Ff,zf,jf,Vf,qf={};class Hf extends Rf{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{name:t=If,optional:r=!1,primitiveSchema:n}=e,i=f(e,tf),o=arguments.length>1?arguments[1]:void 0;super(i),this.name=t,this.optional=r,n&&(this.primitiveSchema=n),this.idBlock=new Lf(i),this.lenBlock=new Mf(i),this.valueBlock=o?new o(i):new Of(i)}fromBER(e,t,r){var n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===n?(this.error=this.valueBlock.error,n):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),n)}toBER(e,t){var r=t||new Ef;t||Kf(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?Tf:r.final()}toJSON(){var e=t(t({},super.toJSON()),{},{idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional});return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(){return"ascii"===(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"ascii")?this.onAsciiEncoding():Yp.Convert.ToHex(this.toBER())}onAsciiEncoding(){var e=this.constructor.NAME,t=Yp.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 Kf(e){var t;if(e instanceof qf.Constructed)for(var r of e.valueBlock.value)Kf(r)&&(e.lenBlock.isIndefiniteForm=!0);return!!(null===(t=e.lenBlock)||void 0===t?void 0:t.isIndefiniteForm)}Hf.NAME="BaseBlock";class Wf extends Hf{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:t=If}=e;super(f(e,rf),arguments.length>1?arguments[1]:void 0),t&&this.fromString(t)}fromBER(e,t,r){var n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===n?(this.error=this.valueBlock.error,n):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),n)}onAsciiEncoding(){return"".concat(this.constructor.NAME," : '").concat(this.valueBlock.value,"'")}}Wf.NAME="BaseStringBlock";class Gf extends(Df(Of)){constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{isHexOnly:t=!0}=e;super(f(e,nf)),this.isHexOnly=t}}Gf.NAME="PrimitiveValueBlock";class Qf extends Hf{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},Gf),this.idBlock.isConstructed=!1}}function Yf(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 Hf({},Of),o=new Rf;if(!Sf(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=Hf;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=qf.EndOfContent;break;case 1:s=qf.Boolean;break;case 2:s=qf.Integer;break;case 3:s=qf.BitString;break;case 4:s=qf.OctetString;break;case 5:s=qf.Null;break;case 6:s=qf.ObjectIdentifier;break;case 10:s=qf.Enumerated;break;case 12:s=qf.Utf8String;break;case 13:s=qf.RelativeObjectIdentifier;break;case 14:s=qf.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:s=qf.Sequence;break;case 17:s=qf.Set;break;case 18:s=qf.NumericString;break;case 19:s=qf.PrintableString;break;case 20:s=qf.TeletexString;break;case 21:s=qf.VideotexString;break;case 22:s=qf.IA5String;break;case 23:s=qf.UTCTime;break;case 24:s=qf.GeneralizedTime;break;case 25:s=qf.GraphicString;break;case 26:s=qf.VisibleString;break;case 27:s=qf.GeneralString;break;case 28:s=qf.UniversalString;break;case 29:s=qf.CharacterString;break;case 30:s=qf.BmpString;break;case 31:s=qf.DATE;break;case 32:s=qf.TimeOfDay;break;case 33:s=qf.DateTime;break;case 34:s=qf.Duration;break;default:var l=i.idBlock.isConstructed?new qf.Constructed:new qf.Primitive;l.idBlock=i.idBlock,l.lenBlock=i.lenBlock,l.warnings=i.warnings,i=l}}else s=i.idBlock.isConstructed?qf.Constructed:qf.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 Jf(e){if(!e.byteLength){var t=new Hf({},Of);return t.error="Input buffer has zero length",{offset:-1,result:t}}return Yf(Yp.BufferSourceConverter.toUint8Array(e).slice(),0,e.byteLength)}function Zf(e,t){return e?1:t}Uf=Qf,qf.Primitive=Uf,Qf.NAME="PRIMITIVE";class $f extends Of{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:t=[],isIndefiniteForm:r=!1}=e;super(f(e,of)),this.value=t,this.isIndefiniteForm=r}fromBER(e,t,r){var n=Yp.BufferSourceConverter.toUint8Array(e);if(!Sf(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;Zf(this.isIndefiniteForm,r)>0;){var o=Yf(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===_f)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===_f?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){for(var r=t||new Ef,n=0;n<this.value.length;n++)this.value[n].toBER(e,r);return t?Tf:r.final()}toJSON(){var e=t(t({},super.toJSON()),{},{isIndefiniteForm:this.isIndefiniteForm,value:[]});for(var r of this.value)e.value.push(r.toJSON());return e}}$f.NAME="ConstructedValueBlock";class Xf extends Hf{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},$f),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," :")}}Ff=Xf,qf.Constructed=Ff,Xf.NAME="CONSTRUCTED";class eg extends Of{fromBER(e,t,r){return t}toBER(e){return Tf}}eg.override="EndOfContentValueBlock";class tg extends Hf{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},eg),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}zf=tg,qf.EndOfContent=zf,tg.NAME=_f;class rg extends Hf{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},Of),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)}}jf=rg,qf.Null=jf,rg.NAME="NULL";class ng extends(Df(Of)){get value(){for(var e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:t}=e,r=f(e,af);super(r),r.valueHex?this.valueHexView=Yp.BufferSourceConverter.toUint8Array(r.valueHex):this.valueHexView=new Uint8Array(1),t&&(this.value=t)}fromBER(e,t,r){var n=Yp.BufferSourceConverter.toUint8Array(e);return Sf(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,Xp.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return t(t({},super.toJSON()),{},{value:this.value})}}ng.NAME="BooleanValueBlock";let ig=class extends Hf{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},ng),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.getValue)}};Vf=ig,qf.Boolean=Vf,ig.NAME="BOOLEAN";class og extends(Df($f)){constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{isConstructed:t=!1}=e;super(f(e,sf)),this.isConstructed=t}fromBER(e,t,r){var n=0;if(this.isConstructed){if(this.isHexOnly=!1,-1===(n=$f.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===_f){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(o!==Bf)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?$f.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return t(t({},super.toJSON()),{},{isConstructed:this.isConstructed})}}var ag;og.NAME="OctetStringValueBlock";let sg=class extends Hf{constructor(){var e,r,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{idBlock:i={},lenBlock:o={}}=n,a=f(n,lf);null!==(e=a.isConstructed)&&void 0!==e||(a.isConstructed=!!(null===(r=a.value)||void 0===r?void 0:r.length)),super(t({idBlock:t({isConstructed:a.isConstructed},i),lenBlock:t(t({},o),{},{isIndefiniteForm:!!a.isIndefiniteForm})},a),og),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=Yf(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 Xf.prototype.onAsciiEncoding.call(this);var e=this.constructor.NAME,t=Yp.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 ag&&e.push(t.valueBlock.valueHexView);return Yp.BufferSourceConverter.concat(e)}};ag=sg,qf.OctetString=ag,sg.NAME=Bf;class lg extends(Df($f)){constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{unusedBits:t=0,isConstructed:r=!1}=e;super(f(e,uf)),this.unusedBits=t,this.isConstructed=r,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,r){if(!r)return t;var n=-1;if(this.isConstructed){if(-1===(n=$f.prototype.fromBER.call(this,e,t,r)))return n;for(var i of this.value){var o=i.constructor.NAME;if(o===_f){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(o!==Nf)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=Yp.BufferSourceConverter.toUint8Array(e);if(!Sf(this,s,t,r))return-1;var l=s.subarray(t,t+r);if(this.unusedBits=l[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){var u=l.subarray(1);try{if(u.byteLength){var c=Yf(u,0,u.byteLength);-1!==c.offset&&c.offset===r-1&&(this.value=[c.result])}}catch(e){}}return this.valueHexView=l.subarray(1),this.blockLength=l.length,t+r}toBER(e,t){if(this.isConstructed)return $f.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Tf;var r=new Uint8Array(this.valueHexView.length+1);return r[0]=this.unusedBits,r.set(this.valueHexView,1),r.buffer}toJSON(){return t(t({},super.toJSON()),{},{unusedBits:this.unusedBits,isConstructed:this.isConstructed})}}var ug;lg.NAME="BitStringValueBlock";let cg=class extends Hf{constructor(){var e,r,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{idBlock:i={},lenBlock:o={}}=n,a=f(n,cf);null!==(e=a.isConstructed)&&void 0!==e||(a.isConstructed=!!(null===(r=a.value)||void 0===r?void 0:r.length)),super(t({idBlock:t({isConstructed:a.isConstructed},i),lenBlock:t(t({},o),{},{isIndefiniteForm:!!a.isIndefiniteForm})},a),lg),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 Xf.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 dg,hg,vg,pg,fg,gg,yg;function mg(e,t){for(var r=new Uint8Array([0]),n=new Uint8Array(e),i=new Uint8Array(t),o=n.slice(0),a=o.length-1,s=i.slice(0),l=s.length-1,u=0,c=0,d=l<a?a:l;d>=0;d--,c++){if(!0==c<s.length)u=o[a-c]+s[l-c]+r[0];else u=o[a-c]+r[0];if(r[0]=u/10,!0==c>=o.length)o=$p(new Uint8Array([u%10]),o);else o[a-c]=u%10}return r[0]>0&&(o=$p(r,o)),o}function wg(e){if(e>=kf.length)for(var t=kf.length;t<=e;t++){for(var r=new Uint8Array([0]),n=kf[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=$p(r,n)),kf.push(n)}return kf[e]}function bg(e,t){for(var r,n=0,i=new Uint8Array(e),o=new Uint8Array(t),a=i.slice(0),s=a.length-1,l=o.slice(0),u=l.length-1,c=0,d=u;d>=0;d--,c++)if(!0==(r=a[s-c]-l[u-c]-n)<0)n=1,a[s-c]=r+10;else n=0,a[s-c]=r;if(n>0)for(var h=s-u+1;h>=0;h--,c++){if(!((r=a[s-c]-n)<0)){n=0,a[s-c]=r;break}n=1,a[s-c]=r+10}return a.slice()}ug=cg,qf.BitString=ug,cg.NAME=Nf;class Sg extends(Df(Of)){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=Xp.call(this)))}constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:t}=e,r=f(e,df);super(r),this._valueDec=0,r.valueHex&&this.setValueHex(),void 0!==t&&(this.valueDec=t)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(function(e){for(var t=e<0?-1*e:e,r=128,n=1;n<8;n++){if(t<=r){if(e<0){var i=Zp(r-t,8,n);return new Uint8Array(i)[0]|=128,i}var o=Zp(t,8,n),a=new Uint8Array(o);if(128&a[0]){var s=o.slice(0),l=new Uint8Array(s);o=new ArrayBuffer(o.byteLength+1),a=new Uint8Array(o);for(var u=0;u<s.byteLength;u++)a[u+1]=l[u];a[0]=0}return o}r*=Math.pow(2,8)}return new ArrayBuffer(0)}(e))}get valueDec(){return this._valueDec}fromDER(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=this.fromBER(e,t,r);if(-1===i)return i;var o=this.valueHexView;return 0===o[0]&&128&o[1]?this.valueHexView=o.subarray(1):0!==n&&o.length<n&&(n-o.length>1&&(n=o.length+1),this.valueHexView=o.subarray(n-o.length)),i}toDER(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.valueHexView;switch(!0){case!!(128&t[0]):var r=new Uint8Array(this.valueHexView.length+1);r[0]=0,r.set(t,1),this.valueHexView=r;break;case 0===t[0]&&!(128&t[1]):this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,r){var n=super.fromBER(e,t,r);return-1===n||this.setValueHex(),n}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return t(t({},super.toJSON()),{},{valueDec:this.valueDec})}toString(){for(var e,t=8*this.valueHexView.length-1,r=new Uint8Array(8*this.valueHexView.length/3),n=0,i=this.valueHexView,o="",a=!1,s=i.byteLength-1;s>=0;s--){e=i[s];for(var l=0;l<8;l++){if(!(1&~e))if(n===t)r=bg(wg(n),r),o="-";else r=mg(r,wg(n));n++,e>>=1}}for(var u=0;u<r.length;u++)r[u]&&(a=!0),a&&(o+=xf.charAt(r[u]));return!1===a&&(o+=xf.charAt(0)),o}}dg=Sg,Sg.NAME="IntegerValueBlock",Object.defineProperty(dg.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class Eg extends Hf{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},Sg),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return wf(),BigInt(this.valueBlock.toString())}static fromBigInt(e){wf();var t=BigInt(e),r=new Ef,n=t.toString(16).replace(/^-/,""),i=new Uint8Array(Yp.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(Yp.Convert.ToHex(o)))+t,s=Yp.BufferSourceConverter.toUint8Array(Yp.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 hg({valueHex:r.final()})}convertToDER(){var e=new hg({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new hg({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.valueBlock.toString())}}hg=Eg,qf.Integer=hg,Eg.NAME="INTEGER";class kg extends Eg{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}vg=kg,qf.Enumerated=vg,kg.NAME="ENUMERATED";class xg extends(Df(Of)){constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{valueDec:t=-1,isFirstSid:r=!1}=e;super(f(e,hf)),this.valueDec=t,this.isFirstSid=r}fromBER(e,t,r){if(!r)return t;var n=Yp.BufferSourceConverter.toUint8Array(e);if(!Sf(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=Jp(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){wf();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=Zp(this.valueDec,7);if(0===i.byteLength)return this.error="Error during encoding SID value",Tf;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=Yp.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){var t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return t(t({},super.toJSON()),{},{valueDec:this.valueDec,isFirstSid:this.isFirstSid})}}xg.NAME="sidBlock";class Ag extends Of{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:t=If}=e;super(f(e,vf)),this.value=[],t&&this.fromString(t)}fromBER(e,t,r){for(var n=t;r>0;){var i=new xg;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,Tf;t.push(n)}return bf(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 xg;if(n>Number.MAX_SAFE_INTEGER){wf();var u=BigInt(n);l.valueBigInt=u}else if(l.valueDec=parseInt(n,10),isNaN(l.valueDec))return;this.value.length||(l.isFirstSid=!0,i=!0),this.value.push(l)}}while(-1!==r)}toString(){for(var e="",t=!1,r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;var n=this.value[r].toString();0!==r&&(e="".concat(e,".")),t?(n="{".concat(n,"}"),this.value[r].isFirstSid?e="2.{".concat(n," - 80}"):e+=n):e+=n}return e}toJSON(){for(var e=t(t({},super.toJSON()),{},{value:this.toString(),sidArray:[]}),r=0;r<this.value.length;r++)e.sidArray.push(this.value[r].toJSON());return e}}Ag.NAME="ObjectIdentifierValueBlock";class Cg extends Hf{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},Ag),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.valueBlock.toString()||"empty")}toJSON(){return t(t({},super.toJSON()),{},{value:this.getValue()})}}pg=Cg,qf.ObjectIdentifier=pg,Cg.NAME="OBJECT IDENTIFIER";class Ig extends(Df(Rf)){constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{valueDec:t=0}=e;super(f(e,pf)),this.valueDec=t}fromBER(e,t,r){if(0===r)return t;var n=Yp.BufferSourceConverter.toUint8Array(e);if(!Sf(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=Jp(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=Zp(this.valueDec,7);if(0===i.byteLength)return this.error="Error during encoding SID value",Tf;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?Yp.Convert.ToHex(this.valueHexView):this.valueDec.toString()}toJSON(){return t(t({},super.toJSON()),{},{valueDec:this.valueDec})}}Ig.NAME="relativeSidBlock";class Tg extends Of{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:t=If}=e;super(f(e,ff)),this.value=[],t&&this.fromString(t)}fromBER(e,t,r){for(var n=t;r>0;){var i=new Ig;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,Tf;r.push(i)}return bf(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 Ig;if(i.valueDec=parseInt(n,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(-1!==r);return!0}toString(){for(var e="",t=!1,r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;var n=this.value[r].toString();0!==r&&(e="".concat(e,".")),e+=t?n="{".concat(n,"}"):n}return e}toJSON(){for(var e=t(t({},super.toJSON()),{},{value:this.toString(),sidArray:[]}),r=0;r<this.value.length;r++)e.sidArray.push(this.value[r].toJSON());return e}}Tg.NAME="RelativeObjectIdentifierValueBlock";class Pg extends Hf{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},Tg),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.valueBlock.toString()||"empty")}toJSON(){return t(t({},super.toJSON()),{},{value:this.getValue()})}}fg=Pg,qf.RelativeObjectIdentifier=fg,Pg.NAME="RelativeObjectIdentifier";class _g extends Xf{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}gg=_g,qf.Sequence=gg,_g.NAME="SEQUENCE";let Bg=class extends Xf{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};yg=Bg,qf.Set=yg,Bg.NAME="SET";class Ng extends(Df(Of)){constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(g({},(y(e),e))),this.isHexOnly=!0,this.value=If}toJSON(){return t(t({},super.toJSON()),{},{value:this.value})}}Ng.NAME="StringValueBlock";class Dg extends Ng{}Dg.NAME="SimpleStringValueBlock";class Rg extends Wf{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(g({},(y(e),e)),Dg)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,Yp.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}}Rg.NAME="SIMPLE STRING";class Og extends Rg{fromBuffer(e){this.valueBlock.valueHexView=Yp.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=Yp.Convert.ToUtf8String(e)}catch(t){this.warnings.push('Error during "decodeURIComponent": '.concat(t,", using raw string")),this.valueBlock.value=Yp.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(Yp.Convert.FromUtf8String(e)),this.valueBlock.value=e}}var Lg,Mg,Ug,Fg,zg,jg,Vg,qg,Hg,Kg,Wg,Gg,Qg,Yg,Jg,Zg,$g,Xg,ey;Og.NAME="Utf8StringValueBlock";class ty extends Og{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}Lg=ty,qf.Utf8String=Lg,ty.NAME="UTF8String";class ry extends Rg{fromBuffer(e){this.valueBlock.value=Yp.Convert.ToUtf16String(e),this.valueBlock.valueHexView=Yp.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(Yp.Convert.FromUtf16String(e))}}ry.NAME="BmpStringValueBlock";class ny extends ry{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(g({},(y(e),e))),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}Mg=ny,qf.BmpString=Mg,ny.NAME="BMPString";class iy extends Rg{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=Zp(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}}iy.NAME="UniversalStringValueBlock";class oy extends iy{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(g({},(y(e),e))),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}Ug=oy,qf.UniversalString=Ug,oy.NAME="UniversalString";class ay extends Rg{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}Fg=ay,qf.NumericString=Fg,ay.NAME="NumericString";class sy extends Rg{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}zg=sy,qf.PrintableString=zg,sy.NAME="PrintableString";class ly extends Rg{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}jg=ly,qf.TeletexString=jg,ly.NAME="TeletexString";class uy extends Rg{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}Vg=uy,qf.VideotexString=Vg,uy.NAME="VideotexString";class cy extends Rg{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}qg=cy,qf.IA5String=qg,cy.NAME="IA5String";class dy extends Rg{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}Hg=dy,qf.GraphicString=Hg,dy.NAME="GraphicString";class hy extends Rg{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}Kg=hy,qf.VisibleString=Kg,hy.NAME="VisibleString";class vy extends Rg{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}Wg=vy,qf.GeneralString=Wg,vy.NAME="GeneralString";class py extends Rg{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}Gg=py,qf.CharacterString=Gg,py.NAME="CharacterString";class fy extends hy{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:t,valueDate:r}=e;if(super(f(e,gf)),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,t){this.fromString(t),this.valueBlock.valueHexView=new Uint8Array(t.length);for(var n=0;n<t.length;n++)this.valueBlock.valueHexView[n]=t.charCodeAt(n)}r&&(this.fromDate(r),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,Yp.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]=ef(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=ef(this.month,2),t[2]=ef(this.day,2),t[3]=ef(this.hour,2),t[4]=ef(this.minute,2),t[5]=ef(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.toDate().toISOString())}toJSON(){return t(t({},super.toJSON()),{},{year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second})}}Qg=fy,qf.UTCTime=Qg,fy.NAME="UTCTime";class gy extends fy{constructor(){var e;super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),null!==(e=this.millisecond)&&void 0!==e||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){var e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){var t,r=!1,n="",i="",o=0,a=0,s=0;if("Z"===e[e.length-1])n=e.substring(0,e.length-1),r=!0;else{var l=new Number(e[e.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(r){if(-1!==n.indexOf("+"))throw new Error("Wrong input string for conversion");if(-1!==n.indexOf("-"))throw new Error("Wrong input string for conversion")}else{var u=1,c=n.indexOf("+"),d="";if(-1===c&&(c=n.indexOf("-"),u=-1),-1!==c){if(d=n.substring(c+1),n=n.substring(0,c),2!==d.length&&4!==d.length)throw new Error("Wrong input string for conversion");var h=parseInt(d.substring(0,2),10);if(isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");if(a=u*h,4===d.length){if(h=parseInt(d.substring(2,4),10),isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");s=u*h}}}var v=n.indexOf(".");if(-1===v&&(v=n.indexOf(",")),-1!==v){var p=new Number("0".concat(n.substring(v)));if(isNaN(p.valueOf()))throw new Error("Wrong input string for conversion");o=p.valueOf(),i=n.substring(0,v)}else i=n;switch(!0){case 8===i.length:if(t=/(\d{4})(\d{2})(\d{2})/gi,-1!==v)throw new Error("Wrong input string for conversion");break;case 10===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})/gi,-1!==v){var f=60*o;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case 12===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==v){var g=60*o;this.second=Math.floor(g),g=1e3*(g-this.second),this.millisecond=Math.floor(g)}break;case 14===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==v){var y=1e3*o;this.millisecond=Math.floor(y)}break;default:throw new Error("Wrong input string for conversion")}var m=t.exec(i);if(null===m)throw new Error("Wrong input string for conversion");for(var w=1;w<m.length;w++)switch(w){case 1:this.year=parseInt(m[w],10);break;case 2:this.month=parseInt(m[w],10);break;case 3:this.day=parseInt(m[w],10);break;case 4:this.hour=parseInt(m[w],10)+a;break;case 5:this.minute=parseInt(m[w],10)+s;break;case 6:this.second=parseInt(m[w],10);break;default:throw new Error("Wrong input string for conversion")}if(!1===r){var b=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=b.getUTCFullYear(),this.month=b.getUTCMonth(),this.day=b.getUTCDay(),this.hour=b.getUTCHours(),this.minute=b.getUTCMinutes(),this.second=b.getUTCSeconds(),this.millisecond=b.getUTCMilliseconds()}}toString(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"iso";if("iso"===e){var t=[];return t.push(ef(this.year,4)),t.push(ef(this.month,2)),t.push(ef(this.day,2)),t.push(ef(this.hour,2)),t.push(ef(this.minute,2)),t.push(ef(this.second,2)),0!==this.millisecond&&(t.push("."),t.push(ef(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return t(t({},super.toJSON()),{},{millisecond:this.millisecond})}}Yg=gy,qf.GeneralizedTime=Yg,gy.NAME="GeneralizedTime";class yy extends ty{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}Jg=yy,qf.DATE=Jg,yy.NAME="DATE";class my extends ty{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}Zg=my,qf.TimeOfDay=Zg,my.NAME="TimeOfDay";class wy extends ty{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}$g=wy,qf.DateTime=$g,wy.NAME="DateTime";class by extends ty{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}Xg=by,qf.Duration=Xg,by.NAME="Duration";class Sy extends ty{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}ey=Sy,qf.TIME=ey,Sy.NAME="TIME";class Ey{constructor(){var{name:e=If,optional:t=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.name=e,this.optional=t}}class ky extends Ey{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:t=[]}=e;super(f(e,yf)),this.value=t}}class xy extends Ey{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:t=new Ey,local:r=!1}=e;super(f(e,mf)),this.value=t,this.local=r}}function Ay(e,t,r){if(r instanceof ky){for(var n of r.value){if(Ay(e,t,n).verified)return{verified:!0,result:e}}var i={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(Af)&&(i.name=r.name),i}if(r instanceof Ey)return r.hasOwnProperty(Af)&&(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(Cf 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,If),r.name&&(e[r.name]=t)),r instanceof qf.Constructed){var u=0,c={verified:!1,result:{error:"Unknown error"}},d=r.valueBlock.value.length;if(d>0&&r.valueBlock.value[0]instanceof xy&&(d=t.valueBlock.value.length),0===d)return{verified:!0,result:e};if(0===t.valueBlock.value.length&&0!==r.valueBlock.value.length){for(var h=!0,v=0;v<r.valueBlock.value.length;v++)h=h&&(r.valueBlock.value[v].optional||!1);return h?{verified:!0,result:e}:(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,If),r.name&&delete e[r.name]),e.error="Inconsistent object length",{verified:!1,result:e})}for(var p=0;p<d;p++)if(p-u>=t.valueBlock.value.length){if(!1===r.valueBlock.value[p].optional){var f={verified:!1,result:e};return e.error="Inconsistent length between ASN.1 data and schema",r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,If),r.name&&(delete e[r.name],f.name=r.name)),f}}else if(r.valueBlock.value[0]instanceof xy){if(!1===(c=Ay(e,t.valueBlock.value[p],r.valueBlock.value[0].value)).verified){if(!r.valueBlock.value[0].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,If),r.name&&delete e[r.name]),c;u++}if(Af in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){var g={};void 0===(g="local"in r.valueBlock.value[0]&&r.valueBlock.value[0].local?t:e)[r.valueBlock.value[0].name]&&(g[r.valueBlock.value[0].name]=[]),g[r.valueBlock.value[0].name].push(t.valueBlock.value[p])}}else if(!1===(c=Ay(e,t.valueBlock.value[p-u],r.valueBlock.value[p])).verified){if(!r.valueBlock.value[p].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,If),r.name&&delete e[r.name]),c;u++}if(!1===c.verified){var y={verified:!1,result:e};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,If),r.name&&(delete e[r.name],y.name=r.name)),y}return{verified:!0,result:e}}if(r.primitiveSchema&&Cf in t.valueBlock){var m=Yf(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,If),r.name&&(delete e[r.name],w.name=r.name)),w}return Ay(e,m.result,r.primitiveSchema)}return{verified:!0,result:e}}var Cy,Iy,Ty=Object.freeze({__proto__:null,Any:Ey,BaseBlock:Hf,BaseStringBlock:Wf,BitString:cg,BmpString:ny,Boolean:ig,CharacterString:py,Choice:ky,Constructed:Xf,DATE:yy,DateTime:wy,Duration:by,EndOfContent:tg,Enumerated:kg,GeneralString:vy,GeneralizedTime:gy,GraphicString:dy,HexBlock:Df,IA5String:cy,Integer:Eg,Null:rg,NumericString:ay,ObjectIdentifier:Cg,OctetString:sg,Primitive:Qf,PrintableString:sy,RawData:class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=Yp.BufferSourceConverter.toUint8Array(e)}constructor(){var{data:e=Pf}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.dataView=Yp.BufferSourceConverter.toUint8Array(e)}fromBER(e,t,r){var n=t+r;return this.dataView=Yp.BufferSourceConverter.toUint8Array(e).subarray(t,n),n}toBER(e){return this.dataView.slice().buffer}},RelativeObjectIdentifier:Pg,Repeated:xy,Sequence:_g,Set:Bg,TIME:Sy,TeletexString:ly,TimeOfDay:my,UTCTime:fy,UniversalString:oy,Utf8String:ty,ValueBlock:Of,VideotexString:uy,ViewWriter:Ef,VisibleString:hy,compareSchema:Ay,fromBER:Jf,verifySchema:function(e,t){if(t instanceof Object==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};var r=Yf(Yp.BufferSourceConverter.toUint8Array(e));return-1===r.offset?{verified:!1,result:r.result}:Ay(r.result,r.result,t)}});!function(e){e[e.Sequence=0]="Sequence",e[e.Set=1]="Set",e[e.Choice=2]="Choice"}(Cy||(Cy={})),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"}(Iy||(Iy={}));class Py{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(!Yp.BufferSourceConverter.isBufferSource(e))throw TypeError("Unsupported type of 'params' argument for BitString");this.unusedBits=t,this.value=Yp.BufferSourceConverter.toArrayBuffer(e)}}fromASN(e){if(!(e instanceof cg))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 cg({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new cg({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 _y{get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){"number"==typeof e?this.buffer=new ArrayBuffer(e):Yp.BufferSourceConverter.isBufferSource(e)?this.buffer=Yp.BufferSourceConverter.toArrayBuffer(e):Array.isArray(e)?this.buffer=new Uint8Array(e):this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof sg))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=e.valueBlock.valueHex,this}toASN(){return new sg({valueHex:this.buffer})}toSchema(e){return new sg({name:e})}}var By={fromASN:e=>e instanceof rg?null:e.valueBeforeDecodeView,toASN:e=>{if(null===e)return new rg;var t=Jf(e);if(t.result.error)throw new Error(t.result.error);return t.result}},Ny={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new Eg({value:+e})},Dy={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new kg({value:e})},Ry={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new Eg({valueHex:e})},Oy={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new cg({valueHex:e})},Ly={fromASN:e=>e.valueBlock.toString(),toASN:e=>new Cg({value:e})},My={fromASN:e=>e.valueBlock.value,toASN:e=>new ig({value:e})},Uy={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new sg({valueHex:e})},Fy={fromASN:e=>new _y(e.getValue()),toASN:e=>e.toASN()};function zy(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}var jy=zy(ty),Vy=zy(ny),qy=zy(oy),Hy=zy(ay),Ky=zy(sy),Wy=zy(ly),Gy=zy(uy),Qy=zy(cy),Yy=zy(dy),Jy=zy(hy),Zy=zy(vy),$y=zy(py),Xy={fromASN:e=>e.toDate(),toASN:e=>new fy({valueDate:e})},em={fromASN:e=>e.toDate(),toASN:e=>new gy({valueDate:e})},tm={fromASN:()=>null,toASN:()=>new rg};function rm(e){switch(e){case Iy.Any:return By;case Iy.BitString:return Oy;case Iy.BmpString:return Vy;case Iy.Boolean:return My;case Iy.CharacterString:return $y;case Iy.Enumerated:return Dy;case Iy.GeneralString:return Zy;case Iy.GeneralizedTime:return em;case Iy.GraphicString:return Yy;case Iy.IA5String:return Qy;case Iy.Integer:return Ny;case Iy.Null:return tm;case Iy.NumericString:return Hy;case Iy.ObjectIdentifier:return Ly;case Iy.OctetString:return Uy;case Iy.PrintableString:return Ky;case Iy.TeletexString:return Wy;case Iy.UTCTime:return Xy;case Iy.UniversalString:return qy;case Iy.Utf8String:return jy;case Iy.VideotexString:return Gy;case Iy.VisibleString:return Jy;default:return null}}function nm(e){return"function"==typeof e&&e.prototype?!(!e.prototype.toASN||!e.prototype.fromASN)||nm(e.prototype):!!(e&&"object"==typeof e&&"toASN"in e&&"fromASN"in e)}function im(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||im(r)}return!1}function om(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 am,sm,lm,um=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:Cy.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=Iy[o.type],u=Ty[l];if(!u)throw new Error("Cannot get ASN1 class by name '".concat(l,"'"));s=new u({name:a})}else if(nm(o.type)){s=(new o.type).toSchema(a)}else if(o.optional){this.get(o.type).type===Cy.Choice?s=new Ey({name:a}):(s=this.create(o.type,!1)).name=a}else s=new Ey({name:a});var c=!!o.optional||void 0!==o.defaultValue;if(o.repeated)s.name="",s=new("set"===o.repeated?Bg:_g)({name:"",value:[new xy({name:a,value:s})]});if(null!==o.context&&void 0!==o.context)if(o.implicit)if("number"==typeof o.type||nm(o.type)){var d=o.repeated?Xf:Qf;n.push(new d({name:a,optional:c,idBlock:{tagClass:3,tagNumber:o.context}}))}else{this.cache(o.type);var h=!!o.repeated,v=h?s:this.get(o.type,!0).schema;v="valueBlock"in v?v.valueBlock.value:v.value,n.push(new Xf({name:h?"":a,optional:c,idBlock:{tagClass:3,tagNumber:o.context},value:v}))}else n.push(new Xf({optional:c,idBlock:{tagClass:3,tagNumber:o.context},value:[s]}));else s.optional=c,n.push(s)}switch(r.type){case Cy.Sequence:return new _g({value:n,name:""});case Cy.Set:return new Bg({value:n,name:""});case Cy.Choice:return new ky({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}},cm=e=>t=>{var r;um.has(t)?r=um.get(t):(r=um.createDefault(t),um.set(t,r)),Object.assign(r,e)},dm=e=>(t,r)=>{var n;um.has(t.constructor)?n=um.get(t.constructor):(n=um.createDefault(t.constructor),um.set(t.constructor,n));var i=Object.assign({},e);if("number"==typeof i.type&&!i.converter){var o=rm(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 hm extends Error{constructor(){super(...arguments),this.schemas=[]}}class vm{static parse(e,t){var r=Jf(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(nm(t))return(new t).fromASN(e);var i=um.get(t);um.cache(t);var o=i.schema;if(e.constructor===Xf&&i.type!==Cy.Choice)for(var a in o=new Xf({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:i.schema.valueBlock.value}),i.items)delete e[a];var s=Ay({},e,o);if(!s.verified)throw new hm("Data does not match to ".concat(t.name," ASN1 schema. ").concat(s.result.error));var l=new t;if(im(t)){if(!("value"in e.valueBlock)||!Array.isArray(e.valueBlock.value))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");var u=i.itemType;if("number"==typeof u){var c=rm(u);if(!c)throw new Error("Cannot get default converter for array item of ".concat(t.name," ASN1 schema"));return t.from(e.valueBlock.value,(e=>c.fromASN(e)))}return t.from(e.valueBlock.value,(e=>this.fromASN(e,u)))}var d=function(){var e=s.result[h];if(!e)return 1;var t=i.items[h],o=t.type;if("number"==typeof o||nm(o)){var a=null!==(r=t.converter)&&void 0!==r?r:nm(o)?new o:null;if(!a)throw new Error("Converter is empty");if(t.repeated)if(t.implicit){var u=new("sequence"===t.repeated?_g:Bg);u.valueBlock=e.valueBlock;var c=Jf(u.toBER(!1));if(-1===c.offset)throw new Error("Cannot parse the child item. ".concat(c.result.error));if(!("value"in c.result.valueBlock)||!Array.isArray(c.result.valueBlock.value))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");var d=c.result.valueBlock.value;l[h]=Array.from(d,(e=>a.fromASN(e)))}else l[h]=Array.from(e,(e=>a.fromASN(e)));else{var v=e;if(t.implicit){var p;if(nm(o))p=(new o).toSchema("");else{var f=Iy[o],g=Ty[f];if(!g)throw new Error("Cannot get '".concat(f,"' class from asn1js module"));p=new g}p.valueBlock=v.valueBlock,v=Jf(p.toBER(!1)).result}l[h]=a.fromASN(v)}}else if(t.repeated){if(!Array.isArray(e))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");l[h]=Array.from(e,(e=>n.fromASN(e,o)))}else l[h]=n.fromASN(e,o)};for(var h in i.items)d();return l}catch(e){throw e instanceof hm&&e.schemas.push(t.name),e}}}class pm{static serialize(e){return e instanceof Hf?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&"object"==typeof e&&nm(e))return e.toASN();if(!e||"object"!=typeof e)throw new TypeError("Parameter 1 should be type of Object.");var r=e.constructor,n=um.get(r);um.cache(r);var i,o=[];if(n.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if("number"==typeof n.itemType){var a=rm(n.itemType);if(!a)throw new Error("Cannot get default converter for array item of ".concat(r.name," ASN1 schema"));o=e.map((e=>a.toASN(e)))}else o=e.map((e=>this.toAsnItem({type:n.itemType},"[]",r,e)))}else for(var s in n.items){var l=n.items[s],u=e[s];if(!(void 0===u||l.defaultValue===u||"object"==typeof l.defaultValue&&"object"==typeof u&&om(this.serialize(l.defaultValue),this.serialize(u)))){var c=pm.toAsnItem(l,s,r,u);if("number"==typeof l.context)if(l.implicit)if(l.repeated||"number"!=typeof l.type&&!nm(l.type))o.push(new Xf({optional:l.optional,idBlock:{tagClass:3,tagNumber:l.context},value:c.valueBlock.value}));else{var d={};d.valueHex=c instanceof rg?c.valueBeforeDecodeView:c.valueBlock.toBER(),o.push(new Qf(t({optional:l.optional,idBlock:{tagClass:3,tagNumber:l.context}},d)))}else o.push(new Xf({optional:l.optional,idBlock:{tagClass:3,tagNumber:l.context},value:[c]}));else l.repeated?o=o.concat(c):o.push(c)}}switch(n.type){case Cy.Sequence:i=new _g({value:o});break;case Cy.Set:i=new Bg({value:o});break;case Cy.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(Iy[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?_g:Bg)({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?_g:Bg)({value:s})}else i=this.toASN(n);return i}}class fm 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 gm{static serialize(e){return pm.serialize(e)}static parse(e,t){return vm.parse(e,t)}static toString(e){var t=Jf(Yp.BufferSourceConverter.isBufferSource(e)?Yp.BufferSourceConverter.toArrayBuffer(e):gm.serialize(e));if(-1===t.offset)throw new Error("Cannot decode ASN.1 data. ".concat(t.result.error));return t.result.toString()}}class ym{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(Yp.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 mm=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||""}};sa([dm({type:Iy.TeletexString})],mm.prototype,"teletexString",void 0),sa([dm({type:Iy.PrintableString})],mm.prototype,"printableString",void 0),sa([dm({type:Iy.UniversalString})],mm.prototype,"universalString",void 0),sa([dm({type:Iy.Utf8String})],mm.prototype,"utf8String",void 0),sa([dm({type:Iy.BmpString})],mm.prototype,"bmpString",void 0),mm=sa([cm({type:Cy.Choice})],mm);var wm=class extends mm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Yp.Convert.ToHex(this.anyValue):super.toString())}};sa([dm({type:Iy.IA5String})],wm.prototype,"ia5String",void 0),sa([dm({type:Iy.Any})],wm.prototype,"anyValue",void 0),wm=sa([cm({type:Cy.Choice})],wm);class bm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.type="",this.value=new wm,Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier})],bm.prototype,"type",void 0),sa([dm({type:wm})],bm.prototype,"value",void 0);var Sm=am=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,am.prototype)}};Sm=am=sa([cm({type:Cy.Set,itemType:bm})],Sm);var Em=sm=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,sm.prototype)}};Em=sm=sa([cm({type:Cy.Sequence,itemType:Sm})],Em);var km=lm=class extends Em{constructor(e){super(e),Object.setPrototypeOf(this,lm.prototype)}};km=lm=sa([cm({type:Cy.Sequence})],km);var xm={fromASN:e=>ym.toString(Uy.fromASN(e)),toASN:e=>Uy.toASN(ym.fromString(e))};class Am{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.typeId="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier})],Am.prototype,"typeId",void 0),sa([dm({type:Iy.Any,context:0})],Am.prototype,"value",void 0);class Cm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.partyName=new mm,Object.assign(this,e)}}sa([dm({type:mm,optional:!0,context:0,implicit:!0})],Cm.prototype,"nameAssigner",void 0),sa([dm({type:mm,context:1,implicit:!0})],Cm.prototype,"partyName",void 0);var Im=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};sa([dm({type:Am,context:0,implicit:!0})],Im.prototype,"otherName",void 0),sa([dm({type:Iy.IA5String,context:1,implicit:!0})],Im.prototype,"rfc822Name",void 0),sa([dm({type:Iy.IA5String,context:2,implicit:!0})],Im.prototype,"dNSName",void 0),sa([dm({type:Iy.Any,context:3,implicit:!0})],Im.prototype,"x400Address",void 0),sa([dm({type:km,context:4,implicit:!1})],Im.prototype,"directoryName",void 0),sa([dm({type:Cm,context:5})],Im.prototype,"ediPartyName",void 0),sa([dm({type:Iy.IA5String,context:6,implicit:!0})],Im.prototype,"uniformResourceIdentifier",void 0),sa([dm({type:Iy.OctetString,context:7,implicit:!0,converter:xm})],Im.prototype,"iPAddress",void 0),sa([dm({type:Iy.ObjectIdentifier,context:8,implicit:!0})],Im.prototype,"registeredID",void 0),Im=sa([cm({type:Cy.Choice})],Im);var Tm,Pm="1.3.6.1.5.5.7",_m="".concat(Pm,".1"),Bm="".concat(Pm,".3"),Nm="".concat(Pm,".48"),Dm="".concat(Nm,".1"),Rm="".concat(Nm,".2"),Om="".concat(Nm,".3"),Lm="".concat(Nm,".5"),Mm="2.5.29",Um="".concat(_m,".1");class Fm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.accessMethod="",this.accessLocation=new Im,Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier})],Fm.prototype,"accessMethod",void 0),sa([dm({type:Im})],Fm.prototype,"accessLocation",void 0);var zm=Tm=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,Tm.prototype)}};zm=Tm=sa([cm({type:Cy.Sequence,itemType:Fm})],zm);var jm="".concat(Mm,".35");class Vm extends _y{}class qm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e&&Object.assign(this,e)}}sa([dm({type:Vm,context:0,optional:!0,implicit:!0})],qm.prototype,"keyIdentifier",void 0),sa([dm({type:Im,context:1,optional:!0,implicit:!0,repeated:"sequence"})],qm.prototype,"authorityCertIssuer",void 0),sa([dm({type:Iy.Integer,context:2,optional:!0,implicit:!0,converter:Ry})],qm.prototype,"authorityCertSerialNumber",void 0);var Hm,Km="".concat(Mm,".19");class Wm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.cA=!1,Object.assign(this,e)}}sa([dm({type:Iy.Boolean,defaultValue:!1})],Wm.prototype,"cA",void 0),sa([dm({type:Iy.Integer,optional:!0})],Wm.prototype,"pathLenConstraint",void 0);var Gm,Qm=Hm=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,Hm.prototype)}};Qm=Hm=sa([cm({type:Cy.Sequence,itemType:Im})],Qm);var Ym,Jm=Gm=class extends Qm{constructor(e){super(e),Object.setPrototypeOf(this,Gm.prototype)}};Jm=Gm=sa([cm({type:Cy.Sequence})],Jm);var Zm="".concat(Mm,".32"),$m=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||""}};sa([dm({type:Iy.IA5String})],$m.prototype,"ia5String",void 0),sa([dm({type:Iy.VisibleString})],$m.prototype,"visibleString",void 0),sa([dm({type:Iy.BmpString})],$m.prototype,"bmpString",void 0),sa([dm({type:Iy.Utf8String})],$m.prototype,"utf8String",void 0),$m=sa([cm({type:Cy.Choice})],$m);class Xm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.organization=new $m,this.noticeNumbers=[],Object.assign(this,e)}}sa([dm({type:$m})],Xm.prototype,"organization",void 0),sa([dm({type:Iy.Integer,repeated:"sequence"})],Xm.prototype,"noticeNumbers",void 0);class ew{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}sa([dm({type:Xm,optional:!0})],ew.prototype,"noticeRef",void 0),sa([dm({type:$m,optional:!0})],ew.prototype,"explicitText",void 0);var tw=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};sa([dm({type:Iy.IA5String})],tw.prototype,"cPSuri",void 0),sa([dm({type:ew})],tw.prototype,"userNotice",void 0),tw=sa([cm({type:Cy.Choice})],tw);class rw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.policyQualifierId="",this.qualifier=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier})],rw.prototype,"policyQualifierId",void 0),sa([dm({type:Iy.Any})],rw.prototype,"qualifier",void 0);class nw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.policyIdentifier="",Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier})],nw.prototype,"policyIdentifier",void 0),sa([dm({type:rw,repeated:"sequence",optional:!0})],nw.prototype,"policyQualifiers",void 0);var iw=Ym=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,Ym.prototype)}};iw=Ym=sa([cm({type:Cy.Sequence,itemType:nw})],iw);var ow=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.value=e}};sa([dm({type:Iy.Integer})],ow.prototype,"value",void 0),ow=sa([cm({type:Cy.Choice})],ow);var aw,sw=class extends ow{};sw=sa([cm({type:Cy.Choice})],sw);var lw,uw="".concat(Mm,".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"}(lw||(lw={}));class cw extends Py{toJSON(){var e=[],t=this.toNumber();return t&lw.aACompromise&&e.push("aACompromise"),t&lw.affiliationChanged&&e.push("affiliationChanged"),t&lw.cACompromise&&e.push("cACompromise"),t&lw.certificateHold&&e.push("certificateHold"),t&lw.cessationOfOperation&&e.push("cessationOfOperation"),t&lw.keyCompromise&&e.push("keyCompromise"),t&lw.privilegeWithdrawn&&e.push("privilegeWithdrawn"),t&lw.superseded&&e.push("superseded"),t&lw.unused&&e.push("unused"),e}toString(){return"[".concat(this.toJSON().join(", "),"]")}}var dw=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};sa([dm({type:Im,context:0,repeated:"sequence",implicit:!0})],dw.prototype,"fullName",void 0),sa([dm({type:Sm,context:1,implicit:!0})],dw.prototype,"nameRelativeToCRLIssuer",void 0),dw=sa([cm({type:Cy.Choice})],dw);class hw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}sa([dm({type:dw,context:0,optional:!0})],hw.prototype,"distributionPoint",void 0),sa([dm({type:cw,context:1,optional:!0,implicit:!0})],hw.prototype,"reasons",void 0),sa([dm({type:Im,context:2,optional:!0,repeated:"sequence",implicit:!0})],hw.prototype,"cRLIssuer",void 0);var vw,pw=aw=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,aw.prototype)}};pw=aw=sa([cm({type:Cy.Sequence,itemType:hw})],pw);var fw,gw=vw=class extends pw{constructor(e){super(e),Object.setPrototypeOf(this,vw.prototype)}};gw=vw=sa([cm({type:Cy.Sequence,itemType:hw})],gw);class yw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.onlyContainsUserCerts=yw.ONLY,this.onlyContainsCACerts=yw.ONLY,this.indirectCRL=yw.ONLY,this.onlyContainsAttributeCerts=yw.ONLY,Object.assign(this,e)}}yw.ONLY=!1,sa([dm({type:dw,context:0,optional:!0})],yw.prototype,"distributionPoint",void 0),sa([dm({type:Iy.Boolean,context:1,defaultValue:yw.ONLY,implicit:!0})],yw.prototype,"onlyContainsUserCerts",void 0),sa([dm({type:Iy.Boolean,context:2,defaultValue:yw.ONLY,implicit:!0})],yw.prototype,"onlyContainsCACerts",void 0),sa([dm({type:cw,context:3,optional:!0,implicit:!0})],yw.prototype,"onlySomeReasons",void 0),sa([dm({type:Iy.Boolean,context:4,defaultValue:yw.ONLY,implicit:!0})],yw.prototype,"indirectCRL",void 0),sa([dm({type:Iy.Boolean,context:5,defaultValue:yw.ONLY,implicit:!0})],yw.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"}(fw||(fw={}));var mw,ww=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:fw.unspecified;this.reason=fw.unspecified,this.reason=e}toJSON(){return fw[this.reason]}toString(){return this.toJSON()}};sa([dm({type:Iy.Enumerated})],ww.prototype,"reason",void 0),ww=sa([cm({type:Cy.Choice})],ww);var bw="".concat(Mm,".37"),Sw=mw=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,mw.prototype)}};Sw=mw=sa([cm({type:Cy.Sequence,itemType:Iy.ObjectIdentifier})],Sw);var Ew="".concat(Bm,".1"),kw="".concat(Bm,".2"),xw="".concat(Bm,".3"),Aw="".concat(Bm,".4"),Cw="".concat(Bm,".8"),Iw="".concat(Bm,".9"),Tw=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new ArrayBuffer(0);this.value=e}};sa([dm({type:Iy.Integer,converter:Ry})],Tw.prototype,"value",void 0),Tw=sa([cm({type:Cy.Choice})],Tw);var Pw,_w=class{constructor(e){this.value=new Date,e&&(this.value=e)}};sa([dm({type:Iy.GeneralizedTime})],_w.prototype,"value",void 0),_w=sa([cm({type:Cy.Choice})],_w);var Bw=Pw=class extends Qm{constructor(e){super(e),Object.setPrototypeOf(this,Pw.prototype)}};Bw=Pw=sa([cm({type:Cy.Sequence})],Bw);var Nw,Dw,Rw="".concat(Mm,".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"}(Nw||(Nw={}));class Ow extends Py{toJSON(){var e=this.toNumber(),t=[];return e&Nw.cRLSign&&t.push("crlSign"),e&Nw.dataEncipherment&&t.push("dataEncipherment"),e&Nw.decipherOnly&&t.push("decipherOnly"),e&Nw.digitalSignature&&t.push("digitalSignature"),e&Nw.encipherOnly&&t.push("encipherOnly"),e&Nw.keyAgreement&&t.push("keyAgreement"),e&Nw.keyCertSign&&t.push("keyCertSign"),e&Nw.keyEncipherment&&t.push("keyEncipherment"),e&Nw.nonRepudiation&&t.push("nonRepudiation"),t}toString(){return"[".concat(this.toJSON().join(", "),"]")}}class Lw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.base=new Im,this.minimum=0,Object.assign(this,e)}}sa([dm({type:Im})],Lw.prototype,"base",void 0),sa([dm({type:Iy.Integer,context:0,defaultValue:0,implicit:!0})],Lw.prototype,"minimum",void 0),sa([dm({type:Iy.Integer,context:1,optional:!0,implicit:!0})],Lw.prototype,"maximum",void 0);var Mw,Uw=Dw=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,Dw.prototype)}};Uw=Dw=sa([cm({type:Cy.Sequence,itemType:Lw})],Uw);class Fw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}sa([dm({type:Uw,context:0,optional:!0,implicit:!0})],Fw.prototype,"permittedSubtrees",void 0),sa([dm({type:Uw,context:1,optional:!0,implicit:!0})],Fw.prototype,"excludedSubtrees",void 0);class zw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}sa([dm({type:Iy.Integer,context:0,implicit:!0,optional:!0,converter:Ry})],zw.prototype,"requireExplicitPolicy",void 0),sa([dm({type:Iy.Integer,context:1,implicit:!0,optional:!0,converter:Ry})],zw.prototype,"inhibitPolicyMapping",void 0);class jw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.issuerDomainPolicy="",this.subjectDomainPolicy="",Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier})],jw.prototype,"issuerDomainPolicy",void 0),sa([dm({type:Iy.ObjectIdentifier})],jw.prototype,"subjectDomainPolicy",void 0);var Vw,qw=Mw=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,Mw.prototype)}};qw=Mw=sa([cm({type:Cy.Sequence,itemType:jw})],qw);var Hw="".concat(Mm,".17"),Kw=Vw=class extends Qm{constructor(e){super(e),Object.setPrototypeOf(this,Vw.prototype)}};Kw=Vw=sa([cm({type:Cy.Sequence})],Kw);let Ww=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.type="",this.values=[],Object.assign(this,e)}};var Gw;sa([dm({type:Iy.ObjectIdentifier})],Ww.prototype,"type",void 0),sa([dm({type:Iy.Any,repeated:"set"})],Ww.prototype,"values",void 0);var Qw=Gw=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,Gw.prototype)}};Qw=Gw=sa([cm({type:Cy.Sequence,itemType:Ww})],Qw);var Yw,Jw,Zw="".concat(Mm,".14");class $w extends Vm{}class Xw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}sa([dm({type:Iy.GeneralizedTime,context:0,implicit:!0,optional:!0})],Xw.prototype,"notBefore",void 0),sa([dm({type:Iy.GeneralizedTime,context:1,implicit:!0,optional:!0})],Xw.prototype,"notAfter",void 0),function(e){e[e.keyUpdateAllowed=1]="keyUpdateAllowed",e[e.newExtensions=2]="newExtensions",e[e.pKIXCertificate=4]="pKIXCertificate"}(Yw||(Yw={}));class eb extends Py{toJSON(){var e=[],t=this.toNumber();return t&Yw.pKIXCertificate&&e.push("pKIXCertificate"),t&Yw.newExtensions&&e.push("newExtensions"),t&Yw.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return"[".concat(this.toJSON().join(", "),"]")}}class tb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.entrustVers="",this.entrustInfoFlags=new eb,Object.assign(this,e)}}sa([dm({type:Iy.GeneralString})],tb.prototype,"entrustVers",void 0),sa([dm({type:eb})],tb.prototype,"entrustInfoFlags",void 0);var rb=Jw=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,Jw.prototype)}};rb=Jw=sa([cm({type:Cy.Sequence,itemType:Fm})],rb);class nb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.algorithm="",Object.assign(this,e)}isEqual(e){return e instanceof nb&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&Yp.isEqual(e.parameters,this.parameters)||e.parameters===this.parameters)}}sa([dm({type:Iy.ObjectIdentifier})],nb.prototype,"algorithm",void 0),sa([dm({type:Iy.Any,optional:!0})],nb.prototype,"parameters",void 0);class ib{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.algorithm=new nb,this.subjectPublicKey=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:nb})],ib.prototype,"algorithm",void 0),sa([dm({type:Iy.BitString})],ib.prototype,"subjectPublicKey",void 0);var ob,ab=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}};sa([dm({type:Iy.UTCTime})],ab.prototype,"utcTime",void 0),sa([dm({type:Iy.GeneralizedTime})],ab.prototype,"generalTime",void 0),ab=sa([cm({type:Cy.Choice})],ab);class sb{constructor(e){this.notBefore=new ab(new Date),this.notAfter=new ab(new Date),e&&(this.notBefore=new ab(e.notBefore),this.notAfter=new ab(e.notAfter))}}sa([dm({type:ab})],sb.prototype,"notBefore",void 0),sa([dm({type:ab})],sb.prototype,"notAfter",void 0);let lb=class e{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.extnID="",this.critical=e.CRITICAL,this.extnValue=new _y,Object.assign(this,t)}};lb.CRITICAL=!1,sa([dm({type:Iy.ObjectIdentifier})],lb.prototype,"extnID",void 0),sa([dm({type:Iy.Boolean,defaultValue:lb.CRITICAL})],lb.prototype,"critical",void 0),sa([dm({type:_y})],lb.prototype,"extnValue",void 0);var ub,cb=ob=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,ob.prototype)}};cb=ob=sa([cm({type:Cy.Sequence,itemType:lb})],cb),function(e){e[e.v1=0]="v1",e[e.v2=1]="v2",e[e.v3=2]="v3"}(ub||(ub={}));class db{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=ub.v1,this.serialNumber=new ArrayBuffer(0),this.signature=new nb,this.issuer=new km,this.validity=new sb,this.subject=new km,this.subjectPublicKeyInfo=new ib,Object.assign(this,e)}}sa([dm({type:Iy.Integer,context:0,defaultValue:ub.v1})],db.prototype,"version",void 0),sa([dm({type:Iy.Integer,converter:Ry})],db.prototype,"serialNumber",void 0),sa([dm({type:nb})],db.prototype,"signature",void 0),sa([dm({type:km})],db.prototype,"issuer",void 0),sa([dm({type:sb})],db.prototype,"validity",void 0),sa([dm({type:km})],db.prototype,"subject",void 0),sa([dm({type:ib})],db.prototype,"subjectPublicKeyInfo",void 0),sa([dm({type:Iy.BitString,context:1,implicit:!0,optional:!0})],db.prototype,"issuerUniqueID",void 0),sa([dm({type:Iy.BitString,context:2,implicit:!0,optional:!0})],db.prototype,"subjectUniqueID",void 0),sa([dm({type:cb,context:3,optional:!0})],db.prototype,"extensions",void 0);class hb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.tbsCertificate=new db,this.signatureAlgorithm=new nb,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:db})],hb.prototype,"tbsCertificate",void 0),sa([dm({type:nb})],hb.prototype,"signatureAlgorithm",void 0),sa([dm({type:Iy.BitString})],hb.prototype,"signatureValue",void 0);class vb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.userCertificate=new ArrayBuffer(0),this.revocationDate=new ab,Object.assign(this,e)}}sa([dm({type:Iy.Integer,converter:Ry})],vb.prototype,"userCertificate",void 0),sa([dm({type:ab})],vb.prototype,"revocationDate",void 0),sa([dm({type:lb,optional:!0,repeated:"sequence"})],vb.prototype,"crlEntryExtensions",void 0);class pb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.signature=new nb,this.issuer=new km,this.thisUpdate=new ab,Object.assign(this,e)}}sa([dm({type:Iy.Integer,optional:!0})],pb.prototype,"version",void 0),sa([dm({type:nb})],pb.prototype,"signature",void 0),sa([dm({type:km})],pb.prototype,"issuer",void 0),sa([dm({type:ab})],pb.prototype,"thisUpdate",void 0),sa([dm({type:ab,optional:!0})],pb.prototype,"nextUpdate",void 0),sa([dm({type:vb,repeated:"sequence",optional:!0})],pb.prototype,"revokedCertificates",void 0),sa([dm({type:lb,optional:!0,context:0,repeated:"sequence"})],pb.prototype,"crlExtensions",void 0);class fb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.tbsCertList=new pb,this.signatureAlgorithm=new nb,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:pb})],fb.prototype,"tbsCertList",void 0),sa([dm({type:nb})],fb.prototype,"signatureAlgorithm",void 0),sa([dm({type:Iy.BitString})],fb.prototype,"signature",void 0);class gb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.issuer=new km,this.serialNumber=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:km})],gb.prototype,"issuer",void 0),sa([dm({type:Iy.Integer,converter:Ry})],gb.prototype,"serialNumber",void 0);var yb,mb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};sa([dm({type:$w,context:0,implicit:!0})],mb.prototype,"subjectKeyIdentifier",void 0),sa([dm({type:gb})],mb.prototype,"issuerAndSerialNumber",void 0),mb=sa([cm({type:Cy.Choice})],mb),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"}(yb||(yb={}));var wb=class extends nb{};wb=sa([cm({type:Cy.Sequence})],wb);var bb=class extends nb{};bb=sa([cm({type:Cy.Sequence})],bb);var Sb=class extends nb{};Sb=sa([cm({type:Cy.Sequence})],Sb);var Eb=class extends nb{};Eb=sa([cm({type:Cy.Sequence})],Eb);var kb=class extends nb{};kb=sa([cm({type:Cy.Sequence})],kb);var xb=class extends nb{};xb=sa([cm({type:Cy.Sequence})],xb);let Ab=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.attrType="",this.attrValues=[],Object.assign(this,e)}};var Cb;sa([dm({type:Iy.ObjectIdentifier})],Ab.prototype,"attrType",void 0),sa([dm({type:Iy.Any,repeated:"set"})],Ab.prototype,"attrValues",void 0);class Ib{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=yb.v0,this.sid=new mb,this.digestAlgorithm=new wb,this.signatureAlgorithm=new bb,this.signature=new _y,Object.assign(this,e)}}sa([dm({type:Iy.Integer})],Ib.prototype,"version",void 0),sa([dm({type:mb})],Ib.prototype,"sid",void 0),sa([dm({type:wb})],Ib.prototype,"digestAlgorithm",void 0),sa([dm({type:Ab,repeated:"set",context:0,implicit:!0,optional:!0})],Ib.prototype,"signedAttrs",void 0),sa([dm({type:bb})],Ib.prototype,"signatureAlgorithm",void 0),sa([dm({type:_y})],Ib.prototype,"signature",void 0),sa([dm({type:Ab,repeated:"set",context:1,implicit:!0,optional:!0})],Ib.prototype,"unsignedAttrs",void 0);var Tb=Cb=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,Cb.prototype)}};Tb=Cb=sa([cm({type:Cy.Set,itemType:Ib})],Tb);var Pb=class extends ab{};Pb=sa([cm({type:Cy.Choice})],Pb);var _b,Bb=class extends Ib{};Bb=sa([cm({type:Cy.Sequence})],Bb);class Nb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.acIssuer=new Im,this.acSerial=0,this.attrs=[],Object.assign(this,e)}}sa([dm({type:Im})],Nb.prototype,"acIssuer",void 0),sa([dm({type:Iy.Integer})],Nb.prototype,"acSerial",void 0),sa([dm({type:Ww,repeated:"sequence"})],Nb.prototype,"attrs",void 0);var Db,Rb=_b=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,_b.prototype)}};Rb=_b=sa([cm({type:Cy.Sequence,itemType:Iy.ObjectIdentifier})],Rb);class Ob{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.permitUnSpecified=!0,Object.assign(this,e)}}sa([dm({type:Iy.Integer,optional:!0})],Ob.prototype,"pathLenConstraint",void 0),sa([dm({type:Rb,implicit:!0,context:0,optional:!0})],Ob.prototype,"permittedAttrs",void 0),sa([dm({type:Rb,implicit:!0,context:1,optional:!0})],Ob.prototype,"excludedAttrs",void 0),sa([dm({type:Iy.Boolean,defaultValue:!0})],Ob.prototype,"permitUnSpecified",void 0);class Lb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.issuer=new Qm,this.serial=new ArrayBuffer(0),this.issuerUID=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:Qm})],Lb.prototype,"issuer",void 0),sa([dm({type:Iy.Integer,converter:Ry})],Lb.prototype,"serial",void 0),sa([dm({type:Iy.BitString,optional:!0})],Lb.prototype,"issuerUID",void 0),function(e){e[e.publicKey=0]="publicKey",e[e.publicKeyCert=1]="publicKeyCert",e[e.otherObjectTypes=2]="otherObjectTypes"}(Db||(Db={}));class Mb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.digestedObjectType=Db.publicKey,this.digestAlgorithm=new nb,this.objectDigest=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:Iy.Enumerated})],Mb.prototype,"digestedObjectType",void 0),sa([dm({type:Iy.ObjectIdentifier,optional:!0})],Mb.prototype,"otherObjectTypeID",void 0),sa([dm({type:nb})],Mb.prototype,"digestAlgorithm",void 0),sa([dm({type:Iy.BitString})],Mb.prototype,"objectDigest",void 0);class Ub{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}sa([dm({type:Qm,optional:!0})],Ub.prototype,"issuerName",void 0),sa([dm({type:Lb,context:0,implicit:!0,optional:!0})],Ub.prototype,"baseCertificateID",void 0),sa([dm({type:Mb,context:1,implicit:!0,optional:!0})],Ub.prototype,"objectDigestInfo",void 0);var Fb,zb,jb,Vb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};sa([dm({type:Im,repeated:"sequence"})],Vb.prototype,"v1Form",void 0),sa([dm({type:Ub,context:0,implicit:!0})],Vb.prototype,"v2Form",void 0),Vb=sa([cm({type:Cy.Choice})],Vb);class qb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.notBeforeTime=new Date,this.notAfterTime=new Date,Object.assign(this,e)}}sa([dm({type:Iy.GeneralizedTime})],qb.prototype,"notBeforeTime",void 0),sa([dm({type:Iy.GeneralizedTime})],qb.prototype,"notAfterTime",void 0);class Hb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}sa([dm({type:Lb,implicit:!0,context:0,optional:!0})],Hb.prototype,"baseCertificateID",void 0),sa([dm({type:Qm,implicit:!0,context:1,optional:!0})],Hb.prototype,"entityName",void 0),sa([dm({type:Mb,implicit:!0,context:2,optional:!0})],Hb.prototype,"objectDigestInfo",void 0),function(e){e[e.v2=1]="v2"}(Fb||(Fb={}));class Kb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Fb.v2,this.holder=new Hb,this.issuer=new Vb,this.signature=new nb,this.serialNumber=new ArrayBuffer(0),this.attrCertValidityPeriod=new qb,this.attributes=[],Object.assign(this,e)}}sa([dm({type:Iy.Integer})],Kb.prototype,"version",void 0),sa([dm({type:Hb})],Kb.prototype,"holder",void 0),sa([dm({type:Vb})],Kb.prototype,"issuer",void 0),sa([dm({type:nb})],Kb.prototype,"signature",void 0),sa([dm({type:Iy.Integer,converter:Ry})],Kb.prototype,"serialNumber",void 0),sa([dm({type:qb})],Kb.prototype,"attrCertValidityPeriod",void 0),sa([dm({type:Ww,repeated:"sequence"})],Kb.prototype,"attributes",void 0),sa([dm({type:Iy.BitString,optional:!0})],Kb.prototype,"issuerUniqueID",void 0),sa([dm({type:cb,optional:!0})],Kb.prototype,"extensions",void 0);class Wb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.acinfo=new Kb,this.signatureAlgorithm=new nb,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:Kb})],Wb.prototype,"acinfo",void 0),sa([dm({type:nb})],Wb.prototype,"signatureAlgorithm",void 0),sa([dm({type:Iy.BitString})],Wb.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"}(zb||(zb={}));class Gb extends Py{}class Qb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.type="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier,implicit:!0,context:0})],Qb.prototype,"type",void 0),sa([dm({type:Iy.Any,implicit:!0,context:1})],Qb.prototype,"value",void 0);class Yb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.policyId="",this.classList=new Gb(zb.unclassified),Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier})],Yb.prototype,"policyId",void 0),sa([dm({type:Gb,defaultValue:new Gb(zb.unclassified)})],Yb.prototype,"classList",void 0),sa([dm({type:Qb,repeated:"set"})],Yb.prototype,"securityCategories",void 0);class Jb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}sa([dm({type:_y})],Jb.prototype,"cotets",void 0),sa([dm({type:Iy.ObjectIdentifier})],Jb.prototype,"oid",void 0),sa([dm({type:Iy.Utf8String})],Jb.prototype,"string",void 0);class Zb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.values=[],Object.assign(this,e)}}sa([dm({type:Qm,implicit:!0,context:0,optional:!0})],Zb.prototype,"policyAuthority",void 0),sa([dm({type:Jb,repeated:"sequence"})],Zb.prototype,"values",void 0);class $b{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.targetCertificate=new Lb,Object.assign(this,e)}}sa([dm({type:Lb})],$b.prototype,"targetCertificate",void 0),sa([dm({type:Im,optional:!0})],$b.prototype,"targetName",void 0),sa([dm({type:Mb,optional:!0})],$b.prototype,"certDigestInfo",void 0);var Xb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};sa([dm({type:Im,context:0,implicit:!0})],Xb.prototype,"targetName",void 0),sa([dm({type:Im,context:1,implicit:!0})],Xb.prototype,"targetGroup",void 0),sa([dm({type:$b,context:2,implicit:!0})],Xb.prototype,"targetCert",void 0),Xb=sa([cm({type:Cy.Choice})],Xb);var eS,tS=jb=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,jb.prototype)}};tS=jb=sa([cm({type:Cy.Sequence,itemType:Xb})],tS);var rS,nS=eS=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,eS.prototype)}};nS=eS=sa([cm({type:Cy.Sequence,itemType:tS})],nS);class iS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}sa([dm({type:Qm,implicit:!0,context:0,optional:!0})],iS.prototype,"roleAuthority",void 0),sa([dm({type:Im,implicit:!0,context:1})],iS.prototype,"roleName",void 0);class oS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.service=new Im,this.ident=new Im,Object.assign(this,e)}}sa([dm({type:Im})],oS.prototype,"service",void 0),sa([dm({type:Im})],oS.prototype,"ident",void 0),sa([dm({type:_y,optional:!0})],oS.prototype,"authInfo",void 0);class aS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.otherCertFormat="",this.otherCert=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier})],aS.prototype,"otherCertFormat",void 0),sa([dm({type:Iy.Any})],aS.prototype,"otherCert",void 0);var sS=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};sa([dm({type:hb})],sS.prototype,"certificate",void 0),sa([dm({type:Wb,context:2,implicit:!0})],sS.prototype,"v2AttrCert",void 0),sa([dm({type:aS,context:3,implicit:!0})],sS.prototype,"other",void 0),sS=sa([cm({type:Cy.Choice})],sS);var lS=rS=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,rS.prototype)}};lS=rS=sa([cm({type:Cy.Set,itemType:sS})],lS);class uS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.contentType="",this.content=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier})],uS.prototype,"contentType",void 0),sa([dm({type:Iy.Any,context:0})],uS.prototype,"content",void 0);var cS=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};sa([dm({type:_y})],cS.prototype,"single",void 0),sa([dm({type:Iy.Any})],cS.prototype,"any",void 0),cS=sa([cm({type:Cy.Choice})],cS);class dS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.eContentType="",Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier})],dS.prototype,"eContentType",void 0),sa([dm({type:cS,context:0,optional:!0})],dS.prototype,"eContent",void 0);var hS,vS=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};sa([dm({type:_y,context:0,implicit:!0,optional:!0})],vS.prototype,"value",void 0),sa([dm({type:_y,converter:Fy,context:0,implicit:!0,optional:!0,repeated:"sequence"})],vS.prototype,"constructedValue",void 0),vS=sa([cm({type:Cy.Choice})],vS);class pS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.contentType="",this.contentEncryptionAlgorithm=new Eb,Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier})],pS.prototype,"contentType",void 0),sa([dm({type:Eb})],pS.prototype,"contentEncryptionAlgorithm",void 0),sa([dm({type:vS,optional:!0})],pS.prototype,"encryptedContent",void 0);class fS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.keyAttrId="",Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier})],fS.prototype,"keyAttrId",void 0),sa([dm({type:Iy.Any,optional:!0})],fS.prototype,"keyAttr",void 0);class gS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.subjectKeyIdentifier=new $w,Object.assign(this,e)}}sa([dm({type:$w})],gS.prototype,"subjectKeyIdentifier",void 0),sa([dm({type:Iy.GeneralizedTime,optional:!0})],gS.prototype,"date",void 0),sa([dm({type:fS,optional:!0})],gS.prototype,"other",void 0);var yS=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};sa([dm({type:gS,context:0,implicit:!0,optional:!0})],yS.prototype,"rKeyId",void 0),sa([dm({type:gb,optional:!0})],yS.prototype,"issuerAndSerialNumber",void 0),yS=sa([cm({type:Cy.Choice})],yS);class mS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.rid=new yS,this.encryptedKey=new _y,Object.assign(this,e)}}sa([dm({type:yS})],mS.prototype,"rid",void 0),sa([dm({type:_y})],mS.prototype,"encryptedKey",void 0);var wS=hS=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,hS.prototype)}};wS=hS=sa([cm({type:Cy.Sequence,itemType:mS})],wS);class bS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.algorithm=new nb,this.publicKey=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:nb})],bS.prototype,"algorithm",void 0),sa([dm({type:Iy.BitString})],bS.prototype,"publicKey",void 0);var SS=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};sa([dm({type:$w,context:0,implicit:!0,optional:!0})],SS.prototype,"subjectKeyIdentifier",void 0),sa([dm({type:bS,context:1,implicit:!0,optional:!0})],SS.prototype,"originatorKey",void 0),sa([dm({type:gb,optional:!0})],SS.prototype,"issuerAndSerialNumber",void 0),SS=sa([cm({type:Cy.Choice})],SS);class ES{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=yb.v3,this.originator=new SS,this.keyEncryptionAlgorithm=new Sb,this.recipientEncryptedKeys=new wS,Object.assign(this,e)}}sa([dm({type:Iy.Integer})],ES.prototype,"version",void 0),sa([dm({type:SS,context:0})],ES.prototype,"originator",void 0),sa([dm({type:_y,context:1,optional:!0})],ES.prototype,"ukm",void 0),sa([dm({type:Sb})],ES.prototype,"keyEncryptionAlgorithm",void 0),sa([dm({type:wS})],ES.prototype,"recipientEncryptedKeys",void 0);var kS=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};sa([dm({type:$w,context:0,implicit:!0})],kS.prototype,"subjectKeyIdentifier",void 0),sa([dm({type:gb})],kS.prototype,"issuerAndSerialNumber",void 0),kS=sa([cm({type:Cy.Choice})],kS);class xS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=yb.v0,this.rid=new kS,this.keyEncryptionAlgorithm=new Sb,this.encryptedKey=new _y,Object.assign(this,e)}}sa([dm({type:Iy.Integer})],xS.prototype,"version",void 0),sa([dm({type:kS})],xS.prototype,"rid",void 0),sa([dm({type:Sb})],xS.prototype,"keyEncryptionAlgorithm",void 0),sa([dm({type:_y})],xS.prototype,"encryptedKey",void 0);class AS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.keyIdentifier=new _y,Object.assign(this,e)}}sa([dm({type:_y})],AS.prototype,"keyIdentifier",void 0),sa([dm({type:Iy.GeneralizedTime,optional:!0})],AS.prototype,"date",void 0),sa([dm({type:fS,optional:!0})],AS.prototype,"other",void 0);class CS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=yb.v4,this.kekid=new AS,this.keyEncryptionAlgorithm=new Sb,this.encryptedKey=new _y,Object.assign(this,e)}}sa([dm({type:Iy.Integer})],CS.prototype,"version",void 0),sa([dm({type:AS})],CS.prototype,"kekid",void 0),sa([dm({type:Sb})],CS.prototype,"keyEncryptionAlgorithm",void 0),sa([dm({type:_y})],CS.prototype,"encryptedKey",void 0);class IS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=yb.v0,this.keyEncryptionAlgorithm=new Sb,this.encryptedKey=new _y,Object.assign(this,e)}}sa([dm({type:Iy.Integer})],IS.prototype,"version",void 0),sa([dm({type:xb,context:0,optional:!0})],IS.prototype,"keyDerivationAlgorithm",void 0),sa([dm({type:Sb})],IS.prototype,"keyEncryptionAlgorithm",void 0),sa([dm({type:_y})],IS.prototype,"encryptedKey",void 0);class TS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.oriType="",this.oriValue=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier})],TS.prototype,"oriType",void 0),sa([dm({type:Iy.Any})],TS.prototype,"oriValue",void 0);var PS,_S=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};sa([dm({type:xS,optional:!0})],_S.prototype,"ktri",void 0),sa([dm({type:ES,context:1,implicit:!0,optional:!0})],_S.prototype,"kari",void 0),sa([dm({type:CS,context:2,implicit:!0,optional:!0})],_S.prototype,"kekri",void 0),sa([dm({type:IS,context:3,implicit:!0,optional:!0})],_S.prototype,"pwri",void 0),sa([dm({type:TS,context:4,implicit:!0,optional:!0})],_S.prototype,"ori",void 0),_S=sa([cm({type:Cy.Choice})],_S);var BS,NS=PS=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,PS.prototype)}};NS=PS=sa([cm({type:Cy.Set,itemType:_S})],NS);class DS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.otherRevInfoFormat="",this.otherRevInfo=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier})],DS.prototype,"otherRevInfoFormat",void 0),sa([dm({type:Iy.Any})],DS.prototype,"otherRevInfo",void 0);var RS=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.other=new DS,Object.assign(this,e)}};sa([dm({type:DS,context:1,implicit:!0})],RS.prototype,"other",void 0),RS=sa([cm({type:Cy.Choice})],RS);var OS,LS=BS=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,BS.prototype)}};LS=BS=sa([cm({type:Cy.Set,itemType:RS})],LS);class MS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}sa([dm({type:lS,context:0,implicit:!0,optional:!0})],MS.prototype,"certs",void 0),sa([dm({type:LS,context:1,implicit:!0,optional:!0})],MS.prototype,"crls",void 0);var US=OS=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,OS.prototype)}};US=OS=sa([cm({type:Cy.Set,itemType:Ab})],US);class FS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=yb.v0,this.recipientInfos=new NS,this.encryptedContentInfo=new pS,Object.assign(this,e)}}sa([dm({type:Iy.Integer})],FS.prototype,"version",void 0),sa([dm({type:MS,context:0,implicit:!0,optional:!0})],FS.prototype,"originatorInfo",void 0),sa([dm({type:NS})],FS.prototype,"recipientInfos",void 0),sa([dm({type:pS})],FS.prototype,"encryptedContentInfo",void 0),sa([dm({type:US,context:1,implicit:!0,optional:!0})],FS.prototype,"unprotectedAttrs",void 0);var zS,jS="1.2.840.113549.1.7.2",VS=zS=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,zS.prototype)}};VS=zS=sa([cm({type:Cy.Set,itemType:wb})],VS);class qS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=yb.v0,this.digestAlgorithms=new VS,this.encapContentInfo=new dS,this.signerInfos=new Tb,Object.assign(this,e)}}sa([dm({type:Iy.Integer})],qS.prototype,"version",void 0),sa([dm({type:VS})],qS.prototype,"digestAlgorithms",void 0),sa([dm({type:dS})],qS.prototype,"encapContentInfo",void 0),sa([dm({type:lS,context:0,implicit:!0,optional:!0})],qS.prototype,"certificates",void 0),sa([dm({type:LS,context:1,implicit:!0,optional:!0})],qS.prototype,"crls",void 0),sa([dm({type:Tb})],qS.prototype,"signerInfos",void 0);var HS="1.2.840.10045.2.1",KS="1.2.840.10045.4.1",WS="1.2.840.10045.4.3.1",GS="1.2.840.10045.4.3.2",QS="1.2.840.10045.4.3.3",YS="1.2.840.10045.4.3.4",JS="1.2.840.10045.3.1.7",ZS="1.3.132.0.34",$S="1.3.132.0.35";function XS(e){return new nb({algorithm:e})}var eE=XS(KS);XS(WS);var tE=XS(GS),rE=XS(QS),nE=XS(YS),iE=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};sa([dm({type:Iy.ObjectIdentifier})],iE.prototype,"fieldType",void 0),sa([dm({type:Iy.Any})],iE.prototype,"parameters",void 0),iE=sa([cm({type:Cy.Sequence})],iE);var oE,aE=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};sa([dm({type:Iy.OctetString})],aE.prototype,"a",void 0),sa([dm({type:Iy.OctetString})],aE.prototype,"b",void 0),sa([dm({type:Iy.BitString,optional:!0})],aE.prototype,"seed",void 0),aE=sa([cm({type:Cy.Sequence})],aE),function(e){e[e.ecpVer1=1]="ecpVer1"}(oE||(oE={}));var sE=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=oE.ecpVer1,Object.assign(this,e)}};sa([dm({type:Iy.Integer})],sE.prototype,"version",void 0),sa([dm({type:iE})],sE.prototype,"fieldID",void 0),sa([dm({type:aE})],sE.prototype,"curve",void 0),sa([dm({type:class extends _y{}})],sE.prototype,"base",void 0),sa([dm({type:Iy.Integer,converter:Ry})],sE.prototype,"order",void 0),sa([dm({type:Iy.Integer,optional:!0})],sE.prototype,"cofactor",void 0),sE=sa([cm({type:Cy.Sequence})],sE);var lE=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};sa([dm({type:Iy.ObjectIdentifier})],lE.prototype,"namedCurve",void 0),sa([dm({type:Iy.Null})],lE.prototype,"implicitCurve",void 0),sa([dm({type:sE})],lE.prototype,"specifiedCurve",void 0),lE=sa([cm({type:Cy.Choice})],lE);class uE{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=1,this.privateKey=new _y,Object.assign(this,e)}}sa([dm({type:Iy.Integer})],uE.prototype,"version",void 0),sa([dm({type:_y})],uE.prototype,"privateKey",void 0),sa([dm({type:lE,context:0,optional:!0})],uE.prototype,"parameters",void 0),sa([dm({type:Iy.BitString,context:1,optional:!0})],uE.prototype,"publicKey",void 0);class cE{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)}}sa([dm({type:Iy.Integer,converter:Ry})],cE.prototype,"r",void 0),sa([dm({type:Iy.Integer,converter:Ry})],cE.prototype,"s",void 0);var dE="1.2.840.113549.1.1",hE="".concat(dE,".1"),vE="".concat(dE,".7"),pE="".concat(dE,".9"),fE="".concat(dE,".10"),gE="".concat(dE,".2"),yE="".concat(dE,".4"),mE="".concat(dE,".5"),wE="".concat(dE,".14"),bE="".concat(dE,".11"),SE="".concat(dE,".12"),EE="".concat(dE,".13"),kE="".concat(dE,".15"),xE="".concat(dE,".16"),AE="1.3.14.3.2.26",CE="2.16.840.1.101.3.4.2.4",IE="2.16.840.1.101.3.4.2.1",TE="2.16.840.1.101.3.4.2.2",PE="2.16.840.1.101.3.4.2.3",_E="".concat(dE,".8");function BE(e){return new nb({algorithm:e,parameters:null})}BE("1.2.840.113549.2.2"),BE("1.2.840.113549.2.5");var NE=BE(AE);BE(CE),BE(IE),BE(TE),BE(PE),BE("2.16.840.1.101.3.4.2.5"),BE("2.16.840.1.101.3.4.2.6");var DE,RE=new nb({algorithm:_E,parameters:gm.serialize(NE)}),OE=new nb({algorithm:pE,parameters:gm.serialize(Uy.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});BE(hE),BE(gE),BE(yE),BE(mE),BE(kE),BE(xE),BE(SE),BE(EE),BE(kE),BE(xE);class LE{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.hashAlgorithm=new nb(NE),this.maskGenAlgorithm=new nb({algorithm:_E,parameters:gm.serialize(NE)}),this.pSourceAlgorithm=new nb(OE),Object.assign(this,e)}}sa([dm({type:nb,context:0,defaultValue:NE})],LE.prototype,"hashAlgorithm",void 0),sa([dm({type:nb,context:1,defaultValue:RE})],LE.prototype,"maskGenAlgorithm",void 0),sa([dm({type:nb,context:2,defaultValue:OE})],LE.prototype,"pSourceAlgorithm",void 0),new nb({algorithm:vE,parameters:gm.serialize(new LE)});class ME{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.hashAlgorithm=new nb(NE),this.maskGenAlgorithm=new nb({algorithm:_E,parameters:gm.serialize(NE)}),this.saltLength=20,this.trailerField=1,Object.assign(this,e)}}sa([dm({type:nb,context:0,defaultValue:NE})],ME.prototype,"hashAlgorithm",void 0),sa([dm({type:nb,context:1,defaultValue:RE})],ME.prototype,"maskGenAlgorithm",void 0),sa([dm({type:Iy.Integer,context:2,defaultValue:20})],ME.prototype,"saltLength",void 0),sa([dm({type:Iy.Integer,context:3,defaultValue:1})],ME.prototype,"trailerField",void 0),new nb({algorithm:fE,parameters:gm.serialize(new ME)});class UE{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.digestAlgorithm=new nb,this.digest=new _y,Object.assign(this,e)}}sa([dm({type:nb})],UE.prototype,"digestAlgorithm",void 0),sa([dm({type:_y})],UE.prototype,"digest",void 0);class FE{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)}}sa([dm({type:Iy.Integer,converter:Ry})],FE.prototype,"prime",void 0),sa([dm({type:Iy.Integer,converter:Ry})],FE.prototype,"exponent",void 0),sa([dm({type:Iy.Integer,converter:Ry})],FE.prototype,"coefficient",void 0);var zE,jE=DE=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,DE.prototype)}};jE=DE=sa([cm({type:Cy.Sequence,itemType:FE})],jE);class VE{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)}}sa([dm({type:Iy.Integer})],VE.prototype,"version",void 0),sa([dm({type:Iy.Integer,converter:Ry})],VE.prototype,"modulus",void 0),sa([dm({type:Iy.Integer,converter:Ry})],VE.prototype,"publicExponent",void 0),sa([dm({type:Iy.Integer,converter:Ry})],VE.prototype,"privateExponent",void 0),sa([dm({type:Iy.Integer,converter:Ry})],VE.prototype,"prime1",void 0),sa([dm({type:Iy.Integer,converter:Ry})],VE.prototype,"prime2",void 0),sa([dm({type:Iy.Integer,converter:Ry})],VE.prototype,"exponent1",void 0),sa([dm({type:Iy.Integer,converter:Ry})],VE.prototype,"exponent2",void 0),sa([dm({type:Iy.Integer,converter:Ry})],VE.prototype,"coefficient",void 0),sa([dm({type:jE,optional:!0})],VE.prototype,"otherPrimeInfos",void 0);class qE{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)}}sa([dm({type:Iy.Integer,converter:Ry})],qE.prototype,"modulus",void 0),sa([dm({type:Iy.Integer,converter:Ry})],qE.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"}(zE||(zE={}));var HE=zE;function KE(e){return!!e.useClass}function WE(e){return!!e.useFactory}var GE=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,ha(t))}})),t},e}();function QE(e){return"string"==typeof e||"symbol"==typeof e}function YE(e){return"object"==typeof e&&"token"in e&&"transform"in e}function JE(e){return!!e.useToken}function ZE(e){return null!=e.useValue}var $E=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}(),XE=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return aa(t,e),t}($E),ek=function(){this.scopedResolutions=new Map};function tk(e,t,r){var n,i,o=da(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=" "),ha([n],r.message.split("\n").map((function(e){return i+e}))).join("\n")}var rk,nk=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return aa(t,e),t}($E),ik=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return aa(t,e),t}($E),ok=function(){this.preResolution=new nk,this.postResolution=new ik},ak=new Map,sk=function(){function e(e){this.parent=e,this._registry=new XE,this.interceptors=new ok,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,r){var n;if(void 0===r&&(r={lifecycle:HE.Transient}),this.ensureNotDisposed(),n=function(e){return KE(e)||ZE(e)||JE(e)||WE(e)}(t)?t:{useClass:t},JE(n))for(var i=[e],o=n;null!=o;){var a=o.useToken;if(i.includes(a))throw new Error("Token registration cycle detected! "+ha(i,[a]).join(" -> "));i.push(a);var s=this._registry.get(a);o=s&&JE(s.provider)?s.provider:null}if((r.lifecycle===HE.Singleton||r.lifecycle==HE.ContainerScoped||r.lifecycle==HE.ResolutionScoped)&&(ZE(n)||WE(n)))throw new Error('Cannot use lifecycle "'+HE[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(),QE(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(),QE(e)){if(QE(t))return this.register(e,{useToken:t},{lifecycle:HE.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:HE.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var r=e;return t&&!QE(t)&&(r=t),this.register(e,{useClass:r},{lifecycle:HE.Singleton})},e.prototype.resolve=function(e,t,r){void 0===t&&(t=new ek),void 0===r&&(r=!1),this.ensureNotDisposed();var n=this.getRegistration(e);if(!n&&QE(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 GE}(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=ca(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=ca(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===HE.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var r,n=e.options.lifecycle===HE.Singleton,i=e.options.lifecycle===HE.ContainerScoped,o=n||i;return r=ZE(e.provider)?e.provider.useValue:JE(e.provider)?o?e.instance||(e.instance=this.resolve(e.provider.useToken,t)):this.resolve(e.provider.useToken,t):KE(e.provider)?o?e.instance||(e.instance=this.construct(e.provider.useClass,t)):this.construct(e.provider.useClass,t):WE(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t),e.options.lifecycle===HE.ResolutionScoped&&t.scopedResolutions.set(e,r),r},e.prototype.resolveAll=function(e,t,r){var n=this;void 0===t&&(t=new ek),void 0===r&&(r=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&QE(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=ca(this._registry.entries()),n=r.next();!n.done;n=r.next()){var i=da(n.value,2),o=i[0],a=i[1];this._registry.setAll(o,a.filter((function(e){return!ZE(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=ca(this._registry.entries()),o=i.next();!o.done;o=i.next()){var a=da(o.value,2),s=a[0],l=a[1];l.some((function(e){return e.options.lifecycle===HE.ContainerScoped}))&&n._registry.setAll(s,l.map((function(e){return e.options.lifecycle===HE.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 la(this,void 0,void 0,(function(){var e;return ua(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 GE)return e.createProxy((function(e){return r.resolve(e,t)}));var n,i=function(){var n=ak.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,ha([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?YE(n)?n.multiple?(o=r.resolve(n.transform)).transform.apply(o,ha([r.resolveAll(n.token,new ek,n.isOptional)],n.transformArgs)):(a=r.resolve(n.transform)).transform.apply(a,ha([r.resolve(n.token,e,n.isOptional)],n.transformArgs)):n.multiple?r.resolveAll(n.token,new ek,n.isOptional):r.resolve(n.token,e,n.isOptional):YE(n)?(s=r.resolve(n.transform,e)).transform.apply(s,ha([r.resolve(n.token,e)],n.transformArgs)):r.resolve(n,e)}catch(e){throw new Error(tk(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}(),lk=new sk;function uk(e){return function(e){ak.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 ck{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.attrId="",this.attrValues=[],Object.assign(e)}}sa([dm({type:Iy.ObjectIdentifier})],ck.prototype,"attrId",void 0),sa([dm({type:Iy.Any,repeated:"set"})],ck.prototype,"attrValues",void 0);var dk,hk=rk=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,rk.prototype)}};hk=rk=sa([cm({type:Cy.Sequence,itemType:ck})],hk);var vk=dk=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,dk.prototype)}};vk=dk=sa([cm({type:Cy.Sequence,itemType:uS})],vk);class pk{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.certId="",this.certValue=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier})],pk.prototype,"certId",void 0),sa([dm({type:Iy.Any,context:0})],pk.prototype,"certValue",void 0);class fk{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.crlId="",this.crltValue=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier})],fk.prototype,"crlId",void 0),sa([dm({type:Iy.Any,context:0})],fk.prototype,"crltValue",void 0);class gk extends _y{}let yk=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.encryptionAlgorithm=new nb,this.encryptedData=new gk,Object.assign(this,e)}};var mk,wk;sa([dm({type:nb})],yk.prototype,"encryptionAlgorithm",void 0),sa([dm({type:gk})],yk.prototype,"encryptedData",void 0),function(e){e[e.v1=0]="v1"}(wk||(wk={}));class bk extends _y{}var Sk=mk=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,mk.prototype)}};Sk=mk=sa([cm({type:Cy.Sequence,itemType:Ww})],Sk);class Ek{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=wk.v1,this.privateKeyAlgorithm=new nb,this.privateKey=new bk,Object.assign(this,e)}}sa([dm({type:Iy.Integer})],Ek.prototype,"version",void 0),sa([dm({type:nb})],Ek.prototype,"privateKeyAlgorithm",void 0),sa([dm({type:bk})],Ek.prototype,"privateKey",void 0),sa([dm({type:Sk,implicit:!0,context:0,optional:!0})],Ek.prototype,"attributes",void 0);var kk=class extends Ek{};kk=sa([cm({type:Cy.Sequence})],kk);var xk,Ak=class extends yk{};Ak=sa([cm({type:Cy.Sequence})],Ak);class Ck{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.secretTypeId="",this.secretValue=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier})],Ck.prototype,"secretTypeId",void 0),sa([dm({type:Iy.Any,context:0})],Ck.prototype,"secretValue",void 0);class Ik{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.mac=new UE,this.macSalt=new _y,this.iterations=1,Object.assign(this,e)}}sa([dm({type:UE})],Ik.prototype,"mac",void 0),sa([dm({type:_y})],Ik.prototype,"macSalt",void 0),sa([dm({type:Iy.Integer,defaultValue:1})],Ik.prototype,"iterations",void 0);class Tk{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=3,this.authSafe=new uS,this.macData=new Ik,Object.assign(this,e)}}sa([dm({type:Iy.Integer})],Tk.prototype,"version",void 0),sa([dm({type:uS})],Tk.prototype,"authSafe",void 0),sa([dm({type:Ik,optional:!0})],Tk.prototype,"macData",void 0);class Pk{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.bagId="",this.bagValue=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:Iy.ObjectIdentifier})],Pk.prototype,"bagId",void 0),sa([dm({type:Iy.Any,context:0})],Pk.prototype,"bagValue",void 0),sa([dm({type:ck,repeated:"set",optional:!0})],Pk.prototype,"bagAttributes",void 0);var _k,Bk,Nk,Dk=xk=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,xk.prototype)}};Dk=xk=sa([cm({type:Cy.Sequence,itemType:Pk})],Dk);var Rk="1.2.840.113549.1.9",Ok="".concat(Rk,".7"),Lk="".concat(Rk,".14"),Mk=class extends mm{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{})}toString(){return this.ia5String||super.toString()}};sa([dm({type:Iy.IA5String})],Mk.prototype,"ia5String",void 0),Mk=sa([cm({type:Cy.Choice})],Mk);var Uk=class extends uS{};Uk=sa([cm({type:Cy.Sequence})],Uk);var Fk=class extends Tk{};Fk=sa([cm({type:Cy.Sequence})],Fk);var zk=class extends yk{};zk=sa([cm({type:Cy.Sequence})],zk);var jk=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.value=e}toString(){return this.value}};sa([dm({type:Iy.IA5String})],jk.prototype,"value",void 0),jk=sa([cm({type:Cy.Choice})],jk);var Vk=class extends Mk{};Vk=sa([cm({type:Cy.Choice})],Vk);var qk=class extends mm{};qk=sa([cm({type:Cy.Choice})],qk);var Hk=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Date;this.value=e}};sa([dm({type:Iy.GeneralizedTime})],Hk.prototype,"value",void 0),Hk=sa([cm({type:Cy.Choice})],Hk);var Kk=class extends mm{};Kk=sa([cm({type:Cy.Choice})],Kk);var Wk=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"M";this.value=e}toString(){return this.value}};sa([dm({type:Iy.PrintableString})],Wk.prototype,"value",void 0),Wk=sa([cm({type:Cy.Choice})],Wk);var Gk=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.value=e}toString(){return this.value}};sa([dm({type:Iy.PrintableString})],Gk.prototype,"value",void 0),Gk=sa([cm({type:Cy.Choice})],Gk);var Qk=class extends Gk{};Qk=sa([cm({type:Cy.Choice})],Qk);var Yk=class extends mm{};Yk=sa([cm({type:Cy.Choice})],Yk);var Jk=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.value=e}toString(){return this.value}};sa([dm({type:Iy.ObjectIdentifier})],Jk.prototype,"value",void 0),Jk=sa([cm({type:Cy.Choice})],Jk);var Zk=class extends ab{};Zk=sa([cm({type:Cy.Choice})],Zk);var $k=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.value=e}toString(){return this.value.toString()}};sa([dm({type:Iy.Integer})],$k.prototype,"value",void 0),$k=sa([cm({type:Cy.Choice})],$k);var Xk=class extends Ib{};Xk=sa([cm({type:Cy.Sequence})],Xk);var ex=class extends mm{};ex=sa([cm({type:Cy.Choice})],ex);var tx=_k=class extends cb{constructor(e){super(e),Object.setPrototypeOf(this,_k.prototype)}};tx=_k=sa([cm({type:Cy.Sequence})],tx);var rx=Bk=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,Bk.prototype)}};rx=Bk=sa([cm({type:Cy.Set,itemType:Ab})],rx);var nx=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.value=e}toString(){return this.value}};sa([dm({type:Iy.BmpString})],nx.prototype,"value",void 0),nx=sa([cm({type:Cy.Choice})],nx);var ix=class extends nb{};ix=sa([cm({type:Cy.Sequence})],ix);var ox,ax=Nk=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,Nk.prototype)}};ax=Nk=sa([cm({type:Cy.Sequence,itemType:ix})],ax);var sx=ox=class extends fm{constructor(e){super(e),Object.setPrototypeOf(this,ox.prototype)}};sx=ox=sa([cm({type:Cy.Sequence,itemType:Ww})],sx);class lx{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=0,this.subject=new km,this.subjectPKInfo=new ib,this.attributes=new sx,Object.assign(this,e)}}sa([dm({type:Iy.Integer})],lx.prototype,"version",void 0),sa([dm({type:km})],lx.prototype,"subject",void 0),sa([dm({type:ib})],lx.prototype,"subjectPKInfo",void 0),sa([dm({type:sx,implicit:!0,context:0})],lx.prototype,"attributes",void 0);class ux{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.certificationRequestInfo=new lx,this.signatureAlgorithm=new nb,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}sa([dm({type:lx})],ux.prototype,"certificationRequestInfo",void 0),sa([dm({type:nb})],ux.prototype,"signatureAlgorithm",void 0),sa([dm({type:Iy.BitString})],ux.prototype,"signature",void 0);var cx="crypto.algorithm";var dx,hx="crypto.algorithmProvider";lk.registerSingleton(hx,class{getAlgorithms(){return lk.resolveAll(cx)}toAsnAlgorithm(e){for(var r of(t({},e),this.getAlgorithms())){var n=r.toAsnAlgorithm(e);if(n)return n}if(/^[0-9.]+$/.test(e.name)){var i=new nb({algorithm:e.name});if("parameters"in e){var o=e;i.parameters=o.parameters}return i}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(var t of this.getAlgorithms()){var r=t.toWebAlgorithm(e);if(r)return r}return{name:e.algorithm,parameters:e.parameters}}});var vx="1.3.36.3.3.2.8.1.1",px="".concat(vx,".1"),fx="".concat(vx,".2"),gx="".concat(vx,".3"),yx="".concat(vx,".4"),mx="".concat(vx,".5"),wx="".concat(vx,".6"),bx="".concat(vx,".7"),Sx="".concat(vx,".8"),Ex="".concat(vx,".9"),kx="".concat(vx,".10"),xx="".concat(vx,".11"),Ax="".concat(vx,".12"),Cx="".concat(vx,".13"),Ix="".concat(vx,".14"),Tx="brainpoolP160r1",Px="brainpoolP160t1",_x="brainpoolP192r1",Bx="brainpoolP192t1",Nx="brainpoolP224r1",Dx="brainpoolP224t1",Rx="brainpoolP256r1",Ox="brainpoolP256t1",Lx="brainpoolP320r1",Mx="brainpoolP320t1",Ux="brainpoolP384r1",Fx="brainpoolP384t1",zx="brainpoolP512r1",jx="brainpoolP512t1",Vx="ECDSA",qx=dx=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===Vx.toLowerCase())if("hash"in e)switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return eE;case"sha-256":return tE;case"sha-384":return rE;case"sha-512":return nE}else if("namedCurve"in e){var t="";switch(e.namedCurve){case"P-256":t=JS;break;case"K-256":t=dx.SECP256K1;break;case"P-384":t=ZS;break;case"P-521":t=$S;break;case Tx:t=px;break;case Px:t=fx;break;case _x:t=gx;break;case Bx:t=yx;break;case Nx:t=mx;break;case Dx:t=wx;break;case Rx:t=bx;break;case Ox:t=Sx;break;case Lx:t=Ex;break;case Mx:t=kx;break;case Ux:t=xx;break;case Fx:t=Ax;break;case zx:t=Cx;break;case jx:t=Ix}if(t)return new nb({algorithm:HS,parameters:gm.serialize(new lE({namedCurve:t}))})}return null}toWebAlgorithm(e){switch(e.algorithm){case KS:return{name:Vx,hash:{name:"SHA-1"}};case GS:return{name:Vx,hash:{name:"SHA-256"}};case QS:return{name:Vx,hash:{name:"SHA-384"}};case YS:return{name:Vx,hash:{name:"SHA-512"}};case HS:if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(gm.parse(e.parameters,lE).namedCurve){case JS:return{name:Vx,namedCurve:"P-256"};case dx.SECP256K1:return{name:Vx,namedCurve:"K-256"};case ZS:return{name:Vx,namedCurve:"P-384"};case $S:return{name:Vx,namedCurve:"P-521"};case px:return{name:Vx,namedCurve:Tx};case fx:return{name:Vx,namedCurve:Px};case gx:return{name:Vx,namedCurve:_x};case yx:return{name:Vx,namedCurve:Bx};case mx:return{name:Vx,namedCurve:Nx};case wx:return{name:Vx,namedCurve:Dx};case bx:return{name:Vx,namedCurve:Rx};case Sx:return{name:Vx,namedCurve:Ox};case Ex:return{name:Vx,namedCurve:Lx};case kx:return{name:Vx,namedCurve:Mx};case xx:return{name:Vx,namedCurve:Ux};case Ax:return{name:Vx,namedCurve:Fx};case Cx:return{name:Vx,namedCurve:zx};case Ix:return{name:Vx,namedCurve:jx}}}return null}};qx.SECP256K1="1.3.132.0.10",qx=dx=sa([uk()],qx),lk.registerSingleton(cx,qx);var Hx,Kx=Symbol("name"),Wx=Symbol("value");class Gx{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[Kx]=e,this[Wx]=r,t)this[n]=t[n]}}Gx.NAME=Kx,Gx.VALUE=Wx;class Qx{static toString(e){var t=this.items[e];return t||e}}Qx.items={[AE]:"sha1",[CE]:"sha224",[IE]:"sha256",[TE]:"sha384",[PE]:"sha512",[hE]:"rsaEncryption",[mE]:"sha1WithRSAEncryption",[wE]:"sha224WithRSAEncryption",[bE]:"sha256WithRSAEncryption",[SE]:"sha384WithRSAEncryption",[EE]:"sha512WithRSAEncryption",[HS]:"ecPublicKey",[KS]:"ecdsaWithSHA1",[WS]:"ecdsaWithSHA224",[GS]:"ecdsaWithSHA256",[QS]:"ecdsaWithSHA384",[YS]:"ecdsaWithSHA512",[Ew]:"TLS WWW server authentication",[kw]:"TLS WWW client authentication",[xw]:"Code Signing",[Aw]:"E-mail Protection",[Cw]:"Time Stamping",[Iw]:"OCSP Signing",[jS]:"Signed Data"};class Yx{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[Gx.VALUE];for(var a in o&&(i=" ".concat(o)),r.push("".concat(n).concat(e[Gx.NAME],":").concat(i)),n=this.pad(t),e)if("symbol"!=typeof a){var s=e[a],l=a?"".concat(a,": "):"";if("string"==typeof s||"number"==typeof s||"boolean"==typeof s)r.push("".concat(n).concat(l).concat(s));else if(s instanceof Date)r.push("".concat(n).concat(l).concat(s.toUTCString()));else if(Array.isArray(s))for(var u of s)u[Gx.NAME]=a,r.push(...this.serializeObj(u,t));else if(s instanceof Gx)s[Gx.NAME]=a,r.push(...this.serializeObj(s,t));else if(Yp.BufferSourceConverter.isBufferSource(s))a?(r.push("".concat(n).concat(l)),r.push(...this.serializeBufferSource(s,t+1))):r.push(...this.serializeBufferSource(s,t));else{if(!("toTextObject"in s))throw new TypeError("Cannot serialize data in text format. Unsupported type.");var c=s.toTextObject();c[Gx.NAME]=a,r.push(...this.serializeObj(c,t))}}return r}static serializeBufferSource(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=this.pad(t),n=Yp.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)}}Yx.oidSerializer=Qx,Yx.algorithmSerializer=class{static toTextObject(e){var t=new Gx("Algorithm Identifier",{},Qx.toString(e.algorithm));if(e.parameters)if(e.algorithm===HS){var r=(new qx).toWebAlgorithm(e);r&&"namedCurve"in r?t["Named Curve"]=r.namedCurve:t.Parameters=e.parameters}else t.Parameters=e.parameters;return t}};class Jx{constructor(){if(1===arguments.length){var e=arguments.length<=0?void 0:arguments[0];this.rawData=gm.serialize(e),this.onInit(e)}else{var t=gm.parse(arguments.length<=0?void 0:arguments[0],arguments.length<=1?void 0:arguments[1]);this.rawData=Yp.BufferSourceConverter.toArrayBuffer(arguments.length<=0?void 0:arguments[0]),this.onInit(t)}}equal(e){return e instanceof Jx&&Yp.isEqual(e.rawData,this.rawData)}toString(){switch(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"text"){case"asn":return gm.toString(this.rawData);case"text":return Yx.serialize(this.toTextObject());case"hex":return Yp.Convert.ToHex(this.rawData);case"base64":return Yp.Convert.ToBase64(this.rawData);case"base64url":return Yp.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 Gx(this.getTextName(),{},e)}}Jx.NAME="ASN";class Zx extends Jx{constructor(){super(Yp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])?Yp.BufferSourceConverter.toArrayBuffer(arguments.length<=0?void 0:arguments[0]):gm.serialize(new lb({extnID:arguments.length<=0?void 0:arguments[0],critical:arguments.length<=1?void 0:arguments[1],extnValue:new _y(Yp.BufferSourceConverter.toArrayBuffer(arguments.length<=2?void 0:arguments[2]))})),lb)}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[Gx.NAME]===Zx.NAME&&(e[Gx.NAME]=Qx.toString(this.type)),e}}class $x{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[Hx]="CryptoProvider","undefined"!=typeof self&&"undefined"!=typeof crypto?this.set($x.DEFAULT,crypto):"undefined"!=typeof global&&global.crypto&&global.crypto.subtle&&this.set($x.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]:$x.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($x.DEFAULT,e);return this}}Hx=Symbol.toStringTag,$x.DEFAULT="default";var Xx=new $x,eA=/^[0-2](?:\.[1-9][0-9]*)+$/;class tA{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(eA).test(t)?e:this.get(e);var t}register(e,t){this.items[e]=t,this.items[t]=e}}var rA=new tA;function nA(e,t){return"\\".concat(Yp.Convert.ToHex(Yp.Convert.FromUtf8String(t)).toUpperCase())}rA.register("CN","2.5.4.3"),rA.register("L","2.5.4.7"),rA.register("ST","2.5.4.8"),rA.register("O","2.5.4.10"),rA.register("OU","2.5.4.11"),rA.register("C","2.5.4.6"),rA.register("DC","0.9.2342.19200300.100.1.25"),rA.register("E","1.2.840.113549.1.9.1"),rA.register("G","2.5.4.42"),rA.register("I","2.5.4.43"),rA.register("SN","2.5.4.4"),rA.register("T","2.5.4.12");class iA{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 tA,this.asn=new km,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 km?this.asn=e:Yp.BufferSourceConverter.isBufferSource(e)?this.asn=gm.parse(e,km):this.asn=this.fromJSON(e)}getField(e){var t=this.extraNames.findId(e)||rA.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)||rA.get(e)}toString(){return this.asn.map((e=>e.map((e=>{var t=this.getName(e.type)||e.type,r=e.value.anyValue?"#".concat(Yp.Convert.ToHex(e.value.anyValue)):e.value.toString().replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,nA);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(Yp.Convert.ToHex(i.value.anyValue)):i.value.toString())}t.push(n)}return t}fromString(e){for(var t=new km,r=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g,n=null,i=",";n=r.exec("".concat(e,","));){var[,o,a]=n,s=a[a.length-1];","!==s&&"+"!==s||(a=a.slice(0,a.length-1),n[3]=s);var l=n[3];o=this.getTypeOid(o);var u=this.createAttribute(o,a);"+"===i?t[t.length-1].push(u):t.push(new Sm([u])),i=l}return t}fromJSON(e){var t=new km;for(var r of e){var n=new Sm;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 bm({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=Yp.Convert.FromHex(t.slice(1));else{var i=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=i:iA.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 gm.serialize(this.asn)}getThumbprint(){var e=arguments,t=this;return r((function*(){var r,n,i="SHA-1";return e.length>=1&&!(null===(r=e.length<=0?void 0:e[0])||void 0===r?void 0:r.subtle)?(i=(e.length<=0?void 0:e[0])||i,n=(e.length<=1?void 0:e[1])||Xx.get()):n=(e.length<=0?void 0:e[0])||Xx.get(),yield n.subtle.digest(i,t.toArrayBuffer())}))()}}var oA="Cannot initialize GeneralName from ASN.1 data.",aA="".concat(oA," Unsupported string format in use."),sA="".concat(oA," Value doesn't match to GUID regular expression."),lA=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,uA="1.3.6.1.4.1.311.25.1",cA="1.3.6.1.4.1.311.20.2.3",dA="dns",hA="dn",vA="email",pA="ip",fA="url",gA="guid",yA="upn",mA="id";class wA extends Jx{constructor(){var e;if(2===arguments.length)switch(arguments.length<=0?void 0:arguments[0]){case hA:var t=new iA(arguments.length<=1?void 0:arguments[1]).toArrayBuffer(),r=gm.parse(t,km);e=new Im({directoryName:r});break;case dA:e=new Im({dNSName:arguments.length<=1?void 0:arguments[1]});break;case vA:e=new Im({rfc822Name:arguments.length<=1?void 0:arguments[1]});break;case gA:var n=new RegExp(lA,"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?Yp.Convert.ToHex(new Uint8Array(Yp.Convert.FromHex(e)).reverse()):e)).join("");e=new Im({otherName:new Am({typeId:uA,value:gm.serialize(new _y(Yp.Convert.FromHex(i)))})});break;case pA:e=new Im({iPAddress:arguments.length<=1?void 0:arguments[1]});break;case mA:e=new Im({registeredID:arguments.length<=1?void 0:arguments[1]});break;case yA:e=new Im({otherName:new Am({typeId:cA,value:gm.serialize(jy.toASN(arguments.length<=1?void 0:arguments[1]))})});break;case fA:e=new Im({uniformResourceIdentifier:arguments.length<=1?void 0:arguments[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else e=Yp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])?gm.parse(arguments.length<=0?void 0:arguments[0],Im):arguments.length<=0?void 0:arguments[0];super(e)}onInit(e){if(null!=e.dNSName)this.type=dA,this.value=e.dNSName;else if(null!=e.rfc822Name)this.type=vA,this.value=e.rfc822Name;else if(null!=e.iPAddress)this.type=pA,this.value=e.iPAddress;else if(null!=e.uniformResourceIdentifier)this.type=fA,this.value=e.uniformResourceIdentifier;else if(null!=e.registeredID)this.type=mA,this.value=e.registeredID;else if(null!=e.directoryName)this.type=hA,this.value=new iA(e.directoryName).toString();else{if(null==e.otherName)throw new Error(aA);if(e.otherName.typeId===uA){this.type=gA;var t=gm.parse(e.otherName.value,_y),r=new RegExp(lA,"i").exec(Yp.Convert.ToHex(t));if(!r)throw new Error(sA);this.value=r.slice(1).map(((e,t)=>t<3?Yp.Convert.ToHex(new Uint8Array(Yp.Convert.FromHex(e)).reverse()):e)).join("-")}else{if(e.otherName.typeId!==cA)throw new Error(aA);this.type=yA,this.value=gm.parse(e.otherName.value,mm).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){var e;switch(this.type){case hA:case dA:case gA:case pA:case mA:case yA:case fA:e=this.type.toUpperCase();break;case vA:e="Email";break;default:throw new Error("Unsupported GeneralName type")}var t=this.value;return this.type===mA&&(t=Qx.toString(t)),new Gx(e,void 0,t)}}class bA extends Jx{constructor(e){var t;if(e instanceof Qm)t=e;else if(Array.isArray(e)){var r=[];for(var n of e)if(n instanceof Im)r.push(n);else{var i=gm.parse(new wA(n.type,n.value).rawData,Im);r.push(i)}t=new Qm(r)}else{if(!Yp.BufferSourceConverter.isBufferSource(e))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");t=gm.parse(e,Qm)}super(t)}onInit(e){var t=[];for(var r of e){var n=null;try{n=new wA(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[Gx.NAME]];Array.isArray(n)||(n=[],e[r[Gx.NAME]]=n),n.push(r)}return e}}bA.NAME="GeneralNames";var SA,EA,kA="-{5}",xA="\\n",AA="[^".concat(xA,"]+"),CA="".concat(kA,"BEGIN (").concat(AA,"(?=").concat(kA,"))").concat(kA),IA="".concat(kA,"END \\1").concat(kA),TA="\\n",PA="[^:".concat(xA,"]+"),_A="(?:[^".concat(xA,"]+").concat(TA,"(?: +[^").concat(xA,"]+").concat(TA,")*)"),BA="(?:".concat("[a-zA-Z0-9=+/]+").concat(TA,")+"),NA="".concat(CA).concat(TA,"(?:((?:").concat(PA,": ").concat(_A,")+))?").concat(TA,"?(").concat(BA,")").concat(IA);class DA{static isPem(e){return"string"==typeof e&&new RegExp(NA,"g").test(e)}static decodeWithHeaders(e){e=e.replace(/\r/g,"");for(var t=new RegExp(NA,"g"),r=[],n=null;n=t.exec(e);){var i=n[3].replace(new RegExp("[".concat(xA,"]+"),"g"),""),o={type:n[1],headers:[],rawData:Yp.Convert.FromBase64(i)},a=n[2];if(a){var s=a.split(new RegExp(TA,"g")),l=null;for(var u of s){var[c,d]=u.split(/:(.*)/);if(void 0===d){if(!l)throw new Error("Cannot parse PEM string. Incorrect header value");l.value+=c.trim()}else l&&o.headers.push(l),l={key:c,value:d.trim()}}l&&o.headers.push(l)}r.push(o)}return r}static decode(e){return this.decodeWithHeaders(e).map((e=>e.rawData))}static decodeFirst(e){var t=this.decode(e);if(!t.length)throw new RangeError("PEM string doesn't contain any objects");return t[0]}static encode(e,t){if(Array.isArray(e)){var r=new Array;return t?e.forEach((e=>{if(!Yp.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:Yp.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:Yp.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=Yp.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")}}DA.CertificateTag="CERTIFICATE",DA.CrlTag="CRL",DA.CertificateRequestTag="CERTIFICATE REQUEST",DA.PublicKeyTag="PUBLIC KEY",DA.PrivateKeyTag="PRIVATE KEY";class RA extends Jx{static isAsnEncoded(e){return Yp.BufferSourceConverter.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e){if(DA.isPem(e))return DA.decode(e)[0];if(Yp.Convert.isHex(e))return Yp.Convert.FromHex(e);if(Yp.Convert.isBase64(e))return Yp.Convert.FromBase64(e);if(Yp.Convert.isBase64Url(e))return Yp.Convert.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}var t=Yp.Convert.ToBinary(e);return DA.isPem(t)?DA.decode(t)[0]:Yp.Convert.isHex(t)?Yp.Convert.FromHex(t):Yp.Convert.isBase64(t)?Yp.Convert.FromBase64(t):Yp.Convert.isBase64Url(t)?Yp.Convert.FromBase64Url(t):Yp.BufferSourceConverter.toArrayBuffer(e)}constructor(){RA.isAsnEncoded(arguments.length<=0?void 0:arguments[0])?super(RA.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?DA.encode(this.rawData,this.tag):super.toString(e)}}class OA extends RA{static create(e){var t=arguments;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:Xx.get();if(e instanceof OA)return e;if($x.isCryptoKey(e)){if("public"!==e.type)throw new TypeError("Public key is required");var n=yield r.subtle.exportKey("spki",e);return new OA(n)}if(e.publicKey)return e.publicKey;if(Yp.BufferSourceConverter.isBufferSource(e))return new OA(e);throw new TypeError("Unsupported PublicKeyType")}))()}constructor(e){RA.isAsnEncoded(e)?super(e,ib):super(e),this.tag=DA.PublicKeyTag}export(){var e=arguments,n=this;return r((function*(){var r,i=["verify"],o=t({hash:"SHA-256"},n.algorithm);e.length>1?(o=(e.length<=0?void 0:e[0])||o,i=(e.length<=1?void 0:e[1])||i,r=(e.length<=2?void 0:e[2])||Xx.get()):r=(e.length<=0?void 0:e[0])||Xx.get();var a=n.rawData,s=gm.parse(n.rawData,ib);return s.algorithm.algorithm===fE&&(a=function(e,t){return e.algorithm=new nb({algorithm:hE,parameters:null}),t=gm.serialize(e),t}(s,a)),r.subtle.importKey("spki",a,o,!0,i)}))()}onInit(e){var t=lk.resolve(hx),r=this.algorithm=t.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===hE){var n=gm.parse(e.subjectPublicKey,qE),i=Yp.BufferSourceConverter.toUint8Array(n.modulus);r.publicExponent=Yp.BufferSourceConverter.toUint8Array(n.publicExponent),r.modulusLength=(i[0]?i:i.slice(1)).byteLength<<3}}getThumbprint(){var e=arguments,t=this;return r((function*(){var r,n,i="SHA-1";return e.length>=1&&!(null===(r=e.length<=0?void 0:e[0])||void 0===r?void 0:r.subtle)?(i=(e.length<=0?void 0:e[0])||i,n=(e.length<=1?void 0:e[1])||Xx.get()):n=(e.length<=0?void 0:e[0])||Xx.get(),yield n.subtle.digest(i,t.rawData)}))()}getKeyIdentifier(){var e=arguments,t=this;return r((function*(){var r,n="SHA-1";1===e.length?"string"==typeof(e.length<=0?void 0:e[0])?(n=e.length<=0?void 0:e[0],r=Xx.get()):r=e.length<=0?void 0:e[0]:2===e.length?(n=e.length<=0?void 0:e[0],r=e.length<=1?void 0:e[1]):r=Xx.get();var i=gm.parse(t.rawData,ib);return yield r.subtle.digest(n,i.subjectPublicKey)}))()}toTextObject(){var e=this.toTextObjectEmpty(),t=gm.parse(this.rawData,ib);if(e.Algorithm=Yx.serializeAlgorithm(t.algorithm),t.algorithm.algorithm===HS)e["EC Point"]=t.subjectPublicKey;else e["Raw Data"]=t.subjectPublicKey;return e}}class LA extends Zx{static create(e){var t=arguments;return r((function*(){var r=t.length>1&&void 0!==t[1]&&t[1],n=t.length>2&&void 0!==t[2]?t[2]:Xx.get();if("name"in e&&"serialNumber"in e)return new LA(e,r);var i=yield OA.create(e,n),o=yield i.getKeyIdentifier(n);return new LA(Yp.Convert.ToHex(o),r)}))()}constructor(){if(Yp.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 qm({keyIdentifier:new Vm(Yp.Convert.FromHex(arguments.length<=0?void 0:arguments[0]))});super(jm,arguments.length<=1?void 0:arguments[1],gm.serialize(e))}else{var t=arguments.length<=0?void 0:arguments[0],r=t.name instanceof bA?gm.parse(t.name.rawData,Qm):t.name,n=new qm({authorityCertIssuer:r,authorityCertSerialNumber:Yp.Convert.FromHex(t.serialNumber)});super(jm,arguments.length<=1?void 0:arguments[1],gm.serialize(n))}}onInit(e){super.onInit(e);var t=gm.parse(e.extnValue,qm);t.keyIdentifier&&(this.keyId=Yp.Convert.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?Yp.Convert.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){var e=this.toTextObjectWithoutValue(),t=gm.parse(this.value,qm);return t.authorityCertIssuer&&(e["Authority Issuer"]=new bA(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}}LA.NAME="Authority Key Identifier";class MA extends Zx{constructor(){if(Yp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var e=gm.parse(this.value,Wm);this.ca=e.cA,this.pathLength=e.pathLenConstraint}else{var t=new Wm({cA:arguments.length<=0?void 0:arguments[0],pathLenConstraint:arguments.length<=1?void 0:arguments[1]});super(Km,arguments.length<=2?void 0:arguments[2],gm.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}}MA.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"}(SA||(SA={}));class UA extends Zx{constructor(){if(Yp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var e=gm.parse(this.value,Sw);this.usages=e.map((e=>e))}else{var t=new Sw(arguments.length<=0?void 0:arguments[0]);super(bw,arguments.length<=1?void 0:arguments[1],gm.serialize(t)),this.usages=arguments.length<=0?void 0:arguments[0]}}toTextObject(){var e=this.toTextObjectWithoutValue();return e[""]=this.usages.map((e=>Qx.toString(e))).join(", "),e}}UA.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"}(EA||(EA={}));class FA extends Zx{constructor(){if(Yp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var e=gm.parse(this.value,Ow);this.usages=e.toNumber()}else{var t=new Ow(arguments.length<=0?void 0:arguments[0]);super(Rw,arguments.length<=1?void 0:arguments[1],gm.serialize(t)),this.usages=arguments.length<=0?void 0:arguments[0]}}toTextObject(){var e=this.toTextObjectWithoutValue(),t=gm.parse(this.value,Ow);return e[""]=t.toJSON().join(", "),e}}FA.NAME="Key Usages";class zA extends Zx{static create(e){var t=arguments;return r((function*(){var r=t.length>1&&void 0!==t[1]&&t[1],n=t.length>2&&void 0!==t[2]?t[2]:Xx.get(),i=yield OA.create(e,n),o=yield i.getKeyIdentifier(n);return new zA(Yp.Convert.ToHex(o),r)}))()}constructor(){if(Yp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var e=gm.parse(this.value,$w);this.keyId=Yp.Convert.ToHex(e)}else{var t="string"==typeof(arguments.length<=0?void 0:arguments[0])?Yp.Convert.FromHex(arguments.length<=0?void 0:arguments[0]):arguments.length<=0?void 0:arguments[0],r=new $w(t);super(Zw,arguments.length<=1?void 0:arguments[1],gm.serialize(r)),this.keyId=Yp.Convert.ToHex(t)}}toTextObject(){var e=this.toTextObjectWithoutValue(),t=gm.parse(this.value,$w);return e[""]=t,e}}zA.NAME="Subject Key Identifier";class jA extends Zx{constructor(){Yp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])?super(arguments.length<=0?void 0:arguments[0]):super(Hw,arguments.length<=1?void 0:arguments[1],new bA((arguments.length<=0?void 0:arguments[0])||[]).rawData)}onInit(e){super.onInit(e);var t=gm.parse(e.extnValue,Kw);this.names=new bA(t)}toTextObject(){var e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(var r in t)e[r]=t[r];return e}}jA.NAME="Subject Alternative Name";class VA{static register(e,t){this.items.set(e,t)}static create(e){var t=new Zx(e),r=this.items.get(t.type);return r?new r(e):t}}VA.items=new Map;class qA extends Zx{constructor(){var e;if(Yp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var t=gm.parse(this.value,iw);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 iw(r.map((e=>new nw({policyIdentifier:e}))));super(Zm,n,gm.serialize(i)),this.policies=r}}toTextObject(){var e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map((e=>new Gx("",{},Qx.toString(e)))),e}}qA.NAME="Certificate Policies",VA.register(Zm,qA);class HA extends Zx{constructor(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];if(Yp.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 hw({distributionPoint:new dw({fullName:[new Im({uniformResourceIdentifier:e})]})}))),o=new pw(i);super(uw,r[1],gm.serialize(o))}else{var a=new pw(r[0]);super(uw,r[1],gm.serialize(a))}null!==(e=this.distributionPoints)&&void 0!==e||(this.distributionPoints=[])}onInit(e){super.onInit(e);var t=gm.parse(e.extnValue,pw);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 wA(e).toString())).join(", ")),e.reasons&&(r.Reasons=e.reasons.toString()),e.cRLIssuer&&(r["CRL Issuer"]=e.cRLIssuer.map((e=>e.toString())).join(", ")),r})),e}}HA.NAME="CRL Distribution Points";class KA extends Zx{constructor(){var e,t,r,n;if(Yp.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 zm){var i=new zm(arguments.length<=0?void 0:arguments[0]);super(Um,arguments.length<=1?void 0:arguments[1],gm.serialize(i))}else{var o=arguments.length<=0?void 0:arguments[0],a=new zm;GA(a,o,Dm,"ocsp"),GA(a,o,Rm,"caIssuers"),GA(a,o,Om,"timeStamping"),GA(a,o,Lm,"caRepository"),super(Um,arguments.length<=1?void 0:arguments[1],gm.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=[],gm.parse(e.extnValue,zm).forEach((e=>{switch(e.accessMethod){case Dm:this.ocsp.push(new wA(e.accessLocation));break;case Rm:this.caIssuers.push(new wA(e.accessLocation));break;case Om:this.timeStamping.push(new wA(e.accessLocation));break;case Lm:this.caRepository.push(new wA(e.accessLocation))}}))}toTextObject(){var e=this.toTextObjectWithoutValue();return this.ocsp.length&&WA(e,"OCSP",this.ocsp),this.caIssuers.length&&WA(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&WA(e,"Time Stamping",this.timeStamping),this.caRepository.length&&WA(e,"CA Repository",this.caRepository),e}}function WA(e,t,r){if(1===r.length)e[t]=r[0].toTextObject();else{var n=new Gx("");r.forEach(((e,t)=>{var r=e.toTextObject(),i="".concat(r[Gx.NAME]," ").concat(t+1),o=n[i];Array.isArray(o)||(o=[],n[i]=o),o.push(r)})),e[t]=n}}function GA(e,t,r,n){var i=t[n];i&&(Array.isArray(i)?i:[i]).forEach((t=>{"string"==typeof t&&(t=new wA("url",t)),e.push(new Fm({accessMethod:r,accessLocation:gm.parse(t.rawData,Im)}))}))}KA.NAME="Authority Info Access";class QA extends Jx{constructor(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];if(Yp.BufferSourceConverter.isBufferSource(r[0]))e=Yp.BufferSourceConverter.toArrayBuffer(r[0]);else{var i=r[0],o=Array.isArray(r[1])?r[1].map((e=>Yp.BufferSourceConverter.toArrayBuffer(e))):[];e=gm.serialize(new Ww({type:i,values:o}))}super(e,Ww)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){var e=this.toTextObjectWithoutValue();return e.Value=this.values.map((e=>new Gx("",{"":e}))),e}toTextObjectWithoutValue(){var e=this.toTextObjectEmpty();return e[Gx.NAME]===QA.NAME&&(e[Gx.NAME]=Qx.toString(this.type)),e}}QA.NAME="Attribute";class YA extends QA{constructor(){var e;if(Yp.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0]))super(arguments.length<=0?void 0:arguments[0]);else{var t=new ex({printableString:arguments.length<=0?void 0:arguments[0]});super(Ok,[gm.serialize(t)])}null!==(e=this.password)&&void 0!==e||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){var t=gm.parse(this.values[0],ex);this.password=t.toString()}}toTextObject(){var e=this.toTextObjectWithoutValue();return e[Gx.VALUE]=this.password,e}}YA.NAME="Challenge Password";class JA extends QA{constructor(){var e;if(Yp.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 cb;for(var n of t)r.push(gm.parse(n.rawData,lb));super(Lk,[gm.serialize(r)])}null!==(e=this.items)&&void 0!==e||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){var t=gm.parse(this.values[0],cb);this.items=t.map((e=>VA.create(gm.serialize(e))))}}toTextObject(){var e=this.toTextObjectWithoutValue(),t=this.items.map((e=>e.toTextObject()));for(var r of t)e[r[Gx.NAME]]=r;return e}}JA.NAME="Extensions";class ZA{static register(e,t){this.items.set(e,t)}static create(e){var t=new QA(e),r=this.items.get(t.type);return r?new r(e):t}}ZA.items=new Map;var $A,XA="crypto.signatureFormatter";var eC=$A=class{static createPssParams(e,t){var r=$A.getHashAlgorithm(e);return r?new ME({hashAlgorithm:r,maskGenAlgorithm:new nb({algorithm:_E,parameters:gm.serialize(r)}),saltLength:t}):null}static getHashAlgorithm(e){var t=lk.resolve(hx);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 nb({algorithm:hE,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 nb({algorithm:mE,parameters:null});case"sha-256":return new nb({algorithm:bE,parameters:null});case"sha-384":return new nb({algorithm:SE,parameters:null});case"sha-512":return new nb({algorithm:EE,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=$A.createPssParams(e.hash,e.saltLength);if(!r)throw new Error("Cannot create PSS parameters");return new nb({algorithm:fE,parameters:gm.serialize(r)})}return new nb({algorithm:fE,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case hE:return{name:"RSASSA-PKCS1-v1_5"};case mE:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case bE:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case SE:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case EE:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case fE:if(e.parameters){var t=gm.parse(e.parameters,ME);return{name:"RSA-PSS",hash:lk.resolve(hx).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:"RSA-PSS"}}return null}};eC=$A=sa([uk()],eC),lk.registerSingleton(cx,eC);var tC=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new nb({algorithm:AE});case"sha-256":return new nb({algorithm:IE});case"sha-384":return new nb({algorithm:TE});case"sha-512":return new nb({algorithm:PE})}return null}toWebAlgorithm(e){switch(e.algorithm){case AE:return{name:"SHA-1"};case IE:return{name:"SHA-256"};case TE:return{name:"SHA-384"};case PE:return{name:"SHA-512"}}return null}};tC=sa([uk()],tC),lk.registerSingleton(cx,tC);class rC{addPadding(e,t){var r=Yp.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=Yp.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=rC.namedCurveSize.get(r)||rC.defaultNamedCurveSize,i=new cE,o=Yp.BufferSourceConverter.toUint8Array(t);return i.r=this.removePadding(o.slice(0,n),!0),i.s=this.removePadding(o.slice(n,n+n),!0),gm.serialize(i)}return null}toWebSignature(e,t){if("ECDSA"===e.name){var r=gm.parse(t,cE),n=e.namedCurve,i=rC.namedCurveSize.get(n)||rC.defaultNamedCurveSize,o=this.addPadding(i,this.removePadding(r.r)),a=this.addPadding(i,this.removePadding(r.s));return Yp.combine(o,a)}return null}}rC.namedCurveSize=new Map,rC.defaultNamedCurveSize=32;var nC,iC,oC="1.3.101.110",aC="1.3.101.111",sC="1.3.101.112",lC="1.3.101.113",uC=class{toAsnAlgorithm(e){var t=null;switch(e.name.toLowerCase()){case"ed25519":t=sC;break;case"x25519":t=oC;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=sC;break;case"ed448":t=lC}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=oC;break;case"x448":t=aC}}return t?new nb({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case sC:return{name:"Ed25519"};case lC:return{name:"EdDSA",namedCurve:"Ed448"};case oC:return{name:"X25519"};case aC:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};uC=sa([uk()],uC),lk.registerSingleton(cx,uC);(class extends RA{constructor(e){RA.isAsnEncoded(e)?super(e,ux):super(e),this.tag=DA.CertificateRequestTag}onInit(e){this.tbs=gm.serialize(e.certificationRequestInfo),this.publicKey=new OA(e.certificationRequestInfo.subjectPKInfo);var t=lk.resolve(hx);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map((e=>ZA.create(gm.serialize(e))));var r=this.getAttribute(Lk);this.extensions=[],r instanceof JA&&(this.extensions=r.items),this.subjectName=new iA(e.certificationRequestInfo.subject),this.subject=this.subjectName.toString()}getAttribute(e){for(var t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter((t=>t.type===e))}getExtension(e){for(var t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter((t=>t.type===e))}verify(){var e=arguments,n=this;return r((function*(){var r=e.length>0&&void 0!==e[0]?e[0]:Xx.get(),i=t(t({},n.publicKey.algorithm),n.signatureAlgorithm),o=yield n.publicKey.export(i,["verify"],r),a=lk.resolveAll(XA).reverse(),s=null;for(var l of a)if(s=l.toWebSignature(i,n.signature))break;if(!s)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return yield r.subtle.verify(n.signatureAlgorithm,o,s,n.tbs)}))()}toTextObject(){var e=this.toTextObjectEmpty(),t=gm.parse(this.rawData,ux),r=t.certificationRequestInfo,n=new Gx("",{Version:"".concat(ub[r.version]," (").concat(r.version,")"),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){var i=new Gx("");for(var o of this.attributes){var a=o.toTextObject();i[a[Gx.NAME]]=a}n.Attributes=i}return e.Data=n,e.Signature=new Gx("",{Algorithm:Yx.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}).NAME="PKCS#10 Certificate Request";class cC extends RA{constructor(e){RA.isAsnEncoded(e)?super(e,hb):super(e),this.tag=DA.CertificateTag}onInit(e){var t=e.tbsCertificate;this.tbs=gm.serialize(t),this.serialNumber=Yp.Convert.ToHex(t.serialNumber),this.subjectName=new iA(t.subject),this.subject=new iA(t.subject).toString(),this.issuerName=new iA(t.issuer),this.issuer=this.issuerName.toString();var r=lk.resolve(hx);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=>VA.create(gm.serialize(e))))),this.publicKey=new OA(t.subjectPublicKeyInfo)}getExtension(e){for(var t of this.extensions)if("string"==typeof e){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter((t=>"string"==typeof e?t.type===e:t instanceof e))}verify(){var e=arguments,n=this;return r((function*(){var r,i,o=e.length>0&&void 0!==e[0]?e[0]:{},a=e.length>1&&void 0!==e[1]?e[1]:Xx.get(),s=o.publicKey;try{if(s)if("publicKey"in s)r=t(t({},s.publicKey.algorithm),n.signatureAlgorithm),i=yield s.publicKey.export(r,["verify"],a);else if(s instanceof OA)r=t(t({},s.algorithm),n.signatureAlgorithm),i=yield s.export(r,["verify"],a);else if(Yp.BufferSourceConverter.isBufferSource(s)){var l=new OA(s);r=t(t({},l.algorithm),n.signatureAlgorithm),i=yield l.export(r,["verify"],a)}else r=t(t({},s.algorithm),n.signatureAlgorithm),i=s;else r=t(t({},n.publicKey.algorithm),n.signatureAlgorithm),i=yield n.publicKey.export(r,["verify"],a)}catch(e){return!1}var u=lk.resolveAll(XA).reverse(),c=null;for(var d of u)if(c=d.toWebSignature(r,n.signature))break;if(!c)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");var h=yield a.subtle.verify(n.signatureAlgorithm,i,c,n.tbs);if(o.signatureOnly)return h;var v=(o.date||new Date).getTime();return h&&n.notBefore.getTime()<v&&v<n.notAfter.getTime()}))()}getThumbprint(){var e=arguments,t=this;return r((function*(){for(var r,n="SHA-1",i=e.length,o=new Array(i),a=0;a<i;a++)o[a]=e[a];return o[0]&&(o[0].subtle?r=o[0]:(n=o[0]||n,r=o[1])),null!=r||(r=Xx.get()),yield r.subtle.digest(n,t.rawData)}))()}isSelfSigned(){var e=arguments,t=this;return r((function*(){var r=e.length>0&&void 0!==e[0]?e[0]:Xx.get();return t.subject===t.issuer&&(yield t.verify({signatureOnly:!0},r))}))()}toTextObject(){var e=this.toTextObjectEmpty(),t=gm.parse(this.rawData,hb),r=t.tbsCertificate,n=new Gx("",{Version:"".concat(ub[r.version]," (").concat(r.version,")"),"Serial Number":r.serialNumber,"Signature Algorithm":Yx.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new Gx("",{"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 Gx("");for(var o of this.extensions){var a=o.toTextObject();i[a[Gx.NAME]]=a}n.Extensions=i}return e.Data=n,e.Signature=new Gx("",{Algorithm:Yx.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}}cC.NAME="Certificate";class dC{static createSelfSigned(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:Xx.get();if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return n.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},r)}))()}static create(e){var n=arguments;return r((function*(){var r,i,o=n.length>1&&void 0!==n[1]?n[1]:Xx.get();i=e.publicKey instanceof OA?e.publicKey.rawData:"publicKey"in e.publicKey?e.publicKey.publicKey.rawData:Yp.BufferSourceConverter.isBufferSource(e.publicKey)?e.publicKey:yield o.subtle.exportKey("spki",e.publicKey);var a=e.serialNumber?Yp.BufferSourceConverter.toUint8Array(Yp.Convert.FromHex(e.serialNumber)):o.getRandomValues(new Uint8Array(16));a[0]>127&&(a[0]&=127),a.length>1&&0===a[0]&&(a[1]|=128);var s=e.notBefore||new Date,l=e.notAfter||new Date(s.getTime()+31536e6),u=new hb({tbsCertificate:new db({version:ub.v3,serialNumber:a,validity:new sb({notBefore:s,notAfter:l}),extensions:new cb((null===(r=e.extensions)||void 0===r?void 0:r.map((e=>gm.parse(e.rawData,lb))))||[]),subjectPublicKeyInfo:gm.parse(i,ib)})});if(e.subject){var c=e.subject instanceof iA?e.subject:new iA(e.subject);u.tbsCertificate.subject=gm.parse(c.toArrayBuffer(),km)}if(e.issuer){var d=e.issuer instanceof iA?e.issuer:new iA(e.issuer);u.tbsCertificate.issuer=gm.parse(d.toArrayBuffer(),km)}var h={hash:"SHA-256"},v="signingKey"in e?t(t(t({},h),e.signingAlgorithm),e.signingKey.algorithm):t(t({},h),e.signingAlgorithm),p=lk.resolve(hx);u.tbsCertificate.signature=u.signatureAlgorithm=p.toAsnAlgorithm(v);var f=gm.serialize(u.tbsCertificate),g="signingKey"in e?yield o.subtle.sign(v,e.signingKey,f):e.signature,y=lk.resolveAll(XA).reverse(),m=null;for(var w of y)if(m=w.toAsnSignature(v,g))break;if(!m)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return u.signatureValue=m,new cC(gm.serialize(u))}))()}}!function(e){e[e.unspecified=0]="unspecified",e[e.keyCompromise=1]="keyCompromise",e[e.cACompromise=2]="cACompromise",e[e.affiliationChanged=3]="affiliationChanged",e[e.superseded=4]="superseded",e[e.cessationOfOperation=5]="cessationOfOperation",e[e.certificateHold=6]="certificateHold",e[e.removeFromCRL=8]="removeFromCRL",e[e.privilegeWithdrawn=9]="privilegeWithdrawn",e[e.aACompromise=10]="aACompromise"}(nC||(nC={})),VA.register(Km,MA),VA.register(bw,UA),VA.register(Rw,FA),VA.register(Zw,zA),VA.register(jm,LA),VA.register(Hw,jA),VA.register(uw,HA),VA.register(Um,KA),ZA.register(Ok,YA),ZA.register(Lk,JA),lk.registerSingleton(XA,class{toAsnSignature(e,t){return Yp.BufferSourceConverter.toArrayBuffer(t)}toWebSignature(e,t){return Yp.BufferSourceConverter.toArrayBuffer(t)}}),lk.registerSingleton(XA,rC),rC.namedCurveSize.set("P-256",32),rC.namedCurveSize.set("K-256",32),rC.namedCurveSize.set("P-384",48),rC.namedCurveSize.set("P-521",66);class hC extends os{listen(){return r((function*(){throw new Lp("WebRTCTransport.createListener")}))()}getAddrs(){return[]}updateAnnounceAddrs(){}close(){return r((function*(){}))()}}function vC(){var e,t=Cc(),n=!1;return{sink:(e=r((function*(e){if(n)throw new Error("already piped");n=!0,t.resolve(e)})),function(t){return e.apply(this,arguments)}),source:l((function*(){var e=yield u(t.promise);yield*c(s(e))}))()}}var pC=65535,fC=Boolean(null===(iC=globalThis.process)||void 0===iC||null===(iC=iC.env)||void 0===iC?void 0:iC.DUMP_SESSION_KEYS);function gC(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function yC(e){if("boolean"!=typeof e)throw new Error("boolean expected, not ".concat(e))}function mC(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function wC(e){if(!gC(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 bC(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 SC(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function EC(){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 kC=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function xC(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(!gC(e))throw new Error("Uint8Array expected, got "+typeof e);e=PC(e)}return e}var AC=(e,t)=>{function r(r){if(wC(r),!kC)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?wC(a):wC(a,e.nonceLength)}var s=e.tagLength;s&&void 0!==i[1]&&wC(i[1]);var l=t(r,...i),u=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");wC(t)}},c=!1;return{encrypt(e,t){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,wC(e),u(l.encrypt.length,t),l.encrypt(e,t)},decrypt(e,t){if(wC(e),s&&e.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return u(l.decrypt.length,t),l.decrypt(e,t)}}}return Object.assign(r,e),r};function CC(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 IC(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 TC(e,t,r){yC(r);var n,i=new Uint8Array(16),o=(n=i,new DataView(n.buffer,n.byteOffset,n.byteLength));return IC(o,0,BigInt(t),r),IC(o,8,BigInt(e),r),i}function PC(e){return Uint8Array.from(e)}var _C=e=>Uint8Array.from(e.split("").map((e=>e.charCodeAt(0)))),BC=_C("expand 16-byte k"),NC=_C("expand 32-byte k"),DC=SC(BC),RC=SC(NC);function OC(e,t){return e<<t|e>>>32-t}function LC(e){return e.byteOffset%4==0}var MC=2**32-1,UC=new Uint32Array;function FC(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 mC(i),mC(a),yC(o),yC(r),function(t,s,l,u){var c=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0;wC(t),wC(s),wC(l);var d=l.length;if(void 0===u&&(u=new Uint8Array(d)),wC(u),mC(c),c<0||c>=MC)throw new Error("arx: counter overflow");if(u.length<d)throw new Error("arx: output (".concat(u.length,") is shorter than data (").concat(d,")"));var h,v,p=[],f=t.length;if(32===f)p.push(h=PC(t)),v=RC;else{if(16!==f||!r)throw new Error("arx: invalid 32-byte key, got length=".concat(f));(h=new Uint8Array(32)).set(t),h.set(t,16),v=DC,p.push(h)}LC(s)||p.push(s=PC(s));var g=SC(h);if(n){if(24!==s.length)throw new Error("arx: extended nonce must be 24 bytes");n(v,g,SC(s.subarray(0,16)),g),s=s.subarray(16)}var y=16-i;if(y!==s.length)throw new Error("arx: nonce must be ".concat(y," or 16 bytes"));if(12!==y){var m=new Uint8Array(12);m.set(s,o?0:12-s.length),s=m,p.push(s)}var w=SC(s);return function(e,t,r,n,i,o,a,s){for(var l=i.length,u=new Uint8Array(64),c=SC(u),d=LC(i)&&LC(o),h=d?SC(i):UC,v=d?SC(o):UC,p=0;p<l;a++){if(e(t,r,n,c,a,s),a>=MC)throw new Error("arx: counter overflow");var f=Math.min(64,l-p);if(d&&64===f){var g=p/4;if(p%4!=0)throw new Error("arx: invalid block position");for(var y,m=0;m<16;m++)v[y=g+m]=h[y]^c[m];p+=64}else{for(var w,b=0;b<f;b++)o[w=p+b]=i[w]^u[b];p+=f}}}(e,v,g,w,l,u,c,a),EC(...p),u}}var zC=(e,t)=>255&e[t++]|(255&e[t++])<<8;class jC{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,wC(e=xC(e),32);var t=zC(e,0),r=zC(e,2),n=zC(e,4),i=zC(e,6),o=zC(e,8),a=zC(e,10),s=zC(e,12),l=zC(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|r<<3),this.r[2]=7939&(r>>>10|n<<6),this.r[3]=8191&(n>>>7|i<<9),this.r[4]=255&(i>>>4|o<<12),this.r[5]=o>>>1&8190,this.r[6]=8191&(o>>>14|a<<2),this.r[7]=8065&(a>>>11|s<<5),this.r[8]=8191&(s>>>8|l<<8),this.r[9]=l>>>5&127;for(var u=0;u<8;u++)this.pad[u]=zC(e,16+2*u)}process(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2]?0:2048,{h:n,r:i}=this,o=i[0],a=i[1],s=i[2],l=i[3],u=i[4],c=i[5],d=i[6],h=i[7],v=i[8],p=i[9],f=zC(e,t+0),g=zC(e,t+2),y=zC(e,t+4),m=zC(e,t+6),w=zC(e,t+8),b=zC(e,t+10),S=zC(e,t+12),E=zC(e,t+14),k=n[0]+(8191&f),x=n[1]+(8191&(f>>>13|g<<3)),A=n[2]+(8191&(g>>>10|y<<6)),C=n[3]+(8191&(y>>>7|m<<9)),I=n[4]+(8191&(m>>>4|w<<12)),T=n[5]+(w>>>1&8191),P=n[6]+(8191&(w>>>14|b<<2)),_=n[7]+(8191&(b>>>11|S<<5)),B=n[8]+(8191&(S>>>8|E<<8)),N=n[9]+(E>>>5|r),D=0,R=D+k*o+x*(5*p)+A*(5*v)+C*(5*h)+I*(5*d);D=R>>>13,R&=8191;var O=(D+=(R+=T*(5*c)+P*(5*u)+_*(5*l)+B*(5*s)+N*(5*a))>>>13)+k*a+x*o+A*(5*p)+C*(5*v)+I*(5*h);D=O>>>13,O&=8191,D+=(O+=T*(5*d)+P*(5*c)+_*(5*u)+B*(5*l)+N*(5*s))>>>13,O&=8191;var L=D+k*s+x*a+A*o+C*(5*p)+I*(5*v);D=L>>>13,L&=8191,D+=(L+=T*(5*h)+P*(5*d)+_*(5*c)+B*(5*u)+N*(5*l))>>>13,L&=8191;var M=D+k*l+x*s+A*a+C*o+I*(5*p);D=M>>>13,M&=8191,D+=(M+=T*(5*v)+P*(5*h)+_*(5*d)+B*(5*c)+N*(5*u))>>>13,M&=8191;var U=D+k*u+x*l+A*s+C*a+I*o;D=U>>>13,U&=8191,D+=(U+=T*(5*p)+P*(5*v)+_*(5*h)+B*(5*d)+N*(5*c))>>>13,U&=8191;var F=D+k*c+x*u+A*l+C*s+I*a;D=F>>>13,F&=8191,D+=(F+=T*o+P*(5*p)+_*(5*v)+B*(5*h)+N*(5*d))>>>13,F&=8191;var z=D+k*d+x*c+A*u+C*l+I*s;D=z>>>13,z&=8191,D+=(z+=T*a+P*o+_*(5*p)+B*(5*v)+N*(5*h))>>>13,z&=8191;var j=D+k*h+x*d+A*c+C*u+I*l;D=j>>>13,j&=8191,D+=(j+=T*s+P*a+_*o+B*(5*p)+N*(5*v))>>>13,j&=8191;var V=D+k*v+x*h+A*d+C*c+I*u;D=V>>>13,V&=8191,D+=(V+=T*l+P*s+_*a+B*o+N*(5*p))>>>13,V&=8191;var q=D+k*p+x*v+A*h+C*d+I*c;D=q>>>13,q&=8191,D+=(q+=T*u+P*l+_*s+B*a+N*o)>>>13,q&=8191,R=8191&(D=(D=(D<<2)+D|0)+(R&=8191)|0),O+=D>>>=13,n[0]=R,n[1]=O,n[2]=L,n[3]=M,n[4]=U,n[5]=F,n[6]=z,n[7]=j,n[8]=V,n[9]=q}finalize(){var{h:e,pad:t}=this,r=new Uint16Array(10),n=e[1]>>>13;e[1]&=8191;for(var i=2;i<10;i++)e[i]+=n,n=e[i]>>>13,e[i]&=8191;e[0]+=5*n,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(var o=1;o<10;o++)r[o]=e[o]+n,n=r[o]>>>13,r[o]&=8191;r[9]-=8192;for(var a=(1^n)-1,s=0;s<10;s++)r[s]&=a;a=~a;for(var l=0;l<10;l++)e[l]=e[l]&a|r[l];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);var u=e[0]+t[0];e[0]=65535&u;for(var c=1;c<8;c++)u=(e[c]+t[c]|0)+(u>>>16)|0,e[c]=65535&u;EC(r)}update(e){bC(this),wC(e=xC(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(){EC(this.h,this.r,this.buffer,this.pad)}digestInto(e){bC(this),function(e,t){wC(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 VC,qC,HC,KC=(qC=(e,t)=>VC(t).update(xC(e)).digest(),HC=(VC=e=>new jC(e))(new Uint8Array(32)),qC.outputLen=HC.outputLen,qC.blockLen=HC.blockLen,qC.create=e=>VC(e),qC);function WC(e,t,r,n,i){for(var o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:20,a=e[0],s=e[1],l=e[2],u=e[3],c=t[0],d=t[1],h=t[2],v=t[3],p=t[4],f=t[5],g=t[6],y=t[7],m=i,w=r[0],b=r[1],S=r[2],E=a,k=s,x=l,A=u,C=c,I=d,T=h,P=v,_=p,B=f,N=g,D=y,R=m,O=w,L=b,M=S,U=0;U<o;U+=2)R=OC(R^(E=E+C|0),16),C=OC(C^(_=_+R|0),12),R=OC(R^(E=E+C|0),8),C=OC(C^(_=_+R|0),7),O=OC(O^(k=k+I|0),16),I=OC(I^(B=B+O|0),12),O=OC(O^(k=k+I|0),8),I=OC(I^(B=B+O|0),7),L=OC(L^(x=x+T|0),16),T=OC(T^(N=N+L|0),12),L=OC(L^(x=x+T|0),8),T=OC(T^(N=N+L|0),7),M=OC(M^(A=A+P|0),16),P=OC(P^(D=D+M|0),12),M=OC(M^(A=A+P|0),8),P=OC(P^(D=D+M|0),7),M=OC(M^(E=E+I|0),16),I=OC(I^(N=N+M|0),12),M=OC(M^(E=E+I|0),8),I=OC(I^(N=N+M|0),7),R=OC(R^(k=k+T|0),16),T=OC(T^(D=D+R|0),12),R=OC(R^(k=k+T|0),8),T=OC(T^(D=D+R|0),7),O=OC(O^(x=x+P|0),16),P=OC(P^(_=_+O|0),12),O=OC(O^(x=x+P|0),8),P=OC(P^(_=_+O|0),7),L=OC(L^(A=A+C|0),16),C=OC(C^(B=B+L|0),12),L=OC(L^(A=A+C|0),8),C=OC(C^(B=B+L|0),7);var F=0;n[F++]=a+E|0,n[F++]=s+k|0,n[F++]=l+x|0,n[F++]=u+A|0,n[F++]=c+C|0,n[F++]=d+I|0,n[F++]=h+T|0,n[F++]=v+P|0,n[F++]=p+_|0,n[F++]=f+B|0,n[F++]=g+N|0,n[F++]=y+D|0,n[F++]=m+R|0,n[F++]=w+O|0,n[F++]=b+L|0,n[F++]=S+M|0}var GC=FC(WC,{counterRight:!1,counterLength:4,allowShortKeys:!1}),QC=new Uint8Array(16),YC=(e,t)=>{e.update(t);var r=t.length%16;r&&e.update(QC.subarray(r))},JC=new Uint8Array(32);function ZC(e,t,r,n,i){var o=e(t,r,JC),a=KC.create(o);i&&YC(a,i),YC(a,n);var s=TC(n.length,i?i.length:0,!0);a.update(s);var l=a.digest();return EC(o,s),l}var $C,XC=AC({blockSize:64,nonceLength:12,tagLength:16},($C=GC,(e,t,r)=>{var n=16;return{encrypt(i,o){var a=i.length;(o=CC(a+n,o,!1)).set(i);var s=o.subarray(0,-16);$C(e,t,s,s,1);var l=ZC($C,e,t,s,r);return o.set(l,a),EC(l),o},decrypt(i,o){o=CC(i.length-n,o,!1);var a=i.subarray(0,-16),s=i.subarray(-16),l=ZC($C,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)),$C(e,t,o,o,1),EC(l),o}}}));var eI=Uint8Array.from([0]),tI=Uint8Array.of();var rI={hashSHA256:e=>Yo(e.subarray()),getHKDF(e,t){var r=function(e,t,r){return Tr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),Qn(e,en(r),en(t))}(Yo,t,e),n=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:32;Tr(e),Cr(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=tI);for(var a=new Uint8Array(o*i),s=Qn.create(e,t),l=s._cloneInto(),u=new Uint8Array(s.outputLen),c=0;c<o;c++)eI[0]=c+1,l.update(0===c?tI:u).update(r).update(eI).digestInto(u),a.set(u,i*c),s._cloneInto(l);return s.destroy(),l.destroy(),Nr(u,eI),a.slice(0,n)}(Yo,r,void 0,96),i=n;return[i.subarray(0,32),i.subarray(32,64),i.subarray(64,96)]},generateX25519KeyPair(){var e=Qo.utils.randomPrivateKey();return{publicKey:Qo.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:Qo.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>Qo.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>XC(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,i)=>XC(n,t,r).decrypt(e.subarray(),i)},nI=rI;var iI=e=>{var t=dt(2);return t[0]=e>>8,t[1]=e,t};iI.bytes=2;var oI=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 aI(e,t){t.enabled&&fC&&(e?(t("LOCAL_STATIC_PUBLIC_KEY ".concat(gt(e.publicKey,"hex"))),t("LOCAL_STATIC_PRIVATE_KEY ".concat(gt(e.privateKey,"hex")))):t("Missing local static keys."))}function sI(e,t){t.enabled&&fC&&(e?(t("LOCAL_PUBLIC_EPHEMERAL_KEY ".concat(gt(e.publicKey,"hex"))),t("LOCAL_PRIVATE_EPHEMERAL_KEY ".concat(gt(e.privateKey,"hex")))):t("Missing local ephemeral keys."))}function lI(e,t){t.enabled&&fC&&t(e?"REMOTE_EPHEMERAL_PUBLIC_KEY ".concat(gt(e.subarray(),"hex")):"Missing remote ephemeral keys.")}function uI(e,t,r){r.enabled&&fC&&(r("CIPHER_STATE_1 ".concat(e.n.getUint64()," ").concat(e.k&&gt(e.k,"hex"))),r("CIPHER_STATE_2 ".concat(t.n.getUint64()," ").concat(t.k&&gt(t.k,"hex"))))}function cI(e,t){if(e.length!==t.length)throw new Error("Inputs should have the same length");for(var r=dt(e.length),n=0;n<e.length;n++)r[n]=e[n]^t[n];return r}function dI(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}oI.bytes=2;class hI extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid crypto exchange"),e(this,"code",void 0),this.code=hI.code}}e(hI,"code","ERR_INVALID_CRYPTO_EXCHANGE");class vI{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;e(this,"n",void 0),e(this,"bytes",void 0),e(this,"view",void 0),this.n=t,this.bytes=ct(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw new Error("Cipherstate has reached maximum n, a new handshake must be performed")}}var pI,fI,gI=ct(0);class yI{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;e(this,"k",void 0),e(this,"n",void 0),e(this,"crypto",void 0),this.crypto=t,this.k=r,this.n=new vI(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 mI{constructor(t,r){e(this,"cs",void 0),e(this,"ck",void 0),e(this,"h",void 0),e(this,"crypto",void 0),this.crypto=t;var n=Et(r,"utf-8");this.h=function(e,t){if(t.length<=32){var r=ct(32);return r.set(t),r}return e.hash(t)}(t,n),this.ck=this.h,this.cs=new yI(t)}mixKey(e){var[t,r]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new yI(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new gs(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,gI);return[new yI(this.crypto,e),new yI(this.crypto,t)]}}class wI{constructor(t){e(this,"ss",void 0),e(this,"s",void 0),e(this,"e",void 0),e(this,"rs",void 0),e(this,"re",void 0),e(this,"initiator",void 0),e(this,"crypto",void 0);var{crypto:r,protocolName:n,prologue:i,initiator:o,s:a,e:s,rs:l,re:u}=t;this.crypto=r,this.ss=new mI(r,n),this.ss.mixHash(i),this.initiator=o,this.s=a,this.e=s,this.rs=l,this.re=u}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");var e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(this.rs)throw new Error("remote static public key is already set");var r=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+r)throw new Error("message is not long enough");var n=e.sublist(t,t+r);return this.rs=this.ss.decryptAndHash(n),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class bI extends wI{writeMessageA(e){return new gs(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){var t=this.writeE();this.writeEE();var r=this.writeS();return this.writeES(),new gs(t,r,this.ss.encryptAndHash(e))}writeMessageC(e){var t=this.writeS();return this.writeSE(),new gs(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(e){throw new hI("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 hI("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 hI("handshake stage 2 validation fail: ".concat(e.message))}}}function SI(e,t,r){return EI.apply(this,arguments)}function EI(){return(EI=r((function*(e,t,r){var n=yield e.sign(AI(t));return fI.encode({identityKey:Su(e.publicKey),identitySig:n,extensions:r})}))).apply(this,arguments)}function kI(e,t,r){return xI.apply(this,arguments)}function xI(){return xI=r((function*(e,t,r){try{var n=fI.decode(e),i=mu(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=AI(t);if(!(yield i.verify(o,n.identitySig)))throw new Error("Invalid payload signature");return n}catch(e){throw new Ta(e.message)}})),xI.apply(this,arguments)}function AI(e){var t=Et("noise-libp2p-static-key:");return e instanceof Uint8Array?Mt([t,e],t.length+e.length):(e.prepend(t),e)}function CI(){return CI=r((function*(e,t){var{log:r,connection:n,crypto:i,privateKey:o,prologue:a,s:s,remoteIdentityKey:l,extensions:u}=e,c=yield SI(o,s.publicKey,u),d=new bI({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:a,s:s});aI(d.s,r),r.trace("Stage 0 - Initiator starting to send first message."),yield n.write(d.writeMessageA(gI),t),r.trace("Stage 0 - Initiator finished sending first message."),sI(d.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");var h,v,p=d.readMessageB(yield n.read(t));r.trace("Stage 1 - Initiator received the message."),lI(d.re,r),h=d.rs,(v=r).enabled&&fC&&v(h?"REMOTE_STATIC_PUBLIC_KEY ".concat(gt(h.subarray(),"hex")):"Missing remote static public key."),r.trace("Initiator going to check remote's signature...");var f=yield kI(p,d.rs,l);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),yield n.write(d.writeMessageC(c),t),r.trace("Stage 2 - Initiator sent message with signed payload.");var[g,y]=d.ss.split();return uI(g,y,r),{payload:f,encrypt:e=>g.encryptWithAd(gI,e),decrypt:(e,t)=>y.decryptWithAd(gI,e,t)}})),CI.apply(this,arguments)}function II(){return II=r((function*(e,t){var{log:r,connection:n,crypto:i,privateKey:o,prologue:a,s:s,remoteIdentityKey:l,extensions:u}=e,c=yield SI(o,s.publicKey,u),d=new bI({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:a,s:s});aI(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."),lI(d.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),yield n.write(d.writeMessageB(c),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),sI(d.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");var h=d.readMessageC(yield n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");var v=yield kI(h,d.rs,l),[p,f]=d.ss.split();return uI(p,f,r),{payload:v,encrypt:e=>f.encryptWithAd(gI,e),decrypt:(e,t)=>p.decryptWithAd(gI,e,t)}})),II.apply(this,arguments)}!function(e){var t;e.codec=()=>(null==t&&(t=Hl((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 Kl('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 Kl('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=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(pI||(pI={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((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),pI.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={identityKey:ct(0),identitySig:ct(0)},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.identityKey=e.bytes();break;case 2:n.identitySig=e.bytes();break;case 4:var a;n.extensions=pI.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=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(fI||(fI={}));class TI{constructor(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"protocol","/noise"),e(this,"crypto",void 0),e(this,"prologue",void 0),e(this,"staticKey",void 0),e(this,"extensions",void 0),e(this,"metrics",void 0),e(this,"components",void 0),e(this,Symbol.toStringTag,"@chainsafe/libp2p-noise"),e(this,ds,["@libp2p/connection-encryption","@chainsafe/libp2p-noise"]);var{staticNoiseKey:i,extensions:o,crypto:a,prologueBytes:s}=n,{metrics:l}=r;this.components=r;var u=null!=a?a:nI;this.crypto=function(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}(u),this.extensions=t({webtransportCerthashes:[]},o),this.metrics=l?function(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}(l):void 0,this.staticKey=i?u.generateX25519KeyPairFromSeed(i):u.generateX25519KeyPair(),this.prologue=null!=s?s:ct(0)}secureOutbound(e,t){var n=this;return r((function*(){var r,i,o=kd(e,{lengthEncoder:iI,lengthDecoder:oI,maxDataLength:pC}),a=yield n.performHandshakeInitiator(o,n.components.privateKey,null==t||null===(r=t.remotePeer)||void 0===r?void 0:r.publicKey,t),s=yield n.createSecureConnection(o,a);e.source=s.source,e.sink=s.sink;var l=mu(a.payload.identityKey);return{conn:e,remoteExtensions:a.payload.extensions,remotePeer:Ru(l),streamMuxer:!0===(null==t?void 0:t.skipStreamMuxerNegotiation)?void 0:n.getStreamMuxer(null===(i=a.payload.extensions)||void 0===i?void 0:i.streamMuxers)}}))()}getStreamMuxer(e){if(null!=e&&0!==e.length){var t=this.components.upgrader.getStreamMuxers();if(null!=t)for(var r of e){var n=t.get(r);if(null!=n)return n}if(e.length)throw new Pa("Early muxer negotiation was requested but the initiator and responder had no common muxers")}}secureInbound(e,t){var n=this;return r((function*(){var r,i,o=kd(e,{lengthEncoder:iI,lengthDecoder:oI,maxDataLength:pC}),a=yield n.performHandshakeResponder(o,n.components.privateKey,null==t||null===(r=t.remotePeer)||void 0===r?void 0:r.publicKey,t),s=yield n.createSecureConnection(o,a);e.source=s.source,e.sink=s.sink;var l=mu(a.payload.identityKey);return{conn:e,remoteExtensions:a.payload.extensions,remotePeer:Ru(l),streamMuxer:!0===(null==t?void 0:t.skipStreamMuxerNegotiation)?void 0:n.getStreamMuxer(null===(i=a.payload.extensions)||void 0===i?void 0:i.streamMuxers)}}))()}performHandshakeInitiator(e,n,i,o){var a=this;return r((function*(){var r,s=!0===(null==o?void 0:o.skipStreamMuxerNegotiation)?[]:[...a.components.upgrader.getStreamMuxers().keys()];try{var l;r=yield function(e,t){return CI.apply(this,arguments)}({connection:e,privateKey:n,remoteIdentityKey:i,log:a.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:a.crypto,prologue:a.prologue,s:a.staticKey,extensions:t({streamMuxers:s,webtransportCerthashes:[]},a.extensions)},o),null===(l=a.metrics)||void 0===l||l.xxHandshakeSuccesses.increment()}catch(e){var u;throw null===(u=a.metrics)||void 0===u||u.xxHandshakeErrors.increment(),e}return r}))()}performHandshakeResponder(e,n,i,o){var a=this;return r((function*(){var r,s=!0===(null==o?void 0:o.skipStreamMuxerNegotiation)?[]:[...a.components.upgrader.getStreamMuxers().keys()];try{var l;r=yield function(e,t){return II.apply(this,arguments)}({connection:e,privateKey:n,remoteIdentityKey:i,log:a.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:a.crypto,prologue:a.prologue,s:a.staticKey,extensions:t({streamMuxers:s,webtransportCerthashes:[]},a.extensions)},o),null===(l=a.metrics)||void 0===l||l.xxHandshakeSuccesses.increment()}catch(e){var u;throw null===(u=a.metrics)||void 0===u||u.xxHandshakeErrors.increment(),e}return r}))()}createSecureConnection(e,t){var n=this;return r((function*(){var r,i,[o,a]=(r=vC(),i=vC(),[{source:r.source,sink:i.sink},{source:i.source,sink:r.sink}]),c=e.unwrap();return yield Fc(o,function(e,t){return function(){var r=l((function*(r){var n,i=!1,o=!1;try{for(var a,l=s(r);i=!(a=yield u(l.next())).done;i=!1)for(var c=a.value,d=0;d<c.length;d+=65519){var h=d+65519;h>c.length&&(h=c.length);var v=void 0;v=c instanceof Uint8Array?e.encrypt(c.subarray(d,h)):e.encrypt(c.sublist(d,h)),null==t||t.encryptedPackets.increment(),yield new gs(iI(v.byteLength),v)}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}));return function(e){return r.apply(this,arguments)}}()}(t,n.metrics),c,(e=>Ep(e,{lengthDecoder:oI})),function(e,t){return function(){var r=l((function*(r){var n,i=!1,o=!1;try{for(var a,l=s(r);i=!(a=yield u(l.next())).done;i=!1)for(var c=a.value,d=0;d<c.length;d+=pC){var h=d+pC;if(h>c.length&&(h=c.length),h-16<d)throw new Error("Invalid chunk");var v=c.sublist(d,h),p=c.subarray(d,h-16);try{var f=e.decrypt(v,p);null==t||t.decryptedPackets.increment(),yield f}catch(e){throw null==t||t.decryptErrors.increment(),e}}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}));return function(e){return r.apply(this,arguments)}}()}(t,n.metrics),o),a}))()}}function PI(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new TI(t,e)}var _I=Object.values(ut).map((e=>e.decoder)).reduce(((e,t)=>e.or(t))),BI=m(/^a=fingerprint:(?:\w+-[0-9]+)\s((:?[0-9a-fA-F]{2})+)$/m,{fingerprint:1});function NI(e){var t=e.stringTuples().filter((e=>466===e[0])).map((e=>e[1]))[0];if(void 0===t||""===t)throw new _a("Couldn't find a certhash component of multiaddr: ".concat(e.toString()));return t}function DI(e){var t=function(e){return He(_I.decode(e))}(NI(e)),r=function(e){switch(e){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new Mp(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 Op(n,e.toString());return"".concat(r," ").concat(i.join(":").toUpperCase())}function RI(e,t){if(void 0===e.sdp)throw new _a("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 OI=Et("libp2p-webrtc-noise:");var LI=tp?"iceconnectionstatechange":"connectionstatechange";function MI(){return MI=r((function*(e,r,n){var i=e.createDataChannel("",{negotiated:!0,id:0});try{var o,a,s;if("client"===n.role){n.log.trace("client creating local offer");var l=yield e.createOffer();n.log.trace("client created local offer %s",l.sdp);var u=RI(l,r);n.log.trace("client setting local offer %s",u.sdp),yield e.setLocalDescription(u);var c=function(e,t){var{host:r,port:n,family:i}=e.toOptions(),o=DI(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(Ov,"\na=candidate:1467250027 1 UDP 1467250027 ").concat(r," ").concat(n," typ host\na=end-of-candidates\n")}}(n.remoteAddr,r);n.log.trace("client setting server description %s",c.sdp),yield e.setRemoteDescription(c)}else{var d=function(e,t){var{host:r,port:n,family:i}=e.toOptions();return{type:"offer",sdp:"v=0\no=- 0 0 IN IP".concat(i," ").concat(r,"\ns=-\nc=IN IP").concat(i," ").concat(r,"\nt=0 0\na=ice-options:ice2,trickle\nm=application ").concat(n," UDP/DTLS/SCTP webrtc-datachannel\na=mid:0\na=setup:active\na=ice-ufrag:").concat(t,"\na=ice-pwd:").concat(t,"\na=fingerprint:sha-256 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\na=sctp-port:5000\na=max-message-size:").concat(Ov,"\na=candidate:1467250027 1 UDP 1467250027 ").concat(r," ").concat(n," typ host\na=end-of-candidates\n")}}(n.remoteAddr,r);n.log.trace("server setting client %s %s",d.type,d.sdp),yield e.setRemoteDescription(d),n.log.trace("server creating local answer");var h=yield e.createAnswer();n.log.trace("server created local answer");var v=RI(h,r);n.log.trace("server setting local description %s",h.sdp),yield e.setLocalDescription(v)}if("open"!==i.readyState&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,i.readyState),yield lv(i,"open",n.signal)),n.log.trace("%s handshake channel opened",n.role),"server"===n.role){var p,f,g=null!==(p=null===(f=e.remoteFingerprint())||void 0===f?void 0:f.value)&&void 0!==p?p:"";n.remoteAddr=n.remoteAddr.encapsulate(function(e){var t=e.split(":").map((e=>parseInt(e,16))),r=Uint8Array.from(t),n=qe($e.code,r);return kr("/certhash/".concat(ue.encode(n.bytes)))}(g))}var y=function(e){var t;if(null!=e){var r=e.match(BI);return null==r||null===(t=r.groups)||void 0===t?void 0:t.fingerprint}}(null===(o=e.localDescription)||void 0===o?void 0:o.sdp);if(null==y)throw new Dp("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=Et(e.trim().toLowerCase().replaceAll(":",""),"hex"),i=qe($e.code,n),o=_I.decode(NI(t)),a=OI.byteLength+i.bytes.byteLength+o.byteLength;return Mt("server"===r?[OI,o,i.bytes]:[OI,i.bytes,o],a)}(y,n.remoteAddr,n.role),w=PI({prologueBytes:m})(n),b=xp(t({channel:i,direction:"outbound",handshake:!0,logger:n.logger},null!==(a=n.dataChannel)&&void 0!==a?a:{})),S=new ap(n,{peerConnection:e,remoteAddr:n.remoteAddr,timeline:{open:Date.now()},metrics:n.events});e.addEventListener(LI,(()=>{switch(e.connectionState){case"failed":case"disconnected":case"closed":S.close().catch((e=>{n.log.error("error closing connection",e),S.abort(e)}))}})),null===(s=n.events)||void 0===s||s.increment({peer_connection:!0});var E=new Ap(n,{peerConnection:e,metrics:n.events,dataChannelOptions:n.dataChannel});if("client"===n.role)return n.log.trace("%s secure inbound",n.role),yield w.secureInbound(b,{remotePeer:n.remotePeerId,signal:n.signal,skipStreamMuxerNegotiation:!0}),n.log.trace("%s upgrade outbound",n.role),yield n.upgrader.upgradeOutbound(S,{skipProtection:!0,skipEncryption:!0,muxerFactory:E,signal:n.signal});n.log.trace("%s secure outbound",n.role);var k=yield w.secureOutbound(b,{remotePeer:n.remotePeerId,signal:n.signal,skipStreamMuxerNegotiation:!0});S.remoteAddr=S.remoteAddr.encapsulate("/p2p/".concat(k.remotePeer)),n.log.trace("%s upgrade inbound",n.role),yield n.upgrader.upgradeInbound(S,{skipProtection:!0,skipEncryption:!0,muxerFactory:E,signal:n.signal})}catch(e){throw i.close(),e}})),MI.apply(this,arguments)}function UI(){return(UI=r((function*(e,r,n,i){null==i&&(i=yield RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));var o="function"==typeof n?yield n():n;return new RTCPeerConnection(t(t({},null!=o?o:{}),{},{certificates:[i]}))}))).apply(this,arguments)}function FI(e){return zI.apply(this,arguments)}function zI(){return(zI=r((function*(e){var t=yield Au(e),r=yield crypto.subtle.exportKey("pkcs8",t.privateKey);return["-----BEGIN PRIVATE KEY-----",...gt(new Uint8Array(r),"base64pad").split(/(.{64})/).filter(Boolean),"-----END PRIVATE KEY-----"].join("\n")}))).apply(this,arguments)}class jI{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e(this,"log",void 0),e(this,"metrics",void 0),e(this,"components",void 0),e(this,"init",void 0),e(this,"certificate",void 0),e(this,"privateKey",void 0),e(this,"emitter",void 0),e(this,"renewCertificateTask",void 0),e(this,Ca,!0),e(this,Symbol.toStringTag,"@libp2p/webrtc-direct"),e(this,ds,["@libp2p/transport"]),this.log=t.logger.forComponent("libp2p:webrtc-direct"),this.components=t,this.init=r,this.emitter=new os,null!=r.certificateLifespan&&null!=r.certificateRenewalThreshold&&r.certificateRenewalThreshold>=r.certificateLifespan)throw new _a("Certificate renewal threshold must be less than certificate lifespan");null!=t.metrics&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}start(){var e=this;return r((function*(){e.certificate=yield e.getCertificate()}))()}stop(){var e=this;return r((function*(){null!=e.renewCertificateTask&&clearTimeout(e.renewCertificateTask),e.certificate=void 0}))()}dial(e,t){var n=this;return r((function*(){var r,i;n.log("dial %a",e),t.signal.throwIfAborted();var o=e.getPeerId();null!=o&&(i=Du(o));var a=function(){return"libp2p+webrtc+v1/"+[...Array(arguments.length>0&&void 0!==arguments[0]?arguments[0]:32)].map((()=>Rv.at(Math.floor(Math.random()*Rv.length)))).join("")}(),s=yield function(e,t,r,n){return UI.apply(this,arguments)}("client",a,"function"==typeof n.init.rtcConfiguration?yield n.init.rtcConfiguration():null!==(r=n.init.rtcConfiguration)&&void 0!==r?r:{});try{var l;return yield function(e,t,r){return MI.apply(this,arguments)}(s,a,{role:"client",log:n.log,logger:n.components.logger,metrics:n.components.metrics,events:null===(l=n.metrics)||void 0===l?void 0:l.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:n.init.dataChannel,upgrader:t.upgrader,peerId:n.components.peerId,remotePeerId:i,privateKey:n.components.privateKey})}catch(e){throw s.close(),e}}))()}createListener(e){if(null==this.certificate)throw new Ya;return new hC(this.components,t(t(t({},this.init),e),{},{certificate:this.certificate,emitter:this.emitter}))}listenFilter(e){return e.filter(bh.exactMatch)}dialFilter(e){return this.listenFilter(e)}getCertificate(e){var t=this;return r((function*(){if(function(e){if(null==e)return!1;return"string"==typeof e.privateKey&&"string"==typeof e.pem&&"string"==typeof e.certhash}(t.init.certificate))return t.log("using provided TLS certificate"),t.init.certificate;var r=yield t.loadOrCreatePrivateKey(),{pem:n,certhash:i}=yield t.loadOrCreateCertificate(r,e);return{privateKey:yield FI(r),pem:n,certhash:i}}))()}loadOrCreatePrivateKey(){var e=this;return r((function*(){var t;if(null!=e.privateKey)return e.privateKey;var r=null!==(t=e.init.certificateKeychainName)&&void 0!==t?t:"webrtc-direct-certificate-private-key",n=e.getKeychain();try{if(null==n)throw e.log("no keychain configured - not checking for stored private key"),new za;e.log.trace("checking for stored private key"),e.privateKey=yield n.exportKey(r)}catch(t){if("NotFoundError"!==t.name)throw t;e.log.trace("generating private key"),e.privateKey=yield gu("ECDSA","P-256"),null!=n?(e.log.trace("storing private key"),yield n.importKey(r,e.privateKey)):e.log("no keychain configured - not storing private key")}return e.privateKey}))()}loadOrCreateCertificate(e,t){var n=this;return r((function*(){var r,i,o;if(null!=n.certificate&&!0!==t)return n.certificate;var a=new lc(null!==(r=n.init.certificateDatastoreKey)&&void 0!==r?r:"/libp2p/webrtc-direct/certificate"),s=yield Au(e);try{if(!0===t)throw n.log.trace("forcing renewal of TLS certificate"),new za;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:Fv)-Date.now();return l<0&&(l=100),n.log("will renew TLS certificate after %d ms",l),n.renewCertificateTask=setTimeout((()=>{n.log("renewing TLS certificate"),n.getCertificate(!0).then((e=>{n.certificate=e,n.emitter.safeDispatchEvent("certificate:renew",{detail:e})})).catch((e=>{n.log.error("could not renew certificate - %e",e)}))}),l),{pem:o.toString("pem"),certhash:ue.encode((yield $e.digest(new Uint8Array(o.rawData))).bytes)}}))()}loadCertificate(e,t){var n=this;return r((function*(){var r,i=yield n.components.datastore.get(e),o=new cC(i),a=o.notAfter.getTime()-(null!==(r=n.init.certificateRenewalThreshold)&&void 0!==r?r:Fv);if(Date.now()>a)throw n.log("stored TLS certificate has expired"),new za;n.log("loaded certificate, expires in %d ms",a);var s=yield o.publicKey.export(crypto),l=yield crypto.subtle.exportKey("raw",s),u=yield crypto.subtle.exportKey("raw",t.publicKey);if(!St(new Uint8Array(l,0,l.byteLength),new Uint8Array(u,0,u.byteLength)))throw n.log("stored TLS certificate public key did not match public key from private key"),new za;return n.log("loaded certificate, expiry time is %o",a),o}))()}createCertificate(e,t){var n=this;return r((function*(){var r,i=new Date,o=new Date(Date.now()+(null!==(r=n.init.certificateLifespan)&&void 0!==r?r:12096e5));i.setMilliseconds(0),o.setMilliseconds(0);var a=yield dC.createSelfSigned({serialNumber:(100000n*BigInt(Math.random().toString().replace(".",""))).toString(16),name:"CN=example.com, C=US, L=CA, O=example, ST=CA",notBefore:i,notAfter:o,keys:t,extensions:[new MA(!1,void 0,!0)]},crypto);return null!=n.getKeychain()?(n.log.trace("storing TLS certificate"),yield n.components.datastore.put(e,Et(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 VI(e){return t=>new jI(t,e)}function qI(e){return t=>new Hp(t,e)}var HI,KI,WI,GI,QI,YI,JI,ZI,$I,XI="/ipfs/bitswap/1.2.0",eT=4194304,tT=eT;!function(e){e.WantBlock="WantBlock",e.WantHave="WantHave"}(HI||(HI={})),function(e){e[e.WantBlock=0]="WantBlock",e[e.WantHave=1]="WantHave"}(KI||(KI={})),function(e){e.codec=()=>ql(KI)}(HI||(HI={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((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),HI.codec().encode(e.wantType,t)),null!=e.sendDontHave&&(t.uint32(40),t.bool(e.sendDontHave)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={cid:ct(0),priority:0},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.cid=e.bytes();break;case 2:r.priority=e.int32();break;case 3:r.cancel=e.bool();break;case 4:r.wantType=HI.codec().decode(e);break;case 5:r.sendDontHave=e.bool();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(WI||(WI={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((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),WI.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 Kl('Decode error - map field "entries" had too many elements');n.entries.push(WI.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=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(GI||(GI={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.prefix&&e.prefix.byteLength>0&&(t.uint32(10),t.bytes(e.prefix)),null!=e.data&&e.data.byteLength>0&&(t.uint32(18),t.bytes(e.data)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={prefix:ct(0),data:ct(0)},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.prefix=e.bytes();break;case 2:r.data=e.bytes();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(QI||(QI={})),function(e){e.HaveBlock="HaveBlock",e.DoNotHaveBlock="DoNotHaveBlock"}(YI||(YI={})),function(e){e[e.HaveBlock=0]="HaveBlock",e[e.DoNotHaveBlock=1]="DoNotHaveBlock"}(JI||(JI={})),function(e){e.codec=()=>ql(JI)}(YI||(YI={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((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!==JI[e.type]&&(t.uint32(16),YI.codec().encode(e.type,t)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={cid:ct(0),type:YI.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=YI.codec().decode(e);break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(ZI||(ZI={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((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),GI.codec().encode(e.wantlist,t)),null!=e.blocks)for(var n of e.blocks)t.uint32(26),QI.codec().encode(n,t);if(null!=e.blockPresences)for(var i of e.blockPresences)t.uint32(34),ZI.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=GI.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 Kl('Decode error - map field "blocks" had too many elements');n.blocks.push(QI.codec().decode(e,e.uint32(),{limits:null===(l=r.limits)||void 0===l?void 0:l.blocks$}));break;case 4:var u,c;if(null!=(null===(u=r.limits)||void 0===u?void 0:u.blockPresences)&&n.blockPresences.length===r.limits.blockPresences)throw new Kl('Decode error - map field "blockPresences" had too many elements');n.blockPresences.push(ZI.codec().decode(e,e.uint32(),{limits:null===(c=r.limits)||void 0===c?void 0:c.blockPresences$}));break;case 5:n.pendingBytes=e.int32();break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}($I||($I={}));class rT extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Block too large"),this.name="BlockTooLargeError"}}e(rT,"name","BlockTooLargeError");function nT(e,t,r,n,i,o){for(var a=0,s=!1,l=r;l<e.length;l++){var u=e[l],c=o(u);if(c>4193664)throw new rT("Cannot send block as after encoding it is over the max message size");var d=i+c;if(d>n){s=!0;break}t.push(u),a++,i=d}return{hasMore:s,added:a,newSize:i}}function iT(e){return sT(3,QI.encode(e))}function oT(e){return sT(4,ZI.encode(e))}function aT(e){return sT(1,WI.encode(e))}function sT(e,t){return Nt(e)+Nt(t.byteLength)+t.byteLength}let lT=class extends os{constructor(t){var r,n,i,o,a,s,l,u,c,d,h,v=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),e(this,"log",void 0),e(this,"libp2p",void 0),e(this,"routing",void 0),e(this,"protocols",void 0),e(this,"running",void 0),e(this,"maxInboundStreams",void 0),e(this,"maxOutboundStreams",void 0),e(this,"messageReceiveTimeout",void 0),e(this,"registrarIds",void 0),e(this,"metrics",void 0),e(this,"sendQueue",void 0),e(this,"runOnLimitedConnections",void 0),e(this,"maxOutgoingMessageSize",void 0),e(this,"maxIncomingMessageSize",void 0),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=null!==(r=v.protocols)&&void 0!==r?r:[XI],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=null!==(n=v.maxInboundStreams)&&void 0!==n?n:1024,this.maxOutboundStreams=null!==(i=v.maxOutboundStreams)&&void 0!==i?i:1024,this.messageReceiveTimeout=null!==(o=v.messageReceiveTimeout)&&void 0!==o?o:5e3,this.runOnLimitedConnections=null!==(a=v.runOnLimitedConnections)&&void 0!==a&&a,this.maxIncomingMessageSize=null!==(s=v.maxIncomingMessageSize)&&void 0!==s?s:eT,this.maxOutgoingMessageSize=null!==(l=null!==(u=v.maxOutgoingMessageSize)&&void 0!==u?u:v.maxIncomingMessageSize)&&void 0!==l?l:tT,this.metrics={blocksSent:null===(c=t.metrics)||void 0===c?void 0:c.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:null===(d=t.metrics)||void 0===d?void 0:d.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new gv({concurrency:null!==(h=v.messageSendConcurrency)&&void 0!==h?h:50,metrics:t.metrics,metricName:"helia_bitswap_message_send_queue"}),this.sendQueue.addEventListener("error",(e=>{this.log.error("error sending wantlist to peer",e.detail)}))}start(){var e=this;return r((function*(){if(!e.running){e.running=!0,yield e.libp2p.handle(e.protocols,e._onStream,{maxInboundStreams:e.maxInboundStreams,maxOutboundStreams:e.maxOutboundStreams,runOnLimitedConnection:e.runOnLimitedConnections});var t={onConnect:t=>{e.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{e.safeDispatchEvent("peer:disconnected",{detail:t})}};for(var r of(e.registrarIds=[],e.protocols))e.registrarIds.push(yield e.libp2p.register(r,t));e.libp2p.getConnections().forEach((t=>{e.safeDispatchEvent("peer:connected",{detail:t.remotePeer})}))}}))()}stop(){var e=this;return r((function*(){if(e.running=!1,yield e.libp2p.unhandle(e.protocols),null!=e.registrarIds){for(var t of e.registrarIds)e.libp2p.unregister(t);e.registrarIds=[]}}))()}_onStream(e){var t=this;if(this.running){var{stream:n,connection:i}=e;Promise.resolve().then(r((function*(){t.log("incoming new bitswap %s stream from %p",n.protocol,i.remotePeer);var e=()=>{"open"===n.status?n.abort(new Qa("Incoming Bitswap stream timed out after ".concat(t.messageReceiveTimeout,"ms"))):t.log("stream aborted with status %s",n.status)},o=AbortSignal.timeout(t.messageReceiveTimeout);o.addEventListener("abort",e),yield n.closeWrite(),yield Fc(n,(e=>Ep(e,{maxDataLength:t.maxIncomingMessageSize})),function(){var a=r((function*(r){var a,l=!1,u=!1;try{for(var c,d=s(r);l=!(c=yield d.next()).done;l=!1){var h=c.value;try{var v=$I.decode(h);t.log("incoming new bitswap %s message from %p on stream",n.protocol,i.remotePeer,n.id),t.safeDispatchEvent("bitswap:message",{detail:{peer:i.remotePeer,message:v}}),o.removeEventListener("abort",e),(o=AbortSignal.timeout(t.messageReceiveTimeout)).addEventListener("abort",e)}catch(e){t.log.error("error reading incoming bitswap message from %p on stream",i.remotePeer,n.id,e),n.abort(e);break}}}catch(e){u=!0,a=e}finally{try{l&&null!=d.return&&(yield d.return())}finally{if(u)throw a}}}));return function(e){return a.apply(this,arguments)}}())}))).catch((e=>{this.log.error("error handling incoming stream from %p",i.remotePeer,e),n.abort(e)}))}}findProviders(e,t){var r=this;return l((function*(){var n;null==t||null===(n=t.onProgress)||void 0===n||n.call(t,new av("bitswap:network:find-providers",e));var i,o=!1,a=!1;try{for(var l,c=s(r.routing.findProviders(e,t));o=!(l=yield u(c.next())).done;o=!1){var d=l.value;(yield u(r.libp2p.isDialable(d.multiaddrs,{runOnLimitedConnection:r.runOnLimitedConnections})))&&(yield d)}}catch(e){a=!0,i=e}finally{try{o&&null!=c.return&&(yield u(c.return()))}finally{if(a)throw i}}}))()}findAndConnect(e,t){var n=this;return r((function*(){var i;null!=(null==t?void 0:t.providers)&&(yield Promise.all(t.providers.map(function(){var e=r((function*(e){return n.connectTo(e).catch((e=>{n.log.error("could not connect to supplied provider - %e",e)}))}));return function(t){return e.apply(this,arguments)}}()))),yield uc(Ac(pc(n.findProviders(e,t),null!==(i=null==t?void 0:t.maxProviders)&&void 0!==i?i:3),function(){var e=r((function*(e){return n.connectTo(e.id,t)}));return function(t){return e.apply(this,arguments)}}())).catch((e=>{n.log.error(e)}))}))()}sendMessage(e,t,n){var i=this;return r((function*(){if(!i.running)throw new Error("network isn't running");var o=i.sendQueue.queue.find((t=>e.equals(t.options.peerId)&&"queued"===t.status));if(null!=o)return o.options.message=function(e,t){for(var[r,n]of t.wantlist.entries()){var i,o,a,s=e.wantlist.get(r);null!=s&&(s.priority>n.priority&&(n.priority=s.priority),n.cancel=null!==(i=n.cancel)&&void 0!==i?i:s.cancel,n.wantType=null!==(o=n.wantType)&&void 0!==o?o:s.wantType,n.sendDontHave=null!==(a=n.sendDontHave)&&void 0!==a?a:s.sendDontHave),e.wantlist.set(r,n)}for(var[l,u]of t.blockPresences.entries())e.blockPresences.set(l,u);for(var[c,d]of t.blocks.entries())e.blocks.set(c,d);return t.full&&!e.full&&(e.full=!0),e}(o.options.message,t),void(yield o.join({signal:null==n?void 0:n.signal}));yield i.sendQueue.add(function(){var t=r((function*(t){var r,n=null==t?void 0:t.message;if(null==n)throw new _a("No message to send");i.log("sendMessage to %p",e),null==t||null===(r=t.onProgress)||void 0===r||r.call(t,new av("bitswap:network:send-wantlist",e));var o=yield i.libp2p.dialProtocol(e,XI,t);yield o.closeRead();try{yield Fc(function*(e,t){for(var r=[...e.wantlist.values()],n=[...e.blockPresences.values()],i=[...e.blocks.values()],o=0,a=0,s=0,l=!1;;){var u,c={wantlist:{full:null!==(u=e.full)&&void 0!==u&&u,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},d=$I.encode(c).byteLength,{added:h,hasMore:v,newSize:p}=nT(i,c.blocks,s,t,d,iT);s+=h,d=p;var f=v;({added:h,hasMore:v,newSize:p}=nT(n,c.blockPresences,a,t,d,oT)),a+=h,d=p;var g=v;if(({added:h,hasMore:v,newSize:p}=nT(r,c.wantlist.entries,o,t,d,aT)),o+=h,d=p,(l=!f&&!g&&!v)||(c.wantlist.full=!1),yield $I.encode(c),l)break}}(n,i.maxOutgoingMessageSize),(e=>bp(e)),o),yield o.close(t)}catch(r){var a;null==t||null===(a=t.onProgress)||void 0===a||a.call(t,new av("bitswap:network:send-wantlist:error",{peer:e,error:r})),i.log.error("error sending message to %p",e,r),o.abort(r)}i._updateSentStats(n.blocks)}));return function(e){return t.apply(this,arguments)}}(),{peerId:e,signal:null==n?void 0:n.signal,message:t})}))()}connectTo(e,t){var n=this;return r((function*(){var r;if(!n.running)throw new Ya("Network isn't running");null==t||null===(r=t.onProgress)||void 0===r||r.call(t,new av("bitswap:network:dial",e));var[i]=yield Promise.all([n.libp2p.dial(e,t),lv(n.libp2p,"peer:identify",null==t?void 0:t.signal,{filter:t=>{if(!t.detail.peerId.equals(e))return!1;if(t.detail.protocols.includes(XI))return!0;throw new Ka("".concat(e," did not support ").concat(XI))}})]);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 uT{constructor(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];e(this,"full",void 0),e(this,"pendingBytes",void 0),e(this,"wantlist",void 0),e(this,"blocks",void 0),e(this,"blockPresences",void 0),this.full=t,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){var r=se.encode(e.multihash.bytes);this.wantlist.set(r,t)}addBlockPresence(e,t){var r=se.encode(e.multihash.bytes);this.blockPresences.set(r,t)}addBlock(e,t){var r=se.encode(e.multihash.bytes);this.blocks.set(r,t)}}function cT(e){return function(e){var t=new Uint8Array(e.reduce(((e,t)=>e+Nt(t)),0)),r=0;for(var n of e)t=Ot(n,t,r),r+=Nt(n);return t}([e.version,e.code,e.multihash.code,e.multihash.digest.byteLength])}class dT{constructor(t,r){var n;e(this,"peerId",void 0),e(this,"blockstore",void 0),e(this,"network",void 0),e(this,"wants",void 0),e(this,"exchangeCount",void 0),e(this,"bytesSent",void 0),e(this,"bytesReceived",void 0),e(this,"lastExchange",void 0),e(this,"maxSizeReplaceHasWithBlock",void 0),e(this,"log",void 0),this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,this.log=t.logger.forComponent("helia:bitswap:ledger:".concat(t.peerId)),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=null!==(n=r.maxSizeReplaceHasWithBlock)&&void 0!==n?n:1024}sentBytes(e){this.exchangeCount++,this.lastExchange=(new Date).getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=(new Date).getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}sendBlocksToPeer(e){var t=this;return r((function*(){var r=new uT,n=new Set;for(var[i,o]of t.wants.entries())try{var a=yield t.blockstore.get(o.cid,e);o.wantType===HI.WantHave?a.byteLength<t.maxSizeReplaceHasWithBlock?(t.log("sending have and block for %c",o.cid),n.add(i),r.addBlock(o.cid,{data:a,prefix:cT(o.cid)})):(t.log("sending have for %c",o.cid),r.addBlockPresence(o.cid,{cid:o.cid.bytes,type:YI.HaveBlock})):(t.log("sending block for %c",o.cid),n.add(i),r.addBlock(o.cid,{data:a,prefix:cT(o.cid)}))}catch(e){if("NotFoundError"!==e.name)throw e;if(t.log("do not have block for %c",o.cid),!o.sendDontHave)continue;if(!0===o.sentDoNotHave)continue;o.sentDoNotHave=!0,r.addBlockPresence(o.cid,{cid:o.cid.bytes,type:YI.DoNotHaveBlock})}if(r.blocks.size>0||r.blockPresences.size>0)for(var s of(t.log("sending message"),yield t.network.sendMessage(t.peerId,r,e),t.log("sent message"),t.sentBytes([...r.blocks.values()].reduce(((e,t)=>e+t.data.byteLength),0)),n))t.wants.delete(s)}))()}}class hT{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"blockstore",void 0),e(this,"network",void 0),e(this,"ledgerMap",void 0),e(this,"maxSizeReplaceHasWithBlock",void 0),e(this,"log",void 0),e(this,"logger",void 0),this.blockstore=t.blockstore,this.network=t.network,this.maxSizeReplaceHasWithBlock=r.maxSizeReplaceHasWithBlock,this.log=t.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=t.logger,this.ledgerMap=rv({name:"helia_bitswap_ledger_map",metrics:t.metrics}),this.network.addEventListener("bitswap:message",(e=>{this.receiveMessage(e.detail.peer,e.detail.message).catch((t=>{this.log.error("error receiving bitswap message from %p",e.detail.peer,t)}))})),this.network.addEventListener("peer:disconnected",(e=>{this.peerDisconnected(e.detail)}))}ledgerForPeer(e){var t=this.ledgerMap.get(e);if(null!=t)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){var t=this.ledgerMap.get(e);if(null!=t)return[...t.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map((e=>e.peerId))}receiveMessage(e,t){var n=this;return r((function*(){var r,i,o=n.ledgerMap.get(e);if(null==o&&(o=new dT({peerId:e,blockstore:n.blockstore,network:n.network,logger:n.logger},{maxSizeReplaceHasWithBlock:n.maxSizeReplaceHasWithBlock}),n.ledgerMap.set(e,o)),o.receivedBytes(null!==(r=null===(i=t.blocks)||void 0===i?void 0:i.reduce(((e,t)=>e+t.data.byteLength),0))&&void 0!==r?r:0),null!=t.wantlist)for(var a of(!0===t.wantlist.full&&o.wants.clear(),t.wantlist.entries)){var s,l,u=it.decode(a.cid),c=gt(u.multihash.bytes,"base64");if(!0===a.cancel)n.log("peer %p cancelled want of block for %c",e,u),o.wants.delete(c);else a.wantType===HI.WantHave?n.log("peer %p wanted block presence for %c",e,u):n.log("peer %p wanted block for %c",e,u),o.wants.set(c,{cid:u,priority:a.priority,wantType:null!==(s=a.wantType)&&void 0!==s?s:HI.WantBlock,sendDontHave:null!==(l=a.sendDontHave)&&void 0!==l&&l})}n.log("send blocks to peer"),yield o.sendBlocksToPeer()}))()}receivedBlock(e,t){var n=this;return r((function*(){var i=gt(e.multihash.bytes,"base64"),o=[];for(var a of n.ledgerMap.values())a.wants.has(i)&&o.push(a);yield Promise.all(o.map(function(){var e=r((function*(e){return e.sendBlocksToPeer(t)}));return function(t){return e.apply(this,arguments)}}()))}))()}peerDisconnected(e){this.ledgerMap.delete(e)}}var vT=new WeakMap;let pT=class{constructor(){n(this,vT,[])}enqueue(e,r){var n={priority:(r=t({priority:0},r)).priority,id:r.id,run:e};if(0===this.size||o(vT,this)[this.size-1].priority>=r.priority)o(vT,this).push(n);else{var i=function(e,t,r){for(var n=0,i=e.length;i>0;){var o=Math.trunc(i/2),a=n+o;r(e[a],t)<=0?(n=++a,i-=o+1):i=o}return n}(o(vT,this),n,((e,t)=>t.priority-e.priority));o(vT,this).splice(i,0,n)}}setPriority(e,t){var r=o(vT,this).findIndex((t=>t.id===e));if(-1===r)throw new ReferenceError('No promise function with the id "'.concat(e,'" exists in the queue.'));var[n]=o(vT,this).splice(r,1);this.enqueue(n.run,{priority:t,id:e})}dequeue(){var e=o(vT,this).shift();return null==e?void 0:e.run}filter(e){return o(vT,this).filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return o(vT,this).length}};var fT=new WeakMap,gT=new WeakMap,yT=new WeakMap,mT=new WeakMap,wT=new WeakMap,bT=new WeakMap,ST=new WeakMap,ET=new WeakMap,kT=new WeakMap,xT=new WeakMap,AT=new WeakMap,CT=new WeakMap,IT=new WeakMap,TT=new WeakMap,PT=new WeakMap,_T=new WeakSet;class BT extends ia{constructor(r){var o,a,s,l;if(super(),d(this,_T),n(this,fT,void 0),n(this,gT,void 0),n(this,yT,0),n(this,mT,void 0),n(this,wT,void 0),n(this,bT,0),n(this,ST,void 0),n(this,ET,void 0),n(this,kT,void 0),n(this,xT,void 0),n(this,AT,0),n(this,CT,void 0),n(this,IT,void 0),n(this,TT,void 0),n(this,PT,1n),e(this,"timeout",void 0),!("number"==typeof(r=t({carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:pT},r)).intervalCap&&r.intervalCap>=1))throw new TypeError("Expected `intervalCap` to be a number from 1 and up, got `".concat(null!==(o=null===(a=r.intervalCap)||void 0===a?void 0:a.toString())&&void 0!==o?o:"","` (").concat(typeof r.intervalCap,")"));if(void 0===r.interval||!(Number.isFinite(r.interval)&&r.interval>=0))throw new TypeError("Expected `interval` to be a finite number >= 0, got `".concat(null!==(s=null===(l=r.interval)||void 0===l?void 0:l.toString())&&void 0!==s?s:"","` (").concat(typeof r.interval,")"));i(fT,this,r.carryoverConcurrencyCount),i(gT,this,r.intervalCap===Number.POSITIVE_INFINITY||0===r.interval),i(mT,this,r.intervalCap),i(wT,this,r.interval),i(kT,this,new r.queueClass),i(xT,this,r.queueClass),this.concurrency=r.concurrency,this.timeout=r.timeout,i(TT,this,!0===r.throwOnTimeout),i(IT,this,!1===r.autoStart)}get concurrency(){return o(CT,this)}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError("Expected `concurrency` to be a number from 1 and up, got `".concat(e,"` (").concat(typeof e,")"));i(CT,this,e),h(_T,this,zT).call(this)}setPriority(e,t){o(kT,this).setPriority(e,t)}add(e){return r((function*(){var n,a,s,l,u=arguments,c=this,d=u.length>1&&void 0!==u[1]?u[1]:{};return null!==(a=(n=d).id)&&void 0!==a||(n.id=(i(PT,c,(s=o(PT,c),l=s++,s)),l).toString()),d=t({timeout:c.timeout,throwOnTimeout:o(TT,c)},d),new Promise(((t,n)=>{o(kT,c).enqueue(r((function*(){var r,a;i(AT,c,(r=o(AT,c),++r)),i(yT,c,(a=o(yT,c),++a));try{var s;null===(s=d.signal)||void 0===s||s.throwIfAborted();var l=e({signal:d.signal});d.timeout&&(l=Xv(Promise.resolve(l),{milliseconds:d.timeout})),d.signal&&(l=Promise.race([l,h(_T,c,jT).call(c,d.signal)]));var u=yield l;t(u),c.emit("completed",u)}catch(e){if(e instanceof Yv&&!d.throwOnTimeout)return void t();n(e),c.emit("error",e)}finally{h(_T,c,RT).call(c)}})),d),c.emit("add"),h(_T,c,MT).call(c)}))}))()}addAll(e,t){var n=this;return r((function*(){return Promise.all(e.map(function(){var e=r((function*(e){return n.add(e,t)}));return function(t){return e.apply(this,arguments)}}()))}))()}start(){return o(IT,this)?(i(IT,this,!1),h(_T,this,zT).call(this),this):this}pause(){i(IT,this,!0)}clear(){i(kT,this,new(o(xT,this)))}onEmpty(){var e=this;return r((function*(){0!==o(kT,e).size&&(yield h(_T,e,qT).call(e,"empty"))}))()}onSizeLessThan(e){var t=this;return r((function*(){o(kT,t).size<e||(yield h(_T,t,qT).call(t,"next",(()=>o(kT,t).size<e)))}))()}onIdle(){var e=this;return r((function*(){0===o(AT,e)&&0===o(kT,e).size||(yield h(_T,e,qT).call(e,"idle"))}))()}get size(){return o(kT,this).size}sizeBy(e){return o(kT,this).filter(e).length}get pending(){return o(AT,this)}get isPaused(){return o(IT,this)}}function NT(e){return o(gT,e)||o(yT,e)<o(mT,e)}function DT(e){return o(AT,e)<o(CT,e)}function RT(){var e;i(AT,this,(e=o(AT,this),--e)),h(_T,this,MT).call(this),this.emit("next")}function OT(){h(_T,this,FT).call(this),h(_T,this,UT).call(this),i(ET,this,void 0)}function LT(e){var t=Date.now();if(void 0===o(ST,e)){var r=o(bT,e)-t;if(!(r<0))return void 0===o(ET,e)&&i(ET,e,setTimeout((()=>{h(_T,e,OT).call(e)}),r)),!0;i(yT,e,o(fT,e)?o(AT,e):0)}return!1}function MT(){if(0===o(kT,this).size)return o(ST,this)&&clearInterval(o(ST,this)),i(ST,this,void 0),this.emit("empty"),0===o(AT,this)&&this.emit("idle"),!1;if(!o(IT,this)){var e=!w(_T,this,LT);if(w(_T,this,NT)&&w(_T,this,DT)){var t=o(kT,this).dequeue();return!!t&&(this.emit("active"),t(),e&&h(_T,this,UT).call(this),!0)}}return!1}function UT(){o(gT,this)||void 0!==o(ST,this)||(i(ST,this,setInterval((()=>{h(_T,this,FT).call(this)}),o(wT,this))),i(bT,this,Date.now()+o(wT,this)))}function FT(){0===o(yT,this)&&0===o(AT,this)&&o(ST,this)&&(clearInterval(o(ST,this)),i(ST,this,void 0)),i(yT,this,o(fT,this)?o(AT,this):0),h(_T,this,zT).call(this)}function zT(){for(;h(_T,this,MT).call(this););}function jT(e){return VT.apply(this,arguments)}function VT(){return(VT=r((function*(e){return new Promise(((t,r)=>{e.addEventListener("abort",(()=>{r(e.reason)}),{once:!0})}))}))).apply(this,arguments)}function qT(e,t){return HT.apply(this,arguments)}function HT(){return HT=r((function*(e,t){return new Promise((r=>{var n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)}))})),HT.apply(this,arguments)}function KT(e){var t=[eP.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function WT(e){var t,r,n,i,o,a,s,l,u,c,d,h,v,p,f;return{Status:null!==(t=e.Status)&&void 0!==t?t:0,TC:null!==(r=null!==(n=e.TC)&&void 0!==n?n:e.flag_tc)&&void 0!==r&&r,RD:null!==(i=null!==(o=e.RD)&&void 0!==o?o:e.flag_rd)&&void 0!==i&&i,RA:null!==(a=null!==(s=e.RA)&&void 0!==s?s:e.flag_ra)&&void 0!==a&&a,AD:null!==(l=null!==(u=e.AD)&&void 0!==u?u:e.flag_ad)&&void 0!==l&&l,CD:null!==(c=null!==(d=e.CD)&&void 0!==d?d:e.flag_cd)&&void 0!==c&&c,Question:(null!==(h=null!==(v=e.Question)&&void 0!==v?v:e.questions)&&void 0!==h?h:[]).map((e=>({name:e.name,type:eP[e.type]}))),Answer:(null!==(p=null!==(f=e.Answer)&&void 0!==f?f:e.answers)&&void 0!==p?p:[]).map((e=>{var t,r;return{name:e.name,type:eP[e.type],TTL:null!==(t=null!==(r=e.TTL)&&void 0!==r?r:e.ttl)&&void 0!==t?t:60,data:e.data instanceof Uint8Array?gt(e.data):e.data}}))}}var GT,QT;function YT(e){var t,n=new BT({concurrency:null!==(t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).queryConcurrency)&&void 0!==t?t:4});return function(){var t=r((function*(t){var i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=new URLSearchParams;a.set("name",t),KT(o.types).forEach((e=>{a.append("type",eP[e])})),null===(i=o.onProgress)||void 0===i||i.call(o,new av("dns:query",{detail:t}));var s=yield n.add(r((function*(){var t,r=yield fetch("".concat(e,"?").concat(a),{headers:{accept:"application/dns-json"},signal:null==o?void 0:o.signal});if(200!==r.status)throw new Error("Unexpected HTTP status: ".concat(r.status," - ").concat(r.statusText));var n=WT(yield r.json());return null===(t=o.onProgress)||void 0===t||t.call(o,new av("dns:response",{detail:n})),n})),{signal:o.signal});if(null==s)throw new Error("No DNS response received");return s}));return function(e){return t.apply(this,arguments)}}()}var JT=(QT||(QT=1,GT=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)}}}),GT),ZT=a(JT);class $T{constructor(t){e(this,"lru",void 0),this.lru=ZT(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 WT({answers:n})}getAnswers(e,r){var n="".concat(e.toLowerCase(),"-").concat(r),i=this.lru.get(n);if(null!=i){var o=i.filter((e=>e.expires>Date.now())).map((e=>{var{expires:r,value:n}=e;return t(t({},n),{},{TTL:Math.round((r-Date.now())/1e3),type:eP[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 XT=class{constructor(t){var r,n,i;e(this,"resolvers",void 0),e(this,"cache",void 0),this.resolvers={},this.cache=(i=null!==(r=t.cacheSize)&&void 0!==r?r:1e3,new $T(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["."]=[YT("https://cloudflare-dns.com/dns-query"),YT("https://dns.google/resolve")])}query(e){var n=arguments,i=this;return r((function*(){var r,o,a=n.length>1&&void 0!==n[1]?n[1]:{},s=KT(a.types),l=!1!==a.cached?i.cache.get(e,s):void 0;if(null!=l)return null===(o=a.onProgress)||void 0===o||o.call(a,new av("dns:cache",{detail:l})),l;var u="".concat(e.split(".").pop(),"."),c=(null!==(r=i.resolvers[u])&&void 0!==r?r:i.resolvers["."]).sort((()=>Math.random()>.5?-1:1)),d=[];for(var h of c){var v;if(!0===(null===(v=a.signal)||void 0===v?void 0:v.aborted))break;try{var p=yield h(e,t(t({},a),{},{types:s}));for(var f of p.Answer)i.cache.add(e,f);return p}catch(e){var g;d.push(e),null===(g=a.onProgress)||void 0===g||g.call(a,new av("dns:error",{detail:e}))}}if(1===d.length)throw d[0];throw new AggregateError(d,"DNS lookup of ".concat(e," ").concat(s," failed"))}))()}};var eP;function tP(){return new XT(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"}(eP||(eP={}));var rP=["string","number","bigint","symbol"],nP=["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 iP(e){if(null===e)return"null";if(void 0===e)return"undefined";if(!0===e||!1===e)return"boolean";var t=typeof e;if(rP.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(nP.includes(t))return t;return}(e);return r||"Object"}class oP{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}}oP.uint=new oP(0,"uint",!0),oP.negint=new oP(1,"negint",!0),oP.bytes=new oP(2,"bytes",!0),oP.string=new oP(3,"string",!0),oP.array=new oP(4,"array",!1),oP.map=new oP(5,"map",!1),oP.tag=new oP(6,"tag",!1),oP.float=new oP(7,"float",!0),oP.false=new oP(7,"false",!0),oP.true=new oP(7,"true",!0),oP.null=new oP(7,"null",!0),oP.undefined=new oP(7,"undefined",!0),oP.break=new oP(7,"break",!0);class aP{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 sP=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&"function"==typeof globalThis.Buffer.isBuffer,lP=new TextDecoder,uP=new TextEncoder;function cP(e){return sP&&globalThis.Buffer.isBuffer(e)}function dP(e){return e instanceof Uint8Array?cP(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e:Uint8Array.from(e)}var hP=sP?(e,t,r)=>r-t>64?globalThis.Buffer.from(e.subarray(t,r)).toString("utf8"):wP(e,t,r):(e,t,r)=>r-t>64?lP.decode(e.subarray(t,r)):wP(e,t,r),vP=sP?e=>e.length>64?globalThis.Buffer.from(e):mP(e):e=>e.length>64?uP.encode(e):mP(e),pP=e=>Uint8Array.from(e),fP=sP?(e,t,r)=>cP(e)?new Uint8Array(e.subarray(t,r)):e.slice(t,r):(e,t,r)=>e.slice(t,r),gP=sP?(e,t)=>(e=e.map((e=>e instanceof Uint8Array?e:globalThis.Buffer.from(e))),dP(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},yP=sP?e=>globalThis.Buffer.allocUnsafe(e):e=>new Uint8Array(e);function mP(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 wP(e,t,r){for(var n=[];t<r;){var i=e[t],o=null,a=i>239?4:i>223?3:i>191?2:1;if(t+a<=r){var s=void 0,l=void 0,u=void 0,c=void 0;switch(a){case 1:i<128&&(o=i);break;case 2:128==(192&(s=e[t+1]))&&(c=(31&i)<<6|63&s)>127&&(o=c);break;case 3:s=e[t+1],l=e[t+2],128==(192&s)&&128==(192&l)&&(c=(15&i)<<12|(63&s)<<6|63&l)>2047&&(c<55296||c>57343)&&(o=c);break;case 4:s=e[t+1],l=e[t+2],u=e[t+3],128==(192&s)&&128==(192&l)&&128==(192&u)&&(c=(15&i)<<18|(63&s)<<12|(63&l)<<6|63&u)>65535&&c<1114112&&(o=c)}}null===o?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),t+=a}return SP(n)}var bP=4096;function SP(e){var t=e.length;if(t<=bP)return String.fromCharCode.apply(String,e);for(var r="",n=0;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=bP));return r}class EP{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=yP(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=fP(r,0,this.cursor)}else e=gP(this.chunks,this.cursor);return t&&this.reset(),e}}var kP="CBOR decode error:",xP="CBOR encode error:";function AP(e,t,r){if(e.length-t<r)throw new Error("".concat(kP," not enough data for type"))}var CP=[24,256,65536,4294967296,BigInt("18446744073709551616")];function IP(e,t,r){AP(e,t,1);var n=e[t];if(!0===r.strict&&n<CP[0])throw new Error("".concat(kP," integer encoded in more bytes than necessary (strict decode)"));return n}function TP(e,t,r){AP(e,t,2);var n=e[t]<<8|e[t+1];if(!0===r.strict&&n<CP[1])throw new Error("".concat(kP," integer encoded in more bytes than necessary (strict decode)"));return n}function PP(e,t,r){AP(e,t,4);var n=16777216*e[t]+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];if(!0===r.strict&&n<CP[2])throw new Error("".concat(kP," integer encoded in more bytes than necessary (strict decode)"));return n}function _P(e,t,r){AP(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<CP[3])throw new Error("".concat(kP," 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(kP," integers outside of the safe integer range are not supported"))}function BP(e,t){return NP(e,0,t.value)}function NP(e,t,r){if(r<CP[0]){var n=Number(r);e.push([t|n])}else if(r<CP[1]){var i=Number(r);e.push([24|t,i])}else if(r<CP[2]){var o=Number(r);e.push([25|t,o>>>8,255&o])}else if(r<CP[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<CP[4]))throw new Error("".concat(kP," encountered BigInt larger than allowable range"));var l=[27|t,0,0,0,0,0,0,0],u=Number(s&BigInt(4294967295)),c=Number(s>>BigInt(32)&BigInt(4294967295));l[8]=255&u,u>>=8,l[7]=255&u,u>>=8,l[6]=255&u,u>>=8,l[5]=255&u,l[4]=255&c,c>>=8,l[3]=255&c,c>>=8,l[2]=255&c,c>>=8,l[1]=255&c,e.push(l)}}BP.encodedSize=function(e){return NP.encodedSize(e.value)},NP.encodedSize=function(e){return e<CP[0]?1:e<CP[1]?2:e<CP[2]?3:e<CP[3]?5:9},BP.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};var DP=BigInt(-1),RP=BigInt(1);function OP(e,t){var r=t.value,n="bigint"==typeof r?r*DP-RP:-1*r-1;NP(e,t.type.majorEncoded,n)}function LP(e,t,r,n){AP(e,t,r+n);var i=fP(e,t+r,t+r+n);return new aP(oP.bytes,i,r+n)}function MP(e,t,r,n){return LP(e,t,1,r)}function UP(e){return void 0===e.encodedBytes&&(e.encodedBytes=e.type===oP.string?vP(e.value):e.value),e.encodedBytes}function FP(e,t){var r=UP(t);NP(e,t.type.majorEncoded,r.length),e.push(r)}function zP(e,t,r,n,i){var o=r+n;AP(e,t,o);var a=new aP(oP.string,hP(e,t+r,t+o),o);return!0===i.retainStringBytes&&(a.byteValue=fP(e,t+r,t+o)),a}function jP(e,t,r,n){return zP(e,t,1,r,n)}OP.encodedSize=function(e){var t=e.value,r="bigint"==typeof t?t*DP-RP:-1*t-1;return r<CP[0]?1:r<CP[1]?2:r<CP[2]?3:r<CP[3]?5:9},OP.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0},FP.encodedSize=function(e){var t=UP(e);return NP.encodedSize(t.length)+t.length},FP.compareTokens=function(e,t){return r=UP(e),n=UP(t),r.length<n.length?-1:r.length>n.length?1:function(e,t){if(cP(e)&&cP(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 VP=FP;function qP(e,t,r,n){return new aP(oP.array,n,r)}function HP(e,t,r,n){return qP(0,0,1,r)}function KP(e,t){NP(e,oP.array.majorEncoded,t.value)}function WP(e,t,r,n){return new aP(oP.map,n,r)}function GP(e,t,r,n){return WP(0,0,1,r)}function QP(e,t){NP(e,oP.map.majorEncoded,t.value)}function YP(e,t,r,n){return new aP(oP.tag,r,1)}function JP(e,t){NP(e,oP.tag.majorEncoded,t.value)}KP.compareTokens=BP.compareTokens,KP.encodedSize=function(e){return NP.encodedSize(e.value)},QP.compareTokens=BP.compareTokens,QP.encodedSize=function(e){return NP.encodedSize(e.value)},JP.compareTokens=BP.compareTokens,JP.encodedSize=function(e){return NP.encodedSize(e.value)};function ZP(e,t,r){if(r){if(!1===r.allowNaN&&Number.isNaN(e))throw new Error("".concat(kP," NaN values are not supported"));if(!1===r.allowInfinity&&(e===1/0||e===-1/0))throw new Error("".concat(kP," Infinity values are not supported"))}return new aP(oP.float,e,t)}function $P(e,t,r){var n,i=t.value;if(!1===i)e.push([20|oP.float.majorEncoded]);else if(!0===i)e.push([21|oP.float.majorEncoded]);else if(null===i)e.push([22|oP.float.majorEncoded]);else if(void 0===i)e.push([23|oP.float.majorEncoded]);else{var o=!1;r&&!0===r.float64||(r_(i),i===n_(t_,1)||Number.isNaN(i)?(t_[0]=249,e.push(t_.slice(0,3)),o=!0):(i_(i),i===o_(t_,1)&&(t_[0]=250,e.push(t_.slice(0,5)),o=!0))),o||(n=i,e_.setFloat64(0,n,!1),a_(t_,1),t_[0]=251,e.push(t_.slice(0,9)))}}$P.encodedSize=function(e,t){var r=e.value;if(!1===r||!0===r||null==r)return 1;if(!t||!0!==t.float64){r_(r);var n=n_(t_,1);if(r===n||Number.isNaN(r))return 3;if(i_(r),r===(n=o_(t_,1)))return 5}return 9};var XP=new ArrayBuffer(9),e_=new DataView(XP,1),t_=new Uint8Array(XP,0);function r_(e){if(e===1/0)e_.setUint16(0,31744,!1);else if(e===-1/0)e_.setUint16(0,64512,!1);else if(Number.isNaN(e))e_.setUint16(0,32256,!1);else{e_.setFloat32(0,e);var t=e_.getUint32(0),r=(2139095040&t)>>23,n=8388607&t;if(255===r)e_.setUint16(0,31744,!1);else if(0===r)e_.setUint16(0,(2147483648&e)>>16|n>>13,!1);else{var i=r-127;i<-24?e_.setUint16(0,0):i<-14?e_.setUint16(0,(2147483648&t)>>16|1<<24+i,!1):e_.setUint16(0,(2147483648&t)>>16|i+15<<10|n>>13,!1)}}}function n_(e,t){if(e.length-t<2)throw new Error("".concat(kP," 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 i_(e){e_.setFloat32(0,e,!1)}function o_(e,t){if(e.length-t<4)throw new Error("".concat(kP," not enough data for float32"));var r=(e.byteOffset||0)+t;return new DataView(e.buffer,r,4).getFloat32(0,!1)}function a_(e,t){if(e.length-t<8)throw new Error("".concat(kP," not enough data for float64"));var r=(e.byteOffset||0)+t;return new DataView(e.buffer,r,8).getFloat64(0,!1)}function s_(e,t,r){throw new Error("".concat(kP," encountered invalid minor (").concat(r,") for major ").concat(e[t]>>>5))}function l_(e){return()=>{throw new Error("".concat(kP," ").concat(e))}}$P.compareTokens=BP.compareTokens;for(var u_=[],c_=0;c_<=23;c_++)u_[c_]=s_;u_[24]=function(e,t,r,n){return new aP(oP.uint,IP(e,t+1,n),2)},u_[25]=function(e,t,r,n){return new aP(oP.uint,TP(e,t+1,n),3)},u_[26]=function(e,t,r,n){return new aP(oP.uint,PP(e,t+1,n),5)},u_[27]=function(e,t,r,n){return new aP(oP.uint,_P(e,t+1,n),9)},u_[28]=s_,u_[29]=s_,u_[30]=s_,u_[31]=s_;for(var d_=32;d_<=55;d_++)u_[d_]=s_;u_[56]=function(e,t,r,n){return new aP(oP.negint,-1-IP(e,t+1,n),2)},u_[57]=function(e,t,r,n){return new aP(oP.negint,-1-TP(e,t+1,n),3)},u_[58]=function(e,t,r,n){return new aP(oP.negint,-1-PP(e,t+1,n),5)},u_[59]=function(e,t,r,n){var i=_P(e,t+1,n);if("bigint"!=typeof i){var o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new aP(oP.negint,o,9)}if(!0!==n.allowBigInt)throw new Error("".concat(kP," integers outside of the safe integer range are not supported"));return new aP(oP.negint,DP-BigInt(i),9)},u_[60]=s_,u_[61]=s_,u_[62]=s_,u_[63]=s_;for(var h_=64;h_<=87;h_++)u_[h_]=MP;u_[88]=function(e,t,r,n){return LP(e,t,2,IP(e,t+1,n))},u_[89]=function(e,t,r,n){return LP(e,t,3,TP(e,t+1,n))},u_[90]=function(e,t,r,n){return LP(e,t,5,PP(e,t+1,n))},u_[91]=function(e,t,r,n){var i=_P(e,t+1,n);if("bigint"==typeof i)throw new Error("".concat(kP," 64-bit integer bytes lengths not supported"));return LP(e,t,9,i)},u_[92]=s_,u_[93]=s_,u_[94]=s_,u_[95]=l_("indefinite length bytes/strings are not supported");for(var v_=96;v_<=119;v_++)u_[v_]=jP;u_[120]=function(e,t,r,n){return zP(e,t,2,IP(e,t+1,n),n)},u_[121]=function(e,t,r,n){return zP(e,t,3,TP(e,t+1,n),n)},u_[122]=function(e,t,r,n){return zP(e,t,5,PP(e,t+1,n),n)},u_[123]=function(e,t,r,n){var i=_P(e,t+1,n);if("bigint"==typeof i)throw new Error("".concat(kP," 64-bit integer string lengths not supported"));return zP(e,t,9,i,n)},u_[124]=s_,u_[125]=s_,u_[126]=s_,u_[127]=l_("indefinite length bytes/strings are not supported");for(var p_=128;p_<=151;p_++)u_[p_]=HP;u_[152]=function(e,t,r,n){return qP(0,0,2,IP(e,t+1,n))},u_[153]=function(e,t,r,n){return qP(0,0,3,TP(e,t+1,n))},u_[154]=function(e,t,r,n){return qP(0,0,5,PP(e,t+1,n))},u_[155]=function(e,t,r,n){var i=_P(e,t+1,n);if("bigint"==typeof i)throw new Error("".concat(kP," 64-bit integer array lengths not supported"));return qP(0,0,9,i)},u_[156]=s_,u_[157]=s_,u_[158]=s_,u_[159]=function(e,t,r,n){if(!1===n.allowIndefinite)throw new Error("".concat(kP," indefinite length items not allowed"));return qP(0,0,1,1/0)};for(var f_=160;f_<=183;f_++)u_[f_]=GP;u_[184]=function(e,t,r,n){return WP(0,0,2,IP(e,t+1,n))},u_[185]=function(e,t,r,n){return WP(0,0,3,TP(e,t+1,n))},u_[186]=function(e,t,r,n){return WP(0,0,5,PP(e,t+1,n))},u_[187]=function(e,t,r,n){var i=_P(e,t+1,n);if("bigint"==typeof i)throw new Error("".concat(kP," 64-bit integer map lengths not supported"));return WP(0,0,9,i)},u_[188]=s_,u_[189]=s_,u_[190]=s_,u_[191]=function(e,t,r,n){if(!1===n.allowIndefinite)throw new Error("".concat(kP," indefinite length items not allowed"));return WP(0,0,1,1/0)};for(var g_=192;g_<=215;g_++)u_[g_]=YP;u_[216]=function(e,t,r,n){return new aP(oP.tag,IP(e,t+1,n),2)},u_[217]=function(e,t,r,n){return new aP(oP.tag,TP(e,t+1,n),3)},u_[218]=function(e,t,r,n){return new aP(oP.tag,PP(e,t+1,n),5)},u_[219]=function(e,t,r,n){return new aP(oP.tag,_P(e,t+1,n),9)},u_[220]=s_,u_[221]=s_,u_[222]=s_,u_[223]=s_;for(var y_=224;y_<=243;y_++)u_[y_]=l_("simple values are not supported");u_[244]=s_,u_[245]=s_,u_[246]=s_,u_[247]=function(e,t,r,n){if(!1===n.allowUndefined)throw new Error("".concat(kP," undefined values are not supported"));return!0===n.coerceUndefinedToNull?new aP(oP.null,null,1):new aP(oP.undefined,void 0,1)},u_[248]=l_("simple values are not supported"),u_[249]=function(e,t,r,n){return ZP(n_(e,t+1),3,n)},u_[250]=function(e,t,r,n){return ZP(o_(e,t+1),5,n)},u_[251]=function(e,t,r,n){return ZP(a_(e,t+1),9,n)},u_[252]=s_,u_[253]=s_,u_[254]=s_,u_[255]=function(e,t,r,n){if(!1===n.allowIndefinite)throw new Error("".concat(kP," indefinite length items not allowed"));return new aP(oP.break,void 0,1)};for(var m_=[],w_=0;w_<24;w_++)m_[w_]=new aP(oP.uint,w_,1);for(var b_=-1;b_>=-24;b_--)m_[31-b_]=new aP(oP.negint,b_,1);m_[64]=new aP(oP.bytes,new Uint8Array(0),1),m_[96]=new aP(oP.string,"",1),m_[128]=new aP(oP.array,0,1),m_[160]=new aP(oP.map,0,1),m_[244]=new aP(oP.false,!1,1),m_[245]=new aP(oP.true,!0,1),m_[246]=new aP(oP.null,null,1);var S_={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=k_[i].compareTokens(r,n);return o},quickEncodeToken:function(e){switch(e.type){case oP.false:return pP([244]);case oP.true:return pP([245]);case oP.null:return pP([246]);case oP.bytes:return e.value.length?void 0:pP([64]);case oP.string:return""===e.value?pP([96]):void 0;case oP.array:return 0===e.value?pP([128]):void 0;case oP.map:return 0===e.value?pP([160]):void 0;case oP.uint:return e.value<24?pP([Number(e.value)]):void 0;case oP.negint:if(e.value>=-24)return pP([31-Number(e.value)])}}};var E_,k_=((E_=[])[oP.uint.major]=BP,E_[oP.negint.major]=OP,E_[oP.bytes.major]=FP,E_[oP.string.major]=VP,E_[oP.array.major]=KP,E_[oP.map.major]=QP,E_[oP.tag.major]=JP,E_[oP.float.major]=$P,E_),x_=new EP;class A_{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(xP," object contains circular references"));return new A_(t,e)}}var C_={null:new aP(oP.null,null),undefined:new aP(oP.undefined,void 0),true:new aP(oP.true,!0),false:new aP(oP.false,!1),emptyArray:new aP(oP.array,0),emptyMap:new aP(oP.map,0)},I_={number:(e,t,r,n)=>Number.isInteger(e)&&Number.isSafeInteger(e)?new aP(e>=0?oP.uint:oP.negint,e):new aP(oP.float,e),bigint:(e,t,r,n)=>e>=BigInt(0)?new aP(oP.uint,e):new aP(oP.negint,e),Uint8Array:(e,t,r,n)=>new aP(oP.bytes,e),string:(e,t,r,n)=>new aP(oP.string,e),boolean:(e,t,r,n)=>e?C_.true:C_.false,null:(e,t,r,n)=>C_.null,undefined:(e,t,r,n)=>C_.undefined,ArrayBuffer:(e,t,r,n)=>new aP(oP.bytes,new Uint8Array(e)),DataView:(e,t,r,n)=>new aP(oP.bytes,new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),Array(e,t,r,n){if(!e.length)return!0===r.addBreakTokens?[C_.emptyArray,new aP(oP.break)]:C_.emptyArray;n=A_.createCheck(n,e);var i=[],o=0;for(var a of e)i[o++]=P_(a,r,n);return r.addBreakTokens?[new aP(oP.array,e.length),i,new aP(oP.break)]:[new aP(oP.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?[C_.emptyMap,new aP(oP.break)]:C_.emptyMap;n=A_.createCheck(n,e);var s=[],l=0;for(var u of o)s[l++]=[P_(u,r,n),P_(i?e.get(u):e[u],r,n)];return function(e,t){t.mapSorter&&e.sort(t.mapSorter)}(s,r),r.addBreakTokens?[new aP(oP.map,a),s,new aP(oP.break)]:[new aP(oP.map,a),s]}};for(var T_ of(I_.Map=I_.Object,I_.Buffer=I_.Uint8Array,"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" ")))I_["".concat(T_,"Array")]=I_.DataView;function P_(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0,n=iP(e),i=t&&t.typeEncoders&&t.typeEncoders[n]||I_[n];if("function"==typeof i){var o=i(e,n,t,r);if(null!=o)return o}var a=I_[n];if(!a)throw new Error("".concat(xP," unsupported type: ").concat(n));return a(e,n,t,r)}function __(e,t,r,n){if(Array.isArray(t))for(var i of t)__(e,i,r,n);else r[t.type.major](e,t,n)}function B_(e,t,r){var n=P_(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 EP(a);if(o(s,n,r),1!==s.chunks.length)throw new Error("Unexpected error: pre-calculated length for ".concat(n," was wrong"));return dP(s.chunks[0])}}return x_.reset(),__(x_,n,t,r),x_.toBytes(!0)}function N_(e,t){return t=Object.assign({},S_,t),B_(e,k_,t)}var D_={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0};class R_{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=m_[e];if(void 0===t){var r=u_[e];if(!r)throw new Error("".concat(kP," 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 O_=Symbol.for("DONE"),L_=Symbol.for("BREAK");function M_(e,t){if(e.done())return O_;var r=e.next();if(r.type===oP.break)return L_;if(r.type.terminal)return r.value;if(r.type===oP.array)return function(e,t,r){for(var n=[],i=0;i<e.value;i++){var o=M_(t,r);if(o===L_){if(e.value===1/0)break;throw new Error("".concat(kP," got unexpected break to lengthed array"))}if(o===O_)throw new Error("".concat(kP," found array but not enough entries (got ").concat(i,", expected ").concat(e.value,")"));n[i]=o}return n}(r,e,t);if(r.type===oP.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=M_(t,r);if(s===L_){if(e.value===1/0)break;throw new Error("".concat(kP," got unexpected break to lengthed map"))}if(s===O_)throw new Error("".concat(kP," 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(kP," 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(kP,' found repeat map key "').concat(s,'"'));var l=M_(t,r);if(l===O_)throw new Error("".concat(kP," 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===oP.tag){if(t.tags&&"function"==typeof t.tags[r.value]){var n=M_(e,t);return t.tags[r.value](n)}throw new Error("".concat(kP," tag not supported (").concat(r.value,")"))}throw new Error("unsupported")}function U_(e,t){var[r,n]=function(e,t){if(!(e instanceof Uint8Array))throw new Error("".concat(kP," data to decode must be a Uint8Array"));var r=(t=Object.assign({},D_,t)).tokenizer||new R_(e,t),n=M_(r,t);if(n===O_)throw new Error("".concat(kP," did not find any content to decode"));if(n===L_)throw new Error("".concat(kP," got unexpected break"));return[n,e.subarray(r.pos())]}(e,t);if(n.length>0)throw new Error("".concat(kP," too many terminals, data makes no sense"));return r}function F_(){var{enumerable:e=!0,configurable:t=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{enumerable:e,configurable:t,writable:!1}}function*z_(e,t){if(null!=t&&"object"==typeof t)if(Array.isArray(t))for(var[r,n]of t.entries()){var i=[...e,r],o=it.asCID(n);null!=o?yield[i.join("/"),o]:"object"==typeof n&&(yield*j_(n,i))}else{var a=it.asCID(t);null!=a?yield[e.join("/"),a]:yield*j_(t,e)}}function*j_(e,t){if(!(null==e||e instanceof Uint8Array)){var r=it.asCID(e);for(var[n,i]of(null!=r&&(yield[t.join("/"),r]),Object.entries(e))){var o=[...t,n];yield*z_(o,i)}}}function*V_(e,t){if(Array.isArray(t))for(var[r,n]of t.entries()){var i=[...e,r];yield i.join("/"),"object"==typeof n&&null==it.asCID(n)&&(yield*q_(n,i))}else yield*q_(t,e)}function*q_(e,t){if(null!=e&&"object"==typeof e)for(var[r,n]of Object.entries(e)){var i=[...t,r];yield i.join("/"),null==n||n instanceof Uint8Array||"object"!=typeof n||null!=it.asCID(n)||(yield*V_(i,n))}}class H_{constructor(t){var{cid:r,bytes:n,value:i}=t;if(e(this,"cid",void 0),e(this,"bytes",void 0),e(this,"value",void 0),e(this,"asBlock",void 0),null==r||null==n||void 0===i)throw new Error("Missing required argument");this.cid=r,this.bytes=n,this.value=i,this.asBlock=this,Object.defineProperties(this,{cid:F_(),bytes:F_(),value:F_(),asBlock:F_()})}links(){return j_(this.value,[])}tree(){return q_(this.value,[])}get(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/";return function(e,t){var r=e;for(var[n,i]of t.entries()){if(null==(r=r[i]))throw new Error("Object has no property at ".concat(t.slice(0,n+1).map((e=>"[".concat(JSON.stringify(e),"]"))).join("")));var o=it.asCID(r);if(null!=o)return{value:o,remaining:t.slice(n+1).join("/")}}return{value:r}}(this.value,e.split("/").filter(Boolean))}}var K_="/pin/",W_="/pinned-block/",G_=te;function Q_(e){return 0===e.version&&(e=e.toV1()),new lc("".concat(K_).concat(e.toString(G_)))}var Y_=new WeakSet;class J_{constructor(t,r,n){d(this,Y_),e(this,"datastore",void 0),e(this,"blockstore",void 0),e(this,"getCodec",void 0),this.datastore=t,this.blockstore=r,this.getCodec=n}add(e){var r=this;return l((function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(i,o){var a=Q_(e);if(yield u(r.datastore.has(a)))throw new Error("Already pinned");var l=Math.round(null!==(i=n.depth)&&void 0!==i?i:1/0);if(l<0)throw new Error("Depth must be greater than or equal to 0");var c,d=new fv({concurrency:1}),v=!1,p=!1;try{for(var f,g=s(h(Y_,r,Z_).call(r,e,d,t(t({},n),{},{depth:l})));v=!(f=yield u(g.next())).done;v=!1){var y=f.value;yield u(h(Y_,r,$_).call(r,y,(t=>null==t.pinnedBy.find((t=>St(t,e.bytes)))&&(t.pinCount++,t.pinnedBy.push(e.bytes),!0)),n)),yield y}}catch(e){p=!0,c=e}finally{try{v&&null!=g.return&&(yield u(g.return()))}finally{if(p)throw c}}var m={depth:l,metadata:null!==(o=n.metadata)&&void 0!==o?o:{}};yield u(r.datastore.put(a,N_(m),n))}()})).apply(this,arguments)}rm(e){var r=this;return l((function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var i=Q_(e),o=U_(yield u(r.datastore.get(i,n)));yield u(r.datastore.delete(i,n));var a,l=new fv({concurrency:1}),c=!1,d=!1;try{for(var v,p=s(h(Y_,r,Z_).call(r,e,l,t(t({},n),{},{depth:o.depth})));c=!(v=yield u(p.next())).done;c=!1){var f=v.value;yield u(h(Y_,r,$_).call(r,f,(t=>(t.pinCount--,t.pinnedBy=t.pinnedBy.filter((t=>St(t,e.bytes))),!0)),t(t({},n),{},{depth:o.depth}))),yield f}}catch(e){d=!0,a=e}finally{try{c&&null!=p.return&&(yield u(p.return()))}finally{if(d)throw a}}}()})).apply(this,arguments)}ls(){var e=this;return l((function(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var n,i=!1,o=!1;try{for(var a,l=s(e.datastore.query({prefix:K_+(null!=r.cid?"".concat(r.cid.toString(te)):"")},r));i=!(a=yield u(l.next())).done;i=!1){var{key:c,value:d}=a.value,h=it.parse(c.toString().substring(5),te),v=U_(d);yield t({cid:h},v)}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}()})).apply(this,arguments)}isPinned(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{},i=new lc("".concat(W_).concat(G_.encode(e.multihash.bytes)));return n.datastore.has(i,r)}))()}get(e,t){var n=this;return r((function*(){var r=Q_(e);return U_(yield n.datastore.get(r,t))}))()}setMetadata(e,t,n){var i=this;return r((function*(){var r=Q_(e),o=U_(yield i.datastore.get(r,n));o.metadata=null!=t?t:{},yield i.datastore.put(r,N_(o),n)}))()}}function Z_(e,n,i){var o=this;return l((function*(){if(-1!==i.depth){var a=yield u(o.getCodec(e.code)),l=function(e){var{bytes:t,cid:r,value:n,codec:i}=e,o=void 0!==n?n:null==i?void 0:i.decode(t);if(void 0===o)throw new Error('Missing required argument, must either provide "value" or "codec"');return new H_({cid:r,bytes:t,value:o})}({bytes:yield u(o.blockstore.get(e,i)),cid:e,codec:a});yield e;var d=function*(e){yield*c(s(yield u(n.add(r((function*(){return h(Y_,o,Z_).call(o,e,n,t(t({},i),{},{depth:i.depth-1}))}))))))};for(var[,v]of l.links())yield*d(v)}}))()}function $_(e,t,r){return X_.apply(this,arguments)}function X_(){return X_=r((function*(e,t,r){var n,i=new lc("".concat(W_).concat(G_.encode(e.multihash.bytes))),o={pinCount:0,pinnedBy:[]};try{o=U_(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,N_(o),r),null===(n=r.onProgress)||void 0===n||n.call(r,new av("helia:pin:add",e))))})),X_.apply(this,arguments)}class eB extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Insufficient providers found"),this.name="InsufficientProvidersError"}}e(eB,"name","InsufficientProvidersError");class tB extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No routers available"),this.name="NoRoutersAvailableError"}}e(tB,"name","NoRoutersAvailableError");class rB extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unknown hash algorithm"),this.name="UnknownHashAlgorithmError"}}e(rB,"name","UnknownHashAlgorithmError");class nB extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unknown codec"),this.name="UnknownCodecError"}}e(nB,"name","UnknownCodecError");class iB{constructor(t,r){var n,i,o,a,s,l,u,c,d,h,v,p,f,g,y,m;e(this,"log",void 0),e(this,"routers",void 0),e(this,"providerLookupConcurrency",void 0),this.log=t.logger.forComponent("helia:routing"),this.routers=null!==(n=r.routers)&&void 0!==n?n:[],this.providerLookupConcurrency=null!==(i=r.providerLookupConcurrency)&&void 0!==i?i:5,this.findProviders=null!==(o=null===(a=t.metrics)||void 0===a?void 0:a.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1}))&&void 0!==o?o:this.findProviders,this.provide=null!==(s=null===(l=t.metrics)||void 0===l?void 0:l.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1}))&&void 0!==s?s:this.provide,this.cancelReprovide=null!==(u=null===(c=t.metrics)||void 0===c?void 0:c.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1}))&&void 0!==u?u:this.cancelReprovide,this.put=null!==(d=null===(h=t.metrics)||void 0===h?void 0:h.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2}))&&void 0!==d?d:this.put,this.get=null!==(v=null===(p=t.metrics)||void 0===p?void 0:p.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1}))&&void 0!==v?v:this.get,this.findPeer=null!==(f=null===(g=t.metrics)||void 0===g?void 0:g.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1}))&&void 0!==f?f:this.findPeer,this.getClosestPeers=null!==(y=null===(m=t.metrics)||void 0===m?void 0:m.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1}))&&void 0!==y?y:this.getClosestPeers}start(){var e=this;return r((function*(){yield ss(...e.routers)}))()}stop(){var e=this;return r((function*(){yield us(...e.routers)}))()}findProviders(e){var t=this;return l((function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(0===t.routers.length)throw new tB("No content routers available");var i=new gv({concurrency:t.providerLookupConcurrency});i.addEventListener("error",(()=>{}));var o,a=!1,l=!1;try{for(var c,d=function*(){var e=c.value;if(null==e)return 0;if(0===e.multiaddrs.length){if(null!=i.find(e.id))return 0;i.add(r((function*(){try{var r=yield t.findPeer(e.id,n);return 0===r.multiaddrs.length?null:r}catch(r){return t.log.error("could not load multiaddrs for peer %p",e.id,r),null}})),{peerId:e.id,signal:n.signal}).catch((r=>{t.log.error("could not load multiaddrs for peer %p",e.id,r)}))}yield e},h=s(Uc(i.toGenerator(),...oB(t.routers,"findProviders").map((t=>t.findProviders(e,n)))));a=!(c=yield u(h.next())).done;a=!1)yield*d()}catch(e){l=!0,o=e}finally{try{a&&null!=h.return&&(yield u(h.return()))}finally{if(l)throw o}}}()})).apply(this,arguments)}provide(e){var t=arguments,n=this;return r((function*(){var i=t.length>1&&void 0!==t[1]?t[1]:{};if(0===n.routers.length)throw new tB("No content routers available");yield Promise.all(oB(n.routers,"provide").map(function(){var t=r((function*(t){yield t.provide(e,i)}));return function(e){return t.apply(this,arguments)}}()))}))()}cancelReprovide(e){var t=arguments,n=this;return r((function*(){var i=t.length>1&&void 0!==t[1]?t[1]:{};yield Promise.all(oB(n.routers,"cancelReprovide").map(function(){var t=r((function*(t){yield t.cancelReprovide(e,i)}));return function(e){return t.apply(this,arguments)}}()))}))()}put(e,t,n){var i=this;return r((function*(){yield Promise.all(oB(i.routers,"put").map(function(){var i=r((function*(r){yield r.put(e,t,n)}));return function(e){return i.apply(this,arguments)}}()))}))()}get(e,t){var n=this;return r((function*(){return Promise.any(oB(n.routers,"get").map(function(){var n=r((function*(r){return r.get(e,t)}));return function(e){return n.apply(this,arguments)}}()))}))()}findPeer(e,t){var n=this;return r((function*(){if(0===n.routers.length)throw new tB("No peer routers available");var r,i=n,o=Uc(...oB(n.routers,"findPeer").map((r=>l((function*(){try{yield yield u(r.findPeer(e,t))}catch(e){i.log.error(e)}}))()))),a=!1,c=!1;try{for(var d,h=s(o);a=!(d=yield h.next()).done;a=!1){var v=d.value;if(null!=v)return v}}catch(e){c=!0,r=e}finally{try{a&&null!=h.return&&(yield h.return())}finally{if(c)throw r}}throw new za("Could not find peer in routing")}))()}getClosestPeers(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(0===t.routers.length)throw new tB("No peer routers available");var n,i=!1,o=!1;try{for(var a,l=s(Uc(...oB(t.routers,"getClosestPeers").map((t=>t.getClosestPeers(e,r)))));i=!(a=yield u(l.next())).done;i=!1){var c=a.value;null!=c&&(yield c)}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}()})).apply(this,arguments)}}function oB(e,t){return e.filter((e=>null!=e[t]))}let aB=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 sB=new WeakMap;class lB extends EventTarget{constructor(){super(),n(this,sB,new Map)}listenerCount(e){var t=o(sB,this).get(e);return null==t?0:t.length}addEventListener(e,t,r){var n;super.addEventListener(e,t,r);var i=o(sB,this).get(e);null==i&&(i=[],o(sB,this).set(e,i)),i.push({callback:t,once:null!==(n=!0!==r&&!1!==r&&(null==r?void 0:r.once))&&void 0!==n&&n})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),null!=t?t:null,r);var n=o(sB,this).get(e);null!=n&&(n=n.filter((e=>{var{callback:r}=e;return r!==t})),o(sB,this).set(e,n))}dispatchEvent(e){var t=super.dispatchEvent(e),r=o(sB,this).get(e.type);return null==r||(r=r.filter((e=>{var{once:t}=e;return!t})),o(sB,this).set(e.type,r)),t}safeDispatchEvent(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.dispatchEvent(new CustomEvent(e,t))}}class uB extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The queue was full"),this.name="QueueFullError"}}e(uB,"name","QueueFullError");class cB{constructor(t){var r;e(this,"deferred",void 0),e(this,"signal",void 0),this.signal=t,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),null===(r=this.signal)||void 0===r||r.addEventListener("abort",this.onAbort)}onAbort(){var e,t;this.deferred.reject(null!==(e=null===(t=this.signal)||void 0===t?void 0:t.reason)&&void 0!==e?e:new aB)}cleanup(){var e;null===(e=this.signal)||void 0===e||e.removeEventListener("abort",this.onAbort)}}class dB{constructor(t,r){e(this,"id",void 0),e(this,"fn",void 0),e(this,"options",void 0),e(this,"recipients",void 0),e(this,"status",void 0),e(this,"timeline",void 0),e(this,"controller",void 0),this.id="".concat(parseInt(String(1e9*Math.random()),10).toString()).concat(Date.now()),this.status="queued",this.fn=t,this.options=r,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){var e=this.recipients.reduce(((e,t)=>{var r;return e&&!0===(null===(r=t.signal)||void 0===r?void 0:r.aborted)}),!0);e&&(this.controller.abort(new aB),this.cleanup())}join(){var e=arguments,t=this;return r((function*(){var r,n=e.length>0&&void 0!==e[0]?e[0]:{},i=new cB(n.signal);return t.recipients.push(i),null===(r=n.signal)||void 0===r||r.addEventListener("abort",t.onAbort),i.deferred.promise}))()}run(){var e=this;return r((function*(){e.status="running",e.timeline.started=Date.now();try{var r;e.controller.signal.throwIfAborted();var n=yield Nc(e.fn(t(t({},null!==(r=e.options)&&void 0!==r?r:{}),{},{signal:e.controller.signal})),e.controller.signal);e.recipients.forEach((e=>{e.deferred.resolve(n)})),e.status="complete"}catch(t){e.recipients.forEach((e=>{e.deferred.reject(t)})),e.status="errored"}finally{e.timeline.finished=Date.now(),e.cleanup()}}))()}cleanup(){this.recipients.forEach((e=>{var t;e.cleanup(),null===(t=e.signal)||void 0===t||t.removeEventListener("abort",this.onAbort)}))}}function hB(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 vB extends lB{constructor(){var t,r,n,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),e(this,"concurrency",void 0),e(this,"maxSize",void 0),e(this,"queue",void 0),e(this,"pending",void 0),e(this,"sort",void 0),e(this,"autoStart",void 0),this.concurrency=null!==(t=i.concurrency)&&void 0!==t?t:Number.POSITIVE_INFINITY,this.maxSize=null!==(r=i.maxSize)&&void 0!==r?r:Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=null===(n=i.autoStart)||void 0===n||n,this.sort=i.sort,this.queue=[],this.emitEmpty=hB(this.emitEmpty.bind(this),1),this.emitIdle=hB(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){var e;for(var t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally((()=>{for(var t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()})),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}start(){!1===this.autoStart&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}add(e,t){var n=this;return r((function*(){var r;if(null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),n.size===n.maxSize)throw new uB;var i=new dB(e,t);return n.enqueue(i),n.safeDispatchEvent("add"),n.autoStart&&n.tryToStartAnother(),i.join(t).then((e=>(n.safeDispatchEvent("success",{detail:{job:i,result:e}}),e))).catch((e=>{if("queued"===i.status)for(var t=0;t<n.queue.length;t++)if(n.queue[t]===i){n.queue.splice(t,1);break}throw n.safeDispatchEvent("failure",{detail:{job:i,error:e}}),e}))}))()}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach((e=>{e.abort(new aB)})),this.clear()}onEmpty(e){var t=this;return r((function*(){0!==t.size&&(yield lv(t,"empty",null==e?void 0:e.signal))}))()}onSizeLessThan(e,t){var n=this;return r((function*(){n.size<e||(yield lv(n,"next",null==t?void 0:t.signal,{filter:()=>n.size<e}))}))()}onIdle(e){var t=this;return r((function*(){0===t.pending&&0===t.size||(yield lv(t,"idle",null==e?void 0:e.signal))}))()}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}toGenerator(e){var t=this;return l((function*(){var r,n;null==e||null===(r=e.signal)||void 0===r||r.throwIfAborted();var i=_c({objectMode:!0}),o=e=>{null!=e?t.abort():t.clear(),i.end(e)},a=e=>{null!=e.detail&&i.push(e.detail.result)},l=e=>{o(e.detail.error)},d=()=>{o()},h=()=>{o(new aB("Queue aborted"))};t.addEventListener("success",a),t.addEventListener("failure",l),t.addEventListener("idle",d),null==e||null===(n=e.signal)||void 0===n||n.addEventListener("abort",h);try{yield*c(s(i),u)}finally{var v;t.removeEventListener("success",a),t.removeEventListener("failure",l),t.removeEventListener("idle",d),null==e||null===(v=e.signal)||void 0===v||v.removeEventListener("abort",h),o()}}))()}}var pB="lock:worker:request-read",fB="lock:worker:abort-read-request",gB="lock:worker:release-read",yB="lock:master:grant-read",mB="lock:master:error-read",wB="lock:worker:request-write",bB="lock:worker:abort-write-request",SB="lock:worker:release-write",EB="lock:master:grant-write",kB="lock:master:error-write",xB="lock:worker:finalize",AB="mortice",CB={singleProcess:!1},IB=(e,t,n,i,o,a,s,l,u)=>c=>{if(null!=c.data){var d,h={type:c.data.type,name:c.data.name,identifier:c.data.identifier};h.type===o&&e.safeDispatchEvent(n,{detail:{name:h.name,identifier:h.identifier,handler:(d=r((function*(){t.postMessage({type:u,name:h.name,identifier:h.identifier}),yield new Promise((e=>{var r=n=>{if(null!=(null==n?void 0:n.data)){var i=n.data.type,o=(n.data.name,n.data.identifier);i===l&&o===h.identifier&&(t.removeEventListener("message",r),e())}};t.addEventListener("message",r)}))})),function(){return d.apply(this,arguments)}),onError:e=>{t.postMessage({type:s,name:h.name,identifier:h.identifier,error:{message:e.message,name:e.name,stack:e.stack}})}}}),h.type===a&&e.safeDispatchEvent(i,{detail:{name:h.name,identifier:h.identifier}}),h.type===xB&&e.safeDispatchEvent("finalizeRequest",{detail:{name:h.name}})}};class TB{constructor(t){e(this,"name",void 0),e(this,"channel",void 0),this.name=t,this.channel=new BroadcastChannel(AB)}readLock(e){return this.sendRequest(pB,fB,yB,mB,gB,e)}writeLock(e){return this.sendRequest(wB,bB,EB,kB,SB,e)}finalize(){this.channel.postMessage({type:xB,name:this.name}),this.channel.close()}sendRequest(e,t,n,i,o,a){var s=this;return r((function*(){var r;null==a||null===(r=a.signal)||void 0===r||r.throwIfAborted();var l=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;return Math.random().toString().substring(2,e+2)}();return s.channel.postMessage({type:e,identifier:l,name:s.name}),new Promise(((e,r)=>{var u,c=()=>{s.channel.postMessage({type:t,identifier:l,name:s.name})};null==a||null===(u=a.signal)||void 0===u||u.addEventListener("abort",c,{once:!0});var d=t=>{var u,h;if((null===(u=t.data)||void 0===u?void 0:u.identifier)===l){var v;if((null===(h=t.data)||void 0===h?void 0:h.type)===n)s.channel.removeEventListener("message",d),null==a||null===(v=a.signal)||void 0===v||v.removeEventListener("abort",c),e((()=>{s.channel.postMessage({type:o,identifier:l,name:s.name})}));if(t.data.type===i){var p;s.channel.removeEventListener("message",d),null==a||null===(p=a.signal)||void 0===p||p.removeEventListener("abort",c);var f=new Error;null!=t.data.error&&(f.message=t.data.error.message,f.name=t.data.error.name,f.stack=t.data.error.stack),r(f)}}};s.channel.addEventListener("message",d)}))}))()}}var PB,_B=new Map;function BB(e){return"function"==typeof(null==e?void 0:e.readLock)&&"function"==typeof(null==e?void 0:e.writeLock)}function NB(e){if(null==PB&&(PB=(e=>{if(e=Object.assign({},CB,e),Boolean(globalThis.document)||e.singleProcess){var t=new BroadcastChannel(AB),r=new lB;return t.addEventListener("message",IB(r,t,"requestReadLock","abortReadLockRequest",pB,fB,mB,gB,yB)),t.addEventListener("message",IB(r,t,"requestWriteLock","abortWriteLockRequest",wB,bB,kB,SB,EB)),r}return new TB(e.name)})(e),!BB(PB))){var t=PB;t.addEventListener("requestReadLock",(e=>{var n=e.detail.name,i=e.detail.identifier,o=_B.get(n);if(null!=o){var a=new AbortController,s=e=>{e.detail.name===n&&e.detail.identifier===i&&a.abort()};t.addEventListener("abortReadLockRequest",s),o.readLock({signal:a.signal}).then(function(){var t=r((function*(t){yield e.detail.handler().finally((()=>{t()}))}));return function(e){return t.apply(this,arguments)}}()).catch((t=>{e.detail.onError(t)})).finally((()=>{t.removeEventListener("abortReadLockRequest",s)}))}})),t.addEventListener("requestWriteLock",(e=>{var n=e.detail.name,i=e.detail.identifier,o=_B.get(n);if(null!=o){var a=new AbortController,s=e=>{e.detail.name===n&&e.detail.identifier===i&&a.abort()};t.addEventListener("abortWriteLockRequest",s),o.writeLock({signal:a.signal}).then(function(){var t=r((function*(t){yield e.detail.handler().finally((()=>{t()}))}));return function(e){return t.apply(this,arguments)}}()).catch((t=>{e.detail.onError(t)})).finally((()=>{t.removeEventListener("abortWriteLockRequest",s)}))}})),t.addEventListener("finalizeRequest",(e=>{var t=e.detail.name,r=_B.get(t);null!=r&&r.finalize()}))}return PB}function DB(e,t){return RB.apply(this,arguments)}function RB(){return RB=r((function*(e,t){var n,i,o,a=new Promise(((e,t)=>{i=e,o=t})),s=()=>{o(new aB)};return null==t||null===(n=t.signal)||void 0===n||n.addEventListener("abort",s,{once:!0}),e.add(r((function*(){yield new Promise((e=>{i((()=>{var r;null==t||null===(r=t.signal)||void 0===r||r.removeEventListener("abort",s),e()}))}))})),{signal:null==t?void 0:t.signal}).catch((e=>{o(e)})),a})),RB.apply(this,arguments)}var OB={name:"lock",concurrency:1/0,singleProcess:!1};function LB(e){var t=Object.assign({},OB,e);return((e,t)=>{var n=_B.get(e);if(null!=n)return n;var i=NB(t);if(BB(i))return n=i,_B.set(e,n),n;var o,a=new vB({concurrency:1});return n={readLock:e=>r((function*(){if(null!=o)return DB(o,e);var n=o=new vB({concurrency:t.concurrency,autoStart:!1}),i=DB(o,e);return a.add(r((function*(){n.start(),yield n.onIdle().then((()=>{o===n&&(o=null)}))}))),i}))(),writeLock:e=>r((function*(){return o=null,DB(a,e)}))(),finalize:()=>{_B.delete(e)},queue:a},_B.set(e,n),n})(t.name,t)}class MB{constructor(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e(this,"lock",void 0),e(this,"child",void 0),e(this,"pins",void 0),e(this,"started",void 0),this.child=t,this.pins=r,this.lock=LB({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}start(){var e=this;return r((function*(){yield ss(e.child),e.started=!0}))()}stop(){var e=this;return r((function*(){yield us(e.child),e.started=!1}))()}unwrap(){return this.child}put(e,t){var n=arguments,i=this;return r((function*(){var r,o=n.length>2&&void 0!==n[2]?n[2]:{};null==o||null===(r=o.signal)||void 0===r||r.throwIfAborted();var a=yield i.lock.readLock();try{return yield i.child.put(e,t,o)}finally{a()}}))()}putMany(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(n){null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted();var i=yield u(t.lock.readLock());try{yield*c(s(t.child.putMany(e,r)),u)}finally{i()}}()})).apply(this,arguments)}get(e){var t=arguments,n=this;return r((function*(){var r,i=t.length>1&&void 0!==t[1]?t[1]:{};null==i||null===(r=i.signal)||void 0===r||r.throwIfAborted();var o=yield n.lock.readLock();try{return yield n.child.get(e,i)}finally{o()}}))()}getMany(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(n){null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted();var i=yield u(t.lock.readLock());try{yield*c(s(t.child.getMany(e,r)),u)}finally{i()}}()})).apply(this,arguments)}delete(e){var t=arguments,n=this;return r((function*(){var r,i=t.length>1&&void 0!==t[1]?t[1]:{};null==i||null===(r=i.signal)||void 0===r||r.throwIfAborted();var o=yield n.lock.writeLock();try{if(yield n.pins.isPinned(e))throw new Error("CID was pinned");yield n.child.delete(e,i)}finally{o()}}))()}deleteMany(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(n){null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted();var i=yield u(t.lock.writeLock());try{var o=t;yield*c(s(t.child.deleteMany(l((function*(){var t,r=!1,n=!1;try{for(var i,a=s(e);r=!(i=yield u(a.next())).done;r=!1){var l=i.value;if(yield u(o.pins.isPinned(l)))throw new Error("CID was pinned");yield l}}catch(e){n=!0,t=e}finally{try{r&&null!=a.return&&(yield u(a.return()))}finally{if(n)throw t}}}))(),r)),u)}finally{i()}}()})).apply(this,arguments)}has(e){var t=arguments,n=this;return r((function*(){var r,i=t.length>1&&void 0!==t[1]?t[1]:{};null==i||null===(r=i.signal)||void 0===r||r.throwIfAborted();var o=yield n.lock.readLock();try{return yield n.child.has(e,i)}finally{o()}}))()}getAll(){var e=this;return l((function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(r){null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted();var n=yield u(e.lock.readLock());try{yield*c(s(e.child.getAll(t)),u)}finally{n()}}()})).apply(this,arguments)}createSession(e,t){var r;return null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.child.createSession(e,t)}}var UB=new lc("/version");function FB(){return(FB=r((function*(e){if(yield e.has(UB)){var t=gt(yield e.get(UB));if(1!==parseInt(t,10))throw new Error("Unknown datastore version, a datastore migration may be required")}else yield e.put(UB,Et("".concat(1)))}))).apply(this,arguments)}function zB(e){return e instanceof ArrayBuffer?new Uint8Array(e,0,e.byteLength):e}var jB={float64:!0,typeEncoders:{Object:function(e){if(e.asCID!==e&&e["/"]!==e.bytes)return null;var t=it.asCID(e);if(!t)return null;var r=new Uint8Array(t.bytes.byteLength+1);return r.set(t.bytes,1),[new aP(oP.tag,42),new aP(oP.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}}},VB=t(t({},jB),{},{typeEncoders:t({},jB.typeEncoders)});var qB={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};qB.tags[42]=function(e){if(0!==e[0])throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return it.decode(e.subarray(1))};var HB=t(t({},qB),{},{tags:qB.tags.slice()}),KB="dag-cbor",WB=113,GB=e=>N_(e,jB),QB=e=>U_(zB(e),qB),YB=Object.freeze({__proto__:null,code:WB,decode:QB,decodeOptions:HB,encode:GB,encodeOptions:VB,name:KB,toByteView:zB});class JB extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){var t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===oP.array&&(t.elements++,1!==t.elements&&e.push([44])),t.type===oP.map&&(t.elements++,1!==t.elements&&(t.elements%2==1?e.push([44]):e.push([58]))))}[oP.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)}[oP.negint.major](e,t){this[oP.uint.major](e,t)}[oP.bytes.major](e,t){throw new Error("".concat(xP," unsupported type: Uint8Array"))}[oP.string.major](e,t){this.prefix(e);var r=vP(JSON.stringify(t.value));e.push(r.length>32?dP(r):r)}[oP.array.major](e,t){this.prefix(e),this.inRecursive.push({type:oP.array,elements:0}),e.push([91])}[oP.map.major](e,t){this.prefix(e),this.inRecursive.push({type:oP.map,elements:0}),e.push([123])}[oP.tag.major](e,t){}[oP.float.major](e,t){if("break"===t.type.name){var r=this.inRecursive.pop();if(r){if(r.type===oP.array)e.push([93]);else{if(r.type!==oP.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(xP," 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 ZB={addBreakTokens:!0,mapSorter:function(e,t){if(Array.isArray(e[0])||Array.isArray(t[0]))throw new Error("".concat(xP," complex map keys are not supported"));var r=e[0],n=t[0];if(r.type!==oP.string||n.type!==oP.string)throw new Error("".concat(xP," non-string map keys are not supported"));if(r<n)return-1;if(r>n)return 1;throw new Error("".concat(xP," unexpected duplicate map keys, this is not supported"))}};class $B{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(kP," 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(kP," 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 aP(oP.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(kP," unexpected token at position ").concat(this._pos));if(!this.done()&&46===this.ch()){if(r)throw new Error("".concat(kP," 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 aP(oP.float,o,this._pos-e):!0!==this.options.allowBigInt||Number.isSafeInteger(o)?new aP(o>=0?oP.uint:oP.negint,o,this._pos-e):new aP(o>=0?oP.uint:oP.negint,BigInt(i),this._pos-e)}parseString(){if(34!==this.ch())throw new Error("".concat(kP," 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 aP(oP.string,n,t)}}for(var i=this._pos,o=[],a=()=>{if(this._pos+4>=this.data.length)throw new Error("".concat(kP," 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(kP," 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(kP," unexpected unicode sequence at position ").concat(this._pos));switch(s){case 1:i<128&&(a=i);break;case 2:128==(192&(e=this.data[this._pos+1]))&&(n=(31&i)<<6|63&e)>127&&(a=n);break;case 3:e=this.data[this._pos+1],t=this.data[this._pos+2],128==(192&e)&&128==(192&t)&&(n=(15&i)<<12|(63&e)<<6|63&t)>2047&&(n<55296||n>57343)&&(a=n);break;case 4:e=this.data[this._pos+1],t=this.data[this._pos+2],r=this.data[this._pos+3],128==(192&e)&&128==(192&t)&&128==(192&r)&&(n=(15&i)<<18|(63&e)<<12|(63&t)<<6|63&r)>65535&&n<1114112&&(a=n)}null===a?(a=65533,s=1):a>65535&&(a-=65536,o.push(a>>>10&1023|55296),a=56320|1023&a),o.push(a),this._pos+=s};!this.done();){var l=this.ch(),u=void 0;switch(l){case 92:if(this._pos++,this.done())throw new Error("".concat(kP," unexpected string termination at position ").concat(this._pos));switch(u=this.ch(),this._pos++,u){case 34:case 39:case 92:case 47:o.push(u);break;case 98:o.push(8);break;case 116:o.push(9);break;case 110:o.push(10);break;case 102:o.push(12);break;case 114:o.push(13);break;case 117:o.push(a());break;default:throw new Error("".concat(kP," unexpected string escape character at position ").concat(this._pos))}break;case 34:return this._pos++,new aP(oP.string,SP(o),this._pos-i);default:if(l<32)throw new Error("".concat(kP," invalid control character at position ").concat(this._pos));l<128?(o.push(l),this._pos++):s()}}throw new Error("".concat(kP," unexpected end of string at position ").concat(this._pos))}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new aP(oP.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new aP(oP.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new aP(oP.null,null,4);case 102:return this.expect([102,97,108,115,101]),new aP(oP.false,!1,5);case 116:return this.expect([116,114,117,101]),new aP(oP.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(kP," 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 aP(oP.break,void 0,1);if(44!==this.ch())throw new Error("".concat(kP," 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 aP(oP.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 aP(oP.break,void 0,1);if(44!==this.ch())throw new Error("".concat(kP," 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 aP(oP.break,void 0,1);var e=this.parseString();if(this.skipWhitespace(),58!==this.ch())throw new Error("".concat(kP," 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(kP," unexpected parse state at position ").concat(this._pos,"; this shouldn't happen"))}}}function XB(e){var t=se.encode(e).slice(1);return[new aP(oP.map,1/0,1),new aP(oP.string,"/",1),new aP(oP.map,1/0,1),new aP(oP.string,"bytes",5),new aP(oP.string,t,t.length),new aP(oP.break,void 0,1),new aP(oP.break,void 0,1)]}function eN(e){return XB(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}var tN={typeEncoders:{Object:function(e){if(e.asCID!==e&&e["/"]!==e.bytes)return null;var t=it.asCID(e);if(!t)return null;var r=t.toString();return[new aP(oP.map,1/0,1),new aP(oP.string,"/",1),new aP(oP.string,r,r.length),new aP(oP.break,void 0,1)]},Buffer:XB,Uint8Array:XB,Int8Array:eN,Uint16Array:eN,Int16Array:eN,Uint32Array:eN,Int32Array:eN,Float32Array:eN,Float64Array:eN,Uint8ClampedArray:eN,BigInt64Array:eN,BigUint64Array:eN,DataView:eN,ArrayBuffer:function(e){return XB(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 rN extends $B{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===oP.map){var t=this._next();if(t.type===oP.string&&"/"===t.value){var r=this._next();if(r.type===oP.string){if(this._next().type!==oP.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(r),new aP(oP.tag,42,0)}if(r.type===oP.map){var n=this._next();if(n.type===oP.string&&"bytes"===n.value){var i=this._next();if(i.type===oP.string){for(var o=0;o<2;o++){if(this._next().type!==oP.break)throw new Error("Invalid encoded Bytes form")}var a=se.decode("m".concat(i.value));return new aP(oP.bytes,a,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(r)}this.tokenBuffer.push(t)}return e}}var nN={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};nN.tags[42]=it.parse;var iN=297,oN=e=>function(e,t){return t=Object.assign({},ZB,t),B_(e,new JB,t)}(e,tN),aN=e=>{var t=function(e){return e instanceof ArrayBuffer?new Uint8Array(e,0,e.byteLength):e}(e);return function(e,t){return U_(e,t=Object.assign({tokenizer:new $B(e,t)},t))}(t,Object.assign(nN,{tokenizer:new rN(t,nN)}))},sN=e=>lN.decode(oN(e)),lN=new TextDecoder,uN=new TextEncoder,cN=Object.freeze({__proto__:null,code:297,decode:aN,encode:oN,format:sN,name:"dag-json",parse:e=>aN(uN.encode(e)),stringify:sN}),dN=new TextDecoder;function hN(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 vN(e,t){var r;[r,t]=hN(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 pN(e,t){var r;return[r,t]=hN(e,t),[7&r,r>>3,t]}function fN(e){for(var t={},r=e.length,n=0;n<r;){var i=void 0,o=void 0;if([i,o,n]=pN(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]=vN(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]=vN(e,n),t.Name=dN.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]=hN(e,n)}}if(n>r)throw new Error("protobuf: (PBLink) unexpected end of data");return t}var gN=new TextEncoder,yN=2**32,mN=2**31;function wN(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=EN(t,r,e.Tsize)-1]=24}if("string"==typeof e.Name){var n=gN.encode(e.Name);r-=n.length,t.set(n,r),t[r=EN(t,r,n.length)-1]=18}return e.Hash&&(r-=e.Hash.length,t.set(e.Hash,r),t[r=EN(t,r,e.Hash.length)-1]=10),t.length-r}function bN(e){var t=function(e){var t=0;if(e.Data){var r=e.Data.length;t+=1+r+kN(r)}if(e.Links)for(var n of e.Links){var i=SN(n);t+=1+i+kN(i)}return t}(e),r=new Uint8Array(t),n=t;if(e.Data&&(n-=e.Data.length,r.set(e.Data,n),r[n=EN(r,n,e.Data.length)-1]=10),e.Links)for(var i=e.Links.length-1;i>=0;i--){var o=wN(e.Links[i],r.subarray(0,n));r[n=EN(r,n-=o,o)-1]=18}return r}function SN(e){var t=0;if(e.Hash){var r=e.Hash.length;t+=1+r+kN(r)}if("string"==typeof e.Name){var n=gN.encode(e.Name).length;t+=1+n+kN(n)}return"number"==typeof e.Tsize&&(t+=1+kN(e.Tsize)),t}function EN(e,t,r){for(var n=t-=kN(r);r>=mN;)e[t++]=127&r|128,r/=128;for(;r>=128;)e[t++]=127&r|128,r>>>=7;return e[t]=r,n}function kN(e){return e%2==0&&e++,Math.floor((function(e){var t=0;e>=yN&&(e=Math.floor(e/yN),t=32);e>=65536&&(e>>>=16,t+=16);e>=256&&(e>>>=8,t+=8);return t+xN[e]}(e)+6)/7)}var xN=[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],AN=["Data","Links"],CN=["Hash","Name","Tsize"],IN=new TextEncoder;function TN(e,t){if(e===t)return 0;for(var r=e.Name?IN.encode(e.Name):[],n=t.Name?IN.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 PN(e,t){return!Object.keys(e).some((e=>!t.includes(e)))}function _N(e){if("object"==typeof e.asCID){var t=it.asCID(e);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if("object"!=typeof e||Array.isArray(e))throw new TypeError("Invalid DAG-PB form");var r={};if(e.Hash){var n=it.asCID(e.Hash);try{n||("string"==typeof e.Hash?n=it.parse(e.Hash):e.Hash instanceof Uint8Array&&(n=it.decode(e.Hash)))}catch(e){throw new TypeError("Invalid DAG-PB form: ".concat(e.message))}n&&(r.Hash=n)}if(!r.Hash)throw new TypeError("Invalid DAG-PB form");return"string"==typeof e.Name&&(r.Name=e.Name),"number"==typeof e.Tsize&&(r.Tsize=e.Tsize),r}function BN(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=IN.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(_N),t.Links.sort(TN)}else t.Links=[];return t}function NN(e){if(!e||"object"!=typeof e||Array.isArray(e)||e instanceof Uint8Array||e["/"]&&e["/"]===e.bytes)throw new TypeError("Invalid DAG-PB form");if(!PN(e,AN))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(!PN(r,CN))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===TN(r,e.Links[t-1]))throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}var DN=112;function RN(e){NN(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),bN(t)}function ON(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]=pN(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]=vN(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]=vN(e,r),n.push(fN(l))}}if(r>t)throw new Error("protobuf: (PBNode) unexpected end of data");var u={};return o&&(u.Data=o),u.Links=n||[],u}(function(e){return e instanceof ArrayBuffer?new Uint8Array(e,0,e.byteLength):e}(e)),r={};return t.Data&&(r.Data=t.Data),t.Links&&(r.Links=t.Links.map((e=>{var t={};try{t.Hash=it.decode(e.Hash)}catch(e){}if(!t.Hash)throw new Error("Invalid Hash field found in link, expected CID");return void 0!==e.Name&&(t.Name=e.Name),void 0!==e.Tsize&&(t.Tsize=e.Tsize),t}))),r}var LN=Object.freeze({__proto__:null,code:DN,createLink:function(e,t,r){return _N({Hash:r,Name:e,Tsize:t})},createNode:function(e){return BN({Data:e,Links:arguments.length>1&&void 0!==arguments[1]?arguments[1]:[]})},decode:ON,encode:RN,name:"dag-pb",prepare:BN,validate:NN});function MN(e){return null!=(null==e?void 0:e.then)}class UN extends ud{constructor(t){super(),e(this,"child",void 0),this.child=t}put(e,t,r){var n,i;return 0===e.multihash.code?(null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted(),e):null==this.child?(null==r||null===(i=r.signal)||void 0===i||i.throwIfAborted(),e):this.child.put(e,t,r)}get(e,t){var r,n;if(0===e.multihash.code)return null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),e.multihash.digest;if(null==this.child)throw null==t||null===(n=t.signal)||void 0===n||n.throwIfAborted(),new Ec;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 FN{constructor(t){e(this,"child",void 0),e(this,"getHasher",void 0),e(this,"log",void 0),e(this,"logger",void 0),e(this,"components",void 0),this.log=t.logger.forComponent("helia:networked-storage"),this.logger=t.logger,this.components=t,this.child=new UN(t.blockstore),this.getHasher=t.getHasher}put(e,t){var n=arguments,i=this;return r((function*(){var o,a,s,l=n.length>2&&void 0!==n[2]?n[2]:{};return(yield i.child.has(e,l))?(null===(s=l.onProgress)||void 0===s||s.call(l,new av("blocks:put:duplicate",e)),e):(null===(o=l.onProgress)||void 0===o||o.call(l,new av("blocks:put:providers:notify",e)),yield Promise.all(i.components.blockBrokers.map(function(){var n=r((function*(r){var n;return null===(n=r.announce)||void 0===n?void 0:n.call(r,e,t,l)}));return function(e){return n.apply(this,arguments)}}())),null===(a=l.onProgress)||void 0===a||a.call(l,new av("blocks:put:blockstore:put",e)),i.child.put(e,t,l))}))()}putMany(e){var t=this;return l((function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(i){var o=dc(e,function(){var e=r((function*(e){var r,{cid:i}=e,o=yield t.child.has(i,n);o&&(null===(r=n.onProgress)||void 0===r||r.call(n,new av("blocks:put-many:duplicate",i)));return!o}));return function(t){return e.apply(this,arguments)}}()),a=iv(o,function(){var e=r((function*(e){var i,{cid:o,block:a}=e;null===(i=n.onProgress)||void 0===i||i.call(n,new av("blocks:put-many:providers:notify",o)),yield Promise.all(t.components.blockBrokers.map(function(){var e=r((function*(e){var t;return null===(t=e.announce)||void 0===t?void 0:t.call(e,o,a,n)}));return function(t){return e.apply(this,arguments)}}()))}));return function(t){return e.apply(this,arguments)}}());null===(i=n.onProgress)||void 0===i||i.call(n,new av("blocks:put-many:blockstore:put-many")),yield*c(s(t.child.putMany(a,n)))}()})).apply(this,arguments)}get(e){var n=arguments,i=this;return r((function*(){var o,a=n.length>1&&void 0!==n[1]?n[1]:{};if(!0!==a.offline&&!(yield i.child.has(e,a))){var s,l,u,c=yield i.getHasher(e.multihash.code);null===(s=a.onProgress)||void 0===s||s.call(a,new av("blocks:get:providers:get",e));var d=yield HN(e,i.components.blockBrokers,c,t(t({},a),{},{log:i.log}));return null===(l=a.onProgress)||void 0===l||l.call(a,new av("blocks:get:blockstore:put",e)),yield i.child.put(e,d,a),null===(u=a.onProgress)||void 0===u||u.call(a,new av("blocks:get:providers:notify",e)),yield Promise.all(i.components.blockBrokers.map(function(){var t=r((function*(t){var r;return null===(r=t.announce)||void 0===r?void 0:r.call(t,e,d,a)}));return function(e){return t.apply(this,arguments)}}())),d}return null===(o=a.onProgress)||void 0===o||o.call(a,new av("blocks:get:blockstore:get",e)),i.child.get(e,a)}))()}getMany(e){var n=this;return l((function(e){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(o){null===(o=i.onProgress)||void 0===o||o.call(i,new av("blocks:get-many:blockstore:get-many")),yield*c(s(n.child.getMany(iv(e,function(){var e=r((function*(e){if(!0!==i.offline&&!(yield n.child.has(e,i))){var o,a,s,l=yield n.getHasher(e.multihash.code);null===(o=i.onProgress)||void 0===o||o.call(i,new av("blocks:get-many:providers:get",e));var u=yield HN(e,n.components.blockBrokers,l,t(t({},i),{},{log:n.log}));null===(a=i.onProgress)||void 0===a||a.call(i,new av("blocks:get-many:blockstore:put",e)),yield n.child.put(e,u,i),null===(s=i.onProgress)||void 0===s||s.call(i,new av("blocks:get-many:providers:notify",e)),yield Promise.all(n.components.blockBrokers.map(function(){var t=r((function*(t){var r;return null===(r=t.announce)||void 0===r?void 0:r.call(t,e,u,i)}));return function(e){return t.apply(this,arguments)}}()))}}));return function(t){return e.apply(this,arguments)}}()))))}()})).apply(this,arguments)}delete(e){var t=arguments,n=this;return r((function*(){var r,i=t.length>1&&void 0!==t[1]?t[1]:{};null===(r=i.onProgress)||void 0===r||r.call(i,new av("blocks:delete:blockstore:delete",e)),yield n.child.delete(e,i)}))()}deleteMany(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(n){null===(n=r.onProgress)||void 0===n||n.call(r,new av("blocks:delete-many:blockstore:delete-many")),yield*c(s(t.child.deleteMany(l((function*(){var t,r=!1,n=!1;try{for(var i,o=s(e);r=!(i=yield u(o.next())).done;r=!1){var a=i.value;yield a}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw t}}}))(),r)))}()})).apply(this,arguments)}has(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};return n.child.has(e,r)}))()}getAll(){var e=this;return l((function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(r){null===(r=t.onProgress)||void 0===r||r.call(t,new av("blocks:get-all:blockstore:get-many")),yield*c(s(e.child.getAll(t)))}()})).apply(this,arguments)}}class zN extends FN{constructor(t){super(t),e(this,"started",void 0),this.started=!1}isStarted(){return this.started}start(){var e=this;return r((function*(){yield ss(e.child,...e.components.blockBrokers),e.started=!0}))()}stop(){var e=this;return r((function*(){yield us(e.child,...e.components.blockBrokers),e.started=!1}))()}unwrap(){return this.child}createSession(e,t){var r=this.components.blockBrokers.map((e=>null==e.createSession?e:e.createSession(t)));return new jN({blockstore:this.child,blockBrokers:r,getHasher:this.getHasher,logger:this.logger},{root:e})}}class jN extends FN{constructor(t,r){super(t),e(this,"closeController",void 0),this.closeController=new AbortController,this.closeController.signal,this.log=t.logger.forComponent("helia:session-storage:".concat(r.root))}close(){this.closeController.abort()}put(e,n){var i=arguments,o=()=>super.put,a=this;return r((function*(){var r=i.length>2&&void 0!==i[2]?i[2]:{},s=Ph([a.closeController.signal,r.signal]);try{return yield o().call(a,e,n,t(t({},r),{},{signal:s}))}finally{s.clear()}}))()}putMany(e){var r=()=>super.putMany,n=this;return l((function(e){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var o=Ph([n.closeController.signal,i.signal]);try{yield*c(s(r().call(n,e,t(t({},i),{},{signal:o}))),u)}finally{o.clear()}}()})).apply(this,arguments)}get(e){var n=arguments,i=()=>super.get,o=this;return r((function*(){var r=n.length>1&&void 0!==n[1]?n[1]:{},a=Ph([o.closeController.signal,r.signal]);try{return yield i().call(o,e,t(t({},r),{},{signal:a}))}finally{a.clear()}}))()}getMany(e){var r=()=>super.getMany,n=this;return l((function(e){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var o=Ph([n.closeController.signal,i.signal]);try{yield*c(s(r().call(n,e,t(t({},i),{},{signal:o}))),u)}finally{o.clear()}}()})).apply(this,arguments)}delete(e){var n=arguments,i=()=>super.delete,o=this;return r((function*(){var r=n.length>1&&void 0!==n[1]?n[1]:{},a=Ph([o.closeController.signal,r.signal]);try{yield i().call(o,e,t(t({},r),{},{signal:a}))}finally{a.clear()}}))()}deleteMany(e){var r=()=>super.deleteMany,n=this;return l((function(e){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var o=Ph([n.closeController.signal,i.signal]);try{yield*c(s(r().call(n,e,t(t({},i),{},{signal:o}))),u)}finally{o.clear()}}()})).apply(this,arguments)}has(e){var n=arguments,i=()=>super.has,o=this;return r((function*(){var r=n.length>1&&void 0!==n[1]?n[1]:{},a=Ph([o.closeController.signal,r.signal]);try{return yield i().call(o,e,t(t({},r),{},{signal:a}))}finally{a.clear()}}))()}getAll(){var e=()=>super.getAll,r=this;return l((function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i=Ph([r.closeController.signal,n.signal]);try{yield*c(s(e().call(r,t(t({},n),{},{signal:i}))),u)}finally{i.clear()}}()})).apply(this,arguments)}}function VN(e){return"function"==typeof e.retrieve}var qN=(e,t)=>{if(null==t)throw new _a("No hasher configured for multihash code 0x".concat(e.multihash.code.toString(16),", please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv"));return function(){var n=r((function*(r){var n=t.digest(r);if(!St((MN(n)?yield n:n).digest,e.multihash.digest))throw new Ha("Hash of downloaded block did not match multihash from passed CID")}));return function(e){return n.apply(this,arguments)}}()};function HN(e,t,r,n){return KN.apply(this,arguments)}function KN(){return KN=r((function*(e,n,i,o){var a=qN(e,i),s=new AbortController,l=Ph([s.signal,o.signal]);s.signal;var u=[];for(var c of n)VN(c)&&u.push(c);try{return yield Promise.any(u.map(function(){var n=r((function*(n){try{var i=!1,s=yield n.retrieve(e,t(t({},o),{},{signal:l,validateFn:(u=r((function*(e){yield a(e),i=!0})),function(e){return u.apply(this,arguments)})}));return i||(yield a(s)),s}catch(t){throw o.log.error("could not retrieve verified block for %c",e,t),t}var u}));return function(e){return n.apply(this,arguments)}}()))}finally{s.abort(),l.clear()}})),KN.apply(this,arguments)}class WN extends os{constructor(t,r){var n,i,o;super(),e(this,"initialPeerSearchComplete",void 0),e(this,"requests",void 0),e(this,"name",void 0),e(this,"log",void 0),e(this,"logger",void 0),e(this,"minProviders",void 0),e(this,"maxProviders",void 0),e(this,"providers",void 0),e(this,"evictionFilter",void 0),e(this,"initialProviders",void 0),this.name=r.name,this.logger=t.logger,this.log=t.logger.forComponent(this.name),this.requests=new Map,this.minProviders=null!==(n=r.minProviders)&&void 0!==n?n:1,this.maxProviders=null!==(i=r.maxProviders)&&void 0!==i?i:5,this.providers=[],this.evictionFilter=$h(this.maxProviders),this.initialProviders=null!==(o=r.providers)&&void 0!==o?o:[]}retrieve(e){var t=arguments,n=this;return r((function*(){var i,o=t.length>1&&void 0!==t[1]?t[1]:{},a=se.encode(e.multihash.bytes),s=n.requests.get(a);if(null!=s)return n.log("join existing request for %c",e),s;var l=Cc();if(n.requests.set(a,l.promise),0===n.providers.length){var u=!1;null==n.initialPeerSearchComplete&&(u=!0,n.log=n.logger.forComponent("".concat(n.name,":").concat(e)),n.initialPeerSearchComplete=n.findProviders(e,n.minProviders,o)),yield n.initialPeerSearchComplete,u&&n.log("found initial session peers for %c",e)}var c=!1,d=new fv({concurrency:n.maxProviders});d.addEventListener("error",(()=>{})),d.addEventListener("failure",(e=>{n.log.error("error querying provider %o, evicting from session",e.detail.job.options.provider,e.detail.error),n.evict(e.detail.job.options.provider)})),d.addEventListener("success",(e=>{c=!0,l.resolve(e.detail.result)})),d.addEventListener("idle",(()=>{var t;c||!0===(null===(t=o.signal)||void 0===t?void 0:t.aborted)?n.log.trace("session idle, found block"):Promise.resolve().then(r((function*(){n.log("no session peers had block for for %c, finding new providers",e);for(var t=0;t<n.minProviders&&0!==n.providers.length;t++){var r=n.providers[Math.floor(Math.random()*n.providers.length)];n.evict(r)}yield n.findProviders(e,n.minProviders,o),n.log("found new providers re-retrieving %c",e),n.requests.delete(a),l.resolve(yield n.retrieve(e,o))}))).catch((t=>{n.log.error("could not find new providers for %c",e,t),l.reject(t)}))}));var h=t=>{d.add(r((function*(){return n.queryProvider(e,t.detail,o)})),{provider:t.detail}).catch((t=>{var r;!0!==(null===(r=o.signal)||void 0===r?void 0:r.aborted)&&n.log.error("error retrieving session block for %c",e,t)}))};n.addEventListener("provider",h),Promise.all([...n.providers].map(function(){var t=r((function*(t){return d.add(r((function*(){return n.queryProvider(e,t,o)})),{provider:t})}));return function(e){return t.apply(this,arguments)}}())).catch((t=>{var r;!0!==(null===(r=o.signal)||void 0===r?void 0:r.aborted)&&n.log.error("error retrieving session block for %c",e,t)}));var v=()=>{var e,t;l.reject(new Ia(null!==(e=null===(t=o.signal)||void 0===t?void 0:t.reason)&&void 0!==e?e:"Session aborted")),d.abort()};null===(i=o.signal)||void 0===i||i.addEventListener("abort",v);try{return yield l.promise}finally{var p;n.removeEventListener("provider",h),null===(p=o.signal)||void 0===p||p.removeEventListener("abort",v),d.clear(),n.requests.delete(a)}}))()}evict(e){this.evictionFilter.add(this.toEvictionKey(e));var t=this.providers.findIndex((t=>this.equals(t,e)));-1!==t&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return null!=this.providers.find((t=>this.equals(t,e)))||!!this.isEvicted(e)}findProviders(e,t,n){var i=this;return r((function*(){var o=Cc(),a=0;return Promise.resolve().then(r((function*(){if(i.log("finding %d-%d new provider(s) for %c",t,i.maxProviders,e),i.initialProviders.length>0)for(;a<t&&i.initialProviders.length>0;){var r,l=i.initialProviders.pop();if(null==l)break;var u=yield i.convertToProvider(l,n);if(!0===(null===(r=n.signal)||void 0===r?void 0:r.aborted))break;if(null!=u&&(!i.hasProvider(u)&&(i.log("found %d/%d new providers",a,i.maxProviders),i.providers.push(u),i.safeDispatchEvent("provider",{detail:u}),++a===t&&(i.log("session is ready"),o.resolve()),i.providers.length===i.maxProviders))){i.log("found max session peers",a);break}}if(a<i.maxProviders){var c,d=!1,h=!1;try{for(var v,p=s(i.findNewProviders(e,n));d=!(v=yield p.next()).done;d=!1){var f,g=v.value;if(a===i.maxProviders||!0===(null===(f=n.signal)||void 0===f?void 0:f.aborted))break;if(!i.hasProvider(g)&&(i.log("found %d/%d new providers",a,i.maxProviders),i.providers.push(g),i.safeDispatchEvent("provider",{detail:g}),++a===t&&(i.log("session is ready"),o.resolve()),i.providers.length===i.maxProviders)){i.log("found max session peers",a);break}}}catch(e){h=!0,c=e}finally{try{d&&null!=p.return&&(yield p.return())}finally{if(h)throw c}}}if(i.log("found %d/%d new session peers",a,i.maxProviders),a<t)throw new eB("Found ".concat(a," of ").concat(t," ").concat(i.name," providers for ").concat(e))}))).catch((t=>{var r;i.log.error("error searching routing for potential session peers for %c",e,null!==(r=t.errors)&&void 0!==r?r:t),o.reject(t)})),o.promise}))()}}class GN{constructor(n){var i,o,a,s,l;e(this,"blockstore",void 0),e(this,"datastore",void 0),e(this,"pins",void 0),e(this,"logger",void 0),e(this,"routing",void 0),e(this,"getCodec",void 0),e(this,"getHasher",void 0),e(this,"dns",void 0),e(this,"metrics",void 0),e(this,"log",void 0),this.logger=null!==(i=n.logger)&&void 0!==i?i:ad(),this.log=this.logger.forComponent("helia"),this.getHasher=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1?arguments[1]:void 0,n={[$e.code]:$e,[Xe.code]:Xe,[Ge.code]:Ge};return e.forEach((e=>{n[e.code]=e})),function(){var e=r((function*(e){var r=n[e];if(null==r&&null!=t){var i=t(e);r=MN(i)?yield i:i,n[r.code]=r}if(null!=r)return r;throw new rB("No hasher configured for multihash code 0x".concat(e.toString(16),", please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv"))}));return function(t){return e.apply(this,arguments)}}()}(n.hashers,n.loadHasher),this.getCodec=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1?arguments[1]:void 0,n={[DN]:LN,[Se]:Ee,[WB]:YB,[iN]:cN,[me]:be};return e.forEach((e=>{n[e.code]=e})),function(){var e=r((function*(e){var r=n[e];if(null==r&&null!=t){var i=t(e);r=MN(i)?yield i:i,n[r.code]=r}if(null!=r)return r;throw new nB("Could not load codec for ".concat(e))}));return function(t){return e.apply(this,arguments)}}()}(n.codecs,n.loadCodec),this.dns=null!==(o=n.dns)&&void 0!==o?o:tP(),this.metrics=n.metrics;var u=t({blockstore:n.blockstore,datastore:n.datastore,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics},null!==(a=n.components)&&void 0!==a?a:{});this.routing=u.routing=new iB(u,{routers:(null!==(s=n.routers)&&void 0!==s?s:[]).flatMap((e=>{var t=[e];return null!=e[wa]&&t.push(e[wa]),null!=e[xa]&&t.push(e[xa]),t})),providerLookupConcurrency:n.providerLookupConcurrency});var c=new zN(u);this.pins=new J_(n.datastore,c,this.getCodec),this.blockstore=new MB(c,this.pins,{holdGcLock:null===(l=n.holdGcLock)||void 0===l||l}),this.datastore=n.datastore,u.blockBrokers=n.blockBrokers.map((e=>e(u)))}start(){var e=this;return r((function*(){yield function(e){return FB.apply(this,arguments)}(e.datastore),yield ss(e.blockstore,e.datastore,e.routing)}))()}stop(){var e=this;return r((function*(){yield us(e.blockstore,e.datastore,e.routing)}))()}gc(){var e=arguments,t=this;return r((function*(){var r=e.length>0&&void 0!==e[0]?e[0]:{},n=yield t.blockstore.lock.writeLock();try{var i=t,o=t.blockstore.unwrap();t.log("gc start"),yield uc(o.deleteMany(l((function*(){var e,t=!1,n=!1;try{for(var a,l=s(o.getAll());t=!(a=yield u(l.next())).done;t=!1){var{cid:c}=a.value;try{var d;if(yield u(i.pins.isPinned(c,r)))continue;yield c,null===(d=r.onProgress)||void 0===d||d.call(r,new av("helia:gc:deleted",c))}catch(e){var h;i.log.error("Error during gc",e),null===(h=r.onProgress)||void 0===h||h.call(r,new av("helia:gc:error",e))}}}catch(t){n=!0,e=t}finally{try{t&&null!=l.return&&(yield u(l.return()))}finally{if(n)throw e}}}))()))}finally{n()}t.log("gc finished")}))()}}class QN extends WN{constructor(r,n){super(r,t(t({},n),{},{name:"helia:bitswap:session"})),e(this,"wantList",void 0),e(this,"network",void 0),e(this,"libp2p",void 0),this.wantList=r.wantList,this.network=r.network,this.libp2p=r.libp2p}queryProvider(e,t,n){var i=this;return r((function*(){i.log("sending WANT-BLOCK for %c to %p",e,t);var r=yield i.wantList.wantSessionBlock(e,t,n);if(i.log("%p %s %c",t,r.has?"has":"does not have",e),r.has&&null!=r.block)return r.block;throw new Error("Provider did not have block")}))()}findNewProviders(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var n,i=!1,o=!1;try{for(var a,l=s(t.network.findProviders(e,r));i=!(a=yield u(l.next())).done;i=!1){var c=a.value;yield c.id}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}()})).apply(this,arguments)}toEvictionKey(e){return e.toMultihash().bytes}equals(e,t){return e.equals(t)}convertToProvider(e,t){var n=this;return r((function*(){return Ea(e)?e:(yield n.libp2p.dial(e,t)).remotePeer}))()}}class YN{constructor(t){var r,n,i,o;e(this,"blocksReceived",void 0),e(this,"duplicateBlocksReceived",void 0),e(this,"dataReceived",void 0),e(this,"duplicateDataReceived",void 0),this.blocksReceived=null===(r=t.metrics)||void 0===r?void 0:r.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=null===(n=t.metrics)||void 0===n?void 0:n.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=null===(i=t.metrics)||void 0===i?void 0:i.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=null===(o=t.metrics)||void 0===o?void 0:o.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,r=arguments.length>1?arguments[1]:void 0,n={global:t};null!=r&&(n[r.toString()]=t),null===(e=this.blocksReceived)||void 0===e||e.increment(n)}updateDuplicateBlocksReceived(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,r=arguments.length>1?arguments[1]:void 0,n={global:t};null!=r&&(n[r.toString()]=t),null===(e=this.duplicateBlocksReceived)||void 0===e||e.increment(n)}updateDataReceived(e,t){var r,n={global:e};null!=t&&(n[t.toString()]=e),null===(r=this.dataReceived)||void 0===r||r.increment(n)}updateDuplicateDataReceived(e,t){var r,n={global:e};null!=t&&(n[t.toString()]=e),null===(r=this.duplicateDataReceived)||void 0===r||r.increment(n)}}class JN extends Map{constructor(t){super(),e(this,"metric",void 0);var{name:r,metrics:n}=t;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){var t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function ZN(e){var{name:t,metrics:r}=e;return null!=r?new JN({name:t,metrics:r}):new Map}function $N(e){if(!(e instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");for(var t=[];e.length>0;){var r=Lt(e);t.push(r),e=e.slice(Nt(r))}return t}class XN extends os{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),e(this,"peers",void 0),e(this,"wants",void 0),e(this,"network",void 0),e(this,"log",void 0),e(this,"sendMessagesDelay",void 0),e(this,"sendMessagesTimeout",void 0),e(this,"hashLoader",void 0),e(this,"sendingMessages",void 0),this.peers=rv({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=ZN({name:"helia_bitswap_wantlist",metrics:t.metrics}),this.network=t.network,this.sendMessagesDelay=null!==(r=n.sendMessagesDelay)&&void 0!==r?r:10,this.log=t.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=n.hashLoader,this.network.addEventListener("bitswap:message",(e=>{this.receiveMessage(e.detail.peer,e.detail.message).catch((t=>{this.log.error("error receiving bitswap message from %p",e.detail.peer,t)}))})),this.network.addEventListener("peer:connected",(e=>{this.peerConnected(e.detail).catch((t=>{this.log.error("error processing newly connected bitswap peer %p",e.detail,t)}))})),this.network.addEventListener("peer:disconnected",(e=>{this.peerDisconnected(e.detail)}))}addEntry(e,t){var n=this;return r((function*(){var r,i,o=gt(e.multihash.bytes,"base64"),a=n.wants.get(o);null==a&&(a={cid:e,priority:null!==(r=t.priority)&&void 0!==r?r:1,wantType:null!==(i=t.wantType)&&void 0!==i?i:HI.WantBlock,cancel:!1,sendDontHave:!0},n.wants.set(o,a));a.wantType===HI.WantHave&&t.wantType===HI.WantBlock&&(a.wantType=HI.WantBlock),yield n.sendMessagesDebounced();try{if(t.wantType===HI.WantBlock){var s=yield lv(n,"block",null==t?void 0:t.signal,{filter:t=>St(e.multihash.digest,t.detail.cid.multihash.digest),errorMessage:"Want was aborted"});return s.detail}return(yield lv(n,"presence",null==t?void 0:t.signal,{filter:t=>St(e.multihash.digest,t.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{var l;!0===(null===(l=t.signal)||void 0===l?void 0:l.aborted)&&(n.log("want for %c was aborted, cancelling want",e),a.cancel=!0,yield n.sendMessagesDebounced())}}))()}sendMessagesDebounced(){var e=this;return r((function*(){var t;yield null===(t=e.sendingMessages)||void 0===t?void 0:t.promise,clearTimeout(e.sendMessagesTimeout),e.sendMessagesTimeout=setTimeout((()=>{e.sendMessages().catch((t=>{e.log("error sending messages to peers",t)}))}),e.sendMessagesDelay)}))()}sendMessages(){var e=this;return r((function*(){for(var[t,n]of(e.sendingMessages=Cc(),yield Promise.all([...e.peers.entries()].map(function(){var t=r((function*(t){var[r,n]=t,i=new Set,o=new uT;for(var[a,s]of e.wants.entries()){n.has(a)||s.cancel||(i.add(a),o.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:s.priority,wantType:s.wantType,cancel:s.cancel,sendDontHave:s.sendDontHave}))}if(0!==o.wantlist.size)try{for(var l of(yield e.network.sendMessage(r,o),i))n.add(l)}catch(t){e.log.error("error sending full wantlist to new peer",t)}}));return function(e){return t.apply(this,arguments)}}())).catch((t=>{e.log.error("error sending messages",t)})),e.wants))if(n.cancel)for(var i of(e.wants.delete(t),e.peers.values()))i.delete(t);e.sendingMessages.resolve()}))()}has(e){var t=gt(e.multihash.bytes,"base64");return this.wants.has(t)}wantSessionPresence(e,t){var n=arguments,i=this;return r((function*(){var r=n.length>2&&void 0!==n[2]?n[2]:{},o=new uT;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:HI.WantHave,priority:1}),yield i.network.sendMessage(t,o),(yield lv(i,"presence",r.signal,{filter:r=>t.equals(r.detail.sender)&&St(e.multihash.digest,r.detail.cid.multihash.digest)})).detail}))()}wantBlock(e){var n=arguments,i=this;return r((function*(){var r=n.length>1&&void 0!==n[1]?n[1]:{};return i.addEntry(e,t(t({},r),{},{wantType:HI.WantBlock}))}))()}wantSessionBlock(e,t){var n=arguments,i=this;return r((function*(){var r=n.length>2&&void 0!==n[2]?n[2]:{},o=new uT;return o.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:HI.WantBlock,priority:1}),yield i.network.sendMessage(t,o),(yield lv(i,"presence",r.signal,{filter:r=>t.equals(r.detail.sender)&&St(e.multihash.digest,r.detail.cid.multihash.digest)})).detail}))()}receivedBlock(e,t){var n=this;return r((function*(){var t=gt(e.multihash.bytes,"base64"),r=n.wants.get(t);null!=r&&(r.cancel=!0,yield n.sendMessagesDebounced())}))()}receiveMessage(e,t){var n=this;return r((function*(){n.log("received message from %p with %d blocks",e,t.blocks.length);var r=!1;for(var i of t.blocks){var o;if(null!=i.prefix&&null!=i.data){var a=$N(i.prefix),s=a[0],l=a[1],u=a[2],c=u===$e.code?$e:yield null===(o=n.hashLoader)||void 0===o?void 0:o.getHasher(u);if(null!=c){var d=c.digest(i.data);null!=d.then&&(d=yield d);var h=it.create(0===s?0:1,l,d);n.log("received block from %p for %c",e,h),n.safeDispatchEvent("block",{detail:{sender:e,cid:h,block:i.data}}),n.safeDispatchEvent("presence",{detail:{sender:e,cid:h,has:!0,block:i.data}});var v=gt(h.multihash.bytes,"base64"),p=n.wants.get(v);null!=p&&(p.cancel=!0,r=!0)}else n.log.error("unknown hash algorithm",u)}}for(var{cid:f,type:g}of t.blockPresences){var y=it.decode(f);n.log("received %s from %p for %c",g,e,y),n.safeDispatchEvent("presence",{detail:{sender:e,cid:y,has:g===YI.HaveBlock}})}r&&(yield n.sendMessagesDebounced())}))()}peerConnected(e){var t=this;return r((function*(){var r=new Set,n=new uT(!0);for(var[i,o]of t.wants.entries())o.cancel||(r.add(i),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:HI.WantBlock,cancel:!1,sendDontHave:!1}));if(0!==n.wantlist.size)try{yield t.network.sendMessage(e,n),t.peers.set(e,r)}catch(r){t.log.error("error sending full wantlist to new peer %p",e,r)}else t.peers.set(e,r)}))()}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}}class eD{constructor(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"log",void 0),e(this,"logger",void 0),e(this,"stats",void 0),e(this,"network",void 0),e(this,"blockstore",void 0),e(this,"peerWantLists",void 0),e(this,"wantList",void 0),e(this,"libp2p",void 0),this.logger=r.logger,this.log=r.logger.forComponent("helia:bitswap"),this.blockstore=r.blockstore,this.libp2p=r.libp2p,this.stats=new YN(r),this.network=new lT(r,n),this.peerWantLists=new hT(t(t({},r),{},{network:this.network}),n),this.wantList=new XN(t(t({},r),{},{network:this.network}),n)}createSession(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return e={wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},new QN(e,t)}want(e){var n=arguments,i=this;return r((function*(){var r=n.length>1&&void 0!==n[1]?n[1]:{},o=new AbortController,a=Ph([o.signal,r.signal]);o.signal,i.network.findAndConnect(e,t(t({},r),{},{signal:a})).catch((t=>{o.signal.aborted||i.log.error("error during finding and connect for cid %c",e,t)}));try{return(yield i.wantList.wantBlock(e,t(t({},r),{},{signal:a}))).block}finally{o.abort(),a.clear()}}))()}notify(e,t){var n=arguments,i=this;return r((function*(){var t=n.length>2&&void 0!==n[2]?n[2]:{};yield Promise.all([i.peerWantLists.receivedBlock(e,t),i.wantList.receivedBlock(e,t)])}))()}getWantlist(){return[...this.wantList.wants.values()].filter((e=>!e.cancel)).map((e=>({cid:e.cid,priority:e.priority,wantType:e.wantType})))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}start(){var e=this;return r((function*(){e.wantList.start(),yield e.network.start()}))()}stop(){var e=this;return r((function*(){e.wantList.stop(),yield e.network.stop()}))()}}class tD{constructor(n){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"bitswap",void 0),e(this,"started",void 0);var o,{getHasher:a}=n;this.bitswap=function(e){return new eD(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}(n,t({hashLoader:{getHasher:(o=r((function*(e){return a(e)})),function(e){return o.apply(this,arguments)})}},i)),this.started=!1}isStarted(){return this.started}start(){var e=this;return r((function*(){yield e.bitswap.start(),e.started=!0}))()}stop(){var e=this;return r((function*(){yield e.bitswap.stop(),e.started=!1}))()}announce(e,t,n){var i=this;return r((function*(){yield i.bitswap.notify(e,t,n)}))()}retrieve(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};return n.bitswap.want(e,r)}))()}createSession(e){var t,n,i=this,o=this.bitswap.createSession(e);return{announce:(n=r((function*(e,t,r){yield i.bitswap.notify(e,t,r)})),function(e,t,r){return n.apply(this,arguments)}),retrieve:(t=r((function*(e,t){return o.retrieve(e,t)})),function(e,r){return t.apply(this,arguments)})}}}function rD(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new tD(t,e)}var nD,iD={};var oD=(nD||(nD=1,function(){var e,t,r,n,i,o,a,s;s=function(e){return[(e&255<<24)>>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var r,n,i,o,a,s;for(r=[],i=o=0;o<=3&&0!==e.length;i=++o){if(i>0){if("."!==e[0])throw new Error("Invalid IP");e=e.substring(1)}a=(s=t(e))[0],n=s[1],e=e.substring(n),r.push(a)}if(0!==e.length)throw new Error("Invalid IP");switch(r.length){case 1:if(r[0]>4294967295)throw new Error("Invalid IP");return r[0]>>>0;case 2:if(r[0]>255||r[1]>16777215)throw new Error("Invalid IP");return(r[0]<<24|r[1])>>>0;case 3:if(r[0]>255||r[1]>255||r[2]>65535)throw new Error("Invalid IP");return(r[0]<<24|r[1]<<16|r[2])>>>0;case 4:if(r[0]>255||r[1]>255||r[2]>255||r[3]>255)throw new Error("Invalid IP");return(r[0]<<24|r[1]<<16|r[2]<<8|r[3])>>>0;default:throw new Error("Invalid IP")}},n=(r=function(e){return e.charCodeAt(0)})("0"),o=r("a"),i=r("A"),t=function(e){var t,a,s,l,u;for(l=0,t=10,a="9",s=0,e.length>1&&"0"===e[s]&&("x"===e[s+1]||"X"===e[s+1]?(s+=2,t=16):"0"<=e[s+1]&&e[s+1]<="9"&&(s++,t=8,a="7")),u=s;s<e.length;){if("0"<=e[s]&&e[s]<=a)l=l*t+(r(e[s])-n)>>>0;else{if(16!==t)break;if("a"<=e[s]&&e[s]<="f")l=l*t+(10+r(e[s])-o)>>>0;else{if(!("A"<=e[s]&&e[s]<="F"))break;l=l*t+(10+r(e[s])-i)>>>0}}if(l>4294967295)throw new Error("too large");s++}if(s===u)throw new Error("empty octet");return[l,s]},e=function(){function e(e,t){var r,n,i;if("string"!=typeof e)throw new Error("Missing `net' parameter");if(t||(i=e.split("/",2),e=i[0],t=i[1]),t||(t=32),"string"==typeof t&&t.indexOf(".")>-1){try{this.maskLong=a(t)}catch(e){throw new Error("Invalid mask: "+t)}for(r=n=32;n>=0;r=--n)if(this.maskLong===4294967295<<32-r>>>0){this.bitmask=r;break}}else{if(!t&&0!==t)throw new Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(a(e)&this.maskLong)>>>0}catch(t){throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=s(this.netLong),this.mask=s(this.maskLong),this.hostmask=s(~this.maskLong),this.first=this.bitmask<=30?s(this.netLong+1):this.base,this.last=this.bitmask<=30?s(this.netLong+this.size-2):s(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?s(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return"string"==typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e?this.contains(t.base)&&this.contains(t.broadcast||t.last):(a(t)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(s(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,r,n;for(n=a(this.first),r=a(this.last),t=0;n<=r;)e(s(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),iD.ip2long=a,iD.long2ip=s,iD.Netmask=e}.call(iD)),iD),aD=["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 oD.Netmask(e)));function sD(e){for(var t of aD)if(t.contains(e))return!0;return!1}function lD(e){return Vt(e)?sD(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 sD("".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 sD(t[t.length-1])}(e):qt(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 uD=[xr("tcp").code,xr("dns").code,xr("dnsaddr").code,xr("dns4").code,xr("dns6").code];function cD(e){var t;return null===(t=hD("sni",e))||void 0===t?void 0:t[1]}function dD(e){var t,r=null===(t=hD("tcp",e))||void 0===t?void 0:t[1];return null==r?"":":".concat(r)}function hD(e,t){var r;try{r=xr(e).code}catch(e){return}for(var[n,i]of t)if(n===r&&null!=i)return[n,i]}function vD(e){return e.some((e=>{var[t,r]=e;return t===xr("tls").code}))}function pD(e,t,r){var n=fD[xr(e).name];if(null==n)throw new Error("Can't interpret protocol ".concat(xr(e).name));var i=n(t,r);return e===xr("ip6").code?"[".concat(i,"]"):i}var fD={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(pD(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(pD(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(pD(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(pD(n[0],null!==(r=n[1])&&void 0!==r?r:"",t))},http:(e,t)=>{var r,n=vD(t),i=cD(t),o=dD(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=pD(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=pD(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 pD(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 pD(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=pD(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=vD(t),i=cD(t),o=dD(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=pD(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=pD(n[0],null!==(r=n[1])&&void 0!==r?r:"",t);return i=i.replace("tcp://",""),"wss://".concat(i)}};function gD(e,t){var r,n=kr(e).stringTuples(),i=n.pop();if(null==i)throw new Error("Unexpected end of multiaddr");var o=xr(i[0]),a=fD[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 uD.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 yD=new WeakMap,mD=new WeakMap,wD=new WeakMap,bD=new WeakMap,SD=new WeakMap,ED=new WeakSet;class kD{constructor(t,r){var{logger:i,transformRequestInit:o}=r;d(this,ED),e(this,"url",void 0),n(this,yD,0),n(this,mD,0),n(this,wD,0),n(this,bD,0),n(this,SD,new Map),e(this,"log",void 0),e(this,"transformRequestInit",void 0),this.url=t instanceof URL?t:new URL(t),this.transformRequestInit=o,this.log=i.forComponent("helia:trustless-gateway-block-broker:".concat(this.url.hostname))}getRawBlock(e,t){var n=this;return r((function*(){var a=new URL(n.url.toString());if(a.pathname="/ipfs/".concat(e.toString()),a.search="?format=raw",!0===(null==t?void 0:t.aborted))throw new Error("Signal to fetch raw block for CID ".concat(e," from gateway ").concat(n.url," was aborted prior to fetch"));var s=h(ED,n,xD).call(n,e),l=new AbortController,u=()=>{l.abort()};null==t||t.addEventListener("abort",u);try{var c=o(SD,n).get(s);if(null==c){var d;i(yD,n,(d=o(yD,n),d++,d));var v={signal:l.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},p=null!=n.transformRequestInit?yield n.transformRequestInit(v):v;c=fetch(a.toString(),p).then(function(){var t=r((function*(t){var r,s;if(n.log("GET %s %d",a,t.status),!t.ok)throw i(mD,n,(s=o(mD,n),s++,s)),new Error("unable to fetch raw block for CID ".concat(e," from gateway ").concat(n.url));return i(bD,n,(r=o(bD,n),r++,r)),new Uint8Array(yield t.arrayBuffer())}));return function(e){return t.apply(this,arguments)}}()),o(SD,n).set(s,c)}return yield c}catch(r){var f;if(!0===(null==t?void 0:t.aborted))throw new Error("fetching raw block for CID ".concat(e," from gateway ").concat(n.url," was aborted"));throw i(mD,n,(f=o(mD,n),++f)),new Error("unable to fetch raw block for CID ".concat(e))}finally{null==t||t.removeEventListener("abort",u),o(SD,n).delete(s)}}))()}reliability(){return 0===o(yD,this)?1:o(wD,this)>0?-1/0:o(bD,this)/(o(yD,this)+3*o(mD,this))}incrementInvalidBlocks(){var e;i(wD,this,(e=o(wD,this),++e))}getStats(){return{attempts:o(yD,this),errors:o(mD,this),invalidBlocks:o(wD,this),successes:o(bD,this),pendingResponses:o(SD,this).size}}}function xD(e){var t=e.multihash.bytes;return se.encode(t)}function AD(e,t,r){return e.filter((e=>{if(Th.matches(e)||t&&Ih.matches(e))return!!r||(!!$d.matches(e)||!1===lD(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 CD(e,t,r,n,i){return ID.apply(this,arguments)}function ID(){return ID=l((function(e,t,r,n,i){var o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};return function*(){var a,l=!1,c=!1;try{for(var d,h=s(t.findProviders(e,o));l=!(d=yield u(h.next())).done;l=!1){var v=AD(d.value.multiaddrs,n,i);if(0!==v.length){var p=gD(v[0]);yield new kD(p,{logger:r,transformRequestInit:o.transformRequestInit})}}}catch(e){c=!0,a=e}finally{try{l&&null!=h.return&&(yield u(h.return()))}finally{if(c)throw a}}}()})),ID.apply(this,arguments)}class TD extends WN{constructor(r,n){var i,o;super(r,t(t({},n),{},{name:"helia:trustless-gateway:session"})),e(this,"routing",void 0),e(this,"allowInsecure",void 0),e(this,"allowLocal",void 0),e(this,"transformRequestInit",void 0),this.routing=r.routing,this.allowInsecure=null!==(i=n.allowInsecure)&&void 0!==i?i:_D,this.allowLocal=null!==(o=n.allowLocal)&&void 0!==o?o:BD,this.transformRequestInit=n.transformRequestInit}queryProvider(e,t,n){var i=this;return r((function*(){var r;i.log("fetching BLOCK for %c from %s",e,t.url);var o=yield t.getRawBlock(e,n.signal);return i.log.trace("got block for %c from %s",e,t.url),yield null===(r=n.validateFn)||void 0===r?void 0:r.call(n,o),o}))()}findNewProviders(e){var r=this;return l((function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(CD(e,r.routing,r.logger,r.allowInsecure,r.allowLocal,t(t({},n),{},{transformRequestInit:r.transformRequestInit}))))}()})).apply(this,arguments)}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}}class PD{constructor(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"allowInsecure",void 0),e(this,"allowLocal",void 0),e(this,"transformRequestInit",void 0),e(this,"routing",void 0),e(this,"log",void 0),e(this,"logger",void 0),this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.allowInsecure=null!==(r=i.allowInsecure)&&void 0!==r?r:_D,this.allowLocal=null!==(n=i.allowLocal)&&void 0!==n?n:BD,this.transformRequestInit=i.transformRequestInit}retrieve(e){var n=arguments,i=this;return r((function*(){var r,o=n.length>1&&void 0!==n[1]?n[1]:{},a=[],l=!1,u=!1;try{for(var c,d=s(CD(e,i.routing,i.logger,i.allowInsecure,i.allowLocal,t(t({},o),{},{transformRequestInit:i.transformRequestInit})));l=!(c=yield d.next()).done;l=!1){var h=c.value;i.log("getting block for %c from %s",e,h.url);try{var v=yield h.getRawBlock(e,o.signal);i.log.trace("got block for %c from %s",e,h.url);try{var p;yield null===(p=o.validateFn)||void 0===p?void 0:p.call(o,v)}catch(t){i.log.error("failed to validate block for %c from %s",e,h.url,t);continue}return v}catch(t){var f;if(i.log.error("failed to get block for %c from %s",e,h.url,t),t instanceof Error?a.push(t):a.push(new Error("Unable to fetch raw block for CID ".concat(e," from gateway ").concat(h.url))),!0===(null===(f=o.signal)||void 0===f?void 0:f.aborted)){i.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,h.url);break}}}}catch(e){u=!0,r=e}finally{try{l&&null!=d.return&&(yield d.return())}finally{if(u)throw r}}throw a.length>0?new AggregateError(a,"Unable to fetch raw block for CID ".concat(e," from any gateway")):new Error("Unable to fetch raw block for CID ".concat(e," from any gateway"))}))()}createSession(){var e,r,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return e={logger:this.logger,routing:this.routing},r=t(t({},n),{},{allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit}),new TD(e,r)}}var _D=!1,BD=!1;function ND(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new PD(t,e)}function DD(e){return RD.apply(this,arguments)}function RD(){return RD=l((function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var r=e.getReader();try{for(;;){var n=yield u(r.read());if(n.done)return;yield n.value}}finally{!0!==t.preventCancel&&(yield u(r.cancel())),r.releaseLock()}}()})),RD.apply(this,arguments)}var OD,LD={exports:{}};var MD,UD,FD=(OD||(OD=1,MD=LD,function(){MD.exports=f;var e=86400,t=3200,r=146097*t/400,n=e*r,i=1e3*n,o=864e13,a=4294967296,s=1e6,l="000000000",u=Math.trunc||function(e){var t=e-e%1;return 0==t&&(e<0||0===e&&1/e!=1/0)?-0:t},c=f.prototype,d=(f.fromDate=function(e){return new f(+e)},f.fromInt64BE=b(0,1,2,3,0,4),f.fromInt64LE=b(3,2,1,0,4,0),f.fromString=function(e){var t,r=new f;if(e=(e+="").replace(/^\s*[+\-]?\d+/,(function(e){var t=1970+((e=+e)-1970)%400;return r.year=e-t,t})).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,(function(e,r,n){return r<0&&(n*=-1),t=6e4*(60*+r+ +n),""})).replace(/\.\d+$/,(function(e){return r.nano=+(e+l).substr(1,9),""})).split(/\D+/),1<e.length?e[1]--:e[1]=0,r.time=t=Date.UTC.apply(Date,e)-(t||0),isNaN(t))throw new TypeError("Invalid Date");return g(r)},f.fromTimeT=function(e){return m(e,0)},c.year=0,c.time=0,c.nano=0,c.addNano=function(e){return this.nano+=+e||0,this},c.getNano=function(){var e=g(this);return(e.time%1e3*s+ +e.nano+1e9)%1e9},c.getTimeT=function(){var n=g(this),i=Math.floor(n.time/1e3);return(n=n.year)&&(i+=n*r*e/t),i},c.getYear=function(){return this.toDate().getUTCFullYear()+this.year},c.toDate=function(){return y(g(this).time)},c.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},c.toString=function(e){var t=this,r=t.toDate(),n={H:function(){return E(r.getUTCHours())},L:function(){return k(r.getUTCMilliseconds(),3)},M:function(){return E(r.getUTCMinutes())},N:function(){return k(t.getNano(),9)},S:function(){return E(r.getUTCSeconds())},Y:function(){var e=t.getYear();return 999999<e?"+"+e:9999<e?"+"+k(e,6):0<=e?k(e,4):-999999<=e?"-"+k(-e,6):e},a:function(){return v[r.getUTCDay()]},b:function(){return h[r.getUTCMonth()]},d:function(){return E(r.getUTCDate())},e:function(){return function(e){return(9<e?"":" ")+(0|e)}(r.getUTCDate())},m:function(){return E(r.getUTCMonth()+1)}};return function e(t){return t.replace(/%./g,(function(t){var r=t[1],i=p[r];return r=n[r],i?e(i):r?r():t}))}(e||d)},c.writeInt64BE=w(0,1,2,3,0,4),c.writeInt64LE=w(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),h=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],v=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],p={"%":"%",F:"%Y-%m-%d",n:"\n",R:"%H:%M",T:"%H:%M:%S",t:"\t",X:"%T",Z:"GMT",z:"+0000"};return f;function f(e,t,r){var n=this;if(!(n instanceof f))return new f(e,t,r);n.time=+e||0,n.nano=+t||0,n.year=+r||0,g(n)}function g(e){var r,n,a,l=e.year,c=e.time,d=e.nano,h=((d<0||s<=d)&&(d-=(n=Math.floor(d/s))*s,c+=n,n=1),l%t);return(c<-o||o<c||h)&&((r=u(c/i))&&(l+=r*t,c-=r*i),(a=y(c)).setUTCFullYear(h+a.getUTCFullYear()),a=(c=+a)+(r=u((l-=h)/t))*i,r&&-o<=a&&a<=o&&(l-=r*t,c=a),n=1),n&&(e.year=l,e.time=c,e.nano=d),e}function y(e){var t=new Date(0);return t.setTime(e),t}function m(e,r){e=+e||0;var i=u((r=(0|r)*a)/n)+u(e/n);return(e=u((r=r%n+e%n)/n))&&(i+=e,r-=e*n),new f(1e3*r,0,i*t)}function w(n,i,o,s,l,c){return function(n,i){var o=g(this);S(n=n||new Array(8),i|=0);var s=Math.floor(o.time/1e3),h=(o=o.year*(r*e/t),u(o/a)+u(s/a));return o=o%a+s%a,(s=Math.floor(o/a))&&(h+=s,o-=s*a),d(n,i+l,h),d(n,i+c,o),n};function d(e,t,r){e[t+n]=r>>24&255,e[t+i]=r>>16&255,e[t+o]=r>>8&255,e[t+s]=255&r}}function b(e,t,r,n,i,o){return function(e,t){S(e,t|=0);var r=a(e,t+i);return m(a(e,t+o),r)};function a(i,o){return 16777216*i[o+e]+(i[o+t]<<16|i[o+r]<<8|i[o+n])}}function S(e,t){if(null==(e=e&&e.length))throw new TypeError("Invalid Buffer");if(e<t+8)throw new RangeError("Out of range")}function E(e){return(9<e?"":"0")+(0|e)}function k(e,t){return(l+(0|e)).substr(-t)}}()),LD.exports),zD=a(FD);class jD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Record signature creation failed"),this.name="SignatureCreationError"}}e(jD,"name","SignatureCreationError");class VD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Record signature verification failed"),this.name="SignatureVerificationError"}}e(VD,"name","SignatureVerificationError");class qD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Record has expired"),this.name="RecordExpiredError"}}e(qD,"name","RecordExpiredError");class HD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The validity type is unsupported"),this.name="UnsupportedValidityError"}}e(HD,"name","UnsupportedValidityError");class KD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The record is too large"),this.name="RecordTooLargeError"}}e(KD,"name","RecordTooLargeError");class WD 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(WD,"name","InvalidValueError");class GD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid record data"),this.name="InvalidRecordDataError"}}e(GD,"name","InvalidRecordDataError");class QD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid embedded public key"),this.name="InvalidEmbeddedPublicKeyError"}}e(QD,"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=()=>ql(t)}(e.ValidityType||(e.ValidityType={})),e.codec=()=>(null==r&&(r=Hl((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=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(UD||(UD={}));var YD=sd("ipns:utils"),JD=Et("/ipns/");function ZD(e){return"signatureV1"in e?UD.encode({value:Et(e.value),signatureV1:e.signatureV1,validityType:e.validityType,validity:Et(e.validity),sequence:e.sequence,ttl:e.ttl,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data}):UD.encode({pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data})}function $D(e){var t=UD.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 VD("Missing data or signatureV2");var r=tR(t.data),n=function(e){var t=gt(e).trim();if(t.startsWith("/"))return t;try{return"/ipfs/".concat(it.decode(e).toV1().toString())}catch(e){}try{return"/ipfs/".concat(it.parse(t).toV1().toString())}catch(e){}throw new WD("Value must be a valid content path starting with /")}(r.Value),i=gt(r.Validity);if(null!=t.value&&null!=t.signatureV1)return function(e){var t,r;if(null==e.data)throw new GD("Record data is missing");var n=tR(e.data);if(!St(n.Value,null!==(t=e.value)&&void 0!==t?t:new Uint8Array(0)))throw new VD('Field "value" did not match between protobuf and CBOR');if(!St(n.Validity,null!==(r=e.validity)&&void 0!==r?r:new Uint8Array(0)))throw new VD('Field "validity" did not match between protobuf and CBOR');if(n.ValidityType!==e.validityType)throw new VD('Field "validityType" did not match between protobuf and CBOR');if(n.Sequence!==e.sequence)throw new VD('Field "sequence" did not match between protobuf and CBOR');if(n.TTL!==e.ttl)throw new VD('Field "ttl" did not match between protobuf and CBOR')}(t),{value:n,validityType:UD.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:UD.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 XD(e){return Mt([JD,e.bytes])}function eR(e){var t=He(e.slice(JD.length));if(!rR(t,0)&&!rR(t,18))throw new Ha("Multihash in IPNS key was not identity or sha2-256");return t}function tR(e){var t=U_(e);if(0!==t.ValidityType)throw new HD("The validity type is unsupported");return t.ValidityType=UD.ValidityType.EOL,Number.isInteger(t.Sequence)&&(t.Sequence=BigInt(t.Sequence)),Number.isInteger(t.TTL)&&(t.TTL=BigInt(t.TTL)),t}function rR(e,t){return e.code===t}var nR=sd("ipns:validator"),iR=function(){var e=r((function*(e,t){var r,n,i=$D(t);try{var o=(n=i.data,Mt([Et("ipns-signature:"),n]));r=yield e.verify(o,i.signatureV2)}catch(e){r=!1}if(!r)throw nR.error("record signature verification failed"),new VD("Record signature verification failed");if(i.validityType===UD.ValidityType.EOL){if(zD.fromString(i.validity).toDate().getTime()<Date.now())throw nR.error("record has expired"),new qD("record has expired")}else if(null!=i.validityType)throw nR.error("the validity type is unsupported"),new HD("The validity type is unsupported");nR("ipns record for %s is valid",i.value)}));return function(t,r){return e.apply(this,arguments)}}();function oR(e,t){return aR.apply(this,arguments)}function aR(){return(aR=r((function*(e,t){var r;if(t.byteLength>10240)throw new KD("The record is too large");var n,i=eR(e);rR(i,0)&&(n=bu(i));var o=null!==(r=function(e){var t;if(null!=e.pubKey)try{t=mu(e.pubKey)}catch(e){throw YD.error(e),e}if(null!=t)return t}($D(t)))&&void 0!==r?r:n;if(null==o)throw new QD("Could not extract public key from IPNS record or routing key");if(!St(XD(o.toMultihash()),e))throw new QD("Embedded public key did not match routing key");yield iR(o,t)}))).apply(this,arguments)}let sR=class extends Error{constructor(){super(...arguments),e(this,"name","InvalidMessageLengthError"),e(this,"code","ERR_INVALID_MESSAGE_LENGTH")}};function lR(e){return uR.apply(this,arguments)}function uR(){return uR=l((function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var r,n=/\r?\n/,i=new TextDecoder("utf8"),o="",a=!1,l=!1;try{for(var c,d=s(e);a=!(c=yield u(d.next())).done;a=!1){var h,v,p=c.value;if("string"==typeof p&&(p=(new TextEncoder).encode(p)),fs(p)&&(p=p.subarray()),(o+=i.decode(p,{stream:!0})).length>(null!==(h=null==t?void 0:t.maxMessageLength)&&void 0!==h?h:o.length))throw new sR("Incoming message too long");var f=o.split(n);o=null!==(v=f.pop())&&void 0!==v?v:"";for(var g=0;g<f.length;g++)yield JSON.parse(f[g])}}catch(e){l=!0,r=e}finally{try{a&&null!=d.return&&(yield u(d.return()))}finally{if(l)throw r}}""!==(o+=i.decode())&&(yield JSON.parse(o))}()})),uR.apply(this,arguments)}class cR extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid request"),this.name="InvalidRequestError"}}e(cR,"name","InvalidRequestError");class dR extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Bad response"),this.name="BadResponseError"}}function hR(e){if(null!=e[Symbol.asyncIterator])return r((function*(){var t,r=!1,n=!1;try{for(var i,o=s(e);r=!(i=yield o.next()).done;r=!1){return i.value}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield o.return())}finally{if(n)throw t}}}))();for(var t of e)return t}e(dR,"name","BadResponseError");var vR=Et("/ipns/");function pR(e){return St(e.subarray(0,vR.byteLength),vR)}class fR{constructor(t){e(this,"client",void 0),this.client=t}findProviders(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(Ac(t.client.getProviders(e,r),(e=>{var t;return{id:e.ID,multiaddrs:null!==(t=e.Addrs)&&void 0!==t?t:[]}}))))}()})).apply(this,arguments)}provide(){return r((function*(){}))()}cancelReprovide(){return r((function*(){}))()}put(e,t,n){var i=this;return r((function*(){if(pR(e)){var r=eR(e),o=it.createV1(114,r),a=$D(t);yield i.client.putIPNS(o,a,n)}}))()}get(e,t){var n=this;return r((function*(){if(!pR(e))throw new za("Not found");var r=eR(e),i=it.createV1(114,r);try{return ZD(yield n.client.getIPNS(i,t))}catch(e){if("BadResponseError"===e.name)throw new za("Not found");throw e}}))()}}class gR{constructor(t){e(this,"client",void 0),this.client=t}findPeer(e){var t=arguments,n=this;return r((function*(){var r,i=t.length>1&&void 0!==t[1]?t[1]:{},o=yield hR(n.client.getPeers(e,i));if(null!=o)return{id:o.ID,multiaddrs:null!==(r=o.Addrs)&&void 0!==r?r:[]};throw new za("Not found")}))()}getClosestPeers(e){return l((function(e){return function*(){}()})).apply(this,arguments)}}var yR=sd("delegated-routing-v1-http-api-client"),mR={concurrentRequests:4,timeout:3e4,cacheTTL:3e5,cacheName:"delegated-routing-v1-cache"},wR=new WeakSet;class bR{constructor(t){var r,n,i,o,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};d(this,wR),e(this,"started",void 0),e(this,"httpQueue",void 0),e(this,"shutDownController",void 0),e(this,"clientUrl",void 0),e(this,"timeout",void 0),e(this,"contentRouting",void 0),e(this,"peerRouting",void 0),e(this,"filterAddrs",void 0),e(this,"filterProtocols",void 0),e(this,"inFlightRequests",void 0),e(this,"cacheName",void 0),e(this,"cache",void 0),e(this,"cacheTTL",void 0),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new BT({concurrency:null!==(r=a.concurrentRequests)&&void 0!==r?r:mR.concurrentRequests}),this.inFlightRequests=new Map,this.clientUrl=t instanceof URL?t:new URL(t),this.timeout=null!==(n=a.timeout)&&void 0!==n?n:mR.timeout,this.filterAddrs=a.filterAddrs,this.filterProtocols=a.filterProtocols,this.contentRouting=new fR(this),this.peerRouting=new gR(this),this.cacheName=null!==(i=a.cacheName)&&void 0!==i?i:mR.cacheName,this.cacheTTL=null!==(o=a.cacheTTL)&&void 0!==o?o:mR.cacheTTL}get[wa](){return this.contentRouting}get[xa](){return this.peerRouting}isStarted(){return this.started}start(){var e=this;return r((function*(){var t;e.started||(e.started=!0,e.cacheTTL>0&&(e.cache=yield null===(t=globalThis.caches)||void 0===t?void 0:t.open(e.cacheName),null!=e.cache&&yR("cache enabled with ttl %d",e.cacheTTL)))}))()}stop(){var e=this;return r((function*(){var t;e.httpQueue.clear(),e.shutDownController.abort(),yield null===(t=globalThis.caches)||void 0===t?void 0:t.delete(e.cacheName),e.started=!1}))()}getProviders(e){var t=this;return l((function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yR("getProviders starts: %c",e);var i=AbortSignal.timeout(t.timeout),o=Ph([t.shutDownController.signal,i,n.signal]),a=Cc(),l=Cc();t.httpQueue.add(r((function*(){return a.resolve(),l.promise})));try{yield u(a.promise);var c=new URL("".concat(t.clientUrl,"routing/v1/providers/").concat(e.toString()));h(wR,t,ER).call(t,c,n.filterAddrs,n.filterProtocols);var d={headers:{Accept:"application/x-ndjson"},signal:o},v=yield u(h(wR,t,kR).call(t,c.toString(),d));if(null==v)throw new dR("No response received");if(!v.ok){if(404===v.status)throw new za("No matching records found");if(422===v.status)throw new cR("Request does not conform to schema or semantic constraints");throw new dR("Unexpected status code: ".concat(v.status))}if(null==v.body)throw new dR("Routing response had no body");var p=v.headers.get("Content-Type");if(null==p)throw new dR("No Content-Type header received");if(null!=p&&p.startsWith("application/json")){var f=yield u(v.json());for(var g of f.Providers){var y=h(wR,t,SR).call(t,g);null!=y&&(yield y)}}else{if(!p.includes("application/x-ndjson"))throw new dR("Unsupported Content-Type: ".concat(p));var m,w=!1,b=!1;try{for(var S,E=s(lR(DD(v.body)));w=!(S=yield u(E.next())).done;w=!1){var k=S.value,x=h(wR,t,SR).call(t,k);null!=x&&(yield x)}}catch(e){b=!0,m=e}finally{try{w&&null!=E.return&&(yield u(E.return()))}finally{if(b)throw m}}}}finally{o.clear(),l.resolve(),yR("getProviders finished: %c",e)}}()})).apply(this,arguments)}getPeers(e){var t=this;return l((function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yR("getPeers starts: %c",e);var i=AbortSignal.timeout(t.timeout),o=Ph([t.shutDownController.signal,i,n.signal]),a=Cc(),l=Cc();t.httpQueue.add(r((function*(){return a.resolve(),l.promise})));try{yield u(a.promise);var c=new URL("".concat(t.clientUrl,"routing/v1/peers/").concat(e.toCID().toString()));h(wR,t,ER).call(t,c,n.filterAddrs,n.filterProtocols);var d={headers:{Accept:"application/x-ndjson"},signal:o},v=yield u(h(wR,t,kR).call(t,c.toString(),d));if(404===v.status)throw new za("No matching records found");if(422===v.status)throw new cR("Request does not conform to schema or semantic constraints");if(null==v.body)throw new dR("Routing response had no body");if("application/json"===v.headers.get("Content-Type")){var p=yield u(v.json());for(var f of p.Peers){var g=h(wR,t,SR).call(t,f);null!=g&&(yield g)}}else{var y,m=!1,w=!1;try{for(var b,S=s(lR(DD(v.body)));m=!(b=yield u(S.next())).done;m=!1){var E=b.value,k=h(wR,t,SR).call(t,E);null!=k&&(yield k)}}catch(e){w=!0,y=e}finally{try{m&&null!=S.return&&(yield u(S.return()))}finally{if(w)throw y}}}}catch(e){yR.error("getPeers errored:",e)}finally{o.clear(),l.resolve(),yR("getPeers finished: %c",e)}}()})).apply(this,arguments)}getIPNS(e){var t=arguments,n=this;return r((function*(){var i=t.length>1&&void 0!==t[1]?t[1]:{};yR("getIPNS starts: %s",e);var o=AbortSignal.timeout(n.timeout),a=Ph([n.shutDownController.signal,o,i.signal]),s=Cc(),l=Cc();n.httpQueue.add(r((function*(){return s.resolve(),l.promise})));var u="".concat(n.clientUrl,"routing/v1/ipns/").concat(e);try{yield s.promise;var c={headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:a},d=yield h(wR,n,kR).call(n,u,c);if(yR("getIPNS GET %s %d",u,d.status),404===d.status)throw new za("No matching records found");if(422===d.status)throw new cR("Request does not conform to schema or semantic constraints");if(null==d.body)throw new dR("GET ipns response had no body");var v=yield d.arrayBuffer(),p=new Uint8Array(v,0,v.byteLength);return!1!==i.validate&&(yield oR(XD(e.multihash),p)),$D(p)}catch(e){throw yR.error("getIPNS GET %s error:",u,e),e}finally{a.clear(),l.resolve(),yR("getIPNS finished: %s",e)}}))()}putIPNS(e,t){var n=arguments,i=this;return r((function*(){var o=n.length>2&&void 0!==n[2]?n[2]:{};yR("putIPNS starts: %c",e);var a=AbortSignal.timeout(i.timeout),s=Ph([i.shutDownController.signal,a,o.signal]),l=Cc(),u=Cc();i.httpQueue.add(r((function*(){return l.resolve(),u.promise})));var c="".concat(i.clientUrl,"routing/v1/ipns/").concat(e);try{yield l.promise;var d={method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:ZD(t),signal:s},v=yield h(wR,i,kR).call(i,c,d);if(yR("putIPNS PUT %s %d",c,v.status),200!==v.status)throw new dR("PUT ipns response had status other than 200")}catch(e){throw yR.error("putIPNS PUT %s error:",c,e.stack),e}finally{s.clear(),u.resolve(),yR("putIPNS finished: %c",e)}}))()}}function SR(e){try{var r,n,i=[],o=null!==(r=null===(n=e.Addrs)||void 0===n?void 0:n.map(kr))&&void 0!==r?r:[];return null!=e.Protocols&&i.push(...e.Protocols),null!=e.Protocol&&(i.push(e.Protocol),delete e.Protocol),t(t({},e),{},{Schema:"peer",ID:Du(e.ID),Addrs:o,Protocols:i})}catch(e){yR.error("could not conform record to peer schema",e)}}function ER(e,t,r){if(null!=t||null!=this.filterAddrs){var n,i,o,a=null!==(n=null!==(i=null==t?void 0:t.join(","))&&void 0!==i?i:null===(o=this.filterAddrs)||void 0===o?void 0:o.join(","))&&void 0!==n?n:"";""!==a&&e.searchParams.set("filter-addrs",a)}if(null!=r||null!=this.filterProtocols){var s,l,u,c=null!==(s=null!==(l=null==r?void 0:r.join(","))&&void 0!==l?l:null===(u=this.filterProtocols)||void 0===u?void 0:u.join(","))&&void 0!==s?s:"";""!==c&&e.searchParams.set("filter-protocols",c)}}function kR(e,t){return xR.apply(this,arguments)}function xR(){return xR=r((function*(e,t){var n,i=this,o=null!==(n=t.method)&&void 0!==n?n:"GET",a="".concat(o,"-").concat(e);if("GET"===o){var s,l=yield null===(s=this.cache)||void 0===s?void 0:s.match(e);if(null!=l){var u,c;if(parseInt(null!==(u=l.headers.get("x-cache-expires"))&&void 0!==u?u:"0",10)>Date.now())return yR("returning cached response for %s",a),l;yield null===(c=this.cache)||void 0===c?void 0:c.delete(e)}}var d=this.inFlightRequests.get(a);if(null!=d){var h=yield d;return yR("deduplicating outgoing request for %s",a),h.clone()}var v=fetch(e,t).then(function(){var t=r((function*(t){if(null!=i.cache&&t.ok&&"GET"===o){var r=Date.now()+i.cacheTTL,n=new Headers(t.headers);n.set("x-cache-expires",r.toString());var a=new Response(t.clone().body,{status:t.status,statusText:t.statusText,headers:n});yield i.cache.put(e,a)}return t}));return function(e){return t.apply(this,arguments)}}()).finally((()=>{this.inFlightRequests.delete(a)}));return this.inFlightRequests.set(a,v),yield v})),xR.apply(this,arguments)}var AR="[a-fA-F\\d:]",CR=e=>e&&e.includeBoundaries?"(?:(?<=\\s|^)(?=".concat(AR,")|(?<=").concat(AR,")(?=\\s|$))"):"",IR="(?: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}",TR="[a-fA-F\\d]{1,4}",PR="\n(?:\n(?:".concat(TR,":){7}(?:").concat(TR,"|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:").concat(TR,":){6}(?:").concat(IR,"|:").concat(TR,"|:)| // 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(TR,":){5}(?::").concat(IR,"|(?::").concat(TR,"){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(TR,":){4}(?:(?::").concat(TR,"){0,1}:").concat(IR,"|(?::").concat(TR,"){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(TR,":){3}(?:(?::").concat(TR,"){0,2}:").concat(IR,"|(?::").concat(TR,"){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(TR,":){2}(?:(?::").concat(TR,"){0,3}:").concat(IR,"|(?::").concat(TR,"){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(TR,":){1}(?:(?::").concat(TR,"){0,4}:").concat(IR,"|(?::").concat(TR,"){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::").concat(TR,"){0,5}:").concat(IR,"|(?::").concat(TR,"){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(),_R=new RegExp("(?:^".concat(IR,"$)|(?:^").concat(PR,"$)")),BR=new RegExp("^".concat(IR,"$")),NR=new RegExp("^".concat(PR,"$")),DR=e=>e&&e.exact?_R:new RegExp("(?:".concat(CR(e)).concat(IR).concat(CR(e),")|(?:").concat(CR(e)).concat(PR).concat(CR(e),")"),"g");DR.v4=e=>e&&e.exact?BR:new RegExp("".concat(CR(e)).concat(IR).concat(CR(e)),"g"),DR.v6=e=>e&&e.exact?NR:new RegExp("".concat(CR(e)).concat(PR).concat(CR(e)),"g");var{toString:RR}=Object.prototype;var OR={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function LR(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t=e,"[object RegExp]"!==RR.call(t))throw new TypeError("Expected a RegExp instance");var n=Object.keys(OR).map((t=>("boolean"==typeof r[t]?r[t]:e[t])?OR[t]:"")).join(""),i=new RegExp(r.source||e.source,n);return i.lastIndex="number"==typeof r.lastIndex?r.lastIndex:e.lastIndex,i}function MR(e,t){var r,n,{timeout:i}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{return(r=()=>LR(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 UR={timeout:400};function FR(e){return!(e.length>45)&&MR(DR.v6({exact:!0}),e,UR)}var zR={http:"80",https:"443",ws:"80",wss:"443"},jR=["http","https","ws","wss"];function VR(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(":");jR.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==zR[e])return;return zR[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=[qR(o,n),HR(a,i),KR(i)];return null!=s&&l.push(function(e){if(null==e||""===e)return;return["http-path",encodeURIComponent(e)]}(s)),kr("/"+l.filter((e=>Boolean(e))).reduce(((e,t)=>e.concat(t)),[]).join("/"))}function qR(e,t){if(null!=e&&""!==e){if(function(e){return!(e.length>15)&&MR(DR.v4({exact:!0}),e,UR)}(e))return["ip4",e];if(FR(e))return["ip6",e];if("["===e[0]){var r=e.substring(1,e.length-1);if(FR(r))return["ip6",r]}return[t,e]}}function HR(e,t){if(null!=e&&""!==e)return"udp"===t?["udp",e]:["tcp",e]}function KR(e){if(null==e.match(/^tcp$|^udp$/))return"https"===e?["/tls/http"]:"wss"===e?["/tls/ws"]:[e]}var WR=["https://trustless-gateway.link","https://4everland.io"];class GR{constructor(){var t,r,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e(this,"gateways",void 0),e(this,"shuffle",void 0),this.gateways=(null!==(t=n.gateways)&&void 0!==t?t:WR).map((e=>function(e){return e=e.toString(),{id:Mu(it.createV1(2336,Ge.digest(Et(e)))),multiaddrs:[VR(e)]}}(e))),this.shuffle=null===(r=n.shuffle)||void 0===r||r}findProviders(e,r){var n=this;return l((function*(){yield*c(s((n.shuffle?n.gateways.toSorted((()=>Math.random()>.5?1:-1)):n.gateways).map((e=>t(t({},e),{},{protocols:["transport-ipfs-gateway-http"]})))))}))()}}function QR(){return new GR(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{})}class YR{constructor(t){e(this,"libp2p",void 0),this.libp2p=t}provide(e,t){var n=this;return r((function*(){yield n.libp2p.contentRouting.provide(e,t)}))()}cancelReprovide(e,t){var n=this;return r((function*(){yield n.libp2p.contentRouting.cancelReprovide(e,t)}))()}findProviders(e,t){var r=this;return l((function*(){yield*c(s(r.libp2p.contentRouting.findProviders(e,t)))}))()}put(e,t,n){var i=this;return r((function*(){yield i.libp2p.contentRouting.put(e,t,n)}))()}get(e,t){var n=this;return r((function*(){return n.libp2p.contentRouting.get(e,t)}))()}findPeer(e,t){var n=this;return r((function*(){return n.libp2p.peerRouting.findPeer(e,t)}))()}getClosestPeers(e,t){var r=this;return l((function*(){yield*c(s(r.libp2p.peerRouting.getClosestPeers(e,t)))}))()}}function JR(e){return new YR(e)}class ZR extends GN{constructor(r){super(t(t({},r),{},{components:{libp2p:r.libp2p}})),e(this,"libp2p",void 0),this.libp2p=r.libp2p}start(){var e=()=>super.start,t=this;return r((function*(){yield e().call(t),yield t.libp2p.start()}))()}stop(){var e=()=>super.stop,t=this;return r((function*(){yield e().call(t),yield t.libp2p.stop()}))()}}class $R extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The frame was invalid"),this.name="InvalidFrameError"}}e($R,"name","InvalidFrameError");class XR extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unrequested ping error"),this.name="UnrequestedPingError"}}e(XR,"name","UnrequestedPingError");class eO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unrequested ping error"),this.name="NotMatchingPingError"}}e(eO,"name","NotMatchingPingError");class tO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid state"),this.name="InvalidStateError"}}e(tO,"name","InvalidStateError");class rO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Strean already exists"),this.name="StreamAlreadyExistsError"}}e(rO,"name","StreamAlreadyExistsError");class nO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Decode invalid version"),this.name="DecodeInvalidVersionError"}}e(nO,"name","DecodeInvalidVersionError");class iO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Both clients"),this.name="BothClientsError"}}e(iO,"name","BothClientsError");class oO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Receive window exceeded"),this.name="ReceiveWindowExceededError"}}e(oO,"name","ReceiveWindowExceededError");var aO,sO,lO=new Set([$R.name,XR.name,eO.name,rO.name,nO.name,iO.name,oO.name]),uO=262144,cO={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,initialStreamWindowSize:uO,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"}(aO||(aO={})),function(e){e[e.SYN=1]="SYN",e[e.ACK=2]="ACK",e[e.FIN=4]="FIN",e[e.RST=8]="RST"}(sO||(sO={})),Object.values(sO).filter((e=>"string"!=typeof e));var dO;!function(e){e[e.NormalTermination=0]="NormalTermination",e[e.ProtocolError=1]="ProtocolError",e[e.InternalError=2]="InternalError"}(dO||(dO={}));var hO=2**24;let vO=class{constructor(t){e(this,"source",void 0),e(this,"buffer",void 0),e(this,"frameInProgress",void 0),this.source=function(e){if(void 0!==e[Symbol.iterator]){var t=e[Symbol.iterator]();return t.return=void 0,{[Symbol.iterator]:()=>t}}if(void 0!==e[Symbol.asyncIterator]){var r=e[Symbol.asyncIterator]();return r.return=void 0,{[Symbol.asyncIterator]:()=>r}}throw new Error("a source must be either an iterable or an async iterable")}(t),this.buffer=new gs,this.frameInProgress=!1}emitFrames(){var e=this;return l((function*(){var t,r=!1,n=!1;try{for(var i,o=s(e.source);r=!(i=yield u(o.next())).done;r=!1){var a=i.value;for(e.buffer.append(a);;){var l=e.readHeader();if(void 0===l)break;var{type:c,length:d}=l;c===aO.Data?(e.frameInProgress=!0,yield{header:l,readData:e.readBytes.bind(e,d)}):yield{header:l}}}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw t}}}))()}readHeader(){if(this.frameInProgress)throw new tO("decoding frame already in progress");if(!(this.buffer.length<12)){var e=function(e){if(0!==e[0])throw new $R("Invalid frame version");return{type:e[1],flag:(e[2]<<8)+e[3],streamID:e[4]*hO+(e[5]<<16)+(e[6]<<8)+e[7],length:e[8]*hO+(e[9]<<16)+(e[10]<<8)+e[11]}}(this.buffer.subarray(0,12));return this.buffer.consume(12),e}}readBytes(e){var t=this;return r((function*(){if(t.buffer.length<e){var r,n=!1,i=!1;try{for(var o,a=s(t.source);n=!(o=yield a.next()).done;n=!1){var l=o.value;if(t.buffer.append(l),t.buffer.length>=e)break}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield a.return())}finally{if(i)throw r}}}var u=t.buffer.sublist(0,e);return t.buffer.consume(e),t.frameInProgress=!1,u}))()}};function pO(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 fO;!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"}(fO||(fO={}));class gO extends cp{constructor(r){super(t(t({},r),{},{onEnd:e=>{var t;this.state=fO.Finished,null===(t=r.onEnd)||void 0===t||t.call(r,e)}})),e(this,"name",void 0),e(this,"state",void 0),e(this,"config",void 0),e(this,"_id",void 0),e(this,"sendWindowCapacity",void 0),e(this,"sendWindowCapacityUpdate",void 0),e(this,"recvWindow",void 0),e(this,"recvWindowCapacity",void 0),e(this,"epochStart",void 0),e(this,"getRTT",void 0),e(this,"sendFrame",void 0),this.config=r.config,this._id=parseInt(r.id,10),this.name=r.name,this.state=r.state,this.sendWindowCapacity=uO,this.recvWindow=this.config.initialStreamWindowSize,this.recvWindowCapacity=this.recvWindow,this.epochStart=Date.now(),this.getRTT=r.getRTT,this.sendFrame=r.sendFrame,this.source=iv(this.source,(()=>{this.sendWindowUpdate()}))}sendNewStream(){return r((function*(){}))()}sendData(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};for(e=e.sublist();0!==e.byteLength;){var i,o;if(0===n.sendWindowCapacity)if(null===(i=n.log)||void 0===i||i.trace("wait for send window capacity, status %s",n.status),yield n.waitForSendWindowCapacity(r),"closed"===n.status||"aborted"===n.status||"reset"===n.status)return void(null===(o=n.log)||void 0===o||o.trace("%s while waiting for send window capacity",n.status));var a=Math.min(n.sendWindowCapacity,n.config.maxMessageSize-12,e.length),s=n.getSendFlags();n.sendFrame({type:aO.Data,flag:s,streamID:n._id,length:a},e.sublist(0,a)),n.sendWindowCapacity-=a,e.consume(a)}}))()}sendReset(){var e=this;return r((function*(){e.sendFrame({type:aO.WindowUpdate,flag:sO.RST,streamID:e._id,length:0})}))()}sendCloseWrite(){var e=this;return r((function*(){var t=e.getSendFlags()|sO.FIN;e.sendFrame({type:aO.WindowUpdate,flag:t,streamID:e._id,length:0})}))()}sendCloseRead(){return r((function*(){}))()}waitForSendWindowCapacity(){var e=arguments,t=this;return r((function*(){var r,n=e.length>0&&void 0!==e[0]?e[0]:{};if(!(t.sendWindowCapacity>0)){var i,o,a=()=>{"open"===t.status||"closing"===t.status?o(new Ia("Stream aborted")):i()};null===(r=n.signal)||void 0===r||r.addEventListener("abort",a);try{yield new Promise(((e,r)=>{t.sendWindowCapacityUpdate=()=>{e()},o=r,i=e}))}finally{var s;null===(s=n.signal)||void 0===s||s.removeEventListener("abort",a)}}}))()}handleWindowUpdate(e){var t;null===(t=this.log)||void 0===t||t.trace("stream received window update id=%s",this._id),this.processFlags(e.flag);var r,n=this.sendWindowCapacity;(this.sendWindowCapacity+=e.length,0===n&&e.length>0)&&(null===(r=this.sendWindowCapacityUpdate)||void 0===r||r.call(this))}handleData(e,t){var n=this;return r((function*(){var r;if(null===(r=n.log)||void 0===r||r.trace("stream received data id=%s",n._id),n.processFlags(e.flag),n.recvWindowCapacity<e.length)throw new oO("Receive window exceeded");var i=yield t();n.recvWindowCapacity-=e.length,n.sourcePush(i)}))()}processFlags(e){(e&sO.ACK)===sO.ACK&&this.state===fO.SYNSent&&(this.state=fO.Established),(e&sO.FIN)===sO.FIN&&this.remoteCloseWrite(),(e&sO.RST)===sO.RST&&this.reset()}getSendFlags(){switch(this.state){case fO.Init:return this.state=fO.SYNSent,sO.SYN;case fO.SYNReceived:return this.state=fO.Established,sO.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:aO.WindowUpdate,flag:e,streamID:this._id,length:n})}}}var yO="/yamux/1.0.0";class mO{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"protocol",yO),e(this,"_components",void 0),e(this,"_init",void 0),e(this,Symbol.toStringTag,"@chainsafe/libp2p-yamux"),e(this,ds,["@libp2p/stream-multiplexing"]),this._components=t,this._init=r}createStreamMuxer(e){return new wO(this._components,t(t({},this._init),e))}}class wO{constructor(n,i){var o,a=this;e(this,"protocol",yO),e(this,"source",void 0),e(this,"sink",void 0),e(this,"config",void 0),e(this,"log",void 0),e(this,"logger",void 0),e(this,"closeController",void 0),e(this,"nextStreamID",void 0),e(this,"_streams",void 0),e(this,"nextPingID",void 0),e(this,"activePing",void 0),e(this,"rtt",void 0),e(this,"client",void 0),e(this,"localGoAway",void 0),e(this,"remoteGoAway",void 0),e(this,"numInboundStreams",void 0),e(this,"numOutboundStreams",void 0),e(this,"onIncomingStream",void 0),e(this,"onStreamEnd",void 0),this.client="outbound"===i.direction,this.config=t(t({},cO),i),this.logger=n.logger,this.log=this.logger.forComponent("libp2p:yamux"),function(e){if(e.keepAliveInterval<=0)throw new _a("keep-alive interval must be positive");if(e.maxInboundStreams<0)throw new _a("max inbound streams must be larger or equal 0");if(e.maxOutboundStreams<0)throw new _a("max outbound streams must be larger or equal 0");if(e.initialStreamWindowSize<uO)throw new _a("InitialStreamWindowSize must be larger or equal 256 kB");if(e.maxStreamWindowSize<e.initialStreamWindowSize)throw new _a("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(e.maxStreamWindowSize>2**32-1)throw new _a("MaxStreamWindowSize must be less than equal MAX_UINT32");if(e.maxMessageSize<1024)throw new _a("MaxMessageSize must be greater than a kilobyte")}(this.config),this.closeController=new AbortController,this.closeController.signal,this.onIncomingStream=i.onIncomingStream,this.onStreamEnd=i.onStreamEnd,this._streams=new Map,this.source=_c({onEnd:()=>{var e;null===(e=this.log)||void 0===e||e.trace("muxer source ended"),this._streams.forEach((e=>{e.destroy()}))}}),this.sink=function(){var e=r((function*(e){var t,r,n,i=()=>{var t,r=sp(e);if(null!=r.return){var n=r.return();null!=(t=n)&&"function"==typeof t.then&&n.catch((e=>{var t;null===(t=a.log)||void 0===t||t.call(a,"could not cause sink source to return",e)}))}};try{var o=new vO(e);try{a.closeController.signal.addEventListener("abort",i);var l,u=!1,c=!1;try{for(var d,h=s(o.emitFrames());u=!(d=yield h.next()).done;u=!1){var v=d.value;yield a.handleFrame(v.header,v.readData)}}catch(e){c=!0,l=e}finally{try{u&&null!=h.return&&(yield h.return())}finally{if(c)throw l}}}finally{a.closeController.signal.removeEventListener("abort",i)}r=dO.NormalTermination}catch(e){var p,f;if(lO.has(e.name))null===(p=a.log)||void 0===p||p.error("protocol error in sink",e),r=dO.ProtocolError;else null===(f=a.log)||void 0===f||f.error("internal error in sink",e),r=dO.InternalError;n=e}null===(t=a.log)||void 0===t||t.trace("muxer sink ended"),null!=n?a.abort(n,r):yield a.close({reason:r})}));return function(t){return e.apply(this,arguments)}}(),this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,null===(o=this.log)||void 0===o||o.trace("muxer created"),this.config.enableKeepAlive&&this.keepAliveLoop().catch((e=>{var t;return null===(t=this.log)||void 0===t?void 0:t.error("keepalive error: %s",e)})),this.ping().catch((e=>{var t;return null===(t=this.log)||void 0===t?void 0:t.error("ping error: %s",e)}))}get streams(){return Array.from(this._streams.values())}newStream(e){var t;if(void 0!==this.remoteGoAway)throw new Ma("Muxer closed remotely");if(void 0!==this.localGoAway)throw new Ma("Muxer closed locally");var r=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.config.maxOutboundStreams)throw new ts("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,fO.Init,"outbound");return this._streams.set(r,n),this.numOutboundStreams++,n.sendWindowUpdate(),n}ping(){var e=this;return r((function*(){if(void 0!==e.remoteGoAway)throw new Ma("Muxer closed remotely");if(void 0!==e.localGoAway)throw new Ma("Muxer closed locally");if(void 0===e.activePing){var t=()=>{};e.activePing={id:e.nextPingID++,promise:new Promise(((r,n)=>{var i=()=>{n(new Ma("Muxer closed locally"))};e.closeController.signal.addEventListener("abort",i,{once:!0}),t=()=>{e.closeController.signal.removeEventListener("abort",i),r()}})),resolve:t};var r=Date.now();e.sendPing(e.activePing.id);try{yield e.activePing.promise}finally{delete e.activePing}var n=Date.now();e.rtt=n-r}else yield e.activePing.promise;return e.rtt}))()}getRTT(){return this.rtt}close(){var e=arguments,n=this;return r((function*(){var i,o,a,s=e.length>0&&void 0!==e[0]?e[0]:{};if(!n.closeController.signal.aborted){var l=null!==(i=null===(o=s)||void 0===o?void 0:o.reason)&&void 0!==i?i:dO.NormalTermination;if(null===(a=n.log)||void 0===a||a.trace("muxer close reason=%s",l),null==s.signal){var u=AbortSignal.timeout(500);s=t(t({},s),{},{signal:u})}try{yield Promise.all([...n._streams.values()].map(function(){var e=r((function*(e){return e.close(s)}));return function(t){return e.apply(this,arguments)}}())),n.sendGoAway(l),n._closeMuxer()}catch(e){n.abort(e)}}}))()}abort(e,t){var r;if(!this.closeController.signal.aborted){for(var n of(t=null!=t?t:dO.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 _a("Stream already exists with that id");var i=new gO({id:e.toString(),name:t,state:r,direction:n,sendFrame:this.sendFrame.bind(this),onEnd:()=>{var t;this.closeStream(e),null===(t=this.onStreamEnd)||void 0===t||t.call(this,i)},log:this.logger.forComponent("libp2p:yamux:".concat(n,":").concat(e)),config:this.config,getRTT:this.getRTT.bind(this)});return i}closeStream(e){this.client===(e%2==0)?this.numInboundStreams--:this.numOutboundStreams--,this._streams.delete(e)}keepAliveLoop(){var e=this;return r((function*(){var t,r=new Promise(((t,r)=>{e.closeController.signal.addEventListener("abort",r,{once:!0})}));null===(t=e.log)||void 0===t||t.trace("muxer keepalive enabled interval=%s",e.config.keepAliveInterval);for(var n,i=function*(){var t;try{yield Promise.race([r,new Promise((r=>{t=setTimeout(r,e.config.keepAliveInterval)}))]),e.ping().catch((t=>{var r;return null===(r=e.log)||void 0===r?void 0:r.error("ping error: %s",t)}))}catch(e){return clearInterval(t),{v:void 0}}};;)if(n=yield*i())return n.v}))()}handleFrame(e,t){var n=this;return r((function*(){var r,{streamID:i,type:o,length:a}=e;if(null===(r=n.log)||void 0===r||r.trace("received frame %o",e),0===i)switch(o){case aO.Ping:return void n.handlePing(e);case aO.GoAway:return void n.handleGoAway(a);default:throw new $R("Invalid frame type")}else switch(e.type){case aO.Data:case aO.WindowUpdate:return void(yield n.handleStreamMessage(e,t));default:throw new $R("Invalid frame type")}}))()}handlePing(e){if(e.flag===sO.SYN){var t;null===(t=this.log)||void 0===t||t.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,sO.ACK)}else{if(e.flag!==sO.ACK)throw new $R("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 XR("ping not requested");if(this.activePing.id!==e)throw new eO("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=dO[e])&&void 0!==r?r:"unknown"),this.remoteGoAway=e,this._streams.values()))n.reset();this._closeMuxer()}handleStreamMessage(e,t){var n=this;return r((function*(){var{streamID:r,flag:i,type:o}=e;(i&sO.SYN)===sO.SYN&&n.incomingStream(r);var a=n._streams.get(r);if(void 0!==a)switch(o){case aO.WindowUpdate:return void a.handleWindowUpdate(e);case aO.Data:if(void 0===t)throw new Error("unreachable");return void(yield a.handleData(e,t));default:throw new Error("unreachable")}else if(o===aO.Data){var s;if(null===(s=n.log)||void 0===s||s.call(n,"discarding data for stream id=%s",r),void 0===t)throw new Error("unreachable");yield t()}else{var l;null===(l=n.log)||void 0===l||l.trace("frame for missing stream id=%s",r)}}))()}incomingStream(e){var t,r;if(this.client!==(e%2==0))throw new _a("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:aO.WindowUpdate,flag:sO.RST,streamID:e,length:0});var i=this._newStream(e,void 0,fO.SYNReceived,"inbound");this.numInboundStreams++,this._streams.set(e,i),null===(r=this.onIncomingStream)||void 0===r||r.call(this,i)}else this.sendFrame({type:aO.WindowUpdate,flag:sO.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===aO.Data){if(void 0===t)throw new $R("Invalid frame");this.source.push(new gs(pO(e),t))}else this.source.push(pO(e))}sendPing(e){var t,r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:sO.SYN;n===sO.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:aO.Ping,flag:n,streamID:0,length:e})}sendGoAway(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:dO.NormalTermination;null===(e=this.log)||void 0===e||e.call(this,"sending GoAway reason=%s",dO[t]),this.localGoAway=t,this.sendFrame({type:aO.GoAway,flag:0,streamID:0,length:t})}}function bO(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new mO(t,e)}function SO(e){try{var[[t,r]]=e.stringTuples();if(null==r)return!1;if(41===t)return n=r,new wr("2000::/3").contains(n)}catch(e){}var n;return!1}function EO(e){try{var[[t]]=e.stringTuples();return 4===t||41===t}catch(e){}return!1}function kO(e){try{var t;if(!EO(e))return!1;var[[,r]]=e.stringTuples();return null!=r&&(null!==(t=lD(r))&&void 0!==t&&t)}catch(e){}return!0}var xO;!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=()=>ql(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=()=>ql(n)}(e.ResponseStatus||(e.ResponseStatus={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((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 Kl('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=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(e.PeerInfo||(e.PeerInfo={})),function(t){var r;t.codec=()=>(null==r&&(r=Hl((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=>jl(e,t.codec()),t.decode=(e,r)=>wl(e,t.codec(),r)}(e.Dial||(e.Dial={})),function(t){var r;t.codec=()=>(null==r&&(r=Hl((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=>jl(e,t.codec()),t.decode=(e,r)=>wl(e,t.codec(),r)}(e.DialResponse||(e.DialResponse={})),e.codec=()=>(null==i&&(i=Hl((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=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(xO||(xO={}));class AO{constructor(t,n){var i,o,a,s,l,u;e(this,"components",void 0),e(this,"protocol",void 0),e(this,"timeout",void 0),e(this,"maxInboundStreams",void 0),e(this,"maxOutboundStreams",void 0),e(this,"maxMessageSize",void 0),e(this,"started",void 0),e(this,"log",void 0),e(this,"topologyId",void 0),e(this,"dialResults",void 0),e(this,"findPeers",void 0),e(this,"addressFilter",void 0),e(this,"connectionThreshold",void 0),e(this,Symbol.toStringTag,"@libp2p/autonat"),e(this,ds,["@libp2p/autonat"]),this.components=t,this.log=t.logger.forComponent("libp2p:auto-nat"),this.started=!1,this.protocol="/".concat(null!==(i=n.protocolPrefix)&&void 0!==i?i:"libp2p","/").concat("autonat","/").concat("1.0.0"),this.timeout=null!==(o=n.timeout)&&void 0!==o?o:3e4,this.maxInboundStreams=null!==(a=n.maxInboundStreams)&&void 0!==a?a:2,this.maxOutboundStreams=null!==(s=n.maxOutboundStreams)&&void 0!==s?s:20,this.connectionThreshold=null!==(l=n.connectionThreshold)&&void 0!==l?l:80,this.maxMessageSize=null!==(u=n.maxMessageSize)&&void 0!==u?u:8192,this.dialResults=new Map,this.findPeers=function(e,t,n){var i,o;function a(){var s,l={signal:o.signal};if(null!=(null===(s=n)||void 0===s?void 0:s.timeout)){var u=Ph([o.signal,AbortSignal.timeout(n.timeout)]);l.signal=u}Promise.resolve().then(r((function*(){yield e(l)}))).catch((()=>{})).finally((()=>{o.signal.aborted||(i=setTimeout(a,t))}))}var s=!1;return{setInterval:e=>{t!==e&&(t=e,null!=i&&(clearTimeout(i),i=setTimeout(a,t)))},setTimeout:e=>{null!=n||(n={}),n.timeout=e},start:()=>{var e;s||(s=!0,(o=new AbortController).signal,!0===(null===(e=n)||void 0===e?void 0:e.runImmediately)?queueMicrotask((()=>{a()})):i=setTimeout(a,t))},stop:()=>{var e;clearTimeout(i),null===(e=o)||void 0===e||e.abort(),s=!1}}}(this.findRandomPeers.bind(this),6e4),this.addressFilter=$h(1024)}get[hs](){return["@libp2p/identify"]}isStarted(){return this.started}start(){var e=this;return r((function*(){e.started||(yield e.components.registrar.handle(e.protocol,(t=>{e.handleIncomingAutonatStream(t).catch((t=>{e.log.error("error handling incoming autonat stream - %e",t)}))}),{maxInboundStreams:e.maxInboundStreams,maxOutboundStreams:e.maxOutboundStreams}),e.topologyId=yield e.components.registrar.register(e.protocol,{onConnect:(t,r)=>{e.verifyExternalAddresses(r).catch((t=>{e.log.error("could not verify addresses - %e",t)}))}}),e.findPeers.start(),e.started=!0)}))()}stop(){var e=this;return r((function*(){yield e.components.registrar.unhandle(e.protocol),null!=e.topologyId&&(yield e.components.registrar.unhandle(e.topologyId)),e.dialResults.clear(),e.findPeers.stop(),e.started=!1}))()}allAddressesAreVerified(){return this.components.addressManager.getAddressesWithMetadata().every((e=>e.expires>Date.now()||e.verified))}findRandomPeers(e){var t=this;return r((function*(){if(!t.allAddressesAreVerified()){var r=Ph([AbortSignal.timeout(1e4),null==e?void 0:e.signal]);try{t.log("starting random walk to find peers to run AutoNAT");var n,i=!1,o=!1;try{for(var a,l=s(t.components.randomWalk.walk({signal:r}));i=!(a=yield l.next()).done;i=!1){var u=a.value;if(yield t.components.connectionManager.isDialable(u.multiaddrs)){try{t.log.trace("dial random peer %p",u.id),yield t.components.connectionManager.openConnection(u.multiaddrs,{signal:r})}catch(e){}if(t.allAddressesAreVerified())return void t.log("stopping random walk, all addresses are verified");if(!t.hasConnectionCapacity())return void t.log("stopping random walk, too close to max connections")}else t.log.trace("random peer %p was not dialable %s",u.id,u.multiaddrs.map((e=>e.toString())).join(", "))}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield l.return())}finally{if(o)throw n}}}catch(e){}}}))()}handleIncomingAutonatStream(e){var t=this;return r((function*(){var r=AbortSignal.timeout(t.timeout),n=xd(e.stream,{maxDataLength:t.maxMessageSize}).pb(xO);try{var i=yield n.read({signal:r}),o=yield t.handleAutonatMessage(i,e.connection,{signal:r});yield n.write(o,{signal:r}),yield n.unwrap().unwrap().close({signal:r})}catch(r){t.log.error("error handling incoming autonat stream - %e",r),e.stream.abort(r)}}))()}handleAutonatMessage(e,t,n){var i=this;return r((function*(){var r,o=i.components.addressManager.getAddresses().map((e=>e.toOptions().host)),a=e.dial;if(null==a)return i.log.error("dial was missing from message"),{type:xO.MessageType.DIAL_RESPONSE,dialResponse:{status:xO.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:xO.MessageType.DIAL_RESPONSE,dialResponse:{status:xO.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}};try{var l=He(s.id);r=Lu(l)}catch(e){return i.log.error("invalid PeerId - %e",e),{type:xO.MessageType.DIAL_RESPONSE,dialResponse:{status:xO.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}}}if(i.log("incoming request from %p",r),!t.remotePeer.equals(r))return i.log("target peer %p did not equal sending peer %p",r,t.remotePeer),{type:xO.MessageType.DIAL_RESPONSE,dialResponse:{status:xO.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}};var u=s.addrs.map((e=>kr(e))).filter((e=>{var r=e.toOptions();return!kO(e)&&(r.host!==t.remoteAddr.toOptions().host?(i.log.trace("not dialing %a - target host did not match remote host %a",e,t.remoteAddr),!1):!o.includes(r.host)&&(null!=i.components.transportManager.dialTransportForMultiaddr(e)||(i.log.trace("not dialing %a - transport unsupported",e),!1)))})).map((e=>(null==e.getPeerId()&&(e=e.encapsulate("/p2p/".concat(r.toString()))),e)));if(0===u.length)return i.log("refused to dial all multiaddrs for %p from message",r),{type:xO.MessageType.DIAL_RESPONSE,dialResponse:{status:xO.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}};i.log("dial multiaddrs %s for peer %p",u.map((e=>e.toString())).join(", "),r);var c="",d=u[0];for(var h of u){var v=void 0;d=h;try{if(!(v=yield i.components.connectionManager.openConnection(h,n)).remoteAddr.equals(h))throw i.log.error("tried to dial %a but dialed %a",h,v.remoteAddr),new Error("Unexpected remote address");return i.log("successfully dialed %p via %a",r,h),{type:xO.MessageType.DIAL_RESPONSE,dialResponse:{status:xO.ResponseStatus.OK,addr:v.remoteAddr.decapsulateCode(xr("p2p").code).bytes}}}catch(e){i.log.error("could not dial %p - %e",r,e),c=e.message}finally{null!=v&&(yield v.close())}}return{type:xO.MessageType.DIAL_RESPONSE,dialResponse:{status:xO.ResponseStatus.E_DIAL_ERROR,statusText:c,addr:d.bytes}}}))()}getFirstUnverifiedMultiaddr(e,t){var r=this.components.addressManager.getAddressesWithMetadata().sort(((e,t)=>"observed"===e.type&&"observed"!==t.type?1:"observed"===t.type&&"observed"!==e.type?-1:0)).filter((e=>{if(!(e.expires<Date.now()))return!1;if(6===e.multiaddr.toOptions().family){if(!t)return!1;if(!SO(e.multiaddr))return!1}return!kO(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 zh,queue:new gv({concurrency:3,maxSize:50}),type:n.type,lastVerified:n.lastVerified},this.dialResults.set(i,o)}return o}}removeOutdatedMultiaddrResults(){var e=new Set(this.components.addressManager.getAddressesWithMetadata().filter((e=>{var{expires:t}=e;return t<Date.now()})).map((e=>{var{multiaddr:t}=e;return t.toString()})));for(var t of this.dialResults.keys())e.has(t)||(this.log.trace("remove results for %a",t),this.dialResults.delete(t))}verifyExternalAddresses(e){var t=this;return r((function*(){if(t.isStarted()){t.removeOutdatedMultiaddrResults();var n=(yield t.components.peerStore.get(e.remotePeer)).addresses.some((e=>{var{multiaddr:t}=e;return 6===t.toOptions().family})),i=t.getNetworkSegment(e.remoteAddr),o=t.getFirstUnverifiedMultiaddr(i,n);null!=o?t.hasConnectionCapacity()?o.queue.add(function(){var n=r((function*(r){yield t.askPeerToVerify(e,i,r)}));return function(e){return n.apply(this,arguments)}}(),{peerId:e.remotePeer,multiaddr:o.multiaddr}).catch((r=>{null==(null==o?void 0:o.result)&&t.log.error("error from %p verifying address %a - %e",e.remotePeer,null==o?void 0:o.multiaddr,r)})):null!=o.lastVerified?(t.log("automatically re-verifying %a because we are too close to the connection limit",o.multiaddr),t.confirmAddress(o)):t.log("skipping verifying %a because we are too close to the connection limit",o.multiaddr):t.log.trace("no unverified public addresses found for peer %p to verify, not requesting verification",e.remotePeer)}}))()}askPeerToVerify(e,t,n){var i=this;return r((function*(){var r=i.dialResults.get(n.multiaddr.toString());if(null!=r){var o=AbortSignal.timeout(i.timeout);i.log.trace("asking %p to verify multiaddr %s",e.remotePeer,n.multiaddr);var a=yield e.newStream(i.protocol,{signal:o});try{var s=xd(a).pb(xO),[,l]=yield Promise.all([s.write({type:xO.MessageType.DIAL,dial:{peer:{id:i.components.peerId.toMultihash().bytes,addrs:[n.multiaddr.bytes]}}},{signal:o}),s.read({signal:o})]);if(l.type!==xO.MessageType.DIAL_RESPONSE||null==l.dialResponse)return void i.log("invalid autonat response from %p - %j",e.remotePeer,l);var u=l.dialResponse.status;if(i.log.trace("autonat response from %p for %a is %s",e.remotePeer,n.multiaddr,u),u!==xO.ResponseStatus.OK&&u!==xO.ResponseStatus.E_DIAL_ERROR)return;if(null==(r=i.dialResults.get(n.multiaddr.toString())))return void i.log.trace("peer reported %a as %s but there is no result object",n.multiaddr,l.dialResponse.status);if(r.networkSegments.includes(t))return void i.log.trace("%a results included network segment %s",n.multiaddr,t);if(null!=r.result)return void i.log.trace("already resolved result for %a, ignoring response from",n.multiaddr,e.remotePeer);if(r.verifyingPeers.has(e.remotePeer))return void i.log.trace("peer %p has already verified %a, ignoring response",e.remotePeer,n.multiaddr);if(r.verifyingPeers.add(e.remotePeer),r.networkSegments.push(t),u===xO.ResponseStatus.OK){if(r.success++,"observed"!==r.type)return void i.confirmAddress(r)}else u===xO.ResponseStatus.E_DIAL_ERROR&&r.failure++;i.log("%a success %d failure %d",r.multiaddr,r.success,r.failure),4===r.success&&i.confirmAddress(r),8===r.failure&&i.unconfirmAddress(r)}finally{try{yield a.close({signal:o})}catch(e){a.abort(e)}}}else i.log("%a was verified while %p was queued",n.multiaddr,e.remotePeer)}))()}hasConnectionCapacity(){return this.components.connectionManager.getConnections().length/this.components.connectionManager.getMaxConnections()*100<this.connectionThreshold}confirmAddress(e){this.log("%s address %a is externally dialable",e.type,e.multiaddr),this.components.addressManager.confirmObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!0,e.queue.abort()}unconfirmAddress(e){this.log("%s address %a is not externally dialable",e.type,e.multiaddr),this.components.addressManager.removeObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!1,e.queue.abort()}getNetworkSegment(e){var t=e.toOptions();return 4===t.family?t.host.split(".")[0].padStart(3,"0"):t.host.split(":")[0].padStart(4,"0")}}function CO(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new AO(t,e)}var IO=iL("dns4"),TO=iL("dns6"),PO=iL("dnsaddr"),_O=nL(iL("dns"),PO,IO,TO),BO=nL(iL("ip4"),iL("ip6")),NO=nL(rL(BO,iL("tcp")),rL(_O,iL("tcp"))),DO=rL(BO,iL("udp")),RO=rL(DO,iL("utp")),OO=rL(DO,iL("quic")),LO=rL(DO,iL("quic-v1")),MO=nL(rL(NO,iL("ws")),rL(_O,iL("ws"))),UO=nL(rL(MO,iL("p2p")),MO),FO=nL(rL(NO,iL("wss")),rL(_O,iL("wss")),rL(NO,iL("tls"),iL("ws")),rL(_O,iL("tls"),iL("ws"))),zO=nL(rL(FO,iL("p2p")),FO),jO=nL(rL(NO,iL("http")),rL(BO,iL("http")),rL(_O,iL("http"))),VO=nL(rL(NO,iL("https")),rL(BO,iL("https")),rL(_O,iL("https"))),qO=rL(DO,iL("webrtc-direct"),iL("certhash")),HO=nL(rL(qO,iL("p2p")),qO),KO=rL(LO,iL("webtransport"),iL("certhash"),iL("certhash")),WO=nL(rL(KO,iL("p2p")),KO),GO=nL(rL(UO,iL("p2p-webrtc-star"),iL("p2p")),rL(zO,iL("p2p-webrtc-star"),iL("p2p")),rL(UO,iL("p2p-webrtc-star")),rL(zO,iL("p2p-webrtc-star")));nL(rL(UO,iL("p2p-websocket-star"),iL("p2p")),rL(zO,iL("p2p-websocket-star"),iL("p2p")),rL(UO,iL("p2p-websocket-star")),rL(zO,iL("p2p-websocket-star")));var QO=nL(rL(jO,iL("p2p-webrtc-direct"),iL("p2p")),rL(VO,iL("p2p-webrtc-direct"),iL("p2p")),rL(jO,iL("p2p-webrtc-direct")),rL(VO,iL("p2p-webrtc-direct"))),YO=nL(MO,FO,jO,VO,GO,QO,NO,RO,OO,_O,HO,WO);nL(rL(YO,iL("p2p-stardust"),iL("p2p")),rL(YO,iL("p2p-stardust")));var JO=nL(rL(YO,iL("p2p")),GO,QO,HO,WO,iL("p2p")),ZO=nL(rL(JO,iL("p2p-circuit"),JO),rL(JO,iL("p2p-circuit")),rL(iL("p2p-circuit"),JO),rL(YO,iL("p2p-circuit")),rL(iL("p2p-circuit"),YO),iL("p2p-circuit")),$O=()=>nL(rL(ZO,$O),ZO),XO=$O(),eL=nL(rL(XO,JO,XO),rL(JO,XO),rL(XO,JO),XO,JO);function tL(e){return function(t){var r;try{r=kr(t)}catch(e){return!1}var n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function rL(){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:tL(n),partialMatch:n}}function nL(){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:tL(n),partialMatch:n}}function iL(e){var t=e;return{toString:function(){return t},matches:function(e){var r;try{r=kr(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}}}nL(rL(XO,iL("webrtc"),iL("p2p")),rL(XO,iL("webrtc")),rL(YO,iL("webrtc"),iL("p2p")),rL(YO,iL("webrtc")),iL("webrtc"));class oL extends os{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{list:[]};if(null==n.list||0===n.list.length)throw new Error("Bootstrap requires a list of peer addresses");for(var i of(super(),e(this,"log",void 0),e(this,"timer",void 0),e(this,"list",void 0),e(this,"timeout",void 0),e(this,"components",void 0),e(this,"_init",void 0),e(this,ba,this),e(this,Symbol.toStringTag,"@libp2p/bootstrap"),e(this,ds,["@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(eL.matches(i)){var o=kr(i),a=o.getPeerId();if(null!=a){var s={id:Du(a),multiaddrs:[o]};this.list.push(s)}else this.log.error("Invalid bootstrap multiaddr without peer id")}else this.log.error("Invalid multiaddr");this._init=n}isStarted(){return Boolean(this.timer)}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout((()=>{this._discoverBootstrapPeers().catch((e=>{this.log.error(e)}))}),this.timeout))}_discoverBootstrapPeers(){var e=this;return r((function*(){if(null!=e.timer){var t,r=function*(t){var r,n;if(yield e.components.peerStore.merge(t.id,{tags:{[null!==(r=e._init.tagName)&&void 0!==r?r:"bootstrap"]:{value:null!==(n=e._init.tagValue)&&void 0!==n?n:50,ttl:e._init.tagTTL}},multiaddrs:t.multiaddrs}),null==e.timer)return{v:void 0};e.safeDispatchEvent("peer",{detail:t}),e.components.connectionManager.openConnection(t.id).catch((r=>{e.log.error("could not dial bootstrap peer %p",t.id,r)}))};for(var n of e.list)if(t=yield*r(n))return t.v}}))()}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}}e(oL,"tag","bootstrap");var aL=()=>{var e=new Error("Delay aborted");return e.name="AbortError",e},sL=new WeakMap;var lL,uL=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(aL());var l=null!=e?e:clearTimeout,u=()=>{l(n),o(aL())},c=new Promise(((e,l)=>{i=()=>{s&&s.removeEventListener("abort",u),e(a)},o=l,n=(null!=t?t:setTimeout)(i,r)}));return s&&s.addEventListener("abort",u,{once:!0}),sL.set(c,(()=>{l(n),n=null,i()})),c}}();function cL(e,t){return!Ah.matches(e)&&(null!=t.dialTransportForMultiaddr(e)&&(!!$d.matches(e)||!!ah.matches(e)&&!1===lD(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=()=>ql(t)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=Hl((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 Kl('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=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(lL||(lL={}));var dL=5e3,hL=3,vL=1,pL=1;class fL{constructor(t,r){var n,i,o,a;e(this,"started",void 0),e(this,"timeout",void 0),e(this,"retries",void 0),e(this,"maxInboundStreams",void 0),e(this,"maxOutboundStreams",void 0),e(this,"peerStore",void 0),e(this,"registrar",void 0),e(this,"connectionManager",void 0),e(this,"addressManager",void 0),e(this,"transportManager",void 0),e(this,"topologyId",void 0),e(this,"log",void 0),e(this,Symbol.toStringTag,"@libp2p/dcutr"),e(this,hs,["@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:dL,this.retries=null!==(i=r.retries)&&void 0!==i?i:hL,this.maxInboundStreams=null!==(o=r.maxInboundStreams)&&void 0!==o?o:vL,this.maxOutboundStreams=null!==(a=r.maxOutboundStreams)&&void 0!==a?a:pL}isStarted(){return this.started}start(){var e=this;return r((function*(){e.started||(e.topologyId=yield e.registrar.register(yL,{notifyOnLimitedConnection:!0,onConnect:(t,r)=>{Ah.exactMatch(r.remoteAddr)&&"inbound"===r.direction&&e.upgradeInbound(r).catch((t=>{e.log.error("error during outgoing DCUtR attempt",t)}))}}),yield e.registrar.handle(yL,(t=>{e.handleIncomingUpgrade(t.stream,t.connection).catch((r=>{e.log.error("error during incoming DCUtR attempt",r),t.stream.abort(r)}))}),{maxInboundStreams:e.maxInboundStreams,maxOutboundStreams:e.maxOutboundStreams,runOnLimitedConnection:!0}),e.started=!0)}))()}stop(){var e=this;return r((function*(){yield e.registrar.unhandle(yL),null!=e.topologyId&&e.registrar.unregister(e.topologyId),e.started=!1}))()}upgradeInbound(e){var t=this;return r((function*(){if(!(yield t.attemptUnilateralConnectionUpgrade(e)))for(var r,n=0;n<t.retries;n++){var i={signal:AbortSignal.timeout(t.timeout)};try{var o=xd(r=yield e.newStream([yL],{signal:i.signal,runOnLimitedConnection:!0}),{maxDataLength:4096}).pb(lL);t.log("B sending connect to %p",e.remotePeer);var a=Date.now();yield o.write({type:lL.Type.CONNECT,observedAddresses:t.addressManager.getAddresses().map((e=>e.bytes))},i),t.log("B receiving connect from %p",e.remotePeer);var s=yield o.read(i);if(s.type!==lL.Type.CONNECT)throw t.log("A sent wrong message type"),new Wa("DCUtR message type was incorrect");var l=t.getDialableMultiaddrs(s.observedAddresses);if(0===l.length)throw t.log("A did not have any dialable multiaddrs"),new Wa("DCUtR connect message had no multiaddrs");var u=Date.now()-a;t.log("A sending sync, rtt %dms",u),yield o.write({type:lL.Type.SYNC,observedAddresses:[]},i),t.log("A waiting for half RTT"),yield uL(u/2),t.log("B dialing",l);var c=yield t.connectionManager.openConnection(l,{signal:i.signal,priority:100,force:!0,initiator:!1});t.log("DCUtR to %p succeeded to address %a, closing relayed connection",e.remotePeer,c.remoteAddr),yield e.close(i);break}catch(e){var d;if(t.log.error("error while attempting DCUtR on attempt %d of %d",n+1,t.retries,e),null===(d=r)||void 0===d||d.abort(e),n===t.retries)throw e}finally{null!=r&&(yield r.close(i))}}}))()}attemptUnilateralConnectionUpgrade(e){var t=this;return r((function*(){var r=(yield t.peerStore.get(e.remotePeer)).addresses.map((t=>{var r=t.multiaddr;return null==r.getPeerId()?r.encapsulate("/p2p/".concat(e.remotePeer)):r})).filter((e=>cL(e,t.transportManager)));if(r.length>0){var n=AbortSignal.timeout(t.timeout);try{t.log("attempting unilateral connection upgrade to %a",r);var i=yield t.connectionManager.openConnection(r,{signal:n,force:!0});if(Ah.exactMatch(i.remoteAddr))throw new Error("Could not open a new, non-limited, connection");return t.log("unilateral connection upgrade to %p succeeded via %a, closing relayed connection",e.remotePeer,i.remoteAddr),yield e.close({signal:n}),!0}catch(n){t.log.error("unilateral connection upgrade to %p on addresses %a failed",e.remotePeer,r,n)}}else t.log("peer %p has no public addresses, not attempting unilateral connection upgrade",e.remotePeer);return!1}))()}handleIncomingUpgrade(e,t){var n=this;return r((function*(){var r={signal:AbortSignal.timeout(n.timeout)};try{var i=xd(e,{maxDataLength:4096}).pb(lL);n.log("A receiving connect");var o=yield i.read(r);if(o.type!==lL.Type.CONNECT)throw n.log("B sent wrong message type"),new Wa("DCUtR message type was incorrect");if(0===o.observedAddresses.length)throw n.log("B sent no multiaddrs"),new Wa("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 Wa("DCUtR connect message had no dialable multiaddrs");if(n.log("A sending connect"),yield i.write({type:lL.Type.CONNECT,observedAddresses:n.addressManager.getAddresses().map((e=>e.bytes))}),n.log("A receiving sync"),(yield i.read(r)).type!==lL.Type.SYNC)throw new Wa("DCUtR message type was incorrect");n.log("A dialing",a);var s=yield n.connectionManager.openConnection(a,{signal:r.signal,priority:100,force:!0});n.log("DCUtR to %p succeeded via %a, closing relayed connection",t.remotePeer,s.remoteAddr),yield t.close(r)}catch(r){n.log.error("incoming DCUtR from %p failed",t.remotePeer,r),e.abort(r)}finally{yield e.close(r)}}))()}getDialableMultiaddrs(e){var t=[];for(var r of e)if(null!=r&&0!==r.length)try{var n=kr(r);if(!cL(n,this.transportManager))continue;t.push(n)}catch(e){}return t}}var gL,yL="/libp2p/dcutr";function mL(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new fL(t,e)}var wL=null!==(gL=globalThis.CustomEvent)&&void 0!==gL?gL:Event;function bL(e){return SL.apply(this,arguments)}function SL(){return SL=l((function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(n,i){var o=null!==(n=t.concurrency)&&void 0!==n?n:1/0;o<1&&(o=1/0);var a,l=null!==(i=t.ordered)&&void 0!==i&&i,d=new EventTarget,h=[],v=Cc(),p=Cc(),f=!1,g=!1;function y(){var e;return l?null===(e=h[0])||void 0===e?void 0:e.done:Boolean(h.find((e=>e.done)))}function*m(){for(;h.length>0&&h[0].done;){var e=h[0];if(h.shift(),!e.ok)throw g=!0,v.resolve(),e.err;yield e.value,v.resolve()}}function*w(){for(;y();)for(var e=0;e<h.length;e++)if(h[e].done){var t=h[e];if(h.splice(e,1),e--,!t.ok)throw g=!0,v.resolve(),t.err;yield t.value,v.resolve()}}for(d.addEventListener("task-complete",(()=>{p.resolve()})),Promise.resolve().then(r((function*(){try{var t,r=!1,n=!1;try{for(var i,l=function*(){var e=i.value;if(h.length===o&&(v=Cc(),yield v.promise),g)return 1;var t={done:!1};h.push(t),e().then((e=>{t.done=!0,t.ok=!0,t.value=e,d.dispatchEvent(new wL("task-complete"))}),(e=>{t.done=!0,t.err=e,d.dispatchEvent(new wL("task-complete"))}))},u=s(e);(r=!(i=yield u.next()).done)&&!(yield*l());r=!1);}catch(e){n=!0,t=e}finally{try{r&&null!=u.return&&(yield u.return())}finally{if(n)throw t}}f=!0,d.dispatchEvent(new wL("task-complete"))}catch(e){a=e,d.dispatchEvent(new wL("task-complete"))}})));;){if(y()||(p=Cc(),yield u(p.promise)),null!=a)throw a;if(l?yield*c(s(m())):yield*c(s(w())),null!=a)throw a;if(f&&0===h.length)break}}()})),SL.apply(this,arguments)}var EL;!function(e){var t;e.codec=()=>(null==t&&(t=Hl((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 Kl('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 Kl('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=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(EL||(EL={}));var kL={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:8192,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnLimitedConnection:!0,concurrency:32};function xL(e,t,r,n,i){return AL.apply(this,arguments)}function AL(){return AL=r((function*(e,t,r,n,i){if(r("received identify from %p",n.remotePeer),null==i)throw new Wa("message was null or undefined");var o,a={};if(i.listenAddrs.length>0&&(a.addresses=i.listenAddrs.map((e=>({isCertified:!1,multiaddr:kr(e)})))),i.protocols.length>0&&(a.protocols=i.protocols),null!=i.publicKey){var s=mu(i.publicKey);if(!Ru(s).equals(n.remotePeer))throw new Wa("public key did not match remote PeerId");a.publicKey=s}if(null!=i.signedPeerRecord){r.trace("received signedPeerRecord from %p",n.remotePeer);var l,u=i.signedPeerRecord,c=yield hd.openAndCertify(u,yd.DOMAIN),d=yd.createFromProtobuf(c.payload),h=Mu(c.publicKey.toCID());if(!d.peerId.equals(h))throw new Wa("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(d.peerId))throw new Wa("signing key does not match remote PeerId");try{l=yield e.get(d.peerId)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=l&&(a.metadata=l.metadata,null!=l.peerRecordEnvelope)){var v=yield hd.createFromProtobuf(l.peerRecordEnvelope),p=yd.createFromProtobuf(v.payload);p.seqNumber>=d.seqNumber&&(r("sequence number was lower or equal to existing sequence number - stored: %d received: %d",p.seqNumber,d.seqNumber),d=p,u=l.peerRecordEnvelope)}a.peerRecordEnvelope=u,a.addresses=d.multiaddrs.map((e=>({isCertified:!0,multiaddr:e}))),o={seq:d.seqNumber,addresses:d.multiaddrs}}else r("%p did not send a signed peer record",n.remotePeer);if(r.trace("patching %p with",n.remotePeer,a),yield e.patch(n.remotePeer,a),null!=i.agentVersion||null!=i.protocolVersion){var f={};null!=i.agentVersion&&(f.AgentVersion=Et(i.agentVersion)),null!=i.protocolVersion&&(f.ProtocolVersion=Et(i.protocolVersion)),r.trace("merging %p metadata",n.remotePeer,f),yield e.merge(n.remotePeer,{metadata:f})}var g={peerId:n.remotePeer,protocolVersion:i.protocolVersion,agentVersion:i.agentVersion,publicKey:i.publicKey,listenAddrs:i.listenAddrs.map((e=>kr(e))),observedAddr:null==i.observedAddr?void 0:kr(i.observedAddr),protocols:i.protocols,signedPeerRecord:o,connection:n};return t.safeDispatchEvent("peer:identify",{detail:g}),g})),AL.apply(this,arguments)}class CL{constructor(t,r){var n,i,o,a,s,l,u,c,d;e(this,"host",void 0),e(this,"protocol",void 0),e(this,"started",void 0),e(this,"timeout",void 0),e(this,"peerId",void 0),e(this,"privateKey",void 0),e(this,"peerStore",void 0),e(this,"registrar",void 0),e(this,"addressManager",void 0),e(this,"maxInboundStreams",void 0),e(this,"maxOutboundStreams",void 0),e(this,"maxMessageSize",void 0),e(this,"maxObservedAddresses",void 0),e(this,"events",void 0),e(this,"runOnLimitedConnection",void 0),e(this,"log",void 0),this.protocol=r.protocol,this.started=!1,this.peerId=t.peerId,this.privateKey=t.privateKey,this.peerStore=t.peerStore,this.registrar=t.registrar,this.addressManager=t.addressManager,this.events=t.events,this.log=r.log,this.timeout=null!==(n=r.timeout)&&void 0!==n?n:kL.timeout,this.maxInboundStreams=null!==(i=r.maxInboundStreams)&&void 0!==i?i:kL.maxInboundStreams,this.maxOutboundStreams=null!==(o=r.maxOutboundStreams)&&void 0!==o?o:kL.maxOutboundStreams,this.maxMessageSize=null!==(a=r.maxMessageSize)&&void 0!==a?a:kL.maxMessageSize,this.maxObservedAddresses=null!==(s=r.maxObservedAddresses)&&void 0!==s?s:kL.maxObservedAddresses,this.runOnLimitedConnection=null!==(l=r.runOnLimitedConnection)&&void 0!==l?l:kL.runOnLimitedConnection,this.host={protocolVersion:"".concat(null!==(u=r.protocolPrefix)&&void 0!==u?u:kL.protocolPrefix,"/").concat("0.1.0"),agentVersion:(c=t.nodeInfo,d=r.agentVersion,null!=d?d:c.userAgent)}}isStarted(){return this.started}start(){var e=this;return r((function*(){e.started||(yield e.peerStore.merge(e.peerId,{metadata:{AgentVersion:Et(e.host.agentVersion),ProtocolVersion:Et(e.host.protocolVersion)}}),yield e.registrar.handle(e.protocol,(t=>{e.handleProtocol(t).catch((t=>{e.log.error(t)}))}),{maxInboundStreams:e.maxInboundStreams,maxOutboundStreams:e.maxOutboundStreams,runOnLimitedConnection:e.runOnLimitedConnection}),e.started=!0)}))()}stop(){var e=this;return r((function*(){yield e.registrar.unhandle(e.protocol),e.started=!1}))()}}class IL extends CL{constructor(r){var n,i,o,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(r,t(t({},a),{},{protocol:"/".concat(null!==(n=a.protocolPrefix)&&void 0!==n?n:kL.protocolPrefix,"/").concat("id/push","/").concat("1.0.0"),log:r.logger.forComponent("libp2p:identify-push")})),e(this,"connectionManager",void 0),e(this,"concurrency",void 0),e(this,ds,["@libp2p/identify-push"]),this.connectionManager=r.connectionManager,this.concurrency=null!==(i=a.concurrency)&&void 0!==i?i:kL.concurrency,(null!==(o=a.runOnSelfUpdate)&&void 0!==o?o:kL.runOnSelfUpdate)&&r.events.addEventListener("self:peer:update",(e=>{this.push().catch((e=>{this.log.error(e)}))}))}push(){var e=this;return r((function*(){var t,n;if(e.isStarted()){var i=e.addressManager.getAddresses().map((e=>e.decapsulateCode(xr("p2p").code))),o=new yd({peerId:e.peerId,multiaddrs:i}),a=yield hd.seal(o,e.privateKey),s=e.registrar.getProtocols(),c=yield e.peerStore.get(e.peerId),d=gt(null!==(t=c.metadata.get("AgentVersion"))&&void 0!==t?t:Et(e.host.agentVersion)),h=gt(null!==(n=c.metadata.get("ProtocolVersion"))&&void 0!==n?n:Et(e.host.protocolVersion)),v=e;yield uc(bL(function(){return p.apply(this,arguments)}(),{concurrency:e.concurrency}))}function p(){return(p=l((function*(){var e=function*(e){if(!(yield u(v.peerStore.get(e.remotePeer))).protocols.includes(v.protocol))return 1;yield r((function*(){var t,r=AbortSignal.timeout(v.timeout);try{var n=xd(t=yield e.newStream(v.protocol,{signal:r,runOnLimitedConnection:v.runOnLimitedConnection}),{maxDataLength:v.maxMessageSize}).pb(EL);yield n.write({listenAddrs:i.map((e=>e.bytes)),signedPeerRecord:a.marshal(),protocols:s,agentVersion:d,protocolVersion:h},{signal:r}),yield t.close({signal:r})}catch(e){var o;v.log.error("could not push identify update to peer",e),null===(o=t)||void 0===o||o.abort(e)}}))};for(var t of v.connectionManager.getConnections())yield*e(t)}))).apply(this,arguments)}}))()}handleProtocol(e){var t=this;return r((function*(){var{connection:r,stream:n}=e;try{if(t.peerId.equals(r.remotePeer))throw new Error("received push from ourselves?");var i={signal:AbortSignal.timeout(t.timeout)},o=xd(n,{maxDataLength:t.maxMessageSize}).pb(EL),a=yield o.read(i);yield n.close(i),yield xL(t.peerStore,t.events,t.log,r,a)}catch(e){return t.log.error("received invalid message",e),void n.abort(e)}t.log.trace("handled push from %p",r.remotePeer)}))()}}class TL extends CL{constructor(r){var n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(r,t(t({},o),{},{protocol:"/".concat(null!==(n=o.protocolPrefix)&&void 0!==n?n:kL.protocolPrefix,"/").concat("id","/").concat("1.0.0"),log:r.logger.forComponent("libp2p:identify")})),e(this,ds,["@libp2p/identify"]),(null!==(i=o.runOnConnectionOpen)&&void 0!==i?i:kL.runOnConnectionOpen)&&r.events.addEventListener("connection:open",(e=>{var t=e.detail;this.identify(t).catch((e=>{e.name!==Ka.name&&this.log.error("error during identify trigged by connection:open",e)}))}))}_identify(e){var n=arguments,i=this;return r((function*(){var r,o=n.length>1&&void 0!==n[1]?n[1]:{};if(null==o.signal){var a=AbortSignal.timeout(i.timeout);o=t(t({},o),{},{signal:a})}try{var s=xd(r=yield e.newStream(i.protocol,t(t({},o),{},{runOnLimitedConnection:i.runOnLimitedConnection})),{maxDataLength:i.maxMessageSize}).pb(EL),l=yield s.read(o);return yield r.close(o),l}catch(e){var u;throw null===(u=r)||void 0===u||u.abort(e),e}}))()}identify(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{},i=yield n._identify(e,r),{publicKey:o,protocols:a,observedAddr:s}=i;if(null==o)throw new Wa("public key was missing from identify message");var l=Mu(mu(o).toCID());if(!e.remotePeer.equals(l))throw new Wa("identified peer does not match the expected peer");if(n.peerId.equals(l))throw new Wa("identified peer is our own peer id?");return n.maybeAddObservedAddress(s),n.log("identify completed for peer %p and protocols %o",l,a),xL(n.peerStore,n.events,n.log,e,i)}))()}maybeAddObservedAddress(e){var t=function(e){if(null!=e&&e.length>0)try{return kr(e)}catch(e){}}(e);null!=t&&(this.log.trace("our observed address was %a",t),kO(t)?this.log.trace("our observed address was private"):41!==t.stringTuples()[0][0]||SO(t)?uh.exactMatch(t)||(this.log.trace("storing the observed address"),this.addressManager.addObservedAddr(t)):this.log.trace("our observed address was IPv6 but not a global unicast address"))}handleProtocol(e){var t=this;return r((function*(){var{connection:r,stream:n}=e,i=AbortSignal.timeout(t.timeout);try{var o=yield t.peerStore.get(t.peerId),a=t.addressManager.getAddresses().map((e=>e.decapsulateCode(xr("p2p").code))),s=o.peerRecordEnvelope;if(a.length>0&&null==s){var l=new yd({peerId:t.peerId,multiaddrs:a});s=(yield hd.seal(l,t.privateKey)).marshal().subarray()}var u=r.remoteAddr.bytes;nh.matches(r.remoteAddr)||(u=void 0);var c=xd(n).pb(EL);yield c.write({protocolVersion:t.host.protocolVersion,agentVersion:t.host.agentVersion,publicKey:Su(t.privateKey.publicKey),listenAddrs:a.map((e=>e.bytes)),signedPeerRecord:s,observedAddr:u,protocols:o.protocols},{signal:i}),yield n.close({signal:i})}catch(e){t.log.error("could not respond to identify request",e),n.abort(e)}}))()}}function PL(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new TL(t,e)}function _L(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new IL(t,e)}var BL,NL,DL,RL,OL,LL,ML,UL,FL=36e5,zL=36*FL,jL=48*FL,VL=FL,qL="".concat(Aa,"-kad-dht");function HL(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=Hl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.key&&e.key.byteLength>0&&(t.uint32(10),t.bytes(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),null!=e.timeReceived&&""!==e.timeReceived&&(t.uint32(42),t.string(e.timeReceived)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={key:ct(0),value:ct(0),timeReceived:""},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.key=e.bytes();break;case 2:r.value=e.bytes();break;case 5:r.timeReceived=e.string();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(BL||(BL={}));class KL{constructor(t,r,n){if(e(this,"key",void 0),e(this,"value",void 0),e(this,"timeReceived",void 0),!(t instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(r instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=t,this.value=r,this.timeReceived=n}serialize(){return BL.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:HL(this.timeReceived)}}static deserialize(e){var t=BL.decode(e);return new KL(t.key,t.value,new Date(t.timeReceived))}static fromDeserialized(e){var t=function(e){var t=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),r=String(e).trim().match(t);if(null==r)throw new Error("Invalid format");var n=parseInt(r[1],10),i=parseInt(r[2],10)-1,o=parseInt(r[3],10),a=parseInt(r[4],10),s=parseInt(r[5],10),l=parseInt(r[6],10),u=parseInt(r[7].slice(0,-6),10);return new Date(Date.UTC(n,i,o,a,s,l,u))}(e.timeReceived);if(null==e.key)throw new Error("key missing from deserialized object");if(null==e.value)throw new Error("value missing from deserialized object");return new KL(e.key,e.value,t)}}class WL extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Query error"),this.name="QueryError"}}class GL extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Query aborted"),this.name="QueryAbortedError"}}class QL extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid record"),this.name="InvalidRecordError"}}class YL extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No selector function configured for prefix"),this.name="MissingSelectorError"}}function JL(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t(t({},e),{},{name:"SEND_QUERY",type:0,messageName:e.type,messageType:e.type});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:send-query",{detail:i})),i}function ZL(e){var r,n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=t(t({},e),{},{name:"PEER_RESPONSE",type:1,messageName:e.messageType,closer:null!==(r=e.closer)&&void 0!==r?r:[],providers:null!==(n=e.providers)&&void 0!==n?n:[]});return null===(i=o.onProgress)||void 0===i||i.call(o,new CustomEvent("kad-dht:query:peer-response",{detail:a})),a}function $L(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t(t({},e),{},{name:"FINAL_PEER",type:2});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:final-peer",{detail:i})),i}function XL(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t(t({},e),{},{name:"QUERY_ERROR",type:3});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:query-error",{detail:i})),i}function eM(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t(t({},e),{},{name:"PROVIDER",type:4});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:provider",{detail:i})),i}function tM(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t(t({},e),{},{name:"VALUE",type:5});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:value",{detail:i})),i}function rM(e){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t(t({},e),{},{name:"DIAL_PEER",type:7});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:dial-peer",{detail:i})),i}!function(e){var t;e.codec=()=>(null==t&&(t=Hl((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=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(NL||(NL={})),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"}(DL||(DL={})),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"}(RL||(RL={})),function(e){e.codec=()=>ql(RL)}(DL||(DL={})),function(e){e.NOT_CONNECTED="NOT_CONNECTED",e.CONNECTED="CONNECTED",e.CAN_CONNECT="CAN_CONNECT",e.CANNOT_CONNECT="CANNOT_CONNECT"}(OL||(OL={})),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"}(LL||(LL={})),function(e){e.codec=()=>ql(LL)}(OL||(OL={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((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),OL.codec().encode(e.connection,t)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={id:ct(0),multiaddrs:[]},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.id=e.bytes();break;case 2:var a;if(null!=(null===(a=r.limits)||void 0===a?void 0:a.multiaddrs)&&n.multiaddrs.length===r.limits.multiaddrs)throw new Kl('Decode error - map field "multiaddrs" had too many elements');n.multiaddrs.push(e.bytes());break;case 3:n.connection=OL.codec().decode(e);break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(ML||(ML={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.type&&0!==RL[e.type]&&(t.uint32(8),DL.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),ML.codec().encode(n,t);if(null!=e.providers)for(var i of e.providers)t.uint32(74),ML.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:DL.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=DL.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 Kl('Decode error - map field "closer" had too many elements');n.closer.push(ML.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.closer$}));break;case 9:var l,u;if(null!=(null===(l=r.limits)||void 0===l?void 0:l.providers)&&n.providers.length===r.limits.providers)throw new Kl('Decode error - map field "providers" had too many elements');n.providers.push(ML.codec().decode(e,e.uint32(),{limits:null===(u=r.limits)||void 0===u?void 0:u.providers$}));break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(UL||(UL={}));var nM={pk:function(e,t){return 0}};function iM(e,t){return oM.apply(this,arguments)}function oM(){return oM=r((function*(e,t){var r=t.key,n=gt(r).split("/");if(!(n.length<3)){var i=e[n[1].toString()];if(null==i)throw new _a('No validator available for key type "'.concat(n[1],'"'));yield i(r,t.value)}})),oM.apply(this,arguments)}var aM=function(){var e=r((function*(e,t){if(!(e instanceof Uint8Array))throw new _a('"key" must be a Uint8Array');if(e.byteLength<5)throw new _a("Invalid public key record");if("/pk/"!==gt(e.subarray(0,4)))throw new _a("key was not prefixed with /pk/");var r=mu(t);if(!St(e.slice(4),r.toMultihash().bytes))throw new _a("public key does not match passed in key")}));return function(t,r){return e.apply(this,arguments)}}(),sM={pk:aM},lM=Et("/pk/");function uM(e){return t(t({},e),{},{multiaddrs:e.multiaddrs.filter((e=>{var[[t,r]]=e.stringTuples();if(53===t||54===t||55===t)return"localhost"!==r;if(4!==t&&6!==t)return!1;if(null==r)return!1;var n=lD(r);return null==n||!n}))})}function cM(e){return dM.apply(this,arguments)}function dM(){return dM=r((function*(e){return(yield $e.digest(e)).digest})),dM.apply(this,arguments)}function hM(e){return vM.apply(this,arguments)}function vM(){return vM=r((function*(e){return cM(e.toMultihash().bytes)})),vM.apply(this,arguments)}function pM(e,t){return new lc("".concat(e,"/").concat(gt(t,"base32")),!1)}function fM(e,t){var r=new Date;return new KL(e,t,r).serialize()}function gM(e){var t=e.toString().split("/"),r=t.pop(),n=t.pop();if(null==r||null==n)throw new Error("incorrectly formatted provider entry key in datastore: ".concat(e.toString()));return{cid:it.createV1(Se,He(Et(n,"base32"))),peerId:Du(r)}}function yM(e,t,r){var n=[e,"string"==typeof t?t:gt(t.multihash.bytes,"base32")];return null!=r&&n.push(r.toString()),new lc(n.join("/"))}function mM(e){return new Date(Lt(e))}function wM(e,t,r){return l((function*(){var n,i,o=null===(n=t.queryTime)||void 0===n?void 0:n.timer(r),a=null===(i=t.errorTime)||void 0===i?void 0:i.timer(r),l=!1;try{var d;null===(d=t.queries)||void 0===d||d.increment({[r]:!0}),yield*c(s(e(...arguments)),u)}catch(e){var h;throw l=!0,null==a||a(),null===(h=t.errors)||void 0===h||h.increment({[r]:!0}),e}finally{var v;null===(v=t.queries)||void 0===v||v.decrement({[r]:!0}),l||null==o||o()}}))}function bM(e,t,n){return r((function*(){var r,i,o=null==t||null===(r=t.queryTime)||void 0===r?void 0:r.timer(n),a=null==t||null===(i=t.errorTime)||void 0===i?void 0:i.timer(n),s=!1;try{var l;return null===(l=t.queries)||void 0===l||l.increment({[n]:!0}),yield e(...arguments)}catch(e){var u;throw s=!0,null==a||a(),null===(u=t.errors)||void 0===u||u.increment({[n]:!0}),e}finally{var c;null===(c=t.queries)||void 0===c||c.decrement({[n]:!0}),s||null==o||o()}}))}class SM{constructor(t,r){var n,i,o,a;e(this,"log",void 0),e(this,"components",void 0),e(this,"validators",void 0),e(this,"selectors",void 0),e(this,"peerRouting",void 0),e(this,"queryManager",void 0),e(this,"network",void 0),e(this,"datastorePrefix",void 0);var{validators:s,selectors:l,peerRouting:u,queryManager:c,network:d,logPrefix:h}=r;this.components=t,this.log=t.logger.forComponent("".concat(h,":content-fetching")),this.datastorePrefix="".concat(r.datastorePrefix,"/record"),this.validators=s,this.selectors=l,this.peerRouting=u,this.queryManager=c,this.network=d,this.get=null!==(n=null===(i=t.metrics)||void 0===i?void 0:i.traceFunction("libp2p.kadDHT.get",this.get.bind(this),{optionsIndex:1}))&&void 0!==n?n:this.get,this.put=null!==(o=null===(a=t.metrics)||void 0===a?void 0:a.traceFunction("libp2p.kadDHT.put",this.put.bind(this),{optionsIndex:2}))&&void 0!==o?o:this.put}getLocal(e){var t=this;return r((function*(){t.log("getLocal %b",e);var r=pM(t.datastorePrefix,e);t.log("fetching record for key %k",r);var n=yield t.components.datastore.get(r);t.log("found %k in local datastore",r);var i=KL.deserialize(n);return yield iM(t.validators,i),i}))()}sendCorrectionRecord(e,t,r){var n=this;return l((function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return function*(){n.log("sendCorrection for %b",e);var o=fM(e,r);for(var{value:a,from:l}of t)if(St(a,r))n.log("record was ok");else if(n.components.peerId.equals(l))try{var c=pM(n.datastorePrefix,e);n.log("Storing corrected record for key ".concat(c.toString())),yield u(n.components.datastore.put(c,o.subarray()))}catch(e){n.log.error("Failed error correcting self",e)}else{var d,h=!1,v={type:DL.PUT_VALUE,key:e,record:o},p=!1,f=!1;try{for(var g,y=s(n.network.sendRequest(l,v,i));p=!(g=yield u(y.next())).done;p=!1){var m=g.value;"PEER_RESPONSE"===m.name&&null!=m.record&&St(m.record.value,KL.deserialize(o).value)&&(h=!0),yield m}}catch(e){f=!0,d=e}finally{try{p&&null!=y.return&&(yield u(y.return()))}finally{if(f)throw d}}h||(yield XL({from:l,error:new WL("Value not put correctly")},i)),n.log.error("Failed error correcting entry")}}()})).apply(this,arguments)}put(e,n){var i=this;return l((function(e,n){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){i.log("put key %b value %b",e,n);var a=fM(e,n),d=pM(i.datastorePrefix,e);i.log("storing record for key ".concat(d.toString())),yield u(i.components.datastore.put(d,a.subarray())),yield*c(s(Fc(i.peerRouting.getClosestPeers(e,t(t({},o),{},{signal:o.signal})),(t=>Ac(t,(t=>r((function*(){if("FINAL_PEER"!==t.name)return[t];var r=[],n={type:DL.PUT_VALUE,key:e,record:a};i.log("send put to %p",t.peer.id);var l,u=!1,c=!1;try{for(var d,h=s(i.network.sendRequest(t.peer.id,n,o));u=!(d=yield h.next()).done;u=!1){var v=d.value;(r.push(v),"PEER_RESPONSE"===v.name)&&(null!=v.record&&St(v.record.value,KL.deserialize(a).value)||r.push(XL({from:t.peer.id,error:new WL("Value not put correctly")},o)))}}catch(e){c=!0,l=e}finally{try{u&&null!=h.return&&(yield h.return())}finally{if(c)throw l}}return r}))))),(e=>bL(e,{ordered:!1,concurrency:3})),function(){var e=l((function*(e){var t,r=!1,n=!1;try{for(var i,o=s(e);r=!(i=yield u(o.next())).done;r=!1){var a=i.value;yield*c(s(a),u)}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw t}}}));return function(t){return e.apply(this,arguments)}}())))}()})).apply(this,arguments)}get(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){t.log("get %b",e);var n,i=[],o=!1,a=!1;try{for(var l,d=s(t.getMany(e,r));o=!(l=yield u(d.next())).done;o=!1){var h=l.value;"VALUE"===h.name&&i.push(h),yield h}}catch(e){a=!0,n=e}finally{try{o&&null!=d.return&&(yield u(d.return()))}finally{if(a)throw n}}if(0!==i.length){var v=i.map((e=>e.value)),p=0;try{p=function(e,t,r){if(0===r.length)throw new _a("No records given");var n=gt(t).split("/");if(n.length<3)throw new _a("Record key does not have a selector function");var i=e[n[1].toString()];if(null==i)throw new YL('No selector function configured for key type "'.concat(n[1],'"'));return 1===r.length?0:i(t,r)}(t.selectors,e,v)}catch(e){if("InvalidParametersError"!==e.name)throw e}var f=v[p];if(t.log("GetValue %b %b",e,f),null==f)throw new za("Best value was not found");yield*c(s(t.sendCorrectionRecord(e,i,f,r))),yield i[p]}}()})).apply(this,arguments)}getMany(e){var r=this;return l((function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){r.log("getMany values for %b",e);try{var i=yield u(r.getLocal(e));yield tM({value:i.value,from:r.components.peerId},n)}catch(t){r.log("error getting local value for %b",e,t)}var o=r,a=function(){var r=l((function(r){var{peer:i,signal:a}=r;return function*(){var r,l=!1,c=!1;try{for(var d,h=s(o.peerRouting.getValueOrPeers(i,e,t(t({},n),{},{signal:a})));l=!(d=yield u(h.next())).done;l=!1){var v=d.value;yield v,"PEER_RESPONSE"===v.name&&null!=v.record&&(yield tM({from:i,value:v.record.value},n))}}catch(e){c=!0,r=e}finally{try{l&&null!=h.return&&(yield u(h.return()))}finally{if(c)throw r}}}()}));return function(e){return r.apply(this,arguments)}}();yield*c(s(r.queryManager.run(e,a,n)))}()})).apply(this,arguments)}}function EM(e){var t;if(null==e.id)throw new Error("Invalid peer in message");return{id:Lu(He(e.id)),multiaddrs:(null!==(t=e.multiaddrs)&&void 0!==t?t:[]).map((e=>kr(e)))}}class kM{constructor(t,r){var n,i,o,a;e(this,"log",void 0),e(this,"components",void 0),e(this,"network",void 0),e(this,"peerRouting",void 0),e(this,"queryManager",void 0),e(this,"routingTable",void 0),e(this,"providers",void 0);var{network:s,peerRouting:l,queryManager:u,routingTable:c,providers:d,logPrefix:h}=r;this.components=t,this.log=t.logger.forComponent("".concat(h,":content-routing")),this.network=s,this.peerRouting=l,this.queryManager=u,this.routingTable=c,this.providers=d,this.findProviders=null!==(n=null===(i=t.metrics)||void 0===i?void 0:i.traceFunction("libp2p.kadDHT.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromYieldedValue:(e,t)=>{var r;"PROVIDER"===e.name&&(null!==(r=t.providers)&&void 0!==r||(t.providers=[]),t.providers.push(...e.providers.map((e=>e.id.toString()))));return t}}))&&void 0!==n?n:this.findProviders,this.provide=null!==(o=null===(a=t.metrics)||void 0===a?void 0:a.traceFunction("libp2p.kadDHT.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromYieldedValue:(e,t)=>{var r;"PEER_RESPONSE"===e.name&&"ADD_PROVIDER"===e.messageName&&(null!==(r=t.providers)&&void 0!==r||(t.providers=[]),t.providers.push(e.from.toString()));return t}}))&&void 0!==o?o:this.provide}provide(e,t){var n=this;return l((function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){n.log("provide %s",e);var o=e.multihash.bytes;yield u(n.providers.addProvider(e,n.components.peerId));var a,d,h,v,p={type:DL.ADD_PROVIDER,key:o,providers:[(a={id:n.components.peerId,multiaddrs:t},v={id:a.id.toMultihash().bytes,multiaddrs:(null!==(h=a.multiaddrs)&&void 0!==h?h:[]).map((e=>e.bytes)),connection:d},v)]},f=0;yield*c(s(Fc(n.peerRouting.getClosestPeers(o,i),(t=>Ac(t,(t=>(t=>r((function*(){if("FINAL_PEER"!==t.name)return[t];var r=[];n.log("putProvider %s to %p",e,t.peer.id);try{n.log("sending provider record for %s to %p",e,t.peer.id);var o,a=!1,l=!1;try{for(var u,c=s(n.network.sendMessage(t.peer.id,p,i));a=!(u=yield c.next()).done;a=!1){var d=u.value;"PEER_RESPONSE"===d.name&&(n.log("sent provider record for %s to %p",e,t.peer.id),f++),r.push(d)}}catch(e){l=!0,o=e}finally{try{a&&null!=c.return&&(yield c.return())}finally{if(l)throw o}}}catch(e){n.log.error("error sending provide record to peer %p",t.peer.id,e),r.push(XL({from:t.peer.id,error:e},i))}return r})))(t)))),(e=>bL(e,{ordered:!1,concurrency:3})),function(){var e=l((function*(e){var t,r=!1,n=!1;try{for(var i,o=s(e);r=!(i=yield u(o.next())).done;r=!1){var a=i.value;yield*c(s(a),u)}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw t}}}));return function(t){return e.apply(this,arguments)}}()))),n.log("sent provider records to %d peers",f)}()})).apply(this,arguments)}findProviders(e,r){var n=this;return l((function*(){var i=n.routingTable.kBucketSize,o=0,a=e.multihash.bytes,d=n;n.log("findProviders %c",e);var h=yield u(n.providers.getProviders(e));if(h.length>0){var v=[];for(var p of h.slice(0,i))try{var f=yield u(n.components.peerStore.get(p));v.push({id:p,multiaddrs:f.addresses.map((e=>{var{multiaddr:t}=e;return t}))})}catch(e){if("NotFoundError"!==e.name)throw e;n.log("no peer store entry for %p",p)}if(yield ZL({from:n.components.peerId,messageType:DL.GET_PROVIDERS,providers:v},r),yield eM({from:n.components.peerId,providers:v},r),(o+=v.length)>=i)return}var g,y=function(){var e=l((function(e){var{peer:n,signal:i}=e;return function*(){var e={type:DL.GET_PROVIDERS,key:a};yield*c(s(d.network.sendRequest(n,e,t(t({},r),{},{signal:i}))))}()}));return function(t){return e.apply(this,arguments)}}(),m=new zh(h),w=!1,b=!1;try{for(var S,E=s(n.queryManager.run(a,y,r));w=!(S=yield u(E.next())).done;w=!1){var k=S.value;if(yield k,"PEER_RESPONSE"===k.name){n.log("Found %d provider entries for %c and %d closer peers",k.providers.length,e,k.closer.length);var x=[];for(var A of k.providers)m.has(A.id)||(m.add(A.id),x.push(A));if(x.length>0&&(yield eM({from:k.from,providers:x},r),(o+=x.length)>=i))return}}}catch(e){b=!0,g=e}finally{try{w&&null!=E.return&&(yield u(E.return()))}finally{if(b)throw g}}}))()}}class xM{constructor(t){e(this,"movingAverage",void 0),e(this,"variance",void 0),e(this,"deviation",void 0),e(this,"forecast",void 0),e(this,"timeSpan",void 0),e(this,"previousTime",void 0),this.timeSpan=t,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();if(null!=this.previousTime){var r=this.alpha(t,this.previousTime),n=e-this.movingAverage,i=r*n;this.movingAverage=r*e+(1-r)*this.movingAverage,this.variance=(1-r)*(this.variance+n*i),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+r*n}else this.movingAverage=e;this.previousTime=t}}class AM{constructor(){var t,r,n,i,o,a,s,l=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e(this,"success",void 0),e(this,"failure",void 0),e(this,"next",void 0),e(this,"metric",void 0),e(this,"timeoutMultiplier",void 0),e(this,"failureMultiplier",void 0),e(this,"minTimeout",void 0),this.success=new xM(null!==(t=l.interval)&&void 0!==t?t:5e3),this.failure=new xM(null!==(r=l.interval)&&void 0!==r?r:5e3),this.next=new xM(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=Ph([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 CM{constructor(){e(this,"readNext",void 0),e(this,"haveNext",void 0),e(this,"ended",void 0),e(this,"nextResult",void 0),this.ended=!1,this.readNext=Cc(),this.haveNext=Cc()}[Symbol.asyncIterator](){return this}next(){var e=this;return r((function*(){if(null==e.nextResult&&(yield e.haveNext.promise),null==e.nextResult)throw new Error("HaveNext promise resolved but nextResult was undefined");var t=e.nextResult;return e.nextResult=void 0,e.readNext.resolve(),e.readNext=Cc(),t}))()}throw(e){var t=this;return r((function*(){return t.ended=!0,null!=e&&(t.haveNext.promise.catch((()=>{})),t.haveNext.reject(e)),{done:!0,value:void 0}}))()}return(){var e=this;return r((function*(){var t={done:!0,value:void 0};return e.ended=!0,e.nextResult=t,e.haveNext.resolve(),t}))()}push(e,t){var n=this;return r((function*(){yield n._push(e,t)}))()}end(e,t){var n=this;return r((function*(){null!=e?yield n.throw(e):yield n._push(void 0,t)}))()}_push(e,t){var n=this;return r((function*(){if(null!=e&&n.ended)throw new Error("Cannot push value onto an ended pushable");for(;null!=n.nextResult;)yield n.readNext.promise;null!=e?n.nextResult={done:!1,value:e}:(n.ended=!0,n.nextResult={done:!0,value:void 0}),n.haveNext.resolve(),n.haveNext=Cc(),yield Nc(n.readNext.promise,null==t?void 0:t.signal,t)}))()}}class IM extends Error{constructor(){super(...arguments),e(this,"name","UnexpectedEOFError"),e(this,"code","ERR_UNEXPECTED_EOF")}}class TM extends Error{constructor(t,r){super(t),e(this,"code",void 0),this.code=r}}let PM=class extends TM{constructor(t){super(t,"ABORT_ERR"),e(this,"type",void 0),this.type="aborted",this.name="AbortError"}};function _M(e,t){var n=new CM;e.sink(n).catch(function(){var e=r((function*(e){yield n.end(e)}));return function(t){return e.apply(this,arguments)}}()),e.sink=function(){var e=r((function*(e){var t,r=!1,i=!1;try{for(var o,a=s(e);r=!(o=yield a.next()).done;r=!1){var l=o.value;yield n.push(l)}}catch(e){i=!0,t=e}finally{try{r&&null!=a.return&&(yield a.return())}finally{if(i)throw t}}yield n.end()}));return function(t){return e.apply(this,arguments)}}();var i=e.source;null!=e.source[Symbol.iterator]?i=e.source[Symbol.iterator]():null!=e.source[Symbol.asyncIterator]&&(i=e.source[Symbol.asyncIterator]());var o,a=new gs,u={read:function(){var e=r((function*(e,t){var r,n;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted();var o=new Promise(((e,r)=>{var i;n=()=>{r(new PM("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 gs:l}for(;a.byteLength<e;){var{value:u,done:c}=yield Promise.race([i.next(),o]);if(!0===c)throw new IM("unexpected end of input");a.append(u)}var d=a.sublist(0,e);return a.consume(e),d}finally{var h;if(null!=n)null==t||null===(h=t.signal)||void 0===h||h.removeEventListener("abort",n)}}));return function(t,r){return e.apply(this,arguments)}}(),write:(o=r((function*(e,t){var r;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),e instanceof Uint8Array?yield n.push(e,t):yield n.push(e.subarray(),t)})),function(e,t){return o.apply(this,arguments)}),unwrap:()=>{if(a.byteLength>0){var r=e.source;e.source=l((function*(){!1===(null==t?void 0:t.yieldBytes)?yield a:yield*c(s(a)),yield*c(s(r))}))()}return e}};return u}class BM extends Error{constructor(){super(...arguments),e(this,"name","InvalidMessageLengthError"),e(this,"code","ERR_INVALID_MSG_LENGTH")}}class NM extends Error{constructor(){super(...arguments),e(this,"name","InvalidDataLengthError"),e(this,"code","ERR_MSG_DATA_TOO_LONG")}}class DM extends Error{constructor(){super(...arguments),e(this,"name","InvalidDataLengthLengthError"),e(this,"code","ERR_MSG_LENGTH_TOO_LONG")}}function RM(e,t){var n,i=function(e){var t,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=_M(e,i);null!=i.maxDataLength&&null==i.maxLengthLength&&(i.maxLengthLength=Nt(i.maxDataLength));var a,s=null!==(t=null==i?void 0:i.lengthDecoder)&&void 0!==t?t:Lt,l=null!==(n=null==i?void 0:i.lengthEncoder)&&void 0!==n?n:Ot,u={read:function(){var e=r((function*(e){for(var t=-1,r=new gs;;){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 BM("Invalid message length");if(null!=(null==i?void 0:i.maxLengthLength)&&r.byteLength>i.maxLengthLength)throw new DM("message length length too long");if(t>-1)break}if(null!=(null==i?void 0:i.maxDataLength)&&t>i.maxDataLength)throw new NM("message length too long");return o.read(t,e)}));return function(t){return e.apply(this,arguments)}}(),write:function(){var e=r((function*(e,t){yield o.write(new gs(l(e.byteLength),e),t)}));return function(t,r){return e.apply(this,arguments)}}(),writeV:(a=r((function*(e,t){var r=new gs(...e.flatMap((e=>[l(e.byteLength),e])));yield o.write(r,t)})),function(e,t){return a.apply(this,arguments)}),unwrap:()=>o.unwrap()};return u}(e,t),o={read:function(){var e=r((function*(e,t){var r=yield i.read(t);return e.decode(r)}));return function(t,r){return e.apply(this,arguments)}}(),write:function(){var e=r((function*(e,t,r){yield i.write(t.encode(e),r)}));return function(t,r,n){return e.apply(this,arguments)}}(),writeV:(n=r((function*(e,t,r){yield i.writeV(e.map((e=>t.encode(e))),r)})),function(e,t,r){return n.apply(this,arguments)}),pb:e=>{return{read:(i=r((function*(t){return o.read(e,t)})),function(e){return i.apply(this,arguments)}),write:(n=r((function*(t,r){return o.write(t,e,r)})),function(e,t){return n.apply(this,arguments)}),writeV:(t=r((function*(t,r){return o.writeV(t,e,r)})),function(e,r){return t.apply(this,arguments)}),unwrap:()=>o};var t,n,i},unwrap:()=>i.unwrap()};return o}class OM extends os{constructor(r,n){var i,o,a,s,l,u,c;super(),e(this,"log",void 0),e(this,"protocol",void 0),e(this,"running",void 0),e(this,"components",void 0),e(this,"timeout",void 0),e(this,"metrics",void 0),this.components=r,this.log=r.logger.forComponent("".concat(n.logPrefix,":network")),this.running=!1,this.protocol=n.protocol,this.timeout=new AM(t(t({},null!==(i=n.timeout)&&void 0!==i?i:{}),{},{metrics:r.metrics,metricName:"".concat(n.metricsPrefix,"_network_message_send_times_milliseconds")})),this.metrics={operations:null===(o=r.metrics)||void 0===o?void 0:o.registerCounterGroup("".concat(n.metricsPrefix,"_outbound_rpc_requests_total")),errors:null===(a=r.metrics)||void 0===a?void 0:a.registerCounterGroup("".concat(n.metricsPrefix,"_outbound_rpc_errors_total"))},this.sendRequest=null!==(s=null===(l=r.metrics)||void 0===l?void 0:l.traceFunction("libp2p.kadDHT.sendRequest",this.sendRequest.bind(this),{optionsIndex:2,getAttributesFromArgs(e,r){var[n,i]=e;return t(t({},r),{},{to:n.toString(),"message type":"".concat(i.type)})},getAttributesFromYieldedValue:(e,t)=>("PEER_RESPONSE"===e.name&&(e.providers.length>0&&e.providers.forEach(((e,r)=>{t["providers-".concat(r)]=e.id.toString()})),e.closer.length>0&&e.closer.forEach(((e,r)=>{t["closer-".concat(r)]=e.id.toString()}))),t)}))&&void 0!==s?s:this.sendRequest,this.sendMessage=null!==(u=null===(c=r.metrics)||void 0===c?void 0:c.traceFunction("libp2p.kadDHT.sendMessage",this.sendMessage.bind(this),{optionsIndex:2,getAttributesFromArgs(e,r){var[n,i]=e;return t(t({},r),{},{to:n.toString(),"message type":"".concat(i.type)})},getAttributesFromYieldedValue:(e,t)=>("PEER_RESPONSE"===e.name&&(e.providers.length>0&&e.providers.forEach(((e,r)=>{t["providers-".concat(r)]=e.id.toString()})),e.closer.length>0&&e.closer.forEach(((e,r)=>{t["closer-".concat(r)]=e.id.toString()}))),t)}))&&void 0!==u?u:this.sendMessage}start(){var e=this;return r((function*(){e.running||(e.running=!0)}))()}stop(){var e=this;return r((function*(){e.running=!1}))()}isStarted(){return this.running}sendRequest(e,r){var n=this;return l((function(e,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){if(n.running){var o,a=r.type;if(null==a)throw new _a("Message type was missing");n.log("sending %s to %p",r.type,e),yield rM({peer:e},i),yield JL({to:e,type:a},i);var s=n.timeout.getTimeoutSignal(i);i=t(t({},i),{},{signal:s});try{var l;null===(l=n.metrics.operations)||void 0===l||l.increment({[a]:!0});var c=yield u(n.components.connectionManager.openConnection(e,i));o=yield u(c.newStream(n.protocol,i));var d=yield u(n._writeReadMessage(o,r,i));o.close(i).catch((t=>{var r;n.log.error("error closing stream to %p",e,t),null===(r=o)||void 0===r||r.abort(t)})),yield ZL({from:e,messageType:d.type,closer:d.closer.map(EM),providers:d.providers.map(EM),record:null==d.record?void 0:KL.deserialize(d.record)},i)}catch(t){var h,v,p;null===(h=n.metrics.errors)||void 0===h||h.increment({[a]:!0}),null===(v=o)||void 0===v||v.abort(t),!0!==(null===(p=i.signal)||void 0===p?void 0:p.aborted)&&n.log.error("could not send %s to %p - %e",r.type,e,t),yield XL({from:e,error:t},i)}finally{n.timeout.cleanUp(s)}}}()})).apply(this,arguments)}sendMessage(e,r){var n=this;return l((function(e,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){if(n.running){var o,a=r.type;if(null==a)throw new _a("Message type was missing");n.log("sending %s to %p",r.type,e),yield rM({peer:e},i),yield JL({to:e,type:a},i);var s=n.timeout.getTimeoutSignal(i);i=t(t({},i),{},{signal:s});try{var l;null===(l=n.metrics.operations)||void 0===l||l.increment({[a]:!0});var c=yield u(n.components.connectionManager.openConnection(e,i));o=yield u(c.newStream(n.protocol,i)),yield u(n._writeMessage(o,r,i)),o.close(i).catch((t=>{var r;n.log.error("error closing stream to %p",e,t),null===(r=o)||void 0===r||r.abort(t)})),yield ZL({from:e,messageType:a},i)}catch(t){var d,h;null===(d=n.metrics.errors)||void 0===d||d.increment({[a]:!0}),null===(h=o)||void 0===h||h.abort(t),yield XL({from:e,error:t},i)}finally{n.timeout.cleanUp(s)}}}()})).apply(this,arguments)}_writeMessage(e,t,n){return r((function*(){var r=RM(e);yield r.write(t,UL,n)}))()}_writeReadMessage(e,t,n){var i=this;return r((function*(){var r=RM(e);yield r.write(t,UL,n);var o=yield r.read(UL,n);return o.closer.forEach((e=>{i.safeDispatchEvent("peer",{detail:EM(e)})})),o.providers.forEach((e=>{i.safeDispatchEvent("peer",{detail:EM(e)})})),o}))()}}function LM(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 MM{constructor(t,r){e(this,"originDhtKey",void 0),e(this,"capacity",void 0),e(this,"peerDistances",void 0),this.originDhtKey=t,this.capacity=r,this.peerDistances=[]}get length(){return this.peerDistances.length}get peers(){return this.peerDistances.map((e=>e.peer))}add(e){var t=this;return r((function*(){var r=yield hM(e.id);t.addWithKadId(e,r)}))()}addWithKadId(e,t){if(null==this.peerDistances.find((t=>t.peer.id.equals(e.id)))){for(var r={peer:e,distance:cI(this.originDhtKey,t)},n=!1,i=0;i<this.peerDistances.length;i++){var o=LM(this.peerDistances[i].distance,r.distance);if(0===o||1===o){n=!0,this.peerDistances.splice(i,0,r);break}}n||this.peerDistances.push(r),this.peerDistances=this.peerDistances.slice(0,this.capacity)}}isCloser(e){var t=this;return r((function*(){return 0===t.length||-1===LM(cI(yield hM(e),t.originDhtKey),t.peerDistances[t.peerDistances.length-1].distance)}))()}anyCloser(e){var t=this;return r((function*(){return 0!==e.length&&Promise.any(e.map(function(){var e=r((function*(e){return t.isCloser(e)}));return function(t){return e.apply(this,arguments)}}()))}))()}}class UM{constructor(t,r){var n,i,o,a;e(this,"log",void 0),e(this,"routingTable",void 0),e(this,"network",void 0),e(this,"validators",void 0),e(this,"queryManager",void 0),e(this,"peerStore",void 0),e(this,"peerId",void 0),this.routingTable=r.routingTable,this.network=r.network,this.validators=r.validators,this.queryManager=r.queryManager,this.peerStore=t.peerStore,this.peerId=t.peerId,this.log=t.logger.forComponent("".concat(r.logPrefix,":peer-routing")),this.findPeer=null!==(n=null===(i=t.metrics)||void 0===i?void 0:i.traceFunction("libp2p.kadDHT.findPeer",this.findPeer.bind(this),{optionsIndex:1}))&&void 0!==n?n:this.findPeer,this.getClosestPeers=null!==(o=null===(a=t.metrics)||void 0===a?void 0:a.traceFunction("libp2p.kadDHT.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1}))&&void 0!==o?o:this.getClosestPeers}findPeerLocal(e){var t=this;return r((function*(){var r,n=yield t.routingTable.find(e);if(null!=n){t.log("findPeerLocal found %p in routing table",e);try{r=yield t.peerStore.get(n)}catch(e){if("NotFoundError"!==e.name)throw e}}if(null==r)try{r=yield t.peerStore.get(e)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=r)return t.log("findPeerLocal found %p in peer store",e),{id:r.id,multiaddrs:r.addresses.map((e=>e.multiaddr))}}))()}_getValueSingle(e,t){var r=this;return l((function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var i={type:DL.GET_VALUE,key:t};yield*c(s(r.network.sendRequest(e,i,n)))}()})).apply(this,arguments)}getPublicKeyFromNode(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var n,i=function(e){return Mt([lM,e.toMultihash().bytes])}(e),o=!1,a=!1;try{for(var l,c=s(t._getValueSingle(e,i,r));o=!(l=yield u(c.next())).done;o=!1){var d=l.value;if(yield d,"PEER_RESPONSE"===d.name&&null!=d.record){var h=Ru(mu(d.record.value));if(!h.equals(e))throw new Ba("public key does not match id");if(null==h.publicKey)throw new Ba("public key missing");yield tM({from:e,value:d.record.value},r)}}}catch(e){a=!0,n=e}finally{try{o&&null!=c.return&&(yield u(c.return()))}finally{if(a)throw n}}throw new WL("Node not responding with its public key: ".concat(e.toString()))}()})).apply(this,arguments)}findPeer(e){var r=this;return l((function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(r.log("findPeer %p",e),!1!==n.useCache){var i=yield u(r.findPeerLocal(e));if(null!=i)return r.log("found local"),void(yield $L({from:r.peerId,peer:i},n))}var o=!1;if(!1!==n.useNetwork){var a,c=r,d=function(){var r=l((function(r){var{peer:i,signal:o}=r;return function*(){var r,a={type:DL.FIND_NODE,key:e.toMultihash().bytes},l=!1,d=!1;try{for(var h,v=s(c.network.sendRequest(i,a,t(t({},n),{},{signal:o})));l=!(h=yield u(v.next())).done;l=!1){var p=h.value;if(yield p,"PEER_RESPONSE"===p.name){var f=p.closer.find((t=>t.id.equals(e)));null!=f&&(yield $L({from:p.from,peer:f},n))}}}catch(e){d=!0,r=e}finally{try{l&&null!=v.return&&(yield u(v.return()))}finally{if(d)throw r}}}()}));return function(e){return r.apply(this,arguments)}}(),h=!1,v=!1;try{for(var p,f=s(r.queryManager.run(e.toMultihash().bytes,d,n));h=!(p=yield u(f.next())).done;h=!1){var g=p.value;"FINAL_PEER"===g.name&&(o=!0),yield g}}catch(e){v=!0,a=e}finally{try{h&&null!=f.return&&(yield u(f.return()))}finally{if(v)throw a}}}o||(yield XL({from:r.peerId,error:new za("Not found")},n))}()})).apply(this,arguments)}getClosestPeers(e){var n=this;return l((function(e){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){n.log("getClosestPeers to %b",e);var o=yield u(cM(e)),a=n.routingTable.closestPeers(o),d=n,h=new MM(o,n.routingTable.kBucketSize);yield u(Promise.all(a.map(function(){var e=r((function*(e){yield h.add({id:e,multiaddrs:[]})}));return function(t){return e.apply(this,arguments)}}())));var v,p=function(){var r=l((function(r){var{peer:n,signal:o}=r;return function*(){d.log("closerPeersSingle %s from %p",gt(e,"base32"),n);var r={type:DL.FIND_NODE,key:e};yield*c(s(d.network.sendRequest(n,r,t(t({},i),{},{signal:o}))))}()}));return function(e){return r.apply(this,arguments)}}(),f=!1,g=!1;try{for(var y,m=s(n.queryManager.run(e,p,i));f=!(y=yield u(m.next())).done;f=!1){var w=y.value;"PEER_RESPONSE"===w.name&&(yield u(Promise.all(w.closer.map(function(){var e=r((function*(e){yield h.add(e)}));return function(t){return e.apply(this,arguments)}}())))),yield w}}catch(e){g=!0,v=e}finally{try{f&&null!=m.return&&(yield u(m.return()))}finally{if(g)throw v}}for(var b of(n.log("found %d peers close to %b",h.length,e),h.peers))yield $L({from:n.peerId,peer:b},i)}()})).apply(this,arguments)}getValueOrPeers(e,t){var r=this;return l((function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var i,o=!1,a=!1;try{for(var l,c=s(r._getValueSingle(e,t,n));o=!(l=yield u(c.next())).done;o=!1){var d=l.value;if("PEER_RESPONSE"===d.name&&null!=d.record)try{yield u(r._verifyRecordOnline(d.record))}catch(e){var h="invalid record received, discarded";r.log(h),yield XL({from:d.from,error:new WL(h)},n);continue}yield d}}catch(e){a=!0,i=e}finally{try{o&&null!=c.return&&(yield u(c.return()))}finally{if(a)throw i}}}()})).apply(this,arguments)}_verifyRecordOnline(e){var t=this;return r((function*(){if(null==e.timeReceived)throw new QL("invalid record received");yield iM(t.validators,new KL(e.key,e.value,e.timeReceived))}))()}getCloserPeersOffline(e,t){var n=this;return r((function*(){var r=[];try{var i=Lu(He(e)),o=yield n.peerStore.get(i);r.push({id:o.id,multiaddrs:o.addresses.map((e=>{var{multiaddr:t}=e;return t}))})}catch(e){}var a=yield cM(e),s=n.routingTable.closestPeers(a),l=cI(yield hM(t),a);for(var u of s){if(-1===LM(cI(yield hM(u),a),l))try{var c=yield n.peerStore.get(u);r.push({id:u,multiaddrs:c.addresses.map((e=>{var{multiaddr:t}=e;return t}))})}catch(e){if("NotFoundError"!==e.name)throw e}}return r.length>0?n.log("getCloserPeersOffline found %d peer(s) closer to %b than %p",r.length,e,t):n.log("getCloserPeersOffline could not find peer closer to %b than %p with %d peers in the routing table",e,t,n.routingTable.size),r}))()}}class FM{constructor(t,r){e(this,"log",void 0),e(this,"datastore",void 0),e(this,"datastorePrefix",void 0),e(this,"lock",void 0),this.log=t.logger.forComponent("".concat(r.logPrefix,":providers")),this.datastorePrefix="".concat(r.datastorePrefix,"/provider"),this.datastore=t.datastore,this.lock=r.lock}addProvider(e,t){var n=this;return r((function*(){var r=yield n.lock.readLock();try{n.log("%p provides %s",t,e),yield n.writeProviderEntry(e,t)}finally{r()}}))()}removeProvider(e,t){var n=this;return r((function*(){var r=yield n.lock.writeLock();try{var i=yM(n.datastorePrefix,e,t);n.log("%p no longer provides %s",t,e),yield n.datastore.delete(i)}finally{r()}}))()}getProviders(e){var t=this;return r((function*(){var r=yield t.lock.readLock();try{t.log("get providers for %c",e);var n=yield t.loadProviders(e);return t.log("got %d providers for %c",n.size,e),[...n.keys()]}finally{r()}}))()}writeProviderEntry(e,t){var n=arguments,i=this;return r((function*(){var r=n.length>2&&void 0!==n[2]?n[2]:new Date,o=yM(i.datastorePrefix,e,t),a=Ot(r.getTime());yield i.datastore.put(o,a)}))()}loadProviders(e){var t=this;return r((function*(){var r,n=new Fh,i=yM(t.datastorePrefix,e),o=!1,a=!1;try{for(var l,u=s(t.datastore.query({prefix:i.toString()}));o=!(l=yield u.next()).done;o=!1){var c=l.value,{peerId:d}=gM(c.key);n.set(d,mM(c.value))}}catch(e){a=!0,r=e}finally{try{o&&null!=u.return&&(yield u.return())}finally{if(a)throw r}}return n}))()}}function zM(){return zM=l((function*(e){var{key:n,startingPeer:i,ourPeerId:o,signal:a,query:l,alpha:c,pathIndex:d,numPaths:h,queryFuncTimeout:v,log:p,peersSeen:f,connectionManager:g}=e,y=new fv({concurrency:c,sort:(e,t)=>LM(e.options.distance,t.options.distance)}),m=yield u(cM(n));!function i(u,c){if(null!=u){f.add(u);var w=cI(c,m);y.add(r((function*(){var r=[a];null!=v&&r.push(AbortSignal.timeout(v));var c=Ph(r);try{var b,S=!1,E=!1;try{for(var k,x=s(l(t(t({},e),{},{key:n,peer:u,signal:c,pathIndex:d,numPaths:h})));S=!(k=yield x.next()).done;S=!1){var A=k.value;if(c.aborted)return;if("PEER_RESPONSE"===A.name)for(var C of A.closer)if(f.has(C.id))p.trace("already seen %p in query",C.id);else if(o.equals(C.id))p("not querying ourselves");else if(yield g.isDialable(C.multiaddrs)){var I=yield hM(C.id);-1===LM(cI(I,m),w)?(p.trace("querying closer peer %p",C.id),i(C.id,I)):p.trace("skipping %p as they are not closer to %b than %p",C.id,n,u)}else p("not querying undialable peer");y.safeDispatchEvent("completed",{detail:A})}}catch(e){E=!0,b=e}finally{try{S&&null!=x.return&&(yield x.return())}finally{if(E)throw b}}}catch(t){if(!a.aborted)return XL({from:u,error:t},e)}finally{c.clear()}})),{distance:w}).catch((e=>{p.error(e)}))}}(i,yield u(hM(i)));try{var w,b=!1,S=!1;try{for(var E,k=s(y.toGenerator({signal:a}));b=!(E=yield u(k.next())).done;b=!1){var x=E.value;null!=x&&(yield x)}}catch(e){S=!0,w=e}finally{try{b&&null!=k.return&&(yield u(k.return()))}finally{if(S)throw w}}}catch(e){if(a.aborted)throw new GL("Query aborted");throw e}})),zM.apply(this,arguments)}class jM{constructor(t,r){var n,i;e(this,"disjointPaths",void 0),e(this,"alpha",void 0),e(this,"shutDownController",void 0),e(this,"running",void 0),e(this,"logger",void 0),e(this,"peerId",void 0),e(this,"connectionManager",void 0),e(this,"routingTable",void 0),e(this,"initialQuerySelfHasRun",void 0),e(this,"logPrefix",void 0),this.logPrefix=r.logPrefix,this.disjointPaths=null!==(n=r.disjointPaths)&&void 0!==n?n:20,this.alpha=null!==(i=r.alpha)&&void 0!==i?i:3,this.initialQuerySelfHasRun=r.initialQuerySelfHasRun,this.routingTable=r.routingTable,this.logger=t.logger,this.peerId=t.peerId,this.connectionManager=t.connectionManager,this.shutDownController=new AbortController,this.shutDownController.signal,this.running=!1}isStarted(){return this.running}start(){var e=this;return r((function*(){e.running||(e.running=!0,e.shutDownController=new AbortController,e.shutDownController.signal)}))()}stop(){var e=this;return r((function*(){e.running=!1,e.shutDownController.abort()}))()}run(e,r){var n=this;return l((function(e,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){if(!n.running)throw new Error("QueryManager not started");if(null==i.signal){var o=AbortSignal.timeout(18e4);i=t(t({},i),{},{signal:o})}var a=new AbortController,l=Ph([n.shutDownController.signal,a.signal,i.signal]);a.signal;var c=n.logger.forComponent("".concat(n.logPrefix,":query:")+gt(e,"base58btc")),d=!1;try{!0!==i.isSelfQuery&&null!=n.initialQuerySelfHasRun&&(c("waiting for initial query-self query before continuing"),yield u(Nc(n.initialQuerySelfHasRun.promise,l)),n.initialQuerySelfHasRun=void 0),c("query:start");var h=yield u(cM(e)),v=n.routingTable.closestPeers(h),p=v.slice(0,Math.min(n.disjointPaths,v.length));if(0===v.length)return void c.error("Running query with no peers");var f,g=new zh,y=p.map(((o,a)=>function(e){return zM.apply(this,arguments)}(t(t({},i),{},{key:e,startingPeer:o,ourPeerId:n.peerId,signal:l,query:r,pathIndex:a,numPaths:p.length,alpha:n.alpha,queryFuncTimeout:i.queryFuncTimeout,log:c,peersSeen:g,onProgress:i.onProgress,connectionManager:n.connectionManager})))),m=!1,w=!1;try{for(var b,S=s(Uc(...y));m=!(b=yield u(S.next())).done;m=!1){var E=b.value;if("QUERY_ERROR"===E.name&&c.error("query error",E.error),"PEER_RESPONSE"===E.name)for(var k of[...E.closer,...E.providers])(yield u(n.connectionManager.isDialable(k.multiaddrs)))&&(yield u(n.routingTable.add(k.id)));yield E}}catch(e){w=!0,f=e}finally{try{m&&null!=S.return&&(yield u(S.return()))}finally{if(w)throw f}}d=!0}catch(e){if(n.running||"QueryAbortedError"!==e.name)throw e}finally{d||(c("query exited early"),a.abort()),l.clear(),c("query:done")}}()})).apply(this,arguments)}}function VM(e){if(null!=e[Symbol.asyncIterator])return r((function*(){var t,r=0,n=!1,i=!1;try{for(var o,a=s(e);n=!(o=yield a.next()).done;n=!1){o.value;r++}}catch(e){i=!0,t=e}finally{try{n&&null!=a.return&&(yield a.return())}finally{if(i)throw t}}return r}))();var t=0;for(var n of e)t++;return t}function qM(e,r,n){var i,o=new Promise(((o,a)=>{var s;if(!((n=t({rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1},n)).count>=0)||n.count!==Number.POSITIVE_INFINITY&&!Number.isInteger(n.count))throw new TypeError("The `count` option should be at least 0 or more");null===(s=n.signal)||void 0===s||s.throwIfAborted();var l=[r].flat(),u=[],{addListener:c,removeListener:d}=(e=>{var t=e.addEventListener||e.on||e.addListener,r=e.removeEventListener||e.off||e.removeListener;if(!t||!r)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}})(e),h=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];var a=n.multiArgs?t:t[0];n.filter&&!n.filter(a)||(u.push(a),n.count===u.length&&(i(),o(u)))},v=e=>{i(),a(e)};for(var p of(i=()=>{for(var e of l)d(e,h);for(var t of n.rejectionEvents)d(t,v)},l))c(p,h);for(var f of n.rejectionEvents)c(f,v);n.signal&&n.signal.addEventListener("abort",(()=>{v(n.signal.reason)}),{once:!0}),n.resolveImmediately&&o(u)}));if(o.cancel=i,"number"==typeof n.timeout){var a=Xv(o,{milliseconds:n.timeout});return a.cancel=i,a}return o}class HM{constructor(t,r){var n,i,o,a;e(this,"log",void 0),e(this,"peerId",void 0),e(this,"peerRouting",void 0),e(this,"routingTable",void 0),e(this,"count",void 0),e(this,"interval",void 0),e(this,"initialInterval",void 0),e(this,"queryTimeout",void 0),e(this,"running",void 0),e(this,"timeoutId",void 0),e(this,"controller",void 0),e(this,"initialQuerySelfHasRun",void 0),e(this,"querySelfPromise",void 0),this.peerId=t.peerId,this.log=t.logger.forComponent("".concat(r.logPrefix,":query-self")),this.running=!1,this.peerRouting=r.peerRouting,this.routingTable=r.routingTable,this.count=null!==(n=r.count)&&void 0!==n?n:20,this.interval=null!==(i=r.interval)&&void 0!==i?i:3e5,this.initialInterval=null!==(o=r.initialInterval)&&void 0!==o?o:1e3,this.queryTimeout=null!==(a=r.queryTimeout)&&void 0!==a?a:5e3,this.initialQuerySelfHasRun=r.initialQuerySelfHasRun,this.querySelf=bM(this.querySelf.bind(this),r.operationMetrics,"SELF_QUERY")}isStarted(){return this.running}start(){this.running||(this.running=!0,clearTimeout(this.timeoutId),this.timeoutId=setTimeout((()=>{this.querySelf().catch((e=>{this.log.error("error running self-query",e)}))}),this.initialInterval))}stop(){this.running=!1,null!=this.timeoutId&&clearTimeout(this.timeoutId),null!=this.controller&&this.controller.abort()}querySelf(){var e=this;return r((function*(){if(e.running){if(null!=e.querySelfPromise)return e.log("joining existing self query"),e.querySelfPromise.promise;if(e.querySelfPromise=Cc(),e.running){e.controller=new AbortController;var n=[e.controller.signal];if(null==e.initialQuerySelfHasRun){var i=AbortSignal.timeout(e.queryTimeout);n.push(i)}var o=Ph(n);e.controller.signal;try{0===e.routingTable.size&&(e.log("routing table was empty, waiting for some peers before running query"),yield function(e,r,n){"function"==typeof n&&(n={filter:n});var i=qM(e,r,n=t(t({},n),{},{count:1,resolveImmediately:!1})),o=i.then((e=>e[0]));return o.cancel=i.cancel,o}(e.routingTable,"peer:add",{signal:o,filter:t=>!e.peerId.equals(t.detail)}),e.log("routing table has peers, continuing with query")),e.log("run self-query, look for %d peers timing out after %dms",e.count,e.queryTimeout);var a=Date.now(),s=yield Fc(e.peerRouting.getClosestPeers(e.peerId.toMultihash().bytes,{signal:o,isSelfQuery:!0}),(t=>pc(t,e.count)),function(){var e=r((function*(e){return VM(e)}));return function(t){return e.apply(this,arguments)}}());e.log("self-query found %d peers in %dms",s,Date.now()-a)}catch(t){e.log.error("self-query error",t)}finally{o.clear(),null!=e.initialQuerySelfHasRun&&(e.initialQuerySelfHasRun.resolve(),e.initialQuerySelfHasRun=void 0)}}e.querySelfPromise.resolve(),e.querySelfPromise=void 0,e.running&&(e.timeoutId=setTimeout((()=>{e.querySelf().catch((t=>{e.log.error("error running self-query",t)}))}),e.interval))}else e.log("skip self-query because we are not started")}))()}}class KM extends os{constructor(r,n){var i,o,a,s,l,u;super(),e(this,"log",void 0),e(this,"reprovideQueue",void 0),e(this,"maxQueueSize",void 0),e(this,"datastore",void 0),e(this,"timeout",void 0),e(this,"reprovideTimeout",void 0),e(this,"running",void 0),e(this,"shutdownController",void 0),e(this,"reprovideThreshold",void 0),e(this,"contentRouting",void 0),e(this,"datastorePrefix",void 0),e(this,"addressManager",void 0),e(this,"validity",void 0),e(this,"interval",void 0),e(this,"lock",void 0),e(this,"peerId",void 0),this.log=r.logger.forComponent("".concat(n.logPrefix,":reprovider")),this.peerId=r.peerId,this.reprovideQueue=new fv({concurrency:null!==(i=n.concurrency)&&void 0!==i?i:10,metrics:r.metrics,metricName:"".concat(n.metricsPrefix,"_reprovide_queue")}),this.reprovideTimeout=new AM(t(t({},null!==(o=n.timeout)&&void 0!==o?o:{}),{},{metrics:r.metrics,metricName:"".concat(n.metricsPrefix,"_reprovide_timeout_milliseconds")})),this.datastore=r.datastore,this.addressManager=r.addressManager,this.datastorePrefix="".concat(n.datastorePrefix,"/provider"),this.reprovideThreshold=null!==(a=n.threshold)&&void 0!==a?a:864e5,this.maxQueueSize=null!==(s=n.maxQueueSize)&&void 0!==s?s:16384,this.validity=null!==(l=n.validity)&&void 0!==l?l:jL,this.interval=null!==(u=n.interval)&&void 0!==u?u:VL,this.contentRouting=n.contentRouting,this.lock=n.lock,this.running=!1,this.reprovide=bM(this.reprovide.bind(this),n.operationMetrics,"PROVIDE")}start(){this.running||(this.running=!0,this.shutdownController=new AbortController,this.shutdownController.signal,this.timeout=setTimeout((()=>{this.cleanUp().catch((e=>{this.log.error("error running reprovide/cleanup - %e",e)}))}),this.interval))}stop(){var e;this.running=!1,this.reprovideQueue.clear(),clearTimeout(this.timeout),null===(e=this.shutdownController)||void 0===e||e.abort()}cleanUp(){var e=this;return r((function*(){var t=yield e.lock.writeLock();try{e.safeDispatchEvent("reprovide:start");var r,n=!1,i=!1;try{for(var o,a=function*(){var t=o.value;try{var{cid:r,peerId:n}=gM(t.key),i=mM(t.value).getTime(),a=i+e.validity,s=Date.now(),l=s>a;e.log.trace("comparing: %d < %d = %s %s",i,s-e.validity,l,l?"(expired)":""),l&&(yield e.datastore.delete(t.key)),e.peerId.equals(n)&&s-a<e.reprovideThreshold&&e.queueReprovide(r).catch((t=>{e.log.error("could not reprovide %c - %e",r,t)}))}catch(r){e.log.error("error processing datastore key %s - %e",t.key,r.message)}},l=s(e.datastore.query({prefix:e.datastorePrefix}));n=!(o=yield l.next()).done;n=!1)yield*a()}catch(e){i=!0,r=e}finally{try{n&&null!=l.return&&(yield l.return())}finally{if(i)throw r}}e.log("reprovide/cleanup successful")}finally{t(),e.safeDispatchEvent("reprovide:end"),e.running&&(e.timeout=setTimeout((()=>{e.cleanUp().catch((t=>{e.log.error("error running re-provide - %e",t)}))}),e.interval))}}))()}queueReprovide(e){var t=this;return r((function*(){var n;if(t.running){t.log.trace("waiting for queue capacity before adding %c to re-provide queue",e),yield t.reprovideQueue.onSizeLessThan(t.maxQueueSize);var i=t.reprovideQueue.queue.find((t=>t.options.cid.equals(e)));if(null!=i)return t.log.trace("not adding %c to re-provide queue - already in queue",e),i.join();t.log.trace("adding %c to re-provide queue",e),t.reprovideQueue.add(function(){var n=r((function*(r){var n;if(null===(n=r.signal)||void 0===n||n.throwIfAborted(),t.running){t.log.trace("re-providing %c",e);var i=t.reprovideTimeout.getTimeoutSignal(r);try{yield t.reprovide(r.cid,r)}finally{t.reprovideTimeout.cleanUp(i)}t.log.trace("re-provided %c",e)}}));return function(e){return n.apply(this,arguments)}}(),{signal:null===(n=t.shutdownController)||void 0===n?void 0:n.signal,cid:e}).catch((r=>{t.log.error("could not re-provide key %c - %e",e,r)}))}}))()}reprovide(e,t){var n=this;return r((function*(){yield uc(n.contentRouting.provide(e,n.addressManager.getAddresses(),t))}))()}}class WM{constructor(t,r){var n,i,o,a;e(this,"routingTable",void 0),e(this,"components",void 0),e(this,"closestPeers",void 0),e(this,"newPeers",void 0),e(this,"refreshInterval",void 0),e(this,"peerSetSize",void 0),e(this,"timeout",void 0),e(this,"closeTagName",void 0),e(this,"closeTagValue",void 0),e(this,"log",void 0),e(this,"running",void 0),this.components=t,this.log=t.logger.forComponent("".concat(r.logPrefix,":routing-table")),this.routingTable=r.routingTable,this.refreshInterval=null!==(n=r.refreshInterval)&&void 0!==n?n:5e3,this.peerSetSize=null!==(i=r.peerSetSize)&&void 0!==i?i:20,this.closeTagName=null!==(o=r.closeTagName)&&void 0!==o?o:"kad-close",this.closeTagValue=null!==(a=r.closeTagValue)&&void 0!==a?a:50,this.closestPeers=new zh,this.onPeerPing=this.onPeerPing.bind(this),this.running=!1}start(){var e=this;return r((function*(){if(!e.running){e.running=!0;var t=yield hM(e.components.peerId);e.newPeers=new MM(t,e.peerSetSize),e.routingTable.addEventListener("peer:ping",e.onPeerPing),e.timeout=setInterval((()=>{e.updatePeerTags().catch((t=>{e.log.error("error updating peer tags - %e",t)}))}),e.refreshInterval)}}))()}stop(){this.running=!1,this.routingTable.removeEventListener("peer:ping",this.onPeerPing),clearTimeout(this.timeout)}onPeerPing(e){var t;null===(t=this.newPeers)||void 0===t||t.add({id:e.detail,multiaddrs:[]}).catch((e=>{this.log.error("error adding peer to distance list - %e",e)}))}updatePeerTags(){var e=this;return r((function*(){var t,n=new zh(null===(t=e.newPeers)||void 0===t?void 0:t.peers.map((e=>e.id))),i=n.difference(e.closestPeers),o=e.closestPeers.difference(n);e.closestPeers=n,yield Promise.all([...[...i].map(function(){var t=r((function*(t){yield e.components.peerStore.merge(t,{tags:{[e.closeTagName]:{value:e.closeTagValue},[qL]:{value:1}}})}));return function(e){return t.apply(this,arguments)}}()),...[...o].map(function(){var t=r((function*(t){yield e.components.peerStore.merge(t,{tags:{[e.closeTagName]:void 0,[qL]:void 0}})}));return function(e){return t.apply(this,arguments)}}())])}))()}}function GM(e){return Array.isArray(null==e?void 0:e.peers)}class QM{constructor(t){var r,n,i,o,a;e(this,"root",void 0),e(this,"localPeer",void 0),e(this,"prefixLength",void 0),e(this,"splitThreshold",void 0),e(this,"kBucketSize",void 0),e(this,"numberOfNodesToPing",void 0),e(this,"lastPingThreshold",void 0),e(this,"ping",void 0),e(this,"verify",void 0),e(this,"onAdd",void 0),e(this,"onRemove",void 0),e(this,"onMove",void 0),e(this,"addingPeerMap",void 0),this.prefixLength=null!==(r=t.prefixLength)&&void 0!==r?r:JM,this.kBucketSize=null!==(n=t.kBucketSize)&&void 0!==n?n:YM,this.splitThreshold=null!==(i=t.splitThreshold)&&void 0!==i?i:this.kBucketSize,this.numberOfNodesToPing=null!==(o=t.numberOfOldContactsToPing)&&void 0!==o?o:ZM,this.lastPingThreshold=null!==(a=t.lastPingThreshold)&&void 0!==a?a:XM,this.ping=t.ping,this.verify=t.verify,this.onAdd=t.onAdd,this.onRemove=t.onRemove,this.addingPeerMap=new Fh,this.root={prefix:"",depth:0,peers:[]}}addSelfPeer(e){var t=this;return r((function*(){t.localPeer={peerId:e,kadId:yield hM(e),lastPing:Date.now()}}))()}add(e,t){var n=this;return r((function*(){var r={peerId:e,kadId:yield hM(e),lastPing:0},i=n.addingPeerMap.get(e);if(null!=i)return i;try{var o=n._add(r,t);n.addingPeerMap.set(e,o),yield o}finally{n.addingPeerMap.delete(e)}}))()}_add(e,t){var n=this;return r((function*(){var r=n._determineBucket(e.kadId);if(!(n._indexOf(r,e.kadId)>-1)){if(r.peers.length===n.splitThreshold&&r.depth<n.prefixLength)return yield n._split(r),void(yield n._add(e,t));var i;if(r.peers.length<n.kBucketSize)return function(e,t){return e.lastPing<Date.now()-t}(e,n.lastPingThreshold)?void((yield n.verify(e,t))&&(e.lastPing=Date.now(),yield n._add(e,t))):(r.peers.push(e),void(yield null===(i=n.onAdd)||void 0===i?void 0:i.call(n,e,r)));var o,a=r.peers.filter((e=>{var t;return!e.peerId.equals(null===(t=n.localPeer)||void 0===t?void 0:t.peerId)&&!(e.lastPing>Date.now()-n.lastPingThreshold)})).sort(((e,t)=>e.lastPing<t.lastPing?-1:e.lastPing>t.lastPing?1:0)).slice(0,n.numberOfNodesToPing),l=!1,u=!1,c=!1;try{for(var d,h=s(n.ping(a,t));u=!(d=yield h.next()).done;u=!1){var v=d.value;l=!0,yield n.remove(v.kadId)}}catch(e){c=!0,o=e}finally{try{u&&null!=h.return&&(yield h.return())}finally{if(c)throw o}}l&&(yield n._add(e,t))}}))()}closest(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.kBucketSize;return function*(){var n=new MM(e,r);for(var i of t.toIterable())n.addWithKadId({id:i.peerId,multiaddrs:[]},i.kadId);yield*Ac(n.peers,(e=>e.id))}()}count(){return function e(t){if(GM(t))return t.peers.length;var r=0;return null!=t.left&&(r+=e(t.left)),null!=t.right&&(r+=e(t.right)),r}(this.root)}get(e){var t=this._determineBucket(e),r=this._indexOf(t,e);return t.peers[r]}remove(e){var t=this;return r((function*(){var r=t._determineBucket(e),n=t._indexOf(r,e);if(n>-1){var i,o=r.peers.splice(n,1)[0];yield null===(i=t.onRemove)||void 0===i?void 0:i.call(t,o,r)}}))()}*toIterable(){yield*function*e(t){GM(t)?yield*t.peers:(yield*e(t.left),yield*e(t.right))}(this.root)}distance(e,t){return BigInt("0x"+gt(cI(e,t),"base16"))}_determineBucket(e){var t=gt(e,"base2");return function e(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return GM(r)?r:e("0"===t[n]?r.left:r.right,n+1)}(this.root)}_indexOf(e,t){return e.peers.findIndex((e=>St(e.kadId,t)))}_split(e){var t=this;return r((function*(){var r={prefix:"0",depth:e.depth+1,peers:[]},n={prefix:"1",depth:e.depth+1,peers:[]};for(var i of e.peers){var o,a;if("0"===gt(i.kadId,"base2")[e.depth])r.peers.push(i),yield null===(o=t.onMove)||void 0===o?void 0:o.call(t,i,e,r);else n.peers.push(i),yield null===(a=t.onMove)||void 0===a?void 0:a.call(t,i,e,n)}!function(e,t,r){delete e.peers,e.left=t,e.right=r,""===e.prefix&&(delete e.depth,delete e.prefix)}(e,r,n)}))()}}var YM=20,JM=6,ZM=3,$M="kad-peer",XM=6e5;class eU extends os{constructor(r,n){var i,o,a,s,l,u,c,d,h,v,p;super(),e(this,"kBucketSize",void 0),e(this,"kb",void 0),e(this,"network",void 0),e(this,"closestPeerTagger",void 0),e(this,"log",void 0),e(this,"components",void 0),e(this,"running",void 0),e(this,"pingNewContactTimeout",void 0),e(this,"pingNewContactQueue",void 0),e(this,"pingOldContactTimeout",void 0),e(this,"pingOldContactQueue",void 0),e(this,"populateFromDatastoreOnStart",void 0),e(this,"populateFromDatastoreLimit",void 0),e(this,"protocol",void 0),e(this,"peerTagName",void 0),e(this,"peerTagValue",void 0),e(this,"metrics",void 0),this.components=r,this.log=r.logger.forComponent("".concat(n.logPrefix,":routing-table")),this.kBucketSize=null!==(i=n.kBucketSize)&&void 0!==i?i:YM,this.running=!1,this.protocol=n.protocol,this.network=n.network,this.peerTagName=null!==(o=n.peerTagName)&&void 0!==o?o:$M,this.peerTagValue=null!==(a=n.peerTagValue)&&void 0!==a?a:1,this.pingOldContacts=this.pingOldContacts.bind(this),this.verifyNewContact=this.verifyNewContact.bind(this),this.peerAdded=this.peerAdded.bind(this),this.peerRemoved=this.peerRemoved.bind(this),this.populateFromDatastoreOnStart=null===(s=n.populateFromDatastoreOnStart)||void 0===s||s,this.populateFromDatastoreLimit=null!==(l=n.populateFromDatastoreLimit)&&void 0!==l?l:1e3,this.pingOldContactQueue=new gv({concurrency:null!==(u=n.pingOldContactConcurrency)&&void 0!==u?u:20,metricName:"".concat(n.metricsPrefix,"_ping_old_contact_queue"),metrics:this.components.metrics,maxSize:null!==(c=n.pingOldContactMaxQueueSize)&&void 0!==c?c:100}),this.pingOldContactTimeout=new AM(t(t({},null!==(d=n.pingOldContactTimeout)&&void 0!==d?d:{}),{},{metrics:this.components.metrics,metricName:"".concat(n.metricsPrefix,"_routing_table_ping_old_contact_time_milliseconds")})),this.pingNewContactQueue=new gv({concurrency:null!==(h=n.pingNewContactConcurrency)&&void 0!==h?h:20,metricName:"".concat(n.metricsPrefix,"_ping_new_contact_queue"),metrics:this.components.metrics,maxSize:null!==(v=n.pingNewContactMaxQueueSize)&&void 0!==v?v:100}),this.pingNewContactTimeout=new AM(t(t({},null!==(p=n.pingNewContactTimeout)&&void 0!==p?p:{}),{},{metrics:this.components.metrics,metricName:"".concat(n.metricsPrefix,"_routing_table_ping_new_contact_time_milliseconds")})),this.kb=new QM({kBucketSize:n.kBucketSize,prefixLength:n.prefixLength,splitThreshold:n.splitThreshold,numberOfOldContactsToPing:n.numberOfOldContactsToPing,lastPingThreshold:n.lastPingThreshold,ping:this.pingOldContacts,verify:this.verifyNewContact,onAdd:this.peerAdded,onRemove:this.peerRemoved}),this.closestPeerTagger=new WM(this.components,{logPrefix:n.logPrefix,routingTable:this,peerSetSize:n.closestPeerSetSize,refreshInterval:n.closestPeerSetRefreshInterval,closeTagName:n.closeTagName,closeTagValue:n.closeTagValue}),null!=this.components.metrics&&(this.metrics={routingTableSize:this.components.metrics.registerMetric("".concat(n.metricsPrefix,"_routing_table_size")),routingTableKadBucketTotal:this.components.metrics.registerMetric("".concat(n.metricsPrefix,"_routing_table_kad_bucket_total")),routingTableKadBucketAverageOccupancy:this.components.metrics.registerMetric("".concat(n.metricsPrefix,"_routing_table_kad_bucket_average_occupancy")),routingTableKadBucketMinOccupancy:this.components.metrics.registerMetric("".concat(n.metricsPrefix,"_routing_table_kad_bucket_min_occupancy")),routingTableKadBucketMaxOccupancy:this.components.metrics.registerMetric("".concat(n.metricsPrefix,"_routing_table_kad_bucket_max_occupancy")),routingTableKadBucketMaxDepth:this.components.metrics.registerMetric("".concat(n.metricsPrefix,"_routing_table_kad_bucket_max_depth")),kadBucketEvents:this.components.metrics.registerCounterGroup("".concat(n.metricsPrefix,"_kad_bucket_events_total"))})}isStarted(){return this.running}start(){var e=this;return r((function*(){e.running||(e.running=!0,yield ss(e.closestPeerTagger),yield e.kb.addSelfPeer(e.components.peerId))}))()}afterStart(){var e=this;return r((function*(){Promise.resolve().then(r((function*(){if(e.populateFromDatastoreOnStart){var t=0;for(var r of yield e.components.peerStore.all({filters:[t=>t.protocols.includes(e.protocol)&&t.tags.has($M)],limit:e.populateFromDatastoreLimit})){if(!e.running)return;try{yield e.add(r.id),t++}catch(t){e.log("failed to add peer %p to routing table, removing kad-dht peer tags - %e"),yield e.components.peerStore.merge(r.id,{tags:{[e.peerTagName]:void 0}})}}e.log("added %d peer store peers to the routing table",t)}}))).catch((t=>{e.log.error("error adding peer store peers to the routing table %e",t)}))}))()}stop(){var e=this;return r((function*(){e.running=!1,yield us(e.closestPeerTagger),e.pingOldContactQueue.abort(),e.pingNewContactQueue.abort()}))()}peerAdded(e,t){var n=this;return r((function*(){var t;n.components.peerId.equals(e.peerId)||(yield n.components.peerStore.merge(e.peerId,{tags:{[n.peerTagName]:{value:n.peerTagValue}}})),n.updateMetrics(),null===(t=n.metrics)||void 0===t||t.kadBucketEvents.increment({peer_added:!0}),n.safeDispatchEvent("peer:add",{detail:e.peerId})}))()}peerRemoved(e,t){var n=this;return r((function*(){var t;n.components.peerId.equals(e.peerId)||(yield n.components.peerStore.merge(e.peerId,{tags:{[n.peerTagName]:void 0}})),n.updateMetrics(),null===(t=n.metrics)||void 0===t||t.kadBucketEvents.increment({peer_removed:!0}),n.safeDispatchEvent("peer:remove",{detail:e.peerId})}))()}pingOldContacts(e,t){var n=this;return l((function*(){if(n.running){var i=[],o=function*(e){var o;if(null==n.kb.get(e.kadId))return n.log("asked to ping contact %p that was not in routing table",e.peerId),1;null===(o=n.metrics)||void 0===o||o.kadBucketEvents.increment({ping_old_contact:!0}),i.push(r((function*(){var i=n.pingOldContactQueue.find(e.peerId);if(null!=i)return n.log("asked to ping contact %p was already being pinged",e.peerId),(yield i.join(t))?void 0:e;var o=yield n.pingOldContactQueue.add(function(){var t=r((function*(t){var r=n.pingOldContactTimeout.getTimeoutSignal(),i=Ph([r,null==t?void 0:t.signal]);try{return yield n.pingContact(e,t)}catch(e){var o;return null===(o=n.metrics)||void 0===o||o.kadBucketEvents.increment({ping_old_contact_error:!0}),!0}finally{n.pingOldContactTimeout.cleanUp(r),i.clear()}}));return function(e){return t.apply(this,arguments)}}(),{peerId:e.peerId,signal:null==t?void 0:t.signal});return o?void 0:e})))};for(var a of e)yield*o(a);var l,c=!1,d=!1;try{for(var h,v=s(bL(i));c=!(h=yield u(v.next())).done;c=!1){var p=h.value;null!=p&&(yield p)}}catch(e){d=!0,l=e}finally{try{c&&null!=v.return&&(yield u(v.return()))}finally{if(d)throw l}}}}))()}verifyNewContact(e,t){var n=this;return r((function*(){var i=n.pingNewContactTimeout.getTimeoutSignal(),o=Ph([i,null==t?void 0:t.signal]);try{var a=n.pingNewContactQueue.find(e.peerId);return null!=a?(n.log("joining existing ping to add new peer %p to routing table",e.peerId),yield a.join({signal:o})):yield n.pingNewContactQueue.add(function(){var t=r((function*(t){var r;return null===(r=n.metrics)||void 0===r||r.kadBucketEvents.increment({ping_new_contact:!0}),n.log("pinging new peer %p before adding to routing table",e.peerId),n.pingContact(e,t)}));return function(e){return t.apply(this,arguments)}}(),{peerId:e.peerId,signal:o})}catch(t){var s;return n.log.trace("tried to add peer %p but they were not online",e.peerId),null===(s=n.metrics)||void 0===s||s.kadBucketEvents.increment({ping_new_contact_error:!0}),!1}finally{n.pingNewContactTimeout.cleanUp(i),o.clear()}}))()}pingContact(e,t){var n=this;return r((function*(){try{n.log("pinging contact %p",e.peerId);var r,i=!1,o=!1;try{for(var a,l=s(n.network.sendRequest(e.peerId,{type:DL.PING},t));i=!(a=yield l.next()).done;i=!1){var u=a.value;if(u.type===vU.PEER_RESPONSE)return u.messageType===DL.PING&&(n.log("contact %p ping ok",e.peerId),n.safeDispatchEvent("peer:ping",{detail:e.peerId}),!0)}}catch(e){o=!0,r=e}finally{try{i&&null!=l.return&&(yield l.return())}finally{if(o)throw r}}return!1}catch(t){return n.log("error pinging old contact %p - %e",e.peerId,t),!1}}))()}get size(){return null==this.kb?0:this.kb.count()}find(e){var t=this;return r((function*(){var r,n=yield hM(e);return null===(r=t.kb.get(n))||void 0===r?void 0:r.peerId}))()}closestPeer(e){var t=this.closestPeers(e,1);if(t.length>0)return t[0]}closestPeers(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.kBucketSize;return null==this.kb?[]:[...this.kb.closest(e,t)]}add(e,t){var n=this;return r((function*(){if(null==n.kb)throw new Error("RoutingTable is not started");yield n.kb.add(e,t)}))()}remove(e){var t=this;return r((function*(){if(null==t.kb)throw new Error("RoutingTable is not started");var r=yield hM(e);yield t.kb.remove(r)}))()}updateMetrics(){if(null!=this.metrics&&null!=this.kb){var e=0,t=0,r=0,n=20,i=0;!function o(a){if(GM(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 tU=[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 rU{constructor(t,r){e(this,"log",void 0),e(this,"peerRouting",void 0),e(this,"routingTable",void 0),e(this,"refreshInterval",void 0),e(this,"refreshQueryTimeout",void 0),e(this,"commonPrefixLengthRefreshedAt",void 0),e(this,"refreshTimeoutId",void 0);var{peerRouting:n,routingTable:i,refreshInterval:o,refreshQueryTimeout:a,logPrefix:s}=r;this.log=t.logger.forComponent("".concat(s,":routing-table:refresh")),this.peerRouting=n,this.routingTable=i,this.refreshInterval=null!=o?o:3e5,this.refreshQueryTimeout=null!=a?a:3e4,this.commonPrefixLengthRefreshedAt=[],this.refreshTable=this.refreshTable.bind(this)}afterStart(){var e=this;return r((function*(){e.log("refreshing routing table every ".concat(e.refreshInterval,"ms")),e.refreshTable(!0)}))()}stop(){var e=this;return r((function*(){null!=e.refreshTimeoutId&&clearTimeout(e.refreshTimeoutId)}))()}refreshTable(){var e=this,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.log("refreshing routing table");var n=this._maxCommonPrefix(),i=this._getTrackedCommonPrefixLengthsForRefresh(n);this.log("max common prefix length ".concat(n)),this.log("tracked CPLs [ ".concat(i.map((e=>e.toISOString())).join(", ")," ]")),Promise.all(i.map(function(){var o=r((function*(r,o){try{if(yield e._refreshCommonPrefixLength(o,r,t),0===e._numPeersForCpl(n))for(var a=Math.min(2*(o+1),i.length-1),s=o+1;s<a+1;s++)try{yield e._refreshCommonPrefixLength(s,r,t)}catch(t){e.log.error(t)}}catch(t){e.log.error(t)}}));return function(e,t){return o.apply(this,arguments)}}())).catch((e=>{this.log.error(e)})).then((()=>{this.refreshTimeoutId=setTimeout(this.refreshTable,this.refreshInterval),null!=this.refreshTimeoutId.unref&&this.refreshTimeoutId.unref()})).catch((e=>{this.log.error(e)}))}_refreshCommonPrefixLength(e,t,n){var i=this;return r((function*(){if(!n&&t.getTime()>Date.now()-i.refreshInterval)i.log("not running refresh for cpl %s as time since last refresh not above interval",e);else{var r=yield i._generateRandomPeerId(e);i.log("starting refreshing cpl %s with key %p (routing table size was %s)",e,r,i.routingTable.size);var o=AbortSignal.timeout(i.refreshQueryTimeout),a=yield VM(i.peerRouting.getClosestPeers(r.toMultihash().bytes,{signal:o}));i.log("found ".concat(a," peers that were close to imaginary peer %p"),r),i.log("finished refreshing cpl %s with key %p (routing table size is now %s)",e,r,i.routingTable.size)}}))()}_getTrackedCommonPrefixLengthsForRefresh(e){e>15&&(e=15);for(var t=[],r=0;r<=e;r++){var n;t[r]=null!==(n=this.commonPrefixLengthRefreshedAt[r])&&void 0!==n?n:new Date}return t}_generateRandomPeerId(e){var t=this;return r((function*(){if(null==t.routingTable.kb)throw new Error("Routing table not started");if(null==t.routingTable.kb.localPeer)throw new Error("Local peer not set");var r=Gl(2),n=(r[1]<<8)+r[0];return Lu(He(yield t._makePeerId(t.routingTable.kb.localPeer.kadId,n,e)))}))()}_makePeerId(e,t,n){return r((function*(){if(n>15)throw new Error("Cannot generate peer ID for common prefix length greater than ".concat(15));var r=new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(0,!1),i=65535<<16-(n+1),o=tU[(r^32768>>n)&i|t&~i],a=new ArrayBuffer(34),s=new DataView(a,0,a.byteLength);return s.setUint8(0,$e.code),s.setUint8(1,32),s.setUint32(2,o,!1),new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}))()}_maxCommonPrefix(){var e=0;for(var t of this._prefixLengths())t>e&&(e=t);return e}_numPeersForCpl(e){var t=0;for(var r of this._prefixLengths())r===e&&t++;return t}*_prefixLengths(){var e;if(null!=(null===(e=this.routingTable.kb)||void 0===e?void 0:e.localPeer))for(var{kadId:t}of this.routingTable.kb.toIterable()){var r=cI(this.routingTable.kb.localPeer.kadId,t),n=0;for(var i of r){if(0!==i)break;n++}yield n}}}class nU{constructor(t,r){e(this,"peerId",void 0),e(this,"providers",void 0),e(this,"peerStore",void 0),e(this,"log",void 0),this.log=t.logger.forComponent("".concat(r.logPrefix,":rpc:handlers:add-provider")),this.peerId=t.peerId,this.providers=r.providers,this.peerStore=t.peerStore}handle(e,t){var n=this;return r((function*(){if(null==t.key||0===t.key.length)throw new Wa("Missing key");var i;try{i=it.decode(t.key)}catch(e){throw new Wa("Invalid CID")}null!=t.providers&&0!==t.providers.length||n.log.error("no providers found in message"),n.log("%p asked us, %p to store provider record for for %c",e,n.peerId,i),yield Promise.all(t.providers.map(function(){var t=r((function*(t){var r=Lu(He(t.id)),o=t.multiaddrs.map((e=>kr(e)));e.equals(r)?t.multiaddrs.length<1?n.log("no valid addresses for provider %p. Ignore",e):(n.log.trace("received provider %p for %s (addrs %s)",e,i,o),yield n.providers.addProvider(i,r),yield n.peerStore.merge(r,{multiaddrs:o})):n.log("invalid provider peer %p from %p",t.id,e)}));return function(e){return t.apply(this,arguments)}}()))}))()}}class iU{constructor(t,r){e(this,"peerRouting",void 0),e(this,"peerInfoMapper",void 0),e(this,"peerId",void 0),e(this,"addressManager",void 0),e(this,"log",void 0);var{peerRouting:n,logPrefix:i}=r;this.log=t.logger.forComponent("".concat(i,":rpc:handlers:find-node")),this.peerId=t.peerId,this.addressManager=t.addressManager,this.peerRouting=n,this.peerInfoMapper=r.peerInfoMapper}handle(e,t){var n=this;return r((function*(){if(n.log("incoming request from %p for peers closer to %b",e,t.key),null==t.key)throw new Wa("Invalid FIND_NODE message received - key was missing");var r=yield n.peerRouting.getCloserPeersOffline(t.key,e);St(n.peerId.toMultihash().bytes,t.key)&&r.push({id:n.peerId,multiaddrs:n.addressManager.getAddresses().map((e=>e.decapsulateCode(xr("p2p").code)))});var i={type:DL.FIND_NODE,clusterLevel:t.clusterLevel,closer:r.map(n.peerInfoMapper).filter((e=>{var{multiaddrs:t}=e;return t.length})).map((e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map((e=>e.bytes))}))),providers:[]};return 0===i.closer.length&&n.log("could not find any peers closer to %b than %p",t.key,e),i}))()}}class oU{constructor(t,r){e(this,"peerId",void 0),e(this,"peerRouting",void 0),e(this,"providers",void 0),e(this,"peerStore",void 0),e(this,"peerInfoMapper",void 0),e(this,"log",void 0);var{peerRouting:n,providers:i,logPrefix:o}=r;this.log=t.logger.forComponent("".concat(o,":rpc:handlers:get-providers")),this.peerId=t.peerId,this.peerStore=t.peerStore,this.peerRouting=n,this.providers=i,this.peerInfoMapper=r.peerInfoMapper}handle(e,t){var n=this;return r((function*(){if(null==t.key)throw new Wa("Invalid GET_PROVIDERS message received - key was missing");var i;try{i=it.decode(t.key)}catch(e){throw new Wa("Invalid CID")}n.log("%p asking for providers for %s",e,i);var[o,a]=yield Promise.all([hc(Ac(yield n.providers.getProviders(i),function(){var e=r((function*(e){var t=yield n.peerStore.get(e),r={id:t.id,multiaddrs:t.addresses.map((e=>{var{multiaddr:t}=e;return t}))};return r}));return function(t){return e.apply(this,arguments)}}())),n.peerRouting.getCloserPeersOffline(t.key,n.peerId)]),s={type:DL.GET_PROVIDERS,key:t.key,clusterLevel:t.clusterLevel,closer:a.map(n.peerInfoMapper).filter((e=>{var{id:t,multiaddrs:r}=e;return r.length>0})).map((e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map((e=>e.bytes))}))),providers:o.map(n.peerInfoMapper).filter((e=>{var{id:t,multiaddrs:r}=e;return r.length>0})).map((e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map((e=>e.bytes))})))};return n.log("got %s providers %s closerPeers",s.providers.length,s.closer.length),s}))()}_getAddresses(e){return r((function*(){return[]}))()}}class aU{constructor(t,r){e(this,"peerStore",void 0),e(this,"datastore",void 0),e(this,"peerRouting",void 0),e(this,"log",void 0),e(this,"datastorePrefix",void 0),this.log=t.logger.forComponent("".concat(r.logPrefix,":rpc:handlers:get-value")),this.datastorePrefix="".concat(r.datastorePrefix,"/record"),this.peerStore=t.peerStore,this.datastore=t.datastore,this.peerRouting=r.peerRouting}handle(e,t){var n=this;return r((function*(){var r=t.key;if(n.log("%p asked for key %b",e,r),null==r||0===r.length)throw new Wa("Invalid key");var i={type:DL.GET_VALUE,key:r,clusterLevel:t.clusterLevel,closer:[],providers:[]};if(function(e){return"/pk/"===gt(e.subarray(0,4))}(r)){n.log("is public key");var o,a=function(e){return Lu(He(e.subarray(4)))}(r);try{var s=yield n.peerStore.get(a);if(null==s.id.publicKey)throw new za("No public key found in key book");o=Su(s.id.publicKey)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=o)return n.log("returning found public key"),i.record=new KL(r,o,new Date).serialize(),i}var[l,u]=yield Promise.all([n._checkLocalDatastore(r),n.peerRouting.getCloserPeersOffline(r,e)]);return null!=l&&(n.log("had record for %b in local datastore",r),i.record=l.serialize()),u.length>0&&(n.log("had %s closer peers in routing table",u.length),i.closer=u.map((e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map((e=>e.bytes))})))),i}))()}_checkLocalDatastore(e){var t=this;return r((function*(){t.log("checkLocalDatastore looking for %b",e);var r,n=pM(t.datastorePrefix,e);try{r=yield t.datastore.get(n)}catch(e){if("NotFoundError"===e.name)return;throw e}var i=KL.deserialize(r);if(!(null==i.timeReceived||Date.now()-i.timeReceived.getTime()>zL))return i;yield t.datastore.delete(n)}))()}}class sU{constructor(t,r){e(this,"log",void 0),this.log=t.logger.forComponent("".concat(r.logPrefix,":rpc:handlers:ping"))}handle(e,t){var n=this;return r((function*(){return n.log("ping from %p",e),t}))()}}class lU{constructor(t,r){e(this,"components",void 0),e(this,"validators",void 0),e(this,"log",void 0),e(this,"datastorePrefix",void 0);var{validators:n}=r;this.components=t,this.log=t.logger.forComponent("".concat(r.logPrefix,":rpc:handlers:put-value")),this.datastorePrefix="".concat(r.datastorePrefix,"/record"),this.validators=n}handle(e,t){var n=this;return r((function*(){var r=t.key;if(n.log("%p asked us to store value for key %b",e,r),null==t.record){var i="Empty record from: ".concat(e.toString());throw n.log.error(i),new Wa(i)}try{var o=KL.deserialize(t.record);yield iM(n.validators,o),o.timeReceived=new Date;var a=pM(n.datastorePrefix,o.key);yield n.components.datastore.put(a,o.serialize().subarray()),n.log("put record for %b into datastore under key %k",r,a)}catch(e){n.log("did not put record for key %b into datastore %o",r,e)}return t}))()}}class uU{constructor(t,r){var n,i;e(this,"handlers",void 0),e(this,"routingTable",void 0),e(this,"log",void 0),e(this,"metrics",void 0),this.metrics={operations:null===(n=t.metrics)||void 0===n?void 0:n.registerCounterGroup("".concat(r.metricsPrefix,"_inbound_rpc_requests_total")),errors:null===(i=t.metrics)||void 0===i?void 0:i.registerCounterGroup("".concat(r.metricsPrefix,"_inbound_rpc_errors_total"))},this.log=t.logger.forComponent("".concat(r.logPrefix,":rpc")),this.routingTable=r.routingTable,this.handlers={[DL.GET_VALUE.toString()]:new aU(t,r),[DL.PUT_VALUE.toString()]:new lU(t,r),[DL.FIND_NODE.toString()]:new iU(t,r),[DL.ADD_PROVIDER.toString()]:new nU(t,r),[DL.GET_PROVIDERS.toString()]:new oU(t,r),[DL.PING.toString()]:new sU(t,r)}}handleMessage(e,t){var n=this;return r((function*(){var r=n.handlers[t.type];if(null!=r)try{var i;return null===(i=n.metrics.operations)||void 0===i||i.increment({[t.type]:!0}),yield r.handle(e,t)}catch(e){var o;null===(o=n.metrics.errors)||void 0===o||o.increment({[t.type]:!0})}else n.log.error("no handler found for message type: ".concat(t.type))}))()}onIncomingStream(e){var t=this,n="unknown";Promise.resolve().then(r((function*(){var{stream:r,connection:i}=e,o=i.remotePeer,a=t;yield Fc(r,(e=>Ep(e)),function(){var e=l((function*(e){var t,r=!1,i=!1;try{for(var l,c=s(e);r=!(l=yield u(c.next())).done;r=!1){var d=l.value,h=UL.decode(d);n=h.type,a.log("incoming %s from %p",h.type,o);var v=yield u(a.handleMessage(o,h));null!=v&&(yield UL.encode(v))}}catch(e){i=!0,t=e}finally{try{r&&null!=c.return&&(yield u(c.return()))}finally{if(i)throw t}}}));return function(t){return e.apply(this,arguments)}}(),(e=>bp(e)),r)}))).catch((t=>{this.log.error("error handling %s RPC message from %p - %e",n,e.connection.remotePeer,t)}))}}class cU extends os{constructor(t,r){super(),e(this,"log",void 0),e(this,"components",void 0),e(this,"protocol",void 0),e(this,"running",void 0),e(this,"registrarId",void 0);var{protocol:n,logPrefix:i}=r;this.components=t,this.log=t.logger.forComponent("".concat(i,":topology-listener")),this.running=!1,this.protocol=n}isStarted(){return this.running}start(){var e=this;return r((function*(){e.running||(e.running=!0,e.registrarId=yield e.components.registrar.register(e.protocol,{onConnect:t=>{e.log("observed peer %p with protocol %s",t,e.protocol),e.dispatchEvent(new CustomEvent("peer",{detail:t}))}}))}))()}stop(){var e=this;return r((function*(){e.running=!1,null!=e.registrarId&&(e.components.registrar.unregister(e.registrarId),e.registrarId=void 0)}))()}}class dU{constructor(t){e(this,"dht",void 0),this.dht=t}provide(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};yield uc(n.dht.provide(e,r))}))()}cancelReprovide(e){var t=this;return r((function*(){yield t.dht.cancelReprovide(e)}))()}findProviders(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var n,i=!1,o=!1;try{for(var a,l=s(t.dht.findProviders(e,r));i=!(a=yield u(l.next())).done;i=!1){var d=a.value;"PROVIDER"===d.name&&(yield*c(s(d.providers),u))}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}()})).apply(this,arguments)}put(e,t,n){var i=this;return r((function*(){yield uc(i.dht.put(e,t,n))}))()}get(e,t){var n=this;return r((function*(){var r,i=!1,o=!1;try{for(var a,l=s(n.dht.get(e,t));i=!(a=yield l.next()).done;i=!1){var u=a.value;if("VALUE"===u.name)return u.value}}catch(e){o=!0,r=e}finally{try{i&&null!=l.return&&(yield l.return())}finally{if(o)throw r}}throw new za("Could not find value for key")}))()}}class hU{constructor(t){e(this,"dht",void 0),this.dht=t}findPeer(e){var t=arguments,n=this;return r((function*(){var r,i=t.length>1&&void 0!==t[1]?t[1]:{},o=!1,a=!1;try{for(var l,u=s(n.dht.findPeer(e,i));o=!(l=yield u.next()).done;o=!1){var c=l.value;if("FINAL_PEER"===c.name)return c.peer}}catch(e){a=!0,r=e}finally{try{o&&null!=u.return&&(yield u.return())}finally{if(a)throw r}}throw new za("Peer not found")}))()}getClosestPeers(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var n,i=!1,o=!1;try{for(var a,l=s(t.dht.getClosestPeers(e,r));i=!(a=yield u(l.next())).done;i=!1){var c=a.value;"FINAL_PEER"===c.name&&(yield c.peer)}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}()})).apply(this,arguments)}}var vU;class pU extends os{constructor(n){var i,o,a,s,l,u,c,d,h,v,p,f,g,y,m=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),y=this,e(this,"protocol",void 0),e(this,"routingTable",void 0),e(this,"providers",void 0),e(this,"network",void 0),e(this,"peerRouting",void 0),e(this,"components",void 0),e(this,"log",void 0),e(this,"running",void 0),e(this,"kBucketSize",void 0),e(this,"clientMode",void 0),e(this,"validators",void 0),e(this,"selectors",void 0),e(this,"queryManager",void 0),e(this,"contentFetching",void 0),e(this,"contentRouting",void 0),e(this,"routingTableRefresh",void 0),e(this,"rpc",void 0),e(this,"topologyListener",void 0),e(this,"querySelf",void 0),e(this,"maxInboundStreams",void 0),e(this,"maxOutboundStreams",void 0),e(this,"dhtContentRouting",void 0),e(this,"dhtPeerRouting",void 0),e(this,"peerInfoMapper",void 0),e(this,"reprovider",void 0),e(this,Symbol.toStringTag,"@libp2p/kad-dht"),e(this,ds,["@libp2p/content-routing","@libp2p/peer-routing","@libp2p/peer-discovery"]),e(this,hs,["@libp2p/identify"]);var w=null!==(i=m.logPrefix)&&void 0!==i?i:"libp2p:kad-dht",b=null!==(o=m.datastorePrefix)&&void 0!==o?o:"/dht",S=null!==(a=m.metricsPrefix)&&void 0!==a?a:"libp2p_kad_dht",E={queries:null===(s=n.metrics)||void 0===s?void 0:s.registerMetricGroup("".concat(S,"_operations_total"),{label:"operation"}),errors:null===(l=n.metrics)||void 0===l?void 0:l.registerCounterGroup("".concat(S,"_operation_errors_total"),{label:"operation"}),queryTime:null===(u=n.metrics)||void 0===u?void 0:u.registerMetricGroup("".concat(S,"_operation_time_seconds"),{label:"operation"}),errorTime:null===(c=n.metrics)||void 0===c?void 0:c.registerMetricGroup("".concat(S,"_operation_error_time_seconds"),{label:"operation"})};this.running=!1,this.components=n,this.log=n.logger.forComponent(w),this.protocol=null!==(d=m.protocol)&&void 0!==d?d:"/ipfs/kad/1.0.0",this.kBucketSize=null!==(h=m.kBucketSize)&&void 0!==h?h:20,this.clientMode=null===(v=m.clientMode)||void 0===v||v,this.maxInboundStreams=null!==(p=m.maxInboundStreams)&&void 0!==p?p:32,this.maxOutboundStreams=null!==(f=m.maxOutboundStreams)&&void 0!==f?f:64,this.peerInfoMapper=null!==(g=m.peerInfoMapper)&&void 0!==g?g:uM;var k=LB();this.providers=new FM(n,t(t({},m.providers),{},{logPrefix:w,datastorePrefix:b,lock:k})),this.validators=t(t({},sM),m.validators),this.selectors=t(t({},nM),m.selectors),this.network=new OM(n,{protocol:this.protocol,logPrefix:w,metricsPrefix:S}),this.routingTable=new eU(n,{kBucketSize:m.kBucketSize,pingOldContactTimeout:m.pingOldContactTimeout,pingOldContactConcurrency:m.pingOldContactConcurrency,pingOldContactMaxQueueSize:m.pingOldContactMaxQueueSize,pingNewContactTimeout:m.pingNewContactTimeout,pingNewContactConcurrency:m.pingNewContactConcurrency,pingNewContactMaxQueueSize:m.pingNewContactMaxQueueSize,protocol:this.protocol,logPrefix:w,metricsPrefix:S,prefixLength:m.prefixLength,splitThreshold:m.kBucketSplitThreshold,network:this.network});var x=Cc();!0===m.allowQueryWithZeroPeers&&x.resolve(),this.queryManager=new jM(n,{disjointPaths:Math.ceil(this.kBucketSize/2),logPrefix:w,metricsPrefix:S,initialQuerySelfHasRun:x,routingTable:this.routingTable}),this.peerRouting=new UM(n,{routingTable:this.routingTable,network:this.network,validators:this.validators,queryManager:this.queryManager,logPrefix:w}),this.contentFetching=new SM(n,{validators:this.validators,selectors:this.selectors,peerRouting:this.peerRouting,queryManager:this.queryManager,network:this.network,logPrefix:w,datastorePrefix:b}),this.contentRouting=new kM(n,{network:this.network,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,providers:this.providers,logPrefix:w}),this.routingTableRefresh=new rU(n,{peerRouting:this.peerRouting,routingTable:this.routingTable,logPrefix:w}),this.rpc=new uU(n,{routingTable:this.routingTable,providers:this.providers,peerRouting:this.peerRouting,validators:this.validators,logPrefix:w,metricsPrefix:S,datastorePrefix:b,peerInfoMapper:this.peerInfoMapper}),this.topologyListener=new cU(n,{protocol:this.protocol,logPrefix:w}),this.querySelf=new HM(n,{peerRouting:this.peerRouting,interval:m.querySelfInterval,initialInterval:m.initialQuerySelfInterval,logPrefix:w,initialQuerySelfHasRun:x,routingTable:this.routingTable,operationMetrics:E}),this.reprovider=new KM(n,t(t({},m.reprovide),{},{logPrefix:w,metricsPrefix:S,datastorePrefix:b,contentRouting:this.contentRouting,lock:k,operationMetrics:E})),this.network.addEventListener("peer",(e=>{var t=e.detail;this.onPeerConnect(t).catch((e=>{this.log.error("could not add %p to routing table",t.id,e)})),this.dispatchEvent(new CustomEvent("peer",{detail:t}))})),this.topologyListener.addEventListener("peer",(e=>{var t=e.detail;Promise.resolve().then(r((function*(){var e=yield y.components.peerStore.get(t),r={id:t,multiaddrs:e.addresses.map((e=>{var{multiaddr:t}=e;return t})),protocols:e.protocols};yield y.onPeerConnect(r)}))).catch((e=>{this.log.error("could not add %p to routing table - %e",t,e)}))})),this.dhtPeerRouting=new hU(this),this.dhtContentRouting=new dU(this),null==m.clientMode&&n.events.addEventListener("self:peer:update",(e=>{this.log("received update of self-peer info"),Promise.resolve().then(r((function*(){var t=e.detail.peer.addresses.some((e=>{var{multiaddr:t}=e;return function(e){var t=e.stringTuples();for(var r of t)if(290===r[0])return!1;if(54===t[0][0]||55===t[0][0]||56===t[0][0])return!0;if(4===t[0][0]||41===t[0][0]){var n=lD("".concat(t[0][1]));return null==n||!n}return!1}(t)})),r=y.getMode();t&&"client"===r?yield y.setMode("server"):"server"!==r||t||(yield y.setMode("client"))}))).catch((e=>{this.log.error("error setting dht server mode",e)}))})),this.get=wM(this.get.bind(this),E,"GET_VALUE"),this.findProviders=wM(this.findProviders.bind(this),E,"FIND_PROVIDERS"),this.findPeer=wM(this.findPeer.bind(this),E,"FIND_PEER"),this.getClosestPeers=wM(this.getClosestPeers.bind(this),E,"GET_CLOSEST_PEERS"),this.provide=wM(this.provide.bind(this),E,"PROVIDE"),this.put=wM(this.put.bind(this),E,"PUT_VALUE")}get[wa](){return this.dhtContentRouting}get[xa](){return this.dhtPeerRouting}get[ba](){return this}onPeerConnect(e){var t=this;return r((function*(){if(t.log.trace("peer %p connected",e.id),0!==(e=t.peerInfoMapper(e)).multiaddrs.length)try{yield t.routingTable.add(e.id)}catch(r){t.log.error("could not add %p to routing table",e.id,r)}else t.log.trace("ignoring %p as there were no valid addresses in %s after filtering",e.id,e.multiaddrs.map((e=>e.toString())))}))()}isStarted(){return this.running}getMode(){return this.clientMode?"client":"server"}setMode(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]&&t[1];e!==n.getMode()||r?(yield n.components.registrar.unhandle(n.protocol),e!==n.getMode()||r?"client"===e?(n.log("enabling client mode while in %s mode",n.getMode()),n.clientMode=!0):(n.log("enabling server mode while in %s mode",n.getMode()),n.clientMode=!1,yield n.components.registrar.handle(n.protocol,n.rpc.onIncomingStream.bind(n.rpc),{maxInboundStreams:n.maxInboundStreams,maxOutboundStreams:n.maxOutboundStreams})):n.log("already in %s mode",e)):n.log("already in %s mode",e)}))()}start(){var e=this;return r((function*(){e.running||(e.running=!0,yield e.setMode(e.clientMode?"client":"server",!0),yield ss(e.routingTable,e.queryManager,e.network,e.topologyListener,e.routingTableRefresh,e.reprovider),yield ss(e.querySelf))}))()}stop(){var e=this;return r((function*(){e.running=!1,yield us(e.querySelf,e.queryManager,e.network,e.routingTable,e.routingTableRefresh,e.topologyListener,e.reprovider)}))()}put(e,t){var r=this;return l((function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){yield*c(s(r.contentFetching.put(e,t,n)))}()})).apply(this,arguments)}get(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(t.contentFetching.get(e,r)))}()})).apply(this,arguments)}provide(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(t.contentRouting.provide(e,t.components.addressManager.getAddresses(),r)))}()})).apply(this,arguments)}cancelReprovide(e){var t=this;return r((function*(){yield t.providers.removeProvider(e,t.components.peerId)}))()}findProviders(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(t.contentRouting.findProviders(e,r)))}()})).apply(this,arguments)}findPeer(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(t.peerRouting.findPeer(e,r)))}()})).apply(this,arguments)}getClosestPeers(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(t.peerRouting.getClosestPeers(e,r)))}()})).apply(this,arguments)}refreshRoutingTable(){var e=this;return r((function*(){e.routingTableRefresh.refreshTable(!0)}))()}}function fU(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new pU(t,e)}function gU(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"}(vU||(vU={}));var{hasOwnProperty:yU}=Object.prototype,{propertyIsEnumerable:mU}=Object,wU=(e,t,r)=>{Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})},bU={concatArrays:!1,ignoreUndefined:!1},SU=e=>{var t=[];for(var r in e)yU.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);for(var i of n)mU.call(e,i)&&t.push(i)}return t};function EU(e){return Array.isArray(e)?(r=(t=e).slice(0,0),SU(t).forEach((e=>{wU(r,e,EU(t[e]))})),r):gU(e)?function(e){var t=null===Object.getPrototypeOf(e)?Object.create(null):{};return SU(e).forEach((r=>{wU(t,r,EU(e[r]))})),t}(e):e;var t,r}var kU,xU,AU,CU,IU,TU,PU,_U,BU=(e,t,r,n)=>(r.forEach((r=>{void 0===t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?wU(e,r,DU(e[r],t[r],n)):wU(e,r,EU(t[r])))})),e),NU=(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++)yU.call(t,a)&&(o.push(String(a)),wU(n,i++,t===e?t[a]:EU(t[a])));n=BU(n,t,SU(t).filter((e=>!o.includes(e))),r)})),n};function DU(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?NU(e,t,r):gU(t)&&gU(e)?BU(e,t,SU(t),r):EU(t)}function RU(){for(var e=DU(EU(bU),undefined!==this&&this||{},bU),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(!gU(o))throw new TypeError("`"+o+"` is not an Option Object");t=DU(t,{_:o},e)}return t._}function OU(){if(xU)return kU;function e(e){return e>=55296&&e<=56319}function t(e){return e>=56320&&e<=57343}return xU=1,kU=function(r,n,i){if("string"!=typeof n)throw new Error("Input must be string");for(var o,a,s=n.length,l=0,u=0;u<s;u+=1){if(o=n.charCodeAt(u),a=n[u],e(o)&&t(n.charCodeAt(u+1))&&(a+=n[u+=1]),(l+=r(a))===i)return n.slice(0,u+1);if(l>i)return n.slice(0,u-a.length+1)}return n},kU}function LU(){if(TU)return IU;TU=1;var e=OU(),t=function(){if(CU)return AU;function e(e){return e>=55296&&e<=56319}function t(e){return e>=56320&&e<=57343}return CU=1,AU=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},AU}();return IU=e.bind(null,t)}var MU=function(){if(_U)return PU;_U=1;var e=LU(),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 PU=function(e,t){var r=t&&t.replacement||"",n=a(e,r);return""===r?n:a(n,"")},PU}(),UU=a(MU),FU={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function zU(e){var t="AES-GCM",n=16,i=12,o="SHA-256",a=16,s=32767,l=Zl.get();function u(){return(u=r((function*(e,r){var u,c=l.getRandomValues(new Uint8Array(a)),d=l.getRandomValues(new Uint8Array(i)),h={name:t,iv:d};if("string"==typeof r&&(r=Et(r)),0===r.length){u=yield l.subtle.importKey("jwk",FU,{name:"AES-GCM"},!0,["encrypt"]);try{var v={name:"PBKDF2",salt:c,iterations:s,hash:{name:o}},p=yield l.subtle.importKey("raw",r,{name:"PBKDF2"},!1,["deriveKey"]);u=yield l.subtle.deriveKey(v,p,{name:t,length:n},!0,["encrypt"])}catch(e){u=yield l.subtle.importKey("jwk",FU,{name:"AES-GCM"},!0,["encrypt"])}}else{var f={name:"PBKDF2",salt:c,iterations:s,hash:{name:o}},g=yield l.subtle.importKey("raw",r,{name:"PBKDF2"},!1,["deriveKey"]);u=yield l.subtle.deriveKey(f,g,{name:t,length:n},!0,["encrypt"])}var y=yield l.subtle.encrypt(h,u,e);return Mt([c,h.iv,new Uint8Array(y)])}))).apply(this,arguments)}function c(){return(c=r((function*(e,r){var u,c=e.subarray(0,a),d=e.subarray(a,a+i),h=e.subarray(a+i),v={name:t,iv:d};if("string"==typeof r&&(r=Et(r)),0===r.length)try{var p={name:"PBKDF2",salt:c,iterations:s,hash:{name:o}},f=yield l.subtle.importKey("raw",r,{name:"PBKDF2"},!1,["deriveKey"]);u=yield l.subtle.deriveKey(p,f,{name:t,length:n},!0,["decrypt"])}catch(e){u=yield l.subtle.importKey("jwk",FU,{name:"AES-GCM"},!0,["decrypt"])}else{var g={name:"PBKDF2",salt:c,iterations:s,hash:{name:o}},y=yield l.subtle.importKey("raw",r,{name:"PBKDF2"},!1,["deriveKey"]);u=yield l.subtle.deriveKey(g,y,{name:t,length:n},!0,["decrypt"])}var m=yield l.subtle.decrypt(v,u,h);return new Uint8Array(m)}))).apply(this,arguments)}n*=8;var d={encrypt:function(e,t){return u.apply(this,arguments)},decrypt:function(e,t){return c.apply(this,arguments)}};return d}var jU=1e4;function VU(e,t){return qU.apply(this,arguments)}function qU(){return(qU=r((function*(e,t){var r=zU(),n=yield r.encrypt(e,t);return se.encode(n)}))).apply(this,arguments)}function HU(e,t,r){return KU.apply(this,arguments)}function KU(){return KU=r((function*(e,t,r){if("RSA"===e.type)return function(e,t){return YU.apply(this,arguments)}(e,t,r);if("Ed25519"===e.type)return function(e,t){return WU.apply(this,arguments)}(e,t,r);if("secp256k1"===e.type)return function(e,t){return GU.apply(this,arguments)}(e,t,r);if("ECDSA"===e.type)return function(e,t){return QU.apply(this,arguments)}(e,t,r);throw new rs})),KU.apply(this,arguments)}function WU(){return WU=r((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"libp2p-key";if("libp2p-key"===r)return VU(xu(e),t);throw new _a("export format '".concat(r,"' is not supported"))})),WU.apply(this,arguments)}function GU(){return GU=r((function*(e,t){if("libp2p-key"===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:"libp2p-key"))return VU(xu(e),t);throw new _a("Export format is not supported")})),GU.apply(this,arguments)}function QU(){return QU=r((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"libp2p-key";if("libp2p-key"===r)return VU(xu(e),t);throw new _a("export format '".concat(r,"' is not supported"))})),QU.apply(this,arguments)}function YU(){return YU=r((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"pkcs-8";if("pkcs-8"===r)return function(e,t){return JU.apply(this,arguments)}(e,t);if("libp2p-key"===r)return VU(xu(e),t);throw new _a("Export format is not supported")})),YU.apply(this,arguments)}function JU(){return(JU=r((function*(e,t){var r=Zl.get(),n=new _g({value:[new Eg({value:0}),new _g({value:[new Cg({value:"1.2.840.113549.1.1.1"}),new rg]}),new sg({valueHex:e.raw})]}).toBER(),i=new Uint8Array(n,0,n.byteLength),o=Gl(16),a=yield Xo(Jo,t,o,{c:jU,dkLen:32}),s=Gl(16),l=yield r.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),u=yield r.subtle.encrypt({name:"AES-CBC",iv:s},l,i),c=new _g({value:[new sg({valueHex:o}),new Eg({value:jU}),new Eg({value:32}),new _g({value:[new Cg({value:"1.2.840.113549.2.11"}),new rg]})]}),d=new _g({value:[new Cg({value:"1.2.840.113549.1.5.13"}),new _g({value:[new _g({value:[new Cg({value:"1.2.840.113549.1.5.12"}),c]}),new _g({value:[new Cg({value:"2.16.840.1.101.3.4.1.42"}),new sg({valueHex:s})]})]})]}),h=new _g({value:[d,new sg({valueHex:u})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...gt(new Uint8Array(h,0,h.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}))).apply(this,arguments)}function ZU(e,t){return $U.apply(this,arguments)}function $U(){return $U=r((function*(e,t){try{var r=yield function(e,t){return XU.apply(this,arguments)}(e,t);return Eu(r)}catch(e){}if(!e.includes("BEGIN"))throw new _a("Encrypted key was not a libp2p-key or a PEM file");return function(e,t){return eF.apply(this,arguments)}(e,t)})),$U.apply(this,arguments)}function XU(){return(XU=r((function*(e,t){var r=se.decode(e);return zU().decrypt(r,t)}))).apply(this,arguments)}function eF(){return(eF=r((function*(e,t){var r,n=Zl.get();if(e.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){var i=Et(e.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:o}=Jf(i),{iv:a,salt:s,iterations:l,keySize:u,cipherText:c}=function(e){var t=e.valueBlock.value[0];if("OBJECT IDENTIFIER : 1.2.840.113549.1.5.13"!==t.valueBlock.value[0].toString())throw new _a("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 _a("Only pkcs5PBKDF2 key derivation functions are supported");var n=r.valueBlock.value[1],i=rF(n.valueBlock.value[0].getValue()),o=jU,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 _a("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 _a("Only AES-CBC encryption schemes are supported");var u=rF(s.valueBlock.value[1].getValue());return{cipherText:rF(e.valueBlock.value[1].getValue()),salt:i,iterations:o,keySize:a,iv:u}}(o),d=yield Xo(Jo,t,s,{c:l,dkLen:u}),h=yield n.subtle.importKey("raw",d,"AES-CBC",!1,["decrypt"]),v=rF(yield n.subtle.decrypt({name:"AES-CBC",iv:a},h,c)),{result:p}=Jf(v);r=tF(p)}else{if(!e.includes("-----BEGIN PRIVATE KEY-----"))throw new _a("Could not parse private key from PEM data");var f=Et(e.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:g}=Jf(f);r=tF(g)}var y=ku(r);if("RSA"!==y.type)throw new _a("Could not parse RSA private key from PEM data");return y}))).apply(this,arguments)}function tF(e){return rF(e.valueBlock.value[2].getValue())}function rF(e){return new Uint8Array(e,0,e.byteLength)}var nF,iF="/info/",oF=new WeakMap,aF=14,sF=16,lF=1e3,uF={dek:{keyLength:64,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function cF(e){return null!=e&&("string"==typeof e&&(e===UU(e.trim())&&e.length>0))}function dF(){return hF.apply(this,arguments)}function hF(){return hF=r((function*(){var e=800*Math.random()+200;yield new Promise((t=>setTimeout(t,e)))})),hF.apply(this,arguments)}function vF(e){return new lc("/pkcs8/"+e)}function pF(e){return new lc(iF+e)}function fF(){return(fF=r((function*(e){var t=xu(e),r=yield $e.digest(t);return ie.encode(r.bytes).substring(1)}))).apply(this,arguments)}class gF{constructor(t,r){var n,i,o,a,s,l,u,c,d,h;if(e(this,"components",void 0),e(this,"init",void 0),e(this,"log",void 0),e(this,"self",void 0),e(this,Symbol.toStringTag,"@libp2p/keychain"),e(this,ds,["@libp2p/keychain"]),this.components=t,this.log=t.logger.forComponent("libp2p:keychain"),this.init=RU(uF,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<aF)throw new Error("dek.keyLength must be least ".concat(aF," 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<sF)throw new Error("dek.saltLength must be least ".concat(sF," bytes"));if(null!=(null===(s=this.init.dek)||void 0===s?void 0:s.iterationCount)&&this.init.dek.iterationCount<lF)throw new Error("dek.iterationCount must be least ".concat(lF));var v=null!=this.init.pass&&null!=(null===(l=this.init.dek)||void 0===l?void 0:l.salt)?ic(this.init.pass,null===(u=this.init.dek)||void 0===u?void 0:u.salt,null===(c=this.init.dek)||void 0===c?void 0:c.iterationCount,null===(d=this.init.dek)||void 0===d?void 0:d.keyLength,null===(h=this.init.dek)||void 0===h?void 0:h.hash):"";oF.set(this,{dek:v})}static generateOptions(){var e=Object.assign({},uF),t=3*Math.ceil(sF/3);return e.dek.salt=gt(Gl(t),"base64"),e}static get options(){return uF}findKeyByName(e){var t=this;return r((function*(){if(!cF(e))throw yield dF(),new _a("Invalid key name '".concat(e,"'"));var r=pF(e);try{var n=yield t.components.datastore.get(r);return JSON.parse(gt(n))}catch(r){throw yield dF(),t.log.error(r),new za("Key '".concat(e,"' does not exist."))}}))()}findKeyById(e){var t=this;return r((function*(){try{var r,n={prefix:iF},i=!1,o=!1;try{for(var a,l=s(t.components.datastore.query(n));i=!(a=yield l.next()).done;i=!1){var u=a.value,c=JSON.parse(gt(u.value));if(c.id===e)return c}}catch(e){o=!0,r=e}finally{try{i&&null!=l.return&&(yield l.return())}finally{if(o)throw r}}throw new _a("Key with id '".concat(e,"' does not exist."))}catch(e){throw yield dF(),e}}))()}importKey(e,t){var n=this;return r((function*(){if(!cF(e))throw yield dF(),new _a("Invalid key name '".concat(e,"'"));if(null==t)throw yield dF(),new _a("Key is required");var r,i,o=vF(e);if(yield n.components.datastore.has(o))throw yield dF(),new _a("Key '".concat(e,"' already exists"));try{r=yield function(e){return fF.apply(this,arguments)}(t);var a=oF.get(n);if(null==a)throw new _a("dek missing");var s=a.dek;i=yield HU(t,s,"RSA"===t.type?"pkcs-8":"libp2p-key")}catch(e){throw yield dF(),e}var l={name:e,id:r},u=n.components.datastore.batch();return u.put(o,Et(i)),u.put(pF(e),Et(JSON.stringify(l))),yield u.commit(),l}))()}exportKey(e){var t=this;return r((function*(){if(!cF(e))throw yield dF(),new _a("Invalid key name '".concat(e,"'"));var r=vF(e);try{var n=gt(yield t.components.datastore.get(r)),i=oF.get(t);if(null==i)throw new _a("dek missing");var o=i.dek;return yield ZU(n,o)}catch(e){throw yield dF(),e}}))()}removeKey(e){var t=this;return r((function*(){if(!cF(e)||e===t.self)throw yield dF(),new _a("Invalid key name '".concat(e,"'"));var r=vF(e),n=yield t.findKeyByName(e),i=t.components.datastore.batch();return i.delete(r),i.delete(pF(e)),yield i.commit(),n}))()}listKeys(){var e=this;return r((function*(){var t,r={prefix:iF},n=[],i=!1,o=!1;try{for(var a,l=s(e.components.datastore.query(r));i=!(a=yield l.next()).done;i=!1){var u=a.value;n.push(JSON.parse(gt(u.value)))}}catch(e){o=!0,t=e}finally{try{i&&null!=l.return&&(yield l.return())}finally{if(o)throw t}}return n}))()}renameKey(e,t){var n=this;return r((function*(){if(!cF(e)||e===n.self)throw yield dF(),new _a("Invalid old key name '".concat(e,"'"));if(!cF(t)||t===n.self)throw yield dF(),new _a("Invalid new key name '".concat(t,"'"));var r=vF(e),i=vF(t),o=pF(e),a=pF(t);if(yield n.components.datastore.has(i))throw yield dF(),new _a("Key '".concat(t,"' already exists"));try{var s=yield n.components.datastore.get(r),l=yield n.components.datastore.get(o),u=JSON.parse(gt(l));u.name=t;var c=n.components.datastore.batch();return c.put(i,s),c.put(a,Et(JSON.stringify(u))),c.delete(r),c.delete(o),yield c.commit(),u}catch(e){throw yield dF(),e}}))()}rotateKeychainPass(e,t){var n=this;return r((function*(){var r,i,o,a;if("string"!=typeof e)throw yield dF(),new _a("Invalid old pass type '".concat(typeof e,"'"));if("string"!=typeof t)throw yield dF(),new _a("Invalid new pass type '".concat(typeof t,"'"));if(t.length<20)throw yield dF(),new _a("Invalid pass length ".concat(t.length));n.log("recreating keychain");var s=oF.get(n);if(null==s)throw new _a("dek missing");var l=s.dek;n.init.pass=t;var u=null!=t&&null!=(null===(r=n.init.dek)||void 0===r?void 0:r.salt)?ic(t,n.init.dek.salt,null===(i=n.init.dek)||void 0===i?void 0:i.iterationCount,null===(o=n.init.dek)||void 0===o?void 0:o.keyLength,null===(a=n.init.dek)||void 0===a?void 0:a.hash):"";oF.set(n,{dek:u});var c=yield n.listKeys();for(var d of c){var h=gt(yield n.components.datastore.get(vF(d.name))),v=yield ZU(h,l),p=u.toString(),f=yield HU(v,p,"RSA"===v.type?"pkcs-8":"libp2p-key"),g=n.components.datastore.batch(),y={name:d.name,id:d.id};g.put(vF(d.name),Et(f)),g.put(pF(d.name),Et(JSON.stringify(y))),yield g.commit()}n.log("keychain reconstructed")}))()}}function yF(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new gF(t,e)}class mF{constructor(){var t,r,n,i,o,a,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e(this,"memoryStorage",void 0),e(this,"points",void 0),e(this,"duration",void 0),e(this,"blockDuration",void 0),e(this,"execEvenly",void 0),e(this,"execEvenlyMinDelayMs",void 0),e(this,"keyPrefix",void 0),this.points=null!==(t=s.points)&&void 0!==t?t:4,this.duration=null!==(r=s.duration)&&void 0!==r?r:1,this.blockDuration=null!==(n=s.blockDuration)&&void 0!==n?n:0,this.execEvenly=null!==(i=s.execEvenly)&&void 0!==i&&i,this.execEvenlyMinDelayMs=null!==(o=s.execEvenlyMinDelayMs)&&void 0!==o?o:1e3*this.duration/this.points,this.keyPrefix=null!==(a=s.keyPrefix)&&void 0!==a?a:"rlflx",this.memoryStorage=new wF}consume(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:1,i=t.length>2&&void 0!==t[2]?t[2]:{},o=n.getKey(e),a=n._getKeySecDuration(i),s=n.memoryStorage.incrby(o,r,a);if(s.remainingPoints=Math.max(n.points-s.consumedPoints,0),s.consumedPoints>n.points)throw n.blockDuration>0&&s.consumedPoints<=n.points+r&&(s=n.memoryStorage.set(o,s.consumedPoints,n.blockDuration)),new dv("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 uL(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 wF{constructor(){e(this,"storage",void 0),this.storage=new Map}incrby(e,t,r){var n=this.storage.get(e);if(null!=n){var i=null!=n.expiresAt?n.expiresAt.getTime()-(new Date).getTime():-1;return null==n.expiresAt||i>0?(n.value+=t,{remainingPoints:0,msBeforeNext:i,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,r)}return this.set(e,t,r)}set(e,t,r){var n=1e3*r,i=this.storage.get(e);null!=i&&clearTimeout(i.timeoutId);var o={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,o),n>0&&(o.timeoutId=setTimeout((()=>{this.storage.delete(e)}),n),null!=o.timeoutId.unref&&o.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:o.value,isFirstInDuration:!0}}get(e){var t=this.storage.get(e);if(null!=t)return{remainingPoints:0,msBeforeNext:null!=t.expiresAt?t.expiresAt.getTime()-(new Date).getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){var t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}}!function(e){e[e.NEW_STREAM=0]="NEW_STREAM",e[e.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",e[e.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",e[e.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",e[e.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",e[e.RESET_RECEIVER=5]="RESET_RECEIVER",e[e.RESET_INITIATOR=6]="RESET_INITIATOR"}(nF||(nF={}));var bF=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),SF=Object.freeze({NEW_STREAM:nF.NEW_STREAM,MESSAGE:nF.MESSAGE_INITIATOR,CLOSE:nF.CLOSE_INITIATOR,RESET:nF.RESET_INITIATOR}),EF=Object.freeze({MESSAGE:nF.MESSAGE_RECEIVER,CLOSE:nF.CLOSE_RECEIVER,RESET:nF.RESET_RECEIVER}),kF=1<<20;class xF{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:kF,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4194304;e(this,"_buffer",void 0),e(this,"_headerInfo",void 0),e(this,"_maxMessageSize",void 0),e(this,"_maxUnprocessedMessageQueueSize",void 0),this._buffer=new gs,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 Wa("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!==nF.NEW_STREAM&&n!==nF.MESSAGE_INITIATOR&&n!==nF.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}=IF(e),{value:n,offset:i}=IF(e,r),o=7&t;if(null==bF[o])throw new Error("Invalid type received: ".concat(o));if(n>this._maxMessageSize)throw new Wa("Message size too large");return{id:t>>3,type:o,offset:r+i,length:n}}}var AF=128,CF=127;function IF(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&CF)<<i:(t&CF)*Math.pow(2,i),i+=7}while(t>=AF);return{value:n,offset:r=o-r}}var TF=10240;var PF=new class{constructor(){e(this,"_pool",void 0),e(this,"_poolOffset",void 0),this._pool=dt(TF),this._poolOffset=0}write(e,t){var r=this._pool,n=this._poolOffset;Ot(e.id<<3|e.type,r,n),n+=Nt(e.id<<3|e.type),e.type!==nF.NEW_STREAM&&e.type!==nF.MESSAGE_INITIATOR&&e.type!==nF.MESSAGE_RECEIVER||null==e.data?(Ot(0,r,n),n+=Nt(0)):(Ot(e.data.length,r,n),n+=Nt(e.data.length));var i=r.subarray(this._poolOffset,n);TF-n<100?(this._pool=dt(TF),this._poolOffset=0):this._poolOffset=n,t.append(i),e.type!==nF.NEW_STREAM&&e.type!==nF.MESSAGE_INITIATOR&&e.type!==nF.MESSAGE_RECEIVER||null==e.data||t.append(e.data)}};function _F(){return _F=l((function*(e){var t,r=!1,n=!1;try{for(var i,o=s(e);r=!(i=yield u(o.next())).done;r=!1){var a=i.value,l=new gs;PF.write(a,l),yield l}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw t}}})),_F.apply(this,arguments)}class BF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Stream input buffer error"),this.name="StreamInputBufferError"}}class NF extends cp{constructor(t){super(t),e(this,"name",void 0),e(this,"streamId",void 0),e(this,"send",void 0),e(this,"types",void 0),e(this,"maxDataSize",void 0),this.types="outbound"===t.direction?SF:EF,this.send=t.send,this.name=t.name,this.streamId=t.streamId,this.maxDataSize=t.maxDataSize}sendNewStream(){var e=this;return r((function*(){yield e.send({id:e.streamId,type:SF.NEW_STREAM,data:new gs(Et(e.name))})}))()}sendData(e){var t=this;return r((function*(){for(e=e.sublist();e.byteLength>0;){var r=Math.min(e.byteLength,t.maxDataSize);yield t.send({id:t.streamId,type:t.types.MESSAGE,data:e.sublist(0,r)}),e.consume(r)}}))()}sendReset(){var e=this;return r((function*(){yield e.send({id:e.streamId,type:e.types.RESET})}))()}sendCloseWrite(){var e=this;return r((function*(){yield e.send({id:e.streamId,type:e.types.CLOSE})}))()}sendCloseRead(){return r((function*(){}))()}}function DF(e){var r=t(t({},e),{},{type:"".concat(bF[e.type]," (").concat(e.type,")")});return e.type===nF.NEW_STREAM&&(r.data=gt(e.data instanceof Uint8Array?e.data:e.data.subarray())),e.type!==nF.MESSAGE_INITIATOR&&e.type!==nF.MESSAGE_RECEIVER||(r.data=gt(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),r}class RF{constructor(t,r){var n,i;e(this,"protocol","/mplex/6.7.0"),e(this,"sink",void 0),e(this,"source",void 0),e(this,"log",void 0),e(this,"_streamId",void 0),e(this,"_streams",void 0),e(this,"_init",void 0),e(this,"_source",void 0),e(this,"closeController",void 0),e(this,"rateLimiter",void 0),e(this,"closeTimeout",void 0),e(this,"logger",void 0),r=null!=r?r:{},this.log=t.logger.forComponent("libp2p:mplex"),this.logger=t.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=r,this.closeTimeout=null!==(n=r.closeTimeout)&&void 0!==n?n:500,this.sink=this._createSink(),this._source=_c({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=Fc(this._source,(e=>function(e){return _F.apply(this,arguments)}(e))),this.closeController=new AbortController,this.rateLimiter=new mF({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 Ma("Muxer already closed");var t=this._streamId++;e=null==e?t.toString():e.toString();var r=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:r})}close(e){var t=this;return r((function*(){var n;if(!t.closeController.signal.aborted){var i=null!==(n=null==e?void 0:e.signal)&&void 0!==n?n:AbortSignal.timeout(t.closeTimeout);try{yield Promise.all(t.streams.map(function(){var e=r((function*(e){return e.close({signal:i})}));return function(t){return e.apply(this,arguments)}}())),t._source.end(),yield t._source.onEmpty({signal:i}),t.closeController.abort()}catch(e){t.abort(e)}}}))()}abort(e){this.closeController.signal.aborted||(this.streams.forEach((t=>{t.abort(e)})),this.closeController.abort(e))}_newReceiverStream(e){var{id:t,name:r}=e,n=this._streams.receivers;return this._newStream({id:t,name:r,type:"receiver",registry:n})}_newStream(e){var t,n=this,{id:i,name:o,type:a,registry:s}=e;if(this.log("new %s stream %s",a,i),"initiator"===a&&this._streams.initiators.size===(null!==(t=this._init.maxOutboundStreams)&&void 0!==t?t:1024))throw new ts("Too many outbound streams open");if(s.has(i))throw new Error("".concat(a," stream ").concat(i," already exists!"));var l=function(){var e=r((function*(e){n.log.enabled&&n.log.trace("%s stream %s send",a,i,DF(e)),n._source.push(e)}));return function(t){return e.apply(this,arguments)}}(),u=function(e){var{id:t,name:r,send:n,onEnd:i,type:o="initiator",maxMsgSize:a=kF}=e;return new NF({id:"initiator"===o?"i".concat(t):"r".concat(t),streamId:t,name:"".concat(null!=r?r:t),direction:"initiator"===o?"outbound":"inbound",maxDataSize:a,onEnd:i,send:n,log:e.logger.forComponent("libp2p:mplex:stream:".concat(o,":").concat(t))})}({id:i,name:o,send:l,type:a,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",a,i,u.protocol),s.delete(i),null!=this._init.onStreamEnd&&this._init.onStreamEnd(u)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return s.set(i,u),u}_createSink(){var e=this,t=function(){var t=r((function*(t){var r=()=>{lp(t,e.log)};e.closeController.signal.addEventListener("abort",r);try{var n,i=new xF(e._init.maxMsgSize,e._init.maxUnprocessedMessageQueueSize),o=!1,a=!1;try{for(var l,u=s(t);o=!(l=yield u.next()).done;o=!1){var c=l.value;for(var d of i.write(c))yield e._handleIncoming(d)}}catch(e){a=!0,n=e}finally{try{o&&null!=u.return&&(yield u.return())}finally{if(a)throw n}}e._source.end()}catch(t){e.log("error in sink",t),e._source.end(t)}finally{e.closeController.signal.removeEventListener("abort",r)}}));return function(e){return t.apply(this,arguments)}}();return t}_handleIncoming(e){var t=this;return r((function*(){var r,{id:n,type:i}=e;if(t.log.enabled&&t.log.trace("incoming message",DF(e)),e.type!==nF.NEW_STREAM){var o=(1&~i?t._streams.receivers:t._streams.initiators).get(n);if(null!=o){var a=null!==(r=t._init.maxStreamBufferSize)&&void 0!==r?r:4194304;try{switch(i){case nF.MESSAGE_INITIATOR:case nF.MESSAGE_RECEIVER:if(o.sourceReadableLength()>a)throw t._source.push({id:e.id,type:i===nF.MESSAGE_INITIATOR?nF.RESET_RECEIVER:nF.RESET_INITIATOR}),new BF("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers");o.sourcePush(e.data);break;case nF.CLOSE_INITIATOR:case nF.CLOSE_RECEIVER:o.remoteCloseWrite();break;case nF.RESET_INITIATOR:case nF.RESET_RECEIVER:o.reset();break;default:t.log("unknown message type %s",i)}}catch(e){t.log.error("error while processing message",e),o.abort(e)}}else{t.log("missing stream %s for message type %s",n,bF[i]);try{yield t.rateLimiter.consume("missing-stream",1)}catch(e){return t.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),void t.abort(new Error("Too many messages for missing streams"))}}}else{var s;if(t._streams.receivers.size===(null!==(s=t._init.maxInboundStreams)&&void 0!==s?s:1024)){t.log("too many inbound streams open"),t._source.push({id:n,type:nF.RESET_RECEIVER});try{yield t.rateLimiter.consume("new-stream",1)}catch(e){return t.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),void t.abort(new Error("Too many open streams"))}return}var l=t._newReceiverStream({id:n,name:gt(e.data instanceof Uint8Array?e.data:e.data.subarray())});null!=t._init.onIncomingStream&&t._init.onIncomingStream(l)}}))()}}class OF{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"protocol","/mplex/6.7.0"),e(this,"_init",void 0),e(this,"components",void 0),e(this,Symbol.toStringTag,"@libp2p/mplex"),e(this,ds,["@libp2p/stream-multiplexing"]),this.components=t,this._init=r}createStreamMuxer(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new RF(this.components,t(t({},e),this._init))}}function LF(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new OF(t,e)}class MF{constructor(t){var r,n,i,o,a,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"protocol",void 0),e(this,"components",void 0),e(this,"started",void 0),e(this,"timeout",void 0),e(this,"maxInboundStreams",void 0),e(this,"maxOutboundStreams",void 0),e(this,"runOnLimitedConnection",void 0),e(this,"log",void 0),e(this,Symbol.toStringTag,"@libp2p/ping"),e(this,ds,["@libp2p/ping"]),this.components=t,this.log=t.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol="/".concat(null!==(r=s.protocolPrefix)&&void 0!==r?r:"ipfs","/").concat("ping","/").concat("1.0.0"),this.timeout=null!==(n=s.timeout)&&void 0!==n?n:1e4,this.maxInboundStreams=null!==(i=s.maxInboundStreams)&&void 0!==i?i:2,this.maxOutboundStreams=null!==(o=s.maxOutboundStreams)&&void 0!==o?o:1,this.runOnLimitedConnection=null===(a=s.runOnLimitedConnection)||void 0===a||a,this.handleMessage=this.handleMessage.bind(this)}start(){var e=this;return r((function*(){yield e.components.registrar.handle(e.protocol,e.handleMessage,{maxInboundStreams:e.maxInboundStreams,maxOutboundStreams:e.maxOutboundStreams,runOnLimitedConnection:e.runOnLimitedConnection}),e.started=!0}))()}stop(){var e=this;return r((function*(){yield e.components.registrar.unhandle(e.protocol),e.started=!1}))()}isStarted(){return this.started}handleMessage(e){var t=this;this.log("incoming ping from %p",e.connection.remotePeer);var{stream:n}=e,i=Date.now(),o=wd(n),a=!1;Promise.resolve().then(r((function*(){for(;;){var e=AbortSignal.timeout(t.timeout);e.addEventListener("abort",(()=>{null==n||n.abort(new Qa("ping timeout"))}));var r=yield o.read({bytes:32,signal:e});yield o.write(r,{signal:e}),a=!0}}))).catch((t=>{a&&"UnexpectedEOFError"===t.name&&"ready"!==n.readStatus||(this.log.error("incoming ping from %p failed with error - %e",e.connection.remotePeer,t),null==n||n.abort(t))})).finally((()=>{var t=Date.now()-i;this.log("incoming ping from %p complete in %dms",e.connection.remotePeer,t);var r=AbortSignal.timeout(this.timeout);n.close({signal:r}).catch((t=>{this.log.error("error closing ping stream from %p - %e",e.connection.remotePeer,t),null==n||n.abort(t)}))}))}ping(e){var n=arguments,i=this;return r((function*(){var r=n.length>1&&void 0!==n[1]?n[1]:{};i.log("pinging %p",e);var o,a=Date.now(),s=Gl(32),l=yield i.components.connectionManager.openConnection(e,r);if(null==r.signal){var u=AbortSignal.timeout(i.timeout);r=t(t({},r),{},{signal:u})}try{var c=wd(o=yield l.newStream(i.protocol,t(t({},r),{},{runOnLimitedConnection:i.runOnLimitedConnection}))),[,d]=yield Promise.all([c.write(s,r),c.read(t(t({},r),{},{bytes:32}))]),h=Date.now()-a;if(!St(s,d.subarray()))throw new Ga("Received wrong ping ack after ".concat(h,"ms"));return i.log("ping %p complete in %dms",l.remotePeer,h),h}catch(e){var v;throw i.log.error("error while pinging %p",l.remotePeer,e),null===(v=o)||void 0===v||v.abort(e),e}finally{null!=o&&(yield o.close(r))}}))()}}function UF(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new MF(t,e)}var FF,zF,jF=function(){var e=r((function*(e){if(e.readyState>=2)throw new Error("socket closed");1!==e.readyState&&(yield new Promise(((t,r)=>{function n(){e.removeEventListener("open",i),e.removeEventListener("error",o)}function i(){n(),t()}function o(t){var i;n(),r(null!==(i=t.error)&&void 0!==i?i:new Error("connect ECONNREFUSED ".concat(e.url)))}e.addEventListener("open",i),e.addEventListener("error",o)})))}));return function(t){return e.apply(this,arguments)}}(),VF=(e,t)=>{(t=null!=t?t:{}).closeOnEnd=!1!==t.closeOnEnd;var n=function(){var n=r((function*(r){var n,i=!1,o=!1;try{for(var a,l=s(r);i=!(a=yield l.next()).done;i=!1){var u=a.value;try{yield jF(e)}catch(e){if("socket closed"===e.message)break;throw e}if(e.readyState===e.CLOSING||e.readyState===e.CLOSED)break;e.send(u)}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield l.return())}finally{if(o)throw n}}null!=t.closeOnEnd&&e.readyState<=1&&(yield new Promise(((t,r)=>{e.addEventListener("close",(e=>{if(e.wasClean||1006===e.code)t();else{var n=Object.assign(new Error("ws error"),{event:e});r(n)}})),setTimeout((()=>{e.close()}))})))}));return function(e){return n.apply(this,arguments)}}();return n},qF={},HF={};var KF=function(){if(zF)return qF;zF=1,Object.defineProperty(qF,"__esModule",{value:!0});var e=function(){if(FF)return HF;FF=1,Object.defineProperty(HF,"__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 HF.EventIterator=t,HF.default=t,HF}();return qF.EventIterator=e.EventIterator,qF.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)},qF.default=e.EventIterator,qF}();function WF(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 GF=e=>{e.binaryType="arraybuffer";var t,n=function(){var n=r((function*(){yield new Promise(((r,n)=>{if(o)r();else if(null==t){var i=t=>{e.removeEventListener("open",a),e.removeEventListener("error",s),t()},a=()=>{i(r)},s=t=>{i((()=>{var r;n(null!==(r=t.error)&&void 0!==r?r:new Error("connect ECONNREFUSED ".concat(e.url)))}))};e.addEventListener("open",a),e.addEventListener("error",s)}else n(t)}))}));return function(){return n.apply(this,arguments)}}(),i=l((function*(){var t=new KF.EventIterator((t=>{var{push:r,stop:n,fail:i}=t,o=e=>{var t=null;"string"==typeof e.data&&(t=Et(e.data)),WF(e.data)&&(t=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(t=e.data),null!=t&&r(t)},a=e=>{var t;i(null!==(t=e.error)&&void 0!==t?t:new Error("Socket error"))};return e.addEventListener("message",o),e.addEventListener("error",a),e.addEventListener("close",n),()=>{e.removeEventListener("message",o),e.removeEventListener("error",a),e.removeEventListener("close",n)}}),{highWaterMark:1/0});yield u(n());var r,i=!1,o=!1;try{for(var a,l=s(t);i=!(a=yield u(l.next())).done;i=!1){var c=a.value;yield WF(c)?new Uint8Array(c):c}}catch(e){o=!0,r=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw r}}}))(),o=1===e.readyState;return e.addEventListener("open",(()=>{o=!0,t=null})),e.addEventListener("close",(()=>{o=!1,t=null})),e.addEventListener("error",(r=>{var n;o||(t=null!==(n=r.error)&&void 0!==n?n:new Error("connect ECONNREFUSED ".concat(e.url)))})),Object.assign(i,{connected:n})},QF=(e,t)=>{t=null!=t?t:{};var n=GF(e),i=t.remoteAddress,o=t.remotePort;if(null!=e.url)try{var a=new URL(e.url);i=a.hostname,o=parseInt(a.port,10)}catch(e){}if(null==i||null==o)throw new Error("Remote connection did not have address and/or port");var s,l,u={sink:VF(e,t),source:n,connected:(l=r((function*(){yield n.connected()})),function(){return l.apply(this,arguments)}),close:(s=r((function*(){e.readyState!==e.CONNECTING&&e.readyState!==e.OPEN||(yield new Promise((t=>{e.addEventListener("close",(()=>{t()})),e.close()})))})),function(){return s.apply(this,arguments)}),destroy:()=>{null!=e.terminate?e.terminate():e.close()},remoteAddress:i,remotePort:o,socket:e};return u},YF=WebSocket,JF={"http:":"ws:","https:":"wss:"};function ZF(e,t){t=null!=t?t:{};var r=((e,t)=>{var r;if(e.startsWith("//")&&(e="".concat(null!==(r=null==t?void 0:t.protocol)&&void 0!==r?r:"ws:").concat(e)),e.startsWith("/")&&null!=t){var n,i=null!==(n=t.protocol)&&void 0!==n?n:"ws:",o=t.host,a=null!=t.port&&!0!==(null==o?void 0:o.endsWith(":".concat(t.port)))?":".concat(t.port):"";e="".concat(i,"//").concat(o).concat(a).concat(e)}var s=new URL(e);for(var[l,u]of Object.entries(JF))s.protocol===l&&(s.protocol=u);return s})(e,"undefined"==typeof window?void 0:window.location),n=new YF(r.toString(),t.websocket);return QF(n,t)}class $F{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"log",void 0),e(this,"init",void 0),e(this,"logger",void 0),e(this,"metrics",void 0),e(this,"components",void 0),e(this,Ca,!0),e(this,Symbol.toStringTag,"@libp2p/websockets"),e(this,ds,["@libp2p/transport"]),this.log=t.logger.forComponent("libp2p:websockets"),this.logger=t.logger,this.components=t,this.init=r,null!=t.metrics&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}dial(e,n){var i=this;return r((function*(){var o;i.log("dialing %s",e),n=null!=n?n:{};var a=function(e,n,i){var o,a=i.logger.forComponent("libp2p:websockets:maconn"),c=i.metrics,d=null!==(o=i.metricPrefix)&&void 0!==o?o:"",h={log:a,sink:t=>r((function*(){try{yield e.sink(l((function*(){var e,r=!1,n=!1;try{for(var i,o=s(t);r=!(i=yield u(o.next())).done;r=!1){var a=i.value;a instanceof Uint8Array?yield a:yield a.subarray()}}catch(t){n=!0,e=t}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw e}}}))())}catch(e){"aborted"!==e.type&&a.error(e)}}))(),source:e.source,remoteAddr:n,timeline:{open:Date.now()},close(){var n=arguments,i=this;return r((function*(){var r,o=n.length>0&&void 0!==n[0]?n[0]:{},s=Date.now();if(null==o.signal){var l=AbortSignal.timeout(500);o=t(t({},o),{},{signal:l})}var u=()=>{var{host:e,port:t}=h.remoteAddr.toOptions();a("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-s),i.abort(new Ia("Socket close timeout"))};null===(r=o.signal)||void 0===r||r.addEventListener("abort",u);try{yield e.close()}catch(e){a.error("error closing WebSocket gracefully",e),i.abort(e)}finally{var c;null===(c=o.signal)||void 0===c||c.removeEventListener("abort",u),h.timeline.close=Date.now()}}))()},abort(t){var{host:r,port:n}=h.remoteAddr.toOptions();a("timeout closing stream to %s:%s due to error",r,n,t),e.destroy(),h.timeline.close=Date.now(),null==c||c.increment({["".concat(d,"error")]:!0})}};return e.socket.addEventListener("close",(()=>{null==c||c.increment({["".concat(d,"close")]:!0}),null==h.timeline.close&&(h.timeline.close=Date.now())}),{once:!0}),h}(yield i._connect(e,n),e,{logger:i.logger,metrics:null===(o=i.metrics)||void 0===o?void 0:o.dialerEvents});i.log("new outbound connection %s",a.remoteAddr);var c=yield n.upgrader.upgradeOutbound(a,n);return i.log("outbound connection %s upgraded",a.remoteAddr),c}))()}_connect(e,t){var n=this;return r((function*(){var r,i;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted();var o=e.toOptions();n.log("dialing %s:%s",o.host,o.port);var a=Cc(),s=ZF(gD(e),n.init);s.socket.addEventListener("error",(()=>{var t,r=new La("Could not connect to ".concat(e.toString()));n.log.error("connection error:",r),null===(t=n.metrics)||void 0===t||t.dialerEvents.increment({error:!0}),a.reject(r)}));try{var l;null===(l=t.onProgress)||void 0===l||l.call(t,new av("websockets:open-connection")),yield Nc(Promise.race([s.connected(),a.promise]),t.signal)}catch(e){var u,c;if(null!==(u=t.signal)&&void 0!==u&&u.aborted)null===(c=n.metrics)||void 0===c||c.dialerEvents.increment({abort:!0});throw s.close().catch((e=>{n.log.error("error closing raw socket",e)})),e}return n.log("connected %s",e),null===(i=n.metrics)||void 0===i||i.dialerEvents.increment({connect:!0}),s}))()}createListener(e){return function(){throw new Error("WebSocket Servers can not be created in the browser!")}((this.logger,this.components.events,this.components.metrics),t(t({},this.init),e))}listenFilter(e){var t,r;return e=Array.isArray(e)?e:[e],null!=(null===(t=this.init)||void 0===t?void 0:t.filter)?null===(r=this.init)||void 0===r?void 0:r.filter(e):function(e){return e.filter((e=>mh.exactMatch(e)||gh.exactMatch(e)))}(e)}dialFilter(e){return this.listenFilter(e)}}function XF(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new $F(t,e)}function ez(e,t){var r=t.map(((e,t)=>({record:$D(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===UD.ValidityType.EOL&&t.record.validityType===UD.ValidityType.EOL){var i=zD.fromString(e.record.validity).toDate(),o=zD.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 tz="2.8.8",rz="js-libp2p";function nz(e,t){return"".concat(null!=e?e:rz,"/").concat(null!=t?t:tz," browser/").concat(globalThis.navigator.userAgent)}var iz={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 oz(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r="".concat("helia","/").concat("5.3.0"," ").concat(nz());return{privateKey:t.privateKey,dns:t.dns,nodeInfo:{userAgent:r},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[Nv(),qI(),VI(),XF()],connectionEncrypters:[PI()],streamMuxers:[bO(),LF()],peerDiscovery:[(e=iz,t=>new oL(t,e))],services:{autoNAT:CO(),dcutr:mL(),delegatedRouting:()=>function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new bR(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:fU({clientMode:!0,validators:{ipns:oR},selectors:{ipns:ez}}),identify:PL(),identifyPush:_L(),keychain:yF(t.keychain),ping:UF()}}}function az(){return az=r((function*(e){var t,r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=null!==(t=i.selfKey)&&void 0!==t?t:"self",a=yF(i)({datastore:e,logger:ad()});(yield e.has(new lc("/pkcs8/".concat(o))))?r=yield a.exportKey(o):(r=yield gu(null!==(n=i.keyType)&&void 0!==n?n:"Ed25519"),yield a.importKey(o,r));return r})),az.apply(this,arguments)}var sz=-1,lz={},uz={};[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,sz,"ip6zone"],[43,8,"ipcidr"],[53,sz,"dns",!0],[54,sz,"dns4",!0],[55,sz,"dns6",!0],[56,sz,"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,sz,"unix",!1,!0],[421,sz,"ipfs"],[421,sz,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,sz,"garlic64"],[448,0,"tls"],[449,sz,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,sz,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,sz,"http-path"],[777,sz,"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);uz[t.code]=t,lz[t.name]=t}));var{code:cz}=function(e){if(null!=lz[e])return lz[e];throw new Error("no protocol with name: ".concat(e))}("dnsaddr");class dz extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Max recursive depth reached"),this.name="RecursionLimitError"}}var hz=function(){var e=r((function*(e){var r,n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=null!==(r=o.maxRecursiveDepth)&&void 0!==r?r:32;if(0===a)throw new dz("Max recursive depth reached");var[,s]=null!==(n=e.stringTuples().find((e=>{var[t]=e;return t===cz})))&&void 0!==n?n:[],l=null!==(i=null==o?void 0:o.dns)&&void 0!==i?i:tP(),u=yield l.query("_dnsaddr.".concat(s),{signal:null==o?void 0:o.signal,types:[eP.TXT]}),c=e.getPeerId(),d=[];for(var h of u.Answer){var v=h.data.replace(/["']/g,"").trim().split("=")[1];if(null!=v&&(null==c||v.includes(c))){var p=kr(v);if(v.startsWith("/dnsaddr")){var f=yield p.resolve(t(t({},o),{},{maxRecursiveDepth:a-1}));d.push(...f.map((e=>e.toString())))}else d.push(p.toString())}}return d}));return function(t){return e.apply(this,arguments)}}(),vz={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:hz}},transportManager:{faultTolerance:ka.FATAL_ALL}};function pz(){return pz=r((function*(e){var t,r=RU(vz,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 _a("Private network is enforced, but no protector was provided");return r})),pz.apply(this,arguments)}var fz,gz,yz;function mz(e,t){if(null!=e.publicKey||null==t.publicKey)return e;var r;"RSA"===e.type&&(r=He(ie.decode("z".concat(e))));return Ru(mu(t.publicKey,r))}function wz(e,t,r){return bz(e,fz.decode(t),r)}function bz(e,r,n){var i,o=new Map,a=BigInt(Date.now());for(var[s,l]of r.tags.entries())null!=l.expiry&&l.expiry<a||o.set(s,l);return t(t({},r),{},{id:mz(e,r),addresses:r.addresses.filter((e=>{var{observed:t}=e;return null!=t&&t>Date.now()-n})).map((e=>{var{multiaddr:t,isCertified:r}=e;return{multiaddr:kr(t),isCertified:null!=r&&r}})),metadata:r.metadata,peerRecordEnvelope:null!==(i=r.peerRecordEnvelope)&&void 0!==i?i:void 0,tags:o})}function Sz(e,t){return c=e.addresses,d=t.addresses,kz(c,d,((e,t)=>e.isCertified===t.isCertified&&!!St(e.multiaddr,t.multiaddr)))&&(l=e.protocols,u=t.protocols,kz(l,u,((e,t)=>e===t)))&&(a=e.publicKey,s=t.publicKey,Ez(a,s))&&(i=e.peerRecordEnvelope,o=t.peerRecordEnvelope,Ez(i,o))&&(r=e.metadata,n=t.metadata,xz(r,n,((e,t)=>St(e,t))))&&function(e,t){return xz(e,t,((e,t)=>e.value===t.value&&e.expiry===t.expiry))}(e.tags,t.tags);var r,n,i,o,a,s,l,u,c,d}function Ez(e,t){return null==e&&null==t||null!=e&&null!=t&&St(e,t)}function kz(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 xz(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=Hl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={key:"",value:ct(0)},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.key=e.string();break;case 2:r.value=e.bytes();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((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),yz.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=yz.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=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==t&&(t=Hl((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),gz.codec().encode(i,r);if(null!=t.protocols)for(var o of t.protocols)r.uint32(18),r.string(o);if(null!=t.publicKey&&(r.uint32(34),r.bytes(t.publicKey)),null!=t.peerRecordEnvelope&&(r.uint32(42),r.bytes(t.peerRecordEnvelope)),null!=t.metadata&&0!==t.metadata.size)for(var[a,s]of t.metadata.entries())r.uint32(50),e.Peer$metadataEntry.codec().encode({key:a,value:s},r);if(null!=t.tags&&0!==t.tags.size)for(var[l,u]of t.tags.entries())r.uint32(58),e.Peer$tagsEntry.codec().encode({key:l,value:u},r);null!=t.updated&&(r.uint32(64),r.uint64Number(t.updated)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={addresses:[],protocols:[],metadata:new Map,tags:new Map},o=null==r?t.len:t.pos+r;t.pos<o;){var a=t.uint32();switch(a>>>3){case 1:var s,l;if(null!=(null===(s=n.limits)||void 0===s?void 0:s.addresses)&&i.addresses.length===n.limits.addresses)throw new Kl('Decode error - map field "addresses" had too many elements');i.addresses.push(gz.codec().decode(t,t.uint32(),{limits:null===(l=n.limits)||void 0===l?void 0:l.addresses$}));break;case 2:var u;if(null!=(null===(u=n.limits)||void 0===u?void 0:u.protocols)&&i.protocols.length===n.limits.protocols)throw new Kl('Decode error - map field "protocols" had too many elements');i.protocols.push(t.string());break;case 4:i.publicKey=t.bytes();break;case 5:i.peerRecordEnvelope=t.bytes();break;case 6:var c;if(null!=(null===(c=n.limits)||void 0===c?void 0:c.metadata)&&i.metadata.size===n.limits.metadata)throw new Wl('Decode error - map field "metadata" had too many elements');var d=e.Peer$metadataEntry.codec().decode(t,t.uint32());i.metadata.set(d.key,d.value);break;case 7:var h,v;if(null!=(null===(h=n.limits)||void 0===h?void 0:h.tags)&&i.tags.size===n.limits.tags)throw new Wl('Decode error - map field "tags" had too many elements');var p=e.Peer$tagsEntry.codec().decode(t,t.uint32(),{limits:{value:null===(v=n.limits)||void 0===v?void 0:v.tags$value}});i.tags.set(p.key,p.value);break;case 8:i.updated=t.uint64Number();break;default:t.skipType(7&a)}}return i}))),t),e.encode=t=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(fz||(fz={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),null!=e.isCertified&&(t.uint32(16),t.bool(e.isCertified)),null!=e.observed&&(t.uint32(24),t.uint64Number(e.observed)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={multiaddr:ct(0)},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.multiaddr=e.bytes();break;case 2:r.isCertified=e.bool();break;case 3:r.observed=e.uint64Number();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(gz||(gz={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((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=>jl(t,e.codec()),e.decode=(t,r)=>wl(t,e.codec(),r)}(yz||(yz={}));var Az="/peers/";function Cz(e){if(!Ea(e)||null==e.type)throw new _a("Invalid PeerId");var t=e.toCID().toString();return new lc("".concat(Az).concat(t))}function Iz(e,t,r,n){return Tz.apply(this,arguments)}function Tz(){return Tz=r((function*(e,t,r,n){var i=new Map;for(var o of r){var a;if(null!=o){if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=kr(o.multiaddr)),!Er(o.multiaddr))throw new _a("Multiaddr was invalid");if(yield t(e,o.multiaddr)){var s=null!==(a=o.isCertified)&&void 0!==a&&a,l=o.multiaddr.toString(),u=i.get(l);null!=u?o.isCertified=u.isCertified||s:i.set(l,{multiaddr:o.multiaddr,isCertified:s})}}}return[...i.values()].sort(((e,t)=>e.multiaddr.toString().localeCompare(t.multiaddr.toString()))).map((t=>{var{isCertified:r,multiaddr:n}=t,i=n.getPeerId();return e.equals(i)&&(n=n.decapsulate(kr("/p2p/".concat(e)))),{isCertified:r,multiaddr:n.bytes}}))})),Tz.apply(this,arguments)}function Pz(e,t,r,n){return _z.apply(this,arguments)}function _z(){return _z=r((function*(e,t,n,i){var o,a,s,l,u,c,d;if(null==t)throw new _a("Invalid PeerData");if(null!=t.publicKey&&null!=e.publicKey&&!t.publicKey.equals(e.publicKey))throw new _a("publicKey bytes do not match peer id publicKey bytes");var h=null===(o=i.existingPeer)||void 0===o?void 0:o.peer;if(null!=h&&!e.equals(h.id))throw new _a("peer id did not match existing peer id");var v,p=null!==(a=null==h?void 0:h.addresses)&&void 0!==a?a:[],f=new Set(null!==(s=null==h?void 0:h.protocols)&&void 0!==s?s:[]),g=null!==(l=null==h?void 0:h.metadata)&&void 0!==l?l:new Map,y=null!==(u=null==h?void 0:h.tags)&&void 0!==u?u:new Map,m=null==h?void 0:h.peerRecordEnvelope;if("patch"===n){if(null==t.multiaddrs&&null==t.addresses||(p=[],null!=t.multiaddrs&&p.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&p.push(...t.addresses)),null!=t.protocols&&(f=new Set(t.protocols)),null!=t.metadata)g=Bz(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:Nz});if(null!=t.tags)y=Bz(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:Dz,map:Rz});null!=t.peerRecordEnvelope&&(m=t.peerRecordEnvelope)}if("merge"===n){if(null!=t.multiaddrs&&p.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&p.push(...t.addresses),null!=t.protocols&&(f=new Set([...f,...t.protocols])),null!=t.metadata){var w=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(var[b,S]of w)null==S?g.delete(b):g.set(b,S);g=Bz([...g.entries()],{validate:Nz})}if(null!=t.tags){var E=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),k=new Map(y);for(var[x,A]of E)null==A?k.delete(x):k.set(x,A);y=Bz([...k.entries()],{validate:Dz,map:Rz})}null!=t.peerRecordEnvelope&&(m=t.peerRecordEnvelope)}null!=(null==h?void 0:h.id.publicKey)?v=Su(h.id.publicKey):null!=t.publicKey?v=Su(t.publicKey):null!=e.publicKey&&(v=Su(e.publicKey));var C={addresses:yield Iz(e,null!==(c=i.addressFilter)&&void 0!==c?c:r((function*(){return!0})),p,null===(d=i.existingPeer)||void 0===d?void 0:d.peerPB.addresses),protocols:[...f.values()].sort(((e,t)=>e.localeCompare(t))),metadata:g,tags:y,publicKey:v,peerRecordEnvelope:m};return C.addresses.forEach((e=>{var t,r;e.observed=null!==(t=null===(r=i.existingPeer)||void 0===r||null===(r=r.peerPB.addresses)||void 0===r||null===(r=r.find((e=>St(e.multiaddr,e.multiaddr))))||void 0===r?void 0:r.observed)&&void 0!==t?t:Date.now()})),"RSA"!==e.type&&delete C.publicKey,C})),_z.apply(this,arguments)}function Bz(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 Nz(e,t){if("string"!=typeof e)throw new _a("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new _a("Metadata value must be a Uint8Array")}function Dz(e,t){if("string"!=typeof e)throw new _a("Tag name must be a string");if(null!=t.value){if(parseInt("".concat(t.value),10)!==t.value)throw new _a("Tag value must be an integer");if(t.value<0||t.value>100)throw new _a("Tag value must be between 0-100")}if(null!=t.ttl){if(parseInt("".concat(t.ttl),10)!==t.ttl)throw new _a("Tag ttl must be an integer");if(t.ttl<0)throw new _a("Tag ttl must be between greater than 0")}}function Rz(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 Oz(e){var t=e.toString().split("/")[2];return Mu(it.parse(t,K))}function Lz(e,t,r){return wz(Oz(e),t,r)}var Mz=new WeakSet;class Uz{constructor(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};d(this,Mz),e(this,"peerId",void 0),e(this,"datastore",void 0),e(this,"lock",void 0),e(this,"addressFilter",void 0),e(this,"log",void 0),e(this,"maxAddressAge",void 0),e(this,"maxPeerAge",void 0),this.log=t.logger.forComponent("libp2p:peer-store"),this.peerId=t.peerId,this.datastore=t.datastore,this.addressFilter=i.addressFilter,this.lock=LB({name:"peer-store",singleProcess:!0}),this.maxAddressAge=null!==(r=i.maxAddressAge)&&void 0!==r?r:36e5,this.maxPeerAge=null!==(n=i.maxPeerAge)&&void 0!==n?n:216e5}has(e){var t=this;return r((function*(){try{return yield t.load(e),!0}catch(e){if("NotFoundError"!==e.name)throw e}return!1}))()}delete(e){var t=this;return r((function*(){t.peerId.equals(e)||(yield t.datastore.delete(Cz(e)))}))()}load(e){var t=this;return r((function*(){var r=Cz(e),n=yield t.datastore.get(r),i=fz.decode(n);if(h(Mz,t,qz).call(t,e,i))throw yield t.datastore.delete(r),new za;return bz(e,i,t.peerId.equals(e)?1/0:t.maxAddressAge)}))()}save(e,t){var n=this;return r((function*(){var r=yield h(Mz,n,Fz).call(n,e),i=yield Pz(e,t,"patch",{addressFilter:n.addressFilter});return h(Mz,n,jz).call(n,e,i,r)}))()}patch(e,t){var n=this;return r((function*(){var r=yield h(Mz,n,Fz).call(n,e),i=yield Pz(e,t,"patch",{addressFilter:n.addressFilter,existingPeer:r});return h(Mz,n,jz).call(n,e,i,r)}))()}merge(e,t){var n=this;return r((function*(){var r=yield h(Mz,n,Fz).call(n,e),i=yield Pz(e,t,"merge",{addressFilter:n.addressFilter,existingPeer:r});return h(Mz,n,jz).call(n,e,i,r)}))()}all(e){var t=this;return l((function*(){var r,n=!1,i=!1;try{for(var o,a=s(t.datastore.query(function(e,t){var r,n;return{prefix:Az,filters:(null!==(r=e.filters)&&void 0!==r?r:[]).map((e=>r=>{var{key:n,value:i}=r;return e(Lz(n,i,t))})),orders:(null!==(n=e.orders)&&void 0!==n?n:[]).map((e=>(r,n)=>e(Lz(r.key,r.value,t),Lz(n.key,n.value,t))))}}(null!=e?e:{},t.maxAddressAge)));n=!(o=yield u(a.next())).done;n=!1){var{key:l,value:c}=o.value,d=Oz(l);if(!d.equals(t.peerId)){var v=fz.decode(c);h(Mz,t,qz).call(t,d,v)?yield u(t.datastore.delete(l)):yield bz(d,v,t.peerId.equals(d)?1/0:t.maxAddressAge)}}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield u(a.return()))}finally{if(i)throw r}}}))()}}function Fz(e){return zz.apply(this,arguments)}function zz(){return zz=r((function*(e){try{var t=Cz(e),r=yield this.datastore.get(t),n=fz.decode(r);if(h(Mz,this,qz).call(this,e,n))throw yield this.datastore.delete(t),new za;return{peerPB:n,peer:wz(e,r,this.maxAddressAge)}}catch(e){"NotFoundError"!==e.name&&this.log.error("invalid peer data found in peer store - %e",e)}})),zz.apply(this,arguments)}function jz(e,t,r){return Vz.apply(this,arguments)}function Vz(){return Vz=r((function*(e,t,r){t.updated=Date.now();var n=fz.encode(t);return yield this.datastore.put(Cz(e),n),{peer:wz(e,n,this.maxAddressAge),previous:null==r?void 0:r.peer,updated:null==r||!Sz(t,r.peerPB)}})),Vz.apply(this,arguments)}function qz(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 Hz=new WeakSet;class Kz{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};d(this,Hz),e(this,"store",void 0),e(this,"events",void 0),e(this,"peerId",void 0),e(this,"log",void 0),e(this,Symbol.toStringTag,"@libp2p/peer-store"),this.log=t.logger.forComponent("libp2p:peer-store"),this.events=t.events,this.peerId=t.peerId,this.store=new Uz(t,r)}forEach(e,t){var n=this;return r((function*(){n.log.trace("forEach await read lock");var r=yield n.store.lock.readLock();n.log.trace("forEach got read lock");try{var i,o=!1,a=!1;try{for(var l,u=s(n.store.all(t));o=!(l=yield u.next()).done;o=!1){var c=l.value;e(c)}}catch(e){a=!0,i=e}finally{try{o&&null!=u.return&&(yield u.return())}finally{if(a)throw i}}}finally{n.log.trace("forEach release read lock"),r()}}))()}all(e){var t=this;return r((function*(){t.log.trace("all await read lock");var r=yield t.store.lock.readLock();t.log.trace("all got read lock");try{return yield hc(t.store.all(e))}finally{t.log.trace("all release read lock"),r()}}))()}delete(e){var t=this;return r((function*(){t.log.trace("delete await write lock");var r=yield t.store.lock.writeLock();t.log.trace("delete got write lock");try{yield t.store.delete(e)}finally{t.log.trace("delete release write lock"),r()}}))()}has(e){var t=this;return r((function*(){t.log.trace("has await read lock");var r=yield t.store.lock.readLock();t.log.trace("has got read lock");try{return yield t.store.has(e)}finally{t.log.trace("has release read lock"),r()}}))()}get(e){var t=this;return r((function*(){t.log.trace("get await read lock");var r=yield t.store.lock.readLock();t.log.trace("get got read lock");try{return yield t.store.load(e)}finally{t.log.trace("get release read lock"),r()}}))()}getInfo(e){var t=this;return r((function*(){var r=yield t.get(e);return{id:r.id,multiaddrs:r.addresses.map((e=>{var{multiaddr:t}=e;return t}))}}))()}save(e,t){var n=this;return r((function*(){n.log.trace("save await write lock");var r=yield n.store.lock.writeLock();n.log.trace("save got write lock");try{var i=yield n.store.save(e,t);return h(Hz,n,Wz).call(n,e,i),i.peer}finally{n.log.trace("save release write lock"),r()}}))()}patch(e,t){var n=this;return r((function*(){n.log.trace("patch await write lock");var r=yield n.store.lock.writeLock();n.log.trace("patch got write lock");try{var i=yield n.store.patch(e,t);return h(Hz,n,Wz).call(n,e,i),i.peer}finally{n.log.trace("patch release write lock"),r()}}))()}merge(e,t){var n=this;return r((function*(){n.log.trace("merge await write lock");var r=yield n.store.lock.writeLock();n.log.trace("merge got write lock");try{var i=yield n.store.merge(e,t);return h(Hz,n,Wz).call(n,e,i),i.peer}finally{n.log.trace("merge release write lock"),r()}}))()}consumePeerRecord(e,t){var n=this;return r((function*(){var r,i=yield hd.openAndCertify(e,yd.DOMAIN),o=Mu(i.publicKey.toCID());if(!1===(null==t?void 0:t.equals(o)))return n.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,o),!1;var a,s=yd.createFromProtobuf(i.payload);try{a=yield n.get(o)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=(null===(r=a)||void 0===r?void 0:r.peerRecordEnvelope)){var l=yield hd.createFromProtobuf(a.peerRecordEnvelope),u=yd.createFromProtobuf(l.payload);if(u.seqNumber>=s.seqNumber)return n.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",u.seqNumber,s.seqNumber),!1}return yield n.patch(s.peerId,{peerRecordEnvelope:e,addresses:s.multiaddrs.map((e=>({isCertified:!0,multiaddr:e})))}),!0}))()}}function Wz(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}var Gz=864e13;class Qz{constructor(t){e(this,"log",void 0),e(this,"mappings",void 0),this.log=t.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=new Map}has(e){var t=this.findHost(e);for(var r of this.mappings.values())if(r.domain===t)return!0;return!1}add(e,t){t.forEach((t=>{this.log("add DNS mapping %s to %s",t,e);var r=!0===lD(t);this.mappings.set(t,{domain:e,verified:r,expires:r?Gz-Date.now():0,lastVerified:r?Gz-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:kr("/".concat(n.map((e=>[xr(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 Yz{constructor(t){e(this,"log",void 0),e(this,"mappings",void 0),this.log=t.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=new Map}has(e){var t=e.stringTuples();for(var r of this.mappings.values())for(var n of r)if(n.externalIp===t[0][1])return!0;return!1}add(e,t,r){var n,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:t,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"tcp",a="".concat(e,"-").concat(t,"-").concat(o),s=null!==(n=this.mappings.get(a))&&void 0!==n?n:[],l={internalIp:e,internalPort:t,externalIp:r,externalPort:i,externalFamily:Vt(r)?4:6,protocol:o,verified:!1,expires:0};s.push(l),this.mappings.set(a,s)}remove(e){var t,r,n=e.stringTuples(),i=null!==(t=n[0][1])&&void 0!==t?t:"",o=6===n[1][0]?"tcp":"udp",a=parseInt(null!==(r=n[1][1])&&void 0!==r?r:"0"),s=!1;for(var[l,u]of this.mappings.entries()){for(var c=0;c<u.length;c++){var d=u[c];d.externalIp===i&&d.externalPort===a&&d.protocol===o&&(this.log("removing %s:%s to %s:%s %s IP mapping",d.externalIp,d.externalPort,i,a,o),s=s||d.verified,u.splice(c,1),c--)}0===u.length&&this.mappings.delete(l)}return s}getAll(e){var t=[];for(var{multiaddr:r}of e){var n=r.stringTuples(),i=void 0;if(4!==n[0][0]&&41!==n[0][0]||6!==n[1][0]?4!==n[0][0]&&41!==n[0][0]||273!==n[1][0]||(i="".concat(n[0][1],"-").concat(n[1][1],"-udp")):i="".concat(n[0][1],"-").concat(n[1][1],"-tcp"),null!=i){var o=this.mappings.get(i);if(null!=o)for(var a of o)n[0][0]=4===a.externalFamily?4:41,n[0][1]=a.externalIp,n[1][1]="".concat(a.externalPort),t.push({multiaddr:kr("/".concat(n.map((e=>[xr(e[0]).name,e[1]].join("/"))).join("/"))),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}}return t}confirm(e,t){var r=e.stringTuples()[0][1],n=!1;for(var i of this.mappings.values())for(var o of i)o.externalIp===r&&(this.log("marking %s to %s IP mapping as verified",o.internalIp,o.externalIp),n=o.verified,o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now());return n}unconfirm(e,t){var r,n,i=e.stringTuples(),o=null!==(r=i[0][1])&&void 0!==r?r:"",a=6===i[1][0]?"tcp":"udp",s=parseInt(null!==(n=i[1][1])&&void 0!==n?n:"0"),l=!1;for(var u of this.mappings.values())for(var c=0;c<u.length;c++){var d=u[c];d.externalIp===o&&d.externalPort===s&&d.protocol===a&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",d.externalIp,d.externalPort,o,s,a),l=l||d.verified,d.verified=!1,d.expires=Date.now()+t)}return l}}var Jz=10;class Zz{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"log",void 0),e(this,"addresses",void 0),e(this,"maxObservedAddresses",void 0),this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=null!==(r=n.maxObservedAddresses)&&void 0!==r?r:Jz}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&&(kO(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:kr(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 $z=[4,41,53,54,55,56];function Xz(e){try{var[[t]]=e.stringTuples();return $z.includes(t)}catch(e){}return!1}var ej=10;class tj{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"log",void 0),e(this,"addresses",void 0),e(this,"maxObservedAddresses",void 0),this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=null!==(r=n.maxObservedAddresses)&&void 0!==r?r:ej}get(e,t){if(kO(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:!Xz(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(Xz(e)){var t=e.toOptions();return"".concat(t.host,"-").concat(t.port,"-").concat(t.transport)}return e.toString()}}var rj,nj={addressVerificationTTL:6e5,addressVerificationRetry:3e5},ij=e=>e;function oj(e,t){var r=e.getPeerId();null!=r&&(Du(r).equals(t)&&(e=e.decapsulate(kr("/p2p/".concat(t.toString())))));return e}class aj{constructor(t){var r,n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"log",void 0),e(this,"components",void 0),e(this,"listen",void 0),e(this,"announce",void 0),e(this,"appendAnnounce",void 0),e(this,"announceFilter",void 0),e(this,"observed",void 0),e(this,"dnsMappings",void 0),e(this,"ipMappings",void 0),e(this,"transportAddresses",void 0),e(this,"observedAddressFilter",void 0),e(this,"addressVerificationTTL",void 0),e(this,"addressVerificationRetry",void 0),e(this,Symbol.toStringTag,"@libp2p/address-manager");var{listen:a=[],announce:s=[],appendAnnounce:l=[]}=o;this.components=t,this.log=t.logger.forComponent("libp2p:address-manager"),this.listen=a.map((e=>e.toString())),this.announce=new Set(s.map((e=>e.toString()))),this.appendAnnounce=new Set(l.map((e=>e.toString()))),this.observed=new Zz(t,o),this.dnsMappings=new Qz(t,o),this.ipMappings=new Yz(t,o),this.transportAddresses=new tj(t,o),this.announceFilter=null!==(r=o.announceFilter)&&void 0!==r?r:ij,this.observedAddressFilter=$h(1024),this.addressVerificationTTL=null!==(n=o.addressVerificationTTL)&&void 0!==n?n:nj.addressVerificationTTL,this.addressVerificationRetry=null!==(i=o.addressVerificationRetry)&&void 0!==i?i:nj.addressVerificationRetry,this._updatePeerStoreAddresses=cv(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=>kr(e)))}getAnnounceAddrs(){return Array.from(this.announce).map((e=>kr(e)))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map((e=>kr(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=oj(e,this.components.peerId),this.ipMappings.has(e)||this.dnsMappings.has(e)||this.observed.add(e))}confirmObservedAddr(e,t){e=oj(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=oj(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=kr(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(kr("/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(Vt(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(kr("/ip".concat(Vt(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===lD(r.host))return!1;var n,i=this.components.transportManager.getListeners(),o=[e=>gh.exactMatch(e)||mh.exactMatch(e),e=>uh.exactMatch(e),e=>vh.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"}(rj||(rj={}));class sj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Missing service"),this.name="MissingServiceError"}}class lj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unmet service dependencies"),this.name="UnmetServiceDependenciesError"}}class uj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No content routers available"),this.name="NoContentRoutersError"}}class cj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No peer routers available"),this.name="NoPeerRoutersError"}}class dj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Should not try to find self"),this.name="QueriedForSelfError"}}class hj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unhandled protocol error"),this.name="UnhandledProtocolError"}}class vj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Duplicate protocol handler error"),this.name="DuplicateProtocolHandlerError"}}class pj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Dial denied error"),this.name="DialDeniedError"}}class fj 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 gj 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 yj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No valid addresses"),this.name="NoValidAddressesError"}}class mj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Connection intercepted"),this.name="ConnectionInterceptedError"}}class wj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Connection denied"),this.name="ConnectionDeniedError"}}class bj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Stream is not multiplexed"),this.name="MuxerUnavailableError"}}class Sj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Encryption failed"),this.name="EncryptionFailedError"}}class Ej extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Transport unavailable"),this.name="TransportUnavailableError"}}class kj{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(var[r,n]of(e(this,"components",{}),e(this,"_started",!1),this.components={},Object.entries(t)))this.components[r]=n;null==this.components.logger&&(this.components.logger=ad())}isStarted(){return this._started}_invokeStartableMethod(e){var t=this;return r((function*(){yield Promise.all(Object.values(t.components).filter((e=>as(e))).map(function(){var t=r((function*(t){var r;yield null===(r=t[e])||void 0===r?void 0:r.call(t)}));return function(e){return t.apply(this,arguments)}}()))}))()}beforeStart(){var e=this;return r((function*(){yield e._invokeStartableMethod("beforeStart")}))()}start(){var e=this;return r((function*(){yield e._invokeStartableMethod("start"),e._started=!0}))()}afterStart(){var e=this;return r((function*(){yield e._invokeStartableMethod("afterStart")}))()}beforeStop(){var e=this;return r((function*(){yield e._invokeStartableMethod("beforeStop")}))()}stop(){var e=this;return r((function*(){yield e._invokeStartableMethod("stop"),e._started=!1}))()}afterStop(){var e=this;return r((function*(){yield e._invokeStartableMethod("afterStop")}))()}}var xj=["metrics","connectionProtector","dns"],Aj=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function Cj(e){return Array.isArray(null==e?void 0:e[ds])?e[ds]:[]}function Ij(e){return Array.isArray(null==e?void 0:e[hs])?e[hs]:[]}function Tj(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 Pj(){var e,n,i,o,a,s,l,u,c,d=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t({denyDialPeer:(c=r((function*(){return!1})),function(){return c.apply(this,arguments)}),denyDialMultiaddr:(u=r((function*(e){if(gh.matches(e))return!1;var t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&Boolean(lD("".concat(t[0][1])))})),function(e){return u.apply(this,arguments)}),denyInboundConnection:(l=r((function*(){return!1})),function(){return l.apply(this,arguments)}),denyOutboundConnection:(s=r((function*(){return!1})),function(){return s.apply(this,arguments)}),denyInboundEncryptedConnection:(a=r((function*(){return!1})),function(){return a.apply(this,arguments)}),denyOutboundEncryptedConnection:(o=r((function*(){return!1})),function(){return o.apply(this,arguments)}),denyInboundUpgradedConnection:(i=r((function*(){return!1})),function(){return i.apply(this,arguments)}),denyOutboundUpgradedConnection:(n=r((function*(){return!1})),function(){return n.apply(this,arguments)}),filterMultiaddrForPeer:(e=r((function*(){return!0})),function(){return e.apply(this,arguments)})},d)}function _j(e){if(Ea(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:Du(n),r.forEach((e=>{if(!Er(e))throw new Va("Invalid multiaddr");var r=e.getPeerId();if(null==r){if(null!=t)throw new _a("Multiaddrs must all have the same peer id or have no peer id")}else{var n,i=Du(r);if(!0!==(null===(n=t)||void 0===n?void 0:n.equals(i)))throw new _a("Multiaddrs must all have the same peer id or have no peer id")}}))}return r=r.filter((e=>!Gd.exactMatch(e))),{peerId:t,multiaddrs:r}}var Bj=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];function Nj(){return Nj=r((function*(e,t){var r,n,i,o=null!==(r=null==e||null===(n=e.streams)||void 0===n?void 0:n.map((e=>e.protocol)))&&void 0!==r?r:[],a=null!==(i=null==t?void 0:t.closableProtocols)&&void 0!==i?i:Bj;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)}})),Nj.apply(this,arguments)}var Dj="last-dial-failure",Rj="last-dial-success";function Oj(){return Oj=r((function*(e,t){var r=!1;for(var n of br.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})),Oj.apply(this,arguments)}function Lj(e){try{var t;if(!(t="string"==typeof e?kr(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 wr(r,t)}(t)}catch(t){throw new Error("Can't convert to IpNet, Invalid multiaddr format: ".concat(e))}}var Mj=100;class Uj{constructor(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"maxConnections",void 0),e(this,"connectionManager",void 0),e(this,"peerStore",void 0),e(this,"allow",void 0),e(this,"events",void 0),e(this,"log",void 0),this.maxConnections=null!==(r=i.maxConnections)&&void 0!==r?r:Mj,this.allow=(null!==(n=i.allow)&&void 0!==n?n:[]).map((e=>Lj(e))),this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch((e=>{this.log.error("error while pruning connections %e",e)}))}_maybePruneConnections(){var e=this;return r((function*(){var t=e.connectionManager.getConnections(),n=t.length;if(e.log("checking max connections limit %d/%d",n,e.maxConnections),!(n<=e.maxConnections)){var i=new Fh;for(var o of t){var a=o.remotePeer;if(!i.has(a)){i.set(a,0);try{var s=yield e.peerStore.get(a);i.set(a,[...s.tags.values()].reduce(((e,t)=>e+t.value),0))}catch(t){"NotFoundError"!==t.name&&e.log.error("error loading peer tags",t)}}}var l=e.sortConnections(t,i),u=Math.max(n-e.maxConnections,0),c=[],d=function*(t){if(e.log("too many connections open - closing a connection to %p",t.remotePeer),e.allow.some((e=>e.contains(t.remoteAddr.nodeAddress().address)))||c.push(t),c.length===u)return 1};for(var h of l)if(yield*d(h))break;yield Promise.all(c.map(function(){var e=r((function*(e){yield function(e,t){return Nj.apply(this,arguments)}(e,{signal:AbortSignal.timeout(1e3)})}));return function(t){return e.apply(this,arguments)}}())),e.events.safeDispatchEvent("connection:prune",{detail:c})}}))()}sortConnections(e,t){return e.sort(((e,t)=>{var r=e.timeline.open,n=t.timeline.open;return r<n?1:r>n?-1:0})).sort(((e,t)=>"outbound"===e.direction&&"inbound"===t.direction?1:"inbound"===e.direction&&"outbound"===t.direction?-1:0)).sort(((e,t)=>e.streams.length>t.streams.length?1:e.streams.length<t.streams.length?-1:0)).sort(((e,r)=>{var n,i,o=null!==(n=t.get(e.remotePeer))&&void 0!==n?n:0,a=null!==(i=t.get(r.remotePeer))&&void 0!==i?i:0;return o>a?1:o<a?-1:0}))}}class Fj extends fv{constructor(){super(t(t({},arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),{},{sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0}))}}function zj(e){if(!EO(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 jj(e,t){var r=uh.exactMatch(e.multiaddr),n=uh.exactMatch(t.multiaddr);if(r&&!n)return-1;if(!r&&n)return 1;var i=mh.exactMatch(e.multiaddr),o=mh.exactMatch(t.multiaddr);if(i&&!o)return-1;if(!i&&o)return 1;var a=gh.exactMatch(e.multiaddr),s=gh.exactMatch(t.multiaddr);if(a&&!s)return-1;if(!a&&s)return 1;var l=Ch.exactMatch(e.multiaddr),u=Ch.exactMatch(t.multiaddr);if(l&&!u)return-1;if(!l&&u)return 1;var c=bh.exactMatch(e.multiaddr),d=bh.exactMatch(t.multiaddr);if(c&&!d)return-1;if(!c&&d)return 1;var h=Eh.exactMatch(e.multiaddr),v=Eh.exactMatch(t.multiaddr);return h&&!v?-1:!h&&v?1:0}function Vj(e,t){var r=zj(e.multiaddr),n=zj(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function qj(e,t){var r=kO(e.multiaddr),n=kO(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function Hj(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function Kj(e,t){var r=Ah.exactMatch(e.multiaddr),n=Ah.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}var Wj=50,Gj=500,Qj=25,Yj=1e4;class Jj{constructor(t){var r,n,i,o,a,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};for(var[l,u]of(e(this,"queue",void 0),e(this,"components",void 0),e(this,"addressSorter",void 0),e(this,"maxPeerAddrsToDial",void 0),e(this,"maxDialQueueLength",void 0),e(this,"dialTimeout",void 0),e(this,"shutDownController",void 0),e(this,"connections",void 0),e(this,"log",void 0),this.addressSorter=s.addressSorter,this.maxPeerAddrsToDial=null!==(r=s.maxPeerAddrsToDial)&&void 0!==r?r:Qj,this.maxDialQueueLength=null!==(n=s.maxDialQueueLength)&&void 0!==n?n:Gj,this.dialTimeout=null!==(i=s.dialTimeout)&&void 0!==i?i:Yj,this.connections=null!==(o=s.connections)&&void 0!==o?o:new Fh,this.log=t.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=t,this.shutDownController=new AbortController,this.shutDownController.signal,Object.entries(null!==(c=s.resolvers)&&void 0!==c?c:{}))){var c;br.set(l,u)}this.queue=new Fj({concurrency:null!==(a=s.maxParallelDials)&&void 0!==a?a:Wj,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)!==Ia.name&&this.log.error("error in dial queue - %e",e.detail)}))}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}dial(e){var t=arguments,n=this;return r((function*(){var i,o,a,s,l=t.length>1&&void 0!==t[1]?t[1]:{},{peerId:u,multiaddrs:c}=_j(e),d=Array.from(n.connections.values()).flat().find((e=>!0!==l.force&&(!!e.remotePeer.equals(u)||c.find((t=>t.equals(e.remoteAddr))))));if("open"===(null==d?void 0:d.status))return n.log("already connected to %a",d.remoteAddr),null===(s=l.onProgress)||void 0===s||s.call(l,new av("dial-queue:already-connected")),d;var h=n.queue.queue.find((e=>{if(!0===(null==u?void 0:u.equals(e.options.peerId)))return!0;var t=e.options.multiaddrs;if(null==t)return!1;for(var r of c)if(t.has(r.toString()))return!0;return!1}));if(null!=h){var v;for(var p of(n.log("joining existing dial target for %p",u),c))h.options.multiaddrs.add(p.toString());return null===(v=l.onProgress)||void 0===v||v.call(l,new av("dial-queue:already-in-dial-queue")),h.join(l)}if(n.queue.size>=n.maxDialQueueLength)throw new Za("Dial queue is full");return n.log("creating dial target for %p",u,c.map((e=>e.toString()))),null===(i=l.onProgress)||void 0===i||i.call(l,new av("dial-queue:add-to-dial-queue")),n.queue.add(function(){var e=r((function*(e){var t;null===(t=e.onProgress)||void 0===t||t.call(e,new av("dial-queue:start-dial"));var r=Ph([n.shutDownController.signal,e.signal]);try{return yield n.dialPeer(e,r)}finally{r.clear()}}));return function(t){return e.apply(this,arguments)}}(),{peerId:u,priority:null!==(o=l.priority)&&void 0!==o?o:vV,multiaddrs:new Set(c.map((e=>e.toString()))),signal:null!==(a=l.signal)&&void 0!==a?a:AbortSignal.timeout(n.dialTimeout),onProgress:l.onProgress})}))()}dialPeer(e,n){var i=this;return r((function*(){var r=e.peerId,o=e.multiaddrs,a=new Set,s=0===e.multiaddrs.size,l=0,u=0,c=[];for(i.log("starting dial to %p",r);s||o.size>0;){var d;u++,s=!1;var h=[],v=new Set(e.multiaddrs);o.clear(),i.log("calculating addrs to dial %p from %s",r,[...v]);var p=yield i.calculateMultiaddrs(r,v,t(t({},e),{},{signal:n}));for(var f of p)a.has(f.multiaddr.toString())?i.log.trace("skipping previously failed multiaddr %a while dialing %p",f.multiaddr,r):h.push(f);for(var g of(i.log("%s dial to %p with %s",1===u?"starting":"continuing",r,h.map((e=>e.multiaddr.toString()))),null==e||null===(d=e.onProgress)||void 0===d||d.call(e,new av("dial-queue:calculated-addresses",h)),h)){if(l===i.maxPeerAddrsToDial)throw i.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",l,e.peerId),new Za("Peer had more than maxPeerAddrsToDial");l++;try{var y=yield i.components.transportManager.dial(g.multiaddr,t(t({},e),{},{signal:n}));i.log("dial to %a succeeded",g.multiaddr);try{yield i.components.peerStore.merge(y.remotePeer,{multiaddrs:[y.remoteAddr],metadata:{[Rj]:Et(Date.now().toString())}})}catch(e){i.log.error("could not update last dial failure key for %p",r,e)}return y}catch(e){if(i.log.error("dial failed to %a",g.multiaddr,e),a.add(g.multiaddr.toString()),null!=r)try{yield i.components.peerStore.merge(r,{metadata:{[Dj]:Et(Date.now().toString())}})}catch(e){i.log.error("could not update last dial failure key for %p",r,e)}if(n.aborted)throw new Qa(e.message);c.push(e)}}}if(1===c.length)throw c[0];throw new AggregateError(c,"All multiaddr dials failed")}))()}calculateMultiaddrs(e){var n=arguments,i=this;return r((function*(){var o=n.length>1&&void 0!==n[1]?n[1]:new Set,a=n.length>2&&void 0!==n[2]?n[2]:{},s=[...o].map((e=>({multiaddr:kr(e),isCertified:!1})));if(null!=e){var l,u;if(i.components.peerId.equals(e))throw new Za("Tried to dial self");if(!0===(yield null===(l=(u=i.components.connectionGater).denyDialPeer)||void 0===l?void 0:l.call(u,e)))throw new pj("The dial request is blocked by gater.allowDialPeer");if(0===s.length){i.log("loading multiaddrs for %p",e);try{var c=yield i.components.peerStore.get(e);s.push(...c.addresses),i.log("loaded multiaddrs for %p",e,s.map((e=>{var{multiaddr:t}=e;return t.toString()})))}catch(e){if("NotFoundError"!==e.name)throw e}}if(0===s.length){i.log("looking up multiaddrs for %p in the peer routing",e);try{var d=yield i.components.peerRouting.findPeer(e,a);i.log("found multiaddrs for %p in the peer routing",e,s.map((e=>{var{multiaddr:t}=e;return t.toString()}))),s.push(...d.multiaddrs.map((e=>({multiaddr:e,isCertified:!1}))))}catch(t){"NoPeerRoutersError"===t.name?i.log("no peer routers configured",e):i.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,t)}}}var h=(yield Promise.all(s.map(function(){var e=r((function*(e){var r=yield function(e,t){return Oj.apply(this,arguments)}(e.multiaddr,t(t({dns:i.components.dns},a),{},{log:i.log}));return 1===r.length&&r[0].equals(e.multiaddr)?e:r.map((e=>({multiaddr:e,isCertified:!1})))}));return function(t){return e.apply(this,arguments)}}()))).flat();if(null!=e){var v="/p2p/".concat(e.toString());h=h.map((e=>{var t=e.multiaddr.protos().pop();return!0===(null==t?void 0:t.path)?e:null==e.multiaddr.getPeerId()?{multiaddr:e.multiaddr.encapsulate(v),isCertified:e.isCertified}:e}))}var p=h.filter((t=>{if(null==i.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;var r=t.multiaddr.getPeerId();return null==e||null==r||e.equals(r)})),f=new Map;for(var g of p){var y=g.multiaddr.toString(),m=f.get(y);null==m?f.set(y,g):m.isCertified=m.isCertified||g.isCertified||!1}var w=[...f.values()];if(0===w.length)throw new yj("The dial request has no valid addresses");var b=[];for(var S of w)null!=i.components.connectionGater.denyDialMultiaddr&&(yield i.components.connectionGater.denyDialMultiaddr(S.multiaddr))||b.push(S);var E=null==i.addressSorter?b.sort(jj).sort(Hj).sort(Kj).sort(qj).sort(Vj):b.sort(i.addressSorter);if(0===E.length)throw new pj("The connection gater denied all addresses in the dial request");return i.log.trace("addresses for %p before filtering",null!=e?e:"unknown peer",h.map((e=>{var{multiaddr:t}=e;return t.toString()}))),i.log.trace("addresses for %p after filtering",null!=e?e:"unknown peer",E.map((e=>{var{multiaddr:t}=e;return t.toString()}))),E}))()}isDialable(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};Array.isArray(e)||(e=[e]);try{var i=yield n.calculateMultiaddrs(void 0,new Set(e.map((e=>e.toString()))),r);return!1!==r.runOnLimitedConnection||null!=i.find((e=>!Ah.matches(e.multiaddr)))}catch(e){n.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}))()}}var Zj,$j,Xj,eV,tV,rV={};function nV(){return Xj||(Xj=1,e=rV,t=function(){if($j)return Zj;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 $j=1,Zj=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},Zj}(),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}}),rV;var e,t}var iV=a(tV?eV:(tV=1,eV=nV())),oV=Object.prototype.toString,aV=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 sV(e){var t;return!(!e||(t=e,"[object Error]"!==oV.call(t))||"TypeError"!==e.name||"string"!=typeof e.message)&&("Load failed"===e.message?void 0===e.stack:aV.has(e.message))}class lV 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 uV=(e,t,r)=>{var n=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=n,e};function cV(){return cV=r((function*(e,n){return new Promise(((i,o)=>{var a,s,l,u,c,d;null!==(s=(a=n=t({},n)).onFailedAttempt)&&void 0!==s||(a.onFailedAttempt=()=>{}),null!==(u=(l=n).shouldRetry)&&void 0!==u||(l.shouldRetry=()=>!0),null!==(d=(c=n).retries)&&void 0!==d||(c.retries=10);var h=iV.operation(n),v=()=>{var e;h.stop(),o(null===(e=n.signal)||void 0===e?void 0:e.reason)};n.signal&&!n.signal.aborted&&n.signal.addEventListener("abort",v,{once:!0});var p=()=>{var e;null===(e=n.signal)||void 0===e||e.removeEventListener("abort",v),h.stop()};h.attempt(function(){var t=r((function*(t){try{var r=yield e(t);p(),i(r)}catch(e){try{if(!(e instanceof Error))throw new TypeError('Non-error was thrown: "'.concat(e,'". You should only throw errors.'));if(e instanceof lV)throw e.originalError;if(e instanceof TypeError&&!sV(e))throw e;if(uV(e,t,n),(yield n.shouldRetry(e))||(h.stop(),o(e)),yield n.onFailedAttempt(e),!h.retry(e))throw h.mainError()}catch(e){uV(e,t,n),p(),o(e)}}}));return function(e){return t.apply(this,arguments)}}())}))})),cV.apply(this,arguments)}class dV{constructor(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"log",void 0),e(this,"queue",void 0),e(this,"started",void 0),e(this,"peerStore",void 0),e(this,"retries",void 0),e(this,"retryInterval",void 0),e(this,"backoffFactor",void 0),e(this,"connectionManager",void 0),e(this,"events",void 0),this.log=t.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.queue=new gv({concurrency:null!==(r=i.maxParallelReconnects)&&void 0!==r?r:5,metricName:"libp2p_reconnect_queue",metrics:t.metrics}),this.started=!1,this.retries=null!==(n=i.retries)&&void 0!==n?n:5,this.backoffFactor=i.backoffFactor,this.retryInterval=i.retryInterval,this.events=t.events,t.events.addEventListener("peer:disconnect",(e=>{this.maybeReconnect(e.detail).catch((t=>{this.log.error("failed to maybe reconnect to %p - %e",e.detail,t)}))}))}maybeReconnect(e){var t=this;return r((function*(){if(t.started){var n=yield t.peerStore.get(e);hV(n)&&(t.queue.has(e)||t.queue.add(function(){var n=r((function*(n){yield function(e,t){return cV.apply(this,arguments)}(function(){var i=r((function*(r){if(t.started)try{yield t.connectionManager.openConnection(e,{signal:null==n?void 0:n.signal})}catch(n){throw t.log("reconnecting to %p attempt %d of %d failed - %e",e,r,t.retries,n),n}}));return function(e){return i.apply(this,arguments)}}(),{signal:null==n?void 0:n.signal,retries:t.retries,factor:t.backoffFactor,minTimeout:t.retryInterval})}));return function(e){return n.apply(this,arguments)}}(),{peerId:e}).catch(function(){var i=r((function*(r){t.log.error("failed to reconnect to %p - %e",e,r);var i={};[...n.tags.keys()].forEach((e=>{e.startsWith(Aa)&&(i[e]=void 0)})),yield t.peerStore.merge(e,{tags:i}),t.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}));return function(e){return i.apply(this,arguments)}}()).catch(function(){var n=r((function*(r){t.log.error("failed to remove keep-alive tag from %p - %e",e,r)}));return function(e){return n.apply(this,arguments)}}()))}}))()}start(){this.started=!0}afterStart(){var e=this;return r((function*(){Promise.resolve().then(r((function*(){var t=yield e.peerStore.all({filters:[e=>hV(e)]});yield Promise.all(t.map(function(){var t=r((function*(t){yield e.connectionManager.openConnection(t.id).catch((t=>{e.log.error(t)}))}));return function(e){return t.apply(this,arguments)}}()))}))).catch((t=>{e.log.error(t)}))}))()}stop(){this.started=!1,this.queue.abort()}}function hV(e){for(var t of e.tags.keys())if(t.startsWith(Aa))return!0;return!1}var vV=50,pV=100,fV=5,gV=10;class yV{constructor(t){var r,n,i,o,a,s,l,u,c,d,h,v=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e(this,"started",void 0),e(this,"connections",void 0),e(this,"allow",void 0),e(this,"deny",void 0),e(this,"maxIncomingPendingConnections",void 0),e(this,"incomingPendingConnections",void 0),e(this,"outboundPendingConnections",void 0),e(this,"maxConnections",void 0),e(this,"dialQueue",void 0),e(this,"reconnectQueue",void 0),e(this,"connectionPruner",void 0),e(this,"inboundConnectionRateLimiter",void 0),e(this,"peerStore",void 0),e(this,"metrics",void 0),e(this,"events",void 0),e(this,"log",void 0),e(this,"peerId",void 0),e(this,Symbol.toStringTag,"@libp2p/connection-manager"),this.maxConnections=null!==(r=v.maxConnections)&&void 0!==r?r:pV,this.maxConnections<1)throw new _a("Connection Manager maxConnections must be greater than 0");this.connections=new Fh,this.started=!1,this.peerId=t.peerId,this.peerStore=t.peerStore,this.metrics=t.metrics,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(null!==(n=v.allow)&&void 0!==n?n:[]).map((e=>Lj(e))),this.deny=(null!==(i=v.deny)&&void 0!==i?i:[]).map((e=>Lj(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=null!==(o=v.maxIncomingPendingConnections)&&void 0!==o?o:gV,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new mF({points:null!==(a=v.inboundConnectionThreshold)&&void 0!==a?a:fV,duration:1}),this.connectionPruner=new Uj({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{maxConnections:this.maxConnections,allow:null===(s=v.allow)||void 0===s?void 0:s.map((e=>kr(e)))}),this.dialQueue=new Jj(t,{addressSorter:v.addressSorter,maxParallelDials:null!==(l=v.maxParallelDials)&&void 0!==l?l:50,maxDialQueueLength:null!==(u=v.maxDialQueueLength)&&void 0!==u?u:500,maxPeerAddrsToDial:null!==(c=v.maxPeerAddrsToDial)&&void 0!==c?c:25,dialTimeout:null!==(d=v.dialTimeout)&&void 0!==d?d:1e4,resolvers:null!==(h=v.resolvers)&&void 0!==h?h:{dnsaddr:hz},connections:this.connections}),this.reconnectQueue=new dV({events:t.events,peerStore:t.peerStore,logger:t.logger,connectionManager:this},{retries:v.reconnectRetries,retryInterval:v.reconnectRetryInterval,backoffFactor:v.reconnectBackoffFactor,maxParallelReconnects:v.maxParallelReconnects})}start(){var e=this;return r((function*(){var t,r,n;null===(t=e.metrics)||void 0===t||t.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{var t={inbound:0,"inbound pending":e.incomingPendingConnections,outbound:0,"outbound pending":e.outboundPendingConnections};for(var r of e.connections.values())for(var n of r)t[n.direction]++;return t}}),null===(r=e.metrics)||void 0===r||r.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{var t={};for(var r of e.connections.values())for(var n of r)for(var i of n.streams){var o,a,s="".concat(i.direction," ").concat(null!==(o=i.protocol)&&void 0!==o?o:"unnegotiated");t[s]=(null!==(a=t[s])&&void 0!==a?a:0)+1}return t}}),null===(n=e.metrics)||void 0===n||n.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{var t={};for(var r of e.connections.values())for(var n of r){var i={};for(var o of n.streams){var a,s,l="".concat(o.direction," ").concat(null!==(a=o.protocol)&&void 0!==a?a:"unnegotiated");i[l]=(null!==(s=i[l])&&void 0!==s?s:0)+1}for(var[u,c]of Object.entries(i)){var d;t[u]=null!==(d=t[u])&&void 0!==d?d:[],t[u].push(c)}}var h={};for(var[v,p]of Object.entries(t)){p=p.sort(((e,t)=>e-t));var f=Math.floor(.9*p.length);h[v]=p[f]}return h}}),e.events.addEventListener("connection:open",e.onConnect),e.events.addEventListener("connection:close",e.onDisconnect),yield ss(e.dialQueue,e.reconnectQueue,e.connectionPruner),e.started=!0,e.log("started")}))()}stop(){var e=this;return r((function*(){e.events.removeEventListener("connection:open",e.onConnect),e.events.removeEventListener("connection:close",e.onDisconnect),yield us(e.reconnectQueue,e.dialQueue,e.connectionPruner);var t=[];for(var n of e.connections.values()){var i=function*(n){t.push(r((function*(){try{yield n.close()}catch(t){e.log.error(t)}}))())};for(var o of n)yield*i(o)}e.log("closing %d connections",t.length),yield Promise.all(t),e.connections.clear(),e.log("stopped")}))()}getMaxConnections(){return this.maxConnections}onConnect(e){this._onConnect(e).catch((e=>{this.log.error(e)}))}_onConnect(e){var t=this;return r((function*(){var r,{detail:n}=e;if(t.started){if("open"===n.status){var i=n.remotePeer,o=!t.connections.has(i),a=null!==(r=t.connections.get(i))&&void 0!==r?r:[];a.push(n),t.connections.set(i,a),null!=i.publicKey&&"RSA"===i.type&&(yield t.peerStore.patch(i,{publicKey:i.publicKey})),o&&t.events.safeDispatchEvent("peer:connect",{detail:n.remotePeer})}}else yield n.close()}))()}onDisconnect(e){var t,{detail:r}=e,n=r.remotePeer,i=(null!==(t=this.connections.get(n))&&void 0!==t?t:[]).filter((e=>e.id!==r.id));this.connections.set(n,i),0===i.length&&(this.log("onDisconnect remove all connections for peer %p",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:r.remotePeer}))}getConnections(e){var t;if(null!=e)return null!==(t=this.connections.get(e))&&void 0!==t?t:[];var r=[];for(var n of this.connections.values())r=r.concat(n);return r}getConnectionsMap(){return this.connections}openConnection(e){var n=arguments,i=this;return r((function*(){var r=n.length>1&&void 0!==n[1]?n[1]:{};if(!i.started)throw new Ya("Not started");i.outboundPendingConnections++;try{var o,a;null===(o=r.signal)||void 0===o||o.throwIfAborted();var{peerId:s}=_j(e);if(i.peerId.equals(s))throw new ja("Can not dial self");if(null!=s&&!0!==r.force){i.log("dial %p",s);var l,u=i.getConnections(s).find((e=>null==e.limits));if(null!=u)return i.log("had an existing non-limited connection to %p",s),null===(l=r.onProgress)||void 0===l||l.call(r,new av("dial-queue:already-connected")),u}var c=yield i.dialQueue.dial(e,t(t({},r),{},{priority:null!==(a=r.priority)&&void 0!==a?a:vV}));if("open"!==c.status)throw new Oa("Remote closed connection during opening");var d=i.connections.get(c.remotePeer);null==d&&(d=[],i.connections.set(c.remotePeer,d));var h=!1;for(var v of d)if(v.id===c.id&&(h=!0),!0!==r.force&&v.id!==c.id&&v.remoteAddr.equals(c.remoteAddr))return c.abort(new Va("Duplicate multiaddr connection")),v;return h||d.push(c),c}finally{i.outboundPendingConnections--}}))()}closeConnections(e){var t=arguments,n=this;return r((function*(){var i,o=t.length>1&&void 0!==t[1]?t[1]:{},a=null!==(i=n.connections.get(e))&&void 0!==i?i:[];yield Promise.all(a.map(function(){var e=r((function*(e){try{yield e.close(o)}catch(t){e.abort(t)}}));return function(t){return e.apply(this,arguments)}}()))}))()}acceptIncomingConnection(e){var t=this;return r((function*(){if(t.deny.some((t=>t.contains(e.remoteAddr.nodeAddress().address))))return t.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(t.allow.some((t=>t.contains(e.remoteAddr.nodeAddress().address))))return t.incomingPendingConnections++,!0;if(t.incomingPendingConnections===t.maxIncomingPendingConnections)return t.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){var r=e.remoteAddr.nodeAddress().address;try{yield t.inboundConnectionRateLimiter.consume(r,1)}catch(n){return t.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,r),!1}}return t.getConnections().length<t.maxConnections?(t.incomingPendingConnections++,!0):(t.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}))()}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){var e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map((t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map((e=>kr(e)))})))}isDialable(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};return n.dialQueue.isDialable(e,r)}))()}}class mV{constructor(r){var n,i,o,a,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"protocol",void 0),e(this,"components",void 0),e(this,"log",void 0),e(this,"heartbeatInterval",void 0),e(this,"pingIntervalMs",void 0),e(this,"abortController",void 0),e(this,"timeout",void 0),e(this,"abortConnectionOnPingFailure",void 0),e(this,Symbol.toStringTag,"@libp2p/connection-monitor"),e(this,ds,["@libp2p/connection-monitor"]),this.components=r,this.protocol="/".concat(null!==(n=s.protocolPrefix)&&void 0!==n?n:"ipfs","/").concat("ping","/").concat("1.0.0"),this.log=r.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=null!==(i=s.pingInterval)&&void 0!==i?i:1e4,this.abortConnectionOnPingFailure=null===(o=s.abortConnectionOnPingFailure)||void 0===o||o,this.timeout=new AM(t(t({},null!==(a=s.pingTimeout)&&void 0!==a?a:{}),{},{metrics:r.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"}))}start(){var e=this;this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval((()=>{this.components.connectionManager.getConnections().forEach((t=>{Promise.resolve().then(r((function*(){var r=Date.now();try{var n,i=e.timeout.getTimeoutSignal({signal:null===(n=e.abortController)||void 0===n?void 0:n.signal}),o=wd(yield t.newStream(e.protocol,{signal:i,runOnLimitedConnection:!0}));r=Date.now(),yield Promise.all([o.write(Gl(32),{signal:i}),o.read({bytes:32,signal:i})]),t.rtt=Date.now()-r,yield o.unwrap().close({signal:i})}catch(e){if("UnsupportedProtocolError"!==e.name)throw e;t.rtt=(Date.now()-r)/2}}))).catch((e=>{this.log.error("error during heartbeat",e),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),t.abort(e)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")}))}))}),this.pingIntervalMs)}stop(){var e;null===(e=this.abortController)||void 0===e||e.abort(),null!=this.heartbeatInterval&&clearInterval(this.heartbeatInterval)}}class wV{constructor(r,n){var i,o,a,s,l,u,c,d,h,v,p;e(this,"routers",void 0),e(this,"started",void 0),e(this,"components",void 0),e(this,Symbol.toStringTag,"@libp2p/content-routing"),this.routers=null!==(i=n.routers)&&void 0!==i?i:[],this.started=!1,this.components=r,this.findProviders=null!==(o=null===(a=r.metrics)||void 0===a?void 0:a.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:(e,r)=>{var[n]=e;return t(t({},r),{},{cid:n.toString()})},getAttributesFromYieldedValue:(e,r)=>t(t({},r),{},{providers:[...Array.isArray(r.providers)?r.providers:[],e.id.toString()]})}))&&void 0!==o?o:this.findProviders,this.provide=null!==(s=null===(l=r.metrics)||void 0===l?void 0:l.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:(e,r)=>{var[n]=e;return t(t({},r),{},{cid:n.toString()})}}))&&void 0!==s?s:this.provide,this.cancelReprovide=null!==(u=null===(c=r.metrics)||void 0===c?void 0:c.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:(e,r)=>{var[n]=e;return t(t({},r),{},{cid:n.toString()})}}))&&void 0!==u?u:this.cancelReprovide,this.put=null!==(d=null===(h=r.metrics)||void 0===h?void 0:h.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:e=>{var[t]=e;return{key:gt(t,"base36")}}}))&&void 0!==d?d:this.put,this.get=null!==(v=null===(p=r.metrics)||void 0===p?void 0:p.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:e=>{var[t]=e;return{key:gt(t,"base36")}}}))&&void 0!==v?v:this.get}isStarted(){return this.started}start(){var e=this;return r((function*(){e.started=!0}))()}stop(){var e=this;return r((function*(){e.started=!1}))()}findProviders(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(0===t.routers.length)throw new uj("No content routers available");var n,i=t,o=new zh,a=!1,l=!1;try{for(var c,d=s(Uc(...i.routers.filter((e=>e.findProviders instanceof Function)).map((t=>t.findProviders(e,r)))));a=!(c=yield u(d.next())).done;a=!1){var h=c.value;null!=h&&(h.multiaddrs.length>0&&(yield u(t.components.peerStore.merge(h.id,{multiaddrs:h.multiaddrs}))),o.has(h.id)||(o.add(h.id),yield h))}}catch(e){l=!0,n=e}finally{try{a&&null!=d.return&&(yield u(d.return()))}finally{if(l)throw n}}}()})).apply(this,arguments)}provide(e){var t=arguments,n=this;return r((function*(){var i=t.length>1&&void 0!==t[1]?t[1]:{};if(0===n.routers.length)throw new uj("No content routers available");yield Promise.all(n.routers.filter((e=>e.provide instanceof Function)).map(function(){var t=r((function*(t){yield t.provide(e,i)}));return function(e){return t.apply(this,arguments)}}()))}))()}cancelReprovide(e){var t=arguments,n=this;return r((function*(){var i=t.length>1&&void 0!==t[1]?t[1]:{};if(0===n.routers.length)throw new uj("No content routers available");yield Promise.all(n.routers.filter((e=>e.cancelReprovide instanceof Function)).map(function(){var t=r((function*(t){yield t.cancelReprovide(e,i)}));return function(e){return t.apply(this,arguments)}}()))}))()}put(e,t,n){var i=this;return r((function*(){if(!i.isStarted())throw new Ya;yield Promise.all(i.routers.filter((e=>e.put instanceof Function)).map(function(){var i=r((function*(r){yield r.put(e,t,n)}));return function(e){return i.apply(this,arguments)}}()))}))()}get(e,t){var n=this;return r((function*(){if(!n.isStarted())throw new Ya;return Promise.any(n.routers.filter((e=>e.get instanceof Function)).map(function(){var n=r((function*(r){return r.get(e,t)}));return function(e){return n.apply(this,arguments)}}()))}))()}}class bV{constructor(r){var n,i,o,a,s,l=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"log",void 0),e(this,"peerId",void 0),e(this,"peerStore",void 0),e(this,"routers",void 0),e(this,Symbol.toStringTag,"@libp2p/peer-routing"),this.log=r.logger.forComponent("libp2p:peer-routing"),this.peerId=r.peerId,this.peerStore=r.peerStore,this.routers=null!==(n=l.routers)&&void 0!==n?n:[],this.findPeer=null!==(i=null===(o=r.metrics)||void 0===o?void 0:o.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:(e,r)=>{var[n]=e;return t(t({},r),{},{peer:n.toString()})}}))&&void 0!==i?i:this.findPeer,this.getClosestPeers=null!==(a=null===(s=r.metrics)||void 0===s?void 0:s.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:(e,r)=>{var[n]=e;return t(t({},r),{},{key:gt(n,"base36")})},getAttributesFromYieldedValue:(e,r)=>t(t({},r),{},{peers:[...Array.isArray(r.peers)?r.peers:[],e.id.toString()]})}))&&void 0!==a?a:this.getClosestPeers}findPeer(e,t){var n=this;return r((function*(){if(0===n.routers.length)throw new cj("No peer routers available");if(e.toString()===n.peerId.toString())throw new dj("Should not try to find self");var r,i=n,o=Uc(...n.routers.filter((e=>e.findPeer instanceof Function)).map((r=>l((function*(){try{yield yield u(r.findPeer(e,t))}catch(e){i.log.error(e)}}))()))),a=!1,c=!1;try{for(var d,h=s(o);a=!(d=yield h.next()).done;a=!1){var v=d.value;if(null!=v)return v.multiaddrs.length>0&&(yield n.peerStore.merge(v.id,{multiaddrs:v.multiaddrs})),v}}catch(e){c=!0,r=e}finally{try{a&&null!=h.return&&(yield h.return())}finally{if(c)throw r}}throw new za}))()}getClosestPeers(e){var n=this;return l((function(e){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(0===n.routers.length)throw new cj("No peer routers available");var o,a=n,c=$h(1024),d=!1,h=!1;try{for(var v,p=s(bL(l((function*(){var n,o=Uc(...a.routers.filter((e=>e.getClosestPeers instanceof Function)).map((t=>t.getClosestPeers(e,i)))),l=!1,c=!1;try{for(var d,h=function*(){var e=d.value;yield r((function*(){if(0===e.multiaddrs.length)try{e=yield a.findPeer(e.id,t(t({},i),{},{useCache:!1}))}catch(e){return void a.log.error("could not find peer multiaddrs",e)}return e}))},v=s(o);l=!(d=yield u(v.next())).done;l=!1)yield*h()}catch(e){c=!0,n=e}finally{try{l&&null!=v.return&&(yield u(v.return()))}finally{if(c)throw n}}}))()));d=!(v=yield u(p.next())).done;d=!1){var f=v.value;null!=f&&(f.multiaddrs.length>0&&(yield u(n.peerStore.merge(f.id,{multiaddrs:f.multiaddrs}))),c.has(f.id.toMultihash().bytes)||(c.add(f.id.toMultihash().bytes),yield f))}}catch(e){h=!0,o=e}finally{try{d&&null!=p.return&&(yield u(p.return()))}finally{if(h)throw o}}}()})).apply(this,arguments)}}class SV extends os{constructor(t){super(),e(this,"peerRouting",void 0),e(this,"log",void 0),e(this,"walking",void 0),e(this,"walkers",void 0),e(this,"shutdownController",void 0),e(this,"walkController",void 0),e(this,"needNext",void 0),e(this,Symbol.toStringTag,"@libp2p/random-walk"),this.log=t.logger.forComponent("libp2p:random-walk"),this.peerRouting=t.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}walk(e){var t=this;return l((function*(){t.walking||t.startWalk(),t.walkers++;var r=Ph([t.shutdownController.signal,null==e?void 0:e.signal]);try{for(;;){var n;null===(n=t.needNext)||void 0===n||n.resolve(),t.needNext=Cc();var i=yield u(lv(t,"walk:peer",r,{errorEvent:"walk:error"}));yield i.detail}}finally{var o;if(r.clear(),t.walkers--,0===t.walkers)null===(o=t.walkController)||void 0===o||o.abort(),t.walkController=void 0}}))()}startWalk(){var e=this;this.walking=!0,this.walkController=new AbortController,this.walkController.signal;var t=Ph([this.walkController.signal,this.shutdownController.signal]),n=Date.now(),i=0;Promise.resolve().then(r((function*(){for(e.log("start walk");e.walkers>0;)try{var r,n=Gl(32),o=Date.now(),a=!1,l=!1;try{for(var u,c=s(e.peerRouting.getClosestPeers(n,{signal:t}));a=!(u=yield c.next()).done;a=!1){var d=u.value;t.aborted&&e.log("aborting walk"),t.throwIfAborted(),e.log("found peer %p after %dms for %d walkers",d.id,Date.now()-o,e.walkers),i++,e.safeDispatchEvent("walk:peer",{detail:d}),1===e.walkers&&null!=e.needNext&&(e.log("wait for need next"),yield Nc(e.needNext.promise,t)),o=Date.now()}}catch(e){l=!0,r=e}finally{try{a&&null!=c.return&&(yield c.return())}finally{if(l)throw r}}e.log("walk iteration for %b and %d walkers finished, found %d peers",n,e.walkers,i)}catch(t){e.log.error("random walk errored",t),e.safeDispatchEvent("walk:error",{detail:t})}e.log("no walkers left, ended walk")}))).catch((e=>{this.log.error("random walk errored",e)})).finally((()=>{this.log("finished walk, found %d peers after %dms",i,Date.now()-n),this.walking=!1}))}}class EV{constructor(t){e(this,"log",void 0),e(this,"topologies",void 0),e(this,"handlers",void 0),e(this,"components",void 0),e(this,Symbol.toStringTag,"@libp2p/registrar"),this.log=t.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=t,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){var t=this.handlers.get(e);if(null==t)throw new hj("No handler registered for protocol ".concat(e));return t}getTopologies(e){var t=this.topologies.get(e);return null==t?[]:[...t.values()]}handle(e,t,n){var i=this;return r((function*(){if(i.handlers.has(e)&&!0!==(null==n?void 0:n.force))throw new vj("Handler already registered for protocol ".concat(e));var r=RU.bind({ignoreUndefined:!0})({maxInboundStreams:32,maxOutboundStreams:64},n);i.handlers.set(e,{handler:t,options:r}),yield i.components.peerStore.merge(i.components.peerId,{protocols:[e]})}))()}unhandle(e){var t=this;return r((function*(){(Array.isArray(e)?e:[e]).forEach((e=>{t.handlers.delete(e)})),yield t.components.peerStore.patch(t.components.peerId,{protocols:t.getProtocols()})}))()}register(e,t){var n=this;return r((function*(){if(null==t)throw new _a("invalid topology");var r="".concat((1e9*Math.random()).toString(36)).concat(Date.now()),i=n.topologies.get(e);return null==i&&(i=new Map,n.topologies.set(e,i)),i.set(r,t),r}))()}unregister(e){for(var[t,r]of this.topologies.entries())r.has(e)&&(r.delete(e),0===r.size&&this.topologies.delete(t))}_onDisconnect(e){var t=e.detail;this.components.peerStore.get(t).then((e=>{for(var r of e.protocols){var n=this.topologies.get(r);if(null!=n)for(var i of n.values()){var o,a,s;!1!==(null===(o=i.filter)||void 0===o?void 0:o.has(t))&&(null===(a=i.filter)||void 0===a||a.remove(t),null===(s=i.onDisconnect)||void 0===s||s.call(i,t))}}})).catch((e=>{"NotFoundError"!==e.name&&this.log.error("could not inform topologies of disconnecting peer %p",t,e)}))}_onPeerUpdate(e){var t,{peer:r,previous:n}=e.detail,i=(null!==(t=null==n?void 0:n.protocols)&&void 0!==t?t:[]).filter((e=>!r.protocols.includes(e)));for(var o of i){var a=this.topologies.get(o);if(null!=a)for(var s of a.values()){var l,u,c;!1!==(null===(l=s.filter)||void 0===l?void 0:l.has(r.id))&&(null===(u=s.filter)||void 0===u||u.remove(r.id),null===(c=s.onDisconnect)||void 0===c||c.call(s,r.id))}}}_onPeerIdentify(e){var t=e.detail.protocols,r=e.detail.connection,n=e.detail.peerId;for(var i of t){var o=this.topologies.get(i);if(null!=o)for(var a of o.values()){var s,l,u;null!=r.limits&&!0!==a.notifyOnLimitedConnection||!0!==(null===(s=a.filter)||void 0===s?void 0:s.has(n))&&(null===(l=a.filter)||void 0===l||l.add(n),null===(u=a.onConnect)||void 0===u||u.call(a,n,r))}}}}class kV{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,"log",void 0),e(this,"components",void 0),e(this,"transports",void 0),e(this,"listeners",void 0),e(this,"faultTolerance",void 0),e(this,"started",void 0),e(this,Symbol.toStringTag,"@libp2p/transport-manager"),this.log=t.logger.forComponent("libp2p:transports"),this.components=t,this.started=!1,this.transports=new Map,this.listeners=ZN({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=null!==(r=n.faultTolerance)&&void 0!==r?r:ka.FATAL_ALL}add(e){var t=e[Symbol.toStringTag];if(null==t)throw new _a("Transport must have a valid tag");if(this.transports.has(t))throw new _a("There is already a transport with the tag ".concat(t));this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}afterStart(){var e=this;return r((function*(){var t=e.components.addressManager.getListenAddrs();yield e.listen(t)}))()}stop(){var e=this;return r((function*(){var t=[];for(var[r,n]of e.listeners)for(e.log("closing listeners for %s",r);n.length>0;){var i=n.pop();null!=i&&t.push(i.close())}for(var o of(yield Promise.all(t),e.log("all listeners closed"),e.listeners.keys()))e.listeners.set(o,[]);e.started=!1}))()}dial(e,n){var i=this;return r((function*(){var r,o=i.dialTransportForMultiaddr(e);if(null==o)throw new Ej("No transport available for address ".concat(String(e)));return null==n||null===(r=n.onProgress)||void 0===r||r.call(n,new av("transport-manager:selected-transport",o[Symbol.toStringTag])),o.dial(e,t(t({},n),{},{upgrader:i.components.upgrader}))}))()}getAddrs(){var e=[];for(var t of this.listeners.values())for(var r of t)e=[...e,...r.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(var t of this.transports.values()){if(t.dialFilter([e]).length>0)return t}}listenTransportForMultiaddr(e){for(var t of this.transports.values()){if(t.listenFilter([e]).length>0)return t}}listen(e){var t=this;return r((function*(){if(!t.isStarted())throw new Ya("Not started");if(null!=e&&0!==e.length){var r={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach((e=>{r.errors.set(e.toString(),new fj)}));var n=[],i=function*(i){var o=a.listenFilter(e),s=function*(e){var o;t.log("creating listener for %s on %a",i,e);var s=a.createListener({upgrader:t.components.upgrader}),l=null!==(o=t.listeners.get(i))&&void 0!==o?o:[];null==l&&(l=[],t.listeners.set(i,l)),l.push(s),s.addEventListener("listening",(()=>{t.components.events.safeDispatchEvent("transport:listening",{detail:s})})),s.addEventListener("close",(()=>{var e=l.findIndex((e=>e===s));l.splice(e,1),t.components.events.safeDispatchEvent("transport:close",{detail:s})})),ih.matches(e)?r.ipv4.attempts++:oh.matches(e)&&r.ipv6.attempts++,n.push(s.listen(e).then((()=>{r.errors.delete(e.toString()),ih.matches(e)&&r.ipv4.success++,oh.matches(e)&&r.ipv6.success++}),(n=>{throw t.log.error("transport %s could not listen on address %a - %e",i,e,n),r.errors.set(e.toString(),n),n})))};for(var l of o)yield*s(l)};for(var[o,a]of t.transports.entries())yield*i(o);var s=yield Promise.allSettled(n);if(!(s.length>0&&s.every((e=>"fulfilled"===e.status))))if(t.ipv6Unsupported(r))t.log("all IPv4 addresses succeed but all IPv6 failed");else{if(t.faultTolerance!==ka.NO_FATAL)throw new gj("Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set `transportManager.faultTolerance` to NO_FATAL:\n".concat([...r.errors.entries()].map((e=>{var t,[r,n]=e;return"\n ".concat(r,": ").concat("".concat(null!==(t=n.stack)&&void 0!==t?t:n).split("\n").join("\n "),"\n")})).join("")));t.log("failed to listen on any address but fault tolerance allows this")}}else t.log("no addresses were provided for listening, this node is dial only")}))()}ipv6Unsupported(e){if(0===e.ipv4.attempts||0===e.ipv6.attempts)return!1;var t=e.ipv4.attempts===e.ipv4.success,r=0===e.ipv6.success;return t&&r}remove(e){var t=this;return r((function*(){var r,n=null!==(r=t.listeners.get(e))&&void 0!==r?r:[];t.log.trace("removing transport %s",e);var i=[];for(t.log.trace("closing listeners for %s",e);n.length>0;){var o=n.pop();null!=o&&i.push(o.close())}yield Promise.all(i),t.transports.delete(e),t.listeners.delete(e)}))()}removeAll(){var e=this;return r((function*(){var t=[];for(var r of e.transports.keys())t.push(e.remove(r));yield Promise.all(t)}))()}}var xV="/multistream/1.0.0",AV=1024,CV=Et("\n");function IV(e,t,r){return TV.apply(this,arguments)}function TV(){return TV=r((function*(e,t,r){yield e.write(t,r)})),TV.apply(this,arguments)}function PV(){return PV=r((function*(e,t,r){yield e.writeV(t,r)})),PV.apply(this,arguments)}function _V(){return _V=r((function*(e,t){var r=yield e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==CV[0])throw t.log.error("Invalid mss message - missing newline",r),new Wa("Missing newline");return r.sublist(0,-1)})),_V.apply(this,arguments)}function BV(e,t){return NV.apply(this,arguments)}function NV(){return NV=r((function*(e,t){var r=yield function(e,t){return _V.apply(this,arguments)}(e,t);return gt(r.subarray())})),NV.apply(this,arguments)}function DV(e,t,r){return RV.apply(this,arguments)}function RV(){return RV=r((function*(e,n,i){if(1===(n=Array.isArray(n)?[...n]:[n]).length&&!1===i.negotiateFully)return function(e,n,i){var o=e.sink.bind(e),a=e.source,d=!1,h=!1,v=Cc(),p=!1,f=!1,g=Cc(),y=!1,m=!1,w=Cc(),b=kd({sink:o,source:a},t(t({},i),{},{maxDataLength:AV}));function S(){return E.apply(this,arguments)}function E(){return(E=r((function*(){if(h)return i.log.trace("optimistic: already negotiating %s stream",n),void(yield v.promise);h=!0;try{p||(i.log.trace("optimistic: doing send protocol for %s stream",n),yield k()),y||(i.log.trace("optimistic: doing read protocol for %s stream",n),yield A())}finally{h=!1,d=!0,v.resolve()}}))).apply(this,arguments)}function k(){return x.apply(this,arguments)}function x(){return(x=r((function*(){if(f)yield g.promise;else{f=!0;try{i.log.trace('optimistic: write ["%s", "%s", data] in source',xV,n),yield b.writeV([Et("".concat(xV,"\n")),Et("".concat(n,"\n"))]),i.log.trace('optimistic: wrote ["%s", "%s", data] in source',xV,n)}finally{p=!0,f=!1,g.resolve()}}}))).apply(this,arguments)}function A(){return C.apply(this,arguments)}function C(){return C=r((function*(){if(m)yield w.promise;else{m=!0;try{i.log.trace("optimistic: reading multistream select header");var e=yield BV(b,i);if(i.log.trace('optimistic: read multistream select header "%s"',e),e===xV&&(e=yield BV(b,i)),i.log.trace('optimistic: read protocol "%s", expecting "%s"',e,n),e!==n)throw new Ka("protocol selection failed")}finally{y=!0,m=!1,w.resolve()}}})),C.apply(this,arguments)}if(e.sink=function(){var e=r((function*(e){var{sink:t}=b.unwrap();yield t(l((function*(){var t,r=!1,o=!1,a=!1;try{for(var l,c=s(e);o=!(l=yield u(c.next())).done;o=!1){var d=l.value;if(f&&(yield u(g.promise)),p)yield d;else{f=!0,i.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',xV,n,d.byteLength);var h="".concat(n,"\n");yield new gs(Uint8Array.from([19]),Et("".concat(xV,"\n")),Ot(h.length),Et(h),d).subarray(),i.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',xV,n,d.byteLength),p=!0,f=!1,g.resolve(),S().catch((e=>{i.log.error("could not finish optimistic protocol negotiation of %s",n,e)}))}r=!0}}catch(e){a=!0,t=e}finally{try{o&&null!=c.return&&(yield u(c.return()))}finally{if(a)throw t}}r||(yield u(S()))}))())}));return function(t){return e.apply(this,arguments)}}(),e.source=l((function*(){yield u(S()),i.log.trace('optimistic: reading data from "%s" stream',n),yield*c(s(b.unwrap().source))}))(),null!=e.closeRead){var I=e.closeRead.bind(e);e.closeRead=function(){var e=r((function*(e){d||(yield S().catch((e=>{i.log.error("could not negotiate protocol before close read",e)}))),yield I(e)}));return function(t){return e.apply(this,arguments)}}()}if(null!=e.closeWrite){var T=e.closeWrite.bind(e);e.closeWrite=function(){var e=r((function*(e){d||(yield S().catch((e=>{i.log.error("could not negotiate protocol before close write",e)}))),yield T(e)}));return function(t){return e.apply(this,arguments)}}()}if(null!=e.close){var P=e.close.bind(e);e.close=function(){var e=r((function*(e){var t=[];f&&t.push(g.promise),m&&t.push(w.promise),t.length>0?yield Nc(Promise.all(t),null==e?void 0:e.signal):(d=!0,h=!1,v.resolve()),yield P(e)}));return function(t){return e.apply(this,arguments)}}()}return{stream:e,protocol:n}}(e,n[0],i);var o=kd(e,t(t({},i),{},{maxDataLength:AV})),a=n.shift();if(null==a)throw new Error("At least one protocol must be specified");i.log.trace('select: write ["%s", "%s"]',xV,a);var d=Et("".concat(xV,"\n")),h=Et("".concat(a,"\n"));yield function(e,t,r){return PV.apply(this,arguments)}(o,[d,h],i),i.log.trace("select: reading multistream-select header");var v=yield BV(o,i);if(i.log.trace('select: read "%s"',v),v===xV&&(i.log.trace("select: reading protocol response"),v=yield BV(o,i),i.log.trace('select: read "%s"',v)),v===a)return{stream:o.unwrap(),protocol:a};for(var p of n){i.log.trace('select: write "%s"',p),yield IV(o,Et("".concat(p,"\n")),i),i.log.trace("select: reading protocol response");var f=yield BV(o,i);if(i.log.trace('select: read "%s" for "%s"',f,p),f===p)return{stream:o.unwrap(),protocol:p}}throw new Ka("protocol selection failed")})),RV.apply(this,arguments)}function OV(e,t,r){return LV.apply(this,arguments)}function LV(){return LV=r((function*(e,r,n){r=Array.isArray(r)?r:[r],n.log.trace("handle: available protocols %s",r);for(var i=kd(e,t(t({},n),{},{maxDataLength:AV,maxLengthLength:2}));;){n.log.trace("handle: reading incoming string");var o=yield BV(i,n);if(n.log.trace('handle: read "%s"',o),o!==xV){if(r.includes(o))return n.log.trace('handle: respond with "%s" for "%s"',o,o),yield IV(i,Et("".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 IV(i,Et("na\n"),n),n.log('handle: responded with "na" for "%s"',o);else{var a=new gs(...r.map((e=>bp.single(Et("".concat(e,"\n"))))),Et("\n"));n.log.trace('handle: respond with "%s" for %s',r,o),yield IV(i,a,n),n.log.trace('handle: responded with "%s" for %s',r,o)}}else n.log.trace('handle: respond with "%s" for "%s"',xV,o),yield IV(i,Et("".concat(xV,"\n")),n),n.log.trace('handle: responded with "%s" for "%s"',xV,o)}})),LV.apply(this,arguments)}class MV{constructor(t){e(this,"id",void 0),e(this,"remoteAddr",void 0),e(this,"remotePeer",void 0),e(this,"direction",void 0),e(this,"timeline",void 0),e(this,"multiplexer",void 0),e(this,"encryption",void 0),e(this,"status",void 0),e(this,"limits",void 0),e(this,"log",void 0),e(this,"tags",void 0),e(this,"_newStream",void 0),e(this,"_close",void 0),e(this,"_abort",void 0),e(this,"_getStreams",void 0),e(this,Symbol.toStringTag,"Connection"),e(this,ma,!0);var{remoteAddr:r,remotePeer:n,newStream:i,close:o,abort:a,getStreams:s}=t;this.id="".concat(parseInt(String(1e9*Math.random())).toString(36)).concat(Date.now()),this.remoteAddr=r,this.remotePeer=n,this.direction=t.direction,this.status="open",this.timeline=t.timeline,this.multiplexer=t.multiplexer,this.encryption=t.encryption,this.limits=t.limits,this.log=t.logger.forComponent("libp2p:connection:".concat(this.direction,":").concat(this.id)),null==this.remoteAddr.getPeerId()&&(this.remoteAddr=this.remoteAddr.encapsulate("/p2p/".concat(this.remotePeer))),this._newStream=i,this._close=o,this._abort=a,this._getStreams=s,this.tags=[]}get streams(){return this._getStreams()}newStream(e,t){var n=this;return r((function*(){if("closing"===n.status)throw new Ra("the connection is being closed");if("closed"===n.status)throw new Oa("the connection is closed");if(Array.isArray(e)||(e=[e]),null!=n.limits&&!0!==(null==t?void 0:t.runOnLimitedConnection))throw new Xa("Cannot open protocol stream on limited connection");var r=yield n._newStream(e,t);return r.direction="outbound",r}))()}close(){var e=arguments,n=this;return r((function*(){var r=e.length>0&&void 0!==e[0]?e[0]:{};if("closed"!==n.status&&"closing"!==n.status){if(n.log("closing connection to %a",n.remoteAddr),n.status="closing",null==r.signal){var i=AbortSignal.timeout(500);r=t(t({},r),{},{signal:i})}try{n.log.trace("closing underlying transport"),yield n._close(r),n.log.trace("updating timeline with close time"),n.status="closed",n.timeline.close=Date.now()}catch(e){n.log.error("error encountered during graceful close of connection to %a",n.remoteAddr,e),n.abort(e)}}}))()}abort(e){"closed"!==this.status&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}}function UV(e,t,r){var n=0;return r.streams.forEach((r=>{r.direction===t&&r.protocol===e&&n++})),n}class FV{constructor(t,r){var n,i,o,a,s;e(this,"components",void 0),e(this,"connectionEncrypters",void 0),e(this,"streamMuxers",void 0),e(this,"inboundUpgradeTimeout",void 0),e(this,"inboundStreamProtocolNegotiationTimeout",void 0),e(this,"outboundStreamProtocolNegotiationTimeout",void 0),e(this,"events",void 0),e(this,"metrics",void 0),e(this,Symbol.toStringTag,"@libp2p/upgrader"),this.components=t,this.connectionEncrypters=new Map,r.connectionEncrypters.forEach((e=>{this.connectionEncrypters.set(e.protocol,e)})),this.streamMuxers=new Map,r.streamMuxers.forEach((e=>{this.streamMuxers.set(e.protocol,e)})),this.inboundUpgradeTimeout=null!==(n=r.inboundUpgradeTimeout)&&void 0!==n?n:1e4,this.inboundStreamProtocolNegotiationTimeout=null!==(i=r.inboundStreamProtocolNegotiationTimeout)&&void 0!==i?i:1e4,this.outboundStreamProtocolNegotiationTimeout=null!==(o=r.outboundStreamProtocolNegotiationTimeout)&&void 0!==o?o:1e4,this.events=t.events,this.metrics={dials:null===(a=t.metrics)||void 0===a?void 0:a.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:null===(s=t.metrics)||void 0===s?void 0:s.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}shouldBlockConnection(e){var t=arguments,n=this;return r((function*(){var r=n.components.connectionGater[e];if(null!=r){for(var i=t.length,o=new Array(i>1?i-1:0),a=1;a<i;a++)o[a-1]=t[a];if(!0===(yield r.apply(n.components.connectionGater,o)))throw new mj("The multiaddr connection is blocked by gater.".concat(e))}}))()}createInboundAbortSignal(e){return Ph([AbortSignal.timeout(this.inboundUpgradeTimeout),e])}upgradeInbound(e,n){var i=this;return r((function*(){var r=!1,o=i.createInboundAbortSignal(n.signal);try{var a;if(null===(a=i.metrics.dials)||void 0===a||a.increment({inbound:!0}),!(r=yield i.components.connectionManager.acceptIncomingConnection(e)))throw new wj("Connection denied");yield i.shouldBlockConnection("denyInboundConnection",e),yield i._performUpgrade(e,"inbound",t(t({},n),{},{signal:o}))}catch(e){var s;throw null===(s=i.metrics.errors)||void 0===s||s.increment({inbound:!0}),e}finally{o.clear(),r&&i.components.connectionManager.afterUpgradeInbound()}}))()}upgradeOutbound(e,t){var n=this;return r((function*(){try{var r;null===(r=n.metrics.dials)||void 0===r||r.increment({outbound:!0});var i,o=e.remoteAddr.getPeerId();null!=o&&(i=Du(o),yield n.shouldBlockConnection("denyOutboundConnection",i,e));var a="outbound";return!1===t.initiator&&(a="inbound"),yield n._performUpgrade(e,a,t)}catch(e){var s;throw null===(s=n.metrics.errors)||void 0===s||s.increment({outbound:!0}),e}}))()}_performUpgrade(e,n,i){var o=this;return r((function*(){var r,a,s,l,u,c;null===(r=o.components.metrics)||void 0===r||r.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",n);var d=e;if(!0!==(null==i?void 0:i.skipProtection)){var h=o.components.connectionProtector;null!=h&&(e.log("protecting the %s connection",n),d=yield h.protect(e,i))}try{if(a=d,!0!==(null==i?void 0:i.skipEncryption)){var v;null==i||null===(v=i.onProgress)||void 0===v||v.call(i,new av("upgrader:encrypt-".concat(n,"-connection"))),({conn:a,remotePeer:s,protocol:c,streamMuxer:u}=yield"inbound"===n?o._encryptInbound(d,i):o._encryptOutbound(d,i));var p=t(t({},d),a);yield o.shouldBlockConnection("inbound"===n?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,p)}else{var f=e.remoteAddr.getPeerId();if(null==f)throw new Va("".concat(n," connection that skipped encryption must have a peer id"));var g=Du(f);c="native",s=g}if(s.equals(o.components.peerId)){var y=new ja("Can not dial self");throw e.abort(y),y}if(l=a,null!=(null==i?void 0:i.muxerFactory))u=i.muxerFactory;else if(null==u&&o.streamMuxers.size>0){var m;null==i||null===(m=i.onProgress)||void 0===m||m.call(i,new av("upgrader:multiplex-".concat(n,"-connection")));var w=yield"inbound"===n?o._multiplexInbound(t(t({},d),a),o.streamMuxers,i):o._multiplexOutbound(t(t({},d),a),o.streamMuxers,i);u=w.muxerFactory,l=w.stream}}catch(y){throw e.log.error("failed to upgrade inbound connection %s %a - %e","inbound"===n?"from":"to",e.remoteAddr,y),y}return yield o.shouldBlockConnection("inbound"===n?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e),e.log("successfully upgraded %s connection",n),o._createConnection({cryptoProtocol:c,direction:n,maConn:e,upgradedConn:l,muxerFactory:u,remotePeer:s,limits:null==i?void 0:i.limits})}))()}_createConnection(e){var n,i,o,a,s=this,{cryptoProtocol:l,direction:u,maConn:c,upgradedConn:d,remotePeer:h,muxerFactory:v,limits:p}=e;null!=v&&(i=v.createStreamMuxer({direction:u,onIncomingStream:e=>{null!=a&&Promise.resolve().then(r((function*(){var t,r=s.components.registrar.getProtocols(),n=AbortSignal.timeout(s.inboundStreamProtocolNegotiationTimeout),{stream:i,protocol:o}=yield OV(e,r,{signal:n,log:e.log,yieldBytes:!1});if(null!=a){a.log("incoming stream opened on %s",o);var l=function(e,t){try{var{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return 32}(o,s.components.registrar);if(UV(o,"inbound",a)===l){var u=new es('Too many inbound protocol streams for protocol "'.concat(o,'" - limit ').concat(l));throw e.abort(u),u}e.source=i.source,e.sink=i.sink,e.protocol=o,null!=i.closeWrite&&(e.closeWrite=i.closeWrite),null!=i.closeRead&&(e.closeRead=i.closeRead),null!=i.close&&(e.close=i.close),yield s.components.peerStore.merge(h,{protocols:[o]}),null===(t=s.components.metrics)||void 0===t||t.trackProtocolStream(e,a),s._onStream({connection:a,stream:e,protocol:o})}}))).catch(function(){var t=r((function*(t){a.log.error("error handling incoming stream id %s - %e",e.id,t),null==e.timeline.close&&(yield e.close())}));return function(e){return t.apply(this,arguments)}}())}}),o=function(){var n=r((function*(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null==i)throw new bj("Connection is not multiplexed");a.log.trace("starting new stream for protocols %s",r);var o=yield i.newStream();a.log.trace("started new stream %s for protocols %s",o.id,r);try{var l;if(null==n.signal){o.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",r);var c=AbortSignal.timeout(s.outboundStreamProtocolNegotiationTimeout);n=t(t({},n),{},{signal:c})}o.log.trace("selecting protocol from protocols %s",r);var{stream:d,protocol:v}=yield DV(o,r,t(t({},n),{},{log:o.log,yieldBytes:!0}));o.log.trace("selected protocol %s",v);var p=function(e,t){var r,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{var{options:i}=t.getHandler(e);if(null!=i.maxOutboundStreams)return i.maxOutboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return null!==(r=n.maxOutboundStreams)&&void 0!==r?r:64}(v,s.components.registrar,n),f=UV(v,"outbound",a);if(f>=p){var g=new ts('Too many outbound protocol streams for protocol "'.concat(v,'" - ').concat(f,"/").concat(p));throw o.abort(g),g}return yield s.components.peerStore.merge(h,{protocols:[v]}),o.source=d.source,o.sink=d.sink,o.protocol=v,null!=d.closeWrite&&(o.closeWrite=d.closeWrite),null!=d.closeRead&&(o.closeRead=d.closeRead),null!=d.close&&(o.close=d.close),null===(l=s.components.metrics)||void 0===l||l.trackProtocolStream(o,a),o}catch(g){throw a.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e","inbound"===u?"from":"to",e.maConn.remoteAddr,r,g),null==o.timeline.close&&o.abort(g),g}}));return function(e){return n.apply(this,arguments)}}(),Promise.all([i.sink(d.source),d.sink(i.source)]).catch((e=>{a.log.error("error piping data through muxer - %e",e)})));var f=c.timeline;c.timeline=new Proxy(f,{set:function(){return"close"===(arguments.length<=1?void 0:arguments[1])&&null!=(arguments.length<=2?void 0:arguments[2])&&null==f.close&&r((function*(){try{"open"===a.status&&(yield a.close())}catch(e){a.log.error("error closing connection after timeline close %e",e)}finally{s.events.safeDispatchEvent("connection:close",{detail:a})}}))().catch((e=>{a.log.error("error thrown while dispatching connection:close event %e",e)})),Reflect.set(...arguments)}}),c.timeline.upgraded=Date.now();var g,y;return g={remoteAddr:c.remoteAddr,remotePeer:h,status:"open",direction:u,timeline:c.timeline,multiplexer:null===(n=i)||void 0===n?void 0:n.protocol,encryption:l,limits:p,logger:this.components.logger,newStream:null!=o?o:()=>{throw new bj("Connection is not multiplexed")},getStreams:()=>{var e,t;return null!==(e=null===(t=i)||void 0===t?void 0:t.streams)&&void 0!==e?e:[]},close:(y=r((function*(e){var t;yield null===(t=i)||void 0===t?void 0:t.close(e),yield c.close(e)})),function(e){return y.apply(this,arguments)}),abort:e=>{var t;c.abort(e),null===(t=i)||void 0===t||t.abort(e)}},a=new MV(g),this.events.safeDispatchEvent("connection:open",{detail:a}),a.__maConnTimeline=f,a}_onStream(e){var{connection:t,stream:r,protocol:n}=e,{handler:i,options:o}=this.components.registrar.getHandler(n);if(null!=t.limits&&!0!==o.runOnLimitedConnection)throw new Xa("Cannot open protocol stream on limited connection");i({connection:t,stream:r})}_encryptInbound(e,n){var i=this;return r((function*(){var r=Array.from(i.connectionEncrypters.keys());try{var{stream:o,protocol:a}=yield OV(e,r,t(t({},n),{},{log:e.log})),s=i.connectionEncrypters.get(a);if(null==s)throw new Sj("no crypto module found for ".concat(a));return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,a),t(t({},yield s.secureInbound(o,n)),{},{protocol:a})}catch(t){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,t),new Sj(t.message)}}))()}_encryptOutbound(e,n){var i=this;return r((function*(){var r=Array.from(i.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",r);var{stream:o,protocol:a}=yield DV(e,r,t(t({},n),{},{log:e.log,yieldBytes:!0})),s=i.connectionEncrypters.get(a);if(null==s)throw new Sj("no crypto module found for ".concat(a));return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,a),t(t({},yield s.secureOutbound(o,n)),{},{protocol:a})}catch(t){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,t),new Sj(t.message)}}))()}_multiplexOutbound(e,n,i){return r((function*(){var r=Array.from(n.keys());e.log("outbound selecting muxer %s",r);try{e.log.trace("selecting stream muxer from %s",r);var{stream:o,protocol:a}=yield DV(e,r,t(t({},i),{},{log:e.log,yieldBytes:!0}));return e.log("selected %s as muxer protocol",a),{stream:o,muxerFactory:n.get(a)}}catch(t){throw e.log.error("error multiplexing outbound connection",t),new bj(String(t))}}))()}_multiplexInbound(e,n,i){return r((function*(){var r=Array.from(n.keys());e.log("inbound handling muxers %s",r);try{var{stream:o,protocol:a}=yield OV(e,r,t(t({},i),{},{log:e.log}));return{stream:o,muxerFactory:n.get(a)}}catch(t){throw e.log.error("error multiplexing inbound connection",t),new bj(String(t))}}))()}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}}var zV=new WeakSet;class jV extends os{constructor(r){var n,i,o,a,s,l,u,c,v,p,f,g,y,m,w,b,S,E,k,x,A,C;super(),d(this,zV),e(this,"peerId",void 0),e(this,"peerStore",void 0),e(this,"contentRouting",void 0),e(this,"peerRouting",void 0),e(this,"metrics",void 0),e(this,"services",void 0),e(this,"logger",void 0),e(this,"status",void 0),e(this,"components",void 0),e(this,"log",void 0),this.status="stopped";var I=new os,T=I.dispatchEvent.bind(I);I.dispatchEvent=e=>{var t=T(e),r=this.dispatchEvent(new CustomEvent(e.type,{detail:e.detail}));return t||r},this.peerId=r.peerId,this.logger=null!==(n=r.logger)&&void 0!==n?n:ad(),this.log=this.logger.forComponent("libp2p"),this.services={};var P=null!==(i=null===(o=r.nodeInfo)||void 0===o?void 0:o.name)&&void 0!==i?i:rz,_=null!==(a=null===(s=r.nodeInfo)||void 0===s?void 0:s.version)&&void 0!==a?a:tz,B=this.components=function(){var e=new kj(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{});return new Proxy(e,{get(t,r,n){if("string"==typeof r&&!Aj.includes(r)){var i=e.components[r];if(null==i&&!xj.includes(r))throw new sj("".concat(r," not set"));return i}return Reflect.get(t,r,n)},set:(t,r,n)=>("string"==typeof r?e.components[r]=n:Reflect.set(t,r,n),!0)})}({peerId:r.peerId,privateKey:r.privateKey,nodeInfo:{name:P,version:_,userAgent:null!==(l=null===(u=r.nodeInfo)||void 0===u?void 0:u.userAgent)&&void 0!==l?l:nz(P,_)},logger:this.logger,events:I,datastore:null!==(c=r.datastore)&&void 0!==c?c:new xc,connectionGater:Pj(r.connectionGater),dns:r.dns});this.peerStore=this.configureComponent("peerStore",function(e){return new Kz(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}(B,t({addressFilter:this.components.connectionGater.filterMultiaddrForPeer},r.peerStore))),null!=r.metrics&&(this.metrics=this.configureComponent("metrics",r.metrics(this.components))),B.events.addEventListener("peer:update",(e=>{if(null==e.detail.previous){var t={id:e.detail.peer.id,multiaddrs:e.detail.peer.addresses.map((e=>e.multiaddr))};B.events.safeDispatchEvent("peer:discovery",{detail:t})}})),null!=r.connectionProtector&&this.configureComponent("connectionProtector",r.connectionProtector(B)),this.components.upgrader=new FV(this.components,{connectionEncrypters:(null!==(v=r.connectionEncrypters)&&void 0!==v?v:[]).map(((e,t)=>this.configureComponent("connection-encryption-".concat(t),e(this.components)))),streamMuxers:(null!==(p=r.streamMuxers)&&void 0!==p?p:[]).map(((e,t)=>this.configureComponent("stream-muxers-".concat(t),e(this.components)))),inboundUpgradeTimeout:null===(f=r.connectionManager)||void 0===f?void 0:f.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:null!==(g=null===(y=r.connectionManager)||void 0===y?void 0:y.inboundStreamProtocolNegotiationTimeout)&&void 0!==g?g:null===(m=r.connectionManager)||void 0===m?void 0:m.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:null!==(w=null===(b=r.connectionManager)||void 0===b?void 0:b.outboundStreamProtocolNegotiationTimeout)&&void 0!==w?w:null===(S=r.connectionManager)||void 0===S?void 0:S.protocolNegotiationTimeout}),this.configureComponent("transportManager",new kV(this.components,r.transportManager)),this.configureComponent("connectionManager",new yV(this.components,r.connectionManager)),!1!==(null===(E=r.connectionMonitor)||void 0===E?void 0:E.enabled)&&this.configureComponent("connectionMonitor",new mV(this.components,r.connectionMonitor)),this.configureComponent("registrar",new EV(this.components)),this.configureComponent("addressManager",new aj(this.components,r.addresses));var N=(null!==(k=r.peerRouters)&&void 0!==k?k:[]).map(((e,t)=>this.configureComponent("peer-router-".concat(t),e(this.components))));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new bV(this.components,{routers:N}));var D=(null!==(x=r.contentRouters)&&void 0!==x?x:[]).map(((e,t)=>this.configureComponent("content-router-".concat(t),e(this.components))));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new wV(this.components,{routers:D})),this.configureComponent("randomWalk",new SV(this.components)),(null!==(A=r.peerDiscovery)&&void 0!==A?A:[]).forEach(((e,t)=>{this.configureComponent("peer-discovery-".concat(t),e(this.components)).addEventListener("peer",(e=>{h(zV,this,VV).call(this,e)}))})),null===(C=r.transports)||void 0===C||C.forEach(((e,t)=>{this.components.transportManager.add(this.configureComponent("transport-".concat(t),e(this.components)))})),null!=r.services)for(var R of Object.keys(r.services)){var O,L,M=(0,r.services[R])(this.components);if(null!=M){if(this.services[R]=M,this.configureComponent(R,M),null!=M[wa]&&(this.log("registering service %s for content routing",R),D.push(M[wa])),null!=M[xa]&&(this.log("registering service %s for peer routing",R),N.push(M[xa])),null!=M[ba])this.log("registering service %s for peer discovery",R),null===(O=(L=M[ba]).addEventListener)||void 0===O||O.call(L,"peer",(e=>{h(zV,this,VV).call(this,e)}))}else this.log.error("service factory %s returned null or undefined instance",R)}!function(e){var t={};for(var r of Object.values(e.components))for(var n of Cj(r))t[n]=!0;for(var i of Object.values(e.components))for(var o of Ij(i))if(!0!==t[o])throw new lj('Service "'.concat(Tj(i),'" required capability "').concat(o,'" but it was not provided by any component, you may need to add additional configuration when creating your node.'))}(B)}configureComponent(e,t){return null==t&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}start(){var e=this;return r((function*(){if("stopped"===e.status){e.status="starting",e.log("libp2p is starting");try{var t,r,n,i;yield null===(t=(r=e.components).beforeStart)||void 0===t?void 0:t.call(r),yield e.components.start(),yield null===(n=(i=e.components).afterStart)||void 0===n?void 0:n.call(i),e.status="started",e.safeDispatchEvent("start",{detail:e}),e.log("libp2p has started")}catch(t){throw e.log.error("An error occurred starting libp2p",t),e.status="started",yield e.stop(),t}}}))()}stop(){var e=this;return r((function*(){var t,r,n,i;"started"===e.status&&(e.log("libp2p is stopping"),e.status="stopping",yield null===(t=(r=e.components).beforeStop)||void 0===t?void 0:t.call(r),yield e.components.stop(),yield null===(n=(i=e.components).afterStop)||void 0===n?void 0:n.call(i),e.status="stopped",e.safeDispatchEvent("stop",{detail:e}),e.log("libp2p has stopped"))}))()}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){var e=new zh;for(var t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}dial(e){var n=arguments,i=this;return r((function*(){var r=n.length>1&&void 0!==n[1]?n[1]:{};return i.components.connectionManager.openConnection(e,t({priority:75},r))}))()}dialProtocol(e,t){var n=arguments,i=this;return r((function*(){var r=n.length>2&&void 0!==n[2]?n[2]:{};if(null==t)throw new _a("no protocols were provided to open a stream");if(0===(t=Array.isArray(t)?t:[t]).length)throw new _a("no protocols were provided to open a stream");return(yield i.dial(e,r)).newStream(t,r)}))()}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}hangUp(e){var t=arguments,n=this;return r((function*(){var r,i=t.length>1&&void 0!==t[1]?t[1]:{};Er(e)&&(e=Du(null!==(r=e.getPeerId())&&void 0!==r?r:""));yield n.components.connectionManager.closeConnections(e,i)}))()}getPublicKey(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};if(n.log("getPublicKey %p",e),null!=e.publicKey)return e.publicKey;try{var i=yield n.peerStore.get(e);if(null!=i.id.publicKey)return i.id.publicKey}catch(e){if("NotFoundError"!==e.name)throw e}var o=Mt([Et("/pk/"),e.toMultihash().bytes]),a=mu(yield n.contentRouting.get(o,r));return yield n.peerStore.patch(e,{publicKey:a}),a}))()}handle(e,t,n){var i=this;return r((function*(){Array.isArray(e)||(e=[e]),yield Promise.all(e.map(function(){var e=r((function*(e){yield i.components.registrar.handle(e,t,n)}));return function(t){return e.apply(this,arguments)}}()))}))()}unhandle(e){var t=this;return r((function*(){Array.isArray(e)||(e=[e]),yield Promise.all(e.map(function(){var e=r((function*(e){yield t.components.registrar.unhandle(e)}));return function(t){return e.apply(this,arguments)}}()))}))()}register(e,t){var n=this;return r((function*(){return n.components.registrar.register(e,t)}))()}unregister(e){this.components.registrar.unregister(e)}isDialable(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};return n.components.connectionManager.isDialable(e,r)}))()}}function VV(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 qV(){return HV.apply(this,arguments)}function HV(){return HV=r((function*(){var e,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};null!==(e=r.privateKey)&&void 0!==e||(r.privateKey=yield gu("Ed25519"));var n=new jV(t(t({},yield function(e){return pz.apply(this,arguments)}(r)),{},{peerId:Ou(r.privateKey)}));return!1!==r.start&&(yield n.start()),n})),HV.apply(this,arguments)}function KV(){return KV=r((function*(e){var r,n,i=null!==(r=e.libp2p)&&void 0!==r?r:{};null==i.privateKey&&null!=e.datastore&&(i.privateKey=yield function(e){return az.apply(this,arguments)}(e.datastore,e.keychain));var o=oz(i);return o.datastore=null!==(n=o.datastore)&&void 0!==n?n:e.datastore,yield qV(t(t(t({},o),i),{},{start:!1}))})),KV.apply(this,arguments)}function WV(){return GV.apply(this,arguments)}function GV(){return GV=r((function*(){var e,r,n,i,o,a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},s=null!==(e=a.datastore)&&void 0!==e?e:new xc,l=null!==(r=a.blockstore)&&void 0!==r?r:new cd;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 KV.apply(this,arguments)}(t(t({},a),{},{libp2p:t(t({dns:a.dns},a.libp2p),{},{start:void 0}),datastore:s}));var u=new ZR(t(t({},a),{},{libp2p:o,datastore:s,blockstore:l,blockBrokers:null!==(n=a.blockBrokers)&&void 0!==n?n:[ND(),rD()],routers:null!==(i=a.routers)&&void 0!==i?i:[JR(o),QR()],metrics:o.metrics}));return!1!==a.start&&(yield u.start()),u})),GV.apply(this,arguments)}function QV(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return t=Number(t),null!=e[Symbol.asyncIterator]?l((function*(){var r=[];if(t<1&&(t=1),t!==Math.round(t))throw new Error("Batch size must be an integer");var n,i=!1,o=!1;try{for(var a,l=s(e);i=!(a=yield u(l.next())).done;i=!1){var c=a.value;for(r.push(c);r.length>=t;)yield r.slice(0,t),r=r.slice(t)}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}for(;r.length>0;)yield r.slice(0,t),r=r.slice(t)}))():function*(){var r=[];if(t<1&&(t=1),t!==Math.round(t))throw new Error("Batch size must be an integer");for(var n of e)for(r.push(n);r.length>=t;)yield r.slice(0,t),r=r.slice(t);for(;r.length>0;)yield r.slice(0,t),r=r.slice(t)}()}function YV(e){return JV.apply(this,arguments)}function JV(){return JV=l((function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return function*(){var n,i=!1,o=!1;try{for(var a,l=s(QV(e,t));i=!(a=yield u(l.next())).done;i=!1)for(var c=a.value.map(function(){var e=r((function*(e){return e().then((e=>({ok:!0,value:e})),(e=>({ok:!1,err:e})))}));return function(t){return e.apply(this,arguments)}}()),d=0;d<c.length;d++){var h=yield u(c[d]);if(!h.ok)throw h.err;yield h.value}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}()})),JV.apply(this,arguments)}var ZV,$V,XV,eq=function(){var e,t=null!==(e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).chunkSize)&&void 0!==e?e:262144;return function(){var e=l((function*(e){var r,n=new gs,i=0,o=!1,a=!1,l=!1;try{for(var c,d=s(e);a=!(c=yield u(d.next())).done;a=!1){var h=c.value;for(n.append(h),i+=h.length;i>=t;)if(yield n.slice(0,t),o=!0,t===n.length)n=new gs,i=0;else{var v=new gs;v.append(n.sublist(t)),n=v,i-=t}}}catch(e){l=!0,r=e}finally{try{a&&null!=d.return&&(yield u(d.return()))}finally{if(l)throw r}}(!o||i>0)&&(yield n.subarray(0,i))}));return function(t){return e.apply(this,arguments)}}()};class tq extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid type"),e(this,"name",tq.name),e(this,"code",tq.code)}}e(tq,"name","InvalidTypeError"),e(tq,"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=()=>ql(r)}(e.DataType||(e.DataType={})),e.codec=()=>(null==n&&(n=Hl((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),$V.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=$V.codec().decode(t,t.uint32());break;default:t.skipType(7&o)}}return n}))),n),e.encode=t=>jl(t,e.codec()),e.decode=t=>wl(t,e.codec())}(ZV||(ZV={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((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=>jl(t,e.codec()),e.decode=t=>wl(t,e.codec())}($V||($V={})),function(e){var t;e.codec=()=>(null==t&&(t=Hl((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=>jl(t,e.codec()),e.decode=t=>wl(t,e.codec())}(XV||(XV={}));var rq={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},nq=["directory","hamt-sharded-directory"],iq=parseInt("0644",8),oq=parseInt("0755",8);let aq=class t{static unmarshal(e){var r,n,i=ZV.decode(e),o=new t({type:rq[null!=i.Type?i.Type.toString():"File"],data:i.Data,blockSizes:i.blocksizes,mode:i.mode,mtime:null!=i.mtime?{secs:null!==(r=i.mtime.Seconds)&&void 0!==r?r:0n,nsecs:i.mtime.FractionalNanoseconds}:void 0,fanout:i.fanout});return o._originalMode=null!==(n=i.mode)&&void 0!==n?n:0,o}constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{type:"file"};e(this,"type",void 0),e(this,"data",void 0),e(this,"blockSizes",void 0),e(this,"hashType",void 0),e(this,"fanout",void 0),e(this,"mtime",void 0),e(this,"_mode",void 0),e(this,"_originalMode",void 0);var{type:r,data:n,blockSizes:i,hashType:o,fanout:a,mtime:s,mode:l}=t;if(null!=r&&!Object.values(rq).includes(r))throw new tq("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()?oq:iq:4095&e}get mode(){return this._mode}isDirectory(){return nq.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=ZV.DataType.Raw;break;case"directory":e=ZV.DataType.Directory;break;case"file":e=ZV.DataType.File;break;case"metadata":e=ZV.DataType.Metadata;break;case"symlink":e=ZV.DataType.Symlink;break;case"hamt-sharded-directory":e=ZV.DataType.HAMTShard;break;default:throw new tq("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))!==iq||this.isDirectory()||(t=void 0),t===oq&&this.isDirectory()&&(t=void 0));return null!=this.mtime&&(n={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),ZV.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 sq=function(){var e=r((function*(e,t,r){null==r.codec&&(r.codec=LN);var n=yield $e.digest(e),i=it.create(r.cidVersion,r.codec.code,n);return yield t.put(i,e,r),i}));return function(t,r,n){return e.apply(this,arguments)}}();function lq(e){return function(){var t=l((function*(t,n){var i,o=0n,a=!1,l=!1;try{for(var c,d=function*(){var i=c.value;yield r((function*(){var r,a,s={codec:LN,cidVersion:e.cidVersion,onProgress:e.onProgress};e.rawLeaves?(s.codec=Ee,s.cidVersion=1):(a=new aq({type:e.leafType,data:i}),i=RN({Data:a.marshal(),Links:[]}));var l=yield sq(i,n,s);return o+=BigInt(i.byteLength),null===(r=e.onProgress)||void 0===r||r.call(e,new av("unixfs:importer:progress:file:write",{bytesWritten:o,cid:l,path:t.path})),{cid:l,unixfs:a,size:BigInt(i.length),block:i}}))},h=s(t.content);a=!(c=yield u(h.next())).done;a=!1)yield*d()}catch(e){l=!0,i=e}finally{try{a&&null!=h.return&&(yield u(h.return()))}finally{if(l)throw i}}}));return function(e,r){return t.apply(this,arguments)}}()}let uq=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid parameters"),e(this,"name",t.name),e(this,"code",t.code)}};e(uq,"name","InvalidParametersError"),e(uq,"code","ERR_INVALID_PARAMS");class cq extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid avg chunk size"),e(this,"name",cq.name),e(this,"code",cq.code)}}e(cq,"name","InvalidAvgChunkSizeError"),e(cq,"code","ERR_INVALID_AVG_CHUNK_SIZE");class dq extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid chunk size"),e(this,"name",dq.name),e(this,"code",dq.code)}}e(dq,"name","InvalidChunkSizeError"),e(dq,"code","ERR_INVALID_CHUNK_SIZE");class hq extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid min chunk size"),e(this,"name",hq.name),e(this,"code",hq.code)}}e(hq,"name","InvalidMinChunkSizeError"),e(hq,"code","ERR_INVALID_MIN_CHUNK_SIZE");class vq extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid content"),e(this,"name",vq.name),e(this,"code",vq.code)}}e(vq,"name","InvalidContentError"),e(vq,"code","ERR_INVALID_CONTENT");var pq=function(){var e=r((function*(e,t,r){var n=new aq({type:"directory",mtime:e.mtime,mode:e.mode}),i=RN(BN({Data:n.marshal()}));return{cid:yield sq(i,t,r),path:e.path,unixfs:n,size:BigInt(i.length),originalPath:e.originalPath,block:i}}));return function(t,r,n){return e.apply(this,arguments)}}();function fq(){return fq=l((function*(e,r,n){var i,o,a=-1,l=!1,c=!1;try{for(var d,h=s(YV(n.bufferImporter(e,r),n.blockWriteConcurrency));l=!(d=yield u(h.next())).done;l=!1){var v=d.value;0!==++a?(1===a&&null!=i&&(yield t(t({},i),{},{block:void 0,single:void 0}),i=void 0),yield t(t({},v),{},{block:void 0})):i=t(t({},v),{},{single:!0})}}catch(e){c=!0,o=e}finally{try{l&&null!=h.return&&(yield u(h.return()))}finally{if(c)throw o}}null!=i&&(yield i)})),fq.apply(this,arguments)}function gq(e){return!0===e.single}var yq=(e,n,i)=>{var o=function(){var o=r((function*(r){var o;if(1===r.length&&gq(r[0])&&i.reduceSingleLeafToSelf){var a,s=r[0],l=s.block;return!gq(s)||void 0===e.mtime&&void 0===e.mode||(s.unixfs=new aq({type:"file",mtime:e.mtime,mode:e.mode,data:s.block}),l={Data:s.unixfs.marshal(),Links:[]},s.block=RN(BN(l)),s.cid=yield sq(s.block,n,t(t({},i),{},{cidVersion:i.cidVersion})),s.size=BigInt(s.block.length)),null===(a=i.onProgress)||void 0===a||a.call(i,new av("unixfs:importer:progress:file:layout",{cid:s.cid,path:s.originalPath})),{cid:s.cid,path:e.path,unixfs:s.unixfs,size:s.size,originalPath:s.originalPath}}var u=new aq({type:"file",mtime:e.mtime,mode:e.mode}),c=r.filter((e=>{var t;return e.cid.code===Se&&e.size>0||(null!=e.unixfs&&null==e.unixfs.data&&e.unixfs.fileSize()>0n||Boolean(null===(t=e.unixfs)||void 0===t||null===(t=t.data)||void 0===t?void 0:t.length))})).map((e=>{var t,r,n;if(e.cid.code===Se)return u.addBlockSize(e.size),{Name:"",Tsize:Number(e.size),Hash:e.cid};null==(null===(t=e.unixfs)||void 0===t?void 0:t.data)?u.addBlockSize(null!==(r=null===(n=e.unixfs)||void 0===n?void 0:n.fileSize())&&void 0!==r?r:0n):u.addBlockSize(BigInt(e.unixfs.data.length));return{Name:"",Tsize:Number(e.size),Hash:e.cid}})),d={Data:u.marshal(),Links:c},h=RN(BN(d)),v=yield sq(h,n,i);return null===(o=i.onProgress)||void 0===o||o.call(i,new av("unixfs:importer:progress:file:layout",{cid:v,path:e.originalPath})),{cid:v,path:e.path,unixfs:u,size:BigInt(h.length+d.Links.reduce(((e,t)=>{var r;return e+(null!==(r=t.Tsize)&&void 0!==r?r:0)}),0)),originalPath:e.originalPath,block:h}}));return function(e){return o.apply(this,arguments)}}();return o},mq=function(){var e=r((function*(e,t,r){return r.layout(function(e,t,r){return fq.apply(this,arguments)}(e,t,r),yq(e,t,r))}));return function(t,r,n){return e.apply(this,arguments)}}();function wq(e){try{if(e instanceof Uint8Array)return l((function*(){yield e}))();if(t=e,Symbol.iterator in t)return l((function*(){yield*c(s(e),u)}))();if(function(e){return Symbol.asyncIterator in e}(e))return e}catch(e){throw new vq("Content was invalid")}var t;throw new vq("Content was invalid")}var bq=()=>function(){var e=l((function*(e){var t,r=!1,n=!1;try{for(var i,o=s(e);r=!(i=yield u(o.next())).done;r=!1){var a=i.value;if(void 0===a.length)throw new vq("Content was invalid");if("string"==typeof a||a instanceof String)yield Et(a.toString());else if(Array.isArray(a))yield Uint8Array.from(a);else{if(!(a instanceof Uint8Array))throw new vq("Content was invalid");yield a}}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw t}}}));return function(t){return e.apply(this,arguments)}}();function Sq(e){var t,n=null!==(t=null==e?void 0:e.maxChildrenPerNode)&&void 0!==t?t:174;return function(){var e=r((function*(e,r){var i,o=[],a=!1,l=!1;try{for(var u,c=s(QV(e,n));a=!(u=yield c.next()).done;a=!1){var d=u.value;o.push(yield r(d))}}catch(e){l=!0,i=e}finally{try{a&&null!=c.return&&(yield c.return())}finally{if(l)throw i}}return o.length>1?t(o,r):o[0]}));function t(t,r){return e.apply(this,arguments)}return t}()}let Eq=class{constructor(t,r){e(this,"options",void 0),e(this,"root",void 0),e(this,"dir",void 0),e(this,"path",void 0),e(this,"dirty",void 0),e(this,"flat",void 0),e(this,"parent",void 0),e(this,"parentKey",void 0),e(this,"unixfs",void 0),e(this,"mode",void 0),e(this,"mtime",void 0),e(this,"cid",void 0),e(this,"size",void 0),e(this,"nodeSize",void 0),this.options=null!=r?r:{},this.root=t.root,this.dir=t.dir,this.path=t.path,this.dirty=t.dirty,this.flat=t.flat,this.parent=t.parent,this.parentKey=t.parentKey,this.unixfs=t.unixfs,this.mode=t.mode,this.mtime=t.mtime}};var kq=it.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),xq=it.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");class Aq extends Eq{constructor(t,r){super(t,r),e(this,"_children",void 0),this._children=new Map}put(e,t){var n=this;return r((function*(){n.cid=void 0,n.size=void 0,n.nodeSize=void 0,n._children.set(e,t)}))()}get(e){var t=this;return r((function*(){return Promise.resolve(t._children.get(e))}))()}childCount(){return this._children.size}directChildrenCount(){return this.childCount()}onlyChild(){return this._children.values().next().value}eachChildSeries(){var e=this;return l((function*(){for(var[t,r]of e._children.entries())yield{key:t,child:r}}))()}estimateNodeSize(){if(void 0!==this.nodeSize)return this.nodeSize;for(var[e,t]of(this.nodeSize=0,this._children.entries()))null!=t.size&&null!=t.cid&&(this.nodeSize+=e.length+(1===this.options.cidVersion?xq.bytes.byteLength:kq.bytes.byteLength));return this.nodeSize}flush(e){var t=this;return l((function*(){var r=[];for(var[n,i]of t._children.entries()){var o=i;if(i instanceof Eq){var a,l=!1,c=!1;try{for(var d,h=s(i.flush(e));l=!(d=yield u(h.next())).done;l=!1){var v=d.value;o=v,yield v}}catch(e){c=!0,a=e}finally{try{l&&null!=h.return&&(yield u(h.return()))}finally{if(c)throw a}}}null!=o.size&&null!=o.cid&&r.push({Name:n,Tsize:Number(o.size),Hash:o.cid})}var p=new aq({type:"directory",mtime:t.mtime,mode:t.mode}),f={Data:p.marshal(),Links:r},g=RN(BN(f)),y=yield u(sq(g,e,t.options)),m=g.length+f.Links.reduce(((e,t)=>{var r;return e+(null!==(r=t.Tsize)&&void 0!==r?r:0)}),0);t.cid=y,t.size=m,yield{cid:y,unixfs:p,path:t.path,size:BigInt(m)}}))()}}var Cq,Iq,Tq,Pq={exports:{}};var _q=Tq?Iq:(Tq=1,Cq||(Cq=1,function(e,t){!function(r,n){var i={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function o(e){if(!Array.isArray(e)&&!ArrayBuffer.isView(e))return!1;for(var t=0;t<e.length;t++)if(!Number.isInteger(e[t])||e[t]<0||e[t]>255)return!1;return!0}function a(e,t){return(65535&e)*t+(((e>>>16)*t&65535)<<16)}function s(e,t){return e<<t|e>>>32-t}function l(e){return e=a(e^=e>>>16,2246822507),(e=a(e^=e>>>13,3266489909))^e>>>16}function u(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]+t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]+t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]+t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]+t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function c(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]*t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]*t[3],r[1]+=r[2]>>>16,r[2]&=65535,r[2]+=e[3]*t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]*t[3],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[2]*t[2],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[3]*t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]*t[3]+e[1]*t[2]+e[2]*t[1]+e[3]*t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function d(e,t){return 32==(t%=64)?[e[1],e[0]]:t<32?[e[0]<<t|e[1]>>>32-t,e[1]<<t|e[0]>>>32-t]:(t-=32,[e[1]<<t|e[0]>>>32-t,e[0]<<t|e[1]>>>32-t])}function h(e,t){return 0==(t%=64)?e:t<32?[e[0]<<t|e[1]>>>32-t,e[1]<<t]:[e[1]<<t-32,0]}function v(e,t){return[e[0]^t[0],e[1]^t[1]]}function p(e){return e=v(e,[0,e[0]>>>1]),e=v(e=c(e,[4283543511,3981806797]),[0,e[0]>>>1]),v(e=c(e,[3301882366,444984403]),[0,e[0]>>>1])}i.x86.hash32=function(e,t){if(i.inputValidation&&!o(e))return n;t=t||0;for(var r=e.length%4,u=e.length-r,c=t,d=0,h=3432918353,v=461845907,p=0;p<u;p+=4)d=a(d=e[p]|e[p+1]<<8|e[p+2]<<16|e[p+3]<<24,h),d=a(d=s(d,15),v),c=a(c=s(c^=d,13),5)+3864292196;switch(d=0,r){case 3:d^=e[p+2]<<16;case 2:d^=e[p+1]<<8;case 1:d=a(d^=e[p],h),c^=d=a(d=s(d,15),v)}return(c=l(c^=e.length))>>>0},i.x86.hash128=function(e,t){if(i.inputValidation&&!o(e))return n;t=t||0;for(var r=e.length%16,u=e.length-r,c=t,d=t,h=t,v=t,p=0,f=0,g=0,y=0,m=597399067,w=2869860233,b=951274213,S=2716044179,E=0;E<u;E+=16)p=e[E]|e[E+1]<<8|e[E+2]<<16|e[E+3]<<24,f=e[E+4]|e[E+5]<<8|e[E+6]<<16|e[E+7]<<24,g=e[E+8]|e[E+9]<<8|e[E+10]<<16|e[E+11]<<24,y=e[E+12]|e[E+13]<<8|e[E+14]<<16|e[E+15]<<24,p=s(p=a(p,m),15),c=s(c^=p=a(p,w),19),c=a(c+=d,5)+1444728091,f=s(f=a(f,w),16),d=s(d^=f=a(f,b),17),d=a(d+=h,5)+197830471,g=s(g=a(g,b),17),h=s(h^=g=a(g,S),15),h=a(h+=v,5)+2530024501,y=s(y=a(y,S),18),v=s(v^=y=a(y,m),13),v=a(v+=c,5)+850148119;switch(p=0,f=0,g=0,y=0,r){case 15:y^=e[E+14]<<16;case 14:y^=e[E+13]<<8;case 13:y=a(y^=e[E+12],S),v^=y=a(y=s(y,18),m);case 12:g^=e[E+11]<<24;case 11:g^=e[E+10]<<16;case 10:g^=e[E+9]<<8;case 9:g=a(g^=e[E+8],b),h^=g=a(g=s(g,17),S);case 8:f^=e[E+7]<<24;case 7:f^=e[E+6]<<16;case 6:f^=e[E+5]<<8;case 5:f=a(f^=e[E+4],w),d^=f=a(f=s(f,16),b);case 4:p^=e[E+3]<<24;case 3:p^=e[E+2]<<16;case 2:p^=e[E+1]<<8;case 1:p=a(p^=e[E],m),c^=p=a(p=s(p,15),w)}return c^=e.length,c+=d^=e.length,c+=h^=e.length,d+=c+=v^=e.length,h+=c,v+=c,c=l(c),c+=d=l(d),c+=h=l(h),d+=c+=v=l(v),h+=c,v+=c,("00000000"+(c>>>0).toString(16)).slice(-8)+("00000000"+(d>>>0).toString(16)).slice(-8)+("00000000"+(h>>>0).toString(16)).slice(-8)+("00000000"+(v>>>0).toString(16)).slice(-8)},i.x64.hash128=function(e,t){if(i.inputValidation&&!o(e))return n;t=t||0;for(var r=e.length%16,a=e.length-r,s=[0,t],l=[0,t],f=[0,0],g=[0,0],y=[2277735313,289559509],m=[1291169091,658871167],w=0;w<a;w+=16)f=[e[w+4]|e[w+5]<<8|e[w+6]<<16|e[w+7]<<24,e[w]|e[w+1]<<8|e[w+2]<<16|e[w+3]<<24],g=[e[w+12]|e[w+13]<<8|e[w+14]<<16|e[w+15]<<24,e[w+8]|e[w+9]<<8|e[w+10]<<16|e[w+11]<<24],f=d(f=c(f,y),31),s=u(s=d(s=v(s,f=c(f,m)),27),l),s=u(c(s,[0,5]),[0,1390208809]),g=d(g=c(g,m),33),l=u(l=d(l=v(l,g=c(g,y)),31),s),l=u(c(l,[0,5]),[0,944331445]);switch(f=[0,0],g=[0,0],r){case 15:g=v(g,h([0,e[w+14]],48));case 14:g=v(g,h([0,e[w+13]],40));case 13:g=v(g,h([0,e[w+12]],32));case 12:g=v(g,h([0,e[w+11]],24));case 11:g=v(g,h([0,e[w+10]],16));case 10:g=v(g,h([0,e[w+9]],8));case 9:g=c(g=v(g,[0,e[w+8]]),m),l=v(l,g=c(g=d(g,33),y));case 8:f=v(f,h([0,e[w+7]],56));case 7:f=v(f,h([0,e[w+6]],48));case 6:f=v(f,h([0,e[w+5]],40));case 5:f=v(f,h([0,e[w+4]],32));case 4:f=v(f,h([0,e[w+3]],24));case 3:f=v(f,h([0,e[w+2]],16));case 2:f=v(f,h([0,e[w+1]],8));case 1:f=c(f=v(f,[0,e[w]]),y),s=v(s,f=c(f=d(f,31),m))}return s=u(s=v(s,[0,e.length]),l=v(l,[0,e.length])),l=u(l,s),s=u(s=p(s),l=p(l)),l=u(l,s),("00000000"+(s[0]>>>0).toString(16)).slice(-8)+("00000000"+(s[1]>>>0).toString(16)).slice(-8)+("00000000"+(l[0]>>>0).toString(16)).slice(-8)+("00000000"+(l[1]>>>0).toString(16)).slice(-8)},e.exports&&(t=e.exports=i),t.murmurHash3=i}()}(Pq,Pq.exports)),Iq=Pq.exports),Bq=a(_q);Ye({name:"murmur3-32",code:35,encode:e=>function(e){for(var t=new Array(4),r=0;r<4;r++)t[r]=255&e,e>>=8;return new Uint8Array(t)}(Bq.x86.hash32(e))});var Nq,Dq,Rq=Ye({name:"murmur3-128",code:34,encode:e=>S(Bq.x64.hash128(e))});Ye({name:"murmur3-x64-64",code:34,encode:e=>S(Bq.x64.hash128(e)).subarray(0,8)});var Oq=function(){if(Dq)return Nq;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 Dq=1,Nq=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)}},Nq}(),Lq=a(Oq);class Mq{constructor(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;e(this,"_options",void 0),e(this,"_popCount",void 0),e(this,"_parent",void 0),e(this,"_posAtParent",void 0),e(this,"_children",void 0),e(this,"key",void 0),this._options=t,this._popCount=0,this._parent=r,this._posAtParent=n,this._children=new Lq,this.key=null}put(e,t){var n=this;return r((function*(){var r=yield n._findNewBucketAndPos(e);r.bucket._putAt(r,e,t)}))()}get(e){var t=this;return r((function*(){var r=yield t._findChild(e);if(null!=r)return r.value}))()}del(e){var t=this;return r((function*(){var r=yield t._findPlace(e),n=r.bucket._at(r.pos);null!=n&&n.key===e&&r.bucket._delAt(r.pos)}))()}leafCount(){return this._children.compactArray().reduce(((e,t)=>t instanceof Mq?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 Mq?yield*t.eachLeafSeries():yield t}serialize(e,t){return t(this._children.reduce(((r,n,i)=>(null!=n&&(n instanceof Mq?r.push(n.serialize(e,t)):r.push(e(n,i))),r)),[]))}asyncTransform(e,t){var n=this;return r((function*(){return jq(n,e,t)}))()}toJSON(){return this.serialize(Fq,zq)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}_findChild(e){var t=this;return r((function*(){var r=yield t._findPlace(e),n=r.bucket._at(r.pos);if(!(n instanceof Mq))return null!=n&&n.key===e?n:void 0}))()}_findPlace(e){var t=this;return r((function*(){var r=t._options.hash("string"==typeof e?Et(e):e),n=yield r.take(t._options.bits),i=t._children.get(n);return i instanceof Mq?i._findPlace(r):{bucket:t,pos:n,hash:r,existingChild:i}}))()}_findNewBucketAndPos(e){var t=this;return r((function*(){var r=yield t._findPlace(e);if(null!=r.existingChild&&r.existingChild.key!==e){var n=new Mq(t._options,r.bucket,r.pos);r.bucket._putObjectAt(r.pos,n);var i=yield n._findPlace(r.existingChild.hash);return i.bucket._putAt(i,r.existingChild.key,r.existingChild.value),n._findNewBucketAndPos(r.hash)}return r}))()}_putAt(e,t,r){this._putObjectAt(e.pos,{key:t,value:r,hash:e.hash})}_putObjectAt(e,t){null==this._children.get(e)&&this._popCount++,this._children.set(e,t)}_delAt(e){if(-1===e)throw new Error("Invalid position");null!=this._children.get(e)&&this._popCount--,this._children.unset(e),this._level()}_level(){if(null!=this._parent&&this._popCount<=1)if(1===this._popCount){var e=this._children.find(Uq);if(null!=e&&!(e instanceof Mq)){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 Uq(e){return Boolean(e)}function Fq(e,t){return e.key}function zq(e){return e}function jq(e,t,r){return Vq.apply(this,arguments)}function Vq(){return(Vq=r((function*(e,t,r){var n=[];for(var i of e._children.compactArray())if(i instanceof Mq)yield jq(i,t,r);else{var o=yield t(i);n.push({bitField:e._children.bitField(),children:o})}return r(n)}))).apply(this,arguments)}var qq=[255,254,252,248,240,224,192,128],Hq=[1,3,7,15,31,63,127,255];let Kq=class{constructor(t){e(this,"_value",void 0),e(this,"_currentBytePos",void 0),e(this,"_currentBitPos",void 0),this._value=t,this._currentBytePos=t.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+8*this._currentBytePos}totalBits(){return 8*this._value.length}take(e){for(var t=e,r=0;t>0&&this._haveBits();){var n=this._value[this._currentBytePos],i=this._currentBitPos+1,o=Math.min(i,t);r=(r<<o)+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}function Gq(e){return function(t){return t instanceof Qq?t:new Qq(t,e)}}let Qq=class{constructor(t,r){if(e(this,"_value",void 0),e(this,"_hashFn",void 0),e(this,"_depth",void 0),e(this,"_availableBits",void 0),e(this,"_currentBufferIndex",void 0),e(this,"_buffers",void 0),!(t instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=t,this._hashFn=r,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}take(e){var t=this;return r((function*(){for(var r=e;t._availableBits<r;)yield t._produceMoreBits();for(var n=0;r>0;){var i=t._buffers[t._currentBufferIndex],o=Math.min(i.availableBits(),r);n=(n<<o)+i.take(o),r-=o,t._availableBits-=o,0===i.availableBits()&&t._currentBufferIndex++}return n}))()}untake(e){for(var t=e;t>0;){var r=this._buffers[this._currentBufferIndex],n=Math.min(r.totalBits()-r.availableBits(),t);r.untake(n),t-=n,this._availableBits+=n,this._currentBufferIndex>0&&r.totalBits()===r.availableBits()&&(this._depth--,this._currentBufferIndex--)}}_produceMoreBits(){var e=this;return r((function*(){e._depth++;var t=e._depth>0?Mt([e._value,Uint8Array.from([e._depth])]):e._value,r=yield e._hashFn(t),n=new Kq(r);e._buffers.push(n),e._availableBits+=n.availableBits()}))()}};function Yq(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:Gq(e.hashFn)};return new Mq(r)}function Jq(e){return Zq.apply(this,arguments)}function Zq(){return Zq=r((function*(e){return(yield Rq.encode(e)).slice(0,8).reverse()})),Zq.apply(this,arguments)}var $q=BigInt(34);let Xq=class extends Eq{constructor(t,r){var n;super(t,r),e(this,"_bucket",void 0),this._bucket=Yq({hashFn:Jq,bits:null!==(n=r.shardFanoutBits)&&void 0!==n?n:8})}put(e,t){var n=this;return r((function*(){n.cid=void 0,n.size=void 0,n.nodeSize=void 0,yield n._bucket.put(e,t)}))()}get(e){var t=this;return r((function*(){return t._bucket.get(e)}))()}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}eachChildSeries(){var e=this;return l((function*(){var t,r=!1,n=!1;try{for(var i,o=s(e._bucket.eachLeafSeries());r=!(i=yield u(o.next())).done;r=!1){var{key:a,value:l}=i.value;yield{key:a,child:l}}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw t}}}))()}estimateNodeSize(){return void 0!==this.nodeSize||(this.nodeSize=rH(this._bucket,this,this.options)),this.nodeSize}flush(e){var r=this;return l((function*(){var n,i=!1,o=!1;try{for(var a,l=s(eH(r._bucket,e,r,r.options));i=!(a=yield u(l.next())).done;i=!1){var c=a.value;yield t(t({},c),{},{path:r.path})}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}))()}};function eH(e,t,r,n){return tH.apply(this,arguments)}function tH(){return tH=l((function*(e,t,r,n){for(var i=e._children,o=(e.tableSize()-1).toString(16).length,a=[],l=0n,c=0;c<i.length;c++){var d=i.get(c);if(null!=d){var h=c.toString(16).toUpperCase().padStart(o,"0");if(d instanceof Mq){var v,p=void 0,f=!1,g=!1;try{for(var y,m=s(eH(d,t,null,n));f=!(y=yield u(m.next())).done;f=!1){p=y.value}}catch(e){g=!0,v=e}finally{try{f&&null!=m.return&&(yield u(m.return()))}finally{if(g)throw v}}if(null==p)throw new Error("Could not flush sharded directory, no subshard found");a.push({Name:h,Tsize:Number(p.size),Hash:p.cid}),l+=p.size}else if("function"==typeof d.value.flush){var w,b=d.value,S=void 0,E=!1,k=!1;try{for(var x,A=s(b.flush(t));E=!(x=yield u(A.next())).done;E=!1){S=x.value,yield S}}catch(e){k=!0,w=e}finally{try{E&&null!=A.return&&(yield u(A.return()))}finally{if(k)throw w}}if(null==S)throw new Error("Did not flush dir");var C=h+d.key;a.push({Name:C,Tsize:Number(S.size),Hash:S.cid}),l+=S.size}else{var I=d.value;if(null==I.cid)continue;var T=h+d.key,P=I.size;a.push({Name:T,Tsize:Number(P),Hash:I.cid}),l+=BigInt(null!=P?P:0)}}}var _=Uint8Array.from(i.bitField().reverse()),B=new aq({type:"hamt-sharded-directory",data:_,fanout:BigInt(e.tableSize()),hashType:$q,mtime:null==r?void 0:r.mtime,mode:null==r?void 0:r.mode}),N=RN(BN({Data:B.marshal(),Links:a})),D=yield u(sq(N,t,n)),R=BigInt(N.byteLength)+l;yield{cid:D,unixfs:B,size:R}})),tH.apply(this,arguments)}function rH(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 Mq){var u=rH(s,null,r);o.push({Name:l,Tsize:Number(u),Hash:0===r.cidVersion?kq:xq})}else if("function"==typeof s.value.flush){var c=s.value.nodeSize();o.push({Name:l+s.key,Tsize:Number(c),Hash:0===r.cidVersion?kq:xq})}else{var d=s.value;if(null==d.cid)continue;var h=l+s.key,v=d.size;o.push({Name:h,Tsize:Number(v),Hash:d.cid})}}}var p=Uint8Array.from(n.bitField().reverse());return RN(BN({Data:new aq({type:"hamt-sharded-directory",data:p,fanout:BigInt(e.tableSize()),hashType:$q,mtime:null==t?void 0:t.mtime,mode:null==t?void 0:t.mode}).marshal(),Links:o})).length}function nH(e,t,r,n){return iH.apply(this,arguments)}function iH(){return iH=r((function*(e,t,r,n){var i=t;t instanceof Aq&&t.estimateNodeSize()>r&&(i=yield function(e,t){return oH.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 nH(i,o,r,n)}return i})),iH.apply(this,arguments)}function oH(){return oH=r((function*(e,t){var r,n=new Xq({root:e.root,dir:!0,parent:e.parent,parentKey:e.parentKey,path:e.path,dirty:e.dirty,flat:!1,mtime:e.mtime,mode:e.mode},t),i=!1,o=!1;try{for(var a,l=s(e.eachChildSeries());i=!(a=yield l.next()).done;i=!1){var{key:u,child:c}=a.value;yield n.put(u,c)}}catch(e){o=!0,r=e}finally{try{i&&null!=l.return&&(yield l.return())}finally{if(o)throw r}}return n})),oH.apply(this,arguments)}function aH(e,t,r){return sH.apply(this,arguments)}function sH(){return sH=r((function*(e,t,r){for(var n,i=function(){return(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").split(/(?<!\\)\//).filter(Boolean)}(null!==(n=e.path)&&void 0!==n?n:""),o=i.length-1,a=t,s="",l=0;l<i.length;l++){var u=i[l];s+="".concat(""!==s?"/":"").concat(u);var c=l===o;if(a.dirty=!0,a.cid=void 0,a.size=void 0,c)yield a.put(u,e),t=yield nH(null,a,r.shardSplitThresholdBytes,r);else{var d,h,v=yield a.get(u);if(null==v||!(v instanceof Eq))v=new Aq({root:!1,dir:!0,parent:a,parentKey:u,path:s,dirty:!0,flat:!0,mtime:null===(d=v)||void 0===d||null===(d=d.unixfs)||void 0===d?void 0:d.mtime,mode:null===(h=v)||void 0===h||null===(h=h.unixfs)||void 0===h?void 0:h.mode},r);yield a.put(u,v),a=v}}return t})),sH.apply(this,arguments)}function lH(e,t){return uH.apply(this,arguments)}function uH(){return uH=l((function*(e,t){var r;e instanceof Eq?yield*c(s(e.flush(t))):!0===(null===(r=e.unixfs)||void 0===r?void 0:r.isDirectory())&&(yield e)})),uH.apply(this,arguments)}function cH(e,t){return dH.apply(this,arguments)}function dH(){return dH=l((function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(i,o,a,d,h,v,p,f,g,y,m,w,b,S,E){var k;k=Symbol.asyncIterator in e||Symbol.iterator in e?e:[e];var x,A=null!==(i=n.wrapWithDirectory)&&void 0!==i&&i,C=null!==(o=n.shardSplitThresholdBytes)&&void 0!==o?o:262144,I=null!==(a=n.shardFanoutBits)&&void 0!==a?a:8,T=null!==(d=n.cidVersion)&&void 0!==d?d:1,P=null===(h=n.rawLeaves)||void 0===h||h,_=null!==(v=n.leafType)&&void 0!==v?v:"file",B=null!==(p=n.fileImportConcurrency)&&void 0!==p?p:50,N=null!==(f=n.blockWriteConcurrency)&&void 0!==f?f:10,D=null===(g=n.reduceSingleLeafToSelf)||void 0===g||g,R=null!==(y=n.chunker)&&void 0!==y?y:eq(),O=null!==(m=n.chunkValidator)&&void 0!==m?m:bq(),L=null!==(w=n.dagBuilder)&&void 0!==w?w:function(e){return function(){var t=l((function*(t,n){var i,o=!1,a=!1;try{for(var c,d=function*(){var t,i=c.value;if(null!=i.path&&(t=i.path,i.path=i.path.split("/").filter((e=>null!=e&&"."!==e)).join("/")),function(e){return null!=e.content}(i)){var o={path:i.path,mtime:i.mtime,mode:i.mode,content:l((function*(){var t,r=0n,n=!1,o=!1;try{for(var a,l=s(e.chunker(e.chunkValidator(wq(i.content))));n=!(a=yield u(l.next())).done;n=!1){var c,d=a.value,h=BigInt(d.byteLength);r+=h,null===(c=e.onProgress)||void 0===c||c.call(e,new av("unixfs:importer:progress:file:read",{bytesRead:r,chunkSize:h,path:i.path})),yield d}}catch(e){o=!0,t=e}finally{try{n&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw t}}}))(),originalPath:t};yield r((function*(){return mq(o,n,e)}))}else{if(null==i.path)throw new Error("Import candidate must have content or path or both");var a={path:i.path,mtime:i.mtime,mode:i.mode,originalPath:t};yield r((function*(){return pq(a,n,e)}))}},h=s(t);o=!(c=yield u(h.next())).done;o=!1)yield*d()}catch(e){a=!0,i=e}finally{try{o&&null!=h.return&&(yield u(h.return()))}finally{if(a)throw i}}}));return function(e,r){return t.apply(this,arguments)}}()}({chunker:R,chunkValidator:O,wrapWithDirectory:A,layout:null!==(b=n.layout)&&void 0!==b?b:Sq(),bufferImporter:null!==(S=n.bufferImporter)&&void 0!==S?S:lq({cidVersion:T,rawLeaves:P,leafType:_,onProgress:n.onProgress}),blockWriteConcurrency:N,reduceSingleLeafToSelf:D,cidVersion:T,onProgress:n.onProgress}),M=null!==(E=n.treeBuilder)&&void 0!==E?E:function(e){return function(){var t=l((function*(t,r){var n,i,o=new Aq({root:!0,dir:!0,path:"",dirty:!0,flat:!0},e),a=!1,l=!1,d=!1;try{for(var h,v=s(t);l=!(h=yield u(v.next())).done;l=!1){var p,f,g=h.value;if(null!=g){var y="".concat(null!==(p=g.originalPath)&&void 0!==p?p:"").split("/")[0];null!=y&&""!==y&&(null==n?(n=y,a=!0):n!==y&&(a=!1)),o=yield u(aH(g,o,e)),!0!==(null===(f=g.unixfs)||void 0===f?void 0:f.isDirectory())&&(yield g)}}}catch(e){d=!0,i=e}finally{try{l&&null!=v.return&&(yield u(v.return()))}finally{if(d)throw i}}if(e.wrapWithDirectory||a&&o.childCount()>1)yield*c(s(lH(o,r)));else{var m,w=!1,b=!1;try{for(var S,E=s(o.eachChildSeries());w=!(S=yield u(E.next())).done;w=!1){var k=S.value;null!=k&&(yield*c(s(lH(k.child,r)),u))}}catch(e){b=!0,m=e}finally{try{w&&null!=E.return&&(yield u(E.return()))}finally{if(b)throw m}}}}));return function(e,r){return t.apply(this,arguments)}}()}({wrapWithDirectory:A,shardSplitThresholdBytes:C,shardFanoutBits:I,cidVersion:T,onProgress:n.onProgress}),U=!1,F=!1;try{for(var z,j=s(M(YV(L(k,t),B),t));U=!(z=yield u(j.next())).done;U=!1){var V=z.value;yield{cid:V.cid,path:V.path,unixfs:V.unixfs,size:V.size}}}catch(e){F=!0,x=e}finally{try{U&&null!=j.return&&(yield u(j.return()))}finally{if(F)throw x}}}()})),dH.apply(this,arguments)}function hH(e,t){return vH.apply(this,arguments)}function vH(){return vH=r((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=yield hR(cH([e],t,r));if(null==n)throw new uq("Nothing imported");return n})),vH.apply(this,arguments)}function pH(){return pH=r((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=yield hR(cH([e],t,r));if(null==n)throw new uq("Nothing imported");return n})),pH.apply(this,arguments)}function fH(){return fH=r((function*(e,t){return hH({content:e},t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})})),fH.apply(this,arguments)}function gH(){return gH=r((function*(e,t){return hH({content:e},t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})})),gH.apply(this,arguments)}var yH={cidVersion:1,rawLeaves:!0,layout:Sq({maxChildrenPerNode:1024}),chunker:eq({chunkSize:1048576})};function mH(){return mH=l((function(e,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){yield*c(s(cH(e,r,t(t({},yH),n))))}()})),mH.apply(this,arguments)}function wH(){return wH=r((function*(e,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{cid:i}=yield function(e,t){return fH.apply(this,arguments)}(e,r,t(t({},yH),n));return i})),wH.apply(this,arguments)}function bH(){return bH=r((function*(e,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{cid:i}=yield function(e,t){return gH.apply(this,arguments)}(e,r,t(t({},yH),n));return i})),bH.apply(this,arguments)}function SH(){return SH=r((function*(e,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{cid:i}=yield hH(e,r,t(t({},yH),n));return i})),SH.apply(this,arguments)}function EH(){return EH=r((function*(e,r){var n,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{cid:o}=yield function(e,t){return pH.apply(this,arguments)}(t(t({},e),{},{path:null!==(n=e.path)&&void 0!==n?n:"-"}),r,t(t({},yH),i));return o})),EH.apply(this,arguments)}function kH(e){if(null!=e[Symbol.asyncIterator])return r((function*(){var t,r,n=!1,i=!1;try{for(var o,a=s(e);n=!(o=yield a.next()).done;n=!1){t=o.value}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield a.return())}finally{if(i)throw r}}return t}))();var t;for(var n of e)t=n;return t}class xH extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Bad path"),e(this,"name",xH.name),e(this,"code",xH.code)}}e(xH,"name","BadPathError"),e(xH,"code","ERR_BAD_PATH");class AH extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not found"),e(this,"name",AH.name),e(this,"code",AH.code)}}e(AH,"name","NotFoundError"),e(AH,"code","ERR_NOT_FOUND");class CH extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No resolver"),e(this,"name",CH.name),e(this,"code",CH.code)}}e(CH,"name","NoResolverError"),e(CH,"code","ERR_NO_RESOLVER");let IH=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not UnixFS"),e(this,"name",t.name),e(this,"code",t.code)}};e(IH,"name","NotUnixFSError"),e(IH,"code","ERR_NOT_UNIXFS");class TH extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Over read"),e(this,"name",TH.name),e(this,"code",TH.code)}}e(TH,"name","OverReadError"),e(TH,"code","ERR_OVER_READ");class PH extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Under read"),e(this,"name",PH.name),e(this,"code",PH.code)}}e(PH,"name","UnderReadError"),e(PH,"code","ERR_UNDER_READ");class _H extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No Property found"),e(this,"name",_H.name),e(this,"code",_H.code)}}e(_H,"name","NoPropError"),e(_H,"code","ERR_NO_PROP");let BH=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid parameters"),e(this,"name",t.name),e(this,"code",t.code)}};function NH(e,t,r,n,i,o,a){for(var s,u=e,c=i;o.length>0;){var d=o[0];if(!(d in u))throw new _H("No property named ".concat(d," found in node ").concat(r));o.shift(),c="".concat(c,"/").concat(d);var h=it.asCID(u[d]);if(null!=h)return{entry:{type:"object",name:n,path:i,cid:r,node:t,depth:a,size:BigInt(t.length),content:function(){var t=l((function*(){yield e}));return function(){return t.apply(this,arguments)}}()},next:{cid:h,name:d,path:c,toResolve:o}};u=u[d]}return{entry:{type:"object",name:n,path:i,cid:r,node:t,depth:a,size:BigInt(t.length),content:(s=l((function*(){yield e})),function(){return s.apply(this,arguments)})}}}e(BH,"name","InvalidParametersError"),e(BH,"code","ERR_INVALID_PARAMS");var DH=function(){var e=r((function*(e,t,r,n,i,o,a,s){var l=yield a.get(e,s);return NH(QB(l),l,e,t,r,n,o)}));return function(t,r,n,i,o,a,s,l){return e.apply(this,arguments)}}(),RH=function(){var e=r((function*(e,t,r,n,i,o,a,s){var l=yield a.get(e,s);return NH(aN(l),l,e,t,r,n,o)}));return function(t,r,n,i,o,a,s,l){return e.apply(this,arguments)}}();function OH(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 LH=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 BH("Offset must be greater than or equal to 0");if(i>n)throw new BH("Offset must be less than the file size");if(o<0n)throw new BH("Length must be greater than or equal to 0");if(o>n)throw new BH("Length must be less than the file size");return{start:i,end:o}},MH=e=>{function t(){return t=l((function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(r){var{start:n,end:i}=LH(e.length,t.offset,t.length),o=OH(e,0n,n,i);null===(r=t.onProgress)||void 0===r||r.call(t,new av("unixfs:exporter:progress:identity",{bytesRead:BigInt(o.byteLength),totalBytes:i-n,fileSize:BigInt(e.byteLength)})),yield o}()})),t.apply(this,arguments)}return function(){return t.apply(this,arguments)}},UH=function(){var e=r((function*(e,t,r,n,i,o,a,s){if(n.length>0)throw new AH("No link named ".concat(r," found in raw node ").concat(e));var l=He(e.multihash.bytes);return{entry:{type:"identity",name:t,path:r,cid:e,content:MH(l.digest),depth:o,size:BigInt(l.digest.length),node:l.digest}}}));return function(t,r,n,i,o,a,s,l){return e.apply(this,arguments)}}(),FH=function(){var e=r((function*(e,t,r,n,i,o,a,s){var l=yield a.get(e,s);return NH(we(l),l,e,t,r,n,o)}));return function(t,r,n,i,o,a,s,l){return e.apply(this,arguments)}}(),zH=e=>{function t(){return t=l((function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(r){var{start:n,end:i}=LH(e.length,t.offset,t.length),o=OH(e,0n,n,i);null===(r=t.onProgress)||void 0===r||r.call(t,new av("unixfs:exporter:progress:raw",{bytesRead:BigInt(o.byteLength),totalBytes:i-n,fileSize:BigInt(e.byteLength)})),yield o}()})),t.apply(this,arguments)}return function(){return t.apply(this,arguments)}},jH=function(){var e=r((function*(e,t,r,n,i,o,a,s){if(n.length>0)throw new AH("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:zH(l),depth:o,size:BigInt(l.length),node:l}}}));return function(t,r,n,i,o,a,s,l){return e.apply(this,arguments)}}(),VH=function(){var e=r((function*(e){return(yield Rq.encode(e)).slice(0,8).reverse()}));return function(t){return e.apply(this,arguments)}}(),qH=function(){var e=r((function*(e,t,n){var i=(t.tableSize()-1).toString(16).length;yield Promise.all(e.map(function(){var e=r((function*(e){if(null==e.Name)throw new Error("Unexpected Link without a Name");if(e.Name.length!==i)yield n.put(e.Name.substring(2),!0);else{var r=parseInt(e.Name,16);t._putObjectAt(r,new Mq({hash:n._options.hash,bits:n._options.bits},t,r))}}));return function(t){return e.apply(this,arguments)}}()))}));return function(t,r,n){return e.apply(this,arguments)}}(),HH=(e,t)=>e.toString(16).toUpperCase().padStart(t,"0").substring(0,t),KH=function(){var e=r((function*(e,t,r,n,i){if(null==n){if(null==e.Data)throw new IH("no data in PBNode");var o;try{o=aq.unmarshal(e.Data)}catch(e){throw new IH(e.message)}if("hamt-sharded-directory"!==o.type)throw new IH("not a HAMT");if(null==o.fanout)throw new IH("missing fanout");var a=Yq({hashFn:VH,bits:Math.log2(Number(o.fanout))});n={rootBucket:a,hamtDepth:1,lastBucket:a}}var s=(n.lastBucket.tableSize()-1).toString(16).length;yield qH(e.Links,n.lastBucket,n.rootBucket);var l=yield n.rootBucket._findNewBucketAndPos(t),u=HH(l.pos,s),c=(e=>{for(var t=e.bucket,r=[];null!=t._parent;)r.push(t),t=t._parent;return r.push(t),r.reverse()})(l);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],u=HH(n.lastBucket._posAtParent,s));var d=e.Links.find((e=>{if(null==e.Name)return!1;var r=e.Name.substring(0,s),n=e.Name.substring(s);return r===u&&(""===n||n===t)}));if(null!=d)return null!=d.Name&&d.Name.substring(s)===t?d.Hash:(n.hamtDepth++,e=ON(yield r.get(d.Hash,i)),KH(e,t,r,n,i))}));return function(t,r,n,i,o){return e.apply(this,arguments)}}();function WH(e,t,r,n,i,o,a){return GH.apply(this,arguments)}function GH(){return GH=r((function*(e,n,i,o,a,l,u){if(n instanceof Uint8Array){var c=OH(n,o,a,l);i.push(c)}else{if(null==n.Data)throw new IH("no data in PBNode");var d;try{d=aq.unmarshal(n.Data)}catch(e){throw new IH(e.message)}if(null!=d.data){var h=OH(d.data,o,a,l);i.push(h),o+=BigInt(h.byteLength)}var v=[];if(n.Links.length!==d.blockSizes.length)throw new IH("Inconsistent block sizes and dag links");for(var p=0;p<n.Links.length;p++){var f=n.Links[p],g=o,y=g+d.blockSizes[p];if((a>=g&&a<y||l>=g&&l<=y||a<g&&l>y)&&v.push({link:f,blockStart:o}),(o=y)>l)break}yield Fc(v,(n=>Ac(n,(n=>r((function*(){var r=yield e.get(n.link.Hash,u);return t(t({},n),{},{block:r})}))))),(e=>bL(e,{ordered:!0,concurrency:u.blockReadConcurrency})),function(){var t=r((function*(t){var n,o=!1,c=!1;try{for(var d,h,v=function*(){var t,{link:n,block:o,blockStart:s}=h.value;switch(n.Hash.code){case DN:t=ON(o);break;case Se:t=o;break;default:return i.end(new IH("Unsupported codec: ".concat(n.Hash.code))),{v:void 0}}var c=new BT({concurrency:1});c.on("error",(e=>{i.end(e)})),c.add(r((function*(){var r;null===(r=u.onProgress)||void 0===r||r.call(u,new av("unixfs:exporter:walk:file",{cid:n.Hash})),yield WH(e,t,i,s,a,l,u)}))),yield c.onIdle()},p=s(t);o=!(h=yield p.next()).done;o=!1)if(d=yield*v())return d.v}catch(e){c=!0,n=e}finally{try{o&&null!=p.return&&(yield p.return())}finally{if(c)throw n}}}));return function(e){return t.apply(this,arguments)}}()),o>=l&&i.end()}})),GH.apply(this,arguments)}var QH=(e,t,r,n,i,o,a)=>{function c(){return c=l((function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(i){var o=r.fileSize();if(void 0===o)throw new Error("File was a directory");var{start:l,end:c}=LH(o,n.offset,n.length);if(0n!==c){var d=0n,h=c-l,v=_c();null===(i=n.onProgress)||void 0===i||i.call(n,new av("unixfs:exporter:walk:file",{cid:e})),WH(a,t,v,0n,l,c,n).catch((e=>{v.end(e)}));var p,f=!1,g=!1;try{for(var y,m=s(v);f=!(y=yield u(m.next())).done;f=!1){var w,b=y.value;if(null!=b){if((d+=BigInt(b.byteLength))>h)throw v.end(),new TH("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");d===h&&v.end(),null===(w=n.onProgress)||void 0===w||w.call(n,new av("unixfs:exporter:progress:unixfs:file",{bytesRead:d,totalBytes:h,fileSize:o})),yield b}}}catch(e){g=!0,p=e}finally{try{f&&null!=m.return&&(yield u(m.return()))}finally{if(g)throw p}}if(d<h)throw new PH("Traversed entire DAG but did not read enough bytes")}}()})),c.apply(this,arguments)}return function(){return c.apply(this,arguments)}};function YH(e,t,r,n,i,o){return JH.apply(this,arguments)}function JH(){return JH=l((function*(e,t,n,i,o,a){var l,d=e.Links;if(null==e.Data)throw new IH("no data in PBNode");try{l=aq.unmarshal(e.Data)}catch(e){throw new IH(e.message)}if(null==l.fanout)throw new IH("missing fanout");var h,v=(l.fanout-1n).toString(16).length,p=Fc(d,(s=>Ac(s,(s=>r((function*(){var r=null!=s.Name?s.Name.substring(v):null;if(null!=r&&""!==r){var l=yield n(s.Hash,r,"".concat(t,"/").concat(r),[],i+1,o,a);return{entries:null==l.entry?[]:[l.entry]}}var u,c=yield o.get(s.Hash,a);return e=ON(c),null===(u=a.onProgress)||void 0===u||u.call(a,new av("unixfs:exporter:walk:hamt-sharded-directory",{cid:s.Hash})),{entries:YH(e,t,n,i,o,a)}}))))),(e=>bL(e,{ordered:!0,concurrency:a.blockReadConcurrency}))),f=!1,g=!1;try{for(var y,m=s(p);f=!(y=yield u(m.next())).done;f=!1){var{entries:w}=y.value;yield*c(s(w),u)}}catch(e){g=!0,h=e}finally{try{f&&null!=m.return&&(yield u(m.return()))}finally{if(g)throw h}}})),JH.apply(this,arguments)}var ZH,$H,XH,eK,tK={raw:QH,file:QH,directory:(e,t,n,i,o,a,u)=>{function d(){return d=l((function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(l,d,h){var v=null!==(l=n.offset)&&void 0!==l?l:0,p=null!==(d=n.length)&&void 0!==d?d:t.Links.length,f=t.Links.slice(v,p);null===(h=n.onProgress)||void 0===h||h.call(n,new av("unixfs:exporter:walk:directory",{cid:e})),yield*c(s(Fc(f,(e=>Ac(e,(e=>r((function*(){var t,r=null!==(t=e.Name)&&void 0!==t?t:"",s="".concat(i,"/").concat(r);return(yield o(e.Hash,r,s,[],a+1,u,n)).entry}))))),(e=>bL(e,{ordered:!0,concurrency:n.blockReadConcurrency})),(e=>dc(e,(e=>null!=e))))))}()})),d.apply(this,arguments)}return function(){return d.apply(this,arguments)}},"hamt-sharded-directory":(e,t,r,n,i,o,a)=>function(){var r,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return null===(r=s.onProgress)||void 0===r||r.call(s,new av("unixfs:exporter:walk:hamt-sharded-directory",{cid:e})),YH(t,n,i,o,a,s)},metadata:(e,t,r,n,i,o,a)=>()=>[],symlink:(e,t,r,n,i,o,a)=>()=>[]},rK=function(){var e=r((function*(e,t,r,n,i,o,a,s){var l,u,c=ON(yield a.get(e,s));if(null==t&&(t=e.toString()),null==c.Data)throw new IH("no data in PBNode");try{l=aq.unmarshal(c.Data)}catch(e){throw new IH(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 KH(c,n[0],a):((e,t)=>{var r=e.Links.find((e=>e.Name===t));return null==r?void 0:r.Hash})(c,n[0]),null==h)throw new AH("file does not exist");var v=n.shift();u={cid:h,toResolve:n,name:null!=v?v:"",path:"".concat(r,"/").concat(v)}}var p=tK[l.type](e,c,l,r,i,o,a);if(null==p)throw new AH("could not find content exporter");return l.isDirectory()?{entry:{type:"directory",name:t,path:r,cid:e,content:p,unixfs:l,depth:o,node:c,size:l.fileSize()},next:u}:{entry:{type:"file",name:t,path:r,cid:e,content:p,unixfs:l,depth:o,node:c,size:l.fileSize()},next:u}}));return function(t,r,n,i,o,a,s,l){return e.apply(this,arguments)}}(),nK={[DN]:rK,[Se]:jH,[WB]:DH,[iN]:RH,[Ge.code]:UH,[me]:FH},iK=function(){var e=r((function*(e,t,r,n,i,o,a){var s=nK[e.code];if(null==s)throw new CH("No resolver for code ".concat(e.code));return s(e,t,r,n,iK,i,o,a)}));return function(t,r,n,i,o,a,s){return e.apply(this,arguments)}}(),oK=e=>{if(e instanceof Uint8Array)return{cid:it.decode(e),toResolve:[]};var t=it.asCID(e);if(null!=t)return{cid:t,toResolve:[]};if("string"==typeof e){0===e.indexOf("/ipfs/")&&(e=e.substring(6));var r=function(){var e;return(null!==(e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").trim().match(/([^\\^/]|\\\/)+/g))&&void 0!==e?e:[]).filter(Boolean)}(e);return{cid:it.parse(r[0]),toResolve:r.slice(1)}}throw new xH("Unknown path type ".concat(e))};function aK(e,t){return sK.apply(this,arguments)}function sK(){return sK=l((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){for(var{cid:n,toResolve:i}=oK(e),o=n.toString(),a=o,s=i.length;;){var l=yield u(iK(n,o,a,i,s,t,r));if(null==l.entry&&null==l.next)throw new AH("Could not resolve ".concat(e));if(null!=l.entry&&(yield l.entry),null==l.next)return;i=l.next.toResolve,n=l.next.cid,o=l.next.name,a=l.next.path}}()})),sK.apply(this,arguments)}function lK(e,t){return uK.apply(this,arguments)}function uK(){return uK=r((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=yield kH(aK(e,t,r));if(null==n)throw new AH("Could not resolve ".concat(e));return n})),uK.apply(this,arguments)}function cK(e,t){return dK.apply(this,arguments)}function dK(){return dK=l((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var n=yield u(lK(e,t,r));if(null!=n&&(yield n,"directory"===n.type)){var i,o=!1,a=!1;try{for(var d,h=s(p(n,r));o=!(d=yield u(h.next())).done;o=!1){var v=d.value;yield v}}catch(e){a=!0,i=e}finally{try{o&&null!=h.return&&(yield u(h.return()))}finally{if(a)throw i}}}function p(e,t){return f.apply(this,arguments)}function f(){return f=l((function*(e,t){var r,n=!1,i=!1;try{for(var o,a=s(e.content(t));n=!(o=yield u(a.next())).done;n=!1){var l=o.value;(yield l,l instanceof Uint8Array)||"directory"===l.type&&(yield*c(s(p(l,t)),u))}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield u(a.return()))}finally{if(i)throw r}}})),f.apply(this,arguments)}}()})),dK.apply(this,arguments)}var hK=function(){if(eK)return XH;eK=1;var e=$H?ZH:($H=1,ZH=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=XH,o={concatArrays:!1,ignoreUndefined:!1},a=e=>{var n=[];for(var i in e)t.call(e,i)&&n.push(i);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(var a of o)r.call(e,a)&&n.push(a)}return n};function s(t){return Array.isArray(t)?(i=(r=t).slice(0,0),a(r).forEach((e=>{n(i,e,s(r[e]))})),i):e(t)?function(e){var t=null===Object.getPrototypeOf(e)?Object.create(null):{};return a(e).forEach((r=>{n(t,r,s(e[r]))})),t}(t):t;var r,i}var l=(e,t,r,i)=>(r.forEach((r=>{void 0===t[r]&&i.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?n(e,r,c(e[r],t[r],i)):n(e,r,s(t[r])))})),e),u=(e,r,i)=>{var o=e.slice(0,0),u=0;return[e,r].forEach((r=>{for(var c=[],d=0;d<r.length;d++)t.call(r,d)&&(c.push(String(d)),n(o,u++,r===e?r[d]:s(r[d])));o=l(o,r,a(r).filter((e=>!c.includes(e))),i)})),o};function c(t,r,n){return n.concatArrays&&Array.isArray(t)&&Array.isArray(r)?u(t,r,n):e(r)&&e(t)?l(t,r,a(r),n):s(r)}return XH=function(){for(var t=c(s(o),this!==i&&this||{},o),r={_:{}},n=arguments.length,a=new Array(n),l=0;l<n;l++)a[l]=arguments[l];for(var u of a)if(void 0!==u){if(!e(u))throw new TypeError("`"+u+"` is not an Option Object");r=c(r,{_:u},t)}return r._},XH}(),vK=a(hK);class pK extends Error{constructor(t,r,n){super(t),e(this,"name",void 0),e(this,"code",void 0),this.name=r,this.code=n}}class fK extends pK{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"not a Unixfs node","NotUnixFSError","ERR_NOT_UNIXFS")}}class gK extends pK{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"invalid PBNode","InvalidPBNodeError","ERR_INVALID_PB_NODE")}}class yK extends pK{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"unknown error","InvalidPBNodeError","ERR_UNKNOWN_ERROR")}}class mK extends pK{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"path already exists","AlreadyExistsError","ERR_ALREADY_EXISTS")}}class wK extends pK{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"path does not exist","DoesNotExistError","ERR_DOES_NOT_EXIST")}}class bK extends pK{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no content","NoContentError","ERR_NO_CONTENT")}}class SK extends pK{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"not a file","NotAFileError","ERR_NOT_A_FILE")}}class EK extends pK{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"not a directory","NotADirectoryError","ERR_NOT_A_DIRECTORY")}}class kK extends pK{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"invalid parameters","InvalidParametersError","ERR_INVALID_PARAMETERS")}}function xK(e){return function(t){return t instanceof AK?t:new AK(t,e)}}class AK{constructor(t,r){if(e(this,"_value",void 0),e(this,"_hashFn",void 0),e(this,"_depth",void 0),e(this,"_availableBits",void 0),e(this,"_currentBufferIndex",void 0),e(this,"_buffers",void 0),!(t instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=t,this._hashFn=r,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}take(e){var t=this;return r((function*(){for(var r=e;t._availableBits<r;)yield t._produceMoreBits();for(var n=0;r>0;){var i=t._buffers[t._currentBufferIndex],o=Math.min(i.availableBits(),r);n=(n<<o)+i.take(o),r-=o,t._availableBits-=o,0===i.availableBits()&&t._currentBufferIndex++}return n}))()}untake(e){for(var t=e;t>0;){var r=this._buffers[this._currentBufferIndex],n=Math.min(r.totalBits()-r.availableBits(),t);r.untake(n),t-=n,this._availableBits+=n,this._currentBufferIndex>0&&r.totalBits()===r.availableBits()&&(this._depth--,this._currentBufferIndex--)}}_produceMoreBits(){var e=this;return r((function*(){e._depth++;var t=e._depth>0?Mt([e._value,Uint8Array.from([e._depth])]):e._value,r=yield e._hashFn(t),n=new TK(r);e._buffers.push(n),e._availableBits+=n.availableBits()}))()}}var CK=[255,254,252,248,240,224,192,128],IK=[1,3,7,15,31,63,127,255];class TK{constructor(t){e(this,"_value",void 0),e(this,"_currentBytePos",void 0),e(this,"_currentBitPos",void 0),this._value=t,this._currentBytePos=t.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+8*this._currentBytePos}totalBits(){return 8*this._value.length}take(e){for(var t=e,r=0;t>0&&this._haveBits();){var n=this._value[this._currentBytePos],i=this._currentBitPos+1,o=Math.min(i,t);r=(r<<o)+PK(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 PK(e,t,r){var n=function(e,t){return CK[e]&IK[Math.min(t+e-1,7)]}(t,r);return(e&n)>>>t}var _K=BigInt(Rq.code);function BK(e){return NK.apply(this,arguments)}function NK(){return NK=r((function*(e){return(yield Rq.encode(e)).subarray(0,8).reverse()})),NK.apply(this,arguments)}var DK=function(){var e=r((function*(e,r,n){null==n.codec&&(n.codec=LN);var i=yield $e.digest(e),o=it.create(n.cidVersion,n.codec.code,i);return yield r.put(o,e,t(t({},n),{},{signal:n.signal})),o}));return function(t,r,n){return e.apply(this,arguments)}}();class RK{constructor(t,r){e(this,"options",void 0),e(this,"root",void 0),e(this,"dir",void 0),e(this,"path",void 0),e(this,"dirty",void 0),e(this,"flat",void 0),e(this,"parent",void 0),e(this,"parentKey",void 0),e(this,"unixfs",void 0),e(this,"mode",void 0),e(this,"mtime",void 0),e(this,"cid",void 0),e(this,"size",void 0),e(this,"nodeSize",void 0),this.options=null!=r?r:{},this.root=t.root,this.dir=t.dir,this.path=t.path,this.dirty=t.dirty,this.flat=t.flat,this.parent=t.parent,this.parentKey=t.parentKey,this.unixfs=t.unixfs,this.mode=t.mode,this.mtime=t.mtime}}class OK extends RK{constructor(t,r){super(t,r),e(this,"_bucket",void 0),this._bucket=Yq({hashFn:BK,bits:8})}put(e,t){var n=this;return r((function*(){n.cid=void 0,n.size=void 0,n.nodeSize=void 0,yield n._bucket.put(e,t)}))()}get(e){var t=this;return r((function*(){return t._bucket.get(e)}))()}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}eachChildSeries(){var e=this;return l((function*(){var t,r=!1,n=!1;try{for(var i,o=s(e._bucket.eachLeafSeries());r=!(i=yield u(o.next())).done;r=!1){var{key:a,value:l}=i.value;yield{key:a,child:l}}}catch(e){n=!0,t=e}finally{try{r&&null!=o.return&&(yield u(o.return()))}finally{if(n)throw t}}}))()}estimateNodeSize(){return void 0!==this.nodeSize||(this.nodeSize=UK(this._bucket,this,this.options)),this.nodeSize}flush(e){var r=this;return l((function*(){var n,i=!1,o=!1;try{for(var a,l=s(LK(r._bucket,e,r,r.options));i=!(a=yield u(l.next())).done;i=!1){var c=a.value;yield t(t({},c),{},{path:r.path})}}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield u(l.return()))}finally{if(o)throw n}}}))()}}function LK(e,t,r,n){return MK.apply(this,arguments)}function MK(){return MK=l((function*(e,t,r,n){for(var i=e._children,o=[],a=0n,l=0;l<i.length;l++){var c=i.get(l);if(null!=c){var d=l.toString(16).toUpperCase().padStart(2,"0");if(c instanceof Mq){var h,v=void 0,p=!1,f=!1;try{for(var g,y=s(LK(c,t,null,n));p=!(g=yield u(y.next())).done;p=!1){v=g.value}}catch(e){f=!0,h=e}finally{try{p&&null!=y.return&&(yield u(y.return()))}finally{if(f)throw h}}if(null==v)throw new Error("Could not flush sharded directory, no sub-shard found");o.push({Name:d,Tsize:Number(v.size),Hash:v.cid}),a+=v.size}else if("function"==typeof c.value.flush){var m,w=c.value,b=void 0,S=!1,E=!1;try{for(var k,x=s(w.flush(t));S=!(k=yield u(x.next())).done;S=!1){b=k.value,yield b}}catch(e){E=!0,m=e}finally{try{S&&null!=x.return&&(yield u(x.return()))}finally{if(E)throw m}}if(null==b)throw new Error("Did not flush dir");var A=d+c.key;o.push({Name:A,Tsize:Number(b.size),Hash:b.cid}),a+=b.size}else{var C=c.value;if(null==C.cid)continue;var I=d+c.key,T=C.size;o.push({Name:I,Tsize:Number(T),Hash:C.cid}),a+=BigInt(null!=T?T:0)}}}var P=Uint8Array.from(i.bitField().reverse()),_=new aq({type:"hamt-sharded-directory",data:P,fanout:BigInt(e.tableSize()),hashType:_K,mtime:null==r?void 0:r.mtime,mode:null==r?void 0:r.mode}),B=RN(BN({Data:_.marshal(),Links:o})),N=yield u(DK(B,t,n)),D=BigInt(B.byteLength)+a;yield{cid:N,unixfs:_,size:D}})),MK.apply(this,arguments)}function UK(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 Mq){var l=UK(a,null,r);i.push({Name:s,Tsize:Number(l),Hash:0===r.cidVersion?FK:zK})}else if("function"==typeof a.value.flush){var u=a.value.nodeSize();i.push({Name:s+a.key,Tsize:Number(u),Hash:0===r.cidVersion?FK:zK})}else{var c=a.value;if(null==c.cid)continue;var d=s+a.key,h=c.size;i.push({Name:d,Tsize:Number(h),Hash:c.cid})}}}var v=Uint8Array.from(n.bitField().reverse());return RN(BN({Data:new aq({type:"hamt-sharded-directory",data:v,fanout:BigInt(e.tableSize()),hashType:_K,mtime:null==t?void 0:t.mtime,mode:null==t?void 0:t.mode}).marshal(),Links:i})).length}var FK=it.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),zK=it.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi"),jK=sd("helia:unixfs:commands:utils:hamt-utils"),VK=e=>e.toString(16).toUpperCase().padStart(2,"0").substring(0,2),qK=function(){var e=r((function*(e,t,r){for(var n=new OK({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 kH(n.flush(e));if(null==o)throw new Error("Flushing shard yielded no result");return o}));return function(t,r,n){return e.apply(this,arguments)}}(),HK=function(){var e=r((function*(e,t,r){var n,i,o,a=aq.unmarshal(null!==(n=e[0].node.Data)&&void 0!==n?n:new Uint8Array(0)),s=BigInt(Math.pow(2,8));e.reverse();for(var l=function*(){var n=u===e.length-1,l=e[u],c=Uint8Array.from(l.children.bitField().reverse()),d=new aq({type:"hamt-sharded-directory",data:c,fanout:s,hashType:_K});n&&(d.mtime=a.mtime,d.mode=a.mode);var h=RN(BN(o={Data:d.marshal(),Links:l.node.Links}));if(i=yield DK(h,t,r),!n){var v=e[u+1];if(null==v)throw new Error("Was not operating on shard root but also had no parent?");jK("updating link in parent sub-shard with prefix %s",v.prefix),v.node.Links=v.node.Links.filter((e=>e.Name!==v.prefix)),v.node.Links.push({Name:v.prefix,Hash:i,Tsize:l.node.Links.reduce(((e,t)=>{var r;return e+(null!==(r=t.Tsize)&&void 0!==r?r:0)}),h.byteLength)})}},u=0;u<e.length;u++)yield*l();if(null==i||null==o)throw new Error("Noting persisted");return{cid:i,node:o}}));return function(t,r,n){return e.apply(this,arguments)}}(),KK=function(){var e=r((function*(e,t,r,n){for(var i=xK(BK)(Et(t)),o=[];;){var a,s=ON(yield r.get(e,n)),l=new Lq,u=yield i.take(8),c=VK(u);o.push({prefix:c,children:l,node:s});var d=void 0;for(var h of s.Links){var v,p=null!==(v=h.Name)&&void 0!==v?v:"";if(p.length<2)throw new Error("Invalid HAMT - link name was too short");var f=parseInt(p.substring(0,2),16);l.set(f,!0),p.startsWith(c)&&(d=h)}if(null==d){jK("no link found with prefix %s for %s",c,t);break}var g=null!==(a=d.Name)&&void 0!==a?a:"";if(g.length<2)throw new Error("Invalid HAMT - link name was too short");if(2!==g.length)break;e=d.Hash,jK("descend into sub-shard with prefix %s",g)}return{path:o,hash:i}}));return function(t,r,n,i){return e.apply(this,arguments)}}();function WK(e,t,r,n){return GK.apply(this,arguments)}function GK(){return GK=r((function*(e,t,r,n){if(null==e.Data)throw new Error("DagPB node had no data");var i,o=aq.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?zK.bytes.byteLength:FK.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 QK(e,0,r,t,n)}return i>r})),GK.apply(this,arguments)}function QK(e,t,r,n,i){return YK.apply(this,arguments)}function YK(){return YK=r((function*(e,t,r,n,i){if(t>r)return r;if(null==e.Data)return t;if(!aq.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===DN){var l=ON(yield n.get(o.Hash,i));t+=(yield QK(l,t,r,n,i))}}return t})),YK.apply(this,arguments)}var JK=sd("helia:unixfs:components:utils:add-link");function ZK(e,t,r,n){return $K.apply(this,arguments)}function $K(){return $K=r((function*(e,t,r,n){if(null==e.node.Data)throw new kK("Invalid parent passed to addLink");if("hamt-sharded-directory"===aq.unmarshal(e.node.Data).type)return JK("adding link to sharded directory"),tW(e,t,r,n);JK("adding ".concat(t.Name," (").concat(t.Hash,") to regular directory"));var i=yield eW(e,t,r,n);if(yield WK(i.node,r,n.shardSplitThresholdBytes,n)){JK("converting directory to sharded directory");var o=yield XK(i,r);i.cid=o.cid,i.node=ON(yield r.get(o.cid,n))}return i})),$K.apply(this,arguments)}var XK=function(){var e=r((function*(e,t){if(null==e.node.Data)throw new kK("Invalid parent passed to convertToShardedDirectory");var r=aq.unmarshal(e.node.Data),n=yield qK(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 JK("converted directory to sharded directory ".concat(n.cid)),n}));return function(t,r){return e.apply(this,arguments)}}(),eW=function(){var e=r((function*(e,t,r,n){var i=e.node.Links.filter((e=>{var r=e.Name===t.Name;if(r&&!n.allowOverwriting)throw new mK;return!r}));if(i.push(t),null==e.node.Data)throw new gK("Parent node with no data passed to addToDirectory");var o,a=aq.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=BN({Data:o,Links:i});var u=RN(e.node),c=yield $e.digest(u),d=it.create(e.cid.version,DN,c);return yield r.put(d,u),{node:e.node,cid:d}}));return function(t,r,n,i){return e.apply(this,arguments)}}(),tW=function(){var e=r((function*(e,t,r,n){var{path:i,hash:o}=yield KK(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);JK("next prefix for %s is %s",t.Name,s);var u,c="".concat(s).concat(t.Name),d=a.node.Links.find((e=>{var t;return(null!==(t=e.Name)&&void 0!==t?t:"").startsWith(s)}));if(null!=d)if(JK("link %s was present in shard",c),d.Name===c){if(!n.allowOverwriting)throw new mK;JK("overwriting %s in sub-shard",t.Name),a.node.Links=a.node.Links.filter((e=>e.Name!==c)),a.node.Links.push({Name:c,Hash:t.Hash,Tsize:t.Tsize})}else{if(2===(null===(u=d.Name)||void 0===u?void 0:u.length))throw new Error("Existing link was sub-shard?!");var h;JK("prefix %s already exists, creating new sub-shard",s);for(var v=a.node.Links.findIndex((e=>{var t;return null===(t=e.Name)||void 0===t?void 0:t.startsWith(s)})),p=a.node.Links.splice(v,1)[0],f=(null!==(h=p.Name)&&void 0!==h?h:"").substring(2),g=xK(BK)(Et(f)),y=0;y<i.length;y++)yield g.take(8);for(;;){var m=yield g.take(8),w=VK(m);p.Name="".concat(w).concat(f);var b=yield o.take(8),S=VK(b);if(w!==S){var E=new Lq;E.set(b,!0),E.set(m,!0),i.push({prefix:s,children:E,node:{Links:[p,{Name:"".concat(S).concat(t.Name),Hash:t.Hash,Tsize:t.Tsize}]}});break}var k=new Lq;k.set(b,!0),i.push({prefix:S,children:k,node:{Links:[]}})}}else JK("link %s was not present in sub-shard",c),t.Name=c,a.node.Links.push(t),a.children.set(l,!0),JK("adding %s to existing sub-shard",c);return HK(i,r,n)}));return function(t,r,n,i){return e.apply(this,arguments)}}();function rW(e,t){return nW.apply(this,arguments)}function nW(){return nW=r((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=yield lK(e,t,r);if("directory"!==n.type)throw new EK("".concat(e.toString()," was not a UnixFS directory"));return{cid:e,node:n.node}})),nW.apply(this,arguments)}function iW(e,t,r,n){return oW.apply(this,arguments)}function oW(){return oW=r((function*(e,t,r,n){var i,o,a=yield lK(e,r,n);if("directory"!==a.type&&"file"!==a.type&&"raw"!==a.type)throw new fK("".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),RN(i).byteLength+o),Hash:e}})),oW.apply(this,arguments)}var aW=sd("helia:unixfs:components:utils:resolve");function sW(e,t,r,n){return lW.apply(this,arguments)}function lW(){return lW=r((function*(e,t,r,n){if(null==t||""===t)return{cid:e};var i="/ipfs/".concat(e).concat(null==t?"":"/".concat(t)),o=yield hc(aK(i,r,n));if(0===o.length)throw new wK("Could not find path in directory");return aW("resolved %s to %c",t,e),{cid:o[o.length-1].cid,path:t,segments:o}})),lW.apply(this,arguments)}function uW(e,t,r,n){return cW.apply(this,arguments)}function cW(){return cW=r((function*(e,r,n,i){if(null==r.segments||0===r.segments.length)return e;var o=r.segments.pop();if(null==o)throw new Error("Insufficient segments");for(var a of(o.cid=e,r.segments.reverse(),r.segments)){var[s,l]=yield Promise.all([rW(a.cid,n,i),iW(o.cid,o.name,n,i)]);e=(yield ZK(s,l,n,t(t({},i),{},{allowOverwriting:!0,cidVersion:e.version}))).cid,a.cid=e,o=a}return e})),cW.apply(this,arguments)}var dW=vK.bind({ignoreUndefined:!0}),hW={};function vW(){return vW=l((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var n=dW(hW,r),i=yield u(sW(e,n.path,t,n)),o=yield u(lK(i.cid,t,n));if("file"!==o.type&&"raw"!==o.type)throw new SK;if(null==o.content)throw new bK;yield*c(s(o.content(n)))}()})),vW.apply(this,arguments)}var pW=262144,fW=vK.bind({ignoreUndefined:!0}),gW=sd("helia:unixfs:chmod"),yW={recursive:!1,shardSplitThresholdBytes:pW};function mW(){return mW=r((function*(e,n,i){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},a=fW(yW,o),c=yield sW(e,a.path,i,o);if(gW("chmod %c %d",c.cid,n),a.recursive){var d=yield Fc(l((function*(){var e,t=!1,r=!1;try{for(var a,l=s(cK(c.cid,i,o));t=!(a=yield u(l.next())).done;t=!1){var d=a.value,h=void 0,v=[];if("raw"===d.type)h=new aq({type:"file",data:d.node});else{if("file"!==d.type&&"directory"!==d.type)throw new fK;h=d.unixfs,v=d.node.Links}h.mode=n;var p={Data:h.marshal(),Links:v};yield{path:d.path,content:p}}}catch(t){r=!0,e=t}finally{try{t&&null!=l.return&&(yield u(l.return()))}finally{if(r)throw e}}})),(n=>{return cH(n,i,t(t({},a),{},{dagBuilder:(o=l((function*(n,i){var o,l=!1,c=!1;try{for(var d,h=function*(){var n=d.value;yield r((function*(){var r=n.content,o=RN(r),s=yield DK(o,i,t(t({},a),{},{cidVersion:e.version}));if(null==r.Data)throw new gK("".concat(s," had no data"));var l=aq.unmarshal(r.Data);return{cid:s,size:BigInt(o.length),path:n.path,unixfs:l}}))},v=s(n);l=!(d=yield u(v.next())).done;l=!1)yield*h()}catch(e){c=!0,o=e}finally{try{l&&null!=v.return&&(yield u(v.return()))}finally{if(c)throw o}}})),function(e,t){return o.apply(this,arguments)})}));var o}),function(){var e=r((function*(e){return kH(e)}));return function(t){return e.apply(this,arguments)}}());if(null==d)throw new yK("Could not chmod ".concat(c.cid.toString()));return uW(d.cid,c,i,a)}var h,v=yield i.get(c.cid,o),p=[];if(c.cid.code===Se)h=new aq({type:"file",data:v});else{var f=ON(v);if(null==f.Data)throw new gK("".concat(c.cid.toString()," had no data"));p=f.Links,h=aq.unmarshal(f.Data)}h.mode=n;var g=RN({Data:h.marshal(),Links:p}),y=yield $e.digest(g),m=it.create(c.cid.version,DN,y);return yield i.put(m,g),uW(m,c,i,a)})),mW.apply(this,arguments)}var wW=vK.bind({ignoreUndefined:!0}),bW=sd("helia:unixfs:cp"),SW={force:!1,shardSplitThresholdBytes:pW};function EW(){return EW=r((function*(e,r,n,i){var o=wW(SW,arguments.length>4&&void 0!==arguments[4]?arguments[4]:{});if(n.includes("/"))throw new kK("Name must not have slashes");var[a,s]=yield Promise.all([rW(r,i,o),iW(e,n,i,o)]);return bW('Adding %c as "%s" to %c',e,n,r),(yield ZK(a,s,i,t({allowOverwriting:o.force,cidVersion:r.version},o))).cid})),EW.apply(this,arguments)}var kW=vK.bind({ignoreUndefined:!0}),xW={};function AW(){return AW=l((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var n=kW(xW,r),i=yield u(sW(e,n.path,t,n)),o=yield u(lK(i.cid,t));if("file"!==o.type&&"raw"!==o.type){if(null==o.content)throw new bK;if("directory"!==o.type)throw new EK;yield*c(s(o.content({offset:r.offset,length:r.length})))}else yield o}()})),AW.apply(this,arguments)}var CW=vK.bind({ignoreUndefined:!0}),IW=sd("helia:unixfs:mkdir"),TW={cidVersion:1,force:!1,shardSplitThresholdBytes:pW};function PW(){return PW=r((function*(e,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},o=CW(TW,i);if(r.includes("/"))throw new kK("Path must not have slashes");if("directory"!==(yield lK(e,n,i)).type)throw new EK("".concat(e.toString()," was not a UnixFS directory"));IW("creating %s",r);var a=RN({Data:new aq({type:"directory",mode:o.mode,mtime:o.mtime}).marshal(),Links:[]}),s=yield $e.digest(a),l=it.create(o.cidVersion,DN,s);yield n.put(l,a);var[u,c]=yield Promise.all([rW(e,n,o),iW(l,r,n,o)]);return IW("adding empty dir called %s to %c",r,e),(yield ZK(u,c,n,t(t({},o),{},{allowOverwriting:o.force}))).cid})),PW.apply(this,arguments)}var _W=sd("helia:unixfs:utils:remove-link");function BW(){return BW=r((function*(e,t,r,n){if(null==e.node.Data)throw new gK("Parent node had no data");if("hamt-sharded-directory"===aq.unmarshal(e.node.Data).type){_W("removing ".concat(t," from sharded directory"));var i=yield DW(e,t,r,n);return(yield WK(i.node,r,n.shardSplitThresholdBytes,n))?i:(_W("converting shard to flat directory %c",e.cid),RW(i,r,n))}return _W("removing link ".concat(t," regular directory")),NW(e,t,r,n)})),BW.apply(this,arguments)}var NW=function(){var e=r((function*(e,r,n,i){e.node.Links=e.node.Links.filter((e=>e.Name!==r));var o=RN(e.node),a=yield DK(o,n,t(t({},i),{},{cidVersion:e.cid.version}));return _W("Updated regular directory ".concat(a)),{node:e.node,cid:a}}));return function(t,r,n,i){return e.apply(this,arguments)}}(),DW=function(){var e=r((function*(e,t,r,n){var{path:i}=yield KK(e.cid,t,r,n),o=i[i.length-1];if(null==o)throw new Error("Invalid HAMT, could not generate path");var a=o.node.Links.filter((e=>{var r;return(null!==(r=e.Name)&&void 0!==r?r:"").substring(2)===t})).map((e=>e.Name)).pop();if(null==a)throw new Error("File not found");var s=a.substring(0,2),l=parseInt(s,16);if(o.node.Links=o.node.Links.filter((e=>e.Name!==a)),o.children.unset(l),1===o.node.Links.length)for(var u=function*(){var e;if(1===i.length)return 0;var t=i[i.length-1];if(null==t||t.node.Links.length>1)return 0;i.pop();var r=i[i.length-1];if(null==r)return 0;var n=t.node.Links[0];r.node.Links=r.node.Links.filter((e=>{var t;return!(null!==(t=e.Name)&&void 0!==t?t:"").startsWith(r.prefix)})),r.node.Links.push({Hash:n.Hash,Name:"".concat(r.prefix).concat((null!==(e=n.Name)&&void 0!==e?e:"").substring(2)),Tsize:n.Tsize})};0!==(yield*u()););return HK(i,r,n)}));return function(t,r,n,i){return e.apply(this,arguments)}}(),RW=function(){var e=r((function*(e,t,r){if(null==e.node.Data)throw new kK("Invalid parent passed to convertToFlatDirectory");var n={Links:[]},i=yield lK(e.cid,t);if("directory"!==i.type)throw new Error("Unexpected node type");var o,a=!1,l=!1;try{for(var u,c=s(i.content());a=!(u=yield c.next()).done;a=!1){var d=u.value,h=0;h=d.node instanceof Uint8Array?d.node.byteLength:RN(d.node).length,n.Links.push({Hash:d.cid,Name:d.name,Tsize:h})}}catch(e){l=!0,o=e}finally{try{a&&null!=c.return&&(yield c.return())}finally{if(l)throw o}}var v=aq.unmarshal(e.node.Data);n.Data=new aq({type:"directory",mode:v.mode,mtime:v.mtime}).marshal();var p=RN(BN(n));return{cid:yield DK(p,t,{codec:LN,cidVersion:e.cid.version,signal:r.signal}),node:n}}));return function(t,r,n){return e.apply(this,arguments)}}(),OW=vK.bind({ignoreUndefined:!0}),LW=sd("helia:unixfs:rm"),MW={shardSplitThresholdBytes:pW};function UW(){return UW=r((function*(e,r,n){var i=OW(MW,arguments.length>3&&void 0!==arguments[3]?arguments[3]:{});if(r.includes("/"))throw new kK("Name must not have slashes");var o=yield rW(e,n,i);LW("Removing %s from %c",r,e);var a=yield function(e,t,r,n){return BW.apply(this,arguments)}(o,r,n,t(t({},i),{},{cidVersion:e.version}));return a.cid})),UW.apply(this,arguments)}var FW=vK.bind({ignoreUndefined:!0}),zW=sd("helia:unixfs:stat"),jW={};function VW(){return VW=r((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=FW(jW,r),i=yield sW(e,r.path,t,n);zW("stat %c",i.cid);var o=yield lK(i.cid,t,n);if("file"!==o.type&&"directory"!==o.type&&"raw"!==o.type)throw new fK;var a,s,l,u=0n,c=0n,d=0n,h=0n,v=0,p=o.type;if("raw"===o.type&&(u=BigInt(o.node.byteLength),c=BigInt(o.node.byteLength),d=BigInt(o.node.byteLength),h=BigInt(o.node.byteLength),v=1),"directory"===o.type&&(u=0n,d=0n,h=c=BigInt(o.unixfs.marshal().byteLength),v=1,a=o.unixfs.mode,s=o.unixfs.mtime,l=o.unixfs),"file"===o.type){var f,g,y=yield qW(i.cid,t,n);u=o.unixfs.fileSize(),c=BigInt((null!==(f=null===(g=o.node.Data)||void 0===g?void 0:g.byteLength)&&void 0!==f?f:0)+o.node.Links.reduce(((e,t)=>{var r;return e+(null!==(r=t.Tsize)&&void 0!==r?r:0)}),0)),d=BigInt(y.localFileSize),h=BigInt(y.localDagSize),v=y.blocks,a=o.unixfs.mode,s=o.unixfs.mtime,l=o.unixfs}return{cid:i.cid,mode:a,mtime:s,fileSize:u,dagSize:c,localFileSize:d,localDagSize:h,blocks:v,type:p,unixfs:l}})),VW.apply(this,arguments)}function qW(e,t,r){return HW.apply(this,arguments)}function HW(){return HW=r((function*(e,t,r){var n={localFileSize:0,localDagSize:0,blocks:0};if(yield t.has(e,r)){var i=yield t.get(e,r);if(n.blocks++,n.localDagSize+=i.byteLength,e.code===Se)n.localFileSize+=i.byteLength;else{if(e.code!==DN)throw new yK("".concat(e.toString()," was neither DAG_PB nor RAW"));var o=ON(i);if(o.Links.length>0)for(var a of o.Links){var s=yield qW(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 gK("PBNode ".concat(e.toString()," had no data"));var u=aq.unmarshal(o.Data);if(null==u.data)throw new gK("UnixFS node ".concat(e.toString()," had no data"));n.localFileSize+=null!==(l=u.data.byteLength)&&void 0!==l?l:0}}}return n})),HW.apply(this,arguments)}var KW=vK.bind({ignoreUndefined:!0}),WW=sd("helia:unixfs:touch"),GW={recursive:!1,shardSplitThresholdBytes:pW};function QW(){return QW=r((function*(e,n){var i,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=KW(GW,o),c=yield sW(e,a.path,n,a),d=null!==(i=a.mtime)&&void 0!==i?i:{secs:BigInt(Math.round(Date.now()/1e3)),nsecs:0};if(WW("touch %c %o",c.cid,d),a.recursive){var h=yield Fc(l((function*(){var e,t=!1,r=!1;try{for(var i,o=s(cK(c.cid,n));t=!(i=yield u(o.next())).done;t=!1){var a=i.value,l=void 0,h=void 0;if("raw"===a.type)l=new aq({data:a.node}),h=[];else{if("file"!==a.type&&"directory"!==a.type)throw new fK;l=a.unixfs,h=a.node.Links}l.mtime=d;var v={Data:l.marshal(),Links:h};yield{path:a.path,content:v}}}catch(t){r=!0,e=t}finally{try{t&&null!=o.return&&(yield u(o.return()))}finally{if(r)throw e}}})),(i=>{return cH(i,n,t(t({},a),{},{dagBuilder:(o=l((function*(n,i){var o,l=!1,c=!1;try{for(var d,h=function*(){var n=d.value;yield r((function*(){var r=n.content,o=RN(r),s=yield DK(o,i,t(t({},a),{},{cidVersion:e.version}));if(null==r.Data)throw new gK("".concat(s," had no data"));var l=aq.unmarshal(r.Data);return{cid:s,size:BigInt(o.length),path:n.path,unixfs:l}}))},v=s(n);l=!(d=yield u(v.next())).done;l=!1)yield*h()}catch(e){c=!0,o=e}finally{try{l&&null!=v.return&&(yield u(v.return()))}finally{if(c)throw o}}})),function(e,t){return o.apply(this,arguments)})}));var o}),function(){var e=r((function*(e){return kH(e)}));return function(t){return e.apply(this,arguments)}}());if(null==h)throw new yK("Could not chmod ".concat(c.cid.toString()));return uW(h.cid,c,n,a)}var v,p=yield n.get(c.cid,o),f=[];if(c.cid.code===Se)v=new aq({data:p});else{var g=ON(p);if(f=g.Links,null==g.Data)throw new gK("".concat(c.cid.toString()," had no data"));v=aq.unmarshal(g.Data)}v.mtime=d;var y=RN({Data:v.marshal(),Links:f}),m=yield $e.digest(y),w=it.create(c.cid.version,DN,m);return yield n.put(w,y),uW(w,c,n,a)})),QW.apply(this,arguments)}class YW{constructor(t){e(this,"components",void 0),this.components=t}addAll(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(function(e,t){return mH.apply(this,arguments)}(e,t.components.blockstore,r)))}()})).apply(this,arguments)}addBytes(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};return function(e,t){return wH.apply(this,arguments)}(e,n.components.blockstore,r)}))()}addByteStream(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};return function(e,t){return bH.apply(this,arguments)}(e,n.components.blockstore,r)}))()}addFile(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};return function(e,t){return SH.apply(this,arguments)}(e,n.components.blockstore,r)}))()}addDirectory(){var e=arguments,t=this;return r((function*(){var r=e.length>1&&void 0!==e[1]?e[1]:{};return function(e,t){return EH.apply(this,arguments)}(e.length>0&&void 0!==e[0]?e[0]:{},t.components.blockstore,r)}))()}cat(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(function(e,t){return vW.apply(this,arguments)}(e,t.components.blockstore,r)))}()})).apply(this,arguments)}chmod(e,t){var n=arguments,i=this;return r((function*(){var r=n.length>2&&void 0!==n[2]?n[2]:{};return function(e,t,r){return mW.apply(this,arguments)}(e,t,i.components.blockstore,r)}))()}cp(e,t,n){var i=arguments,o=this;return r((function*(){var r=i.length>3&&void 0!==i[3]?i[3]:{};return function(e,t,r,n){return EW.apply(this,arguments)}(e,t,n,o.components.blockstore,r)}))()}ls(e){var t=this;return l((function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*c(s(function(e,t){return AW.apply(this,arguments)}(e,t.components.blockstore,r)))}()})).apply(this,arguments)}mkdir(e,t){var n=arguments,i=this;return r((function*(){var r=n.length>2&&void 0!==n[2]?n[2]:{};return function(e,t,r){return PW.apply(this,arguments)}(e,t,i.components.blockstore,r)}))()}rm(e,t){var n=arguments,i=this;return r((function*(){var r=n.length>2&&void 0!==n[2]?n[2]:{};return function(e,t,r){return UW.apply(this,arguments)}(e,t,i.components.blockstore,r)}))()}stat(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};return function(e,t){return VW.apply(this,arguments)}(e,n.components.blockstore,r)}))()}touch(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{};return function(e,t){return QW.apply(this,arguments)}(e,n.components.blockstore,r)}))()}}function JW(e){return new YW(e)}class ZW{constructor(t){e(this,"components",void 0),this.components=t}add(e){var t=arguments,n=this;return r((function*(){var r,i=t.length>1&&void 0!==t[1]?t[1]:{},o=GB(e),a=yield(null!==(r=i.hasher)&&void 0!==r?r:$e).digest(o),s=it.createV1(WB,a);return yield n.components.blockstore.put(s,o,i),s}))()}get(e){var t=arguments,n=this;return r((function*(){var r=t.length>1&&void 0!==t[1]?t[1]:{},i=yield n.components.blockstore.get(e,r);return QB(i)}))()}}function $W(e){return new ZW(e)}export{Ec as $,xo as A,va as B,da as C,aa as D,ia as E,fa as F,ua as G,nn as H,pa as I,la as J,ga as K,ku as L,Go as M,K as N,Vr as O,Jr as P,it as Q,Ge as R,ie as S,kr as T,hi as U,fc as V,gc as W,Nc as X,mc as Y,wc as Z,ca as _,Nr as a,$W as a$,bc as a0,dc as a1,vc as a2,lc as a3,ud as a4,W as a5,Se as a6,He as a7,_c as a8,Fc as a9,Jo as aA,Du as aB,mu as aC,Eu as aD,xu as aE,Su as aF,Lu as aG,Mt as aH,JW as aI,gt as aJ,ii as aK,wu as aL,Ru as aM,Ou as aN,ya as aO,Er as aP,dI as aQ,ut as aR,rr as aS,GB as aT,$e as aU,WB as aV,QB as aW,Lt as aX,Nt as aY,bv as aZ,KB as a_,gu as aa,qV as ab,WV as ac,Sr as ad,gs as ae,rD as af,UF as ag,_L as ah,PL as ai,mL as aj,CO as ak,bO as al,PI as am,VI as an,Nv as ao,qI as ap,sn as aq,Xo as ar,Wn as as,Kn as at,Dr as au,rn as av,Qn as aw,rc as ax,Oi as ay,Xr as az,Cr as b,an as c,Pr as d,Ir as e,fn as f,Fr as g,_r as h,Bn as i,kn as j,Pn as k,bn as l,wn as m,En as n,Sn as o,_n as p,gn as q,xn as r,Ur as s,en as t,Br as u,on as v,An as w,Cn as x,In as y,Tn as z};