@libp2p/webrtc 5.0.25-21088c519 → 5.0.25-7a1665cd8

Sign up to get free protection for your applications and to get access to all the features.
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 Nh=Object.create;var Fn=Object.defineProperty;var Lh=Object.getOwnPropertyDescriptor;var _h=Object.getOwnPropertyNames;var Rh=Object.getPrototypeOf,Uh=Object.prototype.hasOwnProperty;var Dh=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Ct=(r,t)=>{for(var e in t)Fn(r,e,{get:t[e],enumerable:!0})},Dc=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of _h(t))!Uh.call(r,o)&&o!==e&&Fn(r,o,{get:()=>t[o],enumerable:!(n=Lh(t,o))||n.enumerable});return r};var Ph=(r,t,e)=>(e=r!=null?Nh(Rh(r)):{},Dc(t||!r||!r.__esModule?Fn(e,"default",{value:r,enumerable:!0}):e,r)),Oh=r=>Dc(Fn({},"__esModule",{value:!0}),r);var Ol=Dh(Nr=>{"use strict";var i0="[object ArrayBuffer]",xe=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===i0}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}},da="string",a0=/^[0-9a-f\s]+$/i,c0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,l0=/^[a-zA-Z0-9-_]+$/,go=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=xe.toUint8Array(t),n="";for(let s=0;s<e.length;s++)n+=String.fromCharCode(e[s]);return decodeURIComponent(escape(n))}},qt=class{static toString(t,e=!1){let n=xe.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}},yo=class r{static isHex(t){return typeof t===da&&a0.test(t)}static isBase64(t){return typeof t===da&&c0.test(t)}static isBase64Url(t){return typeof t===da&&l0.test(t)}static ToString(t,e="utf8"){let n=xe.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 qt.toString(n,!0);case"utf16":case"utf16be":return qt.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 qt.fromString(t,!0);case"utf16":case"utf16be":return qt.fromString(t);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToBase64(t){let e=xe.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 go.fromString(t);case"utf16":case"utf16be":return qt.fromString(t);case"utf16le":case"usc2":return qt.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 go.toString(t);case"utf16":case"utf16be":return qt.toString(t);case"utf16le":case"usc2":return qt.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=xe.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=xe.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 qt.toString(t,e)}static FromUtf16String(t,e=!1){return qt.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,"")||""}};yo.DEFAULT_UTF8_ENCODING="utf8";function u0(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 f0(...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 h0(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=xe;Nr.Convert=yo;Nr.assign=u0;Nr.combine=f0;Nr.isEqual=h0});var mg={};Ct(mg,{webRTC:()=>pg,webRTCDirect:()=>dg});var ni=Symbol.for("@libp2p/peer-id");var Kn=Symbol.for("@libp2p/transport");var Pc;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Pc||(Pc={}));var $n=class extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}};var et=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},yr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Wn=class extends Error{static name="ConnectionFailedError";constructor(t="Connection failed"){super(t),this.name="ConnectionFailedError"}};var qn=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}},Ze=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 Gn=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var jr=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}};var Xe=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var jn=(r,...t)=>{try{[...t]}catch{}};var Zn=class extends EventTarget{#t=new Map;constructor(){super(),jn(1/0,this)}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};var wr=Symbol.for("@libp2p/service-capabilities"),Oc=Symbol.for("@libp2p/service-dependencies");var ci={};Ct(ci,{base58btc:()=>nt,base58flickr:()=>$h});var zg=new Uint8Array(0);function Mc(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 he(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 Hc(r){return new TextEncoder().encode(r)}function Vc(r){return new TextDecoder().decode(r)}function Mh(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,w=0,x=y.length;w!==x&&y[w]===0;)w++,g++;for(var m=(x-w)*u+1>>>0,I=new Uint8Array(m);w!==x;){for(var L=y[w],N=0,B=m-1;(L!==0||N<h)&&B!==-1;B--,N++)L+=256*I[B]>>>0,I[B]=L%a>>>0,L=L/a>>>0;if(L!==0)throw new Error("Non-zero carry");h=N,w++}for(var k=m-h;k!==m&&I[k]===0;)k++;for(var S=c.repeat(g);k<m;++k)S+=r.charAt(I[k]);return S}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,w=0;y[g]===c;)h++,g++;for(var x=(y.length-g)*l+1>>>0,m=new Uint8Array(x);y[g];){var I=e[y.charCodeAt(g)];if(I===255)return;for(var L=0,N=x-1;(I!==0||L<w)&&N!==-1;N--,L++)I+=a*m[N]>>>0,m[N]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");w=L,g++}if(y[g]!==" "){for(var B=x-w;B!==x&&m[B]===0;)B++;for(var k=new Uint8Array(h+(x-B)),S=h;B!==x;)k[S++]=m[B++];return k}}}function p(y){var g=d(y);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:p}}var Hh=Mh,Vh=Hh,Kc=Vh;var oi=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")}},si=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 $c(this,t)}},ii=class{decoders;constructor(t){this.decoders=t}or(t){return $c(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 $c(r,t){return new ii({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ai=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 oi(t,e,n),this.decoder=new si(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 ai(r,t,e,n)}function _e({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Kc(e,r);return br({prefix:t,name:r,encode:n,decode:s=>he(o(s))})}function Fh(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 Kh(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 Kh(o,n,e)},decode(o){return Fh(o,n,e,r)}})}var nt=_e({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),$h=_e({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var li={};Ct(li,{base32:()=>de,base32hex:()=>Gh,base32hexpad:()=>Zh,base32hexpadupper:()=>Xh,base32hexupper:()=>jh,base32pad:()=>qh,base32padupper:()=>zh,base32upper:()=>Wh,base32z:()=>Yh});var de=dt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Wh=dt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),qh=dt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),zh=dt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Gh=dt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),jh=dt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Zh=dt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Xh=dt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Yh=dt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ui={};Ct(ui,{base36:()=>Zr,base36upper:()=>Jh});var Zr=_e({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Jh=_e({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Gt={};Ct(Gt,{Digest:()=>Ye,create:()=>Ot,decode:()=>Re,equals:()=>hi,hasCode:()=>yd});var Qh=zc,Wc=128,td=127,ed=~td,rd=Math.pow(2,31);function zc(r,t,e){t=t||[],e=e||0;for(var n=e;r>=rd;)t[e++]=r&255|Wc,r/=128;for(;r&ed;)t[e++]=r&255|Wc,r>>>=7;return t[e]=r|0,zc.bytes=e-n+1,t}var nd=fi,od=128,qc=127;function fi(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw fi.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&qc)<<o:(i&qc)*Math.pow(2,o),o+=7}while(i>=od);return fi.bytes=s-n,e}var sd=Math.pow(2,7),id=Math.pow(2,14),ad=Math.pow(2,21),cd=Math.pow(2,28),ld=Math.pow(2,35),ud=Math.pow(2,42),fd=Math.pow(2,49),hd=Math.pow(2,56),dd=Math.pow(2,63),pd=function(r){return r<sd?1:r<id?2:r<ad?3:r<cd?4:r<ld?5:r<ud?6:r<fd?7:r<hd?8:r<dd?9:10},md={encode:Qh,decode:nd,encodingLength:pd},gd=md,Xr=gd;function Yr(r,t=0){return[Xr.decode(r,t),Xr.decode.bytes]}function xr(r,t,e=0){return Xr.encode(r,t,e),t}function vr(r){return Xr.encodingLength(r)}function Ot(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 Ye(r,e,t,s)}function Re(r){let t=he(r),[e,n]=Yr(t),[o,s]=Yr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Ye(e,o,i,t)}function hi(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Mc(r.bytes,e.bytes)}}var Ye=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function yd(r,t){return r.code===t}function Gc(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return bd(e,di(r),t??nt.encoder);default:return xd(e,di(r),t??de.encoder)}}var jc=new WeakMap;function di(r){let t=jc.get(r);if(t==null){let e=new Map;return jc.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!==Jr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==vd)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Ot(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&&hi(t.multihash,n.multihash)}toString(t){return Gc(this,t)}toJSON(){return{"/":Gc(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??Zc(n,o,s.bytes))}else if(e[Ed]===!0){let{version:n,multihash:o,code:s}=e,i=Re(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!==Jr)throw new Error(`Version 0 CID must use dag-pb (code: ${Jr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Zc(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Jr,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=he(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 Ye(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]=Yr(t.subarray(e));return e+=d,f},o=n(),s=Jr;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]=wd(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 di(s).set(n,t),s}};function wd(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 de.prefix:{let e=t??de;return[de.prefix,e.decode(r)]}case Zr.prefix:{let e=t??Zr;return[Zr.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 bd(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 xd(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 Jr=112,vd=18;function Zc(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 Ed=Symbol.for("@ipld/js-cid/CID");var pi={};Ct(pi,{identity:()=>pe});var Xc=0,Ad="identity",Yc=he;function Bd(r){return Ot(Xc,Yc(r))}var pe={code:Xc,name:Ad,encode:Yc,digest:Bd};function Rt(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 Yn(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Sd(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Er(r,...t){if(!Sd(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 Qr(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Yn(r.outputLen),Yn(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 Jc(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 Je=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Jn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function jt(r,t){return r<<32-t|r>>>t}function Qc(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function Ue(r){return typeof r=="string"&&(r=Qc(r)),Er(r),r}function mi(...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 Qn(r){let t=n=>r().update(Ue(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function tn(r=32){if(Je&&typeof Je.getRandomValues=="function")return Je.getRandomValues(new Uint8Array(r));if(Je&&typeof Je.randomBytes=="function")return Je.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function Id(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 tl(r,t,e){return r&t^~r&e}function el(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=Jn(this.buffer)}update(t){Ar(this);let{view:e,buffer:n,blockLen:o}=this;t=Ue(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=Jn(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),Jc(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;Id(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Jn(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 to=BigInt(4294967295),gi=BigInt(32);function rl(r,t=!1){return t?{h:Number(r&to),l:Number(r>>gi&to)}:{h:Number(r>>gi&to)|0,l:Number(r&to)|0}}function Cd(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}=rl(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var kd=(r,t)=>BigInt(r>>>0)<<gi|BigInt(t>>>0),Td=(r,t,e)=>r>>>e,Nd=(r,t,e)=>r<<32-e|t>>>e,Ld=(r,t,e)=>r>>>e|t<<32-e,_d=(r,t,e)=>r<<32-e|t>>>e,Rd=(r,t,e)=>r<<64-e|t>>>e-32,Ud=(r,t,e)=>r>>>e-32|t<<64-e,Dd=(r,t)=>t,Pd=(r,t)=>r,Od=(r,t,e)=>r<<e|t>>>32-e,Md=(r,t,e)=>t<<e|r>>>32-e,Hd=(r,t,e)=>t<<e-32|r>>>64-e,Vd=(r,t,e)=>r<<e-32|t>>>64-e;function Fd(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Kd=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),$d=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Wd=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),qd=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,zd=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),Gd=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var jd={fromBig:rl,split:Cd,toBig:kd,shrSH:Td,shrSL:Nd,rotrSH:Ld,rotrSL:_d,rotrBH:Rd,rotrBL:Ud,rotr32H:Dd,rotr32L:Pd,rotlSH:Od,rotlSL:Md,rotlBH:Hd,rotlBL:Vd,add:Fd,add3L:Kd,add3H:$d,add4L:Wd,add4H:qd,add5H:Gd,add5L:zd},$=jd;var[Zd,Xd]=$.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))),De=new Uint32Array(80),Pe=new Uint32Array(80),yi=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:p,Gl:y,Hh:g,Hl:h}=this;return[t,e,n,o,s,i,a,c,l,u,f,d,p,y,g,h]}set(t,e,n,o,s,i,a,c,l,u,f,d,p,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=p|0,this.Gl=y|0,this.Hh=g|0,this.Hl=h|0}process(t,e){for(let m=0;m<16;m++,e+=4)De[m]=t.getUint32(e),Pe[m]=t.getUint32(e+=4);for(let m=16;m<80;m++){let I=De[m-15]|0,L=Pe[m-15]|0,N=$.rotrSH(I,L,1)^$.rotrSH(I,L,8)^$.shrSH(I,L,7),B=$.rotrSL(I,L,1)^$.rotrSL(I,L,8)^$.shrSL(I,L,7),k=De[m-2]|0,S=Pe[m-2]|0,H=$.rotrSH(k,S,19)^$.rotrBH(k,S,61)^$.shrSH(k,S,6),_=$.rotrSL(k,S,19)^$.rotrBL(k,S,61)^$.shrSL(k,S,6),M=$.add4L(B,_,Pe[m-7],Pe[m-16]),V=$.add4H(M,N,H,De[m-7],De[m-16]);De[m]=V|0,Pe[m]=M|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:p,Fl:y,Gh:g,Gl:h,Hh:w,Hl:x}=this;for(let m=0;m<80;m++){let I=$.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&p^~f&g,B=d&y^~d&h,k=$.add5L(x,L,B,Xd[m],Pe[m]),S=$.add5H(k,w,I,N,Zd[m],De[m]),H=k|0,_=$.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;w=g|0,x=h|0,g=p|0,h=y|0,p=f|0,y=d|0,{h:f,l:d}=$.add(l|0,u|0,S|0,H|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let T=$.add3L(H,M,C);n=$.add3H(T,S,_,V),o=T|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:p,l:y}=$.add(this.Fh|0,this.Fl|0,p|0,y|0),{h:g,l:h}=$.add(this.Gh|0,this.Gl|0,g|0,h|0),{h:w,l:x}=$.add(this.Hh|0,this.Hl|0,w|0,x|0),this.set(n,o,s,i,a,c,l,u,f,d,p,y,g,h,w,x)}roundClean(){De.fill(0),Pe.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 nl=Qn(()=>new yi);var no={};Ct(no,{aInRange:()=>Et,abool:()=>Zt,abytes:()=>Ir,bitGet:()=>rp,bitLen:()=>vi,bitMask:()=>rn,bitSet:()=>np,bytesToHex:()=>ge,bytesToNumberBE:()=>ye,bytesToNumberLE:()=>Xt,concatBytes:()=>be,createHmacDrbg:()=>Ei,ensureBytes:()=>ot,equalBytes:()=>tp,hexToBytes:()=>tr,hexToNumber:()=>xi,inRange:()=>en,isBytes:()=>Oe,memoized:()=>er,notImplemented:()=>sp,numberToBytesBE:()=>Me,numberToBytesLE:()=>we,numberToHexUnpadded:()=>Qe,numberToVarBytesBE:()=>Qd,utf8ToBytes:()=>ep,validateObject:()=>Wt});var eo=BigInt(0),ro=BigInt(1),Yd=BigInt(2);function Oe(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ir(r){if(!Oe(r))throw new Error("Uint8Array expected")}function Zt(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}var Jd=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function ge(r){Ir(r);let t="";for(let e=0;e<r.length;e++)t+=Jd[r[e]];return t}function Qe(r){let t=r.toString(16);return t.length&1?"0"+t:t}function xi(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?eo:BigInt("0x"+r)}var me={_0:48,_9:57,A:65,F:70,a:97,f:102};function ol(r){if(r>=me._0&&r<=me._9)return r-me._0;if(r>=me.A&&r<=me.F)return r-(me.A-10);if(r>=me.a&&r<=me.f)return r-(me.a-10)}function tr(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=ol(r.charCodeAt(s)),a=ol(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 ye(r){return xi(ge(r))}function Xt(r){return Ir(r),xi(ge(Uint8Array.from(r).reverse()))}function Me(r,t){return tr(r.toString(16).padStart(t*2,"0"))}function we(r,t){return Me(r,t).reverse()}function Qd(r){return tr(Qe(r))}function ot(r,t,e){let n;if(typeof t=="string")try{n=tr(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Oe(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 be(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Ir(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 tp(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 ep(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var wi=r=>typeof r=="bigint"&&eo<=r;function en(r,t,e){return wi(r)&&wi(t)&&wi(e)&&t<=r&&r<e}function Et(r,t,e,n){if(!en(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function vi(r){let t;for(t=0;r>eo;r>>=ro,t+=1);return t}function rp(r,t){return r>>BigInt(t)&ro}function np(r,t,e){return r|(e?ro:eo)<<BigInt(t)}var rn=r=>(Yd<<BigInt(r-1))-ro,bi=r=>new Uint8Array(r),sl=r=>Uint8Array.from(r);function Ei(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=bi(r),o=bi(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=bi())=>{o=a(sl([0]),f),n=a(),f.length!==0&&(o=a(sl([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 p=n.slice();d.push(p),f+=n.length}return be(...d)};return(f,d)=>{i(),c(f);let p;for(;!(p=d(l()));)c();return i(),p}}var op={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"||Oe(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 Wt(r,t,e={}){let n=(o,s,i)=>{let a=op[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 er(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),rr=BigInt(2),ip=BigInt(3),Ai=BigInt(4),il=BigInt(5),al=BigInt(8),ap=BigInt(9),cp=BigInt(16);function Z(r,t){let e=r%t;return e>=mt?e:t+e}function Bi(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 oo(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 lp(r){let t=(r-ft)/rr,e,n,o;for(e=r-ft,n=0;e%rr===mt;e/=rr,n++);for(o=rr;o<r&&Bi(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)/Ai;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)/rr;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 p=1;for(let g=a.sqr(d);p<l&&!a.eql(g,a.ONE);p++)g=a.sqr(g);let y=a.pow(u,ft<<BigInt(l-p-1));u=a.sqr(y),f=a.mul(f,y),d=a.mul(d,u),l=p}return f}}function up(r){if(r%Ai===ip){let t=(r+ft)/Ai;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%al===il){let t=(r-il)/al;return function(n,o){let s=n.mul(o,rr),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,rr),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,lp(r)}var cl=(r,t)=>(Z(r,t)&ft)===ft,fp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Si(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=fp.reduce((n,o)=>(n[o]="function",n),t);return Wt(r,e)}function hp(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 dp(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 Ii(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function He(r,t,e=!1,n={}){if(r<=mt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=Ii(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:rn(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)=>hp(a,c,l),div:(c,l)=>Z(c*oo(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>oo(c,r),sqrt:n.sqrt||(c=>(i||(i=up(r)),i(a,c))),invertBatch:c=>dp(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?we(c,s):Me(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return e?Xt(c):ye(c)}});return Object.freeze(a)}function ll(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=ll(r);return t+Math.ceil(t/2)}function ul(r,t,e=!1){let n=r.length,o=ll(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):ye(r),a=Z(i,t-ft)+ft;return e?we(a,o):Me(a,o)}var fl=BigInt(0),so=BigInt(1);function ki(r,t){let e=t.negate();return r?e:t}function hl(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Ti(r,t){hl(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1);return{windows:e,windowSize:n}}function pp(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 mp(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 Ni=new WeakMap,dl=new WeakMap;function Li(r){return dl.get(r)||1}function io(r,t){return{constTimeNegate:ki,hasPrecomputes(e){return Li(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>fl;)n&so&&(o=o.add(s)),s=s.double(),n>>=so;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=Ti(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}=Ti(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 p=d*i,y=Number(o&l);o>>=f,y>i&&(y-=u,o+=so);let g=p,h=p+Math.abs(y)-1,w=d%2!==0,x=y<0;y===0?c=c.add(ki(w,n[g])):a=a.add(ki(x,n[h]))}return{p:a,f:c}},wNAFUnsafe(e,n,o,s=r.ZERO){let{windows:i,windowSize:a}=Ti(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===fl)break;let p=Number(o&c);if(o>>=u,p>a&&(p-=l,o+=so),p===0)continue;let y=n[d+Math.abs(p)-1];p<0&&(y=y.negate()),s=s.add(y)}return s},getPrecomputes(e,n,o){let s=Ni.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&Ni.set(n,o(s))),s},wNAFCached(e,n,o){let s=Li(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=Li(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){hl(n,t),dl.set(e,n),Ni.delete(e)}}}function ao(r,t,e,n){if(pp(e,r),mp(n,t),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,s=vi(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 p=0;p<n.length;p++){let y=n[p],g=Number(y>>BigInt(f)&BigInt(a));c[g]=c[g].add(e[p])}let d=o;for(let p=c.length-1,y=o;p>0;p--)y=y.add(c[p]),d=d.add(y);if(u=u.add(d),f!==0)for(let p=0;p<i;p++)u=u.double()}return u}function nn(r){return Si(r.Fp),Wt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ii(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Yt=BigInt(0),Mt=BigInt(1),co=BigInt(2),gp=BigInt(8),yp={zip215:!0};function wp(r){let t=nn(r);return Wt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function pl(r){let t=wp(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=co<<BigInt(a*8)-Mt,u=e.create,f=He(t.n,t.nBitLength),d=t.uvRatio||((v,b)=>{try{return{isValid:!0,value:e.sqrt(v*e.inv(b))}}catch{return{isValid:!1,value:Yt}}}),p=t.adjustScalarBytes||(v=>v),y=t.domain||((v,b,A)=>{if(Zt("phflag",A),b.length||A)throw new Error("Contexts/pre-hash are not supported");return v});function g(v,b){Et("coordinate "+v,b,Yt,l)}function h(v){if(!(v instanceof m))throw new Error("ExtendedPoint expected")}let w=er((v,b)=>{let{ex:A,ey:E,ez:R}=v,U=v.is0();b==null&&(b=U?gp:e.inv(R));let O=u(A*b),K=u(E*b),F=u(R*b);if(U)return{x:Yt,y:Mt};if(F!==Mt)throw new Error("invZ was invalid");return{x:O,y:K}}),x=er(v=>{let{a:b,d:A}=t;if(v.is0())throw new Error("bad point: ZERO");let{ex:E,ey:R,ez:U,et:O}=v,K=u(E*E),F=u(R*R),W=u(U*U),j=u(W*W),st=u(K*b),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 It=u(E*R),Pt=u(U*O);if(It!==Pt)throw new Error("bad point: equation left != right (2)");return!0});class m{constructor(b,A,E,R){this.ex=b,this.ey=A,this.ez=E,this.et=R,g("x",b),g("y",A),g("z",E),g("t",R),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(b){if(b instanceof m)throw new Error("extended point not allowed");let{x:A,y:E}=b||{};return g("x",A),g("y",E),new m(A,E,Mt,u(A*E))}static normalizeZ(b){let A=e.invertBatch(b.map(E=>E.ez));return b.map((E,R)=>E.toAffine(A[R])).map(m.fromAffine)}static msm(b,A){return ao(m,f,b,A)}_setWindowSize(b){N.setWindowSize(this,b)}assertValidity(){x(this)}equals(b){h(b);let{ex:A,ey:E,ez:R}=this,{ex:U,ey:O,ez:K}=b,F=u(A*K),W=u(U*R),j=u(E*K),st=u(O*R);return F===W&&j===st}is0(){return this.equals(m.ZERO)}negate(){return new m(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:b}=t,{ex:A,ey:E,ez:R}=this,U=u(A*A),O=u(E*E),K=u(co*u(R*R)),F=u(b*U),W=A+E,j=u(u(W*W)-U-O),st=F+O,it=st-K,ut=F-O,It=u(j*it),Pt=u(st*ut),_t=u(j*ut),oe=u(it*st);return new m(It,Pt,oe,_t)}add(b){h(b);let{a:A,d:E}=t,{ex:R,ey:U,ez:O,et:K}=this,{ex:F,ey:W,ez:j,et:st}=b;if(A===BigInt(-1)){let kc=u((U-R)*(W+F)),Tc=u((U+R)*(W-F)),ri=u(Tc-kc);if(ri===Yt)return this.double();let Nc=u(O*co*st),Lc=u(K*co*j),_c=Lc+Nc,Rc=Tc+kc,Uc=Lc-Nc,Ih=u(_c*ri),Ch=u(Rc*Uc),kh=u(_c*Uc),Th=u(ri*Rc);return new m(Ih,Ch,Th,kh)}let it=u(R*F),ut=u(U*W),It=u(K*E*st),Pt=u(O*j),_t=u((R+U)*(F+W)-it-ut),oe=Pt-It,fe=Pt+It,Gr=u(ut-A*it),Eh=u(_t*oe),Ah=u(fe*Gr),Bh=u(_t*Gr),Sh=u(oe*fe);return new m(Eh,Ah,Sh,Bh)}subtract(b){return this.add(b.negate())}wNAF(b){return N.wNAFCached(this,b,m.normalizeZ)}multiply(b){let A=b;Et("scalar",A,Mt,n);let{p:E,f:R}=this.wNAF(A);return m.normalizeZ([E,R])[0]}multiplyUnsafe(b,A=m.ZERO){let E=b;return Et("scalar",E,Yt,n),E===Yt?L:this.is0()||E===Mt?this:N.wNAFCachedUnsafe(this,E,m.normalizeZ,A)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return N.unsafeLadder(this,n).is0()}toAffine(b){return w(this,b)}clearCofactor(){let{h:b}=t;return b===Mt?this:this.multiplyUnsafe(b)}static fromHex(b,A=!1){let{d:E,a:R}=t,U=e.BYTES;b=ot("pointHex",b,U),Zt("zip215",A);let O=b.slice(),K=b[U-1];O[U-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-R),{isValid:ut,value:It}=d(st,it);if(!ut)throw new Error("Point.fromHex: invalid y coordinate");let Pt=(It&Mt)===Mt,_t=(K&128)!==0;if(!A&&It===Yt&&_t)throw new Error("Point.fromHex: x=0 and x_0=1");return _t!==Pt&&(It=u(-It)),m.fromAffine({x:It,y:F})}static fromPrivateKey(b){return S(b).point}toRawBytes(){let{x:b,y:A}=this.toAffine(),E=we(A,e.BYTES);return E[E.length-1]|=b&Mt?128:0,E}toHex(){return ge(this.toRawBytes())}}m.BASE=new m(t.Gx,t.Gy,Mt,u(t.Gx*t.Gy)),m.ZERO=new m(Yt,Mt,Mt,Yt);let{BASE:I,ZERO:L}=m,N=io(m,a*8);function B(v){return Z(v,n)}function k(v){return B(Xt(v))}function S(v){let b=e.BYTES;v=ot("private key",v,b);let A=ot("hashed private key",s(v),2*b),E=p(A.slice(0,b)),R=A.slice(b,2*b),U=k(E),O=I.multiply(U),K=O.toRawBytes();return{head:E,prefix:R,scalar:U,point:O,pointBytes:K}}function H(v){return S(v).pointBytes}function _(v=new Uint8Array,...b){let A=be(...b);return k(s(y(A,ot("context",v),!!o)))}function M(v,b,A={}){v=ot("message",v),o&&(v=o(v));let{prefix:E,scalar:R,pointBytes:U}=S(b),O=_(A.context,E,v),K=I.multiply(O).toRawBytes(),F=_(A.context,K,U,v),W=B(O+F*R);Et("signature.s",W,Yt,n);let j=be(K,we(W,e.BYTES));return ot("result",j,e.BYTES*2)}let V=yp;function C(v,b,A,E=V){let{context:R,zip215:U}=E,O=e.BYTES;v=ot("signature",v,2*O),b=ot("message",b),A=ot("publicKey",A,O),U!==void 0&&Zt("zip215",U),o&&(b=o(b));let K=Xt(v.slice(O,2*O)),F,W,j;try{F=m.fromHex(A,U),W=m.fromHex(v.slice(0,O),U),j=I.multiplyUnsafe(K)}catch{return!1}if(!U&&F.isSmallOrder())return!1;let st=_(R,W.toRawBytes(),F.toRawBytes(),b);return W.add(F.multiplyUnsafe(st)).subtract(j).clearCofactor().equals(m.ZERO)}return I._setWindowSize(8),{CURVE:t,getPublicKey:H,sign:M,verify:C,ExtendedPoint:m,utils:{getExtendedPublicKey:S,randomPrivateKey:()=>i(e.BYTES),precompute(v=8,b=m.BASE){return b._setWindowSize(v),b.multiply(BigInt(3)),b}}}}var Cr=BigInt(0),_i=BigInt(1);function bp(r){return Wt(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function ml(r){let t=bp(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=>Bi(x,e-BigInt(2),e));function l(x,m,I){let L=n(x*(m-I));return m=n(m-L),I=n(I+L),[m,I]}let u=(t.a-BigInt(2))/BigInt(4);function f(x,m){Et("u",x,Cr,e),Et("scalar",m,Cr,e);let I=m,L=x,N=_i,B=Cr,k=x,S=_i,H=Cr,_;for(let V=BigInt(o-1);V>=Cr;V--){let C=I>>V&_i;H^=C,_=l(H,N,k),N=_[0],k=_[1],_=l(H,B,S),B=_[0],S=_[1],H=C;let T=N+B,v=n(T*T),b=N-B,A=n(b*b),E=v-A,R=k+S,U=k-S,O=n(U*T),K=n(R*b),F=O+K,W=O-K;k=n(F*F),S=n(L*n(W*W)),N=n(v*A),B=n(E*(v+n(u*E)))}_=l(H,N,k),N=_[0],k=_[1],_=l(H,B,S),B=_[0],S=_[1];let M=c(B);return n(N*M)}function d(x){return we(n(x),s)}function p(x){let m=ot("u coordinate",x,s);return i===32&&(m[31]&=127),Xt(m)}function y(x){let m=ot("scalar",x),I=m.length;if(I!==s&&I!==i){let L=""+s+" or "+i;throw new Error("invalid scalar, expected "+L+" bytes, got "+I)}return Xt(a(m))}function g(x,m){let I=p(m),L=y(x),N=f(I,L);if(N===Cr)throw new Error("invalid private or public key received");return d(N)}let h=d(t.Gu);function w(x){return g(x,h)}return{scalarMult:g,scalarMultBase:w,getSharedSecret:(x,m)=>g(x,m),getPublicKey:x=>w(x),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:h}}var on=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),gl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Ky=BigInt(0),xp=BigInt(1),yl=BigInt(2),vp=BigInt(3),Ep=BigInt(5),Ap=BigInt(8);function wl(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=on,a=r*r%s*r%s,c=at(a,yl,s)*a%s,l=at(c,xp,s)*r%s,u=at(l,Ep,s)*l%s,f=at(u,t,s)*u%s,d=at(f,e,s)*f%s,p=at(d,n,s)*d%s,y=at(p,o,s)*p%s,g=at(y,o,s)*p%s,h=at(g,t,s)*u%s;return{pow_p_5_8:at(h,yl,s)*r%s,b2:a}}function bl(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Bp(r,t){let e=on,n=Z(t*t*t,e),o=Z(n*n*t,e),s=wl(r*o).pow_p_5_8,i=Z(r*n*s,e),a=Z(t*i*i,e),c=i,l=Z(i*gl,e),u=a===r,f=a===Z(-r,e),d=a===Z(-r*gl,e);return u&&(i=c),(f||d)&&(i=l),cl(i,e)&&(i=Z(-i,e)),{isValid:u||f,value:i}}var Sp=He(on,void 0,!0),Ip={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Sp,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Ap,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:nl,randomBytes:tn,adjustScalarBytes:bl,uvRatio:Bp},xl=pl(Ip);var sn=ml({P:on,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let t=on,{pow_p_5_8:e,b2:n}=wl(r);return Z(at(e,vp,t)*n,t)},adjustScalarBytes:bl,randomBytes:tn});var lo=32;function vl(r,t,e){return xl.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}var uo=class{type="Ed25519";raw;constructor(t){this.raw=Ri(t,lo)}toMultihash(){return pe.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:Rt(this.raw,t.raw)}verify(t,e){return vl(this.raw,e,t)}};function Ui(r){return r=Ri(r,lo),new uo(r)}function Ri(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new et(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}function gt(r=0){return new Uint8Array(r)}function yt(r=0){return new Uint8Array(r)}var kp=Math.pow(2,7),Tp=Math.pow(2,14),Np=Math.pow(2,21),Di=Math.pow(2,28),Pi=Math.pow(2,35),Oi=Math.pow(2,42),Mi=Math.pow(2,49),J=128,kt=127;function ct(r){if(r<kp)return 1;if(r<Tp)return 2;if(r<Np)return 3;if(r<Di)return 4;if(r<Pi)return 5;if(r<Oi)return 6;if(r<Mi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Hi(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 Lp(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 Vi(r,t){let e=r[t],n=0;if(n+=e&kt,e<J||(e=r[t+1],n+=(e&kt)<<7,e<J)||(e=r[t+2],n+=(e&kt)<<14,e<J)||(e=r[t+3],n+=(e&kt)<<21,e<J)||(e=r[t+4],n+=(e&kt)*Di,e<J)||(e=r[t+5],n+=(e&kt)*Pi,e<J)||(e=r[t+6],n+=(e&kt)*Oi,e<J)||(e=r[t+7],n+=(e&kt)*Mi,e<J))return n;throw new RangeError("Could not decode varint")}function _p(r,t){let e=r.get(t),n=0;if(n+=e&kt,e<J||(e=r.get(t+1),n+=(e&kt)<<7,e<J)||(e=r.get(t+2),n+=(e&kt)<<14,e<J)||(e=r.get(t+3),n+=(e&kt)<<21,e<J)||(e=r.get(t+4),n+=(e&kt)*Di,e<J)||(e=r.get(t+5),n+=(e&kt)*Pi,e<J)||(e=r.get(t+6),n+=(e&kt)*Oi,e<J)||(e=r.get(t+7),n+=(e&kt)*Mi,e<J))return n;throw new RangeError("Could not decode varint")}function se(r,t,e=0){return t==null&&(t=yt(ct(r))),t instanceof Uint8Array?Hi(r,t,e):Lp(r,t,e)}function Jt(r,t=0){return r instanceof Uint8Array?Vi(r,t):_p(r,t)}var Fi=new Float32Array([-0]),Ve=new Uint8Array(Fi.buffer);function Al(r,t,e){Fi[0]=r,t[e]=Ve[0],t[e+1]=Ve[1],t[e+2]=Ve[2],t[e+3]=Ve[3]}function Bl(r,t){return Ve[0]=r[t],Ve[1]=r[t+1],Ve[2]=r[t+2],Ve[3]=r[t+3],Fi[0]}var Ki=new Float64Array([-0]),Tt=new Uint8Array(Ki.buffer);function Sl(r,t,e){Ki[0]=r,t[e]=Tt[0],t[e+1]=Tt[1],t[e+2]=Tt[2],t[e+3]=Tt[3],t[e+4]=Tt[4],t[e+5]=Tt[5],t[e+6]=Tt[6],t[e+7]=Tt[7]}function Il(r,t){return Tt[0]=r[t],Tt[1]=r[t+1],Tt[2]=r[t+2],Tt[3]=r[t+3],Tt[4]=r[t+4],Tt[5]=r[t+5],Tt[6]=r[t+6],Tt[7]=r[t+7],Ki[0]}var Rp=BigInt(Number.MAX_SAFE_INTEGER),Up=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 nr;if(t<Rp&&t>Up)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>Cl&&(o=0n,++n>Cl&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return nr;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):nr}},nr=new Kt(0,0);nr.toBigInt=function(){return 0n};nr.zzEncode=nr.zzDecode=function(){return this};nr.length=function(){return 1};var Cl=4294967296n;function kl(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 Tl(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 $i(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 fo(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Wi=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 fo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Qt(this,4);return fo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Qt(this,4);let t=Bl(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Qt(this,4);let t=Il(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 Tl(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=fo(this.buf,this.pos+=4),e=fo(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=Vi(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 qi(r){return new Wi(r instanceof Uint8Array?r:r.subarray())}function te(r,t,e){let n=qi(r);return t.decode(n,void 0,e)}var zi={};Ct(zi,{base10:()=>Dp});var Dp=_e({prefix:"9",name:"base10",alphabet:"0123456789"});var Gi={};Ct(Gi,{base16:()=>Pp,base16upper:()=>Op});var Pp=dt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Op=dt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ji={};Ct(ji,{base2:()=>Mp});var Mp=dt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Zi={};Ct(Zi,{base256emoji:()=>$p});var Ll=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}"),Hp=Ll.reduce((r,t,e)=>(r[e]=t,r),[]),Vp=Ll.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Fp(r){return r.reduce((t,e)=>(t+=Hp[e],t),"")}function Kp(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Vp[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var $p=br({prefix:"\u{1F680}",name:"base256emoji",encode:Fp,decode:Kp});var Yi={};Ct(Yi,{base64:()=>Wp,base64pad:()=>qp,base64url:()=>Xi,base64urlpad:()=>zp});var Wp=dt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),qp=dt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Xi=dt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zp=dt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ji={};Ct(Ji,{base8:()=>Gp});var Gp=dt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Qi={};Ct(Qi,{identity:()=>jp});var jp=br({prefix:"\0",name:"identity",encode:r=>Vc(r),decode:r=>Hc(r)});var Bw=new TextEncoder,Sw=new TextDecoder;var ra={};Ct(ra,{sha256:()=>cn,sha512:()=>Yp});function ea({name:r,code:t,encode:e}){return new ta(r,t,e)}var ta=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?Ot(this.code,e):e.then(n=>Ot(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Rl(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var cn=ea({name:"sha2-256",code:18,encode:Rl("SHA-256")}),Yp=ea({name:"sha2-512",code:19,encode:Rl("SHA-512")});var or={...Qi,...ji,...Ji,...zi,...Gi,...li,...ui,...ci,...Yi,...Zi},Ow={...ra,...pi};function Dl(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Ul=Dl("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),na=Dl("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}),Jp={utf8:Ul,"utf-8":Ul,hex:or.base16,latin1:na,ascii:na,binary:na,...or},ho=Jp;function Q(r,t="utf8"){let e=ho[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function oa(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 sr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function sa(){}var aa=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Qp=oa();function t0(r){return globalThis.Buffer!=null?yt(r):Qp(r)}var un=class{len;head;tail;states;constructor(){this.len=0,this.head=new sr(sa,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new sr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ca((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(po,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(po,e.length(),e)}uint64Number(t){return this._push(Hi,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(po,e.length(),e)}sint64Number(t){let e=Kt.fromNumber(t).zzEncode();return this._push(po,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ia,1,t?1:0)}fixed32(t){return this._push(ln,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Kt.fromBigInt(t);return this._push(ln,4,e.lo)._push(ln,4,e.hi)}fixed64Number(t){let e=Kt.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(Al,4,t)}double(t){return this._push(Sl,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ia,1,0):this.uint32(e)._push(r0,e,t)}string(t){let e=kl(t);return e!==0?this.uint32(e)._push($i,e,t):this._push(ia,1,0)}fork(){return this.states=new aa(this),this.head=this.tail=new sr(sa,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 sr(sa,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=t0(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ia(r,t,e){t[e]=r&255}function e0(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ca=class extends sr{next;constructor(t,e){super(e0,t,e),this.next=void 0}};function po(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 r0(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(n0,t,r),this},un.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(o0,t,r),this});function n0(r,t,e){t.set(r,e)}function o0(r,t,e){r.length<40?$i(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Q(r),e)}function la(){return new un}function ee(r,t){let e=la();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 mo(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function ir(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 mo("enum",Tr.VARINT,e,n)}function re(r,t){return mo("message",Tr.LENGTH_DELIMITED,r,t)}var wt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(wt||(wt={}));var ua;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(ua||(ua={}));(function(r){r.codec=()=>ir(ua)})(wt||(wt={}));var ie;(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)})(ie||(ie={}));var fa;(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)})(fa||(fa={}));var xn={};Ct(xn,{MAX_RSA_KEY_SIZE:()=>is,generateRSAKeyPair:()=>_u,jwkToJWKKeyPair:()=>Ru,jwkToPkcs1:()=>x0,jwkToPkix:()=>xa,jwkToRSAPrivateKey:()=>Lu,pkcs1ToJwk:()=>ku,pkcs1ToRSAPrivateKey:()=>Nu,pkixToJwk:()=>Tu,pkixToRSAPublicKey:()=>va});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]),Fe=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ke=new Uint32Array(64),ha=class extends Sr{constructor(){super(64,32,8,!1),this.A=Fe[0]|0,this.B=Fe[1]|0,this.C=Fe[2]|0,this.D=Fe[3]|0,this.E=Fe[4]|0,this.F=Fe[5]|0,this.G=Fe[6]|0,this.H=Fe[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)Ke[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Ke[f-15],p=Ke[f-2],y=jt(d,7)^jt(d,18)^d>>>3,g=jt(p,17)^jt(p,19)^p>>>10;Ke[f]=g+Ke[f-7]+y+Ke[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),p=u+d+tl(a,c,l)+s0[f]+Ke[f]|0,g=(jt(n,2)^jt(n,13)^jt(n,22))+el(n,o,s)|0;u=l,l=c,c=a,a=i+p|0,i=s,s=o,o=n,n=p+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(){Ke.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ae=Qn(()=>new ha);var z=Ph(Ol());function ar(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 $e(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 wo(...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 pa(){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=ar(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,ar(s,8)-n}function Ml(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=$e(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=$e(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 Hl(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 wb=Math.log(2);function bo(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function ma(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 Be(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 ma(this.items)}},fn=[new Uint8Array([1])],Vl="0123456789";var Ur="",ne=new ArrayBuffer(0),ga=new Uint8Array(0),dn="EndOfContent",Kl="OCTET STRING",$l="BIT STRING";function Se(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?z.BufferSourceConverter.toUint8Array(s.valueHex):ga}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(!Be(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:z.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var ve=class{constructor({blockLength:t=0,error:e=Ur,warnings:n=[],valueBeforeDecode:o=ga}={}){this.blockLength=t,this.error=e,this.warnings=n,this.valueBeforeDecodeView=z.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:z.Convert.ToHex(this.valueBeforeDecodeView)}}};ve.NAME="baseBlock";var Nt=class extends ve{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 xo=class extends Se(ve){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?z.BufferSourceConverter.toUint8Array(t.valueHex):ga,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=$e(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=z.BufferSourceConverter.toUint8Array(t);if(!Be(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 p=0;p<l.length;p++)d[p]=l[p];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=ar(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}}};xo.NAME="identificationBlock";var vo=class extends ve{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=z.BufferSourceConverter.toUint8Array(t);if(!Be(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=ar(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=$e(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}}};vo.NAME="lengthBlock";var D={},At=class extends ve{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 xo(o),this.lenBlock=new vo(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||Wl(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():z.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${z.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 Hl(e,n)}};At.NAME="BaseBlock";function Wl(r){if(r instanceof D.Constructed)for(let t of r.valueBlock.value)Wl(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var Eo=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}'`}};Eo.NAME="BaseStringBlock";var Ao=class extends Se(Nt){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};Ao.NAME="PrimitiveValueBlock";var ql,Bo=class extends At{constructor(t={}){super(t,Ao),this.idBlock.isConstructed=!1}};ql=Bo;D.Primitive=ql;Bo.NAME="PRIMITIVE";function p0(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 os(r,t=0,e=r.length){let n=t,o=new At({},Nt),s=new ve;if(!Be(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=p0(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 ya(r){if(!r.byteLength){let t=new At({},Nt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return os(z.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function m0(r,t){return r?1:t}var ce=class extends Nt{constructor({value:t=[],isIndefiniteForm:e=!1,...n}={}){super(n),this.value=t,this.isIndefiniteForm=e}fromBER(t,e,n){let o=z.BufferSourceConverter.toUint8Array(t);if(!Be(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(;m0(this.isIndefiniteForm,n)>0;){let i=os(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?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}};ce.NAME="ConstructedValueBlock";var zl,We=class extends At{constructor(t={}){super(t,ce),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 Th=Object.create;var Fn=Object.defineProperty;var Nh=Object.getOwnPropertyDescriptor;var Lh=Object.getOwnPropertyNames;var _h=Object.getPrototypeOf,Rh=Object.prototype.hasOwnProperty;var Uh=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Ct=(r,t)=>{for(var e in t)Fn(r,e,{get:t[e],enumerable:!0})},Uc=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Lh(t))!Rh.call(r,o)&&o!==e&&Fn(r,o,{get:()=>t[o],enumerable:!(n=Nh(t,o))||n.enumerable});return r};var Dh=(r,t,e)=>(e=r!=null?Th(_h(r)):{},Uc(t||!r||!r.__esModule?Fn(e,"default",{value:r,enumerable:!0}):e,r)),Ph=r=>Uc(Fn({},"__esModule",{value:!0}),r);var Pl=Uh(Nr=>{"use strict";var s0="[object ArrayBuffer]",xe=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===s0}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}},ha="string",i0=/^[0-9a-f\s]+$/i,a0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,c0=/^[a-zA-Z0-9-_]+$/,mo=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=xe.toUint8Array(t),n="";for(let s=0;s<e.length;s++)n+=String.fromCharCode(e[s]);return decodeURIComponent(escape(n))}},qt=class{static toString(t,e=!1){let n=xe.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}},go=class r{static isHex(t){return typeof t===ha&&i0.test(t)}static isBase64(t){return typeof t===ha&&a0.test(t)}static isBase64Url(t){return typeof t===ha&&c0.test(t)}static ToString(t,e="utf8"){let n=xe.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 qt.toString(n,!0);case"utf16":case"utf16be":return qt.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 qt.fromString(t,!0);case"utf16":case"utf16be":return qt.fromString(t);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToBase64(t){let e=xe.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 mo.fromString(t);case"utf16":case"utf16be":return qt.fromString(t);case"utf16le":case"usc2":return qt.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 mo.toString(t);case"utf16":case"utf16be":return qt.toString(t);case"utf16le":case"usc2":return qt.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=xe.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=xe.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 qt.toString(t,e)}static FromUtf16String(t,e=!1){return qt.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,"")||""}};go.DEFAULT_UTF8_ENCODING="utf8";function l0(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 u0(...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 f0(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=xe;Nr.Convert=go;Nr.assign=l0;Nr.combine=u0;Nr.isEqual=f0});var pg={};Ct(pg,{webRTC:()=>dg,webRTCDirect:()=>hg});var ri=Symbol.for("@libp2p/peer-id");var Kn=Symbol.for("@libp2p/transport");var Dc;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Dc||(Dc={}));var $n=class extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}};var et=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},yr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Wn=class extends Error{static name="ConnectionFailedError";constructor(t="Connection failed"){super(t),this.name="ConnectionFailedError"}};var qn=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}},Ze=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 Gn=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var jr=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}};var Xe=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var jn=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"),Pc=Symbol.for("@libp2p/service-dependencies");var ai={};Ct(ai,{base58btc:()=>nt,base58flickr:()=>Kh});var Kg=new Uint8Array(0);function Oc(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 he(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 Hc(r){return new TextEncoder().encode(r)}function Mc(r){return new TextDecoder().decode(r)}function Oh(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,w=0,x=y.length;w!==x&&y[w]===0;)w++,g++;for(var m=(x-w)*u+1>>>0,I=new Uint8Array(m);w!==x;){for(var L=y[w],N=0,B=m-1;(L!==0||N<h)&&B!==-1;B--,N++)L+=256*I[B]>>>0,I[B]=L%a>>>0,L=L/a>>>0;if(L!==0)throw new Error("Non-zero carry");h=N,w++}for(var k=m-h;k!==m&&I[k]===0;)k++;for(var S=c.repeat(g);k<m;++k)S+=r.charAt(I[k]);return S}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,w=0;y[g]===c;)h++,g++;for(var x=(y.length-g)*l+1>>>0,m=new Uint8Array(x);y[g];){var I=e[y.charCodeAt(g)];if(I===255)return;for(var L=0,N=x-1;(I!==0||L<w)&&N!==-1;N--,L++)I+=a*m[N]>>>0,m[N]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");w=L,g++}if(y[g]!==" "){for(var B=x-w;B!==x&&m[B]===0;)B++;for(var k=new Uint8Array(h+(x-B)),S=h;B!==x;)k[S++]=m[B++];return k}}}function p(y){var g=d(y);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:p}}var Hh=Oh,Mh=Hh,Fc=Mh;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 Kc(this,t)}},si=class{decoders;constructor(t){this.decoders=t}or(t){return Kc(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 Kc(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 _e({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Fc(e,r);return br({prefix:t,name:r,encode:n,decode:s=>he(o(s))})}function Vh(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 Fh(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 Fh(o,n,e)},decode(o){return Vh(o,n,e,r)}})}var nt=_e({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Kh=_e({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ci={};Ct(ci,{base32:()=>de,base32hex:()=>zh,base32hexpad:()=>jh,base32hexpadupper:()=>Zh,base32hexupper:()=>Gh,base32pad:()=>Wh,base32padupper:()=>qh,base32upper:()=>$h,base32z:()=>Xh});var de=dt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$h=dt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Wh=dt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),qh=dt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),zh=dt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Gh=dt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),jh=dt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Zh=dt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Xh=dt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var li={};Ct(li,{base36:()=>Zr,base36upper:()=>Yh});var Zr=_e({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Yh=_e({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Gt={};Ct(Gt,{Digest:()=>Ye,create:()=>Ot,decode:()=>Re,equals:()=>fi,hasCode:()=>gd});var Jh=qc,$c=128,Qh=127,td=~Qh,ed=Math.pow(2,31);function qc(r,t,e){t=t||[],e=e||0;for(var n=e;r>=ed;)t[e++]=r&255|$c,r/=128;for(;r&td;)t[e++]=r&255|$c,r>>>=7;return t[e]=r|0,qc.bytes=e-n+1,t}var rd=ui,nd=128,Wc=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&Wc)<<o:(i&Wc)*Math.pow(2,o),o+=7}while(i>=nd);return ui.bytes=s-n,e}var od=Math.pow(2,7),sd=Math.pow(2,14),id=Math.pow(2,21),ad=Math.pow(2,28),cd=Math.pow(2,35),ld=Math.pow(2,42),ud=Math.pow(2,49),fd=Math.pow(2,56),hd=Math.pow(2,63),dd=function(r){return r<od?1:r<sd?2:r<id?3:r<ad?4:r<cd?5:r<ld?6:r<ud?7:r<fd?8:r<hd?9:10},pd={encode:Jh,decode:rd,encodingLength:dd},md=pd,Xr=md;function Yr(r,t=0){return[Xr.decode(r,t),Xr.decode.bytes]}function xr(r,t,e=0){return Xr.encode(r,t,e),t}function vr(r){return Xr.encodingLength(r)}function Ot(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 Ye(r,e,t,s)}function Re(r){let t=he(r),[e,n]=Yr(t),[o,s]=Yr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Ye(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&&Oc(r.bytes,e.bytes)}}var Ye=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function gd(r,t){return r.code===t}function zc(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return wd(e,hi(r),t??nt.encoder);default:return bd(e,hi(r),t??de.encoder)}}var Gc=new WeakMap;function hi(r){let t=Gc.get(r);if(t==null){let e=new Map;return Gc.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!==Jr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==xd)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=Ot(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??jc(n,o,s.bytes))}else if(e[vd]===!0){let{version:n,multihash:o,code:s}=e,i=Re(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!==Jr)throw new Error(`Version 0 CID must use dag-pb (code: ${Jr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=jc(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Jr,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=he(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 Ye(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]=Yr(t.subarray(e));return e+=d,f},o=n(),s=Jr;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]=yd(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 yd(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 de.prefix:{let e=t??de;return[de.prefix,e.decode(r)]}case Zr.prefix:{let e=t??Zr;return[Zr.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 wd(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 bd(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 Jr=112,xd=18;function jc(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 vd=Symbol.for("@ipld/js-cid/CID");var di={};Ct(di,{identity:()=>pe});var Zc=0,Ed="identity",Xc=he;function Ad(r){return Ot(Zc,Xc(r))}var pe={code:Zc,name:Ed,encode:Xc,digest:Ad};function Rt(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 Xn(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Bd(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Er(r,...t){if(!Bd(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 Qr(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Xn(r.outputLen),Xn(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 Yc(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 Je=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Yn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function jt(r,t){return r<<32-t|r>>>t}function Jc(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function Ue(r){return typeof r=="string"&&(r=Jc(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 Jn(r){let t=n=>r().update(Ue(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function tn(r=32){if(Je&&typeof Je.getRandomValues=="function")return Je.getRandomValues(new Uint8Array(r));if(Je&&typeof Je.randomBytes=="function")return Je.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function Sd(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 Qc(r,t,e){return r&t^~r&e}function tl(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=Yn(this.buffer)}update(t){Ar(this);let{view:e,buffer:n,blockLen:o}=this;t=Ue(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=Yn(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),Yc(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;Sd(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Yn(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 Qn=BigInt(4294967295),mi=BigInt(32);function el(r,t=!1){return t?{h:Number(r&Qn),l:Number(r>>mi&Qn)}:{h:Number(r>>mi&Qn)|0,l:Number(r&Qn)|0}}function Id(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}=el(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var Cd=(r,t)=>BigInt(r>>>0)<<mi|BigInt(t>>>0),kd=(r,t,e)=>r>>>e,Td=(r,t,e)=>r<<32-e|t>>>e,Nd=(r,t,e)=>r>>>e|t<<32-e,Ld=(r,t,e)=>r<<32-e|t>>>e,_d=(r,t,e)=>r<<64-e|t>>>e-32,Rd=(r,t,e)=>r>>>e-32|t<<64-e,Ud=(r,t)=>t,Dd=(r,t)=>r,Pd=(r,t,e)=>r<<e|t>>>32-e,Od=(r,t,e)=>t<<e|r>>>32-e,Hd=(r,t,e)=>t<<e-32|r>>>64-e,Md=(r,t,e)=>r<<e-32|t>>>64-e;function Vd(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Fd=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Kd=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,$d=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Wd=(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),zd=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var Gd={fromBig:el,split:Id,toBig:Cd,shrSH:kd,shrSL:Td,rotrSH:Nd,rotrSL:Ld,rotrBH:_d,rotrBL:Rd,rotr32H:Ud,rotr32L:Dd,rotlSH:Pd,rotlSL:Od,rotlBH:Hd,rotlBL:Md,add:Vd,add3L:Fd,add3H:Kd,add4L:$d,add4H:Wd,add5H:zd,add5L:qd},$=Gd;var[jd,Zd]=$.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))),De=new Uint32Array(80),Pe=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:p,Gl:y,Hh:g,Hl:h}=this;return[t,e,n,o,s,i,a,c,l,u,f,d,p,y,g,h]}set(t,e,n,o,s,i,a,c,l,u,f,d,p,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=p|0,this.Gl=y|0,this.Hh=g|0,this.Hl=h|0}process(t,e){for(let m=0;m<16;m++,e+=4)De[m]=t.getUint32(e),Pe[m]=t.getUint32(e+=4);for(let m=16;m<80;m++){let I=De[m-15]|0,L=Pe[m-15]|0,N=$.rotrSH(I,L,1)^$.rotrSH(I,L,8)^$.shrSH(I,L,7),B=$.rotrSL(I,L,1)^$.rotrSL(I,L,8)^$.shrSL(I,L,7),k=De[m-2]|0,S=Pe[m-2]|0,M=$.rotrSH(k,S,19)^$.rotrBH(k,S,61)^$.shrSH(k,S,6),_=$.rotrSL(k,S,19)^$.rotrBL(k,S,61)^$.shrSL(k,S,6),H=$.add4L(B,_,Pe[m-7],Pe[m-16]),V=$.add4H(H,N,M,De[m-7],De[m-16]);De[m]=V|0,Pe[m]=H|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:p,Fl:y,Gh:g,Gl:h,Hh:w,Hl:x}=this;for(let m=0;m<80;m++){let I=$.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&p^~f&g,B=d&y^~d&h,k=$.add5L(x,L,B,Zd[m],Pe[m]),S=$.add5H(k,w,I,N,jd[m],De[m]),M=k|0,_=$.rotrSH(n,o,28)^$.rotrBH(n,o,34)^$.rotrBH(n,o,39),H=$.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;w=g|0,x=h|0,g=p|0,h=y|0,p=f|0,y=d|0,{h:f,l:d}=$.add(l|0,u|0,S|0,M|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let T=$.add3L(M,H,C);n=$.add3H(T,S,_,V),o=T|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:p,l:y}=$.add(this.Fh|0,this.Fl|0,p|0,y|0),{h:g,l:h}=$.add(this.Gh|0,this.Gl|0,g|0,h|0),{h:w,l:x}=$.add(this.Hh|0,this.Hl|0,w|0,x|0),this.set(n,o,s,i,a,c,l,u,f,d,p,y,g,h,w,x)}roundClean(){De.fill(0),Pe.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 rl=Jn(()=>new gi);var ro={};Ct(ro,{aInRange:()=>Et,abool:()=>Zt,abytes:()=>Ir,bitGet:()=>ep,bitLen:()=>xi,bitMask:()=>rn,bitSet:()=>rp,bytesToHex:()=>ge,bytesToNumberBE:()=>ye,bytesToNumberLE:()=>Xt,concatBytes:()=>be,createHmacDrbg:()=>vi,ensureBytes:()=>ot,equalBytes:()=>Qd,hexToBytes:()=>tr,hexToNumber:()=>bi,inRange:()=>en,isBytes:()=>Oe,memoized:()=>er,notImplemented:()=>op,numberToBytesBE:()=>He,numberToBytesLE:()=>we,numberToHexUnpadded:()=>Qe,numberToVarBytesBE:()=>Jd,utf8ToBytes:()=>tp,validateObject:()=>Wt});var to=BigInt(0),eo=BigInt(1),Xd=BigInt(2);function Oe(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ir(r){if(!Oe(r))throw new Error("Uint8Array expected")}function Zt(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}var Yd=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function ge(r){Ir(r);let t="";for(let e=0;e<r.length;e++)t+=Yd[r[e]];return t}function Qe(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===""?to:BigInt("0x"+r)}var me={_0:48,_9:57,A:65,F:70,a:97,f:102};function nl(r){if(r>=me._0&&r<=me._9)return r-me._0;if(r>=me.A&&r<=me.F)return r-(me.A-10);if(r>=me.a&&r<=me.f)return r-(me.a-10)}function tr(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=nl(r.charCodeAt(s)),a=nl(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 ye(r){return bi(ge(r))}function Xt(r){return Ir(r),bi(ge(Uint8Array.from(r).reverse()))}function He(r,t){return tr(r.toString(16).padStart(t*2,"0"))}function we(r,t){return He(r,t).reverse()}function Jd(r){return tr(Qe(r))}function ot(r,t,e){let n;if(typeof t=="string")try{n=tr(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Oe(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 be(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Ir(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 Qd(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 tp(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var yi=r=>typeof r=="bigint"&&to<=r;function en(r,t,e){return yi(r)&&yi(t)&&yi(e)&&t<=r&&r<e}function Et(r,t,e,n){if(!en(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function xi(r){let t;for(t=0;r>to;r>>=eo,t+=1);return t}function ep(r,t){return r>>BigInt(t)&eo}function rp(r,t,e){return r|(e?eo:to)<<BigInt(t)}var rn=r=>(Xd<<BigInt(r-1))-eo,wi=r=>new Uint8Array(r),ol=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(ol([0]),f),n=a(),f.length!==0&&(o=a(ol([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 p=n.slice();d.push(p),f+=n.length}return be(...d)};return(f,d)=>{i(),c(f);let p;for(;!(p=d(l()));)c();return i(),p}}var np={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"||Oe(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 Wt(r,t,e={}){let n=(o,s,i)=>{let a=np[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 op=()=>{throw new Error("not implemented")};function er(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),rr=BigInt(2),sp=BigInt(3),Ei=BigInt(4),sl=BigInt(5),il=BigInt(8),ip=BigInt(9),ap=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 no(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 cp(r){let t=(r-ft)/rr,e,n,o;for(e=r-ft,n=0;e%rr===mt;e/=rr,n++);for(o=rr;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)/rr;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 p=1;for(let g=a.sqr(d);p<l&&!a.eql(g,a.ONE);p++)g=a.sqr(g);let y=a.pow(u,ft<<BigInt(l-p-1));u=a.sqr(y),f=a.mul(f,y),d=a.mul(d,u),l=p}return f}}function lp(r){if(r%Ei===sp){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%il===sl){let t=(r-sl)/il;return function(n,o){let s=n.mul(o,rr),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,rr),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%ap,cp(r)}var al=(r,t)=>(Z(r,t)&ft)===ft,up=["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=up.reduce((n,o)=>(n[o]="function",n),t);return Wt(r,e)}function fp(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 hp(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 Me(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:rn(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)=>fp(a,c,l),div:(c,l)=>Z(c*no(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>no(c,r),sqrt:n.sqrt||(c=>(i||(i=lp(r)),i(a,c))),invertBatch:c=>hp(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?we(c,s):He(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return e?Xt(c):ye(c)}});return Object.freeze(a)}function cl(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 Ii(r){let t=cl(r);return t+Math.ceil(t/2)}function ll(r,t,e=!1){let n=r.length,o=cl(t),s=Ii(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?Xt(r):ye(r),a=Z(i,t-ft)+ft;return e?we(a,o):He(a,o)}var ul=BigInt(0),oo=BigInt(1);function Ci(r,t){let e=t.negate();return r?e:t}function fl(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){fl(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1);return{windows:e,windowSize:n}}function dp(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 pp(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,hl=new WeakMap;function Ni(r){return hl.get(r)||1}function so(r,t){return{constTimeNegate:Ci,hasPrecomputes(e){return Ni(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>ul;)n&oo&&(o=o.add(s)),s=s.double(),n>>=oo;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 p=d*i,y=Number(o&l);o>>=f,y>i&&(y-=u,o+=oo);let g=p,h=p+Math.abs(y)-1,w=d%2!==0,x=y<0;y===0?c=c.add(Ci(w,n[g])):a=a.add(Ci(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===ul)break;let p=Number(o&c);if(o>>=u,p>a&&(p-=l,o+=oo),p===0)continue;let y=n[d+Math.abs(p)-1];p<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){fl(n,t),hl.set(e,n),Ti.delete(e)}}}function io(r,t,e,n){if(dp(e,r),pp(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 p=0;p<n.length;p++){let y=n[p],g=Number(y>>BigInt(f)&BigInt(a));c[g]=c[g].add(e[p])}let d=o;for(let p=c.length-1,y=o;p>0;p--)y=y.add(c[p]),d=d.add(y);if(u=u.add(d),f!==0)for(let p=0;p<i;p++)u=u.double()}return u}function nn(r){return Bi(r.Fp),Wt(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),Ht=BigInt(1),ao=BigInt(2),mp=BigInt(8),gp={zip215:!0};function yp(r){let t=nn(r);return Wt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function dl(r){let t=yp(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=ao<<BigInt(a*8)-Ht,u=e.create,f=Me(t.n,t.nBitLength),d=t.uvRatio||((v,b)=>{try{return{isValid:!0,value:e.sqrt(v*e.inv(b))}}catch{return{isValid:!1,value:Yt}}}),p=t.adjustScalarBytes||(v=>v),y=t.domain||((v,b,A)=>{if(Zt("phflag",A),b.length||A)throw new Error("Contexts/pre-hash are not supported");return v});function g(v,b){Et("coordinate "+v,b,Yt,l)}function h(v){if(!(v instanceof m))throw new Error("ExtendedPoint expected")}let w=er((v,b)=>{let{ex:A,ey:E,ez:R}=v,U=v.is0();b==null&&(b=U?mp:e.inv(R));let O=u(A*b),K=u(E*b),F=u(R*b);if(U)return{x:Yt,y:Ht};if(F!==Ht)throw new Error("invZ was invalid");return{x:O,y:K}}),x=er(v=>{let{a:b,d:A}=t;if(v.is0())throw new Error("bad point: ZERO");let{ex:E,ey:R,ez:U,et:O}=v,K=u(E*E),F=u(R*R),W=u(U*U),j=u(W*W),st=u(K*b),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 It=u(E*R),Pt=u(U*O);if(It!==Pt)throw new Error("bad point: equation left != right (2)");return!0});class m{constructor(b,A,E,R){this.ex=b,this.ey=A,this.ez=E,this.et=R,g("x",b),g("y",A),g("z",E),g("t",R),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(b){if(b instanceof m)throw new Error("extended point not allowed");let{x:A,y:E}=b||{};return g("x",A),g("y",E),new m(A,E,Ht,u(A*E))}static normalizeZ(b){let A=e.invertBatch(b.map(E=>E.ez));return b.map((E,R)=>E.toAffine(A[R])).map(m.fromAffine)}static msm(b,A){return io(m,f,b,A)}_setWindowSize(b){N.setWindowSize(this,b)}assertValidity(){x(this)}equals(b){h(b);let{ex:A,ey:E,ez:R}=this,{ex:U,ey:O,ez:K}=b,F=u(A*K),W=u(U*R),j=u(E*K),st=u(O*R);return F===W&&j===st}is0(){return this.equals(m.ZERO)}negate(){return new m(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:b}=t,{ex:A,ey:E,ez:R}=this,U=u(A*A),O=u(E*E),K=u(ao*u(R*R)),F=u(b*U),W=A+E,j=u(u(W*W)-U-O),st=F+O,it=st-K,ut=F-O,It=u(j*it),Pt=u(st*ut),_t=u(j*ut),oe=u(it*st);return new m(It,Pt,oe,_t)}add(b){h(b);let{a:A,d:E}=t,{ex:R,ey:U,ez:O,et:K}=this,{ex:F,ey:W,ez:j,et:st}=b;if(A===BigInt(-1)){let Cc=u((U-R)*(W+F)),kc=u((U+R)*(W-F)),ei=u(kc-Cc);if(ei===Yt)return this.double();let Tc=u(O*ao*st),Nc=u(K*ao*j),Lc=Nc+Tc,_c=kc+Cc,Rc=Nc-Tc,Sh=u(Lc*ei),Ih=u(_c*Rc),Ch=u(Lc*Rc),kh=u(ei*_c);return new m(Sh,Ih,kh,Ch)}let it=u(R*F),ut=u(U*W),It=u(K*E*st),Pt=u(O*j),_t=u((R+U)*(F+W)-it-ut),oe=Pt-It,fe=Pt+It,Gr=u(ut-A*it),vh=u(_t*oe),Eh=u(fe*Gr),Ah=u(_t*Gr),Bh=u(oe*fe);return new m(vh,Eh,Bh,Ah)}subtract(b){return this.add(b.negate())}wNAF(b){return N.wNAFCached(this,b,m.normalizeZ)}multiply(b){let A=b;Et("scalar",A,Ht,n);let{p:E,f:R}=this.wNAF(A);return m.normalizeZ([E,R])[0]}multiplyUnsafe(b,A=m.ZERO){let E=b;return Et("scalar",E,Yt,n),E===Yt?L:this.is0()||E===Ht?this:N.wNAFCachedUnsafe(this,E,m.normalizeZ,A)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return N.unsafeLadder(this,n).is0()}toAffine(b){return w(this,b)}clearCofactor(){let{h:b}=t;return b===Ht?this:this.multiplyUnsafe(b)}static fromHex(b,A=!1){let{d:E,a:R}=t,U=e.BYTES;b=ot("pointHex",b,U),Zt("zip215",A);let O=b.slice(),K=b[U-1];O[U-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-Ht),it=u(E*j-R),{isValid:ut,value:It}=d(st,it);if(!ut)throw new Error("Point.fromHex: invalid y coordinate");let Pt=(It&Ht)===Ht,_t=(K&128)!==0;if(!A&&It===Yt&&_t)throw new Error("Point.fromHex: x=0 and x_0=1");return _t!==Pt&&(It=u(-It)),m.fromAffine({x:It,y:F})}static fromPrivateKey(b){return S(b).point}toRawBytes(){let{x:b,y:A}=this.toAffine(),E=we(A,e.BYTES);return E[E.length-1]|=b&Ht?128:0,E}toHex(){return ge(this.toRawBytes())}}m.BASE=new m(t.Gx,t.Gy,Ht,u(t.Gx*t.Gy)),m.ZERO=new m(Yt,Ht,Ht,Yt);let{BASE:I,ZERO:L}=m,N=so(m,a*8);function B(v){return Z(v,n)}function k(v){return B(Xt(v))}function S(v){let b=e.BYTES;v=ot("private key",v,b);let A=ot("hashed private key",s(v),2*b),E=p(A.slice(0,b)),R=A.slice(b,2*b),U=k(E),O=I.multiply(U),K=O.toRawBytes();return{head:E,prefix:R,scalar:U,point:O,pointBytes:K}}function M(v){return S(v).pointBytes}function _(v=new Uint8Array,...b){let A=be(...b);return k(s(y(A,ot("context",v),!!o)))}function H(v,b,A={}){v=ot("message",v),o&&(v=o(v));let{prefix:E,scalar:R,pointBytes:U}=S(b),O=_(A.context,E,v),K=I.multiply(O).toRawBytes(),F=_(A.context,K,U,v),W=B(O+F*R);Et("signature.s",W,Yt,n);let j=be(K,we(W,e.BYTES));return ot("result",j,e.BYTES*2)}let V=gp;function C(v,b,A,E=V){let{context:R,zip215:U}=E,O=e.BYTES;v=ot("signature",v,2*O),b=ot("message",b),A=ot("publicKey",A,O),U!==void 0&&Zt("zip215",U),o&&(b=o(b));let K=Xt(v.slice(O,2*O)),F,W,j;try{F=m.fromHex(A,U),W=m.fromHex(v.slice(0,O),U),j=I.multiplyUnsafe(K)}catch{return!1}if(!U&&F.isSmallOrder())return!1;let st=_(R,W.toRawBytes(),F.toRawBytes(),b);return W.add(F.multiplyUnsafe(st)).subtract(j).clearCofactor().equals(m.ZERO)}return I._setWindowSize(8),{CURVE:t,getPublicKey:M,sign:H,verify:C,ExtendedPoint:m,utils:{getExtendedPublicKey:S,randomPrivateKey:()=>i(e.BYTES),precompute(v=8,b=m.BASE){return b._setWindowSize(v),b.multiply(BigInt(3)),b}}}}var Cr=BigInt(0),Li=BigInt(1);function wp(r){return Wt(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function pl(r){let t=wp(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,m,I){let L=n(x*(m-I));return m=n(m-L),I=n(I+L),[m,I]}let u=(t.a-BigInt(2))/BigInt(4);function f(x,m){Et("u",x,Cr,e),Et("scalar",m,Cr,e);let I=m,L=x,N=Li,B=Cr,k=x,S=Li,M=Cr,_;for(let V=BigInt(o-1);V>=Cr;V--){let C=I>>V&Li;M^=C,_=l(M,N,k),N=_[0],k=_[1],_=l(M,B,S),B=_[0],S=_[1],M=C;let T=N+B,v=n(T*T),b=N-B,A=n(b*b),E=v-A,R=k+S,U=k-S,O=n(U*T),K=n(R*b),F=O+K,W=O-K;k=n(F*F),S=n(L*n(W*W)),N=n(v*A),B=n(E*(v+n(u*E)))}_=l(M,N,k),N=_[0],k=_[1],_=l(M,B,S),B=_[0],S=_[1];let H=c(B);return n(N*H)}function d(x){return we(n(x),s)}function p(x){let m=ot("u coordinate",x,s);return i===32&&(m[31]&=127),Xt(m)}function y(x){let m=ot("scalar",x),I=m.length;if(I!==s&&I!==i){let L=""+s+" or "+i;throw new Error("invalid scalar, expected "+L+" bytes, got "+I)}return Xt(a(m))}function g(x,m){let I=p(m),L=y(x),N=f(I,L);if(N===Cr)throw new Error("invalid private or public key received");return d(N)}let h=d(t.Gu);function w(x){return g(x,h)}return{scalarMult:g,scalarMultBase:w,getSharedSecret:(x,m)=>g(x,m),getPublicKey:x=>w(x),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:h}}var on=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),ml=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Hy=BigInt(0),bp=BigInt(1),gl=BigInt(2),xp=BigInt(3),vp=BigInt(5),Ep=BigInt(8);function yl(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=on,a=r*r%s*r%s,c=at(a,gl,s)*a%s,l=at(c,bp,s)*r%s,u=at(l,vp,s)*l%s,f=at(u,t,s)*u%s,d=at(f,e,s)*f%s,p=at(d,n,s)*d%s,y=at(p,o,s)*p%s,g=at(y,o,s)*p%s,h=at(g,t,s)*u%s;return{pow_p_5_8:at(h,gl,s)*r%s,b2:a}}function wl(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Ap(r,t){let e=on,n=Z(t*t*t,e),o=Z(n*n*t,e),s=yl(r*o).pow_p_5_8,i=Z(r*n*s,e),a=Z(t*i*i,e),c=i,l=Z(i*ml,e),u=a===r,f=a===Z(-r,e),d=a===Z(-r*ml,e);return u&&(i=c),(f||d)&&(i=l),al(i,e)&&(i=Z(-i,e)),{isValid:u||f,value:i}}var Bp=Me(on,void 0,!0),Sp={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Bp,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Ep,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:rl,randomBytes:tn,adjustScalarBytes:wl,uvRatio:Ap},bl=dl(Sp);var sn=pl({P:on,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let t=on,{pow_p_5_8:e,b2:n}=yl(r);return Z(at(e,xp,t)*n,t)},adjustScalarBytes:wl,randomBytes:tn});var co=32;function xl(r,t,e){return bl.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}var lo=class{type="Ed25519";raw;constructor(t){this.raw=_i(t,co)}toMultihash(){return pe.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:Rt(this.raw,t.raw)}verify(t,e){return xl(this.raw,e,t)}};function Ri(r){return r=_i(r,co),new lo(r)}function _i(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new et(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}function gt(r=0){return new Uint8Array(r)}function yt(r=0){return new Uint8Array(r)}var Cp=Math.pow(2,7),kp=Math.pow(2,14),Tp=Math.pow(2,21),Ui=Math.pow(2,28),Di=Math.pow(2,35),Pi=Math.pow(2,42),Oi=Math.pow(2,49),J=128,kt=127;function ct(r){if(r<Cp)return 1;if(r<kp)return 2;if(r<Tp)return 3;if(r<Ui)return 4;if(r<Di)return 5;if(r<Pi)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 Hi(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 Np(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 Mi(r,t){let e=r[t],n=0;if(n+=e&kt,e<J||(e=r[t+1],n+=(e&kt)<<7,e<J)||(e=r[t+2],n+=(e&kt)<<14,e<J)||(e=r[t+3],n+=(e&kt)<<21,e<J)||(e=r[t+4],n+=(e&kt)*Ui,e<J)||(e=r[t+5],n+=(e&kt)*Di,e<J)||(e=r[t+6],n+=(e&kt)*Pi,e<J)||(e=r[t+7],n+=(e&kt)*Oi,e<J))return n;throw new RangeError("Could not decode varint")}function Lp(r,t){let e=r.get(t),n=0;if(n+=e&kt,e<J||(e=r.get(t+1),n+=(e&kt)<<7,e<J)||(e=r.get(t+2),n+=(e&kt)<<14,e<J)||(e=r.get(t+3),n+=(e&kt)<<21,e<J)||(e=r.get(t+4),n+=(e&kt)*Ui,e<J)||(e=r.get(t+5),n+=(e&kt)*Di,e<J)||(e=r.get(t+6),n+=(e&kt)*Pi,e<J)||(e=r.get(t+7),n+=(e&kt)*Oi,e<J))return n;throw new RangeError("Could not decode varint")}function se(r,t,e=0){return t==null&&(t=yt(ct(r))),t instanceof Uint8Array?Hi(r,t,e):Np(r,t,e)}function Jt(r,t=0){return r instanceof Uint8Array?Mi(r,t):Lp(r,t)}var Vi=new Float32Array([-0]),Ve=new Uint8Array(Vi.buffer);function El(r,t,e){Vi[0]=r,t[e]=Ve[0],t[e+1]=Ve[1],t[e+2]=Ve[2],t[e+3]=Ve[3]}function Al(r,t){return Ve[0]=r[t],Ve[1]=r[t+1],Ve[2]=r[t+2],Ve[3]=r[t+3],Vi[0]}var Fi=new Float64Array([-0]),Tt=new Uint8Array(Fi.buffer);function Bl(r,t,e){Fi[0]=r,t[e]=Tt[0],t[e+1]=Tt[1],t[e+2]=Tt[2],t[e+3]=Tt[3],t[e+4]=Tt[4],t[e+5]=Tt[5],t[e+6]=Tt[6],t[e+7]=Tt[7]}function Sl(r,t){return Tt[0]=r[t],Tt[1]=r[t+1],Tt[2]=r[t+2],Tt[3]=r[t+3],Tt[4]=r[t+4],Tt[5]=r[t+5],Tt[6]=r[t+6],Tt[7]=r[t+7],Fi[0]}var _p=BigInt(Number.MAX_SAFE_INTEGER),Rp=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 nr;if(t<_p&&t>Rp)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>Il&&(o=0n,++n>Il&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return nr;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):nr}},nr=new Kt(0,0);nr.toBigInt=function(){return 0n};nr.zzEncode=nr.zzDecode=function(){return this};nr.length=function(){return 1};var Il=4294967296n;function Cl(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 kl(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 uo(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 uo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Qt(this,4);return uo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Qt(this,4);let t=Al(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Qt(this,4);let t=Sl(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 kl(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=uo(this.buf,this.pos+=4),e=uo(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=Mi(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={};Ct(qi,{base10:()=>Up});var Up=_e({prefix:"9",name:"base10",alphabet:"0123456789"});var zi={};Ct(zi,{base16:()=>Dp,base16upper:()=>Pp});var Dp=dt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Pp=dt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Gi={};Ct(Gi,{base2:()=>Op});var Op=dt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ji={};Ct(ji,{base256emoji:()=>Kp});var Nl=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}"),Hp=Nl.reduce((r,t,e)=>(r[e]=t,r),[]),Mp=Nl.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Vp(r){return r.reduce((t,e)=>(t+=Hp[e],t),"")}function Fp(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Mp[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Kp=br({prefix:"\u{1F680}",name:"base256emoji",encode:Vp,decode:Fp});var Xi={};Ct(Xi,{base64:()=>$p,base64pad:()=>Wp,base64url:()=>Zi,base64urlpad:()=>qp});var $p=dt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Wp=dt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Zi=dt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),qp=dt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Yi={};Ct(Yi,{base8:()=>zp});var zp=dt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ji={};Ct(Ji,{identity:()=>Gp});var Gp=br({prefix:"\0",name:"identity",encode:r=>Mc(r),decode:r=>Hc(r)});var xw=new TextEncoder,vw=new TextDecoder;var ea={};Ct(ea,{sha256:()=>cn,sha512:()=>Xp});function ta({name:r,code:t,encode:e}){return new Qi(r,t,e)}var Qi=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?Ot(this.code,e):e.then(n=>Ot(this.code,n))}else throw Error("Unknown type, must be binary type")}};function _l(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var cn=ta({name:"sha2-256",code:18,encode:_l("SHA-256")}),Xp=ta({name:"sha2-512",code:19,encode:_l("SHA-512")});var or={...Ji,...Gi,...Yi,...qi,...zi,...ci,...li,...ai,...Xi,...ji},Rw={...ea,...di};function Ul(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Rl=Ul("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ra=Ul("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}),Yp={utf8:Rl,"utf-8":Rl,hex:or.base16,latin1:ra,ascii:ra,binary:ra,...or},fo=Yp;function Q(r,t="utf8"){let e=fo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function na(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 sr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function oa(){}var ia=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Jp=na();function Qp(r){return globalThis.Buffer!=null?yt(r):Jp(r)}var un=class{len;head;tail;states;constructor(){this.len=0,this.head=new sr(oa,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new sr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new aa((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(ho,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(ho,e.length(),e)}uint64Number(t){return this._push(Hi,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(ho,e.length(),e)}sint64Number(t){let e=Kt.fromNumber(t).zzEncode();return this._push(ho,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(sa,1,t?1:0)}fixed32(t){return this._push(ln,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Kt.fromBigInt(t);return this._push(ln,4,e.lo)._push(ln,4,e.hi)}fixed64Number(t){let e=Kt.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(El,4,t)}double(t){return this._push(Bl,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(sa,1,0):this.uint32(e)._push(e0,e,t)}string(t){let e=Cl(t);return e!==0?this.uint32(e)._push(Ki,e,t):this._push(sa,1,0)}fork(){return this.states=new ia(this),this.head=this.tail=new sr(oa,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 sr(oa,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=Qp(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function sa(r,t,e){t[e]=r&255}function t0(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var aa=class extends sr{next;constructor(t,e){super(t0,t,e),this.next=void 0}};function ho(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(r0,t,r),this},un.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(n0,t,r),this});function r0(r,t,e){t.set(r,e)}function n0(r,t,e){r.length<40?Ki(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Q(r),e)}function ca(){return new un}function ee(r,t){let e=ca();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 po(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function ir(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 po("enum",Tr.VARINT,e,n)}function re(r,t){return po("message",Tr.LENGTH_DELIMITED,r,t)}var wt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(wt||(wt={}));var la;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(la||(la={}));(function(r){r.codec=()=>ir(la)})(wt||(wt={}));var ie;(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)})(ie||(ie={}));var ua;(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)})(ua||(ua={}));var xn={};Ct(xn,{MAX_RSA_KEY_SIZE:()=>ss,generateRSAKeyPair:()=>Lu,jwkToJWKKeyPair:()=>_u,jwkToPkcs1:()=>b0,jwkToPkix:()=>ba,jwkToRSAPrivateKey:()=>Nu,pkcs1ToJwk:()=>Cu,pkcs1ToRSAPrivateKey:()=>Tu,pkixToJwk:()=>ku,pkixToRSAPublicKey:()=>xa});var o0=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]),Fe=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ke=new Uint32Array(64),fa=class extends Sr{constructor(){super(64,32,8,!1),this.A=Fe[0]|0,this.B=Fe[1]|0,this.C=Fe[2]|0,this.D=Fe[3]|0,this.E=Fe[4]|0,this.F=Fe[5]|0,this.G=Fe[6]|0,this.H=Fe[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)Ke[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Ke[f-15],p=Ke[f-2],y=jt(d,7)^jt(d,18)^d>>>3,g=jt(p,17)^jt(p,19)^p>>>10;Ke[f]=g+Ke[f-7]+y+Ke[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),p=u+d+Qc(a,c,l)+o0[f]+Ke[f]|0,g=(jt(n,2)^jt(n,13)^jt(n,22))+tl(n,o,s)|0;u=l,l=c,c=a,a=i+p|0,i=s,s=o,o=n,n=p+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(){Ke.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ae=Jn(()=>new fa);var z=Dh(Pl());function ar(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 $e(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 yo(...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 da(){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=ar(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,ar(s,8)-n}function Ol(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=$e(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=$e(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 Hl(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 Mt(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 pb=Math.log(2);function wo(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function pa(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 Be(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 pa(this.items)}},fn=[new Uint8Array([1])],Ml="0123456789";var Ur="",ne=new ArrayBuffer(0),ma=new Uint8Array(0),dn="EndOfContent",Fl="OCTET STRING",Kl="BIT STRING";function Se(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?z.BufferSourceConverter.toUint8Array(s.valueHex):ma}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(!Be(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:z.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var ve=class{constructor({blockLength:t=0,error:e=Ur,warnings:n=[],valueBeforeDecode:o=ma}={}){this.blockLength=t,this.error=e,this.warnings=n,this.valueBeforeDecodeView=z.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:z.Convert.ToHex(this.valueBeforeDecodeView)}}};ve.NAME="baseBlock";var Nt=class extends ve{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 bo=class extends Se(ve){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?z.BufferSourceConverter.toUint8Array(t.valueHex):ma,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=$e(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=z.BufferSourceConverter.toUint8Array(t);if(!Be(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 p=0;p<l.length;p++)d[p]=l[p];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=ar(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}}};bo.NAME="identificationBlock";var xo=class extends ve{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=z.BufferSourceConverter.toUint8Array(t);if(!Be(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=ar(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=$e(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}}};xo.NAME="lengthBlock";var D={},At=class extends ve{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 bo(o),this.lenBlock=new xo(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||$l(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():z.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${z.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 Hl(e,n)}};At.NAME="BaseBlock";function $l(r){if(r instanceof D.Constructed)for(let t of r.valueBlock.value)$l(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var vo=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}'`}};vo.NAME="BaseStringBlock";var Eo=class extends Se(Nt){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};Eo.NAME="PrimitiveValueBlock";var Wl,Ao=class extends At{constructor(t={}){super(t,Eo),this.idBlock.isConstructed=!1}};Wl=Ao;D.Primitive=Wl;Ao.NAME="PRIMITIVE";function d0(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 ns(r,t=0,e=r.length){let n=t,o=new At({},Nt),s=new ve;if(!Be(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=d0(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 ga(r){if(!r.byteLength){let t=new At({},Nt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return ns(z.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function p0(r,t){return r?1:t}var ce=class extends Nt{constructor({value:t=[],isIndefiniteForm:e=!1,...n}={}){super(n),this.value=t,this.isIndefiniteForm=e}fromBER(t,e,n){let o=z.BufferSourceConverter.toUint8Array(t);if(!Be(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(;p0(this.isIndefiniteForm,n)>0;){let i=ns(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?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}};ce.NAME="ConstructedValueBlock";var ql,We=class extends At{constructor(t={}){super(t,ce),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} :`}};zl=We;D.Constructed=zl;We.NAME="CONSTRUCTED";var So=class extends Nt{fromBER(t,e,n){return e}toBER(t){return ne}};So.override="EndOfContentValueBlock";var Gl,Io=class extends At{constructor(t={}){super(t,So),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Gl=Io;D.EndOfContent=Gl;Io.NAME=dn;var jl,Lr=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}`}};jl=Lr;D.Null=jl;Lr.NAME="NULL";var Co=class extends Se(Nt){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=z.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=z.BufferSourceConverter.toUint8Array(t);return Be(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,pa.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Co.NAME="BooleanValueBlock";var Zl,ko=class extends At{constructor(t={}){super(t,Co),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}`}};Zl=ko;D.Boolean=Zl;ko.NAME="BOOLEAN";var To=class extends Se(ce){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=ce.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!==Kl)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?ce.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};To.NAME="OctetStringValueBlock";var Xl,No=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},To),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=os(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?We.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${z.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 z.BufferSourceConverter.concat(t)}};Xl=No;D.OctetString=Xl;No.NAME=Kl;var Lo=class extends Se(ce){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=ce.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!==$l)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=z.BufferSourceConverter.toUint8Array(t);if(!Be(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=os(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 ce.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}}};Lo.NAME="BitStringValueBlock";var Yl,_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},Lo),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 We.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)}`}}};Yl=_r;D.BitString=Yl;_r.NAME=$l;var Jl;function g0(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=wo(new Uint8Array([l%10]),s);break;default:s[i-f]=l%10}}return e[0]>0&&(s=wo(e,s)),s}function Fl(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=wo(e,n)),fn.push(n)}return fn[r]}function y0(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 Se(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=pa.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Ml(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=y0(Fl(n),e),i="-";break;default:e=g0(e,Fl(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(i+=Vl.charAt(e[c]));return a===!1&&(i+=Vl.charAt(0)),i}};Jl=pn;pn.NAME="IntegerValueBlock";Object.defineProperty(Jl.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Ql,Bt=class r extends At{constructor(t={}){super(t,pn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return bo(),BigInt(this.valueBlock.toString())}static fromBigInt(t){bo();let e=BigInt(t),n=new hn,o=e.toString(16).replace(/^-/,""),s=new Uint8Array(z.Convert.FromHex(o));if(e<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${z.Convert.ToHex(a)}`)+e,u=z.BufferSourceConverter.toUint8Array(z.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()}`}};Ql=Bt;D.Integer=Ql;Bt.NAME="INTEGER";var tu,_o=class extends Bt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};tu=_o;D.Enumerated=tu;_o.NAME="ENUMERATED";var mn=class extends Se(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=z.BufferSourceConverter.toUint8Array(t);if(!Be(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=ar(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){bo();let e=BigInt(t).toString(2);for(;e.length%7;)e="0"+e;let n=new Uint8Array(e.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(e.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=$e(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=z.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 Ro=class extends Nt{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.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 ma(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){bo();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e?(o=`{${o}}`,this.value[n].isFirstSid?t=`2.{${o} - 80}`:t+=o):t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};Ro.NAME="ObjectIdentifierValueBlock";var eu,Rr=class extends At{constructor(t={}){super(t,Ro),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()}}};eu=Rr;D.ObjectIdentifier=eu;Rr.NAME="OBJECT IDENTIFIER";var gn=class extends Se(ve){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let o=z.BufferSourceConverter.toUint8Array(t);if(!Be(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=ar(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=$e(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=z.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};gn.NAME="relativeSidBlock";var Uo=class extends Nt{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 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,ne;n.push(s)}return ma(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}};Uo.NAME="RelativeObjectIdentifierValueBlock";var ru,Do=class extends At{constructor(t={}){super(t,Uo),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()}}};ru=Do;D.RelativeObjectIdentifier=ru;Do.NAME="RelativeObjectIdentifier";var nu,Ee=class extends We{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};nu=Ee;D.Sequence=nu;Ee.NAME="SEQUENCE";var ou,Po=class extends We{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};ou=Po;D.Set=ou;Po.NAME="SET";var Oo=class extends Se(Nt){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=Ur}toJSON(){return{...super.toJSON(),value:this.value}}};Oo.NAME="StringValueBlock";var Mo=class extends Oo{};Mo.NAME="SimpleStringValueBlock";var Ut=class extends Eo{constructor({...t}={}){super(t,Mo)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,z.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}};Ut.NAME="SIMPLE STRING";var Ho=class extends Ut{fromBuffer(t){this.valueBlock.valueHexView=z.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=z.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=z.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(z.Convert.FromUtf8String(t)),this.valueBlock.value=t}};Ho.NAME="Utf8StringValueBlock";var su,Ae=class extends Ho{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};su=Ae;D.Utf8String=su;Ae.NAME="UTF8String";var Vo=class extends Ut{fromBuffer(t){this.valueBlock.value=z.Convert.ToUtf16String(t),this.valueBlock.valueHexView=z.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(z.Convert.FromUtf16String(t))}};Vo.NAME="BmpStringValueBlock";var iu,Fo=class extends Vo{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};iu=Fo;D.BmpString=iu;Fo.NAME="BMPString";var Ko=class extends Ut{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=$e(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}};Ko.NAME="UniversalStringValueBlock";var au,$o=class extends Ko{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};au=$o;D.UniversalString=au;$o.NAME="UniversalString";var cu,Wo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};cu=Wo;D.NumericString=cu;Wo.NAME="NumericString";var lu,qo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};lu=qo;D.PrintableString=lu;qo.NAME="PrintableString";var uu,zo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};uu=zo;D.TeletexString=uu;zo.NAME="TeletexString";var fu,Go=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};fu=Go;D.VideotexString=fu;Go.NAME="VideotexString";var hu,jo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};hu=jo;D.IA5String=hu;jo.NAME="IA5String";var du,Zo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};du=Zo;D.GraphicString=du;Zo.NAME="GraphicString";var pu,yn=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};pu=yn;D.VisibleString=pu;yn.NAME="VisibleString";var mu,Xo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};mu=Xo;D.GeneralString=mu;Xo.NAME="GeneralString";var gu,Yo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};gu=Yo;D.CharacterString=gu;Yo.NAME="CharacterString";var yu,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,z.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}}};yu=wn;D.UTCTime=yu;wn.NAME="UTCTime";var wu,Jo=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("+"),p="";if(d===-1&&(d=n.indexOf("-"),f=-1),d!==-1){if(p=n.substring(d+1),n=n.substring(0,d),p.length!==2&&p.length!==4)throw new Error("Wrong input string for conversion");let y=parseInt(p.substring(0,2),10);if(isNaN(y.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*y,p.length===4){if(y=parseInt(p.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}}};wu=Jo;D.GeneralizedTime=wu;Jo.NAME="GeneralizedTime";var bu,Qo=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};bu=Qo;D.DATE=bu;Qo.NAME="DATE";var xu,ts=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};xu=ts;D.TimeOfDay=xu;ts.NAME="TimeOfDay";var vu,es=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};vu=es;D.DateTime=vu;es.NAME="DateTime";var Eu,rs=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Eu=rs;D.Duration=Eu;rs.NAME="Duration";var Au,ns=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Au=ns;D.TIME=Au;ns.NAME="TIME";function X(r,t="utf8"){let e=ho[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"}},ss=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Bu={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new ss("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 qe=Bu;async function Su(r){let t=await qe.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 b0(t);return{privateKey:e[0],publicKey:e[1]}}async function Iu(r,t){let e=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await qe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Cu(r,t,e){let n=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return qe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function b0(r){if(r.privateKey==null||r.publicKey==null)throw new et("Private and public key are required");return Promise.all([qe.get().subtle.exportKey("jwk",r.privateKey),qe.get().subtle.exportKey("jwk",r.publicKey)])}function wa(r){if(r.kty!=="RSA")throw new et("invalid key type");if(r.n==null)throw new et("invalid key modulus");return Q(r.n,"base64url").length*8}var Dr=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 vt.createV1(114,this._multihash)}toString(){return nt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Rt(this.raw,t.raw)}verify(t,e){return Cu(this._key,e,t)}},vn=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:Rt(this.raw,t.raw)}sign(t){return Iu(this._key,t)}};var is=8192,ba=18;function ku(r){let{result:t}=ya(r),e=t.valueBlock.value;return{n:le(e[1]),e:le(e[2]),d:le(e[3]),p:le(e[4]),q:le(e[5]),dp:le(e[6]),dq:le(e[7]),qi:le(e[8]),kty:"RSA",alg:"RS256"}}function x0(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new et("JWK was missing components");let e=new Ee({value:[new Bt({value:0}),Bt.fromBigInt(ue(Q(r.n,"base64url"))),Bt.fromBigInt(ue(Q(r.e,"base64url"))),Bt.fromBigInt(ue(Q(r.d,"base64url"))),Bt.fromBigInt(ue(Q(r.p,"base64url"))),Bt.fromBigInt(ue(Q(r.q,"base64url"))),Bt.fromBigInt(ue(Q(r.dp,"base64url"))),Bt.fromBigInt(ue(Q(r.dq,"base64url"))),Bt.fromBigInt(ue(Q(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function Tu(r){let{result:t}=ya(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:le(e[0]),e:le(e[1])}}function xa(r){if(r.n==null||r.e==null)throw new et("JWK was missing components");let e=new Ee({value:[new Ee({value:[new Rr({value:"1.2.840.113549.1.1.1"}),new Lr]}),new _r({valueHex:new Ee({value:[Bt.fromBigInt(ue(Q(r.n,"base64url"))),Bt.fromBigInt(ue(Q(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function le(r){let t=r.valueBlock.valueHexView;for(;t[0]===0;)t=t.subarray(1);return X(t,"base64url")}function ue(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 Nu(r){let t=ku(r);return Lu(t)}function va(r){let t=Tu(r);if(wa(t)>is)throw new yr("Key size is too large");let e=ae(ie.encode({Type:wt.RSA,Data:r})),n=Ot(ba,e);return new Dr(t,n)}function Lu(r){if(wa(r)>is)throw new et("Key size is too large");let t=Ru(r),e=ae(ie.encode({Type:wt.RSA,Data:xa(t.publicKey)})),n=Ot(ba,e);return new vn(t.privateKey,new Dr(t.publicKey,n))}async function _u(r){if(r>is)throw new et("Key size is too large");let t=await Su(r),e=ae(ie.encode({Type:wt.RSA,Data:xa(t.publicKey)})),n=Ot(ba,e);return new vn(t.privateKey,new Dr(t.publicKey,n))}function Ru(r){if(r==null)throw new et("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var as=class extends Br{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Qr(t);let n=Ue(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()}},Pr=(r,t,e)=>new as(r,t).update(e).digest();Pr.create=(r,t)=>new as(r,t);function Uu(r){r.lowS!==void 0&&Zt("lowS",r.lowS),r.prehash!==void 0&&Zt("prehash",r.prehash)}function v0(r){let t=nn(r);Wt(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:E0,hexToBytes:A0}=no,Ea=class extends Error{constructor(t=""){super(t)}},Ie={Err:Ea,_tlv:{encode:(r,t)=>{let{Err:e}=Ie;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=Qe(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Qe(o.length/2|128):"";return Qe(r)+s+o+t},decode(r,t){let{Err:e}=Ie,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}=Ie;if(r<Ce)throw new t("integer: negative integers are not allowed");let e=Qe(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}=Ie;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 E0(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Ie,o=typeof r=="string"?A0(r):r;Ir(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}=Ie,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},Ce=BigInt(0),bt=BigInt(1),Xb=BigInt(2),Du=BigInt(3),Yb=BigInt(4);function B0(r){let t=v0(r),{Fp:e}=t,n=He(t.n,t.nBitLength),o=t.toBytes||((g,h,w)=>{let x=h.toAffine();return be(Uint8Array.from([4]),e.toBytes(x.x),e.toBytes(x.y))}),s=t.fromBytes||(g=>{let h=g.subarray(1),w=e.fromBytes(h.subarray(0,e.BYTES)),x=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:w,y:x}});function i(g){let{a:h,b:w}=t,x=e.sqr(g),m=e.mul(x,g);return e.add(e.add(m,e.mul(g,h)),w)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return en(g,bt,t.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:w,wrapPrivateKey:x,n:m}=t;if(h&&typeof g!="bigint"){if(Oe(g)&&(g=ge(g)),typeof g!="string"||!h.includes(g.length))throw new Error("invalid private key");g=g.padStart(w*2,"0")}let I;try{I=typeof g=="bigint"?g:ye(ot("private key",g,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof g)}return x&&(I=Z(I,m)),Et("private key",I,bt,m),I}function l(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let u=er((g,h)=>{let{px:w,py:x,pz:m}=g;if(e.eql(m,e.ONE))return{x:w,y:x};let I=g.is0();h==null&&(h=I?e.ONE:e.inv(m));let L=e.mul(w,h),N=e.mul(x,h),B=e.mul(m,h);if(I)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=er(g=>{if(g.is0()){if(t.allowInfinityPoint&&!e.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:h,y:w}=g.toAffine();if(!e.isValid(h)||!e.isValid(w))throw new Error("bad point: x or y not FE");let x=e.sqr(w),m=i(h);if(!e.eql(x,m))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,w,x){if(this.px=h,this.py=w,this.pz=x,h==null||!e.isValid(h))throw new Error("x required");if(w==null||!e.isValid(w))throw new Error("y required");if(x==null||!e.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:w,y:x}=h||{};if(!h||!e.isValid(w)||!e.isValid(x))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let m=I=>e.eql(I,e.ZERO);return m(w)&&m(x)?d.ZERO:new d(w,x,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let w=e.invertBatch(h.map(x=>x.pz));return h.map((x,m)=>x.toAffine(w[m])).map(d.fromAffine)}static fromHex(h){let w=d.fromAffine(s(ot("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,w){return ao(d,n,h,w)}_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:w,py:x,pz:m}=this,{px:I,py:L,pz:N}=h,B=e.eql(e.mul(w,N),e.mul(I,m)),k=e.eql(e.mul(x,N),e.mul(L,m));return B&&k}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:w}=t,x=e.mul(w,Du),{px:m,py:I,pz:L}=this,N=e.ZERO,B=e.ZERO,k=e.ZERO,S=e.mul(m,m),H=e.mul(I,I),_=e.mul(L,L),M=e.mul(m,I);return M=e.add(M,M),k=e.mul(m,L),k=e.add(k,k),N=e.mul(h,k),B=e.mul(x,_),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),k=e.mul(x,k),_=e.mul(h,_),M=e.sub(S,_),M=e.mul(h,M),M=e.add(M,k),k=e.add(S,S),S=e.add(k,S),S=e.add(S,_),S=e.mul(S,M),B=e.add(B,S),_=e.mul(I,L),_=e.add(_,_),S=e.mul(_,M),N=e.sub(N,S),k=e.mul(_,H),k=e.add(k,k),k=e.add(k,k),new d(N,B,k)}add(h){l(h);let{px:w,py:x,pz:m}=this,{px:I,py:L,pz:N}=h,B=e.ZERO,k=e.ZERO,S=e.ZERO,H=t.a,_=e.mul(t.b,Du),M=e.mul(w,I),V=e.mul(x,L),C=e.mul(m,N),T=e.add(w,x),v=e.add(I,L);T=e.mul(T,v),v=e.add(M,V),T=e.sub(T,v),v=e.add(w,m);let b=e.add(I,N);return v=e.mul(v,b),b=e.add(M,C),v=e.sub(v,b),b=e.add(x,m),B=e.add(L,N),b=e.mul(b,B),B=e.add(V,C),b=e.sub(b,B),S=e.mul(H,v),B=e.mul(_,C),S=e.add(B,S),B=e.sub(V,S),S=e.add(V,S),k=e.mul(B,S),V=e.add(M,M),V=e.add(V,M),C=e.mul(H,C),v=e.mul(_,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),k=e.add(k,M),M=e.mul(b,v),B=e.mul(T,B),B=e.sub(B,M),M=e.mul(T,V),S=e.mul(b,S),S=e.add(S,M),new d(B,k,S)}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:w,n:x}=t;Et("scalar",h,Ce,x);let m=d.ZERO;if(h===Ce)return m;if(this.is0()||h===bt)return this;if(!w||y.hasPrecomputes(this))return y.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:I,k1:L,k2neg:N,k2:B}=w.splitScalar(h),k=m,S=m,H=this;for(;L>Ce||B>Ce;)L&bt&&(k=k.add(H)),B&bt&&(S=S.add(H)),H=H.double(),L>>=bt,B>>=bt;return I&&(k=k.negate()),N&&(S=S.negate()),S=new d(e.mul(S.px,w.beta),S.py,S.pz),k.add(S)}multiply(h){let{endo:w,n:x}=t;Et("scalar",h,bt,x);let m,I;if(w){let{k1neg:L,k1:N,k2neg:B,k2:k}=w.splitScalar(h),{p:S,f:H}=this.wNAF(N),{p:_,f:M}=this.wNAF(k);S=y.constTimeNegate(L,S),_=y.constTimeNegate(B,_),_=new d(e.mul(_.px,w.beta),_.py,_.pz),m=S.add(_),I=H.add(M)}else{let{p:L,f:N}=this.wNAF(h);m=L,I=N}return d.normalizeZ([m,I])[0]}multiplyAndAddUnsafe(h,w,x){let m=d.BASE,I=(N,B)=>B===Ce||B===bt||!N.equals(m)?N.multiplyUnsafe(B):N.multiply(B),L=I(this,w).add(I(h,x));return L.is0()?void 0:L}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:w}=t;if(h===bt)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:w}=t;return h===bt?this:w?w(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),ge(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let p=t.nBitLength,y=io(d,t.endo?Math.ceil(p/2):p);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function S0(r){let t=nn(r);return Wt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Pu(r){let t=S0(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 oo(C,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=B0({...t,toBytes(C,T,v){let b=T.toAffine(),A=e.toBytes(b.x),E=be;return Zt("isCompressed",v),v?E(Uint8Array.from([T.hasEvenY()?2:3]),A):E(Uint8Array.from([4]),A,e.toBytes(b.y))},fromBytes(C){let T=C.length,v=C[0],b=C.subarray(1);if(T===o&&(v===2||v===3)){let A=ye(b);if(!en(A,bt,e.ORDER))throw new Error("Point is not on curve");let E=u(A),R;try{R=e.sqrt(E)}catch(K){let F=K instanceof Error?": "+K.message:"";throw new Error("Point is not on curve"+F)}let U=(R&bt)===bt;return(v&1)===1!==U&&(R=e.neg(R)),{x:A,y:R}}else if(T===s&&v===4){let A=e.fromBytes(b.subarray(0,e.BYTES)),E=e.fromBytes(b.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 "+T)}}}),d=C=>ge(Me(C,t.nByteLength));function p(C){let T=n>>bt;return C>T}function y(C){return p(C)?i(-C):C}let g=(C,T,v)=>ye(C.slice(T,v));class h{constructor(T,v,b){this.r=T,this.s=v,this.recovery=b,this.assertValidity()}static fromCompact(T){let v=t.nByteLength;return T=ot("compactSignature",T,v*2),new h(g(T,0,v),g(T,v,2*v))}static fromDER(T){let{r:v,s:b}=Ie.toSig(ot("DER",T));return new h(v,b)}assertValidity(){Et("r",this.r,bt,n),Et("s",this.s,bt,n)}addRecoveryBit(T){return new h(this.r,this.s,T)}recoverPublicKey(T){let{r:v,s:b,recovery:A}=this,E=N(ot("msgHash",T));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let R=A===2||A===3?v+t.n:v;if(R>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let U=A&1?"03":"02",O=c.fromHex(U+d(R)),K=a(R),F=i(-E*K),W=i(b*K),j=c.BASE.multiplyAndAddUnsafe(O,F,W);if(!j)throw new Error("point at infinify");return j.assertValidity(),j}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return tr(this.toDERHex())}toDERHex(){return Ie.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return tr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let w={isValidPrivateKey(C){try{return l(C),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let C=Ci(t.n);return ul(t.randomBytes(C),t.n)},precompute(C=8,T=c.BASE){return T._setWindowSize(C),T.multiply(BigInt(3)),T}};function x(C,T=!0){return c.fromPrivateKey(C).toRawBytes(T)}function m(C){let T=Oe(C),v=typeof C=="string",b=(T||v)&&C.length;return T?b===o||b===s:v?b===2*o||b===2*s:C instanceof c}function I(C,T,v=!0){if(m(C))throw new Error("first arg must be private key");if(!m(T))throw new Error("second arg must be public key");return c.fromHex(T).multiply(l(C)).toRawBytes(v)}let L=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let T=ye(C),v=C.length*8-t.nBitLength;return v>0?T>>BigInt(v):T},N=t.bits2int_modN||function(C){return i(L(C))},B=rn(t.nBitLength);function k(C){return Et("num < 2^"+t.nBitLength,C,Ce,B),Me(C,t.nByteLength)}function S(C,T,v=H){if(["recovered","canonical"].some(it=>it in v))throw new Error("sign() legacy options not supported");let{hash:b,randomBytes:A}=t,{lowS:E,prehash:R,extraEntropy:U}=v;E==null&&(E=!0),C=ot("msgHash",C),Uu(v),R&&(C=ot("prehashed msgHash",b(C)));let O=N(C),K=l(T),F=[k(K),k(O)];if(U!=null&&U!==!1){let it=U===!0?A(e.BYTES):U;F.push(ot("extraEntropy",it))}let W=be(...F),j=O;function st(it){let ut=L(it);if(!f(ut))return;let It=a(ut),Pt=c.BASE.multiply(ut).toAffine(),_t=i(Pt.x);if(_t===Ce)return;let oe=i(It*i(j+_t*K));if(oe===Ce)return;let fe=(Pt.x===_t?0:2)|Number(Pt.y&bt),Gr=oe;return E&&p(oe)&&(Gr=y(oe),fe^=1),new h(_t,Gr,fe)}return{seed:W,k2sig:st}}let H={lowS:t.lowS,prehash:!1},_={lowS:t.lowS,prehash:!1};function M(C,T,v=H){let{seed:b,k2sig:A}=S(C,T,v),E=t;return Ei(E.hash.outputLen,E.nByteLength,E.hmac)(b,A)}c.BASE._setWindowSize(8);function V(C,T,v,b=_){let A=C;T=ot("msgHash",T),v=ot("publicKey",v);let{lowS:E,prehash:R,format:U}=b;if(Uu(b),"strict"in b)throw new Error("options.strict was renamed to lowS");if(U!==void 0&&U!=="compact"&&U!=="der")throw new Error("format must be compact or der");let O=typeof A=="string"||Oe(A),K=!O&&!U&&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{U!=="compact"&&(F=h.fromDER(A))}catch(fe){if(!(fe instanceof Ie.Err))throw fe}!F&&U!=="der"&&(F=h.fromCompact(A))}W=c.fromHex(v)}catch{return!1}if(!F||E&&F.hasHighS())return!1;R&&(T=t.hash(T));let{r:j,s:st}=F,it=N(T),ut=a(st),It=i(it*ut),Pt=i(j*ut),_t=c.BASE.multiplyAndAddUnsafe(W,It,Pt)?.toAffine();return _t?i(_t.x)===j:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:I,sign:M,verify:V,ProjectivePoint:c,Signature:h,utils:w}}function I0(r){return{hash:r,hmac:(t,...e)=>Pr(r,t,mi(...e)),randomBytes:tn}}function Ou(r,t){let e=n=>Pu({...r,...I0(n)});return{...e(t),create:e}}var Vu=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Mu=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),C0=BigInt(1),Aa=BigInt(2),Hu=(r,t)=>(r+t/Aa)/t;function k0(r){let t=Vu,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,p=at(d,Aa,t)*l%t,y=at(p,o,t)*p%t,g=at(y,s,t)*y%t,h=at(g,a,t)*g%t,w=at(h,c,t)*h%t,x=at(w,a,t)*g%t,m=at(x,e,t)*u%t,I=at(m,i,t)*y%t,L=at(I,n,t)*l%t,N=at(L,Aa,t);if(!Ba.eql(Ba.sqr(N),r))throw new Error("Cannot find square root");return N}var Ba=He(Vu,void 0,void 0,{sqrt:k0}),cr=Ou({a:BigInt(0),b:BigInt(7),Fp:Ba,n:Mu,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Mu,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-C0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=Hu(s*r,t),c=Hu(-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}}}},ae),ix=BigInt(0);var ax=cr.ProjectivePoint;function xt(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 Fu(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Ku(r,t,e){let n=cn.digest(e instanceof Uint8Array?e:e.subarray());if(Fu(n))return n.then(({digest:o})=>cr.verify(t,o,r)).catch(o=>{throw new bn(String(o))});try{return cr.verify(t,n.digest,r)}catch(o){throw new bn(String(o))}}var cs=class{type="secp256k1";raw;_key;constructor(t){this._key=Wu(t),this.raw=$u(this._key)}toMultihash(){return pe.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:Rt(this.raw,t.raw)}verify(t,e){return Ku(this._key,e,t)}};function Sa(r){return new cs(r)}function $u(r){return cr.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Wu(r){try{return cr.ProjectivePoint.fromHex(r),r}catch(t){throw new yr(String(t))}}function En(r){let{Type:t,Data:e}=ie.decode(r),n=e??new Uint8Array;switch(t){case wt.RSA:return va(n);case wt.Ed25519:return Ui(n);case wt.secp256k1:return Sa(n);default:throw new Xe}}function qu(r){let{Type:t,Data:e}=ie.decode(r.digest),n=e??new Uint8Array;switch(t){case wt.Ed25519:return Ui(n);case wt.secp256k1:return Sa(n);default:throw new Xe}}function kr(r){return ie.encode({Type:wt[r.type],Data:r.raw})}var zu=Symbol.for("nodejs.util.inspect.custom"),N0=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()})`}[ni]=!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(N0,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Rt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Rt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[zu](){return`PeerId(${this.toString()})`}},Bn=class extends An{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Sn=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}},L0=2336,ls=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=pe.digest(Q(this.url))}[zu](){return`PeerId(${this.url})`}[ni]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return vt.createV1(L0,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=Re(nt.decode(`z${r}`));else{if(t==null)throw new et('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Re(t.decode(r))}return _0(e)}function Ia(r){if(r.type==="Ed25519")return new Sn({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 Bn({multihash:r.toCID().multihash,publicKey:r});throw new Xe}function _0(r){if(U0(r))return new Bn({multihash:r});if(R0(r))try{let t=qu(r);if(t.type==="Ed25519")return new Sn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new In({multihash:r,publicKey:t})}catch{let e=X(r.digest);return new ls(new URL(e))}throw new zn("Supplied PeerID Multihash is invalid")}function R0(r){return r.code===pe.code}function U0(r){return r.code===cn.code}var us=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 Gu=45,D0=15,Mr=new us;function Ca(r){if(!(r.length>D0))return Mr.new(r).parseWith(()=>Mr.readIPv4Addr())}function ka(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Gu))return Mr.new(r).parseWith(()=>Mr.readIPv6Addr())}function fs(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>Gu)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 E1=parseInt("0xFFFF",16),A1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function hs(r){return!!Ca(r)}function ds(r){return!!ka(r)}function ps(r){return!!fs(r)}var Xu=hs,V0=ds,Ta=function(r){let t=0;if(r=r.toString().trim(),Xu(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(V0(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Xu(e[n]),i;s&&(i=Ta(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")},Yu=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={},Na={},K0=[[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"]];K0.forEach(r=>{let t=$0(...r);Na[t.code]=t,Hr[t.name]=t});function $0(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function tt(r){if(typeof r=="number"){if(Na[r]!=null)return Na[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 i2=tt("ip4"),a2=tt("ip6"),c2=tt("ipcidr");function Ua(r,t){switch(tt(r).code){case 4:case 41:return q0(t);case 42:return Ra(t);case 43:return X(t,"base10");case 6:case 273:case 33:case 132:return tf(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ra(t);case 421:return Z0(t);case 444:return Qu(t);case 445:return Qu(t);case 466:return j0(t);case 481:return globalThis.encodeURIComponent(Ra(t));default:return X(t,"base16")}}function Da(r,t){switch(tt(r).code){case 4:return Ju(t);case 41:return Ju(t);case 42:return _a(t);case 43:return Q(t,"base10");case 6:case 273:case 33:case 132:return Pa(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return _a(t);case 421:return z0(t);case 444:return X0(t);case 445:return Y0(t);case 466:return G0(t);case 481:return _a(globalThis.decodeURIComponent(t));default:return Q(t,"base16")}}var La=Object.values(or).map(r=>r.decoder),W0=function(){let r=La[0].or(La[1]);return La.slice(2).forEach(t=>r=r.or(t)),r}();function Ju(r){if(!ps(r))throw new Error("invalid ip address");return Ta(r)}function q0(r){let t=Yu(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!ps(t))throw new Error("invalid ip address");return t}function Pa(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function tf(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function _a(r){let t=Q(r),e=Uint8Array.from(se(t.length));return xt([e,t],e.length+t.length)}function Ra(r){let t=Jt(r);if(r=r.slice(ct(t)),r.length!==t)throw new Error("inconsistent lengths");return X(r)}function z0(r){let t;r[0]==="Q"||r[0]==="1"?t=Re(nt.decode(`z${r}`)).bytes:t=vt.parse(r).multihash.bytes;let e=Uint8Array.from(se(t.length));return xt([e,t],e.length+t.length)}function G0(r){let t=W0.decode(r),e=Uint8Array.from(se(t.length));return xt([e,t],e.length+t.length)}function j0(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 Z0(r){let t=Jt(r),e=r.slice(ct(t));if(e.length!==t)throw new Error("inconsistent lengths");return X(e,"base58btc")}function X0(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=de.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=Pa(n);return xt([e,o],e.length+o.length)}function Y0(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=de.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=Pa(n);return xt([e,o],e.length+o.length)}function Qu(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=X(t,"base32"),o=tf(e);return`${n}:${o}`}function ef(r){r=Oa(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 ms("invalid address: "+r);if(a.path===!0){n=Oa(o.slice(s).join("/")),t.push([a.code,Da(a.code,n)]),e.push([a.code,n]);break}let c=Da(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Ua(a.code,c)])}return{string:rf(e),bytes:Ha(t),tuples:t,stringTuples:e,path:n}}function Ma(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=Jt(r,o),i=ct(s),a=tt(s),c=J0(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 ms("Invalid address Uint8Array: "+X(r,"base16"));t.push([s,l]);let u=Ua(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:rf(e),tuples:t,stringTuples:e,path:n}}function rf(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}),Oa(t.join("/"))}function Ha(r){return xt(r.map(t=>{let e=tt(t[0]),n=Uint8Array.from(se(e.code));return t.length>1&&t[1]!=null&&(n=xt([n,t[1]])),n}))}function J0(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 Oa(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var ms=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var Q0=Symbol.for("nodejs.util.inspect.custom"),Fa=Symbol.for("@multiformats/js-multiaddr/multiaddr"),tm=[tt("dns").code,tt("dns4").code,tt("dns6").code,tt("dnsaddr").code],Va=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},gs=class r{bytes;#t;#e;#r;#n;[Fa]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Ma(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=ef(t)}else if(of(t))e=Ma(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[p,y]of this.stringTuples())p===f.code&&(s=`%${y??""}`),tm.includes(p)&&(e=i.name==="tcp"?"tcp":"udp",o=443,n=`${y??""}${s}`,t=p===u.code?6:4),(p===i.code||p===a.code)&&(e=tt(p).name==="tcp"?"tcp":"udp",o=parseInt(y??"")),(p===c.code||p===l.code)&&(e=tt(p).name==="tcp"?"tcp":"udp",n=`${y??""}${s}`,t=p===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(Ha(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 Rt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=nf.get(e.name);if(n==null)throw new Va(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>ze(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)}[Q0](){return`Multiaddr(${this.#t})`}};var nf=new Map;function of(r){return!!r?.[Fa]}function ze(r){return new gs(r)}var em=r=>r.toString().split("/").slice(1),Vr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),q=r=>({match:t=>Vr(e=>e===r).match(t),pattern:r}),lr=()=>({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{nt.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{Xi.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})`}),Lt=(...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(", ")})`}),G=(...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=em(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 ws=G(q("dns4"),lr()),bs=G(q("dns6"),lr()),xs=G(q("dnsaddr"),lr()),$a=G(q("dns"),lr()),O2=lt(ws,Y(rt())),M2=lt(bs,Y(rt())),H2=lt(xs,Y(rt())),V2=lt(Lt($a,xs,ws,bs),Y(rt())),sf=G(q("ip4"),Vr(hs)),af=G(q("ip6"),Vr(ds)),Wa=Lt(sf,af),ke=Lt(Wa,$a,ws,bs,xs),F2=lt(Lt(Wa,G(Lt($a,xs,ws,bs),Y(rt())))),K2=lt(sf),$2=lt(af),W2=lt(Wa),qa=G(ke,q("tcp"),Cn()),Tn=G(ke,q("udp"),Cn()),q2=lt(G(qa,Y(rt()))),z2=lt(Tn),za=G(Tn,q("quic"),Y(rt())),vs=G(Tn,q("quic-v1"),Y(rt())),rm=Lt(za,vs),G2=lt(za),j2=lt(vs),Ka=Lt(ke,qa,Tn,za,vs),cf=Lt(G(Ka,q("ws"),Y(rt()))),Z2=lt(cf),lf=Lt(G(Ka,q("wss"),Y(rt())),G(Ka,q("tls"),Y(G(q("sni"),lr())),q("ws"),Y(rt()))),X2=lt(lf),uf=G(Tn,q("webrtc-direct"),Y(kn()),Y(kn()),Y(rt())),ff=lt(uf),hf=G(vs,q("webtransport"),Y(kn()),Y(kn()),Y(rt())),Y2=lt(hf),ys=Lt(cf,lf,G(qa,Y(rt())),G(rm,Y(rt())),G(ke,Y(rt())),uf,hf,rt()),df=lt(ys),nm=G(ys,q("p2p-circuit"),rt()),J2=lt(nm),om=Lt(G(ys,q("p2p-circuit"),q("webrtc"),Y(rt())),G(ys,q("webrtc"),Y(rt())),G(q("webrtc"),Y(rt()))),pf=lt(om),sm=Lt(G(ke,q("tcp"),Cn(),q("http"),Y(rt())),G(ke,q("http"),Y(rt()))),Q2=lt(sm),im=Lt(G(ke,q("tcp"),Lt(G(q("443"),q("http")),G(Cn(),q("https"))),Y(rt())),G(ke,q("tls"),q("http"),Y(rt())),G(ke,q("https"),Y(rt()))),tv=lt(im),am=Lt(G(q("memory"),lr(),Y(rt()))),ev=lt(am);var mf=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 lm=function(){function r(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return r}();var um=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 fm=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var hm=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var dm=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,pm=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,gf=3,mm=[["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",dm]],yf=[["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 bf(r){return r?wf(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new hm:typeof navigator<"u"?wf(navigator.userAgent):wm()}function gm(r){return r!==""&&mm.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 wf(r){var t=gm(r);if(!t)return null;var e=t[0],n=t[1];if(e==="searchbot")return new fm;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<gf&&(o=mf(mf([],o,!0),bm(gf-o.length),!0)):o=[];var s=o.join("."),i=ym(r),a=pm.exec(r);return a&&a[1]?new um(e,s,i,a[1]):new cm(e,s,i)}function ym(r){for(var t=0,e=yf.length;t<e;t++){var n=yf[t],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function wm(){var r=typeof process<"u"&&process.version;return r?new lm(process.version.slice(1)):null}function bm(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 Ga=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},ja=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},xf=r=>globalThis.DOMException===void 0?new ja(r):new DOMException(r),vf=r=>{let t=r.reason===void 0?xf("This operation was aborted."):r.reason;return t instanceof Error?t:xf(t)};function ur(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:p}=t;p.aborted&&f(vf(p)),a=()=>{f(vf(p))},p.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new Ga;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(p){f(p)}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(p){f(p)}})()}).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 Ef=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"];var Af=bf(),Nn=Af!=null&&Af.name==="firefox",Es=async function*(){},As=async r=>{},xm=30*1e3;function Bf(r,t,e=xm,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 ur(o.promise,{milliseconds:e})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function Ln(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??Ef.map(t=>({urls:[t]})),r}var fr=class{log;peerConnection;remoteAddr;timeline;metrics;source=Es();sink=As;constructor(t,e){this.log=t.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=e.remoteAddr,this.timeline=e.timeline,this.peerConnection=e.peerConnection;let n=this.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",this.peerConnection.connectionState,"initial state",n),(this.peerConnection.connectionState==="disconnected"||this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.timeline.close=Date.now())}}async close(t){this.log.trace("closing connection"),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({close:!0})}abort(t){this.log.error("closing connection due to error",t),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({abort:!0})}};var Bs=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}},Fr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Bs(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 Bs(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 Ge(r={}){return vm(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 vm(r,t){t=t??{};let e=t.onEnd,n=new Fr,o,s,i,a=pt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,w)=>{s=x=>{s=null,n.push(x);try{h(r(n))}catch(m){w(m)}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 Fr,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})),p=()=>(n=new Fr,d(),{done:!0}),y=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:y,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let w=h?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let x,m;w!=null&&(x=new Promise((I,L)=>{m=()=>{L(new Za)},w.addEventListener("abort",m)}));try{await Promise.race([a.promise,x])}finally{m!=null&&w!=null&&w?.removeEventListener("abort",m)}}},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 Ss=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 Te(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new Ss(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new Ss(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 If=Symbol.for("@achingbrain/uint8arraylist");function Sf(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 Is(r){return!!r?.[If]}var ht=class r{bufs;length;[If]=!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(Is(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(Is(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=Sf(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Sf(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(Is(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 xt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:xt(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(!Is(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 p=this.get(f+d);if(n[d]!==p){u=Math.max(1,d-a[p]);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(!Rt(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 Cf(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 Tf(r,t){let e=Cf(r).return?.();kf(e)&&e.catch(n=>{t.error("could not cause iterator to return",n)})}var Em=5e3;function Xa(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Cs=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??Em,this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=Ge({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 Ze(`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=()=>{Tf(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 Te(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 Te(this.sink([]),t.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await Te(this.sendingData.promise,t.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await Te(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 qn("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(t),this.onReset?.()}_closeSinkAndSource(t){this._closeSink(t),this._closeSource(t)}_closeSink(t){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(t)}_closeSource(t){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(t))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(t){this.streamSource.push(t)}sourceReadableLength(){return this.streamSource.readableLength}};function ks(r){return r[Symbol.asyncIterator]!=null}var Ts=r=>{let t=ct(r),e=yt(t);return se(r,e),Ts.bytes=t,e};Ts.bytes=0;function _n(r,t){t=t??{};let e=t.lengthEncoder??Ts;function*n(o){let s=e(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return ks(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}_n.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Ts;return new ht(e(r.byteLength),r)};var Ns=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ls=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},_s=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Rn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Am=8,Bm=1024*1024*4,hr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(hr||(hr={}));var Ya=r=>{let t=Jt(r);return Ya.bytes=ct(t),t};Ya.bytes=0;function dr(r,t){let e=new ht,n=hr.LENGTH,o=-1,s=t?.lengthDecoder??Ya,i=t?.maxLengthLength??Am,a=t?.maxDataLength??Bm;function*c(){for(;e.byteLength>0;){if(n===hr.LENGTH)try{if(o=s(e),o<0)throw new Ns("Invalid message length");if(o>a)throw new Ls("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=hr.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new _s("Message length length too long");break}throw l}if(n===hr.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=hr.LENGTH}}}return ks(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Rn("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Rn("Unexpected end of input")}()}dr.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 dr(n,{...t??{},onLength:s=>{e=s}})};var Im=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function Cm(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:u}=Im(r),f=(...p)=>{let y=e.multiArgs?p:p[0];e.filter&&!e.filter(y)||(c.push(y),e.count===c.length&&(n(),s(c)))},d=p=>{n(),i(p)};n=()=>{for(let p of a)u(p,f);for(let p of e.rejectionEvents)u(p,d)};for(let p of a)l(p,f);for(let p of e.rejectionEvents)l(p,d);e.signal&&e.signal.addEventListener("abort",()=>{d(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=ur(o,{milliseconds:e.timeout});return s.cancel=n,s}return o}function Ja(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=Cm(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}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=()=>ir(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 km=2*1024*1024,Tm=30*1e3,Rs=16*1024;function Nm(r=Rs){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 Lm=Nm(),_m=5e3,Rm=5e3,Qa=class extends Cs{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;constructor(t){let e=t.onEnd;switch(t.onEnd=o=>{this.log.trace("readable and writeable ends closed",this.status),Promise.resolve(async()=>{if(!(this.timeline.abort!=null||this.timeline.reset!==null))try{await ur(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(s){this.log.error("error receiving FIN_ACK",s)}}).then(()=>{this.incomingData.end(),e?.(o)}).catch(s=>{this.log.error("error ending stream",s)})},super(t),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=Ge(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??Tm,this.maxBufferedAmount=t.maxBufferedAmount??km,this.maxMessageSize=(t.maxMessageSize??Rs)-Lm,this.receiveFinAck=pt(),this.finAckTimeout=t.closeTimeout??_m,this.openTimeout=t.openTimeout??Rm,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 Ze("Unknown datachannel state")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime()},this.channel.onclose=o=>{this.receiveFinAck.resolve(),this.close().catch(s=>{this.log.error("error closing stream after channel closed",s)})},this.channel.onerror=o=>{let s=o.error;this.abort(s)},this.channel.onmessage=async o=>{let{data:s}=o;s===null||s.byteLength===0||this.incomingData.push(new Uint8Array(s,0,s.byteLength))};let n=this;Promise.resolve().then(async()=>{for await(let o of dr(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(e&&this.channel.bufferedAmount>this.maxBufferedAmount)try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await Ja(this.channel,"bufferedamountlow",{timeout:this.bufferedAmountLowEventTimeout})}catch(n){throw n instanceof jr?new jr(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`):n}if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new Ze(`Invalid datachannel state - ${this.channel.readyState}`);this.channel.readyState!=="open"&&(this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await Ja(this.channel,"open",{timeout:this.openTimeout}),this.log('channel state is now "%s", sending data',this.channel.readyState)),this.channel.send(t.subarray())}async sendData(t){for(t=t.sublist();t.byteLength>0;){let e=Math.min(t.byteLength,this.maxMessageSize),n=t.subarray(0,e),o=Dt.encode({message:n}),s=_n.single(o);await this._sendMessage(s),t.consume(e)}}async sendReset(){try{await this._sendFlag(Dt.Flag.RESET)}catch(t){this.log.error("failed to send reset - %e",t)}}async sendCloseWrite(t){if(await this._sendFlag(Dt.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await Te(this.receiveFinAck.promise,t?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorName:"FinAckNotReceivedError"})}catch(n){this.log.error("failed to await FIN_ACK",n)}}else this.log.trace("sending FIN failed, not awaiting FIN_ACK");this.receiveFinAck.resolve()}async sendCloseRead(){await this._sendFlag(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=_n.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 Qa({id:e==="inbound"?`i${t.id}`:`r${t.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${e}:${t.id}`),...r})}var Nf="/webrtc",je=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??Nf,this.dataChannelOptions=e.dataChannelOptions??{},this.log=t.logger.forComponent("libp2p:webrtc:datachannelmuxerfactory"),this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace('incoming early datachannel with channel id %d and label "%s"',n.id),n.label==="init"){this.log.trace("closing early init channel"),n.close();return}let o={},s=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 tc(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},tc=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??Nf,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),Bf(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=Es();sink=As;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 pr=globalThis.RTCPeerConnection,Us=globalThis.RTCSessionDescription,Lf=globalThis.RTCIceCandidate;var ec=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 Te(this.readNext.promise,e?.signal,e)}};function _f(){return new ec}var Ds=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var rc=class extends Error{code;constructor(t,e){super(t),this.code=e}},nc=class extends rc{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Rf(r,t){let e=_f();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 nc("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 Ds("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 Ps=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Os=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ms=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Un(r,t={}){let e=Rf(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=ct(t.maxDataLength));let n=t?.lengthDecoder??Jt,o=t?.lengthEncoder??se;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 Ps("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ms("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Os("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 Hs(r,t){let e=Un(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 mr=class extends Error{constructor(t){super(`WebRTC transport error: ${t}`),this.name="WebRTCTransportError"}},zt=class extends mr{constructor(t="SDP handshake failed"){super(t),this.name="SDPHandshakeFailedError"}};var Dn=class extends mr{constructor(t,e){super(`[stream: ${t}] data channel error: ${e}`),this.name="WebRTC/DataChannelError"}};var Pn=class extends mr{constructor(t,e){super(`Invalid fingerprint "${t}" within ${e}`),this.name="WebRTC/InvalidFingerprintError"}};var Vs=class extends mr{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},Fs=class extends mr{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 Vt;(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=()=>ir(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)})(Vt||(Vt={}));var Ks=async(r,t,e)=>{try{let n=pt();for(Um(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!==Vt.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 Lf(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&&$s(r)!=="connected")throw n}};function $s(r){return Nn?r.iceConnectionState:r.connectionState}function Um(r,t){r[Nn?"oniceconnectionstatechange":"onconnectionstatechange"]=e=>{switch($s(r)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new Wn("RTCPeerConnection was closed"));break;default:break}}}async function Uf({rtcConfiguration:r,dataChannel:t,signal:e,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=Df(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",u);let f=u.getPeerId();if(f==null)throw new et("Relay peer was missing");let d=s.getConnections(Or(f)),p,y=!1;d.length===0?(l?.(new $t("webrtc:dial-relay")),p=await i.dial(u,{signal:e,onProgress:l}),y=!0):(l?.(new $t("webrtc:reuse-relay-connection")),p=d[0]);try{l?.(new $t("webrtc:open-signaling-stream"));let g=await p.newStream(Ws,{signal:e,runOnLimitedConnection:!0}),h=Hs(g).pb(Vt),w=new pr(r),x=new je({logger:c},{peerConnection:w,dataChannelOptions:t});try{let m=w.createDataChannel("init");w.onicecandidate=({candidate:B})=>{let k=JSON.stringify(B?.toJSON()??null);a.trace("initiator sending ICE candidate %o",B),h.write({type:Vt.Type.ICE_CANDIDATE,data:k},{signal:e}).catch(S=>{a.error("error sending ICE candidate",S)})},w.onicecandidateerror=B=>{a.error("initiator ICE candidate error",B)};let I=await w.createOffer().catch(B=>{throw a.error("could not execute createOffer",B),new zt("Failed to set createOffer")});a.trace("initiator send SDP offer %s",I.sdp),l?.(new $t("webrtc:send-sdp-offer")),await h.write({type:Vt.Type.SDP_OFFER,data:I.sdp},{signal:e}),await w.setLocalDescription(I).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!==Vt.Type.SDP_ANSWER)throw new zt("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",L.data);let N=new Us({type:"answer",sdp:L.data});return await w.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 Ks(w,h,{direction:"initiator",signal:e,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),m.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:w,muxerFactory:x}}catch(m){throw a.error("outgoing signaling error",m),w.close(),g.abort(m),m}finally{w.onicecandidate=null,w.onicecandidateerror=null}}finally{if(y)try{await p.close({signal:e})}catch(g){p.abort(g)}}}var Dm=lt(df.matchers[0],q("p2p-circuit")),qs=class extends Zn{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=>Dm.exactMatch(e)).map(e=>e.encapsulate("/webrtc"))).flat()}async close(){this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function Pf({peerConnection:r,stream:t,signal:e,connection:n,log:o}){o.trace("new inbound signaling stream");let s=Hs(t).pb(Vt);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:Vt.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!==Vt.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 Us({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:Vt.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 Ks(r,s,{direction:"recipient",signal:e,log:o})}catch(a){if($s(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=ze(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return o.trace("recipient connected to remote address %s",i),{remoteAddress:i}}var Pm="/webrtc",Om="/p2p-circuit",Ws="/webrtc-signaling/0.0.1",Mm=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,jn(1/0,this.shutdownController.signal),t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[Kn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[wr]=["@libp2p/transport"];[Oc]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(Ws,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(Ws),this._started=!1}createListener(t){return new qs(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(pf.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 Uf({rtcConfiguration:await Ln(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 fr(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??Mm),o=new pr(await Ln(this.init.rtcConfiguration)),s=new je(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await Pf({peerConnection:o,connection:t,stream:e,signal:n,log:this.log});await e.close({signal:n});let a=new fr(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 Df(r){let t=r.toString().split(Pm+"/");if(t.length!==2)throw new et("webrtc protocol was not present in multiaddr");if(!t[0].includes(Om))throw new et("p2p-circuit protocol was not present in multiaddr");let e=ze(t[0]),o=ze("/"+t[1]).getPeerId();if(o==null)throw new et("destination peer id was missing");let s=e.protos().pop();if(s===void 0)throw new et("invalid multiaddr");return s.name!=="p2p"&&(e=e.encapsulate(`/p2p/${o}`)),{baseAddr:e,peerId:Or(o)}}function oc(){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 Of(){let r=oc(),t=oc();return[{source:r.source,sink:t.sink},{source:t.source,sink:r.sink}]}function Hm(r){return r[Symbol.asyncIterator]!=null}function Vm(...r){let t=[];for(let e of r)Hm(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=Ge({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 Mf=Vm;function Hf(r,...t){if(r==null)throw new Error("Empty pipeline");if(sc(r)){let n=r;r=()=>n.source}else if(Ff(r)||Vf(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&sc(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++)sc(e[n])&&(e[n]=Km(e[n]));return Fm(...e)}var Fm=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Vf=r=>r?.[Symbol.asyncIterator]!=null,Ff=r=>r?.[Symbol.iterator]!=null,sc=r=>r==null?!1:r.sink!=null&&r.source!=null,Km=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Ge({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(Vf(s))o=async function*(){yield*s,n.end()};else if(Ff(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Mf(n,o())}return r.source};var $r=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function Gs(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function ic(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function ac(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Ft(r,...t){if(!ac(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 cc(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 Kf(r,t){Ft(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var Ne=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),$f=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),$m=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!$m)throw new Error("Non little-endian hardware is not supported");function Wm(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=Wm(r);else if(ac(r))r=Zs(r);else throw new Error(`Uint8Array expected, got ${typeof r}`);return r}function Wf(r,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(r,t)}function qf(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 lc=(r,t)=>(Object.assign(t,r),t);function uc(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 Le(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}var Gf=r=>Uint8Array.from(r.split("").map(t=>t.charCodeAt(0))),qm=Gf("expand 16-byte k"),zm=Gf("expand 32-byte k"),Gm=Ne(qm),jf=Ne(zm),UA=jf.slice();function P(r,t){return r<<t|r>>>32-t}function fc(r){return r.byteOffset%4===0}var Xs=64,jm=16,Zf=2**32-1,zf=new Uint32Array;function Zm(r,t,e,n,o,s,i,a){let c=o.length,l=new Uint8Array(Xs),u=Ne(l),f=fc(o)&&fc(s),d=f?Ne(o):zf,p=f?Ne(s):zf;for(let y=0;y<c;i++){if(r(t,e,n,u,i,a),i>=Zf)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 w=0,x;w<jm;w++)x=h+w,p[x]=d[x]^u[w];y+=Xs;continue}for(let h=0,w;h<g;h++)w=y+h,s[w]=o[w]^l[h];y+=g}}function hc(r,t){let{allowShortKeys:e,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Wf({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof r!="function")throw new Error("core must be a function");return Gs(o),Gs(i),ic(s),ic(e),(a,c,l,u,f=0)=>{Ft(a),Ft(c),Ft(l);let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),Ft(u),Gs(f),f<0||f>=Zf)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let p=[],y=a.length,g,h;if(y===32)p.push(g=Zs(a)),h=jf;else if(y===16&&e)g=new Uint8Array(32),g.set(a),g.set(a,16),h=Gm,p.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${y}`);fc(c)||p.push(c=Zs(c));let w=Ne(g);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,w,Ne(c.subarray(0,16)),w),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 I=new Uint8Array(12);I.set(c,s?0:12-c.length),c=I,p.push(c)}let m=Ne(c);return Zm(r,h,w,m,l,u,f,i),Le(...p),u}}var St=(r,t)=>r[t++]&255|(r[t++]&255)<<8,dc=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),Ft(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],p=i[6],y=i[7],g=i[8],h=i[9],w=St(t,e+0),x=St(t,e+2),m=St(t,e+4),I=St(t,e+6),L=St(t,e+8),N=St(t,e+10),B=St(t,e+12),k=St(t,e+14),S=s[0]+(w&8191),H=s[1]+((w>>>13|x<<3)&8191),_=s[2]+((x>>>10|m<<6)&8191),M=s[3]+((m>>>7|I<<9)&8191),V=s[4]+((I>>>4|L<<12)&8191),C=s[5]+(L>>>1&8191),T=s[6]+((L>>>14|N<<2)&8191),v=s[7]+((N>>>11|B<<5)&8191),b=s[8]+((B>>>8|k<<8)&8191),A=s[9]+(k>>>5|o),E=0,R=E+S*a+H*(5*h)+_*(5*g)+M*(5*y)+V*(5*p);E=R>>>13,R&=8191,R+=C*(5*d)+T*(5*f)+v*(5*u)+b*(5*l)+A*(5*c),E+=R>>>13,R&=8191;let U=E+S*c+H*a+_*(5*h)+M*(5*g)+V*(5*y);E=U>>>13,U&=8191,U+=C*(5*p)+T*(5*d)+v*(5*f)+b*(5*u)+A*(5*l),E+=U>>>13,U&=8191;let O=E+S*l+H*c+_*a+M*(5*h)+V*(5*g);E=O>>>13,O&=8191,O+=C*(5*y)+T*(5*p)+v*(5*d)+b*(5*f)+A*(5*u),E+=O>>>13,O&=8191;let K=E+S*u+H*l+_*c+M*a+V*(5*h);E=K>>>13,K&=8191,K+=C*(5*g)+T*(5*y)+v*(5*p)+b*(5*d)+A*(5*f),E+=K>>>13,K&=8191;let F=E+S*f+H*u+_*l+M*c+V*a;E=F>>>13,F&=8191,F+=C*(5*h)+T*(5*g)+v*(5*y)+b*(5*p)+A*(5*d),E+=F>>>13,F&=8191;let W=E+S*d+H*f+_*u+M*l+V*c;E=W>>>13,W&=8191,W+=C*a+T*(5*h)+v*(5*g)+b*(5*y)+A*(5*p),E+=W>>>13,W&=8191;let j=E+S*p+H*d+_*f+M*u+V*l;E=j>>>13,j&=8191,j+=C*c+T*a+v*(5*h)+b*(5*g)+A*(5*y),E+=j>>>13,j&=8191;let st=E+S*y+H*p+_*d+M*f+V*u;E=st>>>13,st&=8191,st+=C*l+T*c+v*a+b*(5*h)+A*(5*g),E+=st>>>13,st&=8191;let it=E+S*g+H*y+_*p+M*d+V*f;E=it>>>13,it&=8191,it+=C*u+T*l+v*c+b*a+A*(5*h),E+=it>>>13,it&=8191;let ut=E+S*h+H*g+_*y+M*p+V*d;E=ut>>>13,ut&=8191,ut+=C*f+T*u+v*l+b*c+A*a,E+=ut>>>13,ut&=8191,E=(E<<2)+E|0,E=E+R|0,R=E&8191,E=E>>>13,U+=E,s[0]=R,s[1]=U,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;Le(n)}update(t){cc(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(){Le(this.h,this.r,this.buffer,this.pad)}digestInto(t){cc(this),Kf(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 Xm(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 Xf=Xm(r=>new dc(r));function Qf(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],p=t[3],y=t[4],g=t[5],h=t[6],w=t[7],x=o,m=e[0],I=e[1],L=e[2],N=i,B=a,k=c,S=l,H=u,_=f,M=d,V=p,C=y,T=g,v=h,b=w,A=x,E=m,R=I,U=L;for(let K=0;K<s;K+=2)N=N+H|0,A=P(A^N,16),C=C+A|0,H=P(H^C,12),N=N+H|0,A=P(A^N,8),C=C+A|0,H=P(H^C,7),B=B+_|0,E=P(E^B,16),T=T+E|0,_=P(_^T,12),B=B+_|0,E=P(E^B,8),T=T+E|0,_=P(_^T,7),k=k+M|0,R=P(R^k,16),v=v+R|0,M=P(M^v,12),k=k+M|0,R=P(R^k,8),v=v+R|0,M=P(M^v,7),S=S+V|0,U=P(U^S,16),b=b+U|0,V=P(V^b,12),S=S+V|0,U=P(U^S,8),b=b+U|0,V=P(V^b,7),N=N+_|0,U=P(U^N,16),v=v+U|0,_=P(_^v,12),N=N+_|0,U=P(U^N,8),v=v+U|0,_=P(_^v,7),B=B+M|0,A=P(A^B,16),b=b+A|0,M=P(M^b,12),B=B+M|0,A=P(A^B,8),b=b+A|0,M=P(M^b,7),k=k+V|0,E=P(E^k,16),C=C+E|0,V=P(V^C,12),k=k+V|0,E=P(E^k,8),C=C+E|0,V=P(V^C,7),S=S+H|0,R=P(R^S,16),T=T+R|0,H=P(H^T,12),S=S+H|0,R=P(R^S,8),T=T+R|0,H=P(H^T,7);let O=0;n[O++]=i+N|0,n[O++]=a+B|0,n[O++]=c+k|0,n[O++]=l+S|0,n[O++]=u+H|0,n[O++]=f+_|0,n[O++]=d+M|0,n[O++]=p+V|0,n[O++]=y+C|0,n[O++]=g+T|0,n[O++]=h+v|0,n[O++]=w+b|0,n[O++]=x+A|0,n[O++]=m+E|0,n[O++]=I+R|0,n[O++]=L+U|0}function Ym(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],p=t[5],y=t[6],g=t[7],h=e[0],w=e[1],x=e[2],m=e[3];for(let L=0;L<20;L+=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,w=P(w^s,16),p=p+w|0,l=P(l^p,12),s=s+l|0,w=P(w^s,8),p=p+w|0,l=P(l^p,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,m=P(m^a,16),g=g+m|0,f=P(f^g,12),a=a+f|0,m=P(m^a,8),g=g+m|0,f=P(f^g,7),o=o+l|0,m=P(m^o,16),y=y+m|0,l=P(l^y,12),o=o+l|0,m=P(m^o,8),y=y+m|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,w=P(w^i,16),d=d+w|0,f=P(f^d,12),i=i+f|0,w=P(w^i,8),d=d+w|0,f=P(f^d,7),a=a+c|0,x=P(x^a,16),p=p+x|0,c=P(c^p,12),a=a+c|0,x=P(x^a,8),p=p+x|0,c=P(c^p,7);let I=0;n[I++]=o,n[I++]=s,n[I++]=i,n[I++]=a,n[I++]=h,n[I++]=w,n[I++]=x,n[I++]=m}var Jm=hc(Qf,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Qm=hc(Qf,{counterRight:!1,counterLength:8,extendNonceFn:Ym,allowShortKeys:!1});var tg=new Uint8Array(16),Yf=(r,t)=>{r.update(t);let e=t.length%16;e&&r.update(tg.subarray(e))},eg=new Uint8Array(32);function Jf(r,t,e,n,o){let s=r(t,e,eg),i=Xf.create(s);o&&Yf(i,o),Yf(i,n);let a=new Uint8Array(16),c=$f(a);uc(c,0,BigInt(o?o.length:0),!0),uc(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return Le(s,a),l}var th=r=>(t,e,n)=>(Ft(t,32),Ft(e),{encrypt(s,i){let a=s.length,c=a+16;i?Ft(i,c):i=new Uint8Array(c),r(t,e,s,i,1);let l=Jf(r,t,e,i.subarray(0,-16),n);return i.set(l,a),Le(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?Ft(i,c):i=new Uint8Array(c);let l=s.subarray(0,-16),u=s.subarray(-16),f=Jf(r,t,e,l,n);if(!qf(u,f))throw new Error("invalid tag");return r(t,e,l,i,1),Le(f),i}}),pc=lc({blockSize:64,nonceLength:12,tagLength:16},th(Jm)),$A=lc({blockSize:64,nonceLength:24,tagLength:16},th(Qm));function rh(r,t,e){return Qr(r),e===void 0&&(e=new Uint8Array(r.outputLen)),Pr(r,Ue(e),Ue(t))}var mc=new Uint8Array([0]),eh=new Uint8Array;function nh(r,t,e,n=32){if(Qr(r),Yn(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);e===void 0&&(e=eh);let s=new Uint8Array(o*r.outputLen),i=Pr.create(r,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)mc[0]=l+1,a.update(l===0?eh:c).update(e).update(mc).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),mc.fill(0),s.slice(0,n)}var gc={hashSHA256(r){return ae(r.subarray())},getHKDF(r,t){let e=rh(ae,t,r),o=nh(ae,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=sn.utils.randomPrivateKey();return{publicKey:sn.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:sn.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,t){return sn.getSharedSecret(r.subarray(),t.subarray())},chaCha20Poly1305Encrypt(r,t,e,n){return pc(n,t,e).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,t,e,n,o){return pc(n,t,e).decrypt(r.subarray(),o)}};var oh=gc;function sh(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 On=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)};On.bytes=2;function ih(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 yc(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 wc(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 ah(r,t){!t.enabled||!$r||t(r?`REMOTE_STATIC_PUBLIC_KEY ${X(r.subarray(),"hex")}`:"Missing remote static public key.")}function bc(r,t){!t.enabled||!$r||t(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${X(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function xc(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 rg=0,ng=4294967295,og="Cipherstate has reached maximum n, a new handshake must be performed",Ys=class{n;bytes;view;constructor(t=rg){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>ng)throw new Error(og)}};var gr=gt(0),zr=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}},vc=class{cs;ck;h;crypto;constructor(t,e){this.crypto=t;let n=Q(e,"utf-8");this.h=sg(t,n),this.ck=this.h,this.cs=new zr(t)}mixKey(t){let[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new zr(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,gr);return[new zr(this.crypto,t),new zr(this.crypto,e)]}},Ec=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 vc(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()}},Mn=class extends Ec{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 sg(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 Hn;(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())})(Hn||(Hn={}));async function Ac(r,t,e){let n=await r.sign(ch(t));return Hn.encode({identityKey:kr(r.publicKey),identitySig:n,extensions:e})}async function Bc(r,t,e){try{let n=Hn.decode(r),o=En(n.identityKey);if(e?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${e}`);if(!t)throw new Error("Remote static does not exist");let s=ch(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new $n(n.message)}}function ch(r){let t=Q("noise-libp2p-static-key:");return r instanceof Uint8Array?xt([t,r],t.length+r.length):(r.prepend(t),r)}async function lh(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Ac(s,a.publicKey,l),f=new Mn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});yc(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."),wc(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."),bc(f.re,e),ah(f.rs,e),e.trace("Initiator going to check remote's signature...");let p=await Bc(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 xc(y,g,e),{payload:p,encrypt:h=>y.encryptWithAd(gr,h),decrypt:(h,w)=>g.decryptWithAd(gr,h,w)}}async function uh(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Ac(s,a.publicKey,l),f=new Mn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});yc(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."),bc(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."),wc(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 p=await Bc(d,f.rs,c),[y,g]=f.ss.split();return xc(y,g,e),{payload:p,encrypt:h=>g.encryptWithAd(gr,h),decrypt:(h,w)=>y.decryptWithAd(gr,h,w)}}var hh=16;function dh(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 ph(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-hh<o)throw new Error("Invalid chunk");let i=n.sublist(o,s),a=n.subarray(o,s-hh);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??oh;this.crypto=sh(c),this.extensions=o,this.metrics=a?ih(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=Un(t,{lengthEncoder:Wr,lengthDecoder:On,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=En(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Ia(i)}}async secureInbound(t,e){let n=Un(t,{lengthEncoder:Wr,lengthDecoder:On,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=En(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Ia(i)}}async performHandshakeInitiator(t,e,n,o){let s;try{s=await lh({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 uh({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]=Of(),s=t.unwrap();return await Hf(n,dh(e,this.metrics),s,i=>dr(i,{lengthDecoder:On}),ph(e,this.metrics),n),o}};function mh(r={}){return t=>new Qs(t,r)}var Sc=Object.values(or).map(r=>r.decoder).reduce((r,t)=>r.or(t));function gh(r,t){let e=r.getConfiguration().certificates?.at(0);if(e?.getFingerprints==null){t.log.trace("fetching fingerprint from local SDP");let o=r.localDescription;return o==null?void 0:ag(o.sdp)}if(t.log.trace("fetching fingerprint from local certificate"),e.getFingerprints().length===0)return;let n=e.getFingerprints()[0].value;if(n==null)throw new Pn("","no fingerprint on local certificate");return n}var ig=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function ag(r){return r.match(ig)?.groups?.fingerprint}function cg(r){for(let t of r.protoNames())if(t.startsWith("ip"))return t.toUpperCase();return"IP6"}function ti(r){let e=r.stringTuples().filter(n=>n[0]===bh).map(n=>n[1])[0];if(e===void 0||e==="")throw new et(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return e}function Ic(r){return Gt.decode(Sc.decode(r))}function lg(r){let t=Ic(ti(r)),e=Cc(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 Pn(n,r.toString());return[`${e} ${o.join(":").toUpperCase()}`,n]}function Cc(r){switch(r){case 17:return"SHA-1";case 18:return"SHA-256";case 19:return"SHA-512";default:throw new Fs(r)}}function ug(r,t){let{host:e,port:n}=r.toOptions(),o=cg(r),[s]=lg(r);return`v=0
6
+ `)}`:`${e} :`}};ql=We;D.Constructed=ql;We.NAME="CONSTRUCTED";var Bo=class extends Nt{fromBER(t,e,n){return e}toBER(t){return ne}};Bo.override="EndOfContentValueBlock";var zl,So=class extends At{constructor(t={}){super(t,Bo),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};zl=So;D.EndOfContent=zl;So.NAME=dn;var Gl,Lr=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}`}};Gl=Lr;D.Null=Gl;Lr.NAME="NULL";var Io=class extends Se(Nt){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=z.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=z.BufferSourceConverter.toUint8Array(t);return Be(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,da.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Io.NAME="BooleanValueBlock";var jl,Co=class extends At{constructor(t={}){super(t,Io),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}`}};jl=Co;D.Boolean=jl;Co.NAME="BOOLEAN";var ko=class extends Se(ce){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=ce.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!==Fl)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?ce.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};ko.NAME="OctetStringValueBlock";var Zl,To=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},ko),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=ns(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?We.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${z.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 z.BufferSourceConverter.concat(t)}};Zl=To;D.OctetString=Zl;To.NAME=Fl;var No=class extends Se(ce){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=ce.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!==Kl)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=z.BufferSourceConverter.toUint8Array(t);if(!Be(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=ns(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 ce.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}}};No.NAME="BitStringValueBlock";var Xl,_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},No),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 We.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)}`}}};Xl=_r;D.BitString=Xl;_r.NAME=Kl;var Yl;function m0(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=yo(new Uint8Array([l%10]),s);break;default:s[i-f]=l%10}}return e[0]>0&&(s=yo(e,s)),s}function Vl(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=yo(e,n)),fn.push(n)}return fn[r]}function g0(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 Se(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=da.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Ol(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=g0(Vl(n),e),i="-";break;default:e=m0(e,Vl(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(i+=Ml.charAt(e[c]));return a===!1&&(i+=Ml.charAt(0)),i}};Yl=pn;pn.NAME="IntegerValueBlock";Object.defineProperty(Yl.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Jl,Bt=class r extends At{constructor(t={}){super(t,pn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return wo(),BigInt(this.valueBlock.toString())}static fromBigInt(t){wo();let e=BigInt(t),n=new hn,o=e.toString(16).replace(/^-/,""),s=new Uint8Array(z.Convert.FromHex(o));if(e<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${z.Convert.ToHex(a)}`)+e,u=z.BufferSourceConverter.toUint8Array(z.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()}`}};Jl=Bt;D.Integer=Jl;Bt.NAME="INTEGER";var Ql,Lo=class extends Bt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Ql=Lo;D.Enumerated=Ql;Lo.NAME="ENUMERATED";var mn=class extends Se(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=z.BufferSourceConverter.toUint8Array(t);if(!Be(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=ar(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){wo();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=$e(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=z.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 _o=class extends Nt{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.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 pa(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){wo();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}};_o.NAME="ObjectIdentifierValueBlock";var tu,Rr=class extends At{constructor(t={}){super(t,_o),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()}}};tu=Rr;D.ObjectIdentifier=tu;Rr.NAME="OBJECT IDENTIFIER";var gn=class extends Se(ve){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let o=z.BufferSourceConverter.toUint8Array(t);if(!Be(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=ar(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=$e(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=z.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};gn.NAME="relativeSidBlock";var Ro=class extends Nt{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 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,ne;n.push(s)}return pa(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}};Ro.NAME="RelativeObjectIdentifierValueBlock";var eu,Uo=class extends At{constructor(t={}){super(t,Ro),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()}}};eu=Uo;D.RelativeObjectIdentifier=eu;Uo.NAME="RelativeObjectIdentifier";var ru,Ee=class extends We{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};ru=Ee;D.Sequence=ru;Ee.NAME="SEQUENCE";var nu,Do=class extends We{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};nu=Do;D.Set=nu;Do.NAME="SET";var Po=class extends Se(Nt){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=Ur}toJSON(){return{...super.toJSON(),value:this.value}}};Po.NAME="StringValueBlock";var Oo=class extends Po{};Oo.NAME="SimpleStringValueBlock";var Ut=class extends vo{constructor({...t}={}){super(t,Oo)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,z.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}};Ut.NAME="SIMPLE STRING";var Ho=class extends Ut{fromBuffer(t){this.valueBlock.valueHexView=z.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=z.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=z.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(z.Convert.FromUtf8String(t)),this.valueBlock.value=t}};Ho.NAME="Utf8StringValueBlock";var ou,Ae=class extends Ho{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};ou=Ae;D.Utf8String=ou;Ae.NAME="UTF8String";var Mo=class extends Ut{fromBuffer(t){this.valueBlock.value=z.Convert.ToUtf16String(t),this.valueBlock.valueHexView=z.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(z.Convert.FromUtf16String(t))}};Mo.NAME="BmpStringValueBlock";var su,Vo=class extends Mo{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};su=Vo;D.BmpString=su;Vo.NAME="BMPString";var Fo=class extends Ut{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=$e(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 iu,Ko=class extends Fo{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};iu=Ko;D.UniversalString=iu;Ko.NAME="UniversalString";var au,$o=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};au=$o;D.NumericString=au;$o.NAME="NumericString";var cu,Wo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};cu=Wo;D.PrintableString=cu;Wo.NAME="PrintableString";var lu,qo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};lu=qo;D.TeletexString=lu;qo.NAME="TeletexString";var uu,zo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};uu=zo;D.VideotexString=uu;zo.NAME="VideotexString";var fu,Go=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};fu=Go;D.IA5String=fu;Go.NAME="IA5String";var hu,jo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};hu=jo;D.GraphicString=hu;jo.NAME="GraphicString";var du,yn=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};du=yn;D.VisibleString=du;yn.NAME="VisibleString";var pu,Zo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};pu=Zo;D.GeneralString=pu;Zo.NAME="GeneralString";var mu,Xo=class extends Ut{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};mu=Xo;D.CharacterString=mu;Xo.NAME="CharacterString";var gu,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,z.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]=Mt(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=Mt(this.month,2),e[2]=Mt(this.day,2),e[3]=Mt(this.hour,2),e[4]=Mt(this.minute,2),e[5]=Mt(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}}};gu=wn;D.UTCTime=gu;wn.NAME="UTCTime";var yu,Yo=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("+"),p="";if(d===-1&&(d=n.indexOf("-"),f=-1),d!==-1){if(p=n.substring(d+1),n=n.substring(0,d),p.length!==2&&p.length!==4)throw new Error("Wrong input string for conversion");let y=parseInt(p.substring(0,2),10);if(isNaN(y.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*y,p.length===4){if(y=parseInt(p.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(Mt(this.year,4)),e.push(Mt(this.month,2)),e.push(Mt(this.day,2)),e.push(Mt(this.hour,2)),e.push(Mt(this.minute,2)),e.push(Mt(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(Mt(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};yu=Yo;D.GeneralizedTime=yu;Yo.NAME="GeneralizedTime";var wu,Jo=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};wu=Jo;D.DATE=wu;Jo.NAME="DATE";var bu,Qo=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};bu=Qo;D.TimeOfDay=bu;Qo.NAME="TimeOfDay";var xu,ts=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};xu=ts;D.DateTime=xu;ts.NAME="DateTime";var vu,es=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};vu=es;D.Duration=vu;es.NAME="Duration";var Eu,rs=class extends Ae{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Eu=rs;D.TIME=Eu;rs.NAME="TIME";function X(r,t="utf8"){let e=fo[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"}},os=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Au={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new os("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 qe=Au;async function Bu(r){let t=await qe.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 w0(t);return{privateKey:e[0],publicKey:e[1]}}async function Su(r,t){let e=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await qe.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Iu(r,t,e){let n=await qe.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return qe.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function w0(r){if(r.privateKey==null||r.publicKey==null)throw new et("Private and public key are required");return Promise.all([qe.get().subtle.exportKey("jwk",r.privateKey),qe.get().subtle.exportKey("jwk",r.publicKey)])}function ya(r){if(r.kty!=="RSA")throw new et("invalid key type");if(r.n==null)throw new et("invalid key modulus");return Q(r.n,"base64url").length*8}var Dr=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 vt.createV1(114,this._multihash)}toString(){return nt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Rt(this.raw,t.raw)}verify(t,e){return Iu(this._key,e,t)}},vn=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:Rt(this.raw,t.raw)}sign(t){return Su(this._key,t)}};var ss=8192,wa=18;function Cu(r){let{result:t}=ga(r),e=t.valueBlock.value;return{n:le(e[1]),e:le(e[2]),d:le(e[3]),p:le(e[4]),q:le(e[5]),dp:le(e[6]),dq:le(e[7]),qi:le(e[8]),kty:"RSA",alg:"RS256"}}function b0(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new et("JWK was missing components");let e=new Ee({value:[new Bt({value:0}),Bt.fromBigInt(ue(Q(r.n,"base64url"))),Bt.fromBigInt(ue(Q(r.e,"base64url"))),Bt.fromBigInt(ue(Q(r.d,"base64url"))),Bt.fromBigInt(ue(Q(r.p,"base64url"))),Bt.fromBigInt(ue(Q(r.q,"base64url"))),Bt.fromBigInt(ue(Q(r.dp,"base64url"))),Bt.fromBigInt(ue(Q(r.dq,"base64url"))),Bt.fromBigInt(ue(Q(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function ku(r){let{result:t}=ga(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:le(e[0]),e:le(e[1])}}function ba(r){if(r.n==null||r.e==null)throw new et("JWK was missing components");let e=new Ee({value:[new Ee({value:[new Rr({value:"1.2.840.113549.1.1.1"}),new Lr]}),new _r({valueHex:new Ee({value:[Bt.fromBigInt(ue(Q(r.n,"base64url"))),Bt.fromBigInt(ue(Q(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function le(r){let t=r.valueBlock.valueHexView;for(;t[0]===0;)t=t.subarray(1);return X(t,"base64url")}function ue(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 Tu(r){let t=Cu(r);return Nu(t)}function xa(r){let t=ku(r);if(ya(t)>ss)throw new yr("Key size is too large");let e=ae(ie.encode({Type:wt.RSA,Data:r})),n=Ot(wa,e);return new Dr(t,n)}function Nu(r){if(ya(r)>ss)throw new et("Key size is too large");let t=_u(r),e=ae(ie.encode({Type:wt.RSA,Data:ba(t.publicKey)})),n=Ot(wa,e);return new vn(t.privateKey,new Dr(t.publicKey,n))}async function Lu(r){if(r>ss)throw new et("Key size is too large");let t=await Bu(r),e=ae(ie.encode({Type:wt.RSA,Data:ba(t.publicKey)})),n=Ot(wa,e);return new vn(t.privateKey,new Dr(t.publicKey,n))}function _u(r){if(r==null)throw new et("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var is=class extends Br{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Qr(t);let n=Ue(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()}},Pr=(r,t,e)=>new is(r,t).update(e).digest();Pr.create=(r,t)=>new is(r,t);function Ru(r){r.lowS!==void 0&&Zt("lowS",r.lowS),r.prehash!==void 0&&Zt("prehash",r.prehash)}function x0(r){let t=nn(r);Wt(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:E0}=ro,va=class extends Error{constructor(t=""){super(t)}},Ie={Err:va,_tlv:{encode:(r,t)=>{let{Err:e}=Ie;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=Qe(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Qe(o.length/2|128):"";return Qe(r)+s+o+t},decode(r,t){let{Err:e}=Ie,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}=Ie;if(r<Ce)throw new t("integer: negative integers are not allowed");let e=Qe(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}=Ie;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}=Ie,o=typeof r=="string"?E0(r):r;Ir(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}=Ie,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},Ce=BigInt(0),bt=BigInt(1),zb=BigInt(2),Uu=BigInt(3),Gb=BigInt(4);function A0(r){let t=x0(r),{Fp:e}=t,n=Me(t.n,t.nBitLength),o=t.toBytes||((g,h,w)=>{let x=h.toAffine();return be(Uint8Array.from([4]),e.toBytes(x.x),e.toBytes(x.y))}),s=t.fromBytes||(g=>{let h=g.subarray(1),w=e.fromBytes(h.subarray(0,e.BYTES)),x=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:w,y:x}});function i(g){let{a:h,b:w}=t,x=e.sqr(g),m=e.mul(x,g);return e.add(e.add(m,e.mul(g,h)),w)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return en(g,bt,t.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:w,wrapPrivateKey:x,n:m}=t;if(h&&typeof g!="bigint"){if(Oe(g)&&(g=ge(g)),typeof g!="string"||!h.includes(g.length))throw new Error("invalid private key");g=g.padStart(w*2,"0")}let I;try{I=typeof g=="bigint"?g:ye(ot("private key",g,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof g)}return x&&(I=Z(I,m)),Et("private key",I,bt,m),I}function l(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let u=er((g,h)=>{let{px:w,py:x,pz:m}=g;if(e.eql(m,e.ONE))return{x:w,y:x};let I=g.is0();h==null&&(h=I?e.ONE:e.inv(m));let L=e.mul(w,h),N=e.mul(x,h),B=e.mul(m,h);if(I)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=er(g=>{if(g.is0()){if(t.allowInfinityPoint&&!e.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:h,y:w}=g.toAffine();if(!e.isValid(h)||!e.isValid(w))throw new Error("bad point: x or y not FE");let x=e.sqr(w),m=i(h);if(!e.eql(x,m))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,w,x){if(this.px=h,this.py=w,this.pz=x,h==null||!e.isValid(h))throw new Error("x required");if(w==null||!e.isValid(w))throw new Error("y required");if(x==null||!e.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:w,y:x}=h||{};if(!h||!e.isValid(w)||!e.isValid(x))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let m=I=>e.eql(I,e.ZERO);return m(w)&&m(x)?d.ZERO:new d(w,x,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let w=e.invertBatch(h.map(x=>x.pz));return h.map((x,m)=>x.toAffine(w[m])).map(d.fromAffine)}static fromHex(h){let w=d.fromAffine(s(ot("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,w){return io(d,n,h,w)}_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:w,py:x,pz:m}=this,{px:I,py:L,pz:N}=h,B=e.eql(e.mul(w,N),e.mul(I,m)),k=e.eql(e.mul(x,N),e.mul(L,m));return B&&k}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:w}=t,x=e.mul(w,Uu),{px:m,py:I,pz:L}=this,N=e.ZERO,B=e.ZERO,k=e.ZERO,S=e.mul(m,m),M=e.mul(I,I),_=e.mul(L,L),H=e.mul(m,I);return H=e.add(H,H),k=e.mul(m,L),k=e.add(k,k),N=e.mul(h,k),B=e.mul(x,_),B=e.add(N,B),N=e.sub(M,B),B=e.add(M,B),B=e.mul(N,B),N=e.mul(H,N),k=e.mul(x,k),_=e.mul(h,_),H=e.sub(S,_),H=e.mul(h,H),H=e.add(H,k),k=e.add(S,S),S=e.add(k,S),S=e.add(S,_),S=e.mul(S,H),B=e.add(B,S),_=e.mul(I,L),_=e.add(_,_),S=e.mul(_,H),N=e.sub(N,S),k=e.mul(_,M),k=e.add(k,k),k=e.add(k,k),new d(N,B,k)}add(h){l(h);let{px:w,py:x,pz:m}=this,{px:I,py:L,pz:N}=h,B=e.ZERO,k=e.ZERO,S=e.ZERO,M=t.a,_=e.mul(t.b,Uu),H=e.mul(w,I),V=e.mul(x,L),C=e.mul(m,N),T=e.add(w,x),v=e.add(I,L);T=e.mul(T,v),v=e.add(H,V),T=e.sub(T,v),v=e.add(w,m);let b=e.add(I,N);return v=e.mul(v,b),b=e.add(H,C),v=e.sub(v,b),b=e.add(x,m),B=e.add(L,N),b=e.mul(b,B),B=e.add(V,C),b=e.sub(b,B),S=e.mul(M,v),B=e.mul(_,C),S=e.add(B,S),B=e.sub(V,S),S=e.add(V,S),k=e.mul(B,S),V=e.add(H,H),V=e.add(V,H),C=e.mul(M,C),v=e.mul(_,v),V=e.add(V,C),C=e.sub(H,C),C=e.mul(M,C),v=e.add(v,C),H=e.mul(V,v),k=e.add(k,H),H=e.mul(b,v),B=e.mul(T,B),B=e.sub(B,H),H=e.mul(T,V),S=e.mul(b,S),S=e.add(S,H),new d(B,k,S)}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:w,n:x}=t;Et("scalar",h,Ce,x);let m=d.ZERO;if(h===Ce)return m;if(this.is0()||h===bt)return this;if(!w||y.hasPrecomputes(this))return y.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:I,k1:L,k2neg:N,k2:B}=w.splitScalar(h),k=m,S=m,M=this;for(;L>Ce||B>Ce;)L&bt&&(k=k.add(M)),B&bt&&(S=S.add(M)),M=M.double(),L>>=bt,B>>=bt;return I&&(k=k.negate()),N&&(S=S.negate()),S=new d(e.mul(S.px,w.beta),S.py,S.pz),k.add(S)}multiply(h){let{endo:w,n:x}=t;Et("scalar",h,bt,x);let m,I;if(w){let{k1neg:L,k1:N,k2neg:B,k2:k}=w.splitScalar(h),{p:S,f:M}=this.wNAF(N),{p:_,f:H}=this.wNAF(k);S=y.constTimeNegate(L,S),_=y.constTimeNegate(B,_),_=new d(e.mul(_.px,w.beta),_.py,_.pz),m=S.add(_),I=M.add(H)}else{let{p:L,f:N}=this.wNAF(h);m=L,I=N}return d.normalizeZ([m,I])[0]}multiplyAndAddUnsafe(h,w,x){let m=d.BASE,I=(N,B)=>B===Ce||B===bt||!N.equals(m)?N.multiplyUnsafe(B):N.multiply(B),L=I(this,w).add(I(h,x));return L.is0()?void 0:L}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:w}=t;if(h===bt)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:w}=t;return h===bt?this:w?w(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),ge(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let p=t.nBitLength,y=so(d,t.endo?Math.ceil(p/2):p);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function B0(r){let t=nn(r);return Wt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Du(r){let t=B0(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 no(C,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=A0({...t,toBytes(C,T,v){let b=T.toAffine(),A=e.toBytes(b.x),E=be;return Zt("isCompressed",v),v?E(Uint8Array.from([T.hasEvenY()?2:3]),A):E(Uint8Array.from([4]),A,e.toBytes(b.y))},fromBytes(C){let T=C.length,v=C[0],b=C.subarray(1);if(T===o&&(v===2||v===3)){let A=ye(b);if(!en(A,bt,e.ORDER))throw new Error("Point is not on curve");let E=u(A),R;try{R=e.sqrt(E)}catch(K){let F=K instanceof Error?": "+K.message:"";throw new Error("Point is not on curve"+F)}let U=(R&bt)===bt;return(v&1)===1!==U&&(R=e.neg(R)),{x:A,y:R}}else if(T===s&&v===4){let A=e.fromBytes(b.subarray(0,e.BYTES)),E=e.fromBytes(b.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 "+T)}}}),d=C=>ge(He(C,t.nByteLength));function p(C){let T=n>>bt;return C>T}function y(C){return p(C)?i(-C):C}let g=(C,T,v)=>ye(C.slice(T,v));class h{constructor(T,v,b){this.r=T,this.s=v,this.recovery=b,this.assertValidity()}static fromCompact(T){let v=t.nByteLength;return T=ot("compactSignature",T,v*2),new h(g(T,0,v),g(T,v,2*v))}static fromDER(T){let{r:v,s:b}=Ie.toSig(ot("DER",T));return new h(v,b)}assertValidity(){Et("r",this.r,bt,n),Et("s",this.s,bt,n)}addRecoveryBit(T){return new h(this.r,this.s,T)}recoverPublicKey(T){let{r:v,s:b,recovery:A}=this,E=N(ot("msgHash",T));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let R=A===2||A===3?v+t.n:v;if(R>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let U=A&1?"03":"02",O=c.fromHex(U+d(R)),K=a(R),F=i(-E*K),W=i(b*K),j=c.BASE.multiplyAndAddUnsafe(O,F,W);if(!j)throw new Error("point at infinify");return j.assertValidity(),j}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return tr(this.toDERHex())}toDERHex(){return Ie.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return tr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let w={isValidPrivateKey(C){try{return l(C),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let C=Ii(t.n);return ll(t.randomBytes(C),t.n)},precompute(C=8,T=c.BASE){return T._setWindowSize(C),T.multiply(BigInt(3)),T}};function x(C,T=!0){return c.fromPrivateKey(C).toRawBytes(T)}function m(C){let T=Oe(C),v=typeof C=="string",b=(T||v)&&C.length;return T?b===o||b===s:v?b===2*o||b===2*s:C instanceof c}function I(C,T,v=!0){if(m(C))throw new Error("first arg must be private key");if(!m(T))throw new Error("second arg must be public key");return c.fromHex(T).multiply(l(C)).toRawBytes(v)}let L=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let T=ye(C),v=C.length*8-t.nBitLength;return v>0?T>>BigInt(v):T},N=t.bits2int_modN||function(C){return i(L(C))},B=rn(t.nBitLength);function k(C){return Et("num < 2^"+t.nBitLength,C,Ce,B),He(C,t.nByteLength)}function S(C,T,v=M){if(["recovered","canonical"].some(it=>it in v))throw new Error("sign() legacy options not supported");let{hash:b,randomBytes:A}=t,{lowS:E,prehash:R,extraEntropy:U}=v;E==null&&(E=!0),C=ot("msgHash",C),Ru(v),R&&(C=ot("prehashed msgHash",b(C)));let O=N(C),K=l(T),F=[k(K),k(O)];if(U!=null&&U!==!1){let it=U===!0?A(e.BYTES):U;F.push(ot("extraEntropy",it))}let W=be(...F),j=O;function st(it){let ut=L(it);if(!f(ut))return;let It=a(ut),Pt=c.BASE.multiply(ut).toAffine(),_t=i(Pt.x);if(_t===Ce)return;let oe=i(It*i(j+_t*K));if(oe===Ce)return;let fe=(Pt.x===_t?0:2)|Number(Pt.y&bt),Gr=oe;return E&&p(oe)&&(Gr=y(oe),fe^=1),new h(_t,Gr,fe)}return{seed:W,k2sig:st}}let M={lowS:t.lowS,prehash:!1},_={lowS:t.lowS,prehash:!1};function H(C,T,v=M){let{seed:b,k2sig:A}=S(C,T,v),E=t;return vi(E.hash.outputLen,E.nByteLength,E.hmac)(b,A)}c.BASE._setWindowSize(8);function V(C,T,v,b=_){let A=C;T=ot("msgHash",T),v=ot("publicKey",v);let{lowS:E,prehash:R,format:U}=b;if(Ru(b),"strict"in b)throw new Error("options.strict was renamed to lowS");if(U!==void 0&&U!=="compact"&&U!=="der")throw new Error("format must be compact or der");let O=typeof A=="string"||Oe(A),K=!O&&!U&&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{U!=="compact"&&(F=h.fromDER(A))}catch(fe){if(!(fe instanceof Ie.Err))throw fe}!F&&U!=="der"&&(F=h.fromCompact(A))}W=c.fromHex(v)}catch{return!1}if(!F||E&&F.hasHighS())return!1;R&&(T=t.hash(T));let{r:j,s:st}=F,it=N(T),ut=a(st),It=i(it*ut),Pt=i(j*ut),_t=c.BASE.multiplyAndAddUnsafe(W,It,Pt)?.toAffine();return _t?i(_t.x)===j:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:I,sign:H,verify:V,ProjectivePoint:c,Signature:h,utils:w}}function S0(r){return{hash:r,hmac:(t,...e)=>Pr(r,t,pi(...e)),randomBytes:tn}}function Pu(r,t){let e=n=>Du({...r,...S0(n)});return{...e(t),create:e}}var Mu=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Ou=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),I0=BigInt(1),Ea=BigInt(2),Hu=(r,t)=>(r+t/Ea)/t;function C0(r){let t=Mu,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,p=at(d,Ea,t)*l%t,y=at(p,o,t)*p%t,g=at(y,s,t)*y%t,h=at(g,a,t)*g%t,w=at(h,c,t)*h%t,x=at(w,a,t)*g%t,m=at(x,e,t)*u%t,I=at(m,i,t)*y%t,L=at(I,n,t)*l%t,N=at(L,Ea,t);if(!Aa.eql(Aa.sqr(N),r))throw new Error("Cannot find square root");return N}var Aa=Me(Mu,void 0,void 0,{sqrt:C0}),cr=Pu({a:BigInt(0),b:BigInt(7),Fp:Aa,n:Ou,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Ou,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-I0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=Hu(s*r,t),c=Hu(-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}}}},ae),rx=BigInt(0);var nx=cr.ProjectivePoint;function xt(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 Vu(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Fu(r,t,e){let n=cn.digest(e instanceof Uint8Array?e:e.subarray());if(Vu(n))return n.then(({digest:o})=>cr.verify(t,o,r)).catch(o=>{throw new bn(String(o))});try{return cr.verify(t,n.digest,r)}catch(o){throw new bn(String(o))}}var as=class{type="secp256k1";raw;_key;constructor(t){this._key=$u(t),this.raw=Ku(this._key)}toMultihash(){return pe.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:Rt(this.raw,t.raw)}verify(t,e){return Fu(this._key,e,t)}};function Ba(r){return new as(r)}function Ku(r){return cr.ProjectivePoint.fromHex(r).toRawBytes(!0)}function $u(r){try{return cr.ProjectivePoint.fromHex(r),r}catch(t){throw new yr(String(t))}}function En(r){let{Type:t,Data:e}=ie.decode(r),n=e??new Uint8Array;switch(t){case wt.RSA:return xa(n);case wt.Ed25519:return Ri(n);case wt.secp256k1:return Ba(n);default:throw new Xe}}function Wu(r){let{Type:t,Data:e}=ie.decode(r.digest),n=e??new Uint8Array;switch(t){case wt.Ed25519:return Ri(n);case wt.secp256k1:return Ba(n);default:throw new Xe}}function kr(r){return ie.encode({Type:wt[r.type],Data:r.raw})}var qu=Symbol.for("nodejs.util.inspect.custom"),T0=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()})`}[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(T0,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Rt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Rt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[qu](){return`PeerId(${this.toString()})`}},Bn=class extends An{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Sn=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}},N0=2336,cs=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=pe.digest(Q(this.url))}[qu](){return`PeerId(${this.url})`}[ri]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return vt.createV1(N0,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=Re(nt.decode(`z${r}`));else{if(t==null)throw new et('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Re(t.decode(r))}return L0(e)}function Sa(r){if(r.type==="Ed25519")return new Sn({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 Bn({multihash:r.toCID().multihash,publicKey:r});throw new Xe}function L0(r){if(R0(r))return new Bn({multihash:r});if(_0(r))try{let t=Wu(r);if(t.type==="Ed25519")return new Sn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new In({multihash:r,publicKey:t})}catch{let e=X(r.digest);return new cs(new URL(e))}throw new zn("Supplied PeerID Multihash is invalid")}function _0(r){return r.code===pe.code}function R0(r){return r.code===cn.code}var ls=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,U0=15,Hr=new ls;function Ia(r){if(!(r.length>U0))return Hr.new(r).parseWith(()=>Hr.readIPv4Addr())}function Ca(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>zu))return Hr.new(r).parseWith(()=>Hr.readIPv6Addr())}function us(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>zu)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 w1=parseInt("0xFFFF",16),b1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function fs(r){return!!Ia(r)}function hs(r){return!!Ca(r)}function ds(r){return!!us(r)}var Zu=fs,M0=hs,ka=function(r){let t=0;if(r=r.toString().trim(),Zu(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(M0(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Zu(e[n]),i;s&&(i=ka(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")},Xu=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 Mr={},Ta={},F0=[[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"]];F0.forEach(r=>{let t=K0(...r);Ta[t.code]=t,Mr[t.name]=t});function K0(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function tt(r){if(typeof r=="number"){if(Ta[r]!=null)return Ta[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Mr[r]!=null)return Mr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var r2=tt("ip4"),n2=tt("ip6"),o2=tt("ipcidr");function Ra(r,t){switch(tt(r).code){case 4:case 41:return W0(t);case 42:return _a(t);case 43:return X(t,"base10");case 6:case 273:case 33:case 132:return Qu(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return _a(t);case 421:return j0(t);case 444:return Ju(t);case 445:return Ju(t);case 466:return G0(t);case 481:return globalThis.encodeURIComponent(_a(t));default:return X(t,"base16")}}function Ua(r,t){switch(tt(r).code){case 4:return Yu(t);case 41:return Yu(t);case 42:return La(t);case 43:return Q(t,"base10");case 6:case 273:case 33:case 132:return Da(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return La(t);case 421:return q0(t);case 444:return Z0(t);case 445:return X0(t);case 466:return z0(t);case 481:return La(globalThis.decodeURIComponent(t));default:return Q(t,"base16")}}var Na=Object.values(or).map(r=>r.decoder),$0=function(){let r=Na[0].or(Na[1]);return Na.slice(2).forEach(t=>r=r.or(t)),r}();function Yu(r){if(!ds(r))throw new Error("invalid ip address");return ka(r)}function W0(r){let t=Xu(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!ds(t))throw new Error("invalid ip address");return t}function Da(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Qu(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function La(r){let t=Q(r),e=Uint8Array.from(se(t.length));return xt([e,t],e.length+t.length)}function _a(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=Re(nt.decode(`z${r}`)).bytes:t=vt.parse(r).multihash.bytes;let e=Uint8Array.from(se(t.length));return xt([e,t],e.length+t.length)}function z0(r){let t=$0.decode(r),e=Uint8Array.from(se(t.length));return xt([e,t],e.length+t.length)}function G0(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 j0(r){let t=Jt(r),e=r.slice(ct(t));if(e.length!==t)throw new Error("inconsistent lengths");return X(e,"base58btc")}function Z0(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=de.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=Da(n);return xt([e,o],e.length+o.length)}function X0(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=de.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=Da(n);return xt([e,o],e.length+o.length)}function Ju(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=X(t,"base32"),o=Qu(e);return`${n}:${o}`}function tf(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 ps("invalid address: "+r);if(a.path===!0){n=Pa(o.slice(s).join("/")),t.push([a.code,Ua(a.code,n)]),e.push([a.code,n]);break}let c=Ua(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Ra(a.code,c)])}return{string:ef(e),bytes:Ha(t),tuples:t,stringTuples:e,path:n}}function Oa(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=Jt(r,o),i=ct(s),a=tt(s),c=Y0(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let l=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw new ps("Invalid address Uint8Array: "+X(r,"base16"));t.push([s,l]);let u=Ra(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:ef(e),tuples:t,stringTuples:e,path:n}}function ef(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 Ha(r){return xt(r.map(t=>{let e=tt(t[0]),n=Uint8Array.from(se(e.code));return t.length>1&&t[1]!=null&&(n=xt([n,t[1]])),n}))}function Y0(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 ps=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var J0=Symbol.for("nodejs.util.inspect.custom"),Va=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Q0=[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"}},ms=class r{bytes;#t;#e;#r;#n;[Va]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Oa(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=tf(t)}else if(nf(t))e=Oa(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[p,y]of this.stringTuples())p===f.code&&(s=`%${y??""}`),Q0.includes(p)&&(e=i.name==="tcp"?"tcp":"udp",o=443,n=`${y??""}${s}`,t=p===u.code?6:4),(p===i.code||p===a.code)&&(e=tt(p).name==="tcp"?"tcp":"udp",o=parseInt(y??"")),(p===c.code||p===l.code)&&(e=tt(p).name==="tcp"?"tcp":"udp",n=`${y??""}${s}`,t=p===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(Ha(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Mr.p2p.code&&t.push([n,o]),n===Mr["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 Rt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=rf.get(e.name);if(n==null)throw new Ma(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>ze(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)}[J0](){return`Multiaddr(${this.#t})`}};var rf=new Map;function nf(r){return!!r?.[Va]}function ze(r){return new ms(r)}var tm=r=>r.toString().split("/").slice(1),Vr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),q=r=>({match:t=>Vr(e=>e===r).match(t),pattern:r}),lr=()=>({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{nt.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{Zi.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})`}),Lt=(...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(", ")})`}),G=(...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=tm(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 ys=G(q("dns4"),lr()),ws=G(q("dns6"),lr()),bs=G(q("dnsaddr"),lr()),Ka=G(q("dns"),lr()),R2=lt(ys,Y(rt())),U2=lt(ws,Y(rt())),D2=lt(bs,Y(rt())),P2=lt(Lt(Ka,bs,ys,ws),Y(rt())),of=G(q("ip4"),Vr(fs)),sf=G(q("ip6"),Vr(hs)),$a=Lt(of,sf),ke=Lt($a,Ka,ys,ws,bs),O2=lt(Lt($a,G(Lt(Ka,bs,ys,ws),Y(rt())))),H2=lt(of),M2=lt(sf),V2=lt($a),Wa=G(ke,q("tcp"),Cn()),Tn=G(ke,q("udp"),Cn()),F2=lt(G(Wa,Y(rt()))),K2=lt(Tn),qa=G(Tn,q("quic"),Y(rt())),xs=G(Tn,q("quic-v1"),Y(rt())),em=Lt(qa,xs),$2=lt(qa),W2=lt(xs),Fa=Lt(ke,Wa,Tn,qa,xs),af=Lt(G(Fa,q("ws"),Y(rt()))),q2=lt(af),cf=Lt(G(Fa,q("wss"),Y(rt())),G(Fa,q("tls"),Y(G(q("sni"),lr())),q("ws"),Y(rt()))),z2=lt(cf),lf=G(Tn,q("webrtc-direct"),Y(kn()),Y(kn()),Y(rt())),uf=lt(lf),ff=G(xs,q("webtransport"),Y(kn()),Y(kn()),Y(rt())),G2=lt(ff),gs=Lt(af,cf,G(Wa,Y(rt())),G(em,Y(rt())),G(ke,Y(rt())),lf,ff,rt()),hf=lt(gs),rm=G(gs,q("p2p-circuit"),rt()),j2=lt(rm),nm=Lt(G(gs,q("p2p-circuit"),q("webrtc"),Y(rt())),G(gs,q("webrtc"),Y(rt())),G(q("webrtc"),Y(rt()))),df=lt(nm),om=Lt(G(ke,q("tcp"),Cn(),q("http"),Y(rt())),G(ke,q("http"),Y(rt()))),Z2=lt(om),sm=Lt(G(ke,q("tcp"),Lt(G(q("443"),q("http")),G(Cn(),q("https"))),Y(rt())),G(ke,q("tls"),q("http"),Y(rt())),G(ke,q("https"),Y(rt()))),X2=lt(sm),im=Lt(G(q("memory"),lr(),Y(rt()))),Y2=lt(im);var pf=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))},am=function(){function r(t,e,n){this.name=t,this.version=e,this.os=n,this.type="browser"}return r}();var cm=function(){function r(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return r}();var lm=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 um=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var fm=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var hm=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,dm=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,mf=3,pm=[["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",hm]],gf=[["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 wf(r){return r?yf(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new fm:typeof navigator<"u"?yf(navigator.userAgent):ym()}function mm(r){return r!==""&&pm.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 yf(r){var t=mm(r);if(!t)return null;var e=t[0],n=t[1];if(e==="searchbot")return new um;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<mf&&(o=pf(pf([],o,!0),wm(mf-o.length),!0)):o=[];var s=o.join("."),i=gm(r),a=dm.exec(r);return a&&a[1]?new lm(e,s,i,a[1]):new am(e,s,i)}function gm(r){for(var t=0,e=gf.length;t<e;t++){var n=gf[t],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function ym(){var r=typeof process<"u"&&process.version;return r?new cm(process.version.slice(1)):null}function wm(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 za=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Ga=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},bf=r=>globalThis.DOMException===void 0?new Ga(r):new DOMException(r),xf=r=>{let t=r.reason===void 0?bf("This operation was aborted."):r.reason;return t instanceof Error?t:bf(t)};function ur(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:p}=t;p.aborted&&f(xf(p)),a=()=>{f(xf(p))},p.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new za;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(p){f(p)}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(p){f(p)}})()}).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 vf=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"];var Ef=wf(),Nn=Ef!=null&&Ef.name==="firefox",vs=async function*(){},Es=async r=>{},bm=30*1e3;function Af(r,t,e=bm,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 ur(o.promise,{milliseconds:e})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function Ln(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??vf.map(t=>({urls:[t]})),r}var fr=class{log;peerConnection;remoteAddr;timeline;metrics;source=vs();sink=Es;constructor(t,e){this.log=t.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=e.remoteAddr,this.timeline=e.timeline,this.peerConnection=e.peerConnection;let n=this.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",this.peerConnection.connectionState,"initial state",n),(this.peerConnection.connectionState==="disconnected"||this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.timeline.close=Date.now())}}async close(t){this.log.trace("closing connection"),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({close:!0})}abort(t){this.log.error("closing connection due to error",t),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({abort:!0})}};var As=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}},Fr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new As(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 As(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 ja=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Ge(r={}){return xm(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 xm(r,t){t=t??{};let e=t.onEnd,n=new Fr,o,s,i,a=pt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,w)=>{s=x=>{s=null,n.push(x);try{h(r(n))}catch(m){w(m)}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 Fr,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})),p=()=>(n=new Fr,d(),{done:!0}),y=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:y,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let w=h?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let x,m;w!=null&&(x=new Promise((I,L)=>{m=()=>{L(new ja)},w.addEventListener("abort",m)}));try{await Promise.race([a.promise,x])}finally{m!=null&&w!=null&&w?.removeEventListener("abort",m)}}},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 Bs=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 Te(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new Bs(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new Bs(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 Sf=Symbol.for("@achingbrain/uint8arraylist");function Bf(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 Ss(r){return!!r?.[Sf]}var ht=class r{bufs;length;[Sf]=!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(Ss(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(Ss(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=Bf(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Bf(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(Ss(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 xt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:xt(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(!Ss(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 p=this.get(f+d);if(n[d]!==p){u=Math.max(1,d-a[p]);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(!Rt(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 If(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 Cf(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function kf(r,t){let e=If(r).return?.();Cf(e)&&e.catch(n=>{t.error("could not cause iterator to return",n)})}var vm=5e3;function Za(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Is=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=Ge({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 Ze(`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);Za(o)&&await o}let n=()=>{kf(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);Za(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 Te(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 Te(this.sink([]),t.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await Te(this.sendingData.promise,t.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await Te(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();Za(e)&&e.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(t),this.onAbort?.(t)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let t=new qn("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(t),this.onReset?.()}_closeSinkAndSource(t){this._closeSink(t),this._closeSource(t)}_closeSink(t){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(t)}_closeSource(t){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(t))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(t){this.streamSource.push(t)}sourceReadableLength(){return this.streamSource.readableLength}};function Cs(r){return r[Symbol.asyncIterator]!=null}var ks=r=>{let t=ct(r),e=yt(t);return se(r,e),ks.bytes=t,e};ks.bytes=0;function _n(r,t){t=t??{};let e=t.lengthEncoder??ks;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)}()}_n.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??ks;return new ht(e(r.byteLength),r)};var Ts=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ns=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ls=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Rn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Em=8,Am=1024*1024*4,hr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(hr||(hr={}));var Xa=r=>{let t=Jt(r);return Xa.bytes=ct(t),t};Xa.bytes=0;function dr(r,t){let e=new ht,n=hr.LENGTH,o=-1,s=t?.lengthDecoder??Xa,i=t?.maxLengthLength??Em,a=t?.maxDataLength??Am;function*c(){for(;e.byteLength>0;){if(n===hr.LENGTH)try{if(o=s(e),o<0)throw new Ts("Invalid message length");if(o>a)throw new Ns("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=hr.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Ls("Message length length too long");break}throw l}if(n===hr.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=hr.LENGTH}}}return Cs(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Rn("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Rn("Unexpected end of input")}()}dr.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 dr(n,{...t??{},onLength:s=>{e=s}})};var Sm=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function Im(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:u}=Sm(r),f=(...p)=>{let y=e.multiArgs?p:p[0];e.filter&&!e.filter(y)||(c.push(y),e.count===c.length&&(n(),s(c)))},d=p=>{n(),i(p)};n=()=>{for(let p of a)u(p,f);for(let p of e.rejectionEvents)u(p,d)};for(let p of a)l(p,f);for(let p of e.rejectionEvents)l(p,d);e.signal&&e.signal.addEventListener("abort",()=>{d(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=ur(o,{milliseconds:e.timeout});return s.cancel=n,s}return o}function Ya(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=Im(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}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=()=>ir(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 Cm=2*1024*1024,km=30*1e3,_s=16*1024;function Tm(r=_s){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 Nm=Tm(),Lm=5e3,_m=5e3,Ja=class extends Is{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;constructor(t){let e=t.onEnd;switch(t.onEnd=o=>{this.log.trace("readable and writeable ends closed",this.status),Promise.resolve(async()=>{if(!(this.timeline.abort!=null||this.timeline.reset!==null))try{await ur(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(s){this.log.error("error receiving FIN_ACK",s)}}).then(()=>{this.incomingData.end(),e?.(o)}).catch(s=>{this.log.error("error ending stream",s)})},super(t),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=Ge(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??km,this.maxBufferedAmount=t.maxBufferedAmount??Cm,this.maxMessageSize=(t.maxMessageSize??_s)-Nm,this.receiveFinAck=pt(),this.finAckTimeout=t.closeTimeout??Lm,this.openTimeout=t.openTimeout??_m,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 Ze("Unknown datachannel state")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime()},this.channel.onclose=o=>{this.receiveFinAck.resolve(),this.close().catch(s=>{this.log.error("error closing stream after channel closed",s)})},this.channel.onerror=o=>{let s=o.error;this.abort(s)},this.channel.onmessage=async o=>{let{data:s}=o;s===null||s.byteLength===0||this.incomingData.push(new Uint8Array(s,0,s.byteLength))};let n=this;Promise.resolve().then(async()=>{for await(let o of dr(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(e&&this.channel.bufferedAmount>this.maxBufferedAmount)try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await Ya(this.channel,"bufferedamountlow",{timeout:this.bufferedAmountLowEventTimeout})}catch(n){throw n instanceof jr?new jr(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`):n}if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new Ze(`Invalid datachannel state - ${this.channel.readyState}`);this.channel.readyState!=="open"&&(this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await Ya(this.channel,"open",{timeout:this.openTimeout}),this.log('channel state is now "%s", sending data',this.channel.readyState)),this.channel.send(t.subarray())}async sendData(t){for(t=t.sublist();t.byteLength>0;){let e=Math.min(t.byteLength,this.maxMessageSize),n=t.subarray(0,e),o=Dt.encode({message:n}),s=_n.single(o);await this._sendMessage(s),t.consume(e)}}async sendReset(){try{await this._sendFlag(Dt.Flag.RESET)}catch(t){this.log.error("failed to send reset - %e",t)}}async sendCloseWrite(t){if(await this._sendFlag(Dt.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await Te(this.receiveFinAck.promise,t?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorName:"FinAckNotReceivedError"})}catch(n){this.log.error("failed to await FIN_ACK",n)}}else this.log.trace("sending FIN failed, not awaiting FIN_ACK");this.receiveFinAck.resolve()}async sendCloseRead(){await this._sendFlag(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=_n.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 Ja({id:e==="inbound"?`i${t.id}`:`r${t.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${e}:${t.id}`),...r})}var Tf="/webrtc",je=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??Tf,this.dataChannelOptions=e.dataChannelOptions??{},this.log=t.logger.forComponent("libp2p:webrtc:datachannelmuxerfactory"),this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace('incoming early datachannel with channel id %d and label "%s"',n.id),n.label==="init"){this.log.trace("closing early init channel"),n.close();return}let o={},s=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 Qa(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},Qa=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??Tf,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),Af(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=vs();sink=Es;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 pr=globalThis.RTCPeerConnection,Rs=globalThis.RTCSessionDescription,Nf=globalThis.RTCIceCandidate;var tc=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 Te(this.readNext.promise,e?.signal,e)}};function Lf(){return new tc}var Us=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var ec=class extends Error{code;constructor(t,e){super(t),this.code=e}},rc=class extends ec{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function _f(r,t){let e=Lf();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 rc("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 Us("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 Ds=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ps=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Os=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Un(r,t={}){let e=_f(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=ct(t.maxDataLength));let n=t?.lengthDecoder??Jt,o=t?.lengthEncoder??se;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 Ds("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Os("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 Hs(r,t){let e=Un(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 mr=class extends Error{constructor(t){super(`WebRTC transport error: ${t}`),this.name="WebRTCTransportError"}},zt=class extends mr{constructor(t="SDP handshake failed"){super(t),this.name="SDPHandshakeFailedError"}};var Dn=class extends mr{constructor(t,e){super(`[stream: ${t}] data channel error: ${e}`),this.name="WebRTC/DataChannelError"}};var Pn=class extends mr{constructor(t,e){super(`Invalid fingerprint "${t}" within ${e}`),this.name="WebRTC/InvalidFingerprintError"}};var Ms=class extends mr{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},Vs=class extends mr{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 Vt;(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=()=>ir(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)})(Vt||(Vt={}));var Fs=async(r,t,e)=>{try{let n=pt();for(Rm(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!==Vt.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 Nf(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 Rm(r,t){r[Nn?"oniceconnectionstatechange":"onconnectionstatechange"]=e=>{switch(Ks(r)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new Wn("RTCPeerConnection was closed"));break;default:break}}}async function Rf({rtcConfiguration:r,dataChannel:t,signal:e,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=Uf(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",u);let f=u.getPeerId();if(f==null)throw new et("Relay peer was missing");let d=s.getConnections(Or(f)),p,y=!1;d.length===0?(l?.(new $t("webrtc:dial-relay")),p=await i.dial(u,{signal:e,onProgress:l}),y=!0):(l?.(new $t("webrtc:reuse-relay-connection")),p=d[0]);try{l?.(new $t("webrtc:open-signaling-stream"));let g=await p.newStream($s,{signal:e,runOnLimitedConnection:!0}),h=Hs(g).pb(Vt),w=new pr(r),x=new je({logger:c},{peerConnection:w,dataChannelOptions:t});try{let m=w.createDataChannel("init");w.onicecandidate=({candidate:B})=>{let k=JSON.stringify(B?.toJSON()??null);a.trace("initiator sending ICE candidate %o",B),h.write({type:Vt.Type.ICE_CANDIDATE,data:k},{signal:e}).catch(S=>{a.error("error sending ICE candidate",S)})},w.onicecandidateerror=B=>{a.error("initiator ICE candidate error",B)};let I=await w.createOffer().catch(B=>{throw a.error("could not execute createOffer",B),new zt("Failed to set createOffer")});a.trace("initiator send SDP offer %s",I.sdp),l?.(new $t("webrtc:send-sdp-offer")),await h.write({type:Vt.Type.SDP_OFFER,data:I.sdp},{signal:e}),await w.setLocalDescription(I).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!==Vt.Type.SDP_ANSWER)throw new zt("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",L.data);let N=new Rs({type:"answer",sdp:L.data});return await w.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 Fs(w,h,{direction:"initiator",signal:e,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),m.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:w,muxerFactory:x}}catch(m){throw a.error("outgoing signaling error",m),w.close(),g.abort(m),m}finally{w.onicecandidate=null,w.onicecandidateerror=null}}finally{if(y)try{await p.close({signal:e})}catch(g){p.abort(g)}}}var Um=lt(hf.matchers[0],q("p2p-circuit")),Ws=class extends jn{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=>Um.exactMatch(e)).map(e=>e.encapsulate("/webrtc"))).flat()}async close(){this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function Df({peerConnection:r,stream:t,signal:e,connection:n,log:o}){o.trace("new inbound signaling stream");let s=Hs(t).pb(Vt);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:Vt.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!==Vt.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 Rs({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:Vt.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 Fs(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=ze(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return o.trace("recipient connected to remote address %s",i),{remoteAddress:i}}var Dm="/webrtc",Pm="/p2p-circuit",$s="/webrtc-signaling/0.0.1",Om=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"})})}[Kn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[wr]=["@libp2p/transport"];[Pc]=["@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(df.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 Rf({rtcConfiguration:await Ln(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 fr(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??Om),o=new pr(await Ln(this.init.rtcConfiguration)),s=new je(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await Df({peerConnection:o,connection:t,stream:e,signal:n,log:this.log});await e.close({signal:n});let a=new fr(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 Uf(r){let t=r.toString().split(Dm+"/");if(t.length!==2)throw new et("webrtc protocol was not present in multiaddr");if(!t[0].includes(Pm))throw new et("p2p-circuit protocol was not present in multiaddr");let e=ze(t[0]),o=ze("/"+t[1]).getPeerId();if(o==null)throw new et("destination peer id was missing");let s=e.protos().pop();if(s===void 0)throw new et("invalid multiaddr");return s.name!=="p2p"&&(e=e.encapsulate(`/p2p/${o}`)),{baseAddr:e,peerId:Or(o)}}function nc(){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 Pf(){let r=nc(),t=nc();return[{source:r.source,sink:t.sink},{source:t.source,sink:r.sink}]}function Hm(r){return r[Symbol.asyncIterator]!=null}function Mm(...r){let t=[];for(let e of r)Hm(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=Ge({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 Of=Mm;function Hf(r,...t){if(r==null)throw new Error("Empty pipeline");if(oc(r)){let n=r;r=()=>n.source}else if(Vf(r)||Mf(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&oc(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++)oc(e[n])&&(e[n]=Fm(e[n]));return Vm(...e)}var Vm=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Mf=r=>r?.[Symbol.asyncIterator]!=null,Vf=r=>r?.[Symbol.iterator]!=null,oc=r=>r==null?!1:r.sink!=null&&r.source!=null,Fm=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Ge({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(Mf(s))o=async function*(){yield*s,n.end()};else if(Vf(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Of(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 sc(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function ic(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Ft(r,...t){if(!ic(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 ac(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 Ff(r,t){Ft(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var Ne=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),Kf=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Km=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Km)throw new Error("Non little-endian hardware is not supported");function $m(r){if(typeof r!="string")throw new Error(`string expected, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Gs(r){if(typeof r=="string")r=$m(r);else if(ic(r))r=js(r);else throw new Error(`Uint8Array expected, got ${typeof r}`);return r}function $f(r,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(r,t)}function Wf(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 cc=(r,t)=>(Object.assign(t,r),t);function lc(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 js(r){return Uint8Array.from(r)}function Le(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}var zf=r=>Uint8Array.from(r.split("").map(t=>t.charCodeAt(0))),Wm=zf("expand 16-byte k"),qm=zf("expand 32-byte k"),zm=Ne(Wm),Gf=Ne(qm),LA=Gf.slice();function P(r,t){return r<<t|r>>>32-t}function uc(r){return r.byteOffset%4===0}var Zs=64,Gm=16,jf=2**32-1,qf=new Uint32Array;function jm(r,t,e,n,o,s,i,a){let c=o.length,l=new Uint8Array(Zs),u=Ne(l),f=uc(o)&&uc(s),d=f?Ne(o):qf,p=f?Ne(s):qf;for(let y=0;y<c;i++){if(r(t,e,n,u,i,a),i>=jf)throw new Error("arx: counter overflow");let g=Math.min(Zs,c-y);if(f&&g===Zs){let h=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let w=0,x;w<Gm;w++)x=h+w,p[x]=d[x]^u[w];y+=Zs;continue}for(let h=0,w;h<g;h++)w=y+h,s[w]=o[w]^l[h];y+=g}}function fc(r,t){let{allowShortKeys:e,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=$f({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),sc(s),sc(e),(a,c,l,u,f=0)=>{Ft(a),Ft(c),Ft(l);let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),Ft(u),zs(f),f<0||f>=jf)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let p=[],y=a.length,g,h;if(y===32)p.push(g=js(a)),h=Gf;else if(y===16&&e)g=new Uint8Array(32),g.set(a),g.set(a,16),h=zm,p.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${y}`);uc(c)||p.push(c=js(c));let w=Ne(g);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,w,Ne(c.subarray(0,16)),w),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 I=new Uint8Array(12);I.set(c,s?0:12-c.length),c=I,p.push(c)}let m=Ne(c);return jm(r,h,w,m,l,u,f,i),Le(...p),u}}var St=(r,t)=>r[t++]&255|(r[t++]&255)<<8,hc=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=Gs(t),Ft(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],p=i[6],y=i[7],g=i[8],h=i[9],w=St(t,e+0),x=St(t,e+2),m=St(t,e+4),I=St(t,e+6),L=St(t,e+8),N=St(t,e+10),B=St(t,e+12),k=St(t,e+14),S=s[0]+(w&8191),M=s[1]+((w>>>13|x<<3)&8191),_=s[2]+((x>>>10|m<<6)&8191),H=s[3]+((m>>>7|I<<9)&8191),V=s[4]+((I>>>4|L<<12)&8191),C=s[5]+(L>>>1&8191),T=s[6]+((L>>>14|N<<2)&8191),v=s[7]+((N>>>11|B<<5)&8191),b=s[8]+((B>>>8|k<<8)&8191),A=s[9]+(k>>>5|o),E=0,R=E+S*a+M*(5*h)+_*(5*g)+H*(5*y)+V*(5*p);E=R>>>13,R&=8191,R+=C*(5*d)+T*(5*f)+v*(5*u)+b*(5*l)+A*(5*c),E+=R>>>13,R&=8191;let U=E+S*c+M*a+_*(5*h)+H*(5*g)+V*(5*y);E=U>>>13,U&=8191,U+=C*(5*p)+T*(5*d)+v*(5*f)+b*(5*u)+A*(5*l),E+=U>>>13,U&=8191;let O=E+S*l+M*c+_*a+H*(5*h)+V*(5*g);E=O>>>13,O&=8191,O+=C*(5*y)+T*(5*p)+v*(5*d)+b*(5*f)+A*(5*u),E+=O>>>13,O&=8191;let K=E+S*u+M*l+_*c+H*a+V*(5*h);E=K>>>13,K&=8191,K+=C*(5*g)+T*(5*y)+v*(5*p)+b*(5*d)+A*(5*f),E+=K>>>13,K&=8191;let F=E+S*f+M*u+_*l+H*c+V*a;E=F>>>13,F&=8191,F+=C*(5*h)+T*(5*g)+v*(5*y)+b*(5*p)+A*(5*d),E+=F>>>13,F&=8191;let W=E+S*d+M*f+_*u+H*l+V*c;E=W>>>13,W&=8191,W+=C*a+T*(5*h)+v*(5*g)+b*(5*y)+A*(5*p),E+=W>>>13,W&=8191;let j=E+S*p+M*d+_*f+H*u+V*l;E=j>>>13,j&=8191,j+=C*c+T*a+v*(5*h)+b*(5*g)+A*(5*y),E+=j>>>13,j&=8191;let st=E+S*y+M*p+_*d+H*f+V*u;E=st>>>13,st&=8191,st+=C*l+T*c+v*a+b*(5*h)+A*(5*g),E+=st>>>13,st&=8191;let it=E+S*g+M*y+_*p+H*d+V*f;E=it>>>13,it&=8191,it+=C*u+T*l+v*c+b*a+A*(5*h),E+=it>>>13,it&=8191;let ut=E+S*h+M*g+_*y+H*p+V*d;E=ut>>>13,ut&=8191,ut+=C*f+T*u+v*l+b*c+A*a,E+=ut>>>13,ut&=8191,E=(E<<2)+E|0,E=E+R|0,R=E&8191,E=E>>>13,U+=E,s[0]=R,s[1]=U,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;Le(n)}update(t){ac(this);let{buffer:e,blockLen:n}=this;t=Gs(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(){Le(this.h,this.r,this.buffer,this.pad)}digestInto(t){ac(this),Ff(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 Zm(r){let t=(n,o)=>r(o).update(Gs(n)).digest(),e=r(new Uint8Array(32));return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=n=>r(n),t}var Zf=Zm(r=>new hc(r));function Jf(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],p=t[3],y=t[4],g=t[5],h=t[6],w=t[7],x=o,m=e[0],I=e[1],L=e[2],N=i,B=a,k=c,S=l,M=u,_=f,H=d,V=p,C=y,T=g,v=h,b=w,A=x,E=m,R=I,U=L;for(let K=0;K<s;K+=2)N=N+M|0,A=P(A^N,16),C=C+A|0,M=P(M^C,12),N=N+M|0,A=P(A^N,8),C=C+A|0,M=P(M^C,7),B=B+_|0,E=P(E^B,16),T=T+E|0,_=P(_^T,12),B=B+_|0,E=P(E^B,8),T=T+E|0,_=P(_^T,7),k=k+H|0,R=P(R^k,16),v=v+R|0,H=P(H^v,12),k=k+H|0,R=P(R^k,8),v=v+R|0,H=P(H^v,7),S=S+V|0,U=P(U^S,16),b=b+U|0,V=P(V^b,12),S=S+V|0,U=P(U^S,8),b=b+U|0,V=P(V^b,7),N=N+_|0,U=P(U^N,16),v=v+U|0,_=P(_^v,12),N=N+_|0,U=P(U^N,8),v=v+U|0,_=P(_^v,7),B=B+H|0,A=P(A^B,16),b=b+A|0,H=P(H^b,12),B=B+H|0,A=P(A^B,8),b=b+A|0,H=P(H^b,7),k=k+V|0,E=P(E^k,16),C=C+E|0,V=P(V^C,12),k=k+V|0,E=P(E^k,8),C=C+E|0,V=P(V^C,7),S=S+M|0,R=P(R^S,16),T=T+R|0,M=P(M^T,12),S=S+M|0,R=P(R^S,8),T=T+R|0,M=P(M^T,7);let O=0;n[O++]=i+N|0,n[O++]=a+B|0,n[O++]=c+k|0,n[O++]=l+S|0,n[O++]=u+M|0,n[O++]=f+_|0,n[O++]=d+H|0,n[O++]=p+V|0,n[O++]=y+C|0,n[O++]=g+T|0,n[O++]=h+v|0,n[O++]=w+b|0,n[O++]=x+A|0,n[O++]=m+E|0,n[O++]=I+R|0,n[O++]=L+U|0}function Xm(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],p=t[5],y=t[6],g=t[7],h=e[0],w=e[1],x=e[2],m=e[3];for(let L=0;L<20;L+=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,w=P(w^s,16),p=p+w|0,l=P(l^p,12),s=s+l|0,w=P(w^s,8),p=p+w|0,l=P(l^p,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,m=P(m^a,16),g=g+m|0,f=P(f^g,12),a=a+f|0,m=P(m^a,8),g=g+m|0,f=P(f^g,7),o=o+l|0,m=P(m^o,16),y=y+m|0,l=P(l^y,12),o=o+l|0,m=P(m^o,8),y=y+m|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,w=P(w^i,16),d=d+w|0,f=P(f^d,12),i=i+f|0,w=P(w^i,8),d=d+w|0,f=P(f^d,7),a=a+c|0,x=P(x^a,16),p=p+x|0,c=P(c^p,12),a=a+c|0,x=P(x^a,8),p=p+x|0,c=P(c^p,7);let I=0;n[I++]=o,n[I++]=s,n[I++]=i,n[I++]=a,n[I++]=h,n[I++]=w,n[I++]=x,n[I++]=m}var Ym=fc(Jf,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Jm=fc(Jf,{counterRight:!1,counterLength:8,extendNonceFn:Xm,allowShortKeys:!1});var Qm=new Uint8Array(16),Xf=(r,t)=>{r.update(t);let e=t.length%16;e&&r.update(Qm.subarray(e))},tg=new Uint8Array(32);function Yf(r,t,e,n,o){let s=r(t,e,tg),i=Zf.create(s);o&&Xf(i,o),Xf(i,n);let a=new Uint8Array(16),c=Kf(a);lc(c,0,BigInt(o?o.length:0),!0),lc(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return Le(s,a),l}var Qf=r=>(t,e,n)=>(Ft(t,32),Ft(e),{encrypt(s,i){let a=s.length,c=a+16;i?Ft(i,c):i=new Uint8Array(c),r(t,e,s,i,1);let l=Yf(r,t,e,i.subarray(0,-16),n);return i.set(l,a),Le(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?Ft(i,c):i=new Uint8Array(c);let l=s.subarray(0,-16),u=s.subarray(-16),f=Yf(r,t,e,l,n);if(!Wf(u,f))throw new Error("invalid tag");return r(t,e,l,i,1),Le(f),i}}),dc=cc({blockSize:64,nonceLength:12,tagLength:16},Qf(Ym)),VA=cc({blockSize:64,nonceLength:24,tagLength:16},Qf(Jm));function eh(r,t,e){return Qr(r),e===void 0&&(e=new Uint8Array(r.outputLen)),Pr(r,Ue(e),Ue(t))}var pc=new Uint8Array([0]),th=new Uint8Array;function rh(r,t,e,n=32){if(Qr(r),Xn(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);e===void 0&&(e=th);let s=new Uint8Array(o*r.outputLen),i=Pr.create(r,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)pc[0]=l+1,a.update(l===0?th:c).update(e).update(pc).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),pc.fill(0),s.slice(0,n)}var mc={hashSHA256(r){return ae(r.subarray())},getHKDF(r,t){let e=eh(ae,t,r),o=rh(ae,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=sn.utils.randomPrivateKey();return{publicKey:sn.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:sn.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,t){return sn.getSharedSecret(r.subarray(),t.subarray())},chaCha20Poly1305Encrypt(r,t,e,n){return dc(n,t,e).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,t,e,n,o){return dc(n,t,e).decrypt(r.subarray(),o)}};var nh=mc;function oh(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 On=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)};On.bytes=2;function sh(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 gc(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 yc(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 ih(r,t){!t.enabled||!$r||t(r?`REMOTE_STATIC_PUBLIC_KEY ${X(r.subarray(),"hex")}`:"Missing remote static public key.")}function wc(r,t){!t.enabled||!$r||t(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${X(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function bc(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 eg=0,rg=4294967295,ng="Cipherstate has reached maximum n, a new handshake must be performed",Xs=class{n;bytes;view;constructor(t=eg){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>rg)throw new Error(ng)}};var gr=gt(0),zr=class{k;n;crypto;constructor(t,e=void 0,n=0){this.crypto=t,this.k=e,this.n=new Xs(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}},xc=class{cs;ck;h;crypto;constructor(t,e){this.crypto=t;let n=Q(e,"utf-8");this.h=og(t,n),this.ck=this.h,this.cs=new zr(t)}mixKey(t){let[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new zr(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,gr);return[new zr(this.crypto,t),new zr(this.crypto,e)]}},vc=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 xc(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()}},Hn=class extends vc{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 og(r,t){if(t.length<=32){let e=gt(32);return e.set(t),e}else return r.hash(t)}var Ys;(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())})(Ys||(Ys={}));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),Ys.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=Ys.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 Ec(r,t,e){let n=await r.sign(ah(t));return Mn.encode({identityKey:kr(r.publicKey),identitySig:n,extensions:e})}async function Ac(r,t,e){try{let n=Mn.decode(r),o=En(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=ah(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new $n(n.message)}}function ah(r){let t=Q("noise-libp2p-static-key:");return r instanceof Uint8Array?xt([t,r],t.length+r.length):(r.prepend(t),r)}async function ch(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Ec(s,a.publicKey,l),f=new Hn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});gc(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."),yc(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."),wc(f.re,e),ih(f.rs,e),e.trace("Initiator going to check remote's signature...");let p=await Ac(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 bc(y,g,e),{payload:p,encrypt:h=>y.encryptWithAd(gr,h),decrypt:(h,w)=>g.decryptWithAd(gr,h,w)}}async function lh(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Ec(s,a.publicKey,l),f=new Hn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});gc(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."),wc(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."),yc(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 p=await Ac(d,f.rs,c),[y,g]=f.ss.split();return bc(y,g,e),{payload:p,encrypt:h=>g.encryptWithAd(gr,h),decrypt:(h,w)=>y.decryptWithAd(gr,h,w)}}var fh=16;function hh(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 dh(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-fh<o)throw new Error("Invalid chunk");let i=n.sublist(o,s),a=n.subarray(o,s-fh);try{let c=r.decrypt(i,a);t?.decryptedPackets.increment(),yield c}catch(c){throw t?.decryptErrors.increment(),c}}}}var Js=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??nh;this.crypto=oh(c),this.extensions=o,this.metrics=a?sh(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=Un(t,{lengthEncoder:Wr,lengthDecoder:On,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=En(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Sa(i)}}async secureInbound(t,e){let n=Un(t,{lengthEncoder:Wr,lengthDecoder:On,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=En(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Sa(i)}}async performHandshakeInitiator(t,e,n,o){let s;try{s=await ch({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 lh({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]=Pf(),s=t.unwrap();return await Hf(n,hh(e,this.metrics),s,i=>dr(i,{lengthDecoder:On}),dh(e,this.metrics),n),o}};function ph(r={}){return t=>new Js(t,r)}var Bc=Object.values(or).map(r=>r.decoder).reduce((r,t)=>r.or(t));function mh(r,t){let e=r.getConfiguration().certificates?.at(0);if(e?.getFingerprints==null){t.log.trace("fetching fingerprint from local SDP");let o=r.localDescription;return o==null?void 0:ig(o.sdp)}if(t.log.trace("fetching fingerprint from local certificate"),e.getFingerprints().length===0)return;let n=e.getFingerprints()[0].value;if(n==null)throw new Pn("","no fingerprint on local certificate");return n}var sg=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function ig(r){return r.match(sg)?.groups?.fingerprint}function ag(r){for(let t of r.protoNames())if(t.startsWith("ip"))return t.toUpperCase();return"IP6"}function Qs(r){let e=r.stringTuples().filter(n=>n[0]===wh).map(n=>n[1])[0];if(e===void 0||e==="")throw new et(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return e}function Sc(r){return Gt.decode(Bc.decode(r))}function cg(r){let t=Sc(Qs(r)),e=Ic(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 Pn(n,r.toString());return[`${e} ${o.join(":").toUpperCase()}`,n]}function Ic(r){switch(r){case 17:return"SHA-1";case 18:return"SHA-256";case 19:return"SHA-512";default:throw new Vs(r)}}function lg(r,t){let{host:e,port:n}=r.toOptions(),o=ag(r),[s]=cg(r);return`v=0
7
7
  o=- 0 0 IN ${o} ${e}
8
8
  s=-
9
9
  c=IN ${o} ${e}
@@ -16,13 +16,13 @@ a=ice-ufrag:${t}
16
16
  a=ice-pwd:${t}
17
17
  a=fingerprint:${s}
18
18
  a=sctp-port:5000
19
- a=max-message-size:${Rs}
19
+ a=max-message-size:${_s}
20
20
  a=candidate:1467250027 1 UDP 1467250027 ${e} ${n} typ host\r
21
- `}function yh(r,t){return{type:"answer",sdp:ug(r,t)}}function wh(r,t){if(r.sdp===void 0)throw new et("Can't munge a missing SDP");return r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
21
+ `}function gh(r,t){return{type:"answer",sdp:lg(r,t)}}function yh(r,t){if(r.sdp===void 0)throw new et("Can't munge a missing SDP");return r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
22
22
  a=ice-ufrag:`+t+`
23
23
  `).replace(/\na=ice-pwd:[^\n]*\n/,`
24
24
  a=ice-pwd:`+t+`
25
- `),r}var xh=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),vh=r=>[...Array(r)].map(()=>xh.at(Math.floor(Math.random()*xh.length))).join("");var hg=1e4,PS=tt("webrtc-direct").code,bh=tt("certhash").code,ei=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"})})}[Kn]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[wr]=["@libp2p/transport"];async dial(t,e){let n=await this._connect(t,e);return this.log("dialing address: %a",t),n}createListener(t){throw new Vs("WebRTCTransport.createListener")}listenFilter(t){return t.filter(ff.exactMatch)}dialFilter(t){return this.listenFilter(t)}async _connect(t,e){let n=new AbortController,o=n.signal,s,i=t.getPeerId();i!=null&&(s=Or(i));let a=Ic(ti(t)),c=await pr.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:Cc(a.code)}),l=new pr({...await Ln(this.init.rtcConfiguration),certificates:[c]});try{let u=new Promise((B,k)=>{let S=l.createDataChannel("",{negotiated:!0,id:0}),H=setTimeout(()=>{let _=`Data channel was never opened: state: ${S.readyState}`;this.log.error(_),this.metrics?.dialerEvents.increment({open_error:!0}),k(new Dn("data",_))},hg);S.onopen=_=>{clearTimeout(H),B(S)},S.onerror=_=>{clearTimeout(H);let V=`Error opening a data channel for handshaking: ${_.target?.toString()??"not specified"}`;this.log.error(V),this.metrics?.dialerEvents.increment({unknown_error:!0}),k(new Dn("data",V))}}),f="libp2p+webrtc+v1/"+vh(32),d=await l.createOffer(),p=wh(d,f);await l.setLocalDescription(p);let y=yh(t,f);await l.setRemoteDescription(y);let g=await u,h=this.generateNoisePrologue(l,a.code,t),w=mh({prologueBytes:h})(this.components),x=Kr({channel:g,direction:"inbound",logger:this.components.logger,...this.init.dataChannel??{}}),m={...x,sink:x.sink.bind(x),source:async function*(){for await(let B of x.source)for(let k of B)yield k}()},I=new fr(this.components,{peerConnection:l,remoteAddr:t,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),L=Nn?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(L,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":I.close().catch(B=>{this.log.error("error closing connection",B)}).finally(()=>{n.abort()});break;default:break}},{signal:o}),this.metrics?.dialerEvents.increment({peer_connection:!0});let N=new je(this.components,{peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await w.secureInbound(m,{signal:o,remotePeer:s}),await e.upgrader.upgradeOutbound(I,{skipProtection:!0,skipEncryption:!0,muxerFactory:N})}catch(u){throw l.close(),u}}generateNoisePrologue(t,e,n){if(t.getConfiguration().certificates?.length===0)throw new et("no local certificate");let o=gh(t,{log:this.log});if(o==null)throw new et("no local fingerprint found");let s=o.trim().toLowerCase().replaceAll(":",""),i=Q(s,"hex"),a=Ot(e,i),c=Sc.decode(ti(n)),l=Q("libp2p-webrtc-noise:");return xt([l,a.bytes,c])}};function dg(r){return t=>new ei(t,r)}function pg(r){return t=>new zs(t,r)}return Oh(mg);})();
25
+ `),r}var bh=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),xh=r=>[...Array(r)].map(()=>bh.at(Math.floor(Math.random()*bh.length))).join("");var fg=1e4,RS=tt("webrtc-direct").code,wh=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"})})}[Kn]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[wr]=["@libp2p/transport"];async dial(t,e){let n=await this._connect(t,e);return this.log("dialing address: %a",t),n}createListener(t){throw new Ms("WebRTCTransport.createListener")}listenFilter(t){return t.filter(uf.exactMatch)}dialFilter(t){return this.listenFilter(t)}async _connect(t,e){let n=new AbortController,o=n.signal,s,i=t.getPeerId();i!=null&&(s=Or(i));let a=Sc(Qs(t)),c=await pr.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:Ic(a.code)}),l=new pr({...await Ln(this.init.rtcConfiguration),certificates:[c]});try{let u=new Promise((B,k)=>{let S=l.createDataChannel("",{negotiated:!0,id:0}),M=setTimeout(()=>{let _=`Data channel was never opened: state: ${S.readyState}`;this.log.error(_),this.metrics?.dialerEvents.increment({open_error:!0}),k(new Dn("data",_))},fg);S.onopen=_=>{clearTimeout(M),B(S)},S.onerror=_=>{clearTimeout(M);let V=`Error opening a data channel for handshaking: ${_.target?.toString()??"not specified"}`;this.log.error(V),this.metrics?.dialerEvents.increment({unknown_error:!0}),k(new Dn("data",V))}}),f="libp2p+webrtc+v1/"+xh(32),d=await l.createOffer(),p=yh(d,f);await l.setLocalDescription(p);let y=gh(t,f);await l.setRemoteDescription(y);let g=await u,h=this.generateNoisePrologue(l,a.code,t),w=ph({prologueBytes:h})(this.components),x=Kr({channel:g,direction:"inbound",logger:this.components.logger,...this.init.dataChannel??{}}),m={...x,sink:x.sink.bind(x),source:async function*(){for await(let B of x.source)for(let k of B)yield k}()},I=new fr(this.components,{peerConnection:l,remoteAddr:t,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),L=Nn?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(L,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":I.close().catch(B=>{this.log.error("error closing connection",B)}).finally(()=>{n.abort()});break;default:break}},{signal:o}),this.metrics?.dialerEvents.increment({peer_connection:!0});let N=new je(this.components,{peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await w.secureInbound(m,{signal:o,remotePeer:s}),await e.upgrader.upgradeOutbound(I,{skipProtection:!0,skipEncryption:!0,muxerFactory:N})}catch(u){throw l.close(),u}}generateNoisePrologue(t,e,n){if(t.getConfiguration().certificates?.length===0)throw new et("no local certificate");let o=mh(t,{log:this.log});if(o==null)throw new et("no local fingerprint found");let s=o.trim().toLowerCase().replaceAll(":",""),i=Q(s,"hex"),a=Ot(e,i),c=Bc.decode(Qs(n)),l=Q("libp2p-webrtc-noise:");return xt([l,a.bytes,c])}};function hg(r){return t=>new ti(t,r)}function dg(r){return t=>new qs(t,r)}return Ph(pg);})();
26
26
  /*! Bundled license information:
27
27
 
28
28
  pvtsutils/build/index.js: