@libp2p/webrtc 5.1.0 → 5.1.1-700e4c0b5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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 Oh=Object.create;var Fn=Object.defineProperty;var Mh=Object.getOwnPropertyDescriptor;var Hh=Object.getOwnPropertyNames;var Fh=Object.getPrototypeOf,Vh=Object.prototype.hasOwnProperty;var Kh=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),It=(r,t)=>{for(var e in t)Fn(r,e,{get:t[e],enumerable:!0})},Oc=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Hh(t))!Vh.call(r,o)&&o!==e&&Fn(r,o,{get:()=>t[o],enumerable:!(n=Mh(t,o))||n.enumerable});return r};var $h=(r,t,e)=>(e=r!=null?Oh(Fh(r)):{},Oc(t||!r||!r.__esModule?Fn(e,"default",{value:r,enumerable:!0}):e,r)),Wh=r=>Oc(Fn({},"__esModule",{value:!0}),r);var Hl=Kh(Nr=>{"use strict";var d0="[object ArrayBuffer]",Ae=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===d0}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}},fa="string",p0=/^[0-9a-f\s]+$/i,m0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,g0=/^[a-zA-Z0-9-_]+$/,po=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=Ae.toUint8Array(t),n="";for(let s=0;s<e.length;s++)n+=String.fromCharCode(e[s]);return decodeURIComponent(escape(n))}},Gt=class{static toString(t,e=!1){let n=Ae.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}},mo=class r{static isHex(t){return typeof t===fa&&p0.test(t)}static isBase64(t){return typeof t===fa&&m0.test(t)}static isBase64Url(t){return typeof t===fa&&g0.test(t)}static ToString(t,e="utf8"){let n=Ae.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 Gt.toString(n,!0);case"utf16":case"utf16be":return Gt.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 Gt.fromString(t,!0);case"utf16":case"utf16be":return Gt.fromString(t);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToBase64(t){let e=Ae.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 po.fromString(t);case"utf16":case"utf16be":return Gt.fromString(t);case"utf16le":case"usc2":return Gt.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 po.toString(t);case"utf16":case"utf16be":return Gt.toString(t);case"utf16le":case"usc2":return Gt.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=Ae.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=Ae.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 Gt.toString(t,e)}static FromUtf16String(t,e=!1){return Gt.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,"")||""}};mo.DEFAULT_UTF8_ENCODING="utf8";function y0(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 w0(...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 b0(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}Nr.BufferSourceConverter=Ae;Nr.Convert=mo;Nr.assign=y0;Nr.combine=w0;Nr.isEqual=b0});var bg={};It(bg,{webRTC:()=>wg,webRTCDirect:()=>yg});var ri=Symbol.for("@libp2p/peer-id");var Vn=Symbol.for("@libp2p/transport");var Mc;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Mc||(Mc={}));var Kn=class extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}};var rt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},gr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var $n=class extends Error{static name="ConnectionFailedError";constructor(t="Connection failed"){super(t),this.name="ConnectionFailedError"}};var Wn=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}},Ye=class extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}};var qn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var Gn=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var zn=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}};var Je=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var yr=class extends EventTarget{#t=new Map;constructor(){super()}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 wr=Symbol.for("@libp2p/service-capabilities"),Hc=Symbol.for("@libp2p/service-dependencies");var ai={};It(ai,{base58btc:()=>nt,base58flickr:()=>Xh});var zg=new Uint8Array(0);function Fc(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 pe(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 Vc(r){return new TextEncoder().encode(r)}function Kc(r){return new TextDecoder().decode(r)}function qh(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(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var g=0,h=0,b=0,x=y.length;b!==x&&y[b]===0;)b++,g++;for(var p=(x-b)*u+1>>>0,S=new Uint8Array(p);b!==x;){for(var L=y[b],N=0,B=p-1;(L!==0||N<h)&&B!==-1;B--,N++)L+=256*S[B]>>>0,S[B]=L%a>>>0,L=L/a>>>0;if(L!==0)throw new Error("Non-zero carry");h=N,b++}for(var T=p-h;T!==p&&S[T]===0;)T++;for(var I=c.repeat(g);T<p;++T)I+=r.charAt(S[T]);return I}function d(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var g=0;if(y[g]!==" "){for(var h=0,b=0;y[g]===c;)h++,g++;for(var x=(y.length-g)*l+1>>>0,p=new Uint8Array(x);y[g];){var S=e[y.charCodeAt(g)];if(S===255)return;for(var L=0,N=x-1;(S!==0||L<b)&&N!==-1;N--,L++)S+=a*p[N]>>>0,p[N]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");b=L,g++}if(y[g]!==" "){for(var B=x-b;B!==x&&p[B]===0;)B++;for(var T=new Uint8Array(h+(x-B)),I=h;B!==x;)T[I++]=p[B++];return T}}}function m(y){var g=d(y);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:m}}var Gh=qh,zh=Gh,Wc=zh;var ni=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")}},oi=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 qc(this,t)}},si=class{decoders;constructor(t){this.decoders=t}or(t){return qc(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 qc(r,t){return new si({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ii=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 ni(t,e,n),this.decoder=new oi(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 ii(r,t,e,n)}function Ue({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Wc(e,r);return br({prefix:t,name:r,encode:n,decode:s=>pe(o(s))})}function jh(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 Zh(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 dt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return br({prefix:t,name:r,encode(o){return Zh(o,n,e)},decode(o){return jh(o,n,e,r)}})}var nt=Ue({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Xh=Ue({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ci={};It(ci,{base32:()=>me,base32hex:()=>td,base32hexpad:()=>rd,base32hexpadupper:()=>nd,base32hexupper:()=>ed,base32pad:()=>Jh,base32padupper:()=>Qh,base32upper:()=>Yh,base32z:()=>od});var me=dt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Yh=dt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Jh=dt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Qh=dt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),td=dt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ed=dt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),rd=dt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),nd=dt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),od=dt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var li={};It(li,{base36:()=>jr,base36upper:()=>sd});var jr=Ue({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),sd=Ue({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Wt={};It(Wt,{Digest:()=>Qe,create:()=>kt,decode:()=>Pe,equals:()=>fi,hasCode:()=>Bd});var id=jc,Gc=128,ad=127,cd=~ad,ld=Math.pow(2,31);function jc(r,t,e){t=t||[],e=e||0;for(var n=e;r>=ld;)t[e++]=r&255|Gc,r/=128;for(;r&cd;)t[e++]=r&255|Gc,r>>>=7;return t[e]=r|0,jc.bytes=e-n+1,t}var ud=ui,fd=128,zc=127;function ui(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ui.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&zc)<<o:(i&zc)*Math.pow(2,o),o+=7}while(i>=fd);return ui.bytes=s-n,e}var hd=Math.pow(2,7),dd=Math.pow(2,14),pd=Math.pow(2,21),md=Math.pow(2,28),gd=Math.pow(2,35),yd=Math.pow(2,42),wd=Math.pow(2,49),bd=Math.pow(2,56),xd=Math.pow(2,63),vd=function(r){return r<hd?1:r<dd?2:r<pd?3:r<md?4:r<gd?5:r<yd?6:r<wd?7:r<bd?8:r<xd?9:10},Ed={encode:id,decode:ud,encodingLength:vd},Ad=Ed,Zr=Ad;function Xr(r,t=0){return[Zr.decode(r,t),Zr.decode.bytes]}function xr(r,t,e=0){return Zr.encode(r,t,e),t}function vr(r){return Zr.encodingLength(r)}function kt(r,t){let e=t.byteLength,n=vr(r),o=n+vr(e),s=new Uint8Array(o+e);return xr(r,s,0),xr(e,s,n),s.set(t,o),new Qe(r,e,t,s)}function Pe(r){let t=pe(r),[e,n]=Xr(t),[o,s]=Xr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Qe(e,o,i,t)}function fi(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Fc(r.bytes,e.bytes)}}var Qe=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Bd(r,t){return r.code===t}function Zc(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Cd(e,hi(r),t??nt.encoder);default:return Id(e,hi(r),t??me.encoder)}}var Xc=new WeakMap;function hi(r){let t=Xc.get(r);if(t==null){let e=new Map;return Xc.set(r,e),e}return t}var vt=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!==Yr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==kd)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=kt(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&&fi(t.multihash,n.multihash)}toString(t){return Zc(this,t)}toJSON(){return{"/":Zc(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??Yc(n,o,s.bytes))}else if(e[Td]===!0){let{version:n,multihash:o,code:s}=e,i=Pe(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!==Yr)throw new Error(`Version 0 CID must use dag-pb (code: ${Yr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Yc(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Yr,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=pe(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 Qe(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]=Xr(t.subarray(e));return e+=d,f},o=n(),s=Yr;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]=Sd(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 hi(s).set(n,t),s}};function Sd(r,t){switch(r[0]){case"Q":{let e=t??nt;return[nt.prefix,e.decode(`${nt.prefix}${r}`)]}case nt.prefix:{let e=t??nt;return[nt.prefix,e.decode(r)]}case me.prefix:{let e=t??me;return[me.prefix,e.decode(r)]}case jr.prefix:{let e=t??jr;return[jr.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 Cd(r,t,e){let{prefix:n}=e;if(n!==nt.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 Id(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 Yr=112,kd=18;function Yc(r,t,e){let n=vr(r),o=n+vr(t),s=new Uint8Array(o+e.byteLength);return xr(r,s,0),xr(t,s,n),s.set(e,o),s}var Td=Symbol.for("@ipld/js-cid/CID");var di={};It(di,{identity:()=>ge});var Jc=0,Nd="identity",Qc=pe;function Ld(r){return kt(Jc,Qc(r))}var ge={code:Jc,name:Nd,encode:Qc,digest:Ld};function Ut(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 Zn(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function _d(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Er(r,...t){if(!_d(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function Jr(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Zn(r.outputLen),Zn(r.blockLen)}function Ar(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 tl(r,t){Er(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}var tr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Xn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function jt(r,t){return r<<32-t|r>>>t}function el(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function De(r){return typeof r=="string"&&(r=el(r)),Er(r),r}function pi(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Er(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 Br=class{clone(){return this._cloneInto()}};function Yn(r){let t=n=>r().update(De(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Qr(r=32){if(tr&&typeof tr.getRandomValues=="function")return tr.getRandomValues(new Uint8Array(r));if(tr&&typeof tr.randomBytes=="function")return tr.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function Rd(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 rl(r,t,e){return r&t^~r&e}function nl(r,t,e){return r&t^r&e^t&e}var Sr=class extends Br{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=Xn(this.buffer)}update(t){Ar(this);let{view:e,buffer:n,blockLen:o}=this;t=De(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=Xn(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){Ar(this),tl(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;Rd(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Xn(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 Jn=BigInt(4294967295),mi=BigInt(32);function ol(r,t=!1){return t?{h:Number(r&Jn),l:Number(r>>mi&Jn)}:{h:Number(r>>mi&Jn)|0,l:Number(r&Jn)|0}}function Ud(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}=ol(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var Pd=(r,t)=>BigInt(r>>>0)<<mi|BigInt(t>>>0),Dd=(r,t,e)=>r>>>e,Od=(r,t,e)=>r<<32-e|t>>>e,Md=(r,t,e)=>r>>>e|t<<32-e,Hd=(r,t,e)=>r<<32-e|t>>>e,Fd=(r,t,e)=>r<<64-e|t>>>e-32,Vd=(r,t,e)=>r>>>e-32|t<<64-e,Kd=(r,t)=>t,$d=(r,t)=>r,Wd=(r,t,e)=>r<<e|t>>>32-e,qd=(r,t,e)=>t<<e|r>>>32-e,Gd=(r,t,e)=>t<<e-32|r>>>64-e,zd=(r,t,e)=>r<<e-32|t>>>64-e;function jd(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Zd=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Xd=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Yd=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Jd=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Qd=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),tp=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var ep={fromBig:ol,split:Ud,toBig:Pd,shrSH:Dd,shrSL:Od,rotrSH:Md,rotrSL:Hd,rotrBH:Fd,rotrBL:Vd,rotr32H:Kd,rotr32L:$d,rotlSH:Wd,rotlSL:qd,rotlBH:Gd,rotlBL:zd,add:jd,add3L:Zd,add3H:Xd,add4L:Yd,add4H:Jd,add5H:tp,add5L:Qd},$=ep;var[rp,np]=$.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))),Oe=new Uint32Array(80),Me=new Uint32Array(80),gi=class extends Sr{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:y,Hh:g,Hl:h}=this;return[t,e,n,o,s,i,a,c,l,u,f,d,m,y,g,h]}set(t,e,n,o,s,i,a,c,l,u,f,d,m,y,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=y|0,this.Hh=g|0,this.Hl=h|0}process(t,e){for(let p=0;p<16;p++,e+=4)Oe[p]=t.getUint32(e),Me[p]=t.getUint32(e+=4);for(let p=16;p<80;p++){let S=Oe[p-15]|0,L=Me[p-15]|0,N=$.rotrSH(S,L,1)^$.rotrSH(S,L,8)^$.shrSH(S,L,7),B=$.rotrSL(S,L,1)^$.rotrSL(S,L,8)^$.shrSL(S,L,7),T=Oe[p-2]|0,I=Me[p-2]|0,H=$.rotrSH(T,I,19)^$.rotrBH(T,I,61)^$.shrSH(T,I,6),U=$.rotrSL(T,I,19)^$.rotrBL(T,I,61)^$.shrSL(T,I,6),M=$.add4L(B,U,Me[p-7],Me[p-16]),V=$.add4H(M,N,H,Oe[p-7],Oe[p-16]);Oe[p]=V|0,Me[p]=M|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:y,Gh:g,Gl:h,Hh:b,Hl:x}=this;for(let p=0;p<80;p++){let S=$.rotrSH(f,d,14)^$.rotrSH(f,d,18)^$.rotrBH(f,d,41),L=$.rotrSL(f,d,14)^$.rotrSL(f,d,18)^$.rotrBL(f,d,41),N=f&m^~f&g,B=d&y^~d&h,T=$.add5L(x,L,B,np[p],Me[p]),I=$.add5H(T,b,S,N,rp[p],Oe[p]),H=T|0,U=$.rotrSH(n,o,28)^$.rotrBH(n,o,34)^$.rotrBH(n,o,39),M=$.rotrSL(n,o,28)^$.rotrBL(n,o,34)^$.rotrBL(n,o,39),V=n&s^n&a^s&a,C=o&i^o&c^i&c;b=g|0,x=h|0,g=m|0,h=y|0,m=f|0,y=d|0,{h:f,l:d}=$.add(l|0,u|0,I|0,H|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let k=$.add3L(H,M,C);n=$.add3H(k,I,U,V),o=k|0}({h:n,l:o}=$.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=$.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=$.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=$.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=$.add(this.Eh|0,this.El|0,f|0,d|0),{h:m,l:y}=$.add(this.Fh|0,this.Fl|0,m|0,y|0),{h:g,l:h}=$.add(this.Gh|0,this.Gl|0,g|0,h|0),{h:b,l:x}=$.add(this.Hh|0,this.Hl|0,b|0,x|0),this.set(n,o,s,i,a,c,l,u,f,d,m,y,g,h,b,x)}roundClean(){Oe.fill(0),Me.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 sl=Yn(()=>new gi);var eo={};It(eo,{aInRange:()=>Et,abool:()=>Zt,abytes:()=>Cr,bitGet:()=>lp,bitLen:()=>xi,bitMask:()=>en,bitSet:()=>up,bytesToHex:()=>we,bytesToNumberBE:()=>be,bytesToNumberLE:()=>Xt,concatBytes:()=>ve,createHmacDrbg:()=>vi,ensureBytes:()=>ot,equalBytes:()=>ap,hexToBytes:()=>rr,hexToNumber:()=>bi,inRange:()=>tn,isBytes:()=>He,memoized:()=>nr,notImplemented:()=>hp,numberToBytesBE:()=>Fe,numberToBytesLE:()=>xe,numberToHexUnpadded:()=>er,numberToVarBytesBE:()=>ip,utf8ToBytes:()=>cp,validateObject:()=>qt});var Qn=BigInt(0),to=BigInt(1),op=BigInt(2);function He(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Cr(r){if(!He(r))throw new Error("Uint8Array expected")}function Zt(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}var sp=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function we(r){Cr(r);let t="";for(let e=0;e<r.length;e++)t+=sp[r[e]];return t}function er(r){let t=r.toString(16);return t.length&1?"0"+t:t}function bi(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Qn:BigInt("0x"+r)}var ye={_0:48,_9:57,A:65,F:70,a:97,f:102};function il(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 rr(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("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=il(r.charCodeAt(s)),a=il(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 be(r){return bi(we(r))}function Xt(r){return Cr(r),bi(we(Uint8Array.from(r).reverse()))}function Fe(r,t){return rr(r.toString(16).padStart(t*2,"0"))}function xe(r,t){return Fe(r,t).reverse()}function ip(r){return rr(er(r))}function ot(r,t,e){let n;if(typeof t=="string")try{n=rr(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(He(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+" of length "+e+" expected, got "+o);return n}function ve(...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}function ap(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 cp(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var yi=r=>typeof r=="bigint"&&Qn<=r;function tn(r,t,e){return yi(r)&&yi(t)&&yi(e)&&t<=r&&r<e}function Et(r,t,e,n){if(!tn(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function xi(r){let t;for(t=0;r>Qn;r>>=to,t+=1);return t}function lp(r,t){return r>>BigInt(t)&to}function up(r,t,e){return r|(e?to:Qn)<<BigInt(t)}var en=r=>(op<<BigInt(r-1))-to,wi=r=>new Uint8Array(r),al=r=>Uint8Array.from(r);function vi(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=wi(r),o=wi(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=wi())=>{o=a(al([0]),f),n=a(),f.length!==0&&(o=a(al([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 fp={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"||He(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 qt(r,t,e={}){let n=(o,s,i)=>{let a=fp[s];if(typeof a!="function")throw new Error("invalid validator function");let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};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 hp=()=>{throw new Error("not implemented")};function nr(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 mt=BigInt(0),ft=BigInt(1),or=BigInt(2),dp=BigInt(3),Ei=BigInt(4),cl=BigInt(5),ll=BigInt(8),pp=BigInt(9),mp=BigInt(16);function Z(r,t){let e=r%t;return e>=mt?e:t+e}function Ai(r,t,e){if(t<mt)throw new Error("invalid exponent, negatives unsupported");if(e<=mt)throw new Error("invalid modulus");if(e===ft)return mt;let n=ft;for(;t>mt;)t&ft&&(n=n*r%e),r=r*r%e,t>>=ft;return n}function at(r,t,e){let n=r;for(;t-- >mt;)n*=n,n%=e;return n}function ro(r,t){if(r===mt)throw new Error("invert: expected non-zero number");if(t<=mt)throw new Error("invert: expected positive modulus, got "+t);let e=Z(r,t),n=t,o=mt,s=ft,i=ft,a=mt;for(;e!==mt;){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 Z(o,t)}function gp(r){let t=(r-ft)/or,e,n,o;for(e=r-ft,n=0;e%or===mt;e/=or,n++);for(o=or;o<r&&Ai(o,t,r)!==r-ft;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(r+ft)/Ei;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)/or;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 y=a.pow(u,ft<<BigInt(l-m-1));u=a.sqr(y),f=a.mul(f,y),d=a.mul(d,u),l=m}return f}}function yp(r){if(r%Ei===dp){let t=(r+ft)/Ei;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%ll===cl){let t=(r-cl)/ll;return function(n,o){let s=n.mul(o,or),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,or),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%mp,gp(r)}var ul=(r,t)=>(Z(r,t)&ft)===ft,wp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Bi(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=wp.reduce((n,o)=>(n[o]="function",n),t);return qt(r,e)}function bp(r,t,e){if(e<mt)throw new Error("invalid exponent, negatives unsupported");if(e===mt)return r.ONE;if(e===ft)return t;let n=r.ONE,o=t;for(;e>mt;)e&ft&&(n=r.mul(n,o)),o=r.sqr(o),e>>=ft;return n}function xp(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 Si(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Ve(r,t,e=!1,n={}){if(r<=mt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=Si(r,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:r,isLE:e,BITS:o,BYTES:s,MASK:en(o),ZERO:mt,ONE:ft,create:c=>Z(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return mt<=c&&c<r},is0:c=>c===mt,isOdd:c=>(c&ft)===ft,neg:c=>Z(-c,r),eql:(c,l)=>c===l,sqr:c=>Z(c*c,r),add:(c,l)=>Z(c+l,r),sub:(c,l)=>Z(c-l,r),mul:(c,l)=>Z(c*l,r),pow:(c,l)=>bp(a,c,l),div:(c,l)=>Z(c*ro(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>ro(c,r),sqrt:n.sqrt||(c=>(i||(i=yp(r)),i(a,c))),invertBatch:c=>xp(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?xe(c,s):Fe(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return e?Xt(c):be(c)}});return Object.freeze(a)}function fl(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 Ci(r){let t=fl(r);return t+Math.ceil(t/2)}function hl(r,t,e=!1){let n=r.length,o=fl(t),s=Ci(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?Xt(r):be(r),a=Z(i,t-ft)+ft;return e?xe(a,o):Fe(a,o)}var dl=BigInt(0),no=BigInt(1);function Ii(r,t){let e=t.negate();return r?e:t}function pl(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function ki(r,t){pl(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1);return{windows:e,windowSize:n}}function vp(r,t){if(!Array.isArray(r))throw new Error("array expected");r.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}function Ep(r,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}var Ti=new WeakMap,ml=new WeakMap;function Ni(r){return ml.get(r)||1}function oo(r,t){return{constTimeNegate:Ii,hasPrecomputes(e){return Ni(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>dl;)n&no&&(o=o.add(s)),s=s.double(),n>>=no;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=ki(n,t),i=[],a=e,c=a;for(let l=0;l<o;l++){c=a,i.push(c);for(let u=1;u<s;u++)c=c.add(a),i.push(c);a=c.double()}return i},wNAF(e,n,o){let{windows:s,windowSize:i}=ki(e,t),a=r.ZERO,c=r.BASE,l=BigInt(2**e-1),u=2**e,f=BigInt(e);for(let d=0;d<s;d++){let m=d*i,y=Number(o&l);o>>=f,y>i&&(y-=u,o+=no);let g=m,h=m+Math.abs(y)-1,b=d%2!==0,x=y<0;y===0?c=c.add(Ii(b,n[g])):a=a.add(Ii(x,n[h]))}return{p:a,f:c}},wNAFUnsafe(e,n,o,s=r.ZERO){let{windows:i,windowSize:a}=ki(e,t),c=BigInt(2**e-1),l=2**e,u=BigInt(e);for(let f=0;f<i;f++){let d=f*a;if(o===dl)break;let m=Number(o&c);if(o>>=u,m>a&&(m-=l,o+=no),m===0)continue;let y=n[d+Math.abs(m)-1];m<0&&(y=y.negate()),s=s.add(y)}return s},getPrecomputes(e,n,o){let s=Ti.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&Ti.set(n,o(s))),s},wNAFCached(e,n,o){let s=Ni(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=Ni(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){pl(n,t),ml.set(e,n),Ti.delete(e)}}}function so(r,t,e,n){if(vp(e,r),Ep(n,t),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,s=xi(BigInt(e.length)),i=s>12?s-3:s>4?s-2:s?2:1,a=(1<<i)-1,c=new Array(a+1).fill(o),l=Math.floor((t.BITS-1)/i)*i,u=o;for(let f=l;f>=0;f-=i){c.fill(o);for(let m=0;m<n.length;m++){let y=n[m],g=Number(y>>BigInt(f)&BigInt(a));c[g]=c[g].add(e[m])}let d=o;for(let m=c.length-1,y=o;m>0;m--)y=y.add(c[m]),d=d.add(y);if(u=u.add(d),f!==0)for(let m=0;m<i;m++)u=u.double()}return u}function rn(r){return Bi(r.Fp),qt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Si(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Yt=BigInt(0),Mt=BigInt(1),io=BigInt(2),Ap=BigInt(8),Bp={zip215:!0};function Sp(r){let t=rn(r);return qt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function gl(r){let t=Sp(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=io<<BigInt(a*8)-Mt,u=e.create,f=Ve(t.n,t.nBitLength),d=t.uvRatio||((v,w)=>{try{return{isValid:!0,value:e.sqrt(v*e.inv(w))}}catch{return{isValid:!1,value:Yt}}}),m=t.adjustScalarBytes||(v=>v),y=t.domain||((v,w,A)=>{if(Zt("phflag",A),w.length||A)throw new Error("Contexts/pre-hash are not supported");return v});function g(v,w){Et("coordinate "+v,w,Yt,l)}function h(v){if(!(v instanceof p))throw new Error("ExtendedPoint expected")}let b=nr((v,w)=>{let{ex:A,ey:E,ez:_}=v,R=v.is0();w==null&&(w=R?Ap:e.inv(_));let O=u(A*w),K=u(E*w),F=u(_*w);if(R)return{x:Yt,y:Mt};if(F!==Mt)throw new Error("invZ was invalid");return{x:O,y:K}}),x=nr(v=>{let{a:w,d:A}=t;if(v.is0())throw new Error("bad point: ZERO");let{ex:E,ey:_,ez:R,et:O}=v,K=u(E*E),F=u(_*_),W=u(R*R),j=u(W*W),st=u(K*w),it=u(W*u(st+F)),ut=u(j+u(A*u(K*F)));if(it!==ut)throw new Error("bad point: equation left != right (1)");let Ct=u(E*_),Ot=u(R*O);if(Ct!==Ot)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(w,A,E,_){this.ex=w,this.ey=A,this.ez=E,this.et=_,g("x",w),g("y",A),g("z",E),g("t",_),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(w){if(w instanceof p)throw new Error("extended point not allowed");let{x:A,y:E}=w||{};return g("x",A),g("y",E),new p(A,E,Mt,u(A*E))}static normalizeZ(w){let A=e.invertBatch(w.map(E=>E.ez));return w.map((E,_)=>E.toAffine(A[_])).map(p.fromAffine)}static msm(w,A){return so(p,f,w,A)}_setWindowSize(w){N.setWindowSize(this,w)}assertValidity(){x(this)}equals(w){h(w);let{ex:A,ey:E,ez:_}=this,{ex:R,ey:O,ez:K}=w,F=u(A*K),W=u(R*_),j=u(E*K),st=u(O*_);return F===W&&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:w}=t,{ex:A,ey:E,ez:_}=this,R=u(A*A),O=u(E*E),K=u(io*u(_*_)),F=u(w*R),W=A+E,j=u(u(W*W)-R-O),st=F+O,it=st-K,ut=F-O,Ct=u(j*it),Ot=u(st*ut),Rt=u(j*ut),se=u(it*st);return new p(Ct,Ot,se,Rt)}add(w){h(w);let{a:A,d:E}=t,{ex:_,ey:R,ez:O,et:K}=this,{ex:F,ey:W,ez:j,et:st}=w;if(A===BigInt(-1)){let Nc=u((R-_)*(W+F)),Lc=u((R+_)*(W-F)),ei=u(Lc-Nc);if(ei===Yt)return this.double();let _c=u(O*io*st),Rc=u(K*io*j),Uc=Rc+_c,Pc=Lc+Nc,Dc=Rc-_c,Rh=u(Uc*ei),Uh=u(Pc*Dc),Ph=u(Uc*Dc),Dh=u(ei*Pc);return new p(Rh,Uh,Dh,Ph)}let it=u(_*F),ut=u(R*W),Ct=u(K*E*st),Ot=u(O*j),Rt=u((_+R)*(F+W)-it-ut),se=Ot-Ct,de=Ot+Ct,zr=u(ut-A*it),Th=u(Rt*se),Nh=u(de*zr),Lh=u(Rt*zr),_h=u(se*de);return new p(Th,Nh,_h,Lh)}subtract(w){return this.add(w.negate())}wNAF(w){return N.wNAFCached(this,w,p.normalizeZ)}multiply(w){let A=w;Et("scalar",A,Mt,n);let{p:E,f:_}=this.wNAF(A);return p.normalizeZ([E,_])[0]}multiplyUnsafe(w,A=p.ZERO){let E=w;return Et("scalar",E,Yt,n),E===Yt?L:this.is0()||E===Mt?this:N.wNAFCachedUnsafe(this,E,p.normalizeZ,A)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return N.unsafeLadder(this,n).is0()}toAffine(w){return b(this,w)}clearCofactor(){let{h:w}=t;return w===Mt?this:this.multiplyUnsafe(w)}static fromHex(w,A=!1){let{d:E,a:_}=t,R=e.BYTES;w=ot("pointHex",w,R),Zt("zip215",A);let O=w.slice(),K=w[R-1];O[R-1]=K&-129;let F=Xt(O),W=A?l:e.ORDER;Et("pointHex.y",F,Yt,W);let j=u(F*F),st=u(j-Mt),it=u(E*j-_),{isValid:ut,value:Ct}=d(st,it);if(!ut)throw new Error("Point.fromHex: invalid y coordinate");let Ot=(Ct&Mt)===Mt,Rt=(K&128)!==0;if(!A&&Ct===Yt&&Rt)throw new Error("Point.fromHex: x=0 and x_0=1");return Rt!==Ot&&(Ct=u(-Ct)),p.fromAffine({x:Ct,y:F})}static fromPrivateKey(w){return I(w).point}toRawBytes(){let{x:w,y:A}=this.toAffine(),E=xe(A,e.BYTES);return E[E.length-1]|=w&Mt?128:0,E}toHex(){return we(this.toRawBytes())}}p.BASE=new p(t.Gx,t.Gy,Mt,u(t.Gx*t.Gy)),p.ZERO=new p(Yt,Mt,Mt,Yt);let{BASE:S,ZERO:L}=p,N=oo(p,a*8);function B(v){return Z(v,n)}function T(v){return B(Xt(v))}function I(v){let w=e.BYTES;v=ot("private key",v,w);let A=ot("hashed private key",s(v),2*w),E=m(A.slice(0,w)),_=A.slice(w,2*w),R=T(E),O=S.multiply(R),K=O.toRawBytes();return{head:E,prefix:_,scalar:R,point:O,pointBytes:K}}function H(v){return I(v).pointBytes}function U(v=new Uint8Array,...w){let A=ve(...w);return T(s(y(A,ot("context",v),!!o)))}function M(v,w,A={}){v=ot("message",v),o&&(v=o(v));let{prefix:E,scalar:_,pointBytes:R}=I(w),O=U(A.context,E,v),K=S.multiply(O).toRawBytes(),F=U(A.context,K,R,v),W=B(O+F*_);Et("signature.s",W,Yt,n);let j=ve(K,xe(W,e.BYTES));return ot("result",j,e.BYTES*2)}let V=Bp;function C(v,w,A,E=V){let{context:_,zip215:R}=E,O=e.BYTES;v=ot("signature",v,2*O),w=ot("message",w),A=ot("publicKey",A,O),R!==void 0&&Zt("zip215",R),o&&(w=o(w));let K=Xt(v.slice(O,2*O)),F,W,j;try{F=p.fromHex(A,R),W=p.fromHex(v.slice(0,O),R),j=S.multiplyUnsafe(K)}catch{return!1}if(!R&&F.isSmallOrder())return!1;let st=U(_,W.toRawBytes(),F.toRawBytes(),w);return W.add(F.multiplyUnsafe(st)).subtract(j).clearCofactor().equals(p.ZERO)}return S._setWindowSize(8),{CURVE:t,getPublicKey:H,sign:M,verify:C,ExtendedPoint:p,utils:{getExtendedPublicKey:I,randomPrivateKey:()=>i(e.BYTES),precompute(v=8,w=p.BASE){return w._setWindowSize(v),w.multiply(BigInt(3)),w}}}}var Ir=BigInt(0),Li=BigInt(1);function Cp(r){return qt(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function yl(r){let t=Cp(r),{P:e}=t,n=x=>Z(x,e),o=t.montgomeryBits,s=Math.ceil(o/8),i=t.nByteLength,a=t.adjustScalarBytes||(x=>x),c=t.powPminus2||(x=>Ai(x,e-BigInt(2),e));function l(x,p,S){let L=n(x*(p-S));return p=n(p-L),S=n(S+L),[p,S]}let u=(t.a-BigInt(2))/BigInt(4);function f(x,p){Et("u",x,Ir,e),Et("scalar",p,Ir,e);let S=p,L=x,N=Li,B=Ir,T=x,I=Li,H=Ir,U;for(let V=BigInt(o-1);V>=Ir;V--){let C=S>>V&Li;H^=C,U=l(H,N,T),N=U[0],T=U[1],U=l(H,B,I),B=U[0],I=U[1],H=C;let k=N+B,v=n(k*k),w=N-B,A=n(w*w),E=v-A,_=T+I,R=T-I,O=n(R*k),K=n(_*w),F=O+K,W=O-K;T=n(F*F),I=n(L*n(W*W)),N=n(v*A),B=n(E*(v+n(u*E)))}U=l(H,N,T),N=U[0],T=U[1],U=l(H,B,I),B=U[0],I=U[1];let M=c(B);return n(N*M)}function d(x){return xe(n(x),s)}function m(x){let p=ot("u coordinate",x,s);return i===32&&(p[31]&=127),Xt(p)}function y(x){let p=ot("scalar",x),S=p.length;if(S!==s&&S!==i){let L=""+s+" or "+i;throw new Error("invalid scalar, expected "+L+" bytes, got "+S)}return Xt(a(p))}function g(x,p){let S=m(p),L=y(x),N=f(S,L);if(N===Ir)throw new Error("invalid private or public key received");return d(N)}let h=d(t.Gu);function b(x){return g(x,h)}return{scalarMult:g,scalarMultBase:b,getSharedSecret:(x,p)=>g(x,p),getPublicKey:x=>b(x),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:h}}var nn=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),wl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),$y=BigInt(0),Ip=BigInt(1),bl=BigInt(2),kp=BigInt(3),Tp=BigInt(5),Np=BigInt(8);function xl(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=nn,a=r*r%s*r%s,c=at(a,bl,s)*a%s,l=at(c,Ip,s)*r%s,u=at(l,Tp,s)*l%s,f=at(u,t,s)*u%s,d=at(f,e,s)*f%s,m=at(d,n,s)*d%s,y=at(m,o,s)*m%s,g=at(y,o,s)*m%s,h=at(g,t,s)*u%s;return{pow_p_5_8:at(h,bl,s)*r%s,b2:a}}function vl(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Lp(r,t){let e=nn,n=Z(t*t*t,e),o=Z(n*n*t,e),s=xl(r*o).pow_p_5_8,i=Z(r*n*s,e),a=Z(t*i*i,e),c=i,l=Z(i*wl,e),u=a===r,f=a===Z(-r,e),d=a===Z(-r*wl,e);return u&&(i=c),(f||d)&&(i=l),ul(i,e)&&(i=Z(-i,e)),{isValid:u||f,value:i}}var _p=Ve(nn,void 0,!0),Rp={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:_p,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Np,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:sl,randomBytes:Qr,adjustScalarBytes:vl,uvRatio:Lp},El=gl(Rp);var on=yl({P:nn,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let t=nn,{pow_p_5_8:e,b2:n}=xl(r);return Z(at(e,kp,t)*n,t)},adjustScalarBytes:vl,randomBytes:Qr});var ao=32;function Al(r,t,e){return El.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}var co=class{type="Ed25519";raw;constructor(t){this.raw=_i(t,ao)}toMultihash(){return ge.digest(kr(this))}toCID(){return vt.createV1(114,this.toMultihash())}toString(){return nt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Ut(this.raw,t.raw)}verify(t,e){return Al(this.raw,e,t)}};function Ri(r){return r=_i(r,ao),new co(r)}function _i(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new rt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}function gt(r=0){return new Uint8Array(r)}function yt(r=0){return new Uint8Array(r)}var Pp=Math.pow(2,7),Dp=Math.pow(2,14),Op=Math.pow(2,21),Ui=Math.pow(2,28),Pi=Math.pow(2,35),Di=Math.pow(2,42),Oi=Math.pow(2,49),J=128,Tt=127;function ct(r){if(r<Pp)return 1;if(r<Dp)return 2;if(r<Op)return 3;if(r<Ui)return 4;if(r<Pi)return 5;if(r<Di)return 6;if(r<Oi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Mi(r,t,e=0){switch(ct(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 Mp(r,t,e=0){switch(ct(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 Hi(r,t){let e=r[t],n=0;if(n+=e&Tt,e<J||(e=r[t+1],n+=(e&Tt)<<7,e<J)||(e=r[t+2],n+=(e&Tt)<<14,e<J)||(e=r[t+3],n+=(e&Tt)<<21,e<J)||(e=r[t+4],n+=(e&Tt)*Ui,e<J)||(e=r[t+5],n+=(e&Tt)*Pi,e<J)||(e=r[t+6],n+=(e&Tt)*Di,e<J)||(e=r[t+7],n+=(e&Tt)*Oi,e<J))return n;throw new RangeError("Could not decode varint")}function Hp(r,t){let e=r.get(t),n=0;if(n+=e&Tt,e<J||(e=r.get(t+1),n+=(e&Tt)<<7,e<J)||(e=r.get(t+2),n+=(e&Tt)<<14,e<J)||(e=r.get(t+3),n+=(e&Tt)<<21,e<J)||(e=r.get(t+4),n+=(e&Tt)*Ui,e<J)||(e=r.get(t+5),n+=(e&Tt)*Pi,e<J)||(e=r.get(t+6),n+=(e&Tt)*Di,e<J)||(e=r.get(t+7),n+=(e&Tt)*Oi,e<J))return n;throw new RangeError("Could not decode varint")}function ie(r,t,e=0){return t==null&&(t=yt(ct(r))),t instanceof Uint8Array?Mi(r,t,e):Mp(r,t,e)}function Jt(r,t=0){return r instanceof Uint8Array?Hi(r,t):Hp(r,t)}var Fi=new Float32Array([-0]),Ke=new Uint8Array(Fi.buffer);function Sl(r,t,e){Fi[0]=r,t[e]=Ke[0],t[e+1]=Ke[1],t[e+2]=Ke[2],t[e+3]=Ke[3]}function Cl(r,t){return Ke[0]=r[t],Ke[1]=r[t+1],Ke[2]=r[t+2],Ke[3]=r[t+3],Fi[0]}var Vi=new Float64Array([-0]),Nt=new Uint8Array(Vi.buffer);function Il(r,t,e){Vi[0]=r,t[e]=Nt[0],t[e+1]=Nt[1],t[e+2]=Nt[2],t[e+3]=Nt[3],t[e+4]=Nt[4],t[e+5]=Nt[5],t[e+6]=Nt[6],t[e+7]=Nt[7]}function kl(r,t){return Nt[0]=r[t],Nt[1]=r[t+1],Nt[2]=r[t+2],Nt[3]=r[t+3],Nt[4]=r[t+4],Nt[5]=r[t+5],Nt[6]=r[t+6],Nt[7]=r[t+7],Vi[0]}var Fp=BigInt(Number.MAX_SAFE_INTEGER),Vp=BigInt(Number.MIN_SAFE_INTEGER),Kt=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 sr;if(t<Fp&&t>Vp)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>Tl&&(o=0n,++n>Tl&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return sr;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):sr}},sr=new Kt(0,0);sr.toBigInt=function(){return 0n};sr.zzEncode=sr.zzDecode=function(){return this};sr.length=function(){return 1};var Tl=4294967296n;function Nl(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 Ll(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 Ki(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 Qt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function lo(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var $i=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,Qt(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 Qt(this,4);return lo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Qt(this,4);return lo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Qt(this,4);let t=Cl(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Qt(this,4);let t=kl(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 Qt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Ll(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Qt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Qt(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 Kt(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 Qt(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 Qt(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 Qt(this,8);let t=lo(this.buf,this.pos+=4),e=lo(this.buf,this.pos+=4);return new Kt(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=Hi(this.buf,this.pos);return this.pos+=ct(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 Wi(r){return new $i(r instanceof Uint8Array?r:r.subarray())}function te(r,t,e){let n=Wi(r);return t.decode(n,void 0,e)}var qi={};It(qi,{base10:()=>Kp});var Kp=Ue({prefix:"9",name:"base10",alphabet:"0123456789"});var Gi={};It(Gi,{base16:()=>$p,base16upper:()=>Wp});var $p=dt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Wp=dt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var zi={};It(zi,{base2:()=>qp});var qp=dt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ji={};It(ji,{base256emoji:()=>Xp});var Rl=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}"),Gp=Rl.reduce((r,t,e)=>(r[e]=t,r),[]),zp=Rl.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function jp(r){return r.reduce((t,e)=>(t+=Gp[e],t),"")}function Zp(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=zp[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Xp=br({prefix:"\u{1F680}",name:"base256emoji",encode:jp,decode:Zp});var Zi={};It(Zi,{base64:()=>Yp,base64pad:()=>Jp,base64url:()=>an,base64urlpad:()=>Qp});var Yp=dt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Jp=dt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),an=dt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Qp=dt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Xi={};It(Xi,{base8:()=>t0});var t0=dt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Yi={};It(Yi,{identity:()=>e0});var e0=br({prefix:"\0",name:"identity",encode:r=>Kc(r),decode:r=>Vc(r)});var Sw=new TextEncoder,Cw=new TextDecoder;var ta={};It(ta,{sha256:()=>Ee,sha512:()=>o0});function Qi({name:r,code:t,encode:e}){return new Ji(r,t,e)}var Ji=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?kt(this.code,e):e.then(n=>kt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Pl(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Ee=Qi({name:"sha2-256",code:18,encode:Pl("SHA-256")}),o0=Qi({name:"sha2-512",code:19,encode:Pl("SHA-512")});var ir={...Yi,...zi,...Xi,...qi,...Gi,...ci,...li,...ai,...Zi,...ji},Mw={...ta,...di};function Ol(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Dl=Ol("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ea=Ol("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=yt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),s0={utf8:Dl,"utf-8":Dl,hex:ir.base16,latin1:ea,ascii:ea,binary:ea,...ir},uo=s0;function Q(r,t="utf8"){let e=uo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function ra(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return yt(i);o+i>t&&(n=yt(t),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var ar=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function na(){}var sa=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},i0=ra();function a0(r){return globalThis.Buffer!=null?yt(r):i0(r)}var ln=class{len;head;tail;states;constructor(){this.len=0,this.head=new ar(na,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new ar(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ia((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(fo,10,Kt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Kt.fromBigInt(t);return this._push(fo,e.length(),e)}uint64Number(t){return this._push(Mi,ct(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=Kt.fromBigInt(t).zzEncode();return this._push(fo,e.length(),e)}sint64Number(t){let e=Kt.fromNumber(t).zzEncode();return this._push(fo,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(oa,1,t?1:0)}fixed32(t){return this._push(cn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Kt.fromBigInt(t);return this._push(cn,4,e.lo)._push(cn,4,e.hi)}fixed64Number(t){let e=Kt.fromNumber(t);return this._push(cn,4,e.lo)._push(cn,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(Sl,4,t)}double(t){return this._push(Il,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(oa,1,0):this.uint32(e)._push(l0,e,t)}string(t){let e=Nl(t);return e!==0?this.uint32(e)._push(Ki,e,t):this._push(oa,1,0)}fork(){return this.states=new sa(this),this.head=this.tail=new ar(na,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 ar(na,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=a0(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function oa(r,t,e){t[e]=r&255}function c0(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ia=class extends ar{next;constructor(t,e){super(c0,t,e),this.next=void 0}};function fo(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 cn(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 l0(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(ln.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(u0,t,r),this},ln.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(f0,t,r),this});function u0(r,t,e){t.set(r,e)}function f0(r,t,e){r.length<40?Ki(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Q(r),e)}function aa(){return new ln}function ee(r,t){let e=aa();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Tr;(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"})(Tr||(Tr={}));function ho(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function cr(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 ho("enum",Tr.VARINT,e,n)}function re(r,t){return ho("message",Tr.LENGTH_DELIMITED,r,t)}var wt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(wt||(wt={}));var ca;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(ca||(ca={}));(function(r){r.codec=()=>cr(ca)})(wt||(wt={}));var ae;(function(r){let t;r.codec=()=>(t==null&&(t=re((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),wt.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=wt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>ee(e,r.codec()),r.decode=(e,n)=>te(e,r.codec(),n)})(ae||(ae={}));var la;(function(r){let t;r.codec=()=>(t==null&&(t=re((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),wt.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=wt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>ee(e,r.codec()),r.decode=(e,n)=>te(e,r.codec(),n)})(la||(la={}));var bn={};It(bn,{MAX_RSA_KEY_SIZE:()=>os,generateRSAKeyPair:()=>Uu,jwkToJWKKeyPair:()=>Pu,jwkToPkcs1:()=>I0,jwkToPkix:()=>wa,jwkToRSAPrivateKey:()=>Ru,pkcs1ToJwk:()=>Nu,pkcs1ToRSAPrivateKey:()=>_u,pkixToJwk:()=>Lu,pkixToRSAPublicKey:()=>ba});var h0=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]),$e=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),We=new Uint32Array(64),ua=class extends Sr{constructor(){super(64,32,8,!1),this.A=$e[0]|0,this.B=$e[1]|0,this.C=$e[2]|0,this.D=$e[3]|0,this.E=$e[4]|0,this.F=$e[5]|0,this.G=$e[6]|0,this.H=$e[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)We[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=We[f-15],m=We[f-2],y=jt(d,7)^jt(d,18)^d>>>3,g=jt(m,17)^jt(m,19)^m>>>10;We[f]=g+We[f-7]+y+We[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=jt(a,6)^jt(a,11)^jt(a,25),m=u+d+rl(a,c,l)+h0[f]+We[f]|0,g=(jt(n,2)^jt(n,13)^jt(n,22))+nl(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(){We.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ce=Yn(()=>new ua);var G=$h(Hl());function lr(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 qe(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 go(...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 ha(){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=lr(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,lr(s,8)-n}function Fl(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=qe(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=qe(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 Vl(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 Ht(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 bb=Math.log(2);function yo(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function da(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 Ie(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 fn=class{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return da(this.items)}},un=[new Uint8Array([1])],Kl="0123456789";var Ur="",ne=new ArrayBuffer(0),pa=new Uint8Array(0),hn="EndOfContent",Wl="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):pa}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(!Ie(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",ne)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:G.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var Be=class{constructor({blockLength:t=0,error:e=Ur,warnings:n=[],valueBeforeDecode:o=pa}={}){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)}}};Be.NAME="baseBlock";var Lt=class extends Be{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'")}};Lt.NAME="valueBlock";var wo=class extends ke(Be){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):pa,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",ne}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=qe(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(!Ie(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=lr(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}}};wo.NAME="identificationBlock";var bo=class extends Be{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(!Ie(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=lr(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=qe(this.length,8);if(o.byteLength>127)return this.error="Too big length",ne;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}}};bo.NAME="lengthBlock";var P={},At=class extends Be{constructor({name:t=Ur,optional:e=!1,primitiveSchema:n,...o}={},s){super(o),this.name=t,this.optional=e,n&&(this.primitiveSchema=n),this.idBlock=new wo(o),this.lenBlock=new bo(o),this.valueBlock=s?new s(o):new Lt(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 fn;e||Gl(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?ne: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 Vl(e,n)}};At.NAME="BaseBlock";function Gl(r){if(r instanceof P.Constructed)for(let t of r.valueBlock.value)Gl(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var xo=class extends At{constructor({value:t=Ur,...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}'`}};xo.NAME="BaseStringBlock";var vo=class extends ke(Lt){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};vo.NAME="PrimitiveValueBlock";var zl,Eo=class extends At{constructor(t={}){super(t,vo),this.idBlock.isConstructed=!1}};zl=Eo;P.Primitive=zl;Eo.NAME="PRIMITIVE";function v0(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 rs(r,t=0,e=r.length){let n=t,o=new At({},Lt),s=new Be;if(!Ie(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=At;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=v0(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 ma(r){if(!r.byteLength){let t=new At({},Lt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return rs(G.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function E0(r,t){return r?1:t}var le=class extends Lt{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(!Ie(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(;E0(this.isIndefiniteForm,n)>0;){let i=rs(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===hn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===hn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(t,e){let n=e||new fn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(t,n);return e?ne:n.final()}toJSON(){let t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let e of this.value)t.value.push(e.toJSON());return t}};le.NAME="ConstructedValueBlock";var jl,Ge=class extends At{constructor(t={}){super(t,le),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 Gn=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),Ct=(r,t)=>{for(var e in t)Gn(r,e,{get:t[e],enumerable:!0})},zc=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Yh(t))!Qh.call(r,o)&&o!==e&&Gn(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)):{},zc(t||!r||!r.__esModule?Gn(e,"default",{value:r,enumerable:!0}):e,r)),rd=r=>zc(Gn({},"__esModule",{value:!0}),r);var Zl=td(Nr=>{"use strict";var B0="[object ArrayBuffer]",Ae=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===B0}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}},xa="string",I0=/^[0-9a-f\s]+$/i,C0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,k0=/^[a-zA-Z0-9-_]+$/,wo=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=Ae.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=Ae.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}},bo=class r{static isHex(t){return typeof t===xa&&I0.test(t)}static isBase64(t){return typeof t===xa&&C0.test(t)}static isBase64Url(t){return typeof t===xa&&k0.test(t)}static ToString(t,e="utf8"){let n=Ae.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=Ae.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 wo.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 wo.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=Ae.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=Ae.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,"")||""}};bo.DEFAULT_UTF8_ENCODING="utf8";function T0(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 L0(...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 N0(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}Nr.BufferSourceConverter=Ae;Nr.Convert=bo;Nr.assign=T0;Nr.combine=L0;Nr.isEqual=N0});var _g={};Ct(_g,{webRTC:()=>Ng,webRTCDirect:()=>Lg});var fi=Symbol.for("@libp2p/peer-id");var Wn=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 qn=class extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}};var ot=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},yr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var zn=class extends Error{static name="ConnectionFailedError";constructor(t="Connection failed"){super(t),this.name="ConnectionFailedError"}};var jn=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}},Ye=class extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}};var Zn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var Xn=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var Yn=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}};var Je=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var wr=class extends EventTarget{#t=new Map;constructor(){super()}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 br=Symbol.for("@libp2p/service-capabilities"),Zc=Symbol.for("@libp2p/service-dependencies");var gi={};Ct(gi,{base58btc:()=>st,base58flickr:()=>cd});var iy=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 pe(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(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var g=0,h=0,b=0,x=y.length;b!==x&&y[b]===0;)b++,g++;for(var p=(x-b)*u+1>>>0,B=new Uint8Array(p);b!==x;){for(var N=y[b],L=0,S=p-1;(N!==0||L<h)&&S!==-1;S--,L++)N+=256*B[S]>>>0,B[S]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");h=L,b++}for(var T=p-h;T!==p&&B[T]===0;)T++;for(var C=c.repeat(g);T<p;++T)C+=r.charAt(B[T]);return C}function d(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var g=0;if(y[g]!==" "){for(var h=0,b=0;y[g]===c;)h++,g++;for(var x=(y.length-g)*l+1>>>0,p=new Uint8Array(x);y[g];){var B=e[y.charCodeAt(g)];if(B===255)return;for(var N=0,L=x-1;(B!==0||N<b)&&L!==-1;L--,N++)B+=a*p[L]>>>0,p[L]=B%256>>>0,B=B/256>>>0;if(B!==0)throw new Error("Non-zero carry");b=N,g++}if(y[g]!==" "){for(var S=x-b;S!==x&&p[S]===0;)S++;for(var T=new Uint8Array(h+(x-S)),C=h;S!==x;)T[C++]=p[S++];return T}}}function m(y){var g=d(y);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 hi=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")}},di=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)}},pi=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 pi({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var mi=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 hi(t,e,n),this.decoder=new di(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function xr({name:r,prefix:t,encode:e,decode:n}){return new mi(r,t,e,n)}function Ue({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=tl(e,r);return xr({prefix:t,name:r,encode:n,decode:s=>pe(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 dt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return xr({prefix:t,name:r,encode(o){return ad(o,n,e)},decode(o){return id(o,n,e,r)}})}var st=Ue({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),cd=Ue({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var yi={};Ct(yi,{base32:()=>me,base32hex:()=>hd,base32hexpad:()=>pd,base32hexpadupper:()=>md,base32hexupper:()=>dd,base32pad:()=>ud,base32padupper:()=>fd,base32upper:()=>ld,base32z:()=>gd});var me=dt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ld=dt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ud=dt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),fd=dt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),hd=dt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),dd=dt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),pd=dt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),md=dt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),gd=dt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var wi={};Ct(wi,{base36:()=>Xr,base36upper:()=>yd});var Xr=Ue({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),yd=Ue({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Wt={};Ct(Wt,{Digest:()=>Qe,create:()=>kt,decode:()=>De,equals:()=>xi,hasCode:()=>Pd});var wd=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=bi,Ad=128,nl=127;function bi(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw bi.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>=Ad);return bi.bytes=s-n,e}var Sd=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),Ld=Math.pow(2,49),Nd=Math.pow(2,56),_d=Math.pow(2,63),Rd=function(r){return r<Sd?1:r<Bd?2:r<Id?3:r<Cd?4:r<kd?5:r<Td?6:r<Ld?7:r<Nd?8:r<_d?9:10},Ud={encode:wd,decode:vd,encodingLength:Rd},Dd=Ud,Yr=Dd;function Jr(r,t=0){return[Yr.decode(r,t),Yr.decode.bytes]}function Er(r,t,e=0){return Yr.encode(r,t,e),t}function vr(r){return Yr.encodingLength(r)}function kt(r,t){let e=t.byteLength,n=vr(r),o=n+vr(e),s=new Uint8Array(o+e);return Er(r,s,0),Er(e,s,n),s.set(t,o),new Qe(r,e,t,s)}function De(r){let t=pe(r),[e,n]=Jr(t),[o,s]=Jr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Qe(e,o,i,t)}function xi(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 Qe=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 Md(e,Ei(r),t??st.encoder);default:return Hd(e,Ei(r),t??me.encoder)}}var il=new WeakMap;function Ei(r){let t=il.get(r);if(t==null){let e=new Map;return il.set(r,e),e}return t}var Et=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!==Qr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Fd)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=kt(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&&xi(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[Vd]===!0){let{version:n,multihash:o,code:s}=e,i=De(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!==Qr)throw new Error(`Version 0 CID must use dag-pb (code: ${Qr}) 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,Qr,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=pe(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 Qe(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]=Jr(t.subarray(e));return e+=d,f},o=n(),s=Qr;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 Ei(s).set(n,t),s}};function Od(r,t){switch(r[0]){case"Q":{let e=t??st;return[st.prefix,e.decode(`${st.prefix}${r}`)]}case st.prefix:{let e=t??st;return[st.prefix,e.decode(r)]}case me.prefix:{let e=t??me;return[me.prefix,e.decode(r)]}case Xr.prefix:{let e=t??Xr;return[Xr.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 Md(r,t,e){let{prefix:n}=e;if(n!==st.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 Hd(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 Qr=112,Fd=18;function al(r,t,e){let n=vr(r),o=n+vr(t),s=new Uint8Array(o+e.byteLength);return Er(r,s,0),Er(t,s,n),s.set(e,o),s}var Vd=Symbol.for("@ipld/js-cid/CID");var vi={};Ct(vi,{identity:()=>ge});var cl=0,Kd="identity",ll=pe;function $d(r){return kt(cl,ll(r))}var ge={code:cl,name:Kd,encode:ll,digest:$d};function Ut(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 Qn(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Gd(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ar(r,...t){if(!Gd(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function tn(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Qn(r.outputLen),Qn(r.blockLen)}function Sr(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){Ar(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}var tr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function to(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Xt(r,t){return r<<32-t|r>>>t}function fl(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function Pe(r){return typeof r=="string"&&(r=fl(r)),Ar(r),r}function Ai(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Ar(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 Br=class{clone(){return this._cloneInto()}};function eo(r){let t=n=>r().update(Pe(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function en(r=32){if(tr&&typeof tr.getRandomValues=="function")return tr.getRandomValues(new Uint8Array(r));if(tr&&typeof tr.randomBytes=="function")return tr.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function Wd(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 hl(r,t,e){return r&t^~r&e}function dl(r,t,e){return r&t^r&e^t&e}var Ir=class extends Br{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=to(this.buffer)}update(t){Sr(this);let{view:e,buffer:n,blockLen:o}=this;t=Pe(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=to(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){Sr(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;Wd(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=to(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 ro=BigInt(4294967295),Si=BigInt(32);function pl(r,t=!1){return t?{h:Number(r&ro),l:Number(r>>Si&ro)}:{h:Number(r>>Si&ro)|0,l:Number(r&ro)|0}}function qd(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 zd=(r,t)=>BigInt(r>>>0)<<Si|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:qd,toBig:zd,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},$=dp;var[pp,mp]=$.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))),Oe=new Uint32Array(80),Me=new Uint32Array(80),Bi=class extends Ir{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:y,Hh:g,Hl:h}=this;return[t,e,n,o,s,i,a,c,l,u,f,d,m,y,g,h]}set(t,e,n,o,s,i,a,c,l,u,f,d,m,y,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=y|0,this.Hh=g|0,this.Hl=h|0}process(t,e){for(let p=0;p<16;p++,e+=4)Oe[p]=t.getUint32(e),Me[p]=t.getUint32(e+=4);for(let p=16;p<80;p++){let B=Oe[p-15]|0,N=Me[p-15]|0,L=$.rotrSH(B,N,1)^$.rotrSH(B,N,8)^$.shrSH(B,N,7),S=$.rotrSL(B,N,1)^$.rotrSL(B,N,8)^$.shrSL(B,N,7),T=Oe[p-2]|0,C=Me[p-2]|0,H=$.rotrSH(T,C,19)^$.rotrBH(T,C,61)^$.shrSH(T,C,6),U=$.rotrSL(T,C,19)^$.rotrBL(T,C,61)^$.shrSL(T,C,6),M=$.add4L(S,U,Me[p-7],Me[p-16]),V=$.add4H(M,L,H,Oe[p-7],Oe[p-16]);Oe[p]=V|0,Me[p]=M|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:y,Gh:g,Gl:h,Hh:b,Hl:x}=this;for(let p=0;p<80;p++){let B=$.rotrSH(f,d,14)^$.rotrSH(f,d,18)^$.rotrBH(f,d,41),N=$.rotrSL(f,d,14)^$.rotrSL(f,d,18)^$.rotrBL(f,d,41),L=f&m^~f&g,S=d&y^~d&h,T=$.add5L(x,N,S,mp[p],Me[p]),C=$.add5H(T,b,B,L,pp[p],Oe[p]),H=T|0,U=$.rotrSH(n,o,28)^$.rotrBH(n,o,34)^$.rotrBH(n,o,39),M=$.rotrSL(n,o,28)^$.rotrBL(n,o,34)^$.rotrBL(n,o,39),V=n&s^n&a^s&a,I=o&i^o&c^i&c;b=g|0,x=h|0,g=m|0,h=y|0,m=f|0,y=d|0,{h:f,l:d}=$.add(l|0,u|0,C|0,H|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let k=$.add3L(H,M,I);n=$.add3H(k,C,U,V),o=k|0}({h:n,l:o}=$.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=$.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=$.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=$.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=$.add(this.Eh|0,this.El|0,f|0,d|0),{h:m,l:y}=$.add(this.Fh|0,this.Fl|0,m|0,y|0),{h:g,l:h}=$.add(this.Gh|0,this.Gl|0,g|0,h|0),{h:b,l:x}=$.add(this.Hh|0,this.Hl|0,b|0,x|0),this.set(n,o,s,i,a,c,l,u,f,d,m,y,g,h,b,x)}roundClean(){Oe.fill(0),Me.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=eo(()=>new Bi);var so={};Ct(so,{aInRange:()=>vt,abool:()=>Yt,abytes:()=>Cr,bitGet:()=>Ep,bitLen:()=>Ti,bitMask:()=>nn,bitSet:()=>vp,bytesToHex:()=>we,bytesToNumberBE:()=>be,bytesToNumberLE:()=>Jt,concatBytes:()=>Ee,createHmacDrbg:()=>Li,ensureBytes:()=>it,equalBytes:()=>bp,hexToBytes:()=>rr,hexToNumber:()=>ki,inRange:()=>rn,isBytes:()=>He,memoized:()=>nr,notImplemented:()=>Sp,numberToBytesBE:()=>Fe,numberToBytesLE:()=>xe,numberToHexUnpadded:()=>er,numberToVarBytesBE:()=>wp,utf8ToBytes:()=>xp,validateObject:()=>qt});var no=BigInt(0),oo=BigInt(1),gp=BigInt(2);function He(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Cr(r){if(!He(r))throw new Error("Uint8Array expected")}function Yt(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}var yp=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function we(r){Cr(r);let t="";for(let e=0;e<r.length;e++)t+=yp[r[e]];return t}function er(r){let t=r.toString(16);return t.length&1?"0"+t:t}function ki(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?no:BigInt("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 rr(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("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 be(r){return ki(we(r))}function Jt(r){return Cr(r),ki(we(Uint8Array.from(r).reverse()))}function Fe(r,t){return rr(r.toString(16).padStart(t*2,"0"))}function xe(r,t){return Fe(r,t).reverse()}function wp(r){return rr(er(r))}function it(r,t,e){let n;if(typeof t=="string")try{n=rr(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(He(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+" of length "+e+" expected, got "+o);return n}function Ee(...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}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("string expected");return new Uint8Array(new TextEncoder().encode(r))}var Ii=r=>typeof r=="bigint"&&no<=r;function rn(r,t,e){return Ii(r)&&Ii(t)&&Ii(e)&&t<=r&&r<e}function vt(r,t,e,n){if(!rn(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Ti(r){let t;for(t=0;r>no;r>>=oo,t+=1);return t}function Ep(r,t){return r>>BigInt(t)&oo}function vp(r,t,e){return r|(e?oo:no)<<BigInt(t)}var nn=r=>(gp<<BigInt(r-1))-oo,Ci=r=>new Uint8Array(r),yl=r=>Uint8Array.from(r);function Li(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=Ci(r),o=Ci(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=Ci())=>{o=a(yl([0]),f),n=a(),f.length!==0&&(o=a(yl([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 Ee(...d)};return(f,d)=>{i(),c(f);let m;for(;!(m=d(l()));)c();return i(),m}}var Ap={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"||He(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 qt(r,t,e={}){let n=(o,s,i)=>{let a=Ap[s];if(typeof a!="function")throw new Error("invalid validator function");let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};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 Sp=()=>{throw new Error("not implemented")};function nr(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 gt=BigInt(0),ht=BigInt(1),or=BigInt(2),Bp=BigInt(3),Ni=BigInt(4),wl=BigInt(5),bl=BigInt(8),Ip=BigInt(9),Cp=BigInt(16);function Z(r,t){let e=r%t;return e>=gt?e:t+e}function _i(r,t,e){if(t<gt)throw new Error("invalid exponent, negatives unsupported");if(e<=gt)throw new Error("invalid modulus");if(e===ht)return gt;let n=ht;for(;t>gt;)t&ht&&(n=n*r%e),r=r*r%e,t>>=ht;return n}function lt(r,t,e){let n=r;for(;t-- >gt;)n*=n,n%=e;return n}function io(r,t){if(r===gt)throw new Error("invert: expected non-zero number");if(t<=gt)throw new Error("invert: expected positive modulus, got "+t);let e=Z(r,t),n=t,o=gt,s=ht,i=ht,a=gt;for(;e!==gt;){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 Z(o,t)}function kp(r){let t=(r-ht)/or,e,n,o;for(e=r-ht,n=0;e%or===gt;e/=or,n++);for(o=or;o<r&&_i(o,t,r)!==r-ht;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(r+ht)/Ni;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)/or;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 y=a.pow(u,ht<<BigInt(l-m-1));u=a.sqr(y),f=a.mul(f,y),d=a.mul(d,u),l=m}return f}}function Tp(r){if(r%Ni===Bp){let t=(r+ht)/Ni;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===wl){let t=(r-wl)/bl;return function(n,o){let s=n.mul(o,or),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,or),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)=>(Z(r,t)&ht)===ht,Lp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ri(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Lp.reduce((n,o)=>(n[o]="function",n),t);return qt(r,e)}function Np(r,t,e){if(e<gt)throw new Error("invalid exponent, negatives unsupported");if(e===gt)return r.ONE;if(e===ht)return t;let n=r.ONE,o=t;for(;e>gt;)e&ht&&(n=r.mul(n,o)),o=r.sqr(o),e>>=ht;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 Ui(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Ve(r,t,e=!1,n={}){if(r<=gt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=Ui(r,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:r,isLE:e,BITS:o,BYTES:s,MASK:nn(o),ZERO:gt,ONE:ht,create:c=>Z(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return gt<=c&&c<r},is0:c=>c===gt,isOdd:c=>(c&ht)===ht,neg:c=>Z(-c,r),eql:(c,l)=>c===l,sqr:c=>Z(c*c,r),add:(c,l)=>Z(c+l,r),sub:(c,l)=>Z(c-l,r),mul:(c,l)=>Z(c*l,r),pow:(c,l)=>Np(a,c,l),div:(c,l)=>Z(c*io(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>io(c,r),sqrt:n.sqrt||(c=>(i||(i=Tp(r)),i(a,c))),invertBatch:c=>_p(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?xe(c,s):Fe(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return e?Jt(c):be(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 Di(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=Di(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?Jt(r):be(r),a=Z(i,t-ht)+ht;return e?xe(a,o):Fe(a,o)}var Al=BigInt(0),ao=BigInt(1);function Pi(r,t){let e=t.negate();return r?e:t}function Sl(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Oi(r,t){Sl(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1);return{windows:e,windowSize:n}}function Rp(r,t){if(!Array.isArray(r))throw new Error("array expected");r.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}function Up(r,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}var Mi=new WeakMap,Bl=new WeakMap;function Hi(r){return Bl.get(r)||1}function co(r,t){return{constTimeNegate:Pi,hasPrecomputes(e){return Hi(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>Al;)n&ao&&(o=o.add(s)),s=s.double(),n>>=ao;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=Oi(n,t),i=[],a=e,c=a;for(let l=0;l<o;l++){c=a,i.push(c);for(let u=1;u<s;u++)c=c.add(a),i.push(c);a=c.double()}return i},wNAF(e,n,o){let{windows:s,windowSize:i}=Oi(e,t),a=r.ZERO,c=r.BASE,l=BigInt(2**e-1),u=2**e,f=BigInt(e);for(let d=0;d<s;d++){let m=d*i,y=Number(o&l);o>>=f,y>i&&(y-=u,o+=ao);let g=m,h=m+Math.abs(y)-1,b=d%2!==0,x=y<0;y===0?c=c.add(Pi(b,n[g])):a=a.add(Pi(x,n[h]))}return{p:a,f:c}},wNAFUnsafe(e,n,o,s=r.ZERO){let{windows:i,windowSize:a}=Oi(e,t),c=BigInt(2**e-1),l=2**e,u=BigInt(e);for(let f=0;f<i;f++){let d=f*a;if(o===Al)break;let m=Number(o&c);if(o>>=u,m>a&&(m-=l,o+=ao),m===0)continue;let y=n[d+Math.abs(m)-1];m<0&&(y=y.negate()),s=s.add(y)}return s},getPrecomputes(e,n,o){let s=Mi.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&Mi.set(n,o(s))),s},wNAFCached(e,n,o){let s=Hi(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=Hi(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){Sl(n,t),Bl.set(e,n),Mi.delete(e)}}}function lo(r,t,e,n){if(Rp(e,r),Up(n,t),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,s=Ti(BigInt(e.length)),i=s>12?s-3:s>4?s-2:s?2:1,a=(1<<i)-1,c=new Array(a+1).fill(o),l=Math.floor((t.BITS-1)/i)*i,u=o;for(let f=l;f>=0;f-=i){c.fill(o);for(let m=0;m<n.length;m++){let y=n[m],g=Number(y>>BigInt(f)&BigInt(a));c[g]=c[g].add(e[m])}let d=o;for(let m=c.length-1,y=o;m>0;m--)y=y.add(c[m]),d=d.add(y);if(u=u.add(d),f!==0)for(let m=0;m<i;m++)u=u.double()}return u}function on(r){return Ri(r.Fp),qt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ui(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Qt=BigInt(0),Mt=BigInt(1),uo=BigInt(2),Dp=BigInt(8),Pp={zip215:!0};function Op(r){let t=on(r);return qt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Il(r){let t=Op(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=uo<<BigInt(a*8)-Mt,u=e.create,f=Ve(t.n,t.nBitLength),d=t.uvRatio||((E,w)=>{try{return{isValid:!0,value:e.sqrt(E*e.inv(w))}}catch{return{isValid:!1,value:Qt}}}),m=t.adjustScalarBytes||(E=>E),y=t.domain||((E,w,A)=>{if(Yt("phflag",A),w.length||A)throw new Error("Contexts/pre-hash are not supported");return E});function g(E,w){vt("coordinate "+E,w,Qt,l)}function h(E){if(!(E instanceof p))throw new Error("ExtendedPoint expected")}let b=nr((E,w)=>{let{ex:A,ey:v,ez:_}=E,R=E.is0();w==null&&(w=R?Dp:e.inv(_));let O=u(A*w),K=u(v*w),F=u(_*w);if(R)return{x:Qt,y:Mt};if(F!==Mt)throw new Error("invZ was invalid");return{x:O,y:K}}),x=nr(E=>{let{a:w,d:A}=t;if(E.is0())throw new Error("bad point: ZERO");let{ex:v,ey:_,ez:R,et:O}=E,K=u(v*v),F=u(_*_),G=u(R*R),j=u(G*G),at=u(K*w),ct=u(G*u(at+F)),ft=u(j+u(A*u(K*F)));if(ct!==ft)throw new Error("bad point: equation left != right (1)");let It=u(v*_),Ot=u(R*O);if(It!==Ot)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(w,A,v,_){this.ex=w,this.ey=A,this.ez=v,this.et=_,g("x",w),g("y",A),g("z",v),g("t",_),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(w){if(w instanceof p)throw new Error("extended point not allowed");let{x:A,y:v}=w||{};return g("x",A),g("y",v),new p(A,v,Mt,u(A*v))}static normalizeZ(w){let A=e.invertBatch(w.map(v=>v.ez));return w.map((v,_)=>v.toAffine(A[_])).map(p.fromAffine)}static msm(w,A){return lo(p,f,w,A)}_setWindowSize(w){L.setWindowSize(this,w)}assertValidity(){x(this)}equals(w){h(w);let{ex:A,ey:v,ez:_}=this,{ex:R,ey:O,ez:K}=w,F=u(A*K),G=u(R*_),j=u(v*K),at=u(O*_);return F===G&&j===at}is0(){return this.equals(p.ZERO)}negate(){return new p(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:w}=t,{ex:A,ey:v,ez:_}=this,R=u(A*A),O=u(v*v),K=u(uo*u(_*_)),F=u(w*R),G=A+v,j=u(u(G*G)-R-O),at=F+O,ct=at-K,ft=F-O,It=u(j*ct),Ot=u(at*ft),Rt=u(j*ft),ie=u(ct*at);return new p(It,Ot,ie,Rt)}add(w){h(w);let{a:A,d:v}=t,{ex:_,ey:R,ez:O,et:K}=this,{ex:F,ey:G,ez:j,et:at}=w;if(A===BigInt(-1)){let Fc=u((R-_)*(G+F)),Vc=u((R+_)*(G-F)),ui=u(Vc-Fc);if(ui===Qt)return this.double();let Kc=u(O*uo*at),$c=u(K*uo*j),Gc=$c+Kc,Wc=Vc+Fc,qc=$c-Kc,Wh=u(Gc*ui),qh=u(Wc*qc),zh=u(Gc*qc),jh=u(ui*Wc);return new p(Wh,qh,jh,zh)}let ct=u(_*F),ft=u(R*G),It=u(K*v*at),Ot=u(O*j),Rt=u((_+R)*(F+G)-ct-ft),ie=Ot-It,de=Ot+It,Zr=u(ft-A*ct),Vh=u(Rt*ie),Kh=u(de*Zr),$h=u(Rt*Zr),Gh=u(ie*de);return new p(Vh,Kh,Gh,$h)}subtract(w){return this.add(w.negate())}wNAF(w){return L.wNAFCached(this,w,p.normalizeZ)}multiply(w){let A=w;vt("scalar",A,Mt,n);let{p:v,f:_}=this.wNAF(A);return p.normalizeZ([v,_])[0]}multiplyUnsafe(w,A=p.ZERO){let v=w;return vt("scalar",v,Qt,n),v===Qt?N:this.is0()||v===Mt?this:L.wNAFCachedUnsafe(this,v,p.normalizeZ,A)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return L.unsafeLadder(this,n).is0()}toAffine(w){return b(this,w)}clearCofactor(){let{h:w}=t;return w===Mt?this:this.multiplyUnsafe(w)}static fromHex(w,A=!1){let{d:v,a:_}=t,R=e.BYTES;w=it("pointHex",w,R),Yt("zip215",A);let O=w.slice(),K=w[R-1];O[R-1]=K&-129;let F=Jt(O),G=A?l:e.ORDER;vt("pointHex.y",F,Qt,G);let j=u(F*F),at=u(j-Mt),ct=u(v*j-_),{isValid:ft,value:It}=d(at,ct);if(!ft)throw new Error("Point.fromHex: invalid y coordinate");let Ot=(It&Mt)===Mt,Rt=(K&128)!==0;if(!A&&It===Qt&&Rt)throw new Error("Point.fromHex: x=0 and x_0=1");return Rt!==Ot&&(It=u(-It)),p.fromAffine({x:It,y:F})}static fromPrivateKey(w){return C(w).point}toRawBytes(){let{x:w,y:A}=this.toAffine(),v=xe(A,e.BYTES);return v[v.length-1]|=w&Mt?128:0,v}toHex(){return we(this.toRawBytes())}}p.BASE=new p(t.Gx,t.Gy,Mt,u(t.Gx*t.Gy)),p.ZERO=new p(Qt,Mt,Mt,Qt);let{BASE:B,ZERO:N}=p,L=co(p,a*8);function S(E){return Z(E,n)}function T(E){return S(Jt(E))}function C(E){let w=e.BYTES;E=it("private key",E,w);let A=it("hashed private key",s(E),2*w),v=m(A.slice(0,w)),_=A.slice(w,2*w),R=T(v),O=B.multiply(R),K=O.toRawBytes();return{head:v,prefix:_,scalar:R,point:O,pointBytes:K}}function H(E){return C(E).pointBytes}function U(E=new Uint8Array,...w){let A=Ee(...w);return T(s(y(A,it("context",E),!!o)))}function M(E,w,A={}){E=it("message",E),o&&(E=o(E));let{prefix:v,scalar:_,pointBytes:R}=C(w),O=U(A.context,v,E),K=B.multiply(O).toRawBytes(),F=U(A.context,K,R,E),G=S(O+F*_);vt("signature.s",G,Qt,n);let j=Ee(K,xe(G,e.BYTES));return it("result",j,e.BYTES*2)}let V=Pp;function I(E,w,A,v=V){let{context:_,zip215:R}=v,O=e.BYTES;E=it("signature",E,2*O),w=it("message",w),A=it("publicKey",A,O),R!==void 0&&Yt("zip215",R),o&&(w=o(w));let K=Jt(E.slice(O,2*O)),F,G,j;try{F=p.fromHex(A,R),G=p.fromHex(E.slice(0,O),R),j=B.multiplyUnsafe(K)}catch{return!1}if(!R&&F.isSmallOrder())return!1;let at=U(_,G.toRawBytes(),F.toRawBytes(),w);return G.add(F.multiplyUnsafe(at)).subtract(j).clearCofactor().equals(p.ZERO)}return B._setWindowSize(8),{CURVE:t,getPublicKey:H,sign:M,verify:I,ExtendedPoint:p,utils:{getExtendedPublicKey:C,randomPrivateKey:()=>i(e.BYTES),precompute(E=8,w=p.BASE){return w._setWindowSize(E),w.multiply(BigInt(3)),w}}}}var kr=BigInt(0),Fi=BigInt(1);function Mp(r){return qt(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function Cl(r){let t=Mp(r),{P:e}=t,n=x=>Z(x,e),o=t.montgomeryBits,s=Math.ceil(o/8),i=t.nByteLength,a=t.adjustScalarBytes||(x=>x),c=t.powPminus2||(x=>_i(x,e-BigInt(2),e));function l(x,p,B){let N=n(x*(p-B));return p=n(p-N),B=n(B+N),[p,B]}let u=(t.a-BigInt(2))/BigInt(4);function f(x,p){vt("u",x,kr,e),vt("scalar",p,kr,e);let B=p,N=x,L=Fi,S=kr,T=x,C=Fi,H=kr,U;for(let V=BigInt(o-1);V>=kr;V--){let I=B>>V&Fi;H^=I,U=l(H,L,T),L=U[0],T=U[1],U=l(H,S,C),S=U[0],C=U[1],H=I;let k=L+S,E=n(k*k),w=L-S,A=n(w*w),v=E-A,_=T+C,R=T-C,O=n(R*k),K=n(_*w),F=O+K,G=O-K;T=n(F*F),C=n(N*n(G*G)),L=n(E*A),S=n(v*(E+n(u*v)))}U=l(H,L,T),L=U[0],T=U[1],U=l(H,S,C),S=U[0],C=U[1];let M=c(S);return n(L*M)}function d(x){return xe(n(x),s)}function m(x){let p=it("u coordinate",x,s);return i===32&&(p[31]&=127),Jt(p)}function y(x){let p=it("scalar",x),B=p.length;if(B!==s&&B!==i){let N=""+s+" or "+i;throw new Error("invalid scalar, expected "+N+" bytes, got "+B)}return Jt(a(p))}function g(x,p){let B=m(p),N=y(x),L=f(B,N);if(L===kr)throw new Error("invalid private or public key received");return d(L)}let h=d(t.Gu);function b(x){return g(x,h)}return{scalarMult:g,scalarMultBase:b,getSharedSecret:(x,p)=>g(x,p),getPublicKey:x=>b(x),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:h}}var sn=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),kl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),rw=BigInt(0),Hp=BigInt(1),Tl=BigInt(2),Fp=BigInt(3),Vp=BigInt(5),Kp=BigInt(8);function Ll(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=sn,a=r*r%s*r%s,c=lt(a,Tl,s)*a%s,l=lt(c,Hp,s)*r%s,u=lt(l,Vp,s)*l%s,f=lt(u,t,s)*u%s,d=lt(f,e,s)*f%s,m=lt(d,n,s)*d%s,y=lt(m,o,s)*m%s,g=lt(y,o,s)*m%s,h=lt(g,t,s)*u%s;return{pow_p_5_8:lt(h,Tl,s)*r%s,b2:a}}function Nl(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function $p(r,t){let e=sn,n=Z(t*t*t,e),o=Z(n*n*t,e),s=Ll(r*o).pow_p_5_8,i=Z(r*n*s,e),a=Z(t*i*i,e),c=i,l=Z(i*kl,e),u=a===r,f=a===Z(-r,e),d=a===Z(-r*kl,e);return u&&(i=c),(f||d)&&(i=l),xl(i,e)&&(i=Z(-i,e)),{isValid:u||f,value:i}}var Gp=Ve(sn,void 0,!0),Wp={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Gp,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Kp,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:ml,randomBytes:en,adjustScalarBytes:Nl,uvRatio:$p},_l=Il(Wp);var an=Cl({P:sn,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let t=sn,{pow_p_5_8:e,b2:n}=Ll(r);return Z(lt(e,Fp,t)*n,t)},adjustScalarBytes:Nl,randomBytes:en});var fo=32;function Rl(r,t,e){return _l.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}var ho=class{type="Ed25519";raw;constructor(t){this.raw=Vi(t,fo)}toMultihash(){return ge.digest(Tr(this))}toCID(){return Et.createV1(114,this.toMultihash())}toString(){return st.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Ut(this.raw,t.raw)}verify(t,e){return Rl(this.raw,e,t)}};function Ki(r){return r=Vi(r,fo),new ho(r)}function Vi(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new ot(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}function yt(r=0){return new Uint8Array(r)}function mt(r=0){return new Uint8Array(r)}var zp=Math.pow(2,7),jp=Math.pow(2,14),Zp=Math.pow(2,21),$i=Math.pow(2,28),Gi=Math.pow(2,35),Wi=Math.pow(2,42),qi=Math.pow(2,49),J=128,Tt=127;function et(r){if(r<zp)return 1;if(r<jp)return 2;if(r<Zp)return 3;if(r<$i)return 4;if(r<Gi)return 5;if(r<Wi)return 6;if(r<qi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function zi(r,t,e=0){switch(et(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(et(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 ji(r,t){let e=r[t],n=0;if(n+=e&Tt,e<J||(e=r[t+1],n+=(e&Tt)<<7,e<J)||(e=r[t+2],n+=(e&Tt)<<14,e<J)||(e=r[t+3],n+=(e&Tt)<<21,e<J)||(e=r[t+4],n+=(e&Tt)*$i,e<J)||(e=r[t+5],n+=(e&Tt)*Gi,e<J)||(e=r[t+6],n+=(e&Tt)*Wi,e<J)||(e=r[t+7],n+=(e&Tt)*qi,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&Tt,e<J||(e=r.get(t+1),n+=(e&Tt)<<7,e<J)||(e=r.get(t+2),n+=(e&Tt)<<14,e<J)||(e=r.get(t+3),n+=(e&Tt)<<21,e<J)||(e=r.get(t+4),n+=(e&Tt)*$i,e<J)||(e=r.get(t+5),n+=(e&Tt)*Gi,e<J)||(e=r.get(t+6),n+=(e&Tt)*Wi,e<J)||(e=r.get(t+7),n+=(e&Tt)*qi,e<J))return n;throw new RangeError("Could not decode varint")}function zt(r,t,e=0){return t==null&&(t=mt(et(r))),t instanceof Uint8Array?zi(r,t,e):Xp(r,t,e)}function Kt(r,t=0){return r instanceof Uint8Array?ji(r,t):Yp(r,t)}var Zi=new Float32Array([-0]),Ke=new Uint8Array(Zi.buffer);function Dl(r,t,e){Zi[0]=r,t[e]=Ke[0],t[e+1]=Ke[1],t[e+2]=Ke[2],t[e+3]=Ke[3]}function Pl(r,t){return Ke[0]=r[t],Ke[1]=r[t+1],Ke[2]=r[t+2],Ke[3]=r[t+3],Zi[0]}var Xi=new Float64Array([-0]),Lt=new Uint8Array(Xi.buffer);function Ol(r,t,e){Xi[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 Ml(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],Xi[0]}var Jp=BigInt(Number.MAX_SAFE_INTEGER),Qp=BigInt(Number.MIN_SAFE_INTEGER),$t=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 ir;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>Hl&&(o=0n,++n>Hl&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return ir;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):ir}},ir=new $t(0,0);ir.toBigInt=function(){return 0n};ir.zzEncode=ir.zzDecode=function(){return this};ir.length=function(){return 1};var Hl=4294967296n;function Fl(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 Vl(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 Yi(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 te(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function po(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Ji=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,te(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 te(this,4);return po(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw te(this,4);return po(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw te(this,4);let t=Pl(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw te(this,4);let t=Ml(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 te(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Vl(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw te(this,t);this.pos+=t}else do if(this.pos>=this.len)throw te(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 $t(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 te(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 te(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 te(this,8);let t=po(this.buf,this.pos+=4),e=po(this.buf,this.pos+=4);return new $t(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=ji(this.buf,this.pos);return this.pos+=et(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 Qi(r){return new Ji(r instanceof Uint8Array?r:r.subarray())}function ee(r,t,e){let n=Qi(r);return t.decode(n,void 0,e)}var ta={};Ct(ta,{base10:()=>t0});var t0=Ue({prefix:"9",name:"base10",alphabet:"0123456789"});var ea={};Ct(ea,{base16:()=>e0,base16upper:()=>r0});var e0=dt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),r0=dt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ra={};Ct(ra,{base2:()=>n0});var n0=dt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var na={};Ct(na,{base256emoji:()=>c0});var $l=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}"),o0=$l.reduce((r,t,e)=>(r[e]=t,r),[]),s0=$l.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function i0(r){return r.reduce((t,e)=>(t+=o0[e],t),"")}function a0(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=s0[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var c0=xr({prefix:"\u{1F680}",name:"base256emoji",encode:i0,decode:a0});var oa={};Ct(oa,{base64:()=>l0,base64pad:()=>u0,base64url:()=>cn,base64urlpad:()=>f0});var l0=dt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),u0=dt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cn=dt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),f0=dt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var sa={};Ct(sa,{base8:()=>h0});var h0=dt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ia={};Ct(ia,{identity:()=>d0});var d0=xr({prefix:"\0",name:"identity",encode:r=>Jc(r),decode:r=>Yc(r)});var Mw=new TextEncoder,Hw=new TextDecoder;var la={};Ct(la,{sha256:()=>ve,sha512:()=>g0});function ca({name:r,code:t,encode:e}){return new aa(r,t,e)}var aa=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?kt(this.code,e):e.then(n=>kt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Wl(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var ve=ca({name:"sha2-256",code:18,encode:Wl("SHA-256")}),g0=ca({name:"sha2-512",code:19,encode:Wl("SHA-512")});var ar={...ia,...ra,...sa,...ta,...ea,...yi,...wi,...gi,...oa,...na},Yw={...la,...vi};function zl(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var ql=zl("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ua=zl("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=mt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),y0={utf8:ql,"utf-8":ql,hex:ar.base16,latin1:ua,ascii:ua,binary:ua,...ar},mo=y0;function Q(r,t="utf8"){let e=mo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function fa(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return mt(i);o+i>t&&(n=mt(t),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var cr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function ha(){}var pa=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},w0=fa();function b0(r){return globalThis.Buffer!=null?mt(r):w0(r)}var un=class{len;head;tail;states;constructor(){this.len=0,this.head=new cr(ha,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new cr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ma((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(go,10,$t.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=$t.fromBigInt(t);return this._push(go,e.length(),e)}uint64Number(t){return this._push(zi,et(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=$t.fromBigInt(t).zzEncode();return this._push(go,e.length(),e)}sint64Number(t){let e=$t.fromNumber(t).zzEncode();return this._push(go,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(da,1,t?1:0)}fixed32(t){return this._push(ln,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=$t.fromBigInt(t);return this._push(ln,4,e.lo)._push(ln,4,e.hi)}fixed64Number(t){let e=$t.fromNumber(t);return this._push(ln,4,e.lo)._push(ln,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(Dl,4,t)}double(t){return this._push(Ol,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(da,1,0):this.uint32(e)._push(E0,e,t)}string(t){let e=Fl(t);return e!==0?this.uint32(e)._push(Yi,e,t):this._push(da,1,0)}fork(){return this.states=new pa(this),this.head=this.tail=new cr(ha,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 cr(ha,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=b0(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function da(r,t,e){t[e]=r&255}function x0(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ma=class extends cr{next;constructor(t,e){super(x0,t,e),this.next=void 0}};function go(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 ln(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 E0(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(un.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(v0,t,r),this},un.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(A0,t,r),this});function v0(r,t,e){t.set(r,e)}function A0(r,t,e){r.length<40?Yi(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Q(r),e)}function ga(){return new un}function re(r,t){let e=ga();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Lr;(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"})(Lr||(Lr={}));function yo(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function lr(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 yo("enum",Lr.VARINT,e,n)}function ne(r,t){return yo("message",Lr.LENGTH_DELIMITED,r,t)}var wt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(wt||(wt={}));var ya;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(ya||(ya={}));(function(r){r.codec=()=>lr(ya)})(wt||(wt={}));var ae;(function(r){let t;r.codec=()=>(t==null&&(t=ne((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),wt.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=wt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>re(e,r.codec()),r.decode=(e,n)=>ee(e,r.codec(),n)})(ae||(ae={}));var wa;(function(r){let t;r.codec=()=>(t==null&&(t=ne((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),wt.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=wt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>re(e,r.codec()),r.decode=(e,n)=>ee(e,r.codec(),n)})(wa||(wa={}));var xn={};Ct(xn,{MAX_RSA_KEY_SIZE:()=>cs,generateRSAKeyPair:()=>Gu,jwkToJWKKeyPair:()=>Wu,jwkToPkcs1:()=>H0,jwkToPkix:()=>Ca,jwkToRSAPrivateKey:()=>$u,pkcs1ToJwk:()=>Fu,pkcs1ToRSAPrivateKey:()=>Ku,pkixToJwk:()=>Vu,pkixToRSAPublicKey:()=>ka});var S0=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]),$e=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ge=new Uint32Array(64),ba=class extends Ir{constructor(){super(64,32,8,!1),this.A=$e[0]|0,this.B=$e[1]|0,this.C=$e[2]|0,this.D=$e[3]|0,this.E=$e[4]|0,this.F=$e[5]|0,this.G=$e[6]|0,this.H=$e[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)Ge[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Ge[f-15],m=Ge[f-2],y=Xt(d,7)^Xt(d,18)^d>>>3,g=Xt(m,17)^Xt(m,19)^m>>>10;Ge[f]=g+Ge[f-7]+y+Ge[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=Xt(a,6)^Xt(a,11)^Xt(a,25),m=u+d+hl(a,c,l)+S0[f]+Ge[f]|0,g=(Xt(n,2)^Xt(n,13)^Xt(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(){Ge.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ce=eo(()=>new ba);var q=ed(Zl());function ur(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 We(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 xo(...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 Ea(){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=ur(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,ur(s,8)-n}function Xl(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=We(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=We(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 Yl(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 Ht(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 Eo(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function va(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 hn=class{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return va(this.items)}},fn=[new Uint8Array([1])],Jl="0123456789";var Dr="",oe=new ArrayBuffer(0),Aa=new Uint8Array(0),dn="EndOfContent",tu="OCTET STRING",eu="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?q.BufferSourceConverter.toUint8Array(s.valueHex):Aa}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",oe)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:q.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var Se=class{constructor({blockLength:t=0,error:e=Dr,warnings:n=[],valueBeforeDecode:o=Aa}={}){this.blockLength=t,this.error=e,this.warnings=n,this.valueBeforeDecodeView=q.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:q.Convert.ToHex(this.valueBeforeDecodeView)}}};Se.NAME="baseBlock";var Nt=class extends Se{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'")}};Nt.NAME="valueBlock";var vo=class extends ke(Se){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?q.BufferSourceConverter.toUint8Array(t.valueHex):Aa,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",oe}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=We(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=q.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=ur(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}}};vo.NAME="identificationBlock";var Ao=class extends Se{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=q.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=ur(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=We(this.length,8);if(o.byteLength>127)return this.error="Too big length",oe;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}}};Ao.NAME="lengthBlock";var D={},At=class extends Se{constructor({name:t=Dr,optional:e=!1,primitiveSchema:n,...o}={},s){super(o),this.name=t,this.optional=e,n&&(this.primitiveSchema=n),this.idBlock=new vo(o),this.lenBlock=new Ao(o),this.valueBlock=s?new s(o):new Nt(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 hn;e||ru(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?oe: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():q.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${q.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 Yl(e,n)}};At.NAME="BaseBlock";function ru(r){if(r instanceof D.Constructed)for(let t of r.valueBlock.value)ru(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var So=class extends At{constructor({value:t=Dr,...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}'`}};So.NAME="BaseStringBlock";var Bo=class extends ke(Nt){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};Bo.NAME="PrimitiveValueBlock";var nu,Io=class extends At{constructor(t={}){super(t,Bo),this.idBlock.isConstructed=!1}};nu=Io;D.Primitive=nu;Io.NAME="PRIMITIVE";function R0(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 is(r,t=0,e=r.length){let n=t,o=new At({},Nt),s=new Se;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=At;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=D.EndOfContent;break;case 1:c=D.Boolean;break;case 2:c=D.Integer;break;case 3:c=D.BitString;break;case 4:c=D.OctetString;break;case 5:c=D.Null;break;case 6:c=D.ObjectIdentifier;break;case 10:c=D.Enumerated;break;case 12:c=D.Utf8String;break;case 13:c=D.RelativeObjectIdentifier;break;case 14:c=D.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=D.Sequence;break;case 17:c=D.Set;break;case 18:c=D.NumericString;break;case 19:c=D.PrintableString;break;case 20:c=D.TeletexString;break;case 21:c=D.VideotexString;break;case 22:c=D.IA5String;break;case 23:c=D.UTCTime;break;case 24:c=D.GeneralizedTime;break;case 25:c=D.GraphicString;break;case 26:c=D.VisibleString;break;case 27:c=D.GeneralString;break;case 28:c=D.UniversalString;break;case 29:c=D.CharacterString;break;case 30:c=D.BmpString;break;case 31:c=D.DATE;break;case 32:c=D.TimeOfDay;break;case 33:c=D.DateTime;break;case 34:c=D.Duration;break;default:{let l=o.idBlock.isConstructed?new D.Constructed:new D.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?D.Constructed:D.Primitive}return o=R0(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 Sa(r){if(!r.byteLength){let t=new At({},Nt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return is(q.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function U0(r,t){return r?1:t}var le=class extends Nt{constructor({value:t=[],isIndefiniteForm:e=!1,...n}={}){super(n),this.value=t,this.isIndefiniteForm=e}fromBER(t,e,n){let o=q.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(;U0(this.isIndefiniteForm,n)>0;){let i=is(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===dn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===dn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(t,e){let n=e||new hn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(t,n);return e?oe:n.final()}toJSON(){let t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let e of this.value)t.value.push(e.toJSON());return t}};le.NAME="ConstructedValueBlock";var ou,qe=class extends At{constructor(t={}){super(t,le),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} :`}};jl=Ge;P.Constructed=jl;Ge.NAME="CONSTRUCTED";var Ao=class extends Lt{fromBER(t,e,n){return e}toBER(t){return ne}};Ao.override="EndOfContentValueBlock";var Zl,Bo=class extends At{constructor(t={}){super(t,Ao),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Zl=Bo;P.EndOfContent=Zl;Bo.NAME=hn;var Xl,Lr=class extends At{constructor(t={}){super(t,Lt),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}`}};Xl=Lr;P.Null=Xl;Lr.NAME="NULL";var So=class extends ke(Lt){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 Ie(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,ha.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};So.NAME="BooleanValueBlock";var Yl,Co=class extends At{constructor(t={}){super(t,So),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}`}};Yl=Co;P.Boolean=Yl;Co.NAME="BOOLEAN";var Io=class extends ke(le){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=le.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===hn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Wl)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?le.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};Io.NAME="OctetStringValueBlock";var Jl,ko=class r extends At{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},Io),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=rs(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?Ge.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)}};Jl=ko;P.OctetString=Jl;ko.NAME=Wl;var To=class extends ke(le){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=le.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===hn){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(!Ie(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=rs(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 le.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ne;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}}};To.NAME="BitStringValueBlock";var Ql,_r=class extends At{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},To),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 Ge.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)}`}}};Ql=_r;P.BitString=Ql;_r.NAME=ql;var tu;function A0(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=go(new Uint8Array([l%10]),s);break;default:s[i-f]=l%10}}return e[0]>0&&(s=go(e,s)),s}function $l(r){if(r>=un.length)for(let t=un.length;t<=r;t++){let e=new Uint8Array([0]),n=un[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=go(e,n)),un.push(n)}return un[r]}function B0(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 dn=class extends ke(Lt){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=ha.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Fl(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=B0($l(n),e),i="-";break;default:e=A0(e,$l(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(i+=Kl.charAt(e[c]));return a===!1&&(i+=Kl.charAt(0)),i}};tu=dn;dn.NAME="IntegerValueBlock";Object.defineProperty(tu.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var eu,Bt=class r extends At{constructor(t={}){super(t,dn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return yo(),BigInt(this.valueBlock.toString())}static fromBigInt(t){yo();let e=BigInt(t),n=new fn,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()}`}};eu=Bt;P.Integer=eu;Bt.NAME="INTEGER";var ru,No=class extends Bt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};ru=No;P.Enumerated=ru;No.NAME="ENUMERATED";var pn=class extends ke(Lt){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(!Ie(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=lr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){yo();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=qe(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",ne;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}}};pn.NAME="sidBlock";var Lo=class extends Lt{constructor({value:t=Ur,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new pn;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,ne;e.push(o)}return da(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 pn;if(o>Number.MAX_SAFE_INTEGER){yo();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}};Lo.NAME="ObjectIdentifierValueBlock";var nu,Rr=class extends At{constructor(t={}){super(t,Lo),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()}}};nu=Rr;P.ObjectIdentifier=nu;Rr.NAME="OBJECT IDENTIFIER";var mn=class extends ke(Be){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(!Ie(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=lr(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=qe(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",ne;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}}};mn.NAME="relativeSidBlock";var _o=class extends Lt{constructor({value:t=Ur,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new mn;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,ne;n.push(s)}return da(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 mn;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}};_o.NAME="RelativeObjectIdentifierValueBlock";var ou,Ro=class extends At{constructor(t={}){super(t,_o),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()}}};ou=Ro;P.RelativeObjectIdentifier=ou;Ro.NAME="RelativeObjectIdentifier";var su,Se=class extends Ge{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};su=Se;P.Sequence=su;Se.NAME="SEQUENCE";var iu,Uo=class extends Ge{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};iu=Uo;P.Set=iu;Uo.NAME="SET";var Po=class extends ke(Lt){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=Ur}toJSON(){return{...super.toJSON(),value:this.value}}};Po.NAME="StringValueBlock";var Do=class extends Po{};Do.NAME="SimpleStringValueBlock";var Pt=class extends xo{constructor({...t}={}){super(t,Do)}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 Oo=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}};Oo.NAME="Utf8StringValueBlock";var au,Ce=class extends Oo{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};au=Ce;P.Utf8String=au;Ce.NAME="UTF8String";var Mo=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))}};Mo.NAME="BmpStringValueBlock";var cu,Ho=class extends Mo{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};cu=Ho;P.BmpString=cu;Ho.NAME="BMPString";var Fo=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=qe(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}};Fo.NAME="UniversalStringValueBlock";var lu,Vo=class extends Fo{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};lu=Vo;P.UniversalString=lu;Vo.NAME="UniversalString";var uu,Ko=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};uu=Ko;P.NumericString=uu;Ko.NAME="NumericString";var fu,$o=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};fu=$o;P.PrintableString=fu;$o.NAME="PrintableString";var hu,Wo=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};hu=Wo;P.TeletexString=hu;Wo.NAME="TeletexString";var du,qo=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};du=qo;P.VideotexString=du;qo.NAME="VideotexString";var pu,Go=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};pu=Go;P.IA5String=pu;Go.NAME="IA5String";var mu,zo=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};mu=zo;P.GraphicString=mu;zo.NAME="GraphicString";var gu,gn=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};gu=gn;P.VisibleString=gu;gn.NAME="VisibleString";var yu,jo=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};yu=jo;P.GeneralString=yu;jo.NAME="GeneralString";var wu,Zo=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};wu=Zo;P.CharacterString=wu;Zo.NAME="CharacterString";var bu,yn=class extends gn{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]=Ht(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=Ht(this.month,2),e[2]=Ht(this.day,2),e[3]=Ht(this.hour,2),e[4]=Ht(this.minute,2),e[5]=Ht(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}}};bu=yn;P.UTCTime=bu;yn.NAME="UTCTime";var xu,Xo=class extends yn{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 y=parseInt(m.substring(0,2),10);if(isNaN(y.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*y,m.length===4){if(y=parseInt(m.substring(2,4),10),isNaN(y.valueOf()))throw new Error("Wrong input string for conversion");c=f*y}}}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(Ht(this.year,4)),e.push(Ht(this.month,2)),e.push(Ht(this.day,2)),e.push(Ht(this.hour,2)),e.push(Ht(this.minute,2)),e.push(Ht(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(Ht(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};xu=Xo;P.GeneralizedTime=xu;Xo.NAME="GeneralizedTime";var vu,Yo=class extends Ce{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};vu=Yo;P.DATE=vu;Yo.NAME="DATE";var Eu,Jo=class extends Ce{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Eu=Jo;P.TimeOfDay=Eu;Jo.NAME="TimeOfDay";var Au,Qo=class extends Ce{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Au=Qo;P.DateTime=Au;Qo.NAME="DateTime";var Bu,ts=class extends Ce{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Bu=ts;P.Duration=Bu;ts.NAME="Duration";var Su,es=class extends Ce{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Su=es;P.TIME=Su;es.NAME="TIME";function X(r,t="utf8"){let e=uo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var wn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},ns=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Cu={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new ns("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=Cu;async function Iu(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 C0(t);return{privateKey:e[0],publicKey:e[1]}}async function ku(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 Tu(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 C0(r){if(r.privateKey==null||r.publicKey==null)throw new rt("Private and public key are required");return Promise.all([ze.get().subtle.exportKey("jwk",r.privateKey),ze.get().subtle.exportKey("jwk",r.publicKey)])}function ga(r){if(r.kty!=="RSA")throw new rt("invalid key type");if(r.n==null)throw new rt("invalid key modulus");return Q(r.n,"base64url").length*8}var Pr=class{type="RSA";_key;_raw;_multihash;constructor(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=bn.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return vt.createV1(114,this._multihash)}toString(){return nt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Ut(this.raw,t.raw)}verify(t,e){return Tu(this._key,e,t)}},xn=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=bn.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Ut(this.raw,t.raw)}sign(t){return ku(this._key,t)}};var os=8192,ya=18;function Nu(r){let{result:t}=ma(r),e=t.valueBlock.value;return{n:ue(e[1]),e:ue(e[2]),d:ue(e[3]),p:ue(e[4]),q:ue(e[5]),dp:ue(e[6]),dq:ue(e[7]),qi:ue(e[8]),kty:"RSA",alg:"RS256"}}function I0(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 rt("JWK was missing components");let e=new Se({value:[new Bt({value:0}),Bt.fromBigInt(fe(Q(r.n,"base64url"))),Bt.fromBigInt(fe(Q(r.e,"base64url"))),Bt.fromBigInt(fe(Q(r.d,"base64url"))),Bt.fromBigInt(fe(Q(r.p,"base64url"))),Bt.fromBigInt(fe(Q(r.q,"base64url"))),Bt.fromBigInt(fe(Q(r.dp,"base64url"))),Bt.fromBigInt(fe(Q(r.dq,"base64url"))),Bt.fromBigInt(fe(Q(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function Lu(r){let{result:t}=ma(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:ue(e[0]),e:ue(e[1])}}function wa(r){if(r.n==null||r.e==null)throw new rt("JWK was missing components");let e=new Se({value:[new Se({value:[new Rr({value:"1.2.840.113549.1.1.1"}),new Lr]}),new _r({valueHex:new Se({value:[Bt.fromBigInt(fe(Q(r.n,"base64url"))),Bt.fromBigInt(fe(Q(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function ue(r){let t=r.valueBlock.valueHexView;for(;t[0]===0;)t=t.subarray(1);return X(t,"base64url")}function fe(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 _u(r){let t=Nu(r);return Ru(t)}function ba(r){let t=Lu(r);if(ga(t)>os)throw new gr("Key size is too large");let e=ce(ae.encode({Type:wt.RSA,Data:r})),n=kt(ya,e);return new Pr(t,n)}function Ru(r){if(ga(r)>os)throw new rt("Key size is too large");let t=Pu(r),e=ce(ae.encode({Type:wt.RSA,Data:wa(t.publicKey)})),n=kt(ya,e);return new xn(t.privateKey,new Pr(t.publicKey,n))}async function Uu(r){if(r>os)throw new rt("Key size is too large");let t=await Iu(r),e=ce(ae.encode({Type:wt.RSA,Data:wa(t.publicKey)})),n=kt(ya,e);return new xn(t.privateKey,new Pr(t.publicKey,n))}function Pu(r){if(r==null)throw new rt("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var ss=class extends Br{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Jr(t);let n=De(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 Ar(this),this.iHash.update(t),this}digestInto(t){Ar(this),Er(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()}},Dr=(r,t,e)=>new ss(r,t).update(e).digest();Dr.create=(r,t)=>new ss(r,t);function Du(r){r.lowS!==void 0&&Zt("lowS",r.lowS),r.prehash!==void 0&&Zt("prehash",r.prehash)}function k0(r){let t=rn(r);qt(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("invalid 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("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:T0,hexToBytes:N0}=eo,xa=class extends Error{constructor(t=""){super(t)}},Te={Err:xa,_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=er(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?er(o.length/2|128):"";return er(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=er(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");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 T0(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Te,o=typeof r=="string"?N0(r):r;Cr(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)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},Ne=BigInt(0),xt=BigInt(1),Yb=BigInt(2),Ou=BigInt(3),Jb=BigInt(4);function L0(r){let t=k0(r),{Fp:e}=t,n=Ve(t.n,t.nBitLength),o=t.toBytes||((g,h,b)=>{let x=h.toAffine();return ve(Uint8Array.from([4]),e.toBytes(x.x),e.toBytes(x.y))}),s=t.fromBytes||(g=>{let h=g.subarray(1),b=e.fromBytes(h.subarray(0,e.BYTES)),x=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:b,y:x}});function i(g){let{a:h,b}=t,x=e.sqr(g),p=e.mul(x,g);return e.add(e.add(p,e.mul(g,h)),b)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return tn(g,xt,t.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:b,wrapPrivateKey:x,n:p}=t;if(h&&typeof g!="bigint"){if(He(g)&&(g=we(g)),typeof g!="string"||!h.includes(g.length))throw new Error("invalid private key");g=g.padStart(b*2,"0")}let S;try{S=typeof g=="bigint"?g:be(ot("private key",g,b))}catch{throw new Error("invalid private key, expected hex or "+b+" bytes, got "+typeof g)}return x&&(S=Z(S,p)),Et("private key",S,xt,p),S}function l(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let u=nr((g,h)=>{let{px:b,py:x,pz:p}=g;if(e.eql(p,e.ONE))return{x:b,y:x};let S=g.is0();h==null&&(h=S?e.ONE:e.inv(p));let L=e.mul(b,h),N=e.mul(x,h),B=e.mul(p,h);if(S)return{x:e.ZERO,y:e.ZERO};if(!e.eql(B,e.ONE))throw new Error("invZ was invalid");return{x:L,y:N}}),f=nr(g=>{if(g.is0()){if(t.allowInfinityPoint&&!e.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:h,y:b}=g.toAffine();if(!e.isValid(h)||!e.isValid(b))throw new Error("bad point: x or y not FE");let x=e.sqr(b),p=i(h);if(!e.eql(x,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,b,x){if(this.px=h,this.py=b,this.pz=x,h==null||!e.isValid(h))throw new Error("x required");if(b==null||!e.isValid(b))throw new Error("y required");if(x==null||!e.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:b,y:x}=h||{};if(!h||!e.isValid(b)||!e.isValid(x))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let p=S=>e.eql(S,e.ZERO);return p(b)&&p(x)?d.ZERO:new d(b,x,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let b=e.invertBatch(h.map(x=>x.pz));return h.map((x,p)=>x.toAffine(b[p])).map(d.fromAffine)}static fromHex(h){let b=d.fromAffine(s(ot("pointHex",h)));return b.assertValidity(),b}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,b){return so(d,n,h,b)}_setWindowSize(h){y.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:b,py:x,pz:p}=this,{px:S,py:L,pz:N}=h,B=e.eql(e.mul(b,N),e.mul(S,p)),T=e.eql(e.mul(x,N),e.mul(L,p));return B&&T}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b}=t,x=e.mul(b,Ou),{px:p,py:S,pz:L}=this,N=e.ZERO,B=e.ZERO,T=e.ZERO,I=e.mul(p,p),H=e.mul(S,S),U=e.mul(L,L),M=e.mul(p,S);return M=e.add(M,M),T=e.mul(p,L),T=e.add(T,T),N=e.mul(h,T),B=e.mul(x,U),B=e.add(N,B),N=e.sub(H,B),B=e.add(H,B),B=e.mul(N,B),N=e.mul(M,N),T=e.mul(x,T),U=e.mul(h,U),M=e.sub(I,U),M=e.mul(h,M),M=e.add(M,T),T=e.add(I,I),I=e.add(T,I),I=e.add(I,U),I=e.mul(I,M),B=e.add(B,I),U=e.mul(S,L),U=e.add(U,U),I=e.mul(U,M),N=e.sub(N,I),T=e.mul(U,H),T=e.add(T,T),T=e.add(T,T),new d(N,B,T)}add(h){l(h);let{px:b,py:x,pz:p}=this,{px:S,py:L,pz:N}=h,B=e.ZERO,T=e.ZERO,I=e.ZERO,H=t.a,U=e.mul(t.b,Ou),M=e.mul(b,S),V=e.mul(x,L),C=e.mul(p,N),k=e.add(b,x),v=e.add(S,L);k=e.mul(k,v),v=e.add(M,V),k=e.sub(k,v),v=e.add(b,p);let w=e.add(S,N);return v=e.mul(v,w),w=e.add(M,C),v=e.sub(v,w),w=e.add(x,p),B=e.add(L,N),w=e.mul(w,B),B=e.add(V,C),w=e.sub(w,B),I=e.mul(H,v),B=e.mul(U,C),I=e.add(B,I),B=e.sub(V,I),I=e.add(V,I),T=e.mul(B,I),V=e.add(M,M),V=e.add(V,M),C=e.mul(H,C),v=e.mul(U,v),V=e.add(V,C),C=e.sub(M,C),C=e.mul(H,C),v=e.add(v,C),M=e.mul(V,v),T=e.add(T,M),M=e.mul(w,v),B=e.mul(k,B),B=e.sub(B,M),M=e.mul(k,V),I=e.mul(w,I),I=e.add(I,M),new d(B,T,I)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return y.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){let{endo:b,n:x}=t;Et("scalar",h,Ne,x);let p=d.ZERO;if(h===Ne)return p;if(this.is0()||h===xt)return this;if(!b||y.hasPrecomputes(this))return y.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:S,k1:L,k2neg:N,k2:B}=b.splitScalar(h),T=p,I=p,H=this;for(;L>Ne||B>Ne;)L&xt&&(T=T.add(H)),B&xt&&(I=I.add(H)),H=H.double(),L>>=xt,B>>=xt;return S&&(T=T.negate()),N&&(I=I.negate()),I=new d(e.mul(I.px,b.beta),I.py,I.pz),T.add(I)}multiply(h){let{endo:b,n:x}=t;Et("scalar",h,xt,x);let p,S;if(b){let{k1neg:L,k1:N,k2neg:B,k2:T}=b.splitScalar(h),{p:I,f:H}=this.wNAF(N),{p:U,f:M}=this.wNAF(T);I=y.constTimeNegate(L,I),U=y.constTimeNegate(B,U),U=new d(e.mul(U.px,b.beta),U.py,U.pz),p=I.add(U),S=H.add(M)}else{let{p:L,f:N}=this.wNAF(h);p=L,S=N}return d.normalizeZ([p,S])[0]}multiplyAndAddUnsafe(h,b,x){let p=d.BASE,S=(N,B)=>B===Ne||B===xt||!N.equals(p)?N.multiplyUnsafe(B):N.multiply(B),L=S(this,b).add(S(h,x));return L.is0()?void 0:L}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:b}=t;if(h===xt)return!0;if(b)return b(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:b}=t;return h===xt?this:b?b(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return Zt("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return Zt("isCompressed",h),we(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,y=oo(d,t.endo?Math.ceil(m/2):m);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function _0(r){let t=rn(r);return qt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Mu(r){let t=_0(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(C){return Z(C,n)}function a(C){return ro(C,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=L0({...t,toBytes(C,k,v){let w=k.toAffine(),A=e.toBytes(w.x),E=ve;return Zt("isCompressed",v),v?E(Uint8Array.from([k.hasEvenY()?2:3]),A):E(Uint8Array.from([4]),A,e.toBytes(w.y))},fromBytes(C){let k=C.length,v=C[0],w=C.subarray(1);if(k===o&&(v===2||v===3)){let A=be(w);if(!tn(A,xt,e.ORDER))throw new Error("Point is not on curve");let E=u(A),_;try{_=e.sqrt(E)}catch(K){let F=K instanceof Error?": "+K.message:"";throw new Error("Point is not on curve"+F)}let R=(_&xt)===xt;return(v&1)===1!==R&&(_=e.neg(_)),{x:A,y:_}}else if(k===s&&v===4){let A=e.fromBytes(w.subarray(0,e.BYTES)),E=e.fromBytes(w.subarray(e.BYTES,2*e.BYTES));return{x:A,y:E}}else{let A=o,E=s;throw new Error("invalid Point, expected length of "+A+", or uncompressed "+E+", got "+k)}}}),d=C=>we(Fe(C,t.nByteLength));function m(C){let k=n>>xt;return C>k}function y(C){return m(C)?i(-C):C}let g=(C,k,v)=>be(C.slice(k,v));class h{constructor(k,v,w){this.r=k,this.s=v,this.recovery=w,this.assertValidity()}static fromCompact(k){let v=t.nByteLength;return k=ot("compactSignature",k,v*2),new h(g(k,0,v),g(k,v,2*v))}static fromDER(k){let{r:v,s:w}=Te.toSig(ot("DER",k));return new h(v,w)}assertValidity(){Et("r",this.r,xt,n),Et("s",this.s,xt,n)}addRecoveryBit(k){return new h(this.r,this.s,k)}recoverPublicKey(k){let{r:v,s:w,recovery:A}=this,E=N(ot("msgHash",k));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let _=A===2||A===3?v+t.n:v;if(_>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let R=A&1?"03":"02",O=c.fromHex(R+d(_)),K=a(_),F=i(-E*K),W=i(w*K),j=c.BASE.multiplyAndAddUnsafe(O,F,W);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 rr(this.toDERHex())}toDERHex(){return Te.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return rr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let b={isValidPrivateKey(C){try{return l(C),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let C=Ci(t.n);return hl(t.randomBytes(C),t.n)},precompute(C=8,k=c.BASE){return k._setWindowSize(C),k.multiply(BigInt(3)),k}};function x(C,k=!0){return c.fromPrivateKey(C).toRawBytes(k)}function p(C){let k=He(C),v=typeof C=="string",w=(k||v)&&C.length;return k?w===o||w===s:v?w===2*o||w===2*s:C instanceof c}function S(C,k,v=!0){if(p(C))throw new Error("first arg must be private key");if(!p(k))throw new Error("second arg must be public key");return c.fromHex(k).multiply(l(C)).toRawBytes(v)}let L=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let k=be(C),v=C.length*8-t.nBitLength;return v>0?k>>BigInt(v):k},N=t.bits2int_modN||function(C){return i(L(C))},B=en(t.nBitLength);function T(C){return Et("num < 2^"+t.nBitLength,C,Ne,B),Fe(C,t.nByteLength)}function I(C,k,v=H){if(["recovered","canonical"].some(it=>it in v))throw new Error("sign() legacy options not supported");let{hash:w,randomBytes:A}=t,{lowS:E,prehash:_,extraEntropy:R}=v;E==null&&(E=!0),C=ot("msgHash",C),Du(v),_&&(C=ot("prehashed msgHash",w(C)));let O=N(C),K=l(k),F=[T(K),T(O)];if(R!=null&&R!==!1){let it=R===!0?A(e.BYTES):R;F.push(ot("extraEntropy",it))}let W=ve(...F),j=O;function st(it){let ut=L(it);if(!f(ut))return;let Ct=a(ut),Ot=c.BASE.multiply(ut).toAffine(),Rt=i(Ot.x);if(Rt===Ne)return;let se=i(Ct*i(j+Rt*K));if(se===Ne)return;let de=(Ot.x===Rt?0:2)|Number(Ot.y&xt),zr=se;return E&&m(se)&&(zr=y(se),de^=1),new h(Rt,zr,de)}return{seed:W,k2sig:st}}let H={lowS:t.lowS,prehash:!1},U={lowS:t.lowS,prehash:!1};function M(C,k,v=H){let{seed:w,k2sig:A}=I(C,k,v),E=t;return vi(E.hash.outputLen,E.nByteLength,E.hmac)(w,A)}c.BASE._setWindowSize(8);function V(C,k,v,w=U){let A=C;k=ot("msgHash",k),v=ot("publicKey",v);let{lowS:E,prehash:_,format:R}=w;if(Du(w),"strict"in w)throw new Error("options.strict was renamed to lowS");if(R!==void 0&&R!=="compact"&&R!=="der")throw new Error("format must be compact or der");let O=typeof A=="string"||He(A),K=!O&&!R&&typeof A=="object"&&A!==null&&typeof A.r=="bigint"&&typeof A.s=="bigint";if(!O&&!K)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let F,W;try{if(K&&(F=new h(A.r,A.s)),O){try{R!=="compact"&&(F=h.fromDER(A))}catch(de){if(!(de instanceof Te.Err))throw de}!F&&R!=="der"&&(F=h.fromCompact(A))}W=c.fromHex(v)}catch{return!1}if(!F||E&&F.hasHighS())return!1;_&&(k=t.hash(k));let{r:j,s:st}=F,it=N(k),ut=a(st),Ct=i(it*ut),Ot=i(j*ut),Rt=c.BASE.multiplyAndAddUnsafe(W,Ct,Ot)?.toAffine();return Rt?i(Rt.x)===j:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:S,sign:M,verify:V,ProjectivePoint:c,Signature:h,utils:b}}function R0(r){return{hash:r,hmac:(t,...e)=>Dr(r,t,pi(...e)),randomBytes:Qr}}function Hu(r,t){let e=n=>Mu({...r,...R0(n)});return{...e(t),create:e}}var Ku=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Fu=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),U0=BigInt(1),va=BigInt(2),Vu=(r,t)=>(r+t/va)/t;function P0(r){let t=Ku,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=at(u,e,t)*u%t,d=at(f,e,t)*u%t,m=at(d,va,t)*l%t,y=at(m,o,t)*m%t,g=at(y,s,t)*y%t,h=at(g,a,t)*g%t,b=at(h,c,t)*h%t,x=at(b,a,t)*g%t,p=at(x,e,t)*u%t,S=at(p,i,t)*y%t,L=at(S,n,t)*l%t,N=at(L,va,t);if(!Ea.eql(Ea.sqr(N),r))throw new Error("Cannot find square root");return N}var Ea=Ve(Ku,void 0,void 0,{sqrt:P0}),ur=Hu({a:BigInt(0),b:BigInt(7),Fp:Ea,n:Fu,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Fu,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-U0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=Vu(s*r,t),c=Vu(-n*r,t),l=Z(r-a*e-c*o,t),u=Z(-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}}}},ce),ax=BigInt(0);var cx=ur.ProjectivePoint;function bt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=yt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}function $u(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Wu(r,t,e){let n=Ee.digest(e instanceof Uint8Array?e:e.subarray());if($u(n))return n.then(({digest:o})=>ur.verify(t,o,r)).catch(o=>{throw new wn(String(o))});try{return ur.verify(t,n.digest,r)}catch(o){throw new wn(String(o))}}var is=class{type="secp256k1";raw;_key;constructor(t){this._key=Gu(t),this.raw=qu(this._key)}toMultihash(){return ge.digest(kr(this))}toCID(){return vt.createV1(114,this.toMultihash())}toString(){return nt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Ut(this.raw,t.raw)}verify(t,e){return Wu(this._key,e,t)}};function Aa(r){return new is(r)}function qu(r){return ur.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Gu(r){try{return ur.ProjectivePoint.fromHex(r),r}catch(t){throw new gr(String(t))}}function vn(r){let{Type:t,Data:e}=ae.decode(r),n=e??new Uint8Array;switch(t){case wt.RSA:return ba(n);case wt.Ed25519:return Ri(n);case wt.secp256k1:return Aa(n);default:throw new Je}}function zu(r){let{Type:t,Data:e}=ae.decode(r.digest),n=e??new Uint8Array;switch(t){case wt.Ed25519:return Ri(n);case wt.secp256k1:return Aa(n);default:throw new Je}}function kr(r){return ae.encode({Type:wt[r.type],Data:r.raw})}var ju=Symbol.for("nodejs.util.inspect.custom"),O0=114,En=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()})`}[ri]=!0;toString(){return this.string==null&&(this.string=nt.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return vt.createV1(O0,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Ut(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Ut(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[ju](){return`PeerId(${this.toString()})`}},An=class extends En{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Bn=class extends En{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Sn=class extends En{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},M0=2336,as=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=ge.digest(Q(this.url))}[ju](){return`PeerId(${this.url})`}[ri]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return vt.createV1(M0,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=X(t)),t.toString()===this.toString())}};function Or(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Pe(nt.decode(`z${r}`));else{if(t==null)throw new rt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Pe(t.decode(r))}return H0(e)}function Ba(r){if(r.type==="Ed25519")return new Bn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Sn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new An({multihash:r.toCID().multihash,publicKey:r});throw new Je}function H0(r){if(V0(r))return new An({multihash:r});if(F0(r))try{let t=zu(r);if(t.type==="Ed25519")return new Bn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Sn({multihash:r,publicKey:t})}catch{let e=X(r.digest);return new as(new URL(e))}throw new qn("Supplied PeerID Multihash is invalid")}function F0(r){return r.code===ge.code}function V0(r){return r.code===Ee.code}var cs=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 Zu=45,K0=15,Mr=new cs;function Sa(r){if(!(r.length>K0))return Mr.new(r).parseWith(()=>Mr.readIPv4Addr())}function Ca(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Zu))return Mr.new(r).parseWith(()=>Mr.readIPv6Addr())}function ls(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Zu)return;let e=Mr.new(r).parseWith(()=>Mr.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}var A1=parseInt("0xFFFF",16),B1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function us(r){return!!Sa(r)}function fs(r){return!!Ca(r)}function hs(r){return!!ls(r)}var Ju=us,z0=fs,Ia=function(r){let t=0;if(r=r.toString().trim(),Ju(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(z0(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Ju(e[n]),i;s&&(i=Ia(e[n]),e[n]=X(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,X(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")},Qu=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 Hr={},ka={},Z0=[[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"]];Z0.forEach(r=>{let t=X0(...r);ka[t.code]=t,Hr[t.name]=t});function X0(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function tt(r){if(typeof r=="number"){if(ka[r]!=null)return ka[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Hr[r]!=null)return Hr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var a2=tt("ip4"),c2=tt("ip6"),l2=tt("ipcidr");function _a(r,t){switch(tt(r).code){case 4:case 41:return J0(t);case 42:return La(t);case 43:return X(t,"base10");case 6:case 273:case 33:case 132:return rf(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return La(t);case 421:return rm(t);case 444:return ef(t);case 445:return ef(t);case 466:return em(t);case 481:return globalThis.encodeURIComponent(La(t));default:return X(t,"base16")}}function Ra(r,t){switch(tt(r).code){case 4:return tf(t);case 41:return tf(t);case 42:return Na(t);case 43:return Q(t,"base10");case 6:case 273:case 33:case 132:return Ua(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Na(t);case 421:return Q0(t);case 444:return nm(t);case 445:return om(t);case 466:return tm(t);case 481:return Na(globalThis.decodeURIComponent(t));default:return Q(t,"base16")}}var Ta=Object.values(ir).map(r=>r.decoder),Y0=function(){let r=Ta[0].or(Ta[1]);return Ta.slice(2).forEach(t=>r=r.or(t)),r}();function tf(r){if(!hs(r))throw new Error("invalid ip address");return Ia(r)}function J0(r){let t=Qu(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!hs(t))throw new Error("invalid ip address");return t}function Ua(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function rf(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Na(r){let t=Q(r),e=Uint8Array.from(ie(t.length));return bt([e,t],e.length+t.length)}function La(r){let t=Jt(r);if(r=r.slice(ct(t)),r.length!==t)throw new Error("inconsistent lengths");return X(r)}function Q0(r){let t;r[0]==="Q"||r[0]==="1"?t=Pe(nt.decode(`z${r}`)).bytes:t=vt.parse(r).multihash.bytes;let e=Uint8Array.from(ie(t.length));return bt([e,t],e.length+t.length)}function tm(r){let t=Y0.decode(r),e=Uint8Array.from(ie(t.length));return bt([e,t],e.length+t.length)}function em(r){let t=Jt(r),e=r.slice(ct(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+X(e,"base64url")}function rm(r){let t=Jt(r),e=r.slice(ct(t));if(e.length!==t)throw new Error("inconsistent lengths");return X(e,"base58btc")}function nm(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=me.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=Ua(n);return bt([e,o],e.length+o.length)}function om(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=me.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=Ua(n);return bt([e,o],e.length+o.length)}function ef(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=X(t,"base32"),o=rf(e);return`${n}:${o}`}function nf(r){r=Pa(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 new ds("invalid address: "+r);if(a.path===!0){n=Pa(o.slice(s).join("/")),t.push([a.code,Ra(a.code,n)]),e.push([a.code,n]);break}let c=Ra(a.code,o[s]);t.push([a.code,c]),e.push([a.code,_a(a.code,c)])}return{string:of(e),bytes:Oa(t),tuples:t,stringTuples:e,path:n}}function Da(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=Jt(r,o),i=ct(s),a=tt(s),c=sm(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 new ds("Invalid address Uint8Array: "+X(r,"base16"));t.push([s,l]);let u=_a(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:of(e),tuples:t,stringTuples:e,path:n}}function of(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}),Pa(t.join("/"))}function Oa(r){return bt(r.map(t=>{let e=tt(t[0]),n=Uint8Array.from(ie(e.code));return t.length>1&&t[1]!=null&&(n=bt([n,t[1]])),n}))}function sm(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=Jt(t instanceof Uint8Array?t:Uint8Array.from(t));return e+ct(e)}}function Pa(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var ds=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var im=Symbol.for("nodejs.util.inspect.custom"),Ha=Symbol.for("@multiformats/js-multiaddr/multiaddr"),am=[tt("dns").code,tt("dns4").code,tt("dns6").code,tt("dnsaddr").code],Ma=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},ps=class r{bytes;#t;#e;#r;#n;[Ha]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Da(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=nf(t)}else if(af(t))e=Da(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,y]of this.stringTuples())m===f.code&&(s=`%${y??""}`),am.includes(m)&&(e=i.name==="tcp"?"tcp":"udp",o=443,n=`${y??""}${s}`,t=m===u.code?6:4),(m===i.code||m===a.code)&&(e=tt(m).name==="tcp"?"tcp":"udp",o=parseInt(y??"")),(m===c.code||m===l.code)&&(e=tt(m).name==="tcp"?"tcp":"udp",n=`${y??""}${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.map(([t,e])=>e==null?[t]:[t,e])}stringTuples(){return this.#r.map(([t,e])=>e==null?[t]:[t,e])}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(Oa(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Hr.p2p.code&&t.push([n,o]),n===Hr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?X(nt.decode(`z${n}`),"base58btc"):X(vt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return Ut(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=sf.get(e.name);if(n==null)throw new Ma(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>he(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)}[im](){return`Multiaddr(${this.#t})`}};var sf=new Map;function af(r){return!!r?.[Ha]}function he(r){return new ps(r)}var cm=r=>r.toString().split("/").slice(1),Fr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),q=r=>({match:t=>Fr(e=>e===r).match(t),pattern:r}),fr=()=>({match:r=>Fr(t=>typeof t=="string").match(r),pattern:"{string}"}),Cn=()=>({match:r=>Fr(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),et=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{nt.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),In=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{an.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Y=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),_t=(...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(", ")})`}),z=(...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 lt(...r){function t(o){let s=cm(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 gs=z(q("dns4"),fr()),ys=z(q("dns6"),fr()),ws=z(q("dnsaddr"),fr()),Va=z(q("dns"),fr()),M2=lt(gs,Y(et())),H2=lt(ys,Y(et())),F2=lt(ws,Y(et())),V2=lt(_t(Va,ws,gs,ys),Y(et())),cf=z(q("ip4"),Fr(us)),lf=z(q("ip6"),Fr(fs)),Ka=_t(cf,lf),Le=_t(Ka,Va,gs,ys,ws),K2=lt(_t(Ka,z(_t(Va,ws,gs,ys),Y(et())))),$2=lt(cf),W2=lt(lf),q2=lt(Ka),$a=z(Le,q("tcp"),Cn()),kn=z(Le,q("udp"),Cn()),G2=lt(z($a,Y(et()))),z2=lt(kn),Wa=z(kn,q("quic"),Y(et())),bs=z(kn,q("quic-v1"),Y(et())),lm=_t(Wa,bs),j2=lt(Wa),Z2=lt(bs),Fa=_t(Le,$a,kn,Wa,bs),uf=_t(z(Fa,q("ws"),Y(et()))),X2=lt(uf),ff=_t(z(Fa,q("wss"),Y(et())),z(Fa,q("tls"),Y(z(q("sni"),fr())),q("ws"),Y(et()))),Y2=lt(ff),hf=z(kn,q("webrtc-direct"),Y(In()),Y(In()),Y(et())),df=lt(hf),pf=z(bs,q("webtransport"),Y(In()),Y(In()),Y(et())),J2=lt(pf),ms=_t(uf,ff,z($a,Y(et())),z(lm,Y(et())),z(Le,Y(et())),hf,pf,et()),mf=lt(ms),um=z(ms,q("p2p-circuit"),et()),Q2=lt(um),fm=_t(z(ms,q("p2p-circuit"),q("webrtc"),Y(et())),z(ms,q("webrtc"),Y(et())),z(q("webrtc"),Y(et()))),gf=lt(fm),hm=_t(z(Le,q("tcp"),Cn(),q("http"),Y(et())),z(Le,q("http"),Y(et()))),tv=lt(hm),dm=_t(z(Le,q("tcp"),_t(z(q("443"),q("http")),z(Cn(),q("https"))),Y(et())),z(Le,q("tls"),q("http"),Y(et())),z(Le,q("https"),Y(et()))),ev=lt(dm),pm=_t(z(q("memory"),fr(),Y(et()))),rv=lt(pm);var yf=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))},mm=function(){function r(t,e,n){this.name=t,this.version=e,this.os=n,this.type="browser"}return r}();var gm=function(){function r(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return r}();var ym=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 wm=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var bm=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var xm=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,vm=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,wf=3,Em=[["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",xm]],bf=[["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 vf(r){return r?xf(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new bm:typeof navigator<"u"?xf(navigator.userAgent):Sm()}function Am(r){return r!==""&&Em.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 xf(r){var t=Am(r);if(!t)return null;var e=t[0],n=t[1];if(e==="searchbot")return new wm;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<wf&&(o=yf(yf([],o,!0),Cm(wf-o.length),!0)):o=[];var s=o.join("."),i=Bm(r),a=vm.exec(r);return a&&a[1]?new ym(e,s,i,a[1]):new mm(e,s,i)}function Bm(r){for(var t=0,e=bf.length;t<e;t++){var n=bf[t],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function Sm(){var r=typeof process<"u"&&process.version;return r?new gm(process.version.slice(1)):null}function Cm(r){for(var t=[],e=0;e<r;e++)t.push("0");return t}function pt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var qa=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Ga=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Ef=r=>globalThis.DOMException===void 0?new Ga(r):new DOMException(r),Af=r=>{let t=r.reason===void 0?Ef("This operation was aborted."):r.reason;return t instanceof Error?t:Ef(t)};function Tn(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,a,l=new Promise((u,f)=>{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:m}=t;m.aborted&&f(Af(m)),a=()=>{f(Af(m))},m.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new qa;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(m){f(m)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(d.message=o??`Promise timed out after ${e} milliseconds`,f(d))},e),(async()=>{try{u(await r)}catch(m){f(m)}})()}).finally(()=>{l.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},l}var Bf=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],za=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Sf="libp2p+webrtc+v1/";var Cf=vf(),Nn=Cf!=null&&Cf.name==="firefox",xs=async function*(){},vs=async r=>{},Im=30*1e3;function If(r,t,e=Im,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=pt(),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 Tn(o.promise,{milliseconds:e})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function ja(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??Bf.map(t=>({urls:[t]})),r}var kf=(r=32)=>Sf+[...Array(r)].map(()=>za.at(Math.floor(Math.random()*za.length))).join("");var hr=class{log;peerConnection;remoteAddr;timeline;metrics;source=xs();sink=vs;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,o=n.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",n.connectionState,"initial state",o),(n.connectionState==="disconnected"||n.connectionState==="failed"||n.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 Es=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}},Vr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Es(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 Es(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 Za=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function je(r={}){return km(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 km(r,t){t=t??{};let e=t.onEnd,n=new Vr,o,s,i,a=pt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,b)=>{s=x=>{s=null,n.push(x);try{h(r(n))}catch(p){b(p)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=pt()})}},l=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new Vr,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 Vr,d(),{done:!0}),y=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:y,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let b=h?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let x,p;b!=null&&(x=new Promise((S,L)=>{p=()=>{L(new Za)},b.addEventListener("abort",p)}));try{await Promise.race([a.promise,x])}finally{p!=null&&b!=null&&b?.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 As=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 oe(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new As(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new As(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 Nf=Symbol.for("@achingbrain/uint8arraylist");function Tf(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 Bs(r){return!!r?.[Nf]}var ht=class r{bufs;length;[Nf]=!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(Bs(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(Bs(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=Tf(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Tf(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(Bs(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 bt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:bt(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(!Bs(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=yt(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=gt(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=gt(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=gt(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=yt(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=gt(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=gt(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=gt(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=gt(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=gt(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(!Ut(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 Lf(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 _f(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Rf(r,t){let e=Lf(r).return?.();_f(e)&&e.catch(n=>{t.error("could not cause iterator to return",n)})}var Tm=5e3;function Xa(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ss=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=pt(),this.closed=pt(),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??Tm,this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=je({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 Ye(`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);Xa(o)&&await o}let n=()=>{Rf(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 ht(o):o;let s=this.sendData(o,e);Xa(s)&&(this.sendingData=pt(),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.status==="open"&&(this.log.trace("closing gracefully"),this.status="closing",await oe(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 oe(this.sink([]),t.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await oe(this.sendingData.promise,t.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await oe(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();Xa(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 Wn("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 Ya(r){let t=new globalThis.AbortController;function e(){t.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}function Cs(r){return r[Symbol.asyncIterator]!=null}var Is=r=>{let t=ct(r),e=yt(t);return ie(r,e),Is.bytes=t,e};Is.bytes=0;function Ln(r,t){t=t??{};let e=t.lengthEncoder??Is;function*n(o){let s=e(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Cs(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Ln.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Is;return new ht(e(r.byteLength),r)};var ks=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ts=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ns=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},_n=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Nm=8,Lm=1024*1024*4,dr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(dr||(dr={}));var Ja=r=>{let t=Jt(r);return Ja.bytes=ct(t),t};Ja.bytes=0;function pr(r,t){let e=new ht,n=dr.LENGTH,o=-1,s=t?.lengthDecoder??Ja,i=t?.maxLengthLength??Nm,a=t?.maxDataLength??Lm;function*c(){for(;e.byteLength>0;){if(n===dr.LENGTH)try{if(o=s(e),o<0)throw new ks("Invalid message length");if(o>a)throw new Ts("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=dr.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Ns("Message length length too long");break}throw l}if(n===dr.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=dr.LENGTH}}}return Cs(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new _n("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new _n("Unexpected end of input")}()}pr.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 pr(n,{...t??{},onLength:s=>{e=s}})};var Qa=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function Rn(r,t,e,n){let o=new Qa(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){e?.removeEventListener("abort",u),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),i(d);return}a(),s(f)},l=f=>{a(),i(f.detail)},u=()=>{a(),i(o)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var Dt;(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=()=>cr(e)}(t=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=re((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=>ee(o,r.codec()),r.decode=(o,s)=>te(o,r.codec(),s)})(Dt||(Dt={}));var Rm=2*1024*1024,Um=30*1e3,Un=16*1024;function Pm(r=Un){let t=ct(r-ct(r)),e=1+ct(Object.keys(Dt.Flag).length-1),n=1,o=r-t-e-n,s=ct(o);return t+e+n+s}var Dm=Pm(),Om=5e3,Mm=5e3,tc=class extends Ss{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;closeController;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 Tn(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(s){this.log.error("error receiving FIN_ACK",s)}}).then(()=>{this.incomingData.end(),this.channel.close(),e?.(o)}).catch(s=>{this.log.error("error ending stream",s)})},super(t),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=je(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??Um,this.maxBufferedAmount=t.maxBufferedAmount??Rm,this.maxMessageSize=(t.maxMessageSize??Un)-Dm,this.receiveFinAck=pt(),this.finAckTimeout=t.closeTimeout??Om,this.openTimeout=t.openTimeout??Mm,this.closeController=new AbortController,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 Ye("Unknown datachannel state")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime()},this.channel.onclose=o=>{this.log.trace("received onclose event"),this.closeController.abort(),this.receiveFinAck.resolve(),this.close().catch(s=>{this.log.error("error closing stream after channel closed",s)})},this.channel.onerror=o=>{this.log.trace("received onerror event"),this.closeController.abort();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 pr(this.incomingData)){let s=n.processIncomingProtobuf(o);s!=null&&n.sourcePush(new ht(s))}}).catch(o=>{this.log.error("error processing incoming data channel messages",o)})}sendNewStream(){}async _sendMessage(t,e=!0){if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new Ye(`Invalid datachannel state - ${this.channel.readyState}`);if(this.channel.readyState!=="open"){let n=AbortSignal.timeout(this.openTimeout),o=Ya([this.closeController.signal,n]);try{this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await Rn(this.channel,"open",o)}finally{o.clear()}this.log('channel state is now "%s", sending data',this.channel.readyState)}if(e&&this.channel.bufferedAmount>this.maxBufferedAmount){let n=AbortSignal.timeout(this.bufferedAmountLowEventTimeout),o=Ya([this.closeController.signal,n]);try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await Rn(this.channel,"bufferedamountlow",o)}catch(s){throw n.aborted?new zn(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`):s}finally{o.clear()}}try{this.channel.send(t.subarray())}catch(n){this.log.error("error while sending message",n)}}async sendData(t){for(this.log.trace("-> will send %d bytes",t.byteLength),t=t.sublist();t.byteLength>0;){let e=Math.min(t.byteLength,this.maxMessageSize),n=t.subarray(0,e),o=Dt.encode({message:n}),s=Ln.single(o);this.log.trace("-> sending message %s",this.channel.readyState),await this._sendMessage(s),this.log.trace("-> sent message %s",this.channel.readyState),t.consume(e)}this.log.trace("-> sent data %s",this.channel.readyState)}async sendReset(){try{await this._sendFlag(Dt.Flag.RESET)}catch(t){this.log.error("failed to send reset - %e",t)}}async sendCloseWrite(t){if(this.channel.readyState!=="open"){this.receiveFinAck.resolve();return}if(await this._sendFlag(Dt.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await oe(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(){this.channel.readyState==="open"&&await this._sendFlag(Dt.Flag.STOP_SENDING)}processIncomingProtobuf(t){let e=Dt.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===Dt.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Dt.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),e.flag===Dt.Flag.RESET&&this.reset(),e.flag===Dt.Flag.STOP_SENDING&&this.remoteCloseRead(),e.flag===Dt.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=Dt.encode({flag:t}),n=Ln.single(e);try{return await this._sendMessage(n,!1),!0}catch(o){this.log.error("could not send flag %s - %e",t.toString(),o)}return!1}};function Kr(r){let{channel:t,direction:e}=r;return new tc({id:e==="inbound"?`i${t.id}`:`r${t.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${e}:${t.id}`),...r})}var Uf="/webrtc",Ze=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??Uf,this.dataChannelOptions=e.dataChannelOptions??{},this.log=t.logger.forComponent("libp2p:webrtc:muxerfactory"),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=Kr({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 ec(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},ec=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??Uf,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=n.id,s=Kr({channel:n,direction:"inbound",onEnd:()=>{this.#t(s,n),this.log("incoming channel %s ended",o)},logger:this.logger,...this.dataChannelOptions});this.streams.push(s),this.metrics?.increment({incoming_stream:!0}),e?.onIncomingStream?.(s)},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),If(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=xs();sink=vs;newStream(){let t=this.peerConnection.createDataChannel(""),e=t.id;this.log.trace("opened outgoing datachannel with channel id %s",e);let n=Kr({channel:t,direction:"outbound",onEnd:()=>{this.#t(n,t),this.log("outgoing channel %s ended",e)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(n),this.metrics?.increment({outgoing_stream:!0}),n}};var Ls=globalThis.RTCPeerConnection,_s=globalThis.RTCSessionDescription,Pf=globalThis.RTCIceCandidate;var rc=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=pt(),this.haveNext=pt()}[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=pt(),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=pt(),await oe(this.readNext.promise,e?.signal,e)}};function Df(){return new rc}var Rs=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var nc=class extends Error{code;constructor(t,e){super(t),this.code=e}},oc=class extends nc{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Of(r,t){let e=Df();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 ht;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new oc("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 ht:d}for(;o.byteLength<i;){let{value:f,done:d}=await Promise.race([n.next(),l]);if(d===!0)throw new Rs("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 Us=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ps=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ds=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Pn(r,t={}){let e=Of(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=ct(t.maxDataLength));let n=t?.lengthDecoder??Jt,o=t?.lengthEncoder??ie;return{read:async i=>{let a=-1,c=new ht;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 Us("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ds("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Ps("message length too long");return e.read(a,i)},write:async(i,a)=>{await e.write(new ht(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new ht(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Os(r,t){let e=Pn(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 $t=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Xe=class extends Error{constructor(t){super(`WebRTC transport error: ${t}`),this.name="WebRTCTransportError"}},zt=class extends Xe{constructor(t="SDP handshake failed"){super(t),this.name="SDPHandshakeFailedError"}};var Ms=class extends Xe{constructor(t,e){super(`Invalid fingerprint "${t}" within ${e}`),this.name="WebRTC/InvalidFingerprintError"}};var Hs=class extends Xe{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},Fs=class extends Xe{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 Ft;(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=()=>cr(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=re((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=>ee(o,r.codec()),r.decode=(o,s)=>te(o,r.codec(),s)})(Ft||(Ft={}));var Vs=async(r,t,e)=>{try{let n=pt();for(Hm(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!==Ft.Type.ICE_CANDIDATE)throw new Gn("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){e.onProgress?.(new $t("webrtc:end-of-ice-candidates")),e.log.trace("end-of-candidates received");continue}let i=new Pf(s);e.log.trace("%s received new ICE candidate %o",e.direction,s);try{e.onProgress?.(new $t("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&&Ks(r)!=="connected")throw n}};function Ks(r){return Nn?r.iceConnectionState:r.connectionState}function Hm(r,t){r[Nn?"oniceconnectionstatechange":"onconnectionstatechange"]=e=>{switch(Ks(r)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new $n("RTCPeerConnection was closed"));break;default:break}}}async function Mf({rtcConfiguration:r,dataChannel:t,signal:e,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=Hf(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",u);let f=u.getPeerId();if(f==null)throw new rt("Relay peer was missing");let d=s.getConnections(Or(f)),m,y=!1;d.length===0?(l?.(new $t("webrtc:dial-relay")),m=await i.dial(u,{signal:e,onProgress:l}),y=!0):(l?.(new $t("webrtc:reuse-relay-connection")),m=d[0]);try{l?.(new $t("webrtc:open-signaling-stream"));let g=await m.newStream($s,{signal:e,runOnLimitedConnection:!0}),h=Os(g).pb(Ft),b=new Ls(r),x=new Ze({logger:c},{peerConnection:b,dataChannelOptions:t});try{let p=b.createDataChannel("init");b.onicecandidate=({candidate:B})=>{let T=JSON.stringify(B?.toJSON()??null);a.trace("initiator sending ICE candidate %o",B),h.write({type:Ft.Type.ICE_CANDIDATE,data:T},{signal:e}).catch(I=>{a.error("error sending ICE candidate",I)})},b.onicecandidateerror=B=>{a.error("initiator ICE candidate error",B)};let S=await b.createOffer().catch(B=>{throw a.error("could not execute createOffer",B),new zt("Failed to set createOffer")});a.trace("initiator send SDP offer %s",S.sdp),l?.(new $t("webrtc:send-sdp-offer")),await h.write({type:Ft.Type.SDP_OFFER,data:S.sdp},{signal:e}),await b.setLocalDescription(S).catch(B=>{throw a.error("could not execute setLocalDescription",B),new zt("Failed to set localDescription")}),l?.(new $t("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let L=await h.read({signal:e});if(L.type!==Ft.Type.SDP_ANSWER)throw new zt("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",L.data);let N=new _s({type:"answer",sdp:L.data});return await b.setRemoteDescription(N).catch(B=>{throw a.error("could not execute setRemoteDescription",B),new zt("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),l?.(new $t("webrtc:read-ice-candidates")),await Vs(b,h,{direction:"initiator",signal:e,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),p.close(),l?.(new $t("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:b,muxerFactory:x}}catch(p){throw a.error("outgoing signaling error",p),b.close(),g.abort(p),p}finally{b.onicecandidate=null,b.onicecandidateerror=null}}finally{if(y)try{await m.close({signal:e})}catch(g){m.abort(g)}}}var Fm=lt(mf.matchers[0],q("p2p-circuit")),Ws=class extends yr{transportManager;shutdownController;constructor(t,e){super(),this.transportManager=t.transportManager,this.shutdownController=e.shutdownController}async listen(){queueMicrotask(()=>{this.safeDispatchEvent("listening")})}getAddrs(){return this.transportManager.getListeners().filter(t=>t!==this).map(t=>t.getAddrs().filter(e=>Fm.exactMatch(e)).map(e=>e.encapsulate("/webrtc"))).flat()}async close(){this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function Ff({peerConnection:r,stream:t,signal:e,connection:n,log:o}){o.trace("new inbound signaling stream");let s=Os(t).pb(Ft);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:Ft.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!==Ft.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 _s({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:Ft.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 Vs(r,s,{direction:"recipient",signal:e,log:o})}catch(a){if(Ks(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=he(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return o.trace("recipient connected to remote address %s",i),{remoteAddress:i}}var Vm="/webrtc",Km="/p2p-circuit",$s="/webrtc-signaling/0.0.1",$m=30*1e3,qs=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,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"})})}[Vn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[wr]=["@libp2p/transport"];[Hc]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle($s,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($s),this._started=!1}createListener(t){return new Ws(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(gf.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 Mf({rtcConfiguration:await ja(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 hr(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??$m),o=new Ls(await ja(this.init.rtcConfiguration)),s=new Ze(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await Ff({peerConnection:o,connection:t,stream:e,signal:n,log:this.log});await e.close({signal:n});let a=new hr(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 Hf(r){let t=r.toString().split(Vm+"/");if(t.length!==2)throw new rt("webrtc protocol was not present in multiaddr");if(!t[0].includes(Km))throw new rt("p2p-circuit protocol was not present in multiaddr");let e=he(t[0]),o=he("/"+t[1]).getPeerId();if(o==null)throw new rt("destination peer id was missing");let s=e.protos().pop();if(s===void 0)throw new rt("invalid multiaddr");return s.name!=="p2p"&&(e=e.encapsulate(`/p2p/${o}`)),{baseAddr:e,peerId:Or(o)}}var Gs=class extends yr{async listen(){throw new Hs("WebRTCTransport.createListener")}getAddrs(){return[]}async close(){}};function sc(){let r=pt(),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 Vf(){let r=sc(),t=sc();return[{source:r.source,sink:t.sink},{source:t.source,sink:r.sink}]}function Wm(r){return r[Symbol.asyncIterator]!=null}function qm(...r){let t=[];for(let e of r)Wm(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=je({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 Kf=qm;function $f(r,...t){if(r==null)throw new Error("Empty pipeline");if(ic(r)){let n=r;r=()=>n.source}else if(qf(r)||Wf(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&ic(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++)ic(e[n])&&(e[n]=zm(e[n]));return Gm(...e)}var Gm=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Wf=r=>r?.[Symbol.asyncIterator]!=null,qf=r=>r?.[Symbol.iterator]!=null,ic=r=>r==null?!1:r.sink!=null&&r.source!=null,zm=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=je({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(Wf(s))o=async function*(){yield*s,n.end()};else if(qf(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Kf(n,o())}return r.source};var $r=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function zs(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function ac(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function cc(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Vt(r,...t){if(!cc(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 lc(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 Gf(r,t){Vt(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var _e=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),zf=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),jm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!jm)throw new Error("Non little-endian hardware is not supported");function Zm(r){if(typeof r!="string")throw new Error(`string expected, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function js(r){if(typeof r=="string")r=Zm(r);else if(cc(r))r=Zs(r);else throw new Error(`Uint8Array expected, got ${typeof r}`);return r}function jf(r,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(r,t)}function Zf(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 uc=(r,t)=>(Object.assign(t,r),t);function fc(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 Zs(r){return Uint8Array.from(r)}function Re(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}var Yf=r=>Uint8Array.from(r.split("").map(t=>t.charCodeAt(0))),Xm=Yf("expand 16-byte k"),Ym=Yf("expand 32-byte k"),Jm=_e(Xm),Jf=_e(Ym),FA=Jf.slice();function D(r,t){return r<<t|r>>>32-t}function hc(r){return r.byteOffset%4===0}var Xs=64,Qm=16,Qf=2**32-1,Xf=new Uint32Array;function tg(r,t,e,n,o,s,i,a){let c=o.length,l=new Uint8Array(Xs),u=_e(l),f=hc(o)&&hc(s),d=f?_e(o):Xf,m=f?_e(s):Xf;for(let y=0;y<c;i++){if(r(t,e,n,u,i,a),i>=Qf)throw new Error("arx: counter overflow");let g=Math.min(Xs,c-y);if(f&&g===Xs){let h=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let b=0,x;b<Qm;b++)x=h+b,m[x]=d[x]^u[b];y+=Xs;continue}for(let h=0,b;h<g;h++)b=y+h,s[b]=o[b]^l[h];y+=g}}function dc(r,t){let{allowShortKeys:e,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=jf({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof r!="function")throw new Error("core must be a function");return zs(o),zs(i),ac(s),ac(e),(a,c,l,u,f=0)=>{Vt(a),Vt(c),Vt(l);let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),Vt(u),zs(f),f<0||f>=Qf)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let m=[],y=a.length,g,h;if(y===32)m.push(g=Zs(a)),h=Jf;else if(y===16&&e)g=new Uint8Array(32),g.set(a),g.set(a,16),h=Jm,m.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${y}`);hc(c)||m.push(c=Zs(c));let b=_e(g);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,b,_e(c.subarray(0,16)),b),c=c.subarray(16)}let x=16-o;if(x!==c.length)throw new Error(`arx: nonce must be ${x} or 16 bytes`);if(x!==12){let S=new Uint8Array(12);S.set(c,s?0:12-c.length),c=S,m.push(c)}let p=_e(c);return tg(r,h,b,p,l,u,f,i),Re(...m),u}}var St=(r,t)=>r[t++]&255|(r[t++]&255)<<8,pc=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=js(t),Vt(t,32);let e=St(t,0),n=St(t,2),o=St(t,4),s=St(t,6),i=St(t,8),a=St(t,10),c=St(t,12),l=St(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]=St(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],y=i[7],g=i[8],h=i[9],b=St(t,e+0),x=St(t,e+2),p=St(t,e+4),S=St(t,e+6),L=St(t,e+8),N=St(t,e+10),B=St(t,e+12),T=St(t,e+14),I=s[0]+(b&8191),H=s[1]+((b>>>13|x<<3)&8191),U=s[2]+((x>>>10|p<<6)&8191),M=s[3]+((p>>>7|S<<9)&8191),V=s[4]+((S>>>4|L<<12)&8191),C=s[5]+(L>>>1&8191),k=s[6]+((L>>>14|N<<2)&8191),v=s[7]+((N>>>11|B<<5)&8191),w=s[8]+((B>>>8|T<<8)&8191),A=s[9]+(T>>>5|o),E=0,_=E+I*a+H*(5*h)+U*(5*g)+M*(5*y)+V*(5*m);E=_>>>13,_&=8191,_+=C*(5*d)+k*(5*f)+v*(5*u)+w*(5*l)+A*(5*c),E+=_>>>13,_&=8191;let R=E+I*c+H*a+U*(5*h)+M*(5*g)+V*(5*y);E=R>>>13,R&=8191,R+=C*(5*m)+k*(5*d)+v*(5*f)+w*(5*u)+A*(5*l),E+=R>>>13,R&=8191;let O=E+I*l+H*c+U*a+M*(5*h)+V*(5*g);E=O>>>13,O&=8191,O+=C*(5*y)+k*(5*m)+v*(5*d)+w*(5*f)+A*(5*u),E+=O>>>13,O&=8191;let K=E+I*u+H*l+U*c+M*a+V*(5*h);E=K>>>13,K&=8191,K+=C*(5*g)+k*(5*y)+v*(5*m)+w*(5*d)+A*(5*f),E+=K>>>13,K&=8191;let F=E+I*f+H*u+U*l+M*c+V*a;E=F>>>13,F&=8191,F+=C*(5*h)+k*(5*g)+v*(5*y)+w*(5*m)+A*(5*d),E+=F>>>13,F&=8191;let W=E+I*d+H*f+U*u+M*l+V*c;E=W>>>13,W&=8191,W+=C*a+k*(5*h)+v*(5*g)+w*(5*y)+A*(5*m),E+=W>>>13,W&=8191;let j=E+I*m+H*d+U*f+M*u+V*l;E=j>>>13,j&=8191,j+=C*c+k*a+v*(5*h)+w*(5*g)+A*(5*y),E+=j>>>13,j&=8191;let st=E+I*y+H*m+U*d+M*f+V*u;E=st>>>13,st&=8191,st+=C*l+k*c+v*a+w*(5*h)+A*(5*g),E+=st>>>13,st&=8191;let it=E+I*g+H*y+U*m+M*d+V*f;E=it>>>13,it&=8191,it+=C*u+k*l+v*c+w*a+A*(5*h),E+=it>>>13,it&=8191;let ut=E+I*h+H*g+U*y+M*m+V*d;E=ut>>>13,ut&=8191,ut+=C*f+k*u+v*l+w*c+A*a,E+=ut>>>13,ut&=8191,E=(E<<2)+E|0,E=E+_|0,_=E&8191,E=E>>>13,R+=E,s[0]=_,s[1]=R,s[2]=O,s[3]=K,s[4]=F,s[5]=W,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;Re(n)}update(t){lc(this);let{buffer:e,blockLen:n}=this;t=js(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(){Re(this.h,this.r,this.buffer,this.pad)}digestInto(t){lc(this),Gf(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(js(n)).digest(),e=r(new Uint8Array(32));return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=n=>r(n),t}var th=eg(r=>new pc(r));function nh(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],y=t[4],g=t[5],h=t[6],b=t[7],x=o,p=e[0],S=e[1],L=e[2],N=i,B=a,T=c,I=l,H=u,U=f,M=d,V=m,C=y,k=g,v=h,w=b,A=x,E=p,_=S,R=L;for(let K=0;K<s;K+=2)N=N+H|0,A=D(A^N,16),C=C+A|0,H=D(H^C,12),N=N+H|0,A=D(A^N,8),C=C+A|0,H=D(H^C,7),B=B+U|0,E=D(E^B,16),k=k+E|0,U=D(U^k,12),B=B+U|0,E=D(E^B,8),k=k+E|0,U=D(U^k,7),T=T+M|0,_=D(_^T,16),v=v+_|0,M=D(M^v,12),T=T+M|0,_=D(_^T,8),v=v+_|0,M=D(M^v,7),I=I+V|0,R=D(R^I,16),w=w+R|0,V=D(V^w,12),I=I+V|0,R=D(R^I,8),w=w+R|0,V=D(V^w,7),N=N+U|0,R=D(R^N,16),v=v+R|0,U=D(U^v,12),N=N+U|0,R=D(R^N,8),v=v+R|0,U=D(U^v,7),B=B+M|0,A=D(A^B,16),w=w+A|0,M=D(M^w,12),B=B+M|0,A=D(A^B,8),w=w+A|0,M=D(M^w,7),T=T+V|0,E=D(E^T,16),C=C+E|0,V=D(V^C,12),T=T+V|0,E=D(E^T,8),C=C+E|0,V=D(V^C,7),I=I+H|0,_=D(_^I,16),k=k+_|0,H=D(H^k,12),I=I+H|0,_=D(_^I,8),k=k+_|0,H=D(H^k,7);let O=0;n[O++]=i+N|0,n[O++]=a+B|0,n[O++]=c+T|0,n[O++]=l+I|0,n[O++]=u+H|0,n[O++]=f+U|0,n[O++]=d+M|0,n[O++]=m+V|0,n[O++]=y+C|0,n[O++]=g+k|0,n[O++]=h+v|0,n[O++]=b+w|0,n[O++]=x+A|0,n[O++]=p+E|0,n[O++]=S+_|0,n[O++]=L+R|0}function rg(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],y=t[6],g=t[7],h=e[0],b=e[1],x=e[2],p=e[3];for(let L=0;L<20;L+=2)o=o+c|0,h=D(h^o,16),d=d+h|0,c=D(c^d,12),o=o+c|0,h=D(h^o,8),d=d+h|0,c=D(c^d,7),s=s+l|0,b=D(b^s,16),m=m+b|0,l=D(l^m,12),s=s+l|0,b=D(b^s,8),m=m+b|0,l=D(l^m,7),i=i+u|0,x=D(x^i,16),y=y+x|0,u=D(u^y,12),i=i+u|0,x=D(x^i,8),y=y+x|0,u=D(u^y,7),a=a+f|0,p=D(p^a,16),g=g+p|0,f=D(f^g,12),a=a+f|0,p=D(p^a,8),g=g+p|0,f=D(f^g,7),o=o+l|0,p=D(p^o,16),y=y+p|0,l=D(l^y,12),o=o+l|0,p=D(p^o,8),y=y+p|0,l=D(l^y,7),s=s+u|0,h=D(h^s,16),g=g+h|0,u=D(u^g,12),s=s+u|0,h=D(h^s,8),g=g+h|0,u=D(u^g,7),i=i+f|0,b=D(b^i,16),d=d+b|0,f=D(f^d,12),i=i+f|0,b=D(b^i,8),d=d+b|0,f=D(f^d,7),a=a+c|0,x=D(x^a,16),m=m+x|0,c=D(c^m,12),a=a+c|0,x=D(x^a,8),m=m+x|0,c=D(c^m,7);let S=0;n[S++]=o,n[S++]=s,n[S++]=i,n[S++]=a,n[S++]=h,n[S++]=b,n[S++]=x,n[S++]=p}var ng=dc(nh,{counterRight:!1,counterLength:4,allowShortKeys:!1}),og=dc(nh,{counterRight:!1,counterLength:8,extendNonceFn:rg,allowShortKeys:!1});var sg=new Uint8Array(16),eh=(r,t)=>{r.update(t);let e=t.length%16;e&&r.update(sg.subarray(e))},ig=new Uint8Array(32);function rh(r,t,e,n,o){let s=r(t,e,ig),i=th.create(s);o&&eh(i,o),eh(i,n);let a=new Uint8Array(16),c=zf(a);fc(c,0,BigInt(o?o.length:0),!0),fc(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return Re(s,a),l}var oh=r=>(t,e,n)=>(Vt(t,32),Vt(e),{encrypt(s,i){let a=s.length,c=a+16;i?Vt(i,c):i=new Uint8Array(c),r(t,e,s,i,1);let l=rh(r,t,e,i.subarray(0,-16),n);return i.set(l,a),Re(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?Vt(i,c):i=new Uint8Array(c);let l=s.subarray(0,-16),u=s.subarray(-16),f=rh(r,t,e,l,n);if(!Zf(u,f))throw new Error("invalid tag");return r(t,e,l,i,1),Re(f),i}}),mc=uc({blockSize:64,nonceLength:12,tagLength:16},oh(ng)),ZA=uc({blockSize:64,nonceLength:24,tagLength:16},oh(og));function ih(r,t,e){return Jr(r),e===void 0&&(e=new Uint8Array(r.outputLen)),Dr(r,De(e),De(t))}var gc=new Uint8Array([0]),sh=new Uint8Array;function ah(r,t,e,n=32){if(Jr(r),Zn(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);e===void 0&&(e=sh);let s=new Uint8Array(o*r.outputLen),i=Dr.create(r,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)gc[0]=l+1,a.update(l===0?sh:c).update(e).update(gc).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),gc.fill(0),s.slice(0,n)}var yc={hashSHA256(r){return ce(r.subarray())},getHKDF(r,t){let e=ih(ce,t,r),o=ah(ce,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=on.utils.randomPrivateKey();return{publicKey:on.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:on.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,t){return on.getSharedSecret(r.subarray(),t.subarray())},chaCha20Poly1305Encrypt(r,t,e,n){return mc(n,t,e).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,t,e,n,o){return mc(n,t,e).decrypt(r.subarray(),o)}};var ch=yc;function lh(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 Wr=r=>{let t=yt(2);return t[0]=r>>8,t[1]=r,t};Wr.bytes=2;var Dn=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)};Dn.bytes=2;function uh(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 wc(r,t){!t.enabled||!$r||(r?(t(`LOCAL_STATIC_PUBLIC_KEY ${X(r.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${X(r.privateKey,"hex")}`)):t("Missing local static keys."))}function bc(r,t){!t.enabled||!$r||(r?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${X(r.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${X(r.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function fh(r,t){!t.enabled||!$r||t(r?`REMOTE_STATIC_PUBLIC_KEY ${X(r.subarray(),"hex")}`:"Missing remote static public key.")}function xc(r,t){!t.enabled||!$r||t(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${X(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function vc(r,t,e){!e.enabled||!$r||(e(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&X(r.k,"hex")}`),e(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&X(t.k,"hex")}`))}var qr=class r extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var ag=0,cg=4294967295,lg="Cipherstate has reached maximum n, a new handshake must be performed",Ys=class{n;bytes;view;constructor(t=ag){this.n=t,this.bytes=gt(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(lg)}};var mr=gt(0),Gr=class{k;n;crypto;constructor(t,e=void 0,n=0){this.crypto=t,this.k=e,this.n=new Ys(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}},Ec=class{cs;ck;h;crypto;constructor(t,e){this.crypto=t;let n=Q(e,"utf-8");this.h=ug(t,n),this.ck=this.h,this.cs=new Gr(t)}mixKey(t){let[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new Gr(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new ht(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,mr);return[new Gr(this.crypto,t),new Gr(this.crypto,e)]}},Ac=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 Ec(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()}},On=class extends Ac{writeMessageA(t){return new ht(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let e=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new ht(e,n,this.ss.encryptAndHash(t))}writeMessageC(t){let e=this.writeS();return this.writeSE(),new ht(e,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(e){throw new qr(`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 qr(`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 qr(`handshake stage 2 validation fail: ${e.message}`)}}};function ug(r,t){if(t.length<=32){let e=gt(32);return e.set(t),e}else return r.hash(t)}var Js;(function(r){let t;r.codec=()=>(t==null&&(t=re((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=>ee(e,r.codec()),r.decode=e=>te(e,r.codec())})(Js||(Js={}));var Mn;(function(r){let t;r.codec=()=>(t==null&&(t=re((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),Js.codec().encode(e.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={identityKey:gt(0),identitySig:gt(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=Js.codec().decode(e,e.uint32());break}default:{e.skipType(i&7);break}}}return o})),t),r.encode=e=>ee(e,r.codec()),r.decode=e=>te(e,r.codec())})(Mn||(Mn={}));async function Bc(r,t,e){let n=await r.sign(hh(t));return Mn.encode({identityKey:kr(r.publicKey),identitySig:n,extensions:e})}async function Sc(r,t,e){try{let n=Mn.decode(r),o=vn(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=hh(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Kn(n.message)}}function hh(r){let t=Q("noise-libp2p-static-key:");return r instanceof Uint8Array?bt([t,r],t.length+r.length):(r.prepend(t),r)}async function dh(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Bc(s,a.publicKey,l),f=new On({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});wc(f.s,e),e.trace("Stage 0 - Initiator starting to send first message."),await n.write(f.writeMessageA(mr),t),e.trace("Stage 0 - Initiator finished sending first message."),bc(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."),xc(f.re,e),fh(f.rs,e),e.trace("Initiator going to check remote's signature...");let m=await Sc(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[y,g]=f.ss.split();return vc(y,g,e),{payload:m,encrypt:h=>y.encryptWithAd(mr,h),decrypt:(h,b)=>g.decryptWithAd(mr,h,b)}}async function ph(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Bc(s,a.publicKey,l),f=new On({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});wc(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."),xc(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."),bc(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 Sc(d,f.rs,c),[y,g]=f.ss.split();return vc(y,g,e),{payload:m,encrypt:h=>g.encryptWithAd(mr,h),decrypt:(h,b)=>y.decryptWithAd(mr,h,b)}}var gh=16;function yh(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 ht(Wr(i.byteLength),i)}}}function wh(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-gh<o)throw new Error("Invalid chunk");let i=n.sublist(o,s),a=n.subarray(o,s-gh);try{let c=r.decrypt(i,a);t?.decryptedPackets.increment(),yield c}catch(c){throw t?.decryptErrors.increment(),c}}}}var Qs=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??ch;this.crypto=lh(c),this.extensions=o,this.metrics=a?uh(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??gt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[wr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,e){let n=Pn(t,{lengthEncoder:Wr,lengthDecoder:Dn,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=vn(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Ba(i)}}async secureInbound(t,e){let n=Pn(t,{lengthEncoder:Wr,lengthDecoder:Dn,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=vn(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Ba(i)}}async performHandshakeInitiator(t,e,n,o){let s;try{s=await dh({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 ph({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]=Vf(),s=t.unwrap();return await $f(n,yh(e,this.metrics),s,i=>pr(i,{lengthDecoder:Dn}),wh(e,this.metrics),n),o}};function bh(r={}){return t=>new Qs(t,r)}var Cc=Object.values(ir).map(r=>r.decoder).reduce((r,t)=>r.or(t)),fg=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function xh(r){return r?.match(fg)?.groups?.fingerprint}function Ic(r){let e=r.stringTuples().filter(n=>n[0]===Sh).map(n=>n[1])[0];if(e===void 0||e==="")throw new rt(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return e}function hg(r){return Wt.decode(Cc.decode(r))}function dg(r){let t=hg(Ic(r)),e=pg(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 Ms(n,r.toString());return`${e} ${o.join(":").toUpperCase()}`}function vh(r){let t=r.split(":").map(o=>parseInt(o,16)),e=Uint8Array.from(t),n=kt(Ee.code,e);return he(`/certhash/${an.encode(n.bytes)}`)}function pg(r){switch(r){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new Fs(r)}}function Eh(r,t){let{host:e,port:n,family:o}=r.toOptions(),s=dg(r);return{type:"answer",sdp:`v=0
6
+ `)}`:`${e} :`}};ou=qe;D.Constructed=ou;qe.NAME="CONSTRUCTED";var Co=class extends Nt{fromBER(t,e,n){return e}toBER(t){return oe}};Co.override="EndOfContentValueBlock";var su,ko=class extends At{constructor(t={}){super(t,Co),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};su=ko;D.EndOfContent=su;ko.NAME=dn;var iu,_r=class extends At{constructor(t={}){super(t,Nt),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}`}};iu=_r;D.Null=iu;_r.NAME="NULL";var To=class extends ke(Nt){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=q.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=q.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,Ea.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};To.NAME="BooleanValueBlock";var au,Lo=class extends At{constructor(t={}){super(t,To),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}`}};au=Lo;D.Boolean=au;Lo.NAME="BOOLEAN";var No=class extends ke(le){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=le.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===dn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==tu)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?le.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};No.NAME="OctetStringValueBlock";var cu,_o=class r extends At{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},No),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=is(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?qe.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${q.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 q.BufferSourceConverter.concat(t)}};cu=_o;D.OctetString=cu;_o.NAME=tu;var Ro=class extends ke(le){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=le.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===dn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==eu)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=q.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=is(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 le.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return oe;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}}};Ro.NAME="BitStringValueBlock";var lu,Rr=class extends At{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},Ro),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 qe.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)}`}}};lu=Rr;D.BitString=lu;Rr.NAME=eu;var uu;function D0(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=xo(new Uint8Array([l%10]),s);break;default:s[i-f]=l%10}}return e[0]>0&&(s=xo(e,s)),s}function Ql(r){if(r>=fn.length)for(let t=fn.length;t<=r;t++){let e=new Uint8Array([0]),n=fn[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=xo(e,n)),fn.push(n)}return fn[r]}function P0(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 pn=class extends ke(Nt){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=Ea.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Xl(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=P0(Ql(n),e),i="-";break;default:e=D0(e,Ql(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(i+=Jl.charAt(e[c]));return a===!1&&(i+=Jl.charAt(0)),i}};uu=pn;pn.NAME="IntegerValueBlock";Object.defineProperty(uu.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var fu,St=class r extends At{constructor(t={}){super(t,pn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Eo(),BigInt(this.valueBlock.toString())}static fromBigInt(t){Eo();let e=BigInt(t),n=new hn,o=e.toString(16).replace(/^-/,""),s=new Uint8Array(q.Convert.FromHex(o));if(e<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${q.Convert.ToHex(a)}`)+e,u=q.BufferSourceConverter.toUint8Array(q.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()}`}};fu=St;D.Integer=fu;St.NAME="INTEGER";var hu,Uo=class extends St{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};hu=Uo;D.Enumerated=hu;Uo.NAME="ENUMERATED";var mn=class extends ke(Nt){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=q.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=ur(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){Eo();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=We(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",oe;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=q.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}}};mn.NAME="sidBlock";var Do=class extends Nt{constructor({value:t=Dr,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new mn;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,oe;e.push(o)}return va(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 mn;if(o>Number.MAX_SAFE_INTEGER){Eo();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}};Do.NAME="ObjectIdentifierValueBlock";var du,Ur=class extends At{constructor(t={}){super(t,Do),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()}}};du=Ur;D.ObjectIdentifier=du;Ur.NAME="OBJECT IDENTIFIER";var gn=class extends ke(Se){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let o=q.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=ur(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=We(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",oe;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=q.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};gn.NAME="relativeSidBlock";var Po=class extends Nt{constructor({value:t=Dr,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new gn;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,oe;n.push(s)}return va(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 gn;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}};Po.NAME="RelativeObjectIdentifierValueBlock";var pu,Oo=class extends At{constructor(t={}){super(t,Po),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()}}};pu=Oo;D.RelativeObjectIdentifier=pu;Oo.NAME="RelativeObjectIdentifier";var mu,Be=class extends qe{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};mu=Be;D.Sequence=mu;Be.NAME="SEQUENCE";var gu,Mo=class extends qe{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};gu=Mo;D.Set=gu;Mo.NAME="SET";var Ho=class extends ke(Nt){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=Dr}toJSON(){return{...super.toJSON(),value:this.value}}};Ho.NAME="StringValueBlock";var Fo=class extends Ho{};Fo.NAME="SimpleStringValueBlock";var Dt=class extends So{constructor({...t}={}){super(t,Fo)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,q.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}};Dt.NAME="SIMPLE STRING";var Vo=class extends Dt{fromBuffer(t){this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=q.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=q.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf8String(t)),this.valueBlock.value=t}};Vo.NAME="Utf8StringValueBlock";var yu,Ie=class extends Vo{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};yu=Ie;D.Utf8String=yu;Ie.NAME="UTF8String";var Ko=class extends Dt{fromBuffer(t){this.valueBlock.value=q.Convert.ToUtf16String(t),this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf16String(t))}};Ko.NAME="BmpStringValueBlock";var wu,$o=class extends Ko{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};wu=$o;D.BmpString=wu;$o.NAME="BMPString";var Go=class extends Dt{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=We(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}};Go.NAME="UniversalStringValueBlock";var bu,Wo=class extends Go{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};bu=Wo;D.UniversalString=bu;Wo.NAME="UniversalString";var xu,qo=class extends Dt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};xu=qo;D.NumericString=xu;qo.NAME="NumericString";var Eu,zo=class extends Dt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Eu=zo;D.PrintableString=Eu;zo.NAME="PrintableString";var vu,jo=class extends Dt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};vu=jo;D.TeletexString=vu;jo.NAME="TeletexString";var Au,Zo=class extends Dt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Au=Zo;D.VideotexString=Au;Zo.NAME="VideotexString";var Su,Xo=class extends Dt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Su=Xo;D.IA5String=Su;Xo.NAME="IA5String";var Bu,Yo=class extends Dt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Bu=Yo;D.GraphicString=Bu;Yo.NAME="GraphicString";var Iu,yn=class extends Dt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Iu=yn;D.VisibleString=Iu;yn.NAME="VisibleString";var Cu,Jo=class extends Dt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Cu=Jo;D.GeneralString=Cu;Jo.NAME="GeneralString";var ku,Qo=class extends Dt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};ku=Qo;D.CharacterString=ku;Qo.NAME="CharacterString";var Tu,wn=class extends yn{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,q.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]=Ht(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=Ht(this.month,2),e[2]=Ht(this.day,2),e[3]=Ht(this.hour,2),e[4]=Ht(this.minute,2),e[5]=Ht(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}}};Tu=wn;D.UTCTime=Tu;wn.NAME="UTCTime";var Lu,ts=class extends wn{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 y=parseInt(m.substring(0,2),10);if(isNaN(y.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*y,m.length===4){if(y=parseInt(m.substring(2,4),10),isNaN(y.valueOf()))throw new Error("Wrong input string for conversion");c=f*y}}}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(Ht(this.year,4)),e.push(Ht(this.month,2)),e.push(Ht(this.day,2)),e.push(Ht(this.hour,2)),e.push(Ht(this.minute,2)),e.push(Ht(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(Ht(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Lu=ts;D.GeneralizedTime=Lu;ts.NAME="GeneralizedTime";var Nu,es=class extends Ie{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Nu=es;D.DATE=Nu;es.NAME="DATE";var _u,rs=class extends Ie{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};_u=rs;D.TimeOfDay=_u;rs.NAME="TimeOfDay";var Ru,ns=class extends Ie{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Ru=ns;D.DateTime=Ru;ns.NAME="DateTime";var Uu,os=class extends Ie{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Uu=os;D.Duration=Uu;os.NAME="Duration";var Du,ss=class extends Ie{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Du=ss;D.TIME=Du;ss.NAME="TIME";function X(r,t="utf8"){let e=mo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var bn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},as=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Pu={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new as("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=Pu;async function Ou(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 M0(t);return{privateKey:e[0],publicKey:e[1]}}async function Mu(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 Hu(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 M0(r){if(r.privateKey==null||r.publicKey==null)throw new ot("Private and public key are required");return Promise.all([ze.get().subtle.exportKey("jwk",r.privateKey),ze.get().subtle.exportKey("jwk",r.publicKey)])}function Ba(r){if(r.kty!=="RSA")throw new ot("invalid key type");if(r.n==null)throw new ot("invalid key modulus");return Q(r.n,"base64url").length*8}var Pr=class{type="RSA";_key;_raw;_multihash;constructor(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=xn.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return Et.createV1(114,this._multihash)}toString(){return st.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Ut(this.raw,t.raw)}verify(t,e){return Hu(this._key,e,t)}},En=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=xn.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Ut(this.raw,t.raw)}sign(t){return Mu(this._key,t)}};var cs=8192,Ia=18;function Fu(r){let{result:t}=Sa(r),e=t.valueBlock.value;return{n:ue(e[1]),e:ue(e[2]),d:ue(e[3]),p:ue(e[4]),q:ue(e[5]),dp:ue(e[6]),dq:ue(e[7]),qi:ue(e[8]),kty:"RSA",alg:"RS256"}}function H0(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 ot("JWK was missing components");let e=new Be({value:[new St({value:0}),St.fromBigInt(fe(Q(r.n,"base64url"))),St.fromBigInt(fe(Q(r.e,"base64url"))),St.fromBigInt(fe(Q(r.d,"base64url"))),St.fromBigInt(fe(Q(r.p,"base64url"))),St.fromBigInt(fe(Q(r.q,"base64url"))),St.fromBigInt(fe(Q(r.dp,"base64url"))),St.fromBigInt(fe(Q(r.dq,"base64url"))),St.fromBigInt(fe(Q(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function Vu(r){let{result:t}=Sa(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:ue(e[0]),e:ue(e[1])}}function Ca(r){if(r.n==null||r.e==null)throw new ot("JWK was missing components");let e=new Be({value:[new Be({value:[new Ur({value:"1.2.840.113549.1.1.1"}),new _r]}),new Rr({valueHex:new Be({value:[St.fromBigInt(fe(Q(r.n,"base64url"))),St.fromBigInt(fe(Q(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function ue(r){let t=r.valueBlock.valueHexView;for(;t[0]===0;)t=t.subarray(1);return X(t,"base64url")}function fe(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 Ku(r){let t=Fu(r);return $u(t)}function ka(r){let t=Vu(r);if(Ba(t)>cs)throw new yr("Key size is too large");let e=ce(ae.encode({Type:wt.RSA,Data:r})),n=kt(Ia,e);return new Pr(t,n)}function $u(r){if(Ba(r)>cs)throw new ot("Key size is too large");let t=Wu(r),e=ce(ae.encode({Type:wt.RSA,Data:Ca(t.publicKey)})),n=kt(Ia,e);return new En(t.privateKey,new Pr(t.publicKey,n))}async function Gu(r){if(r>cs)throw new ot("Key size is too large");let t=await Ou(r),e=ce(ae.encode({Type:wt.RSA,Data:Ca(t.publicKey)})),n=kt(Ia,e);return new En(t.privateKey,new Pr(t.publicKey,n))}function Wu(r){if(r==null)throw new ot("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var ls=class extends Br{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,tn(t);let n=Pe(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 Sr(this),this.iHash.update(t),this}digestInto(t){Sr(this),Ar(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()}},Or=(r,t,e)=>new ls(r,t).update(e).digest();Or.create=(r,t)=>new ls(r,t);function qu(r){r.lowS!==void 0&&Yt("lowS",r.lowS),r.prehash!==void 0&&Yt("prehash",r.prehash)}function F0(r){let t=on(r);qt(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("invalid 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("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:V0,hexToBytes:K0}=so,Ta=class extends Error{constructor(t=""){super(t)}},Te={Err:Ta,_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=er(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?er(o.length/2|128):"";return er(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<Le)throw new t("integer: negative integers are not allowed");let e=er(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");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 V0(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Te,o=typeof r=="string"?K0(r):r;Cr(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)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},Le=BigInt(0),xt=BigInt(1),ux=BigInt(2),zu=BigInt(3),fx=BigInt(4);function $0(r){let t=F0(r),{Fp:e}=t,n=Ve(t.n,t.nBitLength),o=t.toBytes||((g,h,b)=>{let x=h.toAffine();return Ee(Uint8Array.from([4]),e.toBytes(x.x),e.toBytes(x.y))}),s=t.fromBytes||(g=>{let h=g.subarray(1),b=e.fromBytes(h.subarray(0,e.BYTES)),x=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:b,y:x}});function i(g){let{a:h,b}=t,x=e.sqr(g),p=e.mul(x,g);return e.add(e.add(p,e.mul(g,h)),b)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return rn(g,xt,t.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:b,wrapPrivateKey:x,n:p}=t;if(h&&typeof g!="bigint"){if(He(g)&&(g=we(g)),typeof g!="string"||!h.includes(g.length))throw new Error("invalid private key");g=g.padStart(b*2,"0")}let B;try{B=typeof g=="bigint"?g:be(it("private key",g,b))}catch{throw new Error("invalid private key, expected hex or "+b+" bytes, got "+typeof g)}return x&&(B=Z(B,p)),vt("private key",B,xt,p),B}function l(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let u=nr((g,h)=>{let{px:b,py:x,pz:p}=g;if(e.eql(p,e.ONE))return{x:b,y:x};let B=g.is0();h==null&&(h=B?e.ONE:e.inv(p));let N=e.mul(b,h),L=e.mul(x,h),S=e.mul(p,h);if(B)return{x:e.ZERO,y:e.ZERO};if(!e.eql(S,e.ONE))throw new Error("invZ was invalid");return{x:N,y:L}}),f=nr(g=>{if(g.is0()){if(t.allowInfinityPoint&&!e.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:h,y:b}=g.toAffine();if(!e.isValid(h)||!e.isValid(b))throw new Error("bad point: x or y not FE");let x=e.sqr(b),p=i(h);if(!e.eql(x,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,b,x){if(this.px=h,this.py=b,this.pz=x,h==null||!e.isValid(h))throw new Error("x required");if(b==null||!e.isValid(b))throw new Error("y required");if(x==null||!e.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:b,y:x}=h||{};if(!h||!e.isValid(b)||!e.isValid(x))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(b)&&p(x)?d.ZERO:new d(b,x,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let b=e.invertBatch(h.map(x=>x.pz));return h.map((x,p)=>x.toAffine(b[p])).map(d.fromAffine)}static fromHex(h){let b=d.fromAffine(s(it("pointHex",h)));return b.assertValidity(),b}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,b){return lo(d,n,h,b)}_setWindowSize(h){y.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:b,py:x,pz:p}=this,{px:B,py:N,pz:L}=h,S=e.eql(e.mul(b,L),e.mul(B,p)),T=e.eql(e.mul(x,L),e.mul(N,p));return S&&T}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b}=t,x=e.mul(b,zu),{px:p,py:B,pz:N}=this,L=e.ZERO,S=e.ZERO,T=e.ZERO,C=e.mul(p,p),H=e.mul(B,B),U=e.mul(N,N),M=e.mul(p,B);return M=e.add(M,M),T=e.mul(p,N),T=e.add(T,T),L=e.mul(h,T),S=e.mul(x,U),S=e.add(L,S),L=e.sub(H,S),S=e.add(H,S),S=e.mul(L,S),L=e.mul(M,L),T=e.mul(x,T),U=e.mul(h,U),M=e.sub(C,U),M=e.mul(h,M),M=e.add(M,T),T=e.add(C,C),C=e.add(T,C),C=e.add(C,U),C=e.mul(C,M),S=e.add(S,C),U=e.mul(B,N),U=e.add(U,U),C=e.mul(U,M),L=e.sub(L,C),T=e.mul(U,H),T=e.add(T,T),T=e.add(T,T),new d(L,S,T)}add(h){l(h);let{px:b,py:x,pz:p}=this,{px:B,py:N,pz:L}=h,S=e.ZERO,T=e.ZERO,C=e.ZERO,H=t.a,U=e.mul(t.b,zu),M=e.mul(b,B),V=e.mul(x,N),I=e.mul(p,L),k=e.add(b,x),E=e.add(B,N);k=e.mul(k,E),E=e.add(M,V),k=e.sub(k,E),E=e.add(b,p);let w=e.add(B,L);return E=e.mul(E,w),w=e.add(M,I),E=e.sub(E,w),w=e.add(x,p),S=e.add(N,L),w=e.mul(w,S),S=e.add(V,I),w=e.sub(w,S),C=e.mul(H,E),S=e.mul(U,I),C=e.add(S,C),S=e.sub(V,C),C=e.add(V,C),T=e.mul(S,C),V=e.add(M,M),V=e.add(V,M),I=e.mul(H,I),E=e.mul(U,E),V=e.add(V,I),I=e.sub(M,I),I=e.mul(H,I),E=e.add(E,I),M=e.mul(V,E),T=e.add(T,M),M=e.mul(w,E),S=e.mul(k,S),S=e.sub(S,M),M=e.mul(k,V),C=e.mul(w,C),C=e.add(C,M),new d(S,T,C)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return y.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){let{endo:b,n:x}=t;vt("scalar",h,Le,x);let p=d.ZERO;if(h===Le)return p;if(this.is0()||h===xt)return this;if(!b||y.hasPrecomputes(this))return y.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:B,k1:N,k2neg:L,k2:S}=b.splitScalar(h),T=p,C=p,H=this;for(;N>Le||S>Le;)N&xt&&(T=T.add(H)),S&xt&&(C=C.add(H)),H=H.double(),N>>=xt,S>>=xt;return B&&(T=T.negate()),L&&(C=C.negate()),C=new d(e.mul(C.px,b.beta),C.py,C.pz),T.add(C)}multiply(h){let{endo:b,n:x}=t;vt("scalar",h,xt,x);let p,B;if(b){let{k1neg:N,k1:L,k2neg:S,k2:T}=b.splitScalar(h),{p:C,f:H}=this.wNAF(L),{p:U,f:M}=this.wNAF(T);C=y.constTimeNegate(N,C),U=y.constTimeNegate(S,U),U=new d(e.mul(U.px,b.beta),U.py,U.pz),p=C.add(U),B=H.add(M)}else{let{p:N,f:L}=this.wNAF(h);p=N,B=L}return d.normalizeZ([p,B])[0]}multiplyAndAddUnsafe(h,b,x){let p=d.BASE,B=(L,S)=>S===Le||S===xt||!L.equals(p)?L.multiplyUnsafe(S):L.multiply(S),N=B(this,b).add(B(h,x));return N.is0()?void 0:N}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:b}=t;if(h===xt)return!0;if(b)return b(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:b}=t;return h===xt?this:b?b(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return Yt("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return Yt("isCompressed",h),we(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,y=co(d,t.endo?Math.ceil(m/2):m);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function G0(r){let t=on(r);return qt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function ju(r){let t=G0(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(I){return Z(I,n)}function a(I){return io(I,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=$0({...t,toBytes(I,k,E){let w=k.toAffine(),A=e.toBytes(w.x),v=Ee;return Yt("isCompressed",E),E?v(Uint8Array.from([k.hasEvenY()?2:3]),A):v(Uint8Array.from([4]),A,e.toBytes(w.y))},fromBytes(I){let k=I.length,E=I[0],w=I.subarray(1);if(k===o&&(E===2||E===3)){let A=be(w);if(!rn(A,xt,e.ORDER))throw new Error("Point is not on curve");let v=u(A),_;try{_=e.sqrt(v)}catch(K){let F=K instanceof Error?": "+K.message:"";throw new Error("Point is not on curve"+F)}let R=(_&xt)===xt;return(E&1)===1!==R&&(_=e.neg(_)),{x:A,y:_}}else if(k===s&&E===4){let A=e.fromBytes(w.subarray(0,e.BYTES)),v=e.fromBytes(w.subarray(e.BYTES,2*e.BYTES));return{x:A,y:v}}else{let A=o,v=s;throw new Error("invalid Point, expected length of "+A+", or uncompressed "+v+", got "+k)}}}),d=I=>we(Fe(I,t.nByteLength));function m(I){let k=n>>xt;return I>k}function y(I){return m(I)?i(-I):I}let g=(I,k,E)=>be(I.slice(k,E));class h{constructor(k,E,w){this.r=k,this.s=E,this.recovery=w,this.assertValidity()}static fromCompact(k){let E=t.nByteLength;return k=it("compactSignature",k,E*2),new h(g(k,0,E),g(k,E,2*E))}static fromDER(k){let{r:E,s:w}=Te.toSig(it("DER",k));return new h(E,w)}assertValidity(){vt("r",this.r,xt,n),vt("s",this.s,xt,n)}addRecoveryBit(k){return new h(this.r,this.s,k)}recoverPublicKey(k){let{r:E,s:w,recovery:A}=this,v=L(it("msgHash",k));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let _=A===2||A===3?E+t.n:E;if(_>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let R=A&1?"03":"02",O=c.fromHex(R+d(_)),K=a(_),F=i(-v*K),G=i(w*K),j=c.BASE.multiplyAndAddUnsafe(O,F,G);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 rr(this.toDERHex())}toDERHex(){return Te.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return rr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let b={isValidPrivateKey(I){try{return l(I),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let I=Di(t.n);return vl(t.randomBytes(I),t.n)},precompute(I=8,k=c.BASE){return k._setWindowSize(I),k.multiply(BigInt(3)),k}};function x(I,k=!0){return c.fromPrivateKey(I).toRawBytes(k)}function p(I){let k=He(I),E=typeof I=="string",w=(k||E)&&I.length;return k?w===o||w===s:E?w===2*o||w===2*s:I instanceof c}function B(I,k,E=!0){if(p(I))throw new Error("first arg must be private key");if(!p(k))throw new Error("second arg must be public key");return c.fromHex(k).multiply(l(I)).toRawBytes(E)}let N=t.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");let k=be(I),E=I.length*8-t.nBitLength;return E>0?k>>BigInt(E):k},L=t.bits2int_modN||function(I){return i(N(I))},S=nn(t.nBitLength);function T(I){return vt("num < 2^"+t.nBitLength,I,Le,S),Fe(I,t.nByteLength)}function C(I,k,E=H){if(["recovered","canonical"].some(ct=>ct in E))throw new Error("sign() legacy options not supported");let{hash:w,randomBytes:A}=t,{lowS:v,prehash:_,extraEntropy:R}=E;v==null&&(v=!0),I=it("msgHash",I),qu(E),_&&(I=it("prehashed msgHash",w(I)));let O=L(I),K=l(k),F=[T(K),T(O)];if(R!=null&&R!==!1){let ct=R===!0?A(e.BYTES):R;F.push(it("extraEntropy",ct))}let G=Ee(...F),j=O;function at(ct){let ft=N(ct);if(!f(ft))return;let It=a(ft),Ot=c.BASE.multiply(ft).toAffine(),Rt=i(Ot.x);if(Rt===Le)return;let ie=i(It*i(j+Rt*K));if(ie===Le)return;let de=(Ot.x===Rt?0:2)|Number(Ot.y&xt),Zr=ie;return v&&m(ie)&&(Zr=y(ie),de^=1),new h(Rt,Zr,de)}return{seed:G,k2sig:at}}let H={lowS:t.lowS,prehash:!1},U={lowS:t.lowS,prehash:!1};function M(I,k,E=H){let{seed:w,k2sig:A}=C(I,k,E),v=t;return Li(v.hash.outputLen,v.nByteLength,v.hmac)(w,A)}c.BASE._setWindowSize(8);function V(I,k,E,w=U){let A=I;k=it("msgHash",k),E=it("publicKey",E);let{lowS:v,prehash:_,format:R}=w;if(qu(w),"strict"in w)throw new Error("options.strict was renamed to lowS");if(R!==void 0&&R!=="compact"&&R!=="der")throw new Error("format must be compact or der");let O=typeof A=="string"||He(A),K=!O&&!R&&typeof A=="object"&&A!==null&&typeof A.r=="bigint"&&typeof A.s=="bigint";if(!O&&!K)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let F,G;try{if(K&&(F=new h(A.r,A.s)),O){try{R!=="compact"&&(F=h.fromDER(A))}catch(de){if(!(de instanceof Te.Err))throw de}!F&&R!=="der"&&(F=h.fromCompact(A))}G=c.fromHex(E)}catch{return!1}if(!F||v&&F.hasHighS())return!1;_&&(k=t.hash(k));let{r:j,s:at}=F,ct=L(k),ft=a(at),It=i(ct*ft),Ot=i(j*ft),Rt=c.BASE.multiplyAndAddUnsafe(G,It,Ot)?.toAffine();return Rt?i(Rt.x)===j:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:B,sign:M,verify:V,ProjectivePoint:c,Signature:h,utils:b}}function W0(r){return{hash:r,hmac:(t,...e)=>Or(r,t,Ai(...e)),randomBytes:en}}function Zu(r,t){let e=n=>ju({...r,...W0(n)});return{...e(t),create:e}}var Ju=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Xu=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),q0=BigInt(1),La=BigInt(2),Yu=(r,t)=>(r+t/La)/t;function z0(r){let t=Ju,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=lt(u,e,t)*u%t,d=lt(f,e,t)*u%t,m=lt(d,La,t)*l%t,y=lt(m,o,t)*m%t,g=lt(y,s,t)*y%t,h=lt(g,a,t)*g%t,b=lt(h,c,t)*h%t,x=lt(b,a,t)*g%t,p=lt(x,e,t)*u%t,B=lt(p,i,t)*y%t,N=lt(B,n,t)*l%t,L=lt(N,La,t);if(!Na.eql(Na.sqr(L),r))throw new Error("Cannot find square root");return L}var Na=Ve(Ju,void 0,void 0,{sqrt:z0}),fr=Zu({a:BigInt(0),b:BigInt(7),Fp:Na,n:Xu,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Xu,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-q0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=Yu(s*r,t),c=Yu(-n*r,t),l=Z(r-a*e-c*o,t),u=Z(-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}}}},ce),xx=BigInt(0);var Ex=fr.ProjectivePoint;function bt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=mt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}function Qu(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function tf(r,t,e){let n=ve.digest(e instanceof Uint8Array?e:e.subarray());if(Qu(n))return n.then(({digest:o})=>fr.verify(t,o,r)).catch(o=>{throw new bn(String(o))});try{return fr.verify(t,n.digest,r)}catch(o){throw new bn(String(o))}}var us=class{type="secp256k1";raw;_key;constructor(t){this._key=rf(t),this.raw=ef(this._key)}toMultihash(){return ge.digest(Tr(this))}toCID(){return Et.createV1(114,this.toMultihash())}toString(){return st.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Ut(this.raw,t.raw)}verify(t,e){return tf(this._key,e,t)}};function _a(r){return new us(r)}function ef(r){return fr.ProjectivePoint.fromHex(r).toRawBytes(!0)}function rf(r){try{return fr.ProjectivePoint.fromHex(r),r}catch(t){throw new yr(String(t))}}function vn(r){let{Type:t,Data:e}=ae.decode(r),n=e??new Uint8Array;switch(t){case wt.RSA:return ka(n);case wt.Ed25519:return Ki(n);case wt.secp256k1:return _a(n);default:throw new Je}}function nf(r){let{Type:t,Data:e}=ae.decode(r.digest),n=e??new Uint8Array;switch(t){case wt.Ed25519:return Ki(n);case wt.secp256k1:return _a(n);default:throw new Je}}function Tr(r){return ae.encode({Type:wt[r.type],Data:r.raw})}var of=Symbol.for("nodejs.util.inspect.custom"),Z0=114,An=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()})`}[fi]=!0;toString(){return this.string==null&&(this.string=st.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Et.createV1(Z0,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Ut(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Ut(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[of](){return`PeerId(${this.toString()})`}},Sn=class extends An{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Bn=class extends An{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},In=class extends An{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},X0=2336,fs=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=ge.digest(Q(this.url))}[of](){return`PeerId(${this.url})`}[fi]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Et.createV1(X0,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=X(t)),t.toString()===this.toString())}};function Mr(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=De(st.decode(`z${r}`));else{if(t==null)throw new ot('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=De(t.decode(r))}return Y0(e)}function Ra(r){if(r.type==="Ed25519")return new Bn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new In({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Sn({multihash:r.toCID().multihash,publicKey:r});throw new Je}function Y0(r){if(Q0(r))return new Sn({multihash:r});if(J0(r))try{let t=nf(r);if(t.type==="Ed25519")return new Bn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new In({multihash:r,publicKey:t})}catch{let e=X(r.digest);return new fs(new URL(e))}throw new Zn("Supplied PeerID Multihash is invalid")}function J0(r){return r.code===ge.code}function Q0(r){return r.code===ve.code}var hs=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 sf=45,tm=15,Hr=new hs;function Ua(r){if(!(r.length>tm))return Hr.new(r).parseWith(()=>Hr.readIPv4Addr())}function Da(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>sf))return Hr.new(r).parseWith(()=>Hr.readIPv6Addr())}function ds(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>sf)return;let e=Hr.new(r).parseWith(()=>Hr.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}var P1=parseInt("0xFFFF",16),O1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function ps(r){return!!Ua(r)}function ms(r){return!!Da(r)}function gs(r){return!!ds(r)}var lf=ps,sm=ms,Pa=function(r){let t=0;if(r=r.toString().trim(),lf(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(sm(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=lf(e[n]),i;s&&(i=Pa(e[n]),e[n]=X(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,X(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")},uf=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 Fr={},Oa={},am=[[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"]];am.forEach(r=>{let t=cm(...r);Oa[t.code]=t,Fr[t.name]=t});function cm(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function tt(r){if(typeof r=="number"){if(Oa[r]!=null)return Oa[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Fr[r]!=null)return Fr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var x2=tt("ip4"),E2=tt("ip6"),v2=tt("ipcidr");function Va(r,t){switch(tt(r).code){case 4:case 41:return um(t);case 42:return Fa(t);case 43:return X(t,"base10");case 6:case 273:case 33:case 132:return df(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Fa(t);case 421:return pm(t);case 444:return hf(t);case 445:return hf(t);case 466:return dm(t);case 481:return globalThis.encodeURIComponent(Fa(t));default:return X(t,"base16")}}function Ka(r,t){switch(tt(r).code){case 4:return ff(t);case 41:return ff(t);case 42:return Ha(t);case 43:return Q(t,"base10");case 6:case 273:case 33:case 132:return $a(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ha(t);case 421:return fm(t);case 444:return mm(t);case 445:return gm(t);case 466:return hm(t);case 481:return Ha(globalThis.decodeURIComponent(t));default:return Q(t,"base16")}}var Ma=Object.values(ar).map(r=>r.decoder),lm=function(){let r=Ma[0].or(Ma[1]);return Ma.slice(2).forEach(t=>r=r.or(t)),r}();function ff(r){if(!gs(r))throw new Error("invalid ip address");return Pa(r)}function um(r){let t=uf(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!gs(t))throw new Error("invalid ip address");return t}function $a(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function df(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Ha(r){let t=Q(r),e=Uint8Array.from(zt(t.length));return bt([e,t],e.length+t.length)}function Fa(r){let t=Kt(r);if(r=r.slice(et(t)),r.length!==t)throw new Error("inconsistent lengths");return X(r)}function fm(r){let t;r[0]==="Q"||r[0]==="1"?t=De(st.decode(`z${r}`)).bytes:t=Et.parse(r).multihash.bytes;let e=Uint8Array.from(zt(t.length));return bt([e,t],e.length+t.length)}function hm(r){let t=lm.decode(r),e=Uint8Array.from(zt(t.length));return bt([e,t],e.length+t.length)}function dm(r){let t=Kt(r),e=r.slice(et(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+X(e,"base64url")}function pm(r){let t=Kt(r),e=r.slice(et(t));if(e.length!==t)throw new Error("inconsistent lengths");return X(e,"base58btc")}function mm(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=me.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=$a(n);return bt([e,o],e.length+o.length)}function gm(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=me.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=$a(n);return bt([e,o],e.length+o.length)}function hf(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=X(t,"base32"),o=df(e);return`${n}:${o}`}function pf(r){r=Ga(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 new ys("invalid address: "+r);if(a.path===!0){n=Ga(o.slice(s).join("/")),t.push([a.code,Ka(a.code,n)]),e.push([a.code,n]);break}let c=Ka(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Va(a.code,c)])}return{string:mf(e),bytes:qa(t),tuples:t,stringTuples:e,path:n}}function Wa(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=Kt(r,o),i=et(s),a=tt(s),c=ym(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 new ys("Invalid address Uint8Array: "+X(r,"base16"));t.push([s,l]);let u=Va(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:mf(e),tuples:t,stringTuples:e,path:n}}function mf(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}),Ga(t.join("/"))}function qa(r){return bt(r.map(t=>{let e=tt(t[0]),n=Uint8Array.from(zt(e.code));return t.length>1&&t[1]!=null&&(n=bt([n,t[1]])),n}))}function ym(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=Kt(t instanceof Uint8Array?t:Uint8Array.from(t));return e+et(e)}}function Ga(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var ys=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var wm=Symbol.for("nodejs.util.inspect.custom"),ja=Symbol.for("@multiformats/js-multiaddr/multiaddr"),bm=[tt("dns").code,tt("dns4").code,tt("dns6").code,tt("dnsaddr").code],za=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},ws=class r{bytes;#t;#e;#r;#n;[ja]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Wa(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=pf(t)}else if(yf(t))e=Wa(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,y]of this.stringTuples())m===f.code&&(s=`%${y??""}`),bm.includes(m)&&(e=i.name==="tcp"?"tcp":"udp",o=443,n=`${y??""}${s}`,t=m===u.code?6:4),(m===i.code||m===a.code)&&(e=tt(m).name==="tcp"?"tcp":"udp",o=parseInt(y??"")),(m===c.code||m===l.code)&&(e=tt(m).name==="tcp"?"tcp":"udp",n=`${y??""}${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.map(([t,e])=>e==null?[t]:[t,e])}stringTuples(){return this.#r.map(([t,e])=>e==null?[t]:[t,e])}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(qa(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Fr.p2p.code&&t.push([n,o]),n===Fr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?X(st.decode(`z${n}`),"base58btc"):X(Et.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return Ut(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=gf.get(e.name);if(n==null)throw new za(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>he(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)}[wm](){return`Multiaddr(${this.#t})`}};var gf=new Map;function yf(r){return!!r?.[ja]}function he(r){return new ws(r)}var xm=r=>r.toString().split("/").slice(1),Vr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),W=r=>({match:t=>Vr(e=>e===r).match(t),pattern:r}),hr=()=>({match:r=>Vr(t=>typeof t=="string").match(r),pattern:"{string}"}),Cn=()=>({match:r=>Vr(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),rt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{st.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),kn=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{cn.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Y=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),_t=(...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(", ")})`}),z=(...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 ut(...r){function t(o){let s=xm(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 xs=z(W("dns4"),hr()),Es=z(W("dns6"),hr()),vs=z(W("dnsaddr"),hr()),Xa=z(W("dns"),hr()),Y2=ut(xs,Y(rt())),J2=ut(Es,Y(rt())),Q2=ut(vs,Y(rt())),tE=ut(_t(Xa,vs,xs,Es),Y(rt())),wf=z(W("ip4"),Vr(ps)),bf=z(W("ip6"),Vr(ms)),Ya=_t(wf,bf),Ne=_t(Ya,Xa,xs,Es,vs),eE=ut(_t(Ya,z(_t(Xa,vs,xs,Es),Y(rt())))),rE=ut(wf),nE=ut(bf),oE=ut(Ya),Ja=z(Ne,W("tcp"),Cn()),Tn=z(Ne,W("udp"),Cn()),sE=ut(z(Ja,Y(rt()))),iE=ut(Tn),Qa=z(Tn,W("quic"),Y(rt())),As=z(Tn,W("quic-v1"),Y(rt())),Em=_t(Qa,As),aE=ut(Qa),cE=ut(As),Za=_t(Ne,Ja,Tn,Qa,As),xf=_t(z(Za,W("ws"),Y(rt()))),lE=ut(xf),Ef=_t(z(Za,W("wss"),Y(rt())),z(Za,W("tls"),Y(z(W("sni"),hr())),W("ws"),Y(rt()))),uE=ut(Ef),vf=z(Tn,W("webrtc-direct"),Y(kn()),Y(kn()),Y(rt())),Af=ut(vf),Sf=z(As,W("webtransport"),Y(kn()),Y(kn()),Y(rt())),fE=ut(Sf),bs=_t(xf,Ef,z(Ja,Y(rt())),z(Em,Y(rt())),z(Ne,Y(rt())),vf,Sf,rt()),Bf=ut(bs),vm=z(bs,W("p2p-circuit"),rt()),hE=ut(vm),Am=_t(z(bs,W("p2p-circuit"),W("webrtc"),Y(rt())),z(bs,W("webrtc"),Y(rt())),z(W("webrtc"),Y(rt()))),If=ut(Am),Sm=_t(z(Ne,W("tcp"),Cn(),W("http"),Y(rt())),z(Ne,W("http"),Y(rt()))),dE=ut(Sm),Bm=_t(z(Ne,W("tcp"),_t(z(W("443"),W("http")),z(Cn(),W("https"))),Y(rt())),z(Ne,W("tls"),W("http"),Y(rt())),z(Ne,W("https"),Y(rt()))),pE=ut(Bm),Im=_t(z(W("memory"),hr(),Y(rt()))),mE=ut(Im);var Cf=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))},Cm=function(){function r(t,e,n){this.name=t,this.version=e,this.os=n,this.type="browser"}return r}();var km=function(){function r(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return r}();var Tm=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 Lm=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var Nm=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var _m=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Rm=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,kf=3,Um=[["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",_m]],Tf=[["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 Nf(r){return r?Lf(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Nm:typeof navigator<"u"?Lf(navigator.userAgent):Om()}function Dm(r){return r!==""&&Um.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 Lf(r){var t=Dm(r);if(!t)return null;var e=t[0],n=t[1];if(e==="searchbot")return new Lm;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<kf&&(o=Cf(Cf([],o,!0),Mm(kf-o.length),!0)):o=[];var s=o.join("."),i=Pm(r),a=Rm.exec(r);return a&&a[1]?new Tm(e,s,i,a[1]):new Cm(e,s,i)}function Pm(r){for(var t=0,e=Tf.length;t<e;t++){var n=Tf[t],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function Om(){var r=typeof process<"u"&&process.version;return r?new km(process.version.slice(1)):null}function Mm(r){for(var t=[],e=0;e<r;e++)t.push("0");return t}function pt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var tc=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},ec=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},_f=r=>globalThis.DOMException===void 0?new ec(r):new DOMException(r),Rf=r=>{let t=r.reason===void 0?_f("This operation was aborted."):r.reason;return t instanceof Error?t:_f(t)};function Ln(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,a,l=new Promise((u,f)=>{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:m}=t;m.aborted&&f(Rf(m)),a=()=>{f(Rf(m))},m.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new tc;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(m){f(m)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(d.message=o??`Promise timed out after ${e} milliseconds`,f(d))},e),(async()=>{try{u(await r)}catch(m){f(m)}})()}).finally(()=>{l.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},l}var Uf=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],rc=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Df="libp2p+webrtc+v1/";var Pf=Nf(),Nn=Pf!=null&&Pf.name==="firefox",Ss=async function*(){},Bs=async r=>{},Hm=30*1e3;function Of(r,t,e=Hm,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=pt(),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 Ln(o.promise,{milliseconds:e})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function nc(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??Uf.map(t=>({urls:[t]})),r}var Mf=(r=32)=>Df+[...Array(r)].map(()=>rc.at(Math.floor(Math.random()*rc.length))).join("");var dr=class{log;peerConnection;remoteAddr;timeline;metrics;source=Ss();sink=Bs;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,o=n.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",n.connectionState,"initial state",o),(n.connectionState==="disconnected"||n.connectionState==="failed"||n.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 Is=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}},Kr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Is(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 Is(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 oc=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function je(r={}){return Fm(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 Fm(r,t){t=t??{};let e=t.onEnd,n=new Kr,o,s,i,a=pt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,b)=>{s=x=>{s=null,n.push(x);try{h(r(n))}catch(p){b(p)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=pt()})}},l=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new Kr,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 Kr,d(),{done:!0}),y=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:y,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let b=h?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let x,p;b!=null&&(x=new Promise((B,N)=>{p=()=>{N(new oc)},b.addEventListener("abort",p)}));try{await Promise.race([a.promise,x])}finally{p!=null&&b!=null&&b?.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 Cs=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 se(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new Cs(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new Cs(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 Ff=Symbol.for("@achingbrain/uint8arraylist");function Hf(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 ks(r){return!!r?.[Ff]}var nt=class r{bufs;length;[Ff]=!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(ks(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(ks(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=Hf(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Hf(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(ks(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 bt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:bt(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(!ks(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=mt(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=yt(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=yt(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=yt(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=mt(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=yt(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=yt(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=yt(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=yt(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=yt(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(!Ut(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 Vf(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 Kf(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function $f(r,t){let e=Vf(r).return?.();Kf(e)&&e.catch(n=>{t.error("could not cause iterator to return",n)})}var Vm=5e3;function sc(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ts=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=pt(),this.closed=pt(),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??Vm,this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=je({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 Ye(`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);sc(o)&&await o}let n=()=>{$f(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 nt(o):o;let s=this.sendData(o,e);sc(s)&&(this.sendingData=pt(),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.status==="open"&&(this.log.trace("closing gracefully"),this.status="closing",await se(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 se(this.sink([]),t.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await se(this.sendingData.promise,t.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await se(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();sc(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 jn("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 ic(r){let t=new globalThis.AbortController;function e(){t.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}var Ls=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},$r=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ns=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},_n=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function _s(r){return r[Symbol.asyncIterator]!=null}function Gf(r,t){if(r.byteLength>t)throw new $r("Message length too long")}var Us=r=>{let t=et(r),e=mt(t);return zt(r,e),Us.bytes=t,e};Us.bytes=0;function Rn(r,t){t=t??{};let e=t.lengthEncoder??Us,n=t?.maxDataLength??4194304;function*o(s){Gf(s,n);let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return _s(r)?async function*(){for await(let s of r)yield*o(s)}():function*(){for(let s of r)yield*o(s)}()}Rn.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Us,n=t?.maxDataLength??4194304;return Gf(r,n),new nt(e(r.byteLength),r)};var pr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(pr||(pr={}));var ac=r=>{let t=Kt(r);return ac.bytes=et(t),t};ac.bytes=0;function Un(r,t){let e=new nt,n=pr.LENGTH,o=-1,s=t?.lengthDecoder??ac,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===pr.LENGTH)try{if(o=s(e),o<0)throw new Ls("Invalid message length");if(o>a)throw new $r("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=pr.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Ns("Message length length too long");break}throw l}if(n===pr.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=pr.LENGTH}}}return _s(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new _n("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new _n("Unexpected end of input")}()}Un.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 Un(n,{...t??{},onLength:s=>{e=s}})};var cc=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function Dn(r,t,e,n){let o=new cc(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){e?.removeEventListener("abort",u),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),i(d);return}a(),s(f)},l=f=>{a(),i(f.detail)},u=()=>{a(),i(o)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var Pt;(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=()=>lr(e)}(t=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=ne((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=>re(o,r.codec()),r.decode=(o,s)=>ee(o,r.codec(),s)})(Pt||(Pt={}));var Gm=2*1024*1024,Wm=30*1e3,Pn=16*1024;function qm(r=Pn){let t=et(r-et(r)),e=1+et(Object.keys(Pt.Flag).length-1),n=1,o=r-t-e-n,s=et(o);return t+e+n+s}var zm=qm(),jm=5e3,Zm=5e3,lc=class extends Ts{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;closeController;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 Ln(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(s){this.log.error("error receiving FIN_ACK",s)}}).then(()=>{this.incomingData.end(),this.channel.close(),e?.(o)}).catch(s=>{this.log.error("error ending stream",s)})},super(t),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=je(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??Wm,this.maxBufferedAmount=t.maxBufferedAmount??Gm,this.maxMessageSize=(t.maxMessageSize??Pn)-zm,this.receiveFinAck=pt(),this.finAckTimeout=t.closeTimeout??jm,this.openTimeout=t.openTimeout??Zm,this.closeController=new AbortController,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 Ye("Unknown datachannel state")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime()},this.channel.onclose=o=>{this.log.trace("received onclose event"),this.closeController.abort(),this.receiveFinAck.resolve(),this.close().catch(s=>{this.log.error("error closing stream after channel closed",s)})},this.channel.onerror=o=>{this.log.trace("received onerror event"),this.closeController.abort();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 Un(this.incomingData)){let s=n.processIncomingProtobuf(o);s!=null&&n.sourcePush(new nt(s))}}).catch(o=>{this.log.error("error processing incoming data channel messages",o)})}sendNewStream(){}async _sendMessage(t,e=!0){if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new Ye(`Invalid datachannel state - ${this.channel.readyState}`);if(this.channel.readyState!=="open"){let n=AbortSignal.timeout(this.openTimeout),o=ic([this.closeController.signal,n]);try{this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await Dn(this.channel,"open",o)}finally{o.clear()}this.log('channel state is now "%s", sending data',this.channel.readyState)}if(e&&this.channel.bufferedAmount>this.maxBufferedAmount){let n=AbortSignal.timeout(this.bufferedAmountLowEventTimeout),o=ic([this.closeController.signal,n]);try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await Dn(this.channel,"bufferedamountlow",o)}catch(s){throw n.aborted?new Yn(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`):s}finally{o.clear()}}try{this.channel.send(t.subarray())}catch(n){this.log.error("error while sending message",n)}}async sendData(t){for(this.log.trace("-> will send %d bytes",t.byteLength),t=t.sublist();t.byteLength>0;){let e=Math.min(t.byteLength,this.maxMessageSize),n=t.subarray(0,e),o=Pt.encode({message:n}),s=Rn.single(o);this.log.trace("-> sending message %s",this.channel.readyState),await this._sendMessage(s),this.log.trace("-> sent message %s",this.channel.readyState),t.consume(e)}this.log.trace("-> sent data %s",this.channel.readyState)}async sendReset(){try{await this._sendFlag(Pt.Flag.RESET)}catch(t){this.log.error("failed to send reset - %e",t)}}async sendCloseWrite(t){if(this.channel.readyState!=="open"){this.receiveFinAck.resolve();return}if(await this._sendFlag(Pt.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await se(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(){this.channel.readyState==="open"&&await this._sendFlag(Pt.Flag.STOP_SENDING)}processIncomingProtobuf(t){let e=Pt.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===Pt.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Pt.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),e.flag===Pt.Flag.RESET&&this.reset(),e.flag===Pt.Flag.STOP_SENDING&&this.remoteCloseRead(),e.flag===Pt.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=Pt.encode({flag:t}),n=Rn.single(e);try{return await this._sendMessage(n,!1),!0}catch(o){this.log.error("could not send flag %s - %e",t.toString(),o)}return!1}};function Gr(r){let{channel:t,direction:e}=r;return new lc({id:e==="inbound"?`i${t.id}`:`r${t.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${e}:${t.id}`),...r})}var Wf="/webrtc",Ze=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??Wf,this.dataChannelOptions=e.dataChannelOptions??{},this.log=t.logger.forComponent("libp2p:webrtc:muxerfactory"),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=Gr({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 uc(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},uc=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??Wf,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=n.id,s=Gr({channel:n,direction:"inbound",onEnd:()=>{this.#t(s,n),this.log("incoming channel %s ended",o)},logger:this.logger,...this.dataChannelOptions});this.streams.push(s),this.metrics?.increment({incoming_stream:!0}),e?.onIncomingStream?.(s)},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),Of(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=Ss();sink=Bs;newStream(){let t=this.peerConnection.createDataChannel(""),e=t.id;this.log.trace("opened outgoing datachannel with channel id %s",e);let n=Gr({channel:t,direction:"outbound",onEnd:()=>{this.#t(n,t),this.log("outgoing channel %s ended",e)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(n),this.metrics?.increment({outgoing_stream:!0}),n}};var Ds=globalThis.RTCPeerConnection,Ps=globalThis.RTCSessionDescription,qf=globalThis.RTCIceCandidate;var fc=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=pt(),this.haveNext=pt()}[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=pt(),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=pt(),await se(this.readNext.promise,e?.signal,e)}};function zf(){return new fc}var Os=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var hc=class extends Error{code;constructor(t,e){super(t),this.code=e}},dc=class extends hc{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function jf(r,t){let e=zf();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 nt;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new dc("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 nt:d}for(;o.byteLength<i;){let{value:f,done:d}=await Promise.race([n.next(),l]);if(d===!0)throw new Os("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 Ms=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Hs=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Fs=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function On(r,t={}){let e=jf(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=et(t.maxDataLength));let n=t?.lengthDecoder??Kt,o=t?.lengthEncoder??zt;return{read:async i=>{let a=-1,c=new nt;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 Ms("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Fs("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Hs("message length too long");return e.read(a,i)},write:async(i,a)=>{await e.write(new nt(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new nt(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Vs(r,t){let e=On(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 Gt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Xe=class extends Error{constructor(t){super(`WebRTC transport error: ${t}`),this.name="WebRTCTransportError"}},Zt=class extends Xe{constructor(t="SDP handshake failed"){super(t),this.name="SDPHandshakeFailedError"}};var Ks=class extends Xe{constructor(t,e){super(`Invalid fingerprint "${t}" within ${e}`),this.name="WebRTC/InvalidFingerprintError"}};var $s=class extends Xe{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},Gs=class extends Xe{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 Ft;(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=()=>lr(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ne((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=>re(o,r.codec()),r.decode=(o,s)=>ee(o,r.codec(),s)})(Ft||(Ft={}));var Ws=async(r,t,e)=>{try{let n=pt();for(Xm(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!==Ft.Type.ICE_CANDIDATE)throw new Xn("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){e.onProgress?.(new Gt("webrtc:end-of-ice-candidates")),e.log.trace("end-of-candidates received");continue}let i=new qf(s);e.log.trace("%s received new ICE candidate %o",e.direction,s);try{e.onProgress?.(new Gt("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&&qs(r)!=="connected")throw n}};function qs(r){return Nn?r.iceConnectionState:r.connectionState}function Xm(r,t){r[Nn?"oniceconnectionstatechange":"onconnectionstatechange"]=e=>{switch(qs(r)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new zn("RTCPeerConnection was closed"));break;default:break}}}async function Zf({rtcConfiguration:r,dataChannel:t,signal:e,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=Xf(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",u);let f=u.getPeerId();if(f==null)throw new ot("Relay peer was missing");let d=s.getConnections(Mr(f)),m,y=!1;d.length===0?(l?.(new Gt("webrtc:dial-relay")),m=await i.dial(u,{signal:e,onProgress:l}),y=!0):(l?.(new Gt("webrtc:reuse-relay-connection")),m=d[0]);try{l?.(new Gt("webrtc:open-signaling-stream"));let g=await m.newStream(zs,{signal:e,runOnLimitedConnection:!0}),h=Vs(g).pb(Ft),b=new Ds(r),x=new Ze({logger:c},{peerConnection:b,dataChannelOptions:t});try{let p=b.createDataChannel("init");b.onicecandidate=({candidate:S})=>{let T=JSON.stringify(S?.toJSON()??null);a.trace("initiator sending ICE candidate %o",S),h.write({type:Ft.Type.ICE_CANDIDATE,data:T},{signal:e}).catch(C=>{a.error("error sending ICE candidate",C)})},b.onicecandidateerror=S=>{a.error("initiator ICE candidate error",S)};let B=await b.createOffer().catch(S=>{throw a.error("could not execute createOffer",S),new Zt("Failed to set createOffer")});a.trace("initiator send SDP offer %s",B.sdp),l?.(new Gt("webrtc:send-sdp-offer")),await h.write({type:Ft.Type.SDP_OFFER,data:B.sdp},{signal:e}),await b.setLocalDescription(B).catch(S=>{throw a.error("could not execute setLocalDescription",S),new Zt("Failed to set localDescription")}),l?.(new Gt("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let N=await h.read({signal:e});if(N.type!==Ft.Type.SDP_ANSWER)throw new Zt("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",N.data);let L=new Ps({type:"answer",sdp:N.data});return await b.setRemoteDescription(L).catch(S=>{throw a.error("could not execute setRemoteDescription",S),new Zt("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),l?.(new Gt("webrtc:read-ice-candidates")),await Ws(b,h,{direction:"initiator",signal:e,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),p.close(),l?.(new Gt("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:b,muxerFactory:x}}catch(p){throw a.error("outgoing signaling error",p),b.close(),g.abort(p),p}finally{b.onicecandidate=null,b.onicecandidateerror=null}}finally{if(y)try{await m.close({signal:e})}catch(g){m.abort(g)}}}var Ym=ut(Bf.matchers[0],W("p2p-circuit")),js=class extends wr{transportManager;shutdownController;constructor(t,e){super(),this.transportManager=t.transportManager,this.shutdownController=e.shutdownController}async listen(){queueMicrotask(()=>{this.safeDispatchEvent("listening")})}getAddrs(){return this.transportManager.getListeners().filter(t=>t!==this).map(t=>t.getAddrs().filter(e=>Ym.exactMatch(e)).map(e=>e.encapsulate("/webrtc"))).flat()}async close(){this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function Yf({peerConnection:r,stream:t,signal:e,connection:n,log:o}){o.trace("new inbound signaling stream");let s=Vs(t).pb(Ft);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:Ft.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!==Ft.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 Ps({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:Ft.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 Ws(r,s,{direction:"recipient",signal:e,log:o})}catch(a){if(qs(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=he(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return o.trace("recipient connected to remote address %s",i),{remoteAddress:i}}var Jm="/webrtc",Qm="/p2p-circuit",zs="/webrtc-signaling/0.0.1",tg=30*1e3,Zs=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,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"})})}[Wn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[br]=["@libp2p/transport"];[Zc]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(zs,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(zs),this._started=!1}createListener(t){return new js(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(If.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 Zf({rtcConfiguration:await nc(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 dr(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??tg),o=new Ds(await nc(this.init.rtcConfiguration)),s=new Ze(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await Yf({peerConnection:o,connection:t,stream:e,signal:n,log:this.log});await e.close({signal:n});let a=new dr(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 Xf(r){let t=r.toString().split(Jm+"/");if(t.length!==2)throw new ot("webrtc protocol was not present in multiaddr");if(!t[0].includes(Qm))throw new ot("p2p-circuit protocol was not present in multiaddr");let e=he(t[0]),o=he("/"+t[1]).getPeerId();if(o==null)throw new ot("destination peer id was missing");let s=e.protos().pop();if(s===void 0)throw new ot("invalid multiaddr");return s.name!=="p2p"&&(e=e.encapsulate(`/p2p/${o}`)),{baseAddr:e,peerId:Mr(o)}}var Xs=class extends wr{async listen(){throw new $s("WebRTCTransport.createListener")}getAddrs(){return[]}async close(){}};function Ys(r){return r[Symbol.asyncIterator]!=null}var Js=r=>{let t=et(r),e=mt(t);return zt(r,e),Js.bytes=t,e};Js.bytes=0;function Jf(r,t){t=t??{};let e=t.lengthEncoder??Js;function*n(o){let s=e(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Ys(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Jf.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Js;return new nt(e(r.byteLength),r)};var Qs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ti=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ei=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Mn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var eg=8,rg=1024*1024*4,mr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(mr||(mr={}));var pc=r=>{let t=Kt(r);return pc.bytes=et(t),t};pc.bytes=0;function Hn(r,t){let e=new nt,n=mr.LENGTH,o=-1,s=t?.lengthDecoder??pc,i=t?.maxLengthLength??eg,a=t?.maxDataLength??rg;function*c(){for(;e.byteLength>0;){if(n===mr.LENGTH)try{if(o=s(e),o<0)throw new Qs("Invalid message length");if(o>a)throw new ti("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=mr.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new ei("Message length length too long");break}throw l}if(n===mr.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=mr.LENGTH}}}return Ys(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Mn("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Mn("Unexpected end of input")}()}Hn.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 Hn(n,{...t??{},onLength:s=>{e=s}})};function mc(){let r=pt(),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 Qf(){let r=mc(),t=mc();return[{source:r.source,sink:t.sink},{source:t.source,sink:r.sink}]}function ng(r){return r[Symbol.asyncIterator]!=null}function og(...r){let t=[];for(let e of r)ng(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=je({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 th=og;function eh(r,...t){if(r==null)throw new Error("Empty pipeline");if(gc(r)){let n=r;r=()=>n.source}else if(nh(r)||rh(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&gc(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++)gc(e[n])&&(e[n]=ig(e[n]));return sg(...e)}var sg=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},rh=r=>r?.[Symbol.asyncIterator]!=null,nh=r=>r?.[Symbol.iterator]!=null,gc=r=>r==null?!1:r.sink!=null&&r.source!=null,ig=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=je({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(rh(s))o=async function*(){yield*s,n.end()};else if(nh(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return th(n,o())}return r.source};var Wr=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function ri(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 wc(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Vt(r,...t){if(!wc(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 bc(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 oh(r,t){Vt(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var _e=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),sh=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ag=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!ag)throw new Error("Non little-endian hardware is not supported");function cg(r){if(typeof r!="string")throw new Error(`string expected, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function ni(r){if(typeof r=="string")r=cg(r);else if(wc(r))r=oi(r);else throw new Error(`Uint8Array expected, got ${typeof r}`);return r}function ih(r,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(r,t)}function ah(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 xc=(r,t)=>(Object.assign(t,r),t);function Ec(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 oi(r){return Uint8Array.from(r)}function Re(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}var lh=r=>Uint8Array.from(r.split("").map(t=>t.charCodeAt(0))),lg=lh("expand 16-byte k"),ug=lh("expand 32-byte k"),fg=_e(lg),uh=_e(ug),gS=uh.slice();function P(r,t){return r<<t|r>>>32-t}function vc(r){return r.byteOffset%4===0}var si=64,hg=16,fh=2**32-1,ch=new Uint32Array;function dg(r,t,e,n,o,s,i,a){let c=o.length,l=new Uint8Array(si),u=_e(l),f=vc(o)&&vc(s),d=f?_e(o):ch,m=f?_e(s):ch;for(let y=0;y<c;i++){if(r(t,e,n,u,i,a),i>=fh)throw new Error("arx: counter overflow");let g=Math.min(si,c-y);if(f&&g===si){let h=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let b=0,x;b<hg;b++)x=h+b,m[x]=d[x]^u[b];y+=si;continue}for(let h=0,b;h<g;h++)b=y+h,s[b]=o[b]^l[h];y+=g}}function Ac(r,t){let{allowShortKeys:e,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=ih({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof r!="function")throw new Error("core must be a function");return ri(o),ri(i),yc(s),yc(e),(a,c,l,u,f=0)=>{Vt(a),Vt(c),Vt(l);let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),Vt(u),ri(f),f<0||f>=fh)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let m=[],y=a.length,g,h;if(y===32)m.push(g=oi(a)),h=uh;else if(y===16&&e)g=new Uint8Array(32),g.set(a),g.set(a,16),h=fg,m.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${y}`);vc(c)||m.push(c=oi(c));let b=_e(g);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,b,_e(c.subarray(0,16)),b),c=c.subarray(16)}let x=16-o;if(x!==c.length)throw new Error(`arx: nonce must be ${x} or 16 bytes`);if(x!==12){let B=new Uint8Array(12);B.set(c,s?0:12-c.length),c=B,m.push(c)}let p=_e(c);return dg(r,h,b,p,l,u,f,i),Re(...m),u}}var Bt=(r,t)=>r[t++]&255|(r[t++]&255)<<8,Sc=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=ni(t),Vt(t,32);let e=Bt(t,0),n=Bt(t,2),o=Bt(t,4),s=Bt(t,6),i=Bt(t,8),a=Bt(t,10),c=Bt(t,12),l=Bt(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]=Bt(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],y=i[7],g=i[8],h=i[9],b=Bt(t,e+0),x=Bt(t,e+2),p=Bt(t,e+4),B=Bt(t,e+6),N=Bt(t,e+8),L=Bt(t,e+10),S=Bt(t,e+12),T=Bt(t,e+14),C=s[0]+(b&8191),H=s[1]+((b>>>13|x<<3)&8191),U=s[2]+((x>>>10|p<<6)&8191),M=s[3]+((p>>>7|B<<9)&8191),V=s[4]+((B>>>4|N<<12)&8191),I=s[5]+(N>>>1&8191),k=s[6]+((N>>>14|L<<2)&8191),E=s[7]+((L>>>11|S<<5)&8191),w=s[8]+((S>>>8|T<<8)&8191),A=s[9]+(T>>>5|o),v=0,_=v+C*a+H*(5*h)+U*(5*g)+M*(5*y)+V*(5*m);v=_>>>13,_&=8191,_+=I*(5*d)+k*(5*f)+E*(5*u)+w*(5*l)+A*(5*c),v+=_>>>13,_&=8191;let R=v+C*c+H*a+U*(5*h)+M*(5*g)+V*(5*y);v=R>>>13,R&=8191,R+=I*(5*m)+k*(5*d)+E*(5*f)+w*(5*u)+A*(5*l),v+=R>>>13,R&=8191;let O=v+C*l+H*c+U*a+M*(5*h)+V*(5*g);v=O>>>13,O&=8191,O+=I*(5*y)+k*(5*m)+E*(5*d)+w*(5*f)+A*(5*u),v+=O>>>13,O&=8191;let K=v+C*u+H*l+U*c+M*a+V*(5*h);v=K>>>13,K&=8191,K+=I*(5*g)+k*(5*y)+E*(5*m)+w*(5*d)+A*(5*f),v+=K>>>13,K&=8191;let F=v+C*f+H*u+U*l+M*c+V*a;v=F>>>13,F&=8191,F+=I*(5*h)+k*(5*g)+E*(5*y)+w*(5*m)+A*(5*d),v+=F>>>13,F&=8191;let G=v+C*d+H*f+U*u+M*l+V*c;v=G>>>13,G&=8191,G+=I*a+k*(5*h)+E*(5*g)+w*(5*y)+A*(5*m),v+=G>>>13,G&=8191;let j=v+C*m+H*d+U*f+M*u+V*l;v=j>>>13,j&=8191,j+=I*c+k*a+E*(5*h)+w*(5*g)+A*(5*y),v+=j>>>13,j&=8191;let at=v+C*y+H*m+U*d+M*f+V*u;v=at>>>13,at&=8191,at+=I*l+k*c+E*a+w*(5*h)+A*(5*g),v+=at>>>13,at&=8191;let ct=v+C*g+H*y+U*m+M*d+V*f;v=ct>>>13,ct&=8191,ct+=I*u+k*l+E*c+w*a+A*(5*h),v+=ct>>>13,ct&=8191;let ft=v+C*h+H*g+U*y+M*m+V*d;v=ft>>>13,ft&=8191,ft+=I*f+k*u+E*l+w*c+A*a,v+=ft>>>13,ft&=8191,v=(v<<2)+v|0,v=v+_|0,_=v&8191,v=v>>>13,R+=v,s[0]=_,s[1]=R,s[2]=O,s[3]=K,s[4]=F,s[5]=G,s[6]=j,s[7]=at,s[8]=ct,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;Re(n)}update(t){bc(this);let{buffer:e,blockLen:n}=this;t=ni(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(){Re(this.h,this.r,this.buffer,this.pad)}digestInto(t){bc(this),oh(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 pg(r){let t=(n,o)=>r(o).update(ni(n)).digest(),e=r(new Uint8Array(32));return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=n=>r(n),t}var hh=pg(r=>new Sc(r));function mh(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],y=t[4],g=t[5],h=t[6],b=t[7],x=o,p=e[0],B=e[1],N=e[2],L=i,S=a,T=c,C=l,H=u,U=f,M=d,V=m,I=y,k=g,E=h,w=b,A=x,v=p,_=B,R=N;for(let K=0;K<s;K+=2)L=L+H|0,A=P(A^L,16),I=I+A|0,H=P(H^I,12),L=L+H|0,A=P(A^L,8),I=I+A|0,H=P(H^I,7),S=S+U|0,v=P(v^S,16),k=k+v|0,U=P(U^k,12),S=S+U|0,v=P(v^S,8),k=k+v|0,U=P(U^k,7),T=T+M|0,_=P(_^T,16),E=E+_|0,M=P(M^E,12),T=T+M|0,_=P(_^T,8),E=E+_|0,M=P(M^E,7),C=C+V|0,R=P(R^C,16),w=w+R|0,V=P(V^w,12),C=C+V|0,R=P(R^C,8),w=w+R|0,V=P(V^w,7),L=L+U|0,R=P(R^L,16),E=E+R|0,U=P(U^E,12),L=L+U|0,R=P(R^L,8),E=E+R|0,U=P(U^E,7),S=S+M|0,A=P(A^S,16),w=w+A|0,M=P(M^w,12),S=S+M|0,A=P(A^S,8),w=w+A|0,M=P(M^w,7),T=T+V|0,v=P(v^T,16),I=I+v|0,V=P(V^I,12),T=T+V|0,v=P(v^T,8),I=I+v|0,V=P(V^I,7),C=C+H|0,_=P(_^C,16),k=k+_|0,H=P(H^k,12),C=C+H|0,_=P(_^C,8),k=k+_|0,H=P(H^k,7);let O=0;n[O++]=i+L|0,n[O++]=a+S|0,n[O++]=c+T|0,n[O++]=l+C|0,n[O++]=u+H|0,n[O++]=f+U|0,n[O++]=d+M|0,n[O++]=m+V|0,n[O++]=y+I|0,n[O++]=g+k|0,n[O++]=h+E|0,n[O++]=b+w|0,n[O++]=x+A|0,n[O++]=p+v|0,n[O++]=B+_|0,n[O++]=N+R|0}function mg(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],y=t[6],g=t[7],h=e[0],b=e[1],x=e[2],p=e[3];for(let N=0;N<20;N+=2)o=o+c|0,h=P(h^o,16),d=d+h|0,c=P(c^d,12),o=o+c|0,h=P(h^o,8),d=d+h|0,c=P(c^d,7),s=s+l|0,b=P(b^s,16),m=m+b|0,l=P(l^m,12),s=s+l|0,b=P(b^s,8),m=m+b|0,l=P(l^m,7),i=i+u|0,x=P(x^i,16),y=y+x|0,u=P(u^y,12),i=i+u|0,x=P(x^i,8),y=y+x|0,u=P(u^y,7),a=a+f|0,p=P(p^a,16),g=g+p|0,f=P(f^g,12),a=a+f|0,p=P(p^a,8),g=g+p|0,f=P(f^g,7),o=o+l|0,p=P(p^o,16),y=y+p|0,l=P(l^y,12),o=o+l|0,p=P(p^o,8),y=y+p|0,l=P(l^y,7),s=s+u|0,h=P(h^s,16),g=g+h|0,u=P(u^g,12),s=s+u|0,h=P(h^s,8),g=g+h|0,u=P(u^g,7),i=i+f|0,b=P(b^i,16),d=d+b|0,f=P(f^d,12),i=i+f|0,b=P(b^i,8),d=d+b|0,f=P(f^d,7),a=a+c|0,x=P(x^a,16),m=m+x|0,c=P(c^m,12),a=a+c|0,x=P(x^a,8),m=m+x|0,c=P(c^m,7);let B=0;n[B++]=o,n[B++]=s,n[B++]=i,n[B++]=a,n[B++]=h,n[B++]=b,n[B++]=x,n[B++]=p}var gg=Ac(mh,{counterRight:!1,counterLength:4,allowShortKeys:!1}),yg=Ac(mh,{counterRight:!1,counterLength:8,extendNonceFn:mg,allowShortKeys:!1});var wg=new Uint8Array(16),dh=(r,t)=>{r.update(t);let e=t.length%16;e&&r.update(wg.subarray(e))},bg=new Uint8Array(32);function ph(r,t,e,n,o){let s=r(t,e,bg),i=hh.create(s);o&&dh(i,o),dh(i,n);let a=new Uint8Array(16),c=sh(a);Ec(c,0,BigInt(o?o.length:0),!0),Ec(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return Re(s,a),l}var gh=r=>(t,e,n)=>(Vt(t,32),Vt(e),{encrypt(s,i){let a=s.length,c=a+16;i?Vt(i,c):i=new Uint8Array(c),r(t,e,s,i,1);let l=ph(r,t,e,i.subarray(0,-16),n);return i.set(l,a),Re(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?Vt(i,c):i=new Uint8Array(c);let l=s.subarray(0,-16),u=s.subarray(-16),f=ph(r,t,e,l,n);if(!ah(u,f))throw new Error("invalid tag");return r(t,e,l,i,1),Re(f),i}}),Bc=xc({blockSize:64,nonceLength:12,tagLength:16},gh(gg)),BS=xc({blockSize:64,nonceLength:24,tagLength:16},gh(yg));function wh(r,t,e){return tn(r),e===void 0&&(e=new Uint8Array(r.outputLen)),Or(r,Pe(e),Pe(t))}var Ic=new Uint8Array([0]),yh=new Uint8Array;function bh(r,t,e,n=32){if(tn(r),Qn(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);e===void 0&&(e=yh);let s=new Uint8Array(o*r.outputLen),i=Or.create(r,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)Ic[0]=l+1,a.update(l===0?yh:c).update(e).update(Ic).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),Ic.fill(0),s.slice(0,n)}var Cc={hashSHA256(r){return ce(r.subarray())},getHKDF(r,t){let e=wh(ce,t,r),o=bh(ce,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=an.utils.randomPrivateKey();return{publicKey:an.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:an.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,t){return an.getSharedSecret(r.subarray(),t.subarray())},chaCha20Poly1305Encrypt(r,t,e,n){return Bc(n,t,e).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,t,e,n,o){return Bc(n,t,e).decrypt(r.subarray(),o)}};var xh=Cc;function Eh(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 qr=r=>{let t=mt(2);return t[0]=r>>8,t[1]=r,t};qr.bytes=2;var Fn=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)};Fn.bytes=2;function vh(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 kc(r,t){!t.enabled||!Wr||(r?(t(`LOCAL_STATIC_PUBLIC_KEY ${X(r.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${X(r.privateKey,"hex")}`)):t("Missing local static keys."))}function Tc(r,t){!t.enabled||!Wr||(r?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${X(r.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${X(r.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function Ah(r,t){!t.enabled||!Wr||t(r?`REMOTE_STATIC_PUBLIC_KEY ${X(r.subarray(),"hex")}`:"Missing remote static public key.")}function Lc(r,t){!t.enabled||!Wr||t(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${X(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Nc(r,t,e){!e.enabled||!Wr||(e(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&X(r.k,"hex")}`),e(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&X(t.k,"hex")}`))}var zr=class r extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var xg=0,Eg=4294967295,vg="Cipherstate has reached maximum n, a new handshake must be performed",ii=class{n;bytes;view;constructor(t=xg){this.n=t,this.bytes=yt(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>Eg)throw new Error(vg)}};var gr=yt(0),jr=class{k;n;crypto;constructor(t,e=void 0,n=0){this.crypto=t,this.k=e,this.n=new ii(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}},_c=class{cs;ck;h;crypto;constructor(t,e){this.crypto=t;let n=Q(e,"utf-8");this.h=Ag(t,n),this.ck=this.h,this.cs=new jr(t)}mixKey(t){let[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new jr(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new nt(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,gr);return[new jr(this.crypto,t),new jr(this.crypto,e)]}},Rc=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 _c(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()}},Vn=class extends Rc{writeMessageA(t){return new nt(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let e=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new nt(e,n,this.ss.encryptAndHash(t))}writeMessageC(t){let e=this.writeS();return this.writeSE(),new nt(e,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(e){throw new zr(`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 zr(`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 zr(`handshake stage 2 validation fail: ${e.message}`)}}};function Ag(r,t){if(t.length<=32){let e=yt(32);return e.set(t),e}else return r.hash(t)}var ai;(function(r){let t;r.codec=()=>(t==null&&(t=ne((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=>re(e,r.codec()),r.decode=e=>ee(e,r.codec())})(ai||(ai={}));var Kn;(function(r){let t;r.codec=()=>(t==null&&(t=ne((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),ai.codec().encode(e.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={identityKey:yt(0),identitySig:yt(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=ai.codec().decode(e,e.uint32());break}default:{e.skipType(i&7);break}}}return o})),t),r.encode=e=>re(e,r.codec()),r.decode=e=>ee(e,r.codec())})(Kn||(Kn={}));async function Uc(r,t,e){let n=await r.sign(Sh(t));return Kn.encode({identityKey:Tr(r.publicKey),identitySig:n,extensions:e})}async function Dc(r,t,e){try{let n=Kn.decode(r),o=vn(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=Sh(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new qn(n.message)}}function Sh(r){let t=Q("noise-libp2p-static-key:");return r instanceof Uint8Array?bt([t,r],t.length+r.length):(r.prepend(t),r)}async function Bh(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Uc(s,a.publicKey,l),f=new Vn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});kc(f.s,e),e.trace("Stage 0 - Initiator starting to send first message."),await n.write(f.writeMessageA(gr),t),e.trace("Stage 0 - Initiator finished sending first message."),Tc(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),Ah(f.rs,e),e.trace("Initiator going to check remote's signature...");let m=await Dc(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[y,g]=f.ss.split();return Nc(y,g,e),{payload:m,encrypt:h=>y.encryptWithAd(gr,h),decrypt:(h,b)=>g.decryptWithAd(gr,h,b)}}async function Ih(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Uc(s,a.publicKey,l),f=new Vn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});kc(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."),Tc(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 Dc(d,f.rs,c),[y,g]=f.ss.split();return Nc(y,g,e),{payload:m,encrypt:h=>g.encryptWithAd(gr,h),decrypt:(h,b)=>y.decryptWithAd(gr,h,b)}}var kh=16;function Th(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 nt(qr(i.byteLength),i)}}}function Lh(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-kh<o)throw new Error("Invalid chunk");let i=n.sublist(o,s),a=n.subarray(o,s-kh);try{let c=r.decrypt(i,a);t?.decryptedPackets.increment(),yield c}catch(c){throw t?.decryptErrors.increment(),c}}}}var ci=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??xh;this.crypto=Eh(c),this.extensions=o,this.metrics=a?vh(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??yt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[br]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,e){let n=On(t,{lengthEncoder:qr,lengthDecoder:Fn,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=vn(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Ra(i)}}async secureInbound(t,e){let n=On(t,{lengthEncoder:qr,lengthDecoder:Fn,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=vn(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Ra(i)}}async performHandshakeInitiator(t,e,n,o){let s;try{s=await Bh({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 Ih({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]=Qf(),s=t.unwrap();return await eh(n,Th(e,this.metrics),s,i=>Hn(i,{lengthDecoder:Fn}),Lh(e,this.metrics),n),o}};function Nh(r={}){return t=>new ci(t,r)}var Pc=Object.values(ar).map(r=>r.decoder).reduce((r,t)=>r.or(t)),Sg=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function _h(r){return r?.match(Sg)?.groups?.fingerprint}function Oc(r){let e=r.stringTuples().filter(n=>n[0]===Oh).map(n=>n[1])[0];if(e===void 0||e==="")throw new ot(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return e}function Bg(r){return Wt.decode(Pc.decode(r))}function Ig(r){let t=Bg(Oc(r)),e=Cg(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 Ks(n,r.toString());return`${e} ${o.join(":").toUpperCase()}`}function Rh(r){let t=r.split(":").map(o=>parseInt(o,16)),e=Uint8Array.from(t),n=kt(ve.code,e);return he(`/certhash/${cn.encode(n.bytes)}`)}function Cg(r){switch(r){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new Gs(r)}}function Uh(r,t){let{host:e,port:n,family:o}=r.toOptions(),s=Ig(r);return{type:"answer",sdp:`v=0
7
7
  o=- 0 0 IN IP${o} ${e}
8
8
  s=-
9
9
  t=0 0
@@ -17,10 +17,10 @@ a=ice-pwd:${t}
17
17
  a=fingerprint:${s}
18
18
  a=setup:passive
19
19
  a=sctp-port:5000
20
- a=max-message-size:${Un}
20
+ a=max-message-size:${Pn}
21
21
  a=candidate:1467250027 1 UDP 1467250027 ${e} ${n} typ host
22
22
  a=end-of-candidates
23
- `}}function Ah(r,t){let{host:e,port:n,family:o}=r.toOptions();return{type:"offer",sdp:`v=0
23
+ `}}function Dh(r,t){let{host:e,port:n,family:o}=r.toOptions();return{type:"offer",sdp:`v=0
24
24
  o=- 0 0 IN IP${o} ${e}
25
25
  s=-
26
26
  c=IN IP${o} ${e}
@@ -33,15 +33,15 @@ a=ice-ufrag:${t}
33
33
  a=ice-pwd:${t}
34
34
  a=fingerprint:sha-256 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00
35
35
  a=sctp-port:5000
36
- a=max-message-size:${Un}
36
+ a=max-message-size:${Pn}
37
37
  a=candidate:1467250027 1 UDP 1467250027 ${e} ${n} typ host
38
38
  a=end-of-candidates
39
- `}}function kc(r,t){if(r.sdp===void 0)throw new rt("Can't munge a missing SDP");let e=r.sdp.includes(`\r
39
+ `}}function Mc(r,t){if(r.sdp===void 0)throw new ot("Can't munge a missing SDP");let e=r.sdp.includes(`\r
40
40
  `)?`\r
41
41
  `:`
42
42
  `;return r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
43
43
  a=ice-ufrag:`+t+e).replace(/\na=ice-pwd:[^\n]*\n/,`
44
- a=ice-pwd:`+t+e),r}var Tc=Q("libp2p-webrtc-noise:");function Ch(r,t,e){let n=r.trim().toLowerCase().replaceAll(":",""),o=Q(n,"hex"),s=kt(Ee.code,o),i=Cc.decode(Ic(t)),a=Tc.byteLength+s.bytes.byteLength+i.byteLength;return e==="server"?bt([Tc,i,s.bytes],a):bt([Tc,s.bytes,i],a)}var mg=Nn?"iceconnectionstatechange":"connectionstatechange";async function Ih(r,t,e){let n=r.createDataChannel("",{negotiated:!0,id:0});if(e.role==="client"){e.log.trace("client creating local offer");let d=await r.createOffer();e.log.trace("client created local offer %s",d.sdp);let m=kc(d,t);e.log.trace("client setting local offer %s",m.sdp),await r.setLocalDescription(m);let y=Eh(e.remoteAddr,t);e.log.trace("client setting server description %s",y.sdp),await r.setRemoteDescription(y)}else{let d=Ah(e.remoteAddr,t);e.log.trace("server setting client %s %s",d.type,d.sdp),await r.setRemoteDescription(d),e.log.trace("server creating local answer");let m=await r.createAnswer();e.log.trace("server created local answer");let y=kc(m,t);e.log.trace("server setting local description %s",m.sdp),await r.setLocalDescription(y)}if(e.log.trace("%s wait for handshake channel to open",e.role),await Rn(n,"open",e.signal),e.log.trace("%s handshake channel opened",e.role),e.role==="server"){let d=r.remoteFingerprint()?.value??"";e.remoteAddr=e.remoteAddr.encapsulate(vh(d))}let o=xh(r.localDescription?.sdp);if(o==null)throw new Xe("Could not get fingerprint from local description sdp");e.log.trace("%s performing noise handshake",e.role);let s=Ch(o,e.remoteAddr,e.role),i=bh({prologueBytes:s})(e),a=Kr({channel:n,direction:"inbound",logger:e.logger,...e.dataChannel??{}}),c={...a,sink:a.sink.bind(a),source:async function*(){for await(let d of a.source)for(let m of d)yield m}()},l=new hr(e,{peerConnection:r,remoteAddr:e.remoteAddr,timeline:{open:Date.now()},metrics:e.events});r.addEventListener(mg,()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(d=>{e.log.error("error closing connection",d)});break;default:break}}),e.events?.increment({peer_connection:!0});let u=new Ze(e,{peerConnection:r,metrics:e.events,dataChannelOptions:e.dataChannel});if(e.role==="client")return e.log.trace("%s secure inbound",e.role),await i.secureInbound(c,{remotePeer:e.remotePeerId}),e.log.trace("%s upgrade outbound",e.role),e.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,muxerFactory:u});e.log.trace("%s secure outbound",e.role);let f=await i.secureOutbound(c,{remotePeer:e.remotePeerId});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${f.remotePeer}`),e.log.trace("%s upgrade inbound",e.role),await e.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,muxerFactory:u})}async function kh(r,t,e,n){n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof e=="function"?await e():e;return new RTCPeerConnection({...o??{},certificates:[n]})}var gg=1e4,JS=tt("webrtc-direct").code,Sh=tt("certhash").code,ti=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"})})}[Vn]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[wr]=["@libp2p/transport"];async dial(t,e){e?.signal?.throwIfAborted();let n=await this._connect(t,e);return this.log("dialing address: %a",t),n}createListener(t){return new Gs(this.components,{...this.init,...t})}listenFilter(t){return t.filter(df.exactMatch)}dialFilter(t){return this.listenFilter(t)}async _connect(t,e){let n,o=t.getPeerId();o!=null&&(n=Or(o));let s=kf(),i=await kh("client",s,typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{});try{return await oe(Ih(i,s,{role:"client",log:this.log,logger:this.components.logger,metrics:this.components.metrics,events:this.metrics?.dialerEvents,signal:e.signal??AbortSignal.timeout(gg),remoteAddr:t,dataChannel:this.init.dataChannel,upgrader:e.upgrader,peerId:this.components.peerId,remotePeerId:n,privateKey:this.components.privateKey}),e.signal)}catch(a){throw i.close(),a}}};function yg(r){return t=>new ti(t,r)}function wg(r){return t=>new qs(t,r)}return Wh(bg);})();
44
+ a=ice-pwd:`+t+e),r}var Hc=Q("libp2p-webrtc-noise:");function Mh(r,t,e){let n=r.trim().toLowerCase().replaceAll(":",""),o=Q(n,"hex"),s=kt(ve.code,o),i=Pc.decode(Oc(t)),a=Hc.byteLength+s.bytes.byteLength+i.byteLength;return e==="server"?bt([Hc,i,s.bytes],a):bt([Hc,s.bytes,i],a)}var kg=Nn?"iceconnectionstatechange":"connectionstatechange";async function Hh(r,t,e){let n=r.createDataChannel("",{negotiated:!0,id:0});if(e.role==="client"){e.log.trace("client creating local offer");let d=await r.createOffer();e.log.trace("client created local offer %s",d.sdp);let m=Mc(d,t);e.log.trace("client setting local offer %s",m.sdp),await r.setLocalDescription(m);let y=Uh(e.remoteAddr,t);e.log.trace("client setting server description %s",y.sdp),await r.setRemoteDescription(y)}else{let d=Dh(e.remoteAddr,t);e.log.trace("server setting client %s %s",d.type,d.sdp),await r.setRemoteDescription(d),e.log.trace("server creating local answer");let m=await r.createAnswer();e.log.trace("server created local answer");let y=Mc(m,t);e.log.trace("server setting local description %s",m.sdp),await r.setLocalDescription(y)}if(e.log.trace("%s wait for handshake channel to open",e.role),await Dn(n,"open",e.signal),e.log.trace("%s handshake channel opened",e.role),e.role==="server"){let d=r.remoteFingerprint()?.value??"";e.remoteAddr=e.remoteAddr.encapsulate(Rh(d))}let o=_h(r.localDescription?.sdp);if(o==null)throw new Xe("Could not get fingerprint from local description sdp");e.log.trace("%s performing noise handshake",e.role);let s=Mh(o,e.remoteAddr,e.role),i=Nh({prologueBytes:s})(e),a=Gr({channel:n,direction:"inbound",logger:e.logger,...e.dataChannel??{}}),c={...a,sink:a.sink.bind(a),source:async function*(){for await(let d of a.source)for(let m of d)yield m}()},l=new dr(e,{peerConnection:r,remoteAddr:e.remoteAddr,timeline:{open:Date.now()},metrics:e.events});r.addEventListener(kg,()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(d=>{e.log.error("error closing connection",d)});break;default:break}}),e.events?.increment({peer_connection:!0});let u=new Ze(e,{peerConnection:r,metrics:e.events,dataChannelOptions:e.dataChannel});if(e.role==="client")return e.log.trace("%s secure inbound",e.role),await i.secureInbound(c,{remotePeer:e.remotePeerId}),e.log.trace("%s upgrade outbound",e.role),e.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,muxerFactory:u});e.log.trace("%s secure outbound",e.role);let f=await i.secureOutbound(c,{remotePeer:e.remotePeerId});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${f.remotePeer}`),e.log.trace("%s upgrade inbound",e.role),await e.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,muxerFactory:u})}async function Fh(r,t,e,n){n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof e=="function"?await e():e;return new RTCPeerConnection({...o??{},certificates:[n]})}var Tg=1e4,k8=tt("webrtc-direct").code,Oh=tt("certhash").code,li=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"})})}[Wn]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[br]=["@libp2p/transport"];async dial(t,e){e?.signal?.throwIfAborted();let n=await this._connect(t,e);return this.log("dialing address: %a",t),n}createListener(t){return new Xs(this.components,{...this.init,...t})}listenFilter(t){return t.filter(Af.exactMatch)}dialFilter(t){return this.listenFilter(t)}async _connect(t,e){let n,o=t.getPeerId();o!=null&&(n=Mr(o));let s=Mf(),i=await Fh("client",s,typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{});try{return await se(Hh(i,s,{role:"client",log:this.log,logger:this.components.logger,metrics:this.components.metrics,events:this.metrics?.dialerEvents,signal:e.signal??AbortSignal.timeout(Tg),remoteAddr:t,dataChannel:this.init.dataChannel,upgrader:e.upgrader,peerId:this.components.peerId,remotePeerId:n,privateKey:this.components.privateKey}),e.signal)}catch(a){throw i.close(),a}}};function Lg(r){return t=>new li(t,r)}function Ng(r){return t=>new Zs(t,r)}return rd(_g);})();
45
45
  /*! Bundled license information:
46
46
 
47
47
  pvtsutils/build/index.js: