@libp2p/webrtc 1.1.11 → 1.2.0

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
@@ -31,7 +31,7 @@ if (cid) {
31
31
  // Make sure to use cid instead of value
32
32
  doSomethingWithCID(cid)
33
33
  }
34
- `;tl.CID=Je});var H2=_(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});var i_=rl(),s_=Hs(),o_=Er(),a_=yc(),c_=Mi();Mn.CID=i_.CID;Mn.varint=s_;Mn.bytes=o_;Mn.hasher=a_;Mn.digest=c_});var z2=_(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});var u_=h2(),f_=d2(),l_=p2(),h_=y2(),d_=b2(),p_=Y0(),y_=x2(),g_=J0(),b_=v2(),m_=S2(),x_=R2(),w_=U2(),v_=M2(),E_=K2();H2();var S_=rl(),__=yc(),A_=Mi(),C_=Hs(),D_=Er(),T_={...u_,...f_,...l_,...h_,...d_,...p_,...y_,...g_,...b_,...m_},B_={...x_,...w_},I_={raw:v_,json:E_};Sr.CID=S_.CID;Sr.hasher=__;Sr.digest=A_;Sr.varint=C_;Sr.bytes=D_;Sr.bases=T_;Sr.codecs=I_;Sr.hashes=B_});var vc=_(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});function k_(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}nl.asUint8Array=k_});var il=_(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var G2=vc();function L_(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.alloc!=null?G2.asUint8Array(globalThis.Buffer.alloc(t)):new Uint8Array(t)}function N_(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?G2.asUint8Array(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}Ec.alloc=L_;Ec.allocUnsafe=N_});var ol=_((oO,X2)=>{"use strict";var W2=z2(),R_=il();function $2(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var j2=$2("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),sl=$2("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=R_.allocUnsafe(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),O_={utf8:j2,"utf-8":j2,hex:W2.bases.base16,latin1:sl,ascii:sl,binary:sl,...W2.bases};X2.exports=O_});var Y2=_(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});var P_=ol();function U_(t,e="utf8"){let r=P_[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}al.toString=U_});var J2=_(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});var F_=ol(),M_=vc();function K_(t,e="utf8"){let r=F_[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?M_.asUint8Array(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}cl.fromString=K_});var Z2=_(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});var V_=il(),q_=vc();function H_(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));let r=V_.allocUnsafe(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return q_.asUint8Array(r)}ul.concat=H_});var ll=_((fO,ib)=>{"use strict";var Q2=$g(),qi=s2(),{names:js}=a2(),{toString:Sc}=Y2(),{fromString:z_}=J2(),{concat:G_}=Z2(),Hi={};for(let t in js){let e=t;Hi[js[e]]=e}Object.freeze(Hi);function W_(t){if(!(t instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return Sc(t,"base16")}function j_(t){return z_(t,"base16")}function $_(t){if(!(t instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return Sc(Q2.encode("base58btc",t)).slice(1)}function X_(t){let e=t instanceof Uint8Array?Sc(t):t;return Q2.decode("z"+e)}function eb(t){if(!(t instanceof Uint8Array))throw new Error("multihash must be a Uint8Array");if(t.length<2)throw new Error("multihash too short. must be > 2 bytes.");let e=qi.decode(t);if(!rb(e))throw new Error(`multihash unknown function code: 0x${e.toString(16)}`);t=t.slice(qi.decode.bytes);let r=qi.decode(t);if(r<0)throw new Error(`multihash invalid length: ${r}`);if(t=t.slice(qi.decode.bytes),t.length!==r)throw new Error(`multihash length inconsistent: 0x${Sc(t,"base16")}`);return{code:e,name:Hi[e],length:r,digest:t}}function Y_(t,e,r){if(!t||e===void 0)throw new Error("multihash encode requires at least two args: digest, code");let n=tb(e);if(!(t instanceof Uint8Array))throw new Error("digest should be a Uint8Array");if(r==null&&(r=t.length),r&&t.length!==r)throw new Error("digest length should be equal to specified length.");let i=qi.encode(n),s=qi.encode(r);return G_([i,s,t],i.length+s.length+t.length)}function tb(t){let e=t;if(typeof t=="string"){if(js[t]===void 0)throw new Error(`Unrecognized hash function named: ${t}`);e=js[t]}if(typeof e!="number")throw new Error(`Hash function code should be a number. Got: ${e}`);if(Hi[e]===void 0&&!fl(e))throw new Error(`Unrecognized function code: ${e}`);return e}function fl(t){return t>0&&t<16}function rb(t){return!!(fl(t)||Hi[t])}function nb(t){eb(t)}function J_(t){return nb(t),t.subarray(0,2)}ib.exports={names:js,codes:Hi,toHexString:W_,fromHexString:j_,toB58String:$_,fromB58String:X_,decode:eb,encode:Y_,coerceCode:tb,isAppCode:fl,validate:nb,prefix:J_,isValidCode:rb}});var uA={};Ze(uA,{webRTC:()=>cA,webRTCDirect:()=>aA});var Xs=Symbol.for("@libp2p/transport");var ml;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(ml||(ml={}));var ee=class extends Error{code;props;constructor(e,r,n){super(e),this.code=r,this.name=n?.name??"CodeError",this.props=n??{}}};var It=G(Bl(),1);var Rc={};Ze(Rc,{base58btc:()=>Fe,base58flickr:()=>zb});function Mb(t,e){if(t.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<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var y=0,g=0,b=0,v=d.length;b!==v&&d[b]===0;)b++,y++;for(var w=(v-b)*f+1>>>0,C=new Uint8Array(w);b!==v;){for(var E=d[b],S=0,T=w-1;(E!==0||S<g)&&T!==-1;T--,S++)E+=256*C[T]>>>0,C[T]=E%a>>>0,E=E/a>>>0;if(E!==0)throw new Error("Non-zero carry");g=S,b++}for(var I=w-g;I!==w&&C[I]===0;)I++;for(var O=c.repeat(y);I<w;++I)O+=t.charAt(C[I]);return O}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var y=0;if(d[y]!==" "){for(var g=0,b=0;d[y]===c;)g++,y++;for(var v=(d.length-y)*u+1>>>0,w=new Uint8Array(v);d[y];){var C=r[d.charCodeAt(y)];if(C===255)return;for(var E=0,S=v-1;(C!==0||E<b)&&S!==-1;S--,E++)C+=a*w[S]>>>0,w[S]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");b=E,y++}if(d[y]!==" "){for(var T=v-b;T!==v&&w[T]===0;)T++;for(var I=new Uint8Array(g+(v-T)),O=g;T!==v;)I[O++]=w[T++];return I}}}function p(d){var y=h(d);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:h,decode:p}}var Kb=Mb,Vb=Kb,Il=Vb;var vA=new Uint8Array(0);var kl=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0},Bt=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")};var Ll=t=>new TextEncoder().encode(t),Nl=t=>new TextDecoder().decode(t);var Ic=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},kc=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Ol(this,e)}},Lc=class{constructor(e){this.decoders=e}or(e){return Ol(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},Ol=(t,e)=>new Lc({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Nc=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new Ic(e,r,n),this.decoder=new kc(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},zn=({name:t,prefix:e,encode:r,decode:n})=>new Nc(t,e,r,n),qr=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=Il(r,e);return zn({prefix:t,name:e,encode:n,decode:s=>Bt(i(s))})},qb=(t,e,r,n)=>{let i={};for(let f=0;f<e.length;++f)i[e[f]]=f;let s=t.length;for(;t[s-1]==="=";)--s;let o=new Uint8Array(s*r/8|0),a=0,c=0,u=0;for(let f=0;f<s;++f){let l=i[t[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|l,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Hb=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<<r)-1,s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},Re=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>zn({prefix:e,name:t,encode(i){return Hb(i,n,r)},decode(i){return qb(i,n,r,t)}});var Fe=qr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),zb=qr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Oc={};Ze(Oc,{base32:()=>Mt,base32hex:()=>$b,base32hexpad:()=>Yb,base32hexpadupper:()=>Jb,base32hexupper:()=>Xb,base32pad:()=>Wb,base32padupper:()=>jb,base32upper:()=>Gb,base32z:()=>Zb});var Mt=Re({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Gb=Re({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Wb=Re({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),jb=Re({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),$b=Re({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Xb=Re({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Yb=Re({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Jb=Re({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Zb=Re({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Pc={};Ze(Pc,{base64:()=>Gn,base64pad:()=>Qb,base64url:()=>em,base64urlpad:()=>tm});var Gn=Re({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Qb=Re({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),em=Re({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),tm=Re({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});It.default.formatters.b=t=>t==null?"undefined":Fe.baseEncode(t);It.default.formatters.t=t=>t==null?"undefined":Mt.baseEncode(t);It.default.formatters.m=t=>t==null?"undefined":Gn.baseEncode(t);It.default.formatters.p=t=>t==null?"undefined":t.toString();It.default.formatters.c=t=>t==null?"undefined":t.toString();It.default.formatters.k=t=>t==null?"undefined":t.toString();function rm(t){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=t,e.destroy=()=>!0,e.extend=()=>e,e}function lt(t){let e=rm(`${t}:trace`);return It.default.enabled(`${t}:trace`)&&It.default.names.map(r=>r.toString()).find(r=>r.includes(":trace"))!=null&&(e=(0,It.default)(`${t}:trace`)),Object.assign((0,It.default)(t),{error:(0,It.default)(`${t}:error`),trace:e})}var nm=Fl,Pl=128,im=127,sm=~im,om=Math.pow(2,31);function Fl(t,e,r){e=e||[],r=r||0;for(var n=r;t>=om;)e[r++]=t&255|Pl,t/=128;for(;t&sm;)e[r++]=t&255|Pl,t>>>=7;return e[r]=t|0,Fl.bytes=r-n+1,e}var am=Uc,cm=128,Ul=127;function Uc(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw Uc.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&Ul)<<i:(o&Ul)*Math.pow(2,i),i+=7}while(o>=cm);return Uc.bytes=s-n,r}var um=Math.pow(2,7),fm=Math.pow(2,14),lm=Math.pow(2,21),hm=Math.pow(2,28),dm=Math.pow(2,35),pm=Math.pow(2,42),ym=Math.pow(2,49),gm=Math.pow(2,56),bm=Math.pow(2,63),mm=function(t){return t<um?1:t<fm?2:t<lm?3:t<hm?4:t<dm?5:t<pm?6:t<ym?7:t<gm?8:t<bm?9:10},xm={encode:nm,decode:am,encodingLength:mm},wm=xm,zi=wm;var Gi=(t,e=0)=>[zi.decode(t,e),zi.decode.bytes],Wn=(t,e,r=0)=>(zi.encode(t,e,r),e),jn=t=>zi.encodingLength(t);var er=(t,e)=>{let r=e.byteLength,n=jn(t),i=n+jn(r),s=new Uint8Array(i+r);return Wn(t,s,0),Wn(r,s,n),s.set(e,i),new $n(t,r,e,s)},un=t=>{let e=Bt(t),[r,n]=Gi(e),[i,s]=Gi(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new $n(r,i,o,e)},Ml=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&kl(t.bytes,r.bytes)}},$n=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};var Kl=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return Em(r,Fc(t),e||Fe.encoder);default:return Sm(r,Fc(t),e||Mt.encoder)}};var Vl=new WeakMap,Fc=t=>{let e=Vl.get(t);if(e==null){let r=new Map;return Vl.set(t,r),r}return e},xe=class{constructor(e,r,n,i){this.code=r,this.version=e,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:e,multihash:r}=this;if(e!==Wi)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==_m)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return xe.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:e,digest:r}=this.multihash,n=er(e,r);return xe.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(e){return xe.equals(this,e)}static equals(e,r){let n=r;return n&&e.code===n.code&&e.version===n.version&&Ml(e.multihash,n.multihash)}toString(e){return Kl(this,e)}toJSON(){return{"/":Kl(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof xe)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:i,multihash:s,bytes:o}=r;return new xe(n,i,s,o||ql(n,i,s.bytes))}else if(r[Am]===!0){let{version:n,multihash:i,code:s}=r,o=un(i);return xe.create(n,s,o)}else return null}static create(e,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(e){case 0:{if(r!==Wi)throw new Error(`Version 0 CID must use dag-pb (code: ${Wi}) block encoding`);return new xe(e,r,n,n.bytes)}case 1:{let i=ql(e,r,n.bytes);return new xe(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return xe.create(0,Wi,e)}static createV1(e,r){return xe.create(1,e,r)}static decode(e){let[r,n]=xe.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=xe.inspectBytes(e),n=r.size-r.multihashSize,i=Bt(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=i.subarray(r.multihashSize-r.digestSize),o=new $n(r.multihashCode,r.digestSize,s,i);return[r.version===0?xe.createV0(o):xe.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[l,h]=Gi(e.subarray(r));return r+=h,l},i=n(),s=Wi;if(i===18?(i=0,r=0):s=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=r,a=n(),c=n(),u=r+c,f=u-o;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,r){let[n,i]=vm(e,r),s=xe.decode(i);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Fc(s).set(n,e),s}},vm=(t,e)=>{switch(t[0]){case"Q":{let r=e||Fe;return[Fe.prefix,r.decode(`${Fe.prefix}${t}`)]}case Fe.prefix:{let r=e||Fe;return[Fe.prefix,r.decode(t)]}case Mt.prefix:{let r=e||Mt;return[Mt.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},Em=(t,e,r)=>{let{prefix:n}=r;if(n!==Fe.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return i},Sm=(t,e,r)=>{let{prefix:n}=r,i=e.get(n);if(i==null){let s=r.encode(t);return e.set(n,s),s}else return i},Wi=112,_m=18,ql=(t,e,r)=>{let n=jn(t),i=n+jn(e),s=new Uint8Array(i+r.byteLength);return Wn(t,s,0),Wn(e,s,n),s.set(r,i),s},Am=Symbol.for("@ipld/js-cid/CID");var Mc={};Ze(Mc,{identity:()=>Cm});var Cm=zn({prefix:"\0",name:"identity",encode:t=>Nl(t),decode:t=>Ll(t)});var Kc={};Ze(Kc,{base2:()=>Dm});var Dm=Re({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Vc={};Ze(Vc,{base8:()=>Tm});var Tm=Re({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var qc={};Ze(qc,{base10:()=>Bm});var Bm=qr({prefix:"9",name:"base10",alphabet:"0123456789"});var Hc={};Ze(Hc,{base16:()=>Im,base16upper:()=>km});var Im=Re({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),km=Re({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var zc={};Ze(zc,{base36:()=>Lm,base36upper:()=>Nm});var Lm=qr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Nm=qr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Gc={};Ze(Gc,{base256emoji:()=>Fm});var Hl=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}"),Rm=Hl.reduce((t,e,r)=>(t[r]=e,t),[]),Om=Hl.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Pm(t){return t.reduce((e,r)=>(e+=Rm[r],e),"")}function Um(t){let e=[];for(let r of t){let n=Om[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var Fm=zn({prefix:"\u{1F680}",name:"base256emoji",encode:Pm,decode:Um});var Xc={};Ze(Xc,{sha256:()=>et,sha512:()=>Mm});var $c=G(Ge("crypto"),1);var jc=({name:t,code:e,encode:r})=>new Wc(t,e,r),Wc=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?er(this.code,r):r.then(n=>er(this.code,n))}else throw Error("Unknown type, must be binary type")}};var et=jc({name:"sha2-256",code:18,encode:t=>Bt($c.default.createHash("sha256").update(t).digest())}),Mm=jc({name:"sha2-512",code:19,encode:t=>Bt($c.default.createHash("sha512").update(t).digest())});var Yc={};Ze(Yc,{identity:()=>Hr});var Gl=0,Km="identity",Wl=Bt,Vm=t=>er(Gl,Wl(t)),Hr={code:Gl,name:Km,encode:Wl,digest:Vm};var ZA=new TextEncoder,QA=new TextDecoder;var tr={...Mc,...Kc,...Vc,...qc,...Hc,...Oc,...zc,...Rc,...Pc,...Gc},iC={...Xc,...Yc};function qe(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}var jl=Symbol.for("@libp2p/peer-id");var zm=Symbol.for("nodejs.util.inspect.custom"),$l=Object.values(tr).map(t=>t.decoder).reduce((t,e)=>t.or(e),tr.identity.decoder),Xl=114,Jc=36,Zc=37,ji=class{constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}get[jl](){return!0}toString(){return this.string==null&&(this.string=Fe.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return xe.createV1(Xl,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e instanceof Uint8Array)return qe(this.multihash.bytes,e);if(typeof e=="string")return $i(e).equals(this);if(e?.multihash?.bytes!=null)return qe(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[zm](){return`PeerId(${this.toString()})`}},Xn=class extends ji{constructor(e){super({...e,type:"RSA"}),this.type="RSA",this.publicKey=e.publicKey}},Yn=class extends ji{constructor(e){super({...e,type:"Ed25519"}),this.type="Ed25519",this.publicKey=e.multihash.digest}},Jn=class extends ji{constructor(e){super({...e,type:"secp256k1"}),this.type="secp256k1",this.publicKey=e.multihash.digest}};function $i(t,e){if(e=e??$l,t.charAt(0)==="1"||t.charAt(0)==="Q"){let r=un(Fe.decode(`z${t}`));return t.startsWith("12D")?new Yn({multihash:r}):t.startsWith("16U")?new Jn({multihash:r}):new Xn({multihash:r})}return Gm($l.decode(t))}function Gm(t){try{let e=un(t);if(e.code===Hr.code){if(e.digest.length===Jc)return new Yn({multihash:e});if(e.digest.length===Zc)return new Jn({multihash:e})}if(e.code===et.code)return new Xn({multihash:e})}catch{return Wm(xe.decode(t))}throw new Error("Supplied PeerID CID is invalid")}function Wm(t){if(t==null||t.multihash==null||t.version==null||t.version===1&&t.code!==Xl)throw new Error("Supplied PeerID CID is invalid");let e=t.multihash;if(e.code===et.code)return new Xn({multihash:t.multihash});if(e.code===Hr.code){if(e.digest.length===Jc)return new Yn({multihash:t.multihash});if(e.digest.length===Zc)return new Jn({multihash:t.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function Qc(t,e){return t.length===Jc?new Yn({multihash:er(Hr.code,t),privateKey:e}):t.length===Zc?new Jn({multihash:er(Hr.code,t),privateKey:e}):new Xn({multihash:await et.digest(t),publicKey:t,privateKey:e})}var zr=Ge("node:net");function to(t){return!!(0,zr.isIP)(t)}function Gr(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function _r(t=0){return globalThis.Buffer?.alloc!=null?Gr(globalThis.Buffer.alloc(t)):new Uint8Array(t)}function mt(t=0){return globalThis.Buffer?.allocUnsafe!=null?Gr(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Jl(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var Yl=Jl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),eu=Jl("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=mt(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),$m={utf8:Yl,"utf-8":Yl,hex:tr.base16,latin1:eu,ascii:eu,binary:eu,...tr},ro=$m;function $(t,e="utf8"){let r=ro[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}var Zl=zr.isIPv4,Xm=zr.isIPv6,tu=function(t){let e=0;if(t=t.toString().trim(),Zl(t)){let r=new Uint8Array(e+4);return t.split(/\./g).forEach(n=>{r[e++]=parseInt(n,10)&255}),r}if(Xm(t)){let r=t.split(":",8),n;for(n=0;n<r.length;n++){let s=Zl(r[n]),o;s&&(o=tu(r[n]),r[n]=$(o.slice(0,2),"base16")),o!=null&&++n<8&&r.splice(n,0,$(o.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 s=[n,1];for(n=9-r.length;n>0;n--)s.push("0");r.splice.apply(r,s)}let i=new Uint8Array(e+16);for(n=0;n<r.length;n++){let s=parseInt(r[n],16);i[e++]=s>>8&255,i[e++]=s&255}return i}throw new Error("invalid ip address")},Ql=function(t,e=0,r){e=~~e,r=r??t.length-e;let n=new DataView(t.buffer);if(r===4){let i=[];for(let s=0;s<r;s++)i.push(t[e+s]);return i.join(".")}if(r===16){let i=[];for(let s=0;s<r;s+=2)i.push(n.getUint16(e+s).toString(16));return i.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Xi={},ru={},Jm=[[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"]];Jm.forEach(t=>{let e=Zm(...t);ru[e.code]=e,Xi[e.name]=e});function Zm(t,e,r,n,i){return{code:t,size:e,name:r,resolvable:!!n,path:!!i}}function pe(t){if(typeof t=="number"){if(ru[t]!=null)return ru[t];throw new Error(`no protocol with code: ${t}`)}else if(typeof t=="string"){if(Xi[t]!=null)return Xi[t];throw new Error(`no protocol with name: ${t}`)}throw new Error(`invalid protocol id type: ${typeof t}`)}var rr=G(no(),1);function Ae(t,e="utf8"){let r=ro[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Gr(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function ye(t,e){e==null&&(e=t.reduce((i,s)=>i+s.length,0));let r=mt(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return Gr(r)}var io=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let r=this.index,n=e();return n===void 0&&(this.index=r),n}parseWith(e){let r=e();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(e){return this.readAtomically(()=>{let r=this.readChar();if(r===e)return r})}readSeparator(e,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,r,n,i){return this.readAtomically(()=>{let s=0,o=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 h=Number.parseInt(l,e);if(!Number.isNaN(h))return h});if(f===void 0)break;if(s*=e,s+=f,s>u||(o+=1,r!==void 0&&o>r))return}if(o!==0)return!n&&c&&o>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let r=0;r<e.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[r]=n}return e})}readIPv6Addr(){let e=r=>{for(let n=0;n<r.length/2;n++){let i=n*2;if(n<r.length-3){let o=this.readSeparator(":",n,()=>this.readIPv4Addr());if(o!==void 0)return r[i]=o[0],r[i+1]=o[1],r[i+2]=o[2],r[i+3]=o[3],[i+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[i,!1];r[i]=s>>8,r[i+1]=s&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,i]=e(r);if(n===16)return r;if(i||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),o=16-(n+2),[a]=e(s.subarray(0,o));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var VC=new io;var XC=parseInt("0xFFFF",16),YC=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var BD=pe("ip4"),ID=pe("ip6"),kD=pe("ipcidr");function yh(t,e){switch(pe(t).code){case 4:case 41:return mx(e);case 42:return dh(e);case 6:case 273:case 33:case 132:return bh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return dh(e);case 421:return Ex(e);case 444:return ph(e);case 445:return ph(e);case 466:return vx(e);default:return $(e,"base16")}}function gh(t,e){switch(pe(t).code){case 4:return lh(e);case 41:return lh(e);case 42:return hh(e);case 6:case 273:case 33:case 132:return ou(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return hh(e);case 421:return xx(e);case 444:return Sx(e);case 445:return _x(e);case 466:return wx(e);default:return Ae(e,"base16")}}var su=Object.values(tr).map(t=>t.decoder),bx=function(){let t=su[0].or(su[1]);return su.slice(2).forEach(e=>t=t.or(e)),t}();function lh(t){if(!to(t))throw new Error("invalid ip address");return tu(t)}function mx(t){let e=Ql(t,0,t.length);if(e==null)throw new Error("ipBuff is required");if(!to(e))throw new Error("invalid ip address");return e}function ou(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,t),new Uint8Array(e)}function bh(t){return new DataView(t.buffer).getUint16(t.byteOffset)}function hh(t){let e=Ae(t),r=Uint8Array.from(rr.default.encode(e.length));return ye([r,e],r.length+e.length)}function dh(t){let e=rr.default.decode(t);if(t=t.slice(rr.default.decode.bytes),t.length!==e)throw new Error("inconsistent lengths");return $(t)}function xx(t){let e;t[0]==="Q"||t[0]==="1"?e=un(Fe.decode(`z${t}`)).bytes:e=xe.parse(t).multihash.bytes;let r=Uint8Array.from(rr.default.encode(e.length));return ye([r,e],r.length+e.length)}function wx(t){let e=bx.decode(t),r=Uint8Array.from(rr.default.encode(e.length));return ye([r,e],r.length+e.length)}function vx(t){let e=rr.default.decode(t),r=t.slice(rr.default.decode.bytes);if(r.length!==e)throw new Error("inconsistent lengths");return"u"+$(r,"base64url")}function Ex(t){let e=rr.default.decode(t),r=t.slice(rr.default.decode.bytes);if(r.length!==e)throw new Error("inconsistent lengths");return $(r,"base58btc")}function Sx(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let r=Mt.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=ou(n);return ye([r,i],r.length+i.length)}function _x(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let r=Mt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=ou(n);return ye([r,i],r.length+i.length)}function ph(t){let e=t.slice(0,t.length-2),r=t.slice(t.length-2),n=$(e,"base32"),i=bh(r);return`${n}:${i}`}var Zn=G(no(),1);function Ax(t){let e=[],r=t.split("/").slice(1);if(r.length===1&&r[0]==="")return[];for(let n=0;n<r.length;n++){let i=r[n],s=pe(i);if(s.size===0){e.push([i]);continue}if(n++,n>=r.length)throw xh("invalid address: "+t);if(s.path===!0){e.push([i,lu(r.slice(n).join("/"))]);break}e.push([i,r[n]])}return e}function Cx(t){let e=[];return t.map(r=>{let n=ao(r);return e.push(n.name),r.length>1&&r[1]!=null&&e.push(r[1]),null}),lu(e.join("/"))}function Dx(t){return t.map(e=>{Array.isArray(e)||(e=[e]);let r=ao(e);return e.length>1?[r.code,gh(r.code,e[1])]:[r.code]})}function au(t){return t.map(e=>{let r=ao(e);return e[1]!=null?[r.code,yh(r.code,e[1])]:[r.code]})}function cu(t){return oo(ye(t.map(e=>{let r=ao(e),n=Uint8Array.from(Zn.default.encode(r.code));return e.length>1&&e[1]!=null&&(n=ye([n,e[1]])),n})))}function uu(t,e){return t.size>0?t.size/8:t.size===0?0:Zn.default.decode(e)+(Zn.default.decode.bytes??0)}function so(t){let e=[],r=0;for(;r<t.length;){let n=Zn.default.decode(t,r),i=Zn.default.decode.bytes??0,s=pe(n),o=uu(s,t.slice(r+i));if(o===0){e.push([n]),r+=i;continue}let a=t.slice(r+i,r+i+o);if(r+=o+i,r>t.length)throw xh("Invalid address Uint8Array: "+$(t,"base16"));e.push([n,a])}return e}function fu(t){let e=so(t),r=au(e);return Cx(r)}function Tx(t){t=lu(t);let e=Ax(t),r=Dx(e);return cu(r)}function mh(t){return Tx(t)}function oo(t){let e=Bx(t);if(e!=null)throw e;return Uint8Array.from(t)}function Bx(t){try{so(t)}catch(e){return e}}function lu(t){return"/"+t.trim().split("/").filter(e=>e).join("/")}function xh(t){return new Error("Error parsing address: "+t)}function ao(t){return pe(t[0])}var hu=G(no(),1);var Ar=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},ei=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},Yi,Ji,Zi,Wr,wh,kx=Symbol.for("nodejs.util.inspect.custom"),Lx=[pe("dns").code,pe("dns4").code,pe("dns6").code,pe("dnsaddr").code],Nx=new Map,vh=Symbol.for("@multiformats/js-multiaddr/multiaddr");function Rx(t){return!!t?.[vh]}var Cr=class{constructor(e){if(Yi.set(this,void 0),Ji.set(this,void 0),Zi.set(this,void 0),Wr.set(this,void 0),this[wh]=!0,e==null&&(e=""),e instanceof Uint8Array)this.bytes=oo(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);this.bytes=mh(e)}else if(Rx(e))this.bytes=oo(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr")}toString(){return Ar(this,Yi,"f")==null&&ei(this,Yi,fu(this.bytes),"f"),Ar(this,Yi,"f")}toJSON(){return this.toString()}toOptions(){let e,r,n,i,s="",o=pe("tcp"),a=pe("udp"),c=pe("ip4"),u=pe("ip6"),f=pe("dns6"),l=pe("ip6zone");for(let[p,d]of this.stringTuples())p===l.code&&(s=`%${d??""}`),Lx.includes(p)&&(r=o.name,i=443,n=`${d??""}${s}`,e=p===f.code?6:4),(p===o.code||p===a.code)&&(r=pe(p).name,i=parseInt(d??"")),(p===c.code||p===u.code)&&(r=pe(p).name,n=`${d??""}${s}`,e=p===u.code?6:4);if(e==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:e,host:n,transport:r,port:i}}protos(){return this.protoCodes().map(e=>Object.assign({},pe(e)))}protoCodes(){let e=[],r=this.bytes,n=0;for(;n<r.length;){let i=hu.default.decode(r,n),s=hu.default.decode.bytes??0,o=pe(i),a=uu(o,r.slice(n+s));n+=a+s,e.push(i)}return e}protoNames(){return this.protos().map(e=>e.name)}tuples(){return Ar(this,Ji,"f")==null&&ei(this,Ji,so(this.bytes),"f"),Ar(this,Ji,"f")}stringTuples(){return Ar(this,Zi,"f")==null&&ei(this,Zi,au(this.tuples()),"f"),Ar(this,Zi,"f")}encapsulate(e){return e=new Cr(e),new Cr(this.toString()+e.toString())}decapsulate(e){let r=e.toString(),n=this.toString(),i=n.lastIndexOf(r);if(i<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new Cr(n.slice(0,i))}decapsulateCode(e){let r=this.tuples();for(let n=r.length-1;n>=0;n--)if(r[n][0]===e)return new Cr(cu(r.slice(0,n)));return this}getPeerId(){try{let r=this.stringTuples().filter(n=>n[0]===Xi.ipfs.code).pop();if(r?.[1]!=null){let n=r[1];return n[0]==="Q"||n[0]==="1"?$(Fe.decode(`z${n}`),"base58btc"):$(xe.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){if(Ar(this,Wr,"f")===void 0)try{ei(this,Wr,this.stringTuples().filter(e=>pe(e[0]).path===!0)[0][1],"f"),Ar(this,Wr,"f")==null&&ei(this,Wr,null,"f")}catch{ei(this,Wr,null,"f")}return Ar(this,Wr,"f")}equals(e){return qe(this.bytes,e.bytes)}async resolve(e){let r=this.protos().find(s=>s.resolvable);if(r==null)return[this];let n=Nx.get(r.name);if(n==null)throw new ee(`no available resolver for ${r.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>new Cr(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let r=(e??this).protos();return!(r.length!==2||r[0].code!==4&&r[0].code!==41||r[1].code!==6&&r[1].code!==273)}[(Yi=new WeakMap,Ji=new WeakMap,Zi=new WeakMap,Wr=new WeakMap,wh=vh,kx)](){return`Multiaddr(${fu(this.bytes)})`}};function Qn(t){return new Cr(t)}var kt;(function(t){t.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",t.ERR_DATA_CHANNEL="ERR_DATA_CHANNEL",t.ERR_CONNECTION_CLOSED="ERR_CONNECTION_CLOSED",t.ERR_HASH_NOT_SUPPORTED="ERR_HASH_NOT_SUPPORTED",t.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",t.ERR_INVALID_FINGERPRINT="ERR_INVALID_FINGERPRINT",t.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",t.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",t.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",t.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS"})(kt||(kt={}));var jr=class extends ee{constructor(e,r){super(`WebRTC transport error: ${e}`,r??""),this.name="WebRTCTransportError"}};var du=class extends jr{constructor(e,r){super(`[stream: ${e}] data channel error: ${r}`,kt.ERR_DATA_CHANNEL),this.name="WebRTC/DataChannelError"}};function xu(t,e){return new du(t,e)}var pu=class extends jr{constructor(e){super(`There was a problem with the Multiaddr which was passed in: ${e}`,kt.ERR_INVALID_MULTIADDR),this.name="WebRTC/InappropriateMultiaddrError"}};function ti(t){return new pu(t)}var yu=class extends jr{constructor(e){super(`There was a problem with a provided argument: ${e}`,kt.ERR_INVALID_PARAMETERS),this.name="WebRTC/InvalidArgumentError"}};function Qi(t){return new yu(t)}var gu=class extends jr{constructor(e,r){super(`Invalid fingerprint "${e}" within ${r}`,kt.ERR_INVALID_FINGERPRINT),this.name="WebRTC/InvalidFingerprintError"}};function wu(t,e){return new gu(t,e)}var bu=class extends jr{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`,kt.ERR_NOT_IMPLEMENTED),this.name="WebRTC/UnimplementedError"}};function Eh(t){return new bu(t)}var mu=class extends jr{constructor(e){super(`unsupported hash algorithm: ${e}`,kt.ERR_HASH_NOT_SUPPORTED),this.name="WebRTC/UnsupportedHashAlgorithmError"}};function Sh(t){return new mu(t)}var co=async function*(){},uo=async t=>{},_h=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Ah=t=>[...Array(t)].map(()=>_h.at(Math.floor(Math.random()*_h.length))).join("");var Ch=lt("libp2p:webrtc:connection"),ln=class{peerConnection;remoteAddr;timeline;source=co();sink=uo;constructor(e){this.remoteAddr=e.remoteAddr,this.timeline=e.timeline,this.peerConnection=e.peerConnection}async close(e){e!==void 0&&Ch.error("error closing connection",e),Ch.trace("closing connection"),this.timeline.close=Date.now(),this.peerConnection.close()}};var es=class extends Error{constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Dh(t){if(t!=null){if(typeof t[Symbol.iterator]=="function")return t[Symbol.iterator]();if(typeof t[Symbol.asyncIterator]=="function")return t[Symbol.asyncIterator]();if(typeof t.next=="function")return t}throw new Error("argument is not an iterator or iterable")}function Th(t,e,r){let n=r??{},i=Dh(t);async function*s(){let o,a=()=>{o?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:f,abortCode:l}=n;throw new es(f,l)}let u=new Promise((f,l)=>{o=()=>{let{abortMessage:h,abortCode:p}=n;l(new es(h,p))}});c=await Promise.race([u,i.next()]),o=null}catch(u){e.removeEventListener("abort",a);let f=u.type==="aborted"&&e.aborted;if(f&&n.onAbort!=null&&await n.onAbort(t),typeof i.return=="function")try{let l=i.return();l instanceof Promise&&l.catch(h=>{n.onReturnError!=null&&n.onReturnError(h)})}catch(l){n.onReturnError!=null&&n.onReturnError(l)}if(f&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return s()}function Ox(t,e,r){return n=>t(Th(n,e,r))}function vu(t,e,r){return{sink:Ox(t.sink,e,{...r,onAbort:void 0}),source:Th(t.source,e,r)}}var Ih=Symbol.for("@achingbrain/uint8arraylist");function Bh(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(let n of t){let i=r+n.byteLength;if(e<i)return{buf:n,index:e-r};r=i}throw new RangeError("index is out of bounds")}function fo(t){return!!t?.[Ih]}var me=class{constructor(...e){Object.defineProperty(this,Ih,{value:!0}),this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let r=0;for(let n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(fo(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(...e){this.prependAll(e)}prependAll(e){let r=0;for(let n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(fo(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(e){let r=Bh(this.bufs,e);return r.buf[r.index]}set(e,r){let n=Bh(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(fo(e))for(let n=0;n<e.length;n++)this.set(r+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,r){let{bufs:n,length:i}=this._subList(e,r);return ye(n,i)}subarray(e,r){let{bufs:n,length:i}=this._subList(e,r);return n.length===1?n[0]:ye(n,i)}sublist(e,r){let{bufs:n,length:i}=this._subList(e,r),s=new me;return s.length=i,s.bufs=n,s}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],i=0;for(let s=0;s<this.bufs.length;s++){let o=this.bufs[s],a=i,c=a+o.byteLength;if(i=c,e>=c)continue;let u=e>=a&&e<c,f=r>a&&r<=c;if(u&&f){if(e===a&&r===c){n.push(o);break}let l=e-a;n.push(o.subarray(l,l+(r-e)));break}if(u){if(e===0){n.push(o);continue}n.push(o.subarray(e-a));continue}if(f){if(r===c){n.push(o);break}n.push(o.subarray(0,r-a));break}n.push(o)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!fo(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.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 s=256,o=new Int32Array(s);for(let l=0;l<s;l++)o[l]=-1;for(let l=0;l<i;l++)o[n[l]]=l;let a=o,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=r;l<=c;l+=f){f=0;for(let h=u;h>=0;h--){let p=this.get(l+h);if(n[h]!==p){f=Math.max(1,h-a[p]);break}}if(f===0)return l}return-1}getInt8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){let n=mt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){let i=_r(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,r,n),this.write(i,e)}getInt32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){let i=_r(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,r,n),this.write(i,e)}getBigInt64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){let i=_r(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,r,n),this.write(i,e)}getUint8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){let n=mt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){let i=_r(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,r,n),this.write(i,e)}getUint32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){let i=_r(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,r,n),this.write(i,e)}getBigUint64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){let i=_r(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,r,n),this.write(i,e)}getFloat32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){let i=_r(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,r,n),this.write(i,e)}getFloat64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){let i=_r(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,r,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof me)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!qe(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){let n=new me;return n.bufs=e,r==null&&(r=e.reduce((i,s)=>i+s.byteLength,0)),n.length=r,n}};function lo(t){return t instanceof Uint8Array?{get(e){return t[e]},set(e,r){t[e]=r}}:{get(e){return t.get(e)},set(e,r){t.set(e,r)}}}var kh=4294967296,_t=class{constructor(e=0,r=0){this.hi=e,this.lo=r}toBigInt(e){if(e===!0)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)}toNumber(e){return Number(this.toBigInt(e))}zzDecode(){let e=-(this.lo&1),r=((this.lo>>>1|this.hi<<31)^e)>>>0,n=(this.hi>>>1^e)>>>0;return new _t(n,r)}zzEncode(){let e=this.hi>>31,r=((this.hi<<1|this.lo>>>31)^e)>>>0,n=(this.lo<<1^e)>>>0;return new _t(r,n)}toBytes(e,r=0){let n=lo(e);for(;this.hi>0;)n.set(r++,this.lo&127|128),this.lo=(this.lo>>>7|this.hi<<25)>>>0,this.hi>>>=7;for(;this.lo>127;)n.set(r++,this.lo&127|128),this.lo=this.lo>>>7;n.set(r++,this.lo)}static fromBigInt(e){if(e===0n)return new _t;let r=e<0;r&&(e=-e);let n=Number(e>>32n)|0,i=Number(e-(BigInt(n)<<32n))|0;return r&&(n=~n>>>0,i=~i>>>0,++i>kh&&(i=0,++n>kh&&(n=0))),new _t(n,i)}static fromNumber(e){if(e===0)return new _t;let r=e<0;r&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new _t(i,n)}static fromBytes(e,r=0){let n=lo(e),i=new _t,s=0;if(e.length-r>4){for(;s<4;++s)if(i.lo=(i.lo|(n.get(r)&127)<<s*7)>>>0,n.get(r++)<128)return i;if(i.lo=(i.lo|(n.get(r)&127)<<28)>>>0,i.hi=(i.hi|(n.get(r)&127)>>4)>>>0,n.get(r++)<128)return i;s=0}else for(;s<4;++s){if(r>=e.length)throw RangeError(`index out of range: ${r} > ${e.length}`);if(i.lo=(i.lo|(n.get(r)&127)<<s*7)>>>0,n.get(r++)<128)return i}if(e.length-r>4){for(;s<5;++s)if(i.hi=(i.hi|(n.get(r)&127)<<s*7+3)>>>0,n.get(r++)<128)return i}else if(r<e.byteLength)for(;s<5;++s){if(r>=e.length)throw RangeError(`index out of range: ${r} > ${e.length}`);if(i.hi=(i.hi|(n.get(r)&127)<<s*7+3)>>>0,n.get(r++)<128)return i}throw RangeError("invalid varint encoding")}};var Px=Math.pow(2,7),Ux=Math.pow(2,14),Fx=Math.pow(2,21),Mx=Math.pow(2,28),Kx=Math.pow(2,35),Vx=Math.pow(2,42),qx=Math.pow(2,49),Hx=Math.pow(2,56),zx=Math.pow(2,63),Ne={encodingLength(t){return t<Px?1:t<Ux?2:t<Fx?3:t<Mx?4:t<Kx?5:t<Vx?6:t<qx?7:t<Hx?8:t<zx?9:10},encode(t,e,r=0){if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return e==null&&(e=mt(Ne.encodingLength(t))),_t.fromNumber(t).toBytes(e,r),e},decode(t,e=0){return _t.fromBytes(t,e).toNumber(!0)}};function ho(t){return t[Symbol.asyncIterator]!=null}var po=t=>{let e=Ne.encodingLength(t),r=mt(e);return Ne.encode(t,r),po.bytes=e,r};po.bytes=0;function yo(t,e){e=e??{};let r=e.lengthEncoder??po;function*n(i){let s=r(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return ho(t)?async function*(){for await(let i of t)yield*n(i)}():function*(){for(let i of t)yield*n(i)}()}yo.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??po;return new me(r(t.byteLength),t)};var ni=G(ri(),1);var Wx=8,jx=1024*1024*4,hn;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(hn||(hn={}));var Su=t=>{let e=Ne.decode(t);return Su.bytes=Ne.encodingLength(e),e};Su.bytes=0;function Eu(t,e){let r=new me,n=hn.LENGTH,i=-1,s=e?.lengthDecoder??Su,o=e?.maxLengthLength??Wx,a=e?.maxDataLength??jx;function*c(){for(;r.byteLength>0;){if(n===hn.LENGTH)try{if(i=s(r),i<0)throw(0,ni.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,ni.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=hn.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>o)throw(0,ni.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===hn.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=hn.LENGTH}}}return ho(t)?async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,ni.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,ni.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Eu.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:s,value:o}=await t.next(r);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}}();return Eu(n,{...e??{},onLength:s=>{r=s}})};var go=class{constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},ii=class{constructor(e={}){this.hwm=e.splitLimit??16,this.head=new go(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new go(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};function xt(t={}){return Xx(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}},t)}function Xx(t,e){e=e??{};let r=e.onEnd,n=new ii,i,s,o,a=async()=>n.isEmpty()?o?{done:!0}:await new Promise((y,g)=>{s=b=>{s=null,n.push(b);try{y(t(n))}catch(v){g(v)}return i}}):t(n),c=y=>s!=null?s(y):(n.push(y),i),u=y=>(n=new ii,s!=null?s({error:y}):(n.push({error:y}),i)),f=y=>{if(o)return i;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:y})},l=y=>o?i:(o=!0,y!=null?u(y):c({done:!0})),h=()=>(n=new ii,l(),{done:!0}),p=y=>(l(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:a,return:h,throw:p,push:f,end:l,get readableLength(){return n.size}},r==null)return i;let d=i;return i={[Symbol.asyncIterator](){return this},next(){return d.next()},throw(y){return d.throw(y),r!=null&&(r(y),r=void 0),{done:!0}},return(){return d.return(),r!=null&&(r(),r=void 0),{done:!0}},push:f,end(y){return d.end(y),r!=null&&(r(y),r=void 0),i},get readableLength(){return d.readableLength}},i}var bo=G(ri(),1),Rh=t=>Ne.decode(t);Rh.bytes=0;function _u(t,e){let r=xt();t.sink(r).catch(o=>{r.end(o)}),t.sink=async o=>{for await(let a of o)r.push(a);r.end()};let n=t.source;t.source[Symbol.iterator]!=null?n=t.source[Symbol.iterator]():t.source[Symbol.asyncIterator]!=null&&(n=t.source[Symbol.asyncIterator]());let i=new me,s={read:async o=>{if(o==null){let{done:c,value:u}=await n.next();return c===!0?new me:u}for(;i.byteLength<o;){let{value:c,done:u}=await n.next();if(u===!0)throw(0,bo.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF");i.append(c)}let a=i.sublist(0,o);return i.consume(o),a},readLP:async()=>{let o=-1,a=new me,c=e?.lengthDecoder??Rh;for(;;){a.append(await s.read(1));try{o=c(a)}catch(u){if(u instanceof RangeError)continue;throw u}if(o>-1)break;if(e?.maxLengthLength!=null&&a.byteLength>e.maxLengthLength)throw(0,bo.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG")}if(e?.maxDataLength!=null&&o>e.maxDataLength)throw(0,bo.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");return await s.read(o)},readPB:async o=>{let a=await s.readLP();if(a==null)throw new Error("Value is null");let c=a instanceof Uint8Array?a:a.subarray();return o.decode(c)},write:o=>{o instanceof Uint8Array?r.push(o):r.push(o.subarray())},writeLP:o=>{s.write(yo.single(o,e))},writePB:(o,a)=>{s.writeLP(a.encode(o))},pb:o=>({read:async()=>await s.readPB(o),write:a=>{s.writePB(a,o)},unwrap:()=>s}),unwrap:()=>{let o=t.source;return t.source=async function*(){yield*i,yield*o}(),t}};return s}function nr(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}function Oh(t){return globalThis?.Buffer?.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}var mo=t=>{let e=Ne.encodingLength(t),r=Oh(e);return Ne.encode(t,r),mo.bytes=e,r};mo.bytes=0;function ts(t){t=t??{};let e=t.lengthEncoder??mo;return async function*(n){for await(let i of n){let s=e(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}}}ts.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??mo;return new me(r(t.byteLength),t)};var rs=G(ri(),1),Yx=8,Jx=1024*1024*4,dn;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(dn||(dn={}));var Au=t=>{let e=Ne.decode(t);return Au.bytes=Ne.encodingLength(e),e};Au.bytes=0;function pn(t){return async function*(r){let n=new me,i=dn.LENGTH,s=-1,o=t?.lengthDecoder??Au,a=t?.maxLengthLength??Yx,c=t?.maxDataLength??Jx;for await(let u of r)for(n.append(u);n.byteLength>0;){if(i===dn.LENGTH)try{if(s=o(n),s<0)throw(0,rs.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>c)throw(0,rs.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let f=o.bytes;n.consume(f),t?.onLength!=null&&t.onLength(s),i=dn.DATA}catch(f){if(f instanceof RangeError){if(n.byteLength>a)throw(0,rs.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw f}if(i===dn.DATA){if(n.byteLength<s)break;let f=n.sublist(0,s);n.consume(s),t?.onData!=null&&t.onData(f),yield f,i=dn.LENGTH}}if(n.byteLength>0)throw(0,rs.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}}pn.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:s,value:o}=await t.next(r);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}}();return pn({...e??{},onLength:s=>{r=s}})(n)};function Qx(t){return t[Symbol.asyncIterator]!=null}function ew(...t){let e=[];for(let r of t)Qx(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=xt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(t.map(async n=>{for await(let i of n)r.push(i)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var xo=ew;function Ph(t,...e){if(t==null)throw new Error("Empty pipeline");if(Cu(t)){let n=t;t=()=>n.source}else if(Fh(t)||Uh(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&Cu(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++)Cu(r[n])&&(r[n]=rw(r[n]));return tw(...r)}var tw=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},Uh=t=>t?.[Symbol.asyncIterator]!=null,Fh=t=>t?.[Symbol.iterator]!=null,Cu=t=>t==null?!1:t.sink!=null&&t.source!=null,rw=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=xt({objectMode:!0});r.then(()=>{n.end()},o=>{n.end(o)});let i,s=t.source;if(Uh(s))i=async function*(){yield*s,n.end()};else if(Fh(s))i=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return xo(n,i())}return t.source};var Zu=G(pi(),1),Qu=G(pi(),1),yd=G(pi(),1),gd=G(pi(),1),bd=G(pi(),1),ht;(function(t){t[t.FIN=0]="FIN",t[t.STOP_SENDING=1]="STOP_SENDING",t[t.RESET=2]="RESET"})(ht||(ht={}));var ef=class extends bd.MessageType{constructor(){super("webrtc.pb.Message",[{no:1,name:"flag",kind:"enum",opt:!0,T:()=>["webrtc.pb.Message.Flag",ht]},{no:2,name:"message",kind:"scalar",opt:!0,T:12}])}create(e){let r={};return globalThis.Object.defineProperty(r,gd.MESSAGE_TYPE,{enumerable:!1,value:this}),e!==void 0&&(0,yd.reflectionMergePartial)(this,r,e),r}internalBinaryRead(e,r,n,i){let s=i??this.create(),o=e.pos+r;for(;e.pos<o;){let[a,c]=e.tag();switch(a){case 1:s.flag=e.int32();break;case 2:s.message=e.bytes();break;default:let u=n.readUnknownField;if(u==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${c}) for ${this.typeName}`);let f=e.skip(c);u!==!1&&(u===!0?Qu.UnknownFieldHandler.onRead:u)(this.typeName,s,a,c,f)}}return s}internalBinaryWrite(e,r,n){e.flag!==void 0&&r.tag(1,Zu.WireType.Varint).int32(e.flag),e.message!==void 0&&r.tag(2,Zu.WireType.LengthDelimited).bytes(e.message);let i=n.writeUnknownFields;return i!==!1&&(i==!0?Qu.UnknownFieldHandler.onWrite:i)(this.typeName,e,r),r}},Jo=new ef;var tf=lt("libp2p:webrtc:stream");var Y;(function(t){t[t.OPEN=0]="OPEN",t[t.READ_CLOSED=1]="READ_CLOSED",t[t.WRITE_CLOSED=2]="WRITE_CLOSED",t[t.CLOSED=3]="CLOSED"})(Y||(Y={}));function Zo(t){throw new Error("Case not handled in switch")}var rf=class{state=Y.OPEN;isWriteClosed(){return this.state===Y.CLOSED||this.state===Y.WRITE_CLOSED}transition({direction:e,flag:r}){let n=this.state;if(this.state===Y.CLOSED)return[n,Y.CLOSED];if(e==="inbound")switch(r){case ht.FIN:this.state===Y.OPEN?this.state=Y.READ_CLOSED:this.state===Y.WRITE_CLOSED&&(this.state=Y.CLOSED);break;case ht.STOP_SENDING:this.state===Y.OPEN?this.state=Y.WRITE_CLOSED:this.state===Y.READ_CLOSED&&(this.state=Y.CLOSED);break;case ht.RESET:this.state=Y.CLOSED;break;default:Zo(r)}else switch(r){case ht.FIN:this.state===Y.OPEN?this.state=Y.WRITE_CLOSED:this.state===Y.READ_CLOSED&&(this.state=Y.CLOSED);break;case ht.STOP_SENDING:this.state===Y.OPEN?this.state=Y.READ_CLOSED:this.state===Y.WRITE_CLOSED&&(this.state=Y.CLOSED);break;case ht.RESET:this.state=Y.CLOSED;break;default:Zo(r)}return[n,this.state]}},Ht=class{id;stat;metadata;channel;streamState=new rf;_src;_innersrc=xt();opened=nr();_sinkCalled=!1;closeWritePromise=nr();closeCb;constructor(e){switch(this.channel=e.channel,this.channel.binaryType="arraybuffer",this.id=this.channel.label,this.stat=e.stat,this.channel.readyState){case"open":this.opened.resolve();break;case"closed":case"closing":this.streamState.state=Y.CLOSED,(this.stat.timeline.close===void 0||this.stat.timeline.close===0)&&(this.stat.timeline.close=new Date().getTime()),this.opened.resolve();break;case"connecting":break;default:Zo(this.channel.readyState)}this.metadata=e.metadata??{},this.channel.onopen=n=>{this.stat.timeline.open=new Date().getTime(),this.opened.resolve()},this.channel.onclose=n=>{this.close()},this.channel.onerror=n=>{let i=n.error;this.abort(i)};let r=this;this.channel.onmessage=async({data:n})=>{n===null||n.length===0||this._innersrc.push(new Uint8Array(n))},this._src=Ph(this._innersrc,pn(),n=>async function*(){for await(let i of n){let s=r.processIncomingProtobuf(i.subarray());s!=null&&(yield new me(s))}}())}set source(e){}get source(){return this._src}async sink(e){if(this._sinkCalled)throw new Error("sink already called on this stream");await this.opened.promise;try{await this._sink(e)}finally{this.closeWrite()}}async _sink(e){let r=this._closeWriteIterable();for await(let n of xo(r,e)){if(this.streamState.isWriteClosed())return;let i=Jo.toBinary({message:n.subarray()}),s=ts.single(i);this.channel.send(s.subarray())}}processIncomingProtobuf(e){let r=Jo.fromBinary(e);if(r.flag!==void 0){let[n,i]=this.streamState.transition({direction:"inbound",flag:r.flag});if(n!==i)switch(i){case Y.READ_CLOSED:this._innersrc.end();break;case Y.WRITE_CLOSED:this.closeWritePromise.resolve();break;case Y.CLOSED:this.close();break;case Y.OPEN:break;default:Zo(i)}}return r.message}close(){this.stat.timeline.close=new Date().getTime(),this.streamState.state=Y.CLOSED,this._innersrc.end(),this.closeWritePromise.resolve(),this.channel.close(),this.closeCb!==void 0&&this.closeCb(this)}closeRead(){let[e,r]=this.streamState.transition({direction:"outbound",flag:ht.STOP_SENDING});e!==r&&((e===Y.OPEN||e===Y.WRITE_CLOSED)&&(this._sendFlag(ht.STOP_SENDING),this._innersrc.end()),r===Y.CLOSED&&this.close())}closeWrite(){let[e,r]=this.streamState.transition({direction:"outbound",flag:ht.FIN});e!==r&&((e===Y.OPEN||e===Y.READ_CLOSED)&&(this._sendFlag(ht.FIN),this.closeWritePromise.resolve()),r===Y.CLOSED&&this.close())}abort(e){tf.error(`An error occurred, closing the stream for reading and writing: ${e.message}`),this.close()}reset(){let[e,r]=this.streamState.transition({direction:"outbound",flag:ht.RESET});e!==r&&(this._sendFlag(ht.RESET),this.close())}_sendFlag(e){try{tf.trace("Sending flag: %s",e.toString());let r=Jo.toBinary({flag:e});this.channel.send(ts.single(r).subarray())}catch(r){r instanceof Error&&tf.error(`Exception while sending flag ${e}: ${r.message}`)}}_closeWriteIterable(){let e=this;return{async*[Symbol.asyncIterator](){await e.closeWritePromise.promise,yield new Uint8Array(0)}}}eq(e){return e instanceof Ht?e.channel.id===this.channel.id:!1}};var bn=class{protocol;peerConnection;streamBuffer=[];constructor(e,r="/webrtc"){this.protocol=r,this.peerConnection=e,this.peerConnection.ondatachannel=({channel:n})=>{let i=new Ht({channel:n,stat:{direction:"inbound",timeline:{open:0}},closeCb:s=>{this.streamBuffer=this.streamBuffer.filter(o=>!s.eq(o))}});this.streamBuffer.push(i)}}createStreamMuxer(e){return new nf(this.peerConnection,this.streamBuffer,this.protocol,e)}},nf=class{protocol;peerConnection;streams=[];init;close=()=>{};source=co();sink=uo;constructor(e,r,n="/webrtc",i){this.protocol=n,this.init=i,this.peerConnection=e,this.peerConnection.ondatachannel=({channel:o})=>{let a=new Ht({channel:o,stat:{direction:"inbound",timeline:{open:0}},closeCb:this.wrapStreamEnd(i?.onIncomingStream)});this.streams.push(a),i?.onIncomingStream!=null&&i.onIncomingStream(a)},this.streams=r.filter(o=>o.stat.timeline.close==null).map(o=>(o.closeCb=this.wrapStreamEnd(i?.onStreamEnd),o));let s=i?.onIncomingStream;s!=null&&this.streams.forEach(o=>{s(o)})}newStream(){let e=this.peerConnection.createDataChannel(""),r=new Ht({channel:e,stat:{direction:"outbound",timeline:{open:0}},closeCb:this.wrapStreamEnd(this.init?.onStreamEnd)});return this.streams.push(r),r}wrapStreamEnd(e){let r=this;return n=>{r.streams=r.streams.filter(i=>!(n instanceof Ht&&n.eq(i))),e?.(n)}}};var bf=G(uf(),1),ip=G(Yd(),1),sp=G(xn(),1),mf=G(gf(),1),op=G(np(),1);function Kv(){sp.default._configure(),bf.default._configure(ip.default),mf.default._configure(op.default)}Kv();var ap=["uint64","int64","sint64","fixed64","sfixed64"];function Vv(t){for(let e of ap){if(t[e]==null)continue;let r=t[e];t[e]=function(){return BigInt(r.call(this).toString())}}return t}function xf(t){return Vv(new bf.default(t))}function qv(t){for(let e of ap){if(t[e]==null)continue;let r=t[e];t[e]=function(n){return r.call(this,n.toString())}}return t}function wf(){return qv(mf.default.create())}function Br(t,e){let r=xf(t instanceof Uint8Array?t:t.subarray());return e.decode(r)}function Ir(t,e){let r=wf();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var gi;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(gi||(gi={}));function na(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function ps(t){function e(i){if(t[i.toString()]==null)throw new Error("Invalid enum value");return t[i]}let r=function(s,o){let a=e(s);o.int32(a)},n=function(s){let o=s.int32();return e(o)};return na("enum",gi.VARINT,r,n)}function kr(t,e){return na("message",gi.LENGTH_DELIMITED,t,e)}var Ct;(function(t){let e;(function(i){i.SDP_OFFER="SDP_OFFER",i.SDP_ANSWER="SDP_ANSWER",i.ICE_CANDIDATE="ICE_CANDIDATE"})(e=t.Type||(t.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=()=>ps(r)}(e=t.Type||(t.Type={}));let n;t.codec=()=>(n==null&&(n=kr((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),t.Type.codec().encode(i.type,s)),i.data!=null&&(s.uint32(18),s.string(i.data)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=t.Type.codec().decode(i);break;case 2:o.data=i.string();break;default:i.skipType(c&7);break}}return o})),n),t.encode=i=>Ir(i,t.codec()),t.decode=i=>Br(i,t.codec())})(Ct||(Ct={}));var Ep=G(wp(),1);var vp=(0,Ep.detect)(),sa=vp!=null&&vp.name==="firefox",ia=lt("libp2p:webrtc:peer:util"),Ef=async(t,e,r)=>{for(;;){let n=await Promise.race([t.promise,r.read()]);if(n instanceof Object){let i=n;if(i.type!==Ct.Type.ICE_CANDIDATE)throw new Error("expected only ice candidates");if(i.data==null||i.data===""){ia.trace("end-of-candidates received");break}ia.trace("received new ICE candidate: %s",i.data);try{await e.addIceCandidate(new RTCIceCandidate(JSON.parse(i.data)))}catch(s){throw ia.error("bad candidate received: ",s),new Error("bad candidate received")}}else break}await t.promise};function Sf(t,e){t[sa?"oniceconnectionstatechange":"onconnectionstatechange"]=r=>{switch(ia.trace("receiver peerConnectionState state: ",t.connectionState),sa?t.iceConnectionState:t.connectionState){case"connected":e.resolve();break;case"failed":case"disconnected":case"closed":e.reject();break;default:break}}}var Xv=30*1e3,bi=lt("libp2p:webrtc:peer");async function Sp({rtcConfiguration:t,stream:e}){let r=AbortSignal.timeout(Xv),n=_u(vu(e,r)).pb(Ct),i=new RTCPeerConnection(t),s=new bn(i),o=nr(),a=nr();r.onabort=()=>{o.reject()},i.onicecandidate=({candidate:l})=>{a.promise.then(()=>{n.write({type:Ct.Type.ICE_CANDIDATE,data:l!=null?JSON.stringify(l.toJSON()):""})},h=>{bi.error("cannot set candidate since sending answer failed",h)})},Sf(i,o);let c=await n.read();if(c.type!==Ct.Type.SDP_OFFER)throw new Error(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);let u=new RTCSessionDescription({type:"offer",sdp:c.data});await i.setRemoteDescription(u).catch(l=>{throw bi.error("could not execute setRemoteDescription",l),new Error("Failed to set remoteDescription")});let f=await i.createAnswer().catch(l=>{throw bi.error("could not execute createAnswer",l),a.reject(l),new Error("Failed to create answer")});return n.write({type:Ct.Type.SDP_ANSWER,data:f.sdp}),await i.setLocalDescription(f).catch(l=>{throw bi.error("could not execute setLocalDescription",l),a.reject(l),new Error("Failed to set localDescription")}),a.resolve(),await Ef(o,i,n),[i,s]}async function _p({rtcConfiguration:t,signal:e,stream:r}){let n=_u(vu(r,e)).pb(Ct),i=new RTCPeerConnection(t),s=new bn(i),o=nr();Sf(i,o),e.onabort=o.reject;let a=i.createDataChannel("init");i.onicecandidate=({candidate:l})=>{n.write({type:Ct.Type.ICE_CANDIDATE,data:l!=null?JSON.stringify(l.toJSON()):""})};let c=await i.createOffer();n.write({type:Ct.Type.SDP_OFFER,data:c.sdp}),await i.setLocalDescription(c).catch(l=>{throw bi.error("could not execute setLocalDescription",l),new Error("Failed to set localDescription")});let u=await n.read();if(u.type!==Ct.Type.SDP_ANSWER)throw new Error("remote should send an SDP answer");let f=new RTCSessionDescription({type:"answer",sdp:u.data});return await i.setRemoteDescription(f).catch(l=>{throw bi.error("could not execute setRemoteDescription",l),new Error("Failed to set remoteDescription")}),await Ef(o,i,n),a.close(),[i,s]}var oa=class extends EventTarget{#e=new Map;listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){super.addEventListener(e,r,n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:r,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,r,n){super.removeEventListener(e.toString(),r??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:s})=>s!==r),this.#e.set(e,i))}dispatchEvent(e){let r=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:i})=>!i),this.#e.set(e.type,n)),r}safeDispatchEvent(e,r){return this.dispatchEvent(new Yv(e,r))}},_f=class extends Event{detail;constructor(e,r){super(e,r),this.detail=r?.detail}},Yv=globalThis.CustomEvent??_f;var aa=class extends oa{opts;constructor(e){super(),this.opts=e}getBaseAddress(e){let r=e.toString().split(ys);if(r.length<2)throw ti("base address not found");return Qn(r[0])}listeningAddrs=[];async listen(e){let r=this.getBaseAddress(e),i=this.opts.transportManager.transportForMultiaddr(r)?.createListener({...this.opts});await i?.listen(r);let s=e.encapsulate(`/p2p/${this.opts.peerId.toString()}`);this.listeningAddrs.push(s),i?.addEventListener("close",()=>{this.listeningAddrs=this.listeningAddrs.filter(o=>o!==s)})}getAddrs(){return this.listeningAddrs}async close(){}};var Ap=lt("libp2p:webrtc:peer"),ys="/webrtc",Af="/webrtc-signaling/0.0.1",Jv=pe("webrtc").code,ca=class{components;init;_started=!1;constructor(e,r){this.components=e,this.init=r}isStarted(){return this._started}async start(){await this.components.registrar.handle(Af,e=>{this._onProtocol(e).catch(r=>{Ap.error("failed to handle incoming connect from %p",e.connection.remotePeer,r)})}),this._started=!0}async stop(){await this.components.registrar.unhandle(Af),this._started=!1}createListener(e){return new aa(this.components)}[Symbol.toStringTag]="@libp2p/webrtc";[Xs]=!0;filter(e){return e.filter(r=>r.protoCodes().includes(Jv))}splitAddr(e){let r=e.toString().split(`${ys}/`);if(r.length!==2)throw new ee("invalid multiaddr",kt.ERR_INVALID_MULTIADDR);let n=Qn(r[0]),s=Qn("/"+r[1]).getPeerId();if(s==null)throw new ee("bad destination",kt.ERR_INVALID_MULTIADDR);let o=n.protos().pop();if(o===void 0)throw new ee("invalid multiaddr",kt.ERR_INVALID_MULTIADDR);return o.name!=="p2p"&&(n=n.encapsulate(`/p2p/${s}`)),{baseAddr:n,peerId:$i(s)}}async dial(e,r){Ap.trace("dialing address: ",e);let{baseAddr:n,peerId:i}=this.splitAddr(e);if(r.signal==null){let a=new AbortController;r.signal=a.signal}let o=await(await this.components.transportManager.dial(n)).newStream([Af],r);try{let[a,c]=await _p({stream:o,rtcConfiguration:this.init.rtcConfiguration,signal:r.signal}),u=n.encapsulate(`${ys}/p2p/${i.toString()}`),f=await r.upgrader.upgradeOutbound(new ln({peerConnection:a,timeline:{open:Date.now()},remoteAddr:u}),{skipProtection:!0,skipEncryption:!0,muxerFactory:c});return o.close(),f}catch(a){throw o.reset(),a}}async _onProtocol({connection:e,stream:r}){try{let[n,i]=await Sp({rtcConfiguration:this.init.rtcConfiguration,connection:e,stream:r}),s=e.remoteAddr.getPeerId(),o=e.remoteAddr.encapsulate(`${ys}/p2p/${s}`);await this.components.upgrader.upgradeInbound(new ln({peerConnection:n,timeline:{open:new Date().getTime()},remoteAddr:o}),{skipEncryption:!0,skipProtection:!0,muxerFactory:i})}catch(n){throw r.reset(),n}}};function ua(t){return t[Symbol.asyncIterator]!=null}var fa=t=>{let e=Ne.encodingLength(t),r=mt(e);return Ne.encode(t,r),fa.bytes=e,r};fa.bytes=0;function la(t,e){e=e??{};let r=e.lengthEncoder??fa;function*n(i){let s=r(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return ua(t)?async function*(){for await(let i of t)yield*n(i)}():function*(){for(let i of t)yield*n(i)}()}la.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??fa;return new me(r(t.byteLength),t)};var mi=G(ri(),1);var Zv=8,Qv=1024*1024*4,vn;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(vn||(vn={}));var Df=t=>{let e=Ne.decode(t);return Df.bytes=Ne.encodingLength(e),e};Df.bytes=0;function Cf(t,e){let r=new me,n=vn.LENGTH,i=-1,s=e?.lengthDecoder??Df,o=e?.maxLengthLength??Zv,a=e?.maxDataLength??Qv;function*c(){for(;r.byteLength>0;){if(n===vn.LENGTH)try{if(i=s(r),i<0)throw(0,mi.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,mi.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=vn.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>o)throw(0,mi.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===vn.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=vn.LENGTH}}}return ua(t)?async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,mi.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,mi.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Cf.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:s,value:o}=await t.next(r);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}}();return Cf(n,{...e??{},onLength:s=>{r=s}})};var ha=G(ri(),1),Cp=t=>Ne.decode(t);Cp.bytes=0;function Tf(t,e={}){let r=xt();t.sink(r).catch(o=>{r.end(o)}),t.sink=async o=>{for await(let a of o)r.push(a)};let n=t.source;t.source[Symbol.iterator]!=null?n=t.source[Symbol.iterator]():t.source[Symbol.asyncIterator]!=null&&(n=t.source[Symbol.asyncIterator]());let i=new me,s={read:async o=>{if(o==null){let{done:c,value:u}=await n.next();return c===!0?new me:u}for(;i.byteLength<o;){let{value:c,done:u}=await n.next();if(u===!0)throw(0,ha.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF");i.append(c)}let a=i.sublist(0,o);return i.consume(o),a},readLP:async()=>{let o=-1,a=new me,c=e?.lengthDecoder??Cp;for(;;){a.append(await s.read(1));try{o=c(a)}catch(u){if(u instanceof RangeError)continue;throw u}if(o>-1)break;if(e?.maxLengthLength!=null&&a.byteLength>e.maxLengthLength)throw(0,ha.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG")}if(e?.maxDataLength!=null&&o>e.maxDataLength)throw(0,ha.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");return await s.read(o)},readPB:async o=>{let a=await s.readLP();if(a==null)throw new Error("Value is null");let c=a instanceof Uint8Array?a:a.subarray();return o.decode(c)},write:o=>{o instanceof Uint8Array?r.push(o):r.push(o.subarray())},writeLP:o=>{s.write(la.single(o,e))},writePB:(o,a)=>{s.writeLP(a.encode(o))},pb:o=>({read:async()=>await s.readPB(o),write:a=>{s.writePB(a,o)},unwrap:()=>s}),unwrap:()=>{let o=t.source;return t.source=async function*(){yield*i,yield*o}(),t}};return s}function Bf(){let t=nr(),e=!1;return{sink:async r=>{if(e)throw new Error("already piped");e=!0,t.resolve(r)},source:async function*(){yield*await t.promise}()}}function Dp(){let t=Bf(),e=Bf();return[{source:t.source,sink:e.sink},{source:e.source,sink:t.sink}]}async function*If(...t){let e=xt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(t.map(async r=>{for await(let n of r)e.push(n)})),e.end()}catch(r){e.end(r)}}),yield*e}var t3=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},Tp=t=>t!=null&&(typeof t[Symbol.asyncIterator]=="function"||typeof t[Symbol.iterator]=="function"||typeof t.next=="function"),kf=t=>t!=null&&typeof t.sink=="function"&&Tp(t.source),r3=t=>e=>{let r=t.sink(e);if(r.then!=null){let n=xt({objectMode:!0});return r.then(()=>{n.end()},s=>{n.end(s)}),If(n,async function*(){yield*t.source,n.end()}())}return t.source};function Bp(t,...e){if(kf(t)){let n=t;t=()=>n.source}else if(Tp(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&kf(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++)kf(r[n])&&(r[n]=r3(r[n]));return t3(...r)}var Ip=!!globalThis.process?.env?.DUMP_SESSION_KEYS;var fy=G(Up(),1),wi=G(ty(),1),Ca=G(ny(),1),$f=G(jf(),1),ly={hashSHA256(t){return(0,Ca.hash)(t)},getHKDF(t,e){let i=new fy.HKDF(Ca.SHA256,e,t).expand(96),s=i.subarray(0,32),o=i.subarray(32,64),a=i.subarray(64,96);return[s,o,a]},generateX25519KeyPair(){let t=wi.generateKeyPair();return{publicKey:t.publicKey,privateKey:t.secretKey}},generateX25519KeyPairFromSeed(t){let e=wi.generateKeyPairFromSeed(t);return{publicKey:e.publicKey,privateKey:e.secretKey}},generateX25519SharedKey(t,e){return wi.sharedKey(t,e)},chaCha20Poly1305Encrypt(t,e,r,n){return new $f.ChaCha20Poly1305(n).seal(e,t,r)},chaCha20Poly1305Decrypt(t,e,r,n,i){return new $f.ChaCha20Poly1305(n).open(e,t,r,i)}};var Xf=G(jf(),1);var lE=t=>globalThis.Buffer?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t),vi=t=>{let e=lE(2);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(0,t,!1),e};vi.bytes=2;var vs=t=>{if(t.length<2)throw RangeError("Could not decode int16BE");return t instanceof Uint8Array?new DataView(t.buffer,t.byteOffset,t.byteLength).getUint16(0,!1):t.getUint16(0)};vs.bytes=2;function hy(t){return ye([t.ne,t.ciphertext],t.ne.length+t.ciphertext.length)}function dy(t){return ye([t.ne,t.ns,t.ciphertext],t.ne.length+t.ns.length+t.ciphertext.length)}function py(t){return ye([t.ns,t.ciphertext],t.ns.length+t.ciphertext.length)}function yy(t){if(t.length<32)throw new Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");return{ne:t.subarray(0,32),ciphertext:t.subarray(32,t.length),ns:new Uint8Array(0)}}function gy(t){if(t.length<80)throw new Error("Cannot decode stage 1 MessageBuffer: length less than 80 bytes.");return{ne:t.subarray(0,32),ns:t.subarray(32,80),ciphertext:t.subarray(80,t.length)}}function by(t){if(t.length<48)throw new Error("Cannot decode stage 2 MessageBuffer: length less than 48 bytes.");return{ne:new Uint8Array(0),ns:t.subarray(0,48),ciphertext:t.subarray(48,t.length)}}function xy(t,e){return async function*(r){for await(let n of r)for(let i=0;i<n.length;i+=65519){let s=i+65519;s>n.length&&(s=n.length);let o=t.encrypt(n.subarray(i,s),t.session);e?.encryptedPackets.increment(),yield vi(o.byteLength),yield o}}}function wy(t,e){return async function*(r){for await(let n of r)for(let i=0;i<n.length;i+=65535){let s=i+65535;if(s>n.length&&(s=n.length),s-Xf.TAG_LENGTH<i)throw new Error("Invalid chunk");let o=n.subarray(i,s),a=n.subarray(i,s-Xf.TAG_LENGTH),{plaintext:c,valid:u}=t.decrypt(o,t.session,a);if(!u)throw e?.decryptErrors.increment(),new Error("Failed to validate decrypted chunk");e?.decryptedPackets.increment(),yield c}}}var En=class extends Error{constructor(e="Unexpected Peer"){super(e),this.code=En.code}static get code(){return"ERR_UNEXPECTED_PEER"}},Or=class extends Error{constructor(e="Invalid crypto exchange"){super(e),this.code=Or.code}static get code(){return"ERR_INVALID_CRYPTO_EXCHANGE"}};var hN=G(Cs(),1),dN=G(P1(),1);var E6=G(we(),1);var v0={};Ze(v0,{Ed25519PrivateKey:()=>kn,Ed25519PublicKey:()=>Bs,generateKeyPair:()=>V4,generateKeyPairFromSeed:()=>G1,unmarshalEd25519PrivateKey:()=>M4,unmarshalEd25519PublicKey:()=>K4});var Tn=G(Ge("crypto"),1),U1=Ge("util");var P4=(0,U1.promisify)(Tn.default.generateKeyPair),Bn=32,br=64,Ha=32,U4=64;function F1(t){let r=Tn.default.createPrivateKey({format:"jwk",key:{crv:"Ed25519",x:"",d:$(t,"base64url"),kty:"OKP"}}).export({format:"jwk"});if(r.x==null||r.x==="")throw new Error("Could not export JWK public key");return Ae(r.x,"base64url")}async function M1(){let t=await P4("ed25519",{publicKeyEncoding:{type:"spki",format:"jwk"},privateKeyEncoding:{type:"pkcs8",format:"jwk"}}),e=Ae(t.privateKey.d,"base64url"),r=Ae(t.privateKey.x,"base64url");return{privateKey:H1(e,r),publicKey:r}}async function K1(t){if(t.length!==Ha)throw new TypeError('"seed" must be 32 bytes in length.');if(!(t instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=F1(t);return{privateKey:H1(t,e),publicKey:e}}async function V1(t,e){if(!(t instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');let r,n;if(t.byteLength===br)r=t.subarray(0,32),n=t.subarray(32);else if(t.byteLength===Ha)r=t.subarray(0,32),n=F1(r);else throw new TypeError('"key" must be 64 or 32 bytes in length.');let i=Tn.default.createPrivateKey({format:"jwk",key:{crv:"Ed25519",d:$(r,"base64url"),x:$(n,"base64url"),kty:"OKP"}});return Tn.default.sign(null,e,i)}async function q1(t,e,r){if(t.byteLength!==Bn)throw new TypeError('"key" must be 32 bytes in length.');if(!(t instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');if(e.byteLength!==U4)throw new TypeError('"sig" must be 64 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"sig" must be a node.js Buffer, or Uint8Array.');let n=Tn.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:$(t,"base64url"),kty:"OKP"}});return Tn.default.verify(null,r,n,e)}function H1(t,e){let r=new Uint8Array(br);for(let n=0;n<Ha;n++)r[n]=t[n],r[Ha+n]=e[n];return r}var In=G(Ge("crypto"),1);function x0(t){let e=t?.algorithm??"aes-128-gcm",r=t?.keyLength??16,n=t?.nonceLength??12,i=t?.digest??"sha256",s=t?.saltLength??16,o=t?.iterations??32767,a=t?.algorithmTagLength??16;async function c(p,d){let y=In.default.randomBytes(n),g=In.default.createCipheriv(e,d,y),b=ye([g.update(p),g.final()]);return ye([y,b,g.getAuthTag()])}async function u(p,d){let y=In.default.randomBytes(s);typeof d=="string"&&(d=Ae(d));let g=In.default.pbkdf2Sync(d,y,o,r,i);return ye([y,await c(Uint8Array.from(p),g)])}async function f(p,d){let y=p.subarray(0,n),g=p.subarray(n,p.length-a),b=p.subarray(g.length+n),v=In.default.createDecipheriv(e,d,y);return v.setAuthTag(b),ye([v.update(g),v.final()])}async function l(p,d){let y=p.subarray(0,s),g=p.subarray(s);typeof d=="string"&&(d=Ae(d));let b=In.default.pbkdf2Sync(d,y,o,r,i);return f(g,b)}return{encrypt:u,decrypt:l}}async function Ci(t,e){let n=await x0().encrypt(t,e);return Gn.encode(n)}var Le;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.Secp256k1="Secp256k1"})(Le||(Le={}));var w0;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.Secp256k1=2]="Secp256k1"})(w0||(w0={}));(function(t){t.codec=()=>ps(w0)})(Le||(Le={}));var mr;(function(t){let e;t.codec=()=>(e==null&&(e=kr((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),Le.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.Type=Le.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Ir(r,t.codec()),t.decode=r=>Br(r,t.codec())})(mr||(mr={}));var xr;(function(t){let e;t.codec=()=>(e==null&&(e=kr((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),Le.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.Type=Le.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Ir(r,t.codec()),t.decode=r=>Br(r,t.codec())})(xr||(xr={}));var Bs=class{_key;constructor(e){this._key=Di(e,Bn)}async verify(e,r){return q1(this._key,r,e)}marshal(){return this._key}get bytes(){return mr.encode({Type:Le.Ed25519,Data:this.marshal()}).subarray()}equals(e){return qe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}},kn=class{_key;_publicKey;constructor(e,r){this._key=Di(e,br),this._publicKey=Di(r,Bn)}async sign(e){return V1(this._key,e)}get public(){return new Bs(this._publicKey)}marshal(){return this._key}get bytes(){return xr.encode({Type:Le.Ed25519,Data:this.marshal()}).subarray()}equals(e){return qe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}async id(){let e=Hr.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,r="libp2p-key"){if(r==="libp2p-key")return Ci(this.bytes,e);throw new ee(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function M4(t){if(t.length>br){t=Di(t,br+Bn);let n=t.subarray(0,br),i=t.subarray(br,t.length);return new kn(n,i)}t=Di(t,br);let e=t.subarray(0,br),r=t.subarray(Bn);return new kn(e,r)}function K4(t){return t=Di(t,Bn),new Bs(t)}async function V4(){let{privateKey:t,publicKey:e}=await M1();return new kn(t,e)}async function G1(t){let{privateKey:e,publicKey:r}=await K1(t);return new kn(e,r)}function Di(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new ee(`Key must be a Uint8Array of length ${e}, got ${t.length}`,"ERR_INVALID_KEY_TYPE");return t}var q4={"P-256":"prime256v1","P-384":"secp384r1","P-521":"secp521r1"},H4=Object.keys(q4),bL=H4.join(" / ");var k0={};Ze(k0,{RsaPrivateKey:()=>Ri,RsaPublicKey:()=>Ps,fromJwk:()=>g6,generateKeyPair:()=>b6,unmarshalRsaPrivateKey:()=>p6,unmarshalRsaPublicKey:()=>y6});var Os=G(we(),1);var QL=G(Y1(),1);var On=G(Ge("crypto"),1),hg=Ge("util");var W4=G(Ge("crypto"),1);var ie=BigInt(0),Te=BigInt(1),sn=BigInt(2),Ls=BigInt(3),J1=BigInt(8),Ue=Object.freeze({a:ie,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:Te,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),Z1=(t,e)=>(t+e/sn)/e,Ga={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(t){let{n:e}=Ue,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Te*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,o=BigInt("0x100000000000000000000000000000000"),a=Z1(s*t,e),c=Z1(-n*t,e),u=R(t-a*r-c*i,e),f=R(-a*n-c*s,e),l=u>o,h=f>o;if(l&&(u=e-u),h&&(f=e-f),u>o||f>o)throw new Error("splitScalarEndo: Endomorphism failed, k="+t);return{k1neg:l,k1:u,k2neg:h,k2:f}}},$t=32,Ii=32,j4=32,Q1=$t+1,eg=2*$t+1;function tg(t){let{a:e,b:r}=Ue,n=R(t*t),i=R(n*t);return R(i+e*t+r)}var Wa=Ue.a===ie,Xa=class extends Error{constructor(e){super(e)}};function rg(t){if(!(t instanceof ae))throw new TypeError("JacobianPoint expected")}var ae=class{constructor(e,r,n){this.x=e,this.y=r,this.z=n}static fromAffine(e){if(!(e instanceof ge))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(ge.ZERO)?ae.ZERO:new ae(e.x,e.y,Te)}static toAffineBatch(e){let r=Z4(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(r[i]))}static normalizeZ(e){return ae.toAffineBatch(e).map(ae.fromAffine)}equals(e){rg(e);let{x:r,y:n,z:i}=this,{x:s,y:o,z:a}=e,c=R(i*i),u=R(a*a),f=R(r*u),l=R(s*c),h=R(R(n*a)*u),p=R(R(o*i)*c);return f===l&&h===p}negate(){return new ae(this.x,R(-this.y),this.z)}double(){let{x:e,y:r,z:n}=this,i=R(e*e),s=R(r*r),o=R(s*s),a=e+s,c=R(sn*(R(a*a)-i-o)),u=R(Ls*i),f=R(u*u),l=R(f-sn*c),h=R(u*(c-l)-J1*o),p=R(sn*r*n);return new ae(l,h,p)}add(e){rg(e);let{x:r,y:n,z:i}=this,{x:s,y:o,z:a}=e;if(s===ie||o===ie)return this;if(r===ie||n===ie)return e;let c=R(i*i),u=R(a*a),f=R(r*u),l=R(s*c),h=R(R(n*a)*u),p=R(R(o*i)*c),d=R(l-f),y=R(p-h);if(d===ie)return y===ie?this.double():ae.ZERO;let g=R(d*d),b=R(d*g),v=R(f*g),w=R(y*y-b-sn*v),C=R(y*(v-w)-h*b),E=R(i*a*d);return new ae(w,C,E)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){let r=ae.ZERO;if(typeof e=="bigint"&&e===ie)return r;let n=sg(e);if(n===Te)return this;if(!Wa){let l=r,h=this;for(;n>ie;)n&Te&&(l=l.add(h)),h=h.double(),n>>=Te;return l}let{k1neg:i,k1:s,k2neg:o,k2:a}=Ga.splitScalar(n),c=r,u=r,f=this;for(;s>ie||a>ie;)s&Te&&(c=c.add(f)),a&Te&&(u=u.add(f)),f=f.double(),s>>=Te,a>>=Te;return i&&(c=c.negate()),o&&(u=u.negate()),u=new ae(R(u.x*Ga.beta),u.y,u.z),c.add(u)}precomputeWindow(e){let r=Wa?128/e+1:256/e+1,n=[],i=this,s=i;for(let o=0;o<r;o++){s=i,n.push(s);for(let a=1;a<2**(e-1);a++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,r){!r&&this.equals(ae.BASE)&&(r=ge.BASE);let n=r&&r._WINDOW_SIZE||1;if(256%n)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let i=r&&A0.get(r);i||(i=this.precomputeWindow(n),r&&n!==1&&(i=ae.normalizeZ(i),A0.set(r,i)));let s=ae.ZERO,o=ae.BASE,a=1+(Wa?128/n:256/n),c=2**(n-1),u=BigInt(2**n-1),f=2**n,l=BigInt(n);for(let h=0;h<a;h++){let p=h*c,d=Number(e&u);e>>=l,d>c&&(d-=f,e+=Te);let y=p,g=p+Math.abs(d)-1,b=h%2!==0,v=d<0;d===0?o=o.add(ja(b,i[y])):s=s.add(ja(v,i[g]))}return{p:s,f:o}}multiply(e,r){let n=sg(e),i,s;if(Wa){let{k1neg:o,k1:a,k2neg:c,k2:u}=Ga.splitScalar(n),{p:f,f:l}=this.wNAF(a,r),{p:h,f:p}=this.wNAF(u,r);f=ja(o,f),h=ja(c,h),h=new ae(R(h.x*Ga.beta),h.y,h.z),i=f.add(h),s=l.add(p)}else{let{p:o,f:a}=this.wNAF(n,r);i=o,s=a}return ae.normalizeZ([i,s])[0]}toAffine(e){let{x:r,y:n,z:i}=this,s=this.equals(ae.ZERO);e==null&&(e=s?J1:Ni(i));let o=e,a=R(o*o),c=R(a*o),u=R(r*a),f=R(n*c),l=R(i*o);if(s)return ge.ZERO;if(l!==Te)throw new Error("invZ was invalid");return new ge(u,f)}};ae.BASE=new ae(Ue.Gx,Ue.Gy,Te);ae.ZERO=new ae(ie,Te,ie);function ja(t,e){let r=e.negate();return t?r:e}var A0=new WeakMap,ge=class{constructor(e,r){this.x=e,this.y=r}_setWindowSize(e){this._WINDOW_SIZE=e,A0.delete(this)}hasEvenY(){return this.y%sn===ie}static fromCompressedHex(e){let r=e.length===32,n=on(r?e:e.subarray(1));if(!_0(n))throw new Error("Point is not on curve");let i=tg(n),s=J4(i),o=(s&Te)===Te;r?o&&(s=R(-s)):(e[0]&1)===1!==o&&(s=R(-s));let a=new ge(n,s);return a.assertValidity(),a}static fromUncompressedHex(e){let r=on(e.subarray(1,$t+1)),n=on(e.subarray($t+1,$t*2+1)),i=new ge(r,n);return i.assertValidity(),i}static fromHex(e){let r=Li(e),n=r.length,i=r[0];if(n===$t)return this.fromCompressedHex(r);if(n===Q1&&(i===2||i===3))return this.fromCompressedHex(r);if(n===eg&&i===4)return this.fromUncompressedHex(r);throw new Error(`Point.fromHex: received invalid point. Expected 32-${Q1} compressed bytes or ${eg} uncompressed bytes, not ${n}`)}static fromPrivateKey(e){return ge.BASE.multiply(Ja(e))}static fromSignature(e,r,n){let{r:i,s}=og(r);if(![0,1,2,3].includes(n))throw new Error("Cannot recover: invalid recovery bit");let o=T0(Li(e)),{n:a}=Ue,c=n===2||n===3?i+a:i,u=Ni(c,a),f=R(-o*u,a),l=R(s*u,a),h=n&1?"03":"02",p=ge.fromHex(h+Ti(c)),d=ge.BASE.multiplyAndAddUnsafe(p,f,l);if(!d)throw new Error("Cannot recover signature: point at infinify");return d.assertValidity(),d}toRawBytes(e=!1){return Nn(this.toHex(e))}toHex(e=!1){let r=Ti(this.x);return e?`${this.hasEvenY()?"02":"03"}${r}`:`04${r}${Ti(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){let e="Point is not on elliptic curve",{x:r,y:n}=this;if(!_0(r)||!_0(n))throw new Error(e);let i=R(n*n),s=tg(r);if(R(i-s)!==ie)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new ge(this.x,R(-this.y))}double(){return ae.fromAffine(this).double().toAffine()}add(e){return ae.fromAffine(this).add(ae.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return ae.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,r,n){let i=ae.fromAffine(this),s=r===ie||r===Te||this!==ge.BASE?i.multiplyUnsafe(r):i.multiply(r),o=ae.fromAffine(e).multiplyUnsafe(n),a=s.add(o);return a.equals(ae.ZERO)?void 0:a.toAffine()}};ge.BASE=new ge(Ue.Gx,Ue.Gy);ge.ZERO=new ge(ie,ie);function ng(t){return Number.parseInt(t[0],16)>=8?"00"+t:t}function ig(t){if(t.length<2||t[0]!==2)throw new Error(`Invalid signature integer tag: ${ki(t)}`);let e=t[1],r=t.subarray(2,e+2);if(!e||r.length!==e)throw new Error("Invalid signature integer: wrong length");if(r[0]===0&&r[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:on(r),left:t.subarray(e+2)}}function $4(t){if(t.length<2||t[0]!=48)throw new Error(`Invalid signature tag: ${ki(t)}`);if(t[1]!==t.length-2)throw new Error("Invalid signature: incorrect length");let{data:e,left:r}=ig(t.subarray(2)),{data:n,left:i}=ig(r);if(i.length)throw new Error(`Invalid signature: left bytes after parsing: ${ki(i)}`);return{r:e,s:n}}var wr=class{constructor(e,r){this.r=e,this.s=r,this.assertValidity()}static fromCompact(e){let r=e instanceof Uint8Array,n="Signature.fromCompact";if(typeof e!="string"&&!r)throw new TypeError(`${n}: Expected string or Uint8Array`);let i=r?ki(e):e;if(i.length!==128)throw new Error(`${n}: Expected 64-byte hex`);return new wr(Ya(i.slice(0,64)),Ya(i.slice(64,128)))}static fromDER(e){let r=e instanceof Uint8Array;if(typeof e!="string"&&!r)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");let{r:n,s:i}=$4(r?e:Nn(e));return new wr(n,i)}static fromHex(e){return this.fromDER(e)}assertValidity(){let{r:e,s:r}=this;if(!Rs(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!Rs(r))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){let e=Ue.n>>Te;return this.s>e}normalizeS(){return this.hasHighS()?new wr(this.r,R(-this.s,Ue.n)):this}toDERRawBytes(){return Nn(this.toDERHex())}toDERHex(){let e=ng(ks(this.s)),r=ng(ks(this.r)),n=e.length/2,i=r.length/2,s=ks(n),o=ks(i);return`30${ks(i+n+4)}02${o}${r}02${s}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return Nn(this.toCompactHex())}toCompactHex(){return Ti(this.r)+Ti(this.s)}};function nn(...t){if(!t.every(n=>n instanceof Uint8Array))throw new Error("Uint8Array list expected");if(t.length===1)return t[0];let e=t.reduce((n,i)=>n+i.length,0),r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let s=t[n];r.set(s,i),i+=s.length}return r}var X4=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ki(t){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");let e="";for(let r=0;r<t.length;r++)e+=X4[t[r]];return e}var Y4=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function Ti(t){if(typeof t!="bigint")throw new Error("Expected bigint");if(!(ie<=t&&t<Y4))throw new Error("Expected number 0 <= n < 2^256");return t.toString(16).padStart(64,"0")}function C0(t){let e=Nn(Ti(t));if(e.length!==32)throw new Error("Error: expected 32 bytes");return e}function ks(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function Ya(t){if(typeof t!="string")throw new TypeError("hexToNumber: expected string, got "+typeof t);return BigInt(`0x${t}`)}function Nn(t){if(typeof t!="string")throw new TypeError("hexToBytes: expected string, got "+typeof t);if(t.length%2)throw new Error("hexToBytes: received invalid unpadded hex"+t.length);let e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r++){let n=r*2,i=t.slice(n,n+2),s=Number.parseInt(i,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");e[r]=s}return e}function on(t){return Ya(ki(t))}function Li(t){return t instanceof Uint8Array?Uint8Array.from(t):Nn(t)}function sg(t){if(typeof t=="number"&&Number.isSafeInteger(t)&&t>0)return BigInt(t);if(typeof t=="bigint"&&Rs(t))return t;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function R(t,e=Ue.P){let r=t%e;return r>=ie?r:e+r}function Pt(t,e){let{P:r}=Ue,n=t;for(;e-- >ie;)n*=n,n%=r;return n}function J4(t){let{P:e}=Ue,r=BigInt(6),n=BigInt(11),i=BigInt(22),s=BigInt(23),o=BigInt(44),a=BigInt(88),c=t*t*t%e,u=c*c*t%e,f=Pt(u,Ls)*u%e,l=Pt(f,Ls)*u%e,h=Pt(l,sn)*c%e,p=Pt(h,n)*h%e,d=Pt(p,i)*p%e,y=Pt(d,o)*d%e,g=Pt(y,a)*y%e,b=Pt(g,o)*d%e,v=Pt(b,Ls)*u%e,w=Pt(v,s)*p%e,C=Pt(w,r)*c%e,E=Pt(C,sn);if(E*E%e!==t)throw new Error("Cannot find square root");return E}function Ni(t,e=Ue.P){if(t===ie||e<=ie)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=R(t,e),n=e,i=ie,s=Te,o=Te,a=ie;for(;r!==ie;){let u=n/r,f=n%r,l=i-o*u,h=s-a*u;n=r,r=f,i=o,s=a,o=l,a=h}if(n!==Te)throw new Error("invert: does not exist");return R(i,e)}function Z4(t,e=Ue.P){let r=new Array(t.length),n=t.reduce((s,o,a)=>o===ie?s:(r[a]=s,R(s*o,e)),Te),i=Ni(n,e);return t.reduceRight((s,o,a)=>o===ie?s:(r[a]=R(s*r[a],e),R(s*o,e)),i),r}function Q4(t){let e=t.length*8-Ii*8,r=on(t);return e>0?r>>BigInt(e):r}function T0(t,e=!1){let r=Q4(t);if(e)return r;let{n}=Ue;return r>=n?r-n:r}var Bi,Ns,D0=class{constructor(e,r){if(this.hashLen=e,this.qByteLen=r,typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof r!="number"||r<2)throw new Error("qByteLen must be a number");this.v=new Uint8Array(e).fill(1),this.k=new Uint8Array(e).fill(0),this.counter=0}hmac(...e){return Xt.hmacSha256(this.k,...e)}hmacSync(...e){return Ns(this.k,...e)}checkSync(){if(typeof Ns!="function")throw new Xa("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw new Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),e.length!==0&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),e.length!==0&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0,r=[];for(;e<this.qByteLen;){this.v=await this.hmac(this.v);let n=this.v.slice();r.push(n),e+=this.v.length}return nn(...r)}generateSync(){this.checkSync(),this.incr();let e=0,r=[];for(;e<this.qByteLen;){this.v=this.hmacSync(this.v);let n=this.v.slice();r.push(n),e+=this.v.length}return nn(...r)}};function Rs(t){return ie<t&&t<Ue.n}function _0(t){return ie<t&&t<Ue.P}function e6(t,e,r,n=!0){let{n:i}=Ue,s=T0(t,!0);if(!Rs(s))return;let o=Ni(s,i),a=ge.BASE.multiply(s),c=R(a.x,i);if(c===ie)return;let u=R(o*R(e+r*c,i),i);if(u===ie)return;let f=new wr(c,u),l=(a.x===f.r?0:2)|Number(a.y&Te);return n&&f.hasHighS()&&(f=f.normalizeS(),l^=1),{sig:f,recovery:l}}function Ja(t){let e;if(typeof t=="bigint")e=t;else if(typeof t=="number"&&Number.isSafeInteger(t)&&t>0)e=BigInt(t);else if(typeof t=="string"){if(t.length!==2*Ii)throw new Error("Expected 32 bytes of private key");e=Ya(t)}else if(t instanceof Uint8Array){if(t.length!==Ii)throw new Error("Expected 32 bytes of private key");e=on(t)}else throw new TypeError("Expected valid private key");if(!Rs(e))throw new Error("Expected private key: 0 < key < n");return e}function t6(t){return t instanceof ge?(t.assertValidity(),t):ge.fromHex(t)}function og(t){if(t instanceof wr)return t.assertValidity(),t;try{return wr.fromDER(t)}catch{return wr.fromCompact(t)}}function B0(t,e=!1){return ge.fromPrivateKey(t).toRawBytes(e)}function ag(t){let e=t.length>$t?t.slice(0,$t):t;return on(e)}function r6(t){let e=ag(t),r=R(e,Ue.n);return cg(r<ie?e:r)}function cg(t){return C0(t)}function n6(t,e,r){if(t==null)throw new Error(`sign: expected valid message hash, not "${t}"`);let n=Li(t),i=Ja(e),s=[cg(i),r6(n)];if(r!=null){r===!0&&(r=Xt.randomBytes($t));let c=Li(r);if(c.length!==$t)throw new Error(`sign: Expected ${$t} bytes of extra data`);s.push(c)}let o=nn(...s),a=ag(n);return{seed:o,m:a,d:i}}function i6(t,e){let{sig:r,recovery:n}=t,{der:i,recovered:s}=Object.assign({canonical:!0,der:!0},e),o=i?r.toDERRawBytes():r.toCompactRawBytes();return s?[o,n]:o}async function ug(t,e,r={}){let{seed:n,m:i,d:s}=n6(t,e,r.extraEntropy),o=new D0(j4,Ii);await o.reseed(n);let a;for(;!(a=e6(await o.generate(),i,s,r.canonical));)await o.reseed();return i6(a,r)}var s6={strict:!0};function fg(t,e,r,n=s6){let i;try{i=og(t),e=Li(e)}catch{return!1}let{r:s,s:o}=i;if(n.strict&&i.hasHighS())return!1;let a=T0(e),c;try{c=t6(r)}catch{return!1}let{n:u}=Ue,f=Ni(o,u),l=R(a*f,u),h=R(s*f,u),p=ge.BASE.multiplyAndAddUnsafe(c,l,h);return p?R(p.x,u)===s:!1}ge.BASE._setWindowSize(8);var Tt={node:W4,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0};var $a={},Xt={bytesToHex:ki,hexToBytes:Nn,concatBytes:nn,mod:R,invert:Ni,isValidPrivateKey(t){try{return Ja(t),!0}catch{return!1}},_bigintTo32Bytes:C0,_normalizePrivateKey:Ja,hashToPrivateKey:t=>{t=Li(t);let e=Ii+8;if(t.length<e||t.length>1024)throw new Error("Expected valid bytes of private key as per FIPS 186");let r=R(on(t),Ue.n-Te)+Te;return C0(r)},randomBytes:(t=32)=>{if(Tt.web)return Tt.web.getRandomValues(new Uint8Array(t));if(Tt.node){let{randomBytes:e}=Tt.node;return Uint8Array.from(e(t))}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Xt.hashToPrivateKey(Xt.randomBytes(Ii+8)),precompute(t=8,e=ge.BASE){let r=e===ge.BASE?e:new ge(e.x,e.y);return r._setWindowSize(t),r.multiply(Ls),r},sha256:async(...t)=>{if(Tt.web){let e=await Tt.web.subtle.digest("SHA-256",nn(...t));return new Uint8Array(e)}else if(Tt.node){let{createHash:e}=Tt.node,r=e("sha256");return t.forEach(n=>r.update(n)),Uint8Array.from(r.digest())}else throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(t,...e)=>{if(Tt.web){let r=await Tt.web.subtle.importKey("raw",t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=nn(...e),i=await Tt.web.subtle.sign("HMAC",r,n);return new Uint8Array(i)}else if(Tt.node){let{createHmac:r}=Tt.node,n=r("sha256",t);return e.forEach(i=>n.update(i)),Uint8Array.from(n.digest())}else throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(t,...e)=>{let r=$a[t];if(r===void 0){let n=await Xt.sha256(Uint8Array.from(t,i=>i.charCodeAt(0)));r=nn(n,n),$a[t]=r}return Xt.sha256(r,...e)},taggedHashSync:(t,...e)=>{if(typeof Bi!="function")throw new Xa("sha256Sync is undefined, you need to set it");let r=$a[t];if(r===void 0){let n=Bi(Uint8Array.from(t,i=>i.charCodeAt(0)));r=nn(n,n),$a[t]=r}return Bi(r,...e)},_JacobianPoint:ae};Object.defineProperties(Xt,{sha256Sync:{configurable:!1,get(){return Bi},set(t){Bi||(Bi=t)}},hmacSha256Sync:{configurable:!1,get(){return Ns},set(t){Ns||(Ns=t)}}});function Za(t){if(isNaN(t)||t<=0)throw new ee("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Xt.randomBytes(t)}var Rn={};Ze(Rn,{jwkToPkcs1:()=>u6,jwkToPkix:()=>l6,pkcs1ToJwk:()=>c6,pkixToJwk:()=>f6});var qL=G(Cs(),1),HL=G(m0(),1);var Mr=G(we(),1);var PL=G(Ve(),1),UL=G(Ka(),1),lg=G(we(),1);function Yt(t,e){let r=Uint8Array.from(t.abs().toByteArray());if(r=r[0]===0?r.subarray(1):r,e!=null){if(r.length>e)throw new Error("byte array longer than desired length");r=ye([new Uint8Array(e-r.length),r])}return $(r,"base64url")}function Jt(t){let e=a6(t);return new lg.default.jsbn.BigInteger($(e,"base16"),16)}function a6(t,e){let r=Ae(t,"base64urlpad");if(e!=null){if(r.length>e)throw new Error("byte array longer than desired length");r=ye([new Uint8Array(e-r.length),r])}return r}function c6(t){let e=Mr.default.asn1.fromDer($(t,"ascii")),r=Mr.default.pki.privateKeyFromAsn1(e);return{kty:"RSA",n:Yt(r.n),e:Yt(r.e),d:Yt(r.d),p:Yt(r.p),q:Yt(r.q),dp:Yt(r.dP),dq:Yt(r.dQ),qi:Yt(r.qInv),alg:"RS256"}}function u6(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new ee("JWK was missing components","ERR_INVALID_PARAMETERS");let e=Mr.default.pki.privateKeyToAsn1({n:Jt(t.n),e:Jt(t.e),d:Jt(t.d),p:Jt(t.p),q:Jt(t.q),dP:Jt(t.dp),dQ:Jt(t.dq),qInv:Jt(t.qi)});return Ae(Mr.default.asn1.toDer(e).getBytes(),"ascii")}function f6(t){let e=Mr.default.asn1.fromDer($(t,"ascii")),r=Mr.default.pki.publicKeyFromAsn1(e);return{kty:"RSA",n:Yt(r.n),e:Yt(r.e)}}function l6(t){if(t.n==null||t.e==null)throw new ee("JWK was missing components","ERR_INVALID_PARAMETERS");let e=Mr.default.pki.publicKeyToAsn1({n:Jt(t.n),e:Jt(t.e)});return Ae(Mr.default.asn1.toDer(e).getBytes(),"ascii")}var h6=(0,hg.promisify)(On.default.generateKeyPair);async function dg(t){let e=await h6("rsa",{modulusLength:t,publicKeyEncoding:{type:"pkcs1",format:"jwk"},privateKeyEncoding:{type:"pkcs1",format:"jwk"}});return{privateKey:e.privateKey,publicKey:e.publicKey}}async function I0(t){if(t==null)throw new ee("Missing key parameter","ERR_MISSING_KEY");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function pg(t,e){return On.default.createSign("RSA-SHA256").update(e).sign({format:"jwk",key:t})}async function yg(t,e,r){return On.default.createVerify("RSA-SHA256").update(r).verify({format:"jwk",key:t},e)}var gg=On.default.constants.RSA_PKCS1_PADDING;function bg(t,e){return On.default.publicEncrypt({format:"jwk",key:t,padding:gg},e)}function mg(t,e){return On.default.privateDecrypt({format:"jwk",key:t,padding:gg},e)}var Ps=class{_key;constructor(e){this._key=e}async verify(e,r){return yg(this._key,r,e)}marshal(){return Rn.jwkToPkix(this._key)}get bytes(){return mr.encode({Type:Le.RSA,Data:this.marshal()}).subarray()}encrypt(e){return bg(this._key,e)}equals(e){return qe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}},Ri=class{_key;_publicKey;constructor(e,r){this._key=e,this._publicKey=r}genSecret(){return Za(16)}async sign(e){return pg(this._key,e)}get public(){if(this._publicKey==null)throw new ee("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Ps(this._publicKey)}decrypt(e){return mg(this._key,e)}marshal(){return Rn.jwkToPkcs1(this._key)}get bytes(){return xr.encode({Type:Le.RSA,Data:this.marshal()}).subarray()}equals(e){return qe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}async id(){let e=await this.public.hash();return $(e,"base58btc")}async export(e,r="pkcs-8"){if(r==="pkcs-8"){let n=new Os.default.util.ByteBuffer(this.marshal()),i=Os.default.asn1.fromDer(n),s=Os.default.pki.privateKeyFromAsn1(i),o={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return Os.default.pki.encryptRsaPrivateKey(s,e,o)}else{if(r==="libp2p-key")return Ci(this.bytes,e);throw new ee(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}};async function p6(t){let e=Rn.pkcs1ToJwk(t),r=await I0(e);return new Ri(r.privateKey,r.publicKey)}function y6(t){let e=Rn.pkixToJwk(t);return new Ps(e)}async function g6(t){let e=await I0(t);return new Ri(e.privateKey,e.publicKey)}async function b6(t){let e=await dg(t);return new Ri(e.privateKey,e.publicKey)}var N0={};Ze(N0,{Secp256k1PrivateKey:()=>Fs,Secp256k1PublicKey:()=>Us,generateKeyPair:()=>v6,unmarshalSecp256k1PrivateKey:()=>x6,unmarshalSecp256k1PublicKey:()=>w6});function xg(){return Xt.randomPrivateKey()}async function wg(t,e){let{digest:r}=await et.digest(e);try{return await ug(r,t)}catch(n){throw new ee(String(n),"ERR_INVALID_INPUT")}}async function vg(t,e,r){try{let{digest:n}=await et.digest(r);return fg(e,n,t)}catch(n){throw new ee(String(n),"ERR_INVALID_INPUT")}}function Eg(t){return ge.fromHex(t).toRawBytes(!0)}function Sg(t){try{B0(t,!0)}catch(e){throw new ee(String(e),"ERR_INVALID_PRIVATE_KEY")}}function L0(t){try{ge.fromHex(t)}catch(e){throw new ee(String(e),"ERR_INVALID_PUBLIC_KEY")}}function _g(t){try{return B0(t,!0)}catch(e){throw new ee(String(e),"ERR_INVALID_PRIVATE_KEY")}}var Us=class{_key;constructor(e){L0(e),this._key=e}async verify(e,r){return vg(this._key,r,e)}marshal(){return Eg(this._key)}get bytes(){return mr.encode({Type:Le.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return qe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}},Fs=class{_key;_publicKey;constructor(e,r){this._key=e,this._publicKey=r??_g(e),Sg(this._key),L0(this._publicKey)}async sign(e){return wg(this._key,e)}get public(){return new Us(this._publicKey)}marshal(){return this._key}get bytes(){return xr.encode({Type:Le.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return qe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}async id(){let e=await this.public.hash();return $(e,"base58btc")}async export(e,r="libp2p-key"){if(r==="libp2p-key")return Ci(this.bytes,e);throw new ee(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function x6(t){return new Fs(t)}function w6(t){return new Us(t)}async function v6(){let t=xg();return new Fs(t)}var Pn={rsa:k0,ed25519:v0,secp256k1:N0};function Ag(t){let e=Object.keys(Pn).join(" / ");return new ee(`invalid or unsupported key type ${t}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function Cg(t){let e=mr.decode(t),r=e.Data??new Uint8Array;switch(e.Type){case Le.RSA:return Pn.rsa.unmarshalRsaPublicKey(r);case Le.Ed25519:return Pn.ed25519.unmarshalEd25519PublicKey(r);case Le.Secp256k1:return Pn.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw Ag(e.Type??"RSA")}}async function Dg(t){let e=xr.decode(t),r=e.Data??new Uint8Array;switch(e.Type){case Le.RSA:return Pn.rsa.unmarshalRsaPrivateKey(r);case Le.Ed25519:return Pn.ed25519.unmarshalEd25519PrivateKey(r);case Le.Secp256k1:return Pn.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw Ag(e.Type??"RSA")}}var Qa;(function(t){let e;t.codec=()=>(e==null&&(e=kr((r,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),r.webtransportCerthashes!=null)for(let s of r.webtransportCerthashes)n.uint32(10),n.bytes(s);i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={webtransportCerthashes:[]},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.webtransportCerthashes.push(r.bytes());break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Ir(r,t.codec()),t.decode=r=>Br(r,t.codec())})(Qa||(Qa={}));var Ms;(function(t){let e;t.codec=()=>(e==null&&(e=kr((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||r.identityKey!=null&&r.identityKey.byteLength>0)&&(n.uint32(10),n.bytes(r.identityKey??new Uint8Array(0))),(i.writeDefaults===!0||r.identitySig!=null&&r.identitySig.byteLength>0)&&(n.uint32(18),n.bytes(r.identitySig??new Uint8Array(0))),r.extensions!=null&&(n.uint32(34),Qa.codec().encode(r.extensions,n,{writeDefaults:!1})),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={identityKey:new Uint8Array(0),identitySig:new Uint8Array(0)},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.identityKey=r.bytes();break;case 2:i.identitySig=r.bytes();break;case 4:i.extensions=Qa.codec().decode(r,r.uint32());break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Ir(r,t.codec()),t.decode=r=>Br(r,t.codec())})(Ms||(Ms={}));async function Tg(t,e,r){let n=await _6(t,Bg(e));if(t.publicKey==null)throw new Error("PublicKey was missing from local PeerId");return S6(t.publicKey,n,r)}function S6(t,e,r){return Ms.encode({identityKey:t,identitySig:e,extensions:r??{webtransportCerthashes:[]}}).subarray()}async function _6(t,e){if(t.privateKey==null)throw new Error("PrivateKey was missing from PeerId");return await(await Dg(t.privateKey)).sign(e)}async function R0(t){return await Qc(t.identityKey)}function O0(t){return Ms.decode(t)}function Bg(t){let e=Ae("noise-libp2p-static-key:");return ye([e,t],e.length+t.length)}async function P0(t,e,r){let n=await Qc(e.identityKey);if(!n.equals(r))throw new Error(`Payload identity key ${n.toString()} does not match expected remote peer ${r.toString()}`);let i=Bg(t);if(n.publicKey==null)throw new Error("PublicKey was missing from PeerId");if(e.identitySig==null)throw new Error("Signature was missing from message");if(!await Cg(n.publicKey).verify(i,e.identitySig))throw new Error("Static key doesn't match to peer that signed payload!");return n}function Ks(t){return!(!(t instanceof Uint8Array)||t.length!==32)}var Ye=lt("libp2p:noise");var Ut;Ip?Ut=Ye:Ut=Object.assign(()=>{},{enabled:!1,trace:()=>{},error:()=>{}});function Ig(t){Ut(`LOCAL_STATIC_PUBLIC_KEY ${$(t.publicKey,"hex")}`),Ut(`LOCAL_STATIC_PRIVATE_KEY ${$(t.privateKey,"hex")}`)}function U0(t){t?(Ut(`LOCAL_PUBLIC_EPHEMERAL_KEY ${$(t.publicKey,"hex")}`),Ut(`LOCAL_PRIVATE_EPHEMERAL_KEY ${$(t.privateKey,"hex")}`)):Ut("Missing local ephemeral keys.")}function kg(t){Ut(`REMOTE_STATIC_PUBLIC_KEY ${$(t,"hex")}`)}function F0(t){Ut(`REMOTE_EPHEMERAL_PUBLIC_KEY ${$(t,"hex")}`)}function Lg(t){t.cs1&&t.cs2?(Ut(`CIPHER_STATE_1 ${t.cs1.n.getUint64()} ${$(t.cs1.k,"hex")}`),Ut(`CIPHER_STATE_2 ${t.cs2.n.getUint64()} ${$(t.cs2.k,"hex")}`)):Ut("Missing cipher state.")}var A6="Cipherstate has reached maximum n, a new handshake must be performed",ec=class{constructor(e=0){this.n=e,this.bytes=new Uint8Array(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw new Error(A6)}};var tc=class{constructor(e){this.crypto=e}encryptWithAd(e,r,n){let i=this.encrypt(e.k,e.n,r,n);return e.n.increment(),i}decryptWithAd(e,r,n,i){let{plaintext:s,valid:o}=this.decrypt(e.k,e.n,r,n,i);return o&&e.n.increment(),{plaintext:s,valid:o}}hasKey(e){return!this.isEmptyKey(e.k)}createEmptyKey(){return new Uint8Array(32)}isEmptyKey(e){let r=this.createEmptyKey();return qe(r,e)}encrypt(e,r,n,i){return r.assertValue(),this.crypto.chaCha20Poly1305Encrypt(i,r.getBytes(),n,e)}encryptAndHash(e,r){let n;return this.hasKey(e.cs)?n=this.encryptWithAd(e.cs,e.h,r):n=r,this.mixHash(e,n),n}decrypt(e,r,n,i,s){r.assertValue();let o=this.crypto.chaCha20Poly1305Decrypt(i,r.getBytes(),n,e,s);return o?{plaintext:o,valid:!0}:{plaintext:new Uint8Array(0),valid:!1}}decryptAndHash(e,r){let n,i=!0;return this.hasKey(e.cs)?{plaintext:n,valid:i}=this.decryptWithAd(e.cs,e.h,r):n=r,this.mixHash(e,r),{plaintext:n,valid:i}}dh(e,r){try{let n=this.crypto.generateX25519SharedKey(e,r);return n.length===32?n:n.subarray(0,32)}catch(n){let i=n;return Ye.error(i),new Uint8Array(32)}}mixHash(e,r){e.h=this.getHash(e.h,r)}getHash(e,r){return this.crypto.hashSHA256(ye([e,r],e.length+r.length))}mixKey(e,r){let[n,i]=this.crypto.getHKDF(e.ck,r);e.cs=this.initializeKey(i),e.ck=n}initializeKey(e){return{k:e,n:new ec}}initializeSymmetric(e){let r=Ae(e,"utf-8"),n=this.hashProtocolName(r),i=n,s=this.createEmptyKey();return{cs:this.initializeKey(s),ck:i,h:n}}hashProtocolName(e){if(e.length<=32){let r=new Uint8Array(32);return r.set(e),r}else return this.getHash(e,new Uint8Array(0))}split(e){let[r,n]=this.crypto.getHKDF(e.ck,new Uint8Array(0)),i=this.initializeKey(r),s=this.initializeKey(n);return{cs1:i,cs2:s}}writeMessageRegular(e,r){let n=this.encryptWithAd(e,new Uint8Array(0),r),i=this.createEmptyKey(),s=new Uint8Array(0);return{ne:i,ns:s,ciphertext:n}}readMessageRegular(e,r){return this.decryptWithAd(e,new Uint8Array(0),r.ciphertext)}};var rc=class extends tc{initializeInitiator(e,r,n,i){let s="Noise_XX_25519_ChaChaPoly_SHA256",o=this.initializeSymmetric(s);this.mixHash(o,e);let a=new Uint8Array(32);return{ss:o,s:r,rs:n,psk:i,re:a}}initializeResponder(e,r,n,i){let s="Noise_XX_25519_ChaChaPoly_SHA256",o=this.initializeSymmetric(s);this.mixHash(o,e);let a=new Uint8Array(32);return{ss:o,s:r,rs:n,psk:i,re:a}}writeMessageA(e,r,n){let i=new Uint8Array(0);n!==void 0?e.e=n:e.e=this.crypto.generateX25519KeyPair();let s=e.e.publicKey;this.mixHash(e.ss,s);let o=this.encryptAndHash(e.ss,r);return{ne:s,ns:i,ciphertext:o}}writeMessageB(e,r){e.e=this.crypto.generateX25519KeyPair();let n=e.e.publicKey;this.mixHash(e.ss,n),this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let i=e.s.publicKey,s=this.encryptAndHash(e.ss,i);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let o=this.encryptAndHash(e.ss,r);return{ne:n,ns:s,ciphertext:o}}writeMessageC(e,r){let n=e.s.publicKey,i=this.encryptAndHash(e.ss,n);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let s=this.encryptAndHash(e.ss,r),a={ne:this.createEmptyKey(),ns:i,ciphertext:s},{cs1:c,cs2:u}=this.split(e.ss);return{h:e.ss.h,messageBuffer:a,cs1:c,cs2:u}}readMessageA(e,r){return Ks(r.ne)&&(e.re=r.ne),this.mixHash(e.ss,e.re),this.decryptAndHash(e.ss,r.ciphertext)}readMessageB(e,r){if(Ks(r.ne)&&(e.re=r.ne),this.mixHash(e.ss,e.re),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let{plaintext:n,valid:i}=this.decryptAndHash(e.ss,r.ns);i&&Ks(n)&&(e.rs=n),this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:s,valid:o}=this.decryptAndHash(e.ss,r.ciphertext);return{plaintext:s,valid:i&&o}}readMessageC(e,r){let{plaintext:n,valid:i}=this.decryptAndHash(e.ss,r.ns);if(i&&Ks(n)&&(e.rs=n),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:s,valid:o}=this.decryptAndHash(e.ss,r.ciphertext),{cs1:a,cs2:c}=this.split(e.ss);return{h:e.ss.h,plaintext:s,valid:i&&o,cs1:a,cs2:c}}initSession(e,r,n){let i=this.createEmptyKey(),s=new Uint8Array(32),o;return e?o=this.initializeInitiator(r,n,s,i):o=this.initializeResponder(r,n,s,i),{hs:o,i:e,mc:0}}sendMessage(e,r,n){let i;if(e.mc===0)i=this.writeMessageA(e.hs,r,n);else if(e.mc===1)i=this.writeMessageB(e.hs,r);else if(e.mc===2){let{h:s,messageBuffer:o,cs1:a,cs2:c}=this.writeMessageC(e.hs,r);i=o,e.h=s,e.cs1=a,e.cs2=c}else if(e.mc>2)if(e.i){if(!e.cs1)throw new Error("CS1 (cipher state) is not defined");i=this.writeMessageRegular(e.cs1,r)}else{if(!e.cs2)throw new Error("CS2 (cipher state) is not defined");i=this.writeMessageRegular(e.cs2,r)}else throw new Error("Session invalid.");return e.mc++,i}recvMessage(e,r){let n=new Uint8Array(0),i=!1;if(e.mc===0)({plaintext:n,valid:i}=this.readMessageA(e.hs,r));else if(e.mc===1)({plaintext:n,valid:i}=this.readMessageB(e.hs,r));else if(e.mc===2){let{h:s,plaintext:o,valid:a,cs1:c,cs2:u}=this.readMessageC(e.hs,r);n=o,i=a,e.h=s,e.cs1=c,e.cs2=u}return e.mc++,{plaintext:n,valid:i}}};var nc=class{constructor(e,r,n,i,s,o,a,c){this.remoteExtensions={webtransportCerthashes:[]},this.isInitiator=e,this.payload=r,this.prologue=n,this.staticKeypair=s,this.connection=o,a&&(this.remotePeer=a),this.xx=c??new rc(i),this.session=this.xx.initSession(this.isInitiator,this.prologue,this.staticKeypair)}async propose(){if(Ig(this.session.hs.s),this.isInitiator){Ye.trace("Stage 0 - Initiator starting to send first message.");let e=this.xx.sendMessage(this.session,new Uint8Array(0));this.connection.writeLP(hy(e)),Ye.trace("Stage 0 - Initiator finished sending first message."),U0(this.session.hs.e)}else{Ye.trace("Stage 0 - Responder waiting to receive first message...");let e=yy((await this.connection.readLP()).subarray()),{valid:r}=this.xx.recvMessage(this.session,e);if(!r)throw new Or("xx handshake stage 0 validation fail");Ye.trace("Stage 0 - Responder received first message."),F0(this.session.hs.re)}}async exchange(){if(this.isInitiator){Ye.trace("Stage 1 - Initiator waiting to receive first message from responder...");let e=gy((await this.connection.readLP()).subarray()),{plaintext:r,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new Or("xx handshake stage 1 validation fail");Ye.trace("Stage 1 - Initiator received the message."),F0(this.session.hs.re),kg(this.session.hs.rs),Ye.trace("Initiator going to check remote's signature...");try{let i=O0(r);this.remotePeer=this.remotePeer||await R0(i),await P0(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let s=i;throw new En(`Error occurred while verifying signed payload: ${s.message}`)}Ye.trace("All good with the signature!")}else{Ye.trace("Stage 1 - Responder sending out first message with signed payload and static key.");let e=this.xx.sendMessage(this.session,this.payload);this.connection.writeLP(dy(e)),Ye.trace("Stage 1 - Responder sent the second handshake message with signed payload."),U0(this.session.hs.e)}}async finish(){if(this.isInitiator){Ye.trace("Stage 2 - Initiator sending third handshake message.");let e=this.xx.sendMessage(this.session,this.payload);this.connection.writeLP(py(e)),Ye.trace("Stage 2 - Initiator sent message with signed payload.")}else{Ye.trace("Stage 2 - Responder waiting for third handshake message...");let e=by((await this.connection.readLP()).subarray()),{plaintext:r,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new Or("xx handshake stage 2 validation fail");Ye.trace("Stage 2 - Responder received the message, finished handshake.");try{let i=O0(r);this.remotePeer=this.remotePeer||await R0(i),await P0(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let s=i;throw new En(`Error occurred while verifying signed payload: ${s.message}`)}}Lg(this.session)}encrypt(e,r){let n=this.getCS(r);return this.xx.encryptWithAd(n,new Uint8Array(0),e)}decrypt(e,r,n){let i=this.getCS(r,!1);return this.xx.decryptWithAd(i,new Uint8Array(0),e,n)}getRemoteStaticKey(){return this.session.hs.rs}getCS(e,r=!0){if(!e.cs1||!e.cs2)throw new Or("Handshake not completed properly, cipher state does not exist.");return this.isInitiator?r?e.cs1:e.cs2:r?e.cs2:e.cs1}setRemoteNoiseExtension(e){e&&(this.remoteExtensions=e)}};function Ng(t){return{xxHandshakeSuccesses:t.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:t.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:t.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:t.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:t.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}var ic=class{constructor(e={}){this.protocol="/noise";let{staticNoiseKey:r,extensions:n,crypto:i,prologueBytes:s,metrics:o}=e;this.crypto=i??ly,this.extensions=n,this.metrics=o?Ng(o):void 0,r?this.staticKeys=this.crypto.generateX25519KeyPairFromSeed(r):this.staticKeys=this.crypto.generateX25519KeyPair(),this.prologue=s??new Uint8Array(0)}async secureOutbound(e,r,n){let i=Tf(r,{lengthEncoder:vi,lengthDecoder:vs,maxDataLength:65535}),s=await this.performHandshake({connection:i,isInitiator:!0,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,s),remoteExtensions:s.remoteExtensions,remotePeer:s.remotePeer}}async secureInbound(e,r,n){let i=Tf(r,{lengthEncoder:vi,lengthDecoder:vs,maxDataLength:65535}),s=await this.performHandshake({connection:i,isInitiator:!1,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,s),remotePeer:s.remotePeer,remoteExtensions:s.remoteExtensions}}async performHandshake(e){let r=await Tg(e.localPeer,this.staticKeys.publicKey,this.extensions);return await this.performXXHandshake(e,r)}async performXXHandshake(e,r){let{isInitiator:n,remotePeer:i,connection:s}=e,o=new nc(n,r,this.prologue,this.crypto,this.staticKeys,s,i);try{await o.propose(),await o.exchange(),await o.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 o}async createSecureConnection(e,r){let[n,i]=Dp(),s=e.unwrap();return await Bp(n,xy(r,this.metrics),s,pn({lengthDecoder:vs}),wy(r,this.metrics),n),i}};function Rg(t={}){return()=>new ic(t)}var ub=G(ll(),1);var sb=G(ll(),1);var hl=lt("libp2p:webrtc:sdp"),dl=Object.values(tr).map(t=>t.decoder).reduce((t,e)=>t.or(e));function ob(t){let e=t.getConfiguration().certificates?.at(0);if(e==null||e.getFingerprints==null){hl.trace("fetching fingerprint from local SDP");let n=t.localDescription;return n==null?void 0:Q_(n.sdp)}if(hl.trace("fetching fingerprint from local certificate"),e.getFingerprints().length===0)return;let r=e.getFingerprints()[0].value;if(r==null)throw wu("","no fingerprint on local certificate");return r}var Z_=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function Q_(t){return t.match(Z_)?.groups?.fingerprint}function eA(t){for(let e of t.protoNames())if(e.startsWith("ip"))return e.toUpperCase();return hl("Warning: multiaddr does not appear to contain IP4 or IP6, defaulting to IP6",t),"IP6"}function _c(t){let r=t.stringTuples().filter(n=>n[0]===gl).map(n=>n[1])[0];if(r===void 0||r==="")throw ti(`Couldn't find a certhash component of multiaddr: ${t.toString()}`);return r}function pl(t){let e=dl.decode(t);return sb.decode(e)}function tA(t){let e=pl(_c(t)),r=yl(e.name),n=e.digest.reduce((s,o)=>s+o.toString(16).padStart(2,"0"),""),i=n.match(/.{1,2}/g);if(i==null)throw wu(n,t.toString());return[`${r.toUpperCase()} ${i.join(":").toUpperCase()}`,n]}function yl(t){switch(t){case"sha1":return"sha-1";case"sha2-256":return"sha-256";case"sha2-512":return"sha-512";default:throw Sh(t)}}function rA(t,e){let{host:r,port:n}=t.toOptions(),i=eA(t),[s]=tA(t);return`v=0
34
+ `;tl.CID=Je});var H2=_(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});var i_=rl(),s_=Hs(),o_=Er(),a_=yc(),c_=Mi();Mn.CID=i_.CID;Mn.varint=s_;Mn.bytes=o_;Mn.hasher=a_;Mn.digest=c_});var z2=_(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});var u_=h2(),f_=d2(),l_=p2(),h_=y2(),d_=b2(),p_=Y0(),y_=x2(),g_=J0(),b_=v2(),m_=S2(),x_=R2(),w_=U2(),v_=M2(),E_=K2();H2();var S_=rl(),__=yc(),A_=Mi(),C_=Hs(),D_=Er(),T_={...u_,...f_,...l_,...h_,...d_,...p_,...y_,...g_,...b_,...m_},B_={...x_,...w_},I_={raw:v_,json:E_};Sr.CID=S_.CID;Sr.hasher=__;Sr.digest=A_;Sr.varint=C_;Sr.bytes=D_;Sr.bases=T_;Sr.codecs=I_;Sr.hashes=B_});var vc=_(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});function k_(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}nl.asUint8Array=k_});var il=_(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var G2=vc();function L_(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.alloc!=null?G2.asUint8Array(globalThis.Buffer.alloc(t)):new Uint8Array(t)}function N_(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?G2.asUint8Array(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}Ec.alloc=L_;Ec.allocUnsafe=N_});var ol=_((oO,X2)=>{"use strict";var W2=z2(),R_=il();function $2(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var j2=$2("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),sl=$2("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=R_.allocUnsafe(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),O_={utf8:j2,"utf-8":j2,hex:W2.bases.base16,latin1:sl,ascii:sl,binary:sl,...W2.bases};X2.exports=O_});var Y2=_(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});var P_=ol();function U_(t,e="utf8"){let r=P_[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}al.toString=U_});var J2=_(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});var F_=ol(),M_=vc();function K_(t,e="utf8"){let r=F_[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?M_.asUint8Array(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}cl.fromString=K_});var Z2=_(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});var V_=il(),q_=vc();function H_(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));let r=V_.allocUnsafe(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return q_.asUint8Array(r)}ul.concat=H_});var ll=_((fO,ib)=>{"use strict";var Q2=$g(),qi=s2(),{names:js}=a2(),{toString:Sc}=Y2(),{fromString:z_}=J2(),{concat:G_}=Z2(),Hi={};for(let t in js){let e=t;Hi[js[e]]=e}Object.freeze(Hi);function W_(t){if(!(t instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return Sc(t,"base16")}function j_(t){return z_(t,"base16")}function $_(t){if(!(t instanceof Uint8Array))throw new Error("must be passed a Uint8Array");return Sc(Q2.encode("base58btc",t)).slice(1)}function X_(t){let e=t instanceof Uint8Array?Sc(t):t;return Q2.decode("z"+e)}function eb(t){if(!(t instanceof Uint8Array))throw new Error("multihash must be a Uint8Array");if(t.length<2)throw new Error("multihash too short. must be > 2 bytes.");let e=qi.decode(t);if(!rb(e))throw new Error(`multihash unknown function code: 0x${e.toString(16)}`);t=t.slice(qi.decode.bytes);let r=qi.decode(t);if(r<0)throw new Error(`multihash invalid length: ${r}`);if(t=t.slice(qi.decode.bytes),t.length!==r)throw new Error(`multihash length inconsistent: 0x${Sc(t,"base16")}`);return{code:e,name:Hi[e],length:r,digest:t}}function Y_(t,e,r){if(!t||e===void 0)throw new Error("multihash encode requires at least two args: digest, code");let n=tb(e);if(!(t instanceof Uint8Array))throw new Error("digest should be a Uint8Array");if(r==null&&(r=t.length),r&&t.length!==r)throw new Error("digest length should be equal to specified length.");let i=qi.encode(n),s=qi.encode(r);return G_([i,s,t],i.length+s.length+t.length)}function tb(t){let e=t;if(typeof t=="string"){if(js[t]===void 0)throw new Error(`Unrecognized hash function named: ${t}`);e=js[t]}if(typeof e!="number")throw new Error(`Hash function code should be a number. Got: ${e}`);if(Hi[e]===void 0&&!fl(e))throw new Error(`Unrecognized function code: ${e}`);return e}function fl(t){return t>0&&t<16}function rb(t){return!!(fl(t)||Hi[t])}function nb(t){eb(t)}function J_(t){return nb(t),t.subarray(0,2)}ib.exports={names:js,codes:Hi,toHexString:W_,fromHexString:j_,toB58String:$_,fromB58String:X_,decode:eb,encode:Y_,coerceCode:tb,isAppCode:fl,validate:nb,prefix:J_,isValidCode:rb}});var uA={};Ze(uA,{webRTC:()=>cA,webRTCDirect:()=>aA});var Xs=Symbol.for("@libp2p/transport");var ml;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(ml||(ml={}));var ee=class extends Error{code;props;constructor(e,r,n){super(e),this.code=r,this.name=n?.name??"CodeError",this.props=n??{}}};var It=G(Bl(),1);var Rc={};Ze(Rc,{base58btc:()=>Fe,base58flickr:()=>zb});function Mb(t,e){if(t.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<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var y=0,g=0,b=0,v=d.length;b!==v&&d[b]===0;)b++,y++;for(var w=(v-b)*f+1>>>0,C=new Uint8Array(w);b!==v;){for(var E=d[b],S=0,T=w-1;(E!==0||S<g)&&T!==-1;T--,S++)E+=256*C[T]>>>0,C[T]=E%a>>>0,E=E/a>>>0;if(E!==0)throw new Error("Non-zero carry");g=S,b++}for(var I=w-g;I!==w&&C[I]===0;)I++;for(var O=c.repeat(y);I<w;++I)O+=t.charAt(C[I]);return O}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var y=0;if(d[y]!==" "){for(var g=0,b=0;d[y]===c;)g++,y++;for(var v=(d.length-y)*u+1>>>0,w=new Uint8Array(v);d[y];){var C=r[d.charCodeAt(y)];if(C===255)return;for(var E=0,S=v-1;(C!==0||E<b)&&S!==-1;S--,E++)C+=a*w[S]>>>0,w[S]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");b=E,y++}if(d[y]!==" "){for(var T=v-b;T!==v&&w[T]===0;)T++;for(var I=new Uint8Array(g+(v-T)),O=g;T!==v;)I[O++]=w[T++];return I}}}function p(d){var y=h(d);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:h,decode:p}}var Kb=Mb,Vb=Kb,Il=Vb;var vA=new Uint8Array(0);var kl=(t,e)=>{if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0},Bt=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")};var Ll=t=>new TextEncoder().encode(t),Nl=t=>new TextDecoder().decode(t);var Ic=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},kc=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Ol(this,e)}},Lc=class{constructor(e){this.decoders=e}or(e){return Ol(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},Ol=(t,e)=>new Lc({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),Nc=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new Ic(e,r,n),this.decoder=new kc(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},zn=({name:t,prefix:e,encode:r,decode:n})=>new Nc(t,e,r,n),qr=({prefix:t,name:e,alphabet:r})=>{let{encode:n,decode:i}=Il(r,e);return zn({prefix:t,name:e,encode:n,decode:s=>Bt(i(s))})},qb=(t,e,r,n)=>{let i={};for(let f=0;f<e.length;++f)i[e[f]]=f;let s=t.length;for(;t[s-1]==="=";)--s;let o=new Uint8Array(s*r/8|0),a=0,c=0,u=0;for(let f=0;f<s;++f){let l=i[t[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|l,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Hb=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<<r)-1,s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},Re=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>zn({prefix:e,name:t,encode(i){return Hb(i,n,r)},decode(i){return qb(i,n,r,t)}});var Fe=qr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),zb=qr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Oc={};Ze(Oc,{base32:()=>Mt,base32hex:()=>$b,base32hexpad:()=>Yb,base32hexpadupper:()=>Jb,base32hexupper:()=>Xb,base32pad:()=>Wb,base32padupper:()=>jb,base32upper:()=>Gb,base32z:()=>Zb});var Mt=Re({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Gb=Re({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Wb=Re({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),jb=Re({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),$b=Re({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Xb=Re({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Yb=Re({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Jb=Re({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Zb=Re({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Pc={};Ze(Pc,{base64:()=>Gn,base64pad:()=>Qb,base64url:()=>em,base64urlpad:()=>tm});var Gn=Re({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Qb=Re({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),em=Re({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),tm=Re({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});It.default.formatters.b=t=>t==null?"undefined":Fe.baseEncode(t);It.default.formatters.t=t=>t==null?"undefined":Mt.baseEncode(t);It.default.formatters.m=t=>t==null?"undefined":Gn.baseEncode(t);It.default.formatters.p=t=>t==null?"undefined":t.toString();It.default.formatters.c=t=>t==null?"undefined":t.toString();It.default.formatters.k=t=>t==null?"undefined":t.toString();function rm(t){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=t,e.destroy=()=>!0,e.extend=()=>e,e}function lt(t){let e=rm(`${t}:trace`);return It.default.enabled(`${t}:trace`)&&It.default.names.map(r=>r.toString()).find(r=>r.includes(":trace"))!=null&&(e=(0,It.default)(`${t}:trace`)),Object.assign((0,It.default)(t),{error:(0,It.default)(`${t}:error`),trace:e})}var nm=Fl,Pl=128,im=127,sm=~im,om=Math.pow(2,31);function Fl(t,e,r){e=e||[],r=r||0;for(var n=r;t>=om;)e[r++]=t&255|Pl,t/=128;for(;t&sm;)e[r++]=t&255|Pl,t>>>=7;return e[r]=t|0,Fl.bytes=r-n+1,e}var am=Uc,cm=128,Ul=127;function Uc(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw Uc.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&Ul)<<i:(o&Ul)*Math.pow(2,i),i+=7}while(o>=cm);return Uc.bytes=s-n,r}var um=Math.pow(2,7),fm=Math.pow(2,14),lm=Math.pow(2,21),hm=Math.pow(2,28),dm=Math.pow(2,35),pm=Math.pow(2,42),ym=Math.pow(2,49),gm=Math.pow(2,56),bm=Math.pow(2,63),mm=function(t){return t<um?1:t<fm?2:t<lm?3:t<hm?4:t<dm?5:t<pm?6:t<ym?7:t<gm?8:t<bm?9:10},xm={encode:nm,decode:am,encodingLength:mm},wm=xm,zi=wm;var Gi=(t,e=0)=>[zi.decode(t,e),zi.decode.bytes],Wn=(t,e,r=0)=>(zi.encode(t,e,r),e),jn=t=>zi.encodingLength(t);var er=(t,e)=>{let r=e.byteLength,n=jn(t),i=n+jn(r),s=new Uint8Array(i+r);return Wn(t,s,0),Wn(r,s,n),s.set(e,i),new $n(t,r,e,s)},un=t=>{let e=Bt(t),[r,n]=Gi(e),[i,s]=Gi(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new $n(r,i,o,e)},Ml=(t,e)=>{if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&kl(t.bytes,r.bytes)}},$n=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};var Kl=(t,e)=>{let{bytes:r,version:n}=t;switch(n){case 0:return Em(r,Fc(t),e||Fe.encoder);default:return Sm(r,Fc(t),e||Mt.encoder)}};var Vl=new WeakMap,Fc=t=>{let e=Vl.get(t);if(e==null){let r=new Map;return Vl.set(t,r),r}return e},xe=class{constructor(e,r,n,i){this.code=r,this.version=e,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:e,multihash:r}=this;if(e!==Wi)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==_m)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return xe.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:e,digest:r}=this.multihash,n=er(e,r);return xe.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(e){return xe.equals(this,e)}static equals(e,r){let n=r;return n&&e.code===n.code&&e.version===n.version&&Ml(e.multihash,n.multihash)}toString(e){return Kl(this,e)}toJSON(){return{"/":Kl(this)}}link(){return this}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof xe)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:i,multihash:s,bytes:o}=r;return new xe(n,i,s,o||ql(n,i,s.bytes))}else if(r[Am]===!0){let{version:n,multihash:i,code:s}=r,o=un(i);return xe.create(n,s,o)}else return null}static create(e,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(e){case 0:{if(r!==Wi)throw new Error(`Version 0 CID must use dag-pb (code: ${Wi}) block encoding`);return new xe(e,r,n,n.bytes)}case 1:{let i=ql(e,r,n.bytes);return new xe(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return xe.create(0,Wi,e)}static createV1(e,r){return xe.create(1,e,r)}static decode(e){let[r,n]=xe.decodeFirst(e);if(n.length)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=xe.inspectBytes(e),n=r.size-r.multihashSize,i=Bt(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=i.subarray(r.multihashSize-r.digestSize),o=new $n(r.multihashCode,r.digestSize,s,i);return[r.version===0?xe.createV0(o):xe.createV1(r.codec,o),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[l,h]=Gi(e.subarray(r));return r+=h,l},i=n(),s=Wi;if(i===18?(i=0,r=0):s=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=r,a=n(),c=n(),u=r+c,f=u-o;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(e,r){let[n,i]=vm(e,r),s=xe.decode(i);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Fc(s).set(n,e),s}},vm=(t,e)=>{switch(t[0]){case"Q":{let r=e||Fe;return[Fe.prefix,r.decode(`${Fe.prefix}${t}`)]}case Fe.prefix:{let r=e||Fe;return[Fe.prefix,r.decode(t)]}case Mt.prefix:{let r=e||Mt;return[Mt.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}},Em=(t,e,r)=>{let{prefix:n}=r;if(n!==Fe.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return i},Sm=(t,e,r)=>{let{prefix:n}=r,i=e.get(n);if(i==null){let s=r.encode(t);return e.set(n,s),s}else return i},Wi=112,_m=18,ql=(t,e,r)=>{let n=jn(t),i=n+jn(e),s=new Uint8Array(i+r.byteLength);return Wn(t,s,0),Wn(e,s,n),s.set(r,i),s},Am=Symbol.for("@ipld/js-cid/CID");var Mc={};Ze(Mc,{identity:()=>Cm});var Cm=zn({prefix:"\0",name:"identity",encode:t=>Nl(t),decode:t=>Ll(t)});var Kc={};Ze(Kc,{base2:()=>Dm});var Dm=Re({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Vc={};Ze(Vc,{base8:()=>Tm});var Tm=Re({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var qc={};Ze(qc,{base10:()=>Bm});var Bm=qr({prefix:"9",name:"base10",alphabet:"0123456789"});var Hc={};Ze(Hc,{base16:()=>Im,base16upper:()=>km});var Im=Re({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),km=Re({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var zc={};Ze(zc,{base36:()=>Lm,base36upper:()=>Nm});var Lm=qr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Nm=qr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Gc={};Ze(Gc,{base256emoji:()=>Fm});var Hl=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}"),Rm=Hl.reduce((t,e,r)=>(t[r]=e,t),[]),Om=Hl.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Pm(t){return t.reduce((e,r)=>(e+=Rm[r],e),"")}function Um(t){let e=[];for(let r of t){let n=Om[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}var Fm=zn({prefix:"\u{1F680}",name:"base256emoji",encode:Pm,decode:Um});var Xc={};Ze(Xc,{sha256:()=>et,sha512:()=>Mm});var $c=G(Ge("crypto"),1);var jc=({name:t,code:e,encode:r})=>new Wc(t,e,r),Wc=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?er(this.code,r):r.then(n=>er(this.code,n))}else throw Error("Unknown type, must be binary type")}};var et=jc({name:"sha2-256",code:18,encode:t=>Bt($c.default.createHash("sha256").update(t).digest())}),Mm=jc({name:"sha2-512",code:19,encode:t=>Bt($c.default.createHash("sha512").update(t).digest())});var Yc={};Ze(Yc,{identity:()=>Hr});var Gl=0,Km="identity",Wl=Bt,Vm=t=>er(Gl,Wl(t)),Hr={code:Gl,name:Km,encode:Wl,digest:Vm};var ZA=new TextEncoder,QA=new TextDecoder;var tr={...Mc,...Kc,...Vc,...qc,...Hc,...Oc,...zc,...Rc,...Pc,...Gc},iC={...Xc,...Yc};function qe(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}var jl=Symbol.for("@libp2p/peer-id");var zm=Symbol.for("nodejs.util.inspect.custom"),$l=Object.values(tr).map(t=>t.decoder).reduce((t,e)=>t.or(e),tr.identity.decoder),Xl=114,Jc=36,Zc=37,ji=class{constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}get[jl](){return!0}toString(){return this.string==null&&(this.string=Fe.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return xe.createV1(Xl,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(e instanceof Uint8Array)return qe(this.multihash.bytes,e);if(typeof e=="string")return $i(e).equals(this);if(e?.multihash?.bytes!=null)return qe(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[zm](){return`PeerId(${this.toString()})`}},Xn=class extends ji{constructor(e){super({...e,type:"RSA"}),this.type="RSA",this.publicKey=e.publicKey}},Yn=class extends ji{constructor(e){super({...e,type:"Ed25519"}),this.type="Ed25519",this.publicKey=e.multihash.digest}},Jn=class extends ji{constructor(e){super({...e,type:"secp256k1"}),this.type="secp256k1",this.publicKey=e.multihash.digest}};function $i(t,e){if(e=e??$l,t.charAt(0)==="1"||t.charAt(0)==="Q"){let r=un(Fe.decode(`z${t}`));return t.startsWith("12D")?new Yn({multihash:r}):t.startsWith("16U")?new Jn({multihash:r}):new Xn({multihash:r})}return Gm($l.decode(t))}function Gm(t){try{let e=un(t);if(e.code===Hr.code){if(e.digest.length===Jc)return new Yn({multihash:e});if(e.digest.length===Zc)return new Jn({multihash:e})}if(e.code===et.code)return new Xn({multihash:e})}catch{return Wm(xe.decode(t))}throw new Error("Supplied PeerID CID is invalid")}function Wm(t){if(t==null||t.multihash==null||t.version==null||t.version===1&&t.code!==Xl)throw new Error("Supplied PeerID CID is invalid");let e=t.multihash;if(e.code===et.code)return new Xn({multihash:t.multihash});if(e.code===Hr.code){if(e.digest.length===Jc)return new Yn({multihash:t.multihash});if(e.digest.length===Zc)return new Jn({multihash:t.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function Qc(t,e){return t.length===Jc?new Yn({multihash:er(Hr.code,t),privateKey:e}):t.length===Zc?new Jn({multihash:er(Hr.code,t),privateKey:e}):new Xn({multihash:await et.digest(t),publicKey:t,privateKey:e})}var zr=Ge("node:net");function to(t){return!!(0,zr.isIP)(t)}function Gr(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function _r(t=0){return globalThis.Buffer?.alloc!=null?Gr(globalThis.Buffer.alloc(t)):new Uint8Array(t)}function mt(t=0){return globalThis.Buffer?.allocUnsafe!=null?Gr(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Jl(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var Yl=Jl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),eu=Jl("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);let e=mt(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),$m={utf8:Yl,"utf-8":Yl,hex:tr.base16,latin1:eu,ascii:eu,binary:eu,...tr},ro=$m;function $(t,e="utf8"){let r=ro[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}var Zl=zr.isIPv4,Xm=zr.isIPv6,tu=function(t){let e=0;if(t=t.toString().trim(),Zl(t)){let r=new Uint8Array(e+4);return t.split(/\./g).forEach(n=>{r[e++]=parseInt(n,10)&255}),r}if(Xm(t)){let r=t.split(":",8),n;for(n=0;n<r.length;n++){let s=Zl(r[n]),o;s&&(o=tu(r[n]),r[n]=$(o.slice(0,2),"base16")),o!=null&&++n<8&&r.splice(n,0,$(o.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 s=[n,1];for(n=9-r.length;n>0;n--)s.push("0");r.splice.apply(r,s)}let i=new Uint8Array(e+16);for(n=0;n<r.length;n++){let s=parseInt(r[n],16);i[e++]=s>>8&255,i[e++]=s&255}return i}throw new Error("invalid ip address")},Ql=function(t,e=0,r){e=~~e,r=r??t.length-e;let n=new DataView(t.buffer);if(r===4){let i=[];for(let s=0;s<r;s++)i.push(t[e+s]);return i.join(".")}if(r===16){let i=[];for(let s=0;s<r;s+=2)i.push(n.getUint16(e+s).toString(16));return i.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Xi={},ru={},Jm=[[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"]];Jm.forEach(t=>{let e=Zm(...t);ru[e.code]=e,Xi[e.name]=e});function Zm(t,e,r,n,i){return{code:t,size:e,name:r,resolvable:!!n,path:!!i}}function pe(t){if(typeof t=="number"){if(ru[t]!=null)return ru[t];throw new Error(`no protocol with code: ${t}`)}else if(typeof t=="string"){if(Xi[t]!=null)return Xi[t];throw new Error(`no protocol with name: ${t}`)}throw new Error(`invalid protocol id type: ${typeof t}`)}var rr=G(no(),1);function Ae(t,e="utf8"){let r=ro[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Gr(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function ye(t,e){e==null&&(e=t.reduce((i,s)=>i+s.length,0));let r=mt(e),n=0;for(let i of t)r.set(i,n),n+=i.length;return Gr(r)}var io=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let r=this.index,n=e();return n===void 0&&(this.index=r),n}parseWith(e){let r=e();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(e){return this.readAtomically(()=>{let r=this.readChar();if(r===e)return r})}readSeparator(e,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,r,n,i){return this.readAtomically(()=>{let s=0,o=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 h=Number.parseInt(l,e);if(!Number.isNaN(h))return h});if(f===void 0)break;if(s*=e,s+=f,s>u||(o+=1,r!==void 0&&o>r))return}if(o!==0)return!n&&c&&o>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let r=0;r<e.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[r]=n}return e})}readIPv6Addr(){let e=r=>{for(let n=0;n<r.length/2;n++){let i=n*2;if(n<r.length-3){let o=this.readSeparator(":",n,()=>this.readIPv4Addr());if(o!==void 0)return r[i]=o[0],r[i+1]=o[1],r[i+2]=o[2],r[i+3]=o[3],[i+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[i,!1];r[i]=s>>8,r[i+1]=s&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,i]=e(r);if(n===16)return r;if(i||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),o=16-(n+2),[a]=e(s.subarray(0,o));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var VC=new io;var XC=parseInt("0xFFFF",16),YC=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var BD=pe("ip4"),ID=pe("ip6"),kD=pe("ipcidr");function yh(t,e){switch(pe(t).code){case 4:case 41:return mx(e);case 42:return dh(e);case 6:case 273:case 33:case 132:return bh(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return dh(e);case 421:return Ex(e);case 444:return ph(e);case 445:return ph(e);case 466:return vx(e);default:return $(e,"base16")}}function gh(t,e){switch(pe(t).code){case 4:return lh(e);case 41:return lh(e);case 42:return hh(e);case 6:case 273:case 33:case 132:return ou(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return hh(e);case 421:return xx(e);case 444:return Sx(e);case 445:return _x(e);case 466:return wx(e);default:return Ae(e,"base16")}}var su=Object.values(tr).map(t=>t.decoder),bx=function(){let t=su[0].or(su[1]);return su.slice(2).forEach(e=>t=t.or(e)),t}();function lh(t){if(!to(t))throw new Error("invalid ip address");return tu(t)}function mx(t){let e=Ql(t,0,t.length);if(e==null)throw new Error("ipBuff is required");if(!to(e))throw new Error("invalid ip address");return e}function ou(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,t),new Uint8Array(e)}function bh(t){return new DataView(t.buffer).getUint16(t.byteOffset)}function hh(t){let e=Ae(t),r=Uint8Array.from(rr.default.encode(e.length));return ye([r,e],r.length+e.length)}function dh(t){let e=rr.default.decode(t);if(t=t.slice(rr.default.decode.bytes),t.length!==e)throw new Error("inconsistent lengths");return $(t)}function xx(t){let e;t[0]==="Q"||t[0]==="1"?e=un(Fe.decode(`z${t}`)).bytes:e=xe.parse(t).multihash.bytes;let r=Uint8Array.from(rr.default.encode(e.length));return ye([r,e],r.length+e.length)}function wx(t){let e=bx.decode(t),r=Uint8Array.from(rr.default.encode(e.length));return ye([r,e],r.length+e.length)}function vx(t){let e=rr.default.decode(t),r=t.slice(rr.default.decode.bytes);if(r.length!==e)throw new Error("inconsistent lengths");return"u"+$(r,"base64url")}function Ex(t){let e=rr.default.decode(t),r=t.slice(rr.default.decode.bytes);if(r.length!==e)throw new Error("inconsistent lengths");return $(r,"base58btc")}function Sx(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let r=Mt.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=ou(n);return ye([r,i],r.length+i.length)}function _x(t){let e=t.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let r=Mt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=ou(n);return ye([r,i],r.length+i.length)}function ph(t){let e=t.slice(0,t.length-2),r=t.slice(t.length-2),n=$(e,"base32"),i=bh(r);return`${n}:${i}`}var Zn=G(no(),1);function Ax(t){let e=[],r=t.split("/").slice(1);if(r.length===1&&r[0]==="")return[];for(let n=0;n<r.length;n++){let i=r[n],s=pe(i);if(s.size===0){e.push([i]);continue}if(n++,n>=r.length)throw xh("invalid address: "+t);if(s.path===!0){e.push([i,lu(r.slice(n).join("/"))]);break}e.push([i,r[n]])}return e}function Cx(t){let e=[];return t.map(r=>{let n=ao(r);return e.push(n.name),r.length>1&&r[1]!=null&&e.push(r[1]),null}),lu(e.join("/"))}function Dx(t){return t.map(e=>{Array.isArray(e)||(e=[e]);let r=ao(e);return e.length>1?[r.code,gh(r.code,e[1])]:[r.code]})}function au(t){return t.map(e=>{let r=ao(e);return e[1]!=null?[r.code,yh(r.code,e[1])]:[r.code]})}function cu(t){return oo(ye(t.map(e=>{let r=ao(e),n=Uint8Array.from(Zn.default.encode(r.code));return e.length>1&&e[1]!=null&&(n=ye([n,e[1]])),n})))}function uu(t,e){return t.size>0?t.size/8:t.size===0?0:Zn.default.decode(e)+(Zn.default.decode.bytes??0)}function so(t){let e=[],r=0;for(;r<t.length;){let n=Zn.default.decode(t,r),i=Zn.default.decode.bytes??0,s=pe(n),o=uu(s,t.slice(r+i));if(o===0){e.push([n]),r+=i;continue}let a=t.slice(r+i,r+i+o);if(r+=o+i,r>t.length)throw xh("Invalid address Uint8Array: "+$(t,"base16"));e.push([n,a])}return e}function fu(t){let e=so(t),r=au(e);return Cx(r)}function Tx(t){t=lu(t);let e=Ax(t),r=Dx(e);return cu(r)}function mh(t){return Tx(t)}function oo(t){let e=Bx(t);if(e!=null)throw e;return Uint8Array.from(t)}function Bx(t){try{so(t)}catch(e){return e}}function lu(t){return"/"+t.trim().split("/").filter(e=>e).join("/")}function xh(t){return new Error("Error parsing address: "+t)}function ao(t){return pe(t[0])}var hu=G(no(),1);var Ar=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},ei=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},Yi,Ji,Zi,Wr,wh,kx=Symbol.for("nodejs.util.inspect.custom"),Lx=[pe("dns").code,pe("dns4").code,pe("dns6").code,pe("dnsaddr").code],Nx=new Map,vh=Symbol.for("@multiformats/js-multiaddr/multiaddr");function Rx(t){return!!t?.[vh]}var Cr=class{constructor(e){if(Yi.set(this,void 0),Ji.set(this,void 0),Zi.set(this,void 0),Wr.set(this,void 0),this[wh]=!0,e==null&&(e=""),e instanceof Uint8Array)this.bytes=oo(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);this.bytes=mh(e)}else if(Rx(e))this.bytes=oo(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr")}toString(){return Ar(this,Yi,"f")==null&&ei(this,Yi,fu(this.bytes),"f"),Ar(this,Yi,"f")}toJSON(){return this.toString()}toOptions(){let e,r,n,i,s="",o=pe("tcp"),a=pe("udp"),c=pe("ip4"),u=pe("ip6"),f=pe("dns6"),l=pe("ip6zone");for(let[p,d]of this.stringTuples())p===l.code&&(s=`%${d??""}`),Lx.includes(p)&&(r=o.name,i=443,n=`${d??""}${s}`,e=p===f.code?6:4),(p===o.code||p===a.code)&&(r=pe(p).name,i=parseInt(d??"")),(p===c.code||p===u.code)&&(r=pe(p).name,n=`${d??""}${s}`,e=p===u.code?6:4);if(e==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:e,host:n,transport:r,port:i}}protos(){return this.protoCodes().map(e=>Object.assign({},pe(e)))}protoCodes(){let e=[],r=this.bytes,n=0;for(;n<r.length;){let i=hu.default.decode(r,n),s=hu.default.decode.bytes??0,o=pe(i),a=uu(o,r.slice(n+s));n+=a+s,e.push(i)}return e}protoNames(){return this.protos().map(e=>e.name)}tuples(){return Ar(this,Ji,"f")==null&&ei(this,Ji,so(this.bytes),"f"),Ar(this,Ji,"f")}stringTuples(){return Ar(this,Zi,"f")==null&&ei(this,Zi,au(this.tuples()),"f"),Ar(this,Zi,"f")}encapsulate(e){return e=new Cr(e),new Cr(this.toString()+e.toString())}decapsulate(e){let r=e.toString(),n=this.toString(),i=n.lastIndexOf(r);if(i<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new Cr(n.slice(0,i))}decapsulateCode(e){let r=this.tuples();for(let n=r.length-1;n>=0;n--)if(r[n][0]===e)return new Cr(cu(r.slice(0,n)));return this}getPeerId(){try{let r=this.stringTuples().filter(n=>n[0]===Xi.ipfs.code).pop();if(r?.[1]!=null){let n=r[1];return n[0]==="Q"||n[0]==="1"?$(Fe.decode(`z${n}`),"base58btc"):$(xe.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){if(Ar(this,Wr,"f")===void 0)try{ei(this,Wr,this.stringTuples().filter(e=>pe(e[0]).path===!0)[0][1],"f"),Ar(this,Wr,"f")==null&&ei(this,Wr,null,"f")}catch{ei(this,Wr,null,"f")}return Ar(this,Wr,"f")}equals(e){return qe(this.bytes,e.bytes)}async resolve(e){let r=this.protos().find(s=>s.resolvable);if(r==null)return[this];let n=Nx.get(r.name);if(n==null)throw new ee(`no available resolver for ${r.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,e)).map(s=>new Cr(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let r=(e??this).protos();return!(r.length!==2||r[0].code!==4&&r[0].code!==41||r[1].code!==6&&r[1].code!==273)}[(Yi=new WeakMap,Ji=new WeakMap,Zi=new WeakMap,Wr=new WeakMap,wh=vh,kx)](){return`Multiaddr(${fu(this.bytes)})`}};function Qn(t){return new Cr(t)}var kt;(function(t){t.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",t.ERR_DATA_CHANNEL="ERR_DATA_CHANNEL",t.ERR_CONNECTION_CLOSED="ERR_CONNECTION_CLOSED",t.ERR_HASH_NOT_SUPPORTED="ERR_HASH_NOT_SUPPORTED",t.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",t.ERR_INVALID_FINGERPRINT="ERR_INVALID_FINGERPRINT",t.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",t.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",t.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",t.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS"})(kt||(kt={}));var jr=class extends ee{constructor(e,r){super(`WebRTC transport error: ${e}`,r??""),this.name="WebRTCTransportError"}};var du=class extends jr{constructor(e,r){super(`[stream: ${e}] data channel error: ${r}`,kt.ERR_DATA_CHANNEL),this.name="WebRTC/DataChannelError"}};function xu(t,e){return new du(t,e)}var pu=class extends jr{constructor(e){super(`There was a problem with the Multiaddr which was passed in: ${e}`,kt.ERR_INVALID_MULTIADDR),this.name="WebRTC/InappropriateMultiaddrError"}};function ti(t){return new pu(t)}var yu=class extends jr{constructor(e){super(`There was a problem with a provided argument: ${e}`,kt.ERR_INVALID_PARAMETERS),this.name="WebRTC/InvalidArgumentError"}};function Qi(t){return new yu(t)}var gu=class extends jr{constructor(e,r){super(`Invalid fingerprint "${e}" within ${r}`,kt.ERR_INVALID_FINGERPRINT),this.name="WebRTC/InvalidFingerprintError"}};function wu(t,e){return new gu(t,e)}var bu=class extends jr{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`,kt.ERR_NOT_IMPLEMENTED),this.name="WebRTC/UnimplementedError"}};function Eh(t){return new bu(t)}var mu=class extends jr{constructor(e){super(`unsupported hash algorithm: ${e}`,kt.ERR_HASH_NOT_SUPPORTED),this.name="WebRTC/UnsupportedHashAlgorithmError"}};function Sh(t){return new mu(t)}var co=async function*(){},uo=async t=>{},_h=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Ah=t=>[...Array(t)].map(()=>_h.at(Math.floor(Math.random()*_h.length))).join("");var Ch=lt("libp2p:webrtc:connection"),ln=class{peerConnection;remoteAddr;timeline;metrics;source=co();sink=uo;constructor(e){this.remoteAddr=e.remoteAddr,this.timeline=e.timeline,this.peerConnection=e.peerConnection}async close(e){e!==void 0&&Ch.error("error closing connection",e),Ch.trace("closing connection"),this.timeline.close=Date.now(),this.peerConnection.close(),this.metrics?.increment({close:!0})}};var es=class extends Error{constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Dh(t){if(t!=null){if(typeof t[Symbol.iterator]=="function")return t[Symbol.iterator]();if(typeof t[Symbol.asyncIterator]=="function")return t[Symbol.asyncIterator]();if(typeof t.next=="function")return t}throw new Error("argument is not an iterator or iterable")}function Th(t,e,r){let n=r??{},i=Dh(t);async function*s(){let o,a=()=>{o?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:f,abortCode:l}=n;throw new es(f,l)}let u=new Promise((f,l)=>{o=()=>{let{abortMessage:h,abortCode:p}=n;l(new es(h,p))}});c=await Promise.race([u,i.next()]),o=null}catch(u){e.removeEventListener("abort",a);let f=u.type==="aborted"&&e.aborted;if(f&&n.onAbort!=null&&await n.onAbort(t),typeof i.return=="function")try{let l=i.return();l instanceof Promise&&l.catch(h=>{n.onReturnError!=null&&n.onReturnError(h)})}catch(l){n.onReturnError!=null&&n.onReturnError(l)}if(f&&n.returnOnAbort===!0)return;throw u}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return s()}function Ox(t,e,r){return n=>t(Th(n,e,r))}function vu(t,e,r){return{sink:Ox(t.sink,e,{...r,onAbort:void 0}),source:Th(t.source,e,r)}}var Ih=Symbol.for("@achingbrain/uint8arraylist");function Bh(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(let n of t){let i=r+n.byteLength;if(e<i)return{buf:n,index:e-r};r=i}throw new RangeError("index is out of bounds")}function fo(t){return!!t?.[Ih]}var me=class{constructor(...e){Object.defineProperty(this,Ih,{value:!0}),this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let r=0;for(let n of e)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(fo(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(...e){this.prependAll(e)}prependAll(e){let r=0;for(let n of e.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(fo(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(e){let r=Bh(this.bufs,e);return r.buf[r.index]}set(e,r){let n=Bh(this.bufs,e);n.buf[n.index]=r}write(e,r=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(r+n,e[n]);else if(fo(e))for(let n=0;n<e.length;n++)this.set(r+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,r){let{bufs:n,length:i}=this._subList(e,r);return ye(n,i)}subarray(e,r){let{bufs:n,length:i}=this._subList(e,r);return n.length===1?n[0]:ye(n,i)}sublist(e,r){let{bufs:n,length:i}=this._subList(e,r),s=new me;return s.length=i,s.bufs=n,s}_subList(e,r){if(e=e??0,r=r??this.length,e<0&&(e=this.length+e),r<0&&(r=this.length+r),e<0||r>this.length)throw new RangeError("index is out of bounds");if(e===r)return{bufs:[],length:0};if(e===0&&r===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],i=0;for(let s=0;s<this.bufs.length;s++){let o=this.bufs[s],a=i,c=a+o.byteLength;if(i=c,e>=c)continue;let u=e>=a&&e<c,f=r>a&&r<=c;if(u&&f){if(e===a&&r===c){n.push(o);break}let l=e-a;n.push(o.subarray(l,l+(r-e)));break}if(u){if(e===0){n.push(o);continue}n.push(o.subarray(e-a));continue}if(f){if(r===c){n.push(o);break}n.push(o.subarray(0,r-a));break}n.push(o)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!fo(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),e.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 s=256,o=new Int32Array(s);for(let l=0;l<s;l++)o[l]=-1;for(let l=0;l<i;l++)o[n[l]]=l;let a=o,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=r;l<=c;l+=f){f=0;for(let h=u;h>=0;h--){let p=this.get(l+h);if(n[h]!==p){f=Math.max(1,h-a[p]);break}}if(f===0)return l}return-1}getInt8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){let n=mt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,e)}getInt16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(e,r,n){let i=_r(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,r,n),this.write(i,e)}getInt32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(e,r,n){let i=_r(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,r,n),this.write(i,e)}getBigInt64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(e,r,n){let i=_r(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,r,n),this.write(i,e)}getUint8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(e,r){let n=mt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,e)}getUint16(e,r){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(e,r,n){let i=_r(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,r,n),this.write(i,e)}getUint32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(e,r,n){let i=_r(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,r,n),this.write(i,e)}getBigUint64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(e,r,n){let i=_r(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,r,n),this.write(i,e)}getFloat32(e,r){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(e,r,n){let i=_r(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,r,n),this.write(i,e)}getFloat64(e,r){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(e,r,n){let i=_r(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,r,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof me)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!qe(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){let n=new me;return n.bufs=e,r==null&&(r=e.reduce((i,s)=>i+s.byteLength,0)),n.length=r,n}};function lo(t){return t instanceof Uint8Array?{get(e){return t[e]},set(e,r){t[e]=r}}:{get(e){return t.get(e)},set(e,r){t.set(e,r)}}}var kh=4294967296,_t=class{constructor(e=0,r=0){this.hi=e,this.lo=r}toBigInt(e){if(e===!0)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)}toNumber(e){return Number(this.toBigInt(e))}zzDecode(){let e=-(this.lo&1),r=((this.lo>>>1|this.hi<<31)^e)>>>0,n=(this.hi>>>1^e)>>>0;return new _t(n,r)}zzEncode(){let e=this.hi>>31,r=((this.hi<<1|this.lo>>>31)^e)>>>0,n=(this.lo<<1^e)>>>0;return new _t(r,n)}toBytes(e,r=0){let n=lo(e);for(;this.hi>0;)n.set(r++,this.lo&127|128),this.lo=(this.lo>>>7|this.hi<<25)>>>0,this.hi>>>=7;for(;this.lo>127;)n.set(r++,this.lo&127|128),this.lo=this.lo>>>7;n.set(r++,this.lo)}static fromBigInt(e){if(e===0n)return new _t;let r=e<0;r&&(e=-e);let n=Number(e>>32n)|0,i=Number(e-(BigInt(n)<<32n))|0;return r&&(n=~n>>>0,i=~i>>>0,++i>kh&&(i=0,++n>kh&&(n=0))),new _t(n,i)}static fromNumber(e){if(e===0)return new _t;let r=e<0;r&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return r&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new _t(i,n)}static fromBytes(e,r=0){let n=lo(e),i=new _t,s=0;if(e.length-r>4){for(;s<4;++s)if(i.lo=(i.lo|(n.get(r)&127)<<s*7)>>>0,n.get(r++)<128)return i;if(i.lo=(i.lo|(n.get(r)&127)<<28)>>>0,i.hi=(i.hi|(n.get(r)&127)>>4)>>>0,n.get(r++)<128)return i;s=0}else for(;s<4;++s){if(r>=e.length)throw RangeError(`index out of range: ${r} > ${e.length}`);if(i.lo=(i.lo|(n.get(r)&127)<<s*7)>>>0,n.get(r++)<128)return i}if(e.length-r>4){for(;s<5;++s)if(i.hi=(i.hi|(n.get(r)&127)<<s*7+3)>>>0,n.get(r++)<128)return i}else if(r<e.byteLength)for(;s<5;++s){if(r>=e.length)throw RangeError(`index out of range: ${r} > ${e.length}`);if(i.hi=(i.hi|(n.get(r)&127)<<s*7+3)>>>0,n.get(r++)<128)return i}throw RangeError("invalid varint encoding")}};var Px=Math.pow(2,7),Ux=Math.pow(2,14),Fx=Math.pow(2,21),Mx=Math.pow(2,28),Kx=Math.pow(2,35),Vx=Math.pow(2,42),qx=Math.pow(2,49),Hx=Math.pow(2,56),zx=Math.pow(2,63),Ne={encodingLength(t){return t<Px?1:t<Ux?2:t<Fx?3:t<Mx?4:t<Kx?5:t<Vx?6:t<qx?7:t<Hx?8:t<zx?9:10},encode(t,e,r=0){if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return e==null&&(e=mt(Ne.encodingLength(t))),_t.fromNumber(t).toBytes(e,r),e},decode(t,e=0){return _t.fromBytes(t,e).toNumber(!0)}};function ho(t){return t[Symbol.asyncIterator]!=null}var po=t=>{let e=Ne.encodingLength(t),r=mt(e);return Ne.encode(t,r),po.bytes=e,r};po.bytes=0;function yo(t,e){e=e??{};let r=e.lengthEncoder??po;function*n(i){let s=r(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return ho(t)?async function*(){for await(let i of t)yield*n(i)}():function*(){for(let i of t)yield*n(i)}()}yo.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??po;return new me(r(t.byteLength),t)};var ni=G(ri(),1);var Wx=8,jx=1024*1024*4,hn;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(hn||(hn={}));var Su=t=>{let e=Ne.decode(t);return Su.bytes=Ne.encodingLength(e),e};Su.bytes=0;function Eu(t,e){let r=new me,n=hn.LENGTH,i=-1,s=e?.lengthDecoder??Su,o=e?.maxLengthLength??Wx,a=e?.maxDataLength??jx;function*c(){for(;r.byteLength>0;){if(n===hn.LENGTH)try{if(i=s(r),i<0)throw(0,ni.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,ni.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=hn.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>o)throw(0,ni.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===hn.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=hn.LENGTH}}}return ho(t)?async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,ni.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,ni.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Eu.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:s,value:o}=await t.next(r);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}}();return Eu(n,{...e??{},onLength:s=>{r=s}})};var go=class{constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},ii=class{constructor(e={}){this.hwm=e.splitLimit??16,this.head=new go(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new go(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};function xt(t={}){return Xx(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}},t)}function Xx(t,e){e=e??{};let r=e.onEnd,n=new ii,i,s,o,a=async()=>n.isEmpty()?o?{done:!0}:await new Promise((y,g)=>{s=b=>{s=null,n.push(b);try{y(t(n))}catch(v){g(v)}return i}}):t(n),c=y=>s!=null?s(y):(n.push(y),i),u=y=>(n=new ii,s!=null?s({error:y}):(n.push({error:y}),i)),f=y=>{if(o)return i;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:y})},l=y=>o?i:(o=!0,y!=null?u(y):c({done:!0})),h=()=>(n=new ii,l(),{done:!0}),p=y=>(l(y),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:a,return:h,throw:p,push:f,end:l,get readableLength(){return n.size}},r==null)return i;let d=i;return i={[Symbol.asyncIterator](){return this},next(){return d.next()},throw(y){return d.throw(y),r!=null&&(r(y),r=void 0),{done:!0}},return(){return d.return(),r!=null&&(r(),r=void 0),{done:!0}},push:f,end(y){return d.end(y),r!=null&&(r(y),r=void 0),i},get readableLength(){return d.readableLength}},i}var bo=G(ri(),1),Rh=t=>Ne.decode(t);Rh.bytes=0;function _u(t,e){let r=xt();t.sink(r).catch(o=>{r.end(o)}),t.sink=async o=>{for await(let a of o)r.push(a);r.end()};let n=t.source;t.source[Symbol.iterator]!=null?n=t.source[Symbol.iterator]():t.source[Symbol.asyncIterator]!=null&&(n=t.source[Symbol.asyncIterator]());let i=new me,s={read:async o=>{if(o==null){let{done:c,value:u}=await n.next();return c===!0?new me:u}for(;i.byteLength<o;){let{value:c,done:u}=await n.next();if(u===!0)throw(0,bo.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF");i.append(c)}let a=i.sublist(0,o);return i.consume(o),a},readLP:async()=>{let o=-1,a=new me,c=e?.lengthDecoder??Rh;for(;;){a.append(await s.read(1));try{o=c(a)}catch(u){if(u instanceof RangeError)continue;throw u}if(o>-1)break;if(e?.maxLengthLength!=null&&a.byteLength>e.maxLengthLength)throw(0,bo.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG")}if(e?.maxDataLength!=null&&o>e.maxDataLength)throw(0,bo.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");return await s.read(o)},readPB:async o=>{let a=await s.readLP();if(a==null)throw new Error("Value is null");let c=a instanceof Uint8Array?a:a.subarray();return o.decode(c)},write:o=>{o instanceof Uint8Array?r.push(o):r.push(o.subarray())},writeLP:o=>{s.write(yo.single(o,e))},writePB:(o,a)=>{s.writeLP(a.encode(o))},pb:o=>({read:async()=>await s.readPB(o),write:a=>{s.writePB(a,o)},unwrap:()=>s}),unwrap:()=>{let o=t.source;return t.source=async function*(){yield*i,yield*o}(),t}};return s}function nr(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}function Oh(t){return globalThis?.Buffer?.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}var mo=t=>{let e=Ne.encodingLength(t),r=Oh(e);return Ne.encode(t,r),mo.bytes=e,r};mo.bytes=0;function ts(t){t=t??{};let e=t.lengthEncoder??mo;return async function*(n){for await(let i of n){let s=e(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}}}ts.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??mo;return new me(r(t.byteLength),t)};var rs=G(ri(),1),Yx=8,Jx=1024*1024*4,dn;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(dn||(dn={}));var Au=t=>{let e=Ne.decode(t);return Au.bytes=Ne.encodingLength(e),e};Au.bytes=0;function pn(t){return async function*(r){let n=new me,i=dn.LENGTH,s=-1,o=t?.lengthDecoder??Au,a=t?.maxLengthLength??Yx,c=t?.maxDataLength??Jx;for await(let u of r)for(n.append(u);n.byteLength>0;){if(i===dn.LENGTH)try{if(s=o(n),s<0)throw(0,rs.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(s>c)throw(0,rs.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let f=o.bytes;n.consume(f),t?.onLength!=null&&t.onLength(s),i=dn.DATA}catch(f){if(f instanceof RangeError){if(n.byteLength>a)throw(0,rs.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw f}if(i===dn.DATA){if(n.byteLength<s)break;let f=n.sublist(0,s);n.consume(s),t?.onData!=null&&t.onData(f),yield f,i=dn.LENGTH}}if(n.byteLength>0)throw(0,rs.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}}pn.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:s,value:o}=await t.next(r);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}}();return pn({...e??{},onLength:s=>{r=s}})(n)};function Qx(t){return t[Symbol.asyncIterator]!=null}function ew(...t){let e=[];for(let r of t)Qx(r)||e.push(r);return e.length===t.length?function*(){for(let r of e)yield*r}():async function*(){let r=xt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(t.map(async n=>{for await(let i of n)r.push(i)})),r.end()}catch(n){r.end(n)}}),yield*r}()}var xo=ew;function Ph(t,...e){if(t==null)throw new Error("Empty pipeline");if(Cu(t)){let n=t;t=()=>n.source}else if(Fh(t)||Uh(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&Cu(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++)Cu(r[n])&&(r[n]=rw(r[n]));return tw(...r)}var tw=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},Uh=t=>t?.[Symbol.asyncIterator]!=null,Fh=t=>t?.[Symbol.iterator]!=null,Cu=t=>t==null?!1:t.sink!=null&&t.source!=null,rw=t=>e=>{let r=t.sink(e);if(r?.then!=null){let n=xt({objectMode:!0});r.then(()=>{n.end()},o=>{n.end(o)});let i,s=t.source;if(Uh(s))i=async function*(){yield*s,n.end()};else if(Fh(s))i=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return xo(n,i())}return t.source};var Zu=G(pi(),1),Qu=G(pi(),1),yd=G(pi(),1),gd=G(pi(),1),bd=G(pi(),1),ht;(function(t){t[t.FIN=0]="FIN",t[t.STOP_SENDING=1]="STOP_SENDING",t[t.RESET=2]="RESET"})(ht||(ht={}));var ef=class extends bd.MessageType{constructor(){super("webrtc.pb.Message",[{no:1,name:"flag",kind:"enum",opt:!0,T:()=>["webrtc.pb.Message.Flag",ht]},{no:2,name:"message",kind:"scalar",opt:!0,T:12}])}create(e){let r={};return globalThis.Object.defineProperty(r,gd.MESSAGE_TYPE,{enumerable:!1,value:this}),e!==void 0&&(0,yd.reflectionMergePartial)(this,r,e),r}internalBinaryRead(e,r,n,i){let s=i??this.create(),o=e.pos+r;for(;e.pos<o;){let[a,c]=e.tag();switch(a){case 1:s.flag=e.int32();break;case 2:s.message=e.bytes();break;default:let u=n.readUnknownField;if(u==="throw")throw new globalThis.Error(`Unknown field ${a} (wire type ${c}) for ${this.typeName}`);let f=e.skip(c);u!==!1&&(u===!0?Qu.UnknownFieldHandler.onRead:u)(this.typeName,s,a,c,f)}}return s}internalBinaryWrite(e,r,n){e.flag!==void 0&&r.tag(1,Zu.WireType.Varint).int32(e.flag),e.message!==void 0&&r.tag(2,Zu.WireType.LengthDelimited).bytes(e.message);let i=n.writeUnknownFields;return i!==!1&&(i==!0?Qu.UnknownFieldHandler.onWrite:i)(this.typeName,e,r),r}},Jo=new ef;var tf=lt("libp2p:webrtc:stream");var Y;(function(t){t[t.OPEN=0]="OPEN",t[t.READ_CLOSED=1]="READ_CLOSED",t[t.WRITE_CLOSED=2]="WRITE_CLOSED",t[t.CLOSED=3]="CLOSED"})(Y||(Y={}));function Zo(t){throw new Error("Case not handled in switch")}var rf=class{state=Y.OPEN;isWriteClosed(){return this.state===Y.CLOSED||this.state===Y.WRITE_CLOSED}transition({direction:e,flag:r}){let n=this.state;if(this.state===Y.CLOSED)return[n,Y.CLOSED];if(e==="inbound")switch(r){case ht.FIN:this.state===Y.OPEN?this.state=Y.READ_CLOSED:this.state===Y.WRITE_CLOSED&&(this.state=Y.CLOSED);break;case ht.STOP_SENDING:this.state===Y.OPEN?this.state=Y.WRITE_CLOSED:this.state===Y.READ_CLOSED&&(this.state=Y.CLOSED);break;case ht.RESET:this.state=Y.CLOSED;break;default:Zo(r)}else switch(r){case ht.FIN:this.state===Y.OPEN?this.state=Y.WRITE_CLOSED:this.state===Y.READ_CLOSED&&(this.state=Y.CLOSED);break;case ht.STOP_SENDING:this.state===Y.OPEN?this.state=Y.READ_CLOSED:this.state===Y.WRITE_CLOSED&&(this.state=Y.CLOSED);break;case ht.RESET:this.state=Y.CLOSED;break;default:Zo(r)}return[n,this.state]}},Ht=class{id;stat;metadata;channel;streamState=new rf;_src;_innersrc=xt();opened=nr();_sinkCalled=!1;closeWritePromise=nr();closeCb;constructor(e){switch(this.channel=e.channel,this.channel.binaryType="arraybuffer",this.id=this.channel.label,this.stat=e.stat,this.channel.readyState){case"open":this.opened.resolve();break;case"closed":case"closing":this.streamState.state=Y.CLOSED,(this.stat.timeline.close===void 0||this.stat.timeline.close===0)&&(this.stat.timeline.close=new Date().getTime()),this.opened.resolve();break;case"connecting":break;default:Zo(this.channel.readyState)}this.metadata=e.metadata??{},this.channel.onopen=n=>{this.stat.timeline.open=new Date().getTime(),this.opened.resolve()},this.channel.onclose=n=>{this.close()},this.channel.onerror=n=>{let i=n.error;this.abort(i)};let r=this;this.channel.onmessage=async({data:n})=>{n===null||n.length===0||this._innersrc.push(new Uint8Array(n))},this._src=Ph(this._innersrc,pn(),n=>async function*(){for await(let i of n){let s=r.processIncomingProtobuf(i.subarray());s!=null&&(yield new me(s))}}())}set source(e){}get source(){return this._src}async sink(e){if(this._sinkCalled)throw new Error("sink already called on this stream");await this.opened.promise;try{await this._sink(e)}finally{this.closeWrite()}}async _sink(e){let r=this._closeWriteIterable();for await(let n of xo(r,e)){if(this.streamState.isWriteClosed())return;let i=Jo.toBinary({message:n.subarray()}),s=ts.single(i);this.channel.send(s.subarray())}}processIncomingProtobuf(e){let r=Jo.fromBinary(e);if(r.flag!==void 0){let[n,i]=this.streamState.transition({direction:"inbound",flag:r.flag});if(n!==i)switch(i){case Y.READ_CLOSED:this._innersrc.end();break;case Y.WRITE_CLOSED:this.closeWritePromise.resolve();break;case Y.CLOSED:this.close();break;case Y.OPEN:break;default:Zo(i)}}return r.message}close(){this.stat.timeline.close=new Date().getTime(),this.streamState.state=Y.CLOSED,this._innersrc.end(),this.closeWritePromise.resolve(),this.channel.close(),this.closeCb!==void 0&&this.closeCb(this)}closeRead(){let[e,r]=this.streamState.transition({direction:"outbound",flag:ht.STOP_SENDING});e!==r&&((e===Y.OPEN||e===Y.WRITE_CLOSED)&&(this._sendFlag(ht.STOP_SENDING),this._innersrc.end()),r===Y.CLOSED&&this.close())}closeWrite(){let[e,r]=this.streamState.transition({direction:"outbound",flag:ht.FIN});e!==r&&((e===Y.OPEN||e===Y.READ_CLOSED)&&(this._sendFlag(ht.FIN),this.closeWritePromise.resolve()),r===Y.CLOSED&&this.close())}abort(e){tf.error(`An error occurred, closing the stream for reading and writing: ${e.message}`),this.close()}reset(){let[e,r]=this.streamState.transition({direction:"outbound",flag:ht.RESET});e!==r&&(this._sendFlag(ht.RESET),this.close())}_sendFlag(e){try{tf.trace("Sending flag: %s",e.toString());let r=Jo.toBinary({flag:e});this.channel.send(ts.single(r).subarray())}catch(r){r instanceof Error&&tf.error(`Exception while sending flag ${e}: ${r.message}`)}}_closeWriteIterable(){let e=this;return{async*[Symbol.asyncIterator](){await e.closeWritePromise.promise,yield new Uint8Array(0)}}}eq(e){return e instanceof Ht?e.channel.id===this.channel.id:!1}};var bn=class{protocol;peerConnection;streamBuffer=[];metrics;constructor(e,r,n="/webrtc"){this.protocol=n,this.peerConnection=e,this.peerConnection.ondatachannel=({channel:i})=>{let s=new Ht({channel:i,stat:{direction:"inbound",timeline:{open:0}},closeCb:o=>{this.streamBuffer=this.streamBuffer.filter(a=>!o.eq(a))}});this.streamBuffer.push(s)},this.metrics=r}createStreamMuxer(e){return new nf(this.peerConnection,this.streamBuffer,this.protocol,e,this.metrics)}},nf=class{protocol;peerConnection;metrics;streams=[];init;close=()=>{};source=co();sink=uo;constructor(e,r,n="/webrtc",i,s){this.protocol=n,this.init=i,this.peerConnection=e,this.peerConnection.ondatachannel=({channel:a})=>{let c=new Ht({channel:a,stat:{direction:"inbound",timeline:{open:0}},closeCb:this.wrapStreamEnd(i?.onIncomingStream)});this.streams.push(c),i?.onIncomingStream!=null&&(this.metrics?.increment({incoming_stream:!0}),i.onIncomingStream(c))},this.streams=r.filter(a=>a.stat.timeline.close==null).map(a=>(a.closeCb=this.wrapStreamEnd(i?.onStreamEnd),a));let o=i?.onIncomingStream;o!=null&&this.streams.forEach(a=>{o(a)})}newStream(){let e=this.peerConnection.createDataChannel(""),r=i=>{this.metrics?.increment({stream_end:!0}),this.init?.onStreamEnd?.(i)},n=new Ht({channel:e,stat:{direction:"outbound",timeline:{open:0}},closeCb:this.wrapStreamEnd(r)});return this.streams.push(n),this.metrics?.increment({outgoing_stream:!0}),n}wrapStreamEnd(e){let r=this;return n=>{r.streams=r.streams.filter(i=>!(n instanceof Ht&&n.eq(i))),e?.(n)}}};var bf=G(uf(),1),ip=G(Yd(),1),sp=G(xn(),1),mf=G(gf(),1),op=G(np(),1);function Kv(){sp.default._configure(),bf.default._configure(ip.default),mf.default._configure(op.default)}Kv();var ap=["uint64","int64","sint64","fixed64","sfixed64"];function Vv(t){for(let e of ap){if(t[e]==null)continue;let r=t[e];t[e]=function(){return BigInt(r.call(this).toString())}}return t}function xf(t){return Vv(new bf.default(t))}function qv(t){for(let e of ap){if(t[e]==null)continue;let r=t[e];t[e]=function(n){return r.call(this,n.toString())}}return t}function wf(){return qv(mf.default.create())}function Br(t,e){let r=xf(t instanceof Uint8Array?t:t.subarray());return e.decode(r)}function Ir(t,e){let r=wf();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var gi;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(gi||(gi={}));function na(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function ps(t){function e(i){if(t[i.toString()]==null)throw new Error("Invalid enum value");return t[i]}let r=function(s,o){let a=e(s);o.int32(a)},n=function(s){let o=s.int32();return e(o)};return na("enum",gi.VARINT,r,n)}function kr(t,e){return na("message",gi.LENGTH_DELIMITED,t,e)}var Ct;(function(t){let e;(function(i){i.SDP_OFFER="SDP_OFFER",i.SDP_ANSWER="SDP_ANSWER",i.ICE_CANDIDATE="ICE_CANDIDATE"})(e=t.Type||(t.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=()=>ps(r)}(e=t.Type||(t.Type={}));let n;t.codec=()=>(n==null&&(n=kr((i,s,o={})=>{o.lengthDelimited!==!1&&s.fork(),i.type!=null&&(s.uint32(8),t.Type.codec().encode(i.type,s)),i.data!=null&&(s.uint32(18),s.string(i.data)),o.lengthDelimited!==!1&&s.ldelim()},(i,s)=>{let o={},a=s==null?i.len:i.pos+s;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:o.type=t.Type.codec().decode(i);break;case 2:o.data=i.string();break;default:i.skipType(c&7);break}}return o})),n),t.encode=i=>Ir(i,t.codec()),t.decode=i=>Br(i,t.codec())})(Ct||(Ct={}));var Ep=G(wp(),1);var vp=(0,Ep.detect)(),sa=vp!=null&&vp.name==="firefox",ia=lt("libp2p:webrtc:peer:util"),Ef=async(t,e,r)=>{for(;;){let n=await Promise.race([t.promise,r.read()]);if(n instanceof Object){let i=n;if(i.type!==Ct.Type.ICE_CANDIDATE)throw new Error("expected only ice candidates");if(i.data==null||i.data===""){ia.trace("end-of-candidates received");break}ia.trace("received new ICE candidate: %s",i.data);try{await e.addIceCandidate(new RTCIceCandidate(JSON.parse(i.data)))}catch(s){throw ia.error("bad candidate received: ",s),new Error("bad candidate received")}}else break}await t.promise};function Sf(t,e){t[sa?"oniceconnectionstatechange":"onconnectionstatechange"]=r=>{switch(ia.trace("receiver peerConnectionState state: ",t.connectionState),sa?t.iceConnectionState:t.connectionState){case"connected":e.resolve();break;case"failed":case"disconnected":case"closed":e.reject();break;default:break}}}var Xv=30*1e3,bi=lt("libp2p:webrtc:peer");async function Sp({rtcConfiguration:t,stream:e}){let r=AbortSignal.timeout(Xv),n=_u(vu(e,r)).pb(Ct),i=new RTCPeerConnection(t),s=new bn(i),o=nr(),a=nr();r.onabort=()=>{o.reject()},i.onicecandidate=({candidate:l})=>{a.promise.then(()=>{n.write({type:Ct.Type.ICE_CANDIDATE,data:l!=null?JSON.stringify(l.toJSON()):""})},h=>{bi.error("cannot set candidate since sending answer failed",h)})},Sf(i,o);let c=await n.read();if(c.type!==Ct.Type.SDP_OFFER)throw new Error(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);let u=new RTCSessionDescription({type:"offer",sdp:c.data});await i.setRemoteDescription(u).catch(l=>{throw bi.error("could not execute setRemoteDescription",l),new Error("Failed to set remoteDescription")});let f=await i.createAnswer().catch(l=>{throw bi.error("could not execute createAnswer",l),a.reject(l),new Error("Failed to create answer")});return n.write({type:Ct.Type.SDP_ANSWER,data:f.sdp}),await i.setLocalDescription(f).catch(l=>{throw bi.error("could not execute setLocalDescription",l),a.reject(l),new Error("Failed to set localDescription")}),a.resolve(),await Ef(o,i,n),[i,s]}async function _p({rtcConfiguration:t,signal:e,stream:r}){let n=_u(vu(r,e)).pb(Ct),i=new RTCPeerConnection(t),s=new bn(i),o=nr();Sf(i,o),e.onabort=o.reject;let a=i.createDataChannel("init");i.onicecandidate=({candidate:l})=>{n.write({type:Ct.Type.ICE_CANDIDATE,data:l!=null?JSON.stringify(l.toJSON()):""})};let c=await i.createOffer();n.write({type:Ct.Type.SDP_OFFER,data:c.sdp}),await i.setLocalDescription(c).catch(l=>{throw bi.error("could not execute setLocalDescription",l),new Error("Failed to set localDescription")});let u=await n.read();if(u.type!==Ct.Type.SDP_ANSWER)throw new Error("remote should send an SDP answer");let f=new RTCSessionDescription({type:"answer",sdp:u.data});return await i.setRemoteDescription(f).catch(l=>{throw bi.error("could not execute setRemoteDescription",l),new Error("Failed to set remoteDescription")}),await Ef(o,i,n),a.close(),[i,s]}var oa=class extends EventTarget{#e=new Map;listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){super.addEventListener(e,r,n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:r,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,r,n){super.removeEventListener(e.toString(),r??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:s})=>s!==r),this.#e.set(e,i))}dispatchEvent(e){let r=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:i})=>!i),this.#e.set(e.type,n)),r}safeDispatchEvent(e,r){return this.dispatchEvent(new Yv(e,r))}},_f=class extends Event{detail;constructor(e,r){super(e,r),this.detail=r?.detail}},Yv=globalThis.CustomEvent??_f;var aa=class extends oa{opts;constructor(e){super(),this.opts=e}getBaseAddress(e){let r=e.toString().split(ys);if(r.length<2)throw ti("base address not found");return Qn(r[0])}listeningAddrs=[];async listen(e){let r=this.getBaseAddress(e),i=this.opts.transportManager.transportForMultiaddr(r)?.createListener({...this.opts});await i?.listen(r);let s=e.encapsulate(`/p2p/${this.opts.peerId.toString()}`);this.listeningAddrs.push(s),i?.addEventListener("close",()=>{this.listeningAddrs=this.listeningAddrs.filter(o=>o!==s)})}getAddrs(){return this.listeningAddrs}async close(){}};var Ap=lt("libp2p:webrtc:peer"),ys="/webrtc",Af="/webrtc-signaling/0.0.1",Jv=pe("webrtc").code,ca=class{components;init;_started=!1;constructor(e,r){this.components=e,this.init=r}isStarted(){return this._started}async start(){await this.components.registrar.handle(Af,e=>{this._onProtocol(e).catch(r=>{Ap.error("failed to handle incoming connect from %p",e.connection.remotePeer,r)})}),this._started=!0}async stop(){await this.components.registrar.unhandle(Af),this._started=!1}createListener(e){return new aa(this.components)}[Symbol.toStringTag]="@libp2p/webrtc";[Xs]=!0;filter(e){return e.filter(r=>r.protoCodes().includes(Jv))}splitAddr(e){let r=e.toString().split(`${ys}/`);if(r.length!==2)throw new ee("invalid multiaddr",kt.ERR_INVALID_MULTIADDR);let n=Qn(r[0]),s=Qn("/"+r[1]).getPeerId();if(s==null)throw new ee("bad destination",kt.ERR_INVALID_MULTIADDR);let o=n.protos().pop();if(o===void 0)throw new ee("invalid multiaddr",kt.ERR_INVALID_MULTIADDR);return o.name!=="p2p"&&(n=n.encapsulate(`/p2p/${s}`)),{baseAddr:n,peerId:$i(s)}}async dial(e,r){Ap.trace("dialing address: ",e);let{baseAddr:n,peerId:i}=this.splitAddr(e);if(r.signal==null){let a=new AbortController;r.signal=a.signal}let o=await(await this.components.transportManager.dial(n)).newStream([Af],r);try{let[a,c]=await _p({stream:o,rtcConfiguration:this.init.rtcConfiguration,signal:r.signal}),u=n.encapsulate(`${ys}/p2p/${i.toString()}`),f=await r.upgrader.upgradeOutbound(new ln({peerConnection:a,timeline:{open:Date.now()},remoteAddr:u}),{skipProtection:!0,skipEncryption:!0,muxerFactory:c});return o.close(),f}catch(a){throw o.reset(),a}}async _onProtocol({connection:e,stream:r}){try{let[n,i]=await Sp({rtcConfiguration:this.init.rtcConfiguration,connection:e,stream:r}),s=e.remoteAddr.getPeerId(),o=e.remoteAddr.encapsulate(`${ys}/p2p/${s}`);await this.components.upgrader.upgradeInbound(new ln({peerConnection:n,timeline:{open:new Date().getTime()},remoteAddr:o}),{skipEncryption:!0,skipProtection:!0,muxerFactory:i})}catch(n){throw r.reset(),n}}};function ua(t){return t[Symbol.asyncIterator]!=null}var fa=t=>{let e=Ne.encodingLength(t),r=mt(e);return Ne.encode(t,r),fa.bytes=e,r};fa.bytes=0;function la(t,e){e=e??{};let r=e.lengthEncoder??fa;function*n(i){let s=r(i.byteLength);s instanceof Uint8Array?yield s:yield*s,i instanceof Uint8Array?yield i:yield*i}return ua(t)?async function*(){for await(let i of t)yield*n(i)}():function*(){for(let i of t)yield*n(i)}()}la.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??fa;return new me(r(t.byteLength),t)};var mi=G(ri(),1);var Zv=8,Qv=1024*1024*4,vn;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(vn||(vn={}));var Df=t=>{let e=Ne.decode(t);return Df.bytes=Ne.encodingLength(e),e};Df.bytes=0;function Cf(t,e){let r=new me,n=vn.LENGTH,i=-1,s=e?.lengthDecoder??Df,o=e?.maxLengthLength??Zv,a=e?.maxDataLength??Qv;function*c(){for(;r.byteLength>0;){if(n===vn.LENGTH)try{if(i=s(r),i<0)throw(0,mi.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(i>a)throw(0,mi.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let u=s.bytes;r.consume(u),e?.onLength!=null&&e.onLength(i),n=vn.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>o)throw(0,mi.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw u}if(n===vn.DATA){if(r.byteLength<i)break;let u=r.sublist(0,i);r.consume(i),e?.onData!=null&&e.onData(u),yield u,n=vn.LENGTH}}}return ua(t)?async function*(){for await(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,mi.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let u of t)r.append(u),yield*c();if(r.byteLength>0)throw(0,mi.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}Cf.fromReader=(t,e)=>{let r=1,n=async function*(){for(;;)try{let{done:s,value:o}=await t.next(r);if(s===!0)return;o!=null&&(yield o)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}}();return Cf(n,{...e??{},onLength:s=>{r=s}})};var ha=G(ri(),1),Cp=t=>Ne.decode(t);Cp.bytes=0;function Tf(t,e={}){let r=xt();t.sink(r).catch(o=>{r.end(o)}),t.sink=async o=>{for await(let a of o)r.push(a)};let n=t.source;t.source[Symbol.iterator]!=null?n=t.source[Symbol.iterator]():t.source[Symbol.asyncIterator]!=null&&(n=t.source[Symbol.asyncIterator]());let i=new me,s={read:async o=>{if(o==null){let{done:c,value:u}=await n.next();return c===!0?new me:u}for(;i.byteLength<o;){let{value:c,done:u}=await n.next();if(u===!0)throw(0,ha.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF");i.append(c)}let a=i.sublist(0,o);return i.consume(o),a},readLP:async()=>{let o=-1,a=new me,c=e?.lengthDecoder??Cp;for(;;){a.append(await s.read(1));try{o=c(a)}catch(u){if(u instanceof RangeError)continue;throw u}if(o>-1)break;if(e?.maxLengthLength!=null&&a.byteLength>e.maxLengthLength)throw(0,ha.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG")}if(e?.maxDataLength!=null&&o>e.maxDataLength)throw(0,ha.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");return await s.read(o)},readPB:async o=>{let a=await s.readLP();if(a==null)throw new Error("Value is null");let c=a instanceof Uint8Array?a:a.subarray();return o.decode(c)},write:o=>{o instanceof Uint8Array?r.push(o):r.push(o.subarray())},writeLP:o=>{s.write(la.single(o,e))},writePB:(o,a)=>{s.writeLP(a.encode(o))},pb:o=>({read:async()=>await s.readPB(o),write:a=>{s.writePB(a,o)},unwrap:()=>s}),unwrap:()=>{let o=t.source;return t.source=async function*(){yield*i,yield*o}(),t}};return s}function Bf(){let t=nr(),e=!1;return{sink:async r=>{if(e)throw new Error("already piped");e=!0,t.resolve(r)},source:async function*(){yield*await t.promise}()}}function Dp(){let t=Bf(),e=Bf();return[{source:t.source,sink:e.sink},{source:e.source,sink:t.sink}]}async function*If(...t){let e=xt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(t.map(async r=>{for await(let n of r)e.push(n)})),e.end()}catch(r){e.end(r)}}),yield*e}var t3=(...t)=>{let e;for(;t.length>0;)e=t.shift()(e);return e},Tp=t=>t!=null&&(typeof t[Symbol.asyncIterator]=="function"||typeof t[Symbol.iterator]=="function"||typeof t.next=="function"),kf=t=>t!=null&&typeof t.sink=="function"&&Tp(t.source),r3=t=>e=>{let r=t.sink(e);if(r.then!=null){let n=xt({objectMode:!0});return r.then(()=>{n.end()},s=>{n.end(s)}),If(n,async function*(){yield*t.source,n.end()}())}return t.source};function Bp(t,...e){if(kf(t)){let n=t;t=()=>n.source}else if(Tp(t)){let n=t;t=()=>n}let r=[t,...e];if(r.length>1&&kf(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++)kf(r[n])&&(r[n]=r3(r[n]));return t3(...r)}var Ip=!!globalThis.process?.env?.DUMP_SESSION_KEYS;var fy=G(Up(),1),wi=G(ty(),1),Ca=G(ny(),1),$f=G(jf(),1),ly={hashSHA256(t){return(0,Ca.hash)(t)},getHKDF(t,e){let i=new fy.HKDF(Ca.SHA256,e,t).expand(96),s=i.subarray(0,32),o=i.subarray(32,64),a=i.subarray(64,96);return[s,o,a]},generateX25519KeyPair(){let t=wi.generateKeyPair();return{publicKey:t.publicKey,privateKey:t.secretKey}},generateX25519KeyPairFromSeed(t){let e=wi.generateKeyPairFromSeed(t);return{publicKey:e.publicKey,privateKey:e.secretKey}},generateX25519SharedKey(t,e){return wi.sharedKey(t,e)},chaCha20Poly1305Encrypt(t,e,r,n){return new $f.ChaCha20Poly1305(n).seal(e,t,r)},chaCha20Poly1305Decrypt(t,e,r,n,i){return new $f.ChaCha20Poly1305(n).open(e,t,r,i)}};var Xf=G(jf(),1);var lE=t=>globalThis.Buffer?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t),vi=t=>{let e=lE(2);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(0,t,!1),e};vi.bytes=2;var vs=t=>{if(t.length<2)throw RangeError("Could not decode int16BE");return t instanceof Uint8Array?new DataView(t.buffer,t.byteOffset,t.byteLength).getUint16(0,!1):t.getUint16(0)};vs.bytes=2;function hy(t){return ye([t.ne,t.ciphertext],t.ne.length+t.ciphertext.length)}function dy(t){return ye([t.ne,t.ns,t.ciphertext],t.ne.length+t.ns.length+t.ciphertext.length)}function py(t){return ye([t.ns,t.ciphertext],t.ns.length+t.ciphertext.length)}function yy(t){if(t.length<32)throw new Error("Cannot decode stage 0 MessageBuffer: length less than 32 bytes.");return{ne:t.subarray(0,32),ciphertext:t.subarray(32,t.length),ns:new Uint8Array(0)}}function gy(t){if(t.length<80)throw new Error("Cannot decode stage 1 MessageBuffer: length less than 80 bytes.");return{ne:t.subarray(0,32),ns:t.subarray(32,80),ciphertext:t.subarray(80,t.length)}}function by(t){if(t.length<48)throw new Error("Cannot decode stage 2 MessageBuffer: length less than 48 bytes.");return{ne:new Uint8Array(0),ns:t.subarray(0,48),ciphertext:t.subarray(48,t.length)}}function xy(t,e){return async function*(r){for await(let n of r)for(let i=0;i<n.length;i+=65519){let s=i+65519;s>n.length&&(s=n.length);let o=t.encrypt(n.subarray(i,s),t.session);e?.encryptedPackets.increment(),yield vi(o.byteLength),yield o}}}function wy(t,e){return async function*(r){for await(let n of r)for(let i=0;i<n.length;i+=65535){let s=i+65535;if(s>n.length&&(s=n.length),s-Xf.TAG_LENGTH<i)throw new Error("Invalid chunk");let o=n.subarray(i,s),a=n.subarray(i,s-Xf.TAG_LENGTH),{plaintext:c,valid:u}=t.decrypt(o,t.session,a);if(!u)throw e?.decryptErrors.increment(),new Error("Failed to validate decrypted chunk");e?.decryptedPackets.increment(),yield c}}}var En=class extends Error{constructor(e="Unexpected Peer"){super(e),this.code=En.code}static get code(){return"ERR_UNEXPECTED_PEER"}},Or=class extends Error{constructor(e="Invalid crypto exchange"){super(e),this.code=Or.code}static get code(){return"ERR_INVALID_CRYPTO_EXCHANGE"}};var hN=G(Cs(),1),dN=G(P1(),1);var E6=G(we(),1);var v0={};Ze(v0,{Ed25519PrivateKey:()=>kn,Ed25519PublicKey:()=>Bs,generateKeyPair:()=>V4,generateKeyPairFromSeed:()=>G1,unmarshalEd25519PrivateKey:()=>M4,unmarshalEd25519PublicKey:()=>K4});var Tn=G(Ge("crypto"),1),U1=Ge("util");var P4=(0,U1.promisify)(Tn.default.generateKeyPair),Bn=32,br=64,Ha=32,U4=64;function F1(t){let r=Tn.default.createPrivateKey({format:"jwk",key:{crv:"Ed25519",x:"",d:$(t,"base64url"),kty:"OKP"}}).export({format:"jwk"});if(r.x==null||r.x==="")throw new Error("Could not export JWK public key");return Ae(r.x,"base64url")}async function M1(){let t=await P4("ed25519",{publicKeyEncoding:{type:"spki",format:"jwk"},privateKeyEncoding:{type:"pkcs8",format:"jwk"}}),e=Ae(t.privateKey.d,"base64url"),r=Ae(t.privateKey.x,"base64url");return{privateKey:H1(e,r),publicKey:r}}async function K1(t){if(t.length!==Ha)throw new TypeError('"seed" must be 32 bytes in length.');if(!(t instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let e=F1(t);return{privateKey:H1(t,e),publicKey:e}}async function V1(t,e){if(!(t instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');let r,n;if(t.byteLength===br)r=t.subarray(0,32),n=t.subarray(32);else if(t.byteLength===Ha)r=t.subarray(0,32),n=F1(r);else throw new TypeError('"key" must be 64 or 32 bytes in length.');let i=Tn.default.createPrivateKey({format:"jwk",key:{crv:"Ed25519",d:$(r,"base64url"),x:$(n,"base64url"),kty:"OKP"}});return Tn.default.sign(null,e,i)}async function q1(t,e,r){if(t.byteLength!==Bn)throw new TypeError('"key" must be 32 bytes in length.');if(!(t instanceof Uint8Array))throw new TypeError('"key" must be a node.js Buffer, or Uint8Array.');if(e.byteLength!==U4)throw new TypeError('"sig" must be 64 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"sig" must be a node.js Buffer, or Uint8Array.');let n=Tn.default.createPublicKey({format:"jwk",key:{crv:"Ed25519",x:$(t,"base64url"),kty:"OKP"}});return Tn.default.verify(null,r,n,e)}function H1(t,e){let r=new Uint8Array(br);for(let n=0;n<Ha;n++)r[n]=t[n],r[Ha+n]=e[n];return r}var In=G(Ge("crypto"),1);function x0(t){let e=t?.algorithm??"aes-128-gcm",r=t?.keyLength??16,n=t?.nonceLength??12,i=t?.digest??"sha256",s=t?.saltLength??16,o=t?.iterations??32767,a=t?.algorithmTagLength??16;async function c(p,d){let y=In.default.randomBytes(n),g=In.default.createCipheriv(e,d,y),b=ye([g.update(p),g.final()]);return ye([y,b,g.getAuthTag()])}async function u(p,d){let y=In.default.randomBytes(s);typeof d=="string"&&(d=Ae(d));let g=In.default.pbkdf2Sync(d,y,o,r,i);return ye([y,await c(Uint8Array.from(p),g)])}async function f(p,d){let y=p.subarray(0,n),g=p.subarray(n,p.length-a),b=p.subarray(g.length+n),v=In.default.createDecipheriv(e,d,y);return v.setAuthTag(b),ye([v.update(g),v.final()])}async function l(p,d){let y=p.subarray(0,s),g=p.subarray(s);typeof d=="string"&&(d=Ae(d));let b=In.default.pbkdf2Sync(d,y,o,r,i);return f(g,b)}return{encrypt:u,decrypt:l}}async function Ci(t,e){let n=await x0().encrypt(t,e);return Gn.encode(n)}var Le;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.Secp256k1="Secp256k1"})(Le||(Le={}));var w0;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.Secp256k1=2]="Secp256k1"})(w0||(w0={}));(function(t){t.codec=()=>ps(w0)})(Le||(Le={}));var mr;(function(t){let e;t.codec=()=>(e==null&&(e=kr((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),Le.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.Type=Le.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Ir(r,t.codec()),t.decode=r=>Br(r,t.codec())})(mr||(mr={}));var xr;(function(t){let e;t.codec=()=>(e==null&&(e=kr((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),r.Type!=null&&(n.uint32(8),Le.codec().encode(r.Type,n)),r.Data!=null&&(n.uint32(18),n.bytes(r.Data)),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.Type=Le.codec().decode(r);break;case 2:i.Data=r.bytes();break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Ir(r,t.codec()),t.decode=r=>Br(r,t.codec())})(xr||(xr={}));var Bs=class{_key;constructor(e){this._key=Di(e,Bn)}async verify(e,r){return q1(this._key,r,e)}marshal(){return this._key}get bytes(){return mr.encode({Type:Le.Ed25519,Data:this.marshal()}).subarray()}equals(e){return qe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}},kn=class{_key;_publicKey;constructor(e,r){this._key=Di(e,br),this._publicKey=Di(r,Bn)}async sign(e){return V1(this._key,e)}get public(){return new Bs(this._publicKey)}marshal(){return this._key}get bytes(){return xr.encode({Type:Le.Ed25519,Data:this.marshal()}).subarray()}equals(e){return qe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}async id(){let e=Hr.digest(this.public.bytes);return Fe.encode(e.bytes).substring(1)}async export(e,r="libp2p-key"){if(r==="libp2p-key")return Ci(this.bytes,e);throw new ee(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function M4(t){if(t.length>br){t=Di(t,br+Bn);let n=t.subarray(0,br),i=t.subarray(br,t.length);return new kn(n,i)}t=Di(t,br);let e=t.subarray(0,br),r=t.subarray(Bn);return new kn(e,r)}function K4(t){return t=Di(t,Bn),new Bs(t)}async function V4(){let{privateKey:t,publicKey:e}=await M1();return new kn(t,e)}async function G1(t){let{privateKey:e,publicKey:r}=await K1(t);return new kn(e,r)}function Di(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new ee(`Key must be a Uint8Array of length ${e}, got ${t.length}`,"ERR_INVALID_KEY_TYPE");return t}var q4={"P-256":"prime256v1","P-384":"secp384r1","P-521":"secp521r1"},H4=Object.keys(q4),bL=H4.join(" / ");var k0={};Ze(k0,{RsaPrivateKey:()=>Ri,RsaPublicKey:()=>Ps,fromJwk:()=>g6,generateKeyPair:()=>b6,unmarshalRsaPrivateKey:()=>p6,unmarshalRsaPublicKey:()=>y6});var Os=G(we(),1);var QL=G(Y1(),1);var On=G(Ge("crypto"),1),hg=Ge("util");var W4=G(Ge("crypto"),1);var ie=BigInt(0),Te=BigInt(1),sn=BigInt(2),Ls=BigInt(3),J1=BigInt(8),Ue=Object.freeze({a:ie,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:Te,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),Z1=(t,e)=>(t+e/sn)/e,Ga={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(t){let{n:e}=Ue,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Te*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,o=BigInt("0x100000000000000000000000000000000"),a=Z1(s*t,e),c=Z1(-n*t,e),u=R(t-a*r-c*i,e),f=R(-a*n-c*s,e),l=u>o,h=f>o;if(l&&(u=e-u),h&&(f=e-f),u>o||f>o)throw new Error("splitScalarEndo: Endomorphism failed, k="+t);return{k1neg:l,k1:u,k2neg:h,k2:f}}},$t=32,Ii=32,j4=32,Q1=$t+1,eg=2*$t+1;function tg(t){let{a:e,b:r}=Ue,n=R(t*t),i=R(n*t);return R(i+e*t+r)}var Wa=Ue.a===ie,Xa=class extends Error{constructor(e){super(e)}};function rg(t){if(!(t instanceof ae))throw new TypeError("JacobianPoint expected")}var ae=class{constructor(e,r,n){this.x=e,this.y=r,this.z=n}static fromAffine(e){if(!(e instanceof ge))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(ge.ZERO)?ae.ZERO:new ae(e.x,e.y,Te)}static toAffineBatch(e){let r=Z4(e.map(n=>n.z));return e.map((n,i)=>n.toAffine(r[i]))}static normalizeZ(e){return ae.toAffineBatch(e).map(ae.fromAffine)}equals(e){rg(e);let{x:r,y:n,z:i}=this,{x:s,y:o,z:a}=e,c=R(i*i),u=R(a*a),f=R(r*u),l=R(s*c),h=R(R(n*a)*u),p=R(R(o*i)*c);return f===l&&h===p}negate(){return new ae(this.x,R(-this.y),this.z)}double(){let{x:e,y:r,z:n}=this,i=R(e*e),s=R(r*r),o=R(s*s),a=e+s,c=R(sn*(R(a*a)-i-o)),u=R(Ls*i),f=R(u*u),l=R(f-sn*c),h=R(u*(c-l)-J1*o),p=R(sn*r*n);return new ae(l,h,p)}add(e){rg(e);let{x:r,y:n,z:i}=this,{x:s,y:o,z:a}=e;if(s===ie||o===ie)return this;if(r===ie||n===ie)return e;let c=R(i*i),u=R(a*a),f=R(r*u),l=R(s*c),h=R(R(n*a)*u),p=R(R(o*i)*c),d=R(l-f),y=R(p-h);if(d===ie)return y===ie?this.double():ae.ZERO;let g=R(d*d),b=R(d*g),v=R(f*g),w=R(y*y-b-sn*v),C=R(y*(v-w)-h*b),E=R(i*a*d);return new ae(w,C,E)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){let r=ae.ZERO;if(typeof e=="bigint"&&e===ie)return r;let n=sg(e);if(n===Te)return this;if(!Wa){let l=r,h=this;for(;n>ie;)n&Te&&(l=l.add(h)),h=h.double(),n>>=Te;return l}let{k1neg:i,k1:s,k2neg:o,k2:a}=Ga.splitScalar(n),c=r,u=r,f=this;for(;s>ie||a>ie;)s&Te&&(c=c.add(f)),a&Te&&(u=u.add(f)),f=f.double(),s>>=Te,a>>=Te;return i&&(c=c.negate()),o&&(u=u.negate()),u=new ae(R(u.x*Ga.beta),u.y,u.z),c.add(u)}precomputeWindow(e){let r=Wa?128/e+1:256/e+1,n=[],i=this,s=i;for(let o=0;o<r;o++){s=i,n.push(s);for(let a=1;a<2**(e-1);a++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,r){!r&&this.equals(ae.BASE)&&(r=ge.BASE);let n=r&&r._WINDOW_SIZE||1;if(256%n)throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");let i=r&&A0.get(r);i||(i=this.precomputeWindow(n),r&&n!==1&&(i=ae.normalizeZ(i),A0.set(r,i)));let s=ae.ZERO,o=ae.BASE,a=1+(Wa?128/n:256/n),c=2**(n-1),u=BigInt(2**n-1),f=2**n,l=BigInt(n);for(let h=0;h<a;h++){let p=h*c,d=Number(e&u);e>>=l,d>c&&(d-=f,e+=Te);let y=p,g=p+Math.abs(d)-1,b=h%2!==0,v=d<0;d===0?o=o.add(ja(b,i[y])):s=s.add(ja(v,i[g]))}return{p:s,f:o}}multiply(e,r){let n=sg(e),i,s;if(Wa){let{k1neg:o,k1:a,k2neg:c,k2:u}=Ga.splitScalar(n),{p:f,f:l}=this.wNAF(a,r),{p:h,f:p}=this.wNAF(u,r);f=ja(o,f),h=ja(c,h),h=new ae(R(h.x*Ga.beta),h.y,h.z),i=f.add(h),s=l.add(p)}else{let{p:o,f:a}=this.wNAF(n,r);i=o,s=a}return ae.normalizeZ([i,s])[0]}toAffine(e){let{x:r,y:n,z:i}=this,s=this.equals(ae.ZERO);e==null&&(e=s?J1:Ni(i));let o=e,a=R(o*o),c=R(a*o),u=R(r*a),f=R(n*c),l=R(i*o);if(s)return ge.ZERO;if(l!==Te)throw new Error("invZ was invalid");return new ge(u,f)}};ae.BASE=new ae(Ue.Gx,Ue.Gy,Te);ae.ZERO=new ae(ie,Te,ie);function ja(t,e){let r=e.negate();return t?r:e}var A0=new WeakMap,ge=class{constructor(e,r){this.x=e,this.y=r}_setWindowSize(e){this._WINDOW_SIZE=e,A0.delete(this)}hasEvenY(){return this.y%sn===ie}static fromCompressedHex(e){let r=e.length===32,n=on(r?e:e.subarray(1));if(!_0(n))throw new Error("Point is not on curve");let i=tg(n),s=J4(i),o=(s&Te)===Te;r?o&&(s=R(-s)):(e[0]&1)===1!==o&&(s=R(-s));let a=new ge(n,s);return a.assertValidity(),a}static fromUncompressedHex(e){let r=on(e.subarray(1,$t+1)),n=on(e.subarray($t+1,$t*2+1)),i=new ge(r,n);return i.assertValidity(),i}static fromHex(e){let r=Li(e),n=r.length,i=r[0];if(n===$t)return this.fromCompressedHex(r);if(n===Q1&&(i===2||i===3))return this.fromCompressedHex(r);if(n===eg&&i===4)return this.fromUncompressedHex(r);throw new Error(`Point.fromHex: received invalid point. Expected 32-${Q1} compressed bytes or ${eg} uncompressed bytes, not ${n}`)}static fromPrivateKey(e){return ge.BASE.multiply(Ja(e))}static fromSignature(e,r,n){let{r:i,s}=og(r);if(![0,1,2,3].includes(n))throw new Error("Cannot recover: invalid recovery bit");let o=T0(Li(e)),{n:a}=Ue,c=n===2||n===3?i+a:i,u=Ni(c,a),f=R(-o*u,a),l=R(s*u,a),h=n&1?"03":"02",p=ge.fromHex(h+Ti(c)),d=ge.BASE.multiplyAndAddUnsafe(p,f,l);if(!d)throw new Error("Cannot recover signature: point at infinify");return d.assertValidity(),d}toRawBytes(e=!1){return Nn(this.toHex(e))}toHex(e=!1){let r=Ti(this.x);return e?`${this.hasEvenY()?"02":"03"}${r}`:`04${r}${Ti(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){let e="Point is not on elliptic curve",{x:r,y:n}=this;if(!_0(r)||!_0(n))throw new Error(e);let i=R(n*n),s=tg(r);if(R(i-s)!==ie)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new ge(this.x,R(-this.y))}double(){return ae.fromAffine(this).double().toAffine()}add(e){return ae.fromAffine(this).add(ae.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return ae.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,r,n){let i=ae.fromAffine(this),s=r===ie||r===Te||this!==ge.BASE?i.multiplyUnsafe(r):i.multiply(r),o=ae.fromAffine(e).multiplyUnsafe(n),a=s.add(o);return a.equals(ae.ZERO)?void 0:a.toAffine()}};ge.BASE=new ge(Ue.Gx,Ue.Gy);ge.ZERO=new ge(ie,ie);function ng(t){return Number.parseInt(t[0],16)>=8?"00"+t:t}function ig(t){if(t.length<2||t[0]!==2)throw new Error(`Invalid signature integer tag: ${ki(t)}`);let e=t[1],r=t.subarray(2,e+2);if(!e||r.length!==e)throw new Error("Invalid signature integer: wrong length");if(r[0]===0&&r[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:on(r),left:t.subarray(e+2)}}function $4(t){if(t.length<2||t[0]!=48)throw new Error(`Invalid signature tag: ${ki(t)}`);if(t[1]!==t.length-2)throw new Error("Invalid signature: incorrect length");let{data:e,left:r}=ig(t.subarray(2)),{data:n,left:i}=ig(r);if(i.length)throw new Error(`Invalid signature: left bytes after parsing: ${ki(i)}`);return{r:e,s:n}}var wr=class{constructor(e,r){this.r=e,this.s=r,this.assertValidity()}static fromCompact(e){let r=e instanceof Uint8Array,n="Signature.fromCompact";if(typeof e!="string"&&!r)throw new TypeError(`${n}: Expected string or Uint8Array`);let i=r?ki(e):e;if(i.length!==128)throw new Error(`${n}: Expected 64-byte hex`);return new wr(Ya(i.slice(0,64)),Ya(i.slice(64,128)))}static fromDER(e){let r=e instanceof Uint8Array;if(typeof e!="string"&&!r)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");let{r:n,s:i}=$4(r?e:Nn(e));return new wr(n,i)}static fromHex(e){return this.fromDER(e)}assertValidity(){let{r:e,s:r}=this;if(!Rs(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!Rs(r))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){let e=Ue.n>>Te;return this.s>e}normalizeS(){return this.hasHighS()?new wr(this.r,R(-this.s,Ue.n)):this}toDERRawBytes(){return Nn(this.toDERHex())}toDERHex(){let e=ng(ks(this.s)),r=ng(ks(this.r)),n=e.length/2,i=r.length/2,s=ks(n),o=ks(i);return`30${ks(i+n+4)}02${o}${r}02${s}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return Nn(this.toCompactHex())}toCompactHex(){return Ti(this.r)+Ti(this.s)}};function nn(...t){if(!t.every(n=>n instanceof Uint8Array))throw new Error("Uint8Array list expected");if(t.length===1)return t[0];let e=t.reduce((n,i)=>n+i.length,0),r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let s=t[n];r.set(s,i),i+=s.length}return r}var X4=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ki(t){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");let e="";for(let r=0;r<t.length;r++)e+=X4[t[r]];return e}var Y4=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");function Ti(t){if(typeof t!="bigint")throw new Error("Expected bigint");if(!(ie<=t&&t<Y4))throw new Error("Expected number 0 <= n < 2^256");return t.toString(16).padStart(64,"0")}function C0(t){let e=Nn(Ti(t));if(e.length!==32)throw new Error("Error: expected 32 bytes");return e}function ks(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function Ya(t){if(typeof t!="string")throw new TypeError("hexToNumber: expected string, got "+typeof t);return BigInt(`0x${t}`)}function Nn(t){if(typeof t!="string")throw new TypeError("hexToBytes: expected string, got "+typeof t);if(t.length%2)throw new Error("hexToBytes: received invalid unpadded hex"+t.length);let e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r++){let n=r*2,i=t.slice(n,n+2),s=Number.parseInt(i,16);if(Number.isNaN(s)||s<0)throw new Error("Invalid byte sequence");e[r]=s}return e}function on(t){return Ya(ki(t))}function Li(t){return t instanceof Uint8Array?Uint8Array.from(t):Nn(t)}function sg(t){if(typeof t=="number"&&Number.isSafeInteger(t)&&t>0)return BigInt(t);if(typeof t=="bigint"&&Rs(t))return t;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function R(t,e=Ue.P){let r=t%e;return r>=ie?r:e+r}function Pt(t,e){let{P:r}=Ue,n=t;for(;e-- >ie;)n*=n,n%=r;return n}function J4(t){let{P:e}=Ue,r=BigInt(6),n=BigInt(11),i=BigInt(22),s=BigInt(23),o=BigInt(44),a=BigInt(88),c=t*t*t%e,u=c*c*t%e,f=Pt(u,Ls)*u%e,l=Pt(f,Ls)*u%e,h=Pt(l,sn)*c%e,p=Pt(h,n)*h%e,d=Pt(p,i)*p%e,y=Pt(d,o)*d%e,g=Pt(y,a)*y%e,b=Pt(g,o)*d%e,v=Pt(b,Ls)*u%e,w=Pt(v,s)*p%e,C=Pt(w,r)*c%e,E=Pt(C,sn);if(E*E%e!==t)throw new Error("Cannot find square root");return E}function Ni(t,e=Ue.P){if(t===ie||e<=ie)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=R(t,e),n=e,i=ie,s=Te,o=Te,a=ie;for(;r!==ie;){let u=n/r,f=n%r,l=i-o*u,h=s-a*u;n=r,r=f,i=o,s=a,o=l,a=h}if(n!==Te)throw new Error("invert: does not exist");return R(i,e)}function Z4(t,e=Ue.P){let r=new Array(t.length),n=t.reduce((s,o,a)=>o===ie?s:(r[a]=s,R(s*o,e)),Te),i=Ni(n,e);return t.reduceRight((s,o,a)=>o===ie?s:(r[a]=R(s*r[a],e),R(s*o,e)),i),r}function Q4(t){let e=t.length*8-Ii*8,r=on(t);return e>0?r>>BigInt(e):r}function T0(t,e=!1){let r=Q4(t);if(e)return r;let{n}=Ue;return r>=n?r-n:r}var Bi,Ns,D0=class{constructor(e,r){if(this.hashLen=e,this.qByteLen=r,typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof r!="number"||r<2)throw new Error("qByteLen must be a number");this.v=new Uint8Array(e).fill(1),this.k=new Uint8Array(e).fill(0),this.counter=0}hmac(...e){return Xt.hmacSha256(this.k,...e)}hmacSync(...e){return Ns(this.k,...e)}checkSync(){if(typeof Ns!="function")throw new Xa("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw new Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),e.length!==0&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),e.length!==0&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0,r=[];for(;e<this.qByteLen;){this.v=await this.hmac(this.v);let n=this.v.slice();r.push(n),e+=this.v.length}return nn(...r)}generateSync(){this.checkSync(),this.incr();let e=0,r=[];for(;e<this.qByteLen;){this.v=this.hmacSync(this.v);let n=this.v.slice();r.push(n),e+=this.v.length}return nn(...r)}};function Rs(t){return ie<t&&t<Ue.n}function _0(t){return ie<t&&t<Ue.P}function e6(t,e,r,n=!0){let{n:i}=Ue,s=T0(t,!0);if(!Rs(s))return;let o=Ni(s,i),a=ge.BASE.multiply(s),c=R(a.x,i);if(c===ie)return;let u=R(o*R(e+r*c,i),i);if(u===ie)return;let f=new wr(c,u),l=(a.x===f.r?0:2)|Number(a.y&Te);return n&&f.hasHighS()&&(f=f.normalizeS(),l^=1),{sig:f,recovery:l}}function Ja(t){let e;if(typeof t=="bigint")e=t;else if(typeof t=="number"&&Number.isSafeInteger(t)&&t>0)e=BigInt(t);else if(typeof t=="string"){if(t.length!==2*Ii)throw new Error("Expected 32 bytes of private key");e=Ya(t)}else if(t instanceof Uint8Array){if(t.length!==Ii)throw new Error("Expected 32 bytes of private key");e=on(t)}else throw new TypeError("Expected valid private key");if(!Rs(e))throw new Error("Expected private key: 0 < key < n");return e}function t6(t){return t instanceof ge?(t.assertValidity(),t):ge.fromHex(t)}function og(t){if(t instanceof wr)return t.assertValidity(),t;try{return wr.fromDER(t)}catch{return wr.fromCompact(t)}}function B0(t,e=!1){return ge.fromPrivateKey(t).toRawBytes(e)}function ag(t){let e=t.length>$t?t.slice(0,$t):t;return on(e)}function r6(t){let e=ag(t),r=R(e,Ue.n);return cg(r<ie?e:r)}function cg(t){return C0(t)}function n6(t,e,r){if(t==null)throw new Error(`sign: expected valid message hash, not "${t}"`);let n=Li(t),i=Ja(e),s=[cg(i),r6(n)];if(r!=null){r===!0&&(r=Xt.randomBytes($t));let c=Li(r);if(c.length!==$t)throw new Error(`sign: Expected ${$t} bytes of extra data`);s.push(c)}let o=nn(...s),a=ag(n);return{seed:o,m:a,d:i}}function i6(t,e){let{sig:r,recovery:n}=t,{der:i,recovered:s}=Object.assign({canonical:!0,der:!0},e),o=i?r.toDERRawBytes():r.toCompactRawBytes();return s?[o,n]:o}async function ug(t,e,r={}){let{seed:n,m:i,d:s}=n6(t,e,r.extraEntropy),o=new D0(j4,Ii);await o.reseed(n);let a;for(;!(a=e6(await o.generate(),i,s,r.canonical));)await o.reseed();return i6(a,r)}var s6={strict:!0};function fg(t,e,r,n=s6){let i;try{i=og(t),e=Li(e)}catch{return!1}let{r:s,s:o}=i;if(n.strict&&i.hasHighS())return!1;let a=T0(e),c;try{c=t6(r)}catch{return!1}let{n:u}=Ue,f=Ni(o,u),l=R(a*f,u),h=R(s*f,u),p=ge.BASE.multiplyAndAddUnsafe(c,l,h);return p?R(p.x,u)===s:!1}ge.BASE._setWindowSize(8);var Tt={node:W4,web:typeof self=="object"&&"crypto"in self?self.crypto:void 0};var $a={},Xt={bytesToHex:ki,hexToBytes:Nn,concatBytes:nn,mod:R,invert:Ni,isValidPrivateKey(t){try{return Ja(t),!0}catch{return!1}},_bigintTo32Bytes:C0,_normalizePrivateKey:Ja,hashToPrivateKey:t=>{t=Li(t);let e=Ii+8;if(t.length<e||t.length>1024)throw new Error("Expected valid bytes of private key as per FIPS 186");let r=R(on(t),Ue.n-Te)+Te;return C0(r)},randomBytes:(t=32)=>{if(Tt.web)return Tt.web.getRandomValues(new Uint8Array(t));if(Tt.node){let{randomBytes:e}=Tt.node;return Uint8Array.from(e(t))}else throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Xt.hashToPrivateKey(Xt.randomBytes(Ii+8)),precompute(t=8,e=ge.BASE){let r=e===ge.BASE?e:new ge(e.x,e.y);return r._setWindowSize(t),r.multiply(Ls),r},sha256:async(...t)=>{if(Tt.web){let e=await Tt.web.subtle.digest("SHA-256",nn(...t));return new Uint8Array(e)}else if(Tt.node){let{createHash:e}=Tt.node,r=e("sha256");return t.forEach(n=>r.update(n)),Uint8Array.from(r.digest())}else throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(t,...e)=>{if(Tt.web){let r=await Tt.web.subtle.importKey("raw",t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=nn(...e),i=await Tt.web.subtle.sign("HMAC",r,n);return new Uint8Array(i)}else if(Tt.node){let{createHmac:r}=Tt.node,n=r("sha256",t);return e.forEach(i=>n.update(i)),Uint8Array.from(n.digest())}else throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(t,...e)=>{let r=$a[t];if(r===void 0){let n=await Xt.sha256(Uint8Array.from(t,i=>i.charCodeAt(0)));r=nn(n,n),$a[t]=r}return Xt.sha256(r,...e)},taggedHashSync:(t,...e)=>{if(typeof Bi!="function")throw new Xa("sha256Sync is undefined, you need to set it");let r=$a[t];if(r===void 0){let n=Bi(Uint8Array.from(t,i=>i.charCodeAt(0)));r=nn(n,n),$a[t]=r}return Bi(r,...e)},_JacobianPoint:ae};Object.defineProperties(Xt,{sha256Sync:{configurable:!1,get(){return Bi},set(t){Bi||(Bi=t)}},hmacSha256Sync:{configurable:!1,get(){return Ns},set(t){Ns||(Ns=t)}}});function Za(t){if(isNaN(t)||t<=0)throw new ee("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Xt.randomBytes(t)}var Rn={};Ze(Rn,{jwkToPkcs1:()=>u6,jwkToPkix:()=>l6,pkcs1ToJwk:()=>c6,pkixToJwk:()=>f6});var qL=G(Cs(),1),HL=G(m0(),1);var Mr=G(we(),1);var PL=G(Ve(),1),UL=G(Ka(),1),lg=G(we(),1);function Yt(t,e){let r=Uint8Array.from(t.abs().toByteArray());if(r=r[0]===0?r.subarray(1):r,e!=null){if(r.length>e)throw new Error("byte array longer than desired length");r=ye([new Uint8Array(e-r.length),r])}return $(r,"base64url")}function Jt(t){let e=a6(t);return new lg.default.jsbn.BigInteger($(e,"base16"),16)}function a6(t,e){let r=Ae(t,"base64urlpad");if(e!=null){if(r.length>e)throw new Error("byte array longer than desired length");r=ye([new Uint8Array(e-r.length),r])}return r}function c6(t){let e=Mr.default.asn1.fromDer($(t,"ascii")),r=Mr.default.pki.privateKeyFromAsn1(e);return{kty:"RSA",n:Yt(r.n),e:Yt(r.e),d:Yt(r.d),p:Yt(r.p),q:Yt(r.q),dp:Yt(r.dP),dq:Yt(r.dQ),qi:Yt(r.qInv),alg:"RS256"}}function u6(t){if(t.n==null||t.e==null||t.d==null||t.p==null||t.q==null||t.dp==null||t.dq==null||t.qi==null)throw new ee("JWK was missing components","ERR_INVALID_PARAMETERS");let e=Mr.default.pki.privateKeyToAsn1({n:Jt(t.n),e:Jt(t.e),d:Jt(t.d),p:Jt(t.p),q:Jt(t.q),dP:Jt(t.dp),dQ:Jt(t.dq),qInv:Jt(t.qi)});return Ae(Mr.default.asn1.toDer(e).getBytes(),"ascii")}function f6(t){let e=Mr.default.asn1.fromDer($(t,"ascii")),r=Mr.default.pki.publicKeyFromAsn1(e);return{kty:"RSA",n:Yt(r.n),e:Yt(r.e)}}function l6(t){if(t.n==null||t.e==null)throw new ee("JWK was missing components","ERR_INVALID_PARAMETERS");let e=Mr.default.pki.publicKeyToAsn1({n:Jt(t.n),e:Jt(t.e)});return Ae(Mr.default.asn1.toDer(e).getBytes(),"ascii")}var h6=(0,hg.promisify)(On.default.generateKeyPair);async function dg(t){let e=await h6("rsa",{modulusLength:t,publicKeyEncoding:{type:"pkcs1",format:"jwk"},privateKeyEncoding:{type:"pkcs1",format:"jwk"}});return{privateKey:e.privateKey,publicKey:e.publicKey}}async function I0(t){if(t==null)throw new ee("Missing key parameter","ERR_MISSING_KEY");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function pg(t,e){return On.default.createSign("RSA-SHA256").update(e).sign({format:"jwk",key:t})}async function yg(t,e,r){return On.default.createVerify("RSA-SHA256").update(r).verify({format:"jwk",key:t},e)}var gg=On.default.constants.RSA_PKCS1_PADDING;function bg(t,e){return On.default.publicEncrypt({format:"jwk",key:t,padding:gg},e)}function mg(t,e){return On.default.privateDecrypt({format:"jwk",key:t,padding:gg},e)}var Ps=class{_key;constructor(e){this._key=e}async verify(e,r){return yg(this._key,r,e)}marshal(){return Rn.jwkToPkix(this._key)}get bytes(){return mr.encode({Type:Le.RSA,Data:this.marshal()}).subarray()}encrypt(e){return bg(this._key,e)}equals(e){return qe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}},Ri=class{_key;_publicKey;constructor(e,r){this._key=e,this._publicKey=r}genSecret(){return Za(16)}async sign(e){return pg(this._key,e)}get public(){if(this._publicKey==null)throw new ee("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Ps(this._publicKey)}decrypt(e){return mg(this._key,e)}marshal(){return Rn.jwkToPkcs1(this._key)}get bytes(){return xr.encode({Type:Le.RSA,Data:this.marshal()}).subarray()}equals(e){return qe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}async id(){let e=await this.public.hash();return $(e,"base58btc")}async export(e,r="pkcs-8"){if(r==="pkcs-8"){let n=new Os.default.util.ByteBuffer(this.marshal()),i=Os.default.asn1.fromDer(n),s=Os.default.pki.privateKeyFromAsn1(i),o={algorithm:"aes256",count:1e4,saltSize:128/8,prfAlgorithm:"sha512"};return Os.default.pki.encryptRsaPrivateKey(s,e,o)}else{if(r==="libp2p-key")return Ci(this.bytes,e);throw new ee(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}};async function p6(t){let e=Rn.pkcs1ToJwk(t),r=await I0(e);return new Ri(r.privateKey,r.publicKey)}function y6(t){let e=Rn.pkixToJwk(t);return new Ps(e)}async function g6(t){let e=await I0(t);return new Ri(e.privateKey,e.publicKey)}async function b6(t){let e=await dg(t);return new Ri(e.privateKey,e.publicKey)}var N0={};Ze(N0,{Secp256k1PrivateKey:()=>Fs,Secp256k1PublicKey:()=>Us,generateKeyPair:()=>v6,unmarshalSecp256k1PrivateKey:()=>x6,unmarshalSecp256k1PublicKey:()=>w6});function xg(){return Xt.randomPrivateKey()}async function wg(t,e){let{digest:r}=await et.digest(e);try{return await ug(r,t)}catch(n){throw new ee(String(n),"ERR_INVALID_INPUT")}}async function vg(t,e,r){try{let{digest:n}=await et.digest(r);return fg(e,n,t)}catch(n){throw new ee(String(n),"ERR_INVALID_INPUT")}}function Eg(t){return ge.fromHex(t).toRawBytes(!0)}function Sg(t){try{B0(t,!0)}catch(e){throw new ee(String(e),"ERR_INVALID_PRIVATE_KEY")}}function L0(t){try{ge.fromHex(t)}catch(e){throw new ee(String(e),"ERR_INVALID_PUBLIC_KEY")}}function _g(t){try{return B0(t,!0)}catch(e){throw new ee(String(e),"ERR_INVALID_PRIVATE_KEY")}}var Us=class{_key;constructor(e){L0(e),this._key=e}async verify(e,r){return vg(this._key,r,e)}marshal(){return Eg(this._key)}get bytes(){return mr.encode({Type:Le.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return qe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}},Fs=class{_key;_publicKey;constructor(e,r){this._key=e,this._publicKey=r??_g(e),Sg(this._key),L0(this._publicKey)}async sign(e){return wg(this._key,e)}get public(){return new Us(this._publicKey)}marshal(){return this._key}get bytes(){return xr.encode({Type:Le.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return qe(this.bytes,e.bytes)}async hash(){let{bytes:e}=await et.digest(this.bytes);return e}async id(){let e=await this.public.hash();return $(e,"base58btc")}async export(e,r="libp2p-key"){if(r==="libp2p-key")return Ci(this.bytes,e);throw new ee(`export format '${r}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function x6(t){return new Fs(t)}function w6(t){return new Us(t)}async function v6(){let t=xg();return new Fs(t)}var Pn={rsa:k0,ed25519:v0,secp256k1:N0};function Ag(t){let e=Object.keys(Pn).join(" / ");return new ee(`invalid or unsupported key type ${t}. Must be ${e}`,"ERR_UNSUPPORTED_KEY_TYPE")}function Cg(t){let e=mr.decode(t),r=e.Data??new Uint8Array;switch(e.Type){case Le.RSA:return Pn.rsa.unmarshalRsaPublicKey(r);case Le.Ed25519:return Pn.ed25519.unmarshalEd25519PublicKey(r);case Le.Secp256k1:return Pn.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw Ag(e.Type??"RSA")}}async function Dg(t){let e=xr.decode(t),r=e.Data??new Uint8Array;switch(e.Type){case Le.RSA:return Pn.rsa.unmarshalRsaPrivateKey(r);case Le.Ed25519:return Pn.ed25519.unmarshalEd25519PrivateKey(r);case Le.Secp256k1:return Pn.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw Ag(e.Type??"RSA")}}var Qa;(function(t){let e;t.codec=()=>(e==null&&(e=kr((r,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),r.webtransportCerthashes!=null)for(let s of r.webtransportCerthashes)n.uint32(10),n.bytes(s);i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={webtransportCerthashes:[]},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.webtransportCerthashes.push(r.bytes());break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Ir(r,t.codec()),t.decode=r=>Br(r,t.codec())})(Qa||(Qa={}));var Ms;(function(t){let e;t.codec=()=>(e==null&&(e=kr((r,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),(i.writeDefaults===!0||r.identityKey!=null&&r.identityKey.byteLength>0)&&(n.uint32(10),n.bytes(r.identityKey??new Uint8Array(0))),(i.writeDefaults===!0||r.identitySig!=null&&r.identitySig.byteLength>0)&&(n.uint32(18),n.bytes(r.identitySig??new Uint8Array(0))),r.extensions!=null&&(n.uint32(34),Qa.codec().encode(r.extensions,n,{writeDefaults:!1})),i.lengthDelimited!==!1&&n.ldelim()},(r,n)=>{let i={identityKey:new Uint8Array(0),identitySig:new Uint8Array(0)},s=n==null?r.len:r.pos+n;for(;r.pos<s;){let o=r.uint32();switch(o>>>3){case 1:i.identityKey=r.bytes();break;case 2:i.identitySig=r.bytes();break;case 4:i.extensions=Qa.codec().decode(r,r.uint32());break;default:r.skipType(o&7);break}}return i})),e),t.encode=r=>Ir(r,t.codec()),t.decode=r=>Br(r,t.codec())})(Ms||(Ms={}));async function Tg(t,e,r){let n=await _6(t,Bg(e));if(t.publicKey==null)throw new Error("PublicKey was missing from local PeerId");return S6(t.publicKey,n,r)}function S6(t,e,r){return Ms.encode({identityKey:t,identitySig:e,extensions:r??{webtransportCerthashes:[]}}).subarray()}async function _6(t,e){if(t.privateKey==null)throw new Error("PrivateKey was missing from PeerId");return await(await Dg(t.privateKey)).sign(e)}async function R0(t){return await Qc(t.identityKey)}function O0(t){return Ms.decode(t)}function Bg(t){let e=Ae("noise-libp2p-static-key:");return ye([e,t],e.length+t.length)}async function P0(t,e,r){let n=await Qc(e.identityKey);if(!n.equals(r))throw new Error(`Payload identity key ${n.toString()} does not match expected remote peer ${r.toString()}`);let i=Bg(t);if(n.publicKey==null)throw new Error("PublicKey was missing from PeerId");if(e.identitySig==null)throw new Error("Signature was missing from message");if(!await Cg(n.publicKey).verify(i,e.identitySig))throw new Error("Static key doesn't match to peer that signed payload!");return n}function Ks(t){return!(!(t instanceof Uint8Array)||t.length!==32)}var Ye=lt("libp2p:noise");var Ut;Ip?Ut=Ye:Ut=Object.assign(()=>{},{enabled:!1,trace:()=>{},error:()=>{}});function Ig(t){Ut(`LOCAL_STATIC_PUBLIC_KEY ${$(t.publicKey,"hex")}`),Ut(`LOCAL_STATIC_PRIVATE_KEY ${$(t.privateKey,"hex")}`)}function U0(t){t?(Ut(`LOCAL_PUBLIC_EPHEMERAL_KEY ${$(t.publicKey,"hex")}`),Ut(`LOCAL_PRIVATE_EPHEMERAL_KEY ${$(t.privateKey,"hex")}`)):Ut("Missing local ephemeral keys.")}function kg(t){Ut(`REMOTE_STATIC_PUBLIC_KEY ${$(t,"hex")}`)}function F0(t){Ut(`REMOTE_EPHEMERAL_PUBLIC_KEY ${$(t,"hex")}`)}function Lg(t){t.cs1&&t.cs2?(Ut(`CIPHER_STATE_1 ${t.cs1.n.getUint64()} ${$(t.cs1.k,"hex")}`),Ut(`CIPHER_STATE_2 ${t.cs2.n.getUint64()} ${$(t.cs2.k,"hex")}`)):Ut("Missing cipher state.")}var A6="Cipherstate has reached maximum n, a new handshake must be performed",ec=class{constructor(e=0){this.n=e,this.bytes=new Uint8Array(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw new Error(A6)}};var tc=class{constructor(e){this.crypto=e}encryptWithAd(e,r,n){let i=this.encrypt(e.k,e.n,r,n);return e.n.increment(),i}decryptWithAd(e,r,n,i){let{plaintext:s,valid:o}=this.decrypt(e.k,e.n,r,n,i);return o&&e.n.increment(),{plaintext:s,valid:o}}hasKey(e){return!this.isEmptyKey(e.k)}createEmptyKey(){return new Uint8Array(32)}isEmptyKey(e){let r=this.createEmptyKey();return qe(r,e)}encrypt(e,r,n,i){return r.assertValue(),this.crypto.chaCha20Poly1305Encrypt(i,r.getBytes(),n,e)}encryptAndHash(e,r){let n;return this.hasKey(e.cs)?n=this.encryptWithAd(e.cs,e.h,r):n=r,this.mixHash(e,n),n}decrypt(e,r,n,i,s){r.assertValue();let o=this.crypto.chaCha20Poly1305Decrypt(i,r.getBytes(),n,e,s);return o?{plaintext:o,valid:!0}:{plaintext:new Uint8Array(0),valid:!1}}decryptAndHash(e,r){let n,i=!0;return this.hasKey(e.cs)?{plaintext:n,valid:i}=this.decryptWithAd(e.cs,e.h,r):n=r,this.mixHash(e,r),{plaintext:n,valid:i}}dh(e,r){try{let n=this.crypto.generateX25519SharedKey(e,r);return n.length===32?n:n.subarray(0,32)}catch(n){let i=n;return Ye.error(i),new Uint8Array(32)}}mixHash(e,r){e.h=this.getHash(e.h,r)}getHash(e,r){return this.crypto.hashSHA256(ye([e,r],e.length+r.length))}mixKey(e,r){let[n,i]=this.crypto.getHKDF(e.ck,r);e.cs=this.initializeKey(i),e.ck=n}initializeKey(e){return{k:e,n:new ec}}initializeSymmetric(e){let r=Ae(e,"utf-8"),n=this.hashProtocolName(r),i=n,s=this.createEmptyKey();return{cs:this.initializeKey(s),ck:i,h:n}}hashProtocolName(e){if(e.length<=32){let r=new Uint8Array(32);return r.set(e),r}else return this.getHash(e,new Uint8Array(0))}split(e){let[r,n]=this.crypto.getHKDF(e.ck,new Uint8Array(0)),i=this.initializeKey(r),s=this.initializeKey(n);return{cs1:i,cs2:s}}writeMessageRegular(e,r){let n=this.encryptWithAd(e,new Uint8Array(0),r),i=this.createEmptyKey(),s=new Uint8Array(0);return{ne:i,ns:s,ciphertext:n}}readMessageRegular(e,r){return this.decryptWithAd(e,new Uint8Array(0),r.ciphertext)}};var rc=class extends tc{initializeInitiator(e,r,n,i){let s="Noise_XX_25519_ChaChaPoly_SHA256",o=this.initializeSymmetric(s);this.mixHash(o,e);let a=new Uint8Array(32);return{ss:o,s:r,rs:n,psk:i,re:a}}initializeResponder(e,r,n,i){let s="Noise_XX_25519_ChaChaPoly_SHA256",o=this.initializeSymmetric(s);this.mixHash(o,e);let a=new Uint8Array(32);return{ss:o,s:r,rs:n,psk:i,re:a}}writeMessageA(e,r,n){let i=new Uint8Array(0);n!==void 0?e.e=n:e.e=this.crypto.generateX25519KeyPair();let s=e.e.publicKey;this.mixHash(e.ss,s);let o=this.encryptAndHash(e.ss,r);return{ne:s,ns:i,ciphertext:o}}writeMessageB(e,r){e.e=this.crypto.generateX25519KeyPair();let n=e.e.publicKey;this.mixHash(e.ss,n),this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let i=e.s.publicKey,s=this.encryptAndHash(e.ss,i);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let o=this.encryptAndHash(e.ss,r);return{ne:n,ns:s,ciphertext:o}}writeMessageC(e,r){let n=e.s.publicKey,i=this.encryptAndHash(e.ss,n);this.mixKey(e.ss,this.dh(e.s.privateKey,e.re));let s=this.encryptAndHash(e.ss,r),a={ne:this.createEmptyKey(),ns:i,ciphertext:s},{cs1:c,cs2:u}=this.split(e.ss);return{h:e.ss.h,messageBuffer:a,cs1:c,cs2:u}}readMessageA(e,r){return Ks(r.ne)&&(e.re=r.ne),this.mixHash(e.ss,e.re),this.decryptAndHash(e.ss,r.ciphertext)}readMessageB(e,r){if(Ks(r.ne)&&(e.re=r.ne),this.mixHash(e.ss,e.re),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.re));let{plaintext:n,valid:i}=this.decryptAndHash(e.ss,r.ns);i&&Ks(n)&&(e.rs=n),this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:s,valid:o}=this.decryptAndHash(e.ss,r.ciphertext);return{plaintext:s,valid:i&&o}}readMessageC(e,r){let{plaintext:n,valid:i}=this.decryptAndHash(e.ss,r.ns);if(i&&Ks(n)&&(e.rs=n),!e.e)throw new Error("Handshake state `e` param is missing.");this.mixKey(e.ss,this.dh(e.e.privateKey,e.rs));let{plaintext:s,valid:o}=this.decryptAndHash(e.ss,r.ciphertext),{cs1:a,cs2:c}=this.split(e.ss);return{h:e.ss.h,plaintext:s,valid:i&&o,cs1:a,cs2:c}}initSession(e,r,n){let i=this.createEmptyKey(),s=new Uint8Array(32),o;return e?o=this.initializeInitiator(r,n,s,i):o=this.initializeResponder(r,n,s,i),{hs:o,i:e,mc:0}}sendMessage(e,r,n){let i;if(e.mc===0)i=this.writeMessageA(e.hs,r,n);else if(e.mc===1)i=this.writeMessageB(e.hs,r);else if(e.mc===2){let{h:s,messageBuffer:o,cs1:a,cs2:c}=this.writeMessageC(e.hs,r);i=o,e.h=s,e.cs1=a,e.cs2=c}else if(e.mc>2)if(e.i){if(!e.cs1)throw new Error("CS1 (cipher state) is not defined");i=this.writeMessageRegular(e.cs1,r)}else{if(!e.cs2)throw new Error("CS2 (cipher state) is not defined");i=this.writeMessageRegular(e.cs2,r)}else throw new Error("Session invalid.");return e.mc++,i}recvMessage(e,r){let n=new Uint8Array(0),i=!1;if(e.mc===0)({plaintext:n,valid:i}=this.readMessageA(e.hs,r));else if(e.mc===1)({plaintext:n,valid:i}=this.readMessageB(e.hs,r));else if(e.mc===2){let{h:s,plaintext:o,valid:a,cs1:c,cs2:u}=this.readMessageC(e.hs,r);n=o,i=a,e.h=s,e.cs1=c,e.cs2=u}return e.mc++,{plaintext:n,valid:i}}};var nc=class{constructor(e,r,n,i,s,o,a,c){this.remoteExtensions={webtransportCerthashes:[]},this.isInitiator=e,this.payload=r,this.prologue=n,this.staticKeypair=s,this.connection=o,a&&(this.remotePeer=a),this.xx=c??new rc(i),this.session=this.xx.initSession(this.isInitiator,this.prologue,this.staticKeypair)}async propose(){if(Ig(this.session.hs.s),this.isInitiator){Ye.trace("Stage 0 - Initiator starting to send first message.");let e=this.xx.sendMessage(this.session,new Uint8Array(0));this.connection.writeLP(hy(e)),Ye.trace("Stage 0 - Initiator finished sending first message."),U0(this.session.hs.e)}else{Ye.trace("Stage 0 - Responder waiting to receive first message...");let e=yy((await this.connection.readLP()).subarray()),{valid:r}=this.xx.recvMessage(this.session,e);if(!r)throw new Or("xx handshake stage 0 validation fail");Ye.trace("Stage 0 - Responder received first message."),F0(this.session.hs.re)}}async exchange(){if(this.isInitiator){Ye.trace("Stage 1 - Initiator waiting to receive first message from responder...");let e=gy((await this.connection.readLP()).subarray()),{plaintext:r,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new Or("xx handshake stage 1 validation fail");Ye.trace("Stage 1 - Initiator received the message."),F0(this.session.hs.re),kg(this.session.hs.rs),Ye.trace("Initiator going to check remote's signature...");try{let i=O0(r);this.remotePeer=this.remotePeer||await R0(i),await P0(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let s=i;throw new En(`Error occurred while verifying signed payload: ${s.message}`)}Ye.trace("All good with the signature!")}else{Ye.trace("Stage 1 - Responder sending out first message with signed payload and static key.");let e=this.xx.sendMessage(this.session,this.payload);this.connection.writeLP(dy(e)),Ye.trace("Stage 1 - Responder sent the second handshake message with signed payload."),U0(this.session.hs.e)}}async finish(){if(this.isInitiator){Ye.trace("Stage 2 - Initiator sending third handshake message.");let e=this.xx.sendMessage(this.session,this.payload);this.connection.writeLP(py(e)),Ye.trace("Stage 2 - Initiator sent message with signed payload.")}else{Ye.trace("Stage 2 - Responder waiting for third handshake message...");let e=by((await this.connection.readLP()).subarray()),{plaintext:r,valid:n}=this.xx.recvMessage(this.session,e);if(!n)throw new Or("xx handshake stage 2 validation fail");Ye.trace("Stage 2 - Responder received the message, finished handshake.");try{let i=O0(r);this.remotePeer=this.remotePeer||await R0(i),await P0(this.session.hs.rs,i,this.remotePeer),this.setRemoteNoiseExtension(i.extensions)}catch(i){let s=i;throw new En(`Error occurred while verifying signed payload: ${s.message}`)}}Lg(this.session)}encrypt(e,r){let n=this.getCS(r);return this.xx.encryptWithAd(n,new Uint8Array(0),e)}decrypt(e,r,n){let i=this.getCS(r,!1);return this.xx.decryptWithAd(i,new Uint8Array(0),e,n)}getRemoteStaticKey(){return this.session.hs.rs}getCS(e,r=!0){if(!e.cs1||!e.cs2)throw new Or("Handshake not completed properly, cipher state does not exist.");return this.isInitiator?r?e.cs1:e.cs2:r?e.cs2:e.cs1}setRemoteNoiseExtension(e){e&&(this.remoteExtensions=e)}};function Ng(t){return{xxHandshakeSuccesses:t.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:t.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:t.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:t.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:t.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}var ic=class{constructor(e={}){this.protocol="/noise";let{staticNoiseKey:r,extensions:n,crypto:i,prologueBytes:s,metrics:o}=e;this.crypto=i??ly,this.extensions=n,this.metrics=o?Ng(o):void 0,r?this.staticKeys=this.crypto.generateX25519KeyPairFromSeed(r):this.staticKeys=this.crypto.generateX25519KeyPair(),this.prologue=s??new Uint8Array(0)}async secureOutbound(e,r,n){let i=Tf(r,{lengthEncoder:vi,lengthDecoder:vs,maxDataLength:65535}),s=await this.performHandshake({connection:i,isInitiator:!0,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,s),remoteExtensions:s.remoteExtensions,remotePeer:s.remotePeer}}async secureInbound(e,r,n){let i=Tf(r,{lengthEncoder:vi,lengthDecoder:vs,maxDataLength:65535}),s=await this.performHandshake({connection:i,isInitiator:!1,localPeer:e,remotePeer:n});return{conn:await this.createSecureConnection(i,s),remotePeer:s.remotePeer,remoteExtensions:s.remoteExtensions}}async performHandshake(e){let r=await Tg(e.localPeer,this.staticKeys.publicKey,this.extensions);return await this.performXXHandshake(e,r)}async performXXHandshake(e,r){let{isInitiator:n,remotePeer:i,connection:s}=e,o=new nc(n,r,this.prologue,this.crypto,this.staticKeys,s,i);try{await o.propose(),await o.exchange(),await o.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 o}async createSecureConnection(e,r){let[n,i]=Dp(),s=e.unwrap();return await Bp(n,xy(r,this.metrics),s,pn({lengthDecoder:vs}),wy(r,this.metrics),n),i}};function Rg(t={}){return()=>new ic(t)}var ub=G(ll(),1);var sb=G(ll(),1);var hl=lt("libp2p:webrtc:sdp"),dl=Object.values(tr).map(t=>t.decoder).reduce((t,e)=>t.or(e));function ob(t){let e=t.getConfiguration().certificates?.at(0);if(e==null||e.getFingerprints==null){hl.trace("fetching fingerprint from local SDP");let n=t.localDescription;return n==null?void 0:Q_(n.sdp)}if(hl.trace("fetching fingerprint from local certificate"),e.getFingerprints().length===0)return;let r=e.getFingerprints()[0].value;if(r==null)throw wu("","no fingerprint on local certificate");return r}var Z_=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function Q_(t){return t.match(Z_)?.groups?.fingerprint}function eA(t){for(let e of t.protoNames())if(e.startsWith("ip"))return e.toUpperCase();return hl("Warning: multiaddr does not appear to contain IP4 or IP6, defaulting to IP6",t),"IP6"}function _c(t){let r=t.stringTuples().filter(n=>n[0]===gl).map(n=>n[1])[0];if(r===void 0||r==="")throw ti(`Couldn't find a certhash component of multiaddr: ${t.toString()}`);return r}function pl(t){let e=dl.decode(t);return sb.decode(e)}function tA(t){let e=pl(_c(t)),r=yl(e.name),n=e.digest.reduce((s,o)=>s+o.toString(16).padStart(2,"0"),""),i=n.match(/.{1,2}/g);if(i==null)throw wu(n,t.toString());return[`${r.toUpperCase()} ${i.join(":").toUpperCase()}`,n]}function yl(t){switch(t){case"sha1":return"sha-1";case"sha2-256":return"sha-256";case"sha2-512":return"sha-512";default:throw Sh(t)}}function rA(t,e){let{host:r,port:n}=t.toOptions(),i=eA(t),[s]=tA(t);return`v=0
35
35
  o=- 0 0 IN ${i} ${r}
36
36
  s=-
37
37
  c=IN ${i} ${r}
@@ -50,7 +50,7 @@ a=candidate:1467250027 1 UDP 1467250027 ${r} ${n} typ host\r
50
50
  a=ice-ufrag:`+e+`
51
51
  `).replace(/\na=ice-pwd:[^\n]*\n/,`
52
52
  a=ice-pwd:`+e+`
53
- `),t}var Ac=lt("libp2p:webrtc:transport"),iA=1e4,sA=pe("webrtc-direct").code,gl=pe("certhash").code,Cc=class{components;constructor(e){this.components=e}async dial(e,r){let n=await this._connect(e,r);return Ac(`dialing address - ${e.toString()}`),n}createListener(e){throw Eh("WebRTCTransport.createListener")}filter(e){return e.filter(oA)}[Symbol.toStringTag]="@libp2p/webrtc-direct";[Xs]=!0;async _connect(e,r){let n=new AbortController,i=n.signal,s=e.getPeerId();if(s===null)throw ti("we need to have the remote's PeerId");let o=$i(s),a=pl(_c(e)),c=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:yl(a.name)}),u=new RTCPeerConnection({certificates:[c]}),f=new Promise((I,O)=>{let F=u.createDataChannel("",{negotiated:!0,id:0}),z=setTimeout(()=>{let V=`Data channel was never opened: state: ${F.readyState}`;Ac.error(V),O(xu("data",V))},iA);F.onopen=V=>{clearTimeout(z),I(F)},F.onerror=V=>{clearTimeout(z);let ce=`Error opening a data channel for handshaking: ${V.target?.toString()??"not specified"}`;Ac.error(ce),O(xu("data",ce))}}),l="libp2p+webrtc+v1/"+Ah(32),h=await u.createOffer(),p=cb(h,l);await u.setLocalDescription(p);let d=ab(e,l);await u.setRemoteDescription(d);let y=await f,g=this.components.peerId,b=this.generateNoisePrologue(u,a.code,e),v=Rg({prologueBytes:b})(),w=new Ht({channel:y,stat:{direction:"inbound",timeline:{open:1}}}),C={...w,sink:w.sink.bind(w),source:{[Symbol.asyncIterator]:async function*(){for await(let I of w.source)for(let O of I)yield O}}},E=new ln({peerConnection:u,remoteAddr:e,timeline:{open:Date.now()}}),S=sa?"iceconnectionstatechange":"connectionstatechange";u.addEventListener(S,()=>{switch(u.connectionState){case"failed":case"disconnected":case"closed":E.close().catch(I=>{Ac.error("error closing connection",I)}).finally(()=>{n.abort()});break;default:break}},{signal:i});let T=new bn(u);return await v.secureInbound(g,C,o),r.upgrader.upgradeOutbound(E,{skipProtection:!0,skipEncryption:!0,muxerFactory:T})}generateNoisePrologue(e,r,n){if(e.getConfiguration().certificates?.length===0)throw Qi("no local certificate");let i=ob(e);if(i==null)throw Qi("no local fingerprint found");let s=i.trim().toLowerCase().replaceAll(":",""),o=Ae(s,"hex"),a=ub.encode(o,r),c=dl.decode(_c(n)),u=Ae("libp2p-webrtc-noise:");return ye([u,a,c])}};function oA(t){let e=t.protoCodes();return e.includes(sA)&&e.includes(gl)&&t.getPeerId()!=null&&!e.includes(pe("p2p-circuit").code)}function aA(){return t=>new Cc(t)}function cA(t){return e=>new ca(e,t??{})}return yb(uA);})();
53
+ `),t}var Ac=lt("libp2p:webrtc:transport"),iA=1e4,sA=pe("webrtc-direct").code,gl=pe("certhash").code,Cc=class{metrics;components;constructor(e){this.components=e,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dial events by type"})})}async dial(e,r){let n=await this._connect(e,r);return Ac(`dialing address - ${e.toString()}`),n}createListener(e){throw Eh("WebRTCTransport.createListener")}filter(e){return e.filter(oA)}[Symbol.toStringTag]="@libp2p/webrtc-direct";[Xs]=!0;async _connect(e,r){let n=new AbortController,i=n.signal,s=e.getPeerId();if(s===null)throw ti("we need to have the remote's PeerId");let o=$i(s),a=pl(_c(e)),c=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:yl(a.name)}),u=new RTCPeerConnection({certificates:[c]}),f=new Promise((I,O)=>{let F=u.createDataChannel("",{negotiated:!0,id:0}),z=setTimeout(()=>{let V=`Data channel was never opened: state: ${F.readyState}`;Ac.error(V),this.metrics?.dialerEvents.increment({open_error:!0}),O(xu("data",V))},iA);F.onopen=V=>{clearTimeout(z),I(F)},F.onerror=V=>{clearTimeout(z);let ce=`Error opening a data channel for handshaking: ${V.target?.toString()??"not specified"}`;Ac.error(ce),this.metrics?.dialerEvents.increment({unknown_error:!0}),O(xu("data",ce))}}),l="libp2p+webrtc+v1/"+Ah(32),h=await u.createOffer(),p=cb(h,l);await u.setLocalDescription(p);let d=ab(e,l);await u.setRemoteDescription(d);let y=await f,g=this.components.peerId,b=this.generateNoisePrologue(u,a.code,e),v=Rg({prologueBytes:b})(),w=new Ht({channel:y,stat:{direction:"inbound",timeline:{open:1}}}),C={...w,sink:w.sink.bind(w),source:{[Symbol.asyncIterator]:async function*(){for await(let I of w.source)for(let O of I)yield O}}},E=new ln({peerConnection:u,remoteAddr:e,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),S=sa?"iceconnectionstatechange":"connectionstatechange";u.addEventListener(S,()=>{switch(u.connectionState){case"failed":case"disconnected":case"closed":E.close().catch(I=>{Ac.error("error closing connection",I)}).finally(()=>{n.abort()});break;default:break}},{signal:i}),this.metrics?.dialerEvents.increment({peer_connection:!0});let T=new bn(u,this.metrics?.dialerEvents);return await v.secureInbound(g,C,o),r.upgrader.upgradeOutbound(E,{skipProtection:!0,skipEncryption:!0,muxerFactory:T})}generateNoisePrologue(e,r,n){if(e.getConfiguration().certificates?.length===0)throw Qi("no local certificate");let i=ob(e);if(i==null)throw Qi("no local fingerprint found");let s=i.trim().toLowerCase().replaceAll(":",""),o=Ae(s,"hex"),a=ub.encode(o,r),c=dl.decode(_c(n)),u=Ae("libp2p-webrtc-noise:");return ye([u,a,c])}};function oA(t){let e=t.protoCodes();return e.includes(sA)&&e.includes(gl)&&t.getPeerId()!=null&&!e.includes(pe("p2p-circuit").code)}function aA(){return t=>new Cc(t)}function cA(t){return e=>new ca(e,t??{})}return yb(uA);})();
54
54
  /*! Bundled license information:
55
55
 
56
56
  @noble/secp256k1/lib/esm/index.js: