@libp2p/webrtc 5.0.16-7c085d10c → 5.0.16-adc767899

Sign up to get free protection for your applications and to get access to all the features.
Files changed (2) hide show
  1. package/dist/index.min.js +4 -4
  2. package/package.json +12 -12
package/dist/index.min.js CHANGED
@@ -1,9 +1,9 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PWebrtc = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var Libp2PWebrtc=(()=>{var Zh=Object.create;var Zn=Object.defineProperty;var Xh=Object.getOwnPropertyDescriptor;var Yh=Object.getOwnPropertyNames;var Jh=Object.getPrototypeOf,Qh=Object.prototype.hasOwnProperty;var td=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Nt=(r,t)=>{for(var e in t)Zn(r,e,{get:t[e],enumerable:!0})},Gc=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Yh(t))!Qh.call(r,o)&&o!==e&&Zn(r,o,{get:()=>t[o],enumerable:!(n=Xh(t,o))||n.enumerable});return r};var ed=(r,t,e)=>(e=r!=null?Zh(Jh(r)):{},Gc(t||!r||!r.__esModule?Zn(e,"default",{value:r,enumerable:!0}):e,r)),rd=r=>Gc(Zn({},"__esModule",{value:!0}),r);var Gl=td(Dr=>{"use strict";var Bm="[object ArrayBuffer]",Se=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===Bm}static toArrayBuffer(t){return this.isArrayBuffer(t)?t:t.byteLength===t.buffer.byteLength||t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:this.toUint8Array(t.buffer).slice(t.byteOffset,t.byteOffset+t.byteLength).buffer}static toUint8Array(t){return this.toView(t,Uint8Array)}static toView(t,e){if(t.constructor===e)return t;if(this.isArrayBuffer(t))return new e(t);if(this.isArrayBufferView(t))return new e(t.buffer,t.byteOffset,t.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(t){return this.isArrayBufferView(t)||this.isArrayBuffer(t)}static isArrayBufferView(t){return ArrayBuffer.isView(t)||t&&this.isArrayBuffer(t.buffer)}static isEqual(t,e){let n=r.toUint8Array(t),o=r.toUint8Array(e);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...t){let e;Array.isArray(t[0])&&!(t[1]instanceof Function)||Array.isArray(t[0])&&t[1]instanceof Function?e=t[0]:t[t.length-1]instanceof Function?e=t.slice(0,t.length-1):e=t;let n=0;for(let i of e)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of e){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return t[t.length-1]instanceof Function?this.toView(o,t[t.length-1]):o.buffer}},va="string",Im=/^[0-9a-f]+$/i,Cm=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,km=/^[a-zA-Z0-9-_]+$/,vo=class{static fromString(t){let e=unescape(encodeURIComponent(t)),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n.buffer}static toString(t){let e=Se.toUint8Array(t),n="";for(let s=0;s<e.length;s++)n+=String.fromCharCode(e[s]);return decodeURIComponent(escape(n))}},jt=class{static toString(t,e=!1){let n=Se.toArrayBuffer(t),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,e);s+=String.fromCharCode(a)}return s}static fromString(t,e=!1){let n=new ArrayBuffer(t.length*2),o=new DataView(n);for(let s=0;s<t.length;s++)o.setUint16(s*2,t.charCodeAt(s),e);return n}},So=class r{static isHex(t){return typeof t===va&&Im.test(t)}static isBase64(t){return typeof t===va&&Cm.test(t)}static isBase64Url(t){return typeof t===va&&km.test(t)}static ToString(t,e="utf8"){let n=Se.toUint8Array(t);switch(e.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 jt.toString(n,!0);case"utf16":case"utf16be":return jt.toString(n);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromString(t,e="utf8"){if(!t)return new ArrayBuffer(0);switch(e.toLowerCase()){case"utf8":return this.FromUtf8String(t);case"binary":return this.FromBinary(t);case"hex":return this.FromHex(t);case"base64":return this.FromBase64(t);case"base64url":return this.FromBase64Url(t);case"utf16le":return jt.fromString(t,!0);case"utf16":case"utf16be":return jt.fromString(t);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToBase64(t){let e=Se.toUint8Array(t);if(typeof btoa<"u"){let n=this.ToString(e,"binary");return btoa(n)}else return Buffer.from(e).toString("base64")}static FromBase64(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64(e))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(e)):new Uint8Array(Buffer.from(e,"base64")).buffer}static FromBase64Url(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64Url(e))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(e.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(t){return this.ToBase64(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.FromBinary(t);case"utf8":return vo.fromString(t);case"utf16":case"utf16be":return jt.fromString(t);case"utf16le":case"usc2":return jt.fromString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.ToBinary(t);case"utf8":return vo.toString(t);case"utf16":case"utf16be":return jt.toString(t);case"utf16le":case"usc2":return jt.toString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromBinary(t){let e=t.length,n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);return n.buffer}static ToBinary(t){let e=Se.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=Se.toUint8Array(t),n="",o=e.length;for(let s=0;s<o;s++){let i=e[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isHex(e))throw new TypeError("Argument 'hexString' is not HEX encoded");e.length%2&&(e=`0${e}`);let n=new Uint8Array(e.length/2);for(let o=0;o<e.length;o=o+2){let s=e.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(t,e=!1){return jt.toString(t,e)}static FromUtf16String(t,e=!1){return jt.fromString(t,e)}static Base64Padding(t){let e=4-t.length%4;if(e<4)for(let n=0;n<e;n++)t+="=";return t}static formatString(t){return t?.replace(/[\n\r\t ]/g,"")||""}};So.DEFAULT_UTF8_ENCODING="utf8";function Tm(r,...t){let e=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)e[s]=o[s]}return e}function Nm(...r){let t=r.map(o=>o.byteLength).reduce((o,s)=>o+s),e=new Uint8Array(t),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)e[n++]=s}),e.buffer}function Lm(r,t){if(!(r&&t)||r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)if(e[o]!==n[o])return!1;return!0}Dr.BufferSourceConverter=Se;Dr.Convert=So;Dr.assign=Tm;Dr.combine=Nm;Dr.isEqual=Lm});var Mg={};Nt(Mg,{webRTC:()=>Hg,webRTCDirect:()=>Og});var di=Symbol.for("@libp2p/peer-id");var Xn=Symbol.for("@libp2p/transport");var jc;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(jc||(jc={}));var Yn=class extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}};var et=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},vr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Jn=class extends Error{static name="ConnectionFailedError";constructor(t="Connection failed"){super(t),this.name="ConnectionFailedError"}};var Qn=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}},tr=class extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}};var to=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var eo=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var rn=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}};var er=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var ro=(r,...t)=>{try{[...t]}catch{}};var no=class extends EventTarget{#t=new Map;constructor(){super(),ro(1/0,this)}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};var Sr=Symbol.for("@libp2p/service-capabilities"),Zc=Symbol.for("@libp2p/service-dependencies");var yi={};Nt(yi,{base58btc:()=>ot,base58flickr:()=>cd});var gw=new Uint8Array(0);function Xc(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function me(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Yc(r){return new TextEncoder().encode(r)}function Jc(r){return new TextDecoder().decode(r)}function nd(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(x){if(x instanceof Uint8Array||(ArrayBuffer.isView(x)?x=new Uint8Array(x.buffer,x.byteOffset,x.byteLength):Array.isArray(x)&&(x=Uint8Array.from(x))),!(x instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(x.length===0)return"";for(var g=0,h=0,w=0,b=x.length;w!==b&&x[w]===0;)w++,g++;for(var p=(b-w)*u+1>>>0,B=new Uint8Array(p);w!==b;){for(var L=x[w],N=0,A=p-1;(L!==0||N<h)&&A!==-1;A--,N++)L+=256*B[A]>>>0,B[A]=L%a>>>0,L=L/a>>>0;if(L!==0)throw new Error("Non-zero carry");h=N,w++}for(var k=p-h;k!==p&&B[k]===0;)k++;for(var I=c.repeat(g);k<p;++k)I+=r.charAt(B[k]);return I}function d(x){if(typeof x!="string")throw new TypeError("Expected String");if(x.length===0)return new Uint8Array;var g=0;if(x[g]!==" "){for(var h=0,w=0;x[g]===c;)h++,g++;for(var b=(x.length-g)*l+1>>>0,p=new Uint8Array(b);x[g];){var B=e[x.charCodeAt(g)];if(B===255)return;for(var L=0,N=b-1;(B!==0||L<w)&&N!==-1;N--,L++)B+=a*p[N]>>>0,p[N]=B%256>>>0,B=B/256>>>0;if(B!==0)throw new Error("Non-zero carry");w=L,g++}if(x[g]!==" "){for(var A=b-w;A!==b&&p[A]===0;)A++;for(var k=new Uint8Array(h+(b-A)),I=h;A!==b;)k[I++]=p[A++];return k}}}function m(x){var g=d(x);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:m}}var od=nd,sd=od,tl=sd;var pi=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},mi=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return el(this,t)}},gi=class{decoders;constructor(t){this.decoders=t}or(t){return el(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function el(r,t){return new gi({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var wi=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new pi(t,e,n),this.decoder=new mi(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Ar({name:r,prefix:t,encode:e,decode:n}){return new wi(r,t,e,n)}function Pe({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=tl(e,r);return Ar({prefix:t,name:r,encode:n,decode:s=>me(o(s))})}function id(r,t,e,n){let o={};for(let u=0;u<t.length;++u)o[t[u]]=u;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*e/8|0),a=0,c=0,l=0;for(let u=0;u<s;++u){let f=o[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|f,a+=e,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function ad(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;s.length*e&7;)s+="=";return s}function pt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Ar({prefix:t,name:r,encode(o){return ad(o,n,e)},decode(o){return id(o,n,e,r)}})}var ot=Pe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),cd=Pe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var bi={};Nt(bi,{base32:()=>ge,base32hex:()=>hd,base32hexpad:()=>pd,base32hexpadupper:()=>md,base32hexupper:()=>dd,base32pad:()=>ud,base32padupper:()=>fd,base32upper:()=>ld,base32z:()=>gd});var ge=pt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ld=pt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ud=pt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),fd=pt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),hd=pt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),dd=pt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),pd=pt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),md=pt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),gd=pt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var xi={};Nt(xi,{base36:()=>nn,base36upper:()=>wd});var nn=Pe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),wd=Pe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Xt={};Nt(Xt,{Digest:()=>rr,create:()=>Vt,decode:()=>Oe,equals:()=>vi,hasCode:()=>Pd});var yd=ol,rl=128,bd=127,xd=~bd,Ed=Math.pow(2,31);function ol(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Ed;)t[e++]=r&255|rl,r/=128;for(;r&xd;)t[e++]=r&255|rl,r>>>=7;return t[e]=r|0,ol.bytes=e-n+1,t}var vd=Ei,Sd=128,nl=127;function Ei(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ei.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&nl)<<o:(i&nl)*Math.pow(2,o),o+=7}while(i>=Sd);return Ei.bytes=s-n,e}var Ad=Math.pow(2,7),Bd=Math.pow(2,14),Id=Math.pow(2,21),Cd=Math.pow(2,28),kd=Math.pow(2,35),Td=Math.pow(2,42),Nd=Math.pow(2,49),Ld=Math.pow(2,56),_d=Math.pow(2,63),Rd=function(r){return r<Ad?1:r<Bd?2:r<Id?3:r<Cd?4:r<kd?5:r<Td?6:r<Nd?7:r<Ld?8:r<_d?9:10},Ud={encode:yd,decode:vd,encodingLength:Rd},Dd=Ud,on=Dd;function sn(r,t=0){return[on.decode(r,t),on.decode.bytes]}function Br(r,t,e=0){return on.encode(r,t,e),t}function Ir(r){return on.encodingLength(r)}function Vt(r,t){let e=t.byteLength,n=Ir(r),o=n+Ir(e),s=new Uint8Array(o+e);return Br(r,s,0),Br(e,s,n),s.set(t,o),new rr(r,e,t,s)}function Oe(r){let t=me(r),[e,n]=sn(t),[o,s]=sn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new rr(e,o,i,t)}function vi(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Xc(r.bytes,e.bytes)}}var rr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Pd(r,t){return r.code===t}function sl(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Hd(e,Si(r),t??ot.encoder);default:return Md(e,Si(r),t??ge.encoder)}}var il=new WeakMap;function Si(r){let t=il.get(r);if(t==null){let e=new Map;return il.set(r,e),e}return t}var Bt=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}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:{let{code:t,multihash:e}=this;if(t!==an)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Vd)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Vt(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&vi(t.multihash,n.multihash)}toString(t){return sl(this,t)}toJSON(){return{"/":sl(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??al(n,o,s.bytes))}else if(e[Fd]===!0){let{version:n,multihash:o,code:s}=e,i=Oe(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==an)throw new Error(`Version 0 CID must use dag-pb (code: ${an}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=al(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,an,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=me(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new rr(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,d]=sn(t.subarray(e));return e+=d,f},o=n(),s=an;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=Od(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Si(s).set(n,t),s}};function Od(r,t){switch(r[0]){case"Q":{let e=t??ot;return[ot.prefix,e.decode(`${ot.prefix}${r}`)]}case ot.prefix:{let e=t??ot;return[ot.prefix,e.decode(r)]}case ge.prefix:{let e=t??ge;return[ge.prefix,e.decode(r)]}case nn.prefix:{let e=t??nn;return[nn.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Hd(r,t,e){let{prefix:n}=e;if(n!==ot.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Md(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var an=112,Vd=18;function al(r,t,e){let n=Ir(r),o=n+Ir(t),s=new Uint8Array(o+e.byteLength);return Br(r,s,0),Br(t,s,n),s.set(e,o),s}var Fd=Symbol.for("@ipld/js-cid/CID");var Ai={};Nt(Ai,{identity:()=>we});var cl=0,Kd="identity",ll=me;function $d(r){return Vt(cl,ll(r))}var we={code:cl,name:Kd,encode:ll,digest:$d};function Dt(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function so(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Wd(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Cr(r,...t){if(!Wd(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function cn(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");so(r.outputLen),so(r.blockLen)}function kr(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function ul(r,t){Cr(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var nr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var io=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Yt=(r,t)=>r<<32-t|r>>>t;var Mw=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function fl(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function He(r){return typeof r=="string"&&(r=fl(r)),Cr(r),r}function Bi(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Cr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}var Tr=class{clone(){return this._cloneInto()}},Vw={}.toString;function ao(r){let t=n=>r().update(He(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function ln(r=32){if(nr&&typeof nr.getRandomValues=="function")return nr.getRandomValues(new Uint8Array(r));if(nr&&typeof nr.randomBytes=="function")return nr.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function qd(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}var hl=(r,t,e)=>r&t^~r&e,dl=(r,t,e)=>r&t^r&e^t&e,Nr=class extends Tr{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=io(this.buffer)}update(t){kr(this);let{view:e,buffer:n,blockLen:o}=this;t=He(t);let s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=io(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){kr(this),ul(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;qd(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=io(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.length=o,t.pos=a,t.finished=s,t.destroyed=i,o%e&&t.buffer.set(n),t}};var co=BigInt(4294967295),Ii=BigInt(32);function pl(r,t=!1){return t?{h:Number(r&co),l:Number(r>>Ii&co)}:{h:Number(r>>Ii&co)|0,l:Number(r&co)|0}}function zd(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=pl(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var Gd=(r,t)=>BigInt(r>>>0)<<Ii|BigInt(t>>>0),jd=(r,t,e)=>r>>>e,Zd=(r,t,e)=>r<<32-e|t>>>e,Xd=(r,t,e)=>r>>>e|t<<32-e,Yd=(r,t,e)=>r<<32-e|t>>>e,Jd=(r,t,e)=>r<<64-e|t>>>e-32,Qd=(r,t,e)=>r>>>e-32|t<<64-e,tp=(r,t)=>t,ep=(r,t)=>r,rp=(r,t,e)=>r<<e|t>>>32-e,np=(r,t,e)=>t<<e|r>>>32-e,op=(r,t,e)=>t<<e-32|r>>>64-e,sp=(r,t,e)=>r<<e-32|t>>>64-e;function ip(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var ap=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),cp=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,lp=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),up=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,fp=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),hp=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var dp={fromBig:pl,split:zd,toBig:Gd,shrSH:jd,shrSL:Zd,rotrSH:Xd,rotrSL:Yd,rotrBH:Jd,rotrBL:Qd,rotr32H:tp,rotr32L:ep,rotlSH:rp,rotlSL:np,rotlBH:op,rotlBL:sp,add:ip,add3L:ap,add3H:cp,add4L:lp,add4H:up,add5H:hp,add5L:fp},q=dp;var[pp,mp]=q.split(["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(r=>BigInt(r))),Me=new Uint32Array(80),Ve=new Uint32Array(80),Ci=class extends Nr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:m,Gl:x,Hh:g,Hl:h}=this;return[t,e,n,o,s,i,a,c,l,u,f,d,m,x,g,h]}set(t,e,n,o,s,i,a,c,l,u,f,d,m,x,g,h){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=m|0,this.Gl=x|0,this.Hh=g|0,this.Hl=h|0}process(t,e){for(let p=0;p<16;p++,e+=4)Me[p]=t.getUint32(e),Ve[p]=t.getUint32(e+=4);for(let p=16;p<80;p++){let B=Me[p-15]|0,L=Ve[p-15]|0,N=q.rotrSH(B,L,1)^q.rotrSH(B,L,8)^q.shrSH(B,L,7),A=q.rotrSL(B,L,1)^q.rotrSL(B,L,8)^q.shrSL(B,L,7),k=Me[p-2]|0,I=Ve[p-2]|0,V=q.rotrSH(k,I,19)^q.rotrBH(k,I,61)^q.shrSH(k,I,6),_=q.rotrSL(k,I,19)^q.rotrBL(k,I,61)^q.shrSL(k,I,6),H=q.add4L(A,_,Ve[p-7],Ve[p-16]),K=q.add4H(H,N,V,Me[p-7],Me[p-16]);Me[p]=K|0,Ve[p]=H|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:m,Fl:x,Gh:g,Gl:h,Hh:w,Hl:b}=this;for(let p=0;p<80;p++){let B=q.rotrSH(f,d,14)^q.rotrSH(f,d,18)^q.rotrBH(f,d,41),L=q.rotrSL(f,d,14)^q.rotrSL(f,d,18)^q.rotrBL(f,d,41),N=f&m^~f&g,A=d&x^~d&h,k=q.add5L(b,L,A,mp[p],Ve[p]),I=q.add5H(k,w,B,N,pp[p],Me[p]),V=k|0,_=q.rotrSH(n,o,28)^q.rotrBH(n,o,34)^q.rotrBH(n,o,39),H=q.rotrSL(n,o,28)^q.rotrBL(n,o,34)^q.rotrBL(n,o,39),K=n&s^n&a^s&a,C=o&i^o&c^i&c;w=g|0,b=h|0,g=m|0,h=x|0,m=f|0,x=d|0,{h:f,l:d}=q.add(l|0,u|0,I|0,V|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let T=q.add3L(V,H,C);n=q.add3H(T,I,_,K),o=T|0}({h:n,l:o}=q.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=q.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=q.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=q.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=q.add(this.Eh|0,this.El|0,f|0,d|0),{h:m,l:x}=q.add(this.Fh|0,this.Fl|0,m|0,x|0),{h:g,l:h}=q.add(this.Gh|0,this.Gl|0,g|0,h|0),{h:w,l:b}=q.add(this.Hh|0,this.Hl|0,w|0,b|0),this.set(n,o,s,i,a,c,l,u,f,d,m,x,g,h,w,b)}roundClean(){Me.fill(0),Ve.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var ml=ao(()=>new Ci);var uo={};Nt(uo,{aInRange:()=>It,abool:()=>Jt,abytes:()=>Lr,bitGet:()=>Ep,bitLen:()=>_i,bitMask:()=>fn,bitSet:()=>vp,bytesToHex:()=>be,bytesToNumberBE:()=>xe,bytesToNumberLE:()=>Qt,concatBytes:()=>ve,createHmacDrbg:()=>Ri,ensureBytes:()=>at,equalBytes:()=>bp,hexToBytes:()=>sr,hexToNumber:()=>Li,inRange:()=>un,isBytes:()=>Fe,memoized:()=>ir,notImplemented:()=>Ap,numberToBytesBE:()=>Ke,numberToBytesLE:()=>Ee,numberToHexUnpadded:()=>or,numberToVarBytesBE:()=>yp,utf8ToBytes:()=>xp,validateObject:()=>Gt});var Ni=BigInt(0),lo=BigInt(1),gp=BigInt(2);function Fe(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Lr(r){if(!Fe(r))throw new Error("Uint8Array expected")}function Jt(r,t){if(typeof t!="boolean")throw new Error(`${r} must be valid boolean, got "${t}".`)}var wp=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function be(r){Lr(r);let t="";for(let e=0;e<r.length;e++)t+=wp[r[e]];return t}function or(r){let t=r.toString(16);return t.length&1?`0${t}`:t}function Li(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var ye={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function gl(r){if(r>=ye._0&&r<=ye._9)return r-ye._0;if(r>=ye._A&&r<=ye._F)return r-(ye._A-10);if(r>=ye._a&&r<=ye._f)return r-(ye._a-10)}function sr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=gl(r.charCodeAt(s)),a=gl(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function xe(r){return Li(be(r))}function Qt(r){return Lr(r),Li(be(Uint8Array.from(r).reverse()))}function Ke(r,t){return sr(r.toString(16).padStart(t*2,"0"))}function Ee(r,t){return Ke(r,t).reverse()}function yp(r){return sr(or(r))}function at(r,t,e){let n;if(typeof t=="string")try{n=sr(t)}catch(s){throw new Error(`${r} must be valid hex string, got "${t}". Cause: ${s}`)}else if(Fe(t))n=Uint8Array.from(t);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(`${r} expected ${e} bytes, got ${o}`);return n}function ve(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Lr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function bp(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function xp(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var ki=r=>typeof r=="bigint"&&Ni<=r;function un(r,t,e){return ki(r)&&ki(t)&&ki(e)&&t<=r&&r<e}function It(r,t,e,n){if(!un(t,e,n))throw new Error(`expected valid ${r}: ${e} <= n < ${n}, got ${typeof t} ${t}`)}function _i(r){let t;for(t=0;r>Ni;r>>=lo,t+=1);return t}function Ep(r,t){return r>>BigInt(t)&lo}function vp(r,t,e){return r|(e?lo:Ni)<<BigInt(t)}var fn=r=>(gp<<BigInt(r-1))-lo,Ti=r=>new Uint8Array(r),wl=r=>Uint8Array.from(r);function Ri(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=Ti(r),o=Ti(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=Ti())=>{o=a(wl([0]),f),n=a(),f.length!==0&&(o=a(wl([1]),f),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<t;){n=a();let m=n.slice();d.push(m),f+=n.length}return ve(...d)};return(f,d)=>{i(),c(f);let m;for(;!(m=d(l()));)c();return i(),m}}var Sp={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Fe(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function Gt(r,t,e={}){let n=(o,s,i)=>{let a=Sp[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(e))n(o,s,!0);return r}var Ap=()=>{throw new Error("not implemented")};function ir(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var bt=BigInt(0),ft=BigInt(1),ar=BigInt(2),Bp=BigInt(3),Ui=BigInt(4),yl=BigInt(5),bl=BigInt(8),Ip=BigInt(9),Cp=BigInt(16);function Y(r,t){let e=r%t;return e>=bt?e:t+e}function Di(r,t,e){if(e<=bt||t<bt)throw new Error("Expected power/modulo > 0");if(e===ft)return bt;let n=ft;for(;t>bt;)t&ft&&(n=n*r%e),r=r*r%e,t>>=ft;return n}function ct(r,t,e){let n=r;for(;t-- >bt;)n*=n,n%=e;return n}function fo(r,t){if(r===bt||t<=bt)throw new Error(`invert: expected positive integers, got n=${r} mod=${t}`);let e=Y(r,t),n=t,o=bt,s=ft,i=ft,a=bt;for(;e!==bt;){let l=n/e,u=n%e,f=o-i*l,d=s-a*l;n=e,e=u,o=i,s=a,i=f,a=d}if(n!==ft)throw new Error("invert: does not exist");return Y(o,t)}function kp(r){let t=(r-ft)/ar,e,n,o;for(e=r-ft,n=0;e%ar===bt;e/=ar,n++);for(o=ar;o<r&&Di(o,t,r)!==r-ft;o++);if(n===1){let i=(r+ft)/Ui;return function(c,l){let u=c.pow(l,i);if(!c.eql(c.sqr(u),l))throw new Error("Cannot find square root");return u}}let s=(e+ft)/ar;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),e),f=a.pow(c,s),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let m=1;for(let g=a.sqr(d);m<l&&!a.eql(g,a.ONE);m++)g=a.sqr(g);let x=a.pow(u,ft<<BigInt(l-m-1));u=a.sqr(x),f=a.mul(f,x),d=a.mul(d,u),l=m}return f}}function Tp(r){if(r%Ui===Bp){let t=(r+ft)/Ui;return function(n,o){let s=n.pow(o,t);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%bl===yl){let t=(r-yl)/bl;return function(n,o){let s=n.mul(o,ar),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,ar),i),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%Cp,kp(r)}var xl=(r,t)=>(Y(r,t)&ft)===ft,Np=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Pi(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Np.reduce((n,o)=>(n[o]="function",n),t);return Gt(r,e)}function Lp(r,t,e){if(e<bt)throw new Error("Expected power > 0");if(e===bt)return r.ONE;if(e===ft)return t;let n=r.ONE,o=t;for(;e>bt;)e&ft&&(n=r.mul(n,o)),o=r.sqr(o),e>>=ft;return n}function _p(r,t){let e=new Array(t.length),n=t.reduce((s,i,a)=>r.is0(i)?s:(e[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return t.reduceRight((s,i,a)=>r.is0(i)?s:(e[a]=r.mul(s,e[a]),r.mul(s,i)),o),e}function Oi(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function $e(r,t,e=!1,n={}){if(r<=bt)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=Oi(r,t);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=Tp(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:fn(o),ZERO:bt,ONE:ft,create:c=>Y(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return bt<=c&&c<r},is0:c=>c===bt,isOdd:c=>(c&ft)===ft,neg:c=>Y(-c,r),eql:(c,l)=>c===l,sqr:c=>Y(c*c,r),add:(c,l)=>Y(c+l,r),sub:(c,l)=>Y(c-l,r),mul:(c,l)=>Y(c*l,r),pow:(c,l)=>Lp(a,c,l),div:(c,l)=>Y(c*fo(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>fo(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>_p(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?Ee(c,s):Ke(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return e?Qt(c):xe(c)}});return Object.freeze(a)}function El(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Hi(r){let t=El(r);return t+Math.ceil(t/2)}function vl(r,t,e=!1){let n=r.length,o=El(t),s=Hi(t);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=e?xe(r):Qt(r),a=Y(i,t-ft)+ft;return e?Ee(a,o):Ke(a,o)}var Up=BigInt(0),Mi=BigInt(1),Vi=new WeakMap,Sl=new WeakMap;function ho(r,t){let e=(s,i)=>{let a=i.negate();return s?a:i},n=s=>{if(!Number.isSafeInteger(s)||s<=0||s>t)throw new Error(`Wrong window size=${s}, should be [1..${t}]`)},o=s=>{n(s);let i=Math.ceil(t/s)+1,a=2**(s-1);return{windows:i,windowSize:a}};return{constTimeNegate:e,unsafeLadder(s,i){let a=r.ZERO,c=s;for(;i>Up;)i&Mi&&(a=a.add(c)),c=c.double(),i>>=Mi;return a},precomputeWindow(s,i){let{windows:a,windowSize:c}=o(i),l=[],u=s,f=u;for(let d=0;d<a;d++){f=u,l.push(f);for(let m=1;m<c;m++)f=f.add(u),l.push(f);u=f.double()}return l},wNAF(s,i,a){let{windows:c,windowSize:l}=o(s),u=r.ZERO,f=r.BASE,d=BigInt(2**s-1),m=2**s,x=BigInt(s);for(let g=0;g<c;g++){let h=g*l,w=Number(a&d);a>>=x,w>l&&(w-=m,a+=Mi);let b=h,p=h+Math.abs(w)-1,B=g%2!==0,L=w<0;w===0?f=f.add(e(B,i[b])):u=u.add(e(L,i[p]))}return{p:u,f}},wNAFCached(s,i,a){let c=Sl.get(s)||1,l=Vi.get(s);return l||(l=this.precomputeWindow(s,c),c!==1&&Vi.set(s,a(l))),this.wNAF(c,l,i)},setWindowSize(s,i){n(i),Sl.set(s,i),Vi.delete(s)}}}function po(r,t,e,n){if(!Array.isArray(e)||!Array.isArray(n)||n.length!==e.length)throw new Error("arrays of points and scalars must have equal length");n.forEach((u,f)=>{if(!t.isValid(u))throw new Error(`wrong scalar at index ${f}`)}),e.forEach((u,f)=>{if(!(u instanceof r))throw new Error(`wrong point at index ${f}`)});let o=_i(BigInt(e.length)),s=o>12?o-3:o>4?o-2:o?2:1,i=(1<<s)-1,a=new Array(i+1).fill(r.ZERO),c=Math.floor((t.BITS-1)/s)*s,l=r.ZERO;for(let u=c;u>=0;u-=s){a.fill(r.ZERO);for(let d=0;d<n.length;d++){let m=n[d],x=Number(m>>BigInt(u)&BigInt(i));a[x]=a[x].add(e[d])}let f=r.ZERO;for(let d=a.length-1,m=r.ZERO;d>0;d--)m=m.add(a[d]),f=f.add(m);if(l=l.add(f),u!==0)for(let d=0;d<s;d++)l=l.double()}return l}function hn(r){return Pi(r.Fp),Gt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Oi(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var te=BigInt(0),Ft=BigInt(1),mo=BigInt(2),Dp=BigInt(8),Pp={zip215:!0};function Op(r){let t=hn(r);return Gt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Al(r){let t=Op(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=mo<<BigInt(a*8)-Ft,u=e.create,f=$e(t.n,t.nBitLength),d=t.uvRatio||((E,y)=>{try{return{isValid:!0,value:e.sqrt(E*e.inv(y))}}catch{return{isValid:!1,value:te}}}),m=t.adjustScalarBytes||(E=>E),x=t.domain||((E,y,S)=>{if(Jt("phflag",S),y.length||S)throw new Error("Contexts/pre-hash are not supported");return E});function g(E,y){It("coordinate "+E,y,te,l)}function h(E){if(!(E instanceof p))throw new Error("ExtendedPoint expected")}let w=ir((E,y)=>{let{ex:S,ey:v,ez:R}=E,D=E.is0();y==null&&(y=D?Dp:e.inv(R));let M=u(S*y),$=u(v*y),W=u(R*y);if(D)return{x:te,y:Ft};if(W!==Ft)throw new Error("invZ was invalid");return{x:M,y:$}}),b=ir(E=>{let{a:y,d:S}=t;if(E.is0())throw new Error("bad point: ZERO");let{ex:v,ey:R,ez:D,et:M}=E,$=u(v*v),W=u(R*R),z=u(D*D),j=u(z*z),st=u($*y),it=u(z*u(st+W)),ut=u(j+u(S*u($*W)));if(it!==ut)throw new Error("bad point: equation left != right (1)");let Ut=u(v*R),yt=u(D*M);if(Ut!==yt)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(y,S,v,R){this.ex=y,this.ey=S,this.ez=v,this.et=R,g("x",y),g("y",S),g("z",v),g("t",R),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(y){if(y instanceof p)throw new Error("extended point not allowed");let{x:S,y:v}=y||{};return g("x",S),g("y",v),new p(S,v,Ft,u(S*v))}static normalizeZ(y){let S=e.invertBatch(y.map(v=>v.ez));return y.map((v,R)=>v.toAffine(S[R])).map(p.fromAffine)}static msm(y,S){return po(p,f,y,S)}_setWindowSize(y){N.setWindowSize(this,y)}assertValidity(){b(this)}equals(y){h(y);let{ex:S,ey:v,ez:R}=this,{ex:D,ey:M,ez:$}=y,W=u(S*$),z=u(D*R),j=u(v*$),st=u(M*R);return W===z&&j===st}is0(){return this.equals(p.ZERO)}negate(){return new p(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:y}=t,{ex:S,ey:v,ez:R}=this,D=u(S*S),M=u(v*v),$=u(mo*u(R*R)),W=u(y*D),z=S+v,j=u(u(z*z)-D-M),st=W+M,it=st-$,ut=W-M,Ut=u(j*it),yt=u(st*ut),Mt=u(j*ut),pe=u(it*st);return new p(Ut,yt,pe,Mt)}add(y){h(y);let{a:S,d:v}=t,{ex:R,ey:D,ez:M,et:$}=this,{ex:W,ey:z,ez:j,et:st}=y;if(S===BigInt(-1)){let Vc=u((D-R)*(z+W)),Fc=u((D+R)*(z-W)),hi=u(Fc-Vc);if(hi===te)return this.double();let Kc=u(M*mo*st),$c=u($*mo*j),Wc=$c+Kc,qc=Fc+Vc,zc=$c-Kc,qh=u(Wc*hi),zh=u(qc*zc),Gh=u(Wc*zc),jh=u(hi*qc);return new p(qh,zh,jh,Gh)}let it=u(R*W),ut=u(D*z),Ut=u($*v*st),yt=u(M*j),Mt=u((R+D)*(W+z)-it-ut),pe=yt-Ut,tn=yt+Ut,en=u(ut-S*it),Fh=u(Mt*pe),Kh=u(tn*en),$h=u(Mt*en),Wh=u(pe*tn);return new p(Fh,Kh,Wh,$h)}subtract(y){return this.add(y.negate())}wNAF(y){return N.wNAFCached(this,y,p.normalizeZ)}multiply(y){let S=y;It("scalar",S,Ft,n);let{p:v,f:R}=this.wNAF(S);return p.normalizeZ([v,R])[0]}multiplyUnsafe(y){let S=y;return It("scalar",S,te,n),S===te?L:this.equals(L)||S===Ft?this:this.equals(B)?this.wNAF(S).p:N.unsafeLadder(this,S)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return N.unsafeLadder(this,n).is0()}toAffine(y){return w(this,y)}clearCofactor(){let{h:y}=t;return y===Ft?this:this.multiplyUnsafe(y)}static fromHex(y,S=!1){let{d:v,a:R}=t,D=e.BYTES;y=at("pointHex",y,D),Jt("zip215",S);let M=y.slice(),$=y[D-1];M[D-1]=$&-129;let W=Qt(M),z=S?l:e.ORDER;It("pointHex.y",W,te,z);let j=u(W*W),st=u(j-Ft),it=u(v*j-R),{isValid:ut,value:Ut}=d(st,it);if(!ut)throw new Error("Point.fromHex: invalid y coordinate");let yt=(Ut&Ft)===Ft,Mt=($&128)!==0;if(!S&&Ut===te&&Mt)throw new Error("Point.fromHex: x=0 and x_0=1");return Mt!==yt&&(Ut=u(-Ut)),p.fromAffine({x:Ut,y:W})}static fromPrivateKey(y){return I(y).point}toRawBytes(){let{x:y,y:S}=this.toAffine(),v=Ee(S,e.BYTES);return v[v.length-1]|=y&Ft?128:0,v}toHex(){return be(this.toRawBytes())}}p.BASE=new p(t.Gx,t.Gy,Ft,u(t.Gx*t.Gy)),p.ZERO=new p(te,Ft,Ft,te);let{BASE:B,ZERO:L}=p,N=ho(p,a*8);function A(E){return Y(E,n)}function k(E){return A(Qt(E))}function I(E){let y=a;E=at("private key",E,y);let S=at("hashed private key",s(E),2*y),v=m(S.slice(0,y)),R=S.slice(y,2*y),D=k(v),M=B.multiply(D),$=M.toRawBytes();return{head:v,prefix:R,scalar:D,point:M,pointBytes:$}}function V(E){return I(E).pointBytes}function _(E=new Uint8Array,...y){let S=ve(...y);return k(s(x(S,at("context",E),!!o)))}function H(E,y,S={}){E=at("message",E),o&&(E=o(E));let{prefix:v,scalar:R,pointBytes:D}=I(y),M=_(S.context,v,E),$=B.multiply(M).toRawBytes(),W=_(S.context,$,D,E),z=A(M+W*R);It("signature.s",z,te,n);let j=ve($,Ee(z,e.BYTES));return at("result",j,a*2)}let K=Pp;function C(E,y,S,v=K){let{context:R,zip215:D}=v,M=e.BYTES;E=at("signature",E,2*M),y=at("message",y),D!==void 0&&Jt("zip215",D),o&&(y=o(y));let $=Qt(E.slice(M,2*M)),W,z,j;try{W=p.fromHex(S,D),z=p.fromHex(E.slice(0,M),D),j=B.multiplyUnsafe($)}catch{return!1}if(!D&&W.isSmallOrder())return!1;let st=_(R,z.toRawBytes(),W.toRawBytes(),y);return z.add(W.multiplyUnsafe(st)).subtract(j).clearCofactor().equals(p.ZERO)}return B._setWindowSize(8),{CURVE:t,getPublicKey:V,sign:H,verify:C,ExtendedPoint:p,utils:{getExtendedPublicKey:I,randomPrivateKey:()=>i(e.BYTES),precompute(E=8,y=p.BASE){return y._setWindowSize(E),y.multiply(BigInt(3)),y}}}}var _r=BigInt(0),Fi=BigInt(1);function Hp(r){return Gt(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function Bl(r){let t=Hp(r),{P:e}=t,n=b=>Y(b,e),o=t.montgomeryBits,s=Math.ceil(o/8),i=t.nByteLength,a=t.adjustScalarBytes||(b=>b),c=t.powPminus2||(b=>Di(b,e-BigInt(2),e));function l(b,p,B){let L=n(b*(p-B));return p=n(p-L),B=n(B+L),[p,B]}let u=(t.a-BigInt(2))/BigInt(4);function f(b,p){It("u",b,_r,e),It("scalar",p,_r,e);let B=p,L=b,N=Fi,A=_r,k=b,I=Fi,V=_r,_;for(let K=BigInt(o-1);K>=_r;K--){let C=B>>K&Fi;V^=C,_=l(V,N,k),N=_[0],k=_[1],_=l(V,A,I),A=_[0],I=_[1],V=C;let T=N+A,E=n(T*T),y=N-A,S=n(y*y),v=E-S,R=k+I,D=k-I,M=n(D*T),$=n(R*y),W=M+$,z=M-$;k=n(W*W),I=n(L*n(z*z)),N=n(E*S),A=n(v*(E+n(u*v)))}_=l(V,N,k),N=_[0],k=_[1],_=l(V,A,I),A=_[0],I=_[1];let H=c(A);return n(N*H)}function d(b){return Ee(n(b),s)}function m(b){let p=at("u coordinate",b,s);return i===32&&(p[31]&=127),Qt(p)}function x(b){let p=at("scalar",b),B=p.length;if(B!==s&&B!==i)throw new Error(`Expected ${s} or ${i} bytes, got ${B}`);return Qt(a(p))}function g(b,p){let B=m(p),L=x(b),N=f(B,L);if(N===_r)throw new Error("Invalid private or public key received");return d(N)}let h=d(t.Gu);function w(b){return g(b,h)}return{scalarMult:g,scalarMultBase:w,getSharedSecret:(b,p)=>g(b,p),getPublicKey:b=>w(b),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:h}}var dn=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Il=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),dy=BigInt(0),Mp=BigInt(1),Cl=BigInt(2),Vp=BigInt(3),Fp=BigInt(5),Kp=BigInt(8);function kl(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=dn,a=r*r%s*r%s,c=ct(a,Cl,s)*a%s,l=ct(c,Mp,s)*r%s,u=ct(l,Fp,s)*l%s,f=ct(u,t,s)*u%s,d=ct(f,e,s)*f%s,m=ct(d,n,s)*d%s,x=ct(m,o,s)*m%s,g=ct(x,o,s)*m%s,h=ct(g,t,s)*u%s;return{pow_p_5_8:ct(h,Cl,s)*r%s,b2:a}}function Tl(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function $p(r,t){let e=dn,n=Y(t*t*t,e),o=Y(n*n*t,e),s=kl(r*o).pow_p_5_8,i=Y(r*n*s,e),a=Y(t*i*i,e),c=i,l=Y(i*Il,e),u=a===r,f=a===Y(-r,e),d=a===Y(-r*Il,e);return u&&(i=c),(f||d)&&(i=l),xl(i,e)&&(i=Y(-i,e)),{isValid:u||f,value:i}}var Wp=$e(dn,void 0,!0),qp={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Wp,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Kp,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:ml,randomBytes:ln,adjustScalarBytes:Tl,uvRatio:$p},Nl=Al(qp);var pn=Bl({P:dn,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let t=dn,{pow_p_5_8:e,b2:n}=kl(r);return Y(ct(e,Vp,t)*n,t)},adjustScalarBytes:Tl,randomBytes:ln});var go=32;function Ll(r,t,e){return Nl.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}var wo=class{type="Ed25519";raw;constructor(t){this.raw=Ki(t,go)}toMultihash(){return we.digest(Rr(this))}toCID(){return Bt.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Dt(this.raw,t.raw)}verify(t,e){return Ll(this.raw,e,t)}};function $i(r){return r=Ki(r,go),new wo(r)}function Ki(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new et(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}function xt(r=0){return new Uint8Array(r)}function Et(r=0){return new Uint8Array(r)}var Gp=Math.pow(2,7),jp=Math.pow(2,14),Zp=Math.pow(2,21),Wi=Math.pow(2,28),qi=Math.pow(2,35),zi=Math.pow(2,42),Gi=Math.pow(2,49),J=128,Lt=127;function lt(r){if(r<Gp)return 1;if(r<jp)return 2;if(r<Zp)return 3;if(r<Wi)return 4;if(r<qi)return 5;if(r<zi)return 6;if(r<Gi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ji(r,t,e=0){switch(lt(r)){case 8:t[e++]=r&255|J,r/=128;case 7:t[e++]=r&255|J,r/=128;case 6:t[e++]=r&255|J,r/=128;case 5:t[e++]=r&255|J,r/=128;case 4:t[e++]=r&255|J,r>>>=7;case 3:t[e++]=r&255|J,r>>>=7;case 2:t[e++]=r&255|J,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Xp(r,t,e=0){switch(lt(r)){case 8:t.set(e++,r&255|J),r/=128;case 7:t.set(e++,r&255|J),r/=128;case 6:t.set(e++,r&255|J),r/=128;case 5:t.set(e++,r&255|J),r/=128;case 4:t.set(e++,r&255|J),r>>>=7;case 3:t.set(e++,r&255|J),r>>>=7;case 2:t.set(e++,r&255|J),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Zi(r,t){let e=r[t],n=0;if(n+=e&Lt,e<J||(e=r[t+1],n+=(e&Lt)<<7,e<J)||(e=r[t+2],n+=(e&Lt)<<14,e<J)||(e=r[t+3],n+=(e&Lt)<<21,e<J)||(e=r[t+4],n+=(e&Lt)*Wi,e<J)||(e=r[t+5],n+=(e&Lt)*qi,e<J)||(e=r[t+6],n+=(e&Lt)*zi,e<J)||(e=r[t+7],n+=(e&Lt)*Gi,e<J))return n;throw new RangeError("Could not decode varint")}function Yp(r,t){let e=r.get(t),n=0;if(n+=e&Lt,e<J||(e=r.get(t+1),n+=(e&Lt)<<7,e<J)||(e=r.get(t+2),n+=(e&Lt)<<14,e<J)||(e=r.get(t+3),n+=(e&Lt)<<21,e<J)||(e=r.get(t+4),n+=(e&Lt)*Wi,e<J)||(e=r.get(t+5),n+=(e&Lt)*qi,e<J)||(e=r.get(t+6),n+=(e&Lt)*zi,e<J)||(e=r.get(t+7),n+=(e&Lt)*Gi,e<J))return n;throw new RangeError("Could not decode varint")}function ce(r,t,e=0){return t==null&&(t=Et(lt(r))),t instanceof Uint8Array?ji(r,t,e):Xp(r,t,e)}function ee(r,t=0){return r instanceof Uint8Array?Zi(r,t):Yp(r,t)}var Xi=new Float32Array([-0]),We=new Uint8Array(Xi.buffer);function Rl(r,t,e){Xi[0]=r,t[e]=We[0],t[e+1]=We[1],t[e+2]=We[2],t[e+3]=We[3]}function Ul(r,t){return We[0]=r[t],We[1]=r[t+1],We[2]=r[t+2],We[3]=r[t+3],Xi[0]}var Yi=new Float64Array([-0]),_t=new Uint8Array(Yi.buffer);function Dl(r,t,e){Yi[0]=r,t[e]=_t[0],t[e+1]=_t[1],t[e+2]=_t[2],t[e+3]=_t[3],t[e+4]=_t[4],t[e+5]=_t[5],t[e+6]=_t[6],t[e+7]=_t[7]}function Pl(r,t){return _t[0]=r[t],_t[1]=r[t+1],_t[2]=r[t+2],_t[3]=r[t+3],_t[4]=r[t+4],_t[5]=r[t+5],_t[6]=r[t+6],_t[7]=r[t+7],Yi[0]}var Jp=BigInt(Number.MAX_SAFE_INTEGER),Qp=BigInt(Number.MIN_SAFE_INTEGER),qt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return cr;if(t<Jp&&t>Qp)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>Ol&&(o=0n,++n>Ol&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return cr;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):cr}},cr=new qt(0,0);cr.toBigInt=function(){return 0n};cr.zzEncode=cr.zzDecode=function(){return this};cr.length=function(){return 1};var Ol=4294967296n;function Hl(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Ml(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Ji(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function re(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function yo(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Qi=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,re(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw re(this,4);return yo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw re(this,4);return yo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw re(this,4);let t=Ul(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw re(this,4);let t=Pl(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw re(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Ml(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw re(this,t);this.pos+=t}else do if(this.pos>=this.len)throw re(this);while(this.buf[this.pos++]&128);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new qt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw re(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw re(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw re(this,8);let t=yo(this.buf,this.pos+=4),e=yo(this.buf,this.pos+=4);return new qt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Zi(this.buf,this.pos);return this.pos+=lt(t),t}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 ta(r){return new Qi(r instanceof Uint8Array?r:r.subarray())}function ne(r,t,e){let n=ta(r);return t.decode(n,void 0,e)}var ea={};Nt(ea,{base10:()=>tm});var tm=Pe({prefix:"9",name:"base10",alphabet:"0123456789"});var ra={};Nt(ra,{base16:()=>em,base16upper:()=>rm});var em=pt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),rm=pt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var na={};Nt(na,{base2:()=>nm});var nm=pt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var oa={};Nt(oa,{base256emoji:()=>cm});var Fl=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),om=Fl.reduce((r,t,e)=>(r[e]=t,r),[]),sm=Fl.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function im(r){return r.reduce((t,e)=>(t+=om[e],t),"")}function am(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=sm[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var cm=Ar({prefix:"\u{1F680}",name:"base256emoji",encode:im,decode:am});var ia={};Nt(ia,{base64:()=>lm,base64pad:()=>um,base64url:()=>sa,base64urlpad:()=>fm});var lm=pt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),um=pt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),sa=pt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),fm=pt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var aa={};Nt(aa,{base8:()=>hm});var hm=pt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ca={};Nt(ca,{identity:()=>dm});var dm=Ar({prefix:"\0",name:"identity",encode:r=>Jc(r),decode:r=>Yc(r)});var Zy=new TextEncoder,Xy=new TextDecoder;var fa={};Nt(fa,{sha256:()=>gn,sha512:()=>gm});function ua({name:r,code:t,encode:e}){return new la(r,t,e)}var la=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?Vt(this.code,e):e.then(n=>Vt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function $l(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var gn=ua({name:"sha2-256",code:18,encode:$l("SHA-256")}),gm=ua({name:"sha2-512",code:19,encode:$l("SHA-512")});var lr={...ca,...na,...aa,...ea,...ra,...bi,...xi,...yi,...ia,...oa},cb={...fa,...Ai};function ql(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Wl=ql("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ha=ql("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=Et(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),wm={utf8:Wl,"utf-8":Wl,hex:lr.base16,latin1:ha,ascii:ha,binary:ha,...lr},bo=wm;function rt(r,t="utf8"){let e=bo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function da(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return Et(i);o+i>t&&(n=Et(t),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var ur=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function pa(){}var ga=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},ym=da();function bm(r){return globalThis.Buffer!=null?Et(r):ym(r)}var yn=class{len;head;tail;states;constructor(){this.len=0,this.head=new ur(pa,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new ur(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new wa((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(xo,10,qt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=qt.fromBigInt(t);return this._push(xo,e.length(),e)}uint64Number(t){return this._push(ji,lt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=qt.fromBigInt(t).zzEncode();return this._push(xo,e.length(),e)}sint64Number(t){let e=qt.fromNumber(t).zzEncode();return this._push(xo,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ma,1,t?1:0)}fixed32(t){return this._push(wn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=qt.fromBigInt(t);return this._push(wn,4,e.lo)._push(wn,4,e.hi)}fixed64Number(t){let e=qt.fromNumber(t);return this._push(wn,4,e.lo)._push(wn,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Rl,4,t)}double(t){return this._push(Dl,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ma,1,0):this.uint32(e)._push(Em,e,t)}string(t){let e=Hl(t);return e!==0?this.uint32(e)._push(Ji,e,t):this._push(ma,1,0)}fork(){return this.states=new ga(this),this.head=this.tail=new ur(pa,0,0),this.len=0,this}reset(){return this.states!=null?(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 ur(pa,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=bm(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ma(r,t,e){t[e]=r&255}function xm(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var wa=class extends ur{next;constructor(t,e){super(xm,t,e),this.next=void 0}};function xo(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function wn(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Em(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(yn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(vm,t,r),this},yn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Sm,t,r),this});function vm(r,t,e){t.set(r,e)}function Sm(r,t,e){r.length<40?Ji(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(rt(r),e)}function ya(){return new yn}function oe(r,t){let e=ya();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Ur;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Ur||(Ur={}));function Eo(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function fr(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return Eo("enum",Ur.VARINT,e,n)}function se(r,t){return Eo("message",Ur.LENGTH_DELIMITED,r,t)}var vt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(vt||(vt={}));var ba;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(ba||(ba={}));(function(r){r.codec=()=>fr(ba)})(vt||(vt={}));var le;(function(r){let t;r.codec=()=>(t==null&&(t=se((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),vt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=vt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>oe(e,r.codec()),r.decode=(e,n)=>ne(e,r.codec(),n)})(le||(le={}));var xa;(function(r){let t;r.codec=()=>(t==null&&(t=se((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),vt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=vt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>oe(e,r.codec()),r.decode=(e,n)=>ne(e,r.codec(),n)})(xa||(xa={}));var kn={};Nt(kn,{MAX_RSA_KEY_SIZE:()=>hs,generateRSAKeyPair:()=>Ku,jwkToJWKKeyPair:()=>$u,jwkToPkcs1:()=>Mm,jwkToPkix:()=>Ta,jwkToRSAPrivateKey:()=>Fu,pkcs1ToJwk:()=>Hu,pkcs1ToRSAPrivateKey:()=>Vu,pkixToJwk:()=>Mu,pkixToRSAPublicKey:()=>Na});var Am=new Uint32Array([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]),qe=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ze=new Uint32Array(64),Ea=class extends Nr{constructor(){super(64,32,8,!1),this.A=qe[0]|0,this.B=qe[1]|0,this.C=qe[2]|0,this.D=qe[3]|0,this.E=qe[4]|0,this.F=qe[5]|0,this.G=qe[6]|0,this.H=qe[7]|0}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)ze[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=ze[f-15],m=ze[f-2],x=Yt(d,7)^Yt(d,18)^d>>>3,g=Yt(m,17)^Yt(m,19)^m>>>10;ze[f]=g+ze[f-7]+x+ze[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=Yt(a,6)^Yt(a,11)^Yt(a,25),m=u+d+hl(a,c,l)+Am[f]+ze[f]|0,g=(Yt(n,2)^Yt(n,13)^Yt(n,22))+dl(n,o,s)|0;u=l,l=c,c=a,a=i+m|0,i=s,s=o,o=n,n=m+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){ze.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ue=ao(()=>new Ea);var G=ed(Gl());function hr(r,t){let e=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)e+=r[r.length-1-n]*Math.pow(2,t*n);return e}function Ge(r,t,e=-1){let n=e,o=r,s=0,i=Math.pow(2,t);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let f=Math.pow(2,u*t);l[s-u-1]=Math.floor(o/f),o-=l[s-u-1]*f}return c}i*=Math.pow(2,t)}return new ArrayBuffer(0)}function Ao(...r){let t=0,e=0;for(let s of r)t+=s.length;let n=new ArrayBuffer(t),o=new Uint8Array(n);for(let s of r)o.set(s,e),e+=s.length;return o}function Sa(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let t=new ArrayBuffer(this.valueHex.byteLength),e=new Uint8Array(t);for(let a=0;a<this.valueHex.byteLength;a++)e[a]=0;e[0]=r[0]&128;let n=hr(e,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,hr(s,8)-n}function jl(r){let t=r<0?r*-1:r,e=128;for(let n=1;n<8;n++){if(t<=e){if(r<0){let i=e-t,a=Ge(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Ge(t,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}e*=Math.pow(2,8)}return new ArrayBuffer(0)}function Zl(r,t){if(r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<e.length;o++)if(e[o]!==n[o])return!1;return!0}function Kt(r,t){let e=r.toString(10);if(t<e.length)return"";let n=t-e.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(e)}var $b=Math.log(2);function Bo(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Aa(r){let t=0,e=0;for(let o=0;o<r.length;o++){let s=r[o];t+=s.byteLength}let n=new Uint8Array(t);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),e),e+=s.byteLength}return n.buffer}function Ce(r,t,e,n){return t instanceof Uint8Array?t.byteLength?e<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):t.byteLength-e-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var xn=class{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return Aa(this.items)}},bn=[new Uint8Array([1])],Xl="0123456789";var Mr="",ie=new ArrayBuffer(0),Ba=new Uint8Array(0),En="EndOfContent",Jl="OCTET STRING",Ql="BIT STRING";function ke(r){var t;return t=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?G.BufferSourceConverter.toUint8Array(s.valueHex):Ba}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Ce(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?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",ie)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:G.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var Ae=class{constructor({blockLength:t=0,error:e=Mr,warnings:n=[],valueBeforeDecode:o=Ba}={}){this.blockLength=t,this.error=e,this.warnings=n,this.valueBeforeDecodeView=G.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(t){this.valueBeforeDecodeView=new Uint8Array(t)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:G.Convert.ToHex(this.valueBeforeDecodeView)}}};Ae.NAME="baseBlock";var Rt=class extends Ae{fromBER(t,e,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(t,e){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Rt.NAME="valueBlock";var Io=class extends ke(Ae){constructor({idBlock:t={}}={}){var e,n,o,s;super(),t?(this.isHexOnly=(e=t.isHexOnly)!==null&&e!==void 0?e:!1,this.valueHexView=t.valueHex?G.BufferSourceConverter.toUint8Array(t.valueHex):Ba,this.tagClass=(n=t.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=t.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=t.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(t=!1){let e=0;switch(this.tagClass){case 1:e|=0;break;case 2:e|=64;break;case 3:e|=128;break;case 4:e|=192;break;default:return this.error="Unknown tag class",ie}if(this.isConstructed&&(e|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!t){let s=this.tagNumber;s&=31,e|=s,o[0]=e}return o.buffer}if(!this.isHexOnly){let o=Ge(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=e|31,!t){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=e|31,!t){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(t,e,n){let o=G.BufferSourceConverter.toUint8Array(t);if(!Ce(this,o,e,n))return-1;let s=o.subarray(e,e+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){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=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,l=this.valueHexView=new Uint8Array(255),u=255;for(;s[c]&128;){if(l[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===u){u+=255;let d=new Uint8Array(u);for(let m=0;m<l.length;m++)d[m]=l[m];l=this.valueHexView=new Uint8Array(u)}}this.blockLength=c+1,l[c-1]=s[c]&127;let f=new Uint8Array(c);for(let d=0;d<c;d++)f[d]=l[d];l=this.valueHexView=new Uint8Array(c),l.set(f),this.blockLength<=9?this.tagNumber=hr(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&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 e+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};Io.NAME="identificationBlock";var Co=class extends Ae{constructor({lenBlock:t={}}={}){var e,n,o;super(),this.isIndefiniteForm=(e=t.isIndefiniteForm)!==null&&e!==void 0?e:!1,this.longFormUsed=(n=t.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=t.length)!==null&&o!==void 0?o:0}fromBER(t,e,n){let o=G.BufferSourceConverter.toUint8Array(t);if(!Ce(this,o,e,n))return-1;let s=o.subarray(e,e+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,e+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,e+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=e+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=hr(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,e+this.blockLength}toBER(t=!1){let e,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=128),e;if(this.longFormUsed){let o=Ge(this.length,8);if(o.byteLength>127)return this.error="Too big length",ie;if(e=new ArrayBuffer(o.byteLength+1),t)return e;let s=new Uint8Array(o);n=new Uint8Array(e),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return e}return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=this.length),e}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Co.NAME="lengthBlock";var P={},Ct=class extends Ae{constructor({name:t=Mr,optional:e=!1,primitiveSchema:n,...o}={},s){super(o),this.name=t,this.optional=e,n&&(this.primitiveSchema=n),this.idBlock=new Io(o),this.lenBlock=new Co(o),this.valueBlock=s?new s(o):new Rt(o)}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(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),o)}toBER(t,e){let n=e||new xn;e||tu(this);let o=this.idBlock.toBER(t);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(t,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(t);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(t);n.write(i),n.write(s)}return e?ie:n.final()}toJSON(){let t={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(t="ascii"){return t==="ascii"?this.onAsciiEncoding():G.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${G.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(t){if(this===t)return!0;if(!(t instanceof this.constructor))return!1;let e=this.toBER(),n=t.toBER();return Zl(e,n)}};Ct.NAME="BaseBlock";function tu(r){if(r instanceof P.Constructed)for(let t of r.valueBlock.value)tu(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ko=class extends Ct{constructor({value:t=Mr,...e}={},n){super(e,n),t&&this.fromString(t)}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(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),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};ko.NAME="BaseStringBlock";var To=class extends ke(Rt){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};To.NAME="PrimitiveValueBlock";var eu,No=class extends Ct{constructor(t={}){super(t,To),this.idBlock.isConstructed=!1}};eu=No;P.Primitive=eu;No.NAME="PRIMITIVE";function Rm(r,t){if(r instanceof t)return r;let e=new t;return e.idBlock=r.idBlock,e.lenBlock=r.lenBlock,e.warnings=r.warnings,e.valueBeforeDecodeView=r.valueBeforeDecodeView,e}function us(r,t=0,e=r.length){let n=t,o=new Ct({},Rt),s=new Ae;if(!Ce(s,r,t,e))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(t,t+e).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,t,e);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(t=a,e-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,t,e),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(t=a,e-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Ct;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=P.EndOfContent;break;case 1:c=P.Boolean;break;case 2:c=P.Integer;break;case 3:c=P.BitString;break;case 4:c=P.OctetString;break;case 5:c=P.Null;break;case 6:c=P.ObjectIdentifier;break;case 10:c=P.Enumerated;break;case 12:c=P.Utf8String;break;case 13:c=P.RelativeObjectIdentifier;break;case 14:c=P.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=P.Sequence;break;case 17:c=P.Set;break;case 18:c=P.NumericString;break;case 19:c=P.PrintableString;break;case 20:c=P.TeletexString;break;case 21:c=P.VideotexString;break;case 22:c=P.IA5String;break;case 23:c=P.UTCTime;break;case 24:c=P.GeneralizedTime;break;case 25:c=P.GraphicString;break;case 26:c=P.VisibleString;break;case 27:c=P.GeneralString;break;case 28:c=P.UniversalString;break;case 29:c=P.CharacterString;break;case 30:c=P.BmpString;break;case 31:c=P.DATE;break;case 32:c=P.TimeOfDay;break;case 33:c=P.DateTime;break;case 34:c=P.Duration;break;default:{let l=o.idBlock.isConstructed?new P.Constructed:new P.Primitive;l.idBlock=o.idBlock,l.lenBlock=o.lenBlock,l.warnings=o.warnings,o=l}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?P.Constructed:P.Primitive}return o=Rm(o,c),a=o.fromBER(r,t,o.lenBlock.isIndefiniteForm?e:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function Ia(r){if(!r.byteLength){let t=new Ct({},Rt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return us(G.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function Um(r,t){return r?1:t}var fe=class extends Rt{constructor({value:t=[],isIndefiniteForm:e=!1,...n}={}){super(n),this.value=t,this.isIndefiniteForm=e}fromBER(t,e,n){let o=G.BufferSourceConverter.toUint8Array(t);if(!Ce(this,o,e,n))return-1;if(this.valueBeforeDecodeView=o.subarray(e,e+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),e;let s=e;for(;Um(this.isIndefiniteForm,n)>0;){let i=us(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===En)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===En?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(t,e){let n=e||new xn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(t,n);return e?ie:n.final()}toJSON(){let t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let e of this.value)t.value.push(e.toJSON());return t}};fe.NAME="ConstructedValueBlock";var ru,je=class extends Ct{constructor(t={}){super(t,fe),this.idBlock.isConstructed=!0}fromBER(t,e,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(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),o)}onAsciiEncoding(){let t=[];for(let n of this.valueBlock.value)t.push(n.toString("ascii").split(`
2
+ "use strict";var Libp2PWebrtc=(()=>{var Zh=Object.create;var Zn=Object.defineProperty;var Xh=Object.getOwnPropertyDescriptor;var Yh=Object.getOwnPropertyNames;var Jh=Object.getPrototypeOf,Qh=Object.prototype.hasOwnProperty;var td=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Nt=(r,t)=>{for(var e in t)Zn(r,e,{get:t[e],enumerable:!0})},Gc=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Yh(t))!Qh.call(r,o)&&o!==e&&Zn(r,o,{get:()=>t[o],enumerable:!(n=Xh(t,o))||n.enumerable});return r};var ed=(r,t,e)=>(e=r!=null?Zh(Jh(r)):{},Gc(t||!r||!r.__esModule?Zn(e,"default",{value:r,enumerable:!0}):e,r)),rd=r=>Gc(Zn({},"__esModule",{value:!0}),r);var Gl=td(Pr=>{"use strict";var Bm="[object ArrayBuffer]",Se=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===Bm}static toArrayBuffer(t){return this.isArrayBuffer(t)?t:t.byteLength===t.buffer.byteLength||t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:this.toUint8Array(t.buffer).slice(t.byteOffset,t.byteOffset+t.byteLength).buffer}static toUint8Array(t){return this.toView(t,Uint8Array)}static toView(t,e){if(t.constructor===e)return t;if(this.isArrayBuffer(t))return new e(t);if(this.isArrayBufferView(t))return new e(t.buffer,t.byteOffset,t.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(t){return this.isArrayBufferView(t)||this.isArrayBuffer(t)}static isArrayBufferView(t){return ArrayBuffer.isView(t)||t&&this.isArrayBuffer(t.buffer)}static isEqual(t,e){let n=r.toUint8Array(t),o=r.toUint8Array(e);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...t){let e;Array.isArray(t[0])&&!(t[1]instanceof Function)||Array.isArray(t[0])&&t[1]instanceof Function?e=t[0]:t[t.length-1]instanceof Function?e=t.slice(0,t.length-1):e=t;let n=0;for(let i of e)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of e){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return t[t.length-1]instanceof Function?this.toView(o,t[t.length-1]):o.buffer}},va="string",Im=/^[0-9a-f]+$/i,Cm=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,km=/^[a-zA-Z0-9-_]+$/,vo=class{static fromString(t){let e=unescape(encodeURIComponent(t)),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n.buffer}static toString(t){let e=Se.toUint8Array(t),n="";for(let s=0;s<e.length;s++)n+=String.fromCharCode(e[s]);return decodeURIComponent(escape(n))}},jt=class{static toString(t,e=!1){let n=Se.toArrayBuffer(t),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,e);s+=String.fromCharCode(a)}return s}static fromString(t,e=!1){let n=new ArrayBuffer(t.length*2),o=new DataView(n);for(let s=0;s<t.length;s++)o.setUint16(s*2,t.charCodeAt(s),e);return n}},So=class r{static isHex(t){return typeof t===va&&Im.test(t)}static isBase64(t){return typeof t===va&&Cm.test(t)}static isBase64Url(t){return typeof t===va&&km.test(t)}static ToString(t,e="utf8"){let n=Se.toUint8Array(t);switch(e.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 jt.toString(n,!0);case"utf16":case"utf16be":return jt.toString(n);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromString(t,e="utf8"){if(!t)return new ArrayBuffer(0);switch(e.toLowerCase()){case"utf8":return this.FromUtf8String(t);case"binary":return this.FromBinary(t);case"hex":return this.FromHex(t);case"base64":return this.FromBase64(t);case"base64url":return this.FromBase64Url(t);case"utf16le":return jt.fromString(t,!0);case"utf16":case"utf16be":return jt.fromString(t);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToBase64(t){let e=Se.toUint8Array(t);if(typeof btoa<"u"){let n=this.ToString(e,"binary");return btoa(n)}else return Buffer.from(e).toString("base64")}static FromBase64(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64(e))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(e)):new Uint8Array(Buffer.from(e,"base64")).buffer}static FromBase64Url(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64Url(e))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(e.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(t){return this.ToBase64(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.FromBinary(t);case"utf8":return vo.fromString(t);case"utf16":case"utf16be":return jt.fromString(t);case"utf16le":case"usc2":return jt.fromString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.ToBinary(t);case"utf8":return vo.toString(t);case"utf16":case"utf16be":return jt.toString(t);case"utf16le":case"usc2":return jt.toString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromBinary(t){let e=t.length,n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);return n.buffer}static ToBinary(t){let e=Se.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=Se.toUint8Array(t),n="",o=e.length;for(let s=0;s<o;s++){let i=e[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isHex(e))throw new TypeError("Argument 'hexString' is not HEX encoded");e.length%2&&(e=`0${e}`);let n=new Uint8Array(e.length/2);for(let o=0;o<e.length;o=o+2){let s=e.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(t,e=!1){return jt.toString(t,e)}static FromUtf16String(t,e=!1){return jt.fromString(t,e)}static Base64Padding(t){let e=4-t.length%4;if(e<4)for(let n=0;n<e;n++)t+="=";return t}static formatString(t){return t?.replace(/[\n\r\t ]/g,"")||""}};So.DEFAULT_UTF8_ENCODING="utf8";function Tm(r,...t){let e=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)e[s]=o[s]}return e}function Nm(...r){let t=r.map(o=>o.byteLength).reduce((o,s)=>o+s),e=new Uint8Array(t),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)e[n++]=s}),e.buffer}function _m(r,t){if(!(r&&t)||r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)if(e[o]!==n[o])return!1;return!0}Pr.BufferSourceConverter=Se;Pr.Convert=So;Pr.assign=Tm;Pr.combine=Nm;Pr.isEqual=_m});var Vg={};Nt(Vg,{webRTC:()=>Mg,webRTCDirect:()=>Hg});var di=Symbol.for("@libp2p/peer-id");var Xn=Symbol.for("@libp2p/transport");var jc;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(jc||(jc={}));var Yn=class extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}};var et=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Sr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Jn=class extends Error{static name="ConnectionFailedError";constructor(t="Connection failed"){super(t),this.name="ConnectionFailedError"}};var Qn=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}},tr=class extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}};var to=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var eo=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var rn=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}};var er=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var ro=(r,...t)=>{try{[...t]}catch{}};var no=class extends EventTarget{#t=new Map;constructor(){super(),ro(1/0,this)}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};var Ar=Symbol.for("@libp2p/service-capabilities"),Zc=Symbol.for("@libp2p/service-dependencies");var yi={};Nt(yi,{base58btc:()=>ot,base58flickr:()=>cd});var ww=new Uint8Array(0);function Xc(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function me(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Yc(r){return new TextEncoder().encode(r)}function Jc(r){return new TextDecoder().decode(r)}function nd(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(x){if(x instanceof Uint8Array||(ArrayBuffer.isView(x)?x=new Uint8Array(x.buffer,x.byteOffset,x.byteLength):Array.isArray(x)&&(x=Uint8Array.from(x))),!(x instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(x.length===0)return"";for(var g=0,h=0,w=0,b=x.length;w!==b&&x[w]===0;)w++,g++;for(var p=(b-w)*u+1>>>0,B=new Uint8Array(p);w!==b;){for(var _=x[w],N=0,A=p-1;(_!==0||N<h)&&A!==-1;A--,N++)_+=256*B[A]>>>0,B[A]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");h=N,w++}for(var k=p-h;k!==p&&B[k]===0;)k++;for(var I=c.repeat(g);k<p;++k)I+=r.charAt(B[k]);return I}function d(x){if(typeof x!="string")throw new TypeError("Expected String");if(x.length===0)return new Uint8Array;var g=0;if(x[g]!==" "){for(var h=0,w=0;x[g]===c;)h++,g++;for(var b=(x.length-g)*l+1>>>0,p=new Uint8Array(b);x[g];){var B=e[x.charCodeAt(g)];if(B===255)return;for(var _=0,N=b-1;(B!==0||_<w)&&N!==-1;N--,_++)B+=a*p[N]>>>0,p[N]=B%256>>>0,B=B/256>>>0;if(B!==0)throw new Error("Non-zero carry");w=_,g++}if(x[g]!==" "){for(var A=b-w;A!==b&&p[A]===0;)A++;for(var k=new Uint8Array(h+(b-A)),I=h;A!==b;)k[I++]=p[A++];return k}}}function m(x){var g=d(x);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:m}}var od=nd,sd=od,tl=sd;var pi=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},mi=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return el(this,t)}},gi=class{decoders;constructor(t){this.decoders=t}or(t){return el(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function el(r,t){return new gi({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var wi=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new pi(t,e,n),this.decoder=new mi(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Br({name:r,prefix:t,encode:e,decode:n}){return new wi(r,t,e,n)}function Pe({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=tl(e,r);return Br({prefix:t,name:r,encode:n,decode:s=>me(o(s))})}function id(r,t,e,n){let o={};for(let u=0;u<t.length;++u)o[t[u]]=u;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*e/8|0),a=0,c=0,l=0;for(let u=0;u<s;++u){let f=o[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|f,a+=e,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function ad(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;s.length*e&7;)s+="=";return s}function mt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Br({prefix:t,name:r,encode(o){return ad(o,n,e)},decode(o){return id(o,n,e,r)}})}var ot=Pe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),cd=Pe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var bi={};Nt(bi,{base32:()=>ge,base32hex:()=>hd,base32hexpad:()=>pd,base32hexpadupper:()=>md,base32hexupper:()=>dd,base32pad:()=>ud,base32padupper:()=>fd,base32upper:()=>ld,base32z:()=>gd});var ge=mt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ld=mt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ud=mt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),fd=mt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),hd=mt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),dd=mt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),pd=mt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),md=mt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),gd=mt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var xi={};Nt(xi,{base36:()=>nn,base36upper:()=>wd});var nn=Pe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),wd=Pe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Xt={};Nt(Xt,{Digest:()=>rr,create:()=>Vt,decode:()=>Oe,equals:()=>vi,hasCode:()=>Pd});var yd=ol,rl=128,bd=127,xd=~bd,Ed=Math.pow(2,31);function ol(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Ed;)t[e++]=r&255|rl,r/=128;for(;r&xd;)t[e++]=r&255|rl,r>>>=7;return t[e]=r|0,ol.bytes=e-n+1,t}var vd=Ei,Sd=128,nl=127;function Ei(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ei.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&nl)<<o:(i&nl)*Math.pow(2,o),o+=7}while(i>=Sd);return Ei.bytes=s-n,e}var Ad=Math.pow(2,7),Bd=Math.pow(2,14),Id=Math.pow(2,21),Cd=Math.pow(2,28),kd=Math.pow(2,35),Td=Math.pow(2,42),Nd=Math.pow(2,49),_d=Math.pow(2,56),Ld=Math.pow(2,63),Rd=function(r){return r<Ad?1:r<Bd?2:r<Id?3:r<Cd?4:r<kd?5:r<Td?6:r<Nd?7:r<_d?8:r<Ld?9:10},Ud={encode:yd,decode:vd,encodingLength:Rd},Dd=Ud,on=Dd;function sn(r,t=0){return[on.decode(r,t),on.decode.bytes]}function Ir(r,t,e=0){return on.encode(r,t,e),t}function Cr(r){return on.encodingLength(r)}function Vt(r,t){let e=t.byteLength,n=Cr(r),o=n+Cr(e),s=new Uint8Array(o+e);return Ir(r,s,0),Ir(e,s,n),s.set(t,o),new rr(r,e,t,s)}function Oe(r){let t=me(r),[e,n]=sn(t),[o,s]=sn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new rr(e,o,i,t)}function vi(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Xc(r.bytes,e.bytes)}}var rr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Pd(r,t){return r.code===t}function sl(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Hd(e,Si(r),t??ot.encoder);default:return Md(e,Si(r),t??ge.encoder)}}var il=new WeakMap;function Si(r){let t=il.get(r);if(t==null){let e=new Map;return il.set(r,e),e}return t}var Bt=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}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:{let{code:t,multihash:e}=this;if(t!==an)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Vd)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Vt(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&vi(t.multihash,n.multihash)}toString(t){return sl(this,t)}toJSON(){return{"/":sl(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??al(n,o,s.bytes))}else if(e[Fd]===!0){let{version:n,multihash:o,code:s}=e,i=Oe(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==an)throw new Error(`Version 0 CID must use dag-pb (code: ${an}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=al(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,an,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=me(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new rr(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,d]=sn(t.subarray(e));return e+=d,f},o=n(),s=an;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=Od(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Si(s).set(n,t),s}};function Od(r,t){switch(r[0]){case"Q":{let e=t??ot;return[ot.prefix,e.decode(`${ot.prefix}${r}`)]}case ot.prefix:{let e=t??ot;return[ot.prefix,e.decode(r)]}case ge.prefix:{let e=t??ge;return[ge.prefix,e.decode(r)]}case nn.prefix:{let e=t??nn;return[nn.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Hd(r,t,e){let{prefix:n}=e;if(n!==ot.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Md(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var an=112,Vd=18;function al(r,t,e){let n=Cr(r),o=n+Cr(t),s=new Uint8Array(o+e.byteLength);return Ir(r,s,0),Ir(t,s,n),s.set(e,o),s}var Fd=Symbol.for("@ipld/js-cid/CID");var Ai={};Nt(Ai,{identity:()=>we});var cl=0,Kd="identity",ll=me;function $d(r){return Vt(cl,ll(r))}var we={code:cl,name:Kd,encode:ll,digest:$d};function Pt(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function so(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Wd(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function kr(r,...t){if(!Wd(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function cn(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");so(r.outputLen),so(r.blockLen)}function Tr(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function ul(r,t){kr(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var nr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var io=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Yt=(r,t)=>r<<32-t|r>>>t;var Vw=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function fl(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function He(r){return typeof r=="string"&&(r=fl(r)),kr(r),r}function Bi(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];kr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}var Nr=class{clone(){return this._cloneInto()}},Fw={}.toString;function ao(r){let t=n=>r().update(He(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function ln(r=32){if(nr&&typeof nr.getRandomValues=="function")return nr.getRandomValues(new Uint8Array(r));if(nr&&typeof nr.randomBytes=="function")return nr.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function qd(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}var hl=(r,t,e)=>r&t^~r&e,dl=(r,t,e)=>r&t^r&e^t&e,_r=class extends Nr{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=io(this.buffer)}update(t){Tr(this);let{view:e,buffer:n,blockLen:o}=this;t=He(t);let s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=io(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Tr(this),ul(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;qd(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=io(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.length=o,t.pos=a,t.finished=s,t.destroyed=i,o%e&&t.buffer.set(n),t}};var co=BigInt(4294967295),Ii=BigInt(32);function pl(r,t=!1){return t?{h:Number(r&co),l:Number(r>>Ii&co)}:{h:Number(r>>Ii&co)|0,l:Number(r&co)|0}}function zd(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=pl(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var Gd=(r,t)=>BigInt(r>>>0)<<Ii|BigInt(t>>>0),jd=(r,t,e)=>r>>>e,Zd=(r,t,e)=>r<<32-e|t>>>e,Xd=(r,t,e)=>r>>>e|t<<32-e,Yd=(r,t,e)=>r<<32-e|t>>>e,Jd=(r,t,e)=>r<<64-e|t>>>e-32,Qd=(r,t,e)=>r>>>e-32|t<<64-e,tp=(r,t)=>t,ep=(r,t)=>r,rp=(r,t,e)=>r<<e|t>>>32-e,np=(r,t,e)=>t<<e|r>>>32-e,op=(r,t,e)=>t<<e-32|r>>>64-e,sp=(r,t,e)=>r<<e-32|t>>>64-e;function ip(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var ap=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),cp=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,lp=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),up=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,fp=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),hp=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var dp={fromBig:pl,split:zd,toBig:Gd,shrSH:jd,shrSL:Zd,rotrSH:Xd,rotrSL:Yd,rotrBH:Jd,rotrBL:Qd,rotr32H:tp,rotr32L:ep,rotlSH:rp,rotlSL:np,rotlBH:op,rotlBL:sp,add:ip,add3L:ap,add3H:cp,add4L:lp,add4H:up,add5H:hp,add5L:fp},q=dp;var[pp,mp]=q.split(["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(r=>BigInt(r))),Me=new Uint32Array(80),Ve=new Uint32Array(80),Ci=class extends _r{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:m,Gl:x,Hh:g,Hl:h}=this;return[t,e,n,o,s,i,a,c,l,u,f,d,m,x,g,h]}set(t,e,n,o,s,i,a,c,l,u,f,d,m,x,g,h){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=m|0,this.Gl=x|0,this.Hh=g|0,this.Hl=h|0}process(t,e){for(let p=0;p<16;p++,e+=4)Me[p]=t.getUint32(e),Ve[p]=t.getUint32(e+=4);for(let p=16;p<80;p++){let B=Me[p-15]|0,_=Ve[p-15]|0,N=q.rotrSH(B,_,1)^q.rotrSH(B,_,8)^q.shrSH(B,_,7),A=q.rotrSL(B,_,1)^q.rotrSL(B,_,8)^q.shrSL(B,_,7),k=Me[p-2]|0,I=Ve[p-2]|0,V=q.rotrSH(k,I,19)^q.rotrBH(k,I,61)^q.shrSH(k,I,6),L=q.rotrSL(k,I,19)^q.rotrBL(k,I,61)^q.shrSL(k,I,6),H=q.add4L(A,L,Ve[p-7],Ve[p-16]),K=q.add4H(H,N,V,Me[p-7],Me[p-16]);Me[p]=K|0,Ve[p]=H|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:m,Fl:x,Gh:g,Gl:h,Hh:w,Hl:b}=this;for(let p=0;p<80;p++){let B=q.rotrSH(f,d,14)^q.rotrSH(f,d,18)^q.rotrBH(f,d,41),_=q.rotrSL(f,d,14)^q.rotrSL(f,d,18)^q.rotrBL(f,d,41),N=f&m^~f&g,A=d&x^~d&h,k=q.add5L(b,_,A,mp[p],Ve[p]),I=q.add5H(k,w,B,N,pp[p],Me[p]),V=k|0,L=q.rotrSH(n,o,28)^q.rotrBH(n,o,34)^q.rotrBH(n,o,39),H=q.rotrSL(n,o,28)^q.rotrBL(n,o,34)^q.rotrBL(n,o,39),K=n&s^n&a^s&a,C=o&i^o&c^i&c;w=g|0,b=h|0,g=m|0,h=x|0,m=f|0,x=d|0,{h:f,l:d}=q.add(l|0,u|0,I|0,V|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let T=q.add3L(V,H,C);n=q.add3H(T,I,L,K),o=T|0}({h:n,l:o}=q.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=q.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=q.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=q.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=q.add(this.Eh|0,this.El|0,f|0,d|0),{h:m,l:x}=q.add(this.Fh|0,this.Fl|0,m|0,x|0),{h:g,l:h}=q.add(this.Gh|0,this.Gl|0,g|0,h|0),{h:w,l:b}=q.add(this.Hh|0,this.Hl|0,w|0,b|0),this.set(n,o,s,i,a,c,l,u,f,d,m,x,g,h,w,b)}roundClean(){Me.fill(0),Ve.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var ml=ao(()=>new Ci);var uo={};Nt(uo,{aInRange:()=>It,abool:()=>Jt,abytes:()=>Lr,bitGet:()=>Ep,bitLen:()=>Li,bitMask:()=>fn,bitSet:()=>vp,bytesToHex:()=>be,bytesToNumberBE:()=>xe,bytesToNumberLE:()=>Qt,concatBytes:()=>ve,createHmacDrbg:()=>Ri,ensureBytes:()=>at,equalBytes:()=>bp,hexToBytes:()=>sr,hexToNumber:()=>_i,inRange:()=>un,isBytes:()=>Fe,memoized:()=>ir,notImplemented:()=>Ap,numberToBytesBE:()=>Ke,numberToBytesLE:()=>Ee,numberToHexUnpadded:()=>or,numberToVarBytesBE:()=>yp,utf8ToBytes:()=>xp,validateObject:()=>Gt});var Ni=BigInt(0),lo=BigInt(1),gp=BigInt(2);function Fe(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Lr(r){if(!Fe(r))throw new Error("Uint8Array expected")}function Jt(r,t){if(typeof t!="boolean")throw new Error(`${r} must be valid boolean, got "${t}".`)}var wp=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function be(r){Lr(r);let t="";for(let e=0;e<r.length;e++)t+=wp[r[e]];return t}function or(r){let t=r.toString(16);return t.length&1?`0${t}`:t}function _i(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var ye={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function gl(r){if(r>=ye._0&&r<=ye._9)return r-ye._0;if(r>=ye._A&&r<=ye._F)return r-(ye._A-10);if(r>=ye._a&&r<=ye._f)return r-(ye._a-10)}function sr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=gl(r.charCodeAt(s)),a=gl(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function xe(r){return _i(be(r))}function Qt(r){return Lr(r),_i(be(Uint8Array.from(r).reverse()))}function Ke(r,t){return sr(r.toString(16).padStart(t*2,"0"))}function Ee(r,t){return Ke(r,t).reverse()}function yp(r){return sr(or(r))}function at(r,t,e){let n;if(typeof t=="string")try{n=sr(t)}catch(s){throw new Error(`${r} must be valid hex string, got "${t}". Cause: ${s}`)}else if(Fe(t))n=Uint8Array.from(t);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(`${r} expected ${e} bytes, got ${o}`);return n}function ve(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Lr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function bp(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function xp(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var ki=r=>typeof r=="bigint"&&Ni<=r;function un(r,t,e){return ki(r)&&ki(t)&&ki(e)&&t<=r&&r<e}function It(r,t,e,n){if(!un(t,e,n))throw new Error(`expected valid ${r}: ${e} <= n < ${n}, got ${typeof t} ${t}`)}function Li(r){let t;for(t=0;r>Ni;r>>=lo,t+=1);return t}function Ep(r,t){return r>>BigInt(t)&lo}function vp(r,t,e){return r|(e?lo:Ni)<<BigInt(t)}var fn=r=>(gp<<BigInt(r-1))-lo,Ti=r=>new Uint8Array(r),wl=r=>Uint8Array.from(r);function Ri(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=Ti(r),o=Ti(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=Ti())=>{o=a(wl([0]),f),n=a(),f.length!==0&&(o=a(wl([1]),f),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<t;){n=a();let m=n.slice();d.push(m),f+=n.length}return ve(...d)};return(f,d)=>{i(),c(f);let m;for(;!(m=d(l()));)c();return i(),m}}var Sp={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Fe(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function Gt(r,t,e={}){let n=(o,s,i)=>{let a=Sp[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(e))n(o,s,!0);return r}var Ap=()=>{throw new Error("not implemented")};function ir(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var bt=BigInt(0),ht=BigInt(1),ar=BigInt(2),Bp=BigInt(3),Ui=BigInt(4),yl=BigInt(5),bl=BigInt(8),Ip=BigInt(9),Cp=BigInt(16);function Y(r,t){let e=r%t;return e>=bt?e:t+e}function Di(r,t,e){if(e<=bt||t<bt)throw new Error("Expected power/modulo > 0");if(e===ht)return bt;let n=ht;for(;t>bt;)t&ht&&(n=n*r%e),r=r*r%e,t>>=ht;return n}function ct(r,t,e){let n=r;for(;t-- >bt;)n*=n,n%=e;return n}function fo(r,t){if(r===bt||t<=bt)throw new Error(`invert: expected positive integers, got n=${r} mod=${t}`);let e=Y(r,t),n=t,o=bt,s=ht,i=ht,a=bt;for(;e!==bt;){let l=n/e,u=n%e,f=o-i*l,d=s-a*l;n=e,e=u,o=i,s=a,i=f,a=d}if(n!==ht)throw new Error("invert: does not exist");return Y(o,t)}function kp(r){let t=(r-ht)/ar,e,n,o;for(e=r-ht,n=0;e%ar===bt;e/=ar,n++);for(o=ar;o<r&&Di(o,t,r)!==r-ht;o++);if(n===1){let i=(r+ht)/Ui;return function(c,l){let u=c.pow(l,i);if(!c.eql(c.sqr(u),l))throw new Error("Cannot find square root");return u}}let s=(e+ht)/ar;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),e),f=a.pow(c,s),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let m=1;for(let g=a.sqr(d);m<l&&!a.eql(g,a.ONE);m++)g=a.sqr(g);let x=a.pow(u,ht<<BigInt(l-m-1));u=a.sqr(x),f=a.mul(f,x),d=a.mul(d,u),l=m}return f}}function Tp(r){if(r%Ui===Bp){let t=(r+ht)/Ui;return function(n,o){let s=n.pow(o,t);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%bl===yl){let t=(r-yl)/bl;return function(n,o){let s=n.mul(o,ar),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,ar),i),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%Cp,kp(r)}var xl=(r,t)=>(Y(r,t)&ht)===ht,Np=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Pi(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Np.reduce((n,o)=>(n[o]="function",n),t);return Gt(r,e)}function _p(r,t,e){if(e<bt)throw new Error("Expected power > 0");if(e===bt)return r.ONE;if(e===ht)return t;let n=r.ONE,o=t;for(;e>bt;)e&ht&&(n=r.mul(n,o)),o=r.sqr(o),e>>=ht;return n}function Lp(r,t){let e=new Array(t.length),n=t.reduce((s,i,a)=>r.is0(i)?s:(e[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return t.reduceRight((s,i,a)=>r.is0(i)?s:(e[a]=r.mul(s,e[a]),r.mul(s,i)),o),e}function Oi(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function $e(r,t,e=!1,n={}){if(r<=bt)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=Oi(r,t);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=Tp(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:fn(o),ZERO:bt,ONE:ht,create:c=>Y(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return bt<=c&&c<r},is0:c=>c===bt,isOdd:c=>(c&ht)===ht,neg:c=>Y(-c,r),eql:(c,l)=>c===l,sqr:c=>Y(c*c,r),add:(c,l)=>Y(c+l,r),sub:(c,l)=>Y(c-l,r),mul:(c,l)=>Y(c*l,r),pow:(c,l)=>_p(a,c,l),div:(c,l)=>Y(c*fo(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>fo(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>Lp(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?Ee(c,s):Ke(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return e?Qt(c):xe(c)}});return Object.freeze(a)}function El(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Hi(r){let t=El(r);return t+Math.ceil(t/2)}function vl(r,t,e=!1){let n=r.length,o=El(t),s=Hi(t);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=e?xe(r):Qt(r),a=Y(i,t-ht)+ht;return e?Ee(a,o):Ke(a,o)}var Up=BigInt(0),Mi=BigInt(1),Vi=new WeakMap,Sl=new WeakMap;function ho(r,t){let e=(s,i)=>{let a=i.negate();return s?a:i},n=s=>{if(!Number.isSafeInteger(s)||s<=0||s>t)throw new Error(`Wrong window size=${s}, should be [1..${t}]`)},o=s=>{n(s);let i=Math.ceil(t/s)+1,a=2**(s-1);return{windows:i,windowSize:a}};return{constTimeNegate:e,unsafeLadder(s,i){let a=r.ZERO,c=s;for(;i>Up;)i&Mi&&(a=a.add(c)),c=c.double(),i>>=Mi;return a},precomputeWindow(s,i){let{windows:a,windowSize:c}=o(i),l=[],u=s,f=u;for(let d=0;d<a;d++){f=u,l.push(f);for(let m=1;m<c;m++)f=f.add(u),l.push(f);u=f.double()}return l},wNAF(s,i,a){let{windows:c,windowSize:l}=o(s),u=r.ZERO,f=r.BASE,d=BigInt(2**s-1),m=2**s,x=BigInt(s);for(let g=0;g<c;g++){let h=g*l,w=Number(a&d);a>>=x,w>l&&(w-=m,a+=Mi);let b=h,p=h+Math.abs(w)-1,B=g%2!==0,_=w<0;w===0?f=f.add(e(B,i[b])):u=u.add(e(_,i[p]))}return{p:u,f}},wNAFCached(s,i,a){let c=Sl.get(s)||1,l=Vi.get(s);return l||(l=this.precomputeWindow(s,c),c!==1&&Vi.set(s,a(l))),this.wNAF(c,l,i)},setWindowSize(s,i){n(i),Sl.set(s,i),Vi.delete(s)}}}function po(r,t,e,n){if(!Array.isArray(e)||!Array.isArray(n)||n.length!==e.length)throw new Error("arrays of points and scalars must have equal length");n.forEach((u,f)=>{if(!t.isValid(u))throw new Error(`wrong scalar at index ${f}`)}),e.forEach((u,f)=>{if(!(u instanceof r))throw new Error(`wrong point at index ${f}`)});let o=Li(BigInt(e.length)),s=o>12?o-3:o>4?o-2:o?2:1,i=(1<<s)-1,a=new Array(i+1).fill(r.ZERO),c=Math.floor((t.BITS-1)/s)*s,l=r.ZERO;for(let u=c;u>=0;u-=s){a.fill(r.ZERO);for(let d=0;d<n.length;d++){let m=n[d],x=Number(m>>BigInt(u)&BigInt(i));a[x]=a[x].add(e[d])}let f=r.ZERO;for(let d=a.length-1,m=r.ZERO;d>0;d--)m=m.add(a[d]),f=f.add(m);if(l=l.add(f),u!==0)for(let d=0;d<s;d++)l=l.double()}return l}function hn(r){return Pi(r.Fp),Gt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Oi(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var te=BigInt(0),Ft=BigInt(1),mo=BigInt(2),Dp=BigInt(8),Pp={zip215:!0};function Op(r){let t=hn(r);return Gt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Al(r){let t=Op(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=mo<<BigInt(a*8)-Ft,u=e.create,f=$e(t.n,t.nBitLength),d=t.uvRatio||((E,y)=>{try{return{isValid:!0,value:e.sqrt(E*e.inv(y))}}catch{return{isValid:!1,value:te}}}),m=t.adjustScalarBytes||(E=>E),x=t.domain||((E,y,S)=>{if(Jt("phflag",S),y.length||S)throw new Error("Contexts/pre-hash are not supported");return E});function g(E,y){It("coordinate "+E,y,te,l)}function h(E){if(!(E instanceof p))throw new Error("ExtendedPoint expected")}let w=ir((E,y)=>{let{ex:S,ey:v,ez:R}=E,D=E.is0();y==null&&(y=D?Dp:e.inv(R));let M=u(S*y),$=u(v*y),W=u(R*y);if(D)return{x:te,y:Ft};if(W!==Ft)throw new Error("invZ was invalid");return{x:M,y:$}}),b=ir(E=>{let{a:y,d:S}=t;if(E.is0())throw new Error("bad point: ZERO");let{ex:v,ey:R,ez:D,et:M}=E,$=u(v*v),W=u(R*R),z=u(D*D),Z=u(z*z),st=u($*y),it=u(z*u(st+W)),ft=u(Z+u(S*u($*W)));if(it!==ft)throw new Error("bad point: equation left != right (1)");let Dt=u(v*R),yt=u(D*M);if(Dt!==yt)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(y,S,v,R){this.ex=y,this.ey=S,this.ez=v,this.et=R,g("x",y),g("y",S),g("z",v),g("t",R),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(y){if(y instanceof p)throw new Error("extended point not allowed");let{x:S,y:v}=y||{};return g("x",S),g("y",v),new p(S,v,Ft,u(S*v))}static normalizeZ(y){let S=e.invertBatch(y.map(v=>v.ez));return y.map((v,R)=>v.toAffine(S[R])).map(p.fromAffine)}static msm(y,S){return po(p,f,y,S)}_setWindowSize(y){N.setWindowSize(this,y)}assertValidity(){b(this)}equals(y){h(y);let{ex:S,ey:v,ez:R}=this,{ex:D,ey:M,ez:$}=y,W=u(S*$),z=u(D*R),Z=u(v*$),st=u(M*R);return W===z&&Z===st}is0(){return this.equals(p.ZERO)}negate(){return new p(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:y}=t,{ex:S,ey:v,ez:R}=this,D=u(S*S),M=u(v*v),$=u(mo*u(R*R)),W=u(y*D),z=S+v,Z=u(u(z*z)-D-M),st=W+M,it=st-$,ft=W-M,Dt=u(Z*it),yt=u(st*ft),Mt=u(Z*ft),pe=u(it*st);return new p(Dt,yt,pe,Mt)}add(y){h(y);let{a:S,d:v}=t,{ex:R,ey:D,ez:M,et:$}=this,{ex:W,ey:z,ez:Z,et:st}=y;if(S===BigInt(-1)){let Vc=u((D-R)*(z+W)),Fc=u((D+R)*(z-W)),hi=u(Fc-Vc);if(hi===te)return this.double();let Kc=u(M*mo*st),$c=u($*mo*Z),Wc=$c+Kc,qc=Fc+Vc,zc=$c-Kc,qh=u(Wc*hi),zh=u(qc*zc),Gh=u(Wc*zc),jh=u(hi*qc);return new p(qh,zh,jh,Gh)}let it=u(R*W),ft=u(D*z),Dt=u($*v*st),yt=u(M*Z),Mt=u((R+D)*(W+z)-it-ft),pe=yt-Dt,tn=yt+Dt,en=u(ft-S*it),Fh=u(Mt*pe),Kh=u(tn*en),$h=u(Mt*en),Wh=u(pe*tn);return new p(Fh,Kh,Wh,$h)}subtract(y){return this.add(y.negate())}wNAF(y){return N.wNAFCached(this,y,p.normalizeZ)}multiply(y){let S=y;It("scalar",S,Ft,n);let{p:v,f:R}=this.wNAF(S);return p.normalizeZ([v,R])[0]}multiplyUnsafe(y){let S=y;return It("scalar",S,te,n),S===te?_:this.equals(_)||S===Ft?this:this.equals(B)?this.wNAF(S).p:N.unsafeLadder(this,S)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return N.unsafeLadder(this,n).is0()}toAffine(y){return w(this,y)}clearCofactor(){let{h:y}=t;return y===Ft?this:this.multiplyUnsafe(y)}static fromHex(y,S=!1){let{d:v,a:R}=t,D=e.BYTES;y=at("pointHex",y,D),Jt("zip215",S);let M=y.slice(),$=y[D-1];M[D-1]=$&-129;let W=Qt(M),z=S?l:e.ORDER;It("pointHex.y",W,te,z);let Z=u(W*W),st=u(Z-Ft),it=u(v*Z-R),{isValid:ft,value:Dt}=d(st,it);if(!ft)throw new Error("Point.fromHex: invalid y coordinate");let yt=(Dt&Ft)===Ft,Mt=($&128)!==0;if(!S&&Dt===te&&Mt)throw new Error("Point.fromHex: x=0 and x_0=1");return Mt!==yt&&(Dt=u(-Dt)),p.fromAffine({x:Dt,y:W})}static fromPrivateKey(y){return I(y).point}toRawBytes(){let{x:y,y:S}=this.toAffine(),v=Ee(S,e.BYTES);return v[v.length-1]|=y&Ft?128:0,v}toHex(){return be(this.toRawBytes())}}p.BASE=new p(t.Gx,t.Gy,Ft,u(t.Gx*t.Gy)),p.ZERO=new p(te,Ft,Ft,te);let{BASE:B,ZERO:_}=p,N=ho(p,a*8);function A(E){return Y(E,n)}function k(E){return A(Qt(E))}function I(E){let y=a;E=at("private key",E,y);let S=at("hashed private key",s(E),2*y),v=m(S.slice(0,y)),R=S.slice(y,2*y),D=k(v),M=B.multiply(D),$=M.toRawBytes();return{head:v,prefix:R,scalar:D,point:M,pointBytes:$}}function V(E){return I(E).pointBytes}function L(E=new Uint8Array,...y){let S=ve(...y);return k(s(x(S,at("context",E),!!o)))}function H(E,y,S={}){E=at("message",E),o&&(E=o(E));let{prefix:v,scalar:R,pointBytes:D}=I(y),M=L(S.context,v,E),$=B.multiply(M).toRawBytes(),W=L(S.context,$,D,E),z=A(M+W*R);It("signature.s",z,te,n);let Z=ve($,Ee(z,e.BYTES));return at("result",Z,a*2)}let K=Pp;function C(E,y,S,v=K){let{context:R,zip215:D}=v,M=e.BYTES;E=at("signature",E,2*M),y=at("message",y),D!==void 0&&Jt("zip215",D),o&&(y=o(y));let $=Qt(E.slice(M,2*M)),W,z,Z;try{W=p.fromHex(S,D),z=p.fromHex(E.slice(0,M),D),Z=B.multiplyUnsafe($)}catch{return!1}if(!D&&W.isSmallOrder())return!1;let st=L(R,z.toRawBytes(),W.toRawBytes(),y);return z.add(W.multiplyUnsafe(st)).subtract(Z).clearCofactor().equals(p.ZERO)}return B._setWindowSize(8),{CURVE:t,getPublicKey:V,sign:H,verify:C,ExtendedPoint:p,utils:{getExtendedPublicKey:I,randomPrivateKey:()=>i(e.BYTES),precompute(E=8,y=p.BASE){return y._setWindowSize(E),y.multiply(BigInt(3)),y}}}}var Rr=BigInt(0),Fi=BigInt(1);function Hp(r){return Gt(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function Bl(r){let t=Hp(r),{P:e}=t,n=b=>Y(b,e),o=t.montgomeryBits,s=Math.ceil(o/8),i=t.nByteLength,a=t.adjustScalarBytes||(b=>b),c=t.powPminus2||(b=>Di(b,e-BigInt(2),e));function l(b,p,B){let _=n(b*(p-B));return p=n(p-_),B=n(B+_),[p,B]}let u=(t.a-BigInt(2))/BigInt(4);function f(b,p){It("u",b,Rr,e),It("scalar",p,Rr,e);let B=p,_=b,N=Fi,A=Rr,k=b,I=Fi,V=Rr,L;for(let K=BigInt(o-1);K>=Rr;K--){let C=B>>K&Fi;V^=C,L=l(V,N,k),N=L[0],k=L[1],L=l(V,A,I),A=L[0],I=L[1],V=C;let T=N+A,E=n(T*T),y=N-A,S=n(y*y),v=E-S,R=k+I,D=k-I,M=n(D*T),$=n(R*y),W=M+$,z=M-$;k=n(W*W),I=n(_*n(z*z)),N=n(E*S),A=n(v*(E+n(u*v)))}L=l(V,N,k),N=L[0],k=L[1],L=l(V,A,I),A=L[0],I=L[1];let H=c(A);return n(N*H)}function d(b){return Ee(n(b),s)}function m(b){let p=at("u coordinate",b,s);return i===32&&(p[31]&=127),Qt(p)}function x(b){let p=at("scalar",b),B=p.length;if(B!==s&&B!==i)throw new Error(`Expected ${s} or ${i} bytes, got ${B}`);return Qt(a(p))}function g(b,p){let B=m(p),_=x(b),N=f(B,_);if(N===Rr)throw new Error("Invalid private or public key received");return d(N)}let h=d(t.Gu);function w(b){return g(b,h)}return{scalarMult:g,scalarMultBase:w,getSharedSecret:(b,p)=>g(b,p),getPublicKey:b=>w(b),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:h}}var dn=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Il=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),py=BigInt(0),Mp=BigInt(1),Cl=BigInt(2),Vp=BigInt(3),Fp=BigInt(5),Kp=BigInt(8);function kl(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=dn,a=r*r%s*r%s,c=ct(a,Cl,s)*a%s,l=ct(c,Mp,s)*r%s,u=ct(l,Fp,s)*l%s,f=ct(u,t,s)*u%s,d=ct(f,e,s)*f%s,m=ct(d,n,s)*d%s,x=ct(m,o,s)*m%s,g=ct(x,o,s)*m%s,h=ct(g,t,s)*u%s;return{pow_p_5_8:ct(h,Cl,s)*r%s,b2:a}}function Tl(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function $p(r,t){let e=dn,n=Y(t*t*t,e),o=Y(n*n*t,e),s=kl(r*o).pow_p_5_8,i=Y(r*n*s,e),a=Y(t*i*i,e),c=i,l=Y(i*Il,e),u=a===r,f=a===Y(-r,e),d=a===Y(-r*Il,e);return u&&(i=c),(f||d)&&(i=l),xl(i,e)&&(i=Y(-i,e)),{isValid:u||f,value:i}}var Wp=$e(dn,void 0,!0),qp={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Wp,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Kp,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:ml,randomBytes:ln,adjustScalarBytes:Tl,uvRatio:$p},Nl=Al(qp);var pn=Bl({P:dn,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let t=dn,{pow_p_5_8:e,b2:n}=kl(r);return Y(ct(e,Vp,t)*n,t)},adjustScalarBytes:Tl,randomBytes:ln});var go=32;function _l(r,t,e){return Nl.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}var wo=class{type="Ed25519";raw;constructor(t){this.raw=Ki(t,go)}toMultihash(){return we.digest(Ur(this))}toCID(){return Bt.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Pt(this.raw,t.raw)}verify(t,e){return _l(this.raw,e,t)}};function $i(r){return r=Ki(r,go),new wo(r)}function Ki(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new et(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}function xt(r=0){return new Uint8Array(r)}function Et(r=0){return new Uint8Array(r)}var Gp=Math.pow(2,7),jp=Math.pow(2,14),Zp=Math.pow(2,21),Wi=Math.pow(2,28),qi=Math.pow(2,35),zi=Math.pow(2,42),Gi=Math.pow(2,49),J=128,_t=127;function lt(r){if(r<Gp)return 1;if(r<jp)return 2;if(r<Zp)return 3;if(r<Wi)return 4;if(r<qi)return 5;if(r<zi)return 6;if(r<Gi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ji(r,t,e=0){switch(lt(r)){case 8:t[e++]=r&255|J,r/=128;case 7:t[e++]=r&255|J,r/=128;case 6:t[e++]=r&255|J,r/=128;case 5:t[e++]=r&255|J,r/=128;case 4:t[e++]=r&255|J,r>>>=7;case 3:t[e++]=r&255|J,r>>>=7;case 2:t[e++]=r&255|J,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Xp(r,t,e=0){switch(lt(r)){case 8:t.set(e++,r&255|J),r/=128;case 7:t.set(e++,r&255|J),r/=128;case 6:t.set(e++,r&255|J),r/=128;case 5:t.set(e++,r&255|J),r/=128;case 4:t.set(e++,r&255|J),r>>>=7;case 3:t.set(e++,r&255|J),r>>>=7;case 2:t.set(e++,r&255|J),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Zi(r,t){let e=r[t],n=0;if(n+=e&_t,e<J||(e=r[t+1],n+=(e&_t)<<7,e<J)||(e=r[t+2],n+=(e&_t)<<14,e<J)||(e=r[t+3],n+=(e&_t)<<21,e<J)||(e=r[t+4],n+=(e&_t)*Wi,e<J)||(e=r[t+5],n+=(e&_t)*qi,e<J)||(e=r[t+6],n+=(e&_t)*zi,e<J)||(e=r[t+7],n+=(e&_t)*Gi,e<J))return n;throw new RangeError("Could not decode varint")}function Yp(r,t){let e=r.get(t),n=0;if(n+=e&_t,e<J||(e=r.get(t+1),n+=(e&_t)<<7,e<J)||(e=r.get(t+2),n+=(e&_t)<<14,e<J)||(e=r.get(t+3),n+=(e&_t)<<21,e<J)||(e=r.get(t+4),n+=(e&_t)*Wi,e<J)||(e=r.get(t+5),n+=(e&_t)*qi,e<J)||(e=r.get(t+6),n+=(e&_t)*zi,e<J)||(e=r.get(t+7),n+=(e&_t)*Gi,e<J))return n;throw new RangeError("Could not decode varint")}function ce(r,t,e=0){return t==null&&(t=Et(lt(r))),t instanceof Uint8Array?ji(r,t,e):Xp(r,t,e)}function ee(r,t=0){return r instanceof Uint8Array?Zi(r,t):Yp(r,t)}var Xi=new Float32Array([-0]),We=new Uint8Array(Xi.buffer);function Rl(r,t,e){Xi[0]=r,t[e]=We[0],t[e+1]=We[1],t[e+2]=We[2],t[e+3]=We[3]}function Ul(r,t){return We[0]=r[t],We[1]=r[t+1],We[2]=r[t+2],We[3]=r[t+3],Xi[0]}var Yi=new Float64Array([-0]),Lt=new Uint8Array(Yi.buffer);function Dl(r,t,e){Yi[0]=r,t[e]=Lt[0],t[e+1]=Lt[1],t[e+2]=Lt[2],t[e+3]=Lt[3],t[e+4]=Lt[4],t[e+5]=Lt[5],t[e+6]=Lt[6],t[e+7]=Lt[7]}function Pl(r,t){return Lt[0]=r[t],Lt[1]=r[t+1],Lt[2]=r[t+2],Lt[3]=r[t+3],Lt[4]=r[t+4],Lt[5]=r[t+5],Lt[6]=r[t+6],Lt[7]=r[t+7],Yi[0]}var Jp=BigInt(Number.MAX_SAFE_INTEGER),Qp=BigInt(Number.MIN_SAFE_INTEGER),qt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return cr;if(t<Jp&&t>Qp)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>Ol&&(o=0n,++n>Ol&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return cr;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):cr}},cr=new qt(0,0);cr.toBigInt=function(){return 0n};cr.zzEncode=cr.zzDecode=function(){return this};cr.length=function(){return 1};var Ol=4294967296n;function Hl(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Ml(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Ji(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function re(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function yo(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Qi=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,re(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw re(this,4);return yo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw re(this,4);return yo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw re(this,4);let t=Ul(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw re(this,4);let t=Pl(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw re(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Ml(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw re(this,t);this.pos+=t}else do if(this.pos>=this.len)throw re(this);while(this.buf[this.pos++]&128);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new qt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw re(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw re(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw re(this,8);let t=yo(this.buf,this.pos+=4),e=yo(this.buf,this.pos+=4);return new qt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Zi(this.buf,this.pos);return this.pos+=lt(t),t}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 ta(r){return new Qi(r instanceof Uint8Array?r:r.subarray())}function ne(r,t,e){let n=ta(r);return t.decode(n,void 0,e)}var ea={};Nt(ea,{base10:()=>tm});var tm=Pe({prefix:"9",name:"base10",alphabet:"0123456789"});var ra={};Nt(ra,{base16:()=>em,base16upper:()=>rm});var em=mt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),rm=mt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var na={};Nt(na,{base2:()=>nm});var nm=mt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var oa={};Nt(oa,{base256emoji:()=>cm});var Fl=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),om=Fl.reduce((r,t,e)=>(r[e]=t,r),[]),sm=Fl.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function im(r){return r.reduce((t,e)=>(t+=om[e],t),"")}function am(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=sm[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var cm=Br({prefix:"\u{1F680}",name:"base256emoji",encode:im,decode:am});var ia={};Nt(ia,{base64:()=>lm,base64pad:()=>um,base64url:()=>sa,base64urlpad:()=>fm});var lm=mt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),um=mt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),sa=mt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),fm=mt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var aa={};Nt(aa,{base8:()=>hm});var hm=mt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ca={};Nt(ca,{identity:()=>dm});var dm=Br({prefix:"\0",name:"identity",encode:r=>Jc(r),decode:r=>Yc(r)});var Xy=new TextEncoder,Yy=new TextDecoder;var fa={};Nt(fa,{sha256:()=>gn,sha512:()=>gm});function ua({name:r,code:t,encode:e}){return new la(r,t,e)}var la=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?Vt(this.code,e):e.then(n=>Vt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function $l(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var gn=ua({name:"sha2-256",code:18,encode:$l("SHA-256")}),gm=ua({name:"sha2-512",code:19,encode:$l("SHA-512")});var lr={...ca,...na,...aa,...ea,...ra,...bi,...xi,...yi,...ia,...oa},lb={...fa,...Ai};function ql(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Wl=ql("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ha=ql("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=Et(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),wm={utf8:Wl,"utf-8":Wl,hex:lr.base16,latin1:ha,ascii:ha,binary:ha,...lr},bo=wm;function rt(r,t="utf8"){let e=bo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function da(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return Et(i);o+i>t&&(n=Et(t),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var ur=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function pa(){}var ga=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},ym=da();function bm(r){return globalThis.Buffer!=null?Et(r):ym(r)}var yn=class{len;head;tail;states;constructor(){this.len=0,this.head=new ur(pa,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new ur(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new wa((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(xo,10,qt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=qt.fromBigInt(t);return this._push(xo,e.length(),e)}uint64Number(t){return this._push(ji,lt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=qt.fromBigInt(t).zzEncode();return this._push(xo,e.length(),e)}sint64Number(t){let e=qt.fromNumber(t).zzEncode();return this._push(xo,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ma,1,t?1:0)}fixed32(t){return this._push(wn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=qt.fromBigInt(t);return this._push(wn,4,e.lo)._push(wn,4,e.hi)}fixed64Number(t){let e=qt.fromNumber(t);return this._push(wn,4,e.lo)._push(wn,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Rl,4,t)}double(t){return this._push(Dl,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ma,1,0):this.uint32(e)._push(Em,e,t)}string(t){let e=Hl(t);return e!==0?this.uint32(e)._push(Ji,e,t):this._push(ma,1,0)}fork(){return this.states=new ga(this),this.head=this.tail=new ur(pa,0,0),this.len=0,this}reset(){return this.states!=null?(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 ur(pa,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=bm(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ma(r,t,e){t[e]=r&255}function xm(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var wa=class extends ur{next;constructor(t,e){super(xm,t,e),this.next=void 0}};function xo(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function wn(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Em(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(yn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(vm,t,r),this},yn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Sm,t,r),this});function vm(r,t,e){t.set(r,e)}function Sm(r,t,e){r.length<40?Ji(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(rt(r),e)}function ya(){return new yn}function oe(r,t){let e=ya();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Dr;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Dr||(Dr={}));function Eo(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function fr(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return Eo("enum",Dr.VARINT,e,n)}function se(r,t){return Eo("message",Dr.LENGTH_DELIMITED,r,t)}var vt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(vt||(vt={}));var ba;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(ba||(ba={}));(function(r){r.codec=()=>fr(ba)})(vt||(vt={}));var le;(function(r){let t;r.codec=()=>(t==null&&(t=se((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),vt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=vt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>oe(e,r.codec()),r.decode=(e,n)=>ne(e,r.codec(),n)})(le||(le={}));var xa;(function(r){let t;r.codec=()=>(t==null&&(t=se((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),vt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=vt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>oe(e,r.codec()),r.decode=(e,n)=>ne(e,r.codec(),n)})(xa||(xa={}));var kn={};Nt(kn,{MAX_RSA_KEY_SIZE:()=>hs,generateRSAKeyPair:()=>Ku,jwkToJWKKeyPair:()=>$u,jwkToPkcs1:()=>Mm,jwkToPkix:()=>Ta,jwkToRSAPrivateKey:()=>Fu,pkcs1ToJwk:()=>Hu,pkcs1ToRSAPrivateKey:()=>Vu,pkixToJwk:()=>Mu,pkixToRSAPublicKey:()=>Na});var Am=new Uint32Array([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]),qe=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ze=new Uint32Array(64),Ea=class extends _r{constructor(){super(64,32,8,!1),this.A=qe[0]|0,this.B=qe[1]|0,this.C=qe[2]|0,this.D=qe[3]|0,this.E=qe[4]|0,this.F=qe[5]|0,this.G=qe[6]|0,this.H=qe[7]|0}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)ze[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=ze[f-15],m=ze[f-2],x=Yt(d,7)^Yt(d,18)^d>>>3,g=Yt(m,17)^Yt(m,19)^m>>>10;ze[f]=g+ze[f-7]+x+ze[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=Yt(a,6)^Yt(a,11)^Yt(a,25),m=u+d+hl(a,c,l)+Am[f]+ze[f]|0,g=(Yt(n,2)^Yt(n,13)^Yt(n,22))+dl(n,o,s)|0;u=l,l=c,c=a,a=i+m|0,i=s,s=o,o=n,n=m+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){ze.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ue=ao(()=>new Ea);var G=ed(Gl());function hr(r,t){let e=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)e+=r[r.length-1-n]*Math.pow(2,t*n);return e}function Ge(r,t,e=-1){let n=e,o=r,s=0,i=Math.pow(2,t);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let f=Math.pow(2,u*t);l[s-u-1]=Math.floor(o/f),o-=l[s-u-1]*f}return c}i*=Math.pow(2,t)}return new ArrayBuffer(0)}function Ao(...r){let t=0,e=0;for(let s of r)t+=s.length;let n=new ArrayBuffer(t),o=new Uint8Array(n);for(let s of r)o.set(s,e),e+=s.length;return o}function Sa(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let t=new ArrayBuffer(this.valueHex.byteLength),e=new Uint8Array(t);for(let a=0;a<this.valueHex.byteLength;a++)e[a]=0;e[0]=r[0]&128;let n=hr(e,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,hr(s,8)-n}function jl(r){let t=r<0?r*-1:r,e=128;for(let n=1;n<8;n++){if(t<=e){if(r<0){let i=e-t,a=Ge(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Ge(t,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}e*=Math.pow(2,8)}return new ArrayBuffer(0)}function Zl(r,t){if(r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<e.length;o++)if(e[o]!==n[o])return!1;return!0}function Kt(r,t){let e=r.toString(10);if(t<e.length)return"";let n=t-e.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(e)}var Wb=Math.log(2);function Bo(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Aa(r){let t=0,e=0;for(let o=0;o<r.length;o++){let s=r[o];t+=s.byteLength}let n=new Uint8Array(t);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),e),e+=s.byteLength}return n.buffer}function Ce(r,t,e,n){return t instanceof Uint8Array?t.byteLength?e<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):t.byteLength-e-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var xn=class{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return Aa(this.items)}},bn=[new Uint8Array([1])],Xl="0123456789";var Vr="",ie=new ArrayBuffer(0),Ba=new Uint8Array(0),En="EndOfContent",Jl="OCTET STRING",Ql="BIT STRING";function ke(r){var t;return t=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?G.BufferSourceConverter.toUint8Array(s.valueHex):Ba}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Ce(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?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",ie)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:G.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var Ae=class{constructor({blockLength:t=0,error:e=Vr,warnings:n=[],valueBeforeDecode:o=Ba}={}){this.blockLength=t,this.error=e,this.warnings=n,this.valueBeforeDecodeView=G.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(t){this.valueBeforeDecodeView=new Uint8Array(t)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:G.Convert.ToHex(this.valueBeforeDecodeView)}}};Ae.NAME="baseBlock";var Rt=class extends Ae{fromBER(t,e,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(t,e){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Rt.NAME="valueBlock";var Io=class extends ke(Ae){constructor({idBlock:t={}}={}){var e,n,o,s;super(),t?(this.isHexOnly=(e=t.isHexOnly)!==null&&e!==void 0?e:!1,this.valueHexView=t.valueHex?G.BufferSourceConverter.toUint8Array(t.valueHex):Ba,this.tagClass=(n=t.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=t.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=t.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(t=!1){let e=0;switch(this.tagClass){case 1:e|=0;break;case 2:e|=64;break;case 3:e|=128;break;case 4:e|=192;break;default:return this.error="Unknown tag class",ie}if(this.isConstructed&&(e|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!t){let s=this.tagNumber;s&=31,e|=s,o[0]=e}return o.buffer}if(!this.isHexOnly){let o=Ge(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=e|31,!t){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=e|31,!t){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(t,e,n){let o=G.BufferSourceConverter.toUint8Array(t);if(!Ce(this,o,e,n))return-1;let s=o.subarray(e,e+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){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=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,l=this.valueHexView=new Uint8Array(255),u=255;for(;s[c]&128;){if(l[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===u){u+=255;let d=new Uint8Array(u);for(let m=0;m<l.length;m++)d[m]=l[m];l=this.valueHexView=new Uint8Array(u)}}this.blockLength=c+1,l[c-1]=s[c]&127;let f=new Uint8Array(c);for(let d=0;d<c;d++)f[d]=l[d];l=this.valueHexView=new Uint8Array(c),l.set(f),this.blockLength<=9?this.tagNumber=hr(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&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 e+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};Io.NAME="identificationBlock";var Co=class extends Ae{constructor({lenBlock:t={}}={}){var e,n,o;super(),this.isIndefiniteForm=(e=t.isIndefiniteForm)!==null&&e!==void 0?e:!1,this.longFormUsed=(n=t.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=t.length)!==null&&o!==void 0?o:0}fromBER(t,e,n){let o=G.BufferSourceConverter.toUint8Array(t);if(!Ce(this,o,e,n))return-1;let s=o.subarray(e,e+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,e+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,e+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=e+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=hr(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,e+this.blockLength}toBER(t=!1){let e,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=128),e;if(this.longFormUsed){let o=Ge(this.length,8);if(o.byteLength>127)return this.error="Too big length",ie;if(e=new ArrayBuffer(o.byteLength+1),t)return e;let s=new Uint8Array(o);n=new Uint8Array(e),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return e}return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=this.length),e}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Co.NAME="lengthBlock";var P={},Ct=class extends Ae{constructor({name:t=Vr,optional:e=!1,primitiveSchema:n,...o}={},s){super(o),this.name=t,this.optional=e,n&&(this.primitiveSchema=n),this.idBlock=new Io(o),this.lenBlock=new Co(o),this.valueBlock=s?new s(o):new Rt(o)}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(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),o)}toBER(t,e){let n=e||new xn;e||tu(this);let o=this.idBlock.toBER(t);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(t,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(t);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(t);n.write(i),n.write(s)}return e?ie:n.final()}toJSON(){let t={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(t="ascii"){return t==="ascii"?this.onAsciiEncoding():G.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${G.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(t){if(this===t)return!0;if(!(t instanceof this.constructor))return!1;let e=this.toBER(),n=t.toBER();return Zl(e,n)}};Ct.NAME="BaseBlock";function tu(r){if(r instanceof P.Constructed)for(let t of r.valueBlock.value)tu(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ko=class extends Ct{constructor({value:t=Vr,...e}={},n){super(e,n),t&&this.fromString(t)}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(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),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};ko.NAME="BaseStringBlock";var To=class extends ke(Rt){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};To.NAME="PrimitiveValueBlock";var eu,No=class extends Ct{constructor(t={}){super(t,To),this.idBlock.isConstructed=!1}};eu=No;P.Primitive=eu;No.NAME="PRIMITIVE";function Rm(r,t){if(r instanceof t)return r;let e=new t;return e.idBlock=r.idBlock,e.lenBlock=r.lenBlock,e.warnings=r.warnings,e.valueBeforeDecodeView=r.valueBeforeDecodeView,e}function us(r,t=0,e=r.length){let n=t,o=new Ct({},Rt),s=new Ae;if(!Ce(s,r,t,e))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(t,t+e).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,t,e);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(t=a,e-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,t,e),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(t=a,e-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Ct;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=P.EndOfContent;break;case 1:c=P.Boolean;break;case 2:c=P.Integer;break;case 3:c=P.BitString;break;case 4:c=P.OctetString;break;case 5:c=P.Null;break;case 6:c=P.ObjectIdentifier;break;case 10:c=P.Enumerated;break;case 12:c=P.Utf8String;break;case 13:c=P.RelativeObjectIdentifier;break;case 14:c=P.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=P.Sequence;break;case 17:c=P.Set;break;case 18:c=P.NumericString;break;case 19:c=P.PrintableString;break;case 20:c=P.TeletexString;break;case 21:c=P.VideotexString;break;case 22:c=P.IA5String;break;case 23:c=P.UTCTime;break;case 24:c=P.GeneralizedTime;break;case 25:c=P.GraphicString;break;case 26:c=P.VisibleString;break;case 27:c=P.GeneralString;break;case 28:c=P.UniversalString;break;case 29:c=P.CharacterString;break;case 30:c=P.BmpString;break;case 31:c=P.DATE;break;case 32:c=P.TimeOfDay;break;case 33:c=P.DateTime;break;case 34:c=P.Duration;break;default:{let l=o.idBlock.isConstructed?new P.Constructed:new P.Primitive;l.idBlock=o.idBlock,l.lenBlock=o.lenBlock,l.warnings=o.warnings,o=l}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?P.Constructed:P.Primitive}return o=Rm(o,c),a=o.fromBER(r,t,o.lenBlock.isIndefiniteForm?e:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function Ia(r){if(!r.byteLength){let t=new Ct({},Rt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return us(G.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function Um(r,t){return r?1:t}var fe=class extends Rt{constructor({value:t=[],isIndefiniteForm:e=!1,...n}={}){super(n),this.value=t,this.isIndefiniteForm=e}fromBER(t,e,n){let o=G.BufferSourceConverter.toUint8Array(t);if(!Ce(this,o,e,n))return-1;if(this.valueBeforeDecodeView=o.subarray(e,e+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),e;let s=e;for(;Um(this.isIndefiniteForm,n)>0;){let i=us(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===En)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===En?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(t,e){let n=e||new xn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(t,n);return e?ie:n.final()}toJSON(){let t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let e of this.value)t.value.push(e.toJSON());return t}};fe.NAME="ConstructedValueBlock";var ru,je=class extends Ct{constructor(t={}){super(t,fe),this.idBlock.isConstructed=!0}fromBER(t,e,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(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),o)}onAsciiEncoding(){let t=[];for(let n of this.valueBlock.value)t.push(n.toString("ascii").split(`
3
3
  `).map(o=>` ${o}`).join(`
4
4
  `));let e=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return t.length?`${e} :
5
5
  ${t.join(`
6
- `)}`:`${e} :`}};ru=je;P.Constructed=ru;je.NAME="CONSTRUCTED";var Lo=class extends Rt{fromBER(t,e,n){return e}toBER(t){return ie}};Lo.override="EndOfContentValueBlock";var nu,_o=class extends Ct{constructor(t={}){super(t,Lo),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};nu=_o;P.EndOfContent=nu;_o.NAME=En;var ou,Pr=class extends Ct{constructor(t={}){super(t,Rt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(t,e,n){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+=n,e+n>t.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):e+n}toBER(t,e){let n=new ArrayBuffer(2);if(!t){let o=new Uint8Array(n);o[0]=5,o[1]=0}return e&&e.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};ou=Pr;P.Null=ou;Pr.NAME="NULL";var Ro=class extends ke(Rt){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=G.BufferSourceConverter.toUint8Array(e.valueHex):this.valueHexView=new Uint8Array(1),t&&(this.value=t)}get value(){for(let t of this.valueHexView)if(t>0)return!0;return!1}set value(t){this.valueHexView[0]=t?255:0}fromBER(t,e,n){let o=G.BufferSourceConverter.toUint8Array(t);return Ce(this,o,e,n)?(this.valueHexView=o.subarray(e,e+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Sa.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Ro.NAME="BooleanValueBlock";var su,Uo=class extends Ct{constructor(t={}){super(t,Ro),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};su=Uo;P.Boolean=su;Uo.NAME="BOOLEAN";var Do=class extends ke(fe){constructor({isConstructed:t=!1,...e}={}){super(e),this.isConstructed=t}fromBER(t,e,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=fe.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===En){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Jl)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(t,e,n),this.blockLength=n;return o}toBER(t,e){return this.isConstructed?fe.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Do.NAME="OctetStringValueBlock";var iu,Po=class r extends Ct{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},Do),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(t,e,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),e;if(!this.valueBlock.isConstructed){let s=(t instanceof ArrayBuffer?new Uint8Array(t):t).subarray(e,e+n);try{if(s.byteLength){let i=us(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(t,e,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?je.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${G.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let t=[];for(let e of this.valueBlock.value)e instanceof r&&t.push(e.valueBlock.valueHexView);return G.BufferSourceConverter.concat(t)}};iu=Po;P.OctetString=iu;Po.NAME=Jl;var Oo=class extends ke(fe){constructor({unusedBits:t=0,isConstructed:e=!1,...n}={}){super(n),this.unusedBits=t,this.isConstructed=e,this.blockLength=this.valueHexView.byteLength}fromBER(t,e,n){if(!n)return e;let o=-1;if(this.isConstructed){if(o=fe.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===En){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Ql)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let s=G.BufferSourceConverter.toUint8Array(t);if(!Ce(this,s,e,n))return-1;let i=s.subarray(e,e+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=us(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,e+n}toBER(t,e){if(this.isConstructed)return fe.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ie;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Oo.NAME="BitStringValueBlock";var au,Or=class extends Ct{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},Oo),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(t,e,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(t,e,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return je.prototype.onAsciiEncoding.call(this);{let t=[],e=this.valueBlock.valueHexView;for(let o of e)t.push(o.toString(2).padStart(8,"0"));let n=t.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};au=Or;P.BitString=au;Or.NAME=Ql;var cu;function Dm(r,t){let e=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<i?i:c,f=0;for(let d=u;d>=0;d--,f++){switch(!0){case f<a.length:l=s[i-f]+a[c-f]+e[0];break;default:l=s[i-f]+e[0]}switch(e[0]=l/10,!0){case f>=s.length:s=Ao(new Uint8Array([l%10]),s);break;default:s[i-f]=l%10}}return e[0]>0&&(s=Ao(e,s)),s}function Yl(r){if(r>=bn.length)for(let t=bn.length;t<=r;t++){let e=new Uint8Array([0]),n=bn[t-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+e[0]]);e[0]=s[0]/10,n[o]=s[0]%10}e[0]>0&&(n=Ao(e,n)),bn.push(n)}return bn[r]}function Pm(r,t){let e=0,n=new Uint8Array(r),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let f=c;f>=0;f--,u++)switch(l=s[i-u]-a[c-u]-e,!0){case l<0:e=1,s[i-u]=l+10;break;default:e=0,s[i-u]=l}if(e>0)for(let f=i-c+1;f>=0;f--,u++)if(l=s[i-u]-e,l<0)e=1,s[i-u]=l+10;else{e=0,s[i-u]=l;break}return s.slice()}var vn=class extends ke(Rt){constructor({value:t,...e}={}){super(e),this._valueDec=0,e.valueHex&&this.setValueHex(),t!==void 0&&(this.valueDec=t)}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=Sa.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(jl(t))}get valueDec(){return this._valueDec}fromDER(t,e,n,o=0){let s=this.fromBER(t,e,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(t=!1){let e=this.valueHexView;switch(!0){case(e[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(e,1),this.valueHexView=n}break;case(e[0]===0&&(e[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(t)}fromBER(t,e,n){let o=super.fromBER(t,e,n);return o===-1||this.setValueHex(),o}toBER(t){return t?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let t=this.valueHexView.length*8-1,e=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case t:e=Pm(Yl(n),e),i="-";break;default:e=Dm(e,Yl(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(i+=Xl.charAt(e[c]));return a===!1&&(i+=Xl.charAt(0)),i}};cu=vn;vn.NAME="IntegerValueBlock";Object.defineProperty(cu.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var lu,kt=class r extends Ct{constructor(t={}){super(t,vn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Bo(),BigInt(this.valueBlock.toString())}static fromBigInt(t){Bo();let e=BigInt(t),n=new xn,o=e.toString(16).replace(/^-/,""),s=new Uint8Array(G.Convert.FromHex(o));if(e<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${G.Convert.ToHex(a)}`)+e,u=G.BufferSourceConverter.toUint8Array(G.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let t=new r({valueHex:this.valueBlock.valueHexView});return t.valueBlock.toDER(),t}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};lu=kt;P.Integer=lu;kt.NAME="INTEGER";var uu,Ho=class extends kt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};uu=Ho;P.Enumerated=uu;Ho.NAME="ENUMERATED";var Sn=class extends ke(Rt){constructor({valueDec:t=-1,isFirstSid:e=!1,...n}={}){super(n),this.valueDec=t,this.isFirstSid=e}fromBER(t,e,n){if(!n)return e;let o=G.BufferSourceConverter.toUint8Array(t);if(!Ce(this,o,e,n))return-1;let s=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=hr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){Bo();let e=BigInt(t).toString(2);for(;e.length%7;)e="0"+e;let n=new Uint8Array(e.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(e.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=Ge(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",ie;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let t="";if(this.isHexOnly)t=G.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let e=this.valueDec;this.valueDec<=39?t="0.":this.valueDec<=79?(t="1.",e-=40):(t="2.",e-=80),t+=e.toString()}else t=this.valueDec.toString();return t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Sn.NAME="sidBlock";var Mo=class extends Rt{constructor({value:t=Mr,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new Sn;if(o=s.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(t){let e=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(t);if(o.byteLength===0)return this.error=this.value[n].error,ie;e.push(o)}return Aa(e)}fromString(t){this.value=[];let e=0,n=0,o="",s=!1;do if(n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new Sn;if(o>Number.MAX_SAFE_INTEGER){Bo();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e?(o=`{${o}}`,this.value[n].isFirstSid?t=`2.{${o} - 80}`:t+=o):t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};Mo.NAME="ObjectIdentifierValueBlock";var fu,Hr=class extends Ct{constructor(t={}){super(t,Mo),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};fu=Hr;P.ObjectIdentifier=fu;Hr.NAME="OBJECT IDENTIFIER";var An=class extends ke(Ae){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let o=G.BufferSourceConverter.toUint8Array(t);if(!Ce(this,o,e,n))return-1;let s=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=hr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=Ge(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",ie;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let t="";return this.isHexOnly?t=G.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};An.NAME="relativeSidBlock";var Vo=class extends Rt{constructor({value:t=Mr,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new An;if(o=s.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(t,e){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(t);if(s.byteLength===0)return this.error=this.value[o].error,ie;n.push(s)}return Aa(n)}fromString(t){this.value=[];let e=0,n=0,o="";do{n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1;let s=new An;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e&&(o=`{${o}}`),t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};Vo.NAME="RelativeObjectIdentifierValueBlock";var hu,Fo=class extends Ct{constructor(t={}){super(t,Vo),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};hu=Fo;P.RelativeObjectIdentifier=hu;Fo.NAME="RelativeObjectIdentifier";var du,Be=class extends je{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};du=Be;P.Sequence=du;Be.NAME="SEQUENCE";var pu,Ko=class extends je{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};pu=Ko;P.Set=pu;Ko.NAME="SET";var $o=class extends ke(Rt){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=Mr}toJSON(){return{...super.toJSON(),value:this.value}}};$o.NAME="StringValueBlock";var Wo=class extends $o{};Wo.NAME="SimpleStringValueBlock";var Pt=class extends ko{constructor({...t}={}){super(t,Wo)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,G.BufferSourceConverter.toUint8Array(t))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);this.valueBlock.value=t}};Pt.NAME="SIMPLE STRING";var qo=class extends Pt{fromBuffer(t){this.valueBlock.valueHexView=G.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=G.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=G.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(G.Convert.FromUtf8String(t)),this.valueBlock.value=t}};qo.NAME="Utf8StringValueBlock";var mu,Ie=class extends qo{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};mu=Ie;P.Utf8String=mu;Ie.NAME="UTF8String";var zo=class extends Pt{fromBuffer(t){this.valueBlock.value=G.Convert.ToUtf16String(t),this.valueBlock.valueHexView=G.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(G.Convert.FromUtf16String(t))}};zo.NAME="BmpStringValueBlock";var gu,Go=class extends zo{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};gu=Go;P.BmpString=gu;Go.NAME="BMPString";var jo=class extends Pt{fromBuffer(t){let e=ArrayBuffer.isView(t)?t.slice().buffer:t.slice(0),n=new Uint8Array(e);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(e))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e*4);for(let o=0;o<e;o++){let s=Ge(t.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=t}};jo.NAME="UniversalStringValueBlock";var wu,Zo=class extends jo{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};wu=Zo;P.UniversalString=wu;Zo.NAME="UniversalString";var yu,Xo=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};yu=Xo;P.NumericString=yu;Xo.NAME="NumericString";var bu,Yo=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};bu=Yo;P.PrintableString=bu;Yo.NAME="PrintableString";var xu,Jo=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};xu=Jo;P.TeletexString=xu;Jo.NAME="TeletexString";var Eu,Qo=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Eu=Qo;P.VideotexString=Eu;Qo.NAME="VideotexString";var vu,ts=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};vu=ts;P.IA5String=vu;ts.NAME="IA5String";var Su,es=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Su=es;P.GraphicString=Su;es.NAME="GraphicString";var Au,Bn=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Au=Bn;P.VisibleString=Au;Bn.NAME="VisibleString";var Bu,rs=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Bu=rs;P.GeneralString=Bu;rs.NAME="GeneralString";var Iu,ns=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Iu=ns;P.CharacterString=Iu;ns.NAME="CharacterString";var Cu,In=class extends Bn{constructor({value:t,valueDate:e,...n}={}){if(super(n),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(let o=0;o<t.length;o++)this.valueBlock.valueHexView[o]=t.charCodeAt(o)}e&&(this.fromDate(e),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(t){this.fromString(String.fromCharCode.apply(null,G.BufferSourceConverter.toUint8Array(t)))}toBuffer(){let t=this.toString(),e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return e}fromDate(t){this.year=t.getUTCFullYear(),this.month=t.getUTCMonth()+1,this.day=t.getUTCDate(),this.hour=t.getUTCHours(),this.minute=t.getUTCMinutes(),this.second=t.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(t){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(t);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(t="iso"){if(t==="iso"){let e=new Array(7);return e[0]=Kt(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=Kt(this.month,2),e[2]=Kt(this.day,2),e[3]=Kt(this.hour,2),e[4]=Kt(this.minute,2),e[5]=Kt(this.second,2),e[6]="Z",e.join("")}return super.toString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};Cu=In;P.UTCTime=Cu;In.NAME="UTCTime";var ku,os=class extends In{constructor(t={}){var e;super(t),(e=this.millisecond)!==null&&e!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(t){super.fromDate(t),this.millisecond=t.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(t){let e=!1,n="",o="",s=0,i,a=0,c=0;if(t[t.length-1]==="Z")n=t.substring(0,t.length-1),e=!0;else{let f=new Number(t[t.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=t}if(e){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,d=n.indexOf("+"),m="";if(d===-1&&(d=n.indexOf("-"),f=-1),d!==-1){if(m=n.substring(d+1),n=n.substring(0,d),m.length!==2&&m.length!==4)throw new Error("Wrong input string for conversion");let x=parseInt(m.substring(0,2),10);if(isNaN(x.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*x,m.length===4){if(x=parseInt(m.substring(2,4),10),isNaN(x.valueOf()))throw new Error("Wrong input string for conversion");c=f*x}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let f=new Number(`0${n.substring(l)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");s=f.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;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 o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=1e3*s;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=i.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(e===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(t="iso"){if(t==="iso"){let e=[];return e.push(Kt(this.year,4)),e.push(Kt(this.month,2)),e.push(Kt(this.day,2)),e.push(Kt(this.hour,2)),e.push(Kt(this.minute,2)),e.push(Kt(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(Kt(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};ku=os;P.GeneralizedTime=ku;os.NAME="GeneralizedTime";var Tu,ss=class extends Ie{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Tu=ss;P.DATE=Tu;ss.NAME="DATE";var Nu,is=class extends Ie{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Nu=is;P.TimeOfDay=Nu;is.NAME="TimeOfDay";var Lu,as=class extends Ie{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Lu=as;P.DateTime=Lu;as.NAME="DateTime";var _u,cs=class extends Ie{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};_u=cs;P.Duration=_u;cs.NAME="Duration";var Ru,ls=class extends Ie{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Ru=ls;P.TIME=Ru;ls.NAME="TIME";function Q(r,t="utf8"){let e=bo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Cn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},fs=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Uu={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new fs("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Ze=Uu;async function Du(r){let t=await Ze.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await Hm(t);return{privateKey:e[0],publicKey:e[1]}}async function Pu(r,t){let e=await Ze.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ze.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Ou(r,t,e){let n=await Ze.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ze.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function Hm(r){if(r.privateKey==null||r.publicKey==null)throw new et("Private and public key are required");return Promise.all([Ze.get().subtle.exportKey("jwk",r.privateKey),Ze.get().subtle.exportKey("jwk",r.publicKey)])}function Ca(r){if(r.kty!=="RSA")throw new et("invalid key type");if(r.n==null)throw new et("invalid key modulus");return rt(r.n,"base64url").length*8}var Vr=class{type="RSA";_key;_raw;_multihash;constructor(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=kn.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return Bt.createV1(114,this._multihash)}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Dt(this.raw,t.raw)}verify(t,e){return Ou(this._key,e,t)}},Tn=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=kn.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Dt(this.raw,t.raw)}sign(t){return Pu(this._key,t)}};var hs=8192,ka=18;function Hu(r){let{result:t}=Ia(r),e=t.valueBlock.value;return{n:he(e[1]),e:he(e[2]),d:he(e[3]),p:he(e[4]),q:he(e[5]),dp:he(e[6]),dq:he(e[7]),qi:he(e[8]),kty:"RSA",alg:"RS256"}}function Mm(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new et("JWK was missing components");let e=new Be({value:[new kt({value:0}),kt.fromBigInt(de(rt(r.n,"base64url"))),kt.fromBigInt(de(rt(r.e,"base64url"))),kt.fromBigInt(de(rt(r.d,"base64url"))),kt.fromBigInt(de(rt(r.p,"base64url"))),kt.fromBigInt(de(rt(r.q,"base64url"))),kt.fromBigInt(de(rt(r.dp,"base64url"))),kt.fromBigInt(de(rt(r.dq,"base64url"))),kt.fromBigInt(de(rt(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function Mu(r){let{result:t}=Ia(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:he(e[0]),e:he(e[1])}}function Ta(r){if(r.n==null||r.e==null)throw new et("JWK was missing components");let e=new Be({value:[new Be({value:[new Hr({value:"1.2.840.113549.1.1.1"}),new Pr]}),new Or({valueHex:new Be({value:[kt.fromBigInt(de(rt(r.n,"base64url"))),kt.fromBigInt(de(rt(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function he(r){let t=r.valueBlock.valueHexView;for(;t[0]===0;)t=t.subarray(1);return Q(t,"base64url")}function de(r){let t=[];return r.forEach(function(e){let n=e.toString(16);n.length%2>0&&(n=`0${n}`),t.push(n)}),BigInt("0x"+t.join(""))}function Vu(r){let t=Hu(r);return Fu(t)}function Na(r){let t=Mu(r);if(Ca(t)>hs)throw new vr("Key size is too large");let e=ue(le.encode({Type:vt.RSA,Data:r})),n=Vt(ka,e);return new Vr(t,n)}function Fu(r){if(Ca(r)>hs)throw new et("Key size is too large");let t=$u(r),e=ue(le.encode({Type:vt.RSA,Data:Ta(t.publicKey)})),n=Vt(ka,e);return new Tn(t.privateKey,new Vr(t.publicKey,n))}async function Ku(r){if(r>hs)throw new et("Key size is too large");let t=await Du(r),e=ue(le.encode({Type:vt.RSA,Data:Ta(t.publicKey)})),n=Vt(ka,e);return new Tn(t.privateKey,new Vr(t.publicKey,n))}function $u(r){if(r==null)throw new et("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var ds=class extends Tr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,cn(t);let n=He(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(t){return kr(this),this.iHash.update(t),this}digestInto(t){kr(this),Cr(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Fr=(r,t,e)=>new ds(r,t).update(e).digest();Fr.create=(r,t)=>new ds(r,t);function Wu(r){r.lowS!==void 0&&Jt("lowS",r.lowS),r.prehash!==void 0&&Jt("prehash",r.prehash)}function Vm(r){let t=hn(r);Gt(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:Fm,hexToBytes:Km}=uo,Te={Err:class extends Error{constructor(t=""){super(t)}},_tlv:{encode:(r,t)=>{let{Err:e}=Te;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=or(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?or(o.length/2|128):"";return`${or(r)}${s}${o}${t}`},decode(r,t){let{Err:e}=Te,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=Te;if(r<Ne)throw new t("integer: negative integers are not allowed");let e=or(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected assertion");return e},decode(r){let{Err:t}=Te;if(r[0]&128)throw new t("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return Fm(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Te,o=typeof r=="string"?Km(r):r;Lr(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("Invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("Invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=Te,n=`${t.encode(2,e.encode(r.r))}${t.encode(2,e.encode(r.s))}`;return t.encode(48,n)}},Ne=BigInt(0),St=BigInt(1),Ex=BigInt(2),qu=BigInt(3),vx=BigInt(4);function $m(r){let t=Vm(r),{Fp:e}=t,n=$e(t.n,t.nBitLength),o=t.toBytes||((g,h,w)=>{let b=h.toAffine();return ve(Uint8Array.from([4]),e.toBytes(b.x),e.toBytes(b.y))}),s=t.fromBytes||(g=>{let h=g.subarray(1),w=e.fromBytes(h.subarray(0,e.BYTES)),b=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:w,y:b}});function i(g){let{a:h,b:w}=t,b=e.sqr(g),p=e.mul(b,g);return e.add(e.add(p,e.mul(g,h)),w)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return un(g,St,t.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:w,wrapPrivateKey:b,n:p}=t;if(h&&typeof g!="bigint"){if(Fe(g)&&(g=be(g)),typeof g!="string"||!h.includes(g.length))throw new Error("Invalid key");g=g.padStart(w*2,"0")}let B;try{B=typeof g=="bigint"?g:xe(at("private key",g,w))}catch{throw new Error(`private key must be ${w} bytes, hex or bigint, not ${typeof g}`)}return b&&(B=Y(B,p)),It("private key",B,St,p),B}function l(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let u=ir((g,h)=>{let{px:w,py:b,pz:p}=g;if(e.eql(p,e.ONE))return{x:w,y:b};let B=g.is0();h==null&&(h=B?e.ONE:e.inv(p));let L=e.mul(w,h),N=e.mul(b,h),A=e.mul(p,h);if(B)return{x:e.ZERO,y:e.ZERO};if(!e.eql(A,e.ONE))throw new Error("invZ was invalid");return{x:L,y:N}}),f=ir(g=>{if(g.is0()){if(t.allowInfinityPoint&&!e.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:h,y:w}=g.toAffine();if(!e.isValid(h)||!e.isValid(w))throw new Error("bad point: x or y not FE");let b=e.sqr(w),p=i(h);if(!e.eql(b,p))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,w,b){if(this.px=h,this.py=w,this.pz=b,h==null||!e.isValid(h))throw new Error("x required");if(w==null||!e.isValid(w))throw new Error("y required");if(b==null||!e.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:w,y:b}=h||{};if(!h||!e.isValid(w)||!e.isValid(b))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let p=B=>e.eql(B,e.ZERO);return p(w)&&p(b)?d.ZERO:new d(w,b,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let w=e.invertBatch(h.map(b=>b.pz));return h.map((b,p)=>b.toAffine(w[p])).map(d.fromAffine)}static fromHex(h){let w=d.fromAffine(s(at("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,w){return po(d,n,h,w)}_setWindowSize(h){x.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:w,py:b,pz:p}=this,{px:B,py:L,pz:N}=h,A=e.eql(e.mul(w,N),e.mul(B,p)),k=e.eql(e.mul(b,N),e.mul(L,p));return A&&k}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:w}=t,b=e.mul(w,qu),{px:p,py:B,pz:L}=this,N=e.ZERO,A=e.ZERO,k=e.ZERO,I=e.mul(p,p),V=e.mul(B,B),_=e.mul(L,L),H=e.mul(p,B);return H=e.add(H,H),k=e.mul(p,L),k=e.add(k,k),N=e.mul(h,k),A=e.mul(b,_),A=e.add(N,A),N=e.sub(V,A),A=e.add(V,A),A=e.mul(N,A),N=e.mul(H,N),k=e.mul(b,k),_=e.mul(h,_),H=e.sub(I,_),H=e.mul(h,H),H=e.add(H,k),k=e.add(I,I),I=e.add(k,I),I=e.add(I,_),I=e.mul(I,H),A=e.add(A,I),_=e.mul(B,L),_=e.add(_,_),I=e.mul(_,H),N=e.sub(N,I),k=e.mul(_,V),k=e.add(k,k),k=e.add(k,k),new d(N,A,k)}add(h){l(h);let{px:w,py:b,pz:p}=this,{px:B,py:L,pz:N}=h,A=e.ZERO,k=e.ZERO,I=e.ZERO,V=t.a,_=e.mul(t.b,qu),H=e.mul(w,B),K=e.mul(b,L),C=e.mul(p,N),T=e.add(w,b),E=e.add(B,L);T=e.mul(T,E),E=e.add(H,K),T=e.sub(T,E),E=e.add(w,p);let y=e.add(B,N);return E=e.mul(E,y),y=e.add(H,C),E=e.sub(E,y),y=e.add(b,p),A=e.add(L,N),y=e.mul(y,A),A=e.add(K,C),y=e.sub(y,A),I=e.mul(V,E),A=e.mul(_,C),I=e.add(A,I),A=e.sub(K,I),I=e.add(K,I),k=e.mul(A,I),K=e.add(H,H),K=e.add(K,H),C=e.mul(V,C),E=e.mul(_,E),K=e.add(K,C),C=e.sub(H,C),C=e.mul(V,C),E=e.add(E,C),H=e.mul(K,E),k=e.add(k,H),H=e.mul(y,E),A=e.mul(T,A),A=e.sub(A,H),H=e.mul(T,K),I=e.mul(y,I),I=e.add(I,H),new d(A,k,I)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return x.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){It("scalar",h,Ne,t.n);let w=d.ZERO;if(h===Ne)return w;if(h===St)return this;let{endo:b}=t;if(!b)return x.unsafeLadder(this,h);let{k1neg:p,k1:B,k2neg:L,k2:N}=b.splitScalar(h),A=w,k=w,I=this;for(;B>Ne||N>Ne;)B&St&&(A=A.add(I)),N&St&&(k=k.add(I)),I=I.double(),B>>=St,N>>=St;return p&&(A=A.negate()),L&&(k=k.negate()),k=new d(e.mul(k.px,b.beta),k.py,k.pz),A.add(k)}multiply(h){let{endo:w,n:b}=t;It("scalar",h,St,b);let p,B;if(w){let{k1neg:L,k1:N,k2neg:A,k2:k}=w.splitScalar(h),{p:I,f:V}=this.wNAF(N),{p:_,f:H}=this.wNAF(k);I=x.constTimeNegate(L,I),_=x.constTimeNegate(A,_),_=new d(e.mul(_.px,w.beta),_.py,_.pz),p=I.add(_),B=V.add(H)}else{let{p:L,f:N}=this.wNAF(h);p=L,B=N}return d.normalizeZ([p,B])[0]}multiplyAndAddUnsafe(h,w,b){let p=d.BASE,B=(N,A)=>A===Ne||A===St||!N.equals(p)?N.multiplyUnsafe(A):N.multiply(A),L=B(this,w).add(B(h,b));return L.is0()?void 0:L}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:w}=t;if(h===St)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:w}=t;return h===St?this:w?w(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return Jt("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return Jt("isCompressed",h),be(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let m=t.nBitLength,x=ho(d,t.endo?Math.ceil(m/2):m);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function Wm(r){let t=hn(r);return Gt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function zu(r){let t=Wm(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(C){return Y(C,n)}function a(C){return fo(C,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=$m({...t,toBytes(C,T,E){let y=T.toAffine(),S=e.toBytes(y.x),v=ve;return Jt("isCompressed",E),E?v(Uint8Array.from([T.hasEvenY()?2:3]),S):v(Uint8Array.from([4]),S,e.toBytes(y.y))},fromBytes(C){let T=C.length,E=C[0],y=C.subarray(1);if(T===o&&(E===2||E===3)){let S=xe(y);if(!un(S,St,e.ORDER))throw new Error("Point is not on curve");let v=u(S),R;try{R=e.sqrt(v)}catch($){let W=$ instanceof Error?": "+$.message:"";throw new Error("Point is not on curve"+W)}let D=(R&St)===St;return(E&1)===1!==D&&(R=e.neg(R)),{x:S,y:R}}else if(T===s&&E===4){let S=e.fromBytes(y.subarray(0,e.BYTES)),v=e.fromBytes(y.subarray(e.BYTES,2*e.BYTES));return{x:S,y:v}}else throw new Error(`Point of length ${T} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),d=C=>be(Ke(C,t.nByteLength));function m(C){let T=n>>St;return C>T}function x(C){return m(C)?i(-C):C}let g=(C,T,E)=>xe(C.slice(T,E));class h{constructor(T,E,y){this.r=T,this.s=E,this.recovery=y,this.assertValidity()}static fromCompact(T){let E=t.nByteLength;return T=at("compactSignature",T,E*2),new h(g(T,0,E),g(T,E,2*E))}static fromDER(T){let{r:E,s:y}=Te.toSig(at("DER",T));return new h(E,y)}assertValidity(){It("r",this.r,St,n),It("s",this.s,St,n)}addRecoveryBit(T){return new h(this.r,this.s,T)}recoverPublicKey(T){let{r:E,s:y,recovery:S}=this,v=N(at("msgHash",T));if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");let R=S===2||S===3?E+t.n:E;if(R>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let D=S&1?"03":"02",M=c.fromHex(D+d(R)),$=a(R),W=i(-v*$),z=i(y*$),j=c.BASE.multiplyAndAddUnsafe(M,W,z);if(!j)throw new Error("point at infinify");return j.assertValidity(),j}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return sr(this.toDERHex())}toDERHex(){return Te.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return sr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let w={isValidPrivateKey(C){try{return l(C),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let C=Hi(t.n);return vl(t.randomBytes(C),t.n)},precompute(C=8,T=c.BASE){return T._setWindowSize(C),T.multiply(BigInt(3)),T}};function b(C,T=!0){return c.fromPrivateKey(C).toRawBytes(T)}function p(C){let T=Fe(C),E=typeof C=="string",y=(T||E)&&C.length;return T?y===o||y===s:E?y===2*o||y===2*s:C instanceof c}function B(C,T,E=!0){if(p(C))throw new Error("first arg must be private key");if(!p(T))throw new Error("second arg must be public key");return c.fromHex(T).multiply(l(C)).toRawBytes(E)}let L=t.bits2int||function(C){let T=xe(C),E=C.length*8-t.nBitLength;return E>0?T>>BigInt(E):T},N=t.bits2int_modN||function(C){return i(L(C))},A=fn(t.nBitLength);function k(C){return It(`num < 2^${t.nBitLength}`,C,Ne,A),Ke(C,t.nByteLength)}function I(C,T,E=V){if(["recovered","canonical"].some(it=>it in E))throw new Error("sign() legacy options not supported");let{hash:y,randomBytes:S}=t,{lowS:v,prehash:R,extraEntropy:D}=E;v==null&&(v=!0),C=at("msgHash",C),Wu(E),R&&(C=at("prehashed msgHash",y(C)));let M=N(C),$=l(T),W=[k($),k(M)];if(D!=null&&D!==!1){let it=D===!0?S(e.BYTES):D;W.push(at("extraEntropy",it))}let z=ve(...W),j=M;function st(it){let ut=L(it);if(!f(ut))return;let Ut=a(ut),yt=c.BASE.multiply(ut).toAffine(),Mt=i(yt.x);if(Mt===Ne)return;let pe=i(Ut*i(j+Mt*$));if(pe===Ne)return;let tn=(yt.x===Mt?0:2)|Number(yt.y&St),en=pe;return v&&m(pe)&&(en=x(pe),tn^=1),new h(Mt,en,tn)}return{seed:z,k2sig:st}}let V={lowS:t.lowS,prehash:!1},_={lowS:t.lowS,prehash:!1};function H(C,T,E=V){let{seed:y,k2sig:S}=I(C,T,E),v=t;return Ri(v.hash.outputLen,v.nByteLength,v.hmac)(y,S)}c.BASE._setWindowSize(8);function K(C,T,E,y=_){let S=C;if(T=at("msgHash",T),E=at("publicKey",E),"strict"in y)throw new Error("options.strict was renamed to lowS");Wu(y);let{lowS:v,prehash:R}=y,D,M;try{if(typeof S=="string"||Fe(S))try{D=h.fromDER(S)}catch(yt){if(!(yt instanceof Te.Err))throw yt;D=h.fromCompact(S)}else if(typeof S=="object"&&typeof S.r=="bigint"&&typeof S.s=="bigint"){let{r:yt,s:Mt}=S;D=new h(yt,Mt)}else throw new Error("PARSE");M=c.fromHex(E)}catch(yt){if(yt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(v&&D.hasHighS())return!1;R&&(T=t.hash(T));let{r:$,s:W}=D,z=N(T),j=a(W),st=i(z*j),it=i($*j),ut=c.BASE.multiplyAndAddUnsafe(M,st,it)?.toAffine();return ut?i(ut.x)===$:!1}return{CURVE:t,getPublicKey:b,getSharedSecret:B,sign:H,verify:K,ProjectivePoint:c,Signature:h,utils:w}}function qm(r){return{hash:r,hmac:(t,...e)=>Fr(r,t,Bi(...e)),randomBytes:ln}}function Gu(r,t){let e=n=>zu({...r,...qm(n)});return Object.freeze({...e(t),create:e})}var Xu=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),ju=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),zm=BigInt(1),La=BigInt(2),Zu=(r,t)=>(r+t/La)/t;function Gm(r){let t=Xu,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=ct(u,e,t)*u%t,d=ct(f,e,t)*u%t,m=ct(d,La,t)*l%t,x=ct(m,o,t)*m%t,g=ct(x,s,t)*x%t,h=ct(g,a,t)*g%t,w=ct(h,c,t)*h%t,b=ct(w,a,t)*g%t,p=ct(b,e,t)*u%t,B=ct(p,i,t)*x%t,L=ct(B,n,t)*l%t,N=ct(L,La,t);if(!_a.eql(_a.sqr(N),r))throw new Error("Cannot find square root");return N}var _a=$e(Xu,void 0,void 0,{sqrt:Gm}),dr=Gu({a:BigInt(0),b:BigInt(7),Fp:_a,n:ju,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=ju,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-zm*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=Zu(s*r,t),c=Zu(-n*r,t),l=Y(r-a*e-c*o,t),u=Y(-a*n-c*s,t),f=l>i,d=u>i;if(f&&(l=t-l),d&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},ue),Lx=BigInt(0);var _x=dr.ProjectivePoint;function At(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=Et(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}function Yu(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Ju(r,t,e){let n=gn.digest(e instanceof Uint8Array?e:e.subarray());if(Yu(n))return n.then(({digest:o})=>dr.verify(t,o,r)).catch(o=>{throw new Cn(String(o))});try{return dr.verify(t,n.digest,r)}catch(o){throw new Cn(String(o))}}var ps=class{type="secp256k1";raw;_key;constructor(t){this._key=tf(t),this.raw=Qu(this._key)}toMultihash(){return we.digest(Rr(this))}toCID(){return Bt.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Dt(this.raw,t.raw)}verify(t,e){return Ju(this._key,e,t)}};function Ra(r){return new ps(r)}function Qu(r){return dr.ProjectivePoint.fromHex(r).toRawBytes(!0)}function tf(r){try{return dr.ProjectivePoint.fromHex(r),r}catch(t){throw new vr(String(t))}}function Nn(r){let{Type:t,Data:e}=le.decode(r),n=e??new Uint8Array;switch(t){case vt.RSA:return Na(n);case vt.Ed25519:return $i(n);case vt.secp256k1:return Ra(n);default:throw new er}}function ef(r){let{Type:t,Data:e}=le.decode(r.digest),n=e??new Uint8Array;switch(t){case vt.Ed25519:return $i(n);case vt.secp256k1:return Ra(n);default:throw new er}}function Rr(r){return le.encode({Type:vt[r.type],Data:r.raw})}var rf=Symbol.for("nodejs.util.inspect.custom"),Zm=114,Ln=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[di]=!0;toString(){return this.string==null&&(this.string=ot.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Bt.createV1(Zm,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Dt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Dt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[rf](){return`PeerId(${this.toString()})`}},_n=class extends Ln{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Rn=class extends Ln{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Un=class extends Ln{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Xm=2336,ms=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=we.digest(rt(this.url))}[rf](){return`PeerId(${this.url})`}[di]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Bt.createV1(Xm,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=Q(t)),t.toString()===this.toString())}};function Kr(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Oe(ot.decode(`z${r}`));else{if(t==null)throw new et('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Oe(t.decode(r))}return Ym(e)}function Ua(r){if(r.type==="Ed25519")return new Rn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Un({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new _n({multihash:r.toCID().multihash,publicKey:r});throw new er}function Ym(r){if(Qm(r))return new _n({multihash:r});if(Jm(r))try{let t=ef(r);if(t.type==="Ed25519")return new Rn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Un({multihash:r,publicKey:t})}catch{let e=Q(r.digest);return new ms(new URL(e))}throw new to("Supplied PeerID Multihash is invalid")}function Jm(r){return r.code===we.code}function Qm(r){return r.code===gn.code}var gs=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=t,s+=u,s>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var nf=45,e0=15,$r=new gs;function Da(r){if(!(r.length>e0))return $r.new(r).parseWith(()=>$r.readIPv4Addr())}function Pa(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>nf))return $r.new(r).parseWith(()=>$r.readIPv6Addr())}function ws(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>nf))return $r.new(r).parseWith(()=>$r.readIPAddr())}var z1=parseInt("0xFFFF",16),G1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function ys(r){return!!Da(r)}function bs(r){return!!Pa(r)}function xs(r){return!!ws(r)}var af=ys,i0=bs,Oa=function(r){let t=0;if(r=r.toString().trim(),af(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(i0(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=af(e[n]),i;s&&(i=Oa(e[n]),e[n]=Q(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,Q(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let s=parseInt(e[n],16);o[t++]=s>>8&255,o[t++]=s&255}return o}throw new Error("invalid ip address")},cf=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Wr={},Ha={},c0=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"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,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];c0.forEach(r=>{let t=l0(...r);Ha[t.code]=t,Wr[t.name]=t});function l0(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function tt(r){if(typeof r=="number"){if(Ha[r]!=null)return Ha[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Wr[r]!=null)return Wr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var N2=tt("ip4"),L2=tt("ip6"),_2=tt("ipcidr");function Ka(r,t){switch(tt(r).code){case 4:case 41:return f0(t);case 42:return Fa(t);case 6:case 273:case 33:case 132:return ff(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Fa(t);case 421:return m0(t);case 444:return uf(t);case 445:return uf(t);case 466:return p0(t);case 481:return globalThis.encodeURIComponent(Fa(t));default:return Q(t,"base16")}}function $a(r,t){switch(tt(r).code){case 4:return lf(t);case 41:return lf(t);case 42:return Va(t);case 6:case 273:case 33:case 132:return Wa(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Va(t);case 421:return h0(t);case 444:return g0(t);case 445:return w0(t);case 466:return d0(t);case 481:return Va(globalThis.decodeURIComponent(t));default:return rt(t,"base16")}}var Ma=Object.values(lr).map(r=>r.decoder),u0=function(){let r=Ma[0].or(Ma[1]);return Ma.slice(2).forEach(t=>r=r.or(t)),r}();function lf(r){if(!xs(r))throw new Error("invalid ip address");return Oa(r)}function f0(r){let t=cf(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!xs(t))throw new Error("invalid ip address");return t}function Wa(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function ff(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Va(r){let t=rt(r),e=Uint8Array.from(ce(t.length));return At([e,t],e.length+t.length)}function Fa(r){let t=ee(r);if(r=r.slice(lt(t)),r.length!==t)throw new Error("inconsistent lengths");return Q(r)}function h0(r){let t;r[0]==="Q"||r[0]==="1"?t=Oe(ot.decode(`z${r}`)).bytes:t=Bt.parse(r).multihash.bytes;let e=Uint8Array.from(ce(t.length));return At([e,t],e.length+t.length)}function d0(r){let t=u0.decode(r),e=Uint8Array.from(ce(t.length));return At([e,t],e.length+t.length)}function p0(r){let t=ee(r),e=r.slice(lt(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+Q(e,"base64url")}function m0(r){let t=ee(r),e=r.slice(lt(t));if(e.length!==t)throw new Error("inconsistent lengths");return Q(e,"base58btc")}function g0(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=ge.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Wa(n);return At([e,o],e.length+o.length)}function w0(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=ge.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Wa(n);return At([e,o],e.length+o.length)}function uf(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=Q(t,"base32"),o=ff(e);return`${n}:${o}`}function hf(r){r=qa(r);let t=[],e=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=tt(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw pf("invalid address: "+r);if(a.path===!0){n=qa(o.slice(s).join("/")),t.push([a.code,$a(a.code,n)]),e.push([a.code,n]);break}let c=$a(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Ka(a.code,c)])}return{string:df(e),bytes:Ga(t),tuples:t,stringTuples:e,path:n}}function za(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=ee(r,o),i=lt(s),a=tt(s),c=y0(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let l=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw pf("Invalid address Uint8Array: "+Q(r,"base16"));t.push([s,l]);let u=Ka(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:df(e),tuples:t,stringTuples:e,path:n}}function df(r){let t=[];return r.map(e=>{let n=tt(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),qa(t.join("/"))}function Ga(r){return At(r.map(t=>{let e=tt(t[0]),n=Uint8Array.from(ce(e.code));return t.length>1&&t[1]!=null&&(n=At([n,t[1]])),n}))}function y0(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=ee(t instanceof Uint8Array?t:Uint8Array.from(t));return e+lt(e)}}function qa(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function pf(r){return new Error("Error parsing address: "+r)}var b0=Symbol.for("nodejs.util.inspect.custom"),Za=Symbol.for("@multiformats/js-multiaddr/multiaddr"),x0=[tt("dns").code,tt("dns4").code,tt("dns6").code,tt("dnsaddr").code],ja=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},Es=class r{bytes;#t;#e;#r;#n;[Za]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=za(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=hf(t)}else if(gf(t))e=za(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="",i=tt("tcp"),a=tt("udp"),c=tt("ip4"),l=tt("ip6"),u=tt("dns6"),f=tt("ip6zone");for(let[m,x]of this.stringTuples())m===f.code&&(s=`%${x??""}`),x0.includes(m)&&(e=i.name,o=443,n=`${x??""}${s}`,t=m===u.code?6:4),(m===i.code||m===a.code)&&(e=tt(m).name,o=parseInt(x??"")),(m===c.code||m===l.code)&&(e=tt(m).name,n=`${x??""}${s}`,t=m===l.code?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}protos(){return this.#e.map(([t])=>Object.assign({},tt(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>tt(t).name)}tuples(){return this.#e}stringTuples(){return this.#r}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(Ga(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Wr.p2p.code&&t.push([n,o]),n===Wr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?Q(ot.decode(`z${n}`),"base58btc"):Q(Bt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return Dt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=mf.get(e.name);if(n==null)throw new ja(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>ae(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[b0](){return`Multiaddr(${this.#t})`}};var mf=new Map;function gf(r){return!!r?.[Za]}function ae(r){return new Es(r)}var E0=r=>r.toString().split("/").slice(1),qr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),Z=r=>({match:t=>qr(e=>e===r).match(t),pattern:r}),zr=()=>({match:r=>qr(t=>typeof t=="string").match(r),pattern:"{string}"}),Dn=()=>({match:r=>qr(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),ht=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ot.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Pn=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{sa.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),nt=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Ot=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),X=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function mt(...r){function t(o){let s=E0(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var Ss=X(Z("dns4"),zr()),As=X(Z("dns6"),zr()),Bs=X(Z("dnsaddr"),zr()),Ya=X(Z("dns"),zr()),aE=mt(Ss,nt(ht())),cE=mt(As,nt(ht())),lE=mt(Bs,nt(ht())),uE=mt(Ot(Ya,Bs,Ss,As),nt(ht())),wf=X(Z("ip4"),qr(ys)),yf=X(Z("ip6"),qr(bs)),Ja=Ot(wf,yf),Le=Ot(Ja,Ya,Ss,As,Bs),fE=mt(Ot(Ja,X(Ot(Ya,Bs,Ss,As),nt(ht())))),hE=mt(wf),dE=mt(yf),pE=mt(Ja),Qa=X(Le,Z("tcp"),Dn()),On=X(Le,Z("udp"),Dn()),mE=mt(X(Qa,nt(ht()))),gE=mt(On),tc=X(On,Z("quic")),Is=X(On,Z("quic-v1")),v0=Ot(tc,Is),wE=mt(tc),yE=mt(Is),Xa=Ot(Le,Qa,On,tc,Is),bf=Ot(X(Xa,Z("ws"),nt(ht()))),bE=mt(bf),xf=Ot(X(Xa,Z("wss"),nt(ht())),X(Xa,Z("tls"),nt(X(Z("sni"),zr())),Z("ws"),nt(ht()))),xE=mt(xf),Ef=X(On,Z("webrtc-direct"),nt(Pn()),nt(Pn()),nt(ht())),vf=mt(Ef),Sf=X(Is,Z("webtransport"),nt(Pn()),nt(Pn()),nt(ht())),EE=mt(Sf),vs=Ot(bf,xf,X(Qa,nt(ht())),X(v0,nt(ht())),X(Le,nt(ht())),Ef,Sf,ht()),vE=mt(vs),S0=X(vs,Z("p2p-circuit"),ht()),SE=mt(S0),A0=Ot(X(vs,Z("p2p-circuit"),Z("webrtc"),nt(ht())),X(vs,Z("webrtc"),nt(ht())),Z("webrtc")),Af=mt(A0),B0=Ot(X(Le,Z("tcp"),Dn(),Z("http"),nt(ht())),X(Le,Z("http"),nt(ht()))),AE=mt(B0),I0=Ot(X(Le,Z("tcp"),Ot(X(Z("443"),Z("http")),X(Dn(),Z("https"))),nt(ht())),X(Le,Z("tls"),Z("http"),nt(ht())),X(Le,Z("https"),nt(ht()))),BE=mt(I0);var Bf=function(r,t,e){if(e||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return r.concat(s||Array.prototype.slice.call(t))},C0=function(){function r(t,e,n){this.name=t,this.version=e,this.os=n,this.type="browser"}return r}();var k0=function(){function r(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return r}();var T0=function(){function r(t,e,n,o){this.name=t,this.version=e,this.os=n,this.bot=o,this.type="bot-device"}return r}();var N0=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var L0=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var _0=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,R0=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,If=3,U0=[["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",_0]],Cf=[["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/]];function Tf(r){return r?kf(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new L0:typeof navigator<"u"?kf(navigator.userAgent):O0()}function D0(r){return r!==""&&U0.reduce(function(t,e){var n=e[0],o=e[1];if(t)return t;var s=o.exec(r);return!!s&&[n,s]},!1)}function kf(r){var t=D0(r);if(!t)return null;var e=t[0],n=t[1];if(e==="searchbot")return new N0;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<If&&(o=Bf(Bf([],o,!0),H0(If-o.length),!0)):o=[];var s=o.join("."),i=P0(r),a=R0.exec(r);return a&&a[1]?new T0(e,s,i,a[1]):new C0(e,s,i)}function P0(r){for(var t=0,e=Cf.length;t<e;t++){var n=Cf[t],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function O0(){var r=typeof process<"u"&&process.version;return r?new k0(process.version.slice(1)):null}function H0(r){for(var t=[],e=0;e<r;e++)t.push("0");return t}function gt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var ec=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},rc=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Nf=r=>globalThis.DOMException===void 0?new rc(r):new DOMException(r),Lf=r=>{let t=r.reason===void 0?Nf("This operation was aborted."):r.reason;return t instanceof Error?t:Nf(t)};function pr(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,c=new Promise((l,u)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:d}=t;d.aborted&&u(Lf(d));let m=()=>{u(Lf(d))};d.addEventListener("abort",m,{once:!0}),r.finally(()=>{d.removeEventListener("abort",m)})}if(e===Number.POSITIVE_INFINITY){r.then(l,u);return}let f=new ec;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(d){u(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?u(o):(f.message=o??`Promise timed out after ${e} milliseconds`,u(f))},e),(async()=>{try{l(await r)}catch(d){u(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}var _f=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"];var Rf=Tf(),Hn=Rf!=null&&Rf.name==="firefox",Cs=async function*(){},ks=async r=>{},M0=30*1e3;function Uf(r,t,e=M0,n){r.readyState==="open"&&Promise.resolve().then(async()=>{if(r.bufferedAmount>0){n.log("%s drain channel with %d buffered bytes",t,r.bufferedAmount);let o=gt(),s=!1;r.bufferedAmountLowThreshold=0;let i=()=>{s||(n.log("%s drain channel closed before drain",t),o.resolve())};r.addEventListener("close",i,{once:!0}),r.addEventListener("bufferedamountlow",()=>{s=!0,r.removeEventListener("close",i),o.resolve()}),await pr(o.promise,{milliseconds:e})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function Mn(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??_f.map(t=>({urls:[t]})),r}var mr=class{log;peerConnection;remoteAddr;timeline;metrics;source=Cs();sink=ks;constructor(t,e){this.log=t.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=e.remoteAddr,this.timeline=e.timeline,this.peerConnection=e.peerConnection;let n=this.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",this.peerConnection.connectionState,"initial state",n),(this.peerConnection.connectionState==="disconnected"||this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.timeline.close=Date.now())}}async close(t){this.log.trace("closing connection"),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({close:!0})}abort(t){this.log.error("closing connection due to error",t),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({abort:!0})}};var Ts=class{buffer;mask;top;btm;next;constructor(t){if(!(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(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Gr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Ts(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new Ts(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var nc=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Xe(r={}){return V0(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function V0(r,t){t=t??{};let e=t.onEnd,n=new Gr,o,s,i,a=gt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,w)=>{s=b=>{s=null,n.push(b);try{h(r(n))}catch(p){w(p)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=gt()})}},l=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new Gr,s!=null?s({error:h}):(n.push({error:h}),o)),f=h=>{if(i)return o;if(t?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:h})},d=h=>i?o:(i=!0,h!=null?u(h):l({done:!0})),m=()=>(n=new Gr,d(),{done:!0}),x=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:x,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let w=h?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let b,p;w!=null&&(b=new Promise((B,L)=>{p=()=>{L(new nc)},w.addEventListener("abort",p)}));try{await Promise.race([a.promise,b])}finally{p!=null&&w!=null&&w?.removeEventListener("abort",p)}}},e==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(h){return g.throw(h),e!=null&&(e(h),e=void 0),{done:!0}},return(){return g.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(h){return g.end(h),e!=null&&(e(h),e=void 0),o},get readableLength(){return g.readableLength},onEmpty:h=>g.onEmpty(h)},o}var Ns=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function _e(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new Ns(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new Ns(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var Pf=Symbol.for("@achingbrain/uint8arraylist");function Df(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function Ls(r){return!!r?.[Pf]}var dt=class r{bufs;length;[Pf]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(Ls(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(Ls(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Df(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Df(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Ls(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return At(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:At(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Ls(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=e;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let m=this.get(f+d);if(n[d]!==m){u=Math.max(1,d-a[m]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=Et(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=xt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=xt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=xt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=Et(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=xt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=xt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=xt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=xt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=xt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Dt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};function Of(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function Hf(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Mf(r,t){let e=Of(r).return?.();Hf(e)&&e.catch(n=>{t.error("could not cause iterator to return",n)})}var F0=5e3;function oc(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var _s=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(t){this.sinkController=new AbortController,this.sinkEnd=gt(),this.closed=gt(),this.log=t.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=t.id,this.metadata=t.metadata??{},this.direction=t.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=t.sendCloseWriteTimeout??F0,this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=Xe({onEnd:e=>{e!=null?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(t){if(this.writeStatus!=="ready")throw new tr(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";let e={signal:this.sinkController.signal};if(this.direction==="outbound"){let o=this.sendNewStream(e);oc(o)&&await o}let n=()=>{Mf(t,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let o of t){o=o instanceof Uint8Array?new dt(o):o;let s=this.sendData(o,e);oc(s)&&(this.sendingData=gt(),await s,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",n)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(t){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(t){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(t){this.log.trace("closing gracefully"),this.status="closing",await _e(Promise.all([this.closeWrite(t),this.closeRead(t),this.closed.promise]),t?.signal),this.status="closed",this.log.trace("closed gracefully")}async closeRead(t={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let e=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(t)),e==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(t={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await _e(this.sink([]),t.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await _e(this.sendingData.promise,t.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await _e(this.sinkEnd.promise,t.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(t){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",t),this.log("try to send reset to remote");let e=this.sendReset();oc(e)&&e.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(t),this.onAbort?.(t)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let t=new Qn("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(t),this.onReset?.()}_closeSinkAndSource(t){this._closeSink(t),this._closeSource(t)}_closeSink(t){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(t)}_closeSource(t){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(t))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(t){this.streamSource.push(t)}sourceReadableLength(){return this.streamSource.readableLength}};function Rs(r){return r[Symbol.asyncIterator]!=null}var Us=r=>{let t=lt(r),e=Et(t);return ce(r,e),Us.bytes=t,e};Us.bytes=0;function Vn(r,t){t=t??{};let e=t.lengthEncoder??Us;function*n(o){let s=e(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Rs(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Vn.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Us;return new dt(e(r.byteLength),r)};var Ds=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ps=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Os=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Fn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var K0=8,$0=1024*1024*4,gr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(gr||(gr={}));var sc=r=>{let t=ee(r);return sc.bytes=lt(t),t};sc.bytes=0;function wr(r,t){let e=new dt,n=gr.LENGTH,o=-1,s=t?.lengthDecoder??sc,i=t?.maxLengthLength??K0,a=t?.maxDataLength??$0;function*c(){for(;e.byteLength>0;){if(n===gr.LENGTH)try{if(o=s(e),o<0)throw new Ds("Invalid message length");if(o>a)throw new Ps("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=gr.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Os("Message length length too long");break}throw l}if(n===gr.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=gr.LENGTH}}}return Rs(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Fn("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Fn("Unexpected end of input")}()}wr.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return wr(n,{...t??{},onLength:s=>{e=s}})};var q0=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function z0(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:u}=q0(r),f=(...m)=>{let x=e.multiArgs?m:m[0];e.filter&&!e.filter(x)||(c.push(x),e.count===c.length&&(n(),s(c)))},d=m=>{n(),i(m)};n=()=>{for(let m of a)u(m,f);for(let m of e.rejectionEvents)u(m,d)};for(let m of a)l(m,f);for(let m of e.rejectionEvents)l(m,d);e.signal&&e.signal.addEventListener("abort",()=>{d(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=pr(o,{milliseconds:e.timeout});return s.cancel=n,s}return o}function ic(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=z0(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var Ht;(function(r){let t;(function(o){o.FIN="FIN",o.STOP_SENDING="STOP_SENDING",o.RESET="RESET",o.FIN_ACK="FIN_ACK"})(t=r.Flag||(r.Flag={}));let e;(function(o){o[o.FIN=0]="FIN",o[o.STOP_SENDING=1]="STOP_SENDING",o[o.RESET=2]="RESET",o[o.FIN_ACK=3]="FIN_ACK"})(e||(e={})),function(o){o.codec=()=>fr(e)}(t=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=se((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.flag!=null&&(s.uint32(8),r.Flag.codec().encode(o.flag,s)),o.message!=null&&(s.uint32(18),s.bytes(o.message)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.flag=r.Flag.codec().decode(o);break}case 2:{a.message=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>oe(o,r.codec()),r.decode=(o,s)=>ne(o,r.codec(),s)})(Ht||(Ht={}));var G0=2*1024*1024,j0=30*1e3,Hs=16*1024;function Z0(r=Hs){let t=lt(r-lt(r)),e=1+lt(Object.keys(Ht.Flag).length-1),n=1,o=r-t-e-n,s=lt(o);return t+e+n+s}var X0=Z0(),Y0=5e3,J0=5e3,ac=class extends _s{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;constructor(t){let e=t.onEnd;switch(t.onEnd=o=>{this.log.trace("readable and writeable ends closed",this.status),Promise.resolve(async()=>{if(!(this.timeline.abort!=null||this.timeline.reset!==null))try{await pr(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(s){this.log.error("error receiving FIN_ACK",s)}}).then(()=>{this.incomingData.end(),e?.(o)}).catch(s=>{this.log.error("error ending stream",s)})},super(t),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=Xe(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??j0,this.maxBufferedAmount=t.maxBufferedAmount??G0,this.maxMessageSize=(t.maxMessageSize??Hs)-X0,this.receiveFinAck=gt(),this.finAckTimeout=t.closeTimeout??Y0,this.openTimeout=t.openTimeout??J0,this.channel.readyState){case"open":this.timeline.open=new Date().getTime();break;case"closed":case"closing":(this.timeline.close===void 0||this.timeline.close===0)&&(this.timeline.close=Date.now());break;case"connecting":break;default:throw this.log.error("unknown datachannel state %s",this.channel.readyState),new tr("Unknown datachannel state")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime()},this.channel.onclose=o=>{this.receiveFinAck.resolve(),this.close().catch(s=>{this.log.error("error closing stream after channel closed",s)})},this.channel.onerror=o=>{let s=o.error;this.abort(s)},this.channel.onmessage=async o=>{let{data:s}=o;s===null||s.byteLength===0||this.incomingData.push(new Uint8Array(s,0,s.byteLength))};let n=this;Promise.resolve().then(async()=>{for await(let o of wr(this.incomingData)){let s=n.processIncomingProtobuf(o);s!=null&&n.sourcePush(new dt(s))}}).catch(o=>{this.log.error("error processing incoming data channel messages",o)})}sendNewStream(){}async _sendMessage(t,e=!0){if(e&&this.channel.bufferedAmount>this.maxBufferedAmount)try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await ic(this.channel,"bufferedamountlow",{timeout:this.bufferedAmountLowEventTimeout})}catch(n){throw n instanceof rn?new rn(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`):n}if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new tr(`Invalid datachannel state - ${this.channel.readyState}`);this.channel.readyState!=="open"&&(this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await ic(this.channel,"open",{timeout:this.openTimeout}),this.log('channel state is now "%s", sending data',this.channel.readyState)),this.channel.send(t.subarray())}async sendData(t){for(t=t.sublist();t.byteLength>0;){let e=Math.min(t.byteLength,this.maxMessageSize),n=t.subarray(0,e),o=Ht.encode({message:n}),s=Vn.single(o);await this._sendMessage(s),t.consume(e)}}async sendReset(){await this._sendFlag(Ht.Flag.RESET)}async sendCloseWrite(t){if(await this._sendFlag(Ht.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await _e(this.receiveFinAck.promise,t?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorName:"FinAckNotReceivedError"})}catch(n){this.log.error("failed to await FIN_ACK",n)}}else this.log.trace("sending FIN failed, not awaiting FIN_ACK");this.receiveFinAck.resolve()}async sendCloseRead(){await this._sendFlag(Ht.Flag.STOP_SENDING)}processIncomingProtobuf(t){let e=Ht.decode(t);if(e.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',e.flag,this.writeStatus,this.readStatus),e.flag===Ht.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Ht.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),e.flag===Ht.Flag.RESET&&this.reset(),e.flag===Ht.Flag.STOP_SENDING&&this.remoteCloseRead(),e.flag===Ht.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),this.readStatus==="ready")return e.message}async _sendFlag(t){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',this.channel.readyState,t.toString()),!1;this.log.trace("sending flag %s",t.toString());let e=Ht.encode({flag:t}),n=Vn.single(e);try{return await this._sendMessage(n,!1),!0}catch(o){this.log.error("could not send flag %s",t.toString(),o)}return!1}};function jr(r){let{channel:t,direction:e}=r;return new ac({id:e==="inbound"?`i${t.id}`:`r${t.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${e}:${t.id}`),...r})}var Vf="/webrtc",Ye=class{protocol;peerConnection;bufferedStreams=[];metrics;dataChannelOptions;components;log;constructor(t,e){this.components=t,this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??Vf,this.dataChannelOptions=e.dataChannelOptions??{},this.log=t.logger.forComponent("libp2p:webrtc:datachannelmuxerfactory"),this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace('incoming early datachannel with channel id %d and label "%s"',n.id),n.label==="init"){this.log.trace("closing early init channel"),n.close();return}let o={},s=jr({channel:n,direction:"inbound",onEnd:i=>{o.onEnd(i)},logger:t.logger,...this.dataChannelOptions});o.stream=s,o.channel=n,o.onEnd=()=>{this.bufferedStreams=this.bufferedStreams.filter(i=>i.stream.id!==s.id)},this.bufferedStreams.push(o)}}createStreamMuxer(t){return new cc(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},cc=class{init;streams;protocol;log;peerConnection;dataChannelOptions;metrics;logger;constructor(t,e){this.init=e,this.log=t.logger.forComponent("libp2p:webrtc:muxer"),this.logger=t.logger,this.streams=e.streams.map(n=>n.stream),this.peerConnection=e.peerConnection,this.protocol=e.protocol??Vf,this.metrics=e.metrics,this.dataChannelOptions=e.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace("incoming datachannel with channel id %d",n.id),n.label==="init"){this.log.trace("closing init channel"),n.close();return}let o=jr({channel:n,direction:"inbound",onEnd:()=>{this.log("incoming channel %s ended with state %s",n.id,n.readyState),this.#t(o,n)},logger:this.logger,...this.dataChannelOptions});this.streams.push(o),this.metrics?.increment({incoming_stream:!0}),e?.onIncomingStream?.(o)},this.init.streams.length>0&&queueMicrotask(()=>{this.init.streams.forEach(n=>{n.onEnd=()=>{this.log("incoming early channel %s ended with state %s",n.channel.id,n.channel.readyState),this.#t(n.stream,n.channel)},this.metrics?.increment({incoming_stream:!0}),this.init?.onIncomingStream?.(n.stream)})})}#t(t,e){this.log.trace("stream %s %s %s onEnd",t.direction,t.id,t.protocol),Uf(e,`${t.direction} ${t.id} ${t.protocol}`,this.dataChannelOptions.drainTimeout,{log:this.log}),this.streams=this.streams.filter(n=>n.id!==t.id),this.metrics?.increment({stream_end:!0}),this.init?.onStreamEnd?.(t)}async close(t){try{await Promise.all(this.streams.map(async e=>e.close(t)))}catch(e){this.abort(e)}}abort(t){for(let e of this.streams)e.abort(t)}source=Cs();sink=ks;newStream(){let t=this.peerConnection.createDataChannel("");this.log.trace("opened outgoing datachannel with channel id %s",t.id);let e=jr({channel:t,direction:"outbound",onEnd:()=>{this.log("outgoing channel %s ended with state %s",t.id,t.readyState),this.#t(e,t)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(e),this.metrics?.increment({outgoing_stream:!0}),e}};var yr=globalThis.RTCPeerConnection,Ms=globalThis.RTCSessionDescription,Ff=globalThis.RTCIceCandidate;var lc=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=gt(),this.haveNext=gt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=gt(),t}async throw(t){return this.ended=!0,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return await this._push(void 0),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=gt(),await _e(this.readNext.promise,e?.signal,e)}};function Kf(){return new lc}var Vs=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var uc=class extends Error{code;constructor(t,e){super(t),this.code=e}},fc=class extends uc{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function $f(r,t){let e=Kf();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new dt;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new fc("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:d}=await Promise.race([n.next(),l]);return f===!0?new dt:d}for(;o.byteLength<i;){let{value:f,done:d}=await Promise.race([n.next(),l]);if(d===!0)throw new Vs("unexpected end of input");o.append(f)}let u=o.sublist(0,i);return o.consume(i),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Fs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ks=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},$s=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Kn(r,t={}){let e=$f(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=lt(t.maxDataLength));let n=t?.lengthDecoder??ee,o=t?.lengthEncoder??ce;return{read:async i=>{let a=-1,c=new dt;for(;;){c.append(await e.read(1,i));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Fs("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new $s("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Ks("message length too long");return e.read(a,i)},write:async(i,a)=>{await e.write(new dt(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new dt(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Ws(r,t){let e=Kn(r,t),n={read:async(o,s)=>{let i=await e.read(s);return o.decode(i)},write:async(o,s,i)=>{await e.write(s.encode(o),i)},writeV:async(o,s,i)=>{await e.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>e.unwrap()};return n}var zt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Je=class extends Error{constructor(t){super(`WebRTC transport error: ${t}`),this.name="WebRTCTransportError"}},Zt=class extends Je{constructor(t="SDP handshake failed"){super(t),this.name="SDPHandshakeFailedError"}};var $n=class extends Je{constructor(t,e){super(`[stream: ${t}] data channel error: ${e}`),this.name="WebRTC/DataChannelError"}},qs=class extends Je{constructor(t){super(`There was a problem with the Multiaddr which was passed in: ${t}`),this.name="WebRTC/InappropriateMultiaddrError"}};var Wn=class extends Je{constructor(t,e){super(`Invalid fingerprint "${t}" within ${e}`),this.name="WebRTC/InvalidFingerprintError"}};var zs=class extends Je{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},Gs=class extends Je{constructor(t){super(`unsupported hash algorithm code: ${t} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var $t;(function(r){let t;(function(o){o.SDP_OFFER="SDP_OFFER",o.SDP_ANSWER="SDP_ANSWER",o.ICE_CANDIDATE="ICE_CANDIDATE"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.SDP_OFFER=0]="SDP_OFFER",o[o.SDP_ANSWER=1]="SDP_ANSWER",o[o.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(e||(e={})),function(o){o.codec=()=>fr(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=se((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.data!=null&&(s.uint32(18),s.string(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.data=o.string();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>oe(o,r.codec()),r.decode=(o,s)=>ne(o,r.codec(),s)})($t||($t={}));var js=async(r,t,e)=>{try{let n=gt();for(Q0(r,n);;){let o=await Promise.race([n.promise,t.read({signal:e.signal}).catch(()=>{})]);if(o==null){e.signal?.throwIfAborted();break}if(o.type!==$t.Type.ICE_CANDIDATE)throw new eo("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){e.onProgress?.(new zt("webrtc:end-of-ice-candidates")),e.log.trace("end-of-candidates received");continue}let i=new Ff(s);e.log.trace("%s received new ICE candidate %o",e.direction,s);try{e.onProgress?.(new zt("webrtc:add-ice-candidate",i.candidate)),await r.addIceCandidate(i)}catch(a){e.log.error("%s bad candidate received",e.direction,s,a)}}}catch(n){if(e.log.error("%s error parsing ICE candidate",e.direction,n),e.signal?.aborted===!0&&Zs(r)!=="connected")throw n}};function Zs(r){return Hn?r.iceConnectionState:r.connectionState}function Q0(r,t){r[Hn?"oniceconnectionstatechange":"onconnectionstatechange"]=e=>{switch(Zs(r)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new Jn("RTCPeerConnection was closed"));break;default:break}}}async function Wf({rtcConfiguration:r,dataChannel:t,signal:e,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=qf(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",u);let f=u.getPeerId();if(f==null)throw new et("Relay peer was missing");let d=s.getConnections(Kr(f)),m,x=!1;d.length===0?(l?.(new zt("webrtc:dial-relay")),m=await i.dial(u,{signal:e,onProgress:l}),x=!0):(l?.(new zt("webrtc:reuse-relay-connection")),m=d[0]);try{l?.(new zt("webrtc:open-signaling-stream"));let g=await m.newStream(Xs,{signal:e,runOnLimitedConnection:!0}),h=Ws(g).pb($t),w=new yr(r),b=new Ye({logger:c},{peerConnection:w,dataChannelOptions:t});try{let p=w.createDataChannel("init");w.onicecandidate=({candidate:A})=>{let k=JSON.stringify(A?.toJSON()??null);a.trace("initiator sending ICE candidate %o",A),h.write({type:$t.Type.ICE_CANDIDATE,data:k},{signal:e}).catch(I=>{a.error("error sending ICE candidate",I)})},w.onicecandidateerror=A=>{a.error("initiator ICE candidate error",A)};let B=await w.createOffer().catch(A=>{throw a.error("could not execute createOffer",A),new Zt("Failed to set createOffer")});a.trace("initiator send SDP offer %s",B.sdp),l?.(new zt("webrtc:send-sdp-offer")),await h.write({type:$t.Type.SDP_OFFER,data:B.sdp},{signal:e}),await w.setLocalDescription(B).catch(A=>{throw a.error("could not execute setLocalDescription",A),new Zt("Failed to set localDescription")}),l?.(new zt("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let L=await h.read({signal:e});if(L.type!==$t.Type.SDP_ANSWER)throw new Zt("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",L.data);let N=new Ms({type:"answer",sdp:L.data});return await w.setRemoteDescription(N).catch(A=>{throw a.error("could not execute setRemoteDescription",A),new Zt("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),l?.(new zt("webrtc:read-ice-candidates")),await js(w,h,{direction:"initiator",signal:e,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),p.close(),l?.(new zt("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await g.close({signal:e}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:w,muxerFactory:b}}catch(p){throw a.error("outgoing signaling error",p),w.close(),g.abort(p),p}finally{w.onicecandidate=null,w.onicecandidateerror=null}}finally{if(x)try{await m.close({signal:e})}catch(g){m.abort(g)}}}var tg=U("dns4"),eg=U("dns6"),rg=U("dnsaddr"),br=wt(U("dns"),rg,tg,eg),Qs=wt(U("ip4"),U("ip6")),Zr=wt(F(Qs,U("tcp")),F(br,U("tcp"))),ti=F(Qs,U("udp")),ng=F(ti,U("utp")),og=F(ti,U("quic")),sg=F(ti,U("quic-v1")),hc=wt(F(Zr,U("ws")),F(br,U("ws"))),Ys=wt(F(hc,U("p2p")),hc),dc=wt(F(Zr,U("wss")),F(br,U("wss")),F(Zr,U("tls"),U("ws")),F(br,U("tls"),U("ws"))),Js=wt(F(dc,U("p2p")),dc),pc=wt(F(Zr,U("http")),F(Qs,U("http")),F(br,U("http"))),mc=wt(F(Zr,U("https")),F(Qs,U("https")),F(br,U("https"))),zf=F(ti,U("webrtc-direct"),U("certhash")),Zf=wt(F(zf,U("p2p")),zf),Gf=F(sg,U("webtransport"),U("certhash"),U("certhash")),Xf=wt(F(Gf,U("p2p")),Gf),Yf=wt(F(Ys,U("p2p-webrtc-star"),U("p2p")),F(Js,U("p2p-webrtc-star"),U("p2p")),F(Ys,U("p2p-webrtc-star")),F(Js,U("p2p-webrtc-star"))),ES=wt(F(Ys,U("p2p-websocket-star"),U("p2p")),F(Js,U("p2p-websocket-star"),U("p2p")),F(Ys,U("p2p-websocket-star")),F(Js,U("p2p-websocket-star"))),Jf=wt(F(pc,U("p2p-webrtc-direct"),U("p2p")),F(mc,U("p2p-webrtc-direct"),U("p2p")),F(pc,U("p2p-webrtc-direct")),F(mc,U("p2p-webrtc-direct"))),xr=wt(hc,dc,pc,mc,Yf,Jf,Zr,ng,og,br,Zf,Xf),vS=wt(F(xr,U("p2p-stardust"),U("p2p")),F(xr,U("p2p-stardust"))),Qe=wt(F(xr,U("p2p")),Yf,Jf,Zf,Xf,U("p2p")),jf=wt(F(Qe,U("p2p-circuit"),Qe),F(Qe,U("p2p-circuit")),F(U("p2p-circuit"),Qe),F(xr,U("p2p-circuit")),F(U("p2p-circuit"),xr),U("p2p-circuit")),Qf=()=>wt(F(jf,Qf),jf),Re=Qf(),SS=wt(F(Re,Qe,Re),F(Qe,Re),F(Re,Qe),Re,Qe);var AS=wt(F(Re,U("webrtc"),U("p2p")),F(Re,U("webrtc")),F(xr,U("webrtc"),U("p2p")),F(xr,U("webrtc")),U("webrtc"));function th(r){function t(e){let n;try{n=ae(e)}catch{return!1}let o=r(n.protoNames());return o===null?!1:o===!0||o===!1?o:o.length===0}return t}function F(...r){function t(e){if(e.length<r.length)return null;let n=e;return r.some(o=>(n=typeof o=="function"?o().partialMatch(e):o.partialMatch(e),Array.isArray(n)&&(e=n),n===null)),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:th(t),partialMatch:t}}function wt(...r){function t(n){let o=null;return r.some(s=>{let i=typeof s=="function"?s().partialMatch(n):s.partialMatch(n);return i!=null?(o=i,!0):!1}),o}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:th(t),partialMatch:t}}function U(r){let t=r;function e(o){let s;try{s=ae(o)}catch{return!1}let i=s.protoNames();return i.length===1&&i[0]===t}function n(o){return o.length===0?null:o[0]===t?o.slice(1):null}return{toString:function(){return t},matches:e,partialMatch:n}}var ei=class extends no{peerId;transportManager;shutdownController;constructor(t,e){super(),this.peerId=t.peerId,this.transportManager=t.transportManager,this.shutdownController=e.shutdownController}async listen(){this.safeDispatchEvent("listening",{})}getAddrs(){return this.transportManager.getListeners().filter(t=>t!==this).map(t=>t.getAddrs().filter(e=>Re.matches(e)).map(e=>e.encapsulate(`/webrtc/p2p/${this.peerId}`))).flat()}async close(){this.shutdownController.abort(),this.safeDispatchEvent("close",{})}};async function eh({peerConnection:r,stream:t,signal:e,connection:n,log:o}){o.trace("new inbound signaling stream");let s=Ws(t).pb($t);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:$t.Type.ICE_CANDIDATE,data:f},{signal:e}).catch(d=>{o.error("error sending ICE candidate",d)})},o.trace("recipient read SDP offer");let a=await s.read({signal:e});if(a.type!==$t.Type.SDP_OFFER)throw new Zt(`expected message type SDP_OFFER, received: ${a.type??"undefined"} `);o.trace("recipient received SDP offer %s",a.data);let c=new Ms({type:"offer",sdp:a.data});await r.setRemoteDescription(c).catch(u=>{throw o.error("could not execute setRemoteDescription",u),new Zt("Failed to set remoteDescription")});let l=await r.createAnswer().catch(u=>{throw o.error("could not execute createAnswer",u),new Zt("Failed to create answer")});o.trace("recipient send SDP answer %s",l.sdp),await s.write({type:$t.Type.SDP_ANSWER,data:l.sdp},{signal:e}),await r.setLocalDescription(l).catch(u=>{throw o.error("could not execute setLocalDescription",u),new Zt("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await js(r,s,{direction:"recipient",signal:e,log:o})}catch(a){if(Zs(r)!=="connected")throw o.error("error while handling signaling stream from peer %a",n.remoteAddr,a),r.close(),a;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",n.remoteAddr,a)}let i=ae(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return o.trace("recipient connected to remote address %s",i),{remoteAddress:i}}var ig="/webrtc",ag="/p2p-circuit",Xs="/webrtc-signaling/0.0.1",cg=30*1e3,ri=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,e={}){this.components=t,this.init=e,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,ro(1/0,this.shutdownController.signal),t.metrics!=null&&(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"})})}[Xn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Sr]=["@libp2p/transport"];[Zc]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(Xs,t=>{this._onProtocol(t).catch(e=>{this.log.error("failed to handle incoming connect from %p",t.connection.remotePeer,e)})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(Xs),this._started=!1}createListener(t){return new ei(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(Af.exactMatch)}dialFilter(t){return this.listenFilter(t)}async dial(t,e){this.log.trace("dialing address: %a",t);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await Wf({rtcConfiguration:await Mn(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:t,dataChannelOptions:this.init.dataChannel,signal:e.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:e.onProgress}),i=new mr(this.components,{peerConnection:o,timeline:{open:Date.now()},remoteAddr:n,metrics:this.metrics?.dialerEvents}),a=await e.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,muxerFactory:s,onProgress:e.onProgress});return this._closeOnShutdown(o,i),a}async _onProtocol({connection:t,stream:e}){let n=AbortSignal.timeout(this.init.inboundConnectionTimeout??cg),o=new yr(await Mn(this.init.rtcConfiguration)),s=new Ye(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await eh({peerConnection:o,connection:t,stream:e,signal:n,log:this.log});await e.close({signal:n});let a=new mr(this.components,{peerConnection:o,timeline:{open:new Date().getTime()},remoteAddr:i,metrics:this.metrics?.listenerEvents});await this.components.upgrader.upgradeInbound(a,{skipEncryption:!0,skipProtection:!0,muxerFactory:s}),this._closeOnShutdown(o,a)}catch(i){throw this.log.error("incoming signaling error",i),o.close(),e.abort(i),i}}_closeOnShutdown(t,e){let n=()=>{e.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection",o)})};this.shutdownController.signal.addEventListener("abort",n),t.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function qf(r){let t=r.toString().split(ig+"/");if(t.length!==2)throw new et("webrtc protocol was not present in multiaddr");if(!t[0].includes(ag))throw new et("p2p-circuit protocol was not present in multiaddr");let e=ae(t[0]),o=ae("/"+t[1]).getPeerId();if(o==null)throw new et("destination peer id was missing");let s=e.protos().pop();if(s===void 0)throw new et("invalid multiaddr");return s.name!=="p2p"&&(e=e.encapsulate(`/p2p/${o}`)),{baseAddr:e,peerId:Kr(o)}}function gc(){let r=gt(),t=!1;return{sink:async e=>{if(t)throw new Error("already piped");t=!0,r.resolve(e)},source:async function*(){yield*await r.promise}()}}function rh(){let r=gc(),t=gc();return[{source:r.source,sink:t.sink},{source:t.source,sink:r.sink}]}function lg(r){return r[Symbol.asyncIterator]!=null}function ug(...r){let t=[];for(let e of r)lg(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=Xe({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)e.push(o)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var nh=ug;function oh(r,...t){if(r==null)throw new Error("Empty pipeline");if(wc(r)){let n=r;r=()=>n.source}else if(ih(r)||sh(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&wc(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)wc(e[n])&&(e[n]=hg(e[n]));return fg(...e)}var fg=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},sh=r=>r?.[Symbol.asyncIterator]!=null,ih=r=>r?.[Symbol.iterator]!=null,wc=r=>r==null?!1:r.sink!=null&&r.source!=null,hg=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Xe({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(sh(s))o=async function*(){yield*s,n.end()};else if(ih(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return nh(n,o())}return r.source};var Xr=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function ni(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function yc(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function bc(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Wt(r,...t){if(!bc(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function xc(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function ah(r,t){Wt(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var Ue=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),ch=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),dg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!dg)throw new Error("Non little-endian hardware is not supported");function pg(r){if(typeof r!="string")throw new Error(`string expected, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function oi(r){if(typeof r=="string")r=pg(r);else if(bc(r))r=si(r);else throw new Error(`Uint8Array expected, got ${typeof r}`);return r}function lh(r,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(r,t)}function uh(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}var Ec=(r,t)=>(Object.assign(t,r),t);function vc(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}function si(r){return Uint8Array.from(r)}function De(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}var hh=r=>Uint8Array.from(r.split("").map(t=>t.charCodeAt(0))),mg=hh("expand 16-byte k"),gg=hh("expand 32-byte k"),wg=Ue(mg),dh=Ue(gg),lA=dh.slice();function O(r,t){return r<<t|r>>>32-t}function Sc(r){return r.byteOffset%4===0}var ii=64,yg=16,ph=2**32-1,fh=new Uint32Array;function bg(r,t,e,n,o,s,i,a){let c=o.length,l=new Uint8Array(ii),u=Ue(l),f=Sc(o)&&Sc(s),d=f?Ue(o):fh,m=f?Ue(s):fh;for(let x=0;x<c;i++){if(r(t,e,n,u,i,a),i>=ph)throw new Error("arx: counter overflow");let g=Math.min(ii,c-x);if(f&&g===ii){let h=x/4;if(x%4!==0)throw new Error("arx: invalid block position");for(let w=0,b;w<yg;w++)b=h+w,m[b]=d[b]^u[w];x+=ii;continue}for(let h=0,w;h<g;h++)w=x+h,s[w]=o[w]^l[h];x+=g}}function Ac(r,t){let{allowShortKeys:e,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=lh({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof r!="function")throw new Error("core must be a function");return ni(o),ni(i),yc(s),yc(e),(a,c,l,u,f=0)=>{Wt(a),Wt(c),Wt(l);let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),Wt(u),ni(f),f<0||f>=ph)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let m=[],x=a.length,g,h;if(x===32)m.push(g=si(a)),h=dh;else if(x===16&&e)g=new Uint8Array(32),g.set(a),g.set(a,16),h=wg,m.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${x}`);Sc(c)||m.push(c=si(c));let w=Ue(g);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,w,Ue(c.subarray(0,16)),w),c=c.subarray(16)}let b=16-o;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let B=new Uint8Array(12);B.set(c,s?0:12-c.length),c=B,m.push(c)}let p=Ue(c);return bg(r,h,w,p,l,u,f,i),De(...m),u}}var Tt=(r,t)=>r[t++]&255|(r[t++]&255)<<8,Bc=class{constructor(t){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,t=oi(t),Wt(t,32);let e=Tt(t,0),n=Tt(t,2),o=Tt(t,4),s=Tt(t,6),i=Tt(t,8),a=Tt(t,10),c=Tt(t,12),l=Tt(t,14);this.r[0]=e&8191,this.r[1]=(e>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Tt(t,16+2*u)}process(t,e,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],d=i[5],m=i[6],x=i[7],g=i[8],h=i[9],w=Tt(t,e+0),b=Tt(t,e+2),p=Tt(t,e+4),B=Tt(t,e+6),L=Tt(t,e+8),N=Tt(t,e+10),A=Tt(t,e+12),k=Tt(t,e+14),I=s[0]+(w&8191),V=s[1]+((w>>>13|b<<3)&8191),_=s[2]+((b>>>10|p<<6)&8191),H=s[3]+((p>>>7|B<<9)&8191),K=s[4]+((B>>>4|L<<12)&8191),C=s[5]+(L>>>1&8191),T=s[6]+((L>>>14|N<<2)&8191),E=s[7]+((N>>>11|A<<5)&8191),y=s[8]+((A>>>8|k<<8)&8191),S=s[9]+(k>>>5|o),v=0,R=v+I*a+V*(5*h)+_*(5*g)+H*(5*x)+K*(5*m);v=R>>>13,R&=8191,R+=C*(5*d)+T*(5*f)+E*(5*u)+y*(5*l)+S*(5*c),v+=R>>>13,R&=8191;let D=v+I*c+V*a+_*(5*h)+H*(5*g)+K*(5*x);v=D>>>13,D&=8191,D+=C*(5*m)+T*(5*d)+E*(5*f)+y*(5*u)+S*(5*l),v+=D>>>13,D&=8191;let M=v+I*l+V*c+_*a+H*(5*h)+K*(5*g);v=M>>>13,M&=8191,M+=C*(5*x)+T*(5*m)+E*(5*d)+y*(5*f)+S*(5*u),v+=M>>>13,M&=8191;let $=v+I*u+V*l+_*c+H*a+K*(5*h);v=$>>>13,$&=8191,$+=C*(5*g)+T*(5*x)+E*(5*m)+y*(5*d)+S*(5*f),v+=$>>>13,$&=8191;let W=v+I*f+V*u+_*l+H*c+K*a;v=W>>>13,W&=8191,W+=C*(5*h)+T*(5*g)+E*(5*x)+y*(5*m)+S*(5*d),v+=W>>>13,W&=8191;let z=v+I*d+V*f+_*u+H*l+K*c;v=z>>>13,z&=8191,z+=C*a+T*(5*h)+E*(5*g)+y*(5*x)+S*(5*m),v+=z>>>13,z&=8191;let j=v+I*m+V*d+_*f+H*u+K*l;v=j>>>13,j&=8191,j+=C*c+T*a+E*(5*h)+y*(5*g)+S*(5*x),v+=j>>>13,j&=8191;let st=v+I*x+V*m+_*d+H*f+K*u;v=st>>>13,st&=8191,st+=C*l+T*c+E*a+y*(5*h)+S*(5*g),v+=st>>>13,st&=8191;let it=v+I*g+V*x+_*m+H*d+K*f;v=it>>>13,it&=8191,it+=C*u+T*l+E*c+y*a+S*(5*h),v+=it>>>13,it&=8191;let ut=v+I*h+V*g+_*x+H*m+K*d;v=ut>>>13,ut&=8191,ut+=C*f+T*u+E*l+y*c+S*a,v+=ut>>>13,ut&=8191,v=(v<<2)+v|0,v=v+R|0,R=v&8191,v=v>>>13,D+=v,s[0]=R,s[1]=D,s[2]=M,s[3]=$,s[4]=W,s[5]=z,s[6]=j,s[7]=st,s[8]=it,s[9]=ut}finalize(){let{h:t,pad:e}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+e[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+e[a]|0)+(i>>>16)|0,t[a]=i&65535;De(n)}update(t){xc(this);let{buffer:e,blockLen:n}=this;t=oi(t);let o=t.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(t,s);continue}e.set(t.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(e,0,!1),this.pos=0)}return this}destroy(){De(this.h,this.r,this.buffer,this.pad)}digestInto(t){xc(this),ah(t,this),this.finished=!0;let{buffer:e,h:n}=this,{pos:o}=this;if(o){for(e[o++]=1;o<16;o++)e[o]=0;this.process(e,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)t[s++]=n[i]>>>0,t[s++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}};function xg(r){let t=(n,o)=>r(o).update(oi(n)).digest(),e=r(new Uint8Array(32));return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=n=>r(n),t}var mh=xg(r=>new Bc(r));function yh(r,t,e,n,o,s=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=t[0],f=t[1],d=t[2],m=t[3],x=t[4],g=t[5],h=t[6],w=t[7],b=o,p=e[0],B=e[1],L=e[2],N=i,A=a,k=c,I=l,V=u,_=f,H=d,K=m,C=x,T=g,E=h,y=w,S=b,v=p,R=B,D=L;for(let $=0;$<s;$+=2)N=N+V|0,S=O(S^N,16),C=C+S|0,V=O(V^C,12),N=N+V|0,S=O(S^N,8),C=C+S|0,V=O(V^C,7),A=A+_|0,v=O(v^A,16),T=T+v|0,_=O(_^T,12),A=A+_|0,v=O(v^A,8),T=T+v|0,_=O(_^T,7),k=k+H|0,R=O(R^k,16),E=E+R|0,H=O(H^E,12),k=k+H|0,R=O(R^k,8),E=E+R|0,H=O(H^E,7),I=I+K|0,D=O(D^I,16),y=y+D|0,K=O(K^y,12),I=I+K|0,D=O(D^I,8),y=y+D|0,K=O(K^y,7),N=N+_|0,D=O(D^N,16),E=E+D|0,_=O(_^E,12),N=N+_|0,D=O(D^N,8),E=E+D|0,_=O(_^E,7),A=A+H|0,S=O(S^A,16),y=y+S|0,H=O(H^y,12),A=A+H|0,S=O(S^A,8),y=y+S|0,H=O(H^y,7),k=k+K|0,v=O(v^k,16),C=C+v|0,K=O(K^C,12),k=k+K|0,v=O(v^k,8),C=C+v|0,K=O(K^C,7),I=I+V|0,R=O(R^I,16),T=T+R|0,V=O(V^T,12),I=I+V|0,R=O(R^I,8),T=T+R|0,V=O(V^T,7);let M=0;n[M++]=i+N|0,n[M++]=a+A|0,n[M++]=c+k|0,n[M++]=l+I|0,n[M++]=u+V|0,n[M++]=f+_|0,n[M++]=d+H|0,n[M++]=m+K|0,n[M++]=x+C|0,n[M++]=g+T|0,n[M++]=h+E|0,n[M++]=w+y|0,n[M++]=b+S|0,n[M++]=p+v|0,n[M++]=B+R|0,n[M++]=L+D|0}function Eg(r,t,e,n){let o=r[0],s=r[1],i=r[2],a=r[3],c=t[0],l=t[1],u=t[2],f=t[3],d=t[4],m=t[5],x=t[6],g=t[7],h=e[0],w=e[1],b=e[2],p=e[3];for(let L=0;L<20;L+=2)o=o+c|0,h=O(h^o,16),d=d+h|0,c=O(c^d,12),o=o+c|0,h=O(h^o,8),d=d+h|0,c=O(c^d,7),s=s+l|0,w=O(w^s,16),m=m+w|0,l=O(l^m,12),s=s+l|0,w=O(w^s,8),m=m+w|0,l=O(l^m,7),i=i+u|0,b=O(b^i,16),x=x+b|0,u=O(u^x,12),i=i+u|0,b=O(b^i,8),x=x+b|0,u=O(u^x,7),a=a+f|0,p=O(p^a,16),g=g+p|0,f=O(f^g,12),a=a+f|0,p=O(p^a,8),g=g+p|0,f=O(f^g,7),o=o+l|0,p=O(p^o,16),x=x+p|0,l=O(l^x,12),o=o+l|0,p=O(p^o,8),x=x+p|0,l=O(l^x,7),s=s+u|0,h=O(h^s,16),g=g+h|0,u=O(u^g,12),s=s+u|0,h=O(h^s,8),g=g+h|0,u=O(u^g,7),i=i+f|0,w=O(w^i,16),d=d+w|0,f=O(f^d,12),i=i+f|0,w=O(w^i,8),d=d+w|0,f=O(f^d,7),a=a+c|0,b=O(b^a,16),m=m+b|0,c=O(c^m,12),a=a+c|0,b=O(b^a,8),m=m+b|0,c=O(c^m,7);let B=0;n[B++]=o,n[B++]=s,n[B++]=i,n[B++]=a,n[B++]=h,n[B++]=w,n[B++]=b,n[B++]=p}var vg=Ac(yh,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Sg=Ac(yh,{counterRight:!1,counterLength:8,extendNonceFn:Eg,allowShortKeys:!1});var Ag=new Uint8Array(16),gh=(r,t)=>{r.update(t);let e=t.length%16;e&&r.update(Ag.subarray(e))},Bg=new Uint8Array(32);function wh(r,t,e,n,o){let s=r(t,e,Bg),i=mh.create(s);o&&gh(i,o),gh(i,n);let a=new Uint8Array(16),c=ch(a);vc(c,0,BigInt(o?o.length:0),!0),vc(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return De(s,a),l}var bh=r=>(t,e,n)=>(Wt(t,32),Wt(e),{encrypt(s,i){let a=s.length,c=a+16;i?Wt(i,c):i=new Uint8Array(c),r(t,e,s,i,1);let l=wh(r,t,e,i.subarray(0,-16),n);return i.set(l,a),De(l),i},decrypt(s,i){let a=s.length,c=a-16;if(a<16)throw new Error("encrypted data must be at least 16 bytes");i?Wt(i,c):i=new Uint8Array(c);let l=s.subarray(0,-16),u=s.subarray(-16),f=wh(r,t,e,l,n);if(!uh(u,f))throw new Error("invalid tag");return r(t,e,l,i,1),De(f),i}}),Ic=Ec({blockSize:64,nonceLength:12,tagLength:16},bh(vg)),yA=Ec({blockSize:64,nonceLength:24,tagLength:16},bh(Sg));function Eh(r,t,e){return cn(r),e===void 0&&(e=new Uint8Array(r.outputLen)),Fr(r,He(e),He(t))}var Cc=new Uint8Array([0]),xh=new Uint8Array;function vh(r,t,e,n=32){if(cn(r),so(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);e===void 0&&(e=xh);let s=new Uint8Array(o*r.outputLen),i=Fr.create(r,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)Cc[0]=l+1,a.update(l===0?xh:c).update(e).update(Cc).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),Cc.fill(0),s.slice(0,n)}var kc={hashSHA256(r){return ue(r.subarray())},getHKDF(r,t){let e=Eh(ue,t,r),o=vh(ue,e,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=pn.utils.randomPrivateKey();return{publicKey:pn.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:pn.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,t){return pn.getSharedSecret(r.subarray(),t.subarray())},chaCha20Poly1305Encrypt(r,t,e,n){return Ic(n,t,e).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,t,e,n,o){return Ic(n,t,e).decrypt(r.subarray(),o)}};var Sh=kc;function Ah(r){return{generateKeypair:r.generateX25519KeyPair,dh:(t,e)=>r.generateX25519SharedKey(t.privateKey,e).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var Yr=r=>{let t=Et(2);return t[0]=r>>8,t[1]=r,t};Yr.bytes=2;var qn=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let t=0;return t+=r[0]<<8,t+=r[1],t}return r.getUint16(0)};qn.bytes=2;function Bh(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Tc(r,t){!t.enabled||!Xr||(r?(t(`LOCAL_STATIC_PUBLIC_KEY ${Q(r.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${Q(r.privateKey,"hex")}`)):t("Missing local static keys."))}function Nc(r,t){!t.enabled||!Xr||(r?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${Q(r.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${Q(r.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function Ih(r,t){!t.enabled||!Xr||t(r?`REMOTE_STATIC_PUBLIC_KEY ${Q(r.subarray(),"hex")}`:"Missing remote static public key.")}function Lc(r,t){!t.enabled||!Xr||t(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${Q(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function _c(r,t,e){!e.enabled||!Xr||(e(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&Q(r.k,"hex")}`),e(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&Q(t.k,"hex")}`))}var Jr=class r extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var Ig=0,Cg=4294967295,kg="Cipherstate has reached maximum n, a new handshake must be performed",ai=class{n;bytes;view;constructor(t=Ig){this.n=t,this.bytes=xt(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>Cg)throw new Error(kg)}};var Er=xt(0),Qr=class{k;n;crypto;constructor(t,e=void 0,n=0){this.crypto=t,this.k=e,this.n=new ai(n)}hasKey(){return!!this.k}encryptWithAd(t,e){if(!this.hasKey())return e;this.n.assertValue();let n=this.crypto.encrypt(e,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,e,n){if(!this.hasKey())return e;this.n.assertValue();let o=this.crypto.decrypt(e,this.n.getBytes(),t,this.k,n);return this.n.increment(),o}},Rc=class{cs;ck;h;crypto;constructor(t,e){this.crypto=t;let n=rt(e,"utf-8");this.h=Tg(t,n),this.ck=this.h,this.cs=new Qr(t)}mixKey(t){let[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new Qr(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new dt(this.h,t))}encryptAndHash(t){let e=this.cs.encryptWithAd(this.h,t);return this.mixHash(e),e}decryptAndHash(t){let e=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),e}split(){let[t,e]=this.crypto.hkdf(this.ck,Er);return[new Qr(this.crypto,t),new Qr(this.crypto,e)]}},Uc=class{ss;s;e;rs;re;initiator;crypto;constructor(t){let{crypto:e,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=t;this.crypto=e,this.ss=new Rc(e,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let t=this.crypto.generateKeypair();return this.ss.mixHash(t.publicKey),this.e=t,t.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(t,e=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<e+32)throw new Error("message is not long enough");this.re=t.sublist(e,e+32),this.ss.mixHash(this.re)}readS(t,e=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(t.byteLength<e+n)throw new Error("message is not long enough");let o=t.sublist(e,e+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},zn=class extends Uc{writeMessageA(t){return new dt(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let e=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new dt(e,n,this.ss.encryptAndHash(t))}writeMessageC(t){let e=this.writeS();return this.writeSE(),new dt(e,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(e){throw new Jr(`handshake stage 0 validation fail: ${e.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();let e=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+e))}catch(e){throw new Jr(`handshake stage 1 validation fail: ${e.message}`)}}readMessageC(t){try{let e=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(e))}catch(e){throw new Jr(`handshake stage 2 validation fail: ${e.message}`)}}};function Tg(r,t){if(t.length<=32){let e=xt(32);return e.set(t),e}else return r.hash(t)}var ci;(function(r){let t;r.codec=()=>(t==null&&(t=se((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.webtransportCerthashes!=null)for(let s of e.webtransportCerthashes)n.uint32(10),n.bytes(s);o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={webtransportCerthashes:[]},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:{o.webtransportCerthashes.push(e.bytes());break}default:{e.skipType(i&7);break}}}return o})),t),r.encode=e=>oe(e,r.codec()),r.decode=e=>ne(e,r.codec())})(ci||(ci={}));var Gn;(function(r){let t;r.codec=()=>(t==null&&(t=se((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.identityKey!=null&&e.identityKey.byteLength>0&&(n.uint32(10),n.bytes(e.identityKey)),e.identitySig!=null&&e.identitySig.byteLength>0&&(n.uint32(18),n.bytes(e.identitySig)),e.extensions!=null&&(n.uint32(34),ci.codec().encode(e.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={identityKey:xt(0),identitySig:xt(0)},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:{o.identityKey=e.bytes();break}case 2:{o.identitySig=e.bytes();break}case 4:{o.extensions=ci.codec().decode(e,e.uint32());break}default:{e.skipType(i&7);break}}}return o})),t),r.encode=e=>oe(e,r.codec()),r.decode=e=>ne(e,r.codec())})(Gn||(Gn={}));async function Dc(r,t,e){let n=await r.sign(Ch(t));return Gn.encode({identityKey:Rr(r.publicKey),identitySig:n,extensions:e})}async function Pc(r,t,e){try{let n=Gn.decode(r),o=Nn(n.identityKey);if(e?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${e}`);if(!t)throw new Error("Remote static does not exist");let s=Ch(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Yn(n.message)}}function Ch(r){let t=rt("noise-libp2p-static-key:");return r instanceof Uint8Array?At([t,r],t.length+r.length):(r.prepend(t),r)}async function kh(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Dc(s,a.publicKey,l),f=new zn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Tc(f.s,e),e.trace("Stage 0 - Initiator starting to send first message."),await n.write(f.writeMessageA(Er),t),e.trace("Stage 0 - Initiator finished sending first message."),Nc(f.e,e),e.trace("Stage 1 - Initiator waiting to receive first message from responder...");let d=f.readMessageB(await n.read(t));e.trace("Stage 1 - Initiator received the message."),Lc(f.re,e),Ih(f.rs,e),e.trace("Initiator going to check remote's signature...");let m=await Pc(d,f.rs,c);e.trace("All good with the signature!"),e.trace("Stage 2 - Initiator sending third handshake message."),await n.write(f.writeMessageC(u),t),e.trace("Stage 2 - Initiator sent message with signed payload.");let[x,g]=f.ss.split();return _c(x,g,e),{payload:m,encrypt:h=>x.encryptWithAd(Er,h),decrypt:(h,w)=>g.decryptWithAd(Er,h,w)}}async function Th(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Dc(s,a.publicKey,l),f=new zn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Tc(f.s,e),e.trace("Stage 0 - Responder waiting to receive first message."),f.readMessageA(await n.read(t)),e.trace("Stage 0 - Responder received first message."),Lc(f.re,e),e.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(f.writeMessageB(u),t),e.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Nc(f.e,e),e.trace("Stage 2 - Responder waiting for third handshake message...");let d=f.readMessageC(await n.read(t));e.trace("Stage 2 - Responder received the message, finished handshake.");let m=await Pc(d,f.rs,c),[x,g]=f.ss.split();return _c(x,g,e),{payload:m,encrypt:h=>g.encryptWithAd(Er,h),decrypt:(h,w)=>x.decryptWithAd(Er,h,w)}}var Lh=16;function _h(r,t){return async function*(e){for await(let n of e)for(let o=0;o<n.length;o+=65519){let s=o+65519;s>n.length&&(s=n.length);let i;n instanceof Uint8Array?i=r.encrypt(n.subarray(o,s)):i=r.encrypt(n.sublist(o,s)),t?.encryptedPackets.increment(),yield new dt(Yr(i.byteLength),i)}}}function Rh(r,t){return async function*(e){for await(let n of e)for(let o=0;o<n.length;o+=65535){let s=o+65535;if(s>n.length&&(s=n.length),s-Lh<o)throw new Error("Invalid chunk");let i=n.sublist(o,s),a=n.subarray(o,s-Lh);try{let c=r.decrypt(i,a);t?.decryptedPackets.increment(),yield c}catch(c){throw t?.decryptErrors.increment(),c}}}}var li=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(t,e={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=e,{metrics:a}=t;this.components=t;let c=s??Sh;this.crypto=Ah(c),this.extensions=o,this.metrics=a?Bh(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??xt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Sr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,e){let n=Kn(t,{lengthEncoder:Yr,lengthDecoder:qn,maxDataLength:65535}),o=await this.performHandshakeInitiator(n,this.components.privateKey,e?.remotePeer?.publicKey,e),s=await this.createSecureConnection(n,o);t.source=s.source,t.sink=s.sink;let i=Nn(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Ua(i)}}async secureInbound(t,e){let n=Kn(t,{lengthEncoder:Yr,lengthDecoder:qn,maxDataLength:65535}),o=await this.performHandshakeResponder(n,this.components.privateKey,e?.remotePeer?.publicKey,e),s=await this.createSecureConnection(n,o);t.source=s.source,t.sink=s.sink;let i=Nn(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Ua(i)}}async performHandshakeInitiator(t,e,n,o){let s;try{s=await kh({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async performHandshakeResponder(t,e,n,o){let s;try{s=await Th({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async createSecureConnection(t,e){let[n,o]=rh(),s=t.unwrap();return await oh(n,_h(e,this.metrics),s,i=>wr(i,{lengthDecoder:qn}),Rh(e,this.metrics),n),o}};function Uh(r={}){return t=>new li(t,r)}var Oc=Object.values(lr).map(r=>r.decoder).reduce((r,t)=>r.or(t));function Dh(r,t){let e=r.getConfiguration().certificates?.at(0);if(e?.getFingerprints==null){t.log.trace("fetching fingerprint from local SDP");let o=r.localDescription;return o==null?void 0:Lg(o.sdp)}if(t.log.trace("fetching fingerprint from local certificate"),e.getFingerprints().length===0)return;let n=e.getFingerprints()[0].value;if(n==null)throw new Wn("","no fingerprint on local certificate");return n}var Ng=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function Lg(r){return r.match(Ng)?.groups?.fingerprint}function _g(r){for(let t of r.protoNames())if(t.startsWith("ip"))return t.toUpperCase();return"IP6"}function ui(r){let e=r.stringTuples().filter(n=>n[0]===Hh).map(n=>n[1])[0];if(e===void 0||e==="")throw new et(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return e}function Hc(r){return Xt.decode(Oc.decode(r))}function Rg(r){let t=Hc(ui(r)),e=Mc(t.code),n=t.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new Wn(n,r.toString());return[`${e} ${o.join(":").toUpperCase()}`,n]}function Mc(r){switch(r){case 17:return"SHA-1";case 18:return"SHA-256";case 19:return"SHA-512";default:throw new Gs(r)}}function Ug(r,t){let{host:e,port:n}=r.toOptions(),o=_g(r),[s]=Rg(r);return`v=0
6
+ `)}`:`${e} :`}};ru=je;P.Constructed=ru;je.NAME="CONSTRUCTED";var _o=class extends Rt{fromBER(t,e,n){return e}toBER(t){return ie}};_o.override="EndOfContentValueBlock";var nu,Lo=class extends Ct{constructor(t={}){super(t,_o),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};nu=Lo;P.EndOfContent=nu;Lo.NAME=En;var ou,Or=class extends Ct{constructor(t={}){super(t,Rt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(t,e,n){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+=n,e+n>t.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):e+n}toBER(t,e){let n=new ArrayBuffer(2);if(!t){let o=new Uint8Array(n);o[0]=5,o[1]=0}return e&&e.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};ou=Or;P.Null=ou;Or.NAME="NULL";var Ro=class extends ke(Rt){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=G.BufferSourceConverter.toUint8Array(e.valueHex):this.valueHexView=new Uint8Array(1),t&&(this.value=t)}get value(){for(let t of this.valueHexView)if(t>0)return!0;return!1}set value(t){this.valueHexView[0]=t?255:0}fromBER(t,e,n){let o=G.BufferSourceConverter.toUint8Array(t);return Ce(this,o,e,n)?(this.valueHexView=o.subarray(e,e+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Sa.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Ro.NAME="BooleanValueBlock";var su,Uo=class extends Ct{constructor(t={}){super(t,Ro),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};su=Uo;P.Boolean=su;Uo.NAME="BOOLEAN";var Do=class extends ke(fe){constructor({isConstructed:t=!1,...e}={}){super(e),this.isConstructed=t}fromBER(t,e,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=fe.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===En){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Jl)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(t,e,n),this.blockLength=n;return o}toBER(t,e){return this.isConstructed?fe.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Do.NAME="OctetStringValueBlock";var iu,Po=class r extends Ct{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},Do),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(t,e,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),e;if(!this.valueBlock.isConstructed){let s=(t instanceof ArrayBuffer?new Uint8Array(t):t).subarray(e,e+n);try{if(s.byteLength){let i=us(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(t,e,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?je.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${G.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let t=[];for(let e of this.valueBlock.value)e instanceof r&&t.push(e.valueBlock.valueHexView);return G.BufferSourceConverter.concat(t)}};iu=Po;P.OctetString=iu;Po.NAME=Jl;var Oo=class extends ke(fe){constructor({unusedBits:t=0,isConstructed:e=!1,...n}={}){super(n),this.unusedBits=t,this.isConstructed=e,this.blockLength=this.valueHexView.byteLength}fromBER(t,e,n){if(!n)return e;let o=-1;if(this.isConstructed){if(o=fe.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===En){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Ql)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let s=G.BufferSourceConverter.toUint8Array(t);if(!Ce(this,s,e,n))return-1;let i=s.subarray(e,e+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=us(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,e+n}toBER(t,e){if(this.isConstructed)return fe.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ie;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Oo.NAME="BitStringValueBlock";var au,Hr=class extends Ct{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},Oo),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(t,e,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(t,e,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return je.prototype.onAsciiEncoding.call(this);{let t=[],e=this.valueBlock.valueHexView;for(let o of e)t.push(o.toString(2).padStart(8,"0"));let n=t.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};au=Hr;P.BitString=au;Hr.NAME=Ql;var cu;function Dm(r,t){let e=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<i?i:c,f=0;for(let d=u;d>=0;d--,f++){switch(!0){case f<a.length:l=s[i-f]+a[c-f]+e[0];break;default:l=s[i-f]+e[0]}switch(e[0]=l/10,!0){case f>=s.length:s=Ao(new Uint8Array([l%10]),s);break;default:s[i-f]=l%10}}return e[0]>0&&(s=Ao(e,s)),s}function Yl(r){if(r>=bn.length)for(let t=bn.length;t<=r;t++){let e=new Uint8Array([0]),n=bn[t-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+e[0]]);e[0]=s[0]/10,n[o]=s[0]%10}e[0]>0&&(n=Ao(e,n)),bn.push(n)}return bn[r]}function Pm(r,t){let e=0,n=new Uint8Array(r),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let f=c;f>=0;f--,u++)switch(l=s[i-u]-a[c-u]-e,!0){case l<0:e=1,s[i-u]=l+10;break;default:e=0,s[i-u]=l}if(e>0)for(let f=i-c+1;f>=0;f--,u++)if(l=s[i-u]-e,l<0)e=1,s[i-u]=l+10;else{e=0,s[i-u]=l;break}return s.slice()}var vn=class extends ke(Rt){constructor({value:t,...e}={}){super(e),this._valueDec=0,e.valueHex&&this.setValueHex(),t!==void 0&&(this.valueDec=t)}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=Sa.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(jl(t))}get valueDec(){return this._valueDec}fromDER(t,e,n,o=0){let s=this.fromBER(t,e,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(t=!1){let e=this.valueHexView;switch(!0){case(e[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(e,1),this.valueHexView=n}break;case(e[0]===0&&(e[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(t)}fromBER(t,e,n){let o=super.fromBER(t,e,n);return o===-1||this.setValueHex(),o}toBER(t){return t?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let t=this.valueHexView.length*8-1,e=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case t:e=Pm(Yl(n),e),i="-";break;default:e=Dm(e,Yl(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(i+=Xl.charAt(e[c]));return a===!1&&(i+=Xl.charAt(0)),i}};cu=vn;vn.NAME="IntegerValueBlock";Object.defineProperty(cu.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var lu,kt=class r extends Ct{constructor(t={}){super(t,vn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Bo(),BigInt(this.valueBlock.toString())}static fromBigInt(t){Bo();let e=BigInt(t),n=new xn,o=e.toString(16).replace(/^-/,""),s=new Uint8Array(G.Convert.FromHex(o));if(e<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${G.Convert.ToHex(a)}`)+e,u=G.BufferSourceConverter.toUint8Array(G.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let t=new r({valueHex:this.valueBlock.valueHexView});return t.valueBlock.toDER(),t}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};lu=kt;P.Integer=lu;kt.NAME="INTEGER";var uu,Ho=class extends kt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};uu=Ho;P.Enumerated=uu;Ho.NAME="ENUMERATED";var Sn=class extends ke(Rt){constructor({valueDec:t=-1,isFirstSid:e=!1,...n}={}){super(n),this.valueDec=t,this.isFirstSid=e}fromBER(t,e,n){if(!n)return e;let o=G.BufferSourceConverter.toUint8Array(t);if(!Ce(this,o,e,n))return-1;let s=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=hr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){Bo();let e=BigInt(t).toString(2);for(;e.length%7;)e="0"+e;let n=new Uint8Array(e.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(e.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=Ge(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",ie;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let t="";if(this.isHexOnly)t=G.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let e=this.valueDec;this.valueDec<=39?t="0.":this.valueDec<=79?(t="1.",e-=40):(t="2.",e-=80),t+=e.toString()}else t=this.valueDec.toString();return t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Sn.NAME="sidBlock";var Mo=class extends Rt{constructor({value:t=Vr,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new Sn;if(o=s.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(t){let e=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(t);if(o.byteLength===0)return this.error=this.value[n].error,ie;e.push(o)}return Aa(e)}fromString(t){this.value=[];let e=0,n=0,o="",s=!1;do if(n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new Sn;if(o>Number.MAX_SAFE_INTEGER){Bo();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e?(o=`{${o}}`,this.value[n].isFirstSid?t=`2.{${o} - 80}`:t+=o):t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};Mo.NAME="ObjectIdentifierValueBlock";var fu,Mr=class extends Ct{constructor(t={}){super(t,Mo),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};fu=Mr;P.ObjectIdentifier=fu;Mr.NAME="OBJECT IDENTIFIER";var An=class extends ke(Ae){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let o=G.BufferSourceConverter.toUint8Array(t);if(!Ce(this,o,e,n))return-1;let s=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=hr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=Ge(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",ie;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let t="";return this.isHexOnly?t=G.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};An.NAME="relativeSidBlock";var Vo=class extends Rt{constructor({value:t=Vr,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new An;if(o=s.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(t,e){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(t);if(s.byteLength===0)return this.error=this.value[o].error,ie;n.push(s)}return Aa(n)}fromString(t){this.value=[];let e=0,n=0,o="";do{n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1;let s=new An;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e&&(o=`{${o}}`),t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};Vo.NAME="RelativeObjectIdentifierValueBlock";var hu,Fo=class extends Ct{constructor(t={}){super(t,Vo),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};hu=Fo;P.RelativeObjectIdentifier=hu;Fo.NAME="RelativeObjectIdentifier";var du,Be=class extends je{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};du=Be;P.Sequence=du;Be.NAME="SEQUENCE";var pu,Ko=class extends je{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};pu=Ko;P.Set=pu;Ko.NAME="SET";var $o=class extends ke(Rt){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=Vr}toJSON(){return{...super.toJSON(),value:this.value}}};$o.NAME="StringValueBlock";var Wo=class extends $o{};Wo.NAME="SimpleStringValueBlock";var Ot=class extends ko{constructor({...t}={}){super(t,Wo)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,G.BufferSourceConverter.toUint8Array(t))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);this.valueBlock.value=t}};Ot.NAME="SIMPLE STRING";var qo=class extends Ot{fromBuffer(t){this.valueBlock.valueHexView=G.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=G.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=G.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(G.Convert.FromUtf8String(t)),this.valueBlock.value=t}};qo.NAME="Utf8StringValueBlock";var mu,Ie=class extends qo{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};mu=Ie;P.Utf8String=mu;Ie.NAME="UTF8String";var zo=class extends Ot{fromBuffer(t){this.valueBlock.value=G.Convert.ToUtf16String(t),this.valueBlock.valueHexView=G.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(G.Convert.FromUtf16String(t))}};zo.NAME="BmpStringValueBlock";var gu,Go=class extends zo{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};gu=Go;P.BmpString=gu;Go.NAME="BMPString";var jo=class extends Ot{fromBuffer(t){let e=ArrayBuffer.isView(t)?t.slice().buffer:t.slice(0),n=new Uint8Array(e);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(e))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e*4);for(let o=0;o<e;o++){let s=Ge(t.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=t}};jo.NAME="UniversalStringValueBlock";var wu,Zo=class extends jo{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};wu=Zo;P.UniversalString=wu;Zo.NAME="UniversalString";var yu,Xo=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};yu=Xo;P.NumericString=yu;Xo.NAME="NumericString";var bu,Yo=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};bu=Yo;P.PrintableString=bu;Yo.NAME="PrintableString";var xu,Jo=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};xu=Jo;P.TeletexString=xu;Jo.NAME="TeletexString";var Eu,Qo=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Eu=Qo;P.VideotexString=Eu;Qo.NAME="VideotexString";var vu,ts=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};vu=ts;P.IA5String=vu;ts.NAME="IA5String";var Su,es=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Su=es;P.GraphicString=Su;es.NAME="GraphicString";var Au,Bn=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Au=Bn;P.VisibleString=Au;Bn.NAME="VisibleString";var Bu,rs=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Bu=rs;P.GeneralString=Bu;rs.NAME="GeneralString";var Iu,ns=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Iu=ns;P.CharacterString=Iu;ns.NAME="CharacterString";var Cu,In=class extends Bn{constructor({value:t,valueDate:e,...n}={}){if(super(n),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(let o=0;o<t.length;o++)this.valueBlock.valueHexView[o]=t.charCodeAt(o)}e&&(this.fromDate(e),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(t){this.fromString(String.fromCharCode.apply(null,G.BufferSourceConverter.toUint8Array(t)))}toBuffer(){let t=this.toString(),e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return e}fromDate(t){this.year=t.getUTCFullYear(),this.month=t.getUTCMonth()+1,this.day=t.getUTCDate(),this.hour=t.getUTCHours(),this.minute=t.getUTCMinutes(),this.second=t.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(t){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(t);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(t="iso"){if(t==="iso"){let e=new Array(7);return e[0]=Kt(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=Kt(this.month,2),e[2]=Kt(this.day,2),e[3]=Kt(this.hour,2),e[4]=Kt(this.minute,2),e[5]=Kt(this.second,2),e[6]="Z",e.join("")}return super.toString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};Cu=In;P.UTCTime=Cu;In.NAME="UTCTime";var ku,os=class extends In{constructor(t={}){var e;super(t),(e=this.millisecond)!==null&&e!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(t){super.fromDate(t),this.millisecond=t.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(t){let e=!1,n="",o="",s=0,i,a=0,c=0;if(t[t.length-1]==="Z")n=t.substring(0,t.length-1),e=!0;else{let f=new Number(t[t.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=t}if(e){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,d=n.indexOf("+"),m="";if(d===-1&&(d=n.indexOf("-"),f=-1),d!==-1){if(m=n.substring(d+1),n=n.substring(0,d),m.length!==2&&m.length!==4)throw new Error("Wrong input string for conversion");let x=parseInt(m.substring(0,2),10);if(isNaN(x.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*x,m.length===4){if(x=parseInt(m.substring(2,4),10),isNaN(x.valueOf()))throw new Error("Wrong input string for conversion");c=f*x}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let f=new Number(`0${n.substring(l)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");s=f.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;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 o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=1e3*s;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=i.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(e===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(t="iso"){if(t==="iso"){let e=[];return e.push(Kt(this.year,4)),e.push(Kt(this.month,2)),e.push(Kt(this.day,2)),e.push(Kt(this.hour,2)),e.push(Kt(this.minute,2)),e.push(Kt(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(Kt(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};ku=os;P.GeneralizedTime=ku;os.NAME="GeneralizedTime";var Tu,ss=class extends Ie{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Tu=ss;P.DATE=Tu;ss.NAME="DATE";var Nu,is=class extends Ie{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Nu=is;P.TimeOfDay=Nu;is.NAME="TimeOfDay";var _u,as=class extends Ie{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};_u=as;P.DateTime=_u;as.NAME="DateTime";var Lu,cs=class extends Ie{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Lu=cs;P.Duration=Lu;cs.NAME="Duration";var Ru,ls=class extends Ie{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Ru=ls;P.TIME=Ru;ls.NAME="TIME";function Q(r,t="utf8"){let e=bo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Cn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},fs=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Uu={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new fs("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Ze=Uu;async function Du(r){let t=await Ze.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await Hm(t);return{privateKey:e[0],publicKey:e[1]}}async function Pu(r,t){let e=await Ze.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ze.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Ou(r,t,e){let n=await Ze.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ze.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function Hm(r){if(r.privateKey==null||r.publicKey==null)throw new et("Private and public key are required");return Promise.all([Ze.get().subtle.exportKey("jwk",r.privateKey),Ze.get().subtle.exportKey("jwk",r.publicKey)])}function Ca(r){if(r.kty!=="RSA")throw new et("invalid key type");if(r.n==null)throw new et("invalid key modulus");return rt(r.n,"base64url").length*8}var Fr=class{type="RSA";_key;_raw;_multihash;constructor(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=kn.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return Bt.createV1(114,this._multihash)}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Pt(this.raw,t.raw)}verify(t,e){return Ou(this._key,e,t)}},Tn=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=kn.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Pt(this.raw,t.raw)}sign(t){return Pu(this._key,t)}};var hs=8192,ka=18;function Hu(r){let{result:t}=Ia(r),e=t.valueBlock.value;return{n:he(e[1]),e:he(e[2]),d:he(e[3]),p:he(e[4]),q:he(e[5]),dp:he(e[6]),dq:he(e[7]),qi:he(e[8]),kty:"RSA",alg:"RS256"}}function Mm(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new et("JWK was missing components");let e=new Be({value:[new kt({value:0}),kt.fromBigInt(de(rt(r.n,"base64url"))),kt.fromBigInt(de(rt(r.e,"base64url"))),kt.fromBigInt(de(rt(r.d,"base64url"))),kt.fromBigInt(de(rt(r.p,"base64url"))),kt.fromBigInt(de(rt(r.q,"base64url"))),kt.fromBigInt(de(rt(r.dp,"base64url"))),kt.fromBigInt(de(rt(r.dq,"base64url"))),kt.fromBigInt(de(rt(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function Mu(r){let{result:t}=Ia(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:he(e[0]),e:he(e[1])}}function Ta(r){if(r.n==null||r.e==null)throw new et("JWK was missing components");let e=new Be({value:[new Be({value:[new Mr({value:"1.2.840.113549.1.1.1"}),new Or]}),new Hr({valueHex:new Be({value:[kt.fromBigInt(de(rt(r.n,"base64url"))),kt.fromBigInt(de(rt(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function he(r){let t=r.valueBlock.valueHexView;for(;t[0]===0;)t=t.subarray(1);return Q(t,"base64url")}function de(r){let t=[];return r.forEach(function(e){let n=e.toString(16);n.length%2>0&&(n=`0${n}`),t.push(n)}),BigInt("0x"+t.join(""))}function Vu(r){let t=Hu(r);return Fu(t)}function Na(r){let t=Mu(r);if(Ca(t)>hs)throw new Sr("Key size is too large");let e=ue(le.encode({Type:vt.RSA,Data:r})),n=Vt(ka,e);return new Fr(t,n)}function Fu(r){if(Ca(r)>hs)throw new et("Key size is too large");let t=$u(r),e=ue(le.encode({Type:vt.RSA,Data:Ta(t.publicKey)})),n=Vt(ka,e);return new Tn(t.privateKey,new Fr(t.publicKey,n))}async function Ku(r){if(r>hs)throw new et("Key size is too large");let t=await Du(r),e=ue(le.encode({Type:vt.RSA,Data:Ta(t.publicKey)})),n=Vt(ka,e);return new Tn(t.privateKey,new Fr(t.publicKey,n))}function $u(r){if(r==null)throw new et("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var ds=class extends Nr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,cn(t);let n=He(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(t){return Tr(this),this.iHash.update(t),this}digestInto(t){Tr(this),kr(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Kr=(r,t,e)=>new ds(r,t).update(e).digest();Kr.create=(r,t)=>new ds(r,t);function Wu(r){r.lowS!==void 0&&Jt("lowS",r.lowS),r.prehash!==void 0&&Jt("prehash",r.prehash)}function Vm(r){let t=hn(r);Gt(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:Fm,hexToBytes:Km}=uo,Te={Err:class extends Error{constructor(t=""){super(t)}},_tlv:{encode:(r,t)=>{let{Err:e}=Te;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=or(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?or(o.length/2|128):"";return`${or(r)}${s}${o}${t}`},decode(r,t){let{Err:e}=Te,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=Te;if(r<Ne)throw new t("integer: negative integers are not allowed");let e=or(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected assertion");return e},decode(r){let{Err:t}=Te;if(r[0]&128)throw new t("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return Fm(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Te,o=typeof r=="string"?Km(r):r;Lr(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("Invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("Invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=Te,n=`${t.encode(2,e.encode(r.r))}${t.encode(2,e.encode(r.s))}`;return t.encode(48,n)}},Ne=BigInt(0),St=BigInt(1),vx=BigInt(2),qu=BigInt(3),Sx=BigInt(4);function $m(r){let t=Vm(r),{Fp:e}=t,n=$e(t.n,t.nBitLength),o=t.toBytes||((g,h,w)=>{let b=h.toAffine();return ve(Uint8Array.from([4]),e.toBytes(b.x),e.toBytes(b.y))}),s=t.fromBytes||(g=>{let h=g.subarray(1),w=e.fromBytes(h.subarray(0,e.BYTES)),b=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:w,y:b}});function i(g){let{a:h,b:w}=t,b=e.sqr(g),p=e.mul(b,g);return e.add(e.add(p,e.mul(g,h)),w)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return un(g,St,t.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:w,wrapPrivateKey:b,n:p}=t;if(h&&typeof g!="bigint"){if(Fe(g)&&(g=be(g)),typeof g!="string"||!h.includes(g.length))throw new Error("Invalid key");g=g.padStart(w*2,"0")}let B;try{B=typeof g=="bigint"?g:xe(at("private key",g,w))}catch{throw new Error(`private key must be ${w} bytes, hex or bigint, not ${typeof g}`)}return b&&(B=Y(B,p)),It("private key",B,St,p),B}function l(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let u=ir((g,h)=>{let{px:w,py:b,pz:p}=g;if(e.eql(p,e.ONE))return{x:w,y:b};let B=g.is0();h==null&&(h=B?e.ONE:e.inv(p));let _=e.mul(w,h),N=e.mul(b,h),A=e.mul(p,h);if(B)return{x:e.ZERO,y:e.ZERO};if(!e.eql(A,e.ONE))throw new Error("invZ was invalid");return{x:_,y:N}}),f=ir(g=>{if(g.is0()){if(t.allowInfinityPoint&&!e.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:h,y:w}=g.toAffine();if(!e.isValid(h)||!e.isValid(w))throw new Error("bad point: x or y not FE");let b=e.sqr(w),p=i(h);if(!e.eql(b,p))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,w,b){if(this.px=h,this.py=w,this.pz=b,h==null||!e.isValid(h))throw new Error("x required");if(w==null||!e.isValid(w))throw new Error("y required");if(b==null||!e.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:w,y:b}=h||{};if(!h||!e.isValid(w)||!e.isValid(b))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let p=B=>e.eql(B,e.ZERO);return p(w)&&p(b)?d.ZERO:new d(w,b,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let w=e.invertBatch(h.map(b=>b.pz));return h.map((b,p)=>b.toAffine(w[p])).map(d.fromAffine)}static fromHex(h){let w=d.fromAffine(s(at("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,w){return po(d,n,h,w)}_setWindowSize(h){x.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:w,py:b,pz:p}=this,{px:B,py:_,pz:N}=h,A=e.eql(e.mul(w,N),e.mul(B,p)),k=e.eql(e.mul(b,N),e.mul(_,p));return A&&k}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:w}=t,b=e.mul(w,qu),{px:p,py:B,pz:_}=this,N=e.ZERO,A=e.ZERO,k=e.ZERO,I=e.mul(p,p),V=e.mul(B,B),L=e.mul(_,_),H=e.mul(p,B);return H=e.add(H,H),k=e.mul(p,_),k=e.add(k,k),N=e.mul(h,k),A=e.mul(b,L),A=e.add(N,A),N=e.sub(V,A),A=e.add(V,A),A=e.mul(N,A),N=e.mul(H,N),k=e.mul(b,k),L=e.mul(h,L),H=e.sub(I,L),H=e.mul(h,H),H=e.add(H,k),k=e.add(I,I),I=e.add(k,I),I=e.add(I,L),I=e.mul(I,H),A=e.add(A,I),L=e.mul(B,_),L=e.add(L,L),I=e.mul(L,H),N=e.sub(N,I),k=e.mul(L,V),k=e.add(k,k),k=e.add(k,k),new d(N,A,k)}add(h){l(h);let{px:w,py:b,pz:p}=this,{px:B,py:_,pz:N}=h,A=e.ZERO,k=e.ZERO,I=e.ZERO,V=t.a,L=e.mul(t.b,qu),H=e.mul(w,B),K=e.mul(b,_),C=e.mul(p,N),T=e.add(w,b),E=e.add(B,_);T=e.mul(T,E),E=e.add(H,K),T=e.sub(T,E),E=e.add(w,p);let y=e.add(B,N);return E=e.mul(E,y),y=e.add(H,C),E=e.sub(E,y),y=e.add(b,p),A=e.add(_,N),y=e.mul(y,A),A=e.add(K,C),y=e.sub(y,A),I=e.mul(V,E),A=e.mul(L,C),I=e.add(A,I),A=e.sub(K,I),I=e.add(K,I),k=e.mul(A,I),K=e.add(H,H),K=e.add(K,H),C=e.mul(V,C),E=e.mul(L,E),K=e.add(K,C),C=e.sub(H,C),C=e.mul(V,C),E=e.add(E,C),H=e.mul(K,E),k=e.add(k,H),H=e.mul(y,E),A=e.mul(T,A),A=e.sub(A,H),H=e.mul(T,K),I=e.mul(y,I),I=e.add(I,H),new d(A,k,I)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return x.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){It("scalar",h,Ne,t.n);let w=d.ZERO;if(h===Ne)return w;if(h===St)return this;let{endo:b}=t;if(!b)return x.unsafeLadder(this,h);let{k1neg:p,k1:B,k2neg:_,k2:N}=b.splitScalar(h),A=w,k=w,I=this;for(;B>Ne||N>Ne;)B&St&&(A=A.add(I)),N&St&&(k=k.add(I)),I=I.double(),B>>=St,N>>=St;return p&&(A=A.negate()),_&&(k=k.negate()),k=new d(e.mul(k.px,b.beta),k.py,k.pz),A.add(k)}multiply(h){let{endo:w,n:b}=t;It("scalar",h,St,b);let p,B;if(w){let{k1neg:_,k1:N,k2neg:A,k2:k}=w.splitScalar(h),{p:I,f:V}=this.wNAF(N),{p:L,f:H}=this.wNAF(k);I=x.constTimeNegate(_,I),L=x.constTimeNegate(A,L),L=new d(e.mul(L.px,w.beta),L.py,L.pz),p=I.add(L),B=V.add(H)}else{let{p:_,f:N}=this.wNAF(h);p=_,B=N}return d.normalizeZ([p,B])[0]}multiplyAndAddUnsafe(h,w,b){let p=d.BASE,B=(N,A)=>A===Ne||A===St||!N.equals(p)?N.multiplyUnsafe(A):N.multiply(A),_=B(this,w).add(B(h,b));return _.is0()?void 0:_}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:w}=t;if(h===St)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:w}=t;return h===St?this:w?w(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return Jt("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return Jt("isCompressed",h),be(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let m=t.nBitLength,x=ho(d,t.endo?Math.ceil(m/2):m);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function Wm(r){let t=hn(r);return Gt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function zu(r){let t=Wm(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(C){return Y(C,n)}function a(C){return fo(C,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=$m({...t,toBytes(C,T,E){let y=T.toAffine(),S=e.toBytes(y.x),v=ve;return Jt("isCompressed",E),E?v(Uint8Array.from([T.hasEvenY()?2:3]),S):v(Uint8Array.from([4]),S,e.toBytes(y.y))},fromBytes(C){let T=C.length,E=C[0],y=C.subarray(1);if(T===o&&(E===2||E===3)){let S=xe(y);if(!un(S,St,e.ORDER))throw new Error("Point is not on curve");let v=u(S),R;try{R=e.sqrt(v)}catch($){let W=$ instanceof Error?": "+$.message:"";throw new Error("Point is not on curve"+W)}let D=(R&St)===St;return(E&1)===1!==D&&(R=e.neg(R)),{x:S,y:R}}else if(T===s&&E===4){let S=e.fromBytes(y.subarray(0,e.BYTES)),v=e.fromBytes(y.subarray(e.BYTES,2*e.BYTES));return{x:S,y:v}}else throw new Error(`Point of length ${T} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),d=C=>be(Ke(C,t.nByteLength));function m(C){let T=n>>St;return C>T}function x(C){return m(C)?i(-C):C}let g=(C,T,E)=>xe(C.slice(T,E));class h{constructor(T,E,y){this.r=T,this.s=E,this.recovery=y,this.assertValidity()}static fromCompact(T){let E=t.nByteLength;return T=at("compactSignature",T,E*2),new h(g(T,0,E),g(T,E,2*E))}static fromDER(T){let{r:E,s:y}=Te.toSig(at("DER",T));return new h(E,y)}assertValidity(){It("r",this.r,St,n),It("s",this.s,St,n)}addRecoveryBit(T){return new h(this.r,this.s,T)}recoverPublicKey(T){let{r:E,s:y,recovery:S}=this,v=N(at("msgHash",T));if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");let R=S===2||S===3?E+t.n:E;if(R>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let D=S&1?"03":"02",M=c.fromHex(D+d(R)),$=a(R),W=i(-v*$),z=i(y*$),Z=c.BASE.multiplyAndAddUnsafe(M,W,z);if(!Z)throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return sr(this.toDERHex())}toDERHex(){return Te.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return sr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let w={isValidPrivateKey(C){try{return l(C),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let C=Hi(t.n);return vl(t.randomBytes(C),t.n)},precompute(C=8,T=c.BASE){return T._setWindowSize(C),T.multiply(BigInt(3)),T}};function b(C,T=!0){return c.fromPrivateKey(C).toRawBytes(T)}function p(C){let T=Fe(C),E=typeof C=="string",y=(T||E)&&C.length;return T?y===o||y===s:E?y===2*o||y===2*s:C instanceof c}function B(C,T,E=!0){if(p(C))throw new Error("first arg must be private key");if(!p(T))throw new Error("second arg must be public key");return c.fromHex(T).multiply(l(C)).toRawBytes(E)}let _=t.bits2int||function(C){let T=xe(C),E=C.length*8-t.nBitLength;return E>0?T>>BigInt(E):T},N=t.bits2int_modN||function(C){return i(_(C))},A=fn(t.nBitLength);function k(C){return It(`num < 2^${t.nBitLength}`,C,Ne,A),Ke(C,t.nByteLength)}function I(C,T,E=V){if(["recovered","canonical"].some(it=>it in E))throw new Error("sign() legacy options not supported");let{hash:y,randomBytes:S}=t,{lowS:v,prehash:R,extraEntropy:D}=E;v==null&&(v=!0),C=at("msgHash",C),Wu(E),R&&(C=at("prehashed msgHash",y(C)));let M=N(C),$=l(T),W=[k($),k(M)];if(D!=null&&D!==!1){let it=D===!0?S(e.BYTES):D;W.push(at("extraEntropy",it))}let z=ve(...W),Z=M;function st(it){let ft=_(it);if(!f(ft))return;let Dt=a(ft),yt=c.BASE.multiply(ft).toAffine(),Mt=i(yt.x);if(Mt===Ne)return;let pe=i(Dt*i(Z+Mt*$));if(pe===Ne)return;let tn=(yt.x===Mt?0:2)|Number(yt.y&St),en=pe;return v&&m(pe)&&(en=x(pe),tn^=1),new h(Mt,en,tn)}return{seed:z,k2sig:st}}let V={lowS:t.lowS,prehash:!1},L={lowS:t.lowS,prehash:!1};function H(C,T,E=V){let{seed:y,k2sig:S}=I(C,T,E),v=t;return Ri(v.hash.outputLen,v.nByteLength,v.hmac)(y,S)}c.BASE._setWindowSize(8);function K(C,T,E,y=L){let S=C;if(T=at("msgHash",T),E=at("publicKey",E),"strict"in y)throw new Error("options.strict was renamed to lowS");Wu(y);let{lowS:v,prehash:R}=y,D,M;try{if(typeof S=="string"||Fe(S))try{D=h.fromDER(S)}catch(yt){if(!(yt instanceof Te.Err))throw yt;D=h.fromCompact(S)}else if(typeof S=="object"&&typeof S.r=="bigint"&&typeof S.s=="bigint"){let{r:yt,s:Mt}=S;D=new h(yt,Mt)}else throw new Error("PARSE");M=c.fromHex(E)}catch(yt){if(yt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(v&&D.hasHighS())return!1;R&&(T=t.hash(T));let{r:$,s:W}=D,z=N(T),Z=a(W),st=i(z*Z),it=i($*Z),ft=c.BASE.multiplyAndAddUnsafe(M,st,it)?.toAffine();return ft?i(ft.x)===$:!1}return{CURVE:t,getPublicKey:b,getSharedSecret:B,sign:H,verify:K,ProjectivePoint:c,Signature:h,utils:w}}function qm(r){return{hash:r,hmac:(t,...e)=>Kr(r,t,Bi(...e)),randomBytes:ln}}function Gu(r,t){let e=n=>zu({...r,...qm(n)});return Object.freeze({...e(t),create:e})}var Xu=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),ju=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),zm=BigInt(1),_a=BigInt(2),Zu=(r,t)=>(r+t/_a)/t;function Gm(r){let t=Xu,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=ct(u,e,t)*u%t,d=ct(f,e,t)*u%t,m=ct(d,_a,t)*l%t,x=ct(m,o,t)*m%t,g=ct(x,s,t)*x%t,h=ct(g,a,t)*g%t,w=ct(h,c,t)*h%t,b=ct(w,a,t)*g%t,p=ct(b,e,t)*u%t,B=ct(p,i,t)*x%t,_=ct(B,n,t)*l%t,N=ct(_,_a,t);if(!La.eql(La.sqr(N),r))throw new Error("Cannot find square root");return N}var La=$e(Xu,void 0,void 0,{sqrt:Gm}),dr=Gu({a:BigInt(0),b:BigInt(7),Fp:La,n:ju,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=ju,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-zm*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=Zu(s*r,t),c=Zu(-n*r,t),l=Y(r-a*e-c*o,t),u=Y(-a*n-c*s,t),f=l>i,d=u>i;if(f&&(l=t-l),d&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},ue),Lx=BigInt(0);var Rx=dr.ProjectivePoint;function At(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=Et(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}function Yu(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Ju(r,t,e){let n=gn.digest(e instanceof Uint8Array?e:e.subarray());if(Yu(n))return n.then(({digest:o})=>dr.verify(t,o,r)).catch(o=>{throw new Cn(String(o))});try{return dr.verify(t,n.digest,r)}catch(o){throw new Cn(String(o))}}var ps=class{type="secp256k1";raw;_key;constructor(t){this._key=tf(t),this.raw=Qu(this._key)}toMultihash(){return we.digest(Ur(this))}toCID(){return Bt.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Pt(this.raw,t.raw)}verify(t,e){return Ju(this._key,e,t)}};function Ra(r){return new ps(r)}function Qu(r){return dr.ProjectivePoint.fromHex(r).toRawBytes(!0)}function tf(r){try{return dr.ProjectivePoint.fromHex(r),r}catch(t){throw new Sr(String(t))}}function Nn(r){let{Type:t,Data:e}=le.decode(r),n=e??new Uint8Array;switch(t){case vt.RSA:return Na(n);case vt.Ed25519:return $i(n);case vt.secp256k1:return Ra(n);default:throw new er}}function ef(r){let{Type:t,Data:e}=le.decode(r.digest),n=e??new Uint8Array;switch(t){case vt.Ed25519:return $i(n);case vt.secp256k1:return Ra(n);default:throw new er}}function Ur(r){return le.encode({Type:vt[r.type],Data:r.raw})}var rf=Symbol.for("nodejs.util.inspect.custom"),Zm=114,_n=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[di]=!0;toString(){return this.string==null&&(this.string=ot.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Bt.createV1(Zm,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Pt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Pt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[rf](){return`PeerId(${this.toString()})`}},Ln=class extends _n{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Rn=class extends _n{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Un=class extends _n{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Xm=2336,ms=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=we.digest(rt(this.url))}[rf](){return`PeerId(${this.url})`}[di]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Bt.createV1(Xm,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=Q(t)),t.toString()===this.toString())}};function $r(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Oe(ot.decode(`z${r}`));else{if(t==null)throw new et('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Oe(t.decode(r))}return Ym(e)}function Ua(r){if(r.type==="Ed25519")return new Rn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Un({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Ln({multihash:r.toCID().multihash,publicKey:r});throw new er}function Ym(r){if(Qm(r))return new Ln({multihash:r});if(Jm(r))try{let t=ef(r);if(t.type==="Ed25519")return new Rn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Un({multihash:r,publicKey:t})}catch{let e=Q(r.digest);return new ms(new URL(e))}throw new to("Supplied PeerID Multihash is invalid")}function Jm(r){return r.code===we.code}function Qm(r){return r.code===gn.code}var gs=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}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(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=t,s+=u,s>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var nf=45,e0=15,Wr=new gs;function Da(r){if(!(r.length>e0))return Wr.new(r).parseWith(()=>Wr.readIPv4Addr())}function Pa(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>nf))return Wr.new(r).parseWith(()=>Wr.readIPv6Addr())}function ws(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>nf))return Wr.new(r).parseWith(()=>Wr.readIPAddr())}var G1=parseInt("0xFFFF",16),j1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function ys(r){return!!Da(r)}function bs(r){return!!Pa(r)}function xs(r){return!!ws(r)}var af=ys,i0=bs,Oa=function(r){let t=0;if(r=r.toString().trim(),af(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(i0(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=af(e[n]),i;s&&(i=Oa(e[n]),e[n]=Q(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,Q(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let s=parseInt(e[n],16);o[t++]=s>>8&255,o[t++]=s&255}return o}throw new Error("invalid ip address")},cf=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var qr={},Ha={},c0=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"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,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];c0.forEach(r=>{let t=l0(...r);Ha[t.code]=t,qr[t.name]=t});function l0(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function tt(r){if(typeof r=="number"){if(Ha[r]!=null)return Ha[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(qr[r]!=null)return qr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var _2=tt("ip4"),L2=tt("ip6"),R2=tt("ipcidr");function Ka(r,t){switch(tt(r).code){case 4:case 41:return f0(t);case 42:return Fa(t);case 6:case 273:case 33:case 132:return ff(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Fa(t);case 421:return m0(t);case 444:return uf(t);case 445:return uf(t);case 466:return p0(t);case 481:return globalThis.encodeURIComponent(Fa(t));default:return Q(t,"base16")}}function $a(r,t){switch(tt(r).code){case 4:return lf(t);case 41:return lf(t);case 42:return Va(t);case 6:case 273:case 33:case 132:return Wa(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Va(t);case 421:return h0(t);case 444:return g0(t);case 445:return w0(t);case 466:return d0(t);case 481:return Va(globalThis.decodeURIComponent(t));default:return rt(t,"base16")}}var Ma=Object.values(lr).map(r=>r.decoder),u0=function(){let r=Ma[0].or(Ma[1]);return Ma.slice(2).forEach(t=>r=r.or(t)),r}();function lf(r){if(!xs(r))throw new Error("invalid ip address");return Oa(r)}function f0(r){let t=cf(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!xs(t))throw new Error("invalid ip address");return t}function Wa(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function ff(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Va(r){let t=rt(r),e=Uint8Array.from(ce(t.length));return At([e,t],e.length+t.length)}function Fa(r){let t=ee(r);if(r=r.slice(lt(t)),r.length!==t)throw new Error("inconsistent lengths");return Q(r)}function h0(r){let t;r[0]==="Q"||r[0]==="1"?t=Oe(ot.decode(`z${r}`)).bytes:t=Bt.parse(r).multihash.bytes;let e=Uint8Array.from(ce(t.length));return At([e,t],e.length+t.length)}function d0(r){let t=u0.decode(r),e=Uint8Array.from(ce(t.length));return At([e,t],e.length+t.length)}function p0(r){let t=ee(r),e=r.slice(lt(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+Q(e,"base64url")}function m0(r){let t=ee(r),e=r.slice(lt(t));if(e.length!==t)throw new Error("inconsistent lengths");return Q(e,"base58btc")}function g0(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=ge.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Wa(n);return At([e,o],e.length+o.length)}function w0(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=ge.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Wa(n);return At([e,o],e.length+o.length)}function uf(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=Q(t,"base32"),o=ff(e);return`${n}:${o}`}function hf(r){r=qa(r);let t=[],e=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=tt(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw pf("invalid address: "+r);if(a.path===!0){n=qa(o.slice(s).join("/")),t.push([a.code,$a(a.code,n)]),e.push([a.code,n]);break}let c=$a(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Ka(a.code,c)])}return{string:df(e),bytes:Ga(t),tuples:t,stringTuples:e,path:n}}function za(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=ee(r,o),i=lt(s),a=tt(s),c=y0(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let l=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw pf("Invalid address Uint8Array: "+Q(r,"base16"));t.push([s,l]);let u=Ka(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:df(e),tuples:t,stringTuples:e,path:n}}function df(r){let t=[];return r.map(e=>{let n=tt(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),qa(t.join("/"))}function Ga(r){return At(r.map(t=>{let e=tt(t[0]),n=Uint8Array.from(ce(e.code));return t.length>1&&t[1]!=null&&(n=At([n,t[1]])),n}))}function y0(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=ee(t instanceof Uint8Array?t:Uint8Array.from(t));return e+lt(e)}}function qa(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function pf(r){return new Error("Error parsing address: "+r)}var b0=Symbol.for("nodejs.util.inspect.custom"),Za=Symbol.for("@multiformats/js-multiaddr/multiaddr"),x0=[tt("dns").code,tt("dns4").code,tt("dns6").code,tt("dnsaddr").code],ja=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},Es=class r{bytes;#t;#e;#r;#n;[Za]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=za(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=hf(t)}else if(gf(t))e=za(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="",i=tt("tcp"),a=tt("udp"),c=tt("ip4"),l=tt("ip6"),u=tt("dns6"),f=tt("ip6zone");for(let[m,x]of this.stringTuples())m===f.code&&(s=`%${x??""}`),x0.includes(m)&&(e=i.name,o=443,n=`${x??""}${s}`,t=m===u.code?6:4),(m===i.code||m===a.code)&&(e=tt(m).name,o=parseInt(x??"")),(m===c.code||m===l.code)&&(e=tt(m).name,n=`${x??""}${s}`,t=m===l.code?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}protos(){return this.#e.map(([t])=>Object.assign({},tt(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>tt(t).name)}tuples(){return this.#e}stringTuples(){return this.#r}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(Ga(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===qr.p2p.code&&t.push([n,o]),n===qr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?Q(ot.decode(`z${n}`),"base58btc"):Q(Bt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return Pt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=mf.get(e.name);if(n==null)throw new ja(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>ae(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[b0](){return`Multiaddr(${this.#t})`}};var mf=new Map;function gf(r){return!!r?.[Za]}function ae(r){return new Es(r)}var E0=r=>r.toString().split("/").slice(1),zr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),j=r=>({match:t=>zr(e=>e===r).match(t),pattern:r}),pr=()=>({match:r=>zr(t=>typeof t=="string").match(r),pattern:"{string}"}),Dn=()=>({match:r=>zr(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),ut=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{ot.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),Pn=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{sa.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),nt=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Ut=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),X=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function pt(...r){function t(o){let s=E0(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var Ss=X(j("dns4"),pr()),As=X(j("dns6"),pr()),Bs=X(j("dnsaddr"),pr()),Ya=X(j("dns"),pr()),cE=pt(Ss,nt(ut())),lE=pt(As,nt(ut())),uE=pt(Bs,nt(ut())),fE=pt(Ut(Ya,Bs,Ss,As),nt(ut())),wf=X(j("ip4"),zr(ys)),yf=X(j("ip6"),zr(bs)),Ja=Ut(wf,yf),_e=Ut(Ja,Ya,Ss,As,Bs),hE=pt(Ut(Ja,X(Ut(Ya,Bs,Ss,As),nt(ut())))),dE=pt(wf),pE=pt(yf),mE=pt(Ja),Qa=X(_e,j("tcp"),Dn()),On=X(_e,j("udp"),Dn()),gE=pt(X(Qa,nt(ut()))),wE=pt(On),tc=X(On,j("quic")),Is=X(On,j("quic-v1")),v0=Ut(tc,Is),yE=pt(tc),bE=pt(Is),Xa=Ut(_e,Qa,On,tc,Is),bf=Ut(X(Xa,j("ws"),nt(ut()))),xE=pt(bf),xf=Ut(X(Xa,j("wss"),nt(ut())),X(Xa,j("tls"),nt(X(j("sni"),pr())),j("ws"),nt(ut()))),EE=pt(xf),Ef=X(On,j("webrtc-direct"),nt(Pn()),nt(Pn()),nt(ut())),vf=pt(Ef),Sf=X(Is,j("webtransport"),nt(Pn()),nt(Pn()),nt(ut())),vE=pt(Sf),vs=Ut(bf,xf,X(Qa,nt(ut())),X(v0,nt(ut())),X(_e,nt(ut())),Ef,Sf,ut()),SE=pt(vs),S0=X(vs,j("p2p-circuit"),ut()),AE=pt(S0),A0=Ut(X(vs,j("p2p-circuit"),j("webrtc"),nt(ut())),X(vs,j("webrtc"),nt(ut())),j("webrtc")),Af=pt(A0),B0=Ut(X(_e,j("tcp"),Dn(),j("http"),nt(ut())),X(_e,j("http"),nt(ut()))),BE=pt(B0),I0=Ut(X(_e,j("tcp"),Ut(X(j("443"),j("http")),X(Dn(),j("https"))),nt(ut())),X(_e,j("tls"),j("http"),nt(ut())),X(_e,j("https"),nt(ut()))),IE=pt(I0),C0=Ut(X(j("memory"),pr(),nt(ut()))),CE=pt(C0);var Bf=function(r,t,e){if(e||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return r.concat(s||Array.prototype.slice.call(t))},k0=function(){function r(t,e,n){this.name=t,this.version=e,this.os=n,this.type="browser"}return r}();var T0=function(){function r(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return r}();var N0=function(){function r(t,e,n,o){this.name=t,this.version=e,this.os=n,this.bot=o,this.type="bot-device"}return r}();var _0=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var L0=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var R0=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,U0=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,If=3,D0=[["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",R0]],Cf=[["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/]];function Tf(r){return r?kf(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new L0:typeof navigator<"u"?kf(navigator.userAgent):H0()}function P0(r){return r!==""&&D0.reduce(function(t,e){var n=e[0],o=e[1];if(t)return t;var s=o.exec(r);return!!s&&[n,s]},!1)}function kf(r){var t=P0(r);if(!t)return null;var e=t[0],n=t[1];if(e==="searchbot")return new _0;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<If&&(o=Bf(Bf([],o,!0),M0(If-o.length),!0)):o=[];var s=o.join("."),i=O0(r),a=U0.exec(r);return a&&a[1]?new N0(e,s,i,a[1]):new k0(e,s,i)}function O0(r){for(var t=0,e=Cf.length;t<e;t++){var n=Cf[t],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function H0(){var r=typeof process<"u"&&process.version;return r?new T0(process.version.slice(1)):null}function M0(r){for(var t=[],e=0;e<r;e++)t.push("0");return t}function gt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var ec=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},rc=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Nf=r=>globalThis.DOMException===void 0?new rc(r):new DOMException(r),_f=r=>{let t=r.reason===void 0?Nf("This operation was aborted."):r.reason;return t instanceof Error?t:Nf(t)};function mr(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,c=new Promise((l,u)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:d}=t;d.aborted&&u(_f(d));let m=()=>{u(_f(d))};d.addEventListener("abort",m,{once:!0}),r.finally(()=>{d.removeEventListener("abort",m)})}if(e===Number.POSITIVE_INFINITY){r.then(l,u);return}let f=new ec;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(d){u(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?u(o):(f.message=o??`Promise timed out after ${e} milliseconds`,u(f))},e),(async()=>{try{l(await r)}catch(d){u(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}var Lf=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"];var Rf=Tf(),Hn=Rf!=null&&Rf.name==="firefox",Cs=async function*(){},ks=async r=>{},V0=30*1e3;function Uf(r,t,e=V0,n){r.readyState==="open"&&Promise.resolve().then(async()=>{if(r.bufferedAmount>0){n.log("%s drain channel with %d buffered bytes",t,r.bufferedAmount);let o=gt(),s=!1;r.bufferedAmountLowThreshold=0;let i=()=>{s||(n.log("%s drain channel closed before drain",t),o.resolve())};r.addEventListener("close",i,{once:!0}),r.addEventListener("bufferedamountlow",()=>{s=!0,r.removeEventListener("close",i),o.resolve()}),await mr(o.promise,{milliseconds:e})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function Mn(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??Lf.map(t=>({urls:[t]})),r}var gr=class{log;peerConnection;remoteAddr;timeline;metrics;source=Cs();sink=ks;constructor(t,e){this.log=t.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=e.remoteAddr,this.timeline=e.timeline,this.peerConnection=e.peerConnection;let n=this.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",this.peerConnection.connectionState,"initial state",n),(this.peerConnection.connectionState==="disconnected"||this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.timeline.close=Date.now())}}async close(t){this.log.trace("closing connection"),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({close:!0})}abort(t){this.log.error("closing connection due to error",t),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({abort:!0})}};var Ts=class{buffer;mask;top;btm;next;constructor(t){if(!(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(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Gr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Ts(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new Ts(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var nc=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Xe(r={}){return F0(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function F0(r,t){t=t??{};let e=t.onEnd,n=new Gr,o,s,i,a=gt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,w)=>{s=b=>{s=null,n.push(b);try{h(r(n))}catch(p){w(p)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=gt()})}},l=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new Gr,s!=null?s({error:h}):(n.push({error:h}),o)),f=h=>{if(i)return o;if(t?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:h})},d=h=>i?o:(i=!0,h!=null?u(h):l({done:!0})),m=()=>(n=new Gr,d(),{done:!0}),x=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:x,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let w=h?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let b,p;w!=null&&(b=new Promise((B,_)=>{p=()=>{_(new nc)},w.addEventListener("abort",p)}));try{await Promise.race([a.promise,b])}finally{p!=null&&w!=null&&w?.removeEventListener("abort",p)}}},e==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(h){return g.throw(h),e!=null&&(e(h),e=void 0),{done:!0}},return(){return g.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(h){return g.end(h),e!=null&&(e(h),e=void 0),o},get readableLength(){return g.readableLength},onEmpty:h=>g.onEmpty(h)},o}var Ns=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function Le(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new Ns(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new Ns(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var Pf=Symbol.for("@achingbrain/uint8arraylist");function Df(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function _s(r){return!!r?.[Pf]}var dt=class r{bufs;length;[Pf]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(_s(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(_s(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Df(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Df(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(_s(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return At(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:At(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!_s(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=e;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let m=this.get(f+d);if(n[d]!==m){u=Math.max(1,d-a[m]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=Et(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=xt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=xt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=xt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=Et(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=xt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=xt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=xt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=xt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=xt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Pt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};function Of(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function Hf(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Mf(r,t){let e=Of(r).return?.();Hf(e)&&e.catch(n=>{t.error("could not cause iterator to return",n)})}var K0=5e3;function oc(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ls=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(t){this.sinkController=new AbortController,this.sinkEnd=gt(),this.closed=gt(),this.log=t.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=t.id,this.metadata=t.metadata??{},this.direction=t.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=t.sendCloseWriteTimeout??K0,this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=Xe({onEnd:e=>{e!=null?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(t){if(this.writeStatus!=="ready")throw new tr(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";let e={signal:this.sinkController.signal};if(this.direction==="outbound"){let o=this.sendNewStream(e);oc(o)&&await o}let n=()=>{Mf(t,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let o of t){o=o instanceof Uint8Array?new dt(o):o;let s=this.sendData(o,e);oc(s)&&(this.sendingData=gt(),await s,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",n)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(t){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(t){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(t){this.log.trace("closing gracefully"),this.status="closing",await Le(Promise.all([this.closeWrite(t),this.closeRead(t),this.closed.promise]),t?.signal),this.status="closed",this.log.trace("closed gracefully")}async closeRead(t={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let e=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(t)),e==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(t={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await Le(this.sink([]),t.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await Le(this.sendingData.promise,t.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await Le(this.sinkEnd.promise,t.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(t){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",t),this.log("try to send reset to remote");let e=this.sendReset();oc(e)&&e.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(t),this.onAbort?.(t)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let t=new Qn("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(t),this.onReset?.()}_closeSinkAndSource(t){this._closeSink(t),this._closeSource(t)}_closeSink(t){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(t)}_closeSource(t){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(t))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(t){this.streamSource.push(t)}sourceReadableLength(){return this.streamSource.readableLength}};function Rs(r){return r[Symbol.asyncIterator]!=null}var Us=r=>{let t=lt(r),e=Et(t);return ce(r,e),Us.bytes=t,e};Us.bytes=0;function Vn(r,t){t=t??{};let e=t.lengthEncoder??Us;function*n(o){let s=e(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Rs(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Vn.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Us;return new dt(e(r.byteLength),r)};var Ds=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ps=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Os=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Fn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var $0=8,W0=1024*1024*4,wr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(wr||(wr={}));var sc=r=>{let t=ee(r);return sc.bytes=lt(t),t};sc.bytes=0;function yr(r,t){let e=new dt,n=wr.LENGTH,o=-1,s=t?.lengthDecoder??sc,i=t?.maxLengthLength??$0,a=t?.maxDataLength??W0;function*c(){for(;e.byteLength>0;){if(n===wr.LENGTH)try{if(o=s(e),o<0)throw new Ds("Invalid message length");if(o>a)throw new Ps("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=wr.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Os("Message length length too long");break}throw l}if(n===wr.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=wr.LENGTH}}}return Rs(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Fn("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Fn("Unexpected end of input")}()}yr.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return yr(n,{...t??{},onLength:s=>{e=s}})};var z0=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function G0(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:u}=z0(r),f=(...m)=>{let x=e.multiArgs?m:m[0];e.filter&&!e.filter(x)||(c.push(x),e.count===c.length&&(n(),s(c)))},d=m=>{n(),i(m)};n=()=>{for(let m of a)u(m,f);for(let m of e.rejectionEvents)u(m,d)};for(let m of a)l(m,f);for(let m of e.rejectionEvents)l(m,d);e.signal&&e.signal.addEventListener("abort",()=>{d(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=mr(o,{milliseconds:e.timeout});return s.cancel=n,s}return o}function ic(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=G0(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var Ht;(function(r){let t;(function(o){o.FIN="FIN",o.STOP_SENDING="STOP_SENDING",o.RESET="RESET",o.FIN_ACK="FIN_ACK"})(t=r.Flag||(r.Flag={}));let e;(function(o){o[o.FIN=0]="FIN",o[o.STOP_SENDING=1]="STOP_SENDING",o[o.RESET=2]="RESET",o[o.FIN_ACK=3]="FIN_ACK"})(e||(e={})),function(o){o.codec=()=>fr(e)}(t=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=se((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.flag!=null&&(s.uint32(8),r.Flag.codec().encode(o.flag,s)),o.message!=null&&(s.uint32(18),s.bytes(o.message)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.flag=r.Flag.codec().decode(o);break}case 2:{a.message=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>oe(o,r.codec()),r.decode=(o,s)=>ne(o,r.codec(),s)})(Ht||(Ht={}));var j0=2*1024*1024,Z0=30*1e3,Hs=16*1024;function X0(r=Hs){let t=lt(r-lt(r)),e=1+lt(Object.keys(Ht.Flag).length-1),n=1,o=r-t-e-n,s=lt(o);return t+e+n+s}var Y0=X0(),J0=5e3,Q0=5e3,ac=class extends Ls{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;constructor(t){let e=t.onEnd;switch(t.onEnd=o=>{this.log.trace("readable and writeable ends closed",this.status),Promise.resolve(async()=>{if(!(this.timeline.abort!=null||this.timeline.reset!==null))try{await mr(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(s){this.log.error("error receiving FIN_ACK",s)}}).then(()=>{this.incomingData.end(),e?.(o)}).catch(s=>{this.log.error("error ending stream",s)})},super(t),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=Xe(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??Z0,this.maxBufferedAmount=t.maxBufferedAmount??j0,this.maxMessageSize=(t.maxMessageSize??Hs)-Y0,this.receiveFinAck=gt(),this.finAckTimeout=t.closeTimeout??J0,this.openTimeout=t.openTimeout??Q0,this.channel.readyState){case"open":this.timeline.open=new Date().getTime();break;case"closed":case"closing":(this.timeline.close===void 0||this.timeline.close===0)&&(this.timeline.close=Date.now());break;case"connecting":break;default:throw this.log.error("unknown datachannel state %s",this.channel.readyState),new tr("Unknown datachannel state")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime()},this.channel.onclose=o=>{this.receiveFinAck.resolve(),this.close().catch(s=>{this.log.error("error closing stream after channel closed",s)})},this.channel.onerror=o=>{let s=o.error;this.abort(s)},this.channel.onmessage=async o=>{let{data:s}=o;s===null||s.byteLength===0||this.incomingData.push(new Uint8Array(s,0,s.byteLength))};let n=this;Promise.resolve().then(async()=>{for await(let o of yr(this.incomingData)){let s=n.processIncomingProtobuf(o);s!=null&&n.sourcePush(new dt(s))}}).catch(o=>{this.log.error("error processing incoming data channel messages",o)})}sendNewStream(){}async _sendMessage(t,e=!0){if(e&&this.channel.bufferedAmount>this.maxBufferedAmount)try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await ic(this.channel,"bufferedamountlow",{timeout:this.bufferedAmountLowEventTimeout})}catch(n){throw n instanceof rn?new rn(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`):n}if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new tr(`Invalid datachannel state - ${this.channel.readyState}`);this.channel.readyState!=="open"&&(this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await ic(this.channel,"open",{timeout:this.openTimeout}),this.log('channel state is now "%s", sending data',this.channel.readyState)),this.channel.send(t.subarray())}async sendData(t){for(t=t.sublist();t.byteLength>0;){let e=Math.min(t.byteLength,this.maxMessageSize),n=t.subarray(0,e),o=Ht.encode({message:n}),s=Vn.single(o);await this._sendMessage(s),t.consume(e)}}async sendReset(){await this._sendFlag(Ht.Flag.RESET)}async sendCloseWrite(t){if(await this._sendFlag(Ht.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await Le(this.receiveFinAck.promise,t?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorName:"FinAckNotReceivedError"})}catch(n){this.log.error("failed to await FIN_ACK",n)}}else this.log.trace("sending FIN failed, not awaiting FIN_ACK");this.receiveFinAck.resolve()}async sendCloseRead(){await this._sendFlag(Ht.Flag.STOP_SENDING)}processIncomingProtobuf(t){let e=Ht.decode(t);if(e.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',e.flag,this.writeStatus,this.readStatus),e.flag===Ht.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Ht.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),e.flag===Ht.Flag.RESET&&this.reset(),e.flag===Ht.Flag.STOP_SENDING&&this.remoteCloseRead(),e.flag===Ht.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),this.readStatus==="ready")return e.message}async _sendFlag(t){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',this.channel.readyState,t.toString()),!1;this.log.trace("sending flag %s",t.toString());let e=Ht.encode({flag:t}),n=Vn.single(e);try{return await this._sendMessage(n,!1),!0}catch(o){this.log.error("could not send flag %s",t.toString(),o)}return!1}};function jr(r){let{channel:t,direction:e}=r;return new ac({id:e==="inbound"?`i${t.id}`:`r${t.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${e}:${t.id}`),...r})}var Vf="/webrtc",Ye=class{protocol;peerConnection;bufferedStreams=[];metrics;dataChannelOptions;components;log;constructor(t,e){this.components=t,this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??Vf,this.dataChannelOptions=e.dataChannelOptions??{},this.log=t.logger.forComponent("libp2p:webrtc:datachannelmuxerfactory"),this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace('incoming early datachannel with channel id %d and label "%s"',n.id),n.label==="init"){this.log.trace("closing early init channel"),n.close();return}let o={},s=jr({channel:n,direction:"inbound",onEnd:i=>{o.onEnd(i)},logger:t.logger,...this.dataChannelOptions});o.stream=s,o.channel=n,o.onEnd=()=>{this.bufferedStreams=this.bufferedStreams.filter(i=>i.stream.id!==s.id)},this.bufferedStreams.push(o)}}createStreamMuxer(t){return new cc(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},cc=class{init;streams;protocol;log;peerConnection;dataChannelOptions;metrics;logger;constructor(t,e){this.init=e,this.log=t.logger.forComponent("libp2p:webrtc:muxer"),this.logger=t.logger,this.streams=e.streams.map(n=>n.stream),this.peerConnection=e.peerConnection,this.protocol=e.protocol??Vf,this.metrics=e.metrics,this.dataChannelOptions=e.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace("incoming datachannel with channel id %d",n.id),n.label==="init"){this.log.trace("closing init channel"),n.close();return}let o=jr({channel:n,direction:"inbound",onEnd:()=>{this.log("incoming channel %s ended with state %s",n.id,n.readyState),this.#t(o,n)},logger:this.logger,...this.dataChannelOptions});this.streams.push(o),this.metrics?.increment({incoming_stream:!0}),e?.onIncomingStream?.(o)},this.init.streams.length>0&&queueMicrotask(()=>{this.init.streams.forEach(n=>{n.onEnd=()=>{this.log("incoming early channel %s ended with state %s",n.channel.id,n.channel.readyState),this.#t(n.stream,n.channel)},this.metrics?.increment({incoming_stream:!0}),this.init?.onIncomingStream?.(n.stream)})})}#t(t,e){this.log.trace("stream %s %s %s onEnd",t.direction,t.id,t.protocol),Uf(e,`${t.direction} ${t.id} ${t.protocol}`,this.dataChannelOptions.drainTimeout,{log:this.log}),this.streams=this.streams.filter(n=>n.id!==t.id),this.metrics?.increment({stream_end:!0}),this.init?.onStreamEnd?.(t)}async close(t){try{await Promise.all(this.streams.map(async e=>e.close(t)))}catch(e){this.abort(e)}}abort(t){for(let e of this.streams)e.abort(t)}source=Cs();sink=ks;newStream(){let t=this.peerConnection.createDataChannel("");this.log.trace("opened outgoing datachannel with channel id %s",t.id);let e=jr({channel:t,direction:"outbound",onEnd:()=>{this.log("outgoing channel %s ended with state %s",t.id,t.readyState),this.#t(e,t)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(e),this.metrics?.increment({outgoing_stream:!0}),e}};var br=globalThis.RTCPeerConnection,Ms=globalThis.RTCSessionDescription,Ff=globalThis.RTCIceCandidate;var lc=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=gt(),this.haveNext=gt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=gt(),t}async throw(t){return this.ended=!0,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return await this._push(void 0),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=gt(),await Le(this.readNext.promise,e?.signal,e)}};function Kf(){return new lc}var Vs=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var uc=class extends Error{code;constructor(t,e){super(t),this.code=e}},fc=class extends uc{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function $f(r,t){let e=Kf();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new dt;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new fc("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:d}=await Promise.race([n.next(),l]);return f===!0?new dt:d}for(;o.byteLength<i;){let{value:f,done:d}=await Promise.race([n.next(),l]);if(d===!0)throw new Vs("unexpected end of input");o.append(f)}let u=o.sublist(0,i);return o.consume(i),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Fs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ks=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},$s=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Kn(r,t={}){let e=$f(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=lt(t.maxDataLength));let n=t?.lengthDecoder??ee,o=t?.lengthEncoder??ce;return{read:async i=>{let a=-1,c=new dt;for(;;){c.append(await e.read(1,i));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Fs("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new $s("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Ks("message length too long");return e.read(a,i)},write:async(i,a)=>{await e.write(new dt(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new dt(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Ws(r,t){let e=Kn(r,t),n={read:async(o,s)=>{let i=await e.read(s);return o.decode(i)},write:async(o,s,i)=>{await e.write(s.encode(o),i)},writeV:async(o,s,i)=>{await e.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>e.unwrap()};return n}var zt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Je=class extends Error{constructor(t){super(`WebRTC transport error: ${t}`),this.name="WebRTCTransportError"}},Zt=class extends Je{constructor(t="SDP handshake failed"){super(t),this.name="SDPHandshakeFailedError"}};var $n=class extends Je{constructor(t,e){super(`[stream: ${t}] data channel error: ${e}`),this.name="WebRTC/DataChannelError"}},qs=class extends Je{constructor(t){super(`There was a problem with the Multiaddr which was passed in: ${t}`),this.name="WebRTC/InappropriateMultiaddrError"}};var Wn=class extends Je{constructor(t,e){super(`Invalid fingerprint "${t}" within ${e}`),this.name="WebRTC/InvalidFingerprintError"}};var zs=class extends Je{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},Gs=class extends Je{constructor(t){super(`unsupported hash algorithm code: ${t} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var $t;(function(r){let t;(function(o){o.SDP_OFFER="SDP_OFFER",o.SDP_ANSWER="SDP_ANSWER",o.ICE_CANDIDATE="ICE_CANDIDATE"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.SDP_OFFER=0]="SDP_OFFER",o[o.SDP_ANSWER=1]="SDP_ANSWER",o[o.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(e||(e={})),function(o){o.codec=()=>fr(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=se((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.data!=null&&(s.uint32(18),s.string(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.data=o.string();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>oe(o,r.codec()),r.decode=(o,s)=>ne(o,r.codec(),s)})($t||($t={}));var js=async(r,t,e)=>{try{let n=gt();for(tg(r,n);;){let o=await Promise.race([n.promise,t.read({signal:e.signal}).catch(()=>{})]);if(o==null){e.signal?.throwIfAborted();break}if(o.type!==$t.Type.ICE_CANDIDATE)throw new eo("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){e.onProgress?.(new zt("webrtc:end-of-ice-candidates")),e.log.trace("end-of-candidates received");continue}let i=new Ff(s);e.log.trace("%s received new ICE candidate %o",e.direction,s);try{e.onProgress?.(new zt("webrtc:add-ice-candidate",i.candidate)),await r.addIceCandidate(i)}catch(a){e.log.error("%s bad candidate received",e.direction,s,a)}}}catch(n){if(e.log.error("%s error parsing ICE candidate",e.direction,n),e.signal?.aborted===!0&&Zs(r)!=="connected")throw n}};function Zs(r){return Hn?r.iceConnectionState:r.connectionState}function tg(r,t){r[Hn?"oniceconnectionstatechange":"onconnectionstatechange"]=e=>{switch(Zs(r)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new Jn("RTCPeerConnection was closed"));break;default:break}}}async function Wf({rtcConfiguration:r,dataChannel:t,signal:e,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=qf(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",u);let f=u.getPeerId();if(f==null)throw new et("Relay peer was missing");let d=s.getConnections($r(f)),m,x=!1;d.length===0?(l?.(new zt("webrtc:dial-relay")),m=await i.dial(u,{signal:e,onProgress:l}),x=!0):(l?.(new zt("webrtc:reuse-relay-connection")),m=d[0]);try{l?.(new zt("webrtc:open-signaling-stream"));let g=await m.newStream(Xs,{signal:e,runOnLimitedConnection:!0}),h=Ws(g).pb($t),w=new br(r),b=new Ye({logger:c},{peerConnection:w,dataChannelOptions:t});try{let p=w.createDataChannel("init");w.onicecandidate=({candidate:A})=>{let k=JSON.stringify(A?.toJSON()??null);a.trace("initiator sending ICE candidate %o",A),h.write({type:$t.Type.ICE_CANDIDATE,data:k},{signal:e}).catch(I=>{a.error("error sending ICE candidate",I)})},w.onicecandidateerror=A=>{a.error("initiator ICE candidate error",A)};let B=await w.createOffer().catch(A=>{throw a.error("could not execute createOffer",A),new Zt("Failed to set createOffer")});a.trace("initiator send SDP offer %s",B.sdp),l?.(new zt("webrtc:send-sdp-offer")),await h.write({type:$t.Type.SDP_OFFER,data:B.sdp},{signal:e}),await w.setLocalDescription(B).catch(A=>{throw a.error("could not execute setLocalDescription",A),new Zt("Failed to set localDescription")}),l?.(new zt("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let _=await h.read({signal:e});if(_.type!==$t.Type.SDP_ANSWER)throw new Zt("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",_.data);let N=new Ms({type:"answer",sdp:_.data});return await w.setRemoteDescription(N).catch(A=>{throw a.error("could not execute setRemoteDescription",A),new Zt("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),l?.(new zt("webrtc:read-ice-candidates")),await js(w,h,{direction:"initiator",signal:e,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),p.close(),l?.(new zt("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await g.close({signal:e}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:w,muxerFactory:b}}catch(p){throw a.error("outgoing signaling error",p),w.close(),g.abort(p),p}finally{w.onicecandidate=null,w.onicecandidateerror=null}}finally{if(x)try{await m.close({signal:e})}catch(g){m.abort(g)}}}var eg=U("dns4"),rg=U("dns6"),ng=U("dnsaddr"),xr=wt(U("dns"),ng,eg,rg),Qs=wt(U("ip4"),U("ip6")),Zr=wt(F(Qs,U("tcp")),F(xr,U("tcp"))),ti=F(Qs,U("udp")),og=F(ti,U("utp")),sg=F(ti,U("quic")),ig=F(ti,U("quic-v1")),hc=wt(F(Zr,U("ws")),F(xr,U("ws"))),Ys=wt(F(hc,U("p2p")),hc),dc=wt(F(Zr,U("wss")),F(xr,U("wss")),F(Zr,U("tls"),U("ws")),F(xr,U("tls"),U("ws"))),Js=wt(F(dc,U("p2p")),dc),pc=wt(F(Zr,U("http")),F(Qs,U("http")),F(xr,U("http"))),mc=wt(F(Zr,U("https")),F(Qs,U("https")),F(xr,U("https"))),zf=F(ti,U("webrtc-direct"),U("certhash")),Zf=wt(F(zf,U("p2p")),zf),Gf=F(ig,U("webtransport"),U("certhash"),U("certhash")),Xf=wt(F(Gf,U("p2p")),Gf),Yf=wt(F(Ys,U("p2p-webrtc-star"),U("p2p")),F(Js,U("p2p-webrtc-star"),U("p2p")),F(Ys,U("p2p-webrtc-star")),F(Js,U("p2p-webrtc-star"))),SS=wt(F(Ys,U("p2p-websocket-star"),U("p2p")),F(Js,U("p2p-websocket-star"),U("p2p")),F(Ys,U("p2p-websocket-star")),F(Js,U("p2p-websocket-star"))),Jf=wt(F(pc,U("p2p-webrtc-direct"),U("p2p")),F(mc,U("p2p-webrtc-direct"),U("p2p")),F(pc,U("p2p-webrtc-direct")),F(mc,U("p2p-webrtc-direct"))),Er=wt(hc,dc,pc,mc,Yf,Jf,Zr,og,sg,xr,Zf,Xf),AS=wt(F(Er,U("p2p-stardust"),U("p2p")),F(Er,U("p2p-stardust"))),Qe=wt(F(Er,U("p2p")),Yf,Jf,Zf,Xf,U("p2p")),jf=wt(F(Qe,U("p2p-circuit"),Qe),F(Qe,U("p2p-circuit")),F(U("p2p-circuit"),Qe),F(Er,U("p2p-circuit")),F(U("p2p-circuit"),Er),U("p2p-circuit")),Qf=()=>wt(F(jf,Qf),jf),Re=Qf(),BS=wt(F(Re,Qe,Re),F(Qe,Re),F(Re,Qe),Re,Qe);var IS=wt(F(Re,U("webrtc"),U("p2p")),F(Re,U("webrtc")),F(Er,U("webrtc"),U("p2p")),F(Er,U("webrtc")),U("webrtc"));function th(r){function t(e){let n;try{n=ae(e)}catch{return!1}let o=r(n.protoNames());return o===null?!1:o===!0||o===!1?o:o.length===0}return t}function F(...r){function t(e){if(e.length<r.length)return null;let n=e;return r.some(o=>(n=typeof o=="function"?o().partialMatch(e):o.partialMatch(e),Array.isArray(n)&&(e=n),n===null)),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:th(t),partialMatch:t}}function wt(...r){function t(n){let o=null;return r.some(s=>{let i=typeof s=="function"?s().partialMatch(n):s.partialMatch(n);return i!=null?(o=i,!0):!1}),o}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:th(t),partialMatch:t}}function U(r){let t=r;function e(o){let s;try{s=ae(o)}catch{return!1}let i=s.protoNames();return i.length===1&&i[0]===t}function n(o){return o.length===0?null:o[0]===t?o.slice(1):null}return{toString:function(){return t},matches:e,partialMatch:n}}var ei=class extends no{peerId;transportManager;shutdownController;constructor(t,e){super(),this.peerId=t.peerId,this.transportManager=t.transportManager,this.shutdownController=e.shutdownController}async listen(){this.safeDispatchEvent("listening",{})}getAddrs(){return this.transportManager.getListeners().filter(t=>t!==this).map(t=>t.getAddrs().filter(e=>Re.matches(e)).map(e=>e.encapsulate(`/webrtc/p2p/${this.peerId}`))).flat()}async close(){this.shutdownController.abort(),this.safeDispatchEvent("close",{})}};async function eh({peerConnection:r,stream:t,signal:e,connection:n,log:o}){o.trace("new inbound signaling stream");let s=Ws(t).pb($t);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:$t.Type.ICE_CANDIDATE,data:f},{signal:e}).catch(d=>{o.error("error sending ICE candidate",d)})},o.trace("recipient read SDP offer");let a=await s.read({signal:e});if(a.type!==$t.Type.SDP_OFFER)throw new Zt(`expected message type SDP_OFFER, received: ${a.type??"undefined"} `);o.trace("recipient received SDP offer %s",a.data);let c=new Ms({type:"offer",sdp:a.data});await r.setRemoteDescription(c).catch(u=>{throw o.error("could not execute setRemoteDescription",u),new Zt("Failed to set remoteDescription")});let l=await r.createAnswer().catch(u=>{throw o.error("could not execute createAnswer",u),new Zt("Failed to create answer")});o.trace("recipient send SDP answer %s",l.sdp),await s.write({type:$t.Type.SDP_ANSWER,data:l.sdp},{signal:e}),await r.setLocalDescription(l).catch(u=>{throw o.error("could not execute setLocalDescription",u),new Zt("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await js(r,s,{direction:"recipient",signal:e,log:o})}catch(a){if(Zs(r)!=="connected")throw o.error("error while handling signaling stream from peer %a",n.remoteAddr,a),r.close(),a;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",n.remoteAddr,a)}let i=ae(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return o.trace("recipient connected to remote address %s",i),{remoteAddress:i}}var ag="/webrtc",cg="/p2p-circuit",Xs="/webrtc-signaling/0.0.1",lg=30*1e3,ri=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,e={}){this.components=t,this.init=e,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,ro(1/0,this.shutdownController.signal),t.metrics!=null&&(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"})})}[Xn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Ar]=["@libp2p/transport"];[Zc]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(Xs,t=>{this._onProtocol(t).catch(e=>{this.log.error("failed to handle incoming connect from %p",t.connection.remotePeer,e)})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(Xs),this._started=!1}createListener(t){return new ei(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(Af.exactMatch)}dialFilter(t){return this.listenFilter(t)}async dial(t,e){this.log.trace("dialing address: %a",t);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await Wf({rtcConfiguration:await Mn(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:t,dataChannelOptions:this.init.dataChannel,signal:e.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:e.onProgress}),i=new gr(this.components,{peerConnection:o,timeline:{open:Date.now()},remoteAddr:n,metrics:this.metrics?.dialerEvents}),a=await e.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,muxerFactory:s,onProgress:e.onProgress});return this._closeOnShutdown(o,i),a}async _onProtocol({connection:t,stream:e}){let n=AbortSignal.timeout(this.init.inboundConnectionTimeout??lg),o=new br(await Mn(this.init.rtcConfiguration)),s=new Ye(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await eh({peerConnection:o,connection:t,stream:e,signal:n,log:this.log});await e.close({signal:n});let a=new gr(this.components,{peerConnection:o,timeline:{open:new Date().getTime()},remoteAddr:i,metrics:this.metrics?.listenerEvents});await this.components.upgrader.upgradeInbound(a,{skipEncryption:!0,skipProtection:!0,muxerFactory:s}),this._closeOnShutdown(o,a)}catch(i){throw this.log.error("incoming signaling error",i),o.close(),e.abort(i),i}}_closeOnShutdown(t,e){let n=()=>{e.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection",o)})};this.shutdownController.signal.addEventListener("abort",n),t.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function qf(r){let t=r.toString().split(ag+"/");if(t.length!==2)throw new et("webrtc protocol was not present in multiaddr");if(!t[0].includes(cg))throw new et("p2p-circuit protocol was not present in multiaddr");let e=ae(t[0]),o=ae("/"+t[1]).getPeerId();if(o==null)throw new et("destination peer id was missing");let s=e.protos().pop();if(s===void 0)throw new et("invalid multiaddr");return s.name!=="p2p"&&(e=e.encapsulate(`/p2p/${o}`)),{baseAddr:e,peerId:$r(o)}}function gc(){let r=gt(),t=!1;return{sink:async e=>{if(t)throw new Error("already piped");t=!0,r.resolve(e)},source:async function*(){yield*await r.promise}()}}function rh(){let r=gc(),t=gc();return[{source:r.source,sink:t.sink},{source:t.source,sink:r.sink}]}function ug(r){return r[Symbol.asyncIterator]!=null}function fg(...r){let t=[];for(let e of r)ug(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=Xe({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)e.push(o)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var nh=fg;function oh(r,...t){if(r==null)throw new Error("Empty pipeline");if(wc(r)){let n=r;r=()=>n.source}else if(ih(r)||sh(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&wc(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)wc(e[n])&&(e[n]=dg(e[n]));return hg(...e)}var hg=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},sh=r=>r?.[Symbol.asyncIterator]!=null,ih=r=>r?.[Symbol.iterator]!=null,wc=r=>r==null?!1:r.sink!=null&&r.source!=null,dg=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Xe({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(sh(s))o=async function*(){yield*s,n.end()};else if(ih(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return nh(n,o())}return r.source};var Xr=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function ni(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function yc(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function bc(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Wt(r,...t){if(!bc(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function xc(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function ah(r,t){Wt(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var Ue=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),ch=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),pg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!pg)throw new Error("Non little-endian hardware is not supported");function mg(r){if(typeof r!="string")throw new Error(`string expected, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function oi(r){if(typeof r=="string")r=mg(r);else if(bc(r))r=si(r);else throw new Error(`Uint8Array expected, got ${typeof r}`);return r}function lh(r,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(r,t)}function uh(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}var Ec=(r,t)=>(Object.assign(t,r),t);function vc(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}function si(r){return Uint8Array.from(r)}function De(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}var hh=r=>Uint8Array.from(r.split("").map(t=>t.charCodeAt(0))),gg=hh("expand 16-byte k"),wg=hh("expand 32-byte k"),yg=Ue(gg),dh=Ue(wg),fA=dh.slice();function O(r,t){return r<<t|r>>>32-t}function Sc(r){return r.byteOffset%4===0}var ii=64,bg=16,ph=2**32-1,fh=new Uint32Array;function xg(r,t,e,n,o,s,i,a){let c=o.length,l=new Uint8Array(ii),u=Ue(l),f=Sc(o)&&Sc(s),d=f?Ue(o):fh,m=f?Ue(s):fh;for(let x=0;x<c;i++){if(r(t,e,n,u,i,a),i>=ph)throw new Error("arx: counter overflow");let g=Math.min(ii,c-x);if(f&&g===ii){let h=x/4;if(x%4!==0)throw new Error("arx: invalid block position");for(let w=0,b;w<bg;w++)b=h+w,m[b]=d[b]^u[w];x+=ii;continue}for(let h=0,w;h<g;h++)w=x+h,s[w]=o[w]^l[h];x+=g}}function Ac(r,t){let{allowShortKeys:e,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=lh({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof r!="function")throw new Error("core must be a function");return ni(o),ni(i),yc(s),yc(e),(a,c,l,u,f=0)=>{Wt(a),Wt(c),Wt(l);let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),Wt(u),ni(f),f<0||f>=ph)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let m=[],x=a.length,g,h;if(x===32)m.push(g=si(a)),h=dh;else if(x===16&&e)g=new Uint8Array(32),g.set(a),g.set(a,16),h=yg,m.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${x}`);Sc(c)||m.push(c=si(c));let w=Ue(g);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,w,Ue(c.subarray(0,16)),w),c=c.subarray(16)}let b=16-o;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let B=new Uint8Array(12);B.set(c,s?0:12-c.length),c=B,m.push(c)}let p=Ue(c);return xg(r,h,w,p,l,u,f,i),De(...m),u}}var Tt=(r,t)=>r[t++]&255|(r[t++]&255)<<8,Bc=class{constructor(t){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,t=oi(t),Wt(t,32);let e=Tt(t,0),n=Tt(t,2),o=Tt(t,4),s=Tt(t,6),i=Tt(t,8),a=Tt(t,10),c=Tt(t,12),l=Tt(t,14);this.r[0]=e&8191,this.r[1]=(e>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Tt(t,16+2*u)}process(t,e,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],d=i[5],m=i[6],x=i[7],g=i[8],h=i[9],w=Tt(t,e+0),b=Tt(t,e+2),p=Tt(t,e+4),B=Tt(t,e+6),_=Tt(t,e+8),N=Tt(t,e+10),A=Tt(t,e+12),k=Tt(t,e+14),I=s[0]+(w&8191),V=s[1]+((w>>>13|b<<3)&8191),L=s[2]+((b>>>10|p<<6)&8191),H=s[3]+((p>>>7|B<<9)&8191),K=s[4]+((B>>>4|_<<12)&8191),C=s[5]+(_>>>1&8191),T=s[6]+((_>>>14|N<<2)&8191),E=s[7]+((N>>>11|A<<5)&8191),y=s[8]+((A>>>8|k<<8)&8191),S=s[9]+(k>>>5|o),v=0,R=v+I*a+V*(5*h)+L*(5*g)+H*(5*x)+K*(5*m);v=R>>>13,R&=8191,R+=C*(5*d)+T*(5*f)+E*(5*u)+y*(5*l)+S*(5*c),v+=R>>>13,R&=8191;let D=v+I*c+V*a+L*(5*h)+H*(5*g)+K*(5*x);v=D>>>13,D&=8191,D+=C*(5*m)+T*(5*d)+E*(5*f)+y*(5*u)+S*(5*l),v+=D>>>13,D&=8191;let M=v+I*l+V*c+L*a+H*(5*h)+K*(5*g);v=M>>>13,M&=8191,M+=C*(5*x)+T*(5*m)+E*(5*d)+y*(5*f)+S*(5*u),v+=M>>>13,M&=8191;let $=v+I*u+V*l+L*c+H*a+K*(5*h);v=$>>>13,$&=8191,$+=C*(5*g)+T*(5*x)+E*(5*m)+y*(5*d)+S*(5*f),v+=$>>>13,$&=8191;let W=v+I*f+V*u+L*l+H*c+K*a;v=W>>>13,W&=8191,W+=C*(5*h)+T*(5*g)+E*(5*x)+y*(5*m)+S*(5*d),v+=W>>>13,W&=8191;let z=v+I*d+V*f+L*u+H*l+K*c;v=z>>>13,z&=8191,z+=C*a+T*(5*h)+E*(5*g)+y*(5*x)+S*(5*m),v+=z>>>13,z&=8191;let Z=v+I*m+V*d+L*f+H*u+K*l;v=Z>>>13,Z&=8191,Z+=C*c+T*a+E*(5*h)+y*(5*g)+S*(5*x),v+=Z>>>13,Z&=8191;let st=v+I*x+V*m+L*d+H*f+K*u;v=st>>>13,st&=8191,st+=C*l+T*c+E*a+y*(5*h)+S*(5*g),v+=st>>>13,st&=8191;let it=v+I*g+V*x+L*m+H*d+K*f;v=it>>>13,it&=8191,it+=C*u+T*l+E*c+y*a+S*(5*h),v+=it>>>13,it&=8191;let ft=v+I*h+V*g+L*x+H*m+K*d;v=ft>>>13,ft&=8191,ft+=C*f+T*u+E*l+y*c+S*a,v+=ft>>>13,ft&=8191,v=(v<<2)+v|0,v=v+R|0,R=v&8191,v=v>>>13,D+=v,s[0]=R,s[1]=D,s[2]=M,s[3]=$,s[4]=W,s[5]=z,s[6]=Z,s[7]=st,s[8]=it,s[9]=ft}finalize(){let{h:t,pad:e}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+e[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+e[a]|0)+(i>>>16)|0,t[a]=i&65535;De(n)}update(t){xc(this);let{buffer:e,blockLen:n}=this;t=oi(t);let o=t.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(t,s);continue}e.set(t.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(e,0,!1),this.pos=0)}return this}destroy(){De(this.h,this.r,this.buffer,this.pad)}digestInto(t){xc(this),ah(t,this),this.finished=!0;let{buffer:e,h:n}=this,{pos:o}=this;if(o){for(e[o++]=1;o<16;o++)e[o]=0;this.process(e,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)t[s++]=n[i]>>>0,t[s++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}};function Eg(r){let t=(n,o)=>r(o).update(oi(n)).digest(),e=r(new Uint8Array(32));return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=n=>r(n),t}var mh=Eg(r=>new Bc(r));function yh(r,t,e,n,o,s=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=t[0],f=t[1],d=t[2],m=t[3],x=t[4],g=t[5],h=t[6],w=t[7],b=o,p=e[0],B=e[1],_=e[2],N=i,A=a,k=c,I=l,V=u,L=f,H=d,K=m,C=x,T=g,E=h,y=w,S=b,v=p,R=B,D=_;for(let $=0;$<s;$+=2)N=N+V|0,S=O(S^N,16),C=C+S|0,V=O(V^C,12),N=N+V|0,S=O(S^N,8),C=C+S|0,V=O(V^C,7),A=A+L|0,v=O(v^A,16),T=T+v|0,L=O(L^T,12),A=A+L|0,v=O(v^A,8),T=T+v|0,L=O(L^T,7),k=k+H|0,R=O(R^k,16),E=E+R|0,H=O(H^E,12),k=k+H|0,R=O(R^k,8),E=E+R|0,H=O(H^E,7),I=I+K|0,D=O(D^I,16),y=y+D|0,K=O(K^y,12),I=I+K|0,D=O(D^I,8),y=y+D|0,K=O(K^y,7),N=N+L|0,D=O(D^N,16),E=E+D|0,L=O(L^E,12),N=N+L|0,D=O(D^N,8),E=E+D|0,L=O(L^E,7),A=A+H|0,S=O(S^A,16),y=y+S|0,H=O(H^y,12),A=A+H|0,S=O(S^A,8),y=y+S|0,H=O(H^y,7),k=k+K|0,v=O(v^k,16),C=C+v|0,K=O(K^C,12),k=k+K|0,v=O(v^k,8),C=C+v|0,K=O(K^C,7),I=I+V|0,R=O(R^I,16),T=T+R|0,V=O(V^T,12),I=I+V|0,R=O(R^I,8),T=T+R|0,V=O(V^T,7);let M=0;n[M++]=i+N|0,n[M++]=a+A|0,n[M++]=c+k|0,n[M++]=l+I|0,n[M++]=u+V|0,n[M++]=f+L|0,n[M++]=d+H|0,n[M++]=m+K|0,n[M++]=x+C|0,n[M++]=g+T|0,n[M++]=h+E|0,n[M++]=w+y|0,n[M++]=b+S|0,n[M++]=p+v|0,n[M++]=B+R|0,n[M++]=_+D|0}function vg(r,t,e,n){let o=r[0],s=r[1],i=r[2],a=r[3],c=t[0],l=t[1],u=t[2],f=t[3],d=t[4],m=t[5],x=t[6],g=t[7],h=e[0],w=e[1],b=e[2],p=e[3];for(let _=0;_<20;_+=2)o=o+c|0,h=O(h^o,16),d=d+h|0,c=O(c^d,12),o=o+c|0,h=O(h^o,8),d=d+h|0,c=O(c^d,7),s=s+l|0,w=O(w^s,16),m=m+w|0,l=O(l^m,12),s=s+l|0,w=O(w^s,8),m=m+w|0,l=O(l^m,7),i=i+u|0,b=O(b^i,16),x=x+b|0,u=O(u^x,12),i=i+u|0,b=O(b^i,8),x=x+b|0,u=O(u^x,7),a=a+f|0,p=O(p^a,16),g=g+p|0,f=O(f^g,12),a=a+f|0,p=O(p^a,8),g=g+p|0,f=O(f^g,7),o=o+l|0,p=O(p^o,16),x=x+p|0,l=O(l^x,12),o=o+l|0,p=O(p^o,8),x=x+p|0,l=O(l^x,7),s=s+u|0,h=O(h^s,16),g=g+h|0,u=O(u^g,12),s=s+u|0,h=O(h^s,8),g=g+h|0,u=O(u^g,7),i=i+f|0,w=O(w^i,16),d=d+w|0,f=O(f^d,12),i=i+f|0,w=O(w^i,8),d=d+w|0,f=O(f^d,7),a=a+c|0,b=O(b^a,16),m=m+b|0,c=O(c^m,12),a=a+c|0,b=O(b^a,8),m=m+b|0,c=O(c^m,7);let B=0;n[B++]=o,n[B++]=s,n[B++]=i,n[B++]=a,n[B++]=h,n[B++]=w,n[B++]=b,n[B++]=p}var Sg=Ac(yh,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Ag=Ac(yh,{counterRight:!1,counterLength:8,extendNonceFn:vg,allowShortKeys:!1});var Bg=new Uint8Array(16),gh=(r,t)=>{r.update(t);let e=t.length%16;e&&r.update(Bg.subarray(e))},Ig=new Uint8Array(32);function wh(r,t,e,n,o){let s=r(t,e,Ig),i=mh.create(s);o&&gh(i,o),gh(i,n);let a=new Uint8Array(16),c=ch(a);vc(c,0,BigInt(o?o.length:0),!0),vc(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return De(s,a),l}var bh=r=>(t,e,n)=>(Wt(t,32),Wt(e),{encrypt(s,i){let a=s.length,c=a+16;i?Wt(i,c):i=new Uint8Array(c),r(t,e,s,i,1);let l=wh(r,t,e,i.subarray(0,-16),n);return i.set(l,a),De(l),i},decrypt(s,i){let a=s.length,c=a-16;if(a<16)throw new Error("encrypted data must be at least 16 bytes");i?Wt(i,c):i=new Uint8Array(c);let l=s.subarray(0,-16),u=s.subarray(-16),f=wh(r,t,e,l,n);if(!uh(u,f))throw new Error("invalid tag");return r(t,e,l,i,1),De(f),i}}),Ic=Ec({blockSize:64,nonceLength:12,tagLength:16},bh(Sg)),xA=Ec({blockSize:64,nonceLength:24,tagLength:16},bh(Ag));function Eh(r,t,e){return cn(r),e===void 0&&(e=new Uint8Array(r.outputLen)),Kr(r,He(e),He(t))}var Cc=new Uint8Array([0]),xh=new Uint8Array;function vh(r,t,e,n=32){if(cn(r),so(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);e===void 0&&(e=xh);let s=new Uint8Array(o*r.outputLen),i=Kr.create(r,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)Cc[0]=l+1,a.update(l===0?xh:c).update(e).update(Cc).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),Cc.fill(0),s.slice(0,n)}var kc={hashSHA256(r){return ue(r.subarray())},getHKDF(r,t){let e=Eh(ue,t,r),o=vh(ue,e,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=pn.utils.randomPrivateKey();return{publicKey:pn.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:pn.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,t){return pn.getSharedSecret(r.subarray(),t.subarray())},chaCha20Poly1305Encrypt(r,t,e,n){return Ic(n,t,e).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,t,e,n,o){return Ic(n,t,e).decrypt(r.subarray(),o)}};var Sh=kc;function Ah(r){return{generateKeypair:r.generateX25519KeyPair,dh:(t,e)=>r.generateX25519SharedKey(t.privateKey,e).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var Yr=r=>{let t=Et(2);return t[0]=r>>8,t[1]=r,t};Yr.bytes=2;var qn=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let t=0;return t+=r[0]<<8,t+=r[1],t}return r.getUint16(0)};qn.bytes=2;function Bh(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Tc(r,t){!t.enabled||!Xr||(r?(t(`LOCAL_STATIC_PUBLIC_KEY ${Q(r.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${Q(r.privateKey,"hex")}`)):t("Missing local static keys."))}function Nc(r,t){!t.enabled||!Xr||(r?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${Q(r.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${Q(r.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function Ih(r,t){!t.enabled||!Xr||t(r?`REMOTE_STATIC_PUBLIC_KEY ${Q(r.subarray(),"hex")}`:"Missing remote static public key.")}function _c(r,t){!t.enabled||!Xr||t(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${Q(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Lc(r,t,e){!e.enabled||!Xr||(e(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&Q(r.k,"hex")}`),e(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&Q(t.k,"hex")}`))}var Jr=class r extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var Cg=0,kg=4294967295,Tg="Cipherstate has reached maximum n, a new handshake must be performed",ai=class{n;bytes;view;constructor(t=Cg){this.n=t,this.bytes=xt(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>kg)throw new Error(Tg)}};var vr=xt(0),Qr=class{k;n;crypto;constructor(t,e=void 0,n=0){this.crypto=t,this.k=e,this.n=new ai(n)}hasKey(){return!!this.k}encryptWithAd(t,e){if(!this.hasKey())return e;this.n.assertValue();let n=this.crypto.encrypt(e,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,e,n){if(!this.hasKey())return e;this.n.assertValue();let o=this.crypto.decrypt(e,this.n.getBytes(),t,this.k,n);return this.n.increment(),o}},Rc=class{cs;ck;h;crypto;constructor(t,e){this.crypto=t;let n=rt(e,"utf-8");this.h=Ng(t,n),this.ck=this.h,this.cs=new Qr(t)}mixKey(t){let[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new Qr(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new dt(this.h,t))}encryptAndHash(t){let e=this.cs.encryptWithAd(this.h,t);return this.mixHash(e),e}decryptAndHash(t){let e=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),e}split(){let[t,e]=this.crypto.hkdf(this.ck,vr);return[new Qr(this.crypto,t),new Qr(this.crypto,e)]}},Uc=class{ss;s;e;rs;re;initiator;crypto;constructor(t){let{crypto:e,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=t;this.crypto=e,this.ss=new Rc(e,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let t=this.crypto.generateKeypair();return this.ss.mixHash(t.publicKey),this.e=t,t.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(t,e=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<e+32)throw new Error("message is not long enough");this.re=t.sublist(e,e+32),this.ss.mixHash(this.re)}readS(t,e=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(t.byteLength<e+n)throw new Error("message is not long enough");let o=t.sublist(e,e+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},zn=class extends Uc{writeMessageA(t){return new dt(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let e=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new dt(e,n,this.ss.encryptAndHash(t))}writeMessageC(t){let e=this.writeS();return this.writeSE(),new dt(e,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(e){throw new Jr(`handshake stage 0 validation fail: ${e.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();let e=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+e))}catch(e){throw new Jr(`handshake stage 1 validation fail: ${e.message}`)}}readMessageC(t){try{let e=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(e))}catch(e){throw new Jr(`handshake stage 2 validation fail: ${e.message}`)}}};function Ng(r,t){if(t.length<=32){let e=xt(32);return e.set(t),e}else return r.hash(t)}var ci;(function(r){let t;r.codec=()=>(t==null&&(t=se((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.webtransportCerthashes!=null)for(let s of e.webtransportCerthashes)n.uint32(10),n.bytes(s);o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={webtransportCerthashes:[]},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:{o.webtransportCerthashes.push(e.bytes());break}default:{e.skipType(i&7);break}}}return o})),t),r.encode=e=>oe(e,r.codec()),r.decode=e=>ne(e,r.codec())})(ci||(ci={}));var Gn;(function(r){let t;r.codec=()=>(t==null&&(t=se((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.identityKey!=null&&e.identityKey.byteLength>0&&(n.uint32(10),n.bytes(e.identityKey)),e.identitySig!=null&&e.identitySig.byteLength>0&&(n.uint32(18),n.bytes(e.identitySig)),e.extensions!=null&&(n.uint32(34),ci.codec().encode(e.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={identityKey:xt(0),identitySig:xt(0)},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:{o.identityKey=e.bytes();break}case 2:{o.identitySig=e.bytes();break}case 4:{o.extensions=ci.codec().decode(e,e.uint32());break}default:{e.skipType(i&7);break}}}return o})),t),r.encode=e=>oe(e,r.codec()),r.decode=e=>ne(e,r.codec())})(Gn||(Gn={}));async function Dc(r,t,e){let n=await r.sign(Ch(t));return Gn.encode({identityKey:Ur(r.publicKey),identitySig:n,extensions:e})}async function Pc(r,t,e){try{let n=Gn.decode(r),o=Nn(n.identityKey);if(e?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${e}`);if(!t)throw new Error("Remote static does not exist");let s=Ch(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Yn(n.message)}}function Ch(r){let t=rt("noise-libp2p-static-key:");return r instanceof Uint8Array?At([t,r],t.length+r.length):(r.prepend(t),r)}async function kh(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Dc(s,a.publicKey,l),f=new zn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Tc(f.s,e),e.trace("Stage 0 - Initiator starting to send first message."),await n.write(f.writeMessageA(vr),t),e.trace("Stage 0 - Initiator finished sending first message."),Nc(f.e,e),e.trace("Stage 1 - Initiator waiting to receive first message from responder...");let d=f.readMessageB(await n.read(t));e.trace("Stage 1 - Initiator received the message."),_c(f.re,e),Ih(f.rs,e),e.trace("Initiator going to check remote's signature...");let m=await Pc(d,f.rs,c);e.trace("All good with the signature!"),e.trace("Stage 2 - Initiator sending third handshake message."),await n.write(f.writeMessageC(u),t),e.trace("Stage 2 - Initiator sent message with signed payload.");let[x,g]=f.ss.split();return Lc(x,g,e),{payload:m,encrypt:h=>x.encryptWithAd(vr,h),decrypt:(h,w)=>g.decryptWithAd(vr,h,w)}}async function Th(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Dc(s,a.publicKey,l),f=new zn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Tc(f.s,e),e.trace("Stage 0 - Responder waiting to receive first message."),f.readMessageA(await n.read(t)),e.trace("Stage 0 - Responder received first message."),_c(f.re,e),e.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(f.writeMessageB(u),t),e.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Nc(f.e,e),e.trace("Stage 2 - Responder waiting for third handshake message...");let d=f.readMessageC(await n.read(t));e.trace("Stage 2 - Responder received the message, finished handshake.");let m=await Pc(d,f.rs,c),[x,g]=f.ss.split();return Lc(x,g,e),{payload:m,encrypt:h=>g.encryptWithAd(vr,h),decrypt:(h,w)=>x.decryptWithAd(vr,h,w)}}var _h=16;function Lh(r,t){return async function*(e){for await(let n of e)for(let o=0;o<n.length;o+=65519){let s=o+65519;s>n.length&&(s=n.length);let i;n instanceof Uint8Array?i=r.encrypt(n.subarray(o,s)):i=r.encrypt(n.sublist(o,s)),t?.encryptedPackets.increment(),yield new dt(Yr(i.byteLength),i)}}}function Rh(r,t){return async function*(e){for await(let n of e)for(let o=0;o<n.length;o+=65535){let s=o+65535;if(s>n.length&&(s=n.length),s-_h<o)throw new Error("Invalid chunk");let i=n.sublist(o,s),a=n.subarray(o,s-_h);try{let c=r.decrypt(i,a);t?.decryptedPackets.increment(),yield c}catch(c){throw t?.decryptErrors.increment(),c}}}}var li=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(t,e={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=e,{metrics:a}=t;this.components=t;let c=s??Sh;this.crypto=Ah(c),this.extensions=o,this.metrics=a?Bh(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??xt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Ar]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,e){let n=Kn(t,{lengthEncoder:Yr,lengthDecoder:qn,maxDataLength:65535}),o=await this.performHandshakeInitiator(n,this.components.privateKey,e?.remotePeer?.publicKey,e),s=await this.createSecureConnection(n,o);t.source=s.source,t.sink=s.sink;let i=Nn(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Ua(i)}}async secureInbound(t,e){let n=Kn(t,{lengthEncoder:Yr,lengthDecoder:qn,maxDataLength:65535}),o=await this.performHandshakeResponder(n,this.components.privateKey,e?.remotePeer?.publicKey,e),s=await this.createSecureConnection(n,o);t.source=s.source,t.sink=s.sink;let i=Nn(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Ua(i)}}async performHandshakeInitiator(t,e,n,o){let s;try{s=await kh({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async performHandshakeResponder(t,e,n,o){let s;try{s=await Th({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async createSecureConnection(t,e){let[n,o]=rh(),s=t.unwrap();return await oh(n,Lh(e,this.metrics),s,i=>yr(i,{lengthDecoder:qn}),Rh(e,this.metrics),n),o}};function Uh(r={}){return t=>new li(t,r)}var Oc=Object.values(lr).map(r=>r.decoder).reduce((r,t)=>r.or(t));function Dh(r,t){let e=r.getConfiguration().certificates?.at(0);if(e?.getFingerprints==null){t.log.trace("fetching fingerprint from local SDP");let o=r.localDescription;return o==null?void 0:Lg(o.sdp)}if(t.log.trace("fetching fingerprint from local certificate"),e.getFingerprints().length===0)return;let n=e.getFingerprints()[0].value;if(n==null)throw new Wn("","no fingerprint on local certificate");return n}var _g=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function Lg(r){return r.match(_g)?.groups?.fingerprint}function Rg(r){for(let t of r.protoNames())if(t.startsWith("ip"))return t.toUpperCase();return"IP6"}function ui(r){let e=r.stringTuples().filter(n=>n[0]===Hh).map(n=>n[1])[0];if(e===void 0||e==="")throw new et(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return e}function Hc(r){return Xt.decode(Oc.decode(r))}function Ug(r){let t=Hc(ui(r)),e=Mc(t.code),n=t.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new Wn(n,r.toString());return[`${e} ${o.join(":").toUpperCase()}`,n]}function Mc(r){switch(r){case 17:return"SHA-1";case 18:return"SHA-256";case 19:return"SHA-512";default:throw new Gs(r)}}function Dg(r,t){let{host:e,port:n}=r.toOptions(),o=Rg(r),[s]=Ug(r);return`v=0
7
7
  o=- 0 0 IN ${o} ${e}
8
8
  s=-
9
9
  c=IN ${o} ${e}
@@ -18,11 +18,11 @@ a=fingerprint:${s}
18
18
  a=sctp-port:5000
19
19
  a=max-message-size:${Hs}
20
20
  a=candidate:1467250027 1 UDP 1467250027 ${e} ${n} typ host\r
21
- `}function Ph(r,t){return{type:"answer",sdp:Ug(r,t)}}function Oh(r,t){if(r.sdp===void 0)throw new et("Can't munge a missing SDP");return r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
21
+ `}function Ph(r,t){return{type:"answer",sdp:Dg(r,t)}}function Oh(r,t){if(r.sdp===void 0)throw new et("Can't munge a missing SDP");return r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
22
22
  a=ice-ufrag:`+t+`
23
23
  `).replace(/\na=ice-pwd:[^\n]*\n/,`
24
24
  a=ice-pwd:`+t+`
25
- `),r}var Mh=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Vh=r=>[...Array(r)].map(()=>Mh.at(Math.floor(Math.random()*Mh.length))).join("");var Pg=1e4,u8=tt("webrtc-direct").code,Hh=tt("certhash").code,fi=class{log;metrics;components;init;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:webrtc-direct"),this.components=t,this.init=e,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[Xn]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Sr]=["@libp2p/transport"];async dial(t,e){let n=await this._connect(t,e);return this.log("dialing address: %a",t),n}createListener(t){throw new zs("WebRTCTransport.createListener")}listenFilter(t){return t.filter(vf.exactMatch)}dialFilter(t){return this.listenFilter(t)}async _connect(t,e){let n=new AbortController,o=n.signal,s=t.getPeerId();if(s===null)throw new qs("we need to have the remote's PeerId");let i=Kr(s),a=Hc(ui(t)),c=await yr.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:Mc(a.code)}),l=new yr({...await Mn(this.init.rtcConfiguration),certificates:[c]});try{let u=new Promise((A,k)=>{let I=l.createDataChannel("",{negotiated:!0,id:0}),V=setTimeout(()=>{let _=`Data channel was never opened: state: ${I.readyState}`;this.log.error(_),this.metrics?.dialerEvents.increment({open_error:!0}),k(new $n("data",_))},Pg);I.onopen=_=>{clearTimeout(V),A(I)},I.onerror=_=>{clearTimeout(V);let K=`Error opening a data channel for handshaking: ${_.target?.toString()??"not specified"}`;this.log.error(K),this.metrics?.dialerEvents.increment({unknown_error:!0}),k(new $n("data",K))}}),f="libp2p+webrtc+v1/"+Vh(32),d=await l.createOffer(),m=Oh(d,f);await l.setLocalDescription(m);let x=Ph(t,f);await l.setRemoteDescription(x);let g=await u,h=this.generateNoisePrologue(l,a.code,t),w=Uh({prologueBytes:h})(this.components),b=jr({channel:g,direction:"inbound",logger:this.components.logger,...this.init.dataChannel??{}}),p={...b,sink:b.sink.bind(b),source:async function*(){for await(let A of b.source)for(let k of A)yield k}()},B=new mr(this.components,{peerConnection:l,remoteAddr:t,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),L=Hn?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(L,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":B.close().catch(A=>{this.log.error("error closing connection",A)}).finally(()=>{n.abort()});break;default:break}},{signal:o}),this.metrics?.dialerEvents.increment({peer_connection:!0});let N=new Ye(this.components,{peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await w.secureInbound(p,{signal:o,remotePeer:i}),await e.upgrader.upgradeOutbound(B,{skipProtection:!0,skipEncryption:!0,muxerFactory:N})}catch(u){throw l.close(),u}}generateNoisePrologue(t,e,n){if(t.getConfiguration().certificates?.length===0)throw new et("no local certificate");let o=Dh(t,{log:this.log});if(o==null)throw new et("no local fingerprint found");let s=o.trim().toLowerCase().replaceAll(":",""),i=rt(s,"hex"),a=Vt(e,i),c=Oc.decode(ui(n)),l=rt("libp2p-webrtc-noise:");return At([l,a.bytes,c])}};function Og(r){return t=>new fi(t,r)}function Hg(r){return t=>new ri(t,r)}return rd(Mg);})();
25
+ `),r}var Mh=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Vh=r=>[...Array(r)].map(()=>Mh.at(Math.floor(Math.random()*Mh.length))).join("");var Og=1e4,h8=tt("webrtc-direct").code,Hh=tt("certhash").code,fi=class{log;metrics;components;init;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:webrtc-direct"),this.components=t,this.init=e,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[Xn]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Ar]=["@libp2p/transport"];async dial(t,e){let n=await this._connect(t,e);return this.log("dialing address: %a",t),n}createListener(t){throw new zs("WebRTCTransport.createListener")}listenFilter(t){return t.filter(vf.exactMatch)}dialFilter(t){return this.listenFilter(t)}async _connect(t,e){let n=new AbortController,o=n.signal,s=t.getPeerId();if(s===null)throw new qs("we need to have the remote's PeerId");let i=$r(s),a=Hc(ui(t)),c=await br.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:Mc(a.code)}),l=new br({...await Mn(this.init.rtcConfiguration),certificates:[c]});try{let u=new Promise((A,k)=>{let I=l.createDataChannel("",{negotiated:!0,id:0}),V=setTimeout(()=>{let L=`Data channel was never opened: state: ${I.readyState}`;this.log.error(L),this.metrics?.dialerEvents.increment({open_error:!0}),k(new $n("data",L))},Og);I.onopen=L=>{clearTimeout(V),A(I)},I.onerror=L=>{clearTimeout(V);let K=`Error opening a data channel for handshaking: ${L.target?.toString()??"not specified"}`;this.log.error(K),this.metrics?.dialerEvents.increment({unknown_error:!0}),k(new $n("data",K))}}),f="libp2p+webrtc+v1/"+Vh(32),d=await l.createOffer(),m=Oh(d,f);await l.setLocalDescription(m);let x=Ph(t,f);await l.setRemoteDescription(x);let g=await u,h=this.generateNoisePrologue(l,a.code,t),w=Uh({prologueBytes:h})(this.components),b=jr({channel:g,direction:"inbound",logger:this.components.logger,...this.init.dataChannel??{}}),p={...b,sink:b.sink.bind(b),source:async function*(){for await(let A of b.source)for(let k of A)yield k}()},B=new gr(this.components,{peerConnection:l,remoteAddr:t,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),_=Hn?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(_,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":B.close().catch(A=>{this.log.error("error closing connection",A)}).finally(()=>{n.abort()});break;default:break}},{signal:o}),this.metrics?.dialerEvents.increment({peer_connection:!0});let N=new Ye(this.components,{peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await w.secureInbound(p,{signal:o,remotePeer:i}),await e.upgrader.upgradeOutbound(B,{skipProtection:!0,skipEncryption:!0,muxerFactory:N})}catch(u){throw l.close(),u}}generateNoisePrologue(t,e,n){if(t.getConfiguration().certificates?.length===0)throw new et("no local certificate");let o=Dh(t,{log:this.log});if(o==null)throw new et("no local fingerprint found");let s=o.trim().toLowerCase().replaceAll(":",""),i=rt(s,"hex"),a=Vt(e,i),c=Oc.decode(ui(n)),l=rt("libp2p-webrtc-noise:");return At([l,a.bytes,c])}};function Hg(r){return t=>new fi(t,r)}function Mg(r){return t=>new ri(t,r)}return rd(Vg);})();
26
26
  /*! Bundled license information:
27
27
 
28
28
  pvtsutils/build/index.js: