@libp2p/webrtc 4.0.5 → 4.0.6-16588d27c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -26,7 +26,7 @@ if (cid) {
26
26
  // Make sure to use cid instead of value
27
27
  doSomethingWithCID(cid)
28
28
  }
29
- `});var y1=dt(()=>{p1();ks();kr();Z0();qi()});var J0,Y_,m1=dt(()=>{qp();zp();Gp();Wp();$p();V0();Yp();z0();Xp();Qp();s1();u1();f1();l1();y1();J0={...P0,...U0,...O0,...K0,...M0,...F0,...H0,...q0,...G0,...W0},Y_={...Q0,...j0}});function Qn(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}var Ps=dt(()=>{});function Us(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Qn(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}var tu=dt(()=>{Ps()});function x1(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}var g1,eu,J8,Os,ru=dt(()=>{m1();tu();g1=x1("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),eu=x1("ascii","a",e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},e=>{e=e.substring(1);let t=Us(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}),J8={utf8:g1,"utf-8":g1,hex:J0.base16,latin1:eu,ascii:eu,binary:eu,...J0},Os=J8});var b1={};ft(b1,{toString:()=>tE});function tE(e,t="utf8"){let r=Os[t];if(!r)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"):r.encoder.encode(e).substring(1)}var w1=dt(()=>{ru()});var v1={};ft(v1,{fromString:()=>eE});function eE(e,t="utf8"){let r=Os[t];if(!r)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Qn(globalThis.Buffer.from(e,"utf-8")):r.decoder.decode(`${r.prefix}${e}`)}var E1=dt(()=>{ru();Ps()});var S1={};ft(S1,{concat:()=>rE});function rE(e,t){t||(t=e.reduce((i,o)=>i+o.length,0));let r=Us(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return Qn(r)}var A1=dt(()=>{tu();Ps()});var iu=st((ak,_1)=>{"use strict";var D1=Ep(),jn=Lp(),{names:Gi}=Pp(),{toString:Ks}=(w1(),$i(b1)),{fromString:nE}=(E1(),$i(v1)),{concat:iE}=(A1(),$i(S1)),Jn={};for(let e in Gi){let t=e;Jn[Gi[t]]=t}Object.freeze(Jn);function oE(e){if(!(e instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return Ks(e,"base16")}function sE(e){return nE(e,"base16")}function aE(e){if(!(e instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return Ks(D1.encode("base58btc",e)).slice(1)}function cE(e){let t=e instanceof Uint8Array?Ks(e):e;return D1.decode("z"+t)}function C1(e){if(!(e instanceof Uint8Array))throw new Error("multihash must be a Uint8Array");if(e.length<2)throw new Error("multihash too short. must be > 2 bytes.");let t=jn.decode(e);if(!I1(t))throw new Error(`multihash unknown function code: 0x${t.toString(16)}`);e=e.slice(jn.decode.bytes);let r=jn.decode(e);if(r<0)throw new Error(`multihash invalid length: ${r}`);if(e=e.slice(jn.decode.bytes),e.length!==r)throw new Error(`multihash length inconsistent: 0x${Ks(e,"base16")}`);return{code:t,name:Jn[t],length:r,digest:e}}function uE(e,t,r){if(!e||t===void 0)throw new Error("multihash encode requires at least two args: digest, code");let n=B1(t);if(!(e instanceof Uint8Array))throw new Error("digest should be a Uint8Array");if(r==null&&(r=e.length),r&&e.length!==r)throw new Error("digest length should be equal to specified length.");let i=jn.encode(n),o=jn.encode(r);return iE([i,o,e],i.length+o.length+e.length)}function B1(e){let t=e;if(typeof e=="string"){if(Gi[e]===void 0)throw new Error(`Unrecognized hash function named: ${e}`);t=Gi[e]}if(typeof t!="number")throw new Error(`Hash function code should be a number. Got: ${t}`);if(Jn[t]===void 0&&!nu(t))throw new Error(`Unrecognized function code: ${t}`);return t}function nu(e){return e>0&&e<16}function I1(e){return!!(nu(e)||Jn[e])}function T1(e){C1(e)}function fE(e){return T1(e),e.subarray(0,2)}_1.exports={names:Gi,codes:Jn,toHexString:oE,fromHexString:sE,toB58String:aE,fromB58String:cE,decode:C1,encode:uE,coerceCode:B1,isAppCode:nu,validate:T1,prefix:fE,isValidCode:I1}});var wE={};ft(wE,{webRTC:()=>bE,webRTCDirect:()=>xE});var EE=Symbol.for("@libp2p/connection");var AE=Symbol.for("@libp2p/content-routing");var BE=Symbol.for("@libp2p/peer-discovery");var gu=Symbol.for("@libp2p/peer-id");var _E=Symbol.for("@libp2p/peer-routing");var xu;(function(e){e.Accept="accept",e.Ignore="ignore",e.Reject="reject"})(xu||(xu={}));var Yi=Symbol.for("@libp2p/transport");var bu;(function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"})(bu||(bu={}));var W=class extends Error{code;props;constructor(t,r,n){super(t),this.code=r,this.name=n?.name??"CodeError",this.props=n??{}}};var Xi=class extends EventTarget{#t=new Map;listenerCount(t){let r=this.#t.get(t);return r==null?0:r.length}addEventListener(t,r,n){super.addEventListener(t,r,n);let i=this.#t.get(t);i==null&&(i=[],this.#t.set(t,i)),i.push({callback:r,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,r,n){super.removeEventListener(t.toString(),r??null,n);let i=this.#t.get(t);i!=null&&(i=i.filter(({callback:o})=>o!==r),this.#t.set(t,i))}dispatchEvent(t){let r=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:i})=>!i),this.#t.set(t.type,n)),r}safeDispatchEvent(t,r){return this.dispatchEvent(new j1(t,r))}},Hs=class extends Event{detail;constructor(t,r){super(t,r),this.detail=r?.detail}},j1=globalThis.CustomEvent??Hs;var $s={};ft($s,{base58btc:()=>Nt,base58flickr:()=>i2});function J1(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<e.length;i++){var o=e.charAt(i),s=o.charCodeAt(0);if(r[s]!==255)throw new TypeError(o+" is ambiguous");r[s]=i}var a=e.length,c=e.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var p=0,m=0,g=0,b=h.length;g!==b&&h[g]===0;)g++,p++;for(var x=(b-g)*f+1>>>0,A=new Uint8Array(x);g!==b;){for(var v=h[g],E=0,C=x-1;(v!==0||E<m)&&C!==-1;C--,E++)v+=256*A[C]>>>0,A[C]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");m=E,g++}for(var B=x-m;B!==x&&A[B]===0;)B++;for(var O=c.repeat(p);B<x;++B)O+=e.charAt(A[B]);return O}function d(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var p=0;if(h[p]!==" "){for(var m=0,g=0;h[p]===c;)m++,p++;for(var b=(h.length-p)*u+1>>>0,x=new Uint8Array(b);h[p];){var A=r[h.charCodeAt(p)];if(A===255)return;for(var v=0,E=b-1;(A!==0||v<g)&&E!==-1;E--,v++)A+=a*x[E]>>>0,x[E]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");g=v,p++}if(h[p]!==" "){for(var C=b-g;C!==b&&x[C]===0;)C++;for(var B=new Uint8Array(m+(b-C)),O=m;C!==b;)B[O++]=x[C++];return B}}}function y(h){var p=d(h);if(p)return p;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:d,decode:y}}var t2=J1,e2=t2,wu=e2;var f3=new Uint8Array(0);var vu=(e,t)=>{if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},$e=e=>{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};var Eu=e=>new TextEncoder().encode(e),Su=e=>new TextDecoder().decode(e);var qs=class{constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},zs=class{constructor(t,r,n){if(this.name=t,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),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 Du(this,t)}},Gs=class{constructor(t){this.decoders=t}or(t){return Du(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},Du=(e,t)=>new Gs({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}}),Ws=class{constructor(t,r,n,i){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new qs(t,r,n),this.decoder=new zs(t,r,i)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},ln=({name:e,prefix:t,encode:r,decode:n})=>new Ws(e,t,r,n),hr=({prefix:e,name:t,alphabet:r})=>{let{encode:n,decode:i}=wu(r,t);return ln({prefix:e,name:t,encode:n,decode:o=>$e(i(o))})},r2=(e,t,r,n)=>{let i={};for(let f=0;f<t.length;++f)i[t[f]]=f;let o=e.length;for(;e[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),a=0,c=0,u=0;for(let f=0;f<o;++f){let l=i[e[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|l,a+=r,a>=8&&(a-=8,s[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s},n2=(e,t,r)=>{let n=t[t.length-1]==="=",i=(1<<r)-1,o="",s=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],s+=8;s>r;)s-=r,o+=t[i&a>>s];if(s&&(o+=t[i&a<<r-s]),n)for(;o.length*r&7;)o+="=";return o},Rt=({name:e,prefix:t,bitsPerChar:r,alphabet:n})=>ln({prefix:t,name:e,encode(i){return n2(i,n,r)},decode(i){return r2(i,n,r,e)}});var Nt=hr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),i2=hr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ys={};ft(Ys,{base10:()=>o2});var o2=hr({prefix:"9",name:"base10",alphabet:"0123456789"});var Xs={};ft(Xs,{base16:()=>s2,base16upper:()=>a2});var s2=Rt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),a2=Rt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Zs={};ft(Zs,{base2:()=>c2});var c2=Rt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Qs={};ft(Qs,{base256emoji:()=>d2});var Cu=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}"),u2=Cu.reduce((e,t,r)=>(e[r]=t,e),[]),f2=Cu.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]);function l2(e){return e.reduce((t,r)=>(t+=u2[r],t),"")}function h2(e){let t=[];for(let r of e){let n=f2[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}var d2=ln({prefix:"\u{1F680}",name:"base256emoji",encode:l2,decode:h2});var js={};ft(js,{base32:()=>Ye,base32hex:()=>g2,base32hexpad:()=>b2,base32hexpadupper:()=>w2,base32hexupper:()=>x2,base32pad:()=>y2,base32padupper:()=>m2,base32upper:()=>p2,base32z:()=>v2});var Ye=Rt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),p2=Rt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),y2=Rt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),m2=Rt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),g2=Rt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),x2=Rt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),b2=Rt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),w2=Rt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),v2=Rt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Js={};ft(Js,{base36:()=>E2,base36upper:()=>S2});var E2=hr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),S2=hr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ea={};ft(ea,{base64:()=>Zi,base64pad:()=>A2,base64url:()=>ta,base64urlpad:()=>D2});var Zi=Rt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),A2=Rt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ta=Rt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),D2=Rt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ra={};ft(ra,{base8:()=>C2});var C2=Rt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var na={};ft(na,{identity:()=>B2});var B2=ln({prefix:"\0",name:"identity",encode:e=>Su(e),decode:e=>Eu(e)});var D3=new TextEncoder,C3=new TextDecoder;var oa={};ft(oa,{identity:()=>dr});var _2=Tu,Bu=128,k2=127,R2=~k2,L2=Math.pow(2,31);function Tu(e,t,r){t=t||[],r=r||0;for(var n=r;e>=L2;)t[r++]=e&255|Bu,e/=128;for(;e&R2;)t[r++]=e&255|Bu,e>>>=7;return t[r]=e|0,Tu.bytes=r-n+1,t}var N2=ia,P2=128,Iu=127;function ia(e,n){var r=0,n=n||0,i=0,o=n,s,a=e.length;do{if(o>=a)throw ia.bytes=0,new RangeError("Could not decode varint");s=e[o++],r+=i<28?(s&Iu)<<i:(s&Iu)*Math.pow(2,i),i+=7}while(s>=P2);return ia.bytes=o-n,r}var U2=Math.pow(2,7),O2=Math.pow(2,14),K2=Math.pow(2,21),M2=Math.pow(2,28),F2=Math.pow(2,35),V2=Math.pow(2,42),H2=Math.pow(2,49),q2=Math.pow(2,56),z2=Math.pow(2,63),G2=function(e){return e<U2?1:e<O2?2:e<K2?3:e<M2?4:e<F2?5:e<V2?6:e<H2?7:e<q2?8:e<z2?9:10},W2={encode:_2,decode:N2,encodingLength:G2},$2=W2,ei=$2;var ri=(e,t=0)=>[ei.decode(e,t),ei.decode.bytes],hn=(e,t,r=0)=>(ei.encode(e,t,r),t),dn=e=>ei.encodingLength(e);var Le=(e,t)=>{let r=t.byteLength,n=dn(e),i=n+dn(r),o=new Uint8Array(i+r);return hn(e,o,0),hn(r,o,n),o.set(t,i),new pn(e,r,t,o)},Nr=e=>{let t=$e(e),[r,n]=ri(t),[i,o]=ri(t.subarray(n)),s=t.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new pn(r,i,s,t)},_u=(e,t)=>{if(e===t)return!0;{let r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&vu(e.bytes,r.bytes)}},pn=class{constructor(t,r,n,i){this.code=t,this.size=r,this.digest=n,this.bytes=i}};var ku=0,Y2="identity",Ru=$e,X2=e=>Le(ku,Ru(e)),dr={code:ku,name:Y2,encode:Ru,digest:X2};var ca={};ft(ca,{sha256:()=>Xt,sha512:()=>Z2});var aa=({name:e,code:t,encode:r})=>new sa(e,t,r),sa=class{constructor(t,r,n){this.name=t,this.code=r,this.encode=n}digest(t){if(t instanceof Uint8Array){let r=this.encode(t);return r instanceof Uint8Array?Le(this.code,r):r.then(n=>Le(this.code,n))}else throw Error("Unknown type, must be binary type")}};var Nu=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),Xt=aa({name:"sha2-256",code:18,encode:Nu("SHA-256")}),Z2=aa({name:"sha2-512",code:19,encode:Nu("SHA-512")});var Pu=(e,t)=>{let{bytes:r,version:n}=e;switch(n){case 0:return j2(r,ua(e),t||Nt.encoder);default:return J2(r,ua(e),t||Ye.encoder)}};var Uu=new WeakMap,ua=e=>{let t=Uu.get(e);if(t==null){let r=new Map;return Uu.set(e,r),r}return t},be=class e{constructor(t,r,n,i){this.code=r,this.version=t,this.multihash=n,this.bytes=i,this["/"]=i}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:r}=this;if(t!==ni)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==ty)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return e.createV0(r)}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:r}=this.multihash,n=Le(t,r);return e.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 e.equals(this,t)}static equals(t,r){let n=r;return n&&t.code===n.code&&t.version===n.version&&_u(t.multihash,n.multihash)}toString(t){return Pu(this,t)}toJSON(){return{"/":Pu(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let r=t;if(r instanceof e)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:i,multihash:o,bytes:s}=r;return new e(n,i,o,s||Ou(n,i,o.bytes))}else if(r[ey]===!0){let{version:n,multihash:i,code:o}=r,s=Nr(i);return e.create(n,o,s)}else return null}static create(t,r,n){if(typeof r!="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(r!==ni)throw new Error(`Version 0 CID must use dag-pb (code: ${ni}) block encoding`);return new e(t,r,n,n.bytes)}case 1:{let i=Ou(t,r,n.bytes);return new e(t,r,n,i)}default:throw new Error("Invalid version")}}static createV0(t){return e.create(0,ni,t)}static createV1(t,r){return e.create(1,t,r)}static decode(t){let[r,n]=e.decodeFirst(t);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(t){let r=e.inspectBytes(t),n=r.size-r.multihashSize,i=$e(t.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let o=i.subarray(r.multihashSize-r.digestSize),s=new pn(r.multihashCode,r.digestSize,o,i);return[r.version===0?e.createV0(s):e.createV1(r.codec,s),t.subarray(r.size)]}static inspectBytes(t){let r=0,n=()=>{let[l,d]=ri(t.subarray(r));return r+=d,l},i=n(),o=ni;if(i===18?(i=0,r=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=r,a=n(),c=n(),u=r+c,f=u-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(t,r){let[n,i]=Q2(t,r),o=e.decode(i);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ua(o).set(n,t),o}},Q2=(e,t)=>{switch(e[0]){case"Q":{let r=t||Nt;return[Nt.prefix,r.decode(`${Nt.prefix}${e}`)]}case Nt.prefix:{let r=t||Nt;return[Nt.prefix,r.decode(e)]}case Ye.prefix:{let r=t||Ye;return[Ye.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}},j2=(e,t,r)=>{let{prefix:n}=r;if(n!==Nt.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=t.get(n);if(i==null){let o=r.encode(e).slice(1);return t.set(n,o),o}else return i},J2=(e,t,r)=>{let{prefix:n}=r,i=t.get(n);if(i==null){let o=r.encode(e);return t.set(n,o),o}else return i},ni=112,ty=18,Ou=(e,t,r)=>{let n=dn(e),i=n+dn(t),o=new Uint8Array(i+r.byteLength);return hn(e,o,0),hn(t,o,n),o.set(r,i),o},ey=Symbol.for("@ipld/js-cid/CID");var Ne={...na,...Zs,...ra,...Ys,...Xs,...js,...Js,...$s,...ea,...Qs},H3={...ca,...oa};function Kt(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}var ry=Symbol.for("nodejs.util.inspect.custom"),Ku=Object.values(Ne).map(e=>e.decoder).reduce((e,t)=>e.or(t),Ne.identity.decoder),Mu=114,fa=36,la=37,ii=class{type;multihash;privateKey;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,this.privateKey=t.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[gu]=!0;toString(){return this.string==null&&(this.string=Nt.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return be.createV1(Mu,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(t){if(t instanceof Uint8Array)return Kt(this.multihash.bytes,t);if(typeof t=="string")return Ur(t).equals(this);if(t?.multihash?.bytes!=null)return Kt(this.multihash.bytes,t.multihash.bytes);throw new Error("not valid Id")}[ry](){return`PeerId(${this.toString()})`}},yn=class extends ii{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},mn=class extends ii{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.multihash.digest}},gn=class extends ii{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.multihash.digest}};function Ur(e,t){if(t=t??Ku,e.charAt(0)==="1"||e.charAt(0)==="Q"){let r=Nr(Nt.decode(`z${e}`));return e.startsWith("12D")?new mn({multihash:r}):e.startsWith("16U")?new gn({multihash:r}):new yn({multihash:r})}return ny(Ku.decode(e))}function ny(e){try{let t=Nr(e);if(t.code===dr.code){if(t.digest.length===fa)return new mn({multihash:t});if(t.digest.length===la)return new gn({multihash:t})}if(t.code===Xt.code)return new yn({multihash:t})}catch{return iy(be.decode(e))}throw new Error("Supplied PeerID CID is invalid")}function iy(e){if(e==null||e.multihash==null||e.version==null||e.version===1&&e.code!==Mu)throw new Error("Supplied PeerID CID is invalid");let t=e.multihash;if(t.code===Xt.code)return new yn({multihash:e.multihash});if(t.code===dr.code){if(t.digest.length===fa)return new mn({multihash:e.multihash});if(t.digest.length===la)return new gn({multihash:e.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function ha(e,t){return e.length===fa?new mn({multihash:Le(dr.code,e),privateKey:t}):e.length===la?new gn({multihash:Le(dr.code,e),privateKey:t}):new yn({multihash:await Xt.digest(e),publicKey:e,privateKey:t})}function Xe(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function ot(e=0){return globalThis.Buffer?.alloc!=null?Xe(globalThis.Buffer.alloc(e)):new Uint8Array(e)}function Vt(e=0){return globalThis.Buffer?.allocUnsafe!=null?Xe(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function Vu(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}var Fu=Vu("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),da=Vu("ascii","a",e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},e=>{e=e.substring(1);let t=Vt(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}),sy={utf8:Fu,"utf-8":Fu,hex:Ne.base16,latin1:da,ascii:da,binary:da,...Ne},ji=sy;function at(e,t="utf8"){let r=ji[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"):r.encoder.encode(e).substring(1)}var ay=Math.pow(2,7),cy=Math.pow(2,14),uy=Math.pow(2,21),pa=Math.pow(2,28),ya=Math.pow(2,35),ma=Math.pow(2,42),ga=Math.pow(2,49),pt=128,te=127;function ee(e){if(e<ay)return 1;if(e<cy)return 2;if(e<uy)return 3;if(e<pa)return 4;if(e<ya)return 5;if(e<ma)return 6;if(e<ga)return 7;if(Number.MAX_SAFE_INTEGER!=null&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function fy(e,t,r=0){switch(ee(e)){case 8:t[r++]=e&255|pt,e/=128;case 7:t[r++]=e&255|pt,e/=128;case 6:t[r++]=e&255|pt,e/=128;case 5:t[r++]=e&255|pt,e/=128;case 4:t[r++]=e&255|pt,e>>>=7;case 3:t[r++]=e&255|pt,e>>>=7;case 2:t[r++]=e&255|pt,e>>>=7;case 1:{t[r++]=e&255,e>>>=7;break}default:throw new Error("unreachable")}return t}function ly(e,t,r=0){switch(ee(e)){case 8:t.set(r++,e&255|pt),e/=128;case 7:t.set(r++,e&255|pt),e/=128;case 6:t.set(r++,e&255|pt),e/=128;case 5:t.set(r++,e&255|pt),e/=128;case 4:t.set(r++,e&255|pt),e>>>=7;case 3:t.set(r++,e&255|pt),e>>>=7;case 2:t.set(r++,e&255|pt),e>>>=7;case 1:{t.set(r++,e&255),e>>>=7;break}default:throw new Error("unreachable")}return t}function hy(e,t){let r=e[t],n=0;if(n+=r&te,r<pt||(r=e[t+1],n+=(r&te)<<7,r<pt)||(r=e[t+2],n+=(r&te)<<14,r<pt)||(r=e[t+3],n+=(r&te)<<21,r<pt)||(r=e[t+4],n+=(r&te)*pa,r<pt)||(r=e[t+5],n+=(r&te)*ya,r<pt)||(r=e[t+6],n+=(r&te)*ma,r<pt)||(r=e[t+7],n+=(r&te)*ga,r<pt))return n;throw new RangeError("Could not decode varint")}function dy(e,t){let r=e.get(t),n=0;if(n+=r&te,r<pt||(r=e.get(t+1),n+=(r&te)<<7,r<pt)||(r=e.get(t+2),n+=(r&te)<<14,r<pt)||(r=e.get(t+3),n+=(r&te)<<21,r<pt)||(r=e.get(t+4),n+=(r&te)*pa,r<pt)||(r=e.get(t+5),n+=(r&te)*ya,r<pt)||(r=e.get(t+6),n+=(r&te)*ma,r<pt)||(r=e.get(t+7),n+=(r&te)*ga,r<pt))return n;throw new RangeError("Could not decode varint")}function pr(e,t,r=0){return t==null&&(t=Vt(ee(e))),t instanceof Uint8Array?fy(e,t,r):ly(e,t,r)}function we(e,t=0){return e instanceof Uint8Array?hy(e,t):dy(e,t)}function Ct(e,t){if(globalThis.Buffer!=null)return Xe(globalThis.Buffer.concat(e,t));t==null&&(t=e.reduce((i,o)=>i+o.length,0));let r=Vt(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return Xe(r)}var Ji=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let r=this.index,n=t();return n===void 0&&(this.index=r),n}parseWith(t){let r=t();if(this.index===this.input.length)return r}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 r=this.readChar();if(r===t)return r})}readSeparator(t,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,r,n,i){return this.readAtomically(()=>{let o=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*i)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,t);if(!Number.isNaN(d))return d});if(f===void 0)break;if(o*=t,o+=f,o>u||(s+=1,r!==void 0&&s>r))return}if(s!==0)return!n&&c&&s>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let r=0;r<t.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[r]=n}return t})}readIPv6Addr(){let t=r=>{for(let n=0;n<r.length/2;n++){let i=n*2;if(n<r.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return r[i]=s[0],r[i+1]=s[1],r[i+2]=s[2],r[i+3]=s[3],[i+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[i,!1];r[i]=o>>8,r[i+1]=o&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,i]=t(r);if(n===16)return r;if(i||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),s=16-(n+2),[a]=t(o.subarray(0,s));return r.set(o.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Hu=45,py=15,xn=new Ji;function xa(e){if(!(e.length>py))return xn.new(e).parseWith(()=>xn.readIPv4Addr())}function ba(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>Hu))return xn.new(e).parseWith(()=>xn.readIPv6Addr())}function to(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>Hu))return xn.new(e).parseWith(()=>xn.readIPAddr())}var w4=parseInt("0xFFFF",16),v4=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function wt(e,t="utf8"){let r=ji[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Xe(globalThis.Buffer.from(e,"utf-8")):r.decoder.decode(`${r.prefix}${e}`)}function eo(e){return!!xa(e)}function ro(e){return!!ba(e)}function no(e){return!!to(e)}var Gu=eo,by=ro,wa=function(e){let t=0;if(e=e.toString().trim(),Gu(e)){let r=new Uint8Array(t+4);return e.split(/\./g).forEach(n=>{r[t++]=parseInt(n,10)&255}),r}if(by(e)){let r=e.split(":",8),n;for(n=0;n<r.length;n++){let o=Gu(r[n]),s;o&&(s=wa(r[n]),r[n]=at(s.slice(0,2),"base16")),s!=null&&++n<8&&r.splice(n,0,at(s.slice(2,4),"base16"))}if(r[0]==="")for(;r.length<8;)r.unshift("0");else if(r[r.length-1]==="")for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&r[n]!=="";n++);let o=[n,1];for(n=9-r.length;n>0;n--)o.push("0");r.splice.apply(r,o)}let i=new Uint8Array(t+16);for(n=0;n<r.length;n++){let o=parseInt(r[n],16);i[t++]=o>>8&255,i[t++]=o&255}return i}throw new Error("invalid ip address")},Wu=function(e,t=0,r){t=~~t,r=r??e.length-t;let n=new DataView(e.buffer);if(r===4){let i=[];for(let o=0;o<r;o++)i.push(e[t+o]);return i.join(".")}if(r===16){let i=[];for(let o=0;o<r;o+=2)i.push(n.getUint16(t+o).toString(16));return i.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var bn={},va={},vy=[[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"],[777,-1,"memory"]];vy.forEach(e=>{let t=Ey(...e);va[t.code]=t,bn[t.name]=t});function Ey(e,t,r,n,i){return{code:e,size:t,name:r,resolvable:!!n,path:!!i}}function yt(e){if(typeof e=="number"){if(va[e]!=null)return va[e];throw new Error(`no protocol with code: ${e}`)}else if(typeof e=="string"){if(bn[e]!=null)return bn[e];throw new Error(`no protocol with name: ${e}`)}throw new Error(`invalid protocol id type: ${typeof e}`)}var aS=yt("ip4"),cS=yt("ip6"),uS=yt("ipcidr");function Sa(e,t){switch(yt(e).code){case 4:case 41:return Ay(t);case 42:return Xu(t);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 Xu(t);case 421:return Iy(t);case 444:return Zu(t);case 445:return Zu(t);case 466:return By(t);default:return at(t,"base16")}}function Aa(e,t){switch(yt(e).code){case 4:return $u(t);case 41:return $u(t);case 42:return Yu(t);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 Yu(t);case 421:return Dy(t);case 444:return Ty(t);case 445:return _y(t);case 466:return Cy(t);default:return wt(t,"base16")}}var Ea=Object.values(Ne).map(e=>e.decoder),Sy=function(){let e=Ea[0].or(Ea[1]);return Ea.slice(2).forEach(t=>e=e.or(t)),e}();function $u(e){if(!no(e))throw new Error("invalid ip address");return wa(e)}function Ay(e){let t=Wu(e,0,e.length);if(t==null)throw new Error("ipBuff is required");if(!no(t))throw new Error("invalid ip address");return t}function Da(e){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,e),new Uint8Array(t)}function Qu(e){return new DataView(e.buffer).getUint16(e.byteOffset)}function Yu(e){let t=wt(e),r=Uint8Array.from(pr(t.length));return Ct([r,t],r.length+t.length)}function Xu(e){let t=we(e);if(e=e.slice(ee(t)),e.length!==t)throw new Error("inconsistent lengths");return at(e)}function Dy(e){let t;e[0]==="Q"||e[0]==="1"?t=Nr(Nt.decode(`z${e}`)).bytes:t=be.parse(e).multihash.bytes;let r=Uint8Array.from(pr(t.length));return Ct([r,t],r.length+t.length)}function Cy(e){let t=Sy.decode(e),r=Uint8Array.from(pr(t.length));return Ct([r,t],r.length+t.length)}function By(e){let t=we(e),r=e.slice(ee(t));if(r.length!==t)throw new Error("inconsistent lengths");return"u"+at(r,"base64url")}function Iy(e){let t=we(e),r=e.slice(ee(t));if(r.length!==t)throw new Error("inconsistent lengths");return at(r,"base58btc")}function Ty(e){let t=e.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 r=Ye.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 i=Da(n);return Ct([r,i],r.length+i.length)}function _y(e){let t=e.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 r=Ye.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 i=Da(n);return Ct([r,i],r.length+i.length)}function Zu(e){let t=e.slice(0,e.length-2),r=e.slice(e.length-2),n=at(t,"base32"),i=Qu(r);return`${n}:${i}`}function ju(e){e=Ca(e);let t=[],r=[],n=null,i=e.split("/").slice(1);if(i.length===1&&i[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let o=0;o<i.length;o++){let s=i[o],a=yt(s);if(a.size===0){t.push([a.code]),r.push([a.code]);continue}if(o++,o>=i.length)throw tf("invalid address: "+e);if(a.path===!0){n=Ca(i.slice(o).join("/")),t.push([a.code,Aa(a.code,n)]),r.push([a.code,n]);break}let c=Aa(a.code,i[o]);t.push([a.code,c]),r.push([a.code,Sa(a.code,c)])}return{string:Ju(r),bytes:Ia(t),tuples:t,stringTuples:r,path:n}}function Ba(e){let t=[],r=[],n=null,i=0;for(;i<e.length;){let o=we(e,i),s=ee(o),a=yt(o),c=ky(a,e.slice(i+s));if(c===0){t.push([o]),r.push([o]),i+=s;continue}let u=e.slice(i+s,i+s+c);if(i+=c+s,i>e.length)throw tf("Invalid address Uint8Array: "+at(e,"base16"));t.push([o,u]);let f=Sa(o,u);if(r.push([o,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(e),string:Ju(r),tuples:t,stringTuples:r,path:n}}function Ju(e){let t=[];return e.map(r=>{let n=yt(r[0]);return t.push(n.name),r.length>1&&r[1]!=null&&t.push(r[1]),null}),Ca(t.join("/"))}function Ia(e){return Ct(e.map(t=>{let r=yt(t[0]),n=Uint8Array.from(pr(r.code));return t.length>1&&t[1]!=null&&(n=Ct([n,t[1]])),n}))}function ky(e,t){if(e.size>0)return e.size/8;if(e.size===0)return 0;{let r=we(t instanceof Uint8Array?t:Uint8Array.from(t));return r+ee(r)}}function Ca(e){return"/"+e.trim().split("/").filter(t=>t).join("/")}function tf(e){return new Error("Error parsing address: "+e)}var Ry=Symbol.for("nodejs.util.inspect.custom"),Ta=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Ly=[yt("dns").code,yt("dns4").code,yt("dns6").code,yt("dnsaddr").code],io=class e{bytes;#t;#e;#r;#n;[Ta]=!0;constructor(t){t==null&&(t="");let r;if(t instanceof Uint8Array)r=Ba(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);r=ju(t)}else if(rf(t))r=Ba(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=r.bytes,this.#t=r.string,this.#e=r.tuples,this.#r=r.stringTuples,this.#n=r.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,r,n,i,o="",s=yt("tcp"),a=yt("udp"),c=yt("ip4"),u=yt("ip6"),f=yt("dns6"),l=yt("ip6zone");for(let[y,h]of this.stringTuples())y===l.code&&(o=`%${h??""}`),Ly.includes(y)&&(r=s.name,i=443,n=`${h??""}${o}`,t=y===f.code?6:4),(y===s.code||y===a.code)&&(r=yt(y).name,i=parseInt(h??"")),(y===c.code||y===u.code)&&(r=yt(y).name,n=`${h??""}${o}`,t=y===u.code?6:4);if(t==null||r==null||n==null||i==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:r,port:i}}protos(){return this.#e.map(([t])=>Object.assign({},yt(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>yt(t).name)}tuples(){return this.#e}stringTuples(){return this.#r}encapsulate(t){return t=new e(t),new e(this.toString()+t.toString())}decapsulate(t){let r=t.toString(),n=this.toString(),i=n.lastIndexOf(r);if(i<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new e(n.slice(0,i))}decapsulateCode(t){let r=this.tuples();for(let n=r.length-1;n>=0;n--)if(r[n][0]===t)return new e(Ia(r.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,i])=>{n===bn.p2p.code&&t.push([n,i]),n===bn["p2p-circuit"].code&&(t=[])});let r=t.pop();if(r?.[1]!=null){let n=r[1];return n[0]==="Q"||n[0]==="1"?at(Nt.decode(`z${n}`),"base58btc"):at(be.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return Kt(this.bytes,t.bytes)}async resolve(t){let r=this.protos().find(o=>o.resolvable);if(r==null)return[this];let n=ef.get(r.name);if(n==null)throw new W(`no available resolver for ${r.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,t)).map(o=>new e(o))}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 r=(t??this).protos();return!(r.length!==2||r[0].code!==4&&r[0].code!==41||r[1].code!==6&&r[1].code!==273)}[Ry](){return`Multiaddr(${this.#t})`}};var ef=new Map;function rf(e){return!!e?.[Ta]}function Ze(e){return new io(e)}var Ny=e=>e.toString().split("/").slice(1),si=e=>({match:t=>t.length<1?!1:e(t[0])?t.slice(1):!1,pattern:"fn"}),Pt=e=>({match:t=>si(r=>r===e).match(t),pattern:e}),ao=()=>({match:e=>si(t=>typeof t=="string").match(e),pattern:"{string}"}),nf=()=>({match:e=>si(t=>!isNaN(parseInt(t))).match(e),pattern:"{number}"}),de=()=>({match:e=>{if(e.length<2||e[0]!=="p2p"&&e[0]!=="ipfs")return!1;if(e[1].startsWith("Q")||e[1].startsWith("1"))try{Nt.decode(`z${e[1]}`)}catch{return!1}else return!1;return e.slice(2)},pattern:"/p2p/{peerid}"}),oo=()=>({match:e=>{if(e.length<2||e[0]!=="certhash")return!1;try{ta.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),Pe=e=>({match:t=>{let r=e.match(t);return r===!1?t:r},pattern:`optional(${e.pattern})`}),Ue=(...e)=>({match:t=>{let r;for(let n of e){let i=n.match(t);i!==!1&&(r==null||i.length<r.length)&&(r=i)}return r??!1},pattern:`or(${e.map(t=>t.pattern).join(", ")})`}),Ut=(...e)=>({match:t=>{for(let r of e){let n=r.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${e.map(t=>t.pattern).join(", ")})`});function Ht(...e){function t(i){let o=Ny(i);for(let s of e){let a=s.match(o);if(a===!1)return!1;o=a}return o}function r(i){return t(i)!==!1}function n(i){let o=t(i);return o===!1?!1:o.length===0}return{matches:r,exactMatch:n}}var ka=Ut(Pt("dns4"),ao()),Ra=Ut(Pt("dns6"),ao()),La=Ut(Pt("dnsaddr"),ao()),of=Ut(Pt("dns"),ao()),KS=Ht(ka),MS=Ht(Ra),FS=Ht(La),VS=Ht(Ue(of,La,ka,Ra)),sf=Ut(Pt("ip4"),si(eo)),af=Ut(Pt("ip6"),si(ro)),cf=Ue(sf,af),ai=Ue(cf,of,ka,Ra,La),HS=Ht(ai),qS=Ht(sf),zS=Ht(af),GS=Ht(cf),co=Ut(ai,Pt("tcp"),nf()),ci=Ut(ai,Pt("udp"),nf()),Py=Ue(co,ci),WS=Ht(co),$S=Ht(ci),Na=Ut(ci,Pt("quic")),uo=Ut(ci,Pt("quic-v1")),Uy=Ue(Na,uo),YS=Ht(Na),XS=Ht(uo),_a=Ue(ai,co,ci,Na,uo),uf=Ue(Ut(_a,Pt("ws"),Pe(de()))),ZS=Ht(uf),ff=Ue(Ut(_a,Pt("wss"),Pe(de())),Ut(_a,Pt("tls"),Pt("ws"),Pe(de()))),QS=Ht(ff),lf=Ut(Py,Pt("webrtc-direct"),oo(),Pe(oo()),Pe(de())),hf=Ht(lf),df=Ut(uo,Pt("webtransport"),oo(),oo(),Pe(de())),jS=Ht(df),so=Ue(uf,ff,Ut(co,Pe(de())),Ut(Uy,Pe(de())),Ut(ai,Pe(de())),lf,df,de()),JS=Ht(so),Oy=Ut(so,Pt("p2p-circuit"),de()),t5=Ht(Oy),Ky=Ue(Ut(so,Pt("p2p-circuit"),Pt("webrtc"),de()),Ut(so,Pt("webrtc"),Pe(de())),Pt("webrtc")),pf=Ht(Ky);var fe;(function(e){e.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",e.ERR_DATA_CHANNEL="ERR_DATA_CHANNEL",e.ERR_CONNECTION_CLOSED="ERR_CONNECTION_CLOSED",e.ERR_HASH_NOT_SUPPORTED="ERR_HASH_NOT_SUPPORTED",e.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",e.ERR_INVALID_FINGERPRINT="ERR_INVALID_FINGERPRINT",e.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",e.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",e.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",e.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS"})(fe||(fe={}));var yr=class extends W{constructor(t,r){super(`WebRTC transport error: ${t}`,r??""),this.name="WebRTCTransportError"}};var Pa=class extends yr{constructor(t,r){super(`[stream: ${t}] data channel error: ${r}`,fe.ERR_DATA_CHANNEL),this.name="WebRTC/DataChannelError"}};function Va(e,t){return new Pa(e,t)}var Ua=class extends yr{constructor(t){super(`There was a problem with the Multiaddr which was passed in: ${t}`,fe.ERR_INVALID_MULTIADDR),this.name="WebRTC/InappropriateMultiaddrError"}};function fo(e){return new Ua(e)}var Oa=class extends yr{constructor(t){super(`There was a problem with a provided argument: ${t}`,fe.ERR_INVALID_PARAMETERS),this.name="WebRTC/InvalidArgumentError"}};function ui(e){return new Oa(e)}var Ka=class extends yr{constructor(t,r){super(`Invalid fingerprint "${t}" within ${r}`,fe.ERR_INVALID_FINGERPRINT),this.name="WebRTC/InvalidFingerprintError"}};function Ha(e,t){return new Ka(e,t)}var Ma=class extends yr{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`,fe.ERR_NOT_IMPLEMENTED),this.name="WebRTC/UnimplementedError"}};function yf(e){return new Ma(e)}var Fa=class extends yr{constructor(t){super(`unsupported hash algorithm: ${t}`,fe.ERR_HASH_NOT_SUPPORTED),this.name="WebRTC/UnsupportedHashAlgorithmError"}};function mf(e){return new Fa(e)}var gf=function(e,t,r){if(r||arguments.length===2)for(var n=0,i=t.length,o;n<i;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},My=function(){function e(t,r,n){this.name=t,this.version=r,this.os=n,this.type="browser"}return e}();var Fy=function(){function e(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return e}();var Vy=function(){function e(t,r,n,i){this.name=t,this.version=r,this.os=n,this.bot=i,this.type="bot-device"}return e}();var Hy=function(){function e(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return e}();var qy=function(){function e(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return e}();var zy=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Gy=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,xf=3,Wy=[["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",zy]],bf=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function vf(e){return e?wf(e):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new qy:typeof navigator<"u"?wf(navigator.userAgent):Xy()}function $y(e){return e!==""&&Wy.reduce(function(t,r){var n=r[0],i=r[1];if(t)return t;var o=i.exec(e);return!!o&&[n,o]},!1)}function wf(e){var t=$y(e);if(!t)return null;var r=t[0],n=t[1];if(r==="searchbot")return new Hy;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length<xf&&(i=gf(gf([],i,!0),Zy(xf-i.length),!0)):i=[];var o=i.join("."),s=Yy(e),a=Gy.exec(e);return a&&a[1]?new Vy(r,o,s,a[1]):new My(r,o,s)}function Yy(e){for(var t=0,r=bf.length;t<r;t++){var n=bf[t],i=n[0],o=n[1],s=o.exec(e);if(s)return i}return null}function Xy(){var e=typeof process<"u"&&process.version;return e?new Fy(process.version.slice(1)):null}function Zy(e){for(var t=[],r=0;r<e;r++)t.push("0");return t}function kt(){let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}var wn=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},qa=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Ef=e=>globalThis.DOMException===void 0?new qa(e):new DOMException(e),Sf=e=>{let t=e.reason===void 0?Ef("This operation was aborted."):e.reason;return t instanceof Error?t:Ef(t)};function Or(e,t){let{milliseconds:r,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout}}=t,s,c=new Promise((u,f)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){let{signal:d}=t;d.aborted&&f(Sf(d)),d.addEventListener("abort",()=>{f(Sf(d))})}if(r===Number.POSITIVE_INFINITY){e.then(u,f);return}let l=new wn;s=o.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(d){f(d)}return}typeof e.cancel=="function"&&e.cancel(),i===!1?u():i instanceof Error?f(i):(l.message=i??`Promise timed out after ${r} milliseconds`,f(l))},r),(async()=>{try{u(await e)}catch(d){f(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{o.clearTimeout.call(void 0,s),s=void 0},c}var Af=vf(),fi=Af!=null&&Af.name==="firefox",lo=async function*(){},ho=async e=>{},Qy=30*1e3;function Df(e,t,r=Qy,n){e.readyState==="open"&&Promise.resolve().then(async()=>{if(e.bufferedAmount>0){n.log("%s drain channel with %d buffered bytes",t,e.bufferedAmount);let i=kt(),o=!1;e.bufferedAmountLowThreshold=0;let s=()=>{o||(n.log("%s drain channel closed before drain",t),i.resolve())};e.addEventListener("close",s,{once:!0}),e.addEventListener("bufferedamountlow",()=>{o=!0,e.removeEventListener("close",s),i.resolve()}),await Or(i.promise,{milliseconds:r})}}).then(async()=>{e.readyState==="open"&&e.close()}).catch(i=>{n.log.error("error closing outbound stream",i)})}var Kr=class{log;peerConnection;remoteAddr;timeline;metrics;source=lo();sink=ho;constructor(t,r){this.log=t.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=r.remoteAddr,this.timeline=r.timeline,this.peerConnection=r.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 po=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}},vn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new po(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 r=this.head;this.head=r.next=new po(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,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,r){super(t??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function mr(e={}){return jy(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},e)}function jy(e,t){t=t??{};let r=t.onEnd,n=new vn,i,o,s,a=kt(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((m,g)=>{o=b=>{o=null,n.push(b);try{m(e(n))}catch(x){g(x)}return i}}):e(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=kt()})}},u=m=>o!=null?o(m):(n.push(m),i),f=m=>(n=new vn,o!=null?o({error:m}):(n.push({error:m}),i)),l=m=>{if(s)return i;if(t?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:m})},d=m=>s?i:(s=!0,m!=null?f(m):u({done:!0})),y=()=>(n=new vn,d(),{done:!0}),h=m=>(d(m),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:y,throw:h,push:l,end:d,get readableLength(){return n.size},onEmpty:async m=>{let g=m?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let b,x;g!=null&&(b=new Promise((A,v)=>{x=()=>{v(new za)},g.addEventListener("abort",x)}));try{await Promise.race([a.promise,b])}finally{x!=null&&g!=null&&g?.removeEventListener("abort",x)}}},r==null)return i;let p=i;return i={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(m){return p.throw(m),r!=null&&(r(m),r=void 0),{done:!0}},return(){return p.return(),r!=null&&(r(),r=void 0),{done:!0}},push:l,end(m){return p.end(m),r!=null&&(r(m),r=void 0),i},get readableLength(){return p.readableLength},onEmpty:m=>p.onEmpty(m)},i}var yo=class extends Error{type;code;constructor(t,r){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=r??"ABORT_ERR"}};async function gr(e,t,r){if(t==null)return e;if(t.aborted)return Promise.reject(new yo(r?.errorMessage,r?.errorCode));let n,i=new yo(r?.errorMessage,r?.errorCode);try{return await Promise.race([e,new Promise((o,s)=>{n=()=>{s(i)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var Bf=Symbol.for("@achingbrain/uint8arraylist");function Cf(e,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let r=0;for(let n of e){let i=r+n.byteLength;if(t<i)return{buf:n,index:t-r};r=i}throw new RangeError("index is out of bounds")}function En(e){return!!e?.[Bf]}var Bt=class e{bufs;length;[Bf]=!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 r=0;for(let n of t)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(En(n))r+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...t){this.prependAll(t)}prependAll(t){let r=0;for(let n of t.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(En(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(t){let r=Cf(this.bufs,t);return r.buf[r.index]}set(t,r){let n=Cf(this.bufs,t);n.buf[n.index]=r}write(t,r=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(r+n,t[n]);else if(En(t))for(let n=0;n<t.length;n++)this.set(r+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,r){let{bufs:n,length:i}=this._subList(t,r);return Ct(n,i)}subarray(t,r){let{bufs:n,length:i}=this._subList(t,r);return n.length===1?n[0]:Ct(n,i)}sublist(t,r){let{bufs:n,length:i}=this._subList(t,r),o=new e;return o.length=i,o.bufs=[...n],o}_subList(t,r){if(t=t??0,r=r??this.length,t<0&&(t=this.length+t),r<0&&(r=this.length+r),t<0||r>this.length)throw new RangeError("index is out of bounds");if(t===r)return{bufs:[],length:0};if(t===0&&r===this.length)return{bufs:this.bufs,length:this.length};let n=[],i=0;for(let o=0;o<this.bufs.length;o++){let s=this.bufs[o],a=i,c=a+s.byteLength;if(i=c,t>=c)continue;let u=t>=a&&t<c,f=r>a&&r<=c;if(u&&f){if(t===a&&r===c){n.push(s);break}let l=t-a;n.push(s.subarray(l,l+(r-t)));break}if(u){if(t===0){n.push(s);continue}n.push(s.subarray(t-a));continue}if(f){if(r===c){n.push(s);break}n.push(s.subarray(0,r-a));break}n.push(s)}return{bufs:n,length:r-t}}indexOf(t,r=0){if(!En(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(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),t.length===0)return r>this.length?this.length:r;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let o=256,s=new Int32Array(o);for(let l=0;l<o;l++)s[l]=-1;for(let l=0;l<i;l++)s[n[l]]=l;let a=s,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=r;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let y=this.get(l+d);if(n[d]!==y){f=Math.max(1,d-a[y]);break}}if(f===0)return l}return-1}getInt8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(t,r){let n=Vt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,t)}getInt16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(t,r,n){let i=ot(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,r,n),this.write(i,t)}getInt32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(t,r,n){let i=ot(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,r,n),this.write(i,t)}getBigInt64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(t,r,n){let i=ot(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,r,n),this.write(i,t)}getUint8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(t,r){let n=Vt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,t)}getUint16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(t,r,n){let i=ot(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,r,n),this.write(i,t)}getUint32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(t,r,n){let i=ot(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,r,n),this.write(i,t)}getBigUint64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(t,r,n){let i=ot(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,r,n),this.write(i,t)}getFloat32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(t,r,n){let i=ot(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,r,n),this.write(i,t)}getFloat64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(t,r,n){let i=ot(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,r,n),this.write(i,t)}equals(t){if(t==null||!(t instanceof e)||t.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!Kt(this.bufs[r],t.bufs[r]))return!1;return!0}static fromUint8Arrays(t,r){let n=new e;return n.bufs=t,r==null&&(r=t.reduce((i,o)=>i+o.byteLength,0)),n.length=r,n}};function If(e){if(e!=null){if(typeof e[Symbol.iterator]=="function")return e[Symbol.iterator]();if(typeof e[Symbol.asyncIterator]=="function")return e[Symbol.asyncIterator]();if(typeof e.next=="function")return e}throw new Error("argument is not an iterator or iterable")}function Tf(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}function mo(e,t){let r=If(e).return?.();Tf(r)&&r.catch(n=>{t.error("could not cause iterator to return",n)})}var Jy="ERR_STREAM_RESET",tm="ERR_SINK_INVALID_STATE",em=5e3;function Ga(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}var go=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;constructor(t){this.sinkController=new AbortController,this.sinkEnd=kt(),this.closed=kt(),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=mr({onEnd:r=>{r!=null?this.log.trace("source ended with error",r):this.log.trace("source ended"),this.onSourceEnd(r)}}),this.sink=this.sink.bind(this)}async sink(t){if(this.writeStatus!=="ready")throw new W(`writable end state is "${this.writeStatus}" not "ready"`,tm);try{this.writeStatus="writing";let r={signal:this.sinkController.signal};if(this.direction==="outbound"){let i=this.sendNewStream(r);Ga(i)&&await i}let n=()=>{mo(t,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let i of t){i=i instanceof Uint8Array?new Bt(i):i;let o=this.sendData(i,r);Ga(o)&&await o}}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(r){throw this.log.trace("sink ended with error, calling abort with error",r),this.abort(r),r}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(t){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(t){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(t){this.log.trace("closing gracefully"),this.status="closing",await Promise.all([this.closeRead(t),this.closeWrite(t)]),await gr(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 r=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)),r==="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 gr(this.sink([]),t.signal)),this.writeStatus==="writing"&&await new Promise((r,n)=>{queueMicrotask(()=>{this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),gr(this.sinkEnd.promise,t.signal).then(r,n)})}),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 r=this.sendReset();Ga(r)&&r.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 W("stream reset",Jy);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 xo(e){return e[Symbol.asyncIterator]!=null}var bo=e=>{let t=ee(e),r=Vt(t);return pr(e,r),bo.bytes=t,r};bo.bytes=0;function xr(e,t){t=t??{};let r=t.lengthEncoder??bo;function*n(i){let o=r(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return xo(e)?async function*(){for await(let i of e)yield*n(i)}():function*(){for(let i of e)yield*n(i)}()}xr.single=(e,t)=>{t=t??{};let r=t.lengthEncoder??bo;return new Bt(r(e.byteLength),e)};var Sn=Jt(Rf(),1);var nm=8,im=1024*1024*4,Mr;(function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(Mr||(Mr={}));var Wa=e=>{let t=we(e);return Wa.bytes=ee(t),t};Wa.bytes=0;function Fr(e,t){let r=new Bt,n=Mr.LENGTH,i=-1,o=t?.lengthDecoder??Wa,s=t?.maxLengthLength??nm,a=t?.maxDataLength??im;function*c(){for(;r.byteLength>0;){if(n===Mr.LENGTH)try{if(i=o(r),i<0)throw(0,Sn.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,Sn.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=o.bytes;r.consume(u),t?.onLength!=null&&t.onLength(i),n=Mr.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>s)throw(0,Sn.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===Mr.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),t?.onData!=null&&t.onData(u),yield u,n=Mr.LENGTH}}}return xo(e)?async function*(){for await(let u of e)r.append(u),yield*c();if(r.byteLength>0)throw(0,Sn.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of e)r.append(u),yield*c();if(r.byteLength>0)throw(0,Sn.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Fr.fromReader=(e,t)=>{let r=1,n=async function*(){for(;;)try{let{done:o,value:s}=await e.next(r);if(o===!0)return;s!=null&&(yield s)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{r=1}}();return Fr(n,{...t??{},onLength:o=>{r=o}})};var om=e=>{let t=e.on||e.addListener||e.addEventListener,r=e.off||e.removeListener||e.removeEventListener;if(!t||!r)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}};function sm(e,t,r){let n,i=new Promise((o,s)=>{if(r={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:u,removeListener:f}=om(e),l=(...y)=>{let h=r.multiArgs?y:y[0];r.filter&&!r.filter(h)||(c.push(h),r.count===c.length&&(n(),o(c)))},d=y=>{n(),s(y)};n=()=>{for(let y of a)f(y,l);for(let y of r.rejectionEvents)f(y,d)};for(let y of a)u(y,l);for(let y of r.rejectionEvents)u(y,d);r.signal&&r.signal.addEventListener("abort",()=>{d(r.signal.reason)},{once:!0}),r.resolveImmediately&&o(c)});if(i.cancel=n,typeof r.timeout=="number"){let o=Or(i,{milliseconds:r.timeout});return o.cancel=n,o}return i}function $a(e,t,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=sm(e,t,r),i=n.then(o=>o[0]);return i.cancel=n.cancel,i}var Ya=new Float32Array([-0]),br=new Uint8Array(Ya.buffer);function Nf(e,t,r){Ya[0]=e,t[r]=br[0],t[r+1]=br[1],t[r+2]=br[2],t[r+3]=br[3]}function Pf(e,t){return br[0]=e[t],br[1]=e[t+1],br[2]=e[t+2],br[3]=e[t+3],Ya[0]}var Xa=new Float64Array([-0]),re=new Uint8Array(Xa.buffer);function Uf(e,t,r){Xa[0]=e,t[r]=re[0],t[r+1]=re[1],t[r+2]=re[2],t[r+3]=re[3],t[r+4]=re[4],t[r+5]=re[5],t[r+6]=re[6],t[r+7]=re[7]}function Of(e,t){return re[0]=e[t],re[1]=e[t+1],re[2]=e[t+2],re[3]=e[t+3],re[4]=e[t+4],re[5]=e[t+5],re[6]=e[t+6],re[7]=e[t+7],Xa[0]}var am=BigInt(Number.MAX_SAFE_INTEGER),cm=BigInt(Number.MIN_SAFE_INTEGER),oe=class e{lo;hi;constructor(t,r){this.lo=t|0,this.hi=r|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+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 r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(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,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?t<16384?t<128?1:2:t<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return Vr;if(t<am&&t>cm)return this.fromNumber(Number(t));let r=t<0n;r&&(t=-t);let n=t>>32n,i=t-(n<<32n);return r&&(n=~n|0n,i=~i|0n,++i>Kf&&(i=0n,++n>Kf&&(n=0n))),new e(Number(i),Number(n))}static fromNumber(t){if(t===0)return Vr;let r=t<0;r&&(t=-t);let n=t>>>0,i=(t-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new e(n,i)}static from(t){return typeof t=="number"?e.fromNumber(t):typeof t=="bigint"?e.fromBigInt(t):typeof t=="string"?e.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new e(t.low>>>0,t.high>>>0):Vr}},Vr=new oe(0,0);Vr.toBigInt=function(){return 0n};Vr.zzEncode=Vr.zzDecode=function(){return this};Vr.length=function(){return 1};var Kf=4294967296n;function Mf(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:(r&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Ff(e,t,r){if(r-t<1)return"";let i,o=[],s=0,a;for(;t<r;)a=e[t++],a<128?o[s++]=a:a>191&&a<224?o[s++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,o[s++]=55296+(a>>10),o[s++]=56320+(a&1023)):o[s++]=(a&15)<<12|(e[t++]&63)<<6|e[t++]&63,s>8191&&((i??(i=[])).push(String.fromCharCode.apply(String,o)),s=0);return i!=null?(s>0&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))}function Za(e,t,r){let n=r,i,o;for(let s=0;s<e.length;++s)i=e.charCodeAt(s),i<128?t[r++]=i:i<2048?(t[r++]=i>>6|192,t[r++]=i&63|128):(i&64512)===55296&&((o=e.charCodeAt(s+1))&64512)===56320?(i=65536+((i&1023)<<10)+(o&1023),++s,t[r++]=i>>18|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=i&63|128):(t[r++]=i>>12|224,t[r++]=i>>6&63|128,t[r++]=i&63|128);return r-n}function ve(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function wo(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}var Qa=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,ve(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 ve(this,4);return wo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ve(this,4);return wo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ve(this,4);let t=Pf(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw ve(this,4);let t=Of(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),r=this.pos,n=this.pos+t;if(n>this.len)throw ve(this,t);return this.pos+=t,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let t=this.bytes();return Ff(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw ve(this,t);this.pos+=t}else do if(this.pos>=this.len)throw ve(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 oe(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*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;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw ve(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,t}if(this.len-this.pos>4){for(;r<5;++r)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;r<5;++r){if(this.pos>=this.len)throw ve(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ve(this,8);let t=wo(this.buf,this.pos+=4),r=wo(this.buf,this.pos+=4);return new oe(t,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){return this.readLongVarint().toNumber(!0)}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 ja(e){return new Qa(e instanceof Uint8Array?e:e.subarray())}function Ee(e,t){let r=ja(e);return t.decode(r)}function Ja(e){let t=e??8192,r=t>>>1,n,i=t;return function(s){if(s<1||s>r)return Vt(s);i+s>t&&(n=Vt(t),i=0);let a=n.subarray(i,i+=s);return i&7&&(i=(i|7)+1),a}}var Hr=class{fn;len;next;val;constructor(t,r,n){this.fn=t,this.len=r,this.next=void 0,this.val=n}};function tc(){}var rc=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},um=Ja();function fm(e){return globalThis.Buffer!=null?Vt(e):um(e)}var di=class{len;head;tail;states;constructor(){this.len=0,this.head=new Hr(tc,0,0),this.tail=this.head,this.states=null}_push(t,r,n){return this.tail=this.tail.next=new Hr(t,r,n),this.len+=r,this}uint32(t){return this.len+=(this.tail=this.tail.next=new nc((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(li,10,oe.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let r=oe.fromBigInt(t);return this._push(li,r.length(),r)}uint64Number(t){let r=oe.fromNumber(t);return this._push(li,r.length(),r)}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 r=oe.fromBigInt(t).zzEncode();return this._push(li,r.length(),r)}sint64Number(t){let r=oe.fromNumber(t).zzEncode();return this._push(li,r.length(),r)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ec,1,t?1:0)}fixed32(t){return this._push(hi,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let r=oe.fromBigInt(t);return this._push(hi,4,r.lo)._push(hi,4,r.hi)}fixed64Number(t){let r=oe.fromNumber(t);return this._push(hi,4,r.lo)._push(hi,4,r.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(Nf,4,t)}double(t){return this._push(Uf,8,t)}bytes(t){let r=t.length>>>0;return r===0?this._push(ec,1,0):this.uint32(r)._push(hm,r,t)}string(t){let r=Mf(t);return r!==0?this.uint32(r)._push(Za,r,t):this._push(ec,1,0)}fork(){return this.states=new rc(this),this.head=this.tail=new Hr(tc,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 Hr(tc,0,0),this.len=0),this}ldelim(){let t=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=r,this.len+=n),this}finish(){let t=this.head.next,r=fm(this.len),n=0;for(;t!=null;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}};function ec(e,t,r){t[r]=e&255}function lm(e,t,r){for(;e>127;)t[r++]=e&127|128,e>>>=7;t[r]=e}var nc=class extends Hr{next;constructor(t,r){super(lm,t,r),this.next=void 0}};function li(e,t,r){for(;e.hi!==0;)t[r++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=e.lo&127|128,e.lo=e.lo>>>7;t[r++]=e.lo}function hi(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function hm(e,t,r){t.set(e,r)}globalThis.Buffer!=null&&(di.prototype.bytes=function(e){let t=e.length>>>0;return this.uint32(t),t>0&&this._push(dm,t,e),this},di.prototype.string=function(e){let t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(pm,t,e),this});function dm(e,t,r){t.set(e,r)}function pm(e,t,r){e.length<40?Za(e,t,r):t.utf8Write!=null?t.utf8Write(e,r):t.set(wt(e),r)}function ic(){return new di}function Se(e,t){let r=ic();return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var An;(function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(An||(An={}));function vo(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function qr(e){function t(i){if(e[i.toString()]==null)throw new Error("Invalid enum value");return e[i]}let r=function(o,s){let a=t(o);s.int32(a)},n=function(o){let s=o.int32();return t(s)};return vo("enum",An.VARINT,r,n)}function Ae(e,t){return vo("message",An.LENGTH_DELIMITED,e,t)}var se;(function(e){let t;(function(i){i.FIN="FIN",i.STOP_SENDING="STOP_SENDING",i.RESET="RESET",i.FIN_ACK="FIN_ACK"})(t=e.Flag||(e.Flag={}));let r;(function(i){i[i.FIN=0]="FIN",i[i.STOP_SENDING=1]="STOP_SENDING",i[i.RESET=2]="RESET",i[i.FIN_ACK=3]="FIN_ACK"})(r||(r={})),function(i){i.codec=()=>qr(r)}(t=e.Flag||(e.Flag={}));let n;e.codec=()=>(n==null&&(n=Ae((i,o,s={})=>{s.lengthDelimited!==!1&&o.fork(),i.flag!=null&&(o.uint32(8),e.Flag.codec().encode(i.flag,o)),i.message!=null&&(o.uint32(18),o.bytes(i.message)),s.lengthDelimited!==!1&&o.ldelim()},(i,o)=>{let s={},a=o==null?i.len:i.pos+o;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:s.flag=e.Flag.codec().decode(i);break;case 2:s.message=i.bytes();break;default:i.skipType(c&7);break}}return s})),n),e.encode=i=>Se(i,e.codec()),e.decode=i=>Ee(i,e.codec())})(se||(se={}));var ym=16*1024*1024,mm=30*1e3,gm=5,xm=2,bm=16*1024,wm=5e3,vm=5e3,oc=class extends go{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;constructor(t){let r=t.onEnd;switch(t.onEnd=i=>{this.log.trace("readable and writeable ends closed",this.status),Promise.resolve(async()=>{if(!(this.timeline.abort!=null||this.timeline.reset!==null))try{await Or(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(o){this.log.error("error receiving FIN_ACK",o)}}).then(()=>{this.incomingData.end(),r?.(i)}).catch(o=>{this.log.error("error ending stream",o)})},super(t),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=mr(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??mm,this.maxBufferedAmount=t.maxBufferedAmount??ym,this.maxMessageSize=(t.maxMessageSize??bm)-gm-xm,this.receiveFinAck=kt(),this.finAckTimeout=t.closeTimeout??wm,this.openTimeout=t.openTimeout??vm,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 W("Unknown datachannel state","ERR_INVALID_STATE")}this.channel.onopen=i=>{this.timeline.open=new Date().getTime()},this.channel.onclose=i=>{this.receiveFinAck.resolve(),this.close().catch(o=>{this.log.error("error closing stream after channel closed",o)})},this.channel.onerror=i=>{let o=i.error;this.abort(o)},this.channel.onmessage=async i=>{let{data:o}=i;o===null||o.byteLength===0||this.incomingData.push(new Uint8Array(o,0,o.byteLength))};let n=this;Promise.resolve().then(async()=>{for await(let i of Fr(this.incomingData)){let o=n.processIncomingProtobuf(i);o!=null&&n.sourcePush(new Bt(o))}}).catch(i=>{this.log.error("error processing incoming data channel messages",i)})}sendNewStream(){}async _sendMessage(t,r=!0){if(r&&this.channel.bufferedAmount>this.maxBufferedAmount)try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await $a(this.channel,"bufferedamountlow",{timeout:this.bufferedAmountLowEventTimeout})}catch(n){throw n instanceof wn?new W(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`,"ERR_BUFFER_CLEAR_TIMEOUT"):n}if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new W(`Invalid datachannel state - ${this.channel.readyState}`,"ERR_INVALID_STATE");this.channel.readyState!=="open"&&(this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await $a(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 r=Math.min(t.byteLength,this.maxMessageSize),n=t.subarray(0,r),i=se.encode({message:n}),o=xr.single(i);await this._sendMessage(o),t.consume(r)}}async sendReset(){await this._sendFlag(se.Flag.RESET)}async sendCloseWrite(t){if(await this._sendFlag(se.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await gr(this.receiveFinAck.promise,t?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorCode:"ERR_FIN_ACK_NOT_RECEIVED"})}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(se.Flag.STOP_SENDING)}processIncomingProtobuf(t){let r=se.decode(t);if(r.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',r.flag,this.writeStatus,this.readStatus),r.flag===se.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(se.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),r.flag===se.Flag.RESET&&this.reset(),r.flag===se.Flag.STOP_SENDING&&this.remoteCloseRead(),r.flag===se.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),this.readStatus==="ready")return r.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 r=se.encode({flag:t}),n=xr.single(r);try{return await this._sendMessage(n,!1),!0}catch(i){this.log.error("could not send flag %s",t.toString(),i)}return!1}};function Dn(e){let{channel:t,direction:r}=e;return new oc({id:r==="inbound"?`i${t.id}`:`r${t.id}`,log:e.logger.forComponent(`libp2p:webrtc:stream:${r}:${t.id}`),...e})}var Hf="/webrtc",zr=class{protocol;peerConnection;bufferedStreams=[];metrics;dataChannelOptions;components;log;constructor(t,r){this.components=t,this.peerConnection=r.peerConnection,this.metrics=r.metrics,this.protocol=r.protocol??Hf,this.dataChannelOptions=r.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 i={},o=Dn({channel:n,direction:"inbound",onEnd:s=>{i.onEnd(s)},logger:t.logger,...this.dataChannelOptions});i.stream=o,i.channel=n,i.onEnd=()=>{this.bufferedStreams=this.bufferedStreams.filter(s=>s.stream.id!==o.id)},this.bufferedStreams.push(i)}}createStreamMuxer(t){return new sc(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},sc=class{init;streams;protocol;log;peerConnection;dataChannelOptions;metrics;logger;constructor(t,r){this.init=r,this.log=t.logger.forComponent("libp2p:webrtc:muxer"),this.logger=t.logger,this.streams=r.streams.map(n=>n.stream),this.peerConnection=r.peerConnection,this.protocol=r.protocol??Hf,this.metrics=r.metrics,this.dataChannelOptions=r.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 i=Dn({channel:n,direction:"inbound",onEnd:()=>{this.log("incoming channel %s ended with state %s",n.id,n.readyState),this.#t(i,n)},logger:this.logger,...this.dataChannelOptions});this.streams.push(i),this.metrics?.increment({incoming_stream:!0}),r?.onIncomingStream?.(i)},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,r){this.log.trace("stream %s %s %s onEnd",t.direction,t.id,t.protocol),Df(r,`${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 r=>r.close(t)))}catch(r){this.abort(r)}}abort(t){for(let r of this.streams)r.abort(t)}source=lo();sink=ho;newStream(){let t=this.peerConnection.createDataChannel("");this.log.trace("opened outgoing datachannel with channel id %s",t.id);let r=Dn({channel:t,direction:"outbound",onEnd:()=>{this.log("outgoing channel %s ended with state %s",t.id,t.readyState),this.#t(r,t)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(r),this.metrics?.increment({outgoing_stream:!0}),r}};var Cn=globalThis.RTCPeerConnection,Eo=globalThis.RTCSessionDescription,qf=globalThis.RTCIceCandidate;var ac=class{needNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.needNext=kt(),this.needNext.resolve(),this.haveNext=kt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("Have next but next was undefined");let t=this.nextResult;return this.nextResult=void 0,this.needNext.resolve(),this.needNext=kt(),t}async throw(t){return this.ended=!0,t!=null&&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,r){await this._push(t,r)}async end(t,r){t!=null?await this.throw(t):await this._push(void 0,r)}async _push(t,r){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");this.nextResult!=null&&await this.needNext.promise,t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=kt(),await gr(this.needNext.promise,r?.signal,r)}};function zf(){return new ac}var So=class extends Error{code;constructor(t,r){super(t),this.code=r}},cc=class extends So{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted"}};function Gf(e,t){let r=zf();e.sink(r).catch(async s=>{await r.end(s)}),e.sink=async s=>{for await(let a of s)await r.push(a);await r.end()};let n=e.source;e.source[Symbol.iterator]!=null?n=e.source[Symbol.iterator]():e.source[Symbol.asyncIterator]!=null&&(n=e.source[Symbol.asyncIterator]());let i=new Bt;return{read:async(s,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new cc("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(s==null){let{done:l,value:d}=await Promise.race([n.next(),u]);return l===!0?new Bt:d}for(;i.byteLength<s;){let{value:l,done:d}=await Promise.race([n.next(),u]);if(d===!0)throw new So("unexpected end of input","ERR_UNEXPECTED_EOF");i.append(l)}let f=i.sublist(0,s);return i.consume(s),f}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(s,a)=>{a?.signal?.throwIfAborted(),s instanceof Uint8Array?await r.push(s,a):await r.push(s.subarray(),a)},unwrap:()=>{if(i.byteLength>0){let s=e.source;e.source=async function*(){t?.yieldBytes===!1?yield i:yield*i,yield*s}()}return e}}}var Ao=class extends Error{code;constructor(t,r){super(t),this.code=r}},Wf=e=>we(e);Wf.bytes=0;function pi(e,t={}){let r=Gf(e,t);return t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=ee(t.maxDataLength)),{read:async i=>{let o=-1,s=new Bt,a=t?.lengthDecoder??Wf;for(;;){s.append(await r.read(1,i));try{o=a(s)}catch(c){if(c instanceof RangeError)continue;throw c}if(t?.maxLengthLength!=null&&s.byteLength>t.maxLengthLength)throw new Ao("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(o>-1)break}if(t?.maxDataLength!=null&&o>t.maxDataLength)throw new Ao("message length too long","ERR_MSG_DATA_TOO_LONG");return r.read(o,i)},write:async(i,o)=>{await r.write(xr.single(i,t),o)},writeV:async(i,o)=>{let s=new Bt(...i.map(a=>xr.single(a,t)));await r.write(s,o)},unwrap:()=>r.unwrap()}}function Do(e,t){let r=pi(e,t),n={read:async(i,o)=>{let s=await r.read(o);return i.decode(s)},write:async(i,o,s)=>{await r.write(o.encode(i),s)},writeV:async(i,o,s)=>{await r.writeV(i.map(a=>o.encode(a)),s)},pb:i=>({read:async o=>n.read(i,o),write:async(o,s)=>n.write(o,i,s),writeV:async(o,s)=>n.writeV(o,i,s),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}var ae;(function(e){let t;(function(i){i.SDP_OFFER="SDP_OFFER",i.SDP_ANSWER="SDP_ANSWER",i.ICE_CANDIDATE="ICE_CANDIDATE"})(t=e.Type||(e.Type={}));let r;(function(i){i[i.SDP_OFFER=0]="SDP_OFFER",i[i.SDP_ANSWER=1]="SDP_ANSWER",i[i.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(r||(r={})),function(i){i.codec=()=>qr(r)}(t=e.Type||(e.Type={}));let n;e.codec=()=>(n==null&&(n=Ae((i,o,s={})=>{s.lengthDelimited!==!1&&o.fork(),i.type!=null&&(o.uint32(8),e.Type.codec().encode(i.type,o)),i.data!=null&&(o.uint32(18),o.string(i.data)),s.lengthDelimited!==!1&&o.ldelim()},(i,o)=>{let s={},a=o==null?i.len:i.pos+o;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:s.type=e.Type.codec().decode(i);break;case 2:s.data=i.string();break;default:i.skipType(c&7);break}}return s})),n),e.encode=i=>Se(i,e.codec()),e.decode=i=>Ee(i,e.codec())})(ae||(ae={}));function $f(e){let t=new globalThis.AbortController;function r(){t.abort();for(let o of e)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}for(let o of e){if(o?.aborted===!0){r();break}o?.addEventListener!=null&&o.addEventListener("abort",r)}function n(){for(let o of e)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}let i=t.signal;return i.clear=n,i}var Co=async(e,t,r,n)=>{let i=new AbortController;e.promise.then(()=>{i.abort()},()=>{i.abort()});let o=$f([i.signal,n.signal]),s=()=>{mo(r.unwrap().unwrap().source,n.log)};o.addEventListener("abort",s);try{for(;;){let a=await Promise.race([e.promise,r.read()]);if(a==null)break;if(a.type!==ae.Type.ICE_CANDIDATE)throw new W("ICE candidate message expected","ERR_NOT_ICE_CANDIDATE");let c=JSON.parse(a.data??"null");if(c===""||c===null){n.log.trace("end-of-candidates received");continue}let u=new qf(c);n.log.trace("%s received new ICE candidate",n.direction,u);try{await t.addIceCandidate(u)}catch(f){n.log.error("%s bad candidate received",n.direction,c,f)}}}catch(a){n.log.error("%s error parsing ICE candidate",n.direction,a)}finally{o.removeEventListener("abort",s),o.clear()}};function Bo(e,t){e[fi?"oniceconnectionstatechange":"onconnectionstatechange"]=r=>{switch(fi?e.iceConnectionState:e.connectionState){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new W("RTCPeerConnection was closed","ERR_CONNECTION_CLOSED_BEFORE_CONNECTED"));break;default:break}}}async function Yf({peerConnection:e,signal:t,metrics:r,multiaddr:n,connectionManager:i,transportManager:o,log:s}){let{baseAddr:a}=Xf(n);r?.dialerEvents.increment({open:!0}),s.trace("dialing base address: %a",a);let c=a.getPeerId();if(c==null)throw new W("Relay peer was missing","ERR_INVALID_ADDRESS");let u=i.getConnections(Ur(c)),f,l=!1;u.length===0?(f=await o.dial(a,{signal:t}),l=!0):f=u[0];try{let d=await f.newStream(Io,{signal:t,runOnTransientConnection:!0}),y=Do(d).pb(ae),h=kt(),p=()=>{h.reject(new W("SDP handshake aborted","ERR_SDP_HANDSHAKE_ABORTED"))};try{Bo(e,h),t?.addEventListener("abort",p);let m=e.createDataChannel("init");e.onicecandidate=({candidate:A})=>{let v=JSON.stringify(A?.toJSON()??null);s.trace("initiator sending ICE candidate %s",v),y.write({type:ae.Type.ICE_CANDIDATE,data:v},{signal:t}).catch(E=>{s.error("error sending ICE candidate",E)})},e.onicecandidateerror=A=>{s("initiator ICE candidate error",A)};let g=await e.createOffer();s.trace("initiator send SDP offer %s",g.sdp),await y.write({type:ae.Type.SDP_OFFER,data:g.sdp},{signal:t}),await e.setLocalDescription(g).catch(A=>{throw s.error("could not execute setLocalDescription",A),new W("Failed to set localDescription","ERR_SDP_HANDSHAKE_FAILED")});let b=await y.read({signal:t});if(b.type!==ae.Type.SDP_ANSWER)throw new W("remote should send an SDP answer","ERR_SDP_HANDSHAKE_FAILED");s.trace("initiator receive SDP answer %s",b.data);let x=new Eo({type:"answer",sdp:b.data});return await e.setRemoteDescription(x).catch(A=>{throw s.error("could not execute setRemoteDescription",A),new W("Failed to set remoteDescription","ERR_SDP_HANDSHAKE_FAILED")}),s.trace("initiator read candidates until connected"),await Co(h,e,y,{direction:"initiator",signal:t,log:s}),s.trace("initiator connected, closing init channel"),m.close(),s.trace("initiator closing signalling stream"),await y.unwrap().unwrap().close({signal:t}),s.trace("initiator connected to remote address %s",n),{remoteAddress:n}}catch(m){throw e.close(),d.abort(m),m}finally{t?.removeEventListener("abort",p),e.onicecandidate=null,e.onicecandidateerror=null}}finally{if(l)try{await f.close({signal:t})}catch(d){f.abort(d)}}}var Em=q("dns4"),Sm=q("dns6"),Am=q("dnsaddr"),Gr=Ot(q("dns"),Am,Em,Sm),ko=Ot(q("ip4"),q("ip6")),Bn=Ot(X(ko,q("tcp")),X(Gr,q("tcp"))),Ro=X(ko,q("udp")),Dm=X(Ro,q("utp")),Cm=X(Ro,q("quic")),Bm=X(Ro,q("quic-v1")),uc=Ot(X(Bn,q("ws")),X(Gr,q("ws"))),To=Ot(X(uc,q("p2p")),uc),fc=Ot(X(Bn,q("wss")),X(Gr,q("wss")),X(Bn,q("tls"),q("ws")),X(Gr,q("tls"),q("ws"))),_o=Ot(X(fc,q("p2p")),fc),lc=Ot(X(Bn,q("http")),X(ko,q("http")),X(Gr,q("http"))),hc=Ot(X(Bn,q("https")),X(ko,q("https")),X(Gr,q("https"))),Zf=X(Ro,q("webrtc-direct"),q("certhash")),Jf=Ot(X(Zf,q("p2p")),Zf),Qf=X(Bm,q("webtransport"),q("certhash"),q("certhash")),tl=Ot(X(Qf,q("p2p")),Qf),el=Ot(X(To,q("p2p-webrtc-star"),q("p2p")),X(_o,q("p2p-webrtc-star"),q("p2p")),X(To,q("p2p-webrtc-star")),X(_o,q("p2p-webrtc-star"))),gA=Ot(X(To,q("p2p-websocket-star"),q("p2p")),X(_o,q("p2p-websocket-star"),q("p2p")),X(To,q("p2p-websocket-star")),X(_o,q("p2p-websocket-star"))),rl=Ot(X(lc,q("p2p-webrtc-direct"),q("p2p")),X(hc,q("p2p-webrtc-direct"),q("p2p")),X(lc,q("p2p-webrtc-direct")),X(hc,q("p2p-webrtc-direct"))),Wr=Ot(uc,fc,lc,hc,el,rl,Bn,Dm,Cm,Gr,Jf,tl),xA=Ot(X(Wr,q("p2p-stardust"),q("p2p")),X(Wr,q("p2p-stardust"))),wr=Ot(X(Wr,q("p2p")),el,rl,Jf,tl,q("p2p")),jf=Ot(X(wr,q("p2p-circuit"),wr),X(wr,q("p2p-circuit")),X(q("p2p-circuit"),wr),X(Wr,q("p2p-circuit")),X(q("p2p-circuit"),Wr),q("p2p-circuit")),nl=()=>Ot(X(jf,nl),jf),Qe=nl(),bA=Ot(X(Qe,wr,Qe),X(wr,Qe),X(Qe,wr),Qe,wr);var wA=Ot(X(Qe,q("webrtc"),q("p2p")),X(Qe,q("webrtc")),X(Wr,q("webrtc"),q("p2p")),X(Wr,q("webrtc")),q("webrtc"));function il(e){function t(r){let n;try{n=Ze(r)}catch{return!1}let i=e(n.protoNames());return i===null?!1:i===!0||i===!1?i:i.length===0}return t}function X(...e){function t(r){if(r.length<e.length)return null;let n=r;return e.some(i=>(n=typeof i=="function"?i().partialMatch(r):i.partialMatch(r),Array.isArray(n)&&(r=n),n===null)),n}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:il(t),partialMatch:t}}function Ot(...e){function t(n){let i=null;return e.some(o=>{let s=typeof o=="function"?o().partialMatch(n):o.partialMatch(n);return s!=null?(i=s,!0):!1}),i}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:il(t),partialMatch:t}}function q(e){let t=e;function r(i){let o;try{o=Ze(i)}catch{return!1}let s=o.protoNames();return s.length===1&&s[0]===t}function n(i){return i.length===0?null:i[0]===t?i.slice(1):null}return{toString:function(){return t},matches:r,partialMatch:n}}var Lo=class extends Xi{peerId;transportManager;shutdownController;constructor(t,r){super(),this.peerId=t.peerId,this.transportManager=t.transportManager,this.shutdownController=r.shutdownController}async listen(){this.safeDispatchEvent("listening",{})}getAddrs(){return this.transportManager.getListeners().filter(t=>t!==this).map(t=>t.getAddrs().filter(r=>Qe.matches(r)).map(r=>r.encapsulate(`/webrtc/p2p/${this.peerId}`))).flat()}async close(){this.shutdownController.abort(),this.safeDispatchEvent("close",{})}};async function ol({peerConnection:e,stream:t,signal:r,connection:n,log:i}){i.trace("new inbound signaling stream");let o=Do(t).pb(ae);try{let a=kt(),c=kt();r.onabort=()=>{a.reject(new W("Timed out while trying to connect","ERR_TIMEOUT"))},e.onicecandidate=({candidate:d})=>{c.promise.then(async()=>{let y=JSON.stringify(d?.toJSON()??null);i.trace("recipient sending ICE candidate %s",y),await o.write({type:ae.Type.ICE_CANDIDATE,data:y},{signal:r})},y=>{i.error("cannot set candidate since sending answer failed",y),a.reject(y)})},Bo(e,a);let u=await o.read({signal:r});if(u.type!==ae.Type.SDP_OFFER)throw new W(`expected message type SDP_OFFER, received: ${u.type??"undefined"} `,"ERR_SDP_HANDSHAKE_FAILED");i.trace("recipient receive SDP offer %s",u.data);let f=new Eo({type:"offer",sdp:u.data});await e.setRemoteDescription(f).catch(d=>{throw i.error("could not execute setRemoteDescription",d),new W("Failed to set remoteDescription","ERR_SDP_HANDSHAKE_FAILED")});let l=await e.createAnswer().catch(d=>{throw i.error("could not execute createAnswer",d),c.reject(d),new W("Failed to create answer","ERR_SDP_HANDSHAKE_FAILED")});i.trace("recipient send SDP answer %s",l.sdp),await o.write({type:ae.Type.SDP_ANSWER,data:l.sdp},{signal:r}),await e.setLocalDescription(l).catch(d=>{throw i.error("could not execute setLocalDescription",d),c.reject(d),new W("Failed to set localDescription","ERR_SDP_HANDSHAKE_FAILED")}),c.resolve(),i.trace("recipient read candidates until connected"),await Co(a,e,o,{direction:"recipient",signal:r,log:i}),i.trace("recipient connected, closing signaling stream"),await o.unwrap().unwrap().close({signal:r})}catch(a){if(e.connectionState!=="connected")throw i.error("error while handling signaling stream from peer %a",n.remoteAddr,a),e.close(),a;i("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",n.remoteAddr,a)}let s=Ze(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return i.trace("recipient connected to remote address %s",s),{remoteAddress:s}}var Im="/webrtc",Tm="/p2p-circuit",Io="/webrtc-signaling/0.0.1",_m=30*1e3,No=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,r={}){this.components=t,this.init=r,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,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"})})}isStarted(){return this._started}async start(){await this.components.registrar.handle(Io,t=>{this._onProtocol(t).catch(r=>{this.log.error("failed to handle incoming connect from %p",t.connection.remotePeer,r)})},{runOnTransientConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(Io),this._started=!1}createListener(t){return new Lo(this.components,{shutdownController:this.shutdownController})}[Symbol.toStringTag]="@libp2p/webrtc";[Yi]=!0;filter(t){return t.filter(pf.exactMatch)}async dial(t,r){this.log.trace("dialing address: %a",t);let n=new Cn(this.init.rtcConfiguration),i=new zr(this.components,{peerConnection:n,dataChannelOptions:this.init.dataChannel}),{remoteAddress:o}=await Yf({peerConnection:n,multiaddr:t,dataChannelOptions:this.init.dataChannel,signal:r.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log}),s=new Kr(this.components,{peerConnection:n,timeline:{open:Date.now()},remoteAddr:o,metrics:this.metrics?.dialerEvents}),a=await r.upgrader.upgradeOutbound(s,{skipProtection:!0,skipEncryption:!0,muxerFactory:i});return this._closeOnShutdown(n,s),a}async _onProtocol({connection:t,stream:r}){let n=AbortSignal.timeout(this.init.inboundConnectionTimeout??_m),i=new Cn(this.init.rtcConfiguration),o=new zr(this.components,{peerConnection:i,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:s}=await ol({peerConnection:i,connection:t,stream:r,signal:n,log:this.log}),a=new Kr(this.components,{peerConnection:i,timeline:{open:new Date().getTime()},remoteAddr:s,metrics:this.metrics?.listenerEvents});this._closeOnShutdown(i,a),await this.components.upgrader.upgradeInbound(a,{skipEncryption:!0,skipProtection:!0,muxerFactory:o}),await r.close({signal:n})}catch(s){throw r.abort(s),s}}_closeOnShutdown(t,r){let n=()=>{r.close().catch(i=>{this.log.error("could not close WebRTCMultiaddrConnection",i)})};this.shutdownController.signal.addEventListener("abort",n),t.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function Xf(e){let t=e.toString().split(Im+"/");if(t.length!==2)throw new W("webrtc protocol was not present in multiaddr",fe.ERR_INVALID_MULTIADDR);if(!t[0].includes(Tm))throw new W("p2p-circuit protocol was not present in multiaddr",fe.ERR_INVALID_MULTIADDR);let r=Ze(t[0]),i=Ze("/"+t[1]).getPeerId();if(i==null)throw new W("destination peer id was missing",fe.ERR_INVALID_MULTIADDR);let o=r.protos().pop();if(o===void 0)throw new W("invalid multiaddr",fe.ERR_INVALID_MULTIADDR);return o.name!=="p2p"&&(r=r.encapsulate(`/p2p/${i}`)),{baseAddr:r,peerId:Ur(i)}}function dc(){let e=kt(),t=!1;return{sink:async r=>{if(t)throw new Error("already piped");t=!0,e.resolve(r)},source:async function*(){yield*await e.promise}()}}function sl(){let e=dc(),t=dc();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}function km(e){return e[Symbol.asyncIterator]!=null}function Rm(...e){let t=[];for(let r of e)km(r)||t.push(r);return t.length===e.length?function*(){for(let r of t)yield*r}():async function*(){let r=mr({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(e.map(async n=>{for await(let i of n)r.push(i)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var al=Rm;function cl(e,...t){if(e==null)throw new Error("Empty pipeline");if(pc(e)){let n=e;e=()=>n.source}else if(fl(e)||ul(e)){let n=e;e=()=>n}let r=[e,...t];if(r.length>1&&pc(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)pc(r[n])&&(r[n]=Nm(r[n]));return Lm(...r)}var Lm=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},ul=e=>e?.[Symbol.asyncIterator]!=null,fl=e=>e?.[Symbol.iterator]!=null,pc=e=>e==null?!1:e.sink!=null&&e.source!=null,Nm=e=>t=>{let r=e.sink(t);if(r?.then!=null){let n=mr({objectMode:!0});r.then(()=>{n.end()},s=>{n.end(s)});let i,o=e.source;if(ul(o))i=async function*(){yield*o,n.end()};else if(fl(o))i=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return al(n,i())}return e.source};var In=!!globalThis.process?.env?.DUMP_SESSION_KEYS;var Pm=e=>e instanceof Uint8Array;var je=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),ll=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),Um=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Um)throw new Error("Non little-endian hardware is not supported");function Po(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function Uo(e){if(typeof e=="string")e=Po(e);else if(Pm(e))e=e.slice();else throw new Error(`expected Uint8Array, got ${typeof e}`);return e}var Om=e=>Object.prototype.toString.call(e)==="[object Object]"&&e.constructor===Object;function hl(e,t){if(t!==void 0&&(typeof t!="object"||!Om(t)))throw new Error("options must be object or undefined");return Object.assign(e,t)}function $r(e,t){if(!(e instanceof Uint8Array))throw new Error("Uint8Array expected");if(typeof t=="number"&&e.length!==t)throw new Error(`Uint8Array length ${t} expected`)}function dl(e,t){if(e.length!==t.length)throw new Error("equalBytes: Different size of Uint8Arrays");let r=!0;for(let n=0;n<e.length;n++)r&&(r=e[n]===t[n]);return r}var yc=(e,t)=>(Object.assign(t,e),t);function mc(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),a=Number(r&o),c=n?4:0,u=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+u,a,n)}function Oo(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function gc(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}function Tn(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function xc(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function pl(e,t){Tn(e);let r=t.outputLen;if(e.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var Zt=(e,t)=>e[t++]&255|(e[t++]&255)<<8,bc=class{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=Uo(t),$r(t,32);let r=Zt(t,0),n=Zt(t,2),i=Zt(t,4),o=Zt(t,6),s=Zt(t,8),a=Zt(t,10),c=Zt(t,12),u=Zt(t,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|i<<6)&7939,this.r[3]=(i>>>7|o<<9)&8191,this.r[4]=(o>>>4|s<<12)&255,this.r[5]=s>>>1&8190,this.r[6]=(s>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let f=0;f<8;f++)this.pad[f]=Zt(t,16+2*f)}process(t,r,n=!1){let i=n?0:2048,{h:o,r:s}=this,a=s[0],c=s[1],u=s[2],f=s[3],l=s[4],d=s[5],y=s[6],h=s[7],p=s[8],m=s[9],g=Zt(t,r+0),b=Zt(t,r+2),x=Zt(t,r+4),A=Zt(t,r+6),v=Zt(t,r+8),E=Zt(t,r+10),C=Zt(t,r+12),B=Zt(t,r+14),O=o[0]+(g&8191),K=o[1]+((g>>>13|b<<3)&8191),U=o[2]+((b>>>10|x<<6)&8191),F=o[3]+((x>>>7|A<<9)&8191),G=o[4]+((A>>>4|v<<12)&8191),Q=o[5]+(v>>>1&8191),I=o[6]+((v>>>14|E<<2)&8191),R=o[7]+((E>>>11|C<<5)&8191),_=o[8]+((C>>>8|B<<8)&8191),k=o[9]+(B>>>5|i),S=0,P=S+O*a+K*(5*m)+U*(5*p)+F*(5*h)+G*(5*y);S=P>>>13,P&=8191,P+=Q*(5*d)+I*(5*l)+R*(5*f)+_*(5*u)+k*(5*c),S+=P>>>13,P&=8191;let M=S+O*c+K*a+U*(5*m)+F*(5*p)+G*(5*h);S=M>>>13,M&=8191,M+=Q*(5*y)+I*(5*d)+R*(5*l)+_*(5*f)+k*(5*u),S+=M>>>13,M&=8191;let H=S+O*u+K*c+U*a+F*(5*m)+G*(5*p);S=H>>>13,H&=8191,H+=Q*(5*h)+I*(5*y)+R*(5*d)+_*(5*l)+k*(5*f),S+=H>>>13,H&=8191;let Z=S+O*f+K*u+U*c+F*a+G*(5*m);S=Z>>>13,Z&=8191,Z+=Q*(5*p)+I*(5*h)+R*(5*y)+_*(5*d)+k*(5*l),S+=Z>>>13,Z&=8191;let j=S+O*l+K*f+U*u+F*c+G*a;S=j>>>13,j&=8191,j+=Q*(5*m)+I*(5*p)+R*(5*h)+_*(5*y)+k*(5*d),S+=j>>>13,j&=8191;let it=S+O*d+K*l+U*f+F*u+G*c;S=it>>>13,it&=8191,it+=Q*a+I*(5*m)+R*(5*p)+_*(5*h)+k*(5*y),S+=it>>>13,it&=8191;let J=S+O*y+K*d+U*l+F*f+G*u;S=J>>>13,J&=8191,J+=Q*c+I*a+R*(5*m)+_*(5*p)+k*(5*h),S+=J>>>13,J&=8191;let et=S+O*h+K*y+U*d+F*l+G*f;S=et>>>13,et&=8191,et+=Q*u+I*c+R*a+_*(5*m)+k*(5*p),S+=et>>>13,et&=8191;let bt=S+O*p+K*h+U*y+F*d+G*l;S=bt>>>13,bt&=8191,bt+=Q*f+I*u+R*c+_*a+k*(5*m),S+=bt>>>13,bt&=8191;let gt=S+O*m+K*p+U*h+F*y+G*d;S=gt>>>13,gt&=8191,gt+=Q*l+I*f+R*u+_*c+k*a,S+=gt>>>13,gt&=8191,S=(S<<2)+S|0,S=S+P|0,P=S&8191,S=S>>>13,M+=S,o[0]=P,o[1]=M,o[2]=H,o[3]=Z,o[4]=j,o[5]=it,o[6]=J,o[7]=et,o[8]=bt,o[9]=gt}finalize(){let{h:t,pad:r}=this,n=new Uint16Array(10),i=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=i,i=t[a]>>>13,t[a]&=8191;t[0]+=i*5,i=t[0]>>>13,t[0]&=8191,t[1]+=i,i=t[1]>>>13,t[1]&=8191,t[2]+=i,n[0]=t[0]+5,i=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+i,i=n[a]>>>13,n[a]&=8191;n[9]-=8192;let o=(i^1)-1;for(let a=0;a<10;a++)n[a]&=o;o=~o;for(let a=0;a<10;a++)t[a]=t[a]&o|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 s=t[0]+r[0];t[0]=s&65535;for(let a=1;a<8;a++)s=(t[a]+r[a]|0)+(s>>>16)|0,t[a]=s&65535}update(t){xc(this);let{buffer:r,blockLen:n}=this;t=Uo(t);let i=t.length;for(let o=0;o<i;){let s=Math.min(n-this.pos,i-o);if(s===n){for(;n<=i-o;o+=n)this.process(t,o);continue}r.set(t.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){this.h.fill(0),this.r.fill(0),this.buffer.fill(0),this.pad.fill(0)}digestInto(t){xc(this),pl(t,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:i}=this;if(i){for(r[i++]=1;i<16;i++)r[i]=0;this.process(r,0,!0)}this.finalize();let o=0;for(let s=0;s<8;s++)t[o++]=n[s]>>>0,t[o++]=n[s]>>>8;return t}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}};function Km(e){let t=(n,i)=>e(i).update(Uo(n)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}var yl=Km(e=>new bc(e));var Mm=Po("expand 16-byte k"),Fm=Po("expand 32-byte k"),Vm=je(Mm),Hm=je(Fm);function $(e,t){return e<<t|e>>>32-t}function wc(e){return e.byteOffset%4===0}var Ko=64,qm=16,gl=2**32-1,ml=new Uint32Array;function zm(e,t,r,n,i,o,s,a){let c=i.length,u=new Uint8Array(Ko),f=je(u),l=wc(i)&&wc(o),d=l?je(i):ml,y=l?je(o):ml;for(let h=0;h<c;s++){if(e(t,r,n,f,s,a),s>=gl)throw new Error("arx: counter overflow");let p=Math.min(Ko,c-h);if(l&&p===Ko){let m=h/4;if(h%4!==0)throw new Error("arx: invalid block position");for(let g=0,b;g<qm;g++)b=m+g,y[b]=d[b]^f[g];h+=Ko;continue}for(let m=0,g;m<p;m++)g=h+m,o[g]=i[g]^u[m];h+=p}}function vc(e,t){let{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:o,rounds:s}=hl({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return Oo(i),Oo(s),gc(o),gc(r),(a,c,u,f,l=0)=>{Tn(a),Tn(c),Tn(u);let d=u.length;if(f||(f=new Uint8Array(d)),Tn(f),Oo(l),l<0||l>=gl)throw new Error("arx: counter overflow");if(f.length<d)throw new Error(`arx: output (${f.length}) is shorter than data (${d})`);let y=[],h=a.length,p,m;if(h===32)p=a.slice(),y.push(p),m=Hm;else if(h===16&&r)p=new Uint8Array(32),p.set(a),p.set(a,16),m=Vm,y.push(p);else throw new Error(`arx: invalid 32-byte key, got length=${h}`);wc(c)||(c=c.slice(),y.push(c));let g=je(p);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(m,g,je(c.subarray(0,16)),g),c=c.subarray(16)}let b=16-i;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let A=new Uint8Array(12);A.set(c,o?0:12-c.length),c=A,y.push(c)}let x=je(c);for(zm(e,m,g,x,u,f,l,s);y.length>0;)y.pop().fill(0);return f}}function wl(e,t,r,n,i,o=20){let s=e[0],a=e[1],c=e[2],u=e[3],f=t[0],l=t[1],d=t[2],y=t[3],h=t[4],p=t[5],m=t[6],g=t[7],b=i,x=r[0],A=r[1],v=r[2],E=s,C=a,B=c,O=u,K=f,U=l,F=d,G=y,Q=h,I=p,R=m,_=g,k=b,S=x,P=A,M=v;for(let Z=0;Z<o;Z+=2)E=E+K|0,k=$(k^E,16),Q=Q+k|0,K=$(K^Q,12),E=E+K|0,k=$(k^E,8),Q=Q+k|0,K=$(K^Q,7),C=C+U|0,S=$(S^C,16),I=I+S|0,U=$(U^I,12),C=C+U|0,S=$(S^C,8),I=I+S|0,U=$(U^I,7),B=B+F|0,P=$(P^B,16),R=R+P|0,F=$(F^R,12),B=B+F|0,P=$(P^B,8),R=R+P|0,F=$(F^R,7),O=O+G|0,M=$(M^O,16),_=_+M|0,G=$(G^_,12),O=O+G|0,M=$(M^O,8),_=_+M|0,G=$(G^_,7),E=E+U|0,M=$(M^E,16),R=R+M|0,U=$(U^R,12),E=E+U|0,M=$(M^E,8),R=R+M|0,U=$(U^R,7),C=C+F|0,k=$(k^C,16),_=_+k|0,F=$(F^_,12),C=C+F|0,k=$(k^C,8),_=_+k|0,F=$(F^_,7),B=B+G|0,S=$(S^B,16),Q=Q+S|0,G=$(G^Q,12),B=B+G|0,S=$(S^B,8),Q=Q+S|0,G=$(G^Q,7),O=O+K|0,P=$(P^O,16),I=I+P|0,K=$(K^I,12),O=O+K|0,P=$(P^O,8),I=I+P|0,K=$(K^I,7);let H=0;n[H++]=s+E|0,n[H++]=a+C|0,n[H++]=c+B|0,n[H++]=u+O|0,n[H++]=f+K|0,n[H++]=l+U|0,n[H++]=d+F|0,n[H++]=y+G|0,n[H++]=h+Q|0,n[H++]=p+I|0,n[H++]=m+R|0,n[H++]=g+_|0,n[H++]=b+k|0,n[H++]=x+S|0,n[H++]=A+P|0,n[H++]=v+M|0}function Gm(e,t,r,n){let i=e[0],o=e[1],s=e[2],a=e[3],c=t[0],u=t[1],f=t[2],l=t[3],d=t[4],y=t[5],h=t[6],p=t[7],m=r[0],g=r[1],b=r[2],x=r[3];for(let v=0;v<20;v+=2)i=i+c|0,m=$(m^i,16),d=d+m|0,c=$(c^d,12),i=i+c|0,m=$(m^i,8),d=d+m|0,c=$(c^d,7),o=o+u|0,g=$(g^o,16),y=y+g|0,u=$(u^y,12),o=o+u|0,g=$(g^o,8),y=y+g|0,u=$(u^y,7),s=s+f|0,b=$(b^s,16),h=h+b|0,f=$(f^h,12),s=s+f|0,b=$(b^s,8),h=h+b|0,f=$(f^h,7),a=a+l|0,x=$(x^a,16),p=p+x|0,l=$(l^p,12),a=a+l|0,x=$(x^a,8),p=p+x|0,l=$(l^p,7),i=i+u|0,x=$(x^i,16),h=h+x|0,u=$(u^h,12),i=i+u|0,x=$(x^i,8),h=h+x|0,u=$(u^h,7),o=o+f|0,m=$(m^o,16),p=p+m|0,f=$(f^p,12),o=o+f|0,m=$(m^o,8),p=p+m|0,f=$(f^p,7),s=s+l|0,g=$(g^s,16),d=d+g|0,l=$(l^d,12),s=s+l|0,g=$(g^s,8),d=d+g|0,l=$(l^d,7),a=a+c|0,b=$(b^a,16),y=y+b|0,c=$(c^y,12),a=a+c|0,b=$(b^a,8),y=y+b|0,c=$(c^y,7);let A=0;n[A++]=i,n[A++]=o,n[A++]=s,n[A++]=a,n[A++]=m,n[A++]=g,n[A++]=b,n[A++]=x}var Wm=vc(wl,{counterRight:!1,counterLength:4,allowShortKeys:!1}),$m=vc(wl,{counterRight:!1,counterLength:8,extendNonceFn:Gm,allowShortKeys:!1});var Ym=new Uint8Array(16),xl=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(Ym.subarray(r))},Xm=new Uint8Array(32);function bl(e,t,r,n,i){let o=e(t,r,Xm),s=yl.create(o);i&&xl(s,i),xl(s,n);let a=new Uint8Array(16),c=ll(a);mc(c,0,BigInt(i?i.length:0),!0),mc(c,8,BigInt(n.length),!0),s.update(a);let u=s.digest();return o.fill(0),u}var vl=e=>(t,r,n)=>($r(t,32),$r(r),{encrypt:(o,s)=>{let a=o.length,c=a+16;s?$r(s,c):s=new Uint8Array(c),e(t,r,o,s,1);let u=bl(e,t,r,s.subarray(0,-16),n);return s.set(u,a),s},decrypt:(o,s)=>{let a=o.length,c=a-16;if(a<16)throw new Error("encrypted data must be at least 16 bytes");s?$r(s,c):s=new Uint8Array(c);let u=o.subarray(0,-16),f=o.subarray(-16),l=bl(e,t,r,u,n);if(!dl(f,l))throw new Error("invalid tag");return e(t,r,u,s,1),s}}),Ec=yc({blockSize:64,nonceLength:12,tagLength:16},vl(Wm)),pD=yc({blockSize:64,nonceLength:24,tagLength:16},vl($m));function Mo(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function Sc(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function yi(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Mo(e.outputLen),Mo(e.blockLen)}function _n(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function El(e,t){Sc(e);let r=t.outputLen;if(e.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var Fo=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Sl=e=>e instanceof Uint8Array;var Vo=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),De=(e,t)=>e<<32-t|e>>>t,Zm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Zm)throw new Error("Non little-endian hardware is not supported");function Ac(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function vr(e){if(typeof e=="string"&&(e=Ac(e)),!Sl(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}function Ho(...e){let t=new Uint8Array(e.reduce((n,i)=>n+i.length,0)),r=0;return e.forEach(n=>{if(!Sl(n))throw new Error("Uint8Array expected");t.set(n,r),r+=n.length}),t}var kn=class{clone(){return this._cloneInto()}},bD={}.toString;function qo(e){let t=n=>e().update(vr(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Yr(e=32){if(Fo&&typeof Fo.getRandomValues=="function")return Fo.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function Qm(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),a=Number(r&o),c=n?4:0,u=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+u,a,n)}var Rn=class extends kn{constructor(t,r,n,i){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Vo(this.buffer)}update(t){_n(this);let{view:r,buffer:n,blockLen:i}=this;t=vr(t);let o=t.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=Vo(t);for(;i<=o-s;s+=i)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){_n(this),El(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>i-s&&(this.process(n,0),s=0);for(let l=s;l<i;l++)r[l]=0;Qm(n,i-8,BigInt(this.length*8),o),this.process(n,0);let a=Vo(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],o)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:a}=this;return t.length=i,t.pos=a,t.finished=o,t.destroyed=s,i%r&&t.buffer.set(n),t}};var zo=BigInt(4294967295),Dc=BigInt(32);function Al(e,t=!1){return t?{h:Number(e&zo),l:Number(e>>Dc&zo)}:{h:Number(e>>Dc&zo)|0,l:Number(e&zo)|0}}function jm(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let i=0;i<e.length;i++){let{h:o,l:s}=Al(e[i],t);[r[i],n[i]]=[o,s]}return[r,n]}var Jm=(e,t)=>BigInt(e>>>0)<<Dc|BigInt(t>>>0),tg=(e,t,r)=>e>>>r,eg=(e,t,r)=>e<<32-r|t>>>r,rg=(e,t,r)=>e>>>r|t<<32-r,ng=(e,t,r)=>e<<32-r|t>>>r,ig=(e,t,r)=>e<<64-r|t>>>r-32,og=(e,t,r)=>e>>>r-32|t<<64-r,sg=(e,t)=>t,ag=(e,t)=>e,cg=(e,t,r)=>e<<r|t>>>32-r,ug=(e,t,r)=>t<<r|e>>>32-r,fg=(e,t,r)=>t<<r-32|e>>>64-r,lg=(e,t,r)=>e<<r-32|t>>>64-r;function hg(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}var dg=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),pg=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,yg=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),mg=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,gg=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),xg=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0;var bg={fromBig:Al,split:jm,toBig:Jm,shrSH:tg,shrSL:eg,rotrSH:rg,rotrSL:ng,rotrBH:ig,rotrBL:og,rotr32H:sg,rotr32L:ag,rotlSH:cg,rotlSL:ug,rotlBH:fg,rotlBL:lg,add:hg,add3L:dg,add3H:pg,add4L:yg,add4H:mg,add5H:xg,add5L:gg},rt=bg;var[wg,vg]=rt.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(e=>BigInt(e))),Er=new Uint32Array(80),Sr=new Uint32Array(80),Cc=class extends Rn{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:r,Bh:n,Bl:i,Ch:o,Cl:s,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:d,Gh:y,Gl:h,Hh:p,Hl:m}=this;return[t,r,n,i,o,s,a,c,u,f,l,d,y,h,p,m]}set(t,r,n,i,o,s,a,c,u,f,l,d,y,h,p,m){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=o|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=y|0,this.Gl=h|0,this.Hh=p|0,this.Hl=m|0}process(t,r){for(let x=0;x<16;x++,r+=4)Er[x]=t.getUint32(r),Sr[x]=t.getUint32(r+=4);for(let x=16;x<80;x++){let A=Er[x-15]|0,v=Sr[x-15]|0,E=rt.rotrSH(A,v,1)^rt.rotrSH(A,v,8)^rt.shrSH(A,v,7),C=rt.rotrSL(A,v,1)^rt.rotrSL(A,v,8)^rt.shrSL(A,v,7),B=Er[x-2]|0,O=Sr[x-2]|0,K=rt.rotrSH(B,O,19)^rt.rotrBH(B,O,61)^rt.shrSH(B,O,6),U=rt.rotrSL(B,O,19)^rt.rotrBL(B,O,61)^rt.shrSL(B,O,6),F=rt.add4L(C,U,Sr[x-7],Sr[x-16]),G=rt.add4H(F,E,K,Er[x-7],Er[x-16]);Er[x]=G|0,Sr[x]=F|0}let{Ah:n,Al:i,Bh:o,Bl:s,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:y,Fl:h,Gh:p,Gl:m,Hh:g,Hl:b}=this;for(let x=0;x<80;x++){let A=rt.rotrSH(l,d,14)^rt.rotrSH(l,d,18)^rt.rotrBH(l,d,41),v=rt.rotrSL(l,d,14)^rt.rotrSL(l,d,18)^rt.rotrBL(l,d,41),E=l&y^~l&p,C=d&h^~d&m,B=rt.add5L(b,v,C,vg[x],Sr[x]),O=rt.add5H(B,g,A,E,wg[x],Er[x]),K=B|0,U=rt.rotrSH(n,i,28)^rt.rotrBH(n,i,34)^rt.rotrBH(n,i,39),F=rt.rotrSL(n,i,28)^rt.rotrBL(n,i,34)^rt.rotrBL(n,i,39),G=n&o^n&a^o&a,Q=i&s^i&c^s&c;g=p|0,b=m|0,p=y|0,m=h|0,y=l|0,h=d|0,{h:l,l:d}=rt.add(u|0,f|0,O|0,K|0),u=a|0,f=c|0,a=o|0,c=s|0,o=n|0,s=i|0;let I=rt.add3L(K,F,Q);n=rt.add3H(I,O,U,G),i=I|0}({h:n,l:i}=rt.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:o,l:s}=rt.add(this.Bh|0,this.Bl|0,o|0,s|0),{h:a,l:c}=rt.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=rt.add(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=rt.add(this.Eh|0,this.El|0,l|0,d|0),{h:y,l:h}=rt.add(this.Fh|0,this.Fl|0,y|0,h|0),{h:p,l:m}=rt.add(this.Gh|0,this.Gl|0,p|0,m|0),{h:g,l:b}=rt.add(this.Hh|0,this.Hl|0,g|0,b|0),this.set(n,i,o,s,a,c,u,f,l,d,y,h,p,m,g,b)}roundClean(){Er.fill(0),Sr.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 Bc=qo(()=>new Cc);var $o={};ft($o,{bitGet:()=>Ig,bitLen:()=>Bg,bitMask:()=>mi,bitSet:()=>Tg,bytesToHex:()=>Je,bytesToNumberBE:()=>tr,bytesToNumberLE:()=>Ce,concatBytes:()=>rr,createHmacDrbg:()=>_c,ensureBytes:()=>Et,equalBytes:()=>Dg,hexToBytes:()=>Xr,hexToNumber:()=>Tc,numberToBytesBE:()=>Ar,numberToBytesLE:()=>er,numberToHexUnpadded:()=>Bl,numberToVarBytesBE:()=>Ag,utf8ToBytes:()=>Cg,validateObject:()=>pe});var Cl=BigInt(0),Go=BigInt(1),Eg=BigInt(2),Wo=e=>e instanceof Uint8Array,Sg=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Je(e){if(!Wo(e))throw new Error("Uint8Array expected");let t="";for(let r=0;r<e.length;r++)t+=Sg[e[r]];return t}function Bl(e){let t=e.toString(16);return t.length&1?`0${t}`:t}function Tc(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return BigInt(e===""?"0":`0x${e}`)}function Xr(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);let t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(t/2);for(let n=0;n<r.length;n++){let i=n*2,o=e.slice(i,i+2),s=Number.parseInt(o,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");r[n]=s}return r}function tr(e){return Tc(Je(e))}function Ce(e){if(!Wo(e))throw new Error("Uint8Array expected");return Tc(Je(Uint8Array.from(e).reverse()))}function Ar(e,t){return Xr(e.toString(16).padStart(t*2,"0"))}function er(e,t){return Ar(e,t).reverse()}function Ag(e){return Xr(Bl(e))}function Et(e,t,r){let n;if(typeof t=="string")try{n=Xr(t)}catch(o){throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${o}`)}else if(Wo(t))n=Uint8Array.from(t);else throw new Error(`${e} must be hex string or Uint8Array`);let i=n.length;if(typeof r=="number"&&i!==r)throw new Error(`${e} expected ${r} bytes, got ${i}`);return n}function rr(...e){let t=new Uint8Array(e.reduce((n,i)=>n+i.length,0)),r=0;return e.forEach(n=>{if(!Wo(n))throw new Error("Uint8Array expected");t.set(n,r),r+=n.length}),t}function Dg(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function Cg(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function Bg(e){let t;for(t=0;e>Cl;e>>=Go,t+=1);return t}function Ig(e,t){return e>>BigInt(t)&Go}var Tg=(e,t,r)=>e|(r?Go:Cl)<<BigInt(t),mi=e=>(Eg<<BigInt(e-1))-Go,Ic=e=>new Uint8Array(e),Dl=e=>Uint8Array.from(e);function _c(e,t,r){if(typeof e!="number"||e<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 r!="function")throw new Error("hmacFn must be a function");let n=Ic(e),i=Ic(e),o=0,s=()=>{n.fill(1),i.fill(0),o=0},a=(...l)=>r(i,n,...l),c=(l=Ic())=>{i=a(Dl([0]),l),n=a(),l.length!==0&&(i=a(Dl([1]),l),n=a())},u=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let l=0,d=[];for(;l<t;){n=a();let y=n.slice();d.push(y),l+=n.length}return rr(...d)};return(l,d)=>{s(),c(l);let y;for(;!(y=d(u()));)c();return s(),y}}var _g={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||e instanceof Uint8Array,isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function pe(e,t,r={}){let n=(i,o,s)=>{let a=_g[o];if(typeof a!="function")throw new Error(`Invalid validator "${o}", expected function`);let c=e[i];if(!(s&&c===void 0)&&!a(c,e))throw new Error(`Invalid param ${String(i)}=${c} (${typeof c}), expected ${o}`)};for(let[i,o]of Object.entries(t))n(i,o,!1);for(let[i,o]of Object.entries(r))n(i,o,!0);return e}var qt=BigInt(0),It=BigInt(1),Zr=BigInt(2),kg=BigInt(3),kc=BigInt(4),Il=BigInt(5),Tl=BigInt(8),Rg=BigInt(9),Lg=BigInt(16);function ht(e,t){let r=e%t;return r>=qt?r:t+r}function Rc(e,t,r){if(r<=qt||t<qt)throw new Error("Expected power/modulo > 0");if(r===It)return qt;let n=It;for(;t>qt;)t&It&&(n=n*e%r),e=e*e%r,t>>=It;return n}function St(e,t,r){let n=e;for(;t-- >qt;)n*=n,n%=r;return n}function Yo(e,t){if(e===qt||t<=qt)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=ht(e,t),n=t,i=qt,o=It,s=It,a=qt;for(;r!==qt;){let u=n/r,f=n%r,l=i-s*u,d=o-a*u;n=r,r=f,i=s,o=a,s=l,a=d}if(n!==It)throw new Error("invert: does not exist");return ht(i,t)}function Ng(e){let t=(e-It)/Zr,r,n,i;for(r=e-It,n=0;r%Zr===qt;r/=Zr,n++);for(i=Zr;i<e&&Rc(i,t,e)!==e-It;i++);if(n===1){let s=(e+It)/kc;return function(c,u){let f=c.pow(u,s);if(!c.eql(c.sqr(f),u))throw new Error("Cannot find square root");return f}}let o=(r+It)/Zr;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,f=a.pow(a.mul(a.ONE,i),r),l=a.pow(c,o),d=a.pow(c,r);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let y=1;for(let p=a.sqr(d);y<u&&!a.eql(p,a.ONE);y++)p=a.sqr(p);let h=a.pow(f,It<<BigInt(u-y-1));f=a.sqr(h),l=a.mul(l,h),d=a.mul(d,f),u=y}return l}}function Pg(e){if(e%kc===kg){let t=(e+It)/kc;return function(n,i){let o=n.pow(i,t);if(!n.eql(n.sqr(o),i))throw new Error("Cannot find square root");return o}}if(e%Tl===Il){let t=(e-Il)/Tl;return function(n,i){let o=n.mul(i,Zr),s=n.pow(o,t),a=n.mul(i,s),c=n.mul(n.mul(a,Zr),s),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),i))throw new Error("Cannot find square root");return u}}return e%Lg,Ng(e)}var _l=(e,t)=>(ht(e,t)&It)===It,Ug=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Lc(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Ug.reduce((n,i)=>(n[i]="function",n),t);return pe(e,r)}function Og(e,t,r){if(r<qt)throw new Error("Expected power > 0");if(r===qt)return e.ONE;if(r===It)return t;let n=e.ONE,i=t;for(;r>qt;)r&It&&(n=e.mul(n,i)),i=e.sqr(i),r>>=It;return n}function Kg(e,t){let r=new Array(t.length),n=t.reduce((o,s,a)=>e.is0(s)?o:(r[a]=o,e.mul(o,s)),e.ONE),i=e.inv(n);return t.reduceRight((o,s,a)=>e.is0(s)?o:(r[a]=e.mul(o,r[a]),e.mul(o,s)),i),r}function Nc(e,t){let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Xo(e,t,r=!1,n={}){if(e<=qt)throw new Error(`Expected Field ORDER > 0, got ${e}`);let{nBitLength:i,nByteLength:o}=Nc(e,t);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=Pg(e),a=Object.freeze({ORDER:e,BITS:i,BYTES:o,MASK:mi(i),ZERO:qt,ONE:It,create:c=>ht(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return qt<=c&&c<e},is0:c=>c===qt,isOdd:c=>(c&It)===It,neg:c=>ht(-c,e),eql:(c,u)=>c===u,sqr:c=>ht(c*c,e),add:(c,u)=>ht(c+u,e),sub:(c,u)=>ht(c-u,e),mul:(c,u)=>ht(c*u,e),pow:(c,u)=>Og(a,c,u),div:(c,u)=>ht(c*Yo(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Yo(c,e),sqrt:n.sqrt||(c=>s(a,c)),invertBatch:c=>Kg(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>r?er(c,o):Ar(c,o),fromBytes:c=>{if(c.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${c.length}`);return r?Ce(c):tr(c)}});return Object.freeze(a)}function kl(e,t){if(!e.isOdd)throw new Error("Field doesn't have isOdd");let r=e.sqrt(t);return e.isOdd(r)?e.neg(r):r}function Rl(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function Pc(e){let t=Rl(e);return t+Math.ceil(t/2)}function Ll(e,t,r=!1){let n=e.length,i=Rl(t),o=Pc(t);if(n<16||n<o||n>1024)throw new Error(`expected ${o}-1024 bytes of input, got ${n}`);let s=r?tr(e):Ce(e),a=ht(s,t-It)+It;return r?er(a,i):Ar(a,i)}var Fg=BigInt(0),Uc=BigInt(1);function Zo(e,t){let r=(i,o)=>{let s=o.negate();return i?s:o},n=i=>{let o=Math.ceil(t/i)+1,s=2**(i-1);return{windows:o,windowSize:s}};return{constTimeNegate:r,unsafeLadder(i,o){let s=e.ZERO,a=i;for(;o>Fg;)o&Uc&&(s=s.add(a)),a=a.double(),o>>=Uc;return s},precomputeWindow(i,o){let{windows:s,windowSize:a}=n(o),c=[],u=i,f=u;for(let l=0;l<s;l++){f=u,c.push(f);for(let d=1;d<a;d++)f=f.add(u),c.push(f);u=f.double()}return c},wNAF(i,o,s){let{windows:a,windowSize:c}=n(i),u=e.ZERO,f=e.BASE,l=BigInt(2**i-1),d=2**i,y=BigInt(i);for(let h=0;h<a;h++){let p=h*c,m=Number(s&l);s>>=y,m>c&&(m-=d,s+=Uc);let g=p,b=p+Math.abs(m)-1,x=h%2!==0,A=m<0;m===0?f=f.add(r(x,o[g])):u=u.add(r(A,o[b]))}return{p:u,f}},wNAFCached(i,o,s,a){let c=i._WINDOW_SIZE||1,u=o.get(i);return u||(u=this.precomputeWindow(i,c),c!==1&&o.set(i,a(u))),this.wNAF(c,u,s)}}}function gi(e){return Lc(e.Fp),pe(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Nc(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}var Be=BigInt(0),le=BigInt(1),Qo=BigInt(2),Vg=BigInt(8),Hg={zip215:!0};function qg(e){let t=gi(e);return pe(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function jo(e){let t=qg(e),{Fp:r,n,prehash:i,hash:o,randomBytes:s,nByteLength:a,h:c}=t,u=Qo<<BigInt(a*8)-le,f=r.create,l=t.uvRatio||((k,S)=>{try{return{isValid:!0,value:r.sqrt(k*r.inv(S))}}catch{return{isValid:!1,value:Be}}}),d=t.adjustScalarBytes||(k=>k),y=t.domain||((k,S,P)=>{if(S.length||P)throw new Error("Contexts/pre-hash are not supported");return k}),h=k=>typeof k=="bigint"&&Be<k,p=(k,S)=>h(k)&&h(S)&&k<S,m=k=>k===Be||p(k,u);function g(k,S){if(p(k,S))return k;throw new Error(`Expected valid scalar < ${S}, got ${typeof k} ${k}`)}function b(k){return k===Be?k:g(k,n)}let x=new Map;function A(k){if(!(k instanceof v))throw new Error("ExtendedPoint expected")}class v{constructor(S,P,M,H){if(this.ex=S,this.ey=P,this.ez=M,this.et=H,!m(S))throw new Error("x required");if(!m(P))throw new Error("y required");if(!m(M))throw new Error("z required");if(!m(H))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(S){if(S instanceof v)throw new Error("extended point not allowed");let{x:P,y:M}=S||{};if(!m(P)||!m(M))throw new Error("invalid affine point");return new v(P,M,le,f(P*M))}static normalizeZ(S){let P=r.invertBatch(S.map(M=>M.ez));return S.map((M,H)=>M.toAffine(P[H])).map(v.fromAffine)}_setWindowSize(S){this._WINDOW_SIZE=S,x.delete(this)}assertValidity(){let{a:S,d:P}=t;if(this.is0())throw new Error("bad point: ZERO");let{ex:M,ey:H,ez:Z,et:j}=this,it=f(M*M),J=f(H*H),et=f(Z*Z),bt=f(et*et),gt=f(it*S),$t=f(et*f(gt+J)),Yt=f(bt+f(P*f(it*J)));if($t!==Yt)throw new Error("bad point: equation left != right (1)");let Ft=f(M*H),jt=f(Z*j);if(Ft!==jt)throw new Error("bad point: equation left != right (2)")}equals(S){A(S);let{ex:P,ey:M,ez:H}=this,{ex:Z,ey:j,ez:it}=S,J=f(P*it),et=f(Z*H),bt=f(M*it),gt=f(j*H);return J===et&&bt===gt}is0(){return this.equals(v.ZERO)}negate(){return new v(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:S}=t,{ex:P,ey:M,ez:H}=this,Z=f(P*P),j=f(M*M),it=f(Qo*f(H*H)),J=f(S*Z),et=P+M,bt=f(f(et*et)-Z-j),gt=J+j,$t=gt-it,Yt=J-j,Ft=f(bt*$t),jt=f(gt*Yt),We=f(bt*Yt),Lr=f($t*gt);return new v(Ft,jt,Lr,We)}add(S){A(S);let{a:P,d:M}=t,{ex:H,ey:Z,ez:j,et:it}=this,{ex:J,ey:et,ez:bt,et:gt}=S;if(P===BigInt(-1)){let uu=f((Z-H)*(et+J)),fu=f((Z+H)*(et-J)),Vs=f(fu-uu);if(Vs===Be)return this.double();let lu=f(j*Qo*gt),hu=f(it*Qo*bt),du=hu+lu,pu=fu+uu,yu=hu-lu,q1=f(du*Vs),z1=f(pu*yu),G1=f(du*yu),W1=f(Vs*pu);return new v(q1,z1,W1,G1)}let $t=f(H*J),Yt=f(Z*et),Ft=f(it*M*gt),jt=f(j*bt),We=f((H+Z)*(J+et)-$t-Yt),Lr=jt-Ft,ti=jt+Ft,cu=f(Yt-P*$t),M1=f(We*Lr),F1=f(ti*cu),V1=f(We*cu),H1=f(Lr*ti);return new v(M1,F1,H1,V1)}subtract(S){return this.add(S.negate())}wNAF(S){return B.wNAFCached(this,x,S,v.normalizeZ)}multiply(S){let{p:P,f:M}=this.wNAF(g(S,n));return v.normalizeZ([P,M])[0]}multiplyUnsafe(S){let P=b(S);return P===Be?C:this.equals(C)||P===le?this:this.equals(E)?this.wNAF(P).p:B.unsafeLadder(this,P)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return B.unsafeLadder(this,n).is0()}toAffine(S){let{ex:P,ey:M,ez:H}=this,Z=this.is0();S==null&&(S=Z?Vg:r.inv(H));let j=f(P*S),it=f(M*S),J=f(H*S);if(Z)return{x:Be,y:le};if(J!==le)throw new Error("invZ was invalid");return{x:j,y:it}}clearCofactor(){let{h:S}=t;return S===le?this:this.multiplyUnsafe(S)}static fromHex(S,P=!1){let{d:M,a:H}=t,Z=r.BYTES;S=Et("pointHex",S,Z);let j=S.slice(),it=S[Z-1];j[Z-1]=it&-129;let J=Ce(j);J===Be||(P?g(J,u):g(J,r.ORDER));let et=f(J*J),bt=f(et-le),gt=f(M*et-H),{isValid:$t,value:Yt}=l(bt,gt);if(!$t)throw new Error("Point.fromHex: invalid y coordinate");let Ft=(Yt&le)===le,jt=(it&128)!==0;if(!P&&Yt===Be&&jt)throw new Error("Point.fromHex: x=0 and x_0=1");return jt!==Ft&&(Yt=f(-Yt)),v.fromAffine({x:Yt,y:J})}static fromPrivateKey(S){return U(S).point}toRawBytes(){let{x:S,y:P}=this.toAffine(),M=er(P,r.BYTES);return M[M.length-1]|=S&le?128:0,M}toHex(){return Je(this.toRawBytes())}}v.BASE=new v(t.Gx,t.Gy,le,f(t.Gx*t.Gy)),v.ZERO=new v(Be,le,le,Be);let{BASE:E,ZERO:C}=v,B=Zo(v,a*8);function O(k){return ht(k,n)}function K(k){return O(Ce(k))}function U(k){let S=a;k=Et("private key",k,S);let P=Et("hashed private key",o(k),2*S),M=d(P.slice(0,S)),H=P.slice(S,2*S),Z=K(M),j=E.multiply(Z),it=j.toRawBytes();return{head:M,prefix:H,scalar:Z,point:j,pointBytes:it}}function F(k){return U(k).pointBytes}function G(k=new Uint8Array,...S){let P=rr(...S);return K(o(y(P,Et("context",k),!!i)))}function Q(k,S,P={}){k=Et("message",k),i&&(k=i(k));let{prefix:M,scalar:H,pointBytes:Z}=U(S),j=G(P.context,M,k),it=E.multiply(j).toRawBytes(),J=G(P.context,it,Z,k),et=O(j+J*H);b(et);let bt=rr(it,er(et,r.BYTES));return Et("result",bt,a*2)}let I=Hg;function R(k,S,P,M=I){let{context:H,zip215:Z}=M,j=r.BYTES;k=Et("signature",k,2*j),S=Et("message",S),i&&(S=i(S));let it=Ce(k.slice(j,2*j)),J,et,bt;try{J=v.fromHex(P,Z),et=v.fromHex(k.slice(0,j),Z),bt=E.multiplyUnsafe(it)}catch{return!1}if(!Z&&J.isSmallOrder())return!1;let gt=G(H,et.toRawBytes(),J.toRawBytes(),S);return et.add(J.multiplyUnsafe(gt)).subtract(bt).clearCofactor().equals(v.ZERO)}return E._setWindowSize(8),{CURVE:t,getPublicKey:F,sign:Q,verify:R,ExtendedPoint:v,utils:{getExtendedPublicKey:U,randomPrivateKey:()=>s(r.BYTES),precompute(k=8,S=v.BASE){return S._setWindowSize(k),S.multiply(BigInt(3)),S}}}}var xi=BigInt(0),Oc=BigInt(1);function zg(e){return pe(e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...e})}function Nl(e){let t=zg(e),{P:r}=t,n=x=>ht(x,r),i=t.montgomeryBits,o=Math.ceil(i/8),s=t.nByteLength,a=t.adjustScalarBytes||(x=>x),c=t.powPminus2||(x=>Rc(x,r-BigInt(2),r));function u(x,A,v){let E=n(x*(A-v));return A=n(A-E),v=n(v+E),[A,v]}function f(x){if(typeof x=="bigint"&&xi<=x&&x<r)return x;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let l=(t.a-BigInt(2))/BigInt(4);function d(x,A){let v=f(x),E=f(A),C=v,B=Oc,O=xi,K=v,U=Oc,F=xi,G;for(let I=BigInt(i-1);I>=xi;I--){let R=E>>I&Oc;F^=R,G=u(F,B,K),B=G[0],K=G[1],G=u(F,O,U),O=G[0],U=G[1],F=R;let _=B+O,k=n(_*_),S=B-O,P=n(S*S),M=k-P,H=K+U,Z=K-U,j=n(Z*_),it=n(H*S),J=j+it,et=j-it;K=n(J*J),U=n(C*n(et*et)),B=n(k*P),O=n(M*(k+n(l*M)))}G=u(F,B,K),B=G[0],K=G[1],G=u(F,O,U),O=G[0],U=G[1];let Q=c(O);return n(B*Q)}function y(x){return er(n(x),o)}function h(x){let A=Et("u coordinate",x,o);return s===o&&(A[s-1]&=127),Ce(A)}function p(x){let A=Et("scalar",x);if(A.length!==o&&A.length!==s)throw new Error(`Expected ${o} or ${s} bytes, got ${A.length}`);return Ce(a(A))}function m(x,A){let v=h(A),E=p(x),C=d(v,E);if(C===xi)throw new Error("Invalid private or public key received");return y(C)}let g=y(t.Gu);function b(x){return m(x,g)}return{scalarMult:m,scalarMultBase:b,getSharedSecret:(x,A)=>m(x,A),getPublicKey:x=>b(x),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:g}}var bi=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Pl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),GD=BigInt(0),Gg=BigInt(1),Kc=BigInt(2),Wg=BigInt(5),Ul=BigInt(10),$g=BigInt(20),Yg=BigInt(40),Ol=BigInt(80);function Kl(e){let t=bi,n=e*e%t*e%t,i=St(n,Kc,t)*n%t,o=St(i,Gg,t)*e%t,s=St(o,Wg,t)*o%t,a=St(s,Ul,t)*s%t,c=St(a,$g,t)*a%t,u=St(c,Yg,t)*c%t,f=St(u,Ol,t)*u%t,l=St(f,Ol,t)*u%t,d=St(l,Ul,t)*s%t;return{pow_p_5_8:St(d,Kc,t)*e%t,b2:n}}function Ml(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function Xg(e,t){let r=bi,n=ht(t*t*t,r),i=ht(n*n*t,r),o=Kl(e*i).pow_p_5_8,s=ht(e*n*o,r),a=ht(t*s*s,r),c=s,u=ht(s*Pl,r),f=a===e,l=a===ht(-e,r),d=a===ht(-e*Pl,r);return f&&(s=c),(l||d)&&(s=u),_l(s,r)&&(s=ht(-s,r)),{isValid:f||l,value:s}}var nr=Xo(bi,void 0,!0),Mc={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:nr,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Bc,randomBytes:Yr,adjustScalarBytes:Ml,uvRatio:Xg},Ln=jo(Mc);function Fl(e,t,r){if(t.length>255)throw new Error("Context is too big");return Ho(Ac("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,t.length]),t,e)}var WD=jo({...Mc,domain:Fl}),$D=jo({...Mc,domain:Fl,prehash:Bc}),wi=Nl({P:bi,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:e=>{let t=bi,{pow_p_5_8:r,b2:n}=Kl(e);return ht(St(r,BigInt(3),t)*n,t)},adjustScalarBytes:Ml,randomBytes:Yr});var Zg=(nr.ORDER+BigInt(3))/BigInt(8),YD=nr.pow(Kc,Zg),XD=nr.sqrt(nr.neg(nr.ONE)),ZD=(nr.ORDER-BigInt(5))/BigInt(8),QD=BigInt(486662);var jD=kl(nr,nr.neg(BigInt(486664)));var JD=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),tC=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),eC=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),rC=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var nC=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Jo=class extends kn{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,yi(t);let n=vr(r);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 i=this.blockLen,o=new Uint8Array(i);o.set(n.length>i?t.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),o.fill(0)}update(t){return _n(this),this.iHash.update(t),this}digestInto(t){_n(this),Sc(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:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return t=t,t.finished=i,t.destroyed=o,t.blockLen=s,t.outputLen=a,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Nn=(e,t,r)=>new Jo(e,t).update(r).digest();Nn.create=(e,t)=>new Jo(e,t);function Hl(e,t,r){return yi(e),r===void 0&&(r=new Uint8Array(e.outputLen)),Nn(e,vr(r),vr(t))}var Fc=new Uint8Array([0]),Vl=new Uint8Array;function ql(e,t,r,n=32){if(yi(e),Mo(n),n>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");let i=Math.ceil(n/e.outputLen);r===void 0&&(r=Vl);let o=new Uint8Array(i*e.outputLen),s=Nn.create(e,t),a=s._cloneInto(),c=new Uint8Array(s.outputLen);for(let u=0;u<i;u++)Fc[0]=u+1,a.update(u===0?Vl:c).update(r).update(Fc).digestInto(c),o.set(c,e.outputLen*u),s._cloneInto(a);return s.destroy(),a.destroy(),c.fill(0),Fc.fill(0),o.slice(0,n)}var Qg=(e,t,r)=>e&t^~e&r,jg=(e,t,r)=>e&t^e&r^t&r,Jg=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]),Dr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Cr=new Uint32Array(64),Vc=class extends Rn{constructor(){super(64,32,8,!1),this.A=Dr[0]|0,this.B=Dr[1]|0,this.C=Dr[2]|0,this.D=Dr[3]|0,this.E=Dr[4]|0,this.F=Dr[5]|0,this.G=Dr[6]|0,this.H=Dr[7]|0}get(){let{A:t,B:r,C:n,D:i,E:o,F:s,G:a,H:c}=this;return[t,r,n,i,o,s,a,c]}set(t,r,n,i,o,s,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,r){for(let l=0;l<16;l++,r+=4)Cr[l]=t.getUint32(r,!1);for(let l=16;l<64;l++){let d=Cr[l-15],y=Cr[l-2],h=De(d,7)^De(d,18)^d>>>3,p=De(y,17)^De(y,19)^y>>>10;Cr[l]=p+Cr[l-7]+h+Cr[l-16]|0}let{A:n,B:i,C:o,D:s,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let d=De(a,6)^De(a,11)^De(a,25),y=f+d+Qg(a,c,u)+Jg[l]+Cr[l]|0,p=(De(n,2)^De(n,13)^De(n,22))+jg(n,i,o)|0;f=u,u=c,c=a,a=s+y|0,s=o,o=i,i=n,n=y+p|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,i,o,s,a,c,u,f)}roundClean(){Cr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Pn=qo(()=>new Vc);var Hc={hashSHA256(e){return Pn(e.subarray())},getHKDF(e,t){let r=Hl(Pn,t,e),i=ql(Pn,r,void 0,96),o=i.subarray(0,32),s=i.subarray(32,64),a=i.subarray(64,96);return[o,s,a]},generateX25519KeyPair(){let e=wi.utils.randomPrivateKey();return{publicKey:wi.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed(e){return{publicKey:wi.getPublicKey(e),privateKey:e}},generateX25519SharedKey(e,t){return wi.getSharedSecret(e.subarray(),t.subarray())},chaCha20Poly1305Encrypt(e,t,r,n){return Ec(n,t,r).encrypt(e.subarray())},chaCha20Poly1305Decrypt(e,t,r,n,i){return Ec(n,t,r).decrypt(e.subarray(),i)}};var zl=Hc;var Un=e=>{let t=Vt(2);return new DataView(t.buffer,t.byteOffset,t.byteLength).setUint16(0,e,!1),t};Un.bytes=2;var vi=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");return e instanceof Uint8Array?new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(0,!1):e.getUint16(0)};vi.bytes=2;function Gl(e){return new Bt(e.ne,e.ciphertext)}function Wl(e){return new Bt(e.ne,e.ns,e.ciphertext)}function $l(e){return new Bt(e.ns,e.ciphertext)}function Yl(e){if(e.length<32)throw new Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");return{ne:e.subarray(0,32),ciphertext:e.subarray(32,e.length),ns:ot(0)}}function Xl(e){if(e.length<80)throw new Error("Cannot decode stage 1 MessageBuffer: length less than 80 bytes.");return{ne:e.subarray(0,32),ns:e.subarray(32,80),ciphertext:e.subarray(80,e.length)}}function Zl(e){if(e.length<48)throw new Error("Cannot decode stage 2 MessageBuffer: length less than 48 bytes.");return{ne:ot(0),ns:e.subarray(0,48),ciphertext:e.subarray(48,e.length)}}var jl=16;function Jl(e,t){return async function*(r){for await(let n of r)for(let i=0;i<n.length;i+=65519){let o=i+65519;o>n.length&&(o=n.length);let s;n instanceof Uint8Array?s=e.encrypt(n.subarray(i,o),e.session):s=e.encrypt(n.sublist(i,o),e.session),t?.encryptedPackets.increment(),yield new Bt(Un(s.byteLength),s)}}}function th(e,t){return async function*(r){for await(let n of r)for(let i=0;i<n.length;i+=65535){let o=i+65535;if(o>n.length&&(o=n.length),o-jl<i)throw new Error("Invalid chunk");let s=n.sublist(i,o),a=n.subarray(i,o-jl),{plaintext:c,valid:u}=e.decrypt(s,e.session,a);if(!u)throw t?.decryptErrors.increment(),new Error("Failed to validate decrypted chunk");t?.decryptedPackets.increment(),yield c}}}var Si=class e extends Error{code;constructor(t="Unexpected Peer"){super(t),this.code=e.code}static code="ERR_UNEXPECTED_PEER"},Qr=class e extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=e.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var GI=Jt(Bi(),1),WI=Jt(md(),1);var tv=Jt(xt(),1);var p0={};ft(p0,{Ed25519PrivateKey:()=>nn,Ed25519PublicKey:()=>_i,generateKeyPair:()=>Bw,generateKeyPairFromSeed:()=>Dd,unmarshalEd25519PrivateKey:()=>Dw,unmarshalEd25519PublicKey:()=>Cw});var eB=Jt(Mt(),1),rB=Jt(ps(),1),gd=Jt(xt(),1);function _e(e,t){let r=Uint8Array.from(e.abs().toByteArray());if(r=r[0]===0?r.subarray(1):r,t!=null){if(r.length>t)throw new Error("byte array longer than desired length");r=Ct([new Uint8Array(t-r.length),r])}return at(r,"base64url")}function he(e){let t=xd(e);return new gd.default.jsbn.BigInteger(at(t,"base16"),16)}function xd(e,t){let r=wt(e,"base64urlpad");if(t!=null){if(r.length>t)throw new Error("byte array longer than desired length");r=Ct([new Uint8Array(t-r.length),r])}return r}function ge(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}var Vn=32,ar=64,xs=32;function bd(){let e=Ln.utils.randomPrivateKey(),t=Ln.getPublicKey(e);return{privateKey:Sd(e,t),publicKey:t}}function wd(e){if(e.length!==xs)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let t=e,r=Ln.getPublicKey(t);return{privateKey:Sd(t,r),publicKey:r}}function vd(e,t){let r=e.subarray(0,xs);return Ln.sign(t instanceof Uint8Array?t:t.subarray(),r)}function Ed(e,t,r){return Ln.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}function Sd(e,t){let r=new Uint8Array(ar);for(let n=0;n<xs;n++)r[n]=e[n],r[xs+n]=t[n];return r}var ue={get(e=globalThis){let t=e.crypto;if(t==null||t.subtle==null)throw Object.assign(new Error("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"),{code:"ERR_MISSING_WEB_CRYPTO"});return t}};var l0={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function h0(e){let t=e?.algorithm??"AES-GCM",r=e?.keyLength??16,n=e?.nonceLength??12,i=e?.digest??"SHA-256",o=e?.saltLength??16,s=e?.iterations??32767,a=ue.get();r*=8;async function c(l,d){let y=a.getRandomValues(new Uint8Array(o)),h=a.getRandomValues(new Uint8Array(n)),p={name:t,iv:h};typeof d=="string"&&(d=wt(d));let m;if(d.length===0){m=await a.subtle.importKey("jwk",l0,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:y,iterations:s,hash:{name:i}},x=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(b,x,{name:t,length:r},!0,["encrypt"])}catch{m=await a.subtle.importKey("jwk",l0,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:y,iterations:s,hash:{name:i}},x=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(b,x,{name:t,length:r},!0,["encrypt"])}let g=await a.subtle.encrypt(p,m,l);return Ct([y,p.iv,new Uint8Array(g)])}async function u(l,d){let y=l.subarray(0,o),h=l.subarray(o,o+n),p=l.subarray(o+n),m={name:t,iv:h};typeof d=="string"&&(d=wt(d));let g;if(d.length===0)try{let x={name:"PBKDF2",salt:y,iterations:s,hash:{name:i}},A=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(x,A,{name:t,length:r},!0,["decrypt"])}catch{g=await a.subtle.importKey("jwk",l0,{name:"AES-GCM"},!0,["decrypt"])}else{let x={name:"PBKDF2",salt:y,iterations:s,hash:{name:i}},A=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(x,A,{name:t,length:r},!0,["decrypt"])}let b=await a.subtle.decrypt(m,g,p);return new Uint8Array(b)}return{encrypt:c,decrypt:u}}async function Hn(e,t){let n=await h0().encrypt(e,t);return Zi.encode(n)}var _t;(function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.Secp256k1="Secp256k1"})(_t||(_t={}));var d0;(function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.Secp256k1=2]="Secp256k1"})(d0||(d0={}));(function(e){e.codec=()=>qr(d0)})(_t||(_t={}));var qe;(function(e){let t;e.codec=()=>(t==null&&(t=Ae((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),_t.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.Type=_t.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(s&7);break}}return i})),t),e.encode=r=>Se(r,e.codec()),e.decode=r=>Ee(r,e.codec())})(qe||(qe={}));var ze;(function(e){let t;e.codec=()=>(t==null&&(t=Ae((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),_t.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.Type=_t.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(s&7);break}}return i})),t),e.encode=r=>Se(r,e.codec()),e.decode=r=>Ee(r,e.codec())})(ze||(ze={}));var _i=class{_key;constructor(t){this._key=qn(t,Vn)}verify(t,r){return Ed(this._key,r,t)}marshal(){return this._key}get bytes(){return qe.encode({Type:_t.Ed25519,Data:this.marshal()}).subarray()}equals(t){return Kt(this.bytes,t.bytes)}hash(){let t=Xt.digest(this.bytes);return ge(t)?t.then(({bytes:r})=>r):t.bytes}},nn=class{_key;_publicKey;constructor(t,r){this._key=qn(t,ar),this._publicKey=qn(r,Vn)}sign(t){return vd(this._key,t)}get public(){return new _i(this._publicKey)}marshal(){return this._key}get bytes(){return ze.encode({Type:_t.Ed25519,Data:this.marshal()}).subarray()}equals(t){return Kt(this.bytes,t.bytes)}async hash(){let t=Xt.digest(this.bytes),r;return ge(t)?{bytes:r}=await t:r=t.bytes,r}async id(){let t=dr.digest(this.public.bytes);return Nt.encode(t.bytes).substring(1)}async export(t,r="libp2p-key"){if(r==="libp2p-key")return Hn(this.bytes,t);throw new W(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Dw(e){if(e.length>ar){e=qn(e,ar+Vn);let n=e.subarray(0,ar),i=e.subarray(ar,e.length);return new nn(n,i)}e=qn(e,ar);let t=e.subarray(0,ar),r=e.subarray(Vn);return new nn(t,r)}function Cw(e){return e=qn(e,Vn),new _i(e)}async function Bw(){let{privateKey:e,publicKey:t}=bd();return new nn(e,t)}async function Dd(e){let{privateKey:t,publicKey:r}=wd(e);return new nn(t,r)}function qn(e,t){if(e=Uint8Array.from(e??[]),e.length!==t)throw new W(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}var Iw={"P-256":256,"P-384":384,"P-521":521},Tw=Object.keys(Iw),IB=Tw.join(" / ");var b0={};ft(b0,{MAX_KEY_SIZE:()=>Ni,RsaPrivateKey:()=>zn,RsaPublicKey:()=>Li,fromJwk:()=>Fw,generateKeyPair:()=>Vw,unmarshalRsaPrivateKey:()=>Kw,unmarshalRsaPublicKey:()=>Mw});var Ri=Jt(xt(),1);var hI=Jt(_d(),1);function ws(e){if(isNaN(e)||e<=0)throw new W("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Yr(e)}var YB=Jt(gs(),1),g0=Jt(xt(),1);function kd(e,t){return t.map(r=>he(e[r]))}function Rd(e){return g0.default.pki.setRsaPrivateKey(...kd(e,["n","e","d","p","q","dp","dq","qi"]))}function Ld(e){return g0.default.pki.setRsaPublicKey(...kd(e,["n","e"]))}var sn={};ft(sn,{jwkToPkcs1:()=>Lw,jwkToPkix:()=>Pw,pkcs1ToJwk:()=>Rw,pkixToJwk:()=>Nw});var QB=Jt(Bi(),1),jB=Jt(gs(),1);var cr=Jt(xt(),1);function Rw(e){let t=cr.default.asn1.fromDer(at(e,"ascii")),r=cr.default.pki.privateKeyFromAsn1(t);return{kty:"RSA",n:_e(r.n),e:_e(r.e),d:_e(r.d),p:_e(r.p),q:_e(r.q),dp:_e(r.dP),dq:_e(r.dQ),qi:_e(r.qInv),alg:"RS256"}}function Lw(e){if(e.n==null||e.e==null||e.d==null||e.p==null||e.q==null||e.dp==null||e.dq==null||e.qi==null)throw new W("JWK was missing components","ERR_INVALID_PARAMETERS");let t=cr.default.pki.privateKeyToAsn1({n:he(e.n),e:he(e.e),d:he(e.d),p:he(e.p),q:he(e.q),dP:he(e.dp),dQ:he(e.dq),qInv:he(e.qi)});return wt(cr.default.asn1.toDer(t).getBytes(),"ascii")}function Nw(e){let t=cr.default.asn1.fromDer(at(e,"ascii")),r=cr.default.pki.publicKeyFromAsn1(t);return{kty:"RSA",n:_e(r.n),e:_e(r.e)}}function Pw(e){if(e.n==null||e.e==null)throw new W("JWK was missing components","ERR_INVALID_PARAMETERS");let t=cr.default.pki.publicKeyToAsn1({n:he(e.n),e:he(e.e)});return wt(cr.default.asn1.toDer(t).getBytes(),"ascii")}async function Nd(e){let t=await ue.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=await Od(t);return{privateKey:r[0],publicKey:r[1]}}async function x0(e){let r=[await ue.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Uw(e)],n=await Od({privateKey:r[0],publicKey:r[1]});return{privateKey:n[0],publicKey:n[1]}}async function Pd(e,t){let r=await ue.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await ue.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Ud(e,t,r){let n=await ue.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return ue.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}async function Od(e){if(e.privateKey==null||e.publicKey==null)throw new W("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([ue.get().subtle.exportKey("jwk",e.privateKey),ue.get().subtle.exportKey("jwk",e.publicKey)])}async function Uw(e){return ue.get().subtle.importKey("jwk",{kty:e.kty,n:e.n,e:e.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function Kd(e,t,r,n){let i=t?Ld(e):Rd(e),o=at(r instanceof Uint8Array?r:r.subarray(),"ascii"),s=n(o,i);return wt(s,"ascii")}function Md(e,t){return Kd(e,!0,t,(r,n)=>n.encrypt(r))}function Fd(e,t){return Kd(e,!1,t,(r,n)=>n.decrypt(r))}function vs(e){if(e.kty!=="RSA")throw new W("invalid key type","ERR_INVALID_KEY_TYPE");if(e.n==null)throw new W("invalid key modulus","ERR_INVALID_KEY_MODULUS");return wt(e.n,"base64url").length*8}var Ni=8192,Li=class{_key;constructor(t){this._key=t}verify(t,r){return Ud(this._key,r,t)}marshal(){return sn.jwkToPkix(this._key)}get bytes(){return qe.encode({Type:_t.RSA,Data:this.marshal()}).subarray()}encrypt(t){return Md(this._key,t)}equals(t){return Kt(this.bytes,t.bytes)}hash(){let t=Xt.digest(this.bytes);return ge(t)?t.then(({bytes:r})=>r):t.bytes}},zn=class{_key;_publicKey;constructor(t,r){this._key=t,this._publicKey=r}genSecret(){return ws(16)}sign(t){return Pd(this._key,t)}get public(){if(this._publicKey==null)throw new W("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Li(this._publicKey)}decrypt(t){return Fd(this._key,t)}marshal(){return sn.jwkToPkcs1(this._key)}get bytes(){return ze.encode({Type:_t.RSA,Data:this.marshal()}).subarray()}equals(t){return Kt(this.bytes,t.bytes)}hash(){let t=Xt.digest(this.bytes);return ge(t)?t.then(({bytes:r})=>r):t.bytes}async id(){let t=await this.public.hash();return at(t,"base58btc")}async export(t,r="pkcs-8"){if(r==="pkcs-8"){let n=new Ri.default.util.ByteBuffer(this.marshal()),i=Ri.default.asn1.fromDer(n),o=Ri.default.pki.privateKeyFromAsn1(i),s={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return Ri.default.pki.encryptRsaPrivateKey(o,t,s)}else{if(r==="libp2p-key")return Hn(this.bytes,t);throw new W(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}};async function Kw(e){let t=sn.pkcs1ToJwk(e);if(vs(t)>Ni)throw new W("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let r=await x0(t);return new zn(r.privateKey,r.publicKey)}function Mw(e){let t=sn.pkixToJwk(e);if(vs(t)>Ni)throw new W("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Li(t)}async function Fw(e){if(vs(e)>Ni)throw new W("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await x0(e);return new zn(t.privateKey,t.publicKey)}async function Vw(e){if(e>Ni)throw new W("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await Nd(e);return new zn(t.privateKey,t.publicKey)}var S0={};ft(S0,{Secp256k1PrivateKey:()=>Ui,Secp256k1PublicKey:()=>Pi,generateKeyPair:()=>Jw,unmarshalSecp256k1PrivateKey:()=>Qw,unmarshalSecp256k1PublicKey:()=>jw});function Hw(e){let t=gi(e);pe(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:r,Fp:n,a:i}=t;if(r){if(!n.eql(i,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:qw,hexToBytes:zw}=$o,an={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(e){let{Err:t}=an;if(e.length<2||e[0]!==2)throw new t("Invalid signature integer tag");let r=e[1],n=e.subarray(2,r+2);if(!r||n.length!==r)throw new t("Invalid signature integer: wrong length");if(n[0]&128)throw new t("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return{d:qw(n),l:e.subarray(r+2)}},toSig(e){let{Err:t}=an,r=typeof e=="string"?zw(e):e;if(!(r instanceof Uint8Array))throw new Error("ui8a expected");let n=r.length;if(n<2||r[0]!=48)throw new t("Invalid signature tag");if(r[1]!==n-2)throw new t("Invalid signature: incorrect length");let{d:i,l:o}=an._parseInt(r.subarray(2)),{d:s,l:a}=an._parseInt(o);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:i,s}},hexFromSig(e){let t=u=>Number.parseInt(u[0],16)&8?"00"+u:u,r=u=>{let f=u.toString(16);return f.length&1?`0${f}`:f},n=t(r(e.s)),i=t(r(e.r)),o=n.length/2,s=i.length/2,a=r(o),c=r(s);return`30${r(s+o+4)}02${c}${i}02${a}${n}`}},ur=BigInt(0),xe=BigInt(1),bI=BigInt(2),Vd=BigInt(3),wI=BigInt(4);function Gw(e){let t=Hw(e),{Fp:r}=t,n=t.toBytes||((h,p,m)=>{let g=p.toAffine();return rr(Uint8Array.from([4]),r.toBytes(g.x),r.toBytes(g.y))}),i=t.fromBytes||(h=>{let p=h.subarray(1),m=r.fromBytes(p.subarray(0,r.BYTES)),g=r.fromBytes(p.subarray(r.BYTES,2*r.BYTES));return{x:m,y:g}});function o(h){let{a:p,b:m}=t,g=r.sqr(h),b=r.mul(g,h);return r.add(r.add(b,r.mul(h,p)),m)}if(!r.eql(r.sqr(t.Gy),o(t.Gx)))throw new Error("bad generator point: equation left != right");function s(h){return typeof h=="bigint"&&ur<h&&h<t.n}function a(h){if(!s(h))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(h){let{allowedPrivateKeyLengths:p,nByteLength:m,wrapPrivateKey:g,n:b}=t;if(p&&typeof h!="bigint"){if(h instanceof Uint8Array&&(h=Je(h)),typeof h!="string"||!p.includes(h.length))throw new Error("Invalid key");h=h.padStart(m*2,"0")}let x;try{x=typeof h=="bigint"?h:tr(Et("private key",h,m))}catch{throw new Error(`private key must be ${m} bytes, hex or bigint, not ${typeof h}`)}return g&&(x=ht(x,b)),a(x),x}let u=new Map;function f(h){if(!(h instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(p,m,g){if(this.px=p,this.py=m,this.pz=g,p==null||!r.isValid(p))throw new Error("x required");if(m==null||!r.isValid(m))throw new Error("y required");if(g==null||!r.isValid(g))throw new Error("z required")}static fromAffine(p){let{x:m,y:g}=p||{};if(!p||!r.isValid(m)||!r.isValid(g))throw new Error("invalid affine point");if(p instanceof l)throw new Error("projective point not allowed");let b=x=>r.eql(x,r.ZERO);return b(m)&&b(g)?l.ZERO:new l(m,g,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(p){let m=r.invertBatch(p.map(g=>g.pz));return p.map((g,b)=>g.toAffine(m[b])).map(l.fromAffine)}static fromHex(p){let m=l.fromAffine(i(Et("pointHex",p)));return m.assertValidity(),m}static fromPrivateKey(p){return l.BASE.multiply(c(p))}_setWindowSize(p){this._WINDOW_SIZE=p,u.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!r.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:p,y:m}=this.toAffine();if(!r.isValid(p)||!r.isValid(m))throw new Error("bad point: x or y not FE");let g=r.sqr(m),b=o(p);if(!r.eql(g,b))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:p}=this.toAffine();if(r.isOdd)return!r.isOdd(p);throw new Error("Field doesn't support isOdd")}equals(p){f(p);let{px:m,py:g,pz:b}=this,{px:x,py:A,pz:v}=p,E=r.eql(r.mul(m,v),r.mul(x,b)),C=r.eql(r.mul(g,v),r.mul(A,b));return E&&C}negate(){return new l(this.px,r.neg(this.py),this.pz)}double(){let{a:p,b:m}=t,g=r.mul(m,Vd),{px:b,py:x,pz:A}=this,v=r.ZERO,E=r.ZERO,C=r.ZERO,B=r.mul(b,b),O=r.mul(x,x),K=r.mul(A,A),U=r.mul(b,x);return U=r.add(U,U),C=r.mul(b,A),C=r.add(C,C),v=r.mul(p,C),E=r.mul(g,K),E=r.add(v,E),v=r.sub(O,E),E=r.add(O,E),E=r.mul(v,E),v=r.mul(U,v),C=r.mul(g,C),K=r.mul(p,K),U=r.sub(B,K),U=r.mul(p,U),U=r.add(U,C),C=r.add(B,B),B=r.add(C,B),B=r.add(B,K),B=r.mul(B,U),E=r.add(E,B),K=r.mul(x,A),K=r.add(K,K),B=r.mul(K,U),v=r.sub(v,B),C=r.mul(K,O),C=r.add(C,C),C=r.add(C,C),new l(v,E,C)}add(p){f(p);let{px:m,py:g,pz:b}=this,{px:x,py:A,pz:v}=p,E=r.ZERO,C=r.ZERO,B=r.ZERO,O=t.a,K=r.mul(t.b,Vd),U=r.mul(m,x),F=r.mul(g,A),G=r.mul(b,v),Q=r.add(m,g),I=r.add(x,A);Q=r.mul(Q,I),I=r.add(U,F),Q=r.sub(Q,I),I=r.add(m,b);let R=r.add(x,v);return I=r.mul(I,R),R=r.add(U,G),I=r.sub(I,R),R=r.add(g,b),E=r.add(A,v),R=r.mul(R,E),E=r.add(F,G),R=r.sub(R,E),B=r.mul(O,I),E=r.mul(K,G),B=r.add(E,B),E=r.sub(F,B),B=r.add(F,B),C=r.mul(E,B),F=r.add(U,U),F=r.add(F,U),G=r.mul(O,G),I=r.mul(K,I),F=r.add(F,G),G=r.sub(U,G),G=r.mul(O,G),I=r.add(I,G),U=r.mul(F,I),C=r.add(C,U),U=r.mul(R,I),E=r.mul(Q,E),E=r.sub(E,U),U=r.mul(Q,F),B=r.mul(R,B),B=r.add(B,U),new l(E,C,B)}subtract(p){return this.add(p.negate())}is0(){return this.equals(l.ZERO)}wNAF(p){return y.wNAFCached(this,u,p,m=>{let g=r.invertBatch(m.map(b=>b.pz));return m.map((b,x)=>b.toAffine(g[x])).map(l.fromAffine)})}multiplyUnsafe(p){let m=l.ZERO;if(p===ur)return m;if(a(p),p===xe)return this;let{endo:g}=t;if(!g)return y.unsafeLadder(this,p);let{k1neg:b,k1:x,k2neg:A,k2:v}=g.splitScalar(p),E=m,C=m,B=this;for(;x>ur||v>ur;)x&xe&&(E=E.add(B)),v&xe&&(C=C.add(B)),B=B.double(),x>>=xe,v>>=xe;return b&&(E=E.negate()),A&&(C=C.negate()),C=new l(r.mul(C.px,g.beta),C.py,C.pz),E.add(C)}multiply(p){a(p);let m=p,g,b,{endo:x}=t;if(x){let{k1neg:A,k1:v,k2neg:E,k2:C}=x.splitScalar(m),{p:B,f:O}=this.wNAF(v),{p:K,f:U}=this.wNAF(C);B=y.constTimeNegate(A,B),K=y.constTimeNegate(E,K),K=new l(r.mul(K.px,x.beta),K.py,K.pz),g=B.add(K),b=O.add(U)}else{let{p:A,f:v}=this.wNAF(m);g=A,b=v}return l.normalizeZ([g,b])[0]}multiplyAndAddUnsafe(p,m,g){let b=l.BASE,x=(v,E)=>E===ur||E===xe||!v.equals(b)?v.multiplyUnsafe(E):v.multiply(E),A=x(this,m).add(x(p,g));return A.is0()?void 0:A}toAffine(p){let{px:m,py:g,pz:b}=this,x=this.is0();p==null&&(p=x?r.ONE:r.inv(b));let A=r.mul(m,p),v=r.mul(g,p),E=r.mul(b,p);if(x)return{x:r.ZERO,y:r.ZERO};if(!r.eql(E,r.ONE))throw new Error("invZ was invalid");return{x:A,y:v}}isTorsionFree(){let{h:p,isTorsionFree:m}=t;if(p===xe)return!0;if(m)return m(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:p,clearCofactor:m}=t;return p===xe?this:m?m(l,this):this.multiplyUnsafe(t.h)}toRawBytes(p=!0){return this.assertValidity(),n(l,this,p)}toHex(p=!0){return Je(this.toRawBytes(p))}}l.BASE=new l(t.Gx,t.Gy,r.ONE),l.ZERO=new l(r.ZERO,r.ONE,r.ZERO);let d=t.nBitLength,y=Zo(l,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:s}}function Ww(e){let t=gi(e);return pe(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Hd(e){let t=Ww(e),{Fp:r,n}=t,i=r.BYTES+1,o=2*r.BYTES+1;function s(I){return ur<I&&I<r.ORDER}function a(I){return ht(I,n)}function c(I){return Yo(I,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:l,isWithinCurveOrder:d}=Gw({...t,toBytes(I,R,_){let k=R.toAffine(),S=r.toBytes(k.x),P=rr;return _?P(Uint8Array.from([R.hasEvenY()?2:3]),S):P(Uint8Array.from([4]),S,r.toBytes(k.y))},fromBytes(I){let R=I.length,_=I[0],k=I.subarray(1);if(R===i&&(_===2||_===3)){let S=tr(k);if(!s(S))throw new Error("Point is not on curve");let P=l(S),M=r.sqrt(P),H=(M&xe)===xe;return(_&1)===1!==H&&(M=r.neg(M)),{x:S,y:M}}else if(R===o&&_===4){let S=r.fromBytes(k.subarray(0,r.BYTES)),P=r.fromBytes(k.subarray(r.BYTES,2*r.BYTES));return{x:S,y:P}}else throw new Error(`Point of length ${R} was invalid. Expected ${i} compressed bytes or ${o} uncompressed bytes`)}}),y=I=>Je(Ar(I,t.nByteLength));function h(I){let R=n>>xe;return I>R}function p(I){return h(I)?a(-I):I}let m=(I,R,_)=>tr(I.slice(R,_));class g{constructor(R,_,k){this.r=R,this.s=_,this.recovery=k,this.assertValidity()}static fromCompact(R){let _=t.nByteLength;return R=Et("compactSignature",R,_*2),new g(m(R,0,_),m(R,_,2*_))}static fromDER(R){let{r:_,s:k}=an.toSig(Et("DER",R));return new g(_,k)}assertValidity(){if(!d(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!d(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(R){return new g(this.r,this.s,R)}recoverPublicKey(R){let{r:_,s:k,recovery:S}=this,P=C(Et("msgHash",R));if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");let M=S===2||S===3?_+t.n:_;if(M>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let H=S&1?"03":"02",Z=u.fromHex(H+y(M)),j=c(M),it=a(-P*j),J=a(k*j),et=u.BASE.multiplyAndAddUnsafe(Z,it,J);if(!et)throw new Error("point at infinify");return et.assertValidity(),et}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return Xr(this.toDERHex())}toDERHex(){return an.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Xr(this.toCompactHex())}toCompactHex(){return y(this.r)+y(this.s)}}let b={isValidPrivateKey(I){try{return f(I),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let I=Pc(t.n);return Ll(t.randomBytes(I),t.n)},precompute(I=8,R=u.BASE){return R._setWindowSize(I),R.multiply(BigInt(3)),R}};function x(I,R=!0){return u.fromPrivateKey(I).toRawBytes(R)}function A(I){let R=I instanceof Uint8Array,_=typeof I=="string",k=(R||_)&&I.length;return R?k===i||k===o:_?k===2*i||k===2*o:I instanceof u}function v(I,R,_=!0){if(A(I))throw new Error("first arg must be private key");if(!A(R))throw new Error("second arg must be public key");return u.fromHex(R).multiply(f(I)).toRawBytes(_)}let E=t.bits2int||function(I){let R=tr(I),_=I.length*8-t.nBitLength;return _>0?R>>BigInt(_):R},C=t.bits2int_modN||function(I){return a(E(I))},B=mi(t.nBitLength);function O(I){if(typeof I!="bigint")throw new Error("bigint expected");if(!(ur<=I&&I<B))throw new Error(`bigint expected < 2^${t.nBitLength}`);return Ar(I,t.nByteLength)}function K(I,R,_=U){if(["recovered","canonical"].some(gt=>gt in _))throw new Error("sign() legacy options not supported");let{hash:k,randomBytes:S}=t,{lowS:P,prehash:M,extraEntropy:H}=_;P==null&&(P=!0),I=Et("msgHash",I),M&&(I=Et("prehashed msgHash",k(I)));let Z=C(I),j=f(R),it=[O(j),O(Z)];if(H!=null){let gt=H===!0?S(r.BYTES):H;it.push(Et("extraEntropy",gt))}let J=rr(...it),et=Z;function bt(gt){let $t=E(gt);if(!d($t))return;let Yt=c($t),Ft=u.BASE.multiply($t).toAffine(),jt=a(Ft.x);if(jt===ur)return;let We=a(Yt*a(et+jt*j));if(We===ur)return;let Lr=(Ft.x===jt?0:2)|Number(Ft.y&xe),ti=We;return P&&h(We)&&(ti=p(We),Lr^=1),new g(jt,ti,Lr)}return{seed:J,k2sig:bt}}let U={lowS:t.lowS,prehash:!1},F={lowS:t.lowS,prehash:!1};function G(I,R,_=U){let{seed:k,k2sig:S}=K(I,R,_),P=t;return _c(P.hash.outputLen,P.nByteLength,P.hmac)(k,S)}u.BASE._setWindowSize(8);function Q(I,R,_,k=F){let S=I;if(R=Et("msgHash",R),_=Et("publicKey",_),"strict"in k)throw new Error("options.strict was renamed to lowS");let{lowS:P,prehash:M}=k,H,Z;try{if(typeof S=="string"||S instanceof Uint8Array)try{H=g.fromDER(S)}catch(Ft){if(!(Ft instanceof an.Err))throw Ft;H=g.fromCompact(S)}else if(typeof S=="object"&&typeof S.r=="bigint"&&typeof S.s=="bigint"){let{r:Ft,s:jt}=S;H=new g(Ft,jt)}else throw new Error("PARSE");Z=u.fromHex(_)}catch(Ft){if(Ft.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(P&&H.hasHighS())return!1;M&&(R=t.hash(R));let{r:j,s:it}=H,J=C(R),et=c(it),bt=a(J*et),gt=a(j*et),$t=u.BASE.multiplyAndAddUnsafe(Z,bt,gt)?.toAffine();return $t?a($t.x)===j:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:v,sign:G,verify:Q,ProjectivePoint:u,Signature:g,utils:b}}function $w(e){return{hash:e,hmac:(t,...r)=>Nn(e,t,Ho(...r)),randomBytes:Yr}}function qd(e,t){let r=n=>Hd({...e,...$w(n)});return Object.freeze({...r(t),create:r})}var Wd=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),zd=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Yw=BigInt(1),w0=BigInt(2),Gd=(e,t)=>(e+t/w0)/t;function Xw(e){let t=Wd,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,f=u*u*e%t,l=St(f,r,t)*f%t,d=St(l,r,t)*f%t,y=St(d,w0,t)*u%t,h=St(y,i,t)*y%t,p=St(h,o,t)*h%t,m=St(p,a,t)*p%t,g=St(m,c,t)*m%t,b=St(g,a,t)*p%t,x=St(b,r,t)*f%t,A=St(x,s,t)*h%t,v=St(A,n,t)*u%t,E=St(v,w0,t);if(!v0.eql(v0.sqr(E),e))throw new Error("Cannot find square root");return E}var v0=Xo(Wd,void 0,void 0,{sqrt:Xw}),ke=qd({a:BigInt(0),b:BigInt(7),Fp:v0,n:zd,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=zd,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Yw*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,s=BigInt("0x100000000000000000000000000000000"),a=Gd(o*e,t),c=Gd(-n*e,t),u=ht(e-a*r-c*i,t),f=ht(-a*n-c*o,t),l=u>s,d=f>s;if(l&&(u=t-u),d&&(f=t-f),u>s||f>s)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:l,k1:u,k2neg:d,k2:f}}}},Pn),TI=BigInt(0);var _I=ke.ProjectivePoint;function $d(){return ke.utils.randomPrivateKey()}function Yd(e,t){let r=Xt.digest(t instanceof Uint8Array?t:t.subarray());if(ge(r))return r.then(({digest:n})=>ke.sign(n,e).toDERRawBytes()).catch(n=>{throw new W(String(n),"ERR_INVALID_INPUT")});try{return ke.sign(r.digest,e).toDERRawBytes()}catch(n){throw new W(String(n),"ERR_INVALID_INPUT")}}function Xd(e,t,r){let n=Xt.digest(r instanceof Uint8Array?r:r.subarray());if(ge(n))return n.then(({digest:i})=>ke.verify(t,i,e)).catch(i=>{throw new W(String(i),"ERR_INVALID_INPUT")});try{return ke.verify(t,n.digest,e)}catch(i){throw new W(String(i),"ERR_INVALID_INPUT")}}function Zd(e){return ke.ProjectivePoint.fromHex(e).toRawBytes(!0)}function Qd(e){try{ke.getPublicKey(e,!0)}catch(t){throw new W(String(t),"ERR_INVALID_PRIVATE_KEY")}}function E0(e){try{ke.ProjectivePoint.fromHex(e)}catch(t){throw new W(String(t),"ERR_INVALID_PUBLIC_KEY")}}function jd(e){try{return ke.getPublicKey(e,!0)}catch(t){throw new W(String(t),"ERR_INVALID_PRIVATE_KEY")}}var Pi=class{_key;constructor(t){E0(t),this._key=t}verify(t,r){return Xd(this._key,r,t)}marshal(){return Zd(this._key)}get bytes(){return qe.encode({Type:_t.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return Kt(this.bytes,t.bytes)}async hash(){let t=Xt.digest(this.bytes),r;return ge(t)?{bytes:r}=await t:r=t.bytes,r}},Ui=class{_key;_publicKey;constructor(t,r){this._key=t,this._publicKey=r??jd(t),Qd(this._key),E0(this._publicKey)}sign(t){return Yd(this._key,t)}get public(){return new Pi(this._publicKey)}marshal(){return this._key}get bytes(){return ze.encode({Type:_t.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return Kt(this.bytes,t.bytes)}hash(){let t=Xt.digest(this.bytes);return ge(t)?t.then(({bytes:r})=>r):t.bytes}async id(){let t=await this.public.hash();return at(t,"base58btc")}async export(t,r="libp2p-key"){if(r==="libp2p-key")return Hn(this.bytes,t);throw new W(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Qw(e){return new Ui(e)}function jw(e){return new Pi(e)}async function Jw(){let e=$d();return new Ui(e)}var cn={rsa:b0,ed25519:p0,secp256k1:S0};function Jd(e){let t=Object.keys(cn).join(" / ");return new W(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function tp(e){let t=qe.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case _t.RSA:return cn.rsa.unmarshalRsaPublicKey(r);case _t.Ed25519:return cn.ed25519.unmarshalEd25519PublicKey(r);case _t.Secp256k1:return cn.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw Jd(t.Type??"unknown")}}async function ep(e){let t=ze.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case _t.RSA:return cn.rsa.unmarshalRsaPrivateKey(r);case _t.Ed25519:return cn.ed25519.unmarshalEd25519PrivateKey(r);case _t.Secp256k1:return cn.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw Jd(t.Type??"RSA")}}var Es;(function(e){let t;e.codec=()=>(t==null&&(t=Ae((r,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),r.webtransportCerthashes!=null)for(let o of r.webtransportCerthashes)n.uint32(10),n.bytes(o);i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={webtransportCerthashes:[]},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:{i.webtransportCerthashes.push(r.bytes());break}default:{r.skipType(s&7);break}}}return i})),t),e.encode=r=>Se(r,e.codec()),e.decode=r=>Ee(r,e.codec())})(Es||(Es={}));var Oi;(function(e){let t;e.codec=()=>(t==null&&(t=Ae((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.identityKey!=null&&r.identityKey.byteLength>0&&(n.uint32(10),n.bytes(r.identityKey)),r.identitySig!=null&&r.identitySig.byteLength>0&&(n.uint32(18),n.bytes(r.identitySig)),r.extensions!=null&&(n.uint32(34),Es.codec().encode(r.extensions,n)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={identityKey:ot(0),identitySig:ot(0)},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:{i.identityKey=r.bytes();break}case 2:{i.identitySig=r.bytes();break}case 4:{i.extensions=Es.codec().decode(r,r.uint32());break}default:{r.skipType(s&7);break}}}return i})),t),e.encode=r=>Se(r,e.codec()),e.decode=r=>Ee(r,e.codec())})(Oi||(Oi={}));async function rp(e,t,r){let n=await rv(e,np(t));if(e.publicKey==null)throw new Error("PublicKey was missing from local PeerId");return ev(e.publicKey,n,r)}function ev(e,t,r){return Oi.encode({identityKey:e,identitySig:t,extensions:r??{webtransportCerthashes:[]}}).subarray()}async function rv(e,t){if(e.privateKey==null)throw new Error("PrivateKey was missing from PeerId");return(await ep(e.privateKey)).sign(t)}async function A0(e){return ha(e.identityKey)}function D0(e){return Oi.decode(e)}function np(e){let t=wt("noise-libp2p-static-key:");return e instanceof Uint8Array?Ct([t,e],t.length+e.length):(e.prepend(t),e)}async function C0(e,t,r){let n=await ha(t.identityKey);if(!n.equals(r))throw new Error(`Payload identity key ${n.toString()} does not match expected remote peer ${r.toString()}`);let i=np(e);if(n.publicKey==null)throw new Error("PublicKey was missing from PeerId");if(t.identitySig==null)throw new Error("Signature was missing from message");if(!await tp(n.publicKey).verify(i,t.identitySig))throw new Error("Static key doesn't match to peer that signed payload!");return n}function Ki(e){return!(!(e instanceof Uint8Array)&&!En(e)||e.byteLength!==32)}var nv=0,iv=4294967295,ov="Cipherstate has reached maximum n, a new handshake must be performed",Ss=class{n;bytes;view;constructor(t=nv){this.n=t,this.bytes=ot(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>iv)throw new Error(ov)}};var As=class{crypto;log;constructor(t,r){this.log=t.logger.forComponent("libp2p:noise:abstract-handshake"),this.crypto=r}encryptWithAd(t,r,n){let i=this.encrypt(t.k,t.n,r,n);return t.n.increment(),i}decryptWithAd(t,r,n,i){let{plaintext:o,valid:s}=this.decrypt(t.k,t.n,r,n,i);return s&&t.n.increment(),{plaintext:o,valid:s}}hasKey(t){return!this.isEmptyKey(t.k)}createEmptyKey(){return ot(32)}isEmptyKey(t){let r=this.createEmptyKey();return Kt(r,t)}encrypt(t,r,n,i){return r.assertValue(),this.crypto.chaCha20Poly1305Encrypt(i,r.getBytes(),n,t)}encryptAndHash(t,r){let n;return this.hasKey(t.cs)?n=this.encryptWithAd(t.cs,t.h,r):n=r,this.mixHash(t,n),n}decrypt(t,r,n,i,o){r.assertValue();let s=this.crypto.chaCha20Poly1305Decrypt(i,r.getBytes(),n,t,o);return s?{plaintext:s,valid:!0}:{plaintext:ot(0),valid:!1}}decryptAndHash(t,r){let n,i=!0;return this.hasKey(t.cs)?{plaintext:n,valid:i}=this.decryptWithAd(t.cs,t.h,r):n=r,this.mixHash(t,r),{plaintext:n,valid:i}}dh(t,r){try{let n=this.crypto.generateX25519SharedKey(t,r);return n.length===32?n:n.subarray(0,32)}catch(n){let i=n;return this.log.error("error deriving shared key",i),ot(32)}}mixHash(t,r){t.h=this.getHash(t.h,r)}getHash(t,r){return this.crypto.hashSHA256(new Bt(t,r))}mixKey(t,r){let[n,i]=this.crypto.getHKDF(t.ck,r);t.cs=this.initializeKey(i),t.ck=n}initializeKey(t){return{k:t,n:new Ss}}initializeSymmetric(t){let r=wt(t,"utf-8"),n=this.hashProtocolName(r),i=n,o=this.createEmptyKey();return{cs:this.initializeKey(o),ck:i,h:n}}hashProtocolName(t){if(t.length<=32){let r=ot(32);return r.set(t),r}else return this.getHash(t,ot(0))}split(t){let[r,n]=this.crypto.getHKDF(t.ck,ot(0)),i=this.initializeKey(r),o=this.initializeKey(n);return{cs1:i,cs2:o}}writeMessageRegular(t,r){let n=this.encryptWithAd(t,ot(0),r),i=this.createEmptyKey(),o=ot(0);return{ne:i,ns:o,ciphertext:n}}readMessageRegular(t,r){return this.decryptWithAd(t,ot(0),r.ciphertext)}};var Ds=class extends As{initializeInitiator(t,r,n,i){let o="Noise_XX_25519_ChaChaPoly_SHA256",s=this.initializeSymmetric(o);this.mixHash(s,t);let a=ot(32);return{ss:s,s:r,rs:n,psk:i,re:a}}initializeResponder(t,r,n,i){let o="Noise_XX_25519_ChaChaPoly_SHA256",s=this.initializeSymmetric(o);this.mixHash(s,t);let a=ot(32);return{ss:s,s:r,rs:n,psk:i,re:a}}writeMessageA(t,r,n){let i=ot(0);n!==void 0?t.e=n:t.e=this.crypto.generateX25519KeyPair();let o=t.e.publicKey;this.mixHash(t.ss,o);let s=this.encryptAndHash(t.ss,r);return{ne:o,ns:i,ciphertext:s}}writeMessageB(t,r){t.e=this.crypto.generateX25519KeyPair();let n=t.e.publicKey;this.mixHash(t.ss,n),this.mixKey(t.ss,this.dh(t.e.privateKey,t.re));let i=t.s.publicKey,o=this.encryptAndHash(t.ss,i);this.mixKey(t.ss,this.dh(t.s.privateKey,t.re));let s=this.encryptAndHash(t.ss,r);return{ne:n,ns:o,ciphertext:s}}writeMessageC(t,r){let n=t.s.publicKey,i=this.encryptAndHash(t.ss,n);this.mixKey(t.ss,this.dh(t.s.privateKey,t.re));let o=this.encryptAndHash(t.ss,r),a={ne:this.createEmptyKey(),ns:i,ciphertext:o},{cs1:c,cs2:u}=this.split(t.ss);return{h:t.ss.h,messageBuffer:a,cs1:c,cs2:u}}readMessageA(t,r){return Ki(r.ne)&&(t.re=r.ne),this.mixHash(t.ss,t.re),this.decryptAndHash(t.ss,r.ciphertext)}readMessageB(t,r){if(Ki(r.ne)&&(t.re=r.ne),this.mixHash(t.ss,t.re),!t.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(t.ss,this.dh(t.e.privateKey,t.re));let{plaintext:n,valid:i}=this.decryptAndHash(t.ss,r.ns);i&&Ki(n)&&(t.rs=n),this.mixKey(t.ss,this.dh(t.e.privateKey,t.rs));let{plaintext:o,valid:s}=this.decryptAndHash(t.ss,r.ciphertext);return{plaintext:o,valid:i&&s}}readMessageC(t,r){let{plaintext:n,valid:i}=this.decryptAndHash(t.ss,r.ns);if(i&&Ki(n)&&(t.rs=n),!t.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(t.ss,this.dh(t.e.privateKey,t.rs));let{plaintext:o,valid:s}=this.decryptAndHash(t.ss,r.ciphertext),{cs1:a,cs2:c}=this.split(t.ss);return{h:t.ss.h,plaintext:o,valid:i&&s,cs1:a,cs2:c}}initSession(t,r,n){let i=this.createEmptyKey(),o=ot(32),s;return t?s=this.initializeInitiator(r,n,o,i):s=this.initializeResponder(r,n,o,i),{hs:s,i:t,mc:0}}sendMessage(t,r,n){let i;if(t.mc===0)i=this.writeMessageA(t.hs,r,n);else if(t.mc===1)i=this.writeMessageB(t.hs,r);else if(t.mc===2){let{h:o,messageBuffer:s,cs1:a,cs2:c}=this.writeMessageC(t.hs,r);i=s,t.h=o,t.cs1=a,t.cs2=c}else if(t.mc>2)if(t.i){if(!t.cs1)throw new Error("CS1 (cipher state) is not defined");i=this.writeMessageRegular(t.cs1,r)}else{if(!t.cs2)throw new Error("CS2 (cipher state) is not defined");i=this.writeMessageRegular(t.cs2,r)}else throw new Error("Session invalid.");return t.mc++,i}recvMessage(t,r){let n=ot(0),i=!1;if(t.mc===0)({plaintext:n,valid:i}=this.readMessageA(t.hs,r));else if(t.mc===1)({plaintext:n,valid:i}=this.readMessageB(t.hs,r));else if(t.mc===2){let{h:o,plaintext:s,valid:a,cs1:c,cs2:u}=this.readMessageC(t.hs,r);n=s,i=a,t.h=o,t.cs1=c,t.cs2=u}return t.mc++,{plaintext:n,valid:i}}};function ip(e,t){!t.enabled||!In||(t(`LOCAL_STATIC_PUBLIC_KEY ${at(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${at(e.privateKey,"hex")}`))}function B0(e,t){!t.enabled||!In||(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${at(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${at(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function op(e,t){!t.enabled||!In||t(`REMOTE_STATIC_PUBLIC_KEY ${at(e.subarray(),"hex")}`)}function I0(e,t){!t.enabled||!In||t(`REMOTE_EPHEMERAL_PUBLIC_KEY ${at(e.subarray(),"hex")}`)}function sp(e,t){!t.enabled||!In||(e.cs1&&e.cs2?(t(`CIPHER_STATE_1 ${e.cs1.n.getUint64()} ${at(e.cs1.k,"hex")}`),t(`CIPHER_STATE_2 ${e.cs2.n.getUint64()} ${at(e.cs2.k,"hex")}`)):t("Missing cipher state."))}var Cs=class{isInitiator;session;remotePeer;remoteExtensions={webtransportCerthashes:[]};payload;connection;xx;staticKeypair;prologue;log;constructor(t,r,n,i,o,s,a,c,u){this.log=t.logger.forComponent("libp2p:noise:xxhandshake"),this.isInitiator=r,this.payload=n,this.prologue=i,this.staticKeypair=s,this.connection=a,c&&(this.remotePeer=c),this.xx=u??new Ds(t,o),this.session=this.xx.initSession(this.isInitiator,this.prologue,this.staticKeypair)}async propose(){if(ip(this.session.hs.s,this.log),this.isInitiator){this.log.trace("Stage 0 - Initiator starting to send first message.");let t=this.xx.sendMessage(this.session,ot(0));await this.connection.write(Gl(t)),this.log.trace("Stage 0 - Initiator finished sending first message."),B0(this.session.hs.e,this.log)}else{this.log.trace("Stage 0 - Responder waiting to receive first message...");let t=Yl((await this.connection.read()).subarray()),{valid:r}=this.xx.recvMessage(this.session,t);if(!r)throw new Qr("xx handshake stage 0 validation fail");this.log.trace("Stage 0 - Responder received first message."),I0(this.session.hs.re,this.log)}}async exchange(){if(this.isInitiator){this.log.trace("Stage 1 - Initiator waiting to receive first message from responder...");let t=Xl((await this.connection.read()).subarray()),{plaintext:r,valid:n}=this.xx.recvMessage(this.session,t);if(!n)throw new Qr("xx handshake stage 1 validation fail");this.log.trace("Stage 1 - Initiator received the message."),I0(this.session.hs.re,this.log),op(this.session.hs.rs,this.log),this.log.trace("Initiator going to check remote's signature...");try{let i=D0(r);this.remotePeer=this.remotePeer||await A0(i),await C0(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let o=i;throw new Si(`Error occurred while verifying signed payload: ${o.message}`)}this.log.trace("All good with the signature!")}else{this.log.trace("Stage 1 - Responder sending out first message with signed payload and static key.");let t=this.xx.sendMessage(this.session,this.payload);await this.connection.write(Wl(t)),this.log.trace("Stage 1 - Responder sent the second handshake message with signed payload."),B0(this.session.hs.e,this.log)}}async finish(){if(this.isInitiator){this.log.trace("Stage 2 - Initiator sending third handshake message.");let t=this.xx.sendMessage(this.session,this.payload);await this.connection.write($l(t)),this.log.trace("Stage 2 - Initiator sent message with signed payload.")}else{this.log.trace("Stage 2 - Responder waiting for third handshake message...");let t=Zl((await this.connection.read()).subarray()),{plaintext:r,valid:n}=this.xx.recvMessage(this.session,t);if(!n)throw new Qr("xx handshake stage 2 validation fail");this.log.trace("Stage 2 - Responder received the message, finished handshake.");try{let i=D0(r);this.remotePeer=this.remotePeer||await A0(i),await C0(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let o=i;throw new Si(`Error occurred while verifying signed payload: ${o.message}`)}}sp(this.session,this.log)}encrypt(t,r){let n=this.getCS(r);return this.xx.encryptWithAd(n,ot(0),t)}decrypt(t,r,n){let i=this.getCS(r,!1);return this.xx.decryptWithAd(i,ot(0),t,n)}getRemoteStaticKey(){return this.session.hs.rs}getCS(t,r=!0){if(!t.cs1||!t.cs2)throw new Qr("Handshake not completed properly, cipher state does not exist.");return this.isInitiator?r?t.cs1:t.cs2:r?t.cs2:t.cs1}setRemoteNoiseExtension(t){t&&(this.remoteExtensions=t)}};function ap(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}var Bs=class{protocol="/noise";crypto;prologue;staticKeys;extensions;metrics;components;constructor(t,r={}){let{staticNoiseKey:n,extensions:i,crypto:o,prologueBytes:s}=r,{metrics:a}=t;this.components=t,this.crypto=o??zl,this.extensions=i,this.metrics=a?ap(a):void 0,n?this.staticKeys=this.crypto.generateX25519KeyPairFromSeed(n):this.staticKeys=this.crypto.generateX25519KeyPair(),this.prologue=s??ot(0)}async secureOutbound(t,r,n){let i=pi(r,{lengthEncoder:Un,lengthDecoder:vi,maxDataLength:65535}),o=await this.performHandshake({connection:i,isInitiator:!0,localPeer:t,remotePeer:n}),s=await this.createSecureConnection(i,o);return r.source=s.source,r.sink=s.sink,{conn:r,remoteExtensions:o.remoteExtensions,remotePeer:o.remotePeer}}async secureInbound(t,r,n){let i=pi(r,{lengthEncoder:Un,lengthDecoder:vi,maxDataLength:65535}),o=await this.performHandshake({connection:i,isInitiator:!1,localPeer:t,remotePeer:n}),s=await this.createSecureConnection(i,o);return r.source=s.source,r.sink=s.sink,{conn:r,remotePeer:o.remotePeer,remoteExtensions:o.remoteExtensions}}async performHandshake(t){let r=await rp(t.localPeer,this.staticKeys.publicKey,this.extensions);return this.performXXHandshake(t,r)}async performXXHandshake(t,r){let{isInitiator:n,remotePeer:i,connection:o}=t,s=new Cs(this.components,n,r,this.prologue,this.crypto,this.staticKeys,o,i);try{await s.propose(),await s.exchange(),await s.finish(),this.metrics?.xxHandshakeSuccesses.increment()}catch(a){if(this.metrics?.xxHandshakeErrors.increment(),a instanceof Error)throw a.message=`Error occurred during XX handshake: ${a.message}`,a}return s}async createSecureConnection(t,r){let[n,i]=sl(),o=t.unwrap();return await cl(n,Jl(r,this.metrics),o,s=>Fr(s,{lengthDecoder:vi}),th(r,this.metrics),n),i}};function cp(e={}){return t=>new Bs(t,e)}var K1=Jt(iu(),1);var k1=Jt(iu(),1);var ou=Object.values(Ne).map(e=>e.decoder).reduce((e,t)=>e.or(t));function R1(e,t){let r=e.getConfiguration().certificates?.at(0);if(r==null||r.getFingerprints==null){t.log.trace("fetching fingerprint from local SDP");let i=e.localDescription;return i==null?void 0:hE(i.sdp)}if(t.log.trace("fetching fingerprint from local certificate"),r.getFingerprints().length===0)return;let n=r.getFingerprints()[0].value;if(n==null)throw Ha("","no fingerprint on local certificate");return n}var lE=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function hE(e){return e.match(lE)?.groups?.fingerprint}function dE(e){for(let t of e.protoNames())if(t.startsWith("ip"))return t.toUpperCase();return"IP6"}function Ms(e){let r=e.stringTuples().filter(n=>n[0]===P1).map(n=>n[1])[0];if(r===void 0||r==="")throw fo(`Couldn't find a certhash component of multiaddr: ${e.toString()}`);return r}function su(e){let t=ou.decode(e);return k1.decode(t)}function pE(e){let t=su(Ms(e)),r=au(t.name),n=t.digest.reduce((o,s)=>o+s.toString(16).padStart(2,"0"),""),i=n.match(/.{1,2}/g);if(i==null)throw Ha(n,e.toString());return[`${r.toUpperCase()} ${i.join(":").toUpperCase()}`,n]}function au(e){switch(e){case"sha1":return"sha-1";case"sha2-256":return"sha-256";case"sha2-512":return"sha-512";default:throw mf(e)}}function yE(e,t){let{host:r,port:n}=e.toOptions(),i=dE(e),[o]=pE(e);return`v=0
29
+ `});var y1=dt(()=>{p1();ks();kr();Z0();qi()});var J0,Y_,m1=dt(()=>{qp();zp();Gp();Wp();$p();V0();Yp();z0();Xp();Qp();s1();u1();f1();l1();y1();J0={...P0,...U0,...O0,...K0,...M0,...F0,...H0,...q0,...G0,...W0},Y_={...Q0,...j0}});function Qn(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}var Ps=dt(()=>{});function Us(e=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Qn(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}var tu=dt(()=>{Ps()});function x1(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}var g1,eu,J8,Os,ru=dt(()=>{m1();tu();g1=x1("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),eu=x1("ascii","a",e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},e=>{e=e.substring(1);let t=Us(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}),J8={utf8:g1,"utf-8":g1,hex:J0.base16,latin1:eu,ascii:eu,binary:eu,...J0},Os=J8});var b1={};ft(b1,{toString:()=>tE});function tE(e,t="utf8"){let r=Os[t];if(!r)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"):r.encoder.encode(e).substring(1)}var w1=dt(()=>{ru()});var v1={};ft(v1,{fromString:()=>eE});function eE(e,t="utf8"){let r=Os[t];if(!r)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Qn(globalThis.Buffer.from(e,"utf-8")):r.decoder.decode(`${r.prefix}${e}`)}var E1=dt(()=>{ru();Ps()});var S1={};ft(S1,{concat:()=>rE});function rE(e,t){t||(t=e.reduce((i,o)=>i+o.length,0));let r=Us(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return Qn(r)}var A1=dt(()=>{tu();Ps()});var iu=st((ak,_1)=>{"use strict";var D1=Ep(),jn=Lp(),{names:Gi}=Pp(),{toString:Ks}=(w1(),$i(b1)),{fromString:nE}=(E1(),$i(v1)),{concat:iE}=(A1(),$i(S1)),Jn={};for(let e in Gi){let t=e;Jn[Gi[t]]=t}Object.freeze(Jn);function oE(e){if(!(e instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return Ks(e,"base16")}function sE(e){return nE(e,"base16")}function aE(e){if(!(e instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return Ks(D1.encode("base58btc",e)).slice(1)}function cE(e){let t=e instanceof Uint8Array?Ks(e):e;return D1.decode("z"+t)}function C1(e){if(!(e instanceof Uint8Array))throw new Error("multihash must be a Uint8Array");if(e.length<2)throw new Error("multihash too short. must be > 2 bytes.");let t=jn.decode(e);if(!I1(t))throw new Error(`multihash unknown function code: 0x${t.toString(16)}`);e=e.slice(jn.decode.bytes);let r=jn.decode(e);if(r<0)throw new Error(`multihash invalid length: ${r}`);if(e=e.slice(jn.decode.bytes),e.length!==r)throw new Error(`multihash length inconsistent: 0x${Ks(e,"base16")}`);return{code:t,name:Jn[t],length:r,digest:e}}function uE(e,t,r){if(!e||t===void 0)throw new Error("multihash encode requires at least two args: digest, code");let n=B1(t);if(!(e instanceof Uint8Array))throw new Error("digest should be a Uint8Array");if(r==null&&(r=e.length),r&&e.length!==r)throw new Error("digest length should be equal to specified length.");let i=jn.encode(n),o=jn.encode(r);return iE([i,o,e],i.length+o.length+e.length)}function B1(e){let t=e;if(typeof e=="string"){if(Gi[e]===void 0)throw new Error(`Unrecognized hash function named: ${e}`);t=Gi[e]}if(typeof t!="number")throw new Error(`Hash function code should be a number. Got: ${t}`);if(Jn[t]===void 0&&!nu(t))throw new Error(`Unrecognized function code: ${t}`);return t}function nu(e){return e>0&&e<16}function I1(e){return!!(nu(e)||Jn[e])}function T1(e){C1(e)}function fE(e){return T1(e),e.subarray(0,2)}_1.exports={names:Gi,codes:Jn,toHexString:oE,fromHexString:sE,toB58String:aE,fromB58String:cE,decode:C1,encode:uE,coerceCode:B1,isAppCode:nu,validate:T1,prefix:fE,isValidCode:I1}});var wE={};ft(wE,{webRTC:()=>bE,webRTCDirect:()=>xE});var EE=Symbol.for("@libp2p/connection");var AE=Symbol.for("@libp2p/content-routing");var BE=Symbol.for("@libp2p/peer-discovery");var gu=Symbol.for("@libp2p/peer-id");var _E=Symbol.for("@libp2p/peer-routing");var xu;(function(e){e.Accept="accept",e.Ignore="ignore",e.Reject="reject"})(xu||(xu={}));var Yi=Symbol.for("@libp2p/transport");var bu;(function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"})(bu||(bu={}));var W=class extends Error{code;props;constructor(t,r,n){super(t),this.code=r,this.name=n?.name??"CodeError",this.props=n??{}}};var Xi=class extends EventTarget{#t=new Map;listenerCount(t){let r=this.#t.get(t);return r==null?0:r.length}addEventListener(t,r,n){super.addEventListener(t,r,n);let i=this.#t.get(t);i==null&&(i=[],this.#t.set(t,i)),i.push({callback:r,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,r,n){super.removeEventListener(t.toString(),r??null,n);let i=this.#t.get(t);i!=null&&(i=i.filter(({callback:o})=>o!==r),this.#t.set(t,i))}dispatchEvent(t){let r=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:i})=>!i),this.#t.set(t.type,n)),r}safeDispatchEvent(t,r){return this.dispatchEvent(new j1(t,r))}},Hs=class extends Event{detail;constructor(t,r){super(t,r),this.detail=r?.detail}},j1=globalThis.CustomEvent??Hs;var $s={};ft($s,{base58btc:()=>Nt,base58flickr:()=>i2});function J1(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<e.length;i++){var o=e.charAt(i),s=o.charCodeAt(0);if(r[s]!==255)throw new TypeError(o+" is ambiguous");r[s]=i}var a=e.length,c=e.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var p=0,m=0,g=0,b=h.length;g!==b&&h[g]===0;)g++,p++;for(var x=(b-g)*f+1>>>0,A=new Uint8Array(x);g!==b;){for(var v=h[g],E=0,C=x-1;(v!==0||E<m)&&C!==-1;C--,E++)v+=256*A[C]>>>0,A[C]=v%a>>>0,v=v/a>>>0;if(v!==0)throw new Error("Non-zero carry");m=E,g++}for(var B=x-m;B!==x&&A[B]===0;)B++;for(var O=c.repeat(p);B<x;++B)O+=e.charAt(A[B]);return O}function d(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var p=0;if(h[p]!==" "){for(var m=0,g=0;h[p]===c;)m++,p++;for(var b=(h.length-p)*u+1>>>0,x=new Uint8Array(b);h[p];){var A=r[h.charCodeAt(p)];if(A===255)return;for(var v=0,E=b-1;(A!==0||v<g)&&E!==-1;E--,v++)A+=a*x[E]>>>0,x[E]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");g=v,p++}if(h[p]!==" "){for(var C=b-g;C!==b&&x[C]===0;)C++;for(var B=new Uint8Array(m+(b-C)),O=m;C!==b;)B[O++]=x[C++];return B}}}function y(h){var p=d(h);if(p)return p;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:d,decode:y}}var t2=J1,e2=t2,wu=e2;var f3=new Uint8Array(0);var vu=(e,t)=>{if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},$e=e=>{if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")};var Eu=e=>new TextEncoder().encode(e),Su=e=>new TextDecoder().decode(e);var qs=class{constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},zs=class{constructor(t,r,n){if(this.name=t,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),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 Du(this,t)}},Gs=class{constructor(t){this.decoders=t}or(t){return Du(this,t)}decode(t){let r=t[0],n=this.decoders[r];if(n)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},Du=(e,t)=>new Gs({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}}),Ws=class{constructor(t,r,n,i){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new qs(t,r,n),this.decoder=new zs(t,r,i)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}},ln=({name:e,prefix:t,encode:r,decode:n})=>new Ws(e,t,r,n),hr=({prefix:e,name:t,alphabet:r})=>{let{encode:n,decode:i}=wu(r,t);return ln({prefix:e,name:t,encode:n,decode:o=>$e(i(o))})},r2=(e,t,r,n)=>{let i={};for(let f=0;f<t.length;++f)i[t[f]]=f;let o=e.length;for(;e[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),a=0,c=0,u=0;for(let f=0;f<o;++f){let l=i[e[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|l,a+=r,a>=8&&(a-=8,s[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s},n2=(e,t,r)=>{let n=t[t.length-1]==="=",i=(1<<r)-1,o="",s=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],s+=8;s>r;)s-=r,o+=t[i&a>>s];if(s&&(o+=t[i&a<<r-s]),n)for(;o.length*r&7;)o+="=";return o},Rt=({name:e,prefix:t,bitsPerChar:r,alphabet:n})=>ln({prefix:t,name:e,encode(i){return n2(i,n,r)},decode(i){return r2(i,n,r,e)}});var Nt=hr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),i2=hr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ys={};ft(Ys,{base10:()=>o2});var o2=hr({prefix:"9",name:"base10",alphabet:"0123456789"});var Xs={};ft(Xs,{base16:()=>s2,base16upper:()=>a2});var s2=Rt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),a2=Rt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Zs={};ft(Zs,{base2:()=>c2});var c2=Rt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Qs={};ft(Qs,{base256emoji:()=>d2});var Cu=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}"),u2=Cu.reduce((e,t,r)=>(e[r]=t,e),[]),f2=Cu.reduce((e,t,r)=>(e[t.codePointAt(0)]=r,e),[]);function l2(e){return e.reduce((t,r)=>(t+=u2[r],t),"")}function h2(e){let t=[];for(let r of e){let n=f2[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}var d2=ln({prefix:"\u{1F680}",name:"base256emoji",encode:l2,decode:h2});var js={};ft(js,{base32:()=>Ye,base32hex:()=>g2,base32hexpad:()=>b2,base32hexpadupper:()=>w2,base32hexupper:()=>x2,base32pad:()=>y2,base32padupper:()=>m2,base32upper:()=>p2,base32z:()=>v2});var Ye=Rt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),p2=Rt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),y2=Rt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),m2=Rt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),g2=Rt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),x2=Rt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),b2=Rt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),w2=Rt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),v2=Rt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Js={};ft(Js,{base36:()=>E2,base36upper:()=>S2});var E2=hr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),S2=hr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ea={};ft(ea,{base64:()=>Zi,base64pad:()=>A2,base64url:()=>ta,base64urlpad:()=>D2});var Zi=Rt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),A2=Rt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ta=Rt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),D2=Rt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ra={};ft(ra,{base8:()=>C2});var C2=Rt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var na={};ft(na,{identity:()=>B2});var B2=ln({prefix:"\0",name:"identity",encode:e=>Su(e),decode:e=>Eu(e)});var D3=new TextEncoder,C3=new TextDecoder;var oa={};ft(oa,{identity:()=>dr});var _2=Tu,Bu=128,k2=127,R2=~k2,L2=Math.pow(2,31);function Tu(e,t,r){t=t||[],r=r||0;for(var n=r;e>=L2;)t[r++]=e&255|Bu,e/=128;for(;e&R2;)t[r++]=e&255|Bu,e>>>=7;return t[r]=e|0,Tu.bytes=r-n+1,t}var N2=ia,P2=128,Iu=127;function ia(e,n){var r=0,n=n||0,i=0,o=n,s,a=e.length;do{if(o>=a)throw ia.bytes=0,new RangeError("Could not decode varint");s=e[o++],r+=i<28?(s&Iu)<<i:(s&Iu)*Math.pow(2,i),i+=7}while(s>=P2);return ia.bytes=o-n,r}var U2=Math.pow(2,7),O2=Math.pow(2,14),K2=Math.pow(2,21),M2=Math.pow(2,28),F2=Math.pow(2,35),V2=Math.pow(2,42),H2=Math.pow(2,49),q2=Math.pow(2,56),z2=Math.pow(2,63),G2=function(e){return e<U2?1:e<O2?2:e<K2?3:e<M2?4:e<F2?5:e<V2?6:e<H2?7:e<q2?8:e<z2?9:10},W2={encode:_2,decode:N2,encodingLength:G2},$2=W2,ei=$2;var ri=(e,t=0)=>[ei.decode(e,t),ei.decode.bytes],hn=(e,t,r=0)=>(ei.encode(e,t,r),t),dn=e=>ei.encodingLength(e);var Le=(e,t)=>{let r=t.byteLength,n=dn(e),i=n+dn(r),o=new Uint8Array(i+r);return hn(e,o,0),hn(r,o,n),o.set(t,i),new pn(e,r,t,o)},Nr=e=>{let t=$e(e),[r,n]=ri(t),[i,o]=ri(t.subarray(n)),s=t.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new pn(r,i,s,t)},_u=(e,t)=>{if(e===t)return!0;{let r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&vu(e.bytes,r.bytes)}},pn=class{constructor(t,r,n,i){this.code=t,this.size=r,this.digest=n,this.bytes=i}};var ku=0,Y2="identity",Ru=$e,X2=e=>Le(ku,Ru(e)),dr={code:ku,name:Y2,encode:Ru,digest:X2};var ca={};ft(ca,{sha256:()=>Xt,sha512:()=>Z2});var aa=({name:e,code:t,encode:r})=>new sa(e,t,r),sa=class{constructor(t,r,n){this.name=t,this.code=r,this.encode=n}digest(t){if(t instanceof Uint8Array){let r=this.encode(t);return r instanceof Uint8Array?Le(this.code,r):r.then(n=>Le(this.code,n))}else throw Error("Unknown type, must be binary type")}};var Nu=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),Xt=aa({name:"sha2-256",code:18,encode:Nu("SHA-256")}),Z2=aa({name:"sha2-512",code:19,encode:Nu("SHA-512")});var Pu=(e,t)=>{let{bytes:r,version:n}=e;switch(n){case 0:return j2(r,ua(e),t||Nt.encoder);default:return J2(r,ua(e),t||Ye.encoder)}};var Uu=new WeakMap,ua=e=>{let t=Uu.get(e);if(t==null){let r=new Map;return Uu.set(e,r),r}return t},be=class e{constructor(t,r,n,i){this.code=r,this.version=t,this.multihash=n,this.bytes=i,this["/"]=i}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:r}=this;if(t!==ni)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==ty)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return e.createV0(r)}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:r}=this.multihash,n=Le(t,r);return e.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 e.equals(this,t)}static equals(t,r){let n=r;return n&&t.code===n.code&&t.version===n.version&&_u(t.multihash,n.multihash)}toString(t){return Pu(this,t)}toJSON(){return{"/":Pu(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let r=t;if(r instanceof e)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:i,multihash:o,bytes:s}=r;return new e(n,i,o,s||Ou(n,i,o.bytes))}else if(r[ey]===!0){let{version:n,multihash:i,code:o}=r,s=Nr(i);return e.create(n,o,s)}else return null}static create(t,r,n){if(typeof r!="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(r!==ni)throw new Error(`Version 0 CID must use dag-pb (code: ${ni}) block encoding`);return new e(t,r,n,n.bytes)}case 1:{let i=Ou(t,r,n.bytes);return new e(t,r,n,i)}default:throw new Error("Invalid version")}}static createV0(t){return e.create(0,ni,t)}static createV1(t,r){return e.create(1,t,r)}static decode(t){let[r,n]=e.decodeFirst(t);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(t){let r=e.inspectBytes(t),n=r.size-r.multihashSize,i=$e(t.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let o=i.subarray(r.multihashSize-r.digestSize),s=new pn(r.multihashCode,r.digestSize,o,i);return[r.version===0?e.createV0(s):e.createV1(r.codec,s),t.subarray(r.size)]}static inspectBytes(t){let r=0,n=()=>{let[l,d]=ri(t.subarray(r));return r+=d,l},i=n(),o=ni;if(i===18?(i=0,r=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=r,a=n(),c=n(),u=r+c,f=u-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(t,r){let[n,i]=Q2(t,r),o=e.decode(i);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ua(o).set(n,t),o}},Q2=(e,t)=>{switch(e[0]){case"Q":{let r=t||Nt;return[Nt.prefix,r.decode(`${Nt.prefix}${e}`)]}case Nt.prefix:{let r=t||Nt;return[Nt.prefix,r.decode(e)]}case Ye.prefix:{let r=t||Ye;return[Ye.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}},j2=(e,t,r)=>{let{prefix:n}=r;if(n!==Nt.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=t.get(n);if(i==null){let o=r.encode(e).slice(1);return t.set(n,o),o}else return i},J2=(e,t,r)=>{let{prefix:n}=r,i=t.get(n);if(i==null){let o=r.encode(e);return t.set(n,o),o}else return i},ni=112,ty=18,Ou=(e,t,r)=>{let n=dn(e),i=n+dn(t),o=new Uint8Array(i+r.byteLength);return hn(e,o,0),hn(t,o,n),o.set(r,i),o},ey=Symbol.for("@ipld/js-cid/CID");var Ne={...na,...Zs,...ra,...Ys,...Xs,...js,...Js,...$s,...ea,...Qs},H3={...ca,...oa};function Kt(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}var ry=Symbol.for("nodejs.util.inspect.custom"),Ku=Object.values(Ne).map(e=>e.decoder).reduce((e,t)=>e.or(t),Ne.identity.decoder),Mu=114,fa=36,la=37,ii=class{type;multihash;privateKey;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,this.privateKey=t.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[gu]=!0;toString(){return this.string==null&&(this.string=Nt.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return be.createV1(Mu,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(t){if(t instanceof Uint8Array)return Kt(this.multihash.bytes,t);if(typeof t=="string")return Ur(t).equals(this);if(t?.multihash?.bytes!=null)return Kt(this.multihash.bytes,t.multihash.bytes);throw new Error("not valid Id")}[ry](){return`PeerId(${this.toString()})`}},yn=class extends ii{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},mn=class extends ii{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.multihash.digest}},gn=class extends ii{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.multihash.digest}};function Ur(e,t){if(t=t??Ku,e.charAt(0)==="1"||e.charAt(0)==="Q"){let r=Nr(Nt.decode(`z${e}`));return e.startsWith("12D")?new mn({multihash:r}):e.startsWith("16U")?new gn({multihash:r}):new yn({multihash:r})}return ny(Ku.decode(e))}function ny(e){try{let t=Nr(e);if(t.code===dr.code){if(t.digest.length===fa)return new mn({multihash:t});if(t.digest.length===la)return new gn({multihash:t})}if(t.code===Xt.code)return new yn({multihash:t})}catch{return iy(be.decode(e))}throw new Error("Supplied PeerID CID is invalid")}function iy(e){if(e==null||e.multihash==null||e.version==null||e.version===1&&e.code!==Mu)throw new Error("Supplied PeerID CID is invalid");let t=e.multihash;if(t.code===Xt.code)return new yn({multihash:e.multihash});if(t.code===dr.code){if(t.digest.length===fa)return new mn({multihash:e.multihash});if(t.digest.length===la)return new gn({multihash:e.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function ha(e,t){return e.length===fa?new mn({multihash:Le(dr.code,e),privateKey:t}):e.length===la?new gn({multihash:Le(dr.code,e),privateKey:t}):new yn({multihash:await Xt.digest(e),publicKey:e,privateKey:t})}function Xe(e){return globalThis.Buffer!=null?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e}function ot(e=0){return globalThis.Buffer?.alloc!=null?Xe(globalThis.Buffer.alloc(e)):new Uint8Array(e)}function Vt(e=0){return globalThis.Buffer?.allocUnsafe!=null?Xe(globalThis.Buffer.allocUnsafe(e)):new Uint8Array(e)}function Vu(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}var Fu=Vu("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),da=Vu("ascii","a",e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},e=>{e=e.substring(1);let t=Vt(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}),sy={utf8:Fu,"utf-8":Fu,hex:Ne.base16,latin1:da,ascii:da,binary:da,...Ne},ji=sy;function at(e,t="utf8"){let r=ji[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("utf8"):r.encoder.encode(e).substring(1)}var ay=Math.pow(2,7),cy=Math.pow(2,14),uy=Math.pow(2,21),pa=Math.pow(2,28),ya=Math.pow(2,35),ma=Math.pow(2,42),ga=Math.pow(2,49),pt=128,te=127;function ee(e){if(e<ay)return 1;if(e<cy)return 2;if(e<uy)return 3;if(e<pa)return 4;if(e<ya)return 5;if(e<ma)return 6;if(e<ga)return 7;if(Number.MAX_SAFE_INTEGER!=null&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function fy(e,t,r=0){switch(ee(e)){case 8:t[r++]=e&255|pt,e/=128;case 7:t[r++]=e&255|pt,e/=128;case 6:t[r++]=e&255|pt,e/=128;case 5:t[r++]=e&255|pt,e/=128;case 4:t[r++]=e&255|pt,e>>>=7;case 3:t[r++]=e&255|pt,e>>>=7;case 2:t[r++]=e&255|pt,e>>>=7;case 1:{t[r++]=e&255,e>>>=7;break}default:throw new Error("unreachable")}return t}function ly(e,t,r=0){switch(ee(e)){case 8:t.set(r++,e&255|pt),e/=128;case 7:t.set(r++,e&255|pt),e/=128;case 6:t.set(r++,e&255|pt),e/=128;case 5:t.set(r++,e&255|pt),e/=128;case 4:t.set(r++,e&255|pt),e>>>=7;case 3:t.set(r++,e&255|pt),e>>>=7;case 2:t.set(r++,e&255|pt),e>>>=7;case 1:{t.set(r++,e&255),e>>>=7;break}default:throw new Error("unreachable")}return t}function hy(e,t){let r=e[t],n=0;if(n+=r&te,r<pt||(r=e[t+1],n+=(r&te)<<7,r<pt)||(r=e[t+2],n+=(r&te)<<14,r<pt)||(r=e[t+3],n+=(r&te)<<21,r<pt)||(r=e[t+4],n+=(r&te)*pa,r<pt)||(r=e[t+5],n+=(r&te)*ya,r<pt)||(r=e[t+6],n+=(r&te)*ma,r<pt)||(r=e[t+7],n+=(r&te)*ga,r<pt))return n;throw new RangeError("Could not decode varint")}function dy(e,t){let r=e.get(t),n=0;if(n+=r&te,r<pt||(r=e.get(t+1),n+=(r&te)<<7,r<pt)||(r=e.get(t+2),n+=(r&te)<<14,r<pt)||(r=e.get(t+3),n+=(r&te)<<21,r<pt)||(r=e.get(t+4),n+=(r&te)*pa,r<pt)||(r=e.get(t+5),n+=(r&te)*ya,r<pt)||(r=e.get(t+6),n+=(r&te)*ma,r<pt)||(r=e.get(t+7),n+=(r&te)*ga,r<pt))return n;throw new RangeError("Could not decode varint")}function pr(e,t,r=0){return t==null&&(t=Vt(ee(e))),t instanceof Uint8Array?fy(e,t,r):ly(e,t,r)}function we(e,t=0){return e instanceof Uint8Array?hy(e,t):dy(e,t)}function Ct(e,t){if(globalThis.Buffer!=null)return Xe(globalThis.Buffer.concat(e,t));t==null&&(t=e.reduce((i,o)=>i+o.length,0));let r=Vt(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return Xe(r)}var Ji=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let r=this.index,n=t();return n===void 0&&(this.index=r),n}parseWith(t){let r=t();if(this.index===this.input.length)return r}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 r=this.readChar();if(r===t)return r})}readSeparator(t,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,r,n,i){return this.readAtomically(()=>{let o=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*i)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,t);if(!Number.isNaN(d))return d});if(f===void 0)break;if(o*=t,o+=f,o>u||(s+=1,r!==void 0&&s>r))return}if(s!==0)return!n&&c&&s>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let r=0;r<t.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[r]=n}return t})}readIPv6Addr(){let t=r=>{for(let n=0;n<r.length/2;n++){let i=n*2;if(n<r.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return r[i]=s[0],r[i+1]=s[1],r[i+2]=s[2],r[i+3]=s[3],[i+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[i,!1];r[i]=o>>8,r[i+1]=o&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,i]=t(r);if(n===16)return r;if(i||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),s=16-(n+2),[a]=t(o.subarray(0,s));return r.set(o.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Hu=45,py=15,xn=new Ji;function xa(e){if(!(e.length>py))return xn.new(e).parseWith(()=>xn.readIPv4Addr())}function ba(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>Hu))return xn.new(e).parseWith(()=>xn.readIPv6Addr())}function to(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>Hu))return xn.new(e).parseWith(()=>xn.readIPAddr())}var w4=parseInt("0xFFFF",16),v4=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function wt(e,t="utf8"){let r=ji[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return(t==="utf8"||t==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Xe(globalThis.Buffer.from(e,"utf-8")):r.decoder.decode(`${r.prefix}${e}`)}function eo(e){return!!xa(e)}function ro(e){return!!ba(e)}function no(e){return!!to(e)}var Gu=eo,by=ro,wa=function(e){let t=0;if(e=e.toString().trim(),Gu(e)){let r=new Uint8Array(t+4);return e.split(/\./g).forEach(n=>{r[t++]=parseInt(n,10)&255}),r}if(by(e)){let r=e.split(":",8),n;for(n=0;n<r.length;n++){let o=Gu(r[n]),s;o&&(s=wa(r[n]),r[n]=at(s.slice(0,2),"base16")),s!=null&&++n<8&&r.splice(n,0,at(s.slice(2,4),"base16"))}if(r[0]==="")for(;r.length<8;)r.unshift("0");else if(r[r.length-1]==="")for(;r.length<8;)r.push("0");else if(r.length<8){for(n=0;n<r.length&&r[n]!=="";n++);let o=[n,1];for(n=9-r.length;n>0;n--)o.push("0");r.splice.apply(r,o)}let i=new Uint8Array(t+16);for(n=0;n<r.length;n++){let o=parseInt(r[n],16);i[t++]=o>>8&255,i[t++]=o&255}return i}throw new Error("invalid ip address")},Wu=function(e,t=0,r){t=~~t,r=r??e.length-t;let n=new DataView(e.buffer);if(r===4){let i=[];for(let o=0;o<r;o++)i.push(e[t+o]);return i.join(".")}if(r===16){let i=[];for(let o=0;o<r;o+=2)i.push(n.getUint16(t+o).toString(16));return i.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var bn={},va={},vy=[[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"],[777,-1,"memory"]];vy.forEach(e=>{let t=Ey(...e);va[t.code]=t,bn[t.name]=t});function Ey(e,t,r,n,i){return{code:e,size:t,name:r,resolvable:!!n,path:!!i}}function yt(e){if(typeof e=="number"){if(va[e]!=null)return va[e];throw new Error(`no protocol with code: ${e}`)}else if(typeof e=="string"){if(bn[e]!=null)return bn[e];throw new Error(`no protocol with name: ${e}`)}throw new Error(`invalid protocol id type: ${typeof e}`)}var aS=yt("ip4"),cS=yt("ip6"),uS=yt("ipcidr");function Sa(e,t){switch(yt(e).code){case 4:case 41:return Ay(t);case 42:return Xu(t);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 Xu(t);case 421:return Iy(t);case 444:return Zu(t);case 445:return Zu(t);case 466:return By(t);default:return at(t,"base16")}}function Aa(e,t){switch(yt(e).code){case 4:return $u(t);case 41:return $u(t);case 42:return Yu(t);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 Yu(t);case 421:return Dy(t);case 444:return Ty(t);case 445:return _y(t);case 466:return Cy(t);default:return wt(t,"base16")}}var Ea=Object.values(Ne).map(e=>e.decoder),Sy=function(){let e=Ea[0].or(Ea[1]);return Ea.slice(2).forEach(t=>e=e.or(t)),e}();function $u(e){if(!no(e))throw new Error("invalid ip address");return wa(e)}function Ay(e){let t=Wu(e,0,e.length);if(t==null)throw new Error("ipBuff is required");if(!no(t))throw new Error("invalid ip address");return t}function Da(e){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,e),new Uint8Array(t)}function Qu(e){return new DataView(e.buffer).getUint16(e.byteOffset)}function Yu(e){let t=wt(e),r=Uint8Array.from(pr(t.length));return Ct([r,t],r.length+t.length)}function Xu(e){let t=we(e);if(e=e.slice(ee(t)),e.length!==t)throw new Error("inconsistent lengths");return at(e)}function Dy(e){let t;e[0]==="Q"||e[0]==="1"?t=Nr(Nt.decode(`z${e}`)).bytes:t=be.parse(e).multihash.bytes;let r=Uint8Array.from(pr(t.length));return Ct([r,t],r.length+t.length)}function Cy(e){let t=Sy.decode(e),r=Uint8Array.from(pr(t.length));return Ct([r,t],r.length+t.length)}function By(e){let t=we(e),r=e.slice(ee(t));if(r.length!==t)throw new Error("inconsistent lengths");return"u"+at(r,"base64url")}function Iy(e){let t=we(e),r=e.slice(ee(t));if(r.length!==t)throw new Error("inconsistent lengths");return at(r,"base58btc")}function Ty(e){let t=e.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 r=Ye.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 i=Da(n);return Ct([r,i],r.length+i.length)}function _y(e){let t=e.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 r=Ye.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 i=Da(n);return Ct([r,i],r.length+i.length)}function Zu(e){let t=e.slice(0,e.length-2),r=e.slice(e.length-2),n=at(t,"base32"),i=Qu(r);return`${n}:${i}`}function ju(e){e=Ca(e);let t=[],r=[],n=null,i=e.split("/").slice(1);if(i.length===1&&i[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let o=0;o<i.length;o++){let s=i[o],a=yt(s);if(a.size===0){t.push([a.code]),r.push([a.code]);continue}if(o++,o>=i.length)throw tf("invalid address: "+e);if(a.path===!0){n=Ca(i.slice(o).join("/")),t.push([a.code,Aa(a.code,n)]),r.push([a.code,n]);break}let c=Aa(a.code,i[o]);t.push([a.code,c]),r.push([a.code,Sa(a.code,c)])}return{string:Ju(r),bytes:Ia(t),tuples:t,stringTuples:r,path:n}}function Ba(e){let t=[],r=[],n=null,i=0;for(;i<e.length;){let o=we(e,i),s=ee(o),a=yt(o),c=ky(a,e.slice(i+s));if(c===0){t.push([o]),r.push([o]),i+=s;continue}let u=e.slice(i+s,i+s+c);if(i+=c+s,i>e.length)throw tf("Invalid address Uint8Array: "+at(e,"base16"));t.push([o,u]);let f=Sa(o,u);if(r.push([o,f]),a.path===!0){n=f;break}}return{bytes:Uint8Array.from(e),string:Ju(r),tuples:t,stringTuples:r,path:n}}function Ju(e){let t=[];return e.map(r=>{let n=yt(r[0]);return t.push(n.name),r.length>1&&r[1]!=null&&t.push(r[1]),null}),Ca(t.join("/"))}function Ia(e){return Ct(e.map(t=>{let r=yt(t[0]),n=Uint8Array.from(pr(r.code));return t.length>1&&t[1]!=null&&(n=Ct([n,t[1]])),n}))}function ky(e,t){if(e.size>0)return e.size/8;if(e.size===0)return 0;{let r=we(t instanceof Uint8Array?t:Uint8Array.from(t));return r+ee(r)}}function Ca(e){return"/"+e.trim().split("/").filter(t=>t).join("/")}function tf(e){return new Error("Error parsing address: "+e)}var Ry=Symbol.for("nodejs.util.inspect.custom"),Ta=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Ly=[yt("dns").code,yt("dns4").code,yt("dns6").code,yt("dnsaddr").code],io=class e{bytes;#t;#e;#r;#n;[Ta]=!0;constructor(t){t==null&&(t="");let r;if(t instanceof Uint8Array)r=Ba(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);r=ju(t)}else if(rf(t))r=Ba(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=r.bytes,this.#t=r.string,this.#e=r.tuples,this.#r=r.stringTuples,this.#n=r.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,r,n,i,o="",s=yt("tcp"),a=yt("udp"),c=yt("ip4"),u=yt("ip6"),f=yt("dns6"),l=yt("ip6zone");for(let[y,h]of this.stringTuples())y===l.code&&(o=`%${h??""}`),Ly.includes(y)&&(r=s.name,i=443,n=`${h??""}${o}`,t=y===f.code?6:4),(y===s.code||y===a.code)&&(r=yt(y).name,i=parseInt(h??"")),(y===c.code||y===u.code)&&(r=yt(y).name,n=`${h??""}${o}`,t=y===u.code?6:4);if(t==null||r==null||n==null||i==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:r,port:i}}protos(){return this.#e.map(([t])=>Object.assign({},yt(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>yt(t).name)}tuples(){return this.#e}stringTuples(){return this.#r}encapsulate(t){return t=new e(t),new e(this.toString()+t.toString())}decapsulate(t){let r=t.toString(),n=this.toString(),i=n.lastIndexOf(r);if(i<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new e(n.slice(0,i))}decapsulateCode(t){let r=this.tuples();for(let n=r.length-1;n>=0;n--)if(r[n][0]===t)return new e(Ia(r.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,i])=>{n===bn.p2p.code&&t.push([n,i]),n===bn["p2p-circuit"].code&&(t=[])});let r=t.pop();if(r?.[1]!=null){let n=r[1];return n[0]==="Q"||n[0]==="1"?at(Nt.decode(`z${n}`),"base58btc"):at(be.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return Kt(this.bytes,t.bytes)}async resolve(t){let r=this.protos().find(o=>o.resolvable);if(r==null)return[this];let n=ef.get(r.name);if(n==null)throw new W(`no available resolver for ${r.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,t)).map(o=>new e(o))}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 r=(t??this).protos();return!(r.length!==2||r[0].code!==4&&r[0].code!==41||r[1].code!==6&&r[1].code!==273)}[Ry](){return`Multiaddr(${this.#t})`}};var ef=new Map;function rf(e){return!!e?.[Ta]}function Ze(e){return new io(e)}var Ny=e=>e.toString().split("/").slice(1),si=e=>({match:t=>t.length<1?!1:e(t[0])?t.slice(1):!1,pattern:"fn"}),Pt=e=>({match:t=>si(r=>r===e).match(t),pattern:e}),ao=()=>({match:e=>si(t=>typeof t=="string").match(e),pattern:"{string}"}),nf=()=>({match:e=>si(t=>!isNaN(parseInt(t))).match(e),pattern:"{number}"}),de=()=>({match:e=>{if(e.length<2||e[0]!=="p2p"&&e[0]!=="ipfs")return!1;if(e[1].startsWith("Q")||e[1].startsWith("1"))try{Nt.decode(`z${e[1]}`)}catch{return!1}else return!1;return e.slice(2)},pattern:"/p2p/{peerid}"}),oo=()=>({match:e=>{if(e.length<2||e[0]!=="certhash")return!1;try{ta.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),Pe=e=>({match:t=>{let r=e.match(t);return r===!1?t:r},pattern:`optional(${e.pattern})`}),Ue=(...e)=>({match:t=>{let r;for(let n of e){let i=n.match(t);i!==!1&&(r==null||i.length<r.length)&&(r=i)}return r??!1},pattern:`or(${e.map(t=>t.pattern).join(", ")})`}),Ut=(...e)=>({match:t=>{for(let r of e){let n=r.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${e.map(t=>t.pattern).join(", ")})`});function Ht(...e){function t(i){let o=Ny(i);for(let s of e){let a=s.match(o);if(a===!1)return!1;o=a}return o}function r(i){return t(i)!==!1}function n(i){let o=t(i);return o===!1?!1:o.length===0}return{matches:r,exactMatch:n}}var ka=Ut(Pt("dns4"),ao()),Ra=Ut(Pt("dns6"),ao()),La=Ut(Pt("dnsaddr"),ao()),of=Ut(Pt("dns"),ao()),KS=Ht(ka),MS=Ht(Ra),FS=Ht(La),VS=Ht(Ue(of,La,ka,Ra)),sf=Ut(Pt("ip4"),si(eo)),af=Ut(Pt("ip6"),si(ro)),cf=Ue(sf,af),ai=Ue(cf,of,ka,Ra,La),HS=Ht(ai),qS=Ht(sf),zS=Ht(af),GS=Ht(cf),co=Ut(ai,Pt("tcp"),nf()),ci=Ut(ai,Pt("udp"),nf()),Py=Ue(co,ci),WS=Ht(co),$S=Ht(ci),Na=Ut(ci,Pt("quic")),uo=Ut(ci,Pt("quic-v1")),Uy=Ue(Na,uo),YS=Ht(Na),XS=Ht(uo),_a=Ue(ai,co,ci,Na,uo),uf=Ue(Ut(_a,Pt("ws"),Pe(de()))),ZS=Ht(uf),ff=Ue(Ut(_a,Pt("wss"),Pe(de())),Ut(_a,Pt("tls"),Pt("ws"),Pe(de()))),QS=Ht(ff),lf=Ut(Py,Pt("webrtc-direct"),oo(),Pe(oo()),Pe(de())),hf=Ht(lf),df=Ut(uo,Pt("webtransport"),oo(),oo(),Pe(de())),jS=Ht(df),so=Ue(uf,ff,Ut(co,Pe(de())),Ut(Uy,Pe(de())),Ut(ai,Pe(de())),lf,df,de()),JS=Ht(so),Oy=Ut(so,Pt("p2p-circuit"),de()),t5=Ht(Oy),Ky=Ue(Ut(so,Pt("p2p-circuit"),Pt("webrtc"),de()),Ut(so,Pt("webrtc"),Pe(de())),Pt("webrtc")),pf=Ht(Ky);var fe;(function(e){e.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",e.ERR_DATA_CHANNEL="ERR_DATA_CHANNEL",e.ERR_CONNECTION_CLOSED="ERR_CONNECTION_CLOSED",e.ERR_HASH_NOT_SUPPORTED="ERR_HASH_NOT_SUPPORTED",e.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",e.ERR_INVALID_FINGERPRINT="ERR_INVALID_FINGERPRINT",e.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",e.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",e.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",e.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS"})(fe||(fe={}));var yr=class extends W{constructor(t,r){super(`WebRTC transport error: ${t}`,r??""),this.name="WebRTCTransportError"}};var Pa=class extends yr{constructor(t,r){super(`[stream: ${t}] data channel error: ${r}`,fe.ERR_DATA_CHANNEL),this.name="WebRTC/DataChannelError"}};function Va(e,t){return new Pa(e,t)}var Ua=class extends yr{constructor(t){super(`There was a problem with the Multiaddr which was passed in: ${t}`,fe.ERR_INVALID_MULTIADDR),this.name="WebRTC/InappropriateMultiaddrError"}};function fo(e){return new Ua(e)}var Oa=class extends yr{constructor(t){super(`There was a problem with a provided argument: ${t}`,fe.ERR_INVALID_PARAMETERS),this.name="WebRTC/InvalidArgumentError"}};function ui(e){return new Oa(e)}var Ka=class extends yr{constructor(t,r){super(`Invalid fingerprint "${t}" within ${r}`,fe.ERR_INVALID_FINGERPRINT),this.name="WebRTC/InvalidFingerprintError"}};function Ha(e,t){return new Ka(e,t)}var Ma=class extends yr{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`,fe.ERR_NOT_IMPLEMENTED),this.name="WebRTC/UnimplementedError"}};function yf(e){return new Ma(e)}var Fa=class extends yr{constructor(t){super(`unsupported hash algorithm: ${t}`,fe.ERR_HASH_NOT_SUPPORTED),this.name="WebRTC/UnsupportedHashAlgorithmError"}};function mf(e){return new Fa(e)}var gf=function(e,t,r){if(r||arguments.length===2)for(var n=0,i=t.length,o;n<i;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},My=function(){function e(t,r,n){this.name=t,this.version=r,this.os=n,this.type="browser"}return e}();var Fy=function(){function e(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return e}();var Vy=function(){function e(t,r,n,i){this.name=t,this.version=r,this.os=n,this.bot=i,this.type="bot-device"}return e}();var Hy=function(){function e(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return e}();var qy=function(){function e(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return e}();var zy=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Gy=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,xf=3,Wy=[["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",zy]],bf=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function vf(e){return e?wf(e):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new qy:typeof navigator<"u"?wf(navigator.userAgent):Xy()}function $y(e){return e!==""&&Wy.reduce(function(t,r){var n=r[0],i=r[1];if(t)return t;var o=i.exec(e);return!!o&&[n,o]},!1)}function wf(e){var t=$y(e);if(!t)return null;var r=t[0],n=t[1];if(r==="searchbot")return new Hy;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length<xf&&(i=gf(gf([],i,!0),Zy(xf-i.length),!0)):i=[];var o=i.join("."),s=Yy(e),a=Gy.exec(e);return a&&a[1]?new Vy(r,o,s,a[1]):new My(r,o,s)}function Yy(e){for(var t=0,r=bf.length;t<r;t++){var n=bf[t],i=n[0],o=n[1],s=o.exec(e);if(s)return i}return null}function Xy(){var e=typeof process<"u"&&process.version;return e?new Fy(process.version.slice(1)):null}function Zy(e){for(var t=[],r=0;r<e;r++)t.push("0");return t}function kt(){let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}var wn=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},qa=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Ef=e=>globalThis.DOMException===void 0?new qa(e):new DOMException(e),Sf=e=>{let t=e.reason===void 0?Ef("This operation was aborted."):e.reason;return t instanceof Error?t:Ef(t)};function Or(e,t){let{milliseconds:r,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout}}=t,s,c=new Promise((u,f)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){let{signal:d}=t;d.aborted&&f(Sf(d)),d.addEventListener("abort",()=>{f(Sf(d))})}if(r===Number.POSITIVE_INFINITY){e.then(u,f);return}let l=new wn;s=o.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(d){f(d)}return}typeof e.cancel=="function"&&e.cancel(),i===!1?u():i instanceof Error?f(i):(l.message=i??`Promise timed out after ${r} milliseconds`,f(l))},r),(async()=>{try{u(await e)}catch(d){f(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{o.clearTimeout.call(void 0,s),s=void 0},c}var Af=vf(),fi=Af!=null&&Af.name==="firefox",lo=async function*(){},ho=async e=>{},Qy=30*1e3;function Df(e,t,r=Qy,n){e.readyState==="open"&&Promise.resolve().then(async()=>{if(e.bufferedAmount>0){n.log("%s drain channel with %d buffered bytes",t,e.bufferedAmount);let i=kt(),o=!1;e.bufferedAmountLowThreshold=0;let s=()=>{o||(n.log("%s drain channel closed before drain",t),i.resolve())};e.addEventListener("close",s,{once:!0}),e.addEventListener("bufferedamountlow",()=>{o=!0,e.removeEventListener("close",s),i.resolve()}),await Or(i.promise,{milliseconds:r})}}).then(async()=>{e.readyState==="open"&&e.close()}).catch(i=>{n.log.error("error closing outbound stream",i)})}var Kr=class{log;peerConnection;remoteAddr;timeline;metrics;source=lo();sink=ho;constructor(t,r){this.log=t.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=r.remoteAddr,this.timeline=r.timeline,this.peerConnection=r.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 po=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}},vn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new po(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 r=this.head;this.head=r.next=new po(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,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,r){super(t??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function mr(e={}){return jy(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},e)}function jy(e,t){t=t??{};let r=t.onEnd,n=new vn,i,o,s,a=kt(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((m,g)=>{o=b=>{o=null,n.push(b);try{m(e(n))}catch(x){g(x)}return i}}):e(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=kt()})}},u=m=>o!=null?o(m):(n.push(m),i),f=m=>(n=new vn,o!=null?o({error:m}):(n.push({error:m}),i)),l=m=>{if(s)return i;if(t?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:m})},d=m=>s?i:(s=!0,m!=null?f(m):u({done:!0})),y=()=>(n=new vn,d(),{done:!0}),h=m=>(d(m),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:y,throw:h,push:l,end:d,get readableLength(){return n.size},onEmpty:async m=>{let g=m?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let b,x;g!=null&&(b=new Promise((A,v)=>{x=()=>{v(new za)},g.addEventListener("abort",x)}));try{await Promise.race([a.promise,b])}finally{x!=null&&g!=null&&g?.removeEventListener("abort",x)}}},r==null)return i;let p=i;return i={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(m){return p.throw(m),r!=null&&(r(m),r=void 0),{done:!0}},return(){return p.return(),r!=null&&(r(),r=void 0),{done:!0}},push:l,end(m){return p.end(m),r!=null&&(r(m),r=void 0),i},get readableLength(){return p.readableLength},onEmpty:m=>p.onEmpty(m)},i}var yo=class extends Error{type;code;constructor(t,r){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=r??"ABORT_ERR"}};async function gr(e,t,r){if(t==null)return e;if(t.aborted)return Promise.reject(new yo(r?.errorMessage,r?.errorCode));let n,i=new yo(r?.errorMessage,r?.errorCode);try{return await Promise.race([e,new Promise((o,s)=>{n=()=>{s(i)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var Bf=Symbol.for("@achingbrain/uint8arraylist");function Cf(e,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let r=0;for(let n of e){let i=r+n.byteLength;if(t<i)return{buf:n,index:t-r};r=i}throw new RangeError("index is out of bounds")}function En(e){return!!e?.[Bf]}var Bt=class e{bufs;length;[Bf]=!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 r=0;for(let n of t)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(En(n))r+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...t){this.prependAll(t)}prependAll(t){let r=0;for(let n of t.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(En(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(t){let r=Cf(this.bufs,t);return r.buf[r.index]}set(t,r){let n=Cf(this.bufs,t);n.buf[n.index]=r}write(t,r=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(r+n,t[n]);else if(En(t))for(let n=0;n<t.length;n++)this.set(r+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,r){let{bufs:n,length:i}=this._subList(t,r);return Ct(n,i)}subarray(t,r){let{bufs:n,length:i}=this._subList(t,r);return n.length===1?n[0]:Ct(n,i)}sublist(t,r){let{bufs:n,length:i}=this._subList(t,r),o=new e;return o.length=i,o.bufs=[...n],o}_subList(t,r){if(t=t??0,r=r??this.length,t<0&&(t=this.length+t),r<0&&(r=this.length+r),t<0||r>this.length)throw new RangeError("index is out of bounds");if(t===r)return{bufs:[],length:0};if(t===0&&r===this.length)return{bufs:this.bufs,length:this.length};let n=[],i=0;for(let o=0;o<this.bufs.length;o++){let s=this.bufs[o],a=i,c=a+s.byteLength;if(i=c,t>=c)continue;let u=t>=a&&t<c,f=r>a&&r<=c;if(u&&f){if(t===a&&r===c){n.push(s);break}let l=t-a;n.push(s.subarray(l,l+(r-t)));break}if(u){if(t===0){n.push(s);continue}n.push(s.subarray(t-a));continue}if(f){if(r===c){n.push(s);break}n.push(s.subarray(0,r-a));break}n.push(s)}return{bufs:n,length:r-t}}indexOf(t,r=0){if(!En(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(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),t.length===0)return r>this.length?this.length:r;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let o=256,s=new Int32Array(o);for(let l=0;l<o;l++)s[l]=-1;for(let l=0;l<i;l++)s[n[l]]=l;let a=s,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=r;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let y=this.get(l+d);if(n[d]!==y){f=Math.max(1,d-a[y]);break}}if(f===0)return l}return-1}getInt8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(t,r){let n=Vt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,t)}getInt16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(t,r,n){let i=ot(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,r,n),this.write(i,t)}getInt32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(t,r,n){let i=ot(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,r,n),this.write(i,t)}getBigInt64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(t,r,n){let i=ot(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,r,n),this.write(i,t)}getUint8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(t,r){let n=Vt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,t)}getUint16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(t,r,n){let i=ot(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,r,n),this.write(i,t)}getUint32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(t,r,n){let i=ot(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,r,n),this.write(i,t)}getBigUint64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(t,r,n){let i=ot(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,r,n),this.write(i,t)}getFloat32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(t,r,n){let i=ot(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,r,n),this.write(i,t)}getFloat64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(t,r,n){let i=ot(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,r,n),this.write(i,t)}equals(t){if(t==null||!(t instanceof e)||t.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!Kt(this.bufs[r],t.bufs[r]))return!1;return!0}static fromUint8Arrays(t,r){let n=new e;return n.bufs=t,r==null&&(r=t.reduce((i,o)=>i+o.byteLength,0)),n.length=r,n}};function If(e){if(e!=null){if(typeof e[Symbol.iterator]=="function")return e[Symbol.iterator]();if(typeof e[Symbol.asyncIterator]=="function")return e[Symbol.asyncIterator]();if(typeof e.next=="function")return e}throw new Error("argument is not an iterator or iterable")}function Tf(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}function mo(e,t){let r=If(e).return?.();Tf(r)&&r.catch(n=>{t.error("could not cause iterator to return",n)})}var Jy="ERR_STREAM_RESET",tm="ERR_SINK_INVALID_STATE",em=5e3;function Ga(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}var go=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;constructor(t){this.sinkController=new AbortController,this.sinkEnd=kt(),this.closed=kt(),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=mr({onEnd:r=>{r!=null?this.log.trace("source ended with error",r):this.log.trace("source ended"),this.onSourceEnd(r)}}),this.sink=this.sink.bind(this)}async sink(t){if(this.writeStatus!=="ready")throw new W(`writable end state is "${this.writeStatus}" not "ready"`,tm);try{this.writeStatus="writing";let r={signal:this.sinkController.signal};if(this.direction==="outbound"){let i=this.sendNewStream(r);Ga(i)&&await i}let n=()=>{mo(t,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let i of t){i=i instanceof Uint8Array?new Bt(i):i;let o=this.sendData(i,r);Ga(o)&&await o}}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(r){throw this.log.trace("sink ended with error, calling abort with error",r),this.abort(r),r}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(t){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(t){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(t){this.log.trace("closing gracefully"),this.status="closing",await Promise.all([this.closeRead(t),this.closeWrite(t)]),await gr(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 r=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)),r==="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 gr(this.sink([]),t.signal)),this.writeStatus==="writing"&&await new Promise((r,n)=>{queueMicrotask(()=>{this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),gr(this.sinkEnd.promise,t.signal).then(r,n)})}),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 r=this.sendReset();Ga(r)&&r.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 W("stream reset",Jy);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 xo(e){return e[Symbol.asyncIterator]!=null}var bo=e=>{let t=ee(e),r=Vt(t);return pr(e,r),bo.bytes=t,r};bo.bytes=0;function xr(e,t){t=t??{};let r=t.lengthEncoder??bo;function*n(i){let o=r(i.byteLength);o instanceof Uint8Array?yield o:yield*o,i instanceof Uint8Array?yield i:yield*i}return xo(e)?async function*(){for await(let i of e)yield*n(i)}():function*(){for(let i of e)yield*n(i)}()}xr.single=(e,t)=>{t=t??{};let r=t.lengthEncoder??bo;return new Bt(r(e.byteLength),e)};var Sn=Jt(Rf(),1);var nm=8,im=1024*1024*4,Mr;(function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(Mr||(Mr={}));var Wa=e=>{let t=we(e);return Wa.bytes=ee(t),t};Wa.bytes=0;function Fr(e,t){let r=new Bt,n=Mr.LENGTH,i=-1,o=t?.lengthDecoder??Wa,s=t?.maxLengthLength??nm,a=t?.maxDataLength??im;function*c(){for(;r.byteLength>0;){if(n===Mr.LENGTH)try{if(i=o(r),i<0)throw(0,Sn.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,Sn.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=o.bytes;r.consume(u),t?.onLength!=null&&t.onLength(i),n=Mr.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>s)throw(0,Sn.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===Mr.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),t?.onData!=null&&t.onData(u),yield u,n=Mr.LENGTH}}}return xo(e)?async function*(){for await(let u of e)r.append(u),yield*c();if(r.byteLength>0)throw(0,Sn.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of e)r.append(u),yield*c();if(r.byteLength>0)throw(0,Sn.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Fr.fromReader=(e,t)=>{let r=1,n=async function*(){for(;;)try{let{done:o,value:s}=await e.next(r);if(o===!0)return;s!=null&&(yield s)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{r=1}}();return Fr(n,{...t??{},onLength:o=>{r=o}})};var om=e=>{let t=e.on||e.addListener||e.addEventListener,r=e.off||e.removeListener||e.removeEventListener;if(!t||!r)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}};function sm(e,t,r){let n,i=new Promise((o,s)=>{if(r={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:u,removeListener:f}=om(e),l=(...y)=>{let h=r.multiArgs?y:y[0];r.filter&&!r.filter(h)||(c.push(h),r.count===c.length&&(n(),o(c)))},d=y=>{n(),s(y)};n=()=>{for(let y of a)f(y,l);for(let y of r.rejectionEvents)f(y,d)};for(let y of a)u(y,l);for(let y of r.rejectionEvents)u(y,d);r.signal&&r.signal.addEventListener("abort",()=>{d(r.signal.reason)},{once:!0}),r.resolveImmediately&&o(c)});if(i.cancel=n,typeof r.timeout=="number"){let o=Or(i,{milliseconds:r.timeout});return o.cancel=n,o}return i}function $a(e,t,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=sm(e,t,r),i=n.then(o=>o[0]);return i.cancel=n.cancel,i}var Ya=new Float32Array([-0]),br=new Uint8Array(Ya.buffer);function Nf(e,t,r){Ya[0]=e,t[r]=br[0],t[r+1]=br[1],t[r+2]=br[2],t[r+3]=br[3]}function Pf(e,t){return br[0]=e[t],br[1]=e[t+1],br[2]=e[t+2],br[3]=e[t+3],Ya[0]}var Xa=new Float64Array([-0]),re=new Uint8Array(Xa.buffer);function Uf(e,t,r){Xa[0]=e,t[r]=re[0],t[r+1]=re[1],t[r+2]=re[2],t[r+3]=re[3],t[r+4]=re[4],t[r+5]=re[5],t[r+6]=re[6],t[r+7]=re[7]}function Of(e,t){return re[0]=e[t],re[1]=e[t+1],re[2]=e[t+2],re[3]=e[t+3],re[4]=e[t+4],re[5]=e[t+5],re[6]=e[t+6],re[7]=e[t+7],Xa[0]}var am=BigInt(Number.MAX_SAFE_INTEGER),cm=BigInt(Number.MIN_SAFE_INTEGER),oe=class e{lo;hi;constructor(t,r){this.lo=t|0,this.hi=r|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+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 r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(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,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?t<16384?t<128?1:2:t<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return Vr;if(t<am&&t>cm)return this.fromNumber(Number(t));let r=t<0n;r&&(t=-t);let n=t>>32n,i=t-(n<<32n);return r&&(n=~n|0n,i=~i|0n,++i>Kf&&(i=0n,++n>Kf&&(n=0n))),new e(Number(i),Number(n))}static fromNumber(t){if(t===0)return Vr;let r=t<0;r&&(t=-t);let n=t>>>0,i=(t-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new e(n,i)}static from(t){return typeof t=="number"?e.fromNumber(t):typeof t=="bigint"?e.fromBigInt(t):typeof t=="string"?e.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new e(t.low>>>0,t.high>>>0):Vr}},Vr=new oe(0,0);Vr.toBigInt=function(){return 0n};Vr.zzEncode=Vr.zzDecode=function(){return this};Vr.length=function(){return 1};var Kf=4294967296n;function Mf(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:(r&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Ff(e,t,r){if(r-t<1)return"";let i,o=[],s=0,a;for(;t<r;)a=e[t++],a<128?o[s++]=a:a>191&&a<224?o[s++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,o[s++]=55296+(a>>10),o[s++]=56320+(a&1023)):o[s++]=(a&15)<<12|(e[t++]&63)<<6|e[t++]&63,s>8191&&((i??(i=[])).push(String.fromCharCode.apply(String,o)),s=0);return i!=null?(s>0&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))}function Za(e,t,r){let n=r,i,o;for(let s=0;s<e.length;++s)i=e.charCodeAt(s),i<128?t[r++]=i:i<2048?(t[r++]=i>>6|192,t[r++]=i&63|128):(i&64512)===55296&&((o=e.charCodeAt(s+1))&64512)===56320?(i=65536+((i&1023)<<10)+(o&1023),++s,t[r++]=i>>18|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=i&63|128):(t[r++]=i>>12|224,t[r++]=i>>6&63|128,t[r++]=i&63|128);return r-n}function ve(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function wo(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}var Qa=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,ve(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 ve(this,4);return wo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ve(this,4);return wo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ve(this,4);let t=Pf(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw ve(this,4);let t=Of(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),r=this.pos,n=this.pos+t;if(n>this.len)throw ve(this,t);return this.pos+=t,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let t=this.bytes();return Ff(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw ve(this,t);this.pos+=t}else do if(this.pos>=this.len)throw ve(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 oe(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*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;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw ve(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,t}if(this.len-this.pos>4){for(;r<5;++r)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;r<5;++r){if(this.pos>=this.len)throw ve(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ve(this,8);let t=wo(this.buf,this.pos+=4),r=wo(this.buf,this.pos+=4);return new oe(t,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){return this.readLongVarint().toNumber(!0)}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 ja(e){return new Qa(e instanceof Uint8Array?e:e.subarray())}function Ee(e,t){let r=ja(e);return t.decode(r)}function Ja(e){let t=e??8192,r=t>>>1,n,i=t;return function(s){if(s<1||s>r)return Vt(s);i+s>t&&(n=Vt(t),i=0);let a=n.subarray(i,i+=s);return i&7&&(i=(i|7)+1),a}}var Hr=class{fn;len;next;val;constructor(t,r,n){this.fn=t,this.len=r,this.next=void 0,this.val=n}};function tc(){}var rc=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},um=Ja();function fm(e){return globalThis.Buffer!=null?Vt(e):um(e)}var di=class{len;head;tail;states;constructor(){this.len=0,this.head=new Hr(tc,0,0),this.tail=this.head,this.states=null}_push(t,r,n){return this.tail=this.tail.next=new Hr(t,r,n),this.len+=r,this}uint32(t){return this.len+=(this.tail=this.tail.next=new nc((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(li,10,oe.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let r=oe.fromBigInt(t);return this._push(li,r.length(),r)}uint64Number(t){let r=oe.fromNumber(t);return this._push(li,r.length(),r)}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 r=oe.fromBigInt(t).zzEncode();return this._push(li,r.length(),r)}sint64Number(t){let r=oe.fromNumber(t).zzEncode();return this._push(li,r.length(),r)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ec,1,t?1:0)}fixed32(t){return this._push(hi,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let r=oe.fromBigInt(t);return this._push(hi,4,r.lo)._push(hi,4,r.hi)}fixed64Number(t){let r=oe.fromNumber(t);return this._push(hi,4,r.lo)._push(hi,4,r.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(Nf,4,t)}double(t){return this._push(Uf,8,t)}bytes(t){let r=t.length>>>0;return r===0?this._push(ec,1,0):this.uint32(r)._push(hm,r,t)}string(t){let r=Mf(t);return r!==0?this.uint32(r)._push(Za,r,t):this._push(ec,1,0)}fork(){return this.states=new rc(this),this.head=this.tail=new Hr(tc,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 Hr(tc,0,0),this.len=0),this}ldelim(){let t=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=r,this.len+=n),this}finish(){let t=this.head.next,r=fm(this.len),n=0;for(;t!=null;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}};function ec(e,t,r){t[r]=e&255}function lm(e,t,r){for(;e>127;)t[r++]=e&127|128,e>>>=7;t[r]=e}var nc=class extends Hr{next;constructor(t,r){super(lm,t,r),this.next=void 0}};function li(e,t,r){for(;e.hi!==0;)t[r++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=e.lo&127|128,e.lo=e.lo>>>7;t[r++]=e.lo}function hi(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function hm(e,t,r){t.set(e,r)}globalThis.Buffer!=null&&(di.prototype.bytes=function(e){let t=e.length>>>0;return this.uint32(t),t>0&&this._push(dm,t,e),this},di.prototype.string=function(e){let t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(pm,t,e),this});function dm(e,t,r){t.set(e,r)}function pm(e,t,r){e.length<40?Za(e,t,r):t.utf8Write!=null?t.utf8Write(e,r):t.set(wt(e),r)}function ic(){return new di}function Se(e,t){let r=ic();return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var An;(function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(An||(An={}));function vo(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function qr(e){function t(i){if(e[i.toString()]==null)throw new Error("Invalid enum value");return e[i]}let r=function(o,s){let a=t(o);s.int32(a)},n=function(o){let s=o.int32();return t(s)};return vo("enum",An.VARINT,r,n)}function Ae(e,t){return vo("message",An.LENGTH_DELIMITED,e,t)}var se;(function(e){let t;(function(i){i.FIN="FIN",i.STOP_SENDING="STOP_SENDING",i.RESET="RESET",i.FIN_ACK="FIN_ACK"})(t=e.Flag||(e.Flag={}));let r;(function(i){i[i.FIN=0]="FIN",i[i.STOP_SENDING=1]="STOP_SENDING",i[i.RESET=2]="RESET",i[i.FIN_ACK=3]="FIN_ACK"})(r||(r={})),function(i){i.codec=()=>qr(r)}(t=e.Flag||(e.Flag={}));let n;e.codec=()=>(n==null&&(n=Ae((i,o,s={})=>{s.lengthDelimited!==!1&&o.fork(),i.flag!=null&&(o.uint32(8),e.Flag.codec().encode(i.flag,o)),i.message!=null&&(o.uint32(18),o.bytes(i.message)),s.lengthDelimited!==!1&&o.ldelim()},(i,o)=>{let s={},a=o==null?i.len:i.pos+o;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:s.flag=e.Flag.codec().decode(i);break;case 2:s.message=i.bytes();break;default:i.skipType(c&7);break}}return s})),n),e.encode=i=>Se(i,e.codec()),e.decode=i=>Ee(i,e.codec())})(se||(se={}));var ym=16*1024*1024,mm=30*1e3,gm=5,xm=2,bm=16*1024,wm=5e3,vm=5e3,oc=class extends go{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;constructor(t){let r=t.onEnd;switch(t.onEnd=i=>{this.log.trace("readable and writeable ends closed",this.status),Promise.resolve(async()=>{if(!(this.timeline.abort!=null||this.timeline.reset!==null))try{await Or(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(o){this.log.error("error receiving FIN_ACK",o)}}).then(()=>{this.incomingData.end(),r?.(i)}).catch(o=>{this.log.error("error ending stream",o)})},super(t),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=mr(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??mm,this.maxBufferedAmount=t.maxBufferedAmount??ym,this.maxMessageSize=(t.maxMessageSize??bm)-gm-xm,this.receiveFinAck=kt(),this.finAckTimeout=t.closeTimeout??wm,this.openTimeout=t.openTimeout??vm,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 W("Unknown datachannel state","ERR_INVALID_STATE")}this.channel.onopen=i=>{this.timeline.open=new Date().getTime()},this.channel.onclose=i=>{this.receiveFinAck.resolve(),this.close().catch(o=>{this.log.error("error closing stream after channel closed",o)})},this.channel.onerror=i=>{let o=i.error;this.abort(o)},this.channel.onmessage=async i=>{let{data:o}=i;o===null||o.byteLength===0||this.incomingData.push(new Uint8Array(o,0,o.byteLength))};let n=this;Promise.resolve().then(async()=>{for await(let i of Fr(this.incomingData)){let o=n.processIncomingProtobuf(i);o!=null&&n.sourcePush(new Bt(o))}}).catch(i=>{this.log.error("error processing incoming data channel messages",i)})}sendNewStream(){}async _sendMessage(t,r=!0){if(r&&this.channel.bufferedAmount>this.maxBufferedAmount)try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await $a(this.channel,"bufferedamountlow",{timeout:this.bufferedAmountLowEventTimeout})}catch(n){throw n instanceof wn?new W(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`,"ERR_BUFFER_CLEAR_TIMEOUT"):n}if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new W(`Invalid datachannel state - ${this.channel.readyState}`,"ERR_INVALID_STATE");this.channel.readyState!=="open"&&(this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await $a(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 r=Math.min(t.byteLength,this.maxMessageSize),n=t.subarray(0,r),i=se.encode({message:n}),o=xr.single(i);await this._sendMessage(o),t.consume(r)}}async sendReset(){await this._sendFlag(se.Flag.RESET)}async sendCloseWrite(t){if(await this._sendFlag(se.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await gr(this.receiveFinAck.promise,t?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorCode:"ERR_FIN_ACK_NOT_RECEIVED"})}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(se.Flag.STOP_SENDING)}processIncomingProtobuf(t){let r=se.decode(t);if(r.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',r.flag,this.writeStatus,this.readStatus),r.flag===se.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(se.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),r.flag===se.Flag.RESET&&this.reset(),r.flag===se.Flag.STOP_SENDING&&this.remoteCloseRead(),r.flag===se.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),this.readStatus==="ready")return r.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 r=se.encode({flag:t}),n=xr.single(r);try{return await this._sendMessage(n,!1),!0}catch(i){this.log.error("could not send flag %s",t.toString(),i)}return!1}};function Dn(e){let{channel:t,direction:r}=e;return new oc({id:r==="inbound"?`i${t.id}`:`r${t.id}`,log:e.logger.forComponent(`libp2p:webrtc:stream:${r}:${t.id}`),...e})}var Hf="/webrtc",zr=class{protocol;peerConnection;bufferedStreams=[];metrics;dataChannelOptions;components;log;constructor(t,r){this.components=t,this.peerConnection=r.peerConnection,this.metrics=r.metrics,this.protocol=r.protocol??Hf,this.dataChannelOptions=r.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 i={},o=Dn({channel:n,direction:"inbound",onEnd:s=>{i.onEnd(s)},logger:t.logger,...this.dataChannelOptions});i.stream=o,i.channel=n,i.onEnd=()=>{this.bufferedStreams=this.bufferedStreams.filter(s=>s.stream.id!==o.id)},this.bufferedStreams.push(i)}}createStreamMuxer(t){return new sc(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},sc=class{init;streams;protocol;log;peerConnection;dataChannelOptions;metrics;logger;constructor(t,r){this.init=r,this.log=t.logger.forComponent("libp2p:webrtc:muxer"),this.logger=t.logger,this.streams=r.streams.map(n=>n.stream),this.peerConnection=r.peerConnection,this.protocol=r.protocol??Hf,this.metrics=r.metrics,this.dataChannelOptions=r.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 i=Dn({channel:n,direction:"inbound",onEnd:()=>{this.log("incoming channel %s ended with state %s",n.id,n.readyState),this.#t(i,n)},logger:this.logger,...this.dataChannelOptions});this.streams.push(i),this.metrics?.increment({incoming_stream:!0}),r?.onIncomingStream?.(i)},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,r){this.log.trace("stream %s %s %s onEnd",t.direction,t.id,t.protocol),Df(r,`${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 r=>r.close(t)))}catch(r){this.abort(r)}}abort(t){for(let r of this.streams)r.abort(t)}source=lo();sink=ho;newStream(){let t=this.peerConnection.createDataChannel("");this.log.trace("opened outgoing datachannel with channel id %s",t.id);let r=Dn({channel:t,direction:"outbound",onEnd:()=>{this.log("outgoing channel %s ended with state %s",t.id,t.readyState),this.#t(r,t)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(r),this.metrics?.increment({outgoing_stream:!0}),r}};var Cn=globalThis.RTCPeerConnection,Eo=globalThis.RTCSessionDescription,qf=globalThis.RTCIceCandidate;var ac=class{needNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.needNext=kt(),this.haveNext=kt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("Have next but next was undefined");let t=this.nextResult;return this.nextResult=void 0,this.needNext.resolve(),this.needNext=kt(),t}async throw(t){return this.ended=!0,t!=null&&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,r){await this._push(t,r)}async end(t,r){t!=null?await this.throw(t):await this._push(void 0,r)}async _push(t,r){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");this.nextResult!=null&&await this.needNext.promise,t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=kt(),await gr(this.needNext.promise,r?.signal,r)}};function zf(){return new ac}var So=class extends Error{code;constructor(t,r){super(t),this.code=r}},cc=class extends So{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted"}};function Gf(e,t){let r=zf();e.sink(r).catch(async s=>{await r.end(s)}),e.sink=async s=>{for await(let a of s)await r.push(a);await r.end()};let n=e.source;e.source[Symbol.iterator]!=null?n=e.source[Symbol.iterator]():e.source[Symbol.asyncIterator]!=null&&(n=e.source[Symbol.asyncIterator]());let i=new Bt;return{read:async(s,a)=>{a?.signal?.throwIfAborted();let c,u=new Promise((f,l)=>{c=()=>{l(new cc("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(s==null){let{done:l,value:d}=await Promise.race([n.next(),u]);return l===!0?new Bt:d}for(;i.byteLength<s;){let{value:l,done:d}=await Promise.race([n.next(),u]);if(d===!0)throw new So("unexpected end of input","ERR_UNEXPECTED_EOF");i.append(l)}let f=i.sublist(0,s);return i.consume(s),f}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(s,a)=>{a?.signal?.throwIfAborted(),s instanceof Uint8Array?await r.push(s,a):await r.push(s.subarray(),a)},unwrap:()=>{if(i.byteLength>0){let s=e.source;e.source=async function*(){t?.yieldBytes===!1?yield i:yield*i,yield*s}()}return e}}}var Ao=class extends Error{code;constructor(t,r){super(t),this.code=r}},Wf=e=>we(e);Wf.bytes=0;function pi(e,t={}){let r=Gf(e,t);return t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=ee(t.maxDataLength)),{read:async i=>{let o=-1,s=new Bt,a=t?.lengthDecoder??Wf;for(;;){s.append(await r.read(1,i));try{o=a(s)}catch(c){if(c instanceof RangeError)continue;throw c}if(t?.maxLengthLength!=null&&s.byteLength>t.maxLengthLength)throw new Ao("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(o>-1)break}if(t?.maxDataLength!=null&&o>t.maxDataLength)throw new Ao("message length too long","ERR_MSG_DATA_TOO_LONG");return r.read(o,i)},write:async(i,o)=>{await r.write(xr.single(i,t),o)},writeV:async(i,o)=>{let s=new Bt(...i.map(a=>xr.single(a,t)));await r.write(s,o)},unwrap:()=>r.unwrap()}}function Do(e,t){let r=pi(e,t),n={read:async(i,o)=>{let s=await r.read(o);return i.decode(s)},write:async(i,o,s)=>{await r.write(o.encode(i),s)},writeV:async(i,o,s)=>{await r.writeV(i.map(a=>o.encode(a)),s)},pb:i=>({read:async o=>n.read(i,o),write:async(o,s)=>n.write(o,i,s),writeV:async(o,s)=>n.writeV(o,i,s),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}var ae;(function(e){let t;(function(i){i.SDP_OFFER="SDP_OFFER",i.SDP_ANSWER="SDP_ANSWER",i.ICE_CANDIDATE="ICE_CANDIDATE"})(t=e.Type||(e.Type={}));let r;(function(i){i[i.SDP_OFFER=0]="SDP_OFFER",i[i.SDP_ANSWER=1]="SDP_ANSWER",i[i.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(r||(r={})),function(i){i.codec=()=>qr(r)}(t=e.Type||(e.Type={}));let n;e.codec=()=>(n==null&&(n=Ae((i,o,s={})=>{s.lengthDelimited!==!1&&o.fork(),i.type!=null&&(o.uint32(8),e.Type.codec().encode(i.type,o)),i.data!=null&&(o.uint32(18),o.string(i.data)),s.lengthDelimited!==!1&&o.ldelim()},(i,o)=>{let s={},a=o==null?i.len:i.pos+o;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:s.type=e.Type.codec().decode(i);break;case 2:s.data=i.string();break;default:i.skipType(c&7);break}}return s})),n),e.encode=i=>Se(i,e.codec()),e.decode=i=>Ee(i,e.codec())})(ae||(ae={}));function $f(e){let t=new globalThis.AbortController;function r(){t.abort();for(let o of e)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}for(let o of e){if(o?.aborted===!0){r();break}o?.addEventListener!=null&&o.addEventListener("abort",r)}function n(){for(let o of e)o?.removeEventListener!=null&&o.removeEventListener("abort",r)}let i=t.signal;return i.clear=n,i}var Co=async(e,t,r,n)=>{let i=new AbortController;e.promise.then(()=>{i.abort()},()=>{i.abort()});let o=$f([i.signal,n.signal]),s=()=>{mo(r.unwrap().unwrap().source,n.log)};o.addEventListener("abort",s);try{for(;;){let a=await Promise.race([e.promise,r.read()]);if(a==null)break;if(a.type!==ae.Type.ICE_CANDIDATE)throw new W("ICE candidate message expected","ERR_NOT_ICE_CANDIDATE");let c=JSON.parse(a.data??"null");if(c===""||c===null){n.log.trace("end-of-candidates received");continue}let u=new qf(c);n.log.trace("%s received new ICE candidate",n.direction,u);try{await t.addIceCandidate(u)}catch(f){n.log.error("%s bad candidate received",n.direction,c,f)}}}catch(a){n.log.error("%s error parsing ICE candidate",n.direction,a)}finally{o.removeEventListener("abort",s),o.clear()}};function Bo(e,t){e[fi?"oniceconnectionstatechange":"onconnectionstatechange"]=r=>{switch(fi?e.iceConnectionState:e.connectionState){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new W("RTCPeerConnection was closed","ERR_CONNECTION_CLOSED_BEFORE_CONNECTED"));break;default:break}}}async function Yf({peerConnection:e,signal:t,metrics:r,multiaddr:n,connectionManager:i,transportManager:o,log:s}){let{baseAddr:a}=Xf(n);r?.dialerEvents.increment({open:!0}),s.trace("dialing base address: %a",a);let c=a.getPeerId();if(c==null)throw new W("Relay peer was missing","ERR_INVALID_ADDRESS");let u=i.getConnections(Ur(c)),f,l=!1;u.length===0?(f=await o.dial(a,{signal:t}),l=!0):f=u[0];try{let d=await f.newStream(Io,{signal:t,runOnTransientConnection:!0}),y=Do(d).pb(ae),h=kt(),p=()=>{h.reject(new W("SDP handshake aborted","ERR_SDP_HANDSHAKE_ABORTED"))};try{Bo(e,h),t?.addEventListener("abort",p);let m=e.createDataChannel("init");e.onicecandidate=({candidate:A})=>{let v=JSON.stringify(A?.toJSON()??null);s.trace("initiator sending ICE candidate %s",v),y.write({type:ae.Type.ICE_CANDIDATE,data:v},{signal:t}).catch(E=>{s.error("error sending ICE candidate",E)})},e.onicecandidateerror=A=>{s("initiator ICE candidate error",A)};let g=await e.createOffer();s.trace("initiator send SDP offer %s",g.sdp),await y.write({type:ae.Type.SDP_OFFER,data:g.sdp},{signal:t}),await e.setLocalDescription(g).catch(A=>{throw s.error("could not execute setLocalDescription",A),new W("Failed to set localDescription","ERR_SDP_HANDSHAKE_FAILED")});let b=await y.read({signal:t});if(b.type!==ae.Type.SDP_ANSWER)throw new W("remote should send an SDP answer","ERR_SDP_HANDSHAKE_FAILED");s.trace("initiator receive SDP answer %s",b.data);let x=new Eo({type:"answer",sdp:b.data});return await e.setRemoteDescription(x).catch(A=>{throw s.error("could not execute setRemoteDescription",A),new W("Failed to set remoteDescription","ERR_SDP_HANDSHAKE_FAILED")}),s.trace("initiator read candidates until connected"),await Co(h,e,y,{direction:"initiator",signal:t,log:s}),s.trace("initiator connected, closing init channel"),m.close(),s.trace("initiator closing signalling stream"),await y.unwrap().unwrap().close({signal:t}),s.trace("initiator connected to remote address %s",n),{remoteAddress:n}}catch(m){throw e.close(),d.abort(m),m}finally{t?.removeEventListener("abort",p),e.onicecandidate=null,e.onicecandidateerror=null}}finally{if(l)try{await f.close({signal:t})}catch(d){f.abort(d)}}}var Em=q("dns4"),Sm=q("dns6"),Am=q("dnsaddr"),Gr=Ot(q("dns"),Am,Em,Sm),ko=Ot(q("ip4"),q("ip6")),Bn=Ot(X(ko,q("tcp")),X(Gr,q("tcp"))),Ro=X(ko,q("udp")),Dm=X(Ro,q("utp")),Cm=X(Ro,q("quic")),Bm=X(Ro,q("quic-v1")),uc=Ot(X(Bn,q("ws")),X(Gr,q("ws"))),To=Ot(X(uc,q("p2p")),uc),fc=Ot(X(Bn,q("wss")),X(Gr,q("wss")),X(Bn,q("tls"),q("ws")),X(Gr,q("tls"),q("ws"))),_o=Ot(X(fc,q("p2p")),fc),lc=Ot(X(Bn,q("http")),X(ko,q("http")),X(Gr,q("http"))),hc=Ot(X(Bn,q("https")),X(ko,q("https")),X(Gr,q("https"))),Zf=X(Ro,q("webrtc-direct"),q("certhash")),Jf=Ot(X(Zf,q("p2p")),Zf),Qf=X(Bm,q("webtransport"),q("certhash"),q("certhash")),tl=Ot(X(Qf,q("p2p")),Qf),el=Ot(X(To,q("p2p-webrtc-star"),q("p2p")),X(_o,q("p2p-webrtc-star"),q("p2p")),X(To,q("p2p-webrtc-star")),X(_o,q("p2p-webrtc-star"))),gA=Ot(X(To,q("p2p-websocket-star"),q("p2p")),X(_o,q("p2p-websocket-star"),q("p2p")),X(To,q("p2p-websocket-star")),X(_o,q("p2p-websocket-star"))),rl=Ot(X(lc,q("p2p-webrtc-direct"),q("p2p")),X(hc,q("p2p-webrtc-direct"),q("p2p")),X(lc,q("p2p-webrtc-direct")),X(hc,q("p2p-webrtc-direct"))),Wr=Ot(uc,fc,lc,hc,el,rl,Bn,Dm,Cm,Gr,Jf,tl),xA=Ot(X(Wr,q("p2p-stardust"),q("p2p")),X(Wr,q("p2p-stardust"))),wr=Ot(X(Wr,q("p2p")),el,rl,Jf,tl,q("p2p")),jf=Ot(X(wr,q("p2p-circuit"),wr),X(wr,q("p2p-circuit")),X(q("p2p-circuit"),wr),X(Wr,q("p2p-circuit")),X(q("p2p-circuit"),Wr),q("p2p-circuit")),nl=()=>Ot(X(jf,nl),jf),Qe=nl(),bA=Ot(X(Qe,wr,Qe),X(wr,Qe),X(Qe,wr),Qe,wr);var wA=Ot(X(Qe,q("webrtc"),q("p2p")),X(Qe,q("webrtc")),X(Wr,q("webrtc"),q("p2p")),X(Wr,q("webrtc")),q("webrtc"));function il(e){function t(r){let n;try{n=Ze(r)}catch{return!1}let i=e(n.protoNames());return i===null?!1:i===!0||i===!1?i:i.length===0}return t}function X(...e){function t(r){if(r.length<e.length)return null;let n=r;return e.some(i=>(n=typeof i=="function"?i().partialMatch(r):i.partialMatch(r),Array.isArray(n)&&(r=n),n===null)),n}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:il(t),partialMatch:t}}function Ot(...e){function t(n){let i=null;return e.some(o=>{let s=typeof o=="function"?o().partialMatch(n):o.partialMatch(n);return s!=null?(i=s,!0):!1}),i}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:il(t),partialMatch:t}}function q(e){let t=e;function r(i){let o;try{o=Ze(i)}catch{return!1}let s=o.protoNames();return s.length===1&&s[0]===t}function n(i){return i.length===0?null:i[0]===t?i.slice(1):null}return{toString:function(){return t},matches:r,partialMatch:n}}var Lo=class extends Xi{peerId;transportManager;shutdownController;constructor(t,r){super(),this.peerId=t.peerId,this.transportManager=t.transportManager,this.shutdownController=r.shutdownController}async listen(){this.safeDispatchEvent("listening",{})}getAddrs(){return this.transportManager.getListeners().filter(t=>t!==this).map(t=>t.getAddrs().filter(r=>Qe.matches(r)).map(r=>r.encapsulate(`/webrtc/p2p/${this.peerId}`))).flat()}async close(){this.shutdownController.abort(),this.safeDispatchEvent("close",{})}};async function ol({peerConnection:e,stream:t,signal:r,connection:n,log:i}){i.trace("new inbound signaling stream");let o=Do(t).pb(ae);try{let a=kt(),c=kt();r.onabort=()=>{a.reject(new W("Timed out while trying to connect","ERR_TIMEOUT"))},e.onicecandidate=({candidate:d})=>{c.promise.then(async()=>{let y=JSON.stringify(d?.toJSON()??null);i.trace("recipient sending ICE candidate %s",y),await o.write({type:ae.Type.ICE_CANDIDATE,data:y},{signal:r})},y=>{i.error("cannot set candidate since sending answer failed",y),a.reject(y)})},Bo(e,a);let u=await o.read({signal:r});if(u.type!==ae.Type.SDP_OFFER)throw new W(`expected message type SDP_OFFER, received: ${u.type??"undefined"} `,"ERR_SDP_HANDSHAKE_FAILED");i.trace("recipient receive SDP offer %s",u.data);let f=new Eo({type:"offer",sdp:u.data});await e.setRemoteDescription(f).catch(d=>{throw i.error("could not execute setRemoteDescription",d),new W("Failed to set remoteDescription","ERR_SDP_HANDSHAKE_FAILED")});let l=await e.createAnswer().catch(d=>{throw i.error("could not execute createAnswer",d),c.reject(d),new W("Failed to create answer","ERR_SDP_HANDSHAKE_FAILED")});i.trace("recipient send SDP answer %s",l.sdp),await o.write({type:ae.Type.SDP_ANSWER,data:l.sdp},{signal:r}),await e.setLocalDescription(l).catch(d=>{throw i.error("could not execute setLocalDescription",d),c.reject(d),new W("Failed to set localDescription","ERR_SDP_HANDSHAKE_FAILED")}),c.resolve(),i.trace("recipient read candidates until connected"),await Co(a,e,o,{direction:"recipient",signal:r,log:i}),i.trace("recipient connected, closing signaling stream"),await o.unwrap().unwrap().close({signal:r})}catch(a){if(e.connectionState!=="connected")throw i.error("error while handling signaling stream from peer %a",n.remoteAddr,a),e.close(),a;i("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",n.remoteAddr,a)}let s=Ze(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return i.trace("recipient connected to remote address %s",s),{remoteAddress:s}}var Im="/webrtc",Tm="/p2p-circuit",Io="/webrtc-signaling/0.0.1",_m=30*1e3,No=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,r={}){this.components=t,this.init=r,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,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"})})}isStarted(){return this._started}async start(){await this.components.registrar.handle(Io,t=>{this._onProtocol(t).catch(r=>{this.log.error("failed to handle incoming connect from %p",t.connection.remotePeer,r)})},{runOnTransientConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(Io),this._started=!1}createListener(t){return new Lo(this.components,{shutdownController:this.shutdownController})}[Symbol.toStringTag]="@libp2p/webrtc";[Yi]=!0;filter(t){return t.filter(pf.exactMatch)}async dial(t,r){this.log.trace("dialing address: %a",t);let n=new Cn(this.init.rtcConfiguration),i=new zr(this.components,{peerConnection:n,dataChannelOptions:this.init.dataChannel}),{remoteAddress:o}=await Yf({peerConnection:n,multiaddr:t,dataChannelOptions:this.init.dataChannel,signal:r.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log}),s=new Kr(this.components,{peerConnection:n,timeline:{open:Date.now()},remoteAddr:o,metrics:this.metrics?.dialerEvents}),a=await r.upgrader.upgradeOutbound(s,{skipProtection:!0,skipEncryption:!0,muxerFactory:i});return this._closeOnShutdown(n,s),a}async _onProtocol({connection:t,stream:r}){let n=AbortSignal.timeout(this.init.inboundConnectionTimeout??_m),i=new Cn(this.init.rtcConfiguration),o=new zr(this.components,{peerConnection:i,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:s}=await ol({peerConnection:i,connection:t,stream:r,signal:n,log:this.log}),a=new Kr(this.components,{peerConnection:i,timeline:{open:new Date().getTime()},remoteAddr:s,metrics:this.metrics?.listenerEvents});this._closeOnShutdown(i,a),await this.components.upgrader.upgradeInbound(a,{skipEncryption:!0,skipProtection:!0,muxerFactory:o}),await r.close({signal:n})}catch(s){throw r.abort(s),s}}_closeOnShutdown(t,r){let n=()=>{r.close().catch(i=>{this.log.error("could not close WebRTCMultiaddrConnection",i)})};this.shutdownController.signal.addEventListener("abort",n),t.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function Xf(e){let t=e.toString().split(Im+"/");if(t.length!==2)throw new W("webrtc protocol was not present in multiaddr",fe.ERR_INVALID_MULTIADDR);if(!t[0].includes(Tm))throw new W("p2p-circuit protocol was not present in multiaddr",fe.ERR_INVALID_MULTIADDR);let r=Ze(t[0]),i=Ze("/"+t[1]).getPeerId();if(i==null)throw new W("destination peer id was missing",fe.ERR_INVALID_MULTIADDR);let o=r.protos().pop();if(o===void 0)throw new W("invalid multiaddr",fe.ERR_INVALID_MULTIADDR);return o.name!=="p2p"&&(r=r.encapsulate(`/p2p/${i}`)),{baseAddr:r,peerId:Ur(i)}}function dc(){let e=kt(),t=!1;return{sink:async r=>{if(t)throw new Error("already piped");t=!0,e.resolve(r)},source:async function*(){yield*await e.promise}()}}function sl(){let e=dc(),t=dc();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}function km(e){return e[Symbol.asyncIterator]!=null}function Rm(...e){let t=[];for(let r of e)km(r)||t.push(r);return t.length===e.length?function*(){for(let r of t)yield*r}():async function*(){let r=mr({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(e.map(async n=>{for await(let i of n)r.push(i)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var al=Rm;function cl(e,...t){if(e==null)throw new Error("Empty pipeline");if(pc(e)){let n=e;e=()=>n.source}else if(fl(e)||ul(e)){let n=e;e=()=>n}let r=[e,...t];if(r.length>1&&pc(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let n=1;n<r.length-1;n++)pc(r[n])&&(r[n]=Nm(r[n]));return Lm(...r)}var Lm=(...e)=>{let t;for(;e.length>0;)t=e.shift()(t);return t},ul=e=>e?.[Symbol.asyncIterator]!=null,fl=e=>e?.[Symbol.iterator]!=null,pc=e=>e==null?!1:e.sink!=null&&e.source!=null,Nm=e=>t=>{let r=e.sink(t);if(r?.then!=null){let n=mr({objectMode:!0});r.then(()=>{n.end()},s=>{n.end(s)});let i,o=e.source;if(ul(o))i=async function*(){yield*o,n.end()};else if(fl(o))i=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return al(n,i())}return e.source};var In=!!globalThis.process?.env?.DUMP_SESSION_KEYS;var Pm=e=>e instanceof Uint8Array;var je=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),ll=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),Um=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Um)throw new Error("Non little-endian hardware is not supported");function Po(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function Uo(e){if(typeof e=="string")e=Po(e);else if(Pm(e))e=e.slice();else throw new Error(`expected Uint8Array, got ${typeof e}`);return e}var Om=e=>Object.prototype.toString.call(e)==="[object Object]"&&e.constructor===Object;function hl(e,t){if(t!==void 0&&(typeof t!="object"||!Om(t)))throw new Error("options must be object or undefined");return Object.assign(e,t)}function $r(e,t){if(!(e instanceof Uint8Array))throw new Error("Uint8Array expected");if(typeof t=="number"&&e.length!==t)throw new Error(`Uint8Array length ${t} expected`)}function dl(e,t){if(e.length!==t.length)throw new Error("equalBytes: Different size of Uint8Arrays");let r=!0;for(let n=0;n<e.length;n++)r&&(r=e[n]===t[n]);return r}var yc=(e,t)=>(Object.assign(t,e),t);function mc(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),a=Number(r&o),c=n?4:0,u=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+u,a,n)}function Oo(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function gc(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}function Tn(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function xc(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function pl(e,t){Tn(e);let r=t.outputLen;if(e.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var Zt=(e,t)=>e[t++]&255|(e[t++]&255)<<8,bc=class{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=Uo(t),$r(t,32);let r=Zt(t,0),n=Zt(t,2),i=Zt(t,4),o=Zt(t,6),s=Zt(t,8),a=Zt(t,10),c=Zt(t,12),u=Zt(t,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|i<<6)&7939,this.r[3]=(i>>>7|o<<9)&8191,this.r[4]=(o>>>4|s<<12)&255,this.r[5]=s>>>1&8190,this.r[6]=(s>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let f=0;f<8;f++)this.pad[f]=Zt(t,16+2*f)}process(t,r,n=!1){let i=n?0:2048,{h:o,r:s}=this,a=s[0],c=s[1],u=s[2],f=s[3],l=s[4],d=s[5],y=s[6],h=s[7],p=s[8],m=s[9],g=Zt(t,r+0),b=Zt(t,r+2),x=Zt(t,r+4),A=Zt(t,r+6),v=Zt(t,r+8),E=Zt(t,r+10),C=Zt(t,r+12),B=Zt(t,r+14),O=o[0]+(g&8191),K=o[1]+((g>>>13|b<<3)&8191),U=o[2]+((b>>>10|x<<6)&8191),F=o[3]+((x>>>7|A<<9)&8191),G=o[4]+((A>>>4|v<<12)&8191),Q=o[5]+(v>>>1&8191),I=o[6]+((v>>>14|E<<2)&8191),R=o[7]+((E>>>11|C<<5)&8191),_=o[8]+((C>>>8|B<<8)&8191),k=o[9]+(B>>>5|i),S=0,P=S+O*a+K*(5*m)+U*(5*p)+F*(5*h)+G*(5*y);S=P>>>13,P&=8191,P+=Q*(5*d)+I*(5*l)+R*(5*f)+_*(5*u)+k*(5*c),S+=P>>>13,P&=8191;let M=S+O*c+K*a+U*(5*m)+F*(5*p)+G*(5*h);S=M>>>13,M&=8191,M+=Q*(5*y)+I*(5*d)+R*(5*l)+_*(5*f)+k*(5*u),S+=M>>>13,M&=8191;let H=S+O*u+K*c+U*a+F*(5*m)+G*(5*p);S=H>>>13,H&=8191,H+=Q*(5*h)+I*(5*y)+R*(5*d)+_*(5*l)+k*(5*f),S+=H>>>13,H&=8191;let Z=S+O*f+K*u+U*c+F*a+G*(5*m);S=Z>>>13,Z&=8191,Z+=Q*(5*p)+I*(5*h)+R*(5*y)+_*(5*d)+k*(5*l),S+=Z>>>13,Z&=8191;let j=S+O*l+K*f+U*u+F*c+G*a;S=j>>>13,j&=8191,j+=Q*(5*m)+I*(5*p)+R*(5*h)+_*(5*y)+k*(5*d),S+=j>>>13,j&=8191;let it=S+O*d+K*l+U*f+F*u+G*c;S=it>>>13,it&=8191,it+=Q*a+I*(5*m)+R*(5*p)+_*(5*h)+k*(5*y),S+=it>>>13,it&=8191;let J=S+O*y+K*d+U*l+F*f+G*u;S=J>>>13,J&=8191,J+=Q*c+I*a+R*(5*m)+_*(5*p)+k*(5*h),S+=J>>>13,J&=8191;let et=S+O*h+K*y+U*d+F*l+G*f;S=et>>>13,et&=8191,et+=Q*u+I*c+R*a+_*(5*m)+k*(5*p),S+=et>>>13,et&=8191;let bt=S+O*p+K*h+U*y+F*d+G*l;S=bt>>>13,bt&=8191,bt+=Q*f+I*u+R*c+_*a+k*(5*m),S+=bt>>>13,bt&=8191;let gt=S+O*m+K*p+U*h+F*y+G*d;S=gt>>>13,gt&=8191,gt+=Q*l+I*f+R*u+_*c+k*a,S+=gt>>>13,gt&=8191,S=(S<<2)+S|0,S=S+P|0,P=S&8191,S=S>>>13,M+=S,o[0]=P,o[1]=M,o[2]=H,o[3]=Z,o[4]=j,o[5]=it,o[6]=J,o[7]=et,o[8]=bt,o[9]=gt}finalize(){let{h:t,pad:r}=this,n=new Uint16Array(10),i=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=i,i=t[a]>>>13,t[a]&=8191;t[0]+=i*5,i=t[0]>>>13,t[0]&=8191,t[1]+=i,i=t[1]>>>13,t[1]&=8191,t[2]+=i,n[0]=t[0]+5,i=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+i,i=n[a]>>>13,n[a]&=8191;n[9]-=8192;let o=(i^1)-1;for(let a=0;a<10;a++)n[a]&=o;o=~o;for(let a=0;a<10;a++)t[a]=t[a]&o|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 s=t[0]+r[0];t[0]=s&65535;for(let a=1;a<8;a++)s=(t[a]+r[a]|0)+(s>>>16)|0,t[a]=s&65535}update(t){xc(this);let{buffer:r,blockLen:n}=this;t=Uo(t);let i=t.length;for(let o=0;o<i;){let s=Math.min(n-this.pos,i-o);if(s===n){for(;n<=i-o;o+=n)this.process(t,o);continue}r.set(t.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){this.h.fill(0),this.r.fill(0),this.buffer.fill(0),this.pad.fill(0)}digestInto(t){xc(this),pl(t,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:i}=this;if(i){for(r[i++]=1;i<16;i++)r[i]=0;this.process(r,0,!0)}this.finalize();let o=0;for(let s=0;s<8;s++)t[o++]=n[s]>>>0,t[o++]=n[s]>>>8;return t}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}};function Km(e){let t=(n,i)=>e(i).update(Uo(n)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}var yl=Km(e=>new bc(e));var Mm=Po("expand 16-byte k"),Fm=Po("expand 32-byte k"),Vm=je(Mm),Hm=je(Fm);function $(e,t){return e<<t|e>>>32-t}function wc(e){return e.byteOffset%4===0}var Ko=64,qm=16,gl=2**32-1,ml=new Uint32Array;function zm(e,t,r,n,i,o,s,a){let c=i.length,u=new Uint8Array(Ko),f=je(u),l=wc(i)&&wc(o),d=l?je(i):ml,y=l?je(o):ml;for(let h=0;h<c;s++){if(e(t,r,n,f,s,a),s>=gl)throw new Error("arx: counter overflow");let p=Math.min(Ko,c-h);if(l&&p===Ko){let m=h/4;if(h%4!==0)throw new Error("arx: invalid block position");for(let g=0,b;g<qm;g++)b=m+g,y[b]=d[b]^f[g];h+=Ko;continue}for(let m=0,g;m<p;m++)g=h+m,o[g]=i[g]^u[m];h+=p}}function vc(e,t){let{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:o,rounds:s}=hl({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return Oo(i),Oo(s),gc(o),gc(r),(a,c,u,f,l=0)=>{Tn(a),Tn(c),Tn(u);let d=u.length;if(f||(f=new Uint8Array(d)),Tn(f),Oo(l),l<0||l>=gl)throw new Error("arx: counter overflow");if(f.length<d)throw new Error(`arx: output (${f.length}) is shorter than data (${d})`);let y=[],h=a.length,p,m;if(h===32)p=a.slice(),y.push(p),m=Hm;else if(h===16&&r)p=new Uint8Array(32),p.set(a),p.set(a,16),m=Vm,y.push(p);else throw new Error(`arx: invalid 32-byte key, got length=${h}`);wc(c)||(c=c.slice(),y.push(c));let g=je(p);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(m,g,je(c.subarray(0,16)),g),c=c.subarray(16)}let b=16-i;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let A=new Uint8Array(12);A.set(c,o?0:12-c.length),c=A,y.push(c)}let x=je(c);for(zm(e,m,g,x,u,f,l,s);y.length>0;)y.pop().fill(0);return f}}function wl(e,t,r,n,i,o=20){let s=e[0],a=e[1],c=e[2],u=e[3],f=t[0],l=t[1],d=t[2],y=t[3],h=t[4],p=t[5],m=t[6],g=t[7],b=i,x=r[0],A=r[1],v=r[2],E=s,C=a,B=c,O=u,K=f,U=l,F=d,G=y,Q=h,I=p,R=m,_=g,k=b,S=x,P=A,M=v;for(let Z=0;Z<o;Z+=2)E=E+K|0,k=$(k^E,16),Q=Q+k|0,K=$(K^Q,12),E=E+K|0,k=$(k^E,8),Q=Q+k|0,K=$(K^Q,7),C=C+U|0,S=$(S^C,16),I=I+S|0,U=$(U^I,12),C=C+U|0,S=$(S^C,8),I=I+S|0,U=$(U^I,7),B=B+F|0,P=$(P^B,16),R=R+P|0,F=$(F^R,12),B=B+F|0,P=$(P^B,8),R=R+P|0,F=$(F^R,7),O=O+G|0,M=$(M^O,16),_=_+M|0,G=$(G^_,12),O=O+G|0,M=$(M^O,8),_=_+M|0,G=$(G^_,7),E=E+U|0,M=$(M^E,16),R=R+M|0,U=$(U^R,12),E=E+U|0,M=$(M^E,8),R=R+M|0,U=$(U^R,7),C=C+F|0,k=$(k^C,16),_=_+k|0,F=$(F^_,12),C=C+F|0,k=$(k^C,8),_=_+k|0,F=$(F^_,7),B=B+G|0,S=$(S^B,16),Q=Q+S|0,G=$(G^Q,12),B=B+G|0,S=$(S^B,8),Q=Q+S|0,G=$(G^Q,7),O=O+K|0,P=$(P^O,16),I=I+P|0,K=$(K^I,12),O=O+K|0,P=$(P^O,8),I=I+P|0,K=$(K^I,7);let H=0;n[H++]=s+E|0,n[H++]=a+C|0,n[H++]=c+B|0,n[H++]=u+O|0,n[H++]=f+K|0,n[H++]=l+U|0,n[H++]=d+F|0,n[H++]=y+G|0,n[H++]=h+Q|0,n[H++]=p+I|0,n[H++]=m+R|0,n[H++]=g+_|0,n[H++]=b+k|0,n[H++]=x+S|0,n[H++]=A+P|0,n[H++]=v+M|0}function Gm(e,t,r,n){let i=e[0],o=e[1],s=e[2],a=e[3],c=t[0],u=t[1],f=t[2],l=t[3],d=t[4],y=t[5],h=t[6],p=t[7],m=r[0],g=r[1],b=r[2],x=r[3];for(let v=0;v<20;v+=2)i=i+c|0,m=$(m^i,16),d=d+m|0,c=$(c^d,12),i=i+c|0,m=$(m^i,8),d=d+m|0,c=$(c^d,7),o=o+u|0,g=$(g^o,16),y=y+g|0,u=$(u^y,12),o=o+u|0,g=$(g^o,8),y=y+g|0,u=$(u^y,7),s=s+f|0,b=$(b^s,16),h=h+b|0,f=$(f^h,12),s=s+f|0,b=$(b^s,8),h=h+b|0,f=$(f^h,7),a=a+l|0,x=$(x^a,16),p=p+x|0,l=$(l^p,12),a=a+l|0,x=$(x^a,8),p=p+x|0,l=$(l^p,7),i=i+u|0,x=$(x^i,16),h=h+x|0,u=$(u^h,12),i=i+u|0,x=$(x^i,8),h=h+x|0,u=$(u^h,7),o=o+f|0,m=$(m^o,16),p=p+m|0,f=$(f^p,12),o=o+f|0,m=$(m^o,8),p=p+m|0,f=$(f^p,7),s=s+l|0,g=$(g^s,16),d=d+g|0,l=$(l^d,12),s=s+l|0,g=$(g^s,8),d=d+g|0,l=$(l^d,7),a=a+c|0,b=$(b^a,16),y=y+b|0,c=$(c^y,12),a=a+c|0,b=$(b^a,8),y=y+b|0,c=$(c^y,7);let A=0;n[A++]=i,n[A++]=o,n[A++]=s,n[A++]=a,n[A++]=m,n[A++]=g,n[A++]=b,n[A++]=x}var Wm=vc(wl,{counterRight:!1,counterLength:4,allowShortKeys:!1}),$m=vc(wl,{counterRight:!1,counterLength:8,extendNonceFn:Gm,allowShortKeys:!1});var Ym=new Uint8Array(16),xl=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(Ym.subarray(r))},Xm=new Uint8Array(32);function bl(e,t,r,n,i){let o=e(t,r,Xm),s=yl.create(o);i&&xl(s,i),xl(s,n);let a=new Uint8Array(16),c=ll(a);mc(c,0,BigInt(i?i.length:0),!0),mc(c,8,BigInt(n.length),!0),s.update(a);let u=s.digest();return o.fill(0),u}var vl=e=>(t,r,n)=>($r(t,32),$r(r),{encrypt:(o,s)=>{let a=o.length,c=a+16;s?$r(s,c):s=new Uint8Array(c),e(t,r,o,s,1);let u=bl(e,t,r,s.subarray(0,-16),n);return s.set(u,a),s},decrypt:(o,s)=>{let a=o.length,c=a-16;if(a<16)throw new Error("encrypted data must be at least 16 bytes");s?$r(s,c):s=new Uint8Array(c);let u=o.subarray(0,-16),f=o.subarray(-16),l=bl(e,t,r,u,n);if(!dl(f,l))throw new Error("invalid tag");return e(t,r,u,s,1),s}}),Ec=yc({blockSize:64,nonceLength:12,tagLength:16},vl(Wm)),pD=yc({blockSize:64,nonceLength:24,tagLength:16},vl($m));function Mo(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function Sc(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function yi(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Mo(e.outputLen),Mo(e.blockLen)}function _n(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function El(e,t){Sc(e);let r=t.outputLen;if(e.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}var Fo=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Sl=e=>e instanceof Uint8Array;var Vo=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),De=(e,t)=>e<<32-t|e>>>t,Zm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Zm)throw new Error("Non little-endian hardware is not supported");function Ac(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function vr(e){if(typeof e=="string"&&(e=Ac(e)),!Sl(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}function Ho(...e){let t=new Uint8Array(e.reduce((n,i)=>n+i.length,0)),r=0;return e.forEach(n=>{if(!Sl(n))throw new Error("Uint8Array expected");t.set(n,r),r+=n.length}),t}var kn=class{clone(){return this._cloneInto()}},bD={}.toString;function qo(e){let t=n=>e().update(vr(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Yr(e=32){if(Fo&&typeof Fo.getRandomValues=="function")return Fo.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function Qm(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),a=Number(r&o),c=n?4:0,u=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+u,a,n)}var Rn=class extends kn{constructor(t,r,n,i){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Vo(this.buffer)}update(t){_n(this);let{view:r,buffer:n,blockLen:i}=this;t=vr(t);let o=t.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=Vo(t);for(;i<=o-s;s+=i)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){_n(this),El(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>i-s&&(this.process(n,0),s=0);for(let l=s;l<i;l++)r[l]=0;Qm(n,i-8,BigInt(this.length*8),o),this.process(n,0);let a=Vo(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],o)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:a}=this;return t.length=i,t.pos=a,t.finished=o,t.destroyed=s,i%r&&t.buffer.set(n),t}};var zo=BigInt(4294967295),Dc=BigInt(32);function Al(e,t=!1){return t?{h:Number(e&zo),l:Number(e>>Dc&zo)}:{h:Number(e>>Dc&zo)|0,l:Number(e&zo)|0}}function jm(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let i=0;i<e.length;i++){let{h:o,l:s}=Al(e[i],t);[r[i],n[i]]=[o,s]}return[r,n]}var Jm=(e,t)=>BigInt(e>>>0)<<Dc|BigInt(t>>>0),tg=(e,t,r)=>e>>>r,eg=(e,t,r)=>e<<32-r|t>>>r,rg=(e,t,r)=>e>>>r|t<<32-r,ng=(e,t,r)=>e<<32-r|t>>>r,ig=(e,t,r)=>e<<64-r|t>>>r-32,og=(e,t,r)=>e>>>r-32|t<<64-r,sg=(e,t)=>t,ag=(e,t)=>e,cg=(e,t,r)=>e<<r|t>>>32-r,ug=(e,t,r)=>t<<r|e>>>32-r,fg=(e,t,r)=>t<<r-32|e>>>64-r,lg=(e,t,r)=>e<<r-32|t>>>64-r;function hg(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}var dg=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),pg=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,yg=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),mg=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,gg=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),xg=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0;var bg={fromBig:Al,split:jm,toBig:Jm,shrSH:tg,shrSL:eg,rotrSH:rg,rotrSL:ng,rotrBH:ig,rotrBL:og,rotr32H:sg,rotr32L:ag,rotlSH:cg,rotlSL:ug,rotlBH:fg,rotlBL:lg,add:hg,add3L:dg,add3H:pg,add4L:yg,add4H:mg,add5H:xg,add5L:gg},rt=bg;var[wg,vg]=rt.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(e=>BigInt(e))),Er=new Uint32Array(80),Sr=new Uint32Array(80),Cc=class extends Rn{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:r,Bh:n,Bl:i,Ch:o,Cl:s,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:d,Gh:y,Gl:h,Hh:p,Hl:m}=this;return[t,r,n,i,o,s,a,c,u,f,l,d,y,h,p,m]}set(t,r,n,i,o,s,a,c,u,f,l,d,y,h,p,m){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=o|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=y|0,this.Gl=h|0,this.Hh=p|0,this.Hl=m|0}process(t,r){for(let x=0;x<16;x++,r+=4)Er[x]=t.getUint32(r),Sr[x]=t.getUint32(r+=4);for(let x=16;x<80;x++){let A=Er[x-15]|0,v=Sr[x-15]|0,E=rt.rotrSH(A,v,1)^rt.rotrSH(A,v,8)^rt.shrSH(A,v,7),C=rt.rotrSL(A,v,1)^rt.rotrSL(A,v,8)^rt.shrSL(A,v,7),B=Er[x-2]|0,O=Sr[x-2]|0,K=rt.rotrSH(B,O,19)^rt.rotrBH(B,O,61)^rt.shrSH(B,O,6),U=rt.rotrSL(B,O,19)^rt.rotrBL(B,O,61)^rt.shrSL(B,O,6),F=rt.add4L(C,U,Sr[x-7],Sr[x-16]),G=rt.add4H(F,E,K,Er[x-7],Er[x-16]);Er[x]=G|0,Sr[x]=F|0}let{Ah:n,Al:i,Bh:o,Bl:s,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:y,Fl:h,Gh:p,Gl:m,Hh:g,Hl:b}=this;for(let x=0;x<80;x++){let A=rt.rotrSH(l,d,14)^rt.rotrSH(l,d,18)^rt.rotrBH(l,d,41),v=rt.rotrSL(l,d,14)^rt.rotrSL(l,d,18)^rt.rotrBL(l,d,41),E=l&y^~l&p,C=d&h^~d&m,B=rt.add5L(b,v,C,vg[x],Sr[x]),O=rt.add5H(B,g,A,E,wg[x],Er[x]),K=B|0,U=rt.rotrSH(n,i,28)^rt.rotrBH(n,i,34)^rt.rotrBH(n,i,39),F=rt.rotrSL(n,i,28)^rt.rotrBL(n,i,34)^rt.rotrBL(n,i,39),G=n&o^n&a^o&a,Q=i&s^i&c^s&c;g=p|0,b=m|0,p=y|0,m=h|0,y=l|0,h=d|0,{h:l,l:d}=rt.add(u|0,f|0,O|0,K|0),u=a|0,f=c|0,a=o|0,c=s|0,o=n|0,s=i|0;let I=rt.add3L(K,F,Q);n=rt.add3H(I,O,U,G),i=I|0}({h:n,l:i}=rt.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:o,l:s}=rt.add(this.Bh|0,this.Bl|0,o|0,s|0),{h:a,l:c}=rt.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=rt.add(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=rt.add(this.Eh|0,this.El|0,l|0,d|0),{h:y,l:h}=rt.add(this.Fh|0,this.Fl|0,y|0,h|0),{h:p,l:m}=rt.add(this.Gh|0,this.Gl|0,p|0,m|0),{h:g,l:b}=rt.add(this.Hh|0,this.Hl|0,g|0,b|0),this.set(n,i,o,s,a,c,u,f,l,d,y,h,p,m,g,b)}roundClean(){Er.fill(0),Sr.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 Bc=qo(()=>new Cc);var $o={};ft($o,{bitGet:()=>Ig,bitLen:()=>Bg,bitMask:()=>mi,bitSet:()=>Tg,bytesToHex:()=>Je,bytesToNumberBE:()=>tr,bytesToNumberLE:()=>Ce,concatBytes:()=>rr,createHmacDrbg:()=>_c,ensureBytes:()=>Et,equalBytes:()=>Dg,hexToBytes:()=>Xr,hexToNumber:()=>Tc,numberToBytesBE:()=>Ar,numberToBytesLE:()=>er,numberToHexUnpadded:()=>Bl,numberToVarBytesBE:()=>Ag,utf8ToBytes:()=>Cg,validateObject:()=>pe});var Cl=BigInt(0),Go=BigInt(1),Eg=BigInt(2),Wo=e=>e instanceof Uint8Array,Sg=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Je(e){if(!Wo(e))throw new Error("Uint8Array expected");let t="";for(let r=0;r<e.length;r++)t+=Sg[e[r]];return t}function Bl(e){let t=e.toString(16);return t.length&1?`0${t}`:t}function Tc(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return BigInt(e===""?"0":`0x${e}`)}function Xr(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);let t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(t/2);for(let n=0;n<r.length;n++){let i=n*2,o=e.slice(i,i+2),s=Number.parseInt(o,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");r[n]=s}return r}function tr(e){return Tc(Je(e))}function Ce(e){if(!Wo(e))throw new Error("Uint8Array expected");return Tc(Je(Uint8Array.from(e).reverse()))}function Ar(e,t){return Xr(e.toString(16).padStart(t*2,"0"))}function er(e,t){return Ar(e,t).reverse()}function Ag(e){return Xr(Bl(e))}function Et(e,t,r){let n;if(typeof t=="string")try{n=Xr(t)}catch(o){throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${o}`)}else if(Wo(t))n=Uint8Array.from(t);else throw new Error(`${e} must be hex string or Uint8Array`);let i=n.length;if(typeof r=="number"&&i!==r)throw new Error(`${e} expected ${r} bytes, got ${i}`);return n}function rr(...e){let t=new Uint8Array(e.reduce((n,i)=>n+i.length,0)),r=0;return e.forEach(n=>{if(!Wo(n))throw new Error("Uint8Array expected");t.set(n,r),r+=n.length}),t}function Dg(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function Cg(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function Bg(e){let t;for(t=0;e>Cl;e>>=Go,t+=1);return t}function Ig(e,t){return e>>BigInt(t)&Go}var Tg=(e,t,r)=>e|(r?Go:Cl)<<BigInt(t),mi=e=>(Eg<<BigInt(e-1))-Go,Ic=e=>new Uint8Array(e),Dl=e=>Uint8Array.from(e);function _c(e,t,r){if(typeof e!="number"||e<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 r!="function")throw new Error("hmacFn must be a function");let n=Ic(e),i=Ic(e),o=0,s=()=>{n.fill(1),i.fill(0),o=0},a=(...l)=>r(i,n,...l),c=(l=Ic())=>{i=a(Dl([0]),l),n=a(),l.length!==0&&(i=a(Dl([1]),l),n=a())},u=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let l=0,d=[];for(;l<t;){n=a();let y=n.slice();d.push(y),l+=n.length}return rr(...d)};return(l,d)=>{s(),c(l);let y;for(;!(y=d(u()));)c();return s(),y}}var _g={bigint:e=>typeof e=="bigint",function:e=>typeof e=="function",boolean:e=>typeof e=="boolean",string:e=>typeof e=="string",stringOrUint8Array:e=>typeof e=="string"||e instanceof Uint8Array,isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e=="function"&&Number.isSafeInteger(e.outputLen)};function pe(e,t,r={}){let n=(i,o,s)=>{let a=_g[o];if(typeof a!="function")throw new Error(`Invalid validator "${o}", expected function`);let c=e[i];if(!(s&&c===void 0)&&!a(c,e))throw new Error(`Invalid param ${String(i)}=${c} (${typeof c}), expected ${o}`)};for(let[i,o]of Object.entries(t))n(i,o,!1);for(let[i,o]of Object.entries(r))n(i,o,!0);return e}var qt=BigInt(0),It=BigInt(1),Zr=BigInt(2),kg=BigInt(3),kc=BigInt(4),Il=BigInt(5),Tl=BigInt(8),Rg=BigInt(9),Lg=BigInt(16);function ht(e,t){let r=e%t;return r>=qt?r:t+r}function Rc(e,t,r){if(r<=qt||t<qt)throw new Error("Expected power/modulo > 0");if(r===It)return qt;let n=It;for(;t>qt;)t&It&&(n=n*e%r),e=e*e%r,t>>=It;return n}function St(e,t,r){let n=e;for(;t-- >qt;)n*=n,n%=r;return n}function Yo(e,t){if(e===qt||t<=qt)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=ht(e,t),n=t,i=qt,o=It,s=It,a=qt;for(;r!==qt;){let u=n/r,f=n%r,l=i-s*u,d=o-a*u;n=r,r=f,i=s,o=a,s=l,a=d}if(n!==It)throw new Error("invert: does not exist");return ht(i,t)}function Ng(e){let t=(e-It)/Zr,r,n,i;for(r=e-It,n=0;r%Zr===qt;r/=Zr,n++);for(i=Zr;i<e&&Rc(i,t,e)!==e-It;i++);if(n===1){let s=(e+It)/kc;return function(c,u){let f=c.pow(u,s);if(!c.eql(c.sqr(f),u))throw new Error("Cannot find square root");return f}}let o=(r+It)/Zr;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,f=a.pow(a.mul(a.ONE,i),r),l=a.pow(c,o),d=a.pow(c,r);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let y=1;for(let p=a.sqr(d);y<u&&!a.eql(p,a.ONE);y++)p=a.sqr(p);let h=a.pow(f,It<<BigInt(u-y-1));f=a.sqr(h),l=a.mul(l,h),d=a.mul(d,f),u=y}return l}}function Pg(e){if(e%kc===kg){let t=(e+It)/kc;return function(n,i){let o=n.pow(i,t);if(!n.eql(n.sqr(o),i))throw new Error("Cannot find square root");return o}}if(e%Tl===Il){let t=(e-Il)/Tl;return function(n,i){let o=n.mul(i,Zr),s=n.pow(o,t),a=n.mul(i,s),c=n.mul(n.mul(a,Zr),s),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),i))throw new Error("Cannot find square root");return u}}return e%Lg,Ng(e)}var _l=(e,t)=>(ht(e,t)&It)===It,Ug=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Lc(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Ug.reduce((n,i)=>(n[i]="function",n),t);return pe(e,r)}function Og(e,t,r){if(r<qt)throw new Error("Expected power > 0");if(r===qt)return e.ONE;if(r===It)return t;let n=e.ONE,i=t;for(;r>qt;)r&It&&(n=e.mul(n,i)),i=e.sqr(i),r>>=It;return n}function Kg(e,t){let r=new Array(t.length),n=t.reduce((o,s,a)=>e.is0(s)?o:(r[a]=o,e.mul(o,s)),e.ONE),i=e.inv(n);return t.reduceRight((o,s,a)=>e.is0(s)?o:(r[a]=e.mul(o,r[a]),e.mul(o,s)),i),r}function Nc(e,t){let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Xo(e,t,r=!1,n={}){if(e<=qt)throw new Error(`Expected Field ORDER > 0, got ${e}`);let{nBitLength:i,nByteLength:o}=Nc(e,t);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=Pg(e),a=Object.freeze({ORDER:e,BITS:i,BYTES:o,MASK:mi(i),ZERO:qt,ONE:It,create:c=>ht(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return qt<=c&&c<e},is0:c=>c===qt,isOdd:c=>(c&It)===It,neg:c=>ht(-c,e),eql:(c,u)=>c===u,sqr:c=>ht(c*c,e),add:(c,u)=>ht(c+u,e),sub:(c,u)=>ht(c-u,e),mul:(c,u)=>ht(c*u,e),pow:(c,u)=>Og(a,c,u),div:(c,u)=>ht(c*Yo(u,e),e),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Yo(c,e),sqrt:n.sqrt||(c=>s(a,c)),invertBatch:c=>Kg(a,c),cmov:(c,u,f)=>f?u:c,toBytes:c=>r?er(c,o):Ar(c,o),fromBytes:c=>{if(c.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${c.length}`);return r?Ce(c):tr(c)}});return Object.freeze(a)}function kl(e,t){if(!e.isOdd)throw new Error("Field doesn't have isOdd");let r=e.sqrt(t);return e.isOdd(r)?e.neg(r):r}function Rl(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function Pc(e){let t=Rl(e);return t+Math.ceil(t/2)}function Ll(e,t,r=!1){let n=e.length,i=Rl(t),o=Pc(t);if(n<16||n<o||n>1024)throw new Error(`expected ${o}-1024 bytes of input, got ${n}`);let s=r?tr(e):Ce(e),a=ht(s,t-It)+It;return r?er(a,i):Ar(a,i)}var Fg=BigInt(0),Uc=BigInt(1);function Zo(e,t){let r=(i,o)=>{let s=o.negate();return i?s:o},n=i=>{let o=Math.ceil(t/i)+1,s=2**(i-1);return{windows:o,windowSize:s}};return{constTimeNegate:r,unsafeLadder(i,o){let s=e.ZERO,a=i;for(;o>Fg;)o&Uc&&(s=s.add(a)),a=a.double(),o>>=Uc;return s},precomputeWindow(i,o){let{windows:s,windowSize:a}=n(o),c=[],u=i,f=u;for(let l=0;l<s;l++){f=u,c.push(f);for(let d=1;d<a;d++)f=f.add(u),c.push(f);u=f.double()}return c},wNAF(i,o,s){let{windows:a,windowSize:c}=n(i),u=e.ZERO,f=e.BASE,l=BigInt(2**i-1),d=2**i,y=BigInt(i);for(let h=0;h<a;h++){let p=h*c,m=Number(s&l);s>>=y,m>c&&(m-=d,s+=Uc);let g=p,b=p+Math.abs(m)-1,x=h%2!==0,A=m<0;m===0?f=f.add(r(x,o[g])):u=u.add(r(A,o[b]))}return{p:u,f}},wNAFCached(i,o,s,a){let c=i._WINDOW_SIZE||1,u=o.get(i);return u||(u=this.precomputeWindow(i,c),c!==1&&o.set(i,a(u))),this.wNAF(c,u,s)}}}function gi(e){return Lc(e.Fp),pe(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Nc(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}var Be=BigInt(0),le=BigInt(1),Qo=BigInt(2),Vg=BigInt(8),Hg={zip215:!0};function qg(e){let t=gi(e);return pe(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function jo(e){let t=qg(e),{Fp:r,n,prehash:i,hash:o,randomBytes:s,nByteLength:a,h:c}=t,u=Qo<<BigInt(a*8)-le,f=r.create,l=t.uvRatio||((k,S)=>{try{return{isValid:!0,value:r.sqrt(k*r.inv(S))}}catch{return{isValid:!1,value:Be}}}),d=t.adjustScalarBytes||(k=>k),y=t.domain||((k,S,P)=>{if(S.length||P)throw new Error("Contexts/pre-hash are not supported");return k}),h=k=>typeof k=="bigint"&&Be<k,p=(k,S)=>h(k)&&h(S)&&k<S,m=k=>k===Be||p(k,u);function g(k,S){if(p(k,S))return k;throw new Error(`Expected valid scalar < ${S}, got ${typeof k} ${k}`)}function b(k){return k===Be?k:g(k,n)}let x=new Map;function A(k){if(!(k instanceof v))throw new Error("ExtendedPoint expected")}class v{constructor(S,P,M,H){if(this.ex=S,this.ey=P,this.ez=M,this.et=H,!m(S))throw new Error("x required");if(!m(P))throw new Error("y required");if(!m(M))throw new Error("z required");if(!m(H))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(S){if(S instanceof v)throw new Error("extended point not allowed");let{x:P,y:M}=S||{};if(!m(P)||!m(M))throw new Error("invalid affine point");return new v(P,M,le,f(P*M))}static normalizeZ(S){let P=r.invertBatch(S.map(M=>M.ez));return S.map((M,H)=>M.toAffine(P[H])).map(v.fromAffine)}_setWindowSize(S){this._WINDOW_SIZE=S,x.delete(this)}assertValidity(){let{a:S,d:P}=t;if(this.is0())throw new Error("bad point: ZERO");let{ex:M,ey:H,ez:Z,et:j}=this,it=f(M*M),J=f(H*H),et=f(Z*Z),bt=f(et*et),gt=f(it*S),$t=f(et*f(gt+J)),Yt=f(bt+f(P*f(it*J)));if($t!==Yt)throw new Error("bad point: equation left != right (1)");let Ft=f(M*H),jt=f(Z*j);if(Ft!==jt)throw new Error("bad point: equation left != right (2)")}equals(S){A(S);let{ex:P,ey:M,ez:H}=this,{ex:Z,ey:j,ez:it}=S,J=f(P*it),et=f(Z*H),bt=f(M*it),gt=f(j*H);return J===et&&bt===gt}is0(){return this.equals(v.ZERO)}negate(){return new v(f(-this.ex),this.ey,this.ez,f(-this.et))}double(){let{a:S}=t,{ex:P,ey:M,ez:H}=this,Z=f(P*P),j=f(M*M),it=f(Qo*f(H*H)),J=f(S*Z),et=P+M,bt=f(f(et*et)-Z-j),gt=J+j,$t=gt-it,Yt=J-j,Ft=f(bt*$t),jt=f(gt*Yt),We=f(bt*Yt),Lr=f($t*gt);return new v(Ft,jt,Lr,We)}add(S){A(S);let{a:P,d:M}=t,{ex:H,ey:Z,ez:j,et:it}=this,{ex:J,ey:et,ez:bt,et:gt}=S;if(P===BigInt(-1)){let uu=f((Z-H)*(et+J)),fu=f((Z+H)*(et-J)),Vs=f(fu-uu);if(Vs===Be)return this.double();let lu=f(j*Qo*gt),hu=f(it*Qo*bt),du=hu+lu,pu=fu+uu,yu=hu-lu,q1=f(du*Vs),z1=f(pu*yu),G1=f(du*yu),W1=f(Vs*pu);return new v(q1,z1,W1,G1)}let $t=f(H*J),Yt=f(Z*et),Ft=f(it*M*gt),jt=f(j*bt),We=f((H+Z)*(J+et)-$t-Yt),Lr=jt-Ft,ti=jt+Ft,cu=f(Yt-P*$t),M1=f(We*Lr),F1=f(ti*cu),V1=f(We*cu),H1=f(Lr*ti);return new v(M1,F1,H1,V1)}subtract(S){return this.add(S.negate())}wNAF(S){return B.wNAFCached(this,x,S,v.normalizeZ)}multiply(S){let{p:P,f:M}=this.wNAF(g(S,n));return v.normalizeZ([P,M])[0]}multiplyUnsafe(S){let P=b(S);return P===Be?C:this.equals(C)||P===le?this:this.equals(E)?this.wNAF(P).p:B.unsafeLadder(this,P)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return B.unsafeLadder(this,n).is0()}toAffine(S){let{ex:P,ey:M,ez:H}=this,Z=this.is0();S==null&&(S=Z?Vg:r.inv(H));let j=f(P*S),it=f(M*S),J=f(H*S);if(Z)return{x:Be,y:le};if(J!==le)throw new Error("invZ was invalid");return{x:j,y:it}}clearCofactor(){let{h:S}=t;return S===le?this:this.multiplyUnsafe(S)}static fromHex(S,P=!1){let{d:M,a:H}=t,Z=r.BYTES;S=Et("pointHex",S,Z);let j=S.slice(),it=S[Z-1];j[Z-1]=it&-129;let J=Ce(j);J===Be||(P?g(J,u):g(J,r.ORDER));let et=f(J*J),bt=f(et-le),gt=f(M*et-H),{isValid:$t,value:Yt}=l(bt,gt);if(!$t)throw new Error("Point.fromHex: invalid y coordinate");let Ft=(Yt&le)===le,jt=(it&128)!==0;if(!P&&Yt===Be&&jt)throw new Error("Point.fromHex: x=0 and x_0=1");return jt!==Ft&&(Yt=f(-Yt)),v.fromAffine({x:Yt,y:J})}static fromPrivateKey(S){return U(S).point}toRawBytes(){let{x:S,y:P}=this.toAffine(),M=er(P,r.BYTES);return M[M.length-1]|=S&le?128:0,M}toHex(){return Je(this.toRawBytes())}}v.BASE=new v(t.Gx,t.Gy,le,f(t.Gx*t.Gy)),v.ZERO=new v(Be,le,le,Be);let{BASE:E,ZERO:C}=v,B=Zo(v,a*8);function O(k){return ht(k,n)}function K(k){return O(Ce(k))}function U(k){let S=a;k=Et("private key",k,S);let P=Et("hashed private key",o(k),2*S),M=d(P.slice(0,S)),H=P.slice(S,2*S),Z=K(M),j=E.multiply(Z),it=j.toRawBytes();return{head:M,prefix:H,scalar:Z,point:j,pointBytes:it}}function F(k){return U(k).pointBytes}function G(k=new Uint8Array,...S){let P=rr(...S);return K(o(y(P,Et("context",k),!!i)))}function Q(k,S,P={}){k=Et("message",k),i&&(k=i(k));let{prefix:M,scalar:H,pointBytes:Z}=U(S),j=G(P.context,M,k),it=E.multiply(j).toRawBytes(),J=G(P.context,it,Z,k),et=O(j+J*H);b(et);let bt=rr(it,er(et,r.BYTES));return Et("result",bt,a*2)}let I=Hg;function R(k,S,P,M=I){let{context:H,zip215:Z}=M,j=r.BYTES;k=Et("signature",k,2*j),S=Et("message",S),i&&(S=i(S));let it=Ce(k.slice(j,2*j)),J,et,bt;try{J=v.fromHex(P,Z),et=v.fromHex(k.slice(0,j),Z),bt=E.multiplyUnsafe(it)}catch{return!1}if(!Z&&J.isSmallOrder())return!1;let gt=G(H,et.toRawBytes(),J.toRawBytes(),S);return et.add(J.multiplyUnsafe(gt)).subtract(bt).clearCofactor().equals(v.ZERO)}return E._setWindowSize(8),{CURVE:t,getPublicKey:F,sign:Q,verify:R,ExtendedPoint:v,utils:{getExtendedPublicKey:U,randomPrivateKey:()=>s(r.BYTES),precompute(k=8,S=v.BASE){return S._setWindowSize(k),S.multiply(BigInt(3)),S}}}}var xi=BigInt(0),Oc=BigInt(1);function zg(e){return pe(e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...e})}function Nl(e){let t=zg(e),{P:r}=t,n=x=>ht(x,r),i=t.montgomeryBits,o=Math.ceil(i/8),s=t.nByteLength,a=t.adjustScalarBytes||(x=>x),c=t.powPminus2||(x=>Rc(x,r-BigInt(2),r));function u(x,A,v){let E=n(x*(A-v));return A=n(A-E),v=n(v+E),[A,v]}function f(x){if(typeof x=="bigint"&&xi<=x&&x<r)return x;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let l=(t.a-BigInt(2))/BigInt(4);function d(x,A){let v=f(x),E=f(A),C=v,B=Oc,O=xi,K=v,U=Oc,F=xi,G;for(let I=BigInt(i-1);I>=xi;I--){let R=E>>I&Oc;F^=R,G=u(F,B,K),B=G[0],K=G[1],G=u(F,O,U),O=G[0],U=G[1],F=R;let _=B+O,k=n(_*_),S=B-O,P=n(S*S),M=k-P,H=K+U,Z=K-U,j=n(Z*_),it=n(H*S),J=j+it,et=j-it;K=n(J*J),U=n(C*n(et*et)),B=n(k*P),O=n(M*(k+n(l*M)))}G=u(F,B,K),B=G[0],K=G[1],G=u(F,O,U),O=G[0],U=G[1];let Q=c(O);return n(B*Q)}function y(x){return er(n(x),o)}function h(x){let A=Et("u coordinate",x,o);return s===o&&(A[s-1]&=127),Ce(A)}function p(x){let A=Et("scalar",x);if(A.length!==o&&A.length!==s)throw new Error(`Expected ${o} or ${s} bytes, got ${A.length}`);return Ce(a(A))}function m(x,A){let v=h(A),E=p(x),C=d(v,E);if(C===xi)throw new Error("Invalid private or public key received");return y(C)}let g=y(t.Gu);function b(x){return m(x,g)}return{scalarMult:m,scalarMultBase:b,getSharedSecret:(x,A)=>m(x,A),getPublicKey:x=>b(x),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:g}}var bi=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Pl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),GD=BigInt(0),Gg=BigInt(1),Kc=BigInt(2),Wg=BigInt(5),Ul=BigInt(10),$g=BigInt(20),Yg=BigInt(40),Ol=BigInt(80);function Kl(e){let t=bi,n=e*e%t*e%t,i=St(n,Kc,t)*n%t,o=St(i,Gg,t)*e%t,s=St(o,Wg,t)*o%t,a=St(s,Ul,t)*s%t,c=St(a,$g,t)*a%t,u=St(c,Yg,t)*c%t,f=St(u,Ol,t)*u%t,l=St(f,Ol,t)*u%t,d=St(l,Ul,t)*s%t;return{pow_p_5_8:St(d,Kc,t)*e%t,b2:n}}function Ml(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function Xg(e,t){let r=bi,n=ht(t*t*t,r),i=ht(n*n*t,r),o=Kl(e*i).pow_p_5_8,s=ht(e*n*o,r),a=ht(t*s*s,r),c=s,u=ht(s*Pl,r),f=a===e,l=a===ht(-e,r),d=a===ht(-e*Pl,r);return f&&(s=c),(l||d)&&(s=u),_l(s,r)&&(s=ht(-s,r)),{isValid:f||l,value:s}}var nr=Xo(bi,void 0,!0),Mc={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:nr,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Bc,randomBytes:Yr,adjustScalarBytes:Ml,uvRatio:Xg},Ln=jo(Mc);function Fl(e,t,r){if(t.length>255)throw new Error("Context is too big");return Ho(Ac("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,t.length]),t,e)}var WD=jo({...Mc,domain:Fl}),$D=jo({...Mc,domain:Fl,prehash:Bc}),wi=Nl({P:bi,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:e=>{let t=bi,{pow_p_5_8:r,b2:n}=Kl(e);return ht(St(r,BigInt(3),t)*n,t)},adjustScalarBytes:Ml,randomBytes:Yr});var Zg=(nr.ORDER+BigInt(3))/BigInt(8),YD=nr.pow(Kc,Zg),XD=nr.sqrt(nr.neg(nr.ONE)),ZD=(nr.ORDER-BigInt(5))/BigInt(8),QD=BigInt(486662);var jD=kl(nr,nr.neg(BigInt(486664)));var JD=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),tC=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),eC=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),rC=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var nC=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Jo=class extends kn{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,yi(t);let n=vr(r);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 i=this.blockLen,o=new Uint8Array(i);o.set(n.length>i?t.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),o.fill(0)}update(t){return _n(this),this.iHash.update(t),this}digestInto(t){_n(this),Sc(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:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return t=t,t.finished=i,t.destroyed=o,t.blockLen=s,t.outputLen=a,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Nn=(e,t,r)=>new Jo(e,t).update(r).digest();Nn.create=(e,t)=>new Jo(e,t);function Hl(e,t,r){return yi(e),r===void 0&&(r=new Uint8Array(e.outputLen)),Nn(e,vr(r),vr(t))}var Fc=new Uint8Array([0]),Vl=new Uint8Array;function ql(e,t,r,n=32){if(yi(e),Mo(n),n>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");let i=Math.ceil(n/e.outputLen);r===void 0&&(r=Vl);let o=new Uint8Array(i*e.outputLen),s=Nn.create(e,t),a=s._cloneInto(),c=new Uint8Array(s.outputLen);for(let u=0;u<i;u++)Fc[0]=u+1,a.update(u===0?Vl:c).update(r).update(Fc).digestInto(c),o.set(c,e.outputLen*u),s._cloneInto(a);return s.destroy(),a.destroy(),c.fill(0),Fc.fill(0),o.slice(0,n)}var Qg=(e,t,r)=>e&t^~e&r,jg=(e,t,r)=>e&t^e&r^t&r,Jg=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]),Dr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Cr=new Uint32Array(64),Vc=class extends Rn{constructor(){super(64,32,8,!1),this.A=Dr[0]|0,this.B=Dr[1]|0,this.C=Dr[2]|0,this.D=Dr[3]|0,this.E=Dr[4]|0,this.F=Dr[5]|0,this.G=Dr[6]|0,this.H=Dr[7]|0}get(){let{A:t,B:r,C:n,D:i,E:o,F:s,G:a,H:c}=this;return[t,r,n,i,o,s,a,c]}set(t,r,n,i,o,s,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,r){for(let l=0;l<16;l++,r+=4)Cr[l]=t.getUint32(r,!1);for(let l=16;l<64;l++){let d=Cr[l-15],y=Cr[l-2],h=De(d,7)^De(d,18)^d>>>3,p=De(y,17)^De(y,19)^y>>>10;Cr[l]=p+Cr[l-7]+h+Cr[l-16]|0}let{A:n,B:i,C:o,D:s,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let d=De(a,6)^De(a,11)^De(a,25),y=f+d+Qg(a,c,u)+Jg[l]+Cr[l]|0,p=(De(n,2)^De(n,13)^De(n,22))+jg(n,i,o)|0;f=u,u=c,c=a,a=s+y|0,s=o,o=i,i=n,n=y+p|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,i,o,s,a,c,u,f)}roundClean(){Cr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Pn=qo(()=>new Vc);var Hc={hashSHA256(e){return Pn(e.subarray())},getHKDF(e,t){let r=Hl(Pn,t,e),i=ql(Pn,r,void 0,96),o=i.subarray(0,32),s=i.subarray(32,64),a=i.subarray(64,96);return[o,s,a]},generateX25519KeyPair(){let e=wi.utils.randomPrivateKey();return{publicKey:wi.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed(e){return{publicKey:wi.getPublicKey(e),privateKey:e}},generateX25519SharedKey(e,t){return wi.getSharedSecret(e.subarray(),t.subarray())},chaCha20Poly1305Encrypt(e,t,r,n){return Ec(n,t,r).encrypt(e.subarray())},chaCha20Poly1305Decrypt(e,t,r,n,i){return Ec(n,t,r).decrypt(e.subarray(),i)}};var zl=Hc;var Un=e=>{let t=Vt(2);return new DataView(t.buffer,t.byteOffset,t.byteLength).setUint16(0,e,!1),t};Un.bytes=2;var vi=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");return e instanceof Uint8Array?new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(0,!1):e.getUint16(0)};vi.bytes=2;function Gl(e){return new Bt(e.ne,e.ciphertext)}function Wl(e){return new Bt(e.ne,e.ns,e.ciphertext)}function $l(e){return new Bt(e.ns,e.ciphertext)}function Yl(e){if(e.length<32)throw new Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");return{ne:e.subarray(0,32),ciphertext:e.subarray(32,e.length),ns:ot(0)}}function Xl(e){if(e.length<80)throw new Error("Cannot decode stage 1 MessageBuffer: length less than 80 bytes.");return{ne:e.subarray(0,32),ns:e.subarray(32,80),ciphertext:e.subarray(80,e.length)}}function Zl(e){if(e.length<48)throw new Error("Cannot decode stage 2 MessageBuffer: length less than 48 bytes.");return{ne:ot(0),ns:e.subarray(0,48),ciphertext:e.subarray(48,e.length)}}var jl=16;function Jl(e,t){return async function*(r){for await(let n of r)for(let i=0;i<n.length;i+=65519){let o=i+65519;o>n.length&&(o=n.length);let s;n instanceof Uint8Array?s=e.encrypt(n.subarray(i,o),e.session):s=e.encrypt(n.sublist(i,o),e.session),t?.encryptedPackets.increment(),yield new Bt(Un(s.byteLength),s)}}}function th(e,t){return async function*(r){for await(let n of r)for(let i=0;i<n.length;i+=65535){let o=i+65535;if(o>n.length&&(o=n.length),o-jl<i)throw new Error("Invalid chunk");let s=n.sublist(i,o),a=n.subarray(i,o-jl),{plaintext:c,valid:u}=e.decrypt(s,e.session,a);if(!u)throw t?.decryptErrors.increment(),new Error("Failed to validate decrypted chunk");t?.decryptedPackets.increment(),yield c}}}var Si=class e extends Error{code;constructor(t="Unexpected Peer"){super(t),this.code=e.code}static code="ERR_UNEXPECTED_PEER"},Qr=class e extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=e.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var GI=Jt(Bi(),1),WI=Jt(md(),1);var tv=Jt(xt(),1);var p0={};ft(p0,{Ed25519PrivateKey:()=>nn,Ed25519PublicKey:()=>_i,generateKeyPair:()=>Bw,generateKeyPairFromSeed:()=>Dd,unmarshalEd25519PrivateKey:()=>Dw,unmarshalEd25519PublicKey:()=>Cw});var eB=Jt(Mt(),1),rB=Jt(ps(),1),gd=Jt(xt(),1);function _e(e,t){let r=Uint8Array.from(e.abs().toByteArray());if(r=r[0]===0?r.subarray(1):r,t!=null){if(r.length>t)throw new Error("byte array longer than desired length");r=Ct([new Uint8Array(t-r.length),r])}return at(r,"base64url")}function he(e){let t=xd(e);return new gd.default.jsbn.BigInteger(at(t,"base16"),16)}function xd(e,t){let r=wt(e,"base64urlpad");if(t!=null){if(r.length>t)throw new Error("byte array longer than desired length");r=Ct([new Uint8Array(t-r.length),r])}return r}function ge(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}var Vn=32,ar=64,xs=32;function bd(){let e=Ln.utils.randomPrivateKey(),t=Ln.getPublicKey(e);return{privateKey:Sd(e,t),publicKey:t}}function wd(e){if(e.length!==xs)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let t=e,r=Ln.getPublicKey(t);return{privateKey:Sd(t,r),publicKey:r}}function vd(e,t){let r=e.subarray(0,xs);return Ln.sign(t instanceof Uint8Array?t:t.subarray(),r)}function Ed(e,t,r){return Ln.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}function Sd(e,t){let r=new Uint8Array(ar);for(let n=0;n<xs;n++)r[n]=e[n],r[xs+n]=t[n];return r}var ue={get(e=globalThis){let t=e.crypto;if(t==null||t.subtle==null)throw Object.assign(new Error("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"),{code:"ERR_MISSING_WEB_CRYPTO"});return t}};var l0={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function h0(e){let t=e?.algorithm??"AES-GCM",r=e?.keyLength??16,n=e?.nonceLength??12,i=e?.digest??"SHA-256",o=e?.saltLength??16,s=e?.iterations??32767,a=ue.get();r*=8;async function c(l,d){let y=a.getRandomValues(new Uint8Array(o)),h=a.getRandomValues(new Uint8Array(n)),p={name:t,iv:h};typeof d=="string"&&(d=wt(d));let m;if(d.length===0){m=await a.subtle.importKey("jwk",l0,{name:"AES-GCM"},!0,["encrypt"]);try{let b={name:"PBKDF2",salt:y,iterations:s,hash:{name:i}},x=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(b,x,{name:t,length:r},!0,["encrypt"])}catch{m=await a.subtle.importKey("jwk",l0,{name:"AES-GCM"},!0,["encrypt"])}}else{let b={name:"PBKDF2",salt:y,iterations:s,hash:{name:i}},x=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);m=await a.subtle.deriveKey(b,x,{name:t,length:r},!0,["encrypt"])}let g=await a.subtle.encrypt(p,m,l);return Ct([y,p.iv,new Uint8Array(g)])}async function u(l,d){let y=l.subarray(0,o),h=l.subarray(o,o+n),p=l.subarray(o+n),m={name:t,iv:h};typeof d=="string"&&(d=wt(d));let g;if(d.length===0)try{let x={name:"PBKDF2",salt:y,iterations:s,hash:{name:i}},A=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(x,A,{name:t,length:r},!0,["decrypt"])}catch{g=await a.subtle.importKey("jwk",l0,{name:"AES-GCM"},!0,["decrypt"])}else{let x={name:"PBKDF2",salt:y,iterations:s,hash:{name:i}},A=await a.subtle.importKey("raw",d,{name:"PBKDF2"},!1,["deriveKey"]);g=await a.subtle.deriveKey(x,A,{name:t,length:r},!0,["decrypt"])}let b=await a.subtle.decrypt(m,g,p);return new Uint8Array(b)}return{encrypt:c,decrypt:u}}async function Hn(e,t){let n=await h0().encrypt(e,t);return Zi.encode(n)}var _t;(function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.Secp256k1="Secp256k1"})(_t||(_t={}));var d0;(function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.Secp256k1=2]="Secp256k1"})(d0||(d0={}));(function(e){e.codec=()=>qr(d0)})(_t||(_t={}));var qe;(function(e){let t;e.codec=()=>(t==null&&(t=Ae((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),_t.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.Type=_t.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(s&7);break}}return i})),t),e.encode=r=>Se(r,e.codec()),e.decode=r=>Ee(r,e.codec())})(qe||(qe={}));var ze;(function(e){let t;e.codec=()=>(t==null&&(t=Ae((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),_t.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:i.Type=_t.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(s&7);break}}return i})),t),e.encode=r=>Se(r,e.codec()),e.decode=r=>Ee(r,e.codec())})(ze||(ze={}));var _i=class{_key;constructor(t){this._key=qn(t,Vn)}verify(t,r){return Ed(this._key,r,t)}marshal(){return this._key}get bytes(){return qe.encode({Type:_t.Ed25519,Data:this.marshal()}).subarray()}equals(t){return Kt(this.bytes,t.bytes)}hash(){let t=Xt.digest(this.bytes);return ge(t)?t.then(({bytes:r})=>r):t.bytes}},nn=class{_key;_publicKey;constructor(t,r){this._key=qn(t,ar),this._publicKey=qn(r,Vn)}sign(t){return vd(this._key,t)}get public(){return new _i(this._publicKey)}marshal(){return this._key}get bytes(){return ze.encode({Type:_t.Ed25519,Data:this.marshal()}).subarray()}equals(t){return Kt(this.bytes,t.bytes)}async hash(){let t=Xt.digest(this.bytes),r;return ge(t)?{bytes:r}=await t:r=t.bytes,r}async id(){let t=dr.digest(this.public.bytes);return Nt.encode(t.bytes).substring(1)}async export(t,r="libp2p-key"){if(r==="libp2p-key")return Hn(this.bytes,t);throw new W(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Dw(e){if(e.length>ar){e=qn(e,ar+Vn);let n=e.subarray(0,ar),i=e.subarray(ar,e.length);return new nn(n,i)}e=qn(e,ar);let t=e.subarray(0,ar),r=e.subarray(Vn);return new nn(t,r)}function Cw(e){return e=qn(e,Vn),new _i(e)}async function Bw(){let{privateKey:e,publicKey:t}=bd();return new nn(e,t)}async function Dd(e){let{privateKey:t,publicKey:r}=wd(e);return new nn(t,r)}function qn(e,t){if(e=Uint8Array.from(e??[]),e.length!==t)throw new W(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}var Iw={"P-256":256,"P-384":384,"P-521":521},Tw=Object.keys(Iw),IB=Tw.join(" / ");var b0={};ft(b0,{MAX_KEY_SIZE:()=>Ni,RsaPrivateKey:()=>zn,RsaPublicKey:()=>Li,fromJwk:()=>Fw,generateKeyPair:()=>Vw,unmarshalRsaPrivateKey:()=>Kw,unmarshalRsaPublicKey:()=>Mw});var Ri=Jt(xt(),1);var hI=Jt(_d(),1);function ws(e){if(isNaN(e)||e<=0)throw new W("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Yr(e)}var YB=Jt(gs(),1),g0=Jt(xt(),1);function kd(e,t){return t.map(r=>he(e[r]))}function Rd(e){return g0.default.pki.setRsaPrivateKey(...kd(e,["n","e","d","p","q","dp","dq","qi"]))}function Ld(e){return g0.default.pki.setRsaPublicKey(...kd(e,["n","e"]))}var sn={};ft(sn,{jwkToPkcs1:()=>Lw,jwkToPkix:()=>Pw,pkcs1ToJwk:()=>Rw,pkixToJwk:()=>Nw});var QB=Jt(Bi(),1),jB=Jt(gs(),1);var cr=Jt(xt(),1);function Rw(e){let t=cr.default.asn1.fromDer(at(e,"ascii")),r=cr.default.pki.privateKeyFromAsn1(t);return{kty:"RSA",n:_e(r.n),e:_e(r.e),d:_e(r.d),p:_e(r.p),q:_e(r.q),dp:_e(r.dP),dq:_e(r.dQ),qi:_e(r.qInv),alg:"RS256"}}function Lw(e){if(e.n==null||e.e==null||e.d==null||e.p==null||e.q==null||e.dp==null||e.dq==null||e.qi==null)throw new W("JWK was missing components","ERR_INVALID_PARAMETERS");let t=cr.default.pki.privateKeyToAsn1({n:he(e.n),e:he(e.e),d:he(e.d),p:he(e.p),q:he(e.q),dP:he(e.dp),dQ:he(e.dq),qInv:he(e.qi)});return wt(cr.default.asn1.toDer(t).getBytes(),"ascii")}function Nw(e){let t=cr.default.asn1.fromDer(at(e,"ascii")),r=cr.default.pki.publicKeyFromAsn1(t);return{kty:"RSA",n:_e(r.n),e:_e(r.e)}}function Pw(e){if(e.n==null||e.e==null)throw new W("JWK was missing components","ERR_INVALID_PARAMETERS");let t=cr.default.pki.publicKeyToAsn1({n:he(e.n),e:he(e.e)});return wt(cr.default.asn1.toDer(t).getBytes(),"ascii")}async function Nd(e){let t=await ue.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=await Od(t);return{privateKey:r[0],publicKey:r[1]}}async function x0(e){let r=[await ue.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Uw(e)],n=await Od({privateKey:r[0],publicKey:r[1]});return{privateKey:n[0],publicKey:n[1]}}async function Pd(e,t){let r=await ue.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await ue.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Ud(e,t,r){let n=await ue.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return ue.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())}async function Od(e){if(e.privateKey==null||e.publicKey==null)throw new W("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([ue.get().subtle.exportKey("jwk",e.privateKey),ue.get().subtle.exportKey("jwk",e.publicKey)])}async function Uw(e){return ue.get().subtle.importKey("jwk",{kty:e.kty,n:e.n,e:e.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function Kd(e,t,r,n){let i=t?Ld(e):Rd(e),o=at(r instanceof Uint8Array?r:r.subarray(),"ascii"),s=n(o,i);return wt(s,"ascii")}function Md(e,t){return Kd(e,!0,t,(r,n)=>n.encrypt(r))}function Fd(e,t){return Kd(e,!1,t,(r,n)=>n.decrypt(r))}function vs(e){if(e.kty!=="RSA")throw new W("invalid key type","ERR_INVALID_KEY_TYPE");if(e.n==null)throw new W("invalid key modulus","ERR_INVALID_KEY_MODULUS");return wt(e.n,"base64url").length*8}var Ni=8192,Li=class{_key;constructor(t){this._key=t}verify(t,r){return Ud(this._key,r,t)}marshal(){return sn.jwkToPkix(this._key)}get bytes(){return qe.encode({Type:_t.RSA,Data:this.marshal()}).subarray()}encrypt(t){return Md(this._key,t)}equals(t){return Kt(this.bytes,t.bytes)}hash(){let t=Xt.digest(this.bytes);return ge(t)?t.then(({bytes:r})=>r):t.bytes}},zn=class{_key;_publicKey;constructor(t,r){this._key=t,this._publicKey=r}genSecret(){return ws(16)}sign(t){return Pd(this._key,t)}get public(){if(this._publicKey==null)throw new W("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Li(this._publicKey)}decrypt(t){return Fd(this._key,t)}marshal(){return sn.jwkToPkcs1(this._key)}get bytes(){return ze.encode({Type:_t.RSA,Data:this.marshal()}).subarray()}equals(t){return Kt(this.bytes,t.bytes)}hash(){let t=Xt.digest(this.bytes);return ge(t)?t.then(({bytes:r})=>r):t.bytes}async id(){let t=await this.public.hash();return at(t,"base58btc")}async export(t,r="pkcs-8"){if(r==="pkcs-8"){let n=new Ri.default.util.ByteBuffer(this.marshal()),i=Ri.default.asn1.fromDer(n),o=Ri.default.pki.privateKeyFromAsn1(i),s={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return Ri.default.pki.encryptRsaPrivateKey(o,t,s)}else{if(r==="libp2p-key")return Hn(this.bytes,t);throw new W(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}};async function Kw(e){let t=sn.pkcs1ToJwk(e);if(vs(t)>Ni)throw new W("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let r=await x0(t);return new zn(r.privateKey,r.publicKey)}function Mw(e){let t=sn.pkixToJwk(e);if(vs(t)>Ni)throw new W("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Li(t)}async function Fw(e){if(vs(e)>Ni)throw new W("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await x0(e);return new zn(t.privateKey,t.publicKey)}async function Vw(e){if(e>Ni)throw new W("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await Nd(e);return new zn(t.privateKey,t.publicKey)}var S0={};ft(S0,{Secp256k1PrivateKey:()=>Ui,Secp256k1PublicKey:()=>Pi,generateKeyPair:()=>Jw,unmarshalSecp256k1PrivateKey:()=>Qw,unmarshalSecp256k1PublicKey:()=>jw});function Hw(e){let t=gi(e);pe(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:r,Fp:n,a:i}=t;if(r){if(!n.eql(i,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:qw,hexToBytes:zw}=$o,an={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(e){let{Err:t}=an;if(e.length<2||e[0]!==2)throw new t("Invalid signature integer tag");let r=e[1],n=e.subarray(2,r+2);if(!r||n.length!==r)throw new t("Invalid signature integer: wrong length");if(n[0]&128)throw new t("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return{d:qw(n),l:e.subarray(r+2)}},toSig(e){let{Err:t}=an,r=typeof e=="string"?zw(e):e;if(!(r instanceof Uint8Array))throw new Error("ui8a expected");let n=r.length;if(n<2||r[0]!=48)throw new t("Invalid signature tag");if(r[1]!==n-2)throw new t("Invalid signature: incorrect length");let{d:i,l:o}=an._parseInt(r.subarray(2)),{d:s,l:a}=an._parseInt(o);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:i,s}},hexFromSig(e){let t=u=>Number.parseInt(u[0],16)&8?"00"+u:u,r=u=>{let f=u.toString(16);return f.length&1?`0${f}`:f},n=t(r(e.s)),i=t(r(e.r)),o=n.length/2,s=i.length/2,a=r(o),c=r(s);return`30${r(s+o+4)}02${c}${i}02${a}${n}`}},ur=BigInt(0),xe=BigInt(1),bI=BigInt(2),Vd=BigInt(3),wI=BigInt(4);function Gw(e){let t=Hw(e),{Fp:r}=t,n=t.toBytes||((h,p,m)=>{let g=p.toAffine();return rr(Uint8Array.from([4]),r.toBytes(g.x),r.toBytes(g.y))}),i=t.fromBytes||(h=>{let p=h.subarray(1),m=r.fromBytes(p.subarray(0,r.BYTES)),g=r.fromBytes(p.subarray(r.BYTES,2*r.BYTES));return{x:m,y:g}});function o(h){let{a:p,b:m}=t,g=r.sqr(h),b=r.mul(g,h);return r.add(r.add(b,r.mul(h,p)),m)}if(!r.eql(r.sqr(t.Gy),o(t.Gx)))throw new Error("bad generator point: equation left != right");function s(h){return typeof h=="bigint"&&ur<h&&h<t.n}function a(h){if(!s(h))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(h){let{allowedPrivateKeyLengths:p,nByteLength:m,wrapPrivateKey:g,n:b}=t;if(p&&typeof h!="bigint"){if(h instanceof Uint8Array&&(h=Je(h)),typeof h!="string"||!p.includes(h.length))throw new Error("Invalid key");h=h.padStart(m*2,"0")}let x;try{x=typeof h=="bigint"?h:tr(Et("private key",h,m))}catch{throw new Error(`private key must be ${m} bytes, hex or bigint, not ${typeof h}`)}return g&&(x=ht(x,b)),a(x),x}let u=new Map;function f(h){if(!(h instanceof l))throw new Error("ProjectivePoint expected")}class l{constructor(p,m,g){if(this.px=p,this.py=m,this.pz=g,p==null||!r.isValid(p))throw new Error("x required");if(m==null||!r.isValid(m))throw new Error("y required");if(g==null||!r.isValid(g))throw new Error("z required")}static fromAffine(p){let{x:m,y:g}=p||{};if(!p||!r.isValid(m)||!r.isValid(g))throw new Error("invalid affine point");if(p instanceof l)throw new Error("projective point not allowed");let b=x=>r.eql(x,r.ZERO);return b(m)&&b(g)?l.ZERO:new l(m,g,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(p){let m=r.invertBatch(p.map(g=>g.pz));return p.map((g,b)=>g.toAffine(m[b])).map(l.fromAffine)}static fromHex(p){let m=l.fromAffine(i(Et("pointHex",p)));return m.assertValidity(),m}static fromPrivateKey(p){return l.BASE.multiply(c(p))}_setWindowSize(p){this._WINDOW_SIZE=p,u.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!r.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:p,y:m}=this.toAffine();if(!r.isValid(p)||!r.isValid(m))throw new Error("bad point: x or y not FE");let g=r.sqr(m),b=o(p);if(!r.eql(g,b))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:p}=this.toAffine();if(r.isOdd)return!r.isOdd(p);throw new Error("Field doesn't support isOdd")}equals(p){f(p);let{px:m,py:g,pz:b}=this,{px:x,py:A,pz:v}=p,E=r.eql(r.mul(m,v),r.mul(x,b)),C=r.eql(r.mul(g,v),r.mul(A,b));return E&&C}negate(){return new l(this.px,r.neg(this.py),this.pz)}double(){let{a:p,b:m}=t,g=r.mul(m,Vd),{px:b,py:x,pz:A}=this,v=r.ZERO,E=r.ZERO,C=r.ZERO,B=r.mul(b,b),O=r.mul(x,x),K=r.mul(A,A),U=r.mul(b,x);return U=r.add(U,U),C=r.mul(b,A),C=r.add(C,C),v=r.mul(p,C),E=r.mul(g,K),E=r.add(v,E),v=r.sub(O,E),E=r.add(O,E),E=r.mul(v,E),v=r.mul(U,v),C=r.mul(g,C),K=r.mul(p,K),U=r.sub(B,K),U=r.mul(p,U),U=r.add(U,C),C=r.add(B,B),B=r.add(C,B),B=r.add(B,K),B=r.mul(B,U),E=r.add(E,B),K=r.mul(x,A),K=r.add(K,K),B=r.mul(K,U),v=r.sub(v,B),C=r.mul(K,O),C=r.add(C,C),C=r.add(C,C),new l(v,E,C)}add(p){f(p);let{px:m,py:g,pz:b}=this,{px:x,py:A,pz:v}=p,E=r.ZERO,C=r.ZERO,B=r.ZERO,O=t.a,K=r.mul(t.b,Vd),U=r.mul(m,x),F=r.mul(g,A),G=r.mul(b,v),Q=r.add(m,g),I=r.add(x,A);Q=r.mul(Q,I),I=r.add(U,F),Q=r.sub(Q,I),I=r.add(m,b);let R=r.add(x,v);return I=r.mul(I,R),R=r.add(U,G),I=r.sub(I,R),R=r.add(g,b),E=r.add(A,v),R=r.mul(R,E),E=r.add(F,G),R=r.sub(R,E),B=r.mul(O,I),E=r.mul(K,G),B=r.add(E,B),E=r.sub(F,B),B=r.add(F,B),C=r.mul(E,B),F=r.add(U,U),F=r.add(F,U),G=r.mul(O,G),I=r.mul(K,I),F=r.add(F,G),G=r.sub(U,G),G=r.mul(O,G),I=r.add(I,G),U=r.mul(F,I),C=r.add(C,U),U=r.mul(R,I),E=r.mul(Q,E),E=r.sub(E,U),U=r.mul(Q,F),B=r.mul(R,B),B=r.add(B,U),new l(E,C,B)}subtract(p){return this.add(p.negate())}is0(){return this.equals(l.ZERO)}wNAF(p){return y.wNAFCached(this,u,p,m=>{let g=r.invertBatch(m.map(b=>b.pz));return m.map((b,x)=>b.toAffine(g[x])).map(l.fromAffine)})}multiplyUnsafe(p){let m=l.ZERO;if(p===ur)return m;if(a(p),p===xe)return this;let{endo:g}=t;if(!g)return y.unsafeLadder(this,p);let{k1neg:b,k1:x,k2neg:A,k2:v}=g.splitScalar(p),E=m,C=m,B=this;for(;x>ur||v>ur;)x&xe&&(E=E.add(B)),v&xe&&(C=C.add(B)),B=B.double(),x>>=xe,v>>=xe;return b&&(E=E.negate()),A&&(C=C.negate()),C=new l(r.mul(C.px,g.beta),C.py,C.pz),E.add(C)}multiply(p){a(p);let m=p,g,b,{endo:x}=t;if(x){let{k1neg:A,k1:v,k2neg:E,k2:C}=x.splitScalar(m),{p:B,f:O}=this.wNAF(v),{p:K,f:U}=this.wNAF(C);B=y.constTimeNegate(A,B),K=y.constTimeNegate(E,K),K=new l(r.mul(K.px,x.beta),K.py,K.pz),g=B.add(K),b=O.add(U)}else{let{p:A,f:v}=this.wNAF(m);g=A,b=v}return l.normalizeZ([g,b])[0]}multiplyAndAddUnsafe(p,m,g){let b=l.BASE,x=(v,E)=>E===ur||E===xe||!v.equals(b)?v.multiplyUnsafe(E):v.multiply(E),A=x(this,m).add(x(p,g));return A.is0()?void 0:A}toAffine(p){let{px:m,py:g,pz:b}=this,x=this.is0();p==null&&(p=x?r.ONE:r.inv(b));let A=r.mul(m,p),v=r.mul(g,p),E=r.mul(b,p);if(x)return{x:r.ZERO,y:r.ZERO};if(!r.eql(E,r.ONE))throw new Error("invZ was invalid");return{x:A,y:v}}isTorsionFree(){let{h:p,isTorsionFree:m}=t;if(p===xe)return!0;if(m)return m(l,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:p,clearCofactor:m}=t;return p===xe?this:m?m(l,this):this.multiplyUnsafe(t.h)}toRawBytes(p=!0){return this.assertValidity(),n(l,this,p)}toHex(p=!0){return Je(this.toRawBytes(p))}}l.BASE=new l(t.Gx,t.Gy,r.ONE),l.ZERO=new l(r.ZERO,r.ONE,r.ZERO);let d=t.nBitLength,y=Zo(l,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:l,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:s}}function Ww(e){let t=gi(e);return pe(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Hd(e){let t=Ww(e),{Fp:r,n}=t,i=r.BYTES+1,o=2*r.BYTES+1;function s(I){return ur<I&&I<r.ORDER}function a(I){return ht(I,n)}function c(I){return Yo(I,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:f,weierstrassEquation:l,isWithinCurveOrder:d}=Gw({...t,toBytes(I,R,_){let k=R.toAffine(),S=r.toBytes(k.x),P=rr;return _?P(Uint8Array.from([R.hasEvenY()?2:3]),S):P(Uint8Array.from([4]),S,r.toBytes(k.y))},fromBytes(I){let R=I.length,_=I[0],k=I.subarray(1);if(R===i&&(_===2||_===3)){let S=tr(k);if(!s(S))throw new Error("Point is not on curve");let P=l(S),M=r.sqrt(P),H=(M&xe)===xe;return(_&1)===1!==H&&(M=r.neg(M)),{x:S,y:M}}else if(R===o&&_===4){let S=r.fromBytes(k.subarray(0,r.BYTES)),P=r.fromBytes(k.subarray(r.BYTES,2*r.BYTES));return{x:S,y:P}}else throw new Error(`Point of length ${R} was invalid. Expected ${i} compressed bytes or ${o} uncompressed bytes`)}}),y=I=>Je(Ar(I,t.nByteLength));function h(I){let R=n>>xe;return I>R}function p(I){return h(I)?a(-I):I}let m=(I,R,_)=>tr(I.slice(R,_));class g{constructor(R,_,k){this.r=R,this.s=_,this.recovery=k,this.assertValidity()}static fromCompact(R){let _=t.nByteLength;return R=Et("compactSignature",R,_*2),new g(m(R,0,_),m(R,_,2*_))}static fromDER(R){let{r:_,s:k}=an.toSig(Et("DER",R));return new g(_,k)}assertValidity(){if(!d(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!d(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(R){return new g(this.r,this.s,R)}recoverPublicKey(R){let{r:_,s:k,recovery:S}=this,P=C(Et("msgHash",R));if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");let M=S===2||S===3?_+t.n:_;if(M>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let H=S&1?"03":"02",Z=u.fromHex(H+y(M)),j=c(M),it=a(-P*j),J=a(k*j),et=u.BASE.multiplyAndAddUnsafe(Z,it,J);if(!et)throw new Error("point at infinify");return et.assertValidity(),et}hasHighS(){return h(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return Xr(this.toDERHex())}toDERHex(){return an.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Xr(this.toCompactHex())}toCompactHex(){return y(this.r)+y(this.s)}}let b={isValidPrivateKey(I){try{return f(I),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let I=Pc(t.n);return Ll(t.randomBytes(I),t.n)},precompute(I=8,R=u.BASE){return R._setWindowSize(I),R.multiply(BigInt(3)),R}};function x(I,R=!0){return u.fromPrivateKey(I).toRawBytes(R)}function A(I){let R=I instanceof Uint8Array,_=typeof I=="string",k=(R||_)&&I.length;return R?k===i||k===o:_?k===2*i||k===2*o:I instanceof u}function v(I,R,_=!0){if(A(I))throw new Error("first arg must be private key");if(!A(R))throw new Error("second arg must be public key");return u.fromHex(R).multiply(f(I)).toRawBytes(_)}let E=t.bits2int||function(I){let R=tr(I),_=I.length*8-t.nBitLength;return _>0?R>>BigInt(_):R},C=t.bits2int_modN||function(I){return a(E(I))},B=mi(t.nBitLength);function O(I){if(typeof I!="bigint")throw new Error("bigint expected");if(!(ur<=I&&I<B))throw new Error(`bigint expected < 2^${t.nBitLength}`);return Ar(I,t.nByteLength)}function K(I,R,_=U){if(["recovered","canonical"].some(gt=>gt in _))throw new Error("sign() legacy options not supported");let{hash:k,randomBytes:S}=t,{lowS:P,prehash:M,extraEntropy:H}=_;P==null&&(P=!0),I=Et("msgHash",I),M&&(I=Et("prehashed msgHash",k(I)));let Z=C(I),j=f(R),it=[O(j),O(Z)];if(H!=null){let gt=H===!0?S(r.BYTES):H;it.push(Et("extraEntropy",gt))}let J=rr(...it),et=Z;function bt(gt){let $t=E(gt);if(!d($t))return;let Yt=c($t),Ft=u.BASE.multiply($t).toAffine(),jt=a(Ft.x);if(jt===ur)return;let We=a(Yt*a(et+jt*j));if(We===ur)return;let Lr=(Ft.x===jt?0:2)|Number(Ft.y&xe),ti=We;return P&&h(We)&&(ti=p(We),Lr^=1),new g(jt,ti,Lr)}return{seed:J,k2sig:bt}}let U={lowS:t.lowS,prehash:!1},F={lowS:t.lowS,prehash:!1};function G(I,R,_=U){let{seed:k,k2sig:S}=K(I,R,_),P=t;return _c(P.hash.outputLen,P.nByteLength,P.hmac)(k,S)}u.BASE._setWindowSize(8);function Q(I,R,_,k=F){let S=I;if(R=Et("msgHash",R),_=Et("publicKey",_),"strict"in k)throw new Error("options.strict was renamed to lowS");let{lowS:P,prehash:M}=k,H,Z;try{if(typeof S=="string"||S instanceof Uint8Array)try{H=g.fromDER(S)}catch(Ft){if(!(Ft instanceof an.Err))throw Ft;H=g.fromCompact(S)}else if(typeof S=="object"&&typeof S.r=="bigint"&&typeof S.s=="bigint"){let{r:Ft,s:jt}=S;H=new g(Ft,jt)}else throw new Error("PARSE");Z=u.fromHex(_)}catch(Ft){if(Ft.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(P&&H.hasHighS())return!1;M&&(R=t.hash(R));let{r:j,s:it}=H,J=C(R),et=c(it),bt=a(J*et),gt=a(j*et),$t=u.BASE.multiplyAndAddUnsafe(Z,bt,gt)?.toAffine();return $t?a($t.x)===j:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:v,sign:G,verify:Q,ProjectivePoint:u,Signature:g,utils:b}}function $w(e){return{hash:e,hmac:(t,...r)=>Nn(e,t,Ho(...r)),randomBytes:Yr}}function qd(e,t){let r=n=>Hd({...e,...$w(n)});return Object.freeze({...r(t),create:r})}var Wd=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),zd=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Yw=BigInt(1),w0=BigInt(2),Gd=(e,t)=>(e+t/w0)/t;function Xw(e){let t=Wd,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,f=u*u*e%t,l=St(f,r,t)*f%t,d=St(l,r,t)*f%t,y=St(d,w0,t)*u%t,h=St(y,i,t)*y%t,p=St(h,o,t)*h%t,m=St(p,a,t)*p%t,g=St(m,c,t)*m%t,b=St(g,a,t)*p%t,x=St(b,r,t)*f%t,A=St(x,s,t)*h%t,v=St(A,n,t)*u%t,E=St(v,w0,t);if(!v0.eql(v0.sqr(E),e))throw new Error("Cannot find square root");return E}var v0=Xo(Wd,void 0,void 0,{sqrt:Xw}),ke=qd({a:BigInt(0),b:BigInt(7),Fp:v0,n:zd,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{let t=zd,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Yw*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,s=BigInt("0x100000000000000000000000000000000"),a=Gd(o*e,t),c=Gd(-n*e,t),u=ht(e-a*r-c*i,t),f=ht(-a*n-c*o,t),l=u>s,d=f>s;if(l&&(u=t-u),d&&(f=t-f),u>s||f>s)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:l,k1:u,k2neg:d,k2:f}}}},Pn),TI=BigInt(0);var _I=ke.ProjectivePoint;function $d(){return ke.utils.randomPrivateKey()}function Yd(e,t){let r=Xt.digest(t instanceof Uint8Array?t:t.subarray());if(ge(r))return r.then(({digest:n})=>ke.sign(n,e).toDERRawBytes()).catch(n=>{throw new W(String(n),"ERR_INVALID_INPUT")});try{return ke.sign(r.digest,e).toDERRawBytes()}catch(n){throw new W(String(n),"ERR_INVALID_INPUT")}}function Xd(e,t,r){let n=Xt.digest(r instanceof Uint8Array?r:r.subarray());if(ge(n))return n.then(({digest:i})=>ke.verify(t,i,e)).catch(i=>{throw new W(String(i),"ERR_INVALID_INPUT")});try{return ke.verify(t,n.digest,e)}catch(i){throw new W(String(i),"ERR_INVALID_INPUT")}}function Zd(e){return ke.ProjectivePoint.fromHex(e).toRawBytes(!0)}function Qd(e){try{ke.getPublicKey(e,!0)}catch(t){throw new W(String(t),"ERR_INVALID_PRIVATE_KEY")}}function E0(e){try{ke.ProjectivePoint.fromHex(e)}catch(t){throw new W(String(t),"ERR_INVALID_PUBLIC_KEY")}}function jd(e){try{return ke.getPublicKey(e,!0)}catch(t){throw new W(String(t),"ERR_INVALID_PRIVATE_KEY")}}var Pi=class{_key;constructor(t){E0(t),this._key=t}verify(t,r){return Xd(this._key,r,t)}marshal(){return Zd(this._key)}get bytes(){return qe.encode({Type:_t.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return Kt(this.bytes,t.bytes)}async hash(){let t=Xt.digest(this.bytes),r;return ge(t)?{bytes:r}=await t:r=t.bytes,r}},Ui=class{_key;_publicKey;constructor(t,r){this._key=t,this._publicKey=r??jd(t),Qd(this._key),E0(this._publicKey)}sign(t){return Yd(this._key,t)}get public(){return new Pi(this._publicKey)}marshal(){return this._key}get bytes(){return ze.encode({Type:_t.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return Kt(this.bytes,t.bytes)}hash(){let t=Xt.digest(this.bytes);return ge(t)?t.then(({bytes:r})=>r):t.bytes}async id(){let t=await this.public.hash();return at(t,"base58btc")}async export(t,r="libp2p-key"){if(r==="libp2p-key")return Hn(this.bytes,t);throw new W(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Qw(e){return new Ui(e)}function jw(e){return new Pi(e)}async function Jw(){let e=$d();return new Ui(e)}var cn={rsa:b0,ed25519:p0,secp256k1:S0};function Jd(e){let t=Object.keys(cn).join(" / ");return new W(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function tp(e){let t=qe.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case _t.RSA:return cn.rsa.unmarshalRsaPublicKey(r);case _t.Ed25519:return cn.ed25519.unmarshalEd25519PublicKey(r);case _t.Secp256k1:return cn.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw Jd(t.Type??"unknown")}}async function ep(e){let t=ze.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case _t.RSA:return cn.rsa.unmarshalRsaPrivateKey(r);case _t.Ed25519:return cn.ed25519.unmarshalEd25519PrivateKey(r);case _t.Secp256k1:return cn.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw Jd(t.Type??"RSA")}}var Es;(function(e){let t;e.codec=()=>(t==null&&(t=Ae((r,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),r.webtransportCerthashes!=null)for(let o of r.webtransportCerthashes)n.uint32(10),n.bytes(o);i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={webtransportCerthashes:[]},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:{i.webtransportCerthashes.push(r.bytes());break}default:{r.skipType(s&7);break}}}return i})),t),e.encode=r=>Se(r,e.codec()),e.decode=r=>Ee(r,e.codec())})(Es||(Es={}));var Oi;(function(e){let t;e.codec=()=>(t==null&&(t=Ae((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.identityKey!=null&&r.identityKey.byteLength>0&&(n.uint32(10),n.bytes(r.identityKey)),r.identitySig!=null&&r.identitySig.byteLength>0&&(n.uint32(18),n.bytes(r.identitySig)),r.extensions!=null&&(n.uint32(34),Es.codec().encode(r.extensions,n)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={identityKey:ot(0),identitySig:ot(0)},o=n==null?r.len:r.pos+n;for(;r.pos<o;){let s=r.uint32();switch(s>>>3){case 1:{i.identityKey=r.bytes();break}case 2:{i.identitySig=r.bytes();break}case 4:{i.extensions=Es.codec().decode(r,r.uint32());break}default:{r.skipType(s&7);break}}}return i})),t),e.encode=r=>Se(r,e.codec()),e.decode=r=>Ee(r,e.codec())})(Oi||(Oi={}));async function rp(e,t,r){let n=await rv(e,np(t));if(e.publicKey==null)throw new Error("PublicKey was missing from local PeerId");return ev(e.publicKey,n,r)}function ev(e,t,r){return Oi.encode({identityKey:e,identitySig:t,extensions:r??{webtransportCerthashes:[]}}).subarray()}async function rv(e,t){if(e.privateKey==null)throw new Error("PrivateKey was missing from PeerId");return(await ep(e.privateKey)).sign(t)}async function A0(e){return ha(e.identityKey)}function D0(e){return Oi.decode(e)}function np(e){let t=wt("noise-libp2p-static-key:");return e instanceof Uint8Array?Ct([t,e],t.length+e.length):(e.prepend(t),e)}async function C0(e,t,r){let n=await ha(t.identityKey);if(!n.equals(r))throw new Error(`Payload identity key ${n.toString()} does not match expected remote peer ${r.toString()}`);let i=np(e);if(n.publicKey==null)throw new Error("PublicKey was missing from PeerId");if(t.identitySig==null)throw new Error("Signature was missing from message");if(!await tp(n.publicKey).verify(i,t.identitySig))throw new Error("Static key doesn't match to peer that signed payload!");return n}function Ki(e){return!(!(e instanceof Uint8Array)&&!En(e)||e.byteLength!==32)}var nv=0,iv=4294967295,ov="Cipherstate has reached maximum n, a new handshake must be performed",Ss=class{n;bytes;view;constructor(t=nv){this.n=t,this.bytes=ot(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>iv)throw new Error(ov)}};var As=class{crypto;log;constructor(t,r){this.log=t.logger.forComponent("libp2p:noise:abstract-handshake"),this.crypto=r}encryptWithAd(t,r,n){let i=this.encrypt(t.k,t.n,r,n);return t.n.increment(),i}decryptWithAd(t,r,n,i){let{plaintext:o,valid:s}=this.decrypt(t.k,t.n,r,n,i);return s&&t.n.increment(),{plaintext:o,valid:s}}hasKey(t){return!this.isEmptyKey(t.k)}createEmptyKey(){return ot(32)}isEmptyKey(t){let r=this.createEmptyKey();return Kt(r,t)}encrypt(t,r,n,i){return r.assertValue(),this.crypto.chaCha20Poly1305Encrypt(i,r.getBytes(),n,t)}encryptAndHash(t,r){let n;return this.hasKey(t.cs)?n=this.encryptWithAd(t.cs,t.h,r):n=r,this.mixHash(t,n),n}decrypt(t,r,n,i,o){r.assertValue();let s=this.crypto.chaCha20Poly1305Decrypt(i,r.getBytes(),n,t,o);return s?{plaintext:s,valid:!0}:{plaintext:ot(0),valid:!1}}decryptAndHash(t,r){let n,i=!0;return this.hasKey(t.cs)?{plaintext:n,valid:i}=this.decryptWithAd(t.cs,t.h,r):n=r,this.mixHash(t,r),{plaintext:n,valid:i}}dh(t,r){try{let n=this.crypto.generateX25519SharedKey(t,r);return n.length===32?n:n.subarray(0,32)}catch(n){let i=n;return this.log.error("error deriving shared key",i),ot(32)}}mixHash(t,r){t.h=this.getHash(t.h,r)}getHash(t,r){return this.crypto.hashSHA256(new Bt(t,r))}mixKey(t,r){let[n,i]=this.crypto.getHKDF(t.ck,r);t.cs=this.initializeKey(i),t.ck=n}initializeKey(t){return{k:t,n:new Ss}}initializeSymmetric(t){let r=wt(t,"utf-8"),n=this.hashProtocolName(r),i=n,o=this.createEmptyKey();return{cs:this.initializeKey(o),ck:i,h:n}}hashProtocolName(t){if(t.length<=32){let r=ot(32);return r.set(t),r}else return this.getHash(t,ot(0))}split(t){let[r,n]=this.crypto.getHKDF(t.ck,ot(0)),i=this.initializeKey(r),o=this.initializeKey(n);return{cs1:i,cs2:o}}writeMessageRegular(t,r){let n=this.encryptWithAd(t,ot(0),r),i=this.createEmptyKey(),o=ot(0);return{ne:i,ns:o,ciphertext:n}}readMessageRegular(t,r){return this.decryptWithAd(t,ot(0),r.ciphertext)}};var Ds=class extends As{initializeInitiator(t,r,n,i){let o="Noise_XX_25519_ChaChaPoly_SHA256",s=this.initializeSymmetric(o);this.mixHash(s,t);let a=ot(32);return{ss:s,s:r,rs:n,psk:i,re:a}}initializeResponder(t,r,n,i){let o="Noise_XX_25519_ChaChaPoly_SHA256",s=this.initializeSymmetric(o);this.mixHash(s,t);let a=ot(32);return{ss:s,s:r,rs:n,psk:i,re:a}}writeMessageA(t,r,n){let i=ot(0);n!==void 0?t.e=n:t.e=this.crypto.generateX25519KeyPair();let o=t.e.publicKey;this.mixHash(t.ss,o);let s=this.encryptAndHash(t.ss,r);return{ne:o,ns:i,ciphertext:s}}writeMessageB(t,r){t.e=this.crypto.generateX25519KeyPair();let n=t.e.publicKey;this.mixHash(t.ss,n),this.mixKey(t.ss,this.dh(t.e.privateKey,t.re));let i=t.s.publicKey,o=this.encryptAndHash(t.ss,i);this.mixKey(t.ss,this.dh(t.s.privateKey,t.re));let s=this.encryptAndHash(t.ss,r);return{ne:n,ns:o,ciphertext:s}}writeMessageC(t,r){let n=t.s.publicKey,i=this.encryptAndHash(t.ss,n);this.mixKey(t.ss,this.dh(t.s.privateKey,t.re));let o=this.encryptAndHash(t.ss,r),a={ne:this.createEmptyKey(),ns:i,ciphertext:o},{cs1:c,cs2:u}=this.split(t.ss);return{h:t.ss.h,messageBuffer:a,cs1:c,cs2:u}}readMessageA(t,r){return Ki(r.ne)&&(t.re=r.ne),this.mixHash(t.ss,t.re),this.decryptAndHash(t.ss,r.ciphertext)}readMessageB(t,r){if(Ki(r.ne)&&(t.re=r.ne),this.mixHash(t.ss,t.re),!t.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(t.ss,this.dh(t.e.privateKey,t.re));let{plaintext:n,valid:i}=this.decryptAndHash(t.ss,r.ns);i&&Ki(n)&&(t.rs=n),this.mixKey(t.ss,this.dh(t.e.privateKey,t.rs));let{plaintext:o,valid:s}=this.decryptAndHash(t.ss,r.ciphertext);return{plaintext:o,valid:i&&s}}readMessageC(t,r){let{plaintext:n,valid:i}=this.decryptAndHash(t.ss,r.ns);if(i&&Ki(n)&&(t.rs=n),!t.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(t.ss,this.dh(t.e.privateKey,t.rs));let{plaintext:o,valid:s}=this.decryptAndHash(t.ss,r.ciphertext),{cs1:a,cs2:c}=this.split(t.ss);return{h:t.ss.h,plaintext:o,valid:i&&s,cs1:a,cs2:c}}initSession(t,r,n){let i=this.createEmptyKey(),o=ot(32),s;return t?s=this.initializeInitiator(r,n,o,i):s=this.initializeResponder(r,n,o,i),{hs:s,i:t,mc:0}}sendMessage(t,r,n){let i;if(t.mc===0)i=this.writeMessageA(t.hs,r,n);else if(t.mc===1)i=this.writeMessageB(t.hs,r);else if(t.mc===2){let{h:o,messageBuffer:s,cs1:a,cs2:c}=this.writeMessageC(t.hs,r);i=s,t.h=o,t.cs1=a,t.cs2=c}else if(t.mc>2)if(t.i){if(!t.cs1)throw new Error("CS1 (cipher state) is not defined");i=this.writeMessageRegular(t.cs1,r)}else{if(!t.cs2)throw new Error("CS2 (cipher state) is not defined");i=this.writeMessageRegular(t.cs2,r)}else throw new Error("Session invalid.");return t.mc++,i}recvMessage(t,r){let n=ot(0),i=!1;if(t.mc===0)({plaintext:n,valid:i}=this.readMessageA(t.hs,r));else if(t.mc===1)({plaintext:n,valid:i}=this.readMessageB(t.hs,r));else if(t.mc===2){let{h:o,plaintext:s,valid:a,cs1:c,cs2:u}=this.readMessageC(t.hs,r);n=s,i=a,t.h=o,t.cs1=c,t.cs2=u}return t.mc++,{plaintext:n,valid:i}}};function ip(e,t){!t.enabled||!In||(t(`LOCAL_STATIC_PUBLIC_KEY ${at(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${at(e.privateKey,"hex")}`))}function B0(e,t){!t.enabled||!In||(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${at(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${at(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function op(e,t){!t.enabled||!In||t(`REMOTE_STATIC_PUBLIC_KEY ${at(e.subarray(),"hex")}`)}function I0(e,t){!t.enabled||!In||t(`REMOTE_EPHEMERAL_PUBLIC_KEY ${at(e.subarray(),"hex")}`)}function sp(e,t){!t.enabled||!In||(e.cs1&&e.cs2?(t(`CIPHER_STATE_1 ${e.cs1.n.getUint64()} ${at(e.cs1.k,"hex")}`),t(`CIPHER_STATE_2 ${e.cs2.n.getUint64()} ${at(e.cs2.k,"hex")}`)):t("Missing cipher state."))}var Cs=class{isInitiator;session;remotePeer;remoteExtensions={webtransportCerthashes:[]};payload;connection;xx;staticKeypair;prologue;log;constructor(t,r,n,i,o,s,a,c,u){this.log=t.logger.forComponent("libp2p:noise:xxhandshake"),this.isInitiator=r,this.payload=n,this.prologue=i,this.staticKeypair=s,this.connection=a,c&&(this.remotePeer=c),this.xx=u??new Ds(t,o),this.session=this.xx.initSession(this.isInitiator,this.prologue,this.staticKeypair)}async propose(){if(ip(this.session.hs.s,this.log),this.isInitiator){this.log.trace("Stage 0 - Initiator starting to send first message.");let t=this.xx.sendMessage(this.session,ot(0));await this.connection.write(Gl(t)),this.log.trace("Stage 0 - Initiator finished sending first message."),B0(this.session.hs.e,this.log)}else{this.log.trace("Stage 0 - Responder waiting to receive first message...");let t=Yl((await this.connection.read()).subarray()),{valid:r}=this.xx.recvMessage(this.session,t);if(!r)throw new Qr("xx handshake stage 0 validation fail");this.log.trace("Stage 0 - Responder received first message."),I0(this.session.hs.re,this.log)}}async exchange(){if(this.isInitiator){this.log.trace("Stage 1 - Initiator waiting to receive first message from responder...");let t=Xl((await this.connection.read()).subarray()),{plaintext:r,valid:n}=this.xx.recvMessage(this.session,t);if(!n)throw new Qr("xx handshake stage 1 validation fail");this.log.trace("Stage 1 - Initiator received the message."),I0(this.session.hs.re,this.log),op(this.session.hs.rs,this.log),this.log.trace("Initiator going to check remote's signature...");try{let i=D0(r);this.remotePeer=this.remotePeer||await A0(i),await C0(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let o=i;throw new Si(`Error occurred while verifying signed payload: ${o.message}`)}this.log.trace("All good with the signature!")}else{this.log.trace("Stage 1 - Responder sending out first message with signed payload and static key.");let t=this.xx.sendMessage(this.session,this.payload);await this.connection.write(Wl(t)),this.log.trace("Stage 1 - Responder sent the second handshake message with signed payload."),B0(this.session.hs.e,this.log)}}async finish(){if(this.isInitiator){this.log.trace("Stage 2 - Initiator sending third handshake message.");let t=this.xx.sendMessage(this.session,this.payload);await this.connection.write($l(t)),this.log.trace("Stage 2 - Initiator sent message with signed payload.")}else{this.log.trace("Stage 2 - Responder waiting for third handshake message...");let t=Zl((await this.connection.read()).subarray()),{plaintext:r,valid:n}=this.xx.recvMessage(this.session,t);if(!n)throw new Qr("xx handshake stage 2 validation fail");this.log.trace("Stage 2 - Responder received the message, finished handshake.");try{let i=D0(r);this.remotePeer=this.remotePeer||await A0(i),await C0(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let o=i;throw new Si(`Error occurred while verifying signed payload: ${o.message}`)}}sp(this.session,this.log)}encrypt(t,r){let n=this.getCS(r);return this.xx.encryptWithAd(n,ot(0),t)}decrypt(t,r,n){let i=this.getCS(r,!1);return this.xx.decryptWithAd(i,ot(0),t,n)}getRemoteStaticKey(){return this.session.hs.rs}getCS(t,r=!0){if(!t.cs1||!t.cs2)throw new Qr("Handshake not completed properly, cipher state does not exist.");return this.isInitiator?r?t.cs1:t.cs2:r?t.cs2:t.cs1}setRemoteNoiseExtension(t){t&&(this.remoteExtensions=t)}};function ap(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}var Bs=class{protocol="/noise";crypto;prologue;staticKeys;extensions;metrics;components;constructor(t,r={}){let{staticNoiseKey:n,extensions:i,crypto:o,prologueBytes:s}=r,{metrics:a}=t;this.components=t,this.crypto=o??zl,this.extensions=i,this.metrics=a?ap(a):void 0,n?this.staticKeys=this.crypto.generateX25519KeyPairFromSeed(n):this.staticKeys=this.crypto.generateX25519KeyPair(),this.prologue=s??ot(0)}async secureOutbound(t,r,n){let i=pi(r,{lengthEncoder:Un,lengthDecoder:vi,maxDataLength:65535}),o=await this.performHandshake({connection:i,isInitiator:!0,localPeer:t,remotePeer:n}),s=await this.createSecureConnection(i,o);return r.source=s.source,r.sink=s.sink,{conn:r,remoteExtensions:o.remoteExtensions,remotePeer:o.remotePeer}}async secureInbound(t,r,n){let i=pi(r,{lengthEncoder:Un,lengthDecoder:vi,maxDataLength:65535}),o=await this.performHandshake({connection:i,isInitiator:!1,localPeer:t,remotePeer:n}),s=await this.createSecureConnection(i,o);return r.source=s.source,r.sink=s.sink,{conn:r,remotePeer:o.remotePeer,remoteExtensions:o.remoteExtensions}}async performHandshake(t){let r=await rp(t.localPeer,this.staticKeys.publicKey,this.extensions);return this.performXXHandshake(t,r)}async performXXHandshake(t,r){let{isInitiator:n,remotePeer:i,connection:o}=t,s=new Cs(this.components,n,r,this.prologue,this.crypto,this.staticKeys,o,i);try{await s.propose(),await s.exchange(),await s.finish(),this.metrics?.xxHandshakeSuccesses.increment()}catch(a){if(this.metrics?.xxHandshakeErrors.increment(),a instanceof Error)throw a.message=`Error occurred during XX handshake: ${a.message}`,a}return s}async createSecureConnection(t,r){let[n,i]=sl(),o=t.unwrap();return await cl(n,Jl(r,this.metrics),o,s=>Fr(s,{lengthDecoder:vi}),th(r,this.metrics),n),i}};function cp(e={}){return t=>new Bs(t,e)}var K1=Jt(iu(),1);var k1=Jt(iu(),1);var ou=Object.values(Ne).map(e=>e.decoder).reduce((e,t)=>e.or(t));function R1(e,t){let r=e.getConfiguration().certificates?.at(0);if(r==null||r.getFingerprints==null){t.log.trace("fetching fingerprint from local SDP");let i=e.localDescription;return i==null?void 0:hE(i.sdp)}if(t.log.trace("fetching fingerprint from local certificate"),r.getFingerprints().length===0)return;let n=r.getFingerprints()[0].value;if(n==null)throw Ha("","no fingerprint on local certificate");return n}var lE=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function hE(e){return e.match(lE)?.groups?.fingerprint}function dE(e){for(let t of e.protoNames())if(t.startsWith("ip"))return t.toUpperCase();return"IP6"}function Ms(e){let r=e.stringTuples().filter(n=>n[0]===P1).map(n=>n[1])[0];if(r===void 0||r==="")throw fo(`Couldn't find a certhash component of multiaddr: ${e.toString()}`);return r}function su(e){let t=ou.decode(e);return k1.decode(t)}function pE(e){let t=su(Ms(e)),r=au(t.name),n=t.digest.reduce((o,s)=>o+s.toString(16).padStart(2,"0"),""),i=n.match(/.{1,2}/g);if(i==null)throw Ha(n,e.toString());return[`${r.toUpperCase()} ${i.join(":").toUpperCase()}`,n]}function au(e){switch(e){case"sha1":return"sha-1";case"sha2-256":return"sha-256";case"sha2-512":return"sha-512";default:throw mf(e)}}function yE(e,t){let{host:r,port:n}=e.toOptions(),i=dE(e),[o]=pE(e);return`v=0
30
30
  o=- 0 0 IN ${i} ${r}
31
31
  s=-
32
32
  c=IN ${i} ${r}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@libp2p/webrtc",
3
- "version": "4.0.5",
3
+ "version": "4.0.6-16588d27c",
4
4
  "description": "A libp2p transport using WebRTC connections",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/transport-webrtc#readme",
@@ -50,11 +50,11 @@
50
50
  },
51
51
  "dependencies": {
52
52
  "@chainsafe/libp2p-noise": "^14.0.0",
53
- "@libp2p/interface": "^1.0.1",
54
- "@libp2p/interface-internal": "^1.0.1",
55
- "@libp2p/logger": "^4.0.1",
56
- "@libp2p/peer-id": "^4.0.1",
57
- "@libp2p/utils": "^5.0.2",
53
+ "@libp2p/interface": "1.0.1-16588d27c",
54
+ "@libp2p/interface-internal": "1.0.1-16588d27c",
55
+ "@libp2p/logger": "4.0.1-16588d27c",
56
+ "@libp2p/peer-id": "4.0.1-16588d27c",
57
+ "@libp2p/utils": "5.0.2-16588d27c",
58
58
  "@multiformats/mafmt": "^12.1.6",
59
59
  "@multiformats/multiaddr": "^12.1.10",
60
60
  "@multiformats/multiaddr-matcher": "^1.1.0",
@@ -79,10 +79,10 @@
79
79
  },
80
80
  "devDependencies": {
81
81
  "@chainsafe/libp2p-yamux": "^6.0.1",
82
- "@libp2p/circuit-relay-v2": "^1.0.4",
83
- "@libp2p/interface-compliance-tests": "^5.0.4",
84
- "@libp2p/peer-id-factory": "^4.0.0",
85
- "@libp2p/websockets": "^8.0.4",
82
+ "@libp2p/circuit-relay-v2": "1.0.5-16588d27c",
83
+ "@libp2p/interface-compliance-tests": "5.0.5-16588d27c",
84
+ "@libp2p/peer-id-factory": "4.0.0-16588d27c",
85
+ "@libp2p/websockets": "8.0.5-16588d27c",
86
86
  "@types/sinon": "^17.0.0",
87
87
  "aegir": "^41.0.2",
88
88
  "delay": "^6.0.0",
@@ -90,7 +90,7 @@
90
90
  "it-length": "^3.0.2",
91
91
  "it-map": "^3.0.3",
92
92
  "it-pair": "^2.0.6",
93
- "libp2p": "^1.0.5",
93
+ "libp2p": "1.0.6-16588d27c",
94
94
  "p-retry": "^6.1.0",
95
95
  "protons": "^7.3.0",
96
96
  "sinon": "^17.0.0",
@@ -1,8 +0,0 @@
1
- {
2
- "DataChannelOptions": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_webrtc.DataChannelOptions.html",
3
- ".:DataChannelOptions": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_webrtc.DataChannelOptions.html",
4
- "webRTC": "https://libp2p.github.io/js-libp2p/functions/_libp2p_webrtc.webRTC.html",
5
- ".:webRTC": "https://libp2p.github.io/js-libp2p/functions/_libp2p_webrtc.webRTC.html",
6
- "webRTCDirect": "https://libp2p.github.io/js-libp2p/functions/_libp2p_webrtc.webRTCDirect.html",
7
- ".:webRTCDirect": "https://libp2p.github.io/js-libp2p/functions/_libp2p_webrtc.webRTCDirect.html"
8
- }