@libp2p/webrtc 7.0.0 → 7.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,5 +1,5 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PWebrtc = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var Libp2PWebrtc=(()=>{var Fs=Object.defineProperty;var pd=Object.getOwnPropertyDescriptor;var md=Object.getOwnPropertyNames;var gd=Object.prototype.hasOwnProperty;var Pe=(t,e)=>{for(var r in e)Fs(t,r,{get:e[r],enumerable:!0})},yd=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of md(e))!gd.call(t,o)&&o!==r&&Fs(t,o,{get:()=>e[o],enumerable:!(n=pd(e,o))||n.enumerable});return t};var bd=t=>yd(Fs({},"__esModule",{value:!0}),t);var zg={};Pe(zg,{webRTC:()=>$g,webRTCDirect:()=>Hg});var Yn=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},Xn=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},Z=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},gr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Zn=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},Qn=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},yr=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var at=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},jt=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var Jn=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},eo=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},to=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var ro=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Gt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var no=class extends Event{data;constructor(e,r){super("message",r),this.data=e}},br=class extends Event{error;local;constructor(e,r,n){super("close",n),this.error=r,this.local=e}},oo=class extends br{constructor(e,r){super(!0,e,r)}},so=class extends br{constructor(e,r){super(!1,e,r)}};var Ks=Symbol.for("@libp2p/peer-id");var io=Symbol.for("@libp2p/transport");var Ic;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Ic||(Ic={}));function wd(t){return typeof t?.handleEvent=="function"}function xd(t){return t===!0||t===!1}function Ed(t){return xd(t)?t:t?.capture??!1}function Hs(t){let e={capture:Ed(t),once:!!t?.once};return t?.passive!=null&&(e.passive=t?.passive),t?.signal!=null&&(e.signal=t?.signal),e}function Rc(t,e){return Hs(t).capture===Hs(e).capture}var Lt=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){let o=Hs(n);if(o?.signal?.aborted===!0)return;let s=f=>{o.once&&this.removeEventListener(e,r,o),wd(r)?r.handleEvent(f):r(f)},i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(f=>f.callback!==r?!1:Rc(f.options,o)))return;super.addEventListener(e,s,o);let c=()=>{this.removeEventListener(e,r,o)};o.signal?.addEventListener("abort",c),i.push({callback:r,wrapper:s,options:o,onAbort:c})}removeEventListener(e,r,n){let o=this.#e.get(e);if(o==null){super.removeEventListener(e,r??null,n);return}this.#e.set(e,o.filter(s=>s.callback===r&&Rc(s.options,n)?(super.removeEventListener(e,s.wrapper,n),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}};var wr=Symbol.for("@libp2p/service-capabilities"),Oc=Symbol.for("@libp2p/service-dependencies");var Ws={};Pe(Ws,{base58btc:()=>ge,base58flickr:()=>Bd});var Ey=new Uint8Array(0);function Nc(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}function Ve(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return Yt(t);if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return Yt(new Uint8Array(t.buffer,t.byteOffset,t.byteLength));throw new Error("Unknown type, must be binary type")}function Uc(t){let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}var Pc=4096;function kc(t){let e=t.length;if(e<=Pc)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.subarray(n,n+=Pc));return r}function Sd(t){return t?.buffer instanceof ArrayBuffer}function Yt(t){return Sd(t)?t:t.slice()}function Ad(t,e,r){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<t.length;s++){var i=t.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,r){var c=i.toLowerCase().charCodeAt(0),f=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),f!==a&&(n[f]=s)}}var l=t.length,u=t.charAt(0),d=Math.log(l)/Math.log(256),p=Math.log(256)/Math.log(l);function w(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var E=0,b=0,L=0,C=y.length;L!==C&&y[L]===0;)L++,E++;for(var O=(C-L)*p+1>>>0,R=new Uint8Array(O);L!==C;){for(var N=y[L],B=0,I=O-1;(N!==0||B<b)&&I!==-1;I--,B++)N+=256*R[I]>>>0,R[I]=N%l>>>0,N=N/l>>>0;if(N!==0)throw new Error("Non-zero carry");b=B,L++}for(var K=O-b;K!==O&&R[K]===0;)K++;for(var F=u.repeat(E);K<O;++K)F+=t.charAt(R[K]);return F}function x(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var E=0;if(y[E]!==" "){for(var b=0,L=0;y[E]===u;)b++,E++;for(var C=(y.length-E)*d+1>>>0,O=new Uint8Array(C);y[E];){var R=n[y.charCodeAt(E)];if(R===255)return;for(var N=0,B=C-1;(R!==0||N<L)&&B!==-1;B--,N++)R+=l*O[B]>>>0,O[B]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");L=N,E++}if(y[E]!==" "){for(var I=C-L;I!==C&&O[I]===0;)I++;for(var K=new Uint8Array(b+(C-I)),F=b;I!==C;)K[F++]=O[I++];return K}}}function m(y){var E=x(y);if(E)return E;throw new Error(`Non-${e} character`)}return{encode:w,decodeUnsafe:x,decode:m}}var vd=Ad,Cd=vd,Fc=Cd;var $s=class{name;prefix;baseEncode;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")}},zs=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 Kc(this,e)}},Vs=class{decoders;constructor(e){this.decoders=e}or(e){return Kc(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Kc(t,e){return new Vs({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var qs=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new $s(e,r,n),this.decoder=new zs(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function xr({name:t,prefix:e,encode:r,decode:n}){return new qs(t,e,r,n)}function Bt({name:t,prefix:e,alphabet:r,caseInsensitive:n=!1}){let{encode:o,decode:s}=Fc(r,t,n);return xr({prefix:e,name:t,encode:o,decode:i=>Ve(s(i))})}function _d(t,e,r,n){let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let l=e[t[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|l,i+=r,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Td(t,e,r){let n=e[e.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function Ld(t,e){let r={};for(let n=0;n<t.length;++n)if(r[t[n]]=n,e){let o=t[n].toLowerCase(),s=t[n].toUpperCase();o!==t[n]&&(r[o]=n),s!==t[n]&&(r[s]=n)}return r}function me({name:t,prefix:e,bitsPerChar:r,alphabet:n,caseInsensitive:o=!1}){let s=Ld(n,o);return xr({prefix:e,name:t,encode(i){return Td(i,n,r)},decode(i){return _d(i,s,r,t)}})}var ge=Bt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Bd=Bt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var js={};Pe(js,{base32:()=>Dt,base32hex:()=>Od,base32hexpad:()=>Nd,base32hexpadupper:()=>Ud,base32hexupper:()=>Pd,base32pad:()=>Id,base32padupper:()=>Rd,base32upper:()=>Dd,base32z:()=>kd});var Dt=me({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),Dd=me({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),Id=me({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),Rd=me({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),Od=me({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),Pd=me({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),Nd=me({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),Ud=me({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),kd=me({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Gs={};Pe(Gs,{base36:()=>Qr,base36upper:()=>Md});var Qr=Bt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),Md=Bt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var Xe={};Pe(Xe,{Digest:()=>Xt,create:()=>Ne,decode:()=>Ar,equals:()=>Xs,hasCode:()=>nh});var Fd=zc,Hc=128,Kd=127,Hd=~Kd,$d=Math.pow(2,31);function zc(t,e,r){e=e||[],r=r||0;for(var n=r;t>=$d;)e[r++]=t&255|Hc,t/=128;for(;t&Hd;)e[r++]=t&255|Hc,t>>>=7;return e[r]=t|0,zc.bytes=r-n+1,e}var zd=Ys,Vd=128,$c=127;function Ys(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw Ys.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&$c)<<o:(i&$c)*Math.pow(2,o),o+=7}while(i>=Vd);return Ys.bytes=s-n,r}var qd=Math.pow(2,7),Wd=Math.pow(2,14),jd=Math.pow(2,21),Gd=Math.pow(2,28),Yd=Math.pow(2,35),Xd=Math.pow(2,42),Zd=Math.pow(2,49),Qd=Math.pow(2,56),Jd=Math.pow(2,63),eh=function(t){return t<qd?1:t<Wd?2:t<jd?3:t<Gd?4:t<Yd?5:t<Xd?6:t<Zd?7:t<Qd?8:t<Jd?9:10},th={encode:Fd,decode:zd,encodingLength:eh},rh=th,Jr=rh;function en(t,e=0){let r=Jr.decode(t,e),n=Jr.decode.bytes;if(n>9)throw new RangeError("Invalid varint: too long");if(n>1&&t[e+n-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[r,n]}function Er(t,e,r=0){return Jr.encode(t,e,r),e}function Sr(t){return Jr.encodingLength(t)}function Ne(t,e){let r=e.byteLength,n=Sr(t),o=n+Sr(r),s=new Uint8Array(o+r);return Er(t,s,0),Er(r,s,n),s.set(e,o),new Xt(t,r,e,s)}function Ar(t){let e=Ve(t),[r,n]=en(e),[o,s]=en(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Xt(r,o,i,e)}function Xs(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Nc(t.bytes,r.bytes)}}var Xt=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=Yt(n),this.bytes=Yt(o)}};function nh(t,e){return t.code===e}function Vc(t,e){let{bytes:r,version:n}=t;return n===0?sh(r,Zs(t),e??ge.encoder):ih(r,Zs(t),e??Dt.encoder)}var qc=new WeakMap;function Zs(t){let e=qc.get(t);if(e==null){let r=new Map;return qc.set(t,r),r}return e}var Ee=class t{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=Yt(o),this["/"]=this.bytes}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!==tn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==ah)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.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=Ne(e,r);return t.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 t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&Xs(e.multihash,n.multihash)}toString(e){return Vc(this,e)}toJSON(){return{"/":Vc(this)}}link(){return this}[Symbol.toStringTag]="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 t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new t(n,o,s,i??Wc(n,o,s.bytes))}else if(r[ch]===!0){let{version:n,multihash:o,code:s}=r,i=Ar(o);return t.create(n,s,i)}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!==tn)throw new Error(`Version 0 CID must use dag-pb (code: ${tn}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=Wc(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,tn,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,o=Ve(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new Xt(r.multihashCode,r.digestSize,s,o);return[r.version===0?t.createV0(i):t.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[u,d]=en(e.subarray(r));return r+=d,u},o=n(),s=tn;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,a=n(),c=n(),f=r+c,l=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:f}}static parse(e,r){let[n,o]=oh(e,r),s=t.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Zs(s).set(n,e),s}};function oh(t,e){switch(t[0]){case"Q":{let r=e??ge;return[ge.prefix,r.decode(`${ge.prefix}${t}`)]}case ge.prefix:{let r=e??ge;return[ge.prefix,r.decode(t)]}case Dt.prefix:{let r=e??Dt;return[Dt.prefix,r.decode(t)]}case Qr.prefix:{let r=e??Qr;return[Qr.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function sh(t,e,r){let{prefix:n}=r;if(n!==ge.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return o}function ih(t,e,r){let{prefix:n}=r,o=e.get(n);if(o==null){let s=r.encode(t);return e.set(n,s),s}else return o}var tn=112,ah=18;function Wc(t,e,r){let n=Sr(t),o=n+Sr(e),s=new Uint8Array(o+r.byteLength);return Er(t,s,0),Er(e,s,n),s.set(r,o),s}var ch=Symbol.for("@ipld/js-cid/CID");var Qs={};Pe(Qs,{identity:()=>Ze});var jc=0,fh="identity",Gc=Ve;function uh(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return Ne(jc,Gc(t))}var Ze={code:jc,name:fh,encode:Gc,digest:uh};function ve(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}function lh(t){return t.buffer instanceof ArrayBuffer}function Ce(t){return lh(t)?t:t.slice()}async function Yc(t,e,r,n){let o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,Ce(e),Ce(r.subarray()));return n?.signal?.throwIfAborted(),s}function we(t=0){return new Uint8Array(t)}function xe(t=0){return new Uint8Array(t)}function dh(t){return t?.buffer instanceof ArrayBuffer}function Js(t){if(dh(t))return t;let e=t.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Ue(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=xe(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return Js(r)}var Zc=Symbol.for("@achingbrain/uint8arraylist");function Xc(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(let n of t){let o=r+n.byteLength;if(e<o)return{buf:n,index:e-r};r=o}throw new RangeError("index is out of bounds")}function co(t){return!!t?.[Zc]}var Y=class t{bufs;length;[Zc]=!0;constructor(...e){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(co(n)){r+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}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(co(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=Xc(this.bufs,e);return r.buf[r.index]}set(e,r){let n=Xc(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(co(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:o}=this._subList(e,r);return Ue(n,o)}subarray(e,r){let{bufs:n,length:o}=this._subList(e,r);return n.length===1?n[0]:Ue(n,o)}sublist(e,r){let{bufs:n,length:o}=this._subList(e,r),s=new t;return s.length=o,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=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let f=e>=a&&e<c,l=r>a&&r<=c;if(f&&l){if(e===a&&r===c){n.push(i);break}let u=e-a;n.push(i.subarray(u,u+(r-e)));break}if(f){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(l){if(r===c){n.push(i);break}n.push(i.subarray(0,r-a));break}n.push(i)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!co(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 o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let u=0;u<s;u++)i[u]=-1;for(let u=0;u<o;u++)i[n[u]]=u;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,l;for(let u=r;u<=c;u+=l){l=0;for(let d=f;d>=0;d--){let p=this.get(u+d);if(n[d]!==p){l=Math.max(1,d-a[p]);break}}if(l===0)return u}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=xe(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 o=we(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,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 o=we(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,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 o=we(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,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=xe(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 o=we(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,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 o=we(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,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 o=we(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,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 o=we(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,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 o=we(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof t)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!ve(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){let n=new t;return n.bufs=e,r==null&&(r=e.reduce((o,s)=>o+s.byteLength,0)),n.length=r,n}};var ei={};Pe(ei,{base10:()=>hh});var hh=Bt({prefix:"9",name:"base10",alphabet:"0123456789"});var ti={};Pe(ti,{base16:()=>ph,base16upper:()=>mh});var ph=me({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),mh=me({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var ri={};Pe(ri,{base2:()=>gh});var gh=me({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ni={};Pe(ni,{base256emoji:()=>Eh});var Qc=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}"),yh=Qc.reduce((t,e,r)=>(t[r]=e,t),[]),bh=Qc.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function wh(t){return t.reduce((e,r)=>(e+=yh[r],e),"")}function xh(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=bh[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var Eh=xr({prefix:"\u{1F680}",name:"base256emoji",encode:wh,decode:xh});var oi={};Pe(oi,{base64:()=>Sh,base64pad:()=>Ah,base64url:()=>rn,base64urlpad:()=>vh});var Sh=me({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ah=me({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),rn=me({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),vh=me({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var si={};Pe(si,{base8:()=>Ch});var Ch=me({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ii={};Pe(ii,{identity:()=>_h});var _h=xr({prefix:"\0",name:"identity",encode:t=>kc(Ve(t)),decode:t=>Ve(Uc(t))});var i0=new TextEncoder,a0=new TextDecoder;var fi={};Pe(fi,{sha256:()=>mt,sha512:()=>Dh});var Bh=20;function ci({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new ai(t,e,r,n,o)}var ai=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??Bh,this.maxDigestLength=s}digest(e,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Jc(n,this.code,r?.truncate):n.then(o=>Jc(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function Jc(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return Ne(e,t)}function tf(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var mt=ci({name:"sha2-256",code:18,encode:tf("SHA-256")}),Dh=ci({name:"sha2-512",code:19,encode:tf("SHA-512")});var Zt={...ii,...ri,...si,...ei,...ti,...js,...Gs,...Ws,...oi,...ni},w0={...fi,...Qs};function nf(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var rf=nf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ui=nf("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=xe(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Ih={utf8:rf,"utf-8":rf,hex:Zt.base16,latin1:ui,ascii:ui,binary:ui,...Zt},fo=Ih;function Q(t,e="utf8"){let r=fo[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function j(t,e="utf8"){let r=fo[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}var Rh=parseInt("11111",2),li=parseInt("10000000",2),Oh=parseInt("01111111",2),of={0:nn,1:nn,2:Ph,3:kh,4:Mh,5:Uh,6:Nh,16:nn,22:nn,48:nn};function gt(t,e={offset:0}){let r=t[e.offset]&Rh;if(e.offset++,of[r]!=null)return of[r](t,e);throw new Error("No decoder for tag "+r)}function on(t,e){let r=0;if((t[e.offset]&li)===li){let n=t[e.offset]&Oh,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++){if(e.offset>=t.byteLength)throw new Error("invalid DER element length");o+=t[e.offset].toString(16).padStart(2,"0")}r=parseInt(o,16)}else r=t[e.offset],e.offset++;if(!Number.isInteger(r)||r<0||r>t.byteLength-e.offset)throw new Error("invalid DER element length");return r}function nn(t,e){on(t,e);let r=[];for(;!(e.offset>=t.byteLength);){let n=gt(t,e);if(n===null)break;r.push(n)}return r}function Ph(t,e){let r=on(t,e),n=e.offset,o=e.offset+r,s=[];for(let i=n;i<o;i++)i===n&&t[i]===0||s.push(t[i]);return e.offset+=r,Uint8Array.from(s)}function Nh(t,e){let r=on(t,e),n=e.offset+r,o=t[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let f=t[e.offset];if(e.offset++,c.push(f&127),f<128){c.reverse();let l=0;for(let u=0;u<c.length;u++)l+=c[u]<<u*7;a+=`.${l}`,c=[]}}return a}function Uh(t,e){return e.offset++,null}function kh(t,e){let r=on(t,e),n=t[e.offset];e.offset++;let o=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Mh(t,e){let r=on(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function Fh(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);let r=new Y;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function di(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);let e=Fh(t.byteLength);return new Y(Uint8Array.from([e.byteLength|li]),e)}function Fe(t){let e=new Y,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new Y(Uint8Array.from([2]),di(e),e)}function uo(t){let e=Uint8Array.from([0]),r=new Y(e,t);return new Y(Uint8Array.from([3]),di(r),r)}function It(t,e=48){let r=new Y;for(let n of t)r.append(n);return new Y(Uint8Array.from([e]),di(r),r)}var Kh=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Hh=Uint8Array.from([6,5,43,129,4,0,34]),$h=Uint8Array.from([6,5,43,129,4,0,35]),zh={ext:!0,kty:"EC",crv:"P-256"},Vh={ext:!0,kty:"EC",crv:"P-384"},qh={ext:!0,kty:"EC",crv:"P-521"},hi=32,pi=48,mi=66;function gi(t){let e=gt(t);return sf(e)}function sf(t){let e=t[1][1][0],r=1,n,o;if(e.byteLength===hi*2+1)return n=j(e.subarray(r,r+hi),"base64url"),o=j(e.subarray(r+hi),"base64url"),new vr({...zh,key_ops:["verify"],x:n,y:o});if(e.byteLength===pi*2+1)return n=j(e.subarray(r,r+pi),"base64url"),o=j(e.subarray(r+pi),"base64url"),new vr({...Vh,key_ops:["verify"],x:n,y:o});if(e.byteLength===mi*2+1)return n=j(e.subarray(r,r+mi),"base64url"),o=j(e.subarray(r+mi),"base64url"),new vr({...qh,key_ops:["verify"],x:n,y:o});throw new Z(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function af(t){return It([Fe(Uint8Array.from([1])),It([Wh(t.crv)],160),It([uo(new Y(Uint8Array.from([4]),Q(t.x??"","base64url"),Q(t.y??"","base64url")))],161)]).subarray()}function Wh(t){if(t==="P-256")return Kh;if(t==="P-384")return Hh;if(t==="P-521")return $h;throw new Z(`Invalid curve ${t}`)}var vr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=af(this.jwk)),this._raw}toMultihash(){return Ze.digest(Rt(this))}toCID(){return Ee.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ve(this.raw,e.raw)}async verify(e,r,n){return Yc(this.jwk,r,e,n)}};var lo=BigInt(4294967295),cf=BigInt(32);function jh(t,e=!1){return e?{h:Number(t&lo),l:Number(t>>cf&lo)}:{h:Number(t>>cf&lo)|0,l:Number(t&lo)|0}}function ff(t,e=!1){let r=t.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=jh(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Gh=t=>t/2**32|0,Yh=t=>t>>>0;function uf(t,e,r,n){let o=Gh(r),s=Yh(r);t.setUint32(e,n?s:o,n),t.setUint32(e+4,n?o:s,n)}var yi=(t,e,r)=>t>>>r,bi=(t,e,r)=>t<<32-r|e>>>r,Qt=(t,e,r)=>t>>>r|e<<32-r,Jt=(t,e,r)=>t<<32-r|e>>>r,sn=(t,e,r)=>t<<64-r|e>>>r-32,an=(t,e,r)=>t>>>r-32|e<<64-r;function ct(t,e,r,n){let o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}var lf=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),df=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,hf=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),pf=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0,mf=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0),gf=(t,e,r,n,o,s)=>e+r+n+o+s+(t/2**32|0)|0;function ho(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}var wi=t=>t?`"${t}" `:"";function Qe(t,e=""){if(typeof t!="number")throw new TypeError(wi(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(wi(e)+"expected integer >= 0, got "+t);return t}function ke(t,e,r=""){if(ho(t)&&(e===void 0||t.length===e))return t;e!==void 0&&Qe(e,"length");let n=ho(t),o=e!==void 0?` of length ${e}`:"",s=n?`length=${t.length}`:`type=${typeof t}`,i=wi(r)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}function er(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Qe(t.outputLen),Qe(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var Zh=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)},yf=(t,e)=>{Zh(t,e);let r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(t,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function Cr(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function po(t,e){ke(t,void 0,"output");let r=e.outputLen;if(!(t.length>=r))throw new RangeError('"output" expected length >= '+r)}function qe(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function mo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Je(t,e){return t<<32-e|t>>>e}var wf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qh=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function go(t){if(ke(t),wf)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Qh[t[r]];return e}function bf(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function yo(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(wf)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=bf(t.charCodeAt(s)),a=bf(t.charCodeAt(s+1));if(i===void 0||a===void 0){let c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function xi(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];ke(o),e+=o.length}let r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){let s=t[n];r.set(s,o),o+=s.length}return r}function Jh(t,e,r="opts"){return yf(t,"defaults"),e!==void 0&&yf(e,r),Object.assign(Object.create(null),t,e)}function Ei(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=Jh({},e,"info");let r=(o,s)=>t(s).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function xf(t=32){Qe(t,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var Si=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Ef(t,e,r){return t&e^~t&r}function Sf(t,e,r){return t&e^t&r^e&r}var cn=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,o){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=mo(this.buffer)}update(e){Cr(this),ke(e);let{view:r,buffer:n,blockLen:o}=this,s=e.length,i=!1;for(let a=0;a<s;){let c=Math.min(o-this.pos,s-a);if(c===o){let f=mo(e);for(;o<=s-a;a+=o)this.process(f,a);i=!0;continue}n.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(r,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){Cr(this),po(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,r.fill(0,i),this.padOffset>o-i&&(this.process(n,0),r.fill(0)),uf(n,o-8,this.length*8,s),this.process(n,0),this.roundClean();let a=e===r?n:mo(e),c=this.outputLen,f=c/4,l=this.get();if(c%4||f>l.length)throw new Error("invalid outputLen");for(let u=0;u<f;u++)a.setUint32(4*u,l[u],s)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:r,length:n,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=n,e.pos=i,i&&e.buffer.set(r),e}clone(){return this._cloneInto()}},Af=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var vf=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var ep=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ot=new Uint32Array(64),Ai=class extends cn{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,r){super(64,e,8,!1),this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,r){for(let u=0;u<16;u++,r+=4)Ot[u]=e.getUint32(r,!1);for(let u=16;u<64;u++){let d=Ot[u-15],p=Ot[u-2],w=Je(d,7)^Je(d,18)^d>>>3,x=Je(p,17)^Je(p,19)^p>>>10;Ot[u]=x+Ot[u-7]+w+Ot[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:f,H:l}=this;for(let u=0;u<64;u++){let d=Je(a,6)^Je(a,11)^Je(a,25),p=l+d+Ef(a,c,f)+ep[u]+Ot[u]|0,x=(Je(n,2)^Je(n,13)^Je(n,22))+Sf(n,o,s)|0;l=f,f=c,c=a,a=i+p|0,i=s,s=o,o=n,n=p+x|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,f,l)}roundClean(){qe(Ot)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),qe(this.buffer)}},vi=class extends Ai{constructor(){super(32,Af)}};var Cf=ff(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),tp=Cf[0],rp=Cf[1],Pt=new Uint32Array(80),Nt=new Uint32Array(80),Ci=class extends cn{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,r){super(128,e,16,!1),this.Ah=r[0]|0,this.Al=r[1]|0,this.Bh=r[2]|0,this.Bl=r[3]|0,this.Ch=r[4]|0,this.Cl=r[5]|0,this.Dh=r[6]|0,this.Dl=r[7]|0,this.Eh=r[8]|0,this.El=r[9]|0,this.Fh=r[10]|0,this.Fl=r[11]|0,this.Gh=r[12]|0,this.Gl=r[13]|0,this.Hh=r[14]|0,this.Hl=r[15]|0}get(){let{Ah:e,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:l,Fh:u,Fl:d,Gh:p,Gl:w,Hh:x,Hl:m}=this;return[e,r,n,o,s,i,a,c,f,l,u,d,p,w,x,m]}set(e,r,n,o,s,i,a,c,f,l,u,d,p,w,x,m){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=f|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=p|0,this.Gl=w|0,this.Hh=x|0,this.Hl=m|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,r){for(let b=0;b<16;b++,r+=4)Pt[b]=e.getUint32(r),Nt[b]=e.getUint32(r+=4);for(let b=16;b<80;b++){let L=Pt[b-15]|0,C=Nt[b-15]|0,O=Qt(L,C,1)^Qt(L,C,8)^yi(L,C,7),R=Jt(L,C,1)^Jt(L,C,8)^bi(L,C,7),N=Pt[b-2]|0,B=Nt[b-2]|0,I=Qt(N,B,19)^sn(N,B,61)^yi(N,B,6),K=Jt(N,B,19)^an(N,B,61)^bi(N,B,6),F=hf(R,K,Nt[b-7],Nt[b-16]),V=pf(F,O,I,Pt[b-7],Pt[b-16]);Pt[b]=V|0,Nt[b]=F|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:l,Eh:u,El:d,Fh:p,Fl:w,Gh:x,Gl:m,Hh:y,Hl:E}=this;for(let b=0;b<80;b++){let L=Qt(u,d,14)^Qt(u,d,18)^sn(u,d,41),C=Jt(u,d,14)^Jt(u,d,18)^an(u,d,41),O=u&p^~u&x,R=d&w^~d&m,N=mf(E,C,R,rp[b],Nt[b]),B=gf(N,y,L,O,tp[b],Pt[b]),I=N|0,K=Qt(n,o,28)^sn(n,o,34)^sn(n,o,39),F=Jt(n,o,28)^an(n,o,34)^an(n,o,39),V=n&s^n&a^s&a,_=o&i^o&c^i&c;y=x|0,E=m|0,x=p|0,m=w|0,p=u|0,w=d|0,{h:u,l:d}=ct(f|0,l|0,B|0,I|0),f=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let U=lf(I,F,_);n=df(U,B,K,V),o=U|0}({h:n,l:o}=ct(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ct(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ct(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l}=ct(this.Dh|0,this.Dl|0,f|0,l|0),{h:u,l:d}=ct(this.Eh|0,this.El|0,u|0,d|0),{h:p,l:w}=ct(this.Fh|0,this.Fl|0,p|0,w|0),{h:x,l:m}=ct(this.Gh|0,this.Gl|0,x|0,m|0),{h:y,l:E}=ct(this.Hh|0,this.Hl|0,y|0,E|0),this.set(n,o,s,i,a,c,f,l,u,d,p,w,x,m,y,E)}roundClean(){qe(Pt,Nt)}destroy(){this.destroyed=!0,qe(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},_i=class extends Ci{constructor(){super(64,vf)}};var ft=Ei(()=>new vi,Si(1));var Ti=Ei(()=>new _i,Si(3));function wo(t,e,r=()=>{}){if(!Array.isArray(t))throw new TypeError(`"${e}" expected array, got type=${typeof t}`);for(let n=0;n<t.length;n++)r(t[n],`${e}[${n}]`);return t}var J=(t,e,r)=>ke(t,e,r),Li=Qe;function Tf(t,e=""){if(typeof t!="string"){let r=e&&`"${e}" `;throw new TypeError(r+"expected string, got type="+typeof t)}return t}function Ut(t,e="object"){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`);return t}function tr(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}var fn=go,We=(...t)=>xi(...t),_r=t=>yo(t),Mt=ho,yt=t=>xf(t),bo=BigInt(0),_f=BigInt(1),np=t=>t?`"${t}" `:"";function Ke(t,e=""){if(typeof t!="boolean")throw new TypeError(np(e)+"expected boolean, got type="+typeof t);return t}function xo(t){if(typeof t=="bigint"){if(!kt(t))throw new RangeError("positive bigint expected, got "+t)}else Li(t);return t}function bt(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(r+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){let r=e&&`"${e}" `;throw new RangeError(r+"expected safe integer, got "+t)}}function un(t){let e=xo(t).toString(16);return e.length&1?"0"+e:e}function Lf(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?bo:BigInt("0x"+t)}function ut(t){return Lf(go(t))}function lt(t){return Lf(go(Ft(ke(t)).reverse()))}function Eo(t,e){if(Qe(e),e===0)throw new Error("zero output length is invalid");t=xo(t);let r=e*2,n=t.toString(16);if(n.length>r)throw new RangeError("number is too large");return yo(n.padStart(r,"0"))}function ln(t,e){return Eo(t,e).reverse()}function Ft(t){return Uint8Array.from(J(t))}function kt(t){return typeof t=="bigint"&&bo<=t}function Bi(t,e,r){return kt(t)&&kt(e)&&kt(r)&&e<=t&&t<r}function dt(t,e,r,n){if(!Bi(e,r,n))throw new RangeError("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Tr(t){if(t<bo)throw new Error("expected non-negative bigint, got "+t);return t===bo?0:t.toString(2).length}var dn=t=>(bt(t,"n"),(_f<<BigInt(t))-_f);function Bf(t,e,r){if(Qe(t,"hashLen"),Qe(e,"qByteLen"),typeof r!="function")throw new TypeError("hmacFn must be a function");let n=m=>new Uint8Array(m),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(t),f=n(t),l=0,u=()=>{c.fill(1),f.fill(0),l=0},d=(...m)=>r(f,We(c,...m)),p=(m=o)=>{f=d(s,m),c=d(),m.length!==0&&(f=d(i,m),c=d())},w=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let m=0,y=[];for(;m<e;){c=d();let E=c.slice();y.push(E),m+=c.length}return We(...y)};return(m,y)=>{u(),p(m);let E;for(;(E=y(w()))===void 0;)p();return u(),E}}function Be(t,e={},r={},n="object"){Ut(t,n),Ut(e,"fields"),Ut(r,"optFields");function o(i,a,c){let f=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,l=t[i];if(!Object.hasOwn(t,i)&&(c?l!==void 0:a!=="function"))throw new TypeError(`${f} is invalid: expected own property`);if(c&&l===void 0)return;let u=typeof l;if(u!==a||l===null)throw new TypeError(`${f} is invalid: expected ${a}, got ${u}`)}let s=(i,a)=>Object.entries(i).forEach(([c,f])=>o(c,f,a));s(e,!1),s(r,!0)}var Se=BigInt(0),re=BigInt(1),Kt=BigInt(2),Rf=BigInt(3),Di=BigInt(4),Of=BigInt(5),op=BigInt(7),Pf=BigInt(8),sp=BigInt(9),ip=BigInt(15),Nf=BigInt(16),ap=BigInt("0x10000000000000000");function se(t,e){if(e<=Se)throw new Error("mod: expected positive modulus, got "+e);let r=t%e;return r>=Se?r:e+r}function Uf(t,e,r){if(r<=re)throw new Error("pow: expected modulus > 1, got "+r);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<Se)throw new Error("invalid exponent, negatives unsupported");if(e===Se)return re;if(e===re)return t;let n=t%r;if(n<Se&&(n+=r),e<ap){let a=re;for(;e>Se;)e&re&&(a=a*n%r),n=n*n%r,e>>=re;return a}let o=[];for(;e>Se;)o.push(Number(e&ip)),e>>=Di;let s=new Array(16);s[0]=re,s[1]=n;for(let a=2;a<16;a++)s[a]=s[a-1]*n%r;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%r,i=i*i%r,i=i*i%r,i=i*i%r;let c=o[a];c!==0&&(i=i*s[c]%r)}return i}function le(t,e,r){if(r<=re)throw new Error("pow2: expected modulus > 1, got "+r);if(e<Se)throw new Error("pow2: expected non-negative exponent, got "+e);let n=t;for(;e-- >Se;)n*=n,n%=r;return n}function Df(t,e){if(t===Se)throw new Error("invert: expected non-zero number");if(e<=re)throw new Error("invert: expected modulus > 1, got "+e);let r=se(t,e),n=e,o=Se,s=re;for(;r!==Se;){let a=n/r,c=n-r*a,f=o-s*a;n=r,r=c,o=s,s=f}if(n!==re)throw new Error("invert: does not exist");return se(o,e)}function kf(t,e){if(e<=re)throw new Error("invertCt: expected prime modulus > 1, got "+e);let r=se(t,e);if(r===Se)throw new Error("invertCt: expected non-zero number");let n=Uf(r,e-Kt,e);if(se(r*n,e)!==re)throw new Error("invertCt: does not exist");return n}function Ii(t,e,r){let n=t;if(!n.eql(n.sqr(e),r))throw new Error("Cannot find square root")}function Ri(t,e){if((t&re)===Se)throw new Error(e+": expected odd modulus, got "+t)}function Mf(t,e){let r=t,n=(r.ORDER+re)/Di,o=r.pow(e,n);return Ii(r,o,e),o}function cp(t,e){let r=t,n=(r.ORDER-Of)/Pf,o=r.mul(e,Kt),s=r.pow(o,n),i=r.mul(e,s),a=r.mul(r.mul(i,Kt),s),c=r.mul(i,r.sub(a,r.ONE));return Ii(r,c,e),c}function fp(t){let e=Br(t),r=Ff(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+op)/Nf;return((a,c)=>{let f=a,l=f.pow(c,i),u=f.mul(l,n),d=f.mul(l,o),p=f.mul(l,s),w=f.eql(f.sqr(u),c),x=f.eql(f.sqr(d),c);l=f.cmov(l,u,w),u=f.cmov(p,d,x);let m=f.eql(f.sqr(u),c),y=f.cmov(l,u,m);return Ii(f,y,c),y})}function Ff(t){if(t<Rf)throw new Error("sqrt is not defined for small field");Ri(t,"tonelliShanks");let e=t-re,r=0;for(;e%Kt===Se;)e/=Kt,r++;let n=Kt,o=Br(t);for(;hn(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Mf;let s=o.pow(n,e),i=(e+re)/Kt;return function(c,f){let l=c;if(l.is0(f))return f;if(hn(l,f)!==1)throw new Error("Cannot find square root");let u=r,d=l.mul(l.ONE,s),p=l.pow(f,e),w=l.pow(f,i);for(;!l.eql(p,l.ONE);){if(l.is0(p))throw new Error("Cannot find square root: probably non-prime P");let x=1,m=l.sqr(p);for(;!l.eql(m,l.ONE);)if(x++,m=l.sqr(m),x===u)throw new Error("Cannot find square root");let y=re<<BigInt(u-x-1),E=l.pow(d,y);u=x,d=l.sqr(E),p=l.mul(p,d),w=l.mul(w,E)}return w}}function up(t){return Ri(t,"Fp.sqrt"),t%Di===Rf?Mf:t%Pf===Of?cp:t%Nf===sp?fp(t):Ff(t)}var Kf=(t,e)=>(se(t,e)&re)===re,lp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Lr(t){if(Ut(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);bt(t.BYTES,"BYTES"),bt(t.BITS,"BITS");for(let e of lp)tr(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=re)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function Ao(t,e,r=!1){Lr(t),wo(e,"nums"),Ke(r,"passZero");let n=t,o=new Array(e.length).fill(r?n.ZERO:void 0),s=e.reduce((a,c,f)=>n.is0(c)?a:(o[f]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,f)=>n.is0(c)?a:(o[f]=n.mul(a,o[f]),n.mul(a,c)),i),o}function hn(t,e){Lr(t);let r=t;Ri(r.ORDER,"FpLegendre");let n=(r.ORDER-re)/Kt,o=r.pow(e,n),s=r.eql(o,r.ONE),i=r.eql(o,r.ZERO),a=r.eql(o,r.neg(r.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function dp(t,e){if(e!==void 0&&Li(e),t<=Se)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let r=Tr(t);if(e!==void 0&&e<r)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${r})`);let n=e!==void 0?e:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var If=new WeakMap,So=class{ORDER;BITS;BYTES;isLE;ZERO=Se;ONE=re;_lengths;_mod;constructor(e,r={}){if(e<=re)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:o,nByteLength:s}=dp(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return se(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Se<=e&&e<this.ORDER}is0(e){return e===Se}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&re)===re}neg(e){return se(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return se(e*e,this.ORDER)}add(e,r){return se(e+r,this.ORDER)}sub(e,r){return se(e-r,this.ORDER)}mul(e,r){return se(e*r,this.ORDER)}pow(e,r){return Uf(e,r,this.ORDER)}div(e,r){return se(e*Df(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return Df(e,this.ORDER)}sqrt(e){let r=If.get(this);return r||If.set(this,r=up(this.ORDER)),r(this,e)}toBytes(e){return this.isLE?ln(e,this.BYTES):Eo(e,this.BYTES)}fromBytes(e,r=!1){J(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let f=new Uint8Array(o);f.set(e,s?0:f.length-e.length),e=f}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?lt(e):ut(e);if(a&&(c=se(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Ao(this,e,!0)}cmov(e,r,n){return Ke(n,"condition"),n?r:e}};function Br(t,e={}){return Object.freeze(So.prototype),new So(t,e)}function Hf(t){if(typeof t!="bigint")throw new Error("field order must be bigint");if(t<=re)throw new Error("field order must be greater than 1");let e=Tr(t-re);return Math.ceil(e/8)}function vo(t){let e=Hf(t);return e+Math.ceil(e/2)}function Co(t,e,r=!1){J(t);let n=t.length,o=Hf(e),s=Math.max(vo(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?lt(t):ut(t),a=se(i,e-re)+re;return r?ln(a,o):Eo(a,o)}var Ni=BigInt(0),pn=BigInt(1),hp=BigInt(4),Oi=16,$f=128,pp=5,zf=2**31;function Ht(t){let e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);tr(e.fromAffine,"Point.fromAffine"),tr(e.fromBytes,"Point.fromBytes"),tr(e.fromHex,"Point.fromHex"),Ut(e.BASE,"Point.BASE"),Ut(e.ZERO,"Point.ZERO"),Lr(e.Fp),Lr(e.Fn)}function _o(t,e){Ht(t),qf(e,t);let r=Ao(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function mp(t,e,r=1){if(!Number.isSafeInteger(t)||t<r||t>e)throw new Error("invalid window size, expected ["+r+".."+e+"], got W="+t)}function gp(t,e){let r=t*(4*e+128);if(r>zf)throw new Error("invalid window size: table would need ~"+Math.ceil(r/2**20)+" MiB, max "+zf/2**20+" MiB")}function Ui(t,e){if(t!==void 0){tr(t,"randomBytes");try{let r=t(e);if(!Mt(r)||r.length!==e)return}catch{return}return t}}function qf(t,e){wo(t,"points"),t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function yp(t,e,r){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,o)=>{if(!(r===void 0?e.isValid(n):kt(n)&&n<r))throw new Error("invalid scalar at index "+o)})}var Wf=new WeakMap;function Pi(t){return Wf.get(t)||1}function bp(t,e){let r=t.double(),n=[t];for(let o=1;o<e;o++)n.push(n[o-1].add(r));return n}function wp(t,e){let r=2**e,n=r/2,o=BigInt(r-1),s=[];for(;t>Ni;){let i=0;t&pn&&(i=Number(t&o),i>=n&&(i-=r),t-=BigInt(i)),s.push(i),t>>=pn}return s}function xp(t,e,r){let n=2**e,o=n/2,s=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<r;c++){let f=Number(t&s);t>>=i,f>o&&(f-=n,t+=pn),a.push(f)}if(t!==Ni)throw new Error("invalid wnaf");return a}function Ep(t,e,r){let n=0;for(let s of r)n=Math.max(n,s.length);let o=t;for(let s=n-1;s>=0;s--){s!==n-1&&(o=o.double());for(let i=0;i<r.length;i++){let a=r[i][s];if(a){let c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}var Dr=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,r){Ht(e),this.randomBytes=Ui(r,Oi),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,r,n){let o=Math.ceil(n/r)+1,s=2**(r-1),i=[],a=e;for(let c=0;c<o;c++){let f=a;for(let l=0;l<s;l++)i.push(f),f=f.add(a);a=i[i.length-1].double()}return{W:r,bits:n,windows:o,comp:i}}wnafCachedCT(e,r){let{W:n,windows:o,comp:s}=e,i=2**(n-1),a=xp(r,n,o),c=this.ZERO,f=this.BASE;for(let l=0;l<o;l++){let u=a[l],d=l*i,p=Math.abs(u)-1,w=s[d];for(let m=1;m<i;m++)w=m===p?s[d+m]:w;let x=w.negate();u===0?f=f.add(s[d]):c=c.add(u<0?x:w)}return{p:c,f}}getWnafPrecomputes(e,r,n,o){let s=this.wnafPrecomputes.get(r),i=s?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(r,e,n),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(r,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,r){if(this.assertPoint(e),!Bi(r,pn,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,r,n,o){let s=Pi(e);return s===1?this.fixedWindowCT(e,r,n):this.wnafCachedCT(this.getWnafPrecomputes(s,e,n,o),r)}mulCT(e,r,n){return this.validateMulInput(e,r),this.runCT(e,r,this.bits,n)}mulCTBlinded(e,r,n){if(this.validateMulInput(e,r),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+$f,s=this.randomBytes(Oi);if(!Mt(s)||s.length!==Oi)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;let i=r+ut(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,n)}fixedWindowCT(e,r,n){let o=pp,s=1<<o,i=dn(o),a=new Array(s);a[0]=this.ZERO;for(let l=1;l<s;l++)a[l]=a[l-1].add(e);let c=Math.ceil(n/o),f=this.ZERO;for(let l=c-1;l>=0;l--){if(l!==c-1)for(let p=0;p<o;p++)f=f.double();let u=Number(r>>BigInt(l*o)&i),d=a[0];for(let p=1;p<s;p++)d=p===u?a[p]:d;f=f.add(d)}return{p:f,f}}shouldBlind(e,r){return this.randomBytes===void 0?!1:r===pn?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,r,n,o){return this.shouldBlind(e,n)?this.mulCTBlinded(e,r,o):this.mulCT(e,r,o)}mulUnsafe(e,r,n){if(this.assertPoint(e),!kt(r))throw new Error("invalid scalar");let o=Pi(e);if(o===1||r>=this.Point.Fn.ORDER)return To(this.Point,[e],[r],!0);let s=this.getWnafPrecomputes(o,e,this.bits,n);return this.wnafCachedCT(s,r).p}setWindowSize(e,r){this.assertPoint(e),mp(r,this.bits);let n=Math.ceil((this.bits+$f)/r)+1;gp(n*2**(r-1),this.Point.Fp.BYTES),Wf.set(e,r),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Pi(e)!==1}};function To(t,e,r,n=!1){if(Ht(t),qf(e,t),Ke(n,"allowOversized"),yp(r,t.Fn,n?t.Fn.ORDER**hp:void 0),e.length!==r.length)throw new Error("arrays of points and scalars must have equal length");let o=e.map(i=>bp(i,4)),s=r.map(i=>wp(i,4));return Ep(t.ZERO,o,s)}function Vf(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Lr(e),e}else return Br(t,{isLE:r})}function Lo(t,e,r={},n){if(t!=="weierstrass"&&t!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);Be(r);for(let c of["p","n","h"]){let f=e[c];if(!(kt(f)&&f!==Ni))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Vf(e.p,r.Fp,n),s=Vf(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function Ir(t,e){return function(n){let o=t(n);return{secretKey:o,publicKey:e(o)}}}var Bo=BigInt(0),Do=BigInt(1),Io=BigInt(2),Sp=BigInt(4),jf=BigInt(8);function Ap(t,e,r,n){let o=t.sqr(r),s=t.sqr(n),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function Gf(t,e={}){Be(e,{},{},"extraOpts");let r=e,n=Lo("edwards",t,r,r.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;if(hn(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(hn(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Be(r,{},{uvRatio:"function",randomBytes:"function"});let c=r.randomBytes===void 0?yt:r.randomBytes,f=Io<<BigInt(o.BYTES*8)-Do;function l(E){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(E)}let u=r.uvRatio===void 0?(E,b)=>{try{return{isValid:!0,value:o.sqrt(o.div(E,b))}}catch{return{isValid:!1,value:Bo}}}:r.uvRatio;if(!Ap(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");let d=o.eql(i.a,o.neg(o.ONE))?E=>o.neg(E):o.eql(i.a,o.ONE)?E=>E:E=>o.mul(i.a,E);function p(E,b,L=!1){let C=L?Do:Bo;return dt("coordinate "+E,b,C,f),b}function w(E){if(!(E instanceof x))throw new Error("EdwardsPoint expected")}class x{static BASE=new x(i.Gx,i.Gy,o.ONE,o.mul(i.Gx,i.Gy));static ZERO=new x(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(b,L,C,O){this.X=p("x",b),this.Y=p("y",L),this.Z=p("z",C,!0),this.T=p("t",O),Object.freeze(this)}static CURVE(){return i}static fromAffine(b){if(b instanceof x)throw new Error("extended point not allowed");let{x:L,y:C}=b||{};return p("x",L),p("y",C),new x(L,C,o.ONE,o.mul(L,C))}static fromBytes(b,L=!1){let C=o.BYTES,{a:O,d:R}=i;b=Ft(J(b,C,"point")),Ke(L,"zip215");let N=Ft(b),B=b[C-1];N[C-1]=B&-129;let I=lt(N),K=L?f:o.ORDER;dt("point.y",I,Bo,K);let F=o.sqr(I),V=o.sub(F,o.ONE),_=o.sub(o.mulN(R,F),O),{isValid:U,value:T}=u(V,_);if(!U)throw new Error("bad point: invalid y coordinate");let v=l(T),H=(B&128)!==0;if(!L&&o.is0(T)&&H)throw new Error("bad point: x=0 and x_0=1");return H!==v&&(T=o.neg(T)),x.fromAffine({x:T,y:I})}static fromHex(b,L=!1){return x.fromBytes(_r(b),L)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=6,L=!0){return y.setWindowSize(this,b),L||this.multiply(Io),this}assertValidity(){let b=this,{a:L,d:C}=i;if(b.is0())throw new Error("bad point: ZERO");let{X:O,Y:R,Z:N,T:B}=b,I=o.sqr(O),K=o.sqr(R),F=o.sqr(N),V=o.sqr(F),_=o.mul(I,L),U=o.mul(o.add(_,K),F),T=o.add(V,o.mul(C,o.mul(I,K)));if(!o.eql(U,T))throw new Error("bad point: equation left != right (1)");let v=o.mul(O,R),H=o.mul(N,B);if(!o.eql(v,H))throw new Error("bad point: equation left != right (2)")}equals(b){w(b);let{X:L,Y:C,Z:O}=this,{X:R,Y:N,Z:B}=b,I=o.mul(L,B),K=o.mul(R,O),F=o.mul(C,B),V=o.mul(N,O);return o.eql(I,K)&&o.eql(F,V)}is0(){return this.equals(x.ZERO)}negate(){return new x(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:b,Y:L,Z:C}=this,O=o.sqr(b),R=o.sqr(L),N=o.mul(o.sqr(C),Io),B=d(O),I=o.addN(b,L),K=o.sub(o.subN(o.sqr(I),O),R),F=o.addN(B,R),V=o.subN(F,N),_=o.subN(B,R),U=o.mul(K,V),T=o.mul(F,_),v=o.mul(K,_),H=o.mul(V,F);return new x(U,T,H,v)}add(b){w(b);let{d:L}=i,{X:C,Y:O,Z:R,T:N}=this,{X:B,Y:I,Z:K,T:F}=b,V=o.mul(C,B),_=o.mul(O,I),U=o.mul(o.mulN(N,L),F),T=o.mul(R,K),v=o.sub(o.subN(o.mulN(o.addN(C,O),o.addN(B,I)),V),_),H=o.subN(T,U),D=o.addN(T,U),S=o.sub(_,d(V)),h=o.mul(v,H),g=o.mul(D,S),A=o.mul(v,S),P=o.mul(H,D);return new x(h,g,P,A)}subtract(b){return w(b),this.add(b.negate())}multiply(b){if(!s.isValidNot0(b))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:L,f:C}=y.mulSecret(this,b,a,m);return m([L,C])[0]}multiplyUnsafe(b){if(!s.isValid(b))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return b===Bo?x.ZERO:this.is0()||b===Do?this:y.mulUnsafe(this,b,m)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return y.mulUnsafe(this,i.n).is0()}toAffine(b){let L=this,C=b;if(C!=null&&typeof C!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof C);let{X:O,Y:R,Z:N}=L,B=L.is0();C==null&&(C=B?o.create(jf):o.inv(N));let I=o.mul(O,C),K=o.mul(R,C),F=o.mul(N,C);if(B)return{x:o.ZERO,y:o.ONE};if(!o.eql(F,o.ONE))throw new Error("invZ was invalid");return{x:I,y:K}}clearCofactor(){return a===Do?this:a===Io?this.double():a===Sp?this.double().double():a===jf?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:b,y:L}=this.toAffine(),C=o.toBytes(L);return C[C.length-1]|=l(b)?128:0,C}toHex(){return fn(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let m=E=>_o(x,E),y=new Dr(x,c);return y.bits>=6&&x.BASE.precompute(6),Object.freeze(x.prototype),Object.freeze(x),x}function Yf(t,e,r={}){if(Ht(t),typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=r;Be(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=t,f=n.outputLen,l=2*a.BYTES;if(f!==void 0&&(bt(f,"hash.outputLen"),f!==l))throw new Error(`hash.outputLen must be ${l}, got ${f}`);let u=o.randomBytes===void 0?yt:o.randomBytes,d=o.toMontgomery,p=o.toMontgomerySecret,w=o.adjustScalarBytes===void 0?_=>_:o.adjustScalarBytes,x=o.domain===void 0?(_,U,T)=>{if(Ke(T,"phflag"),U.length||T)throw new Error("Contexts/pre-hash are not supported");return _}:o.domain;function m(_){return c.create(lt(_))}function y(_){let U=B.secretKey;J(_,B.secretKey,"secretKey");let T=J(n(_),2*U,"hashedSecretKey"),v=w(T.slice(0,U)),H=T.slice(U,2*U),D=m(v);return{head:v,prefix:H,scalar:D}}function E(_){let{head:U,prefix:T,scalar:v}=y(_),H=i.multiply(v),D=H.toBytes();return{head:U,prefix:T,scalar:v,point:H,pointBytes:D}}function b(_){return E(_).pointBytes}function L(_=Uint8Array.of(),...U){let T=We(...U);return m(n(x(T,J(_,void 0,"context"),!!s)))}function C(_,U,T={}){Be(T,{},{},"options"),_=Ft(J(_,void 0,"message")),s&&(_=s(_));let{prefix:v,scalar:H,pointBytes:D}=E(U),S=L(T.context,v,_),h=i.multiply(S).toBytes(),g=L(T.context,h,D,_),A=c.create(S+g*H);if(!c.isValid(A))throw new Error("sign failed: invalid s");let P=We(h,c.toBytes(A));return J(P,B.signature,"result")}let O={zip215:o.zip215};function R(_,U,T,v=O){Be(v);let{context:H}=v,D=v.zip215===void 0?!!O.zip215:v.zip215,S=B.signature;_=J(_,S,"signature"),U=J(U,void 0,"message"),T=J(T,B.publicKey,"publicKey"),D!==void 0&&Ke(D,"zip215"),s&&(U=s(U));let h=S/2,g=_.subarray(0,h),A=lt(_.subarray(h,S)),P,k,M;try{P=t.fromBytes(T,D),k=t.fromBytes(g,D),M=i.multiplyUnsafe(A)}catch{return!1}if(!D&&P.isSmallOrder())return!1;let $=L(H,g,T,U);return k.add(P.multiplyUnsafe($)).subtract(M).clearCofactor().is0()}let N=a.BYTES,B={secretKey:N,publicKey:N,signature:2*N,seed:N};function I(_){return _=_===void 0?u(B.seed):_,J(_,B.seed,"seed")}function K(_){return Mt(_)&&_.length===B.secretKey}function F(_,U){try{return!!t.fromBytes(_,U===void 0?O.zip215:U)}catch{return!1}}let V={getExtendedPublicKey:E,randomSecretKey:I,isValidSecretKey:K,isValidPublicKey:F,toMontgomery(_){if(d===void 0)throw new Error("Montgomery conversion is not supported for this curve");return d(t.fromBytes(_))},toMontgomerySecret(_){if(p===void 0)throw new Error("Montgomery conversion is not supported for this curve");return p(_)}};return Object.freeze(B),Object.freeze(V),Object.freeze({keygen:Ir(I,b),getPublicKey:b,sign:C,verify:R,utils:V,Point:t,lengths:B})}var rr=BigInt(0),je=BigInt(1),Ro=BigInt(2);function Xf(t,e){return t+e-(e>>je<<je)}function vp(t){let e=BigInt(6)*t;return(r,n,o)=>{let s=n+o,a=((e+o-n)*r+n)%t;return{x_2:a,x_3:s-a}}}function Cp(t){return Be(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...t})}function Zf(t){let e=Cp(t),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=e.scalarMultBase,c=n==="x25519";if(!c&&n!=="x448")throw new Error("invalid type");let f=i===void 0?yt:i,l=c?255:448,u=vp(r),d=c?32:56,p=BigInt(c?9:5),w=BigInt(c?121665:39081),x=c?Ro**BigInt(254):Ro**BigInt(447),m=c?BigInt(8)*(Ro**BigInt(251)-je):BigInt(4)*(Ro**BigInt(445)-je),y=x+m+je,E=T=>se(T,r),b=L(p);function L(T){return ln(E(T),d)}function C(T){let v=Ft(J(T,d,"uCoordinate"));return c&&(v[31]&=127),E(lt(v))}function O(T){return lt(o(Ft(J(T,d,"scalar"))))}let R=new Set(c?[rr,je,r-je,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[rr,je,r-je]);function N(T,v){let H=C(v);if(R.has(H))throw new Error("invalid private or public key received");let D=F(H,O(T));if(D===rr)throw new Error("invalid private or public key received");return L(D)}function B(T){if(a===void 0)return N(T,b);let v=O(T);dt("scalar",v,x,y);let H=E(a(v));if(H===rr)throw new Error("invalid private or public key received");return L(H)}let I=B,K=N;function F(T,v){dt("u",T,rr,r),dt("scalar",v,x,y);let H=v,D=T,S=je,h=rr,g=T,A=je,P=H^H>>je;for(let $=BigInt(l-1);$>=rr;$--){let z=Xf(r,P>>$);({x_2:S,x_3:g}=u(z,S,g)),{x_2:h,x_3:A}=u(z,h,A);let W=S+h,G=E(W*W),ue=S-h,ie=E(ue*ue),ye=G-ie,Me=g+A,fe=g-A,he=E(fe*W),mr=E(Me*ue),Zr=he+mr,Tt=he-mr;g=E(Zr*Zr),A=E(D*E(Tt*Tt)),S=E(G*ie),h=E(ye*(G+E(w*ye)))}let k=Xf(r,H);({x_2:S,x_3:g}=u(k,S,g)),{x_2:h,x_3:A}=u(k,h,A);let M=s(h);return E(S*M)}let V={secretKey:d,publicKey:d,seed:d},_=T=>(T=T===void 0?f(d):T,J(T,V.seed,"seed"),T),U={randomSecretKey:_};return Object.freeze(V),Object.freeze(U),Object.freeze({keygen:Ir(_,I),getSharedSecret:K,getPublicKey:I,scalarMult:N,scalarMultBase:B,utils:U,GuBytes:b.slice(),lengths:V})}var Qf=BigInt(0),ki=BigInt(1),Jf=BigInt(2),_p=BigInt(3),Tp=BigInt(5),Lp=BigInt(8),Oo=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Bp={p:Oo,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Lp,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function ru(t){let e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=Oo,a=t*t%s*t%s,c=le(a,Jf,s)*a%s,f=le(c,ki,s)*t%s,l=le(f,Tp,s)*f%s,u=le(l,e,s)*l%s,d=le(u,r,s)*u%s,p=le(d,n,s)*d%s,w=le(p,o,s)*p%s,x=le(w,o,s)*p%s,m=le(x,e,s)*l%s;return{pow_p_5_8:le(m,Jf,s)*t%s,b2:a}}function Mi(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var eu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Dp(t,e){let r=Oo,n=se(e*e*e,r),o=se(n*n*e,r),s=ru(t*o).pow_p_5_8,i=se(t*n*s,r),a=se(e*i*i,r),c=i,f=se(i*eu,r),l=a===t,u=a===se(-t,r),d=a===se(-t*eu,r);return l&&(i=c),(u||d)&&(i=f),Kf(i,r)&&(i=se(-i,r)),{isValid:l||u,value:i}}var mn=Gf(Bp,{uvRatio:Dp}),tu=mn.Fp;function Ip(t){let{y:e}=t;return tu.toBytes(tu.div(ki+e,ki-e))}function Rp(t){let e=mn.Fp.BYTES;return ke(t,e),Mi(Ti(t.subarray(0,e))).subarray(0,e)}function Op(t){return Yf(mn,Ti,Object.assign({adjustScalarBytes:Mi,toMontgomery:Ip,toMontgomerySecret:Rp,zip215:!0},t))}var nu=Op({});var gn=(()=>{let t=Oo,e=r=>{let{pow_p_5_8:n,b2:o}=ru(r);return se(le(n,_p,t)*o,t)};return Zf({P:t,type:"x25519",powPminus2:e,adjustScalarBytes:Mi,scalarMultBase:r=>{let n=se(r,mn.Fn.ORDER);if(n===Qf)return Qf;let o=mn.BASE.multiply(n);return se((o.Z+o.Y)*e(se(o.Z-o.Y,t)),t)}})})();var yn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Po=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ge={get(t=globalThis){let e=t.crypto;if(e?.subtle==null)throw new Po("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var No=32;var Fi,Pp=(async()=>{try{return await Ge.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Np(t,e,r){if(t.buffer instanceof ArrayBuffer){let n=await Ge.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await Ge.get().subtle.verify({name:"Ed25519"},n,Ce(e),Ce(r instanceof Uint8Array?r:r.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Up(t,e,r){return nu.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}async function ou(t,e,r){return Fi==null&&(Fi=await Pp),Fi?Np(t,e,r):Up(t,e,r)}function Uo(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var ko=class{type="Ed25519";raw;constructor(e){this.raw=Ki(e,No)}toMultihash(){return Ze.digest(Rt(this))}toCID(){return Ee.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ve(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();let o=ou(this.raw,r,e);return Uo(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Hi(t){return t=Ki(t,No),new ko(t)}function Ki(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new Z(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}var Mp=Math.pow(2,7),Fp=Math.pow(2,14),Kp=Math.pow(2,21),$i=Math.pow(2,28),zi=Math.pow(2,35),Vi=Math.pow(2,42),qi=Math.pow(2,49),ne=128,De=127;function de(t){if(t<Mp)return 1;if(t<Fp)return 2;if(t<Kp)return 3;if(t<$i)return 4;if(t<zi)return 5;if(t<Vi)return 6;if(t<qi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Rr(t,e,r=0){switch(de(t)){case 8:e[r++]=t&255|ne,t/=128;case 7:e[r++]=t&255|ne,t/=128;case 6:e[r++]=t&255|ne,t/=128;case 5:e[r++]=t&255|ne,t/=128;case 4:e[r++]=t&255|ne,t>>>=7;case 3:e[r++]=t&255|ne,t>>>=7;case 2:e[r++]=t&255|ne,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Hp(t,e,r=0){switch(de(t)){case 8:e.set(r++,t&255|ne),t/=128;case 7:e.set(r++,t&255|ne),t/=128;case 6:e.set(r++,t&255|ne),t/=128;case 5:e.set(r++,t&255|ne),t/=128;case 4:e.set(r++,t&255|ne),t>>>=7;case 3:e.set(r++,t&255|ne),t>>>=7;case 2:e.set(r++,t&255|ne),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function Wi(t,e){let r=t[e],n=0;if(n+=r&De,r<ne||(r=t[e+1],n+=(r&De)<<7,r<ne)||(r=t[e+2],n+=(r&De)<<14,r<ne)||(r=t[e+3],n+=(r&De)<<21,r<ne)||(r=t[e+4],n+=(r&De)*$i,r<ne)||(r=t[e+5],n+=(r&De)*zi,r<ne)||(r=t[e+6],n+=(r&De)*Vi,r<ne)||(r=t[e+7],n+=(r&De)*qi,r<ne))return n;throw new RangeError("Could not decode varint")}function $p(t,e){let r=t.get(e),n=0;if(n+=r&De,r<ne||(r=t.get(e+1),n+=(r&De)<<7,r<ne)||(r=t.get(e+2),n+=(r&De)<<14,r<ne)||(r=t.get(e+3),n+=(r&De)<<21,r<ne)||(r=t.get(e+4),n+=(r&De)*$i,r<ne)||(r=t.get(e+5),n+=(r&De)*zi,r<ne)||(r=t.get(e+6),n+=(r&De)*Vi,r<ne)||(r=t.get(e+7),n+=(r&De)*qi,r<ne))return n;throw new RangeError("Could not decode varint")}function Mo(t,e,r=0){return e==null&&(e=xe(de(t))),e instanceof Uint8Array?Rr(t,e,r):Hp(t,e,r)}function wt(t,e=0){return t instanceof Uint8Array?Wi(t,e):$p(t,e)}var ji=new Float32Array([-0]),$t=new Uint8Array(ji.buffer);function iu(t,e,r){ji[0]=t,e[r]=$t[0],e[r+1]=$t[1],e[r+2]=$t[2],e[r+3]=$t[3]}function au(t,e){return $t[0]=t[e],$t[1]=t[e+1],$t[2]=t[e+2],$t[3]=t[e+3],ji[0]}var Gi=new Float64Array([-0]),Ie=new Uint8Array(Gi.buffer);function cu(t,e,r){Gi[0]=t,e[r]=Ie[0],e[r+1]=Ie[1],e[r+2]=Ie[2],e[r+3]=Ie[3],e[r+4]=Ie[4],e[r+5]=Ie[5],e[r+6]=Ie[6],e[r+7]=Ie[7]}function fu(t,e){return Ie[0]=t[e],Ie[1]=t[e+1],Ie[2]=t[e+2],Ie[3]=t[e+3],Ie[4]=t[e+4],Ie[5]=t[e+5],Ie[6]=t[e+6],Ie[7]=t[e+7],Gi[0]}var zp=BigInt(Number.MAX_SAFE_INTEGER),Vp=BigInt(Number.MIN_SAFE_INTEGER),$e=class t{lo;hi;constructor(e,r){this.lo=e|0,this.hi=r|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return nr;if(e<zp&&e>Vp)return this.fromNumber(Number(e));let r=e<0n;r&&(e=-e);let n=e>>32n,o=e-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>uu&&(o=0n,++n>uu&&(n=0n))),new t(Number(o),Number(n))}static fromNumber(e){if(e===0)return nr;let r=e<0;r&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new t(n,o)}static from(e){return typeof e=="number"?t.fromNumber(e):typeof e=="bigint"?t.fromBigInt(e):typeof e=="string"?t.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new t(e.low>>>0,e.high>>>0):nr}},nr=new $e(0,0);nr.toBigInt=function(){return 0n};nr.zzEncode=nr.zzDecode=function(){return this};nr.length=function(){return 1};var uu=4294967296n;function lu(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:(r&64512)===55296&&(t.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function du(t,e,r){if(r-e<1)return"";let o,s=[],i=0,a;for(;e<r;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Yi(t,e,r){let n=r,o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[r++]=o:o<2048?(e[r++]=o>>6|192,e[r++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[r++]=o>>18|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128,e[r++]=o&63|128):(e[r++]=o>>12|224,e[r++]=o>>6&63|128,e[r++]=o&63|128);return r-n}function et(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function Fo(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}var Xi=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Ce(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,et(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw et(this,4);return Fo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw et(this,4);return Fo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw et(this,4);let e=au(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw et(this,4);let e=fu(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw et(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let e=this.bytes();return du(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw et(this,e);this.pos+=e}else do if(this.pos>=this.len)throw et(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new $e(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw et(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,e}if(this.len-this.pos>4){for(;r<5;++r)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;r<5;++r){if(this.pos>=this.len)throw et(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw et(this,8);let e=Fo(this.buf,this.pos+=4),r=Fo(this.buf,this.pos+=4);return new $e(e,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Wi(this.buf,this.pos);return this.pos+=de(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function wn(t){return new Xi(t instanceof Uint8Array?t:t.subarray())}function tt(t,e,r){let n=wn(t);return e.decode(n,void 0,r)}function Zi(t){let e=t??8192,r=e>>>1,n,o=e;return function(i){if(i<1||i>r)return xe(i);o+i>e&&(n=xe(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var or=class{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}};function Qi(){}var ea=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},qp=Zi();function Wp(t){return globalThis.Buffer!=null?xe(t):qp(t)}var En=class{len;head;tail;states;constructor(){this.len=0,this.head=new or(Qi,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new or(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new ta((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Ko,10,$e.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let r=$e.fromBigInt(e);return this._push(Ko,r.length(),r)}uint64Number(e){return this._push(Rr,de(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let r=$e.fromBigInt(e).zzEncode();return this._push(Ko,r.length(),r)}sint64Number(e){let r=$e.fromNumber(e).zzEncode();return this._push(Ko,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Ji,1,e?1:0)}fixed32(e){return this._push(xn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let r=$e.fromBigInt(e);return this._push(xn,4,r.lo)._push(xn,4,r.hi)}fixed64Number(e){let r=$e.fromNumber(e);return this._push(xn,4,r.lo)._push(xn,4,r.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(iu,4,e)}double(e){return this._push(cu,8,e)}bytes(e){let r=e.length>>>0;return r===0?this._push(Ji,1,0):this.uint32(r)._push(Gp,r,e)}string(e){let r=lu(e);return r!==0?this.uint32(r)._push(Yi,r,e):this._push(Ji,1,0)}fork(){return this.states=new ea(this),this.head=this.tail=new or(Qi,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new or(Qi,0,0),this.len=0),this}ldelim(){let e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=r,this.len+=n),this}finish(){let e=this.head.next,r=Wp(this.len),n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}};function Ji(t,e,r){e[r]=t&255}function jp(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}var ta=class extends or{next;constructor(e,r){super(jp,e,r),this.next=void 0}};function Ko(t,e,r){for(;t.hi!==0;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}function xn(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function Gp(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(En.prototype.bytes=function(t){let e=t.length>>>0;return this.uint32(e),e>0&&this._push(Yp,e,t),this},En.prototype.string=function(t){let e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(Xp,e,t),this});function Yp(t,e,r){e.set(t,r)}function Xp(t,e,r){t.length<40?Yi(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(Q(t),r)}function ra(){return new En}function rt(t,e){let r=ra();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}function*nt(t,e,r){let n=wn(t);yield*e.stream(n,void 0,".",r)}var Ho={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function $o(t,e,r,n,o){return{name:t,type:e,encode:r,decode:n,stream:o}}function sr(t){function e(s){if(t[s.toString()]==null)throw new Error("Invalid enum value");return t[s]}let r=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i,a){};return $o("enum",Ho.VARINT,r,n,o)}function ot(t,e,r){return $o("message",Ho.LENGTH_DELIMITED,t,e,r)}var ir=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var pe;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(pe||(pe={}));var na;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(na||(na={}));(function(t){t.codec=()=>sr(na)})(pe||(pe={}));var ht;(function(t){let e;t.codec=()=>(e==null&&(e=ot((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),pe.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=pe.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:pe.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function r(s){return rt(s,t.codec())}t.encode=r;function n(s,i){return tt(s,t.codec(),i)}t.decode=n;function o(s,i){return nt(s,t.codec(),i)}t.stream=o})(ht||(ht={}));var oa;(function(t){let e;t.codec=()=>(e==null&&(e=ot((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),pe.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=pe.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:pe.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function r(s){return rt(s,t.codec())}t.encode=r;function n(s,i){return tt(s,t.codec(),i)}t.decode=n;function o(s,i){return nt(s,t.codec(),i)}t.stream=o})(oa||(oa={}));var An={};Pe(An,{MAX_RSA_KEY_SIZE:()=>sa,generateRSAKeyPair:()=>bu,jwkToJWKKeyPair:()=>wu,jwkToPkcs1:()=>em,jwkToPkix:()=>fa,jwkToRSAPrivateKey:()=>ha,pkcs1MessageToJwk:()=>aa,pkcs1MessageToRSAPrivateKey:()=>ua,pkcs1ToJwk:()=>Jp,pkcs1ToRSAPrivateKey:()=>yu,pkixMessageToJwk:()=>ca,pkixMessageToRSAPublicKey:()=>da,pkixToJwk:()=>tm,pkixToRSAPublicKey:()=>la});var Or=class{type="RSA";jwk;_raw;_multihash;constructor(e,r){this.jwk=e,this._multihash=r}get raw(){return this._raw==null&&(this._raw=An.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Ee.createV1(114,this._multihash)}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ve(this.raw,e.raw)}verify(e,r,n){return gu(this.jwk,r,e,n)}},Sn=class{type="RSA";jwk;_raw;publicKey;constructor(e,r){this.jwk=e,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=An.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ve(this.raw,e.raw)}sign(e,r){return mu(this.jwk,e,r)}};var sa=8192,ia=18,Zp=1062,Qp=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Jp(t){let e=gt(t);return aa(e)}function aa(t){return{n:j(t[1],"base64url"),e:j(t[2],"base64url"),d:j(t[3],"base64url"),p:j(t[4],"base64url"),q:j(t[5],"base64url"),dp:j(t[6],"base64url"),dq:j(t[7],"base64url"),qi:j(t[8],"base64url"),kty:"RSA"}}function em(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 Z("JWK was missing components");return It([Fe(Uint8Array.from([0])),Fe(Q(t.n,"base64url")),Fe(Q(t.e,"base64url")),Fe(Q(t.d,"base64url")),Fe(Q(t.p,"base64url")),Fe(Q(t.q,"base64url")),Fe(Q(t.dp,"base64url")),Fe(Q(t.dq,"base64url")),Fe(Q(t.qi,"base64url"))]).subarray()}function tm(t){let e=gt(t,{offset:0});return ca(e)}function ca(t){let e=gt(t[1],{offset:0});return{kty:"RSA",n:j(e[0],"base64url"),e:j(e[1],"base64url")}}function fa(t){if(t.n==null||t.e==null)throw new Z("JWK was missing components");return It([Qp,uo(It([Fe(Q(t.n,"base64url")),Fe(Q(t.e,"base64url"))]))]).subarray()}function yu(t){let e=gt(t);return ua(e)}function ua(t){let e=aa(t);return ha(e)}function la(t,e){if(t.byteLength>=Zp)throw new gr("Key size is too large");let r=gt(t,{offset:0});return da(r,t,e)}function da(t,e,r){let n=ca(t);if(r==null){let o=ft(ht.encode({Type:pe.RSA,Data:e}));r=Ne(ia,o)}return new Or(n,r)}function ha(t){if(Eu(t)>sa)throw new Z("Key size is too large");let e=wu(t),r=ft(ht.encode({Type:pe.RSA,Data:fa(e.publicKey)})),n=Ne(ia,r);return new Sn(e.privateKey,new Or(e.publicKey,n))}async function bu(t){if(t>sa)throw new Z("Key size is too large");let e=await xu(t),r=ft(ht.encode({Type:pe.RSA,Data:fa(e.publicKey)})),n=Ne(ia,r);return new Sn(e.privateKey,new Or(e.publicKey,n))}function wu(t){if(t==null)throw new Z("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function xu(t,e){let r=await Ge.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await rm(r,e);return{privateKey:n[0],publicKey:n[1]}}async function mu(t,e,r){let n=await Ge.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let o=await Ge.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Ce(e instanceof Uint8Array?e:e.subarray()));return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function gu(t,e,r,n){let o=await Ge.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ge.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,Ce(e),Ce(r instanceof Uint8Array?r:r.subarray()));return n?.signal?.throwIfAborted(),s}async function rm(t,e){if(t.privateKey==null||t.publicKey==null)throw new Z("Private and public key are required");let r=await Promise.all([Ge.get().subtle.exportKey("jwk",t.privateKey),Ge.get().subtle.exportKey("jwk",t.publicKey)]);return e?.signal?.throwIfAborted(),r}function Eu(t){if(t.kty!=="RSA")throw new Z("invalid key type");if(t.n==null)throw new Z("invalid key modulus");return Q(t.n,"base64url").length*8}var zo=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(er(e),ke(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),qe(o)}update(e){return Cr(this),this.iHash.update(e),this}digestInto(e){Cr(this),po(e,this),this.finished=!0;let r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},vn=(()=>{let t=((e,r,n)=>new zo(e,r).update(n).digest());return t.create=(e,r)=>new zo(e,r),t})();var nm=BigInt(0),pa=class extends Error{constructor(e=""){super(e)}},xt={Err:pa,_tlv:{encode:(t,e)=>{let{Err:r}=xt;if(bt(t,"tag"),t<0||t>255)throw new r("tlv.encode: wrong tag");if(Tf(e,"data"),e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,o=un(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?un(o.length/2|128):"";return un(t)+s+o+e},decode(t,e){let{Err:r}=xt;e=J(e,void 0,"DER data");let n=0;if(t<0||t>255)throw new r("tlv.decode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let f=e.subarray(n,n+c);if(f.length!==c)throw new r("tlv.decode: length bytes not complete");if(f[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let l of f)i=i<<8|l;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(t){let{Err:e}=xt;if(xo(t),t<nm)throw new e("integer: negative integers are not allowed");let r=un(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=xt;if(t.length<1)throw new e("invalid signature integer: empty");if(t[0]&128)throw new e("invalid signature integer: negative");if(t.length>1&&t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return ut(t)}},toSig(t,e){let{Err:r,_int:n,_tlv:o}=xt;if(e!==void 0&&(bt(e,"maxScalarBytes"),e<1))throw new r("invalid signature: maxScalarBytes must be positive");let s=J(t,void 0,"signature"),{v:i,l:a}=o.decode(48,s);if(a.length)throw new r("invalid signature: left bytes after parsing");let{v:c,l:f}=o.decode(2,i),{v:l,l:u}=o.decode(2,f);if(u.length)throw new r("invalid signature: left bytes after parsing");if(e!==void 0&&(c.length>e||l.length>e))throw new r("invalid signature: integer too large");return{r:n.decode(c),s:n.decode(l)}},hexFromSig(t){let{_tlv:e,_int:r}=xt;Be(t,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),s=n+o;return e.encode(48,s)}},Vo=(Object.freeze(xt._tlv),Object.freeze(xt._int),Object.freeze(xt));var Su=(t,e)=>(t+(t>=0?e:-e)/Au)/e;function om(t,e,r){dt("scalar",t,Et,r);let[[n,o],[s,i]]=e,a=Su(i*t,r),c=Su(-o*t,r),f=t-a*n-c*s,l=-a*o-c*i,u=f<Et,d=l<Et;u&&(f=-f),d&&(l=-l);let p=dn(Math.ceil(Tr(r)/2))+ar;if(f<Et||f>=p||l<Et||l>=p)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:u,k1:f,k2neg:d,k2:l}}function ya(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function ma(t,e){Be(t);let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Ke(r.lowS,"lowS"),Ke(r.prehash,"prehash"),r.format!==void 0&&ya(r.format),r}var Et=BigInt(0),ar=BigInt(1),Au=BigInt(2),ga=BigInt(3),sm=BigInt(4);function vu(t,e={}){let r=Lo("weierstrass",t,e),n=r.Fp,o=r.Fn,s=r.CURVE,{h:i,n:a}=s;Be(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:f,clearCofactor:l,isTorsionFree:u,fromBytes:d,toBytes:p}=e,w=e.randomBytes===void 0?yt:e.randomBytes;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let x=c?{beta:c.beta,basises:c.basises.map(S=>[...S])}:void 0,m=_u(n,o);function y(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function E(S,h,g){if(h.is0()){if(!f)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:A,y:P}=h.toAffine(),k=n.toBytes(A);if(Ke(g,"isCompressed"),g){y();let M=!n.isOdd(P);return We(Cu(M),k)}else return We(Uint8Array.of(4),k,n.toBytes(P))}function b(S){J(S,void 0,"Point");let{publicKey:h,publicKeyUncompressed:g}=m,A=S.length,P=S[0],k=S.subarray(1);if(f&&A===1&&P===0)return{x:n.ZERO,y:n.ZERO};if(A===h&&(P===2||P===3)){let M=n.fromBytes(k);if(!n.isValid(M))throw new Error("bad point: is not on curve, wrong x");let $=N(M),z;try{z=n.sqrt($)}catch(ue){let ie=ue instanceof Error?": "+ue.message:"";throw new Error("bad point: is not on curve, sqrt error"+ie)}y();let W=n.isOdd(z);return(P&1)===1!==W&&(z=n.neg(z)),{x:M,y:z}}else if(A===g&&P===4){let M=n.BYTES,$=n.fromBytes(k.subarray(0,M)),z=n.fromBytes(k.subarray(M,M*2));if(!B($,z))throw new Error("bad point: is not on curve");return{x:$,y:z}}else throw new Error(`bad point: got length ${A}, expected compressed=${h} or uncompressed=${g}`)}let L=p===void 0?E:p,C=d===void 0?b:d,O=n.mul(s.b,ga),R=n.is0(s.a)?S=>n.ZERO:S=>n.mul(s.a,S);function N(S){let h=n.sqr(S),g=n.mul(h,S);return n.add(n.add(g,n.mul(S,s.a)),s.b)}function B(S,h){let g=n.sqr(h),A=N(S);return n.eql(g,A)}if(!B(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let I=n.mul(n.pow(s.a,ga),sm),K=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(I,K)))throw new Error("bad curve params: a or b");function F(S,h,g=!1){if(!n.isValid(h)||g&&n.is0(h))throw new Error(`bad point coordinate ${S}`);return typeof h=="object"&&h!==null?n.create(h):h}function V(S){if(!(S instanceof v))throw new Error("Weierstrass Point expected")}function _(S){if(!x||!x.basises)throw new Error("no endo");return om(S,x.basises,o.ORDER)}function U(S,h,g,A){if(!o.isValid(A))throw new RangeError("invalid scalar: out of range");if(x){let{k1neg:P,k1:k,k2neg:M,k2:$}=_(A),z=new v(n.mul(g.X,x.beta),g.Y,g.Z);S.push(P?g.negate():g,M?z.negate():z),h.push(k,$)}else S.push(g),h.push(A)}let T=new WeakSet;class v{static BASE=new v(s.Gx,s.Gy,n.ONE);static ZERO=new v(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(h,g,A){this.X=F("x",h),this.Y=F("y",g,!0),this.Z=F("z",A),Object.freeze(this)}static CURVE(){return s}static fromAffine(h){let{x:g,y:A}=h||{};if(!h||!n.isValid(g)||!n.isValid(A))throw new Error("invalid affine point");if(h instanceof v)throw new Error("projective point not allowed");return n.is0(g)&&n.is0(A)?v.ZERO:new v(g,A,n.ONE)}static fromBytes(h){let g=v.fromAffine(C(J(h,void 0,"point")));return g.assertValidity(),g}static fromHex(h){return v.fromBytes(_r(h))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=6,g=!0){return D.setWindowSize(this,h),g||this.multiply(ga),this}assertValidity(){let h=this;if(h.is0()){if(f&&n.is0(h.X)&&n.eql(h.Y,n.ONE)&&n.is0(h.Z))return;throw new Error("bad point: ZERO")}if(T.has(h))return;let{x:g,y:A}=h.toAffine();if(!n.isValid(g)||!n.isValid(A))throw new Error("bad point: x or y not field elements");if(!B(g,A))throw new Error("bad point: equation left != right");if(!h.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");T.add(h)}hasEvenY(){let{y:h}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(h)}equals(h){V(h);let{X:g,Y:A,Z:P}=this,{X:k,Y:M,Z:$}=h,z=n.eql(n.mul(g,$),n.mul(k,P)),W=n.eql(n.mul(A,$),n.mul(M,P));return z&&W}negate(){return new v(this.X,n.neg(this.Y),this.Z)}double(){let{X:h,Y:g,Z:A}=this,P=n.ZERO,k=n.ZERO,M=n.ZERO,$=n.mul(h,h),z=n.mul(g,g),W=n.mul(A,A),G=n.mul(h,g);return G=n.add(G,G),M=n.mul(h,A),M=n.add(M,M),P=R(M),k=n.mul(O,W),k=n.add(P,k),P=n.sub(z,k),k=n.add(z,k),k=n.mul(P,k),P=n.mul(G,P),M=n.mul(O,M),W=R(W),G=n.sub($,W),G=R(G),G=n.add(G,M),M=n.add($,$),$=n.add(M,$),$=n.add($,W),$=n.mul($,G),k=n.add(k,$),W=n.mul(g,A),W=n.add(W,W),$=n.mul(W,G),P=n.sub(P,$),M=n.mul(W,z),M=n.add(M,M),M=n.add(M,M),new v(P,k,M)}add(h){V(h);let{X:g,Y:A,Z:P}=this,{X:k,Y:M,Z:$}=h,z=n.ZERO,W=n.ZERO,G=n.ZERO,ue=n.mul(g,k),ie=n.mul(A,M),ye=n.mul(P,$),Me=n.add(g,A),fe=n.add(k,M);Me=n.mul(Me,fe),fe=n.add(ue,ie),Me=n.sub(Me,fe),fe=n.add(g,P);let he=n.add(k,$);return fe=n.mul(fe,he),he=n.add(ue,ye),fe=n.sub(fe,he),he=n.add(A,P),z=n.add(M,$),he=n.mul(he,z),z=n.add(ie,ye),he=n.sub(he,z),G=R(fe),z=n.mul(O,ye),G=n.add(z,G),z=n.sub(ie,G),G=n.add(ie,G),W=n.mul(z,G),ie=n.add(ue,ue),ie=n.add(ie,ue),ye=R(ye),fe=n.mul(O,fe),ie=n.add(ie,ye),ye=n.sub(ue,ye),ye=R(ye),fe=n.add(fe,ye),ue=n.mul(ie,fe),W=n.add(W,ue),ue=n.mul(he,fe),z=n.mul(Me,z),z=n.sub(z,ue),ue=n.mul(Me,ie),G=n.mul(he,G),G=n.add(G,ue),new v(z,W,G)}subtract(h){return V(h),this.add(h.negate())}is0(){return this.equals(v.ZERO)}multiply(h){if(!o.isValidNot0(h))throw new RangeError("invalid scalar: out of range");let{p:g,f:A}=D.mulSecret(this,h,i,H);return H([g,A])[0]}multiplyUnsafe(h){let g=this,A=h;if(!o.isValid(A))throw new RangeError("invalid scalar: out of range");if(A===Et||g.is0())return v.ZERO;if(A===ar)return g;if(D.hasWindowSize(this))return D.mulUnsafe(g,A,H);let P=[],k=[];return U(P,k,g,A),To(v,P,k)}mulAddUnsafe(h,g,A){V(g);let P=[],k=[];return U(P,k,this,h),U(P,k,g,A),To(v,P,k)}toAffine(h){let g=this,A=h;if(A!=null&&!n.isValid(A))throw new RangeError('"invertedZ" expected valid field element');let{X:P,Y:k,Z:M}=g;if(n.eql(M,n.ONE))return{x:P,y:k};let $=g.is0();A==null&&(A=$?n.ONE:n.inv(M));let z=n.mul(P,A),W=n.mul(k,A),G=n.mul(M,A);if($)return{x:n.ZERO,y:n.ZERO};if(!n.eql(G,n.ONE))throw new Error("invZ was invalid");return{x:z,y:W}}isTorsionFree(){return i===ar?!0:u?u(v,this):D.mulUnsafe(this,a).is0()}clearCofactor(){return i===ar?this:l?l(v,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===ar?this.is0():this.clearCofactor().is0()}toBytes(h=!0){return Ke(h,"isCompressed"),this.assertValidity(),L(v,this,h)}toHex(h=!0){return fn(this.toBytes(h))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let H=S=>_o(v,S),D=new Dr(v,w);return D.bits>=6&&v.BASE.precompute(6),Object.freeze(v.prototype),Object.freeze(v),v}function Cu(t){return Uint8Array.of(t?2:3)}function _u(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function im(t,e={}){Ht(t);let{Fn:r}=t,n=e.randomBytes===void 0?yt:e.randomBytes,o=Object.assign(_u(t.Fp,r),{seed:Math.max(vo(r.ORDER),16)});function s(p){try{let w=r.fromBytes(p);return r.isValidNot0(w)}catch{return!1}}function i(p,w){let{publicKey:x,publicKeyUncompressed:m}=o;try{let y=p.length;return w===!0&&y!==x||w===!1&&y!==m?!1:!t.fromBytes(p).is0()}catch{return!1}}function a(p){return p=p===void 0?n(o.seed):p,Co(J(p,o.seed,"seed"),r.ORDER)}function c(p,w=!0){return t.BASE.multiply(r.fromBytes(p)).toBytes(w)}function f(p){let{secretKey:w,publicKey:x,publicKeyUncompressed:m}=o,y=r._lengths;if(!Mt(p))return;let E=J(p,void 0,"key").length,b=E===x||E===m,L=E===w||!!y?.includes(E);if(!(b&&L))return b}function l(p,w,x=!0){if(f(p)===!0)throw new Error("first arg must be private key");if(f(w)===!1)throw new Error("second arg must be public key");let m=r.fromBytes(p),y=t.fromBytes(w);if(y.is0())throw new Error("invalid public key: point at infinity");return y.multiply(m).toBytes(x)}let u={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=Ir(a,c);return Object.freeze(u),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:d,Point:t,utils:u,lengths:o})}function Tu(t,e,r={}){Ht(t);let n=e;er(n),Be(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},r),s=o.randomBytes===void 0?yt:o.randomBytes,i=o.hmac===void 0?(S,h)=>vn(n,S,h):o.hmac,{Fp:a,Fn:c}=t,{ORDER:f,BITS:l}=c,u=vo(f),d=Ui(s,u),{keygen:p,getPublicKey:w,getSharedSecret:x,utils:m,lengths:y}=im(t,o),E={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},b=f*Au+ar<a.ORDER;function L(S){let h=f>>ar;return S>h}function C(S,h){if(!c.isValidNot0(h))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return h}function O(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function R(S,h,g){return O(),(S===g?0:2)|Number(a.isOdd(h))}function N(){if(b)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(S,h){ya(h);let g=y.signature,A=h==="compact"?g:h==="recovered"?g+1:void 0;return J(S,A)}class I{r;s;recovery;constructor(h,g,A){if(this.r=C("r",h),this.s=C("s",g),A!=null){if(N(),![0,1,2,3].includes(A))throw new Error("invalid recovery id");this.recovery=A}Object.freeze(this)}static fromBytes(h,g=E.format){B(h,g);let A;if(g==="der"){if(h.length>2*c.BYTES+16)throw new Vo.Err("invalid signature: DER signature too long");let{r:$,s:z}=Vo.toSig(J(h),c.BYTES+1);return new I($,z)}g==="recovered"&&(A=h[0],g="compact",h=h.subarray(1));let P=y.signature/2,k=h.subarray(0,P),M=h.subarray(P,P*2);return new I(c.fromBytes(k),c.fromBytes(M),A)}static fromHex(h,g){return this.fromBytes(_r(h),g)}assertRecovery(){let{recovery:h}=this;if(h==null)throw new Error("invalid recovery id: must be present");return h}addRecoveryBit(h){return new I(this.r,this.s,h)}recoverPublicKey(h){let{r:g,s:A}=this,P=this.assertRecovery(),k=P===2||P===3?g+f:g;if(!a.isValid(k))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let M=a.toBytes(k),$=t.fromBytes(We(Cu((P&1)===0),M)),z=c.inv(k),W=F(J(h,void 0,"msgHash")),G=c.create(-W*z),ue=c.create(A*z),ie=t.BASE.mulAddUnsafe(G,$,ue);if(ie.is0())throw new Error("invalid recovery: point at infinify");return ie.assertValidity(),ie}hasHighS(){return L(this.s)}toBytes(h=E.format){if(ya(h),h==="der")return _r(Vo.hexFromSig(this));let{r:g,s:A}=this,P=c.toBytes(g),k=c.toBytes(A);return h==="recovered"?(N(),We(Uint8Array.of(this.assertRecovery()),P,k)):We(P,k)}toHex(h){return fn(this.toBytes(h))}}Object.freeze(I.prototype),Object.freeze(I);let K=o.bits2int===void 0?function(h){if(h.length>8192)throw new Error("input is too large");let g=ut(h),A=h.length*8-l;return A>0?g>>BigInt(A):g}:o.bits2int,F=o.bits2int_modN===void 0?function(h){return c.create(K(h))}:o.bits2int_modN,V=dn(l);function _(S){return dt("num < 2^"+l,S,Et,V),c.toBytes(S)}function U(S,h){return J(S,void 0,"message"),h?J(n(S),void 0,"prehashed message"):S}function T(S,h,g){let{lowS:A,prehash:P,extraEntropy:k}=ma(g,E);S=U(S,P);let M=F(S),$=c.fromBytes(h);if(!c.isValidNot0($))throw new Error("invalid private key");let z=[_($),_(M)];if(k!=null&&k!==!1){let ie=k===!0?s(y.secretKey):k;z.push(J(ie,void 0,"extraEntropy"))}let W=We(...z),G=M;function ue(ie){let ye=K(ie);if(!c.isValidNot0(ye))return;let Me=t.BASE.multiply(ye).toAffine(),fe=c.create(Me.x);if(fe===Et)return;let he;if(d!==void 0){let Tt=ut(Co(d(u),f)),ld=c.inv(c.mul(Tt,ye)),dd=c.mul(Tt,G),hd=c.mul(Tt,$);he=c.create(ld*c.create(dd+hd*fe))}else{let Tt=kf(ye,f);he=c.create(Tt*c.create(G+fe*$))}if(he===Et)return;let mr=R(Me.x,Me.y,fe),Zr=he;return A&&L(he)&&(Zr=c.neg(he),mr^=1),new I(fe,Zr,b?void 0:mr)}return{seed:W,k2sig:ue}}function v(S,h,g={}){let{seed:A,k2sig:P}=T(S,h,g);return Bf(n.outputLen,c.BYTES,i)(A,P).toBytes(g.format)}function H(S,h,g,A={}){let{lowS:P,prehash:k,format:M}=ma(A,E);if(g=J(g,void 0,"publicKey"),h=U(h,k),!Mt(S)){let $=S instanceof I?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+$)}B(S,M);try{let $=I.fromBytes(S,M),z=t.fromBytes(g);if(z.is0()||P&&$.hasHighS())return!1;let{r:W,s:G}=$,ue=F(h),ie=c.inv(G),ye=c.create(ue*ie),Me=c.create(W*ie),fe=t.BASE.mulAddUnsafe(ye,z,Me);if(fe.is0())return!1;let he=fe.toAffine();return!(c.create(he.x)!==W||M==="recovered"&&$.recovery!==R(he.x,he.y,W))}catch{return!1}}function D(S,h,g={}){let{prehash:A}=ma(g,E);return h=U(h,A),I.fromBytes(S,"recovered").recoverPublicKey(h).toBytes()}return Object.freeze({keygen:p,getPublicKey:w,getSharedSecret:x,utils:m,lengths:y,Point:t,sign:v,verify:H,recoverPublicKey:D,Signature:I,hash:n})}var wa={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},am={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Lu=BigInt(2);function cm(t){let e=wa.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=t*t*t%e,l=f*f*t%e,u=le(l,r,e)*l%e,d=le(u,r,e)*l%e,p=le(d,Lu,e)*f%e,w=le(p,o,e)*p%e,x=le(w,s,e)*w%e,m=le(x,a,e)*x%e,y=le(m,c,e)*m%e,E=le(y,a,e)*x%e,b=le(E,r,e)*l%e,L=le(b,i,e)*w%e,C=le(L,n,e)*f%e,O=le(C,Lu,e);if(!ba.eql(ba.sqr(O),t))throw new Error("Cannot find square root");return O}var ba=Br(wa.p,{sqrt:cm}),fm=vu(wa,{Fp:ba,endo:am}),Pr=Tu(fm,ft);function Bu(t,e,r,n){let o=mt.digest(r instanceof Uint8Array?r:r.subarray());if(Uo(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Pr.verify(e,s,t,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new yn(String(s))});try{return n?.signal?.throwIfAborted(),Pr.verify(e,o.digest,t,{prehash:!1,format:"der"})}catch(s){throw new yn(String(s))}}var qo=class{type="secp256k1";raw;_key;constructor(e){this._key=Iu(e),this.raw=Du(this._key)}toMultihash(){return Ze.digest(Rt(this))}toCID(){return Ee.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ve(this.raw,e.raw)}verify(e,r,n){return Bu(this._key,r,e,n)}};function xa(t){return new qo(t)}function Du(t){return Pr.Point.fromBytes(t).toBytes()}function Iu(t){try{return Pr.Point.fromBytes(t),t}catch(e){throw new gr(String(e))}}function Cn(t,e){let{Type:r,Data:n}=ht.decode(t),o=n??new Uint8Array;switch(r){case pe.RSA:return la(o,e);case pe.Ed25519:return Hi(o);case pe.secp256k1:return xa(o);case pe.ECDSA:return gi(o);default:throw new Gt}}function Ru(t){let{Type:e,Data:r}=ht.decode(t.digest),n=r??new Uint8Array;switch(e){case pe.Ed25519:return Hi(n);case pe.secp256k1:return xa(n);case pe.ECDSA:return gi(n);default:throw new Gt}}function Rt(t){return ht.encode({Type:pe[t.type],Data:t.raw})}var Ou=Symbol.for("nodejs.util.inspect.custom"),um=114,_n=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ks]=!0;toString(){return this.string==null&&(this.string=ge.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Ee.createV1(um,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ve(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ve(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Ou](){return`PeerId(${this.toString()})`}},Tn=class extends _n{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Ln=class extends _n{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Bn=class extends _n{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},lm=2336,Dn=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ze.digest(Q(this.url))}[Ou](){return`PeerId(${this.url})`}[Ks]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Ee.createV1(lm,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=j(e)),e.toString()===this.toString())}};var dm=114,Pu=2336;function Nr(t,e){let r;if(t.charAt(0)==="1"||t.charAt(0)==="Q")r=Ar(ge.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return hm(Ee.parse(t));if(e==null)throw new Z('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=Ar(e.decode(t))}return Nu(r)}function In(t){if(t.type==="Ed25519")return new Ln({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new Bn({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new Tn({multihash:t.toCID().multihash,publicKey:t});throw new Gt}function Nu(t){if(mm(t))return new Tn({multihash:t});if(pm(t))try{let e=Ru(t);if(e.type==="Ed25519")return new Ln({multihash:t,publicKey:e});if(e.type==="secp256k1")return new Bn({multihash:t,publicKey:e})}catch{let r=j(t.digest);return new Dn(new URL(r))}throw new to("Supplied PeerID Multihash is invalid")}function hm(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==dm&&t.code!==Pu)throw new eo("Supplied PeerID CID is invalid");if(t.code===Pu){let e=j(t.multihash.digest);return new Dn(new URL(e))}return Nu(t.multihash)}function pm(t){return t.code===Ze.code}function mm(t){return t.code===mt.code}var _e=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},St=class extends Error{static name="ValidationError";name="ValidationError"},Wo=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},jo=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Go=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,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let d=Number.parseInt(u,e);if(!Number.isNaN(d))return d});if(l===void 0)break;if(s*=e,s+=l,s>f||(i+=1,r!==void 0&&i>r))return}if(i!==0)return!n&&c&&i>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 o=n*2;if(n<r.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return r[o]=i[0],r[o+1]=i[1],r[o+2]=i[2],r[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];r[o]=s>>8,r[o+1]=s&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,o]=e(r);if(n===16)return r;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var gm=45,ym=15,Yo=new Go;function Uu(t){if(!(t.length>ym))return Yo.new(t).parseWith(()=>Yo.readIPv4Addr())}function ku(t){if(t.includes("%")&&(t=t.split("%")[0]),!(t.length>gm))return Yo.new(t).parseWith(()=>Yo.readIPv6Addr())}function Xo(t){return!!Uu(t)}function Mu(t){return!!ku(t)}function Sa(t){return e=>j(e,t)}function Aa(t){return e=>Q(e,t)}function Ur(t){return new DataView(t.buffer).getUint16(t.byteOffset).toString()}function cr(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof t=="string"?parseInt(t):t),new Uint8Array(e)}function Fu(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=Q(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=cr(n);return Ue([r,o],r.length+o.length)}function Ku(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=Dt.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 o=cr(n);return Ue([r,o],r.length+o.length)}function va(t){let e=t.subarray(0,t.length-2),r=t.subarray(t.length-2),n=j(e,"base32"),o=Ur(r);return`${n}:${o}`}var Ca=function(t){t=t.toString().trim();let e=new Uint8Array(4);return t.split(/\./g).forEach((r,n)=>{let o=parseInt(r,10);if(isNaN(o)||o<0||o>255)throw new _e("Invalid byte value in IP address");e[n]=o}),e},Hu=function(t){let e=0;t=t.toString().trim();let r=t.split(":",8),n;for(n=0;n<r.length;n++){let s=Xo(r[n]),i;s&&(i=Ca(r[n]),r[n]=j(i.subarray(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,j(i.subarray(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 o=new Uint8Array(e+16);for(n=0;n<r.length;n++){r[n]===""&&(r[n]="0");let s=parseInt(r[n],16);if(isNaN(s)||s<0||s>65535)throw new _e("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},$u=function(t){if(t.byteLength!==4)throw new _e("IPv4 address was incorrect length");let e=[];for(let r=0;r<t.byteLength;r++)e.push(t[r]);return e.join(".")},zu=function(t){if(t.byteLength!==16)throw new _e("IPv6 address was incorrect length");let e=[];for(let n=0;n<t.byteLength;n+=2){let o=t[n],s=t[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let r=e.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new _e(`Invalid IPv6 address "${r}"`)}};function Vu(t){try{let e=new URL(`http://[${t}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new _e(`Invalid IPv6 address "${t}"`)}}var Ea=Object.values(Zt).map(t=>t.decoder),bm=(function(){let t=Ea[0].or(Ea[1]);return Ea.slice(2).forEach(e=>t=t.or(e)),t})();function qu(t){return bm.decode(t)}function Wu(t){return e=>t.encoder.encode(e)}function wm(t){if(parseInt(t).toString()!==t)throw new St("Value must be an integer")}function xm(t){if(t<0)throw new St("Value must be a positive integer, or zero")}function Em(t){return e=>{if(e>t)throw new St(`Value must be smaller than or equal to ${t}`)}}function Sm(...t){return e=>{for(let r of t)r(e)}}var Rn=Sm(wm,xm,Em(65535));var Ae=-1,_a=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let r;if(typeof e=="string"?r=this.protocolsByName.get(e):r=this.protocolsByCode.get(e),r==null)throw new jo(`Protocol ${e} was unknown`);return r}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(r=>{this.protocolsByName.set(r,e)})}removeProtocol(e){let r=this.protocolsByCode.get(e);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},vt=new _a,Um=[{code:4,name:"ip4",size:32,valueToBytes:Ca,bytesToValue:$u,validate:t=>{if(!Xo(t))throw new St(`Invalid IPv4 address "${t}"`)}},{code:6,name:"tcp",size:16,valueToBytes:cr,bytesToValue:Ur,validate:Rn},{code:273,name:"udp",size:16,valueToBytes:cr,bytesToValue:Ur,validate:Rn},{code:33,name:"dccp",size:16,valueToBytes:cr,bytesToValue:Ur,validate:Rn},{code:41,name:"ip6",size:128,valueToBytes:Hu,bytesToValue:zu,stringToValue:Vu,validate:t=>{if(!Mu(t))throw new St(`Invalid IPv6 address "${t}"`)}},{code:42,name:"ip6zone",size:Ae},{code:43,name:"ipcidr",size:8,bytesToValue:Sa("base10"),valueToBytes:Aa("base10")},{code:53,name:"dns",size:Ae},{code:54,name:"dns4",size:Ae},{code:55,name:"dns6",size:Ae},{code:56,name:"dnsaddr",size:Ae},{code:132,name:"sctp",size:16,valueToBytes:cr,bytesToValue:Ur,validate:Rn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Ae,stringToValue:t=>decodeURIComponent(t),valueToString:t=>encodeURIComponent(t)},{code:421,name:"p2p",aliases:["ipfs"],size:Ae,bytesToValue:Sa("base58btc"),valueToBytes:t=>t.startsWith("Q")||t.startsWith("1")?Aa("base58btc")(t):Ee.parse(t).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:va,valueToBytes:Fu},{code:445,name:"onion3",size:296,bytesToValue:va,valueToBytes:Ku},{code:446,name:"garlic64",size:Ae},{code:447,name:"garlic32",size:Ae},{code:448,name:"tls"},{code:449,name:"sni",size:Ae},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Ae,bytesToValue:Wu(rn),valueToBytes:qu},{code:480,name:"http"},{code:481,name:"http-path",size:Ae,stringToValue:t=>`/${decodeURIComponent(t)}`,valueToString:t=>encodeURIComponent(t.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:Ae}];Um.forEach(t=>{vt.addProtocol(t)});function ju(t){let e=[],r=0;for(;r<t.length;){let n=wt(t,r),o=vt.getProtocol(n),s=de(n),i=km(o,t,r+s),a=0;i>0&&o.size===Ae&&(a=de(i));let c=s+a+i,f={code:n,name:o.name,bytes:Ce(t.subarray(r,r+c))};if(i>0){let l=r+s+a,u=t.subarray(l,l+i);f.value=o.bytesToValue?.(u)??j(u)}e.push(f),r+=c}return e}function Gu(t){let e=0,r=[];for(let n of t){if(n.bytes==null){let o=vt.getProtocol(n.code),s=de(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Q(n.value),a=i.byteLength,o.size===Ae&&(c=de(a)));let f=new Uint8Array(s+c+a),l=0;Rr(n.code,f,l),l+=s,i!=null&&(o.size===Ae&&(Rr(a,f,l),l+=c),f.set(i,l)),n.bytes=f}r.push(n.bytes),e+=n.bytes.byteLength}return Ue(r,e)}function Yu(t){if(t.charAt(0)!=="/")throw new _e('String multiaddr must start with "/"');let e=[],r="protocol",n="",o="";for(let s=1;s<t.length;s++){let i=t.charAt(s);i!=="/"&&(r==="protocol"?o+=t.charAt(s):n+=t.charAt(s));let a=s===t.length-1;if(i==="/"||a){let c=vt.getProtocol(o);if(r==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",r="protocol";continue}else if(a)throw new _e(`Component ${o} was missing value`);r="value"}else if(r==="value"){let f={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new _e(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}e.push(f),n="",o="",r="protocol"}}}if(o!==""&&n!=="")throw new _e("Incomplete multiaddr");return e}function Xu(t){return`/${t.flatMap(e=>{if(e.value==null)return e.name;let r=vt.getProtocol(e.code);if(r==null)throw new _e(`Unknown protocol code ${e.code}`);return[e.name,r.valueToString?.(e.value)??e.value]}).join("/")}`}function km(t,e,r){return t.size==null||t.size===0?0:t.size>0?t.size/8:wt(e,r)}var Mm=Symbol.for("nodejs.util.inspect.custom"),za=Symbol.for("@multiformats/multiaddr");function Fm(t){if(t==null&&(t="/"),Zu(t))return t.getComponents();if(t instanceof Uint8Array)return ju(t);if(typeof t=="string")return t=t.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),t===""&&(t="/"),Yu(t);if(Array.isArray(t))return t;throw new _e("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ts=class t{[za]=!0;#e;#t;#r;constructor(e="/",r={}){this.#e=Fm(e),r.validate!==!1&&Km(this)}get bytes(){return this.#r==null&&(this.#r=Gu(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Xu(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let r=new t(e);return new t([...this.#e,...r.getComponents()],{validate:!1})}decapsulate(e){let r=e.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new Wo(`Address ${this.toString()} does not contain subaddress: ${r}`);return new t(n.slice(0,o),{validate:!1})}decapsulateCode(e){let r;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){r=n;break}return new t(this.#e.slice(0,r),{validate:!1})}equals(e){return ve(this.bytes,e.bytes)}[Mm](){return`Multiaddr(${this.toString()})`}};function Km(t){t.getComponents().forEach(e=>{let r=vt.getProtocol(e.code);e.value!=null&&r.validate?.(e.value)})}function Zu(t){return!!t?.[za]}function Kr(t){return new ts(t)}var ae=t=>({match:e=>{let r=e[0];return r==null||r.code!==t||r.value!=null?!1:e.slice(1)}}),q=(t,e)=>({match:r=>{let n=r[0];return n?.code!==t||n.value==null||e!=null&&n.value!==e?!1:r.slice(1)}}),Qu=t=>({match:e=>t.match(e)===!1?e:!1}),X=t=>({match:e=>{let r=t.match(e);return r===!1?e:r}}),Re=(...t)=>({match:e=>{let r;for(let n of t){let o=n.match(e);o!==!1&&(r==null||o.length<r.length)&&(r=o)}return r??!1}}),te=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e}});function ce(...t){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of t){let a=i.match(s);if(a===!1)return!1;s=a}return s}function r(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:t,matches:r,exactMatch:n}}var Hm=q(421),C1=ce(Hm),ns=q(54),os=q(55),ss=q(56),qa=q(53),_1=ce(ns,X(q(421))),T1=ce(os,X(q(421))),L1=ce(ss,X(q(421))),B1=ce(Re(qa,ss,ns,os),X(q(421))),Ju=te(q(4),X(q(43))),el=te(X(q(42)),q(41),X(q(43))),Wa=Re(Ju,el),Hr=Re(Wa,qa,ns,os,ss),D1=ce(Re(Wa,te(Re(qa,ss,ns,os),X(q(421))))),I1=ce(Ju),R1=ce(el),O1=ce(Wa),ja=te(Hr,q(6)),On=te(Hr,q(273)),P1=ce(te(ja,X(q(421)))),N1=ce(On),Ga=te(On,ae(460),X(q(421))),is=te(On,ae(461),X(q(421))),$m=Re(Ga,is),U1=ce(Ga),k1=ce(is),Va=Re(Hr,ja,On,Ga,is),tl=Re(te(Va,ae(477),X(q(421)))),M1=ce(tl),rl=Re(te(Va,ae(478),X(q(421))),te(Va,ae(448),X(q(449)),ae(477),X(q(421)))),F1=ce(rl),nl=te(On,ae(280),X(q(466)),X(q(466)),X(q(421))),ol=ce(nl),sl=te(is,ae(465),X(q(466)),X(q(466)),X(q(421))),K1=ce(sl),rs=Re(tl,rl,te(ja,X(q(421))),te($m,X(q(421))),te(Hr,X(q(421))),nl,sl,q(421)),il=ce(rs),zm=te(X(rs),ae(290),Qu(ae(281)),X(q(421))),H1=ce(zm),Vm=Re(te(rs,ae(290),ae(281),X(q(421))),te(rs,ae(281),X(q(421))),te(ae(281),X(q(421)))),al=ce(Vm),qm=te(Hr,Re(te(q(6,"80")),te(q(6),ae(480)),ae(480)),X(q(481)),X(q(421))),$1=ce(qm),Wm=te(Hr,Re(te(q(6,"443")),te(q(6,"443"),ae(480)),te(q(6),ae(443)),te(q(6),ae(448),ae(480)),te(ae(448),ae(480)),ae(448),ae(443)),X(q(481)),X(q(421))),z1=ce(Wm),jm=Re(te(q(777),X(q(421)))),V1=ce(jm),Gm=Re(te(q(400),X(q(421)))),q1=ce(Gm);var Oe;(function(t){let e;(function(a){a.FIN="FIN",a.STOP_SENDING="STOP_SENDING",a.RESET="RESET",a.FIN_ACK="FIN_ACK"})(e=t.Flag||(t.Flag={}));let r;(function(a){a[a.FIN=0]="FIN",a[a.STOP_SENDING=1]="STOP_SENDING",a[a.RESET=2]="RESET",a[a.FIN_ACK=3]="FIN_ACK"})(r||(r={})),(function(a){a.codec=()=>sr(r)})(e=t.Flag||(t.Flag={}));let n;t.codec=()=>(n==null&&(n=ot((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.flag!=null&&(c.uint32(8),t.Flag.codec().encode(a.flag,c)),a.message!=null&&(c.uint32(18),c.bytes(a.message)),f.lengthDelimited!==!1&&c.ldelim()},(a,c,f={})=>{let l={},u=c==null?a.len:a.pos+c;for(;a.pos<u;){let d=a.uint32();switch(d>>>3){case 1:{l.flag=t.Flag.codec().decode(a);break}case 2:{l.message=a.bytes();break}default:{a.skipType(d&7);break}}}return l},function*(a,c,f,l={}){let u=c==null?a.len:a.pos+c;for(;a.pos<u;){let d=a.uint32();switch(d>>>3){case 1:{yield{field:`${f}.flag`,value:t.Flag.codec().decode(a)};break}case 2:{yield{field:`${f}.message`,value:a.bytes()};break}default:{a.skipType(d&7);break}}}})),n);function o(a){return rt(a,t.codec())}t.encode=o;function s(a,c){return tt(a,t.codec(),c)}t.decode=s;function i(a,c){return nt(a,t.codec(),c)}t.stream=i})(Oe||(Oe={}));var cl=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],Ya=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Pn="libp2p+webrtc+v1/",fl="libp2p+webrtc+v2/",ul=2*1024*1024,ur=16*1024,ll=ur,dl=10,hl=8;function Ym(t=ur){let e=de(t-de(t)),r=1+de(Object.keys(Oe.Flag).length-1),n=1,o=t-e-r-n,s=de(o);return e+r+n+s}var pl=Ym();var ml=1e4,Xa="/webrtc",Nn="/webrtc-signaling/0.0.1";function Xm(t){let e=t.getComponents(),r={},n=0;return e[n]?.name==="ip6zone"&&(r.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(r.type=e[n].name,r.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(r.type=e[n].name,r.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(r.protocol=e[n].name==="tcp"?"tcp":"udp",r.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(r.type==="ip4"?r.cidr=parseInt(`${e[n].value}`):r.type==="ip6"&&(r.cidr=`${e[n].value}`),n++),r.type==null||r.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(r.sni=e[n+1].value,n+=2),r)}function Za(t){let e=Xm(t);if(e==null)throw new Z(`Multiaddr ${t} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function as(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var cs=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)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}},$r=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new cs(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 cs(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()}};var Qa=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function zr(t={}){return Zm(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 Zm(t,e){e=e??{};let r=e.onEnd,n=new $r,o,s,i,a=as(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,y)=>{s=E=>{s=null,n.push(E);try{m(t(n))}catch(b){y(b)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=as()})}},f=m=>s!=null?s(m):(n.push(m),o),l=m=>(n=new $r,s!=null?s({error:m}):(n.push({error:m}),o)),u=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:m})},d=m=>i?o:(i=!0,m!=null?l(m):f({done:!0})),p=()=>(n=new $r,d(),{done:!0}),w=m=>(d(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:w,push:u,end:d,get readableLength(){return n.size},onEmpty:async m=>{let y=m?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let E,b;y!=null&&(E=new Promise((L,C)=>{b=()=>{C(new Qa)},y.addEventListener("abort",b)}));try{await Promise.race([a.promise,E])}finally{b!=null&&y!=null&&y?.removeEventListener("abort",b)}}},r==null)return o;let x=o;return o={[Symbol.asyncIterator](){return this},next(){return x.next()},throw(m){return x.throw(m),r!=null&&(r(m),r=void 0),{done:!0}},return(){return x.return(),r!=null&&(r(),r=void 0),{done:!0}},push:u,end(m){return x.end(m),r!=null&&(r(m),r=void 0),o},get readableLength(){return x.readableLength},onEmpty:m=>x.onEmpty(m)},o}var Ja=class t extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,t)}},gl=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function ec(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,l=new Promise((u,d)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){d(gl(i)),t.then(u,d);return}if(i&&(c=()=>{d(gl(i))},i.addEventListener("abort",c,{once:!0})),t.then(u,d),r===Number.POSITIVE_INFINITY)return;let p=new Ja;a=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(w){d(w)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?u():o instanceof Error?d(o):(p.message=o??`Promise timed out after ${r} milliseconds`,d(p))},r)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},l}var Qm=t=>{let e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function Jm(t,e,r){let n,o=new Promise((s,i)=>{if(r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:f,removeListener:l}=Qm(t),u=async(...p)=>{let w=r.multiArgs?p:p[0];if(r.filter)try{if(!await r.filter(w))return}catch(x){n(),i(x);return}c.push(w),r.count===c.length&&(n(),s(c))},d=(...p)=>{n(),i(r.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)l(p,u);for(let p of r.rejectionEvents)a.includes(p)||l(p,d)};for(let p of a)f(p,u);for(let p of r.rejectionEvents)a.includes(p)||f(p,d);r.signal&&r.signal.addEventListener("abort",()=>{d(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){let s=ec(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Te(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Jm(t,e,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var lr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},fs=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},us=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function eg(t){return t.reason}function Ct(t,e,r){if(e==null||t==null)return t;let n=r?.translateError??eg;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let o;return Promise.race([t,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}var tg=Math.pow(2,20)*4,Vt=class extends Lt{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;#e=!1;#t;#r=new Set;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??tg,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new Y,this.writeBuffer=new Y,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let r=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(o){this.log.error("processSendQueue threw - %e",o)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",r);let n=o=>{this.onDrainPromise?.reject(o.error??new us)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get readableEnded(){return this.#e}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Ct(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){let e=zr(),r,n=s=>{e.push(s.data)};this.addEventListener("message",n);let o=()=>{this.#r.delete(o),this.removeEventListener("message",n),r=this.#t,e.end()};this.#r.add(o),this.readableDone()&&o();try{if(yield*e,r!=null)throw r}finally{this.removeEventListener("message",n),this.#r.delete(o)}}readableDone(){return this.readBuffer.byteLength===0&&(this.remoteWriteStatus==="closed"||this.readStatus==="closing"||this.readStatus==="closed")}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new at(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(this.status==="aborted"||this.status==="reset"||this.status==="closed"){this.readBuffer.byteLength>0&&(this.#t??=e,this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closed",this.maybeDispatchEnd());return}this.log.error("abort with error - %e",e),this.status="aborted",this.#t=e,this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.maybeDispatchEnd();try{this.sendReset(e)}catch(r){this.log.error("failed to send reset to remote - %e",r)}this.dispatchEvent(new oo(e))}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new at("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new at("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new at(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new at(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){if(this.status==="aborted"||this.status==="reset"||this.status==="closed")return;this.log("remote reset");let e=new yr;this.#t=e,this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed",this.maybeDispatchEnd()),this.dispatchEvent(new so(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.maybeDispatchEnd(),this.dispatchEvent(new br))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.maybeDispatchEnd(),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,r=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let s=this.writeBuffer.sublist(0,o),i=new Y(s);this.writeBuffer.consume(s.byteLength);let a;try{a=this.sendData(s)}catch(c){throw this.writeBuffer.prepend(i),this.abort(c),c}if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,r,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}maybeDispatchEnd(){this.readableDone()&&(this.#r.forEach(e=>{e()}),!this.#e&&(this.#e=!0,this.safeDispatchEvent("end")))}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new no(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed",this.maybeDispatchEnd()),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new jt(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new jt(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var ls=class extends Vt{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",r=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),r.error!=null?r.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):r.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Te(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Te(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function yl(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var ds=class extends Lt{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,r){super(),this.maConn=e,this.protocol=r.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(r.name),this.streamOptions=r.streamOptions,this.maxEarlyStreams=r.maxEarlyStreams??10,this.metrics=r.metrics;let n=i=>{try{this.onData(i.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let o=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",o);let s=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",s)}send(e){let r=this.maConn.send(e);return r===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),r}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await Ct(Promise.all([...this.streams].map(async r=>{await r.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(r=>{r.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(r=>{r.onTransportClosed(e)})}catch(r){this.abort(r)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new Qn;let r=this.onCreateStream({...this.streamOptions,...e});return yl(r)&&(r=await r),this.streams.push(r),this.cleanUpStream(r),r}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new fs(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let r=n=>{let o=this.streams.findIndex(s=>s===e);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",r),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(r=>{this.safeDispatchEvent("stream",{detail:r})}),this.earlyStreams=[]})}};var hs=class extends Vt{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Te(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await Te(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){if(!(this.readStatus==="closing"||this.readStatus==="closed")){this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",this.maybeDispatchEnd();try{await this.sendCloseRead(e)}catch(r){throw this.log.error("failed to close readable end - %e",r),r}finally{this.readStatus="closed"}this.log("closed readable end gracefully")}}};var rg=4194304,ps=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Un=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},rc=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},nc=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function ng(t){return typeof t?.closeRead=="function"}function og(t){return typeof t?.close=="function"}function tc(t){return ng(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:og(t)?t.status!=="open":!1}function sg(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function ig(t,e){let r=e?.maxBufferSize??rg,n=new Y,o,s=!1,i;if(!sg(t))throw new Z("Argument should be a Stream or a Multiaddr");let a=u=>{if(!s&&i==null){if(n.append(u.data),n.byteLength>r){let d=n.byteLength;n.consume(d);let p=new jt(`Read buffer overflow - ${d} > ${r}`);i=p,o?.reject(p),queueMicrotask(()=>{t.abort(p)});return}o?.resolve()}};t.addEventListener("message",a);let c=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};t.addEventListener("close",c);let f=()=>{o?.resolve()};t.addEventListener("remoteCloseWrite",f);let l={readBuffer:n,async read(u){if(s===!0)throw new ps("Stream was unwrapped");if(i!=null)throw i;if(tc(t)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new lr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let d=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await Ct(o.promise,u?.signal),tc(t)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let p=u?.bytes??n.byteLength;if(n.byteLength<p){if(tc(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,p),new lr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${p} bytes`);return l.read(u)}let w=n.sublist(0,p);return n.consume(p),w},async write(u,d){if(s===!0)throw new ps("Stream was unwrapped");t.send(u)||await Te(t,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",a),t.removeEventListener("close",c),t.removeEventListener("remoteCloseWrite",f),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.unshift(n),n.consume(n.byteLength))),t}};return l}function ms(t,e={}){let r=ig(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=de(e.maxDataLength));let n=e?.lengthDecoder??wt,o=e?.lengthEncoder??Mo;return{async read(i){let a=-1,c=new Y;for(;;){let l=await r.read({...i,bytes:1});if(l==null)break;c.append(l);try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new Un("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new nc(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new rc(`Message length too long - ${a} > ${e.maxDataLength}`);let f=await r.read({...i,bytes:a});if(f==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new lr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(f.byteLength!==a)throw t.log.error("read %d/%d bytes before the stream closed",f.byteLength,a),new lr(`Unexpected EOF - read ${f.byteLength}/${a} bytes before the stream closed`);return f},async write(i,a){await r.write(new Y(o(i.byteLength),i),a)},async writeV(i,a){let c=new Y(...i.flatMap(f=>[o(f.byteLength),f]));await r.write(c,a)},unwrap(){return r.unwrap()}}}function gs(t,e){let r=ms(t,e),n={read:async(o,s)=>{let i=await r.read(s);return o.decode(i,s)},write:async(o,s,i)=>{await r.write(s.encode(o),i)},writeV:async(o,s,i)=>{await r.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}var ag=1024*1024*4,cg=1024*1024*4,ys=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new Y,this.maxBufferSize=e.maxBufferSize??ag,this.maxDataLength=e.maxDataLength??cg,this.lengthDecoder=e.lengthDecoder??wt,this.encodingLength=e.encodingLength??de}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new Z(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let r;try{r=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(r<0||r>this.maxDataLength)throw new Un("Invalid message length");let n=this.encodingLength(r),o=n+r;if(this.buffer.byteLength>=o){let s=this.buffer.sublist(n,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}};var bs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Vr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ws=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},kn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function xs(t){return t[Symbol.asyncIterator]!=null}function bl(t,e){if(t.byteLength>e)throw new Vr("Message length too long")}var Ss=t=>{let e=de(t),r=xe(e);return Mo(t,r),Ss.bytes=e,r};Ss.bytes=0;function Mn(t,e){e=e??{};let r=e.lengthEncoder??Ss,n=e?.maxDataLength??4194304;function*o(s){bl(s,n);let i=r(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return xs(t)?(async function*(){for await(let s of t)yield*o(s)})():(function*(){for(let s of t)yield*o(s)})()}Mn.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??Ss,n=e?.maxDataLength??4194304;return bl(t,n),new Y(r(t.byteLength),t)};var dr;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(dr||(dr={}));var oc=t=>{let e=wt(t);return oc.bytes=de(e),e};oc.bytes=0;function Fn(t,e){let r=new Y,n=dr.LENGTH,o=-1,s=e?.lengthDecoder??oc,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===dr.LENGTH)try{if(o=s(r),o<0)throw new bs("Invalid message length");if(o>a)throw new Vr("Message length too long");let f=s.bytes;r.consume(f),e?.onLength!=null&&e.onLength(o),n=dr.DATA}catch(f){if(f instanceof RangeError){if(r.byteLength>i)throw new ws("Message length length too long");break}throw f}if(n===dr.DATA){if(r.byteLength<o)break;let f=r.sublist(0,o);r.consume(o),e?.onData!=null&&e.onData(f),yield f,n=dr.LENGTH}}}return xs(t)?(async function*(){for await(let f of t)r.append(f),yield*c();if(r.byteLength>0)throw new kn("Unexpected end of input")})():(function*(){for(let f of t)r.append(f),yield*c();if(r.byteLength>0)throw new kn("Unexpected end of input")})()}Fn.fromReader=(t,e)=>{let r=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await t.next(r);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}})();return Fn(n,{...e??{},onLength:s=>{r=s}})};var sc=class extends hs{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(e){super({...e,maxMessageSize:(e.maxMessageSize??ur)-pl}),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=zr(),this.maxBufferedAmount=e.maxBufferedAmount??ul,this.finAckTimeout=e.finAckTimeout??ml,this.channel.onclose=()=>{this.log.trace("received datachannel close event"),this.onRemoteCloseWrite(),this.onTransportClosed()},this.channel.onerror=n=>{let o=n.error;this.log.trace("received datachannel error event - %e",o),this.abort(o)},this.channel.onmessage=async n=>{this.log("incoming message %d bytes",n.data.byteLength);let{data:o}=n;o===null||o.byteLength===0||this.incomingData.push(new Uint8Array(o,0,o.byteLength))},this.channel.bufferedAmountLowThreshold=0,this.channel.onbufferedamountlow=()=>{this.writableNeedsDrain&&this.safeDispatchEvent("drain")},Promise.resolve().then(async()=>{for await(let n of Fn(this.incomingData))this.processIncomingProtobuf(n)}).catch(n=>{this.log.error("error processing incoming data channel messages - %e",n)});let r=()=>{this.channel.readyState==="open"&&(this.log.trace("stream closed, closing underlying datachannel"),this.channel.close())};this.addEventListener("close",r),this.channel.readyState!=="open"&&(this.log('channel ready state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),Te(this.channel,"open",{rejectionEvents:["close","error"]}).then(()=>{this.log('channel ready state is now "%s", dispatching drain',this.channel.readyState),this.safeDispatchEvent("drain")}).catch(n=>{this.abort(n.error??n)}))}sendNewStream(){}_sendMessage(e){if(this.channel.readyState!=="open")throw new at(`Invalid datachannel state - ${this.channel.readyState}`);this.log.trace('sending message, channel state "%s"',this.channel.readyState);try{for(let r of e)this.channel.send(Ce(r))}catch(r){this.log.error("error sending datachannel message - %e",r),this.abort(r)}}sendData(e){return this.channel.readyState!=="open"?{sentBytes:0,canSendMore:!1}:(this._sendMessage(Mn.single(Oe.encode({message:e.subarray()}))),{sentBytes:e.byteLength,canSendMore:this.channel.bufferedAmount<this.maxBufferedAmount})}sendReset(e){try{this.log.error("sending reset - %e",e),this._sendFlag(Oe.Flag.RESET),this.receivedFinAck?.reject(e)}catch(r){this.log.error("failed to send reset - %e",r)}}async sendCloseWrite(e){this._sendFlag(Oe.Flag.FIN),e?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let r=e?.signal??AbortSignal.timeout(this.finAckTimeout),n=[Te(this.channel,"close",{signal:r}),Te(this.channel,"error",{signal:r})];await Promise.any([Ct(this.receivedFinAck.promise,r),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(e){this._sendFlag(Oe.Flag.STOP_SENDING),e?.signal?.throwIfAborted()}processIncomingProtobuf(e){let r=Oe.decode(e);r.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new Y(r.message)),r.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',r.flag,this.writeStatus,this.readStatus),r.flag===Oe.Flag.FIN&&(this._sendFlag(Oe.Flag.FIN_ACK),this.onRemoteCloseWrite()),r.flag===Oe.Flag.RESET&&(this.receivedFinAck?.reject(new yr("The stream was reset")),this.onRemoteReset()),r.flag===Oe.Flag.STOP_SENDING&&this.onRemoteCloseRead(),r.flag===Oe.Flag.FIN_ACK&&this.receivedFinAck?.resolve())}_sendFlag(e){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',e.toString(),this.channel.readyState),!1;this.log.trace("sending flag %s",e.toString());let r=Oe.encode({flag:e}),n=Mn.single(r);try{return this._sendMessage(n),!0}catch(o){this.log.error("could not send flag %s - %e",e.toString(),o)}return!1}sendPause(){}sendResume(){}};function Kn(t){let{channel:e,direction:r,isHandshake:n}=t;return new sc({...t,id:`${e.id}`,log:t.log.newScope(`${n===!0?"handshake":r}:${e.id}`),protocol:""})}function cc(t,e){try{t.close()}catch(r){e?.trace("error closing early data channel - %e",r)}}function ic(t,e){t.channel.onmessage=null,t.messages.length=0,cc(t.channel,e)}var qt=class{protocol;peerConnection;metrics;log;dataChannelOptions;maxEarlyStreams;earlyDataChannels;handedOff=!1;constructor(e){this.onEarlyDataChannel=this.onEarlyDataChannel.bind(this),this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.log=e.log,this.protocol=e.protocol??Xa,this.dataChannelOptions=e.dataChannelOptions??{},this.maxEarlyStreams=e.maxEarlyStreams??dl,this.peerConnection.addEventListener("datachannel",this.onEarlyDataChannel),this.earlyDataChannels=[]}onEarlyDataChannel(e){let r=e.channel;if(this.earlyDataChannels.length>=this.maxEarlyStreams){this.log?.("rejecting early data channel %d - too many early channels",r.id),this.metrics?.increment({early_data_channel_count_exceeded:!0}),cc(r,this.log);return}r.binaryType="arraybuffer";let n={channel:r,messages:[]};r.onmessage=o=>{let{data:s}=o;if(!(s instanceof ArrayBuffer)){this.closeEarlyDataChannel(n,"invalid_message");return}if(n.messages.length>=hl){this.closeEarlyDataChannel(n,"message_count_exceeded");return}if(n.messages.reduce((a,c)=>a+c.data.byteLength,0)+s.byteLength>ll){this.closeEarlyDataChannel(n,"byte_count_exceeded");return}n.messages.push(o)},this.earlyDataChannels.push(n)}closeEarlyDataChannel(e,r){this.log?.("closing early data channel %d - %s",e.channel.id,r),this.metrics?.increment({[`early_data_channel_${r}`]:!0}),ic(e,this.log);let n=this.earlyDataChannels.indexOf(e);n!==-1&&this.earlyDataChannels.splice(n,1)}createStreamMuxer(e){return this.handedOff=!0,this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel),new ac(e,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,maxEarlyStreams:this.maxEarlyStreams,earlyDataChannels:this.earlyDataChannels})}close(){if(!this.handedOff){this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel);for(let e of this.earlyDataChannels)ic(e,this.log);this.earlyDataChannels.length=0}}},ac=class extends ds{peerConnection;dataChannelOptions;constructor(e,r){super(e,{...r,name:"muxer"}),this.peerConnection=r.peerConnection,this.protocol=r.protocol??Xa,this.dataChannelOptions=r.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{this.onDataChannel(n)},queueMicrotask(()=>{if(this.status!=="open"){r.earlyDataChannels.forEach(n=>{ic(n,this.log)});return}r.earlyDataChannels.forEach(({channel:n,messages:o})=>{try{this.onDataChannel(n,o)}catch(s){this.log.error("error adopting early data channel %d - %e",n.id,s)}})})}onDataChannel(e,r){if(this.log("incoming datachannel with channel id %d, protocol %s and status %s",e.id,e.protocol,e.readyState),e.label==="init"){this.log.trace("closing init channel %d",e.id),cc(e,this.log);return}let n=Kn({...this.streamOptions,...this.dataChannelOptions,channel:e,direction:"inbound",log:this.log});r?.forEach(o=>{e.onmessage?.(o)}),this.onRemoteStream(n)}async onCreateStream(e){let r=this.peerConnection.createDataChannel("",{});return this.log("open channel %d for protocol %s",r.id,e?.protocol),Kn({...e,...this.dataChannelOptions,channel:r,direction:"outbound",log:this.log})}onData(){}};var fc=class extends ls{peerConnection;constructor(e){super(e),this.peerConnection=e.peerConnection;let r=e.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change %s initial state %s",this.peerConnection.connectionState,r),(this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.onTransportClosed(),this.peerConnection.close())}}sendData(e){return{sentBytes:e.byteLength,canSendMore:!0}}async sendClose(e){this.peerConnection.close(),e?.signal?.throwIfAborted()}sendReset(){this.peerConnection.close()}sendPause(){}sendResume(){}},Hn=t=>new fc(t);async function uc(t){return t=t??{},typeof t=="function"&&(t=await t()),t.iceServers=t.iceServers??cl.map(e=>({urls:[e]})),t}var As=(t=32,e=Pn)=>e+[...Array(t)].map(()=>Ya.at(Math.floor(Math.random()*Ya.length))).join("");var vs=globalThis.RTCPeerConnection,Cs=globalThis.RTCSessionDescription,wl=globalThis.RTCIceCandidate;var ze=class extends Event{type;detail;constructor(e,r){super(e),this.type=e,this.detail=r}};var st=class extends Error{constructor(e){super(`WebRTC transport error: ${e}`),this.name="WebRTCTransportError"}},Ye=class extends st{constructor(e="SDP handshake failed"){super(e),this.name="SDPHandshakeFailedError"}};var _s=class extends st{constructor(e,r){super(`Invalid fingerprint "${e}" within ${r}`),this.name="WebRTC/InvalidFingerprintError"}};var Ts=class extends st{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},Ls=class extends st{constructor(e){super(`unsupported hash algorithm code: ${e} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var He;(function(t){let e;(function(a){a.SDP_OFFER="SDP_OFFER",a.SDP_ANSWER="SDP_ANSWER",a.ICE_CANDIDATE="ICE_CANDIDATE"})(e=t.Type||(t.Type={}));let r;(function(a){a[a.SDP_OFFER=0]="SDP_OFFER",a[a.SDP_ANSWER=1]="SDP_ANSWER",a[a.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(r||(r={})),(function(a){a.codec=()=>sr(r)})(e=t.Type||(t.Type={}));let n;t.codec=()=>(n==null&&(n=ot((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),t.Type.codec().encode(a.type,c)),a.data!=null&&(c.uint32(18),c.string(a.data)),f.lengthDelimited!==!1&&c.ldelim()},(a,c,f={})=>{let l={},u=c==null?a.len:a.pos+c;for(;a.pos<u;){let d=a.uint32();switch(d>>>3){case 1:{l.type=t.Type.codec().decode(a);break}case 2:{l.data=a.string();break}default:{a.skipType(d&7);break}}}return l},function*(a,c,f,l={}){let u=c==null?a.len:a.pos+c;for(;a.pos<u;){let d=a.uint32();switch(d>>>3){case 1:{yield{field:`${f}.type`,value:t.Type.codec().decode(a)};break}case 2:{yield{field:`${f}.data`,value:a.string()};break}default:{a.skipType(d&7);break}}}})),n);function o(a){return rt(a,t.codec())}t.encode=o;function s(a,c){return tt(a,t.codec(),c)}t.decode=s;function i(a,c){return nt(a,t.codec(),c)}t.stream=i})(He||(He={}));var Bs=async(t,e,r)=>{try{let n=Promise.withResolvers();for(lg(t,n);;){let o=await Promise.race([n.promise,e.read({signal:r.signal})]);if(o==null){r.signal?.throwIfAborted();break}if(o.type!==He.Type.ICE_CANDIDATE)throw new ro("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){r.onProgress?.(new ze("webrtc:end-of-ice-candidates")),r.log.trace("end-of-candidates received");continue}let i=new wl(s);r.log.trace("%s received new ICE candidate %o",r.direction,s);try{r.onProgress?.(new ze("webrtc:add-ice-candidate",i.candidate)),await t.addIceCandidate(i)}catch(a){r.log.error("%s bad candidate received %o - %e",r.direction,s,a)}}}catch(n){if(r.log.error("%s error parsing ICE candidate - %e",r.direction,n),r.signal?.aborted===!0&&t.connectionState!=="connected")throw n}};function lg(t,e){if(t.connectionState==="connected"){e.resolve();return}t.onconnectionstatechange=r=>{switch(t.connectionState){case"connected":e.resolve();break;case"failed":case"closed":e.reject(new Zn(`RTCPeerConnection connection state became "${t.connectionState}"`));break;default:break}}}function Ds(t){let e;for(let r of t.getComponents())r.name==="p2p"&&(e=Nr(r.value??""));if(e==null)throw new Jn("Remote peerId must be present in multiaddr");return e}async function xl({rtcConfiguration:t,dataChannel:e,maxEarlyStreams:r,signal:n,metrics:o,multiaddr:s,connectionManager:i,transportManager:a,log:c,logger:f,onProgress:l}){let{circuitAddress:u,targetPeer:d}=El(s);o?.dialerEvents.increment({open:!0}),c.trace("dialing circuit address: %a",u);let p=i.getConnections(d),w;p.length===0?(l?.(new ze("webrtc:dial-relay")),w=await a.dial(u,{signal:n,onProgress:l})):(l?.(new ze("webrtc:reuse-relay-connection")),w=p[0]),l?.(new ze("webrtc:open-signaling-stream"));let x=await w.newStream(Nn,{signal:n,runOnLimitedConnection:!0}),m=gs(x).pb(He),y=new vs(t);y.addEventListener("connectionstatechange",()=>{y.connectionState==="closed"&&y.close()});let E=new qt({peerConnection:y,dataChannelOptions:e,maxEarlyStreams:r,metrics:o?.dialerEvents,log:c});try{let b=y.createDataChannel("init");y.onicecandidate=({candidate:R})=>{if(y.connectionState==="connected"){c.trace("ignore new ice candidate as peer connection is already connected");return}if(R==null||R?.candidate===""){c.trace("initiator detected end of ICE candidates");return}let N=JSON.stringify(R?.toJSON()??null);c.trace("initiator sending ICE candidate %o",R),m.write({type:He.Type.ICE_CANDIDATE,data:N},{signal:n}).catch(B=>{c.error("error sending ICE candidate - %e",B)})},y.onicecandidateerror=R=>{c.error("initiator ICE candidate error",R)};let L=await y.createOffer().catch(R=>{throw c.error("could not execute createOffer - %e",R),new Ye("Failed to set createOffer")});c.trace("initiator send SDP offer %s",L.sdp),l?.(new ze("webrtc:send-sdp-offer")),await m.write({type:He.Type.SDP_OFFER,data:L.sdp},{signal:n}),await y.setLocalDescription(L).catch(R=>{throw c.error("could not execute setLocalDescription - %e",R),new Ye("Failed to set localDescription")}),l?.(new ze("webrtc:read-sdp-answer")),c.trace("initiator read SDP answer");let C=await m.read({signal:n});if(C.type!==He.Type.SDP_ANSWER)throw new Ye("Remote should send an SDP answer");c.trace("initiator received SDP answer %s",C.data);let O=new Cs({type:"answer",sdp:C.data});return await y.setRemoteDescription(O).catch(R=>{throw c.error("could not execute setRemoteDescription - %e",R),new Ye("Failed to set remoteDescription")}),c.trace("initiator read candidates until connected"),l?.(new ze("webrtc:read-ice-candidates")),await Bs(y,m,{direction:"initiator",signal:n,log:c,onProgress:l}),c.trace("initiator connected"),b.readyState!=="open"&&(c.trace("wait for init channel to open"),await Te(b,"open",{signal:n})),c.trace("closing init channel"),b.close(),c.trace("waiting for init channel to close"),await Te(b,"close",{signal:n}),l?.(new ze("webrtc:close-signaling-stream")),c.trace("closing signaling channel"),await x.close({signal:n}),c.trace("initiator connected to remote address %s",s),{remoteAddress:s,peerConnection:y,muxerFactory:E}}catch(b){throw c.error("outgoing signaling error - %e",b),E.close(),y.close(),x.abort(b),b}finally{y.onicecandidate=null,y.onicecandidateerror=null}}var Sl=ce(il.matchers[0],ae(290)),Is=class t extends Lt{transportManager;shutdownController;events;constructor(e,r){super(),this.transportManager=e.transportManager,this.events=e.events,this.shutdownController=r.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(e){e.detail.getAddrs().filter(n=>Sl.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(e=>!(e instanceof t)).map(e=>e.getAddrs().filter(r=>Sl.exactMatch(r)).map(r=>r.encapsulate("/webrtc"))).flat()}updateAnnounceAddrs(){}async close(){this.events.removeEventListener("transport:listening",this.onTransportListening),this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function Al(t,e,{peerConnection:r,signal:n,log:o}){o.trace("new inbound signaling stream");let s=gs(t).pb(He);try{r.onicecandidate=({candidate:u})=>{if(r.connectionState==="connected"){o.trace("ignore new ice candidate as peer connection is already connected");return}if(u==null||u?.candidate===""){o.trace("recipient detected end of ICE candidates");return}let d=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",d),s.write({type:He.Type.ICE_CANDIDATE,data:d},{signal:n}).catch(p=>{o.error("error sending ICE candidate - %e",p)})},o.trace("recipient read SDP offer");let c=await s.read({signal:n});if(c.type!==He.Type.SDP_OFFER)throw new Ye(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let f=new Cs({type:"offer",sdp:c.data});await r.setRemoteDescription(f).catch(u=>{throw o.error("could not execute setRemoteDescription - %e",u),new Ye("Failed to set remoteDescription")});let l=await r.createAnswer().catch(u=>{throw o.error("could not execute createAnswer - %e",u),new Ye("Failed to create answer")});o.trace("recipient send SDP answer %s",l.sdp),await s.write({type:He.Type.SDP_ANSWER,data:l.sdp},{signal:n}),await r.setLocalDescription(l).catch(u=>{throw o.error("could not execute setLocalDescription - %e",u),new Ye("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await Bs(r,s,{direction:"recipient",signal:n,log:o})}catch(c){if(r.connectionState!=="connected")throw o.error("error while handling signaling stream from peer %a - %e",e.remoteAddr,c),r.close(),c;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",e.remoteAddr,c)}let i=Ds(e.remoteAddr),a=Kr(`/webrtc/p2p/${i}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:i}}var Rs=class{components;init;log;_started=!1;metrics;shutdownController;constructor(e,r={}){this.components=e,this.init=r,this.log=e.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[io]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[wr]=["@libp2p/transport"];[Oc]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(Nn,(e,r)=>{let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(e,r,n).catch(o=>{this.log.error("failed to handle incoming connect from %p - %e",r.remotePeer,o)}).finally(()=>{n.clear()})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(Nn),this._started=!1}createListener(e){return new Is(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(al.exactMatch)}dialFilter(e){return this.listenFilter(e)}async dial(e,r){this.log.trace("dialing address: %a",e);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await xl({rtcConfiguration:await uc(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,maxEarlyStreams:this.init.maxEarlyStreams,multiaddr:e,dataChannelOptions:this.init.dataChannel,signal:r.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,metrics:this.metrics,log:this.log,logger:this.components.logger,onProgress:r.onProgress}),i=Hn({peerConnection:o,remoteAddr:n,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")}),a;try{a=await r.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,remotePeer:Ds(e),muxerFactory:s,onProgress:r.onProgress,signal:r.signal})}catch(c){throw s.close(),o.close(),c}return this._closeOnShutdown(o,i),a}async _onProtocol(e,r,n){let o=new vs(await uc(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{o.connectionState==="closed"&&o.close()});let s=new qt({peerConnection:o,dataChannelOptions:this.init.dataChannel,maxEarlyStreams:this.init.maxEarlyStreams,metrics:this.metrics?.listenerEvents,log:this.log});try{let{remoteAddress:i,remotePeer:a}=await Al(e,r,{peerConnection:o,signal:n,log:this.log});await e.close({signal:n});let c=Hn({peerConnection:o,remoteAddr:i,metrics:this.metrics?.listenerEvents,direction:"inbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")});await this.components.upgrader.upgradeInbound(c,{skipEncryption:!0,skipProtection:!0,remotePeer:a,muxerFactory:s,signal:n}),this._closeOnShutdown(o,c)}catch(i){throw this.log.error("incoming signaling error - %e",i),s.close(),o.close(),e.abort(i),i}}_closeOnShutdown(e,r){let n=()=>{r.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection - %e",o)})};this.shutdownController.signal.addEventListener("abort",n),e.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function El(t){let e=t.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(e==null)throw new Z("Destination peer id was missing");return{circuitAddress:Kr(t.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:Nr(e)}}var qr=!!globalThis.process?.env?.DUMP_SESSION_KEYS,lc=16;function dc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}var Os=t=>t?`"${t}" `:"";function Ps(t,e=""){if(typeof t!="boolean")throw new TypeError(Os(e)+"expected boolean, got type="+typeof t);return t}function hr(t,e=""){if(typeof t!="number")throw new TypeError(Os(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(Os(e)+"expected integer >= 0, got "+t);return t}function be(t,e,r=""){if(dc(t)&&(e===void 0||t.length===e))return t;e!==void 0&&hr(e,"length");let n=dc(t),o=e!==void 0?` of length ${e}`:"",s=n?`length=${t.length}`:`type=${typeof t}`,i=Os(r)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}var vl=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`)};function hc(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function Cl(t,e){be(t,void 0,"output");let r=e.outputLen;if(!(t.length>=r))throw new RangeError('"output" expected length >= '+r)}function pt(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function it(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function dg(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Wt=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function hg(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function pg(t){for(let e=0;e<t.length;e++)t[e]=hg(t[e]);return t}var _t=Wt?t=>t:pg;function mg(t,e){return!t.byteLength||!e.byteLength?!1:t.buffer===e.buffer&&t.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<t.byteOffset+t.byteLength}function _l(t,e){if(mg(t,e)&&t.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function Tl(t,e){return vl(t,"defaults"),vl(e,"opts"),Object.assign(t,e)}function Ll(t,e){if(t=be(t),e=be(e),t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Bl(t,e,r){let n=e,o=r||(()=>[]),s=(a,c)=>n(c,...o(a)).update(a).digest(),i=n(new Uint8Array(t),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>n(a,...c),s}var Dl=(t,e)=>{function r(n,...o){if(be(n,void 0,"key"),t.nonceLength!==void 0){let u=o[0];be(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let s=t.tagLength,i=t.nonceLength!==void 0?1:0;if(!t.withAAD){for(let u=i;u<o.length;u++)if(dc(o[u]))throw new Error("AAD not supported")}t.withAAD&&o[i]!==void 0&&be(o[i],void 0,"AAD");let a=e(n,...o),c=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");be(d,void 0,"output")}},f=!1;return{encrypt(u,d){if(f)throw new Error("cannot encrypt() twice with same key + nonce");return f=!0,be(u,void 0,"data"),c(a.encrypt.length,d),a.encrypt(u,d)},decrypt(u,d){if(be(u,void 0,"data"),s&&u.length<s)throw new Error('"ciphertext" expected length >= tagLength='+s);return c(a.decrypt.length,d),a.decrypt(u,d)}}}return Object.assign(r,t),r};function $n(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(be(e,t,"output"),r&&!zn(e))throw new Error("invalid output, must be aligned");return e}function Il(t,e,r){hr(t),hr(e),Ps(r);let n=new Uint8Array(16),o=dg(n);return o.setBigUint64(0,BigInt(e),r),o.setBigUint64(8,BigInt(t),r),n}function zn(t){return t.byteOffset%4===0}function Wr(t){return Uint8Array.from(be(t))}var Ol=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),gg=_t(pt(Ol("expand 16-byte k"))),yg=_t(pt(Ol("expand 32-byte k")));function ee(t,e){return t<<e|t>>>32-e}var Vn=64,bg=16,pc=2**32-1,Rl=Uint32Array.of();function wg(t,e,r,n,o,s,i,a){let c=o.length,f=new Uint8Array(Vn),l=pt(f),u=Wt&&zn(o)&&zn(s),d=u?pt(o):Rl,p=u?pt(s):Rl;if(!Wt){for(let w=0;w<c;i++){if(t(e,r,n,l,i,a),_t(l),i>=pc)throw new Error("arx: counter overflow");let x=Math.min(Vn,c-w);for(let m=0,y;m<x;m++)y=w+m,s[y]=o[y]^f[m];w+=x}return}for(let w=0;w<c;i++){if(t(e,r,n,l,i,a),i>=pc)throw new Error("arx: counter overflow");let x=Math.min(Vn,c-w);if(u&&x===Vn){let m=w/4;if(w%4!==0)throw new Error("arx: invalid block position");for(let y=0,E;y<bg;y++)E=m+y,p[E]=d[E]^l[y];w+=Vn;continue}for(let m=0,y;m<x;m++)y=w+m,s[y]=o[y]^f[m];w+=x}}function Pl(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Tl({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return hr(o),hr(i),Ps(s),Ps(r),(a,c,f,l,u=0)=>{be(a,void 0,"key"),be(c,void 0,"nonce"),be(f,void 0,"data");let d=f.length,p=l!==void 0;if(l=$n(d,l,!1),p&&_l(f,l),hr(u),u<0||u>=pc)throw new Error("arx: counter overflow");let w=[],x=a.length,m,y;if(x===32)w.push(m=Wr(a)),y=yg;else if(x===16&&r)m=new Uint8Array(32),m.set(a),m.set(a,16),y=gg,w.push(m);else throw be(a,32,"arx key"),new Error("invalid key size");(!Wt||!zn(c))&&w.push(c=Wr(c));let E=pt(m);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let C=c.subarray(0,16);if(Wt)n(y,E,pt(C),E);else{let O=_t(Uint32Array.from(y));n(O,E,pt(C),E),it(O),_t(E)}c=c.subarray(16)}else Wt||_t(E);let b=16-o;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let C=new Uint8Array(12);C.set(c,s?0:12-c.length),c=C,w.push(c)}let L=_t(pt(c));try{return wg(t,y,E,L,f,l,u,i),l}finally{it(...w)}}}function Le(t,e){return t[e++]&255|(t[e++]&255)<<8}var mc=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=Wr(be(e,32,"key"));let r=Le(e,0),n=Le(e,2),o=Le(e,4),s=Le(e,6),i=Le(e,8),a=Le(e,10),c=Le(e,12),f=Le(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|f<<8)&8191,this.r[9]=f>>>5&127;for(let l=0;l<8;l++)this.pad[l]=Le(e,16+2*l)}process(e,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],f=i[2],l=i[3],u=i[4],d=i[5],p=i[6],w=i[7],x=i[8],m=i[9],y=Le(e,r+0),E=Le(e,r+2),b=Le(e,r+4),L=Le(e,r+6),C=Le(e,r+8),O=Le(e,r+10),R=Le(e,r+12),N=Le(e,r+14),B=s[0]+(y&8191),I=s[1]+((y>>>13|E<<3)&8191),K=s[2]+((E>>>10|b<<6)&8191),F=s[3]+((b>>>7|L<<9)&8191),V=s[4]+((L>>>4|C<<12)&8191),_=s[5]+(C>>>1&8191),U=s[6]+((C>>>14|O<<2)&8191),T=s[7]+((O>>>11|R<<5)&8191),v=s[8]+((R>>>8|N<<8)&8191),H=s[9]+(N>>>5|o),D=0,S=D+B*a+I*(5*m)+K*(5*x)+F*(5*w)+V*(5*p);D=S>>>13,S&=8191,S+=_*(5*d)+U*(5*u)+T*(5*l)+v*(5*f)+H*(5*c),D+=S>>>13,S&=8191;let h=D+B*c+I*a+K*(5*m)+F*(5*x)+V*(5*w);D=h>>>13,h&=8191,h+=_*(5*p)+U*(5*d)+T*(5*u)+v*(5*l)+H*(5*f),D+=h>>>13,h&=8191;let g=D+B*f+I*c+K*a+F*(5*m)+V*(5*x);D=g>>>13,g&=8191,g+=_*(5*w)+U*(5*p)+T*(5*d)+v*(5*u)+H*(5*l),D+=g>>>13,g&=8191;let A=D+B*l+I*f+K*c+F*a+V*(5*m);D=A>>>13,A&=8191,A+=_*(5*x)+U*(5*w)+T*(5*p)+v*(5*d)+H*(5*u),D+=A>>>13,A&=8191;let P=D+B*u+I*l+K*f+F*c+V*a;D=P>>>13,P&=8191,P+=_*(5*m)+U*(5*x)+T*(5*w)+v*(5*p)+H*(5*d),D+=P>>>13,P&=8191;let k=D+B*d+I*u+K*l+F*f+V*c;D=k>>>13,k&=8191,k+=_*a+U*(5*m)+T*(5*x)+v*(5*w)+H*(5*p),D+=k>>>13,k&=8191;let M=D+B*p+I*d+K*u+F*l+V*f;D=M>>>13,M&=8191,M+=_*c+U*a+T*(5*m)+v*(5*x)+H*(5*w),D+=M>>>13,M&=8191;let $=D+B*w+I*p+K*d+F*u+V*l;D=$>>>13,$&=8191,$+=_*f+U*c+T*a+v*(5*m)+H*(5*x),D+=$>>>13,$&=8191;let z=D+B*x+I*w+K*p+F*d+V*u;D=z>>>13,z&=8191,z+=_*l+U*f+T*c+v*a+H*(5*m),D+=z>>>13,z&=8191;let W=D+B*m+I*x+K*w+F*p+V*d;D=W>>>13,W&=8191,W+=_*u+U*l+T*f+v*c+H*a,D+=W>>>13,W&=8191,D=(D<<2)+D|0,D=D+S|0,S=D&8191,D=D>>>13,h+=D,s[0]=S,s[1]=h,s[2]=g,s[3]=A,s[4]=P,s[5]=k,s[6]=M,s[7]=$,s[8]=z,s[9]=W}finalize(){let{h:e,pad:r}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+r[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+r[a]|0)+(i>>>16)|0,e[a]=i&65535;it(n)}update(e){hc(this),be(e),e=Wr(e);let{buffer:r,blockLen:n}=this,o=e.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,it(this.h,this.r,this.buffer,this.pad)}digestInto(e){hc(this),Cl(e,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:o}=this;if(o){for(r[o++]=1;o<16;o++)r[o]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}},Nl=Bl(32,t=>new mc(t));function xg(t,e,r,n,o,s=20){let i=t[0],a=t[1],c=t[2],f=t[3],l=e[0],u=e[1],d=e[2],p=e[3],w=e[4],x=e[5],m=e[6],y=e[7],E=o,b=r[0],L=r[1],C=r[2],O=i,R=a,N=c,B=f,I=l,K=u,F=d,V=p,_=w,U=x,T=m,v=y,H=E,D=b,S=L,h=C;for(let A=0;A<s;A+=2)O=O+I|0,H=ee(H^O,16),_=_+H|0,I=ee(I^_,12),O=O+I|0,H=ee(H^O,8),_=_+H|0,I=ee(I^_,7),R=R+K|0,D=ee(D^R,16),U=U+D|0,K=ee(K^U,12),R=R+K|0,D=ee(D^R,8),U=U+D|0,K=ee(K^U,7),N=N+F|0,S=ee(S^N,16),T=T+S|0,F=ee(F^T,12),N=N+F|0,S=ee(S^N,8),T=T+S|0,F=ee(F^T,7),B=B+V|0,h=ee(h^B,16),v=v+h|0,V=ee(V^v,12),B=B+V|0,h=ee(h^B,8),v=v+h|0,V=ee(V^v,7),O=O+K|0,h=ee(h^O,16),T=T+h|0,K=ee(K^T,12),O=O+K|0,h=ee(h^O,8),T=T+h|0,K=ee(K^T,7),R=R+F|0,H=ee(H^R,16),v=v+H|0,F=ee(F^v,12),R=R+F|0,H=ee(H^R,8),v=v+H|0,F=ee(F^v,7),N=N+V|0,D=ee(D^N,16),_=_+D|0,V=ee(V^_,12),N=N+V|0,D=ee(D^N,8),_=_+D|0,V=ee(V^_,7),B=B+I|0,S=ee(S^B,16),U=U+S|0,I=ee(I^U,12),B=B+I|0,S=ee(S^B,8),U=U+S|0,I=ee(I^U,7);let g=0;n[g++]=i+O|0,n[g++]=a+R|0,n[g++]=c+N|0,n[g++]=f+B|0,n[g++]=l+I|0,n[g++]=u+K|0,n[g++]=d+F|0,n[g++]=p+V|0,n[g++]=w+_|0,n[g++]=x+U|0,n[g++]=m+T|0,n[g++]=y+v|0,n[g++]=E+H|0,n[g++]=b+D|0,n[g++]=L+S|0,n[g++]=C+h|0}var Eg=Pl(xg,{counterRight:!1,counterLength:4,allowShortKeys:!1});var Sg=new Uint8Array(16),Ul=(t,e)=>{t.update(e);let r=e.length%16;r&&t.update(Sg.subarray(r))},Ag=new Uint8Array(32);function kl(t,e,r,n,o){o!==void 0&&be(o,void 0,"AAD");let s=t(e,r,Ag),i=Il(n.length,o?o.length:0,!0),a=Nl.create(s);o&&Ul(a,o),Ul(a,n),a.update(i);let c=a.digest();return it(s,i),c}var vg=t=>(e,r,n)=>({encrypt(s,i){let a=s.length;i=$n(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);t(e,r,c,c,1);let f=kl(t,e,r,c,n);return i.set(f,a),it(f),i},decrypt(s,i){i=$n(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),f=kl(t,e,r,a,n);if(!Ll(c,f))throw it(f),new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,r,i,i,1),it(f),i}}),gc=Dl({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},vg(Eg));function Ml(t,e,r){return er(t),r===void 0&&(r=new Uint8Array(t.outputLen)),vn(t,r,e)}var qn=Uint8Array.of(0),Cg=Uint8Array.of();function Fl(t,e,r,n=32,o){er(t),Qe(n,"length"),ke(e,void 0,"prk");let s=t.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(n>255*s)throw new Error("Length must be <= 255*HashLen");let i=Math.ceil(n/s);if(r===void 0?r=Cg:ke(r,void 0,"info"),!i)return o&&qe(e),new Uint8Array;let a=o&&i===1?e:new Uint8Array(i*s),{iHash:c,oHash:f}=vn.create(t,e),l=o?e:new Uint8Array(s),u=i>1?o?.iHash||t.create():void 0;for(let p=0;p<i-1;p++){qn[0]=p+1;let w=c._cloneInto(u);p&&w.update(l),w.update(r).update(qn).digestInto(l),f._cloneInto(u).update(l).digestInto(l),a.set(l,s*p)}if(qn[0]=i,i>1&&c.update(l),c.update(r).update(qn).digestInto(l),f.update(l).digestInto(l),a.set(l,s*(i-1)),c.destroy(),f.destroy(),u?.destroy(),l!==a&&qe(l),qe(qn),n===a.length)return a;let d=a.slice(0,n);return qe(a),d}var Kl={hashSHA256(t){return ft(t.subarray())},getHKDF(t,e){let r=Ml(ft,e,t),o=Fl(ft,r,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let t=gn.utils.randomSecretKey();return{publicKey:gn.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:gn.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return gn.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,r,n){return gc(n,e,r).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,r,n,o){return gc(n,e,r).decrypt(t.subarray(),o)}};var Hl=Kl;function $l(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,r)=>t.generateX25519SharedKey(e.privateKey,r).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}var jr=t=>{let e=xe(2);return e[0]=t>>8,e[1]=t,e};jr.bytes=2;var Gr=t=>{if(t.length<2)throw RangeError("Could not decode int16BE");if(t instanceof Uint8Array){let e=0;return e+=t[0]<<8,e+=t[1],e}return t.getUint16(0)};Gr.bytes=2;function zl(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"})}}function yc(t,e){!e.enabled||!qr||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${j(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${j(t.privateKey,"hex")}`)):e("Missing local static keys."))}function bc(t,e){!e.enabled||!qr||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${j(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${j(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Vl(t,e){!e.enabled||!qr||e(t?`REMOTE_STATIC_PUBLIC_KEY ${j(t.subarray(),"hex")}`:"Missing remote static public key.")}function wc(t,e){!e.enabled||!qr||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${j(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function xc(t,e,r){!r.enabled||!qr||(r(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&j(t.k,"hex")}`),r(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&j(e.k,"hex")}`))}var Yr=class t extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=t.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var _g=0,Tg=4294967295,Lg="Cipherstate has reached maximum n, a new handshake must be performed",Ns=class{n;bytes;view;constructor(e=_g){this.n=e,this.bytes=we(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>Tg)throw new Error(Lg)}};var pr=we(0),Xr=class{k;n;crypto;constructor(e,r=void 0,n=0){this.crypto=e,this.k=r,this.n=new Ns(n)}hasKey(){return!!this.k}encryptWithAd(e,r){if(!this.hasKey())return r;this.n.assertValue();let n=this.crypto.encrypt(r,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,r,n){if(!this.hasKey())return r;this.n.assertValue();let o=this.crypto.decrypt(r,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},Ec=class{cs;ck;h;crypto;constructor(e,r){this.crypto=e;let n=Q(r,"utf-8");this.h=Bg(e,n),this.ck=this.h,this.cs=new Xr(e)}mixKey(e){let[r,n]=this.crypto.hkdf(this.ck,e);this.ck=r,this.cs=new Xr(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new Y(this.h,e))}encryptAndHash(e){let r=this.cs.encryptWithAd(this.h,e);return this.mixHash(r),r}decryptAndHash(e){let r=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),r}split(){let[e,r]=this.crypto.hkdf(this.ck,pr);return[new Xr(this.crypto,e),new Xr(this.crypto,r)]}},Sc=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:r,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:f}=e;this.crypto=r,this.ss=new Ec(r,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=f}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<r+32)throw new Error("message is not long enough");this.re=e.sublist(r,r+32),this.ss.mixHash(this.re)}readS(e,r=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<r+n)throw new Error("message is not long enough");let o=e.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Wn=class extends Sc{writeMessageA(e){return new Y(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let r=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new Y(r,n,this.ss.encryptAndHash(e))}writeMessageC(e){let r=this.writeS();return this.writeSE(),new Y(r,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(r){throw new Yr(`handshake stage 0 validation fail: ${r.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let r=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+r))}catch(r){throw new Yr(`handshake stage 1 validation fail: ${r.message}`)}}readMessageC(e){try{let r=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(r))}catch(r){throw new Yr(`handshake stage 2 validation fail: ${r.message}`)}}};function Bg(t,e){if(e.length<=32){let r=we(32);return r.set(e),r}else return t.hash(e)}var jn;(function(t){let e;t.codec=()=>(e==null&&(e=ot((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.webtransportCerthashes!=null&&s.webtransportCerthashes.length>0)for(let c of s.webtransportCerthashes)i.uint32(10),i.bytes(c);if(s.streamMuxers!=null&&s.streamMuxers.length>0)for(let c of s.streamMuxers)i.uint32(18),i.string(c);a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={webtransportCerthashes:[],streamMuxers:[]},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{if(a.limits?.webtransportCerthashes!=null&&c.webtransportCerthashes.length===a.limits.webtransportCerthashes)throw new ir('Decode error - repeated field "webtransportCerthashes" had too many elements');c.webtransportCerthashes.push(s.bytes());break}case 2:{if(a.limits?.streamMuxers!=null&&c.streamMuxers.length===a.limits.streamMuxers)throw new ir('Decode error - repeated field "streamMuxers" had too many elements');c.streamMuxers.push(s.string());break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let f={webtransportCerthashes:0,streamMuxers:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{if(c.limits?.webtransportCerthashes!=null&&f.webtransportCerthashes===c.limits.webtransportCerthashes)throw new ir('Streaming decode error - repeated field "webtransportCerthashes" had too many elements');yield{field:`${a}.webtransportCerthashes[]`,index:f.webtransportCerthashes,value:s.bytes()},f.webtransportCerthashes++;break}case 2:{if(c.limits?.streamMuxers!=null&&f.streamMuxers===c.limits.streamMuxers)throw new ir('Streaming decode error - repeated field "streamMuxers" had too many elements');yield{field:`${a}.streamMuxers[]`,index:f.streamMuxers,value:s.string()},f.streamMuxers++;break}default:{s.skipType(u&7);break}}}})),e);function r(s){return rt(s,t.codec())}t.encode=r;function n(s,i){return tt(s,t.codec(),i)}t.decode=n;function o(s,i){return nt(s,t.codec(),i)}t.stream=o})(jn||(jn={}));var Gn;(function(t){let e;t.codec=()=>(e==null&&(e=ot((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.identityKey!=null&&s.identityKey.byteLength>0&&(i.uint32(10),i.bytes(s.identityKey)),s.identitySig!=null&&s.identitySig.byteLength>0&&(i.uint32(18),i.bytes(s.identitySig)),s.extensions!=null&&(i.uint32(34),jn.codec().encode(s.extensions,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={identityKey:we(0),identitySig:we(0)},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{c.identityKey=s.bytes();break}case 2:{c.identitySig=s.bytes();break}case 4:{c.extensions=jn.codec().decode(s,s.uint32(),{limits:a.limits?.extensions});break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.identityKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.identitySig`,value:s.bytes()};break}case 4:{yield*jn.codec().stream(s,s.uint32(),`${a}.extensions`,{limits:c.limits?.extensions});break}default:{s.skipType(l&7);break}}}})),e);function r(s){return rt(s,t.codec())}t.encode=r;function n(s,i){return tt(s,t.codec(),i)}t.decode=n;function o(s,i){return nt(s,t.codec(),i)}t.stream=o})(Gn||(Gn={}));async function vc(t,e,r){let n=await t.sign(Wl(e));return Gn.encode({identityKey:Rt(t.publicKey),identitySig:n,extensions:r})}async function Cc(t,e,r){try{let n=Gn.decode(t),o=Cn(n.identityKey);if(r!=null){let i=In(o);if(!r.equals(i))throw new Error(`Payload peer id ${i} does not match expected remote peer id ${r}`)}if(!e)throw new Error("Remote static does not exist");let s=Wl(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Yn(n.message)}}function Wl(t){let e=Q("noise-libp2p-static-key:");return t instanceof Uint8Array?Ue([e,t],e.length+t.length):(t.prepend(e),t)}var Ac=class extends Vt{stream;handshake;metrics;decoder;constructor(e,r,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=r,this.metrics=n,this.decoder=new ys({lengthDecoder:Gr,maxBufferSize:16*1024*1024,encodingLength:()=>2});let o=c=>{try{for(let f of this.decoder.decode(c.data))this.onData(this.decrypt(f))}catch(f){this.abort(f)}};this.stream.addEventListener("message",o);let s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){let r=new Y;for(let n=0;n<e.byteLength;n+=65519){let o=n+65519;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),r.append(jr(s.byteLength)),r.append(s)}return r}decrypt(e){let r=new Y;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-lc<n)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(n,o):s=e.sublist(n,o);let i=e.subarray(n,o-lc);try{let a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),r.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return r}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function _c(t,e,r){return new Ac(t,e,r)}async function jl(t,e){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remotePeer:c,extensions:f}=t,l=await vc(s,a.publicKey,f),u=new Wn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});yc(u.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(u.writeMessageA(pr),e),r.trace("Stage 0 - Initiator finished sending first message."),bc(u.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");let d=u.readMessageB(await n.read(e));r.trace("Stage 1 - Initiator received the message."),wc(u.re,r),Vl(u.rs,r),r.trace("Initiator going to check remote's signature...");let p=await Cc(d,u.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(u.writeMessageC(l),e),r.trace("Stage 2 - Initiator sent message with signed payload.");let[w,x]=u.ss.split();return xc(w,x,r),{payload:p,encrypt:m=>w.encryptWithAd(pr,m),decrypt:(m,y)=>x.decryptWithAd(pr,m,y)}}async function Gl(t,e){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remotePeer:c,extensions:f}=t,l=await vc(s,a.publicKey,f),u=new Wn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});yc(u.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),u.readMessageA(await n.read(e)),r.trace("Stage 0 - Responder received first message."),wc(u.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(u.writeMessageB(l),e),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),bc(u.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");let d=u.readMessageC(await n.read(e));r.trace("Stage 2 - Responder received the message, finished handshake.");let p=await Cc(d,u.rs,c),[w,x]=u.ss.split();return xc(w,x,r),{payload:p,encrypt:m=>x.encryptWithAd(pr,m),decrypt:(m,y)=>w.decryptWithAd(pr,m,y)}}var ks=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,r={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=r,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=s??Hl;this.crypto=$l(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?zl(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??we(0)}[Symbol.toStringTag]="@libp2p/noise";[wr]=["@libp2p/connection-encryption","@libp2p/noise"];async secureOutbound(e,r){let n=e.log?.newScope("noise")??this.log,o=ms(e,{lengthEncoder:jr,lengthDecoder:Gr,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,r?.remotePeer,r),i=Cn(s.payload.identityKey);return{connection:_c(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:In(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let r=this.components.upgrader.getStreamMuxers();if(r!=null)for(let n of e){let o=r.get(n);if(o!=null)return o}if(e.length)throw new Xn("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,r){let n=e.log?.newScope("noise")??this.log,o=ms(e,{lengthEncoder:jr,lengthDecoder:Gr,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,r?.remotePeer,r),i=Cn(s.payload.identityKey);return{connection:_c(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:In(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await jl({connection:e,privateKey:r,remotePeer:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Gl({connection:e,privateKey:r,remotePeer:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function Yl(t={}){return e=>new ks(e,t)}var Tc=Object.values(Zt).map(t=>t.decoder).reduce((t,e)=>t.or(e)),Dg=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m,Ig=/^a=ice-ufrag:(?<ufrag>[^\r\n]+)$/m,Rg=/^a=ice-pwd:(?<pwd>[^\r\n]+)$/m;function Xl(t){return t?.match(Dg)?.groups?.fingerprint}function Zl(t){if(t!=null)return t.match(Ig)?.groups?.ufrag}function Lc(t){if(t!=null)return t.match(Rg)?.groups?.pwd}function Bc(t){let r=t.getComponents().find(n=>n.code===466)?.value;if(r===void 0||r==="")throw new Z(`Couldn't find a certhash component of multiaddr: ${t.toString()}`);return r}function Og(t){return Xe.decode(Tc.decode(t))}function Pg(t){let e=Og(Bc(t)),r=Ng(e.code),n=e.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new _s(n,t.toString());return`${r} ${o.join(":").toUpperCase()}`}function Ql(t){let e=t.split(":").map(o=>parseInt(o,16)),r=Uint8Array.from(e),n=Ne(mt.code,r);return Kr(`/certhash/${rn.encode(n.bytes)}`)}function Ng(t){switch(t){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new Ls(t)}}function Jl(t,e){let{host:r,port:n,type:o}=Za(t);if(o!=="ip4"&&o!=="ip6")throw new Z(`Multiaddr ${t} was not an IPv4 or IPv6 address`);let s=Pg(t);return{type:"answer",sdp:`v=0
2
+ "use strict";var Libp2PWebrtc=(()=>{var ks=Object.defineProperty;var md=Object.getOwnPropertyDescriptor;var gd=Object.getOwnPropertyNames;var yd=Object.prototype.hasOwnProperty;var Oe=(t,e)=>{for(var r in e)ks(t,r,{get:e[r],enumerable:!0})},bd=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of gd(e))!yd.call(t,o)&&o!==r&&ks(t,o,{get:()=>e[o],enumerable:!(n=md(e,o))||n.enumerable});return t};var wd=t=>bd(ks({},"__esModule",{value:!0}),t);var Xg={};Oe(Xg,{webRTC:()=>Yg,webRTCDirect:()=>Gg});var jn=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},Gn=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},Z=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},jt=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Yn=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},Xn=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},yr=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var at=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Gt=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var Zn=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Qn=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Jn=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var eo=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Yt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var to=class extends Event{data;constructor(e,r){super("message",r),this.data=e}},br=class extends Event{error;local;constructor(e,r,n){super("close",n),this.error=r,this.local=e}},ro=class extends br{constructor(e,r){super(!0,e,r)}},no=class extends br{constructor(e,r){super(!1,e,r)}};var Ms=Symbol.for("@libp2p/peer-id");var oo=Symbol.for("@libp2p/transport");var Bc;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Bc||(Bc={}));function xd(t){return typeof t?.handleEvent=="function"}function Ed(t){return t===!0||t===!1}function Sd(t){return Ed(t)?t:t?.capture??!1}function Fs(t){let e={capture:Sd(t),once:!!t?.once};return t?.passive!=null&&(e.passive=t?.passive),t?.signal!=null&&(e.signal=t?.signal),e}function Dc(t,e){return Fs(t).capture===Fs(e).capture}var Lt=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let r=this.#e.get(e);return r==null?0:r.length}addEventListener(e,r,n){let o=Fs(n);if(o?.signal?.aborted===!0)return;let s=f=>{o.once&&this.removeEventListener(e,r,o),xd(r)?r.handleEvent(f):r(f)},i=this.#e.get(e);if(i==null&&(i=[],this.#e.set(e,i)),i.some(f=>f.callback!==r?!1:Dc(f.options,o)))return;super.addEventListener(e,s,o);let c=()=>{this.removeEventListener(e,r,o)};o.signal?.addEventListener("abort",c),i.push({callback:r,wrapper:s,options:o,onAbort:c})}removeEventListener(e,r,n){let o=this.#e.get(e);if(o==null){super.removeEventListener(e,r??null,n);return}this.#e.set(e,o.filter(s=>s.callback===r&&Dc(s.options,n)?(super.removeEventListener(e,s.wrapper,n),s.options?.signal?.removeEventListener("abort",s.onAbort),!1):!0))}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}};var wr=Symbol.for("@libp2p/service-capabilities"),Ic=Symbol.for("@libp2p/service-dependencies");function Ae(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 qs={};Oe(qs,{base58btc:()=>ge,base58flickr:()=>Dd});var By=new Uint8Array(0);function Pc(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}function qe(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return Xt(t);if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return Xt(new Uint8Array(t.buffer,t.byteOffset,t.byteLength));throw new Error("Unknown type, must be binary type")}function Oc(t){let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}var Rc=4096;function Nc(t){let e=t.length;if(e<=Rc)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.subarray(n,n+=Rc));return r}function Ad(t){return t?.buffer instanceof ArrayBuffer}function Xt(t){return Ad(t)?t:t.slice()}function vd(t,e,r){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),o=0;o<n.length;o++)n[o]=255;for(var s=0;s<t.length;s++){var i=t.charAt(s),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");if(n[a]=s,r){var c=i.toLowerCase().charCodeAt(0),f=i.toUpperCase().charCodeAt(0);c!==a&&(n[c]=s),f!==a&&(n[f]=s)}}var l=t.length,u=t.charAt(0),d=Math.log(l)/Math.log(256),p=Math.log(256)/Math.log(l);function x(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var E=0,b=0,v=0,C=g.length;v!==C&&g[v]===0;)v++,E++;for(var P=(C-v)*p+1>>>0,R=new Uint8Array(P);v!==C;){for(var N=g[v],B=0,I=P-1;(N!==0||B<b)&&I!==-1;I--,B++)N+=256*R[I]>>>0,R[I]=N%l>>>0,N=N/l>>>0;if(N!==0)throw new Error("Non-zero carry");b=B,v++}for(var K=P-b;K!==P&&R[K]===0;)K++;for(var F=u.repeat(E);K<P;++K)F+=t.charAt(R[K]);return F}function w(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var E=0;if(g[E]!==" "){for(var b=0,v=0;g[E]===u;)b++,E++;for(var C=(g.length-E)*d+1>>>0,P=new Uint8Array(C);g[E];){var R=n[g.charCodeAt(E)];if(R===255)return;for(var N=0,B=C-1;(R!==0||N<v)&&B!==-1;B--,N++)R+=l*P[B]>>>0,P[B]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");v=N,E++}if(g[E]!==" "){for(var I=C-v;I!==C&&P[I]===0;)I++;for(var K=new Uint8Array(b+(C-I)),F=b;I!==C;)K[F++]=P[I++];return K}}}function m(g){var E=w(g);if(E)return E;throw new Error(`Non-${e} character`)}return{encode:x,decodeUnsafe:w,decode:m}}var Cd=vd,_d=Cd,kc=_d;var Ks=class{name;prefix;baseEncode;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")}},Hs=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let o=r.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 Mc(this,e)}},$s=class{decoders;constructor(e){this.decoders=e}or(e){return Mc(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Mc(t,e){return new $s({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var zs=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,o){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Ks(e,r,n),this.decoder=new Hs(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function xr({name:t,prefix:e,encode:r,decode:n}){return new zs(t,e,r,n)}function Bt({name:t,prefix:e,alphabet:r,caseInsensitive:n=!1}){let{encode:o,decode:s}=kc(r,t,n);return xr({prefix:e,name:t,encode:o,decode:i=>qe(s(i))})}function Td(t,e,r,n){let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let l=e[t[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|l,i+=r,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=r||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Ld(t,e,r){let n=e[e.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],i+=8;i>r;)i-=r,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function Bd(t,e){let r={};for(let n=0;n<t.length;++n)if(r[t[n]]=n,e){let o=t[n].toLowerCase(),s=t[n].toUpperCase();o!==t[n]&&(r[o]=n),s!==t[n]&&(r[s]=n)}return r}function me({name:t,prefix:e,bitsPerChar:r,alphabet:n,caseInsensitive:o=!1}){let s=Bd(n,o);return xr({prefix:e,name:t,encode(i){return Ld(i,n,r)},decode(i){return Td(i,s,r,t)}})}var ge=Bt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Dd=Bt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Vs={};Oe(Vs,{base32:()=>Dt,base32hex:()=>Od,base32hexpad:()=>Ud,base32hexpadupper:()=>kd,base32hexupper:()=>Nd,base32pad:()=>Rd,base32padupper:()=>Pd,base32upper:()=>Id,base32z:()=>Md});var Dt=me({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),Id=me({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),Rd=me({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),Pd=me({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),Od=me({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),Nd=me({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),Ud=me({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),kd=me({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),Md=me({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ws={};Oe(Ws,{base36:()=>Qr,base36upper:()=>Fd});var Qr=Bt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),Fd=Bt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var Xe={};Oe(Xe,{Digest:()=>Zt,create:()=>Ne,decode:()=>Ar,equals:()=>Gs,hasCode:()=>oh});var Kd=Hc,Fc=128,Hd=127,$d=~Hd,zd=Math.pow(2,31);function Hc(t,e,r){e=e||[],r=r||0;for(var n=r;t>=zd;)e[r++]=t&255|Fc,t/=128;for(;t&$d;)e[r++]=t&255|Fc,t>>>=7;return e[r]=t|0,Hc.bytes=r-n+1,e}var qd=js,Vd=128,Kc=127;function js(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw js.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&Kc)<<o:(i&Kc)*Math.pow(2,o),o+=7}while(i>=Vd);return js.bytes=s-n,r}var Wd=Math.pow(2,7),jd=Math.pow(2,14),Gd=Math.pow(2,21),Yd=Math.pow(2,28),Xd=Math.pow(2,35),Zd=Math.pow(2,42),Qd=Math.pow(2,49),Jd=Math.pow(2,56),eh=Math.pow(2,63),th=function(t){return t<Wd?1:t<jd?2:t<Gd?3:t<Yd?4:t<Xd?5:t<Zd?6:t<Qd?7:t<Jd?8:t<eh?9:10},rh={encode:Kd,decode:qd,encodingLength:th},nh=rh,Jr=nh;function en(t,e=0){let r=Jr.decode(t,e),n=Jr.decode.bytes;if(n>9)throw new RangeError("Invalid varint: too long");if(n>1&&t[e+n-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[r,n]}function Er(t,e,r=0){return Jr.encode(t,e,r),e}function Sr(t){return Jr.encodingLength(t)}function Ne(t,e){let r=e.byteLength,n=Sr(t),o=n+Sr(r),s=new Uint8Array(o+r);return Er(t,s,0),Er(r,s,n),s.set(e,o),new Zt(t,r,e,s)}function Ar(t){let e=qe(t),[r,n]=en(e),[o,s]=en(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Zt(r,o,i,e)}function Gs(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Pc(t.bytes,r.bytes)}}var Zt=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=Xt(n),this.bytes=Xt(o)}};function oh(t,e){return t.code===e}function $c(t,e){let{bytes:r,version:n}=t;return n===0?ih(r,Ys(t),e??ge.encoder):ah(r,Ys(t),e??Dt.encoder)}var zc=new WeakMap;function Ys(t){let e=zc.get(t);if(e==null){let r=new Map;return zc.set(t,r),r}return e}var Ee=class t{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=Xt(o),this["/"]=this.bytes}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!==tn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==ch)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.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=Ne(e,r);return t.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 t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&Gs(e.multihash,n.multihash)}toString(e){return $c(this,e)}toJSON(){return{"/":$c(this)}}link(){return this}[Symbol.toStringTag]="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 t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new t(n,o,s,i??qc(n,o,s.bytes))}else if(r[fh]===!0){let{version:n,multihash:o,code:s}=r,i=Ar(o);return t.create(n,s,i)}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!==tn)throw new Error(`Version 0 CID must use dag-pb (code: ${tn}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=qc(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,tn,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,o=qe(e.subarray(n,n+r.multihashSize));if(o.byteLength!==r.multihashSize)throw new Error("Incorrect length");let s=o.subarray(r.multihashSize-r.digestSize),i=new Zt(r.multihashCode,r.digestSize,s,o);return[r.version===0?t.createV0(i):t.createV1(r.codec,i),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[u,d]=en(e.subarray(r));return r+=d,u},o=n(),s=tn;if(o===18?(o=0,r=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=r,a=n(),c=n(),f=r+c,l=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:f}}static parse(e,r){let[n,o]=sh(e,r),s=t.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ys(s).set(n,e),s}};function sh(t,e){switch(t[0]){case"Q":{let r=e??ge;return[ge.prefix,r.decode(`${ge.prefix}${t}`)]}case ge.prefix:{let r=e??ge;return[ge.prefix,r.decode(t)]}case Dt.prefix:{let r=e??Dt;return[Dt.prefix,r.decode(t)]}case Qr.prefix:{let r=e??Qr;return[Qr.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function ih(t,e,r){let{prefix:n}=r;if(n!==ge.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=e.get(n);if(o==null){let s=r.encode(t).slice(1);return e.set(n,s),s}else return o}function ah(t,e,r){let{prefix:n}=r,o=e.get(n);if(o==null){let s=r.encode(t);return e.set(n,s),s}else return o}var tn=112,ch=18;function qc(t,e,r){let n=Sr(t),o=n+Sr(e),s=new Uint8Array(o+r.byteLength);return Er(t,s,0),Er(e,s,n),s.set(r,o),s}var fh=Symbol.for("@ipld/js-cid/CID");var Xs={};Oe(Xs,{identity:()=>Ze});var Vc=0,uh="identity",Wc=qe;function lh(t,e){if(e?.truncate!=null&&e.truncate!==t.byteLength){if(e.truncate<0||e.truncate>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,e.truncate)}return Ne(Vc,Wc(t))}var Ze={code:Vc,name:uh,encode:Wc,digest:lh};function dh(t){return t.buffer instanceof ArrayBuffer}function Ce(t){return dh(t)?t:t.slice()}async function jc(t,e,r,n){let o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,Ce(e),Ce(r.subarray()));return n?.signal?.throwIfAborted(),s}function we(t=0){return new Uint8Array(t)}function xe(t=0){return new Uint8Array(t)}function hh(t){return t?.buffer instanceof ArrayBuffer}function Zs(t){if(hh(t))return t;let e=t.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function Ue(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=xe(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return Zs(r)}var Yc=Symbol.for("@achingbrain/uint8arraylist");function Gc(t,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let r=0;for(let n of t){let o=r+n.byteLength;if(e<o)return{buf:n,index:e-r};r=o}throw new RangeError("index is out of bounds")}function io(t){return!!t?.[Yc]}var Y=class t{bufs;length;[Yc]=!0;constructor(...e){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(io(n)){r+=n.byteLength;for(let o of n.bufs)this.bufs.push(o)}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(io(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=Gc(this.bufs,e);return r.buf[r.index]}set(e,r){let n=Gc(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(io(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:o}=this._subList(e,r);return Ue(n,o)}subarray(e,r){let{bufs:n,length:o}=this._subList(e,r);return n.length===1?n[0]:Ue(n,o)}sublist(e,r){let{bufs:n,length:o}=this._subList(e,r),s=new t;return s.length=o,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=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let f=e>=a&&e<c,l=r>a&&r<=c;if(f&&l){if(e===a&&r===c){n.push(i);break}let u=e-a;n.push(i.subarray(u,u+(r-e)));break}if(f){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(l){if(r===c){n.push(i);break}n.push(i.subarray(0,r-a));break}n.push(i)}return{bufs:n,length:r-e}}indexOf(e,r=0){if(!io(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 o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let u=0;u<s;u++)i[u]=-1;for(let u=0;u<o;u++)i[n[u]]=u;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,l;for(let u=r;u<=c;u+=l){l=0;for(let d=f;d>=0;d--){let p=this.get(u+d);if(n[d]!==p){l=Math.max(1,d-a[p]);break}}if(l===0)return u}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=xe(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 o=we(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,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 o=we(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,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 o=we(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,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=xe(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 o=we(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,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 o=we(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,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 o=we(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,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 o=we(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,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 o=we(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof t)||e.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!Ae(this.bufs[r],e.bufs[r]))return!1;return!0}static fromUint8Arrays(e,r){let n=new t;return n.bufs=e,r==null&&(r=e.reduce((o,s)=>o+s.byteLength,0)),n.length=r,n}};var Qs={};Oe(Qs,{base10:()=>ph});var ph=Bt({prefix:"9",name:"base10",alphabet:"0123456789"});var Js={};Oe(Js,{base16:()=>mh,base16upper:()=>gh});var mh=me({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),gh=me({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var ei={};Oe(ei,{base2:()=>yh});var yh=me({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ti={};Oe(ti,{base256emoji:()=>Sh});var Xc=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}"),bh=Xc.reduce((t,e,r)=>(t[r]=e,t),[]),wh=Xc.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function xh(t){return t.reduce((e,r)=>(e+=bh[r],e),"")}function Eh(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=wh[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var Sh=xr({prefix:"\u{1F680}",name:"base256emoji",encode:xh,decode:Eh});var ri={};Oe(ri,{base64:()=>Ah,base64pad:()=>vh,base64url:()=>rn,base64urlpad:()=>Ch});var Ah=me({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),vh=me({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),rn=me({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ch=me({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ni={};Oe(ni,{base8:()=>_h});var _h=me({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var oi={};Oe(oi,{identity:()=>Th});var Th=xr({prefix:"\0",name:"identity",encode:t=>Nc(qe(t)),decode:t=>qe(Oc(t))});var h0=new TextEncoder,p0=new TextDecoder;var ai={};Oe(ai,{sha256:()=>mt,sha512:()=>Ih});var Dh=20;function ii({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new si(t,e,r,n,o)}var si=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??Dh,this.maxDigestLength=s}digest(e,r){if(r?.truncate!=null){if(r.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&r.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Zc(n,this.code,r?.truncate):n.then(o=>Zc(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function Zc(t,e,r){if(r!=null&&r!==t.byteLength){if(r>t.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${t.byteLength}`);t=t.subarray(0,r)}return Ne(e,t)}function Jc(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var mt=ii({name:"sha2-256",code:18,encode:Jc("SHA-256")}),Ih=ii({name:"sha2-512",code:19,encode:Jc("SHA-512")});var Qt={...oi,...ei,...ni,...Qs,...Js,...Vs,...Ws,...qs,...ri,...ti},_0={...ai,...Xs};function tf(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var ef=tf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ci=tf("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=xe(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Rh={utf8:ef,"utf-8":ef,hex:Qt.base16,latin1:ci,ascii:ci,binary:ci,...Qt},ao=Rh;function Q(t,e="utf8"){let r=ao[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function j(t,e="utf8"){let r=ao[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}var Ph=parseInt("11111",2),fi=parseInt("10000000",2),Oh=parseInt("01111111",2),rf={0:nn,1:nn,2:Nh,3:Mh,4:Fh,5:kh,6:Uh,16:nn,22:nn,48:nn};function gt(t,e={offset:0}){let r=t[e.offset]&Ph;if(e.offset++,rf[r]!=null)return rf[r](t,e);throw new Error("No decoder for tag "+r)}function on(t,e){let r=0;if((t[e.offset]&fi)===fi){let n=t[e.offset]&Oh,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++){if(e.offset>=t.byteLength)throw new Error("invalid DER element length");o+=t[e.offset].toString(16).padStart(2,"0")}r=parseInt(o,16)}else r=t[e.offset],e.offset++;if(!Number.isInteger(r)||r<0||r>t.byteLength-e.offset)throw new Error("invalid DER element length");return r}function nn(t,e){on(t,e);let r=[];for(;!(e.offset>=t.byteLength);){let n=gt(t,e);if(n===null)break;r.push(n)}return r}function Nh(t,e){let r=on(t,e),n=e.offset,o=e.offset+r,s=[];for(let i=n;i<o;i++)i===n&&t[i]===0||s.push(t[i]);return e.offset+=r,Uint8Array.from(s)}function Uh(t,e){let r=on(t,e),n=e.offset+r,o=t[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;e.offset<n;){let f=t[e.offset];if(e.offset++,c.push(f&127),f<128){c.reverse();let l=0;for(let u=0;u<c.length;u++)l+=c[u]<<u*7;a+=`.${l}`,c=[]}}return a}function kh(t,e){return e.offset++,null}function Mh(t,e){let r=on(t,e),n=t[e.offset];e.offset++;let o=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Fh(t,e){let r=on(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function Kh(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);let r=new Y;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function ui(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);let e=Kh(t.byteLength);return new Y(Uint8Array.from([e.byteLength|fi]),e)}function Fe(t){let e=new Y,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new Y(Uint8Array.from([2]),ui(e),e)}function co(t){let e=Uint8Array.from([0]),r=new Y(e,t);return new Y(Uint8Array.from([3]),ui(r),r)}function It(t,e=48){let r=new Y;for(let n of t)r.append(n);return new Y(Uint8Array.from([e]),ui(r),r)}var Hh=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),$h=Uint8Array.from([6,5,43,129,4,0,34]),zh=Uint8Array.from([6,5,43,129,4,0,35]),qh={ext:!0,kty:"EC",crv:"P-256"},Vh={ext:!0,kty:"EC",crv:"P-384"},Wh={ext:!0,kty:"EC",crv:"P-521"},li=32,di=48,hi=66;function pi(t){let e=gt(t);return nf(e)}function nf(t){let e=t[1][1][0],r=1,n,o;if(e.byteLength===li*2+1)return n=j(e.subarray(r,r+li),"base64url"),o=j(e.subarray(r+li),"base64url"),new vr({...qh,key_ops:["verify"],x:n,y:o});if(e.byteLength===di*2+1)return n=j(e.subarray(r,r+di),"base64url"),o=j(e.subarray(r+di),"base64url"),new vr({...Vh,key_ops:["verify"],x:n,y:o});if(e.byteLength===hi*2+1)return n=j(e.subarray(r,r+hi),"base64url"),o=j(e.subarray(r+hi),"base64url"),new vr({...Wh,key_ops:["verify"],x:n,y:o});throw new Z(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function of(t){return It([Fe(Uint8Array.from([1])),It([jh(t.crv)],160),It([co(new Y(Uint8Array.from([4]),Q(t.x??"","base64url"),Q(t.y??"","base64url")))],161)]).subarray()}function jh(t){if(t==="P-256")return Hh;if(t==="P-384")return $h;if(t==="P-521")return zh;throw new Z(`Invalid curve ${t}`)}var vr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=of(this.jwk)),this._raw}toMultihash(){return Ze.digest(Rt(this))}toCID(){return Ee.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ae(this.raw,e.raw)}async verify(e,r,n){return jc(this.jwk,r,e,n)}};var fo=BigInt(4294967295),sf=BigInt(32);function Gh(t,e=!1){return e?{h:Number(t&fo),l:Number(t>>sf&fo)}:{h:Number(t>>sf&fo)|0,l:Number(t&fo)|0}}function af(t,e=!1){let r=t.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=Gh(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Yh=t=>t/2**32|0,Xh=t=>t>>>0;function cf(t,e,r,n){let o=Yh(r),s=Xh(r);t.setUint32(e,n?s:o,n),t.setUint32(e+4,n?o:s,n)}var mi=(t,e,r)=>t>>>r,gi=(t,e,r)=>t<<32-r|e>>>r,Jt=(t,e,r)=>t>>>r|e<<32-r,er=(t,e,r)=>t<<32-r|e>>>r,sn=(t,e,r)=>t<<64-r|e>>>r-32,an=(t,e,r)=>t>>>r-32|e<<64-r;function ct(t,e,r,n){let o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}var ff=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),uf=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,lf=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),df=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0,hf=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0),pf=(t,e,r,n,o,s)=>e+r+n+o+s+(t/2**32|0)|0;function uo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}var yi=t=>t?`"${t}" `:"";function Qe(t,e=""){if(typeof t!="number")throw new TypeError(yi(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(yi(e)+"expected integer >= 0, got "+t);return t}function ke(t,e,r=""){if(uo(t)&&(e===void 0||t.length===e))return t;e!==void 0&&Qe(e,"length");let n=uo(t),o=e!==void 0?` of length ${e}`:"",s=n?`length=${t.length}`:`type=${typeof t}`,i=yi(r)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}function tr(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Qe(t.outputLen),Qe(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var Qh=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)},mf=(t,e)=>{Qh(t,e);let r=Object.getPrototypeOf(t);if(r!==Object.prototype&&r!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(t,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};function Cr(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function lo(t,e){ke(t,void 0,"output");let r=e.outputLen;if(!(t.length>=r))throw new RangeError('"output" expected length >= '+r)}function Ve(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function ho(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Je(t,e){return t<<32-e|t>>>e}var yf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Jh=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function po(t){if(ke(t),yf)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Jh[t[r]];return e}function gf(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function mo(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(yf)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=gf(t.charCodeAt(s)),a=gf(t.charCodeAt(s+1));if(i===void 0||a===void 0){let c=t[s]+t[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function bi(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];ke(o),e+=o.length}let r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){let s=t[n];r.set(s,o),o+=s.length}return r}function ep(t,e,r="opts"){return mf(t,"defaults"),e!==void 0&&mf(e,r),Object.assign(Object.create(null),t,e)}function wi(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=ep({},e,"info");let r=(o,s)=>t(s).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function bf(t=32){Qe(t,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var xi=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function wf(t,e,r){return t&e^~t&r}function xf(t,e,r){return t&e^t&r^e&r}var cn=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,o){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=ho(this.buffer)}update(e){Cr(this),ke(e);let{view:r,buffer:n,blockLen:o}=this,s=e.length,i=!1;for(let a=0;a<s;){let c=Math.min(o-this.pos,s-a);if(c===o){let f=ho(e);for(;o<=s-a;a+=o)this.process(f,a);i=!0;continue}n.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(r,0),this.pos=0,i=!0)}return this.length+=e.length,i&&this.roundClean(),this}digestInto(e){Cr(this),lo(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,r.fill(0,i),this.padOffset>o-i&&(this.process(n,0),r.fill(0)),cf(n,o-8,this.length*8,s),this.process(n,0),this.roundClean();let a=e===r?n:ho(e),c=this.outputLen,f=c/4,l=this.get();if(c%4||f>l.length)throw new Error("invalid outputLen");for(let u=0;u<f;u++)a.setUint32(4*u,l[u],s)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:r,length:n,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=n,e.pos=i,i&&e.buffer.set(r),e}clone(){return this._cloneInto()}},Ef=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Sf=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var tp=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Pt=new Uint32Array(64),Ei=class extends cn{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,r){super(64,e,8,!1),this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,r){for(let u=0;u<16;u++,r+=4)Pt[u]=e.getUint32(r,!1);for(let u=16;u<64;u++){let d=Pt[u-15],p=Pt[u-2],x=Je(d,7)^Je(d,18)^d>>>3,w=Je(p,17)^Je(p,19)^p>>>10;Pt[u]=w+Pt[u-7]+x+Pt[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:f,H:l}=this;for(let u=0;u<64;u++){let d=Je(a,6)^Je(a,11)^Je(a,25),p=l+d+wf(a,c,f)+tp[u]+Pt[u]|0,w=(Je(n,2)^Je(n,13)^Je(n,22))+xf(n,o,s)|0;l=f,f=c,c=a,a=i+p|0,i=s,s=o,o=n,n=p+w|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,f,l)}roundClean(){Ve(Pt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ve(this.buffer)}},Si=class extends Ei{constructor(){super(32,Ef)}};var Af=af(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),rp=Af[0],np=Af[1],Ot=new Uint32Array(80),Nt=new Uint32Array(80),Ai=class extends cn{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,r){super(128,e,16,!1),this.Ah=r[0]|0,this.Al=r[1]|0,this.Bh=r[2]|0,this.Bl=r[3]|0,this.Ch=r[4]|0,this.Cl=r[5]|0,this.Dh=r[6]|0,this.Dl=r[7]|0,this.Eh=r[8]|0,this.El=r[9]|0,this.Fh=r[10]|0,this.Fl=r[11]|0,this.Gh=r[12]|0,this.Gl=r[13]|0,this.Hh=r[14]|0,this.Hl=r[15]|0}get(){let{Ah:e,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:l,Fh:u,Fl:d,Gh:p,Gl:x,Hh:w,Hl:m}=this;return[e,r,n,o,s,i,a,c,f,l,u,d,p,x,w,m]}set(e,r,n,o,s,i,a,c,f,l,u,d,p,x,w,m){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=f|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=p|0,this.Gl=x|0,this.Hh=w|0,this.Hl=m|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,r){for(let b=0;b<16;b++,r+=4)Ot[b]=e.getUint32(r),Nt[b]=e.getUint32(r+=4);for(let b=16;b<80;b++){let v=Ot[b-15]|0,C=Nt[b-15]|0,P=Jt(v,C,1)^Jt(v,C,8)^mi(v,C,7),R=er(v,C,1)^er(v,C,8)^gi(v,C,7),N=Ot[b-2]|0,B=Nt[b-2]|0,I=Jt(N,B,19)^sn(N,B,61)^mi(N,B,6),K=er(N,B,19)^an(N,B,61)^gi(N,B,6),F=lf(R,K,Nt[b-7],Nt[b-16]),q=df(F,P,I,Ot[b-7],Ot[b-16]);Ot[b]=q|0,Nt[b]=F|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:l,Eh:u,El:d,Fh:p,Fl:x,Gh:w,Gl:m,Hh:g,Hl:E}=this;for(let b=0;b<80;b++){let v=Jt(u,d,14)^Jt(u,d,18)^sn(u,d,41),C=er(u,d,14)^er(u,d,18)^an(u,d,41),P=u&p^~u&w,R=d&x^~d&m,N=hf(E,C,R,np[b],Nt[b]),B=pf(N,g,v,P,rp[b],Ot[b]),I=N|0,K=Jt(n,o,28)^sn(n,o,34)^sn(n,o,39),F=er(n,o,28)^an(n,o,34)^an(n,o,39),q=n&s^n&a^s&a,T=o&i^o&c^i&c;g=w|0,E=m|0,w=p|0,m=x|0,p=u|0,x=d|0,{h:u,l:d}=ct(f|0,l|0,B|0,I|0),f=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let U=ff(I,F,T);n=uf(U,B,K,q),o=U|0}({h:n,l:o}=ct(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ct(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ct(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l}=ct(this.Dh|0,this.Dl|0,f|0,l|0),{h:u,l:d}=ct(this.Eh|0,this.El|0,u|0,d|0),{h:p,l:x}=ct(this.Fh|0,this.Fl|0,p|0,x|0),{h:w,l:m}=ct(this.Gh|0,this.Gl|0,w|0,m|0),{h:g,l:E}=ct(this.Hh|0,this.Hl|0,g|0,E|0),this.set(n,o,s,i,a,c,f,l,u,d,p,x,w,m,g,E)}roundClean(){Ve(Ot,Nt)}destroy(){this.destroyed=!0,Ve(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},vi=class extends Ai{constructor(){super(64,Sf)}};var ft=wi(()=>new Si,xi(1));var Ci=wi(()=>new vi,xi(3));function yo(t,e,r=()=>{}){if(!Array.isArray(t))throw new TypeError(`"${e}" expected array, got type=${typeof t}`);for(let n=0;n<t.length;n++)r(t[n],`${e}[${n}]`);return t}var J=(t,e,r)=>ke(t,e,r),_i=Qe;function Cf(t,e=""){if(typeof t!="string"){let r=e&&`"${e}" `;throw new TypeError(r+"expected string, got type="+typeof t)}return t}function Ut(t,e="object"){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`);return t}function rr(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}var fn=po,We=(...t)=>bi(...t),_r=t=>mo(t),Mt=uo,yt=t=>bf(t),go=BigInt(0),vf=BigInt(1),op=t=>t?`"${t}" `:"";function Ke(t,e=""){if(typeof t!="boolean")throw new TypeError(op(e)+"expected boolean, got type="+typeof t);return t}function bo(t){if(typeof t=="bigint"){if(!kt(t))throw new RangeError("positive bigint expected, got "+t)}else _i(t);return t}function bt(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(r+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){let r=e&&`"${e}" `;throw new RangeError(r+"expected safe integer, got "+t)}}function un(t){let e=bo(t).toString(16);return e.length&1?"0"+e:e}function _f(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?go:BigInt("0x"+t)}function ut(t){return _f(po(t))}function lt(t){return _f(po(Ft(ke(t)).reverse()))}function wo(t,e){if(Qe(e),e===0)throw new Error("zero output length is invalid");t=bo(t);let r=e*2,n=t.toString(16);if(n.length>r)throw new RangeError("number is too large");return mo(n.padStart(r,"0"))}function ln(t,e){return wo(t,e).reverse()}function Ft(t){return Uint8Array.from(J(t))}function kt(t){return typeof t=="bigint"&&go<=t}function Ti(t,e,r){return kt(t)&&kt(e)&&kt(r)&&e<=t&&t<r}function dt(t,e,r,n){if(!Ti(e,r,n))throw new RangeError("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Tr(t){if(t<go)throw new Error("expected non-negative bigint, got "+t);return t===go?0:t.toString(2).length}var dn=t=>(bt(t,"n"),(vf<<BigInt(t))-vf);function Tf(t,e,r){if(Qe(t,"hashLen"),Qe(e,"qByteLen"),typeof r!="function")throw new TypeError("hmacFn must be a function");let n=m=>new Uint8Array(m),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(t),f=n(t),l=0,u=()=>{c.fill(1),f.fill(0),l=0},d=(...m)=>r(f,We(c,...m)),p=(m=o)=>{f=d(s,m),c=d(),m.length!==0&&(f=d(i,m),c=d())},x=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let m=0,g=[];for(;m<e;){c=d();let E=c.slice();g.push(E),m+=c.length}return We(...g)};return(m,g)=>{u(),p(m);let E;for(;(E=g(x()))===void 0;)p();return u(),E}}function Be(t,e={},r={},n="object"){Ut(t,n),Ut(e,"fields"),Ut(r,"optFields");function o(i,a,c){let f=n==="object"?`param "${String(i)}"`:`"${n}.${String(i)}"`,l=t[i];if(!Object.hasOwn(t,i)&&(c?l!==void 0:a!=="function"))throw new TypeError(`${f} is invalid: expected own property`);if(c&&l===void 0)return;let u=typeof l;if(u!==a||l===null)throw new TypeError(`${f} is invalid: expected ${a}, got ${u}`)}let s=(i,a)=>Object.entries(i).forEach(([c,f])=>o(c,f,a));s(e,!1),s(r,!0)}var Se=BigInt(0),re=BigInt(1),Kt=BigInt(2),Df=BigInt(3),Li=BigInt(4),If=BigInt(5),sp=BigInt(7),Rf=BigInt(8),ip=BigInt(9),ap=BigInt(15),Pf=BigInt(16),cp=BigInt("0x10000000000000000");function se(t,e){if(e<=Se)throw new Error("mod: expected positive modulus, got "+e);let r=t%e;return r>=Se?r:e+r}function Of(t,e,r){if(r<=re)throw new Error("pow: expected modulus > 1, got "+r);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<Se)throw new Error("invalid exponent, negatives unsupported");if(e===Se)return re;if(e===re)return t;let n=t%r;if(n<Se&&(n+=r),e<cp){let a=re;for(;e>Se;)e&re&&(a=a*n%r),n=n*n%r,e>>=re;return a}let o=[];for(;e>Se;)o.push(Number(e&ap)),e>>=Li;let s=new Array(16);s[0]=re,s[1]=n;for(let a=2;a<16;a++)s[a]=s[a-1]*n%r;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%r,i=i*i%r,i=i*i%r,i=i*i%r;let c=o[a];c!==0&&(i=i*s[c]%r)}return i}function le(t,e,r){if(r<=re)throw new Error("pow2: expected modulus > 1, got "+r);if(e<Se)throw new Error("pow2: expected non-negative exponent, got "+e);let n=t;for(;e-- >Se;)n*=n,n%=r;return n}function Lf(t,e){if(t===Se)throw new Error("invert: expected non-zero number");if(e<=re)throw new Error("invert: expected modulus > 1, got "+e);let r=se(t,e),n=e,o=Se,s=re;for(;r!==Se;){let a=n/r,c=n-r*a,f=o-s*a;n=r,r=c,o=s,s=f}if(n!==re)throw new Error("invert: does not exist");return se(o,e)}function Nf(t,e){if(e<=re)throw new Error("invertCt: expected prime modulus > 1, got "+e);let r=se(t,e);if(r===Se)throw new Error("invertCt: expected non-zero number");let n=Of(r,e-Kt,e);if(se(r*n,e)!==re)throw new Error("invertCt: does not exist");return n}function Bi(t,e,r){let n=t;if(!n.eql(n.sqr(e),r))throw new Error("Cannot find square root")}function Di(t,e){if((t&re)===Se)throw new Error(e+": expected odd modulus, got "+t)}function Uf(t,e){let r=t,n=(r.ORDER+re)/Li,o=r.pow(e,n);return Bi(r,o,e),o}function fp(t,e){let r=t,n=(r.ORDER-If)/Rf,o=r.mul(e,Kt),s=r.pow(o,n),i=r.mul(e,s),a=r.mul(r.mul(i,Kt),s),c=r.mul(i,r.sub(a,r.ONE));return Bi(r,c,e),c}function up(t){let e=Br(t),r=kf(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+sp)/Pf;return((a,c)=>{let f=a,l=f.pow(c,i),u=f.mul(l,n),d=f.mul(l,o),p=f.mul(l,s),x=f.eql(f.sqr(u),c),w=f.eql(f.sqr(d),c);l=f.cmov(l,u,x),u=f.cmov(p,d,w);let m=f.eql(f.sqr(u),c),g=f.cmov(l,u,m);return Bi(f,g,c),g})}function kf(t){if(t<Df)throw new Error("sqrt is not defined for small field");Di(t,"tonelliShanks");let e=t-re,r=0;for(;e%Kt===Se;)e/=Kt,r++;let n=Kt,o=Br(t);for(;hn(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Uf;let s=o.pow(n,e),i=(e+re)/Kt;return function(c,f){let l=c;if(l.is0(f))return f;if(hn(l,f)!==1)throw new Error("Cannot find square root");let u=r,d=l.mul(l.ONE,s),p=l.pow(f,e),x=l.pow(f,i);for(;!l.eql(p,l.ONE);){if(l.is0(p))throw new Error("Cannot find square root: probably non-prime P");let w=1,m=l.sqr(p);for(;!l.eql(m,l.ONE);)if(w++,m=l.sqr(m),w===u)throw new Error("Cannot find square root");let g=re<<BigInt(u-w-1),E=l.pow(d,g);u=w,d=l.sqr(E),p=l.mul(p,d),x=l.mul(x,E)}return x}}function lp(t){return Di(t,"Fp.sqrt"),t%Li===Df?Uf:t%Rf===If?fp:t%Pf===ip?up(t):kf(t)}var Mf=(t,e)=>(se(t,e)&re)===re,dp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Lr(t){if(Ut(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);bt(t.BYTES,"BYTES"),bt(t.BITS,"BITS");for(let e of dp)rr(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=re)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function Eo(t,e,r=!1){Lr(t),yo(e,"nums"),Ke(r,"passZero");let n=t,o=new Array(e.length).fill(r?n.ZERO:void 0),s=e.reduce((a,c,f)=>n.is0(c)?a:(o[f]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return e.reduceRight((a,c,f)=>n.is0(c)?a:(o[f]=n.mul(a,o[f]),n.mul(a,c)),i),o}function hn(t,e){Lr(t);let r=t;Di(r.ORDER,"FpLegendre");let n=(r.ORDER-re)/Kt,o=r.pow(e,n),s=r.eql(o,r.ONE),i=r.eql(o,r.ZERO),a=r.eql(o,r.neg(r.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function hp(t,e){if(e!==void 0&&_i(e),t<=Se)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let r=Tr(t);if(e!==void 0&&e<r)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${r})`);let n=e!==void 0?e:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Bf=new WeakMap,xo=class{ORDER;BITS;BYTES;isLE;ZERO=Se;ONE=re;_lengths;_mod;constructor(e,r={}){if(e<=re)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:o,nByteLength:s}=hp(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return se(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Se<=e&&e<this.ORDER}is0(e){return e===Se}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&re)===re}neg(e){return se(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return se(e*e,this.ORDER)}add(e,r){return se(e+r,this.ORDER)}sub(e,r){return se(e-r,this.ORDER)}mul(e,r){return se(e*r,this.ORDER)}pow(e,r){return Of(e,r,this.ORDER)}div(e,r){return se(e*Lf(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return Lf(e,this.ORDER)}sqrt(e){let r=Bf.get(this);return r||Bf.set(this,r=lp(this.ORDER)),r(this,e)}toBytes(e){return this.isLE?ln(e,this.BYTES):wo(e,this.BYTES)}fromBytes(e,r=!1){J(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let f=new Uint8Array(o);f.set(e,s?0:f.length-e.length),e=f}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?lt(e):ut(e);if(a&&(c=se(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Eo(this,e,!0)}cmov(e,r,n){return Ke(n,"condition"),n?r:e}};function Br(t,e={}){return Object.freeze(xo.prototype),new xo(t,e)}function Ff(t){if(typeof t!="bigint")throw new Error("field order must be bigint");if(t<=re)throw new Error("field order must be greater than 1");let e=Tr(t-re);return Math.ceil(e/8)}function So(t){let e=Ff(t);return e+Math.ceil(e/2)}function Ao(t,e,r=!1){J(t);let n=t.length,o=Ff(e),s=Math.max(So(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?lt(t):ut(t),a=se(i,e-re)+re;return r?ln(a,o):wo(a,o)}var Pi=BigInt(0),pn=BigInt(1),pp=BigInt(4),Ii=16,Kf=128,mp=5,Hf=2**31;function Ht(t){let e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);rr(e.fromAffine,"Point.fromAffine"),rr(e.fromBytes,"Point.fromBytes"),rr(e.fromHex,"Point.fromHex"),Ut(e.BASE,"Point.BASE"),Ut(e.ZERO,"Point.ZERO"),Lr(e.Fp),Lr(e.Fn)}function vo(t,e){Ht(t),zf(e,t);let r=Eo(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function gp(t,e,r=1){if(!Number.isSafeInteger(t)||t<r||t>e)throw new Error("invalid window size, expected ["+r+".."+e+"], got W="+t)}function yp(t,e){let r=t*(4*e+128);if(r>Hf)throw new Error("invalid window size: table would need ~"+Math.ceil(r/2**20)+" MiB, max "+Hf/2**20+" MiB")}function Oi(t,e){if(t!==void 0){rr(t,"randomBytes");try{let r=t(e);if(!Mt(r)||r.length!==e)return}catch{return}return t}}function zf(t,e){yo(t,"points"),t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function bp(t,e,r){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,o)=>{if(!(r===void 0?e.isValid(n):kt(n)&&n<r))throw new Error("invalid scalar at index "+o)})}var qf=new WeakMap;function Ri(t){return qf.get(t)||1}function wp(t,e){let r=t.double(),n=[t];for(let o=1;o<e;o++)n.push(n[o-1].add(r));return n}function xp(t,e){let r=2**e,n=r/2,o=BigInt(r-1),s=[];for(;t>Pi;){let i=0;t&pn&&(i=Number(t&o),i>=n&&(i-=r),t-=BigInt(i)),s.push(i),t>>=pn}return s}function Ep(t,e,r){let n=2**e,o=n/2,s=BigInt(n-1),i=BigInt(e),a=[];for(let c=0;c<r;c++){let f=Number(t&s);t>>=i,f>o&&(f-=n,t+=pn),a.push(f)}if(t!==Pi)throw new Error("invalid wnaf");return a}function Sp(t,e,r){let n=0;for(let s of r)n=Math.max(n,s.length);let o=t;for(let s=n-1;s>=0;s--){s!==n-1&&(o=o.double());for(let i=0;i<r.length;i++){let a=r[i][s];if(a){let c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}var Dr=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,r){Ht(e),this.randomBytes=Oi(r,Ii),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,r,n){let o=Math.ceil(n/r)+1,s=2**(r-1),i=[],a=e;for(let c=0;c<o;c++){let f=a;for(let l=0;l<s;l++)i.push(f),f=f.add(a);a=i[i.length-1].double()}return{W:r,bits:n,windows:o,comp:i}}wnafCachedCT(e,r){let{W:n,windows:o,comp:s}=e,i=2**(n-1),a=Ep(r,n,o),c=this.ZERO,f=this.BASE;for(let l=0;l<o;l++){let u=a[l],d=l*i,p=Math.abs(u)-1,x=s[d];for(let m=1;m<i;m++)x=m===p?s[d+m]:x;let w=x.negate();u===0?f=f.add(s[d]):c=c.add(u<0?w:x)}return{p:c,f}}getWnafPrecomputes(e,r,n,o){let s=this.wnafPrecomputes.get(r),i=s?.find(a=>a.W===e&&a.bits===n);return i||(i=this.buildWnafTable(r,e,n),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(r,s)),s.push(i)),i}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,r){if(this.assertPoint(e),!Ti(r,pn,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,r,n,o){let s=Ri(e);return s===1?this.fixedWindowCT(e,r,n):this.wnafCachedCT(this.getWnafPrecomputes(s,e,n,o),r)}mulCT(e,r,n){return this.validateMulInput(e,r),this.runCT(e,r,this.bits,n)}mulCTBlinded(e,r,n){if(this.validateMulInput(e,r),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+Kf,s=this.randomBytes(Ii);if(!Mt(s)||s.length!==Ii)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;let i=r+ut(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,n)}fixedWindowCT(e,r,n){let o=mp,s=1<<o,i=dn(o),a=new Array(s);a[0]=this.ZERO;for(let l=1;l<s;l++)a[l]=a[l-1].add(e);let c=Math.ceil(n/o),f=this.ZERO;for(let l=c-1;l>=0;l--){if(l!==c-1)for(let p=0;p<o;p++)f=f.double();let u=Number(r>>BigInt(l*o)&i),d=a[0];for(let p=1;p<s;p++)d=p===u?a[p]:d;f=f.add(d)}return{p:f,f}}shouldBlind(e,r){return this.randomBytes===void 0?!1:r===pn?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,r,n,o){return this.shouldBlind(e,n)?this.mulCTBlinded(e,r,o):this.mulCT(e,r,o)}mulUnsafe(e,r,n){if(this.assertPoint(e),!kt(r))throw new Error("invalid scalar");let o=Ri(e);if(o===1||r>=this.Point.Fn.ORDER)return Co(this.Point,[e],[r],!0);let s=this.getWnafPrecomputes(o,e,this.bits,n);return this.wnafCachedCT(s,r).p}setWindowSize(e,r){this.assertPoint(e),gp(r,this.bits);let n=Math.ceil((this.bits+Kf)/r)+1;yp(n*2**(r-1),this.Point.Fp.BYTES),qf.set(e,r),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Ri(e)!==1}};function Co(t,e,r,n=!1){if(Ht(t),zf(e,t),Ke(n,"allowOversized"),bp(r,t.Fn,n?t.Fn.ORDER**pp:void 0),e.length!==r.length)throw new Error("arrays of points and scalars must have equal length");let o=e.map(i=>wp(i,4)),s=r.map(i=>xp(i,4));return Sp(t.ZERO,o,s)}function $f(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Lr(e),e}else return Br(t,{isLE:r})}function _o(t,e,r={},n){if(t!=="weierstrass"&&t!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);Be(r);for(let c of["p","n","h"]){let f=e[c];if(!(kt(f)&&f!==Pi))throw new Error(`CURVE.${c} must be positive bigint`)}let o=$f(e.p,r.Fp,n),s=$f(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function Ir(t,e){return function(n){let o=t(n);return{secretKey:o,publicKey:e(o)}}}var To=BigInt(0),Lo=BigInt(1),Bo=BigInt(2),Ap=BigInt(4),Vf=BigInt(8);function vp(t,e,r,n){let o=t.sqr(r),s=t.sqr(n),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function Wf(t,e={}){Be(e,{},{},"extraOpts");let r=e,n=_o("edwards",t,r,r.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;if(hn(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(hn(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Be(r,{},{uvRatio:"function",randomBytes:"function"});let c=r.randomBytes===void 0?yt:r.randomBytes,f=Bo<<BigInt(o.BYTES*8)-Lo;function l(E){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(E)}let u=r.uvRatio===void 0?(E,b)=>{try{return{isValid:!0,value:o.sqrt(o.div(E,b))}}catch{return{isValid:!1,value:To}}}:r.uvRatio;if(!vp(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");let d=o.eql(i.a,o.neg(o.ONE))?E=>o.neg(E):o.eql(i.a,o.ONE)?E=>E:E=>o.mul(i.a,E);function p(E,b,v=!1){let C=v?Lo:To;return dt("coordinate "+E,b,C,f),b}function x(E){if(!(E instanceof w))throw new Error("EdwardsPoint expected")}class w{static BASE=new w(i.Gx,i.Gy,o.ONE,o.mul(i.Gx,i.Gy));static ZERO=new w(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(b,v,C,P){this.X=p("x",b),this.Y=p("y",v),this.Z=p("z",C,!0),this.T=p("t",P),Object.freeze(this)}static CURVE(){return i}static fromAffine(b){if(b instanceof w)throw new Error("extended point not allowed");let{x:v,y:C}=b||{};return p("x",v),p("y",C),new w(v,C,o.ONE,o.mul(v,C))}static fromBytes(b,v=!1){let C=o.BYTES,{a:P,d:R}=i;b=Ft(J(b,C,"point")),Ke(v,"zip215");let N=Ft(b),B=b[C-1];N[C-1]=B&-129;let I=lt(N),K=v?f:o.ORDER;dt("point.y",I,To,K);let F=o.sqr(I),q=o.sub(F,o.ONE),T=o.sub(o.mulN(R,F),P),{isValid:U,value:L}=u(q,T);if(!U)throw new Error("bad point: invalid y coordinate");let _=l(L),H=(B&128)!==0;if(!v&&o.is0(L)&&H)throw new Error("bad point: x=0 and x_0=1");return H!==_&&(L=o.neg(L)),w.fromAffine({x:L,y:I})}static fromHex(b,v=!1){return w.fromBytes(_r(b),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=6,v=!0){return g.setWindowSize(this,b),v||this.multiply(Bo),this}assertValidity(){let b=this,{a:v,d:C}=i;if(b.is0())throw new Error("bad point: ZERO");let{X:P,Y:R,Z:N,T:B}=b,I=o.sqr(P),K=o.sqr(R),F=o.sqr(N),q=o.sqr(F),T=o.mul(I,v),U=o.mul(o.add(T,K),F),L=o.add(q,o.mul(C,o.mul(I,K)));if(!o.eql(U,L))throw new Error("bad point: equation left != right (1)");let _=o.mul(P,R),H=o.mul(N,B);if(!o.eql(_,H))throw new Error("bad point: equation left != right (2)")}equals(b){x(b);let{X:v,Y:C,Z:P}=this,{X:R,Y:N,Z:B}=b,I=o.mul(v,B),K=o.mul(R,P),F=o.mul(C,B),q=o.mul(N,P);return o.eql(I,K)&&o.eql(F,q)}is0(){return this.equals(w.ZERO)}negate(){return new w(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:b,Y:v,Z:C}=this,P=o.sqr(b),R=o.sqr(v),N=o.mul(o.sqr(C),Bo),B=d(P),I=o.addN(b,v),K=o.sub(o.subN(o.sqr(I),P),R),F=o.addN(B,R),q=o.subN(F,N),T=o.subN(B,R),U=o.mul(K,q),L=o.mul(F,T),_=o.mul(K,T),H=o.mul(q,F);return new w(U,L,H,_)}add(b){x(b);let{d:v}=i,{X:C,Y:P,Z:R,T:N}=this,{X:B,Y:I,Z:K,T:F}=b,q=o.mul(C,B),T=o.mul(P,I),U=o.mul(o.mulN(N,v),F),L=o.mul(R,K),_=o.sub(o.subN(o.mulN(o.addN(C,P),o.addN(B,I)),q),T),H=o.subN(L,U),D=o.addN(L,U),S=o.sub(T,d(q)),h=o.mul(_,H),y=o.mul(D,S),A=o.mul(_,S),O=o.mul(H,D);return new w(h,y,O,A)}subtract(b){return x(b),this.add(b.negate())}multiply(b){if(!s.isValidNot0(b))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:C}=g.mulSecret(this,b,a,m);return m([v,C])[0]}multiplyUnsafe(b){if(!s.isValid(b))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return b===To?w.ZERO:this.is0()||b===Lo?this:g.mulUnsafe(this,b,m)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return g.mulUnsafe(this,i.n).is0()}toAffine(b){let v=this,C=b;if(C!=null&&typeof C!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof C);let{X:P,Y:R,Z:N}=v,B=v.is0();C==null&&(C=B?o.create(Vf):o.inv(N));let I=o.mul(P,C),K=o.mul(R,C),F=o.mul(N,C);if(B)return{x:o.ZERO,y:o.ONE};if(!o.eql(F,o.ONE))throw new Error("invZ was invalid");return{x:I,y:K}}clearCofactor(){return a===Lo?this:a===Bo?this.double():a===Ap?this.double().double():a===Vf?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:b,y:v}=this.toAffine(),C=o.toBytes(v);return C[C.length-1]|=l(b)?128:0,C}toHex(){return fn(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let m=E=>vo(w,E),g=new Dr(w,c);return g.bits>=6&&w.BASE.precompute(6),Object.freeze(w.prototype),Object.freeze(w),w}function jf(t,e,r={}){if(Ht(t),typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=r;Be(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=t,f=n.outputLen,l=2*a.BYTES;if(f!==void 0&&(bt(f,"hash.outputLen"),f!==l))throw new Error(`hash.outputLen must be ${l}, got ${f}`);let u=o.randomBytes===void 0?yt:o.randomBytes,d=o.toMontgomery,p=o.toMontgomerySecret,x=o.adjustScalarBytes===void 0?T=>T:o.adjustScalarBytes,w=o.domain===void 0?(T,U,L)=>{if(Ke(L,"phflag"),U.length||L)throw new Error("Contexts/pre-hash are not supported");return T}:o.domain;function m(T){return c.create(lt(T))}function g(T){let U=B.secretKey;J(T,B.secretKey,"secretKey");let L=J(n(T),2*U,"hashedSecretKey"),_=x(L.slice(0,U)),H=L.slice(U,2*U),D=m(_);return{head:_,prefix:H,scalar:D}}function E(T){let{head:U,prefix:L,scalar:_}=g(T),H=i.multiply(_),D=H.toBytes();return{head:U,prefix:L,scalar:_,point:H,pointBytes:D}}function b(T){return E(T).pointBytes}function v(T=Uint8Array.of(),...U){let L=We(...U);return m(n(w(L,J(T,void 0,"context"),!!s)))}function C(T,U,L={}){Be(L,{},{},"options"),T=Ft(J(T,void 0,"message")),s&&(T=s(T));let{prefix:_,scalar:H,pointBytes:D}=E(U),S=v(L.context,_,T),h=i.multiply(S).toBytes(),y=v(L.context,h,D,T),A=c.create(S+y*H);if(!c.isValid(A))throw new Error("sign failed: invalid s");let O=We(h,c.toBytes(A));return J(O,B.signature,"result")}let P={zip215:o.zip215};function R(T,U,L,_=P){Be(_);let{context:H}=_,D=_.zip215===void 0?!!P.zip215:_.zip215,S=B.signature;T=J(T,S,"signature"),U=J(U,void 0,"message"),L=J(L,B.publicKey,"publicKey"),D!==void 0&&Ke(D,"zip215"),s&&(U=s(U));let h=S/2,y=T.subarray(0,h),A=lt(T.subarray(h,S)),O,k,M;try{O=t.fromBytes(L,D),k=t.fromBytes(y,D),M=i.multiplyUnsafe(A)}catch{return!1}if(!D&&O.isSmallOrder())return!1;let $=v(H,y,L,U);return k.add(O.multiplyUnsafe($)).subtract(M).clearCofactor().is0()}let N=a.BYTES,B={secretKey:N,publicKey:N,signature:2*N,seed:N};function I(T){return T=T===void 0?u(B.seed):T,J(T,B.seed,"seed")}function K(T){return Mt(T)&&T.length===B.secretKey}function F(T,U){try{return!!t.fromBytes(T,U===void 0?P.zip215:U)}catch{return!1}}let q={getExtendedPublicKey:E,randomSecretKey:I,isValidSecretKey:K,isValidPublicKey:F,toMontgomery(T){if(d===void 0)throw new Error("Montgomery conversion is not supported for this curve");return d(t.fromBytes(T))},toMontgomerySecret(T){if(p===void 0)throw new Error("Montgomery conversion is not supported for this curve");return p(T)}};return Object.freeze(B),Object.freeze(q),Object.freeze({keygen:Ir(I,b),getPublicKey:b,sign:C,verify:R,utils:q,Point:t,lengths:B})}var nr=BigInt(0),je=BigInt(1),Do=BigInt(2);function Gf(t,e){return t+e-(e>>je<<je)}function Cp(t){let e=BigInt(6)*t;return(r,n,o)=>{let s=n+o,a=((e+o-n)*r+n)%t;return{x_2:a,x_3:s-a}}}function _p(t){return Be(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...t})}function Yf(t){let e=_p(t),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=e.scalarMultBase,c=n==="x25519";if(!c&&n!=="x448")throw new Error("invalid type");let f=i===void 0?yt:i,l=c?255:448,u=Cp(r),d=c?32:56,p=BigInt(c?9:5),x=BigInt(c?121665:39081),w=c?Do**BigInt(254):Do**BigInt(447),m=c?BigInt(8)*(Do**BigInt(251)-je):BigInt(4)*(Do**BigInt(445)-je),g=w+m+je,E=L=>se(L,r),b=v(p);function v(L){return ln(E(L),d)}function C(L){let _=Ft(J(L,d,"uCoordinate"));return c&&(_[31]&=127),E(lt(_))}function P(L){return lt(o(Ft(J(L,d,"scalar"))))}let R=new Set(c?[nr,je,r-je,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[nr,je,r-je]);function N(L,_){let H=C(_);if(R.has(H))throw new Error("invalid private or public key received");let D=F(H,P(L));if(D===nr)throw new Error("invalid private or public key received");return v(D)}function B(L){if(a===void 0)return N(L,b);let _=P(L);dt("scalar",_,w,g);let H=E(a(_));if(H===nr)throw new Error("invalid private or public key received");return v(H)}let I=B,K=N;function F(L,_){dt("u",L,nr,r),dt("scalar",_,w,g);let H=_,D=L,S=je,h=nr,y=L,A=je,O=H^H>>je;for(let $=BigInt(l-1);$>=nr;$--){let z=Gf(r,O>>$);({x_2:S,x_3:y}=u(z,S,y)),{x_2:h,x_3:A}=u(z,h,A);let W=S+h,G=E(W*W),ue=S-h,ie=E(ue*ue),ye=G-ie,Me=y+A,fe=y-A,he=E(fe*W),gr=E(Me*ue),Zr=he+gr,Tt=he-gr;y=E(Zr*Zr),A=E(D*E(Tt*Tt)),S=E(G*ie),h=E(ye*(G+E(x*ye)))}let k=Gf(r,H);({x_2:S,x_3:y}=u(k,S,y)),{x_2:h,x_3:A}=u(k,h,A);let M=s(h);return E(S*M)}let q={secretKey:d,publicKey:d,seed:d},T=L=>(L=L===void 0?f(d):L,J(L,q.seed,"seed"),L),U={randomSecretKey:T};return Object.freeze(q),Object.freeze(U),Object.freeze({keygen:Ir(T,I),getSharedSecret:K,getPublicKey:I,scalarMult:N,scalarMultBase:B,utils:U,GuBytes:b.slice(),lengths:q})}var Xf=BigInt(0),Ni=BigInt(1),Zf=BigInt(2),Tp=BigInt(3),Lp=BigInt(5),Bp=BigInt(8),Io=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Dp={p:Io,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Bp,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function eu(t){let e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=Io,a=t*t%s*t%s,c=le(a,Zf,s)*a%s,f=le(c,Ni,s)*t%s,l=le(f,Lp,s)*f%s,u=le(l,e,s)*l%s,d=le(u,r,s)*u%s,p=le(d,n,s)*d%s,x=le(p,o,s)*p%s,w=le(x,o,s)*p%s,m=le(w,e,s)*l%s;return{pow_p_5_8:le(m,Zf,s)*t%s,b2:a}}function Ui(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var Qf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ip(t,e){let r=Io,n=se(e*e*e,r),o=se(n*n*e,r),s=eu(t*o).pow_p_5_8,i=se(t*n*s,r),a=se(e*i*i,r),c=i,f=se(i*Qf,r),l=a===t,u=a===se(-t,r),d=a===se(-t*Qf,r);return l&&(i=c),(u||d)&&(i=f),Mf(i,r)&&(i=se(-i,r)),{isValid:l||u,value:i}}var mn=Wf(Dp,{uvRatio:Ip}),Jf=mn.Fp;function Rp(t){let{y:e}=t;return Jf.toBytes(Jf.div(Ni+e,Ni-e))}function Pp(t){let e=mn.Fp.BYTES;return ke(t,e),Ui(Ci(t.subarray(0,e))).subarray(0,e)}function Op(t){return jf(mn,Ci,Object.assign({adjustScalarBytes:Ui,toMontgomery:Rp,toMontgomerySecret:Pp,zip215:!0},t))}var tu=Op({});var gn=(()=>{let t=Io,e=r=>{let{pow_p_5_8:n,b2:o}=eu(r);return se(le(n,Tp,t)*o,t)};return Yf({P:t,type:"x25519",powPminus2:e,adjustScalarBytes:Ui,scalarMultBase:r=>{let n=se(r,mn.Fn.ORDER);if(n===Xf)return Xf;let o=mn.BASE.multiply(n);return se((o.Z+o.Y)*e(se(o.Z-o.Y,t)),t)}})})();var yn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Ro=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ge={get(t=globalThis){let e=t.crypto;if(e?.subtle==null)throw new Ro("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var Po=32;var ki,Np=(async()=>{try{return await Ge.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Up(t,e,r){if(t.buffer instanceof ArrayBuffer){let n=await Ge.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await Ge.get().subtle.verify({name:"Ed25519"},n,Ce(e),Ce(r instanceof Uint8Array?r:r.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function kp(t,e,r){return tu.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}async function ru(t,e,r){return ki==null&&(ki=await Np),ki?Up(t,e,r):kp(t,e,r)}function Oo(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var No=class{type="Ed25519";raw;constructor(e){this.raw=Mi(e,Po)}toMultihash(){return Ze.digest(Rt(this))}toCID(){return Ee.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ae(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();let o=ru(this.raw,r,e);return Oo(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Fi(t){return t=Mi(t,Po),new No(t)}function Mi(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new Z(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}var Fp=Math.pow(2,7),Kp=Math.pow(2,14),Hp=Math.pow(2,21),Ki=Math.pow(2,28),Hi=Math.pow(2,35),$i=Math.pow(2,42),zi=Math.pow(2,49),ne=128,De=127;function de(t){if(t<Fp)return 1;if(t<Kp)return 2;if(t<Hp)return 3;if(t<Ki)return 4;if(t<Hi)return 5;if(t<$i)return 6;if(t<zi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Rr(t,e,r=0){switch(de(t)){case 8:e[r++]=t&255|ne,t/=128;case 7:e[r++]=t&255|ne,t/=128;case 6:e[r++]=t&255|ne,t/=128;case 5:e[r++]=t&255|ne,t/=128;case 4:e[r++]=t&255|ne,t>>>=7;case 3:e[r++]=t&255|ne,t>>>=7;case 2:e[r++]=t&255|ne,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function $p(t,e,r=0){switch(de(t)){case 8:e.set(r++,t&255|ne),t/=128;case 7:e.set(r++,t&255|ne),t/=128;case 6:e.set(r++,t&255|ne),t/=128;case 5:e.set(r++,t&255|ne),t/=128;case 4:e.set(r++,t&255|ne),t>>>=7;case 3:e.set(r++,t&255|ne),t>>>=7;case 2:e.set(r++,t&255|ne),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function qi(t,e){let r=t[e],n=0;if(n+=r&De,r<ne||(r=t[e+1],n+=(r&De)<<7,r<ne)||(r=t[e+2],n+=(r&De)<<14,r<ne)||(r=t[e+3],n+=(r&De)<<21,r<ne)||(r=t[e+4],n+=(r&De)*Ki,r<ne)||(r=t[e+5],n+=(r&De)*Hi,r<ne)||(r=t[e+6],n+=(r&De)*$i,r<ne)||(r=t[e+7],n+=(r&De)*zi,r<ne))return n;throw new RangeError("Could not decode varint")}function zp(t,e){let r=t.get(e),n=0;if(n+=r&De,r<ne||(r=t.get(e+1),n+=(r&De)<<7,r<ne)||(r=t.get(e+2),n+=(r&De)<<14,r<ne)||(r=t.get(e+3),n+=(r&De)<<21,r<ne)||(r=t.get(e+4),n+=(r&De)*Ki,r<ne)||(r=t.get(e+5),n+=(r&De)*Hi,r<ne)||(r=t.get(e+6),n+=(r&De)*$i,r<ne)||(r=t.get(e+7),n+=(r&De)*zi,r<ne))return n;throw new RangeError("Could not decode varint")}function Uo(t,e,r=0){return e==null&&(e=xe(de(t))),e instanceof Uint8Array?Rr(t,e,r):$p(t,e,r)}function wt(t,e=0){return t instanceof Uint8Array?qi(t,e):zp(t,e)}var Vi=new Float32Array([-0]),$t=new Uint8Array(Vi.buffer);function ou(t,e,r){Vi[0]=t,e[r]=$t[0],e[r+1]=$t[1],e[r+2]=$t[2],e[r+3]=$t[3]}function su(t,e){return $t[0]=t[e],$t[1]=t[e+1],$t[2]=t[e+2],$t[3]=t[e+3],Vi[0]}var Wi=new Float64Array([-0]),Ie=new Uint8Array(Wi.buffer);function iu(t,e,r){Wi[0]=t,e[r]=Ie[0],e[r+1]=Ie[1],e[r+2]=Ie[2],e[r+3]=Ie[3],e[r+4]=Ie[4],e[r+5]=Ie[5],e[r+6]=Ie[6],e[r+7]=Ie[7]}function au(t,e){return Ie[0]=t[e],Ie[1]=t[e+1],Ie[2]=t[e+2],Ie[3]=t[e+3],Ie[4]=t[e+4],Ie[5]=t[e+5],Ie[6]=t[e+6],Ie[7]=t[e+7],Wi[0]}var qp=BigInt(Number.MAX_SAFE_INTEGER),Vp=BigInt(Number.MIN_SAFE_INTEGER),$e=class t{lo;hi;constructor(e,r){this.lo=e|0,this.hi=r|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?e<16384?e<128?1:2:e<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return or;if(e<qp&&e>Vp)return this.fromNumber(Number(e));let r=e<0n;r&&(e=-e);let n=e>>32n,o=e-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>cu&&(o=0n,++n>cu&&(n=0n))),new t(Number(o),Number(n))}static fromNumber(e){if(e===0)return or;let r=e<0;r&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new t(n,o)}static from(e){return typeof e=="number"?t.fromNumber(e):typeof e=="bigint"?t.fromBigInt(e):typeof e=="string"?t.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new t(e.low>>>0,e.high>>>0):or}},or=new $e(0,0);or.toBigInt=function(){return 0n};or.zzEncode=or.zzDecode=function(){return this};or.length=function(){return 1};var cu=4294967296n;function fu(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:(r&64512)===55296&&(t.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function uu(t,e,r){if(r-e<1)return"";let o,s=[],i=0,a;for(;e<r;)a=t[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|t[e++]&63:a>239&&a<365?(a=((a&7)<<18|(t[e++]&63)<<12|(t[e++]&63)<<6|t[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(t[e++]&63)<<6|t[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function ji(t,e,r){let n=r,o,s;for(let i=0;i<t.length;++i)o=t.charCodeAt(i),o<128?e[r++]=o:o<2048?(e[r++]=o>>6|192,e[r++]=o&63|128):(o&64512)===55296&&((s=t.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[r++]=o>>18|240,e[r++]=o>>12&63|128,e[r++]=o>>6&63|128,e[r++]=o&63|128):(e[r++]=o>>12|224,e[r++]=o>>6&63|128,e[r++]=o&63|128);return r-n}function et(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function ko(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}var Gi=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=Ce(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,et(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw et(this,4);return ko(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw et(this,4);return ko(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw et(this,4);let e=su(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw et(this,4);let e=au(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),r=this.pos,n=this.pos+e;if(n>this.len)throw et(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let e=this.bytes();return uu(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw et(this,e);this.pos+=e}else do if(this.pos>=this.len)throw et(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new $e(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw et(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,e}if(this.len-this.pos>4){for(;r<5;++r)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;r<5;++r){if(this.pos>=this.len)throw et(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw et(this,8);let e=ko(this.buf,this.pos+=4),r=ko(this.buf,this.pos+=4);return new $e(e,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=qi(this.buf,this.pos);return this.pos+=de(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function wn(t){return new Gi(t instanceof Uint8Array?t:t.subarray())}function tt(t,e,r){let n=wn(t);return e.decode(n,void 0,r)}function Yi(t){let e=t??8192,r=e>>>1,n,o=e;return function(i){if(i<1||i>r)return xe(i);o+i>e&&(n=xe(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var sr=class{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}};function Xi(){}var Qi=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Wp=Yi();function jp(t){return globalThis.Buffer!=null?xe(t):Wp(t)}var En=class{len;head;tail;states;constructor(){this.len=0,this.head=new sr(Xi,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new sr(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Ji((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Mo,10,$e.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let r=$e.fromBigInt(e);return this._push(Mo,r.length(),r)}uint64Number(e){return this._push(Rr,de(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let r=$e.fromBigInt(e).zzEncode();return this._push(Mo,r.length(),r)}sint64Number(e){let r=$e.fromNumber(e).zzEncode();return this._push(Mo,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Zi,1,e?1:0)}fixed32(e){return this._push(xn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let r=$e.fromBigInt(e);return this._push(xn,4,r.lo)._push(xn,4,r.hi)}fixed64Number(e){let r=$e.fromNumber(e);return this._push(xn,4,r.lo)._push(xn,4,r.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(ou,4,e)}double(e){return this._push(iu,8,e)}bytes(e){let r=e.length>>>0;return r===0?this._push(Zi,1,0):this.uint32(r)._push(Yp,r,e)}string(e){let r=fu(e);return r!==0?this.uint32(r)._push(ji,r,e):this._push(Zi,1,0)}fork(){return this.states=new Qi(this),this.head=this.tail=new sr(Xi,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new sr(Xi,0,0),this.len=0),this}ldelim(){let e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=r,this.len+=n),this}finish(){let e=this.head.next,r=jp(this.len),n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}};function Zi(t,e,r){e[r]=t&255}function Gp(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}var Ji=class extends sr{next;constructor(e,r){super(Gp,e,r),this.next=void 0}};function Mo(t,e,r){for(;t.hi!==0;)e[r++]=t.lo&127|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[r++]=t.lo&127|128,t.lo=t.lo>>>7;e[r++]=t.lo}function xn(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function Yp(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(En.prototype.bytes=function(t){let e=t.length>>>0;return this.uint32(e),e>0&&this._push(Xp,e,t),this},En.prototype.string=function(t){let e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(Zp,e,t),this});function Xp(t,e,r){e.set(t,r)}function Zp(t,e,r){t.length<40?ji(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(Q(t),r)}function ea(){return new En}function rt(t,e){let r=ea();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}function*nt(t,e,r){let n=wn(t);yield*e.stream(n,void 0,".",r)}var Fo={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Ko(t,e,r,n,o){return{name:t,type:e,encode:r,decode:n,stream:o}}function ir(t){function e(s){if(t[s.toString()]==null)throw new Error("Invalid enum value");return t[s]}let r=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i,a){};return Ko("enum",Fo.VARINT,r,n,o)}function ot(t,e,r){return Ko("message",Fo.LENGTH_DELIMITED,t,e,r)}var ar=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var pe;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(pe||(pe={}));var ta;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(ta||(ta={}));(function(t){t.codec=()=>ir(ta)})(pe||(pe={}));var ht;(function(t){let e;t.codec=()=>(e==null&&(e=ot((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),pe.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=pe.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:pe.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function r(s){return rt(s,t.codec())}t.encode=r;function n(s,i){return tt(s,t.codec(),i)}t.decode=n;function o(s,i){return nt(s,t.codec(),i)}t.stream=o})(ht||(ht={}));var ra;(function(t){let e;t.codec=()=>(e==null&&(e=ot((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),pe.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{c.Type=pe.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Type`,value:pe.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(l&7);break}}}})),e);function r(s){return rt(s,t.codec())}t.encode=r;function n(s,i){return tt(s,t.codec(),i)}t.decode=n;function o(s,i){return nt(s,t.codec(),i)}t.stream=o})(ra||(ra={}));var An={};Oe(An,{MAX_RSA_KEY_SIZE:()=>na,generateRSAKeyPair:()=>gu,jwkToJWKKeyPair:()=>yu,jwkToPkcs1:()=>tm,jwkToPkix:()=>aa,jwkToRSAPrivateKey:()=>la,pkcs1MessageToJwk:()=>sa,pkcs1MessageToRSAPrivateKey:()=>ca,pkcs1ToJwk:()=>em,pkcs1ToRSAPrivateKey:()=>mu,pkixMessageToJwk:()=>ia,pkixMessageToRSAPublicKey:()=>ua,pkixToJwk:()=>rm,pkixToRSAPublicKey:()=>fa});var Pr=class{type="RSA";jwk;_raw;_multihash;constructor(e,r){this.jwk=e,this._multihash=r}get raw(){return this._raw==null&&(this._raw=An.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Ee.createV1(114,this._multihash)}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ae(this.raw,e.raw)}verify(e,r,n){return pu(this.jwk,r,e,n)}},Sn=class{type="RSA";jwk;_raw;publicKey;constructor(e,r){this.jwk=e,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=An.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ae(this.raw,e.raw)}sign(e,r){return hu(this.jwk,e,r)}};var na=8192,oa=18,Qp=1062,Jp=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function em(t){let e=gt(t);return sa(e)}function sa(t){return{n:j(t[1],"base64url"),e:j(t[2],"base64url"),d:j(t[3],"base64url"),p:j(t[4],"base64url"),q:j(t[5],"base64url"),dp:j(t[6],"base64url"),dq:j(t[7],"base64url"),qi:j(t[8],"base64url"),kty:"RSA"}}function tm(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 Z("JWK was missing components");return It([Fe(Uint8Array.from([0])),Fe(Q(t.n,"base64url")),Fe(Q(t.e,"base64url")),Fe(Q(t.d,"base64url")),Fe(Q(t.p,"base64url")),Fe(Q(t.q,"base64url")),Fe(Q(t.dp,"base64url")),Fe(Q(t.dq,"base64url")),Fe(Q(t.qi,"base64url"))]).subarray()}function rm(t){let e=gt(t,{offset:0});return ia(e)}function ia(t){let e=gt(t[1],{offset:0});return{kty:"RSA",n:j(e[0],"base64url"),e:j(e[1],"base64url")}}function aa(t){if(t.n==null||t.e==null)throw new Z("JWK was missing components");return It([Jp,co(It([Fe(Q(t.n,"base64url")),Fe(Q(t.e,"base64url"))]))]).subarray()}function mu(t){let e=gt(t);return ca(e)}function ca(t){let e=sa(t);return la(e)}function fa(t,e){if(t.byteLength>=Qp)throw new jt("Key size is too large");let r=gt(t,{offset:0});return ua(r,t,e)}function ua(t,e,r){let n=ia(t);if(r==null){let o=ft(ht.encode({Type:pe.RSA,Data:e}));r=Ne(oa,o)}return new Pr(n,r)}function la(t){if(wu(t)>na)throw new Z("Key size is too large");let e=yu(t),r=ft(ht.encode({Type:pe.RSA,Data:aa(e.publicKey)})),n=Ne(oa,r);return new Sn(e.privateKey,new Pr(e.publicKey,n))}async function gu(t){if(t>na)throw new Z("Key size is too large");let e=await bu(t),r=ft(ht.encode({Type:pe.RSA,Data:aa(e.publicKey)})),n=Ne(oa,r);return new Sn(e.privateKey,new Pr(e.publicKey,n))}function yu(t){if(t==null)throw new Z("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function bu(t,e){let r=await Ge.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:t,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await nm(r,e);return{privateKey:n[0],publicKey:n[1]}}async function hu(t,e,r){let n=await Ge.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let o=await Ge.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Ce(e instanceof Uint8Array?e:e.subarray()));return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function pu(t,e,r,n){let o=await Ge.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ge.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,Ce(e),Ce(r instanceof Uint8Array?r:r.subarray()));return n?.signal?.throwIfAborted(),s}async function nm(t,e){if(t.privateKey==null||t.publicKey==null)throw new Z("Private and public key are required");let r=await Promise.all([Ge.get().subtle.exportKey("jwk",t.privateKey),Ge.get().subtle.exportKey("jwk",t.publicKey)]);return e?.signal?.throwIfAborted(),r}function wu(t){if(t.kty!=="RSA")throw new Z("invalid key type");if(t.n==null)throw new Z("invalid key modulus");return Q(t.n,"base64url").length*8}var Ho=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(tr(e),ke(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Ve(o)}update(e){return Cr(this),this.iHash.update(e),this}digestInto(e){Cr(this),lo(e,this),this.finished=!0;let r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},vn=(()=>{let t=((e,r,n)=>new Ho(e,r).update(n).digest());return t.create=(e,r)=>new Ho(e,r),t})();var om=BigInt(0),da=class extends Error{constructor(e=""){super(e)}},xt={Err:da,_tlv:{encode:(t,e)=>{let{Err:r}=xt;if(bt(t,"tag"),t<0||t>255)throw new r("tlv.encode: wrong tag");if(Cf(e,"data"),e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,o=un(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?un(o.length/2|128):"";return un(t)+s+o+e},decode(t,e){let{Err:r}=xt;e=J(e,void 0,"DER data");let n=0;if(t<0||t>255)throw new r("tlv.decode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let f=e.subarray(n,n+c);if(f.length!==c)throw new r("tlv.decode: length bytes not complete");if(f[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let l of f)i=i<<8|l;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(t){let{Err:e}=xt;if(bo(t),t<om)throw new e("integer: negative integers are not allowed");let r=un(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=xt;if(t.length<1)throw new e("invalid signature integer: empty");if(t[0]&128)throw new e("invalid signature integer: negative");if(t.length>1&&t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return ut(t)}},toSig(t,e){let{Err:r,_int:n,_tlv:o}=xt;if(e!==void 0&&(bt(e,"maxScalarBytes"),e<1))throw new r("invalid signature: maxScalarBytes must be positive");let s=J(t,void 0,"signature"),{v:i,l:a}=o.decode(48,s);if(a.length)throw new r("invalid signature: left bytes after parsing");let{v:c,l:f}=o.decode(2,i),{v:l,l:u}=o.decode(2,f);if(u.length)throw new r("invalid signature: left bytes after parsing");if(e!==void 0&&(c.length>e||l.length>e))throw new r("invalid signature: integer too large");return{r:n.decode(c),s:n.decode(l)}},hexFromSig(t){let{_tlv:e,_int:r}=xt;Be(t,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),s=n+o;return e.encode(48,s)}},$o=(Object.freeze(xt._tlv),Object.freeze(xt._int),Object.freeze(xt));var xu=(t,e)=>(t+(t>=0?e:-e)/Eu)/e;function sm(t,e,r){dt("scalar",t,Et,r);let[[n,o],[s,i]]=e,a=xu(i*t,r),c=xu(-o*t,r),f=t-a*n-c*s,l=-a*o-c*i,u=f<Et,d=l<Et;u&&(f=-f),d&&(l=-l);let p=dn(Math.ceil(Tr(r)/2))+cr;if(f<Et||f>=p||l<Et||l>=p)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:u,k1:f,k2neg:d,k2:l}}function ma(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function ha(t,e){Be(t);let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Ke(r.lowS,"lowS"),Ke(r.prehash,"prehash"),r.format!==void 0&&ma(r.format),r}var Et=BigInt(0),cr=BigInt(1),Eu=BigInt(2),pa=BigInt(3),im=BigInt(4);function Su(t,e={}){let r=_o("weierstrass",t,e),n=r.Fp,o=r.Fn,s=r.CURVE,{h:i,n:a}=s;Be(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:f,clearCofactor:l,isTorsionFree:u,fromBytes:d,toBytes:p}=e,x=e.randomBytes===void 0?yt:e.randomBytes;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let w=c?{beta:c.beta,basises:c.basises.map(S=>[...S])}:void 0,m=vu(n,o);function g(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function E(S,h,y){if(h.is0()){if(!f)throw new Error("bad point: ZERO");return Uint8Array.of(0)}let{x:A,y:O}=h.toAffine(),k=n.toBytes(A);if(Ke(y,"isCompressed"),y){g();let M=!n.isOdd(O);return We(Au(M),k)}else return We(Uint8Array.of(4),k,n.toBytes(O))}function b(S){J(S,void 0,"Point");let{publicKey:h,publicKeyUncompressed:y}=m,A=S.length,O=S[0],k=S.subarray(1);if(f&&A===1&&O===0)return{x:n.ZERO,y:n.ZERO};if(A===h&&(O===2||O===3)){let M=n.fromBytes(k);if(!n.isValid(M))throw new Error("bad point: is not on curve, wrong x");let $=N(M),z;try{z=n.sqrt($)}catch(ue){let ie=ue instanceof Error?": "+ue.message:"";throw new Error("bad point: is not on curve, sqrt error"+ie)}g();let W=n.isOdd(z);return(O&1)===1!==W&&(z=n.neg(z)),{x:M,y:z}}else if(A===y&&O===4){let M=n.BYTES,$=n.fromBytes(k.subarray(0,M)),z=n.fromBytes(k.subarray(M,M*2));if(!B($,z))throw new Error("bad point: is not on curve");return{x:$,y:z}}else throw new Error(`bad point: got length ${A}, expected compressed=${h} or uncompressed=${y}`)}let v=p===void 0?E:p,C=d===void 0?b:d,P=n.mul(s.b,pa),R=n.is0(s.a)?S=>n.ZERO:S=>n.mul(s.a,S);function N(S){let h=n.sqr(S),y=n.mul(h,S);return n.add(n.add(y,n.mul(S,s.a)),s.b)}function B(S,h){let y=n.sqr(h),A=N(S);return n.eql(y,A)}if(!B(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let I=n.mul(n.pow(s.a,pa),im),K=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(I,K)))throw new Error("bad curve params: a or b");function F(S,h,y=!1){if(!n.isValid(h)||y&&n.is0(h))throw new Error(`bad point coordinate ${S}`);return typeof h=="object"&&h!==null?n.create(h):h}function q(S){if(!(S instanceof _))throw new Error("Weierstrass Point expected")}function T(S){if(!w||!w.basises)throw new Error("no endo");return sm(S,w.basises,o.ORDER)}function U(S,h,y,A){if(!o.isValid(A))throw new RangeError("invalid scalar: out of range");if(w){let{k1neg:O,k1:k,k2neg:M,k2:$}=T(A),z=new _(n.mul(y.X,w.beta),y.Y,y.Z);S.push(O?y.negate():y,M?z.negate():z),h.push(k,$)}else S.push(y),h.push(A)}let L=new WeakSet;class _{static BASE=new _(s.Gx,s.Gy,n.ONE);static ZERO=new _(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(h,y,A){this.X=F("x",h),this.Y=F("y",y,!0),this.Z=F("z",A),Object.freeze(this)}static CURVE(){return s}static fromAffine(h){let{x:y,y:A}=h||{};if(!h||!n.isValid(y)||!n.isValid(A))throw new Error("invalid affine point");if(h instanceof _)throw new Error("projective point not allowed");return n.is0(y)&&n.is0(A)?_.ZERO:new _(y,A,n.ONE)}static fromBytes(h){let y=_.fromAffine(C(J(h,void 0,"point")));return y.assertValidity(),y}static fromHex(h){return _.fromBytes(_r(h))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=6,y=!0){return D.setWindowSize(this,h),y||this.multiply(pa),this}assertValidity(){let h=this;if(h.is0()){if(f&&n.is0(h.X)&&n.eql(h.Y,n.ONE)&&n.is0(h.Z))return;throw new Error("bad point: ZERO")}if(L.has(h))return;let{x:y,y:A}=h.toAffine();if(!n.isValid(y)||!n.isValid(A))throw new Error("bad point: x or y not field elements");if(!B(y,A))throw new Error("bad point: equation left != right");if(!h.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");L.add(h)}hasEvenY(){let{y:h}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(h)}equals(h){q(h);let{X:y,Y:A,Z:O}=this,{X:k,Y:M,Z:$}=h,z=n.eql(n.mul(y,$),n.mul(k,O)),W=n.eql(n.mul(A,$),n.mul(M,O));return z&&W}negate(){return new _(this.X,n.neg(this.Y),this.Z)}double(){let{X:h,Y:y,Z:A}=this,O=n.ZERO,k=n.ZERO,M=n.ZERO,$=n.mul(h,h),z=n.mul(y,y),W=n.mul(A,A),G=n.mul(h,y);return G=n.add(G,G),M=n.mul(h,A),M=n.add(M,M),O=R(M),k=n.mul(P,W),k=n.add(O,k),O=n.sub(z,k),k=n.add(z,k),k=n.mul(O,k),O=n.mul(G,O),M=n.mul(P,M),W=R(W),G=n.sub($,W),G=R(G),G=n.add(G,M),M=n.add($,$),$=n.add(M,$),$=n.add($,W),$=n.mul($,G),k=n.add(k,$),W=n.mul(y,A),W=n.add(W,W),$=n.mul(W,G),O=n.sub(O,$),M=n.mul(W,z),M=n.add(M,M),M=n.add(M,M),new _(O,k,M)}add(h){q(h);let{X:y,Y:A,Z:O}=this,{X:k,Y:M,Z:$}=h,z=n.ZERO,W=n.ZERO,G=n.ZERO,ue=n.mul(y,k),ie=n.mul(A,M),ye=n.mul(O,$),Me=n.add(y,A),fe=n.add(k,M);Me=n.mul(Me,fe),fe=n.add(ue,ie),Me=n.sub(Me,fe),fe=n.add(y,O);let he=n.add(k,$);return fe=n.mul(fe,he),he=n.add(ue,ye),fe=n.sub(fe,he),he=n.add(A,O),z=n.add(M,$),he=n.mul(he,z),z=n.add(ie,ye),he=n.sub(he,z),G=R(fe),z=n.mul(P,ye),G=n.add(z,G),z=n.sub(ie,G),G=n.add(ie,G),W=n.mul(z,G),ie=n.add(ue,ue),ie=n.add(ie,ue),ye=R(ye),fe=n.mul(P,fe),ie=n.add(ie,ye),ye=n.sub(ue,ye),ye=R(ye),fe=n.add(fe,ye),ue=n.mul(ie,fe),W=n.add(W,ue),ue=n.mul(he,fe),z=n.mul(Me,z),z=n.sub(z,ue),ue=n.mul(Me,ie),G=n.mul(he,G),G=n.add(G,ue),new _(z,W,G)}subtract(h){return q(h),this.add(h.negate())}is0(){return this.equals(_.ZERO)}multiply(h){if(!o.isValidNot0(h))throw new RangeError("invalid scalar: out of range");let{p:y,f:A}=D.mulSecret(this,h,i,H);return H([y,A])[0]}multiplyUnsafe(h){let y=this,A=h;if(!o.isValid(A))throw new RangeError("invalid scalar: out of range");if(A===Et||y.is0())return _.ZERO;if(A===cr)return y;if(D.hasWindowSize(this))return D.mulUnsafe(y,A,H);let O=[],k=[];return U(O,k,y,A),Co(_,O,k)}mulAddUnsafe(h,y,A){q(y);let O=[],k=[];return U(O,k,this,h),U(O,k,y,A),Co(_,O,k)}toAffine(h){let y=this,A=h;if(A!=null&&!n.isValid(A))throw new RangeError('"invertedZ" expected valid field element');let{X:O,Y:k,Z:M}=y;if(n.eql(M,n.ONE))return{x:O,y:k};let $=y.is0();A==null&&(A=$?n.ONE:n.inv(M));let z=n.mul(O,A),W=n.mul(k,A),G=n.mul(M,A);if($)return{x:n.ZERO,y:n.ZERO};if(!n.eql(G,n.ONE))throw new Error("invZ was invalid");return{x:z,y:W}}isTorsionFree(){return i===cr?!0:u?u(_,this):D.mulUnsafe(this,a).is0()}clearCofactor(){return i===cr?this:l?l(_,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===cr?this.is0():this.clearCofactor().is0()}toBytes(h=!0){return Ke(h,"isCompressed"),this.assertValidity(),v(_,this,h)}toHex(h=!0){return fn(this.toBytes(h))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let H=S=>vo(_,S),D=new Dr(_,x);return D.bits>=6&&_.BASE.precompute(6),Object.freeze(_.prototype),Object.freeze(_),_}function Au(t){return Uint8Array.of(t?2:3)}function vu(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function am(t,e={}){Ht(t);let{Fn:r}=t,n=e.randomBytes===void 0?yt:e.randomBytes,o=Object.assign(vu(t.Fp,r),{seed:Math.max(So(r.ORDER),16)});function s(p){try{let x=r.fromBytes(p);return r.isValidNot0(x)}catch{return!1}}function i(p,x){let{publicKey:w,publicKeyUncompressed:m}=o;try{let g=p.length;return x===!0&&g!==w||x===!1&&g!==m?!1:!t.fromBytes(p).is0()}catch{return!1}}function a(p){return p=p===void 0?n(o.seed):p,Ao(J(p,o.seed,"seed"),r.ORDER)}function c(p,x=!0){return t.BASE.multiply(r.fromBytes(p)).toBytes(x)}function f(p){let{secretKey:x,publicKey:w,publicKeyUncompressed:m}=o,g=r._lengths;if(!Mt(p))return;let E=J(p,void 0,"key").length,b=E===w||E===m,v=E===x||!!g?.includes(E);if(!(b&&v))return b}function l(p,x,w=!0){if(f(p)===!0)throw new Error("first arg must be private key");if(f(x)===!1)throw new Error("second arg must be public key");let m=r.fromBytes(p),g=t.fromBytes(x);if(g.is0())throw new Error("invalid public key: point at infinity");return g.multiply(m).toBytes(w)}let u={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=Ir(a,c);return Object.freeze(u),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:d,Point:t,utils:u,lengths:o})}function Cu(t,e,r={}){Ht(t);let n=e;tr(n),Be(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},r),s=o.randomBytes===void 0?yt:o.randomBytes,i=o.hmac===void 0?(S,h)=>vn(n,S,h):o.hmac,{Fp:a,Fn:c}=t,{ORDER:f,BITS:l}=c,u=So(f),d=Oi(s,u),{keygen:p,getPublicKey:x,getSharedSecret:w,utils:m,lengths:g}=am(t,o),E={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},b=f*Eu+cr<a.ORDER;function v(S){let h=f>>cr;return S>h}function C(S,h){if(!c.isValidNot0(h))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return h}function P(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function R(S,h,y){return P(),(S===y?0:2)|Number(a.isOdd(h))}function N(){if(b)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(S,h){ma(h);let y=g.signature,A=h==="compact"?y:h==="recovered"?y+1:void 0;return J(S,A)}class I{r;s;recovery;constructor(h,y,A){if(this.r=C("r",h),this.s=C("s",y),A!=null){if(N(),![0,1,2,3].includes(A))throw new Error("invalid recovery id");this.recovery=A}Object.freeze(this)}static fromBytes(h,y=E.format){B(h,y);let A;if(y==="der"){if(h.length>2*c.BYTES+16)throw new $o.Err("invalid signature: DER signature too long");let{r:$,s:z}=$o.toSig(J(h),c.BYTES+1);return new I($,z)}y==="recovered"&&(A=h[0],y="compact",h=h.subarray(1));let O=g.signature/2,k=h.subarray(0,O),M=h.subarray(O,O*2);return new I(c.fromBytes(k),c.fromBytes(M),A)}static fromHex(h,y){return this.fromBytes(_r(h),y)}assertRecovery(){let{recovery:h}=this;if(h==null)throw new Error("invalid recovery id: must be present");return h}addRecoveryBit(h){return new I(this.r,this.s,h)}recoverPublicKey(h){let{r:y,s:A}=this,O=this.assertRecovery(),k=O===2||O===3?y+f:y;if(!a.isValid(k))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let M=a.toBytes(k),$=t.fromBytes(We(Au((O&1)===0),M)),z=c.inv(k),W=F(J(h,void 0,"msgHash")),G=c.create(-W*z),ue=c.create(A*z),ie=t.BASE.mulAddUnsafe(G,$,ue);if(ie.is0())throw new Error("invalid recovery: point at infinify");return ie.assertValidity(),ie}hasHighS(){return v(this.s)}toBytes(h=E.format){if(ma(h),h==="der")return _r($o.hexFromSig(this));let{r:y,s:A}=this,O=c.toBytes(y),k=c.toBytes(A);return h==="recovered"?(N(),We(Uint8Array.of(this.assertRecovery()),O,k)):We(O,k)}toHex(h){return fn(this.toBytes(h))}}Object.freeze(I.prototype),Object.freeze(I);let K=o.bits2int===void 0?function(h){if(h.length>8192)throw new Error("input is too large");let y=ut(h),A=h.length*8-l;return A>0?y>>BigInt(A):y}:o.bits2int,F=o.bits2int_modN===void 0?function(h){return c.create(K(h))}:o.bits2int_modN,q=dn(l);function T(S){return dt("num < 2^"+l,S,Et,q),c.toBytes(S)}function U(S,h){return J(S,void 0,"message"),h?J(n(S),void 0,"prehashed message"):S}function L(S,h,y){let{lowS:A,prehash:O,extraEntropy:k}=ha(y,E);S=U(S,O);let M=F(S),$=c.fromBytes(h);if(!c.isValidNot0($))throw new Error("invalid private key");let z=[T($),T(M)];if(k!=null&&k!==!1){let ie=k===!0?s(g.secretKey):k;z.push(J(ie,void 0,"extraEntropy"))}let W=We(...z),G=M;function ue(ie){let ye=K(ie);if(!c.isValidNot0(ye))return;let Me=t.BASE.multiply(ye).toAffine(),fe=c.create(Me.x);if(fe===Et)return;let he;if(d!==void 0){let Tt=ut(Ao(d(u),f)),dd=c.inv(c.mul(Tt,ye)),hd=c.mul(Tt,G),pd=c.mul(Tt,$);he=c.create(dd*c.create(hd+pd*fe))}else{let Tt=Nf(ye,f);he=c.create(Tt*c.create(G+fe*$))}if(he===Et)return;let gr=R(Me.x,Me.y,fe),Zr=he;return A&&v(he)&&(Zr=c.neg(he),gr^=1),new I(fe,Zr,b?void 0:gr)}return{seed:W,k2sig:ue}}function _(S,h,y={}){let{seed:A,k2sig:O}=L(S,h,y);return Tf(n.outputLen,c.BYTES,i)(A,O).toBytes(y.format)}function H(S,h,y,A={}){let{lowS:O,prehash:k,format:M}=ha(A,E);if(y=J(y,void 0,"publicKey"),h=U(h,k),!Mt(S)){let $=S instanceof I?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+$)}B(S,M);try{let $=I.fromBytes(S,M),z=t.fromBytes(y);if(z.is0()||O&&$.hasHighS())return!1;let{r:W,s:G}=$,ue=F(h),ie=c.inv(G),ye=c.create(ue*ie),Me=c.create(W*ie),fe=t.BASE.mulAddUnsafe(ye,z,Me);if(fe.is0())return!1;let he=fe.toAffine();return!(c.create(he.x)!==W||M==="recovered"&&$.recovery!==R(he.x,he.y,W))}catch{return!1}}function D(S,h,y={}){let{prehash:A}=ha(y,E);return h=U(h,A),I.fromBytes(S,"recovered").recoverPublicKey(h).toBytes()}return Object.freeze({keygen:p,getPublicKey:x,getSharedSecret:w,utils:m,lengths:g,Point:t,sign:_,verify:H,recoverPublicKey:D,Signature:I,hash:n})}var ya={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},cm={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var _u=BigInt(2);function fm(t){let e=ya.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=t*t*t%e,l=f*f*t%e,u=le(l,r,e)*l%e,d=le(u,r,e)*l%e,p=le(d,_u,e)*f%e,x=le(p,o,e)*p%e,w=le(x,s,e)*x%e,m=le(w,a,e)*w%e,g=le(m,c,e)*m%e,E=le(g,a,e)*w%e,b=le(E,r,e)*l%e,v=le(b,i,e)*x%e,C=le(v,n,e)*f%e,P=le(C,_u,e);if(!ga.eql(ga.sqr(P),t))throw new Error("Cannot find square root");return P}var ga=Br(ya.p,{sqrt:fm}),um=Su(ya,{Fp:ga,endo:cm}),Or=Cu(um,ft);function Tu(t,e,r,n){let o=mt.digest(r instanceof Uint8Array?r:r.subarray());if(Oo(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Or.verify(e,s,t,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new yn(String(s))});try{return n?.signal?.throwIfAborted(),Or.verify(e,o.digest,t,{prehash:!1,format:"der"})}catch(s){throw new yn(String(s))}}var zo=class{type="secp256k1";raw;_key;constructor(e){this._key=Bu(e),this.raw=Lu(this._key)}toMultihash(){return Ze.digest(Rt(this))}toCID(){return Ee.createV1(114,this.toMultihash())}toString(){return ge.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Ae(this.raw,e.raw)}verify(e,r,n){return Tu(this._key,r,e,n)}};function ba(t){return new zo(t)}function Lu(t){return Or.Point.fromBytes(t).toBytes()}function Bu(t){try{return Or.Point.fromBytes(t),t}catch(e){throw new jt(String(e))}}function Du(t,e){let{Type:r,Data:n}=ht.decode(t),o=n??new Uint8Array;switch(r){case pe.RSA:return fa(o,e);case pe.Ed25519:return Fi(o);case pe.secp256k1:return ba(o);case pe.ECDSA:return pi(o);default:throw new Yt}}function Iu(t){let{Type:e,Data:r}=ht.decode(t.digest),n=r??new Uint8Array;switch(e){case pe.Ed25519:return Fi(n);case pe.secp256k1:return ba(n);case pe.ECDSA:return pi(n);default:throw new Yt}}function Rt(t){return ht.encode({Type:pe[t.type],Data:t.raw})}var Ru=Symbol.for("nodejs.util.inspect.custom"),lm=114,Cn=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ms]=!0;toString(){return this.string==null&&(this.string=ge.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Ee.createV1(lm,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Ae(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Ae(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Ru](){return`PeerId(${this.toString()})`}},_n=class extends Cn{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Tn=class extends Cn{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Ln=class extends Cn{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},dm=2336,Bn=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ze.digest(Q(this.url))}[Ru](){return`PeerId(${this.url})`}[Ms]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Ee.createV1(dm,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=j(e)),e.toString()===this.toString())}};var hm=114,Pu=2336;function Nr(t,e){let r;if(t.charAt(0)==="1"||t.charAt(0)==="Q")r=Ar(ge.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return pm(Ee.parse(t));if(e==null)throw new Z('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=Ar(e.decode(t))}return Nu(r)}function Ou(t){if(t.type==="Ed25519")return new Tn({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new Ln({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new _n({multihash:t.toCID().multihash,publicKey:t});throw new Yt}function Nu(t){if(gm(t))return new _n({multihash:t});if(mm(t))try{let e=Iu(t);if(e.type==="Ed25519")return new Tn({multihash:t,publicKey:e});if(e.type==="secp256k1")return new Ln({multihash:t,publicKey:e})}catch{let r=j(t.digest);return new Bn(new URL(r))}throw new Jn("Supplied PeerID Multihash is invalid")}function pm(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==hm&&t.code!==Pu)throw new Qn("Supplied PeerID CID is invalid");if(t.code===Pu){let e=j(t.multihash.digest);return new Bn(new URL(e))}return Nu(t.multihash)}function mm(t){return t.code===Ze.code}function gm(t){return t.code===mt.code}var _e=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},St=class extends Error{static name="ValidationError";name="ValidationError"},qo=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Vo=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Wo=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,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*o)-1;for(;;){let l=this.readAtomically(()=>{let u=this.readChar();if(u===void 0)return;let d=Number.parseInt(u,e);if(!Number.isNaN(d))return d});if(l===void 0)break;if(s*=e,s+=l,s>f||(i+=1,r!==void 0&&i>r))return}if(i!==0)return!n&&c&&i>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 o=n*2;if(n<r.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return r[o]=i[0],r[o+1]=i[1],r[o+2]=i[2],r[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];r[o]=s>>8,r[o+1]=s&255}return[r.length,!1]};return this.readAtomically(()=>{let r=new Uint8Array(16),[n,o]=e(r);if(n===16)return r;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var ym=45,bm=15,jo=new Wo;function Uu(t){if(!(t.length>bm))return jo.new(t).parseWith(()=>jo.readIPv4Addr())}function ku(t){if(t.includes("%")&&(t=t.split("%")[0]),!(t.length>ym))return jo.new(t).parseWith(()=>jo.readIPv6Addr())}function Go(t){return!!Uu(t)}function Mu(t){return!!ku(t)}function xa(t){return e=>j(e,t)}function Ea(t){return e=>Q(e,t)}function Ur(t){return new DataView(t.buffer).getUint16(t.byteOffset).toString()}function fr(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof t=="string"?parseInt(t):t),new Uint8Array(e)}function Fu(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=Q(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=fr(n);return Ue([r,o],r.length+o.length)}function Ku(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=Dt.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 o=fr(n);return Ue([r,o],r.length+o.length)}function Sa(t){let e=t.subarray(0,t.length-2),r=t.subarray(t.length-2),n=j(e,"base32"),o=Ur(r);return`${n}:${o}`}var Aa=function(t){t=t.toString().trim();let e=new Uint8Array(4);return t.split(/\./g).forEach((r,n)=>{let o=parseInt(r,10);if(isNaN(o)||o<0||o>255)throw new _e("Invalid byte value in IP address");e[n]=o}),e},Hu=function(t){let e=0;t=t.toString().trim();let r=t.split(":",8),n;for(n=0;n<r.length;n++){let s=Go(r[n]),i;s&&(i=Aa(r[n]),r[n]=j(i.subarray(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,j(i.subarray(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 o=new Uint8Array(e+16);for(n=0;n<r.length;n++){r[n]===""&&(r[n]="0");let s=parseInt(r[n],16);if(isNaN(s)||s<0||s>65535)throw new _e("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},$u=function(t){if(t.byteLength!==4)throw new _e("IPv4 address was incorrect length");let e=[];for(let r=0;r<t.byteLength;r++)e.push(t[r]);return e.join(".")},zu=function(t){if(t.byteLength!==16)throw new _e("IPv6 address was incorrect length");let e=[];for(let n=0;n<t.byteLength;n+=2){let o=t[n],s=t[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let r=e.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new _e(`Invalid IPv6 address "${r}"`)}};function qu(t){try{let e=new URL(`http://[${t}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new _e(`Invalid IPv6 address "${t}"`)}}var wa=Object.values(Qt).map(t=>t.decoder),wm=(function(){let t=wa[0].or(wa[1]);return wa.slice(2).forEach(e=>t=t.or(e)),t})();function Vu(t){return wm.decode(t)}function Wu(t){return e=>t.encoder.encode(e)}function xm(t){if(parseInt(t).toString()!==t)throw new St("Value must be an integer")}function Em(t){if(t<0)throw new St("Value must be a positive integer, or zero")}function Sm(t){return e=>{if(e>t)throw new St(`Value must be smaller than or equal to ${t}`)}}function Am(...t){return e=>{for(let r of t)r(e)}}var Dn=Am(xm,Em,Sm(65535));var ve=-1,va=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let r;if(typeof e=="string"?r=this.protocolsByName.get(e):r=this.protocolsByCode.get(e),r==null)throw new Vo(`Protocol ${e} was unknown`);return r}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(r=>{this.protocolsByName.set(r,e)})}removeProtocol(e){let r=this.protocolsByCode.get(e);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},vt=new va,km=[{code:4,name:"ip4",size:32,valueToBytes:Aa,bytesToValue:$u,validate:t=>{if(!Go(t))throw new St(`Invalid IPv4 address "${t}"`)}},{code:6,name:"tcp",size:16,valueToBytes:fr,bytesToValue:Ur,validate:Dn},{code:273,name:"udp",size:16,valueToBytes:fr,bytesToValue:Ur,validate:Dn},{code:33,name:"dccp",size:16,valueToBytes:fr,bytesToValue:Ur,validate:Dn},{code:41,name:"ip6",size:128,valueToBytes:Hu,bytesToValue:zu,stringToValue:qu,validate:t=>{if(!Mu(t))throw new St(`Invalid IPv6 address "${t}"`)}},{code:42,name:"ip6zone",size:ve},{code:43,name:"ipcidr",size:8,bytesToValue:xa("base10"),valueToBytes:Ea("base10")},{code:53,name:"dns",size:ve},{code:54,name:"dns4",size:ve},{code:55,name:"dns6",size:ve},{code:56,name:"dnsaddr",size:ve},{code:132,name:"sctp",size:16,valueToBytes:fr,bytesToValue:Ur,validate:Dn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:ve,stringToValue:t=>decodeURIComponent(t),valueToString:t=>encodeURIComponent(t)},{code:421,name:"p2p",aliases:["ipfs"],size:ve,bytesToValue:xa("base58btc"),valueToBytes:t=>t.startsWith("Q")||t.startsWith("1")?Ea("base58btc")(t):Ee.parse(t).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Sa,valueToBytes:Fu},{code:445,name:"onion3",size:296,bytesToValue:Sa,valueToBytes:Ku},{code:446,name:"garlic64",size:ve},{code:447,name:"garlic32",size:ve},{code:448,name:"tls"},{code:449,name:"sni",size:ve},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:ve,bytesToValue:Wu(rn),valueToBytes:Vu},{code:480,name:"http"},{code:481,name:"http-path",size:ve,stringToValue:t=>`/${decodeURIComponent(t)}`,valueToString:t=>encodeURIComponent(t.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:ve}];km.forEach(t=>{vt.addProtocol(t)});function ju(t){let e=[],r=0;for(;r<t.length;){let n=wt(t,r),o=vt.getProtocol(n),s=de(n),i=Mm(o,t,r+s),a=0;i>0&&o.size===ve&&(a=de(i));let c=s+a+i,f={code:n,name:o.name,bytes:Ce(t.subarray(r,r+c))};if(i>0){let l=r+s+a,u=t.subarray(l,l+i);f.value=o.bytesToValue?.(u)??j(u)}e.push(f),r+=c}return e}function Gu(t){let e=0,r=[];for(let n of t){if(n.bytes==null){let o=vt.getProtocol(n.code),s=de(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Q(n.value),a=i.byteLength,o.size===ve&&(c=de(a)));let f=new Uint8Array(s+c+a),l=0;Rr(n.code,f,l),l+=s,i!=null&&(o.size===ve&&(Rr(a,f,l),l+=c),f.set(i,l)),n.bytes=f}r.push(n.bytes),e+=n.bytes.byteLength}return Ue(r,e)}function Yu(t){if(t.charAt(0)!=="/")throw new _e('String multiaddr must start with "/"');let e=[],r="protocol",n="",o="";for(let s=1;s<t.length;s++){let i=t.charAt(s);i!=="/"&&(r==="protocol"?o+=t.charAt(s):n+=t.charAt(s));let a=s===t.length-1;if(i==="/"||a){let c=vt.getProtocol(o);if(r==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",r="protocol";continue}else if(a)throw new _e(`Component ${o} was missing value`);r="value"}else if(r==="value"){let f={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new _e(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}e.push(f),n="",o="",r="protocol"}}}if(o!==""&&n!=="")throw new _e("Incomplete multiaddr");return e}function Xu(t){return`/${t.flatMap(e=>{if(e.value==null)return e.name;let r=vt.getProtocol(e.code);if(r==null)throw new _e(`Unknown protocol code ${e.code}`);return[e.name,r.valueToString?.(e.value)??e.value]}).join("/")}`}function Mm(t,e,r){return t.size==null||t.size===0?0:t.size>0?t.size/8:wt(e,r)}var Fm=Symbol.for("nodejs.util.inspect.custom"),Ha=Symbol.for("@multiformats/multiaddr");function Km(t){if(t==null&&(t="/"),Zu(t))return t.getComponents();if(t instanceof Uint8Array)return ju(t);if(typeof t=="string")return t=t.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),t===""&&(t="/"),Yu(t);if(Array.isArray(t))return t;throw new _e("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Jo=class t{[Ha]=!0;#e;#t;#r;constructor(e="/",r={}){this.#e=Km(e),r.validate!==!1&&Hm(this)}get bytes(){return this.#r==null&&(this.#r=Gu(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Xu(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}encapsulate(e){let r=new t(e);return new t([...this.#e,...r.getComponents()],{validate:!1})}decapsulate(e){let r=e.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new qo(`Address ${this.toString()} does not contain subaddress: ${r}`);return new t(n.slice(0,o),{validate:!1})}decapsulateCode(e){let r;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){r=n;break}return new t(this.#e.slice(0,r),{validate:!1})}equals(e){return Ae(this.bytes,e.bytes)}[Fm](){return`Multiaddr(${this.toString()})`}};function Hm(t){t.getComponents().forEach(e=>{let r=vt.getProtocol(e.code);e.value!=null&&r.validate?.(e.value)})}function Zu(t){return!!t?.[Ha]}function Kr(t){return new Jo(t)}var ae=t=>({match:e=>{let r=e[0];return r==null||r.code!==t||r.value!=null?!1:e.slice(1)}}),V=(t,e)=>({match:r=>{let n=r[0];return n?.code!==t||n.value==null||e!=null&&n.value!==e?!1:r.slice(1)}}),Qu=t=>({match:e=>t.match(e)===!1?e:!1}),X=t=>({match:e=>{let r=t.match(e);return r===!1?e:r}}),Re=(...t)=>({match:e=>{let r;for(let n of t){let o=n.match(e);o!==!1&&(r==null||o.length<r.length)&&(r=o)}return r??!1}}),te=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e}});function ce(...t){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of t){let a=i.match(s);if(a===!1)return!1;s=a}return s}function r(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:t,matches:r,exactMatch:n}}var $m=V(421),P1=ce($m),ts=V(54),rs=V(55),ns=V(56),za=V(53),O1=ce(ts,X(V(421))),N1=ce(rs,X(V(421))),U1=ce(ns,X(V(421))),k1=ce(Re(za,ns,ts,rs),X(V(421))),Ju=te(V(4),X(V(43))),el=te(X(V(42)),V(41),X(V(43))),qa=Re(Ju,el),Hr=Re(qa,za,ts,rs,ns),M1=ce(Re(qa,te(Re(za,ns,ts,rs),X(V(421))))),F1=ce(Ju),K1=ce(el),H1=ce(qa),Va=te(Hr,V(6)),In=te(Hr,V(273)),$1=ce(te(Va,X(V(421)))),z1=ce(In),Wa=te(In,ae(460),X(V(421))),os=te(In,ae(461),X(V(421))),zm=Re(Wa,os),q1=ce(Wa),V1=ce(os),$a=Re(Hr,Va,In,Wa,os),tl=Re(te($a,ae(477),X(V(421)))),W1=ce(tl),rl=Re(te($a,ae(478),X(V(421))),te($a,ae(448),X(V(449)),ae(477),X(V(421)))),j1=ce(rl),nl=te(In,ae(280),X(V(466)),X(V(466)),X(V(421))),ol=ce(nl),sl=te(os,ae(465),X(V(466)),X(V(466)),X(V(421))),G1=ce(sl),es=Re(tl,rl,te(Va,X(V(421))),te(zm,X(V(421))),te(Hr,X(V(421))),nl,sl,V(421)),il=ce(es),qm=te(X(es),ae(290),Qu(ae(281)),X(V(421))),Y1=ce(qm),Vm=Re(te(es,ae(290),ae(281),X(V(421))),te(es,ae(281),X(V(421))),te(ae(281),X(V(421)))),al=ce(Vm),Wm=te(Hr,Re(te(V(6,"80")),te(V(6),ae(480)),ae(480)),X(V(481)),X(V(421))),X1=ce(Wm),jm=te(Hr,Re(te(V(6,"443")),te(V(6,"443"),ae(480)),te(V(6),ae(443)),te(V(6),ae(448),ae(480)),te(ae(448),ae(480)),ae(448),ae(443)),X(V(481)),X(V(421))),Z1=ce(jm),Gm=Re(te(V(777),X(V(421)))),Q1=ce(Gm),Ym=Re(te(V(400),X(V(421)))),J1=ce(Ym);var Pe;(function(t){let e;(function(a){a.FIN="FIN",a.STOP_SENDING="STOP_SENDING",a.RESET="RESET",a.FIN_ACK="FIN_ACK"})(e=t.Flag||(t.Flag={}));let r;(function(a){a[a.FIN=0]="FIN",a[a.STOP_SENDING=1]="STOP_SENDING",a[a.RESET=2]="RESET",a[a.FIN_ACK=3]="FIN_ACK"})(r||(r={})),(function(a){a.codec=()=>ir(r)})(e=t.Flag||(t.Flag={}));let n;t.codec=()=>(n==null&&(n=ot((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.flag!=null&&(c.uint32(8),t.Flag.codec().encode(a.flag,c)),a.message!=null&&(c.uint32(18),c.bytes(a.message)),f.lengthDelimited!==!1&&c.ldelim()},(a,c,f={})=>{let l={},u=c==null?a.len:a.pos+c;for(;a.pos<u;){let d=a.uint32();switch(d>>>3){case 1:{l.flag=t.Flag.codec().decode(a);break}case 2:{l.message=a.bytes();break}default:{a.skipType(d&7);break}}}return l},function*(a,c,f,l={}){let u=c==null?a.len:a.pos+c;for(;a.pos<u;){let d=a.uint32();switch(d>>>3){case 1:{yield{field:`${f}.flag`,value:t.Flag.codec().decode(a)};break}case 2:{yield{field:`${f}.message`,value:a.bytes()};break}default:{a.skipType(d&7);break}}}})),n);function o(a){return rt(a,t.codec())}t.encode=o;function s(a,c){return tt(a,t.codec(),c)}t.decode=s;function i(a,c){return nt(a,t.codec(),c)}t.stream=i})(Pe||(Pe={}));var cl=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],ja=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Rn="libp2p+webrtc+v1/",fl="libp2p+webrtc+v2/",ul=2*1024*1024,lr=16*1024,ll=lr,dl=10,hl=8;function Xm(t=lr){let e=de(t-de(t)),r=1+de(Object.keys(Pe.Flag).length-1),n=1,o=t-e-r-n,s=de(o);return e+r+n+s}var pl=Xm();var ml=1e4,Ga="/webrtc",Pn="/webrtc-signaling/0.0.1";function Zm(t){let e=t.getComponents(),r={},n=0;return e[n]?.name==="ip6zone"&&(r.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(r.type=e[n].name,r.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(r.type=e[n].name,r.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(r.protocol=e[n].name==="tcp"?"tcp":"udp",r.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(r.type==="ip4"?r.cidr=parseInt(`${e[n].value}`):r.type==="ip6"&&(r.cidr=`${e[n].value}`),n++),r.type==null||r.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(r.sni=e[n+1].value,n+=2),r)}function Ya(t){let e=Zm(t);if(e==null)throw new Z(`Multiaddr ${t} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function ss(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var is=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)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}},$r=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new is(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 is(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()}};var Xa=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function zr(t={}){return Qm(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 Qm(t,e){e=e??{};let r=e.onEnd,n=new $r,o,s,i,a=ss(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((m,g)=>{s=E=>{s=null,n.push(E);try{m(t(n))}catch(b){g(b)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ss()})}},f=m=>s!=null?s(m):(n.push(m),o),l=m=>(n=new $r,s!=null?s({error:m}):(n.push({error:m}),o)),u=m=>{if(i)return o;if(e?.objectMode!==!0&&m?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:m})},d=m=>i?o:(i=!0,m!=null?l(m):f({done:!0})),p=()=>(n=new $r,d(),{done:!0}),x=m=>(d(m),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:x,push:u,end:d,get readableLength(){return n.size},onEmpty:async m=>{let g=m?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let E,b;g!=null&&(E=new Promise((v,C)=>{b=()=>{C(new Xa)},g.addEventListener("abort",b)}));try{await Promise.race([a.promise,E])}finally{b!=null&&g!=null&&g?.removeEventListener("abort",b)}}},r==null)return o;let w=o;return o={[Symbol.asyncIterator](){return this},next(){return w.next()},throw(m){return w.throw(m),r!=null&&(r(m),r=void 0),{done:!0}},return(){return w.return(),r!=null&&(r(),r=void 0),{done:!0}},push:u,end(m){return w.end(m),r!=null&&(r(m),r=void 0),o},get readableLength(){return w.readableLength},onEmpty:m=>w.onEmpty(m)},o}var Za=class t extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,t)}},gl=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function Qa(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,l=new Promise((u,d)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){d(gl(i)),t.then(u,d);return}if(i&&(c=()=>{d(gl(i))},i.addEventListener("abort",c,{once:!0})),t.then(u,d),r===Number.POSITIVE_INFINITY)return;let p=new Za;a=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(x){d(x)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?u():o instanceof Error?d(o):(p.message=o??`Promise timed out after ${r} milliseconds`,d(p))},r)}).finally(()=>{l.clear(),c&&i&&i.removeEventListener("abort",c)});return l.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},l}var yl=t=>typeof t=="function"?{filter:t}:{...t},Jm=t=>t===1/0||Number.isSafeInteger(t)&&t>=0,eg=[["addEventListener","removeEventListener"],["on","off"],["addListener","removeListener"]],tg=t=>{for(let[e,r]of eg){let n=t?.[e],o=t?.[r];if(typeof n=="function"&&typeof o=="function")return{addListener:n.bind(t),removeListener:o.bind(t)}}throw new TypeError("Emitter is not compatible")},rg=t=>{let e=new Map;for(let[r,n]of t)for(let o of Array.isArray(r)?r:[r])e.has(o)||e.set(o,n);return e},ng=({addListener:t,removeListener:e,handlers:r,signal:n,abortHandler:o,isDone:s})=>{n?.addEventListener("abort",o,{once:!0});for(let[i,a]of r)if(t(i,a),s()){e(i,a);return}},og=({removeListener:t,handlers:e,signal:r,abortHandler:n})=>{for(let[o,s]of e)t(o,s);r?.removeEventListener("abort",n)},sg=(t,e,r)=>{let n=Promise.resolve();return(o,s)=>{n=n.then(async()=>{if(e())return;let i;try{i=t?await t(o):!0}catch(a){e()||r(a);return}e()||s(i)})}};function ig(t,e,r){let n=()=>{},o=!1,s,i=new Promise((a,c)=>{r=yl(r);let{filter:f}=r;if(!Jm(r.count))throw new TypeError("The `count` option should be at least 0 or more");if(typeof r.timeout=="number"&&!(r.timeout>0))throw new TypeError(`Expected the \`timeout\` option to be a positive number, got \`${r.timeout}\``);r.signal?.throwIfAborted();let{addListener:l,removeListener:u}=tg(t);if(r.count===0){a([]);return}let d=[],p=v=>{n(),c(v)},x=sg(f,()=>o,p),w=v=>{d.push(v),r.count===d.length&&(n(),a(d))},m=(...v)=>{if(o)return;let C=r.multiArgs?v:v[0];if(!f){w(C);return}x(C,P=>{P&&w(C)})},g=(...v)=>{p(r.rejectionMultiArgs?v:v[0])},E=()=>{p(r.signal.reason)},b={addListener:l,removeListener:u,handlers:rg([[e,m],[r.rejectionEvents??["error"],g]]),signal:r.signal,abortHandler:E,isDone:()=>o};n=()=>{o=!0,clearTimeout(s),og(b)},ng(b),!(o||!r.resolveImmediately)&&(Number.isFinite(r.timeout)&&(s=setTimeout(n,r.timeout)),a(d))});if(i.cancel=n,typeof r.timeout=="number"&&r.timeout>0&&!r.resolveImmediately){let a=Qa(i,{milliseconds:r.timeout});return a.cancel=()=>{n(),a.clear()},a}return i}function Te(t,e,r){let n=ig(t,e,{...yl(r),count:1,resolveImmediately:!1}),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var dr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},as=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},cs=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function ag(t){return t.reason}function Ct(t,e,r){if(e==null||t==null)return t;let n=r?.translateError??ag;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let o;return Promise.race([t,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}var cg=Math.pow(2,20)*4,qt=class extends Lt{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;#e=!1;#t;#r=new Set;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??cg,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new Y,this.writeBuffer=new Y,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let r=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(o){this.log.error("processSendQueue threw - %e",o)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",r);let n=o=>{this.onDrainPromise?.reject(o.error??new cs)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get readableEnded(){return this.#e}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Ct(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){let e=zr(),r,n=s=>{e.push(s.data)};this.addEventListener("message",n);let o=()=>{this.#r.delete(o),this.removeEventListener("message",n),r=this.#t,e.end()};this.#r.add(o),this.readableDone()&&o();try{if(yield*e,r!=null)throw r}finally{this.removeEventListener("message",n),this.#r.delete(o)}}readableDone(){return this.readBuffer.byteLength===0&&(this.remoteWriteStatus==="closed"||this.readStatus==="closing"||this.readStatus==="closed")}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new at(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(this.status==="aborted"||this.status==="reset"||this.status==="closed"){this.readBuffer.byteLength>0&&(this.#t??=e,this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closed",this.maybeDispatchEnd());return}this.log.error("abort with error - %e",e),this.status="aborted",this.#t=e,this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.maybeDispatchEnd();try{this.sendReset(e)}catch(r){this.log.error("failed to send reset to remote - %e",r)}this.dispatchEvent(new ro(e))}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new at("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new at("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new at(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new at(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){if(this.status==="aborted"||this.status==="reset"||this.status==="closed")return;this.log("remote reset");let e=new yr;this.#t=e,this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed",this.maybeDispatchEnd()),this.dispatchEvent(new no(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.maybeDispatchEnd(),this.dispatchEvent(new br))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.maybeDispatchEnd(),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,r=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let s=this.writeBuffer.sublist(0,o),i=new Y(s);this.writeBuffer.consume(s.byteLength);let a;try{a=this.sendData(s)}catch(c){throw this.writeBuffer.prepend(i),this.abort(c),c}if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,r,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}maybeDispatchEnd(){this.readableDone()&&(this.#r.forEach(e=>{e()}),!this.#e&&(this.#e=!0,this.safeDispatchEvent("end")))}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new to(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed",this.maybeDispatchEnd()),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Gt(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Gt(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var fs=class extends qt{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",r=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),r.error!=null?r.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):r.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Te(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Te(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function bl(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var us=class extends Lt{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,r){super(),this.maConn=e,this.protocol=r.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(r.name),this.streamOptions=r.streamOptions,this.maxEarlyStreams=r.maxEarlyStreams??10,this.metrics=r.metrics;let n=i=>{try{this.onData(i.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",n);let o=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(i=>{i.onMuxerDrain()})};this.maConn.addEventListener("drain",o);let s=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",s)}send(e){let r=this.maConn.send(e);return r===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),r}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await Ct(Promise.all([...this.streams].map(async r=>{await r.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(r=>{r.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(r=>{r.onTransportClosed(e)})}catch(r){this.abort(r)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new Xn;let r=this.onCreateStream({...this.streamOptions,...e});return bl(r)&&(r=await r),this.streams.push(r),this.cleanUpStream(r),r}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new as(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let r=n=>{let o=this.streams.findIndex(s=>s===e);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",r),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(r=>{this.safeDispatchEvent("stream",{detail:r})}),this.earlyStreams=[]})}};var ls=class extends qt{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Te(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await Te(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){if(!(this.readStatus==="closing"||this.readStatus==="closed")){this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",this.maybeDispatchEnd();try{await this.sendCloseRead(e)}catch(r){throw this.log.error("failed to close readable end - %e",r),r}finally{this.readStatus="closed"}this.log("closed readable end gracefully")}}};var fg=4194304,ds=class extends Error{static name="UnwrappedError";name="UnwrappedError"},On=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ec=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},tc=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function ug(t){return typeof t?.closeRead=="function"}function lg(t){return typeof t?.close=="function"}function Ja(t){return ug(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:lg(t)?t.status!=="open":!1}function dg(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function hg(t,e){let r=e?.maxBufferSize??fg,n=new Y,o,s=!1,i;if(!dg(t))throw new Z("Argument should be a Stream or a Multiaddr");let a=u=>{if(!s&&i==null){if(n.append(u.data),n.byteLength>r){let d=n.byteLength;n.consume(d);let p=new Gt(`Read buffer overflow - ${d} > ${r}`);i=p,o?.reject(p),queueMicrotask(()=>{t.abort(p)});return}o?.resolve()}};t.addEventListener("message",a);let c=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};t.addEventListener("close",c);let f=()=>{o?.resolve()};t.addEventListener("remoteCloseWrite",f);let l={readBuffer:n,async read(u){if(s===!0)throw new ds("Stream was unwrapped");if(i!=null)throw i;if(Ja(t)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new dr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let d=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await Ct(o.promise,u?.signal),Ja(t)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let p=u?.bytes??n.byteLength;if(n.byteLength<p){if(Ja(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,p),new dr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${p} bytes`);return l.read(u)}let x=n.sublist(0,p);return n.consume(p),x},async write(u,d){if(s===!0)throw new ds("Stream was unwrapped");t.send(u)||await Te(t,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",a),t.removeEventListener("close",c),t.removeEventListener("remoteCloseWrite",f),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.unshift(n),n.consume(n.byteLength))),t}};return l}function hs(t,e={}){let r=hg(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=de(e.maxDataLength));let n=e?.lengthDecoder??wt,o=e?.lengthEncoder??Uo;return{async read(i){let a=-1,c=new Y;for(;;){let l=await r.read({...i,bytes:1});if(l==null)break;c.append(l);try{a=n(c)}catch(u){if(u instanceof RangeError)continue;throw u}if(a<0)throw new On("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new tc(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new ec(`Message length too long - ${a} > ${e.maxDataLength}`);let f=await r.read({...i,bytes:a});if(f==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new dr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(f.byteLength!==a)throw t.log.error("read %d/%d bytes before the stream closed",f.byteLength,a),new dr(`Unexpected EOF - read ${f.byteLength}/${a} bytes before the stream closed`);return f},async write(i,a){await r.write(new Y(o(i.byteLength),i),a)},async writeV(i,a){let c=new Y(...i.flatMap(f=>[o(f.byteLength),f]));await r.write(c,a)},unwrap(){return r.unwrap()}}}function ps(t,e){let r=hs(t,e),n={read:async(o,s)=>{let i=await r.read(s);return o.decode(i,s)},write:async(o,s,i)=>{await r.write(s.encode(o),i)},writeV:async(o,s,i)=>{await r.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}var pg=1024*1024*4,mg=1024*1024*4,ms=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new Y,this.maxBufferSize=e.maxBufferSize??pg,this.maxDataLength=e.maxDataLength??mg,this.lengthDecoder=e.lengthDecoder??wt,this.encodingLength=e.encodingLength??de}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new Z(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let r;try{r=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(r<0||r>this.maxDataLength)throw new On("Invalid message length");let n=this.encodingLength(r),o=n+r;if(this.buffer.byteLength>=o){let s=this.buffer.sublist(n,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}};var gs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},qr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ys=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Nn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function bs(t){return t[Symbol.asyncIterator]!=null}function wl(t,e){if(t.byteLength>e)throw new qr("Message length too long")}var xs=t=>{let e=de(t),r=xe(e);return Uo(t,r),xs.bytes=e,r};xs.bytes=0;function Un(t,e){e=e??{};let r=e.lengthEncoder??xs,n=e?.maxDataLength??4194304;function*o(s){wl(s,n);let i=r(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return bs(t)?(async function*(){for await(let s of t)yield*o(s)})():(function*(){for(let s of t)yield*o(s)})()}Un.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??xs,n=e?.maxDataLength??4194304;return wl(t,n),new Y(r(t.byteLength),t)};var hr;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(hr||(hr={}));var rc=t=>{let e=wt(t);return rc.bytes=de(e),e};rc.bytes=0;function kn(t,e){let r=new Y,n=hr.LENGTH,o=-1,s=e?.lengthDecoder??rc,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===hr.LENGTH)try{if(o=s(r),o<0)throw new gs("Invalid message length");if(o>a)throw new qr("Message length too long");let f=s.bytes;r.consume(f),e?.onLength!=null&&e.onLength(o),n=hr.DATA}catch(f){if(f instanceof RangeError){if(r.byteLength>i)throw new ys("Message length length too long");break}throw f}if(n===hr.DATA){if(r.byteLength<o)break;let f=r.sublist(0,o);r.consume(o),e?.onData!=null&&e.onData(f),yield f,n=hr.LENGTH}}}return bs(t)?(async function*(){for await(let f of t)r.append(f),yield*c();if(r.byteLength>0)throw new Nn("Unexpected end of input")})():(function*(){for(let f of t)r.append(f),yield*c();if(r.byteLength>0)throw new Nn("Unexpected end of input")})()}kn.fromReader=(t,e)=>{let r=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await t.next(r);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{r=1}})();return kn(n,{...e??{},onLength:s=>{r=s}})};var nc=class extends ls{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(e){super({...e,maxMessageSize:(e.maxMessageSize??lr)-pl}),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=zr(),this.maxBufferedAmount=e.maxBufferedAmount??ul,this.finAckTimeout=e.finAckTimeout??ml,this.channel.onclose=()=>{this.log.trace("received datachannel close event"),this.onRemoteCloseWrite(),this.onTransportClosed()},this.channel.onerror=n=>{let o=n.error;this.log.trace("received datachannel error event - %e",o),this.abort(o)},this.channel.onmessage=async n=>{this.log("incoming message %d bytes",n.data.byteLength);let{data:o}=n;o===null||o.byteLength===0||this.incomingData.push(new Uint8Array(o,0,o.byteLength))},this.channel.bufferedAmountLowThreshold=0,this.channel.onbufferedamountlow=()=>{this.writableNeedsDrain&&this.safeDispatchEvent("drain")},Promise.resolve().then(async()=>{for await(let n of kn(this.incomingData))this.processIncomingProtobuf(n)}).catch(n=>{this.log.error("error processing incoming data channel messages - %e",n)});let r=()=>{this.channel.readyState==="open"&&(this.log.trace("stream closed, closing underlying datachannel"),this.channel.close())};this.addEventListener("close",r),this.channel.readyState!=="open"&&(this.log('channel ready state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),Te(this.channel,"open",{rejectionEvents:["close","error"]}).then(()=>{this.log('channel ready state is now "%s", dispatching drain',this.channel.readyState),this.safeDispatchEvent("drain")}).catch(n=>{this.abort(n.error??n)}))}sendNewStream(){}_sendMessage(e){if(this.channel.readyState!=="open")throw new at(`Invalid datachannel state - ${this.channel.readyState}`);this.log.trace('sending message, channel state "%s"',this.channel.readyState);try{for(let r of e)this.channel.send(Ce(r))}catch(r){this.log.error("error sending datachannel message - %e",r),this.abort(r)}}sendData(e){return this.channel.readyState!=="open"?{sentBytes:0,canSendMore:!1}:(this._sendMessage(Un.single(Pe.encode({message:e.subarray()}))),{sentBytes:e.byteLength,canSendMore:this.channel.bufferedAmount<this.maxBufferedAmount})}sendReset(e){try{this.log.error("sending reset - %e",e),this._sendFlag(Pe.Flag.RESET),this.receivedFinAck?.reject(e)}catch(r){this.log.error("failed to send reset - %e",r)}}async sendCloseWrite(e){this._sendFlag(Pe.Flag.FIN),e?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let r=e?.signal??AbortSignal.timeout(this.finAckTimeout),n=[Te(this.channel,"close",{signal:r}),Te(this.channel,"error",{signal:r})];await Promise.any([Ct(this.receivedFinAck.promise,r),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(e){this._sendFlag(Pe.Flag.STOP_SENDING),e?.signal?.throwIfAborted()}processIncomingProtobuf(e){let r=Pe.decode(e);r.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new Y(r.message)),r.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',r.flag,this.writeStatus,this.readStatus),r.flag===Pe.Flag.FIN&&(this._sendFlag(Pe.Flag.FIN_ACK),this.onRemoteCloseWrite()),r.flag===Pe.Flag.RESET&&(this.receivedFinAck?.reject(new yr("The stream was reset")),this.onRemoteReset()),r.flag===Pe.Flag.STOP_SENDING&&this.onRemoteCloseRead(),r.flag===Pe.Flag.FIN_ACK&&this.receivedFinAck?.resolve())}_sendFlag(e){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',e.toString(),this.channel.readyState),!1;this.log.trace("sending flag %s",e.toString());let r=Pe.encode({flag:e}),n=Un.single(r);try{return this._sendMessage(n),!0}catch(o){this.log.error("could not send flag %s - %e",e.toString(),o)}return!1}sendPause(){}sendResume(){}};function Mn(t){let{channel:e,direction:r,isHandshake:n}=t;return new nc({...t,id:`${e.id}`,log:t.log.newScope(`${n===!0?"handshake":r}:${e.id}`),protocol:""})}function ic(t,e){try{t.close()}catch(r){e?.trace("error closing early data channel - %e",r)}}function oc(t,e){t.channel.onmessage=null,t.messages.length=0,ic(t.channel,e)}var Vt=class{protocol;peerConnection;metrics;log;dataChannelOptions;maxEarlyStreams;earlyDataChannels;handedOff=!1;constructor(e){this.onEarlyDataChannel=this.onEarlyDataChannel.bind(this),this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.log=e.log,this.protocol=e.protocol??Ga,this.dataChannelOptions=e.dataChannelOptions??{},this.maxEarlyStreams=e.maxEarlyStreams??dl,this.peerConnection.addEventListener("datachannel",this.onEarlyDataChannel),this.earlyDataChannels=[]}onEarlyDataChannel(e){let r=e.channel;if(this.earlyDataChannels.length>=this.maxEarlyStreams){this.log?.("rejecting early data channel %d - too many early channels",r.id),this.metrics?.increment({early_data_channel_count_exceeded:!0}),ic(r,this.log);return}r.binaryType="arraybuffer";let n={channel:r,messages:[]};r.onmessage=o=>{let{data:s}=o;if(!(s instanceof ArrayBuffer)){this.closeEarlyDataChannel(n,"invalid_message");return}if(n.messages.length>=hl){this.closeEarlyDataChannel(n,"message_count_exceeded");return}if(n.messages.reduce((a,c)=>a+c.data.byteLength,0)+s.byteLength>ll){this.closeEarlyDataChannel(n,"byte_count_exceeded");return}n.messages.push(o)},this.earlyDataChannels.push(n)}closeEarlyDataChannel(e,r){this.log?.("closing early data channel %d - %s",e.channel.id,r),this.metrics?.increment({[`early_data_channel_${r}`]:!0}),oc(e,this.log);let n=this.earlyDataChannels.indexOf(e);n!==-1&&this.earlyDataChannels.splice(n,1)}createStreamMuxer(e){return this.handedOff=!0,this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel),new sc(e,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,maxEarlyStreams:this.maxEarlyStreams,earlyDataChannels:this.earlyDataChannels})}close(){if(!this.handedOff){this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel);for(let e of this.earlyDataChannels)oc(e,this.log);this.earlyDataChannels.length=0}}},sc=class extends us{peerConnection;dataChannelOptions;constructor(e,r){super(e,{...r,name:"muxer"}),this.peerConnection=r.peerConnection,this.protocol=r.protocol??Ga,this.dataChannelOptions=r.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{this.onDataChannel(n)},queueMicrotask(()=>{if(this.status!=="open"){r.earlyDataChannels.forEach(n=>{oc(n,this.log)});return}r.earlyDataChannels.forEach(({channel:n,messages:o})=>{try{this.onDataChannel(n,o)}catch(s){this.log.error("error adopting early data channel %d - %e",n.id,s)}})})}onDataChannel(e,r){if(this.log("incoming datachannel with channel id %d, protocol %s and status %s",e.id,e.protocol,e.readyState),e.label==="init"){this.log.trace("closing init channel %d",e.id),ic(e,this.log);return}let n=Mn({...this.streamOptions,...this.dataChannelOptions,channel:e,direction:"inbound",log:this.log});r?.forEach(o=>{e.onmessage?.(o)}),this.onRemoteStream(n)}async onCreateStream(e){let r=this.peerConnection.createDataChannel("",{});return this.log("open channel %d for protocol %s",r.id,e?.protocol),Mn({...e,...this.dataChannelOptions,channel:r,direction:"outbound",log:this.log})}onData(){}};var ac=class extends fs{peerConnection;constructor(e){super(e),this.peerConnection=e.peerConnection;let r=e.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change %s initial state %s",this.peerConnection.connectionState,r),(this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.onTransportClosed(),this.peerConnection.close())}}sendData(e){return{sentBytes:e.byteLength,canSendMore:!0}}async sendClose(e){this.peerConnection.close(),e?.signal?.throwIfAborted()}sendReset(){this.peerConnection.close()}sendPause(){}sendResume(){}},Fn=t=>new ac(t);async function cc(t){return t=t??{},typeof t=="function"&&(t=await t()),t.iceServers=t.iceServers??cl.map(e=>({urls:[e]})),t}var Es=(t=32,e=Rn)=>e+[...Array(t)].map(()=>ja.at(Math.floor(Math.random()*ja.length))).join("");var Ss=globalThis.RTCPeerConnection,As=globalThis.RTCSessionDescription,xl=globalThis.RTCIceCandidate;var ze=class extends Event{type;detail;constructor(e,r){super(e),this.type=e,this.detail=r}};var st=class extends Error{constructor(e){super(`WebRTC transport error: ${e}`),this.name="WebRTCTransportError"}},Ye=class extends st{constructor(e="SDP handshake failed"){super(e),this.name="SDPHandshakeFailedError"}};var vs=class extends st{constructor(e,r){super(`Invalid fingerprint "${e}" within ${r}`),this.name="WebRTC/InvalidFingerprintError"}};var Cs=class extends st{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},_s=class extends st{constructor(e){super(`unsupported hash algorithm code: ${e} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var He;(function(t){let e;(function(a){a.SDP_OFFER="SDP_OFFER",a.SDP_ANSWER="SDP_ANSWER",a.ICE_CANDIDATE="ICE_CANDIDATE"})(e=t.Type||(t.Type={}));let r;(function(a){a[a.SDP_OFFER=0]="SDP_OFFER",a[a.SDP_ANSWER=1]="SDP_ANSWER",a[a.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(r||(r={})),(function(a){a.codec=()=>ir(r)})(e=t.Type||(t.Type={}));let n;t.codec=()=>(n==null&&(n=ot((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),t.Type.codec().encode(a.type,c)),a.data!=null&&(c.uint32(18),c.string(a.data)),f.lengthDelimited!==!1&&c.ldelim()},(a,c,f={})=>{let l={},u=c==null?a.len:a.pos+c;for(;a.pos<u;){let d=a.uint32();switch(d>>>3){case 1:{l.type=t.Type.codec().decode(a);break}case 2:{l.data=a.string();break}default:{a.skipType(d&7);break}}}return l},function*(a,c,f,l={}){let u=c==null?a.len:a.pos+c;for(;a.pos<u;){let d=a.uint32();switch(d>>>3){case 1:{yield{field:`${f}.type`,value:t.Type.codec().decode(a)};break}case 2:{yield{field:`${f}.data`,value:a.string()};break}default:{a.skipType(d&7);break}}}})),n);function o(a){return rt(a,t.codec())}t.encode=o;function s(a,c){return tt(a,t.codec(),c)}t.decode=s;function i(a,c){return nt(a,t.codec(),c)}t.stream=i})(He||(He={}));var Ts=async(t,e,r)=>{try{let n=Promise.withResolvers();for(bg(t,n);;){let o=await Promise.race([n.promise,e.read({signal:r.signal})]);if(o==null){r.signal?.throwIfAborted();break}if(o.type!==He.Type.ICE_CANDIDATE)throw new eo("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){r.onProgress?.(new ze("webrtc:end-of-ice-candidates")),r.log.trace("end-of-candidates received");continue}let i=new xl(s);r.log.trace("%s received new ICE candidate %o",r.direction,s);try{r.onProgress?.(new ze("webrtc:add-ice-candidate",i.candidate)),await t.addIceCandidate(i)}catch(a){r.log.error("%s bad candidate received %o - %e",r.direction,s,a)}}}catch(n){if(r.log.error("%s error parsing ICE candidate - %e",r.direction,n),r.signal?.aborted===!0&&t.connectionState!=="connected")throw n}};function bg(t,e){if(t.connectionState==="connected"){e.resolve();return}t.onconnectionstatechange=r=>{switch(t.connectionState){case"connected":e.resolve();break;case"failed":case"closed":e.reject(new Yn(`RTCPeerConnection connection state became "${t.connectionState}"`));break;default:break}}}function Ls(t){let e;for(let r of t.getComponents())r.name==="p2p"&&(e=Nr(r.value??""));if(e==null)throw new Zn("Remote peerId must be present in multiaddr");return e}async function El({rtcConfiguration:t,dataChannel:e,maxEarlyStreams:r,signal:n,metrics:o,multiaddr:s,connectionManager:i,transportManager:a,log:c,logger:f,onProgress:l}){let{circuitAddress:u,targetPeer:d}=Sl(s);o?.dialerEvents.increment({open:!0}),c.trace("dialing circuit address: %a",u);let p=i.getConnections(d),x;p.length===0?(l?.(new ze("webrtc:dial-relay")),x=await a.dial(u,{signal:n,onProgress:l})):(l?.(new ze("webrtc:reuse-relay-connection")),x=p[0]),l?.(new ze("webrtc:open-signaling-stream"));let w=await x.newStream(Pn,{signal:n,runOnLimitedConnection:!0}),m=ps(w).pb(He),g=new Ss(t);g.addEventListener("connectionstatechange",()=>{g.connectionState==="closed"&&g.close()});let E=new Vt({peerConnection:g,dataChannelOptions:e,maxEarlyStreams:r,metrics:o?.dialerEvents,log:c});try{let b=g.createDataChannel("init");g.onicecandidate=({candidate:R})=>{if(g.connectionState==="connected"){c.trace("ignore new ice candidate as peer connection is already connected");return}if(R==null||R?.candidate===""){c.trace("initiator detected end of ICE candidates");return}let N=JSON.stringify(R?.toJSON()??null);c.trace("initiator sending ICE candidate %o",R),m.write({type:He.Type.ICE_CANDIDATE,data:N},{signal:n}).catch(B=>{c.error("error sending ICE candidate - %e",B)})},g.onicecandidateerror=R=>{c.error("initiator ICE candidate error",R)};let v=await g.createOffer().catch(R=>{throw c.error("could not execute createOffer - %e",R),new Ye("Failed to set createOffer")});c.trace("initiator send SDP offer %s",v.sdp),l?.(new ze("webrtc:send-sdp-offer")),await m.write({type:He.Type.SDP_OFFER,data:v.sdp},{signal:n}),await g.setLocalDescription(v).catch(R=>{throw c.error("could not execute setLocalDescription - %e",R),new Ye("Failed to set localDescription")}),l?.(new ze("webrtc:read-sdp-answer")),c.trace("initiator read SDP answer");let C=await m.read({signal:n});if(C.type!==He.Type.SDP_ANSWER)throw new Ye("Remote should send an SDP answer");c.trace("initiator received SDP answer %s",C.data);let P=new As({type:"answer",sdp:C.data});return await g.setRemoteDescription(P).catch(R=>{throw c.error("could not execute setRemoteDescription - %e",R),new Ye("Failed to set remoteDescription")}),c.trace("initiator read candidates until connected"),l?.(new ze("webrtc:read-ice-candidates")),await Ts(g,m,{direction:"initiator",signal:n,log:c,onProgress:l}),c.trace("initiator connected"),b.readyState!=="open"&&(c.trace("wait for init channel to open"),await Te(b,"open",{signal:n})),c.trace("closing init channel"),b.close(),c.trace("waiting for init channel to close"),await Te(b,"close",{signal:n}),l?.(new ze("webrtc:close-signaling-stream")),c.trace("closing signaling channel"),await w.close({signal:n}),c.trace("initiator connected to remote address %s",s),{remoteAddress:s,peerConnection:g,muxerFactory:E}}catch(b){throw c.error("outgoing signaling error - %e",b),E.close(),g.close(),w.abort(b),b}finally{g.onicecandidate=null,g.onicecandidateerror=null}}var Al=ce(il.matchers[0],ae(290)),Bs=class t extends Lt{transportManager;shutdownController;events;constructor(e,r){super(),this.transportManager=e.transportManager,this.events=e.events,this.shutdownController=r.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(e){e.detail.getAddrs().filter(n=>Al.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(e=>!(e instanceof t)).map(e=>e.getAddrs().filter(r=>Al.exactMatch(r)).map(r=>r.encapsulate("/webrtc"))).flat()}updateAnnounceAddrs(){}async close(){this.events.removeEventListener("transport:listening",this.onTransportListening),this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function vl(t,e,{peerConnection:r,signal:n,log:o}){o.trace("new inbound signaling stream");let s=ps(t).pb(He);try{r.onicecandidate=({candidate:u})=>{if(r.connectionState==="connected"){o.trace("ignore new ice candidate as peer connection is already connected");return}if(u==null||u?.candidate===""){o.trace("recipient detected end of ICE candidates");return}let d=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",d),s.write({type:He.Type.ICE_CANDIDATE,data:d},{signal:n}).catch(p=>{o.error("error sending ICE candidate - %e",p)})},o.trace("recipient read SDP offer");let c=await s.read({signal:n});if(c.type!==He.Type.SDP_OFFER)throw new Ye(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let f=new As({type:"offer",sdp:c.data});await r.setRemoteDescription(f).catch(u=>{throw o.error("could not execute setRemoteDescription - %e",u),new Ye("Failed to set remoteDescription")});let l=await r.createAnswer().catch(u=>{throw o.error("could not execute createAnswer - %e",u),new Ye("Failed to create answer")});o.trace("recipient send SDP answer %s",l.sdp),await s.write({type:He.Type.SDP_ANSWER,data:l.sdp},{signal:n}),await r.setLocalDescription(l).catch(u=>{throw o.error("could not execute setLocalDescription - %e",u),new Ye("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await Ts(r,s,{direction:"recipient",signal:n,log:o})}catch(c){if(r.connectionState!=="connected")throw o.error("error while handling signaling stream from peer %a - %e",e.remoteAddr,c),r.close(),c;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",e.remoteAddr,c)}let i=Ls(e.remoteAddr),a=Kr(`/webrtc/p2p/${i}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:i}}var Ds=class{components;init;log;_started=!1;metrics;shutdownController;constructor(e,r={}){this.components=e,this.init=r,this.log=e.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:e.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[oo]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[wr]=["@libp2p/transport"];[Ic]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(Pn,(e,r)=>{let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(e,r,n).catch(o=>{this.log.error("failed to handle incoming connect from %p - %e",r.remotePeer,o)}).finally(()=>{n.clear()})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(Pn),this._started=!1}createListener(e){return new Bs(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(al.exactMatch)}dialFilter(e){return this.listenFilter(e)}async dial(e,r){this.log.trace("dialing address: %a",e);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await El({rtcConfiguration:await cc(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,maxEarlyStreams:this.init.maxEarlyStreams,multiaddr:e,dataChannelOptions:this.init.dataChannel,signal:r.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,metrics:this.metrics,log:this.log,logger:this.components.logger,onProgress:r.onProgress}),i=Fn({peerConnection:o,remoteAddr:n,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")}),a;try{a=await r.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,remotePeer:Ls(e),muxerFactory:s,onProgress:r.onProgress,signal:r.signal})}catch(c){throw s.close(),o.close(),c}return this._closeOnShutdown(o,i),a}async _onProtocol(e,r,n){let o=new Ss(await cc(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{o.connectionState==="closed"&&o.close()});let s=new Vt({peerConnection:o,dataChannelOptions:this.init.dataChannel,maxEarlyStreams:this.init.maxEarlyStreams,metrics:this.metrics?.listenerEvents,log:this.log});try{let{remoteAddress:i,remotePeer:a}=await vl(e,r,{peerConnection:o,signal:n,log:this.log});await e.close({signal:n});let c=Fn({peerConnection:o,remoteAddr:i,metrics:this.metrics?.listenerEvents,direction:"inbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")});await this.components.upgrader.upgradeInbound(c,{skipEncryption:!0,skipProtection:!0,remotePeer:a,muxerFactory:s,signal:n}),this._closeOnShutdown(o,c)}catch(i){throw this.log.error("incoming signaling error - %e",i),s.close(),o.close(),e.abort(i),i}}_closeOnShutdown(e,r){let n=()=>{r.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection - %e",o)})};this.shutdownController.signal.addEventListener("abort",n),e.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function Sl(t){let e=t.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(e==null)throw new Z("Destination peer id was missing");return{circuitAddress:Kr(t.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:Nr(e)}}var Vr=!!globalThis.process?.env?.DUMP_SESSION_KEYS,fc=16;function uc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}var Is=t=>t?`"${t}" `:"";function Rs(t,e=""){if(typeof t!="boolean")throw new TypeError(Is(e)+"expected boolean, got type="+typeof t);return t}function pr(t,e=""){if(typeof t!="number")throw new TypeError(Is(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(Is(e)+"expected integer >= 0, got "+t);return t}function be(t,e,r=""){if(uc(t)&&(e===void 0||t.length===e))return t;e!==void 0&&pr(e,"length");let n=uc(t),o=e!==void 0?` of length ${e}`:"",s=n?`length=${t.length}`:`type=${typeof t}`,i=Is(r)+"expected Uint8Array"+o+", got "+s;throw n?new RangeError(i):new TypeError(i)}var Cl=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`)};function lc(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function _l(t,e){be(t,void 0,"output");let r=e.outputLen;if(!(t.length>=r))throw new RangeError('"output" expected length >= '+r)}function pt(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function it(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function wg(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Wt=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function xg(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Eg(t){for(let e=0;e<t.length;e++)t[e]=xg(t[e]);return t}var _t=Wt?t=>t:Eg;function Sg(t,e){return!t.byteLength||!e.byteLength?!1:t.buffer===e.buffer&&t.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<t.byteOffset+t.byteLength}function Tl(t,e){if(Sg(t,e)&&t.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function Ll(t,e){return Cl(t,"defaults"),Cl(e,"opts"),Object.assign(t,e)}function Bl(t,e){if(t=be(t),e=be(e),t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Dl(t,e,r){let n=e,o=r||(()=>[]),s=(a,c)=>n(c,...o(a)).update(a).digest(),i=n(new Uint8Array(t),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>n(a,...c),s}var Il=(t,e)=>{function r(n,...o){if(be(n,void 0,"key"),t.nonceLength!==void 0){let u=o[0];be(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let s=t.tagLength,i=t.nonceLength!==void 0?1:0;if(!t.withAAD){for(let u=i;u<o.length;u++)if(uc(o[u]))throw new Error("AAD not supported")}t.withAAD&&o[i]!==void 0&&be(o[i],void 0,"AAD");let a=e(n,...o),c=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");be(d,void 0,"output")}},f=!1;return{encrypt(u,d){if(f)throw new Error("cannot encrypt() twice with same key + nonce");return f=!0,be(u,void 0,"data"),c(a.encrypt.length,d),a.encrypt(u,d)},decrypt(u,d){if(be(u,void 0,"data"),s&&u.length<s)throw new Error('"ciphertext" expected length >= tagLength='+s);return c(a.decrypt.length,d),a.decrypt(u,d)}}}return Object.assign(r,t),r};function Kn(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(be(e,t,"output"),r&&!Hn(e))throw new Error("invalid output, must be aligned");return e}function Rl(t,e,r){pr(t),pr(e),Rs(r);let n=new Uint8Array(16),o=wg(n);return o.setBigUint64(0,BigInt(e),r),o.setBigUint64(8,BigInt(t),r),n}function Hn(t){return t.byteOffset%4===0}function Wr(t){return Uint8Array.from(be(t))}var Ol=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),Ag=_t(pt(Ol("expand 16-byte k"))),vg=_t(pt(Ol("expand 32-byte k")));function ee(t,e){return t<<e|t>>>32-e}var $n=64,Cg=16,dc=2**32-1,Pl=Uint32Array.of();function _g(t,e,r,n,o,s,i,a){let c=o.length,f=new Uint8Array($n),l=pt(f),u=Wt&&Hn(o)&&Hn(s),d=u?pt(o):Pl,p=u?pt(s):Pl;if(!Wt){for(let x=0;x<c;i++){if(t(e,r,n,l,i,a),_t(l),i>=dc)throw new Error("arx: counter overflow");let w=Math.min($n,c-x);for(let m=0,g;m<w;m++)g=x+m,s[g]=o[g]^f[m];x+=w}return}for(let x=0;x<c;i++){if(t(e,r,n,l,i,a),i>=dc)throw new Error("arx: counter overflow");let w=Math.min($n,c-x);if(u&&w===$n){let m=x/4;if(x%4!==0)throw new Error("arx: invalid block position");for(let g=0,E;g<Cg;g++)E=m+g,p[E]=d[E]^l[g];x+=$n;continue}for(let m=0,g;m<w;m++)g=x+m,s[g]=o[g]^f[m];x+=w}}function Nl(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Ll({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return pr(o),pr(i),Rs(s),Rs(r),(a,c,f,l,u=0)=>{be(a,void 0,"key"),be(c,void 0,"nonce"),be(f,void 0,"data");let d=f.length,p=l!==void 0;if(l=Kn(d,l,!1),p&&Tl(f,l),pr(u),u<0||u>=dc)throw new Error("arx: counter overflow");let x=[],w=a.length,m,g;if(w===32)x.push(m=Wr(a)),g=vg;else if(w===16&&r)m=new Uint8Array(32),m.set(a),m.set(a,16),g=Ag,x.push(m);else throw be(a,32,"arx key"),new Error("invalid key size");(!Wt||!Hn(c))&&x.push(c=Wr(c));let E=pt(m);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let C=c.subarray(0,16);if(Wt)n(g,E,pt(C),E);else{let P=_t(Uint32Array.from(g));n(P,E,pt(C),E),it(P),_t(E)}c=c.subarray(16)}else Wt||_t(E);let b=16-o;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let C=new Uint8Array(12);C.set(c,s?0:12-c.length),c=C,x.push(c)}let v=_t(pt(c));try{return _g(t,g,E,v,f,l,u,i),l}finally{it(...x)}}}function Le(t,e){return t[e++]&255|(t[e++]&255)<<8}var hc=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=Wr(be(e,32,"key"));let r=Le(e,0),n=Le(e,2),o=Le(e,4),s=Le(e,6),i=Le(e,8),a=Le(e,10),c=Le(e,12),f=Le(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|f<<8)&8191,this.r[9]=f>>>5&127;for(let l=0;l<8;l++)this.pad[l]=Le(e,16+2*l)}process(e,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],f=i[2],l=i[3],u=i[4],d=i[5],p=i[6],x=i[7],w=i[8],m=i[9],g=Le(e,r+0),E=Le(e,r+2),b=Le(e,r+4),v=Le(e,r+6),C=Le(e,r+8),P=Le(e,r+10),R=Le(e,r+12),N=Le(e,r+14),B=s[0]+(g&8191),I=s[1]+((g>>>13|E<<3)&8191),K=s[2]+((E>>>10|b<<6)&8191),F=s[3]+((b>>>7|v<<9)&8191),q=s[4]+((v>>>4|C<<12)&8191),T=s[5]+(C>>>1&8191),U=s[6]+((C>>>14|P<<2)&8191),L=s[7]+((P>>>11|R<<5)&8191),_=s[8]+((R>>>8|N<<8)&8191),H=s[9]+(N>>>5|o),D=0,S=D+B*a+I*(5*m)+K*(5*w)+F*(5*x)+q*(5*p);D=S>>>13,S&=8191,S+=T*(5*d)+U*(5*u)+L*(5*l)+_*(5*f)+H*(5*c),D+=S>>>13,S&=8191;let h=D+B*c+I*a+K*(5*m)+F*(5*w)+q*(5*x);D=h>>>13,h&=8191,h+=T*(5*p)+U*(5*d)+L*(5*u)+_*(5*l)+H*(5*f),D+=h>>>13,h&=8191;let y=D+B*f+I*c+K*a+F*(5*m)+q*(5*w);D=y>>>13,y&=8191,y+=T*(5*x)+U*(5*p)+L*(5*d)+_*(5*u)+H*(5*l),D+=y>>>13,y&=8191;let A=D+B*l+I*f+K*c+F*a+q*(5*m);D=A>>>13,A&=8191,A+=T*(5*w)+U*(5*x)+L*(5*p)+_*(5*d)+H*(5*u),D+=A>>>13,A&=8191;let O=D+B*u+I*l+K*f+F*c+q*a;D=O>>>13,O&=8191,O+=T*(5*m)+U*(5*w)+L*(5*x)+_*(5*p)+H*(5*d),D+=O>>>13,O&=8191;let k=D+B*d+I*u+K*l+F*f+q*c;D=k>>>13,k&=8191,k+=T*a+U*(5*m)+L*(5*w)+_*(5*x)+H*(5*p),D+=k>>>13,k&=8191;let M=D+B*p+I*d+K*u+F*l+q*f;D=M>>>13,M&=8191,M+=T*c+U*a+L*(5*m)+_*(5*w)+H*(5*x),D+=M>>>13,M&=8191;let $=D+B*x+I*p+K*d+F*u+q*l;D=$>>>13,$&=8191,$+=T*f+U*c+L*a+_*(5*m)+H*(5*w),D+=$>>>13,$&=8191;let z=D+B*w+I*x+K*p+F*d+q*u;D=z>>>13,z&=8191,z+=T*l+U*f+L*c+_*a+H*(5*m),D+=z>>>13,z&=8191;let W=D+B*m+I*w+K*x+F*p+q*d;D=W>>>13,W&=8191,W+=T*u+U*l+L*f+_*c+H*a,D+=W>>>13,W&=8191,D=(D<<2)+D|0,D=D+S|0,S=D&8191,D=D>>>13,h+=D,s[0]=S,s[1]=h,s[2]=y,s[3]=A,s[4]=O,s[5]=k,s[6]=M,s[7]=$,s[8]=z,s[9]=W}finalize(){let{h:e,pad:r}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+r[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+r[a]|0)+(i>>>16)|0,e[a]=i&65535;it(n)}update(e){lc(this),be(e),e=Wr(e);let{buffer:r,blockLen:n}=this,o=e.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,it(this.h,this.r,this.buffer,this.pad)}digestInto(e){lc(this),_l(e,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:o}=this;if(o){for(r[o++]=1;o<16;o++)r[o]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}},Ul=Dl(32,t=>new hc(t));function Tg(t,e,r,n,o,s=20){let i=t[0],a=t[1],c=t[2],f=t[3],l=e[0],u=e[1],d=e[2],p=e[3],x=e[4],w=e[5],m=e[6],g=e[7],E=o,b=r[0],v=r[1],C=r[2],P=i,R=a,N=c,B=f,I=l,K=u,F=d,q=p,T=x,U=w,L=m,_=g,H=E,D=b,S=v,h=C;for(let A=0;A<s;A+=2)P=P+I|0,H=ee(H^P,16),T=T+H|0,I=ee(I^T,12),P=P+I|0,H=ee(H^P,8),T=T+H|0,I=ee(I^T,7),R=R+K|0,D=ee(D^R,16),U=U+D|0,K=ee(K^U,12),R=R+K|0,D=ee(D^R,8),U=U+D|0,K=ee(K^U,7),N=N+F|0,S=ee(S^N,16),L=L+S|0,F=ee(F^L,12),N=N+F|0,S=ee(S^N,8),L=L+S|0,F=ee(F^L,7),B=B+q|0,h=ee(h^B,16),_=_+h|0,q=ee(q^_,12),B=B+q|0,h=ee(h^B,8),_=_+h|0,q=ee(q^_,7),P=P+K|0,h=ee(h^P,16),L=L+h|0,K=ee(K^L,12),P=P+K|0,h=ee(h^P,8),L=L+h|0,K=ee(K^L,7),R=R+F|0,H=ee(H^R,16),_=_+H|0,F=ee(F^_,12),R=R+F|0,H=ee(H^R,8),_=_+H|0,F=ee(F^_,7),N=N+q|0,D=ee(D^N,16),T=T+D|0,q=ee(q^T,12),N=N+q|0,D=ee(D^N,8),T=T+D|0,q=ee(q^T,7),B=B+I|0,S=ee(S^B,16),U=U+S|0,I=ee(I^U,12),B=B+I|0,S=ee(S^B,8),U=U+S|0,I=ee(I^U,7);let y=0;n[y++]=i+P|0,n[y++]=a+R|0,n[y++]=c+N|0,n[y++]=f+B|0,n[y++]=l+I|0,n[y++]=u+K|0,n[y++]=d+F|0,n[y++]=p+q|0,n[y++]=x+T|0,n[y++]=w+U|0,n[y++]=m+L|0,n[y++]=g+_|0,n[y++]=E+H|0,n[y++]=b+D|0,n[y++]=v+S|0,n[y++]=C+h|0}var Lg=Nl(Tg,{counterRight:!1,counterLength:4,allowShortKeys:!1});var Bg=new Uint8Array(16),kl=(t,e)=>{t.update(e);let r=e.length%16;r&&t.update(Bg.subarray(r))},Dg=new Uint8Array(32);function Ml(t,e,r,n,o){o!==void 0&&be(o,void 0,"AAD");let s=t(e,r,Dg),i=Rl(n.length,o?o.length:0,!0),a=Ul.create(s);o&&kl(a,o),kl(a,n),a.update(i);let c=a.digest();return it(s,i),c}var Ig=t=>(e,r,n)=>({encrypt(s,i){let a=s.length;i=Kn(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);t(e,r,c,c,1);let f=Ml(t,e,r,c,n);return i.set(f,a),it(f),i},decrypt(s,i){i=Kn(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),f=Ml(t,e,r,a,n);if(!Bl(c,f))throw it(f),new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,r,i,i,1),it(f),i}}),pc=Il({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},Ig(Lg));function Fl(t,e,r){return tr(t),r===void 0&&(r=new Uint8Array(t.outputLen)),vn(t,r,e)}var zn=Uint8Array.of(0),Rg=Uint8Array.of();function Kl(t,e,r,n=32,o){tr(t),Qe(n,"length"),ke(e,void 0,"prk");let s=t.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(n>255*s)throw new Error("Length must be <= 255*HashLen");let i=Math.ceil(n/s);if(r===void 0?r=Rg:ke(r,void 0,"info"),!i)return o&&Ve(e),new Uint8Array;let a=o&&i===1?e:new Uint8Array(i*s),{iHash:c,oHash:f}=vn.create(t,e),l=o?e:new Uint8Array(s),u=i>1?o?.iHash||t.create():void 0;for(let p=0;p<i-1;p++){zn[0]=p+1;let x=c._cloneInto(u);p&&x.update(l),x.update(r).update(zn).digestInto(l),f._cloneInto(u).update(l).digestInto(l),a.set(l,s*p)}if(zn[0]=i,i>1&&c.update(l),c.update(r).update(zn).digestInto(l),f.update(l).digestInto(l),a.set(l,s*(i-1)),c.destroy(),f.destroy(),u?.destroy(),l!==a&&Ve(l),Ve(zn),n===a.length)return a;let d=a.slice(0,n);return Ve(a),d}var Hl={hashSHA256(t){return ft(t.subarray())},getHKDF(t,e){let r=Fl(ft,e,t),o=Kl(ft,r,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let t=gn.utils.randomSecretKey();return{publicKey:gn.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:gn.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return gn.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,r,n){return pc(n,e,r).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,r,n,o){return pc(n,e,r).decrypt(t.subarray(),o)}};var $l=Hl;function zl(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,r)=>t.generateX25519SharedKey(e.privateKey,r).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}var jr=t=>{let e=xe(2);return e[0]=t>>8,e[1]=t,e};jr.bytes=2;var Gr=t=>{if(t.length<2)throw RangeError("Could not decode int16BE");if(t instanceof Uint8Array){let e=0;return e+=t[0]<<8,e+=t[1],e}return t.getUint16(0)};Gr.bytes=2;function ql(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"})}}function mc(t,e){!e.enabled||!Vr||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${j(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${j(t.privateKey,"hex")}`)):e("Missing local static keys."))}function gc(t,e){!e.enabled||!Vr||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${j(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${j(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Vl(t,e){!e.enabled||!Vr||e(t?`REMOTE_STATIC_PUBLIC_KEY ${j(t.subarray(),"hex")}`:"Missing remote static public key.")}function yc(t,e){!e.enabled||!Vr||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${j(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function bc(t,e,r){!r.enabled||!Vr||(r(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&j(t.k,"hex")}`),r(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&j(e.k,"hex")}`))}var Yr=class t extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=t.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var Pg=0,Og=4294967295,Ng="Cipherstate has reached maximum n, a new handshake must be performed",Ps=class{n;bytes;view;constructor(e=Pg){this.n=e,this.bytes=we(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>Og)throw new Error(Ng)}};var mr=we(0),Xr=class{k;n;crypto;constructor(e,r=void 0,n=0){this.crypto=e,this.k=r,this.n=new Ps(n)}hasKey(){return!!this.k}encryptWithAd(e,r){if(!this.hasKey())return r;this.n.assertValue();let n=this.crypto.encrypt(r,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,r,n){if(!this.hasKey())return r;this.n.assertValue();let o=this.crypto.decrypt(r,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},wc=class{cs;ck;h;crypto;constructor(e,r){this.crypto=e;let n=Q(r,"utf-8");this.h=Ug(e,n),this.ck=this.h,this.cs=new Xr(e)}mixKey(e){let[r,n]=this.crypto.hkdf(this.ck,e);this.ck=r,this.cs=new Xr(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new Y(this.h,e))}encryptAndHash(e){let r=this.cs.encryptWithAd(this.h,e);return this.mixHash(r),r}decryptAndHash(e){let r=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),r}split(){let[e,r]=this.crypto.hkdf(this.ck,mr);return[new Xr(this.crypto,e),new Xr(this.crypto,r)]}},xc=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:r,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:f}=e;this.crypto=r,this.ss=new wc(r,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=f}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<r+32)throw new Error("message is not long enough");this.re=e.sublist(r,r+32),this.ss.mixHash(this.re)}readS(e,r=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<r+n)throw new Error("message is not long enough");let o=e.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},qn=class extends xc{writeMessageA(e){return new Y(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let r=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new Y(r,n,this.ss.encryptAndHash(e))}writeMessageC(e){let r=this.writeS();return this.writeSE(),new Y(r,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(r){throw new Yr(`handshake stage 0 validation fail: ${r.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let r=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+r))}catch(r){throw new Yr(`handshake stage 1 validation fail: ${r.message}`)}}readMessageC(e){try{let r=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(r))}catch(r){throw new Yr(`handshake stage 2 validation fail: ${r.message}`)}}};function Ug(t,e){if(e.length<=32){let r=we(32);return r.set(e),r}else return t.hash(e)}var Vn;(function(t){let e;t.codec=()=>(e==null&&(e=ot((s,i,a={})=>{if(a.lengthDelimited!==!1&&i.fork(),s.webtransportCerthashes!=null&&s.webtransportCerthashes.length>0)for(let c of s.webtransportCerthashes)i.uint32(10),i.bytes(c);if(s.streamMuxers!=null&&s.streamMuxers.length>0)for(let c of s.streamMuxers)i.uint32(18),i.string(c);a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={webtransportCerthashes:[],streamMuxers:[]},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{if(a.limits?.webtransportCerthashes!=null&&c.webtransportCerthashes.length===a.limits.webtransportCerthashes)throw new ar('Decode error - repeated field "webtransportCerthashes" had too many elements');c.webtransportCerthashes.push(s.bytes());break}case 2:{if(a.limits?.streamMuxers!=null&&c.streamMuxers.length===a.limits.streamMuxers)throw new ar('Decode error - repeated field "streamMuxers" had too many elements');c.streamMuxers.push(s.string());break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let f={webtransportCerthashes:0,streamMuxers:0},l=i==null?s.len:s.pos+i;for(;s.pos<l;){let u=s.uint32();switch(u>>>3){case 1:{if(c.limits?.webtransportCerthashes!=null&&f.webtransportCerthashes===c.limits.webtransportCerthashes)throw new ar('Streaming decode error - repeated field "webtransportCerthashes" had too many elements');yield{field:`${a}.webtransportCerthashes[]`,index:f.webtransportCerthashes,value:s.bytes()},f.webtransportCerthashes++;break}case 2:{if(c.limits?.streamMuxers!=null&&f.streamMuxers===c.limits.streamMuxers)throw new ar('Streaming decode error - repeated field "streamMuxers" had too many elements');yield{field:`${a}.streamMuxers[]`,index:f.streamMuxers,value:s.string()},f.streamMuxers++;break}default:{s.skipType(u&7);break}}}})),e);function r(s){return rt(s,t.codec())}t.encode=r;function n(s,i){return tt(s,t.codec(),i)}t.decode=n;function o(s,i){return nt(s,t.codec(),i)}t.stream=o})(Vn||(Vn={}));var Wn;(function(t){let e;t.codec=()=>(e==null&&(e=ot((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.identityKey!=null&&s.identityKey.byteLength>0&&(i.uint32(10),i.bytes(s.identityKey)),s.identitySig!=null&&s.identitySig.byteLength>0&&(i.uint32(18),i.bytes(s.identitySig)),s.extensions!=null&&(i.uint32(34),Vn.codec().encode(s.extensions,i)),a.lengthDelimited!==!1&&i.ldelim()},(s,i,a={})=>{let c={identityKey:we(0),identitySig:we(0)},f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{c.identityKey=s.bytes();break}case 2:{c.identitySig=s.bytes();break}case 4:{c.extensions=Vn.codec().decode(s,s.uint32(),{limits:a.limits?.extensions});break}default:{s.skipType(l&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.identityKey`,value:s.bytes()};break}case 2:{yield{field:`${a}.identitySig`,value:s.bytes()};break}case 4:{yield*Vn.codec().stream(s,s.uint32(),`${a}.extensions`,{limits:c.limits?.extensions});break}default:{s.skipType(l&7);break}}}})),e);function r(s){return rt(s,t.codec())}t.encode=r;function n(s,i){return tt(s,t.codec(),i)}t.decode=n;function o(s,i){return nt(s,t.codec(),i)}t.stream=o})(Wn||(Wn={}));async function Sc(t,e,r){let n=await t.sign(jl(e));return Wn.encode({identityKey:Rt(t.publicKey),identitySig:n,extensions:r})}async function Ac(t,e,r){try{let n=Wn.decode(t),o=Du(n.identityKey),s=Ou(o);if(r!=null&&!r.equals(s))throw new Error(`Payload peer id ${s} does not match expected remote peer id ${r}`);if(!e)throw new Error("Remote static does not exist");let i=jl(e);if(!await o.verify(i,n.identitySig))throw new Error("Invalid payload signature");return{payload:n,remotePeer:s}}catch(n){throw new jn(n.message)}}function jl(t){let e=Q("noise-libp2p-static-key:");return t instanceof Uint8Array?Ue([e,t],e.length+t.length):(t.prepend(e),t)}var Ec=class extends qt{stream;handshake;metrics;decoder;constructor(e,r,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=r,this.metrics=n,this.decoder=new ms({lengthDecoder:Gr,maxBufferSize:16*1024*1024,encodingLength:()=>2});let o=c=>{try{for(let f of this.decoder.decode(c.data))this.onData(this.decrypt(f))}catch(f){this.abort(f)}};this.stream.addEventListener("message",o);let s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){let r=new Y;for(let n=0;n<e.byteLength;n+=65519){let o=n+65519;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),r.append(jr(s.byteLength)),r.append(s)}return r}decrypt(e){let r=new Y;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-fc<n)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(n,o):s=e.sublist(n,o);let i=e.subarray(n,o-fc);try{let a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),r.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return r}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function vc(t,e,r){return new Ec(t,e,r)}async function Gl(t,e){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remotePeer:c,extensions:f}=t,l=await Sc(s,a.publicKey,f),u=new qn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});mc(u.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(u.writeMessageA(mr),e),r.trace("Stage 0 - Initiator finished sending first message."),gc(u.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");let d=u.readMessageB(await n.read(e));r.trace("Stage 1 - Initiator received the message."),yc(u.re,r),Vl(u.rs,r),r.trace("Initiator going to check remote's signature...");let p=await Ac(d,u.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(u.writeMessageC(l),e),r.trace("Stage 2 - Initiator sent message with signed payload.");let[x,w]=u.ss.split();return bc(x,w,r),{payload:p.payload,remotePeer:p.remotePeer,encrypt:m=>x.encryptWithAd(mr,m),decrypt:(m,g)=>w.decryptWithAd(mr,m,g)}}async function Yl(t,e){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remotePeer:c,extensions:f}=t,l=await Sc(s,a.publicKey,f),u=new qn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});mc(u.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),u.readMessageA(await n.read(e)),r.trace("Stage 0 - Responder received first message."),yc(u.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(u.writeMessageB(l),e),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),gc(u.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");let d=u.readMessageC(await n.read(e));r.trace("Stage 2 - Responder received the message, finished handshake.");let p=await Ac(d,u.rs,c),[x,w]=u.ss.split();return bc(x,w,r),{payload:p.payload,remotePeer:p.remotePeer,encrypt:m=>w.encryptWithAd(mr,m),decrypt:(m,g)=>x.decryptWithAd(mr,m,g)}}var Ns=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,r={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=r,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=s??$l;this.crypto=zl(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?ql(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??we(0)}[Symbol.toStringTag]="@libp2p/noise";[wr]=["@libp2p/connection-encryption","@libp2p/noise"];async secureOutbound(e,r){let n=e.log?.newScope("noise")??this.log,o=hs(e,{lengthEncoder:jr,lengthDecoder:Gr,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,r?.remotePeer,r);return{connection:vc(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:s.remotePeer,streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let r=this.components.upgrader.getStreamMuxers();if(r!=null)for(let n of e){let o=r.get(n);if(o!=null)return o}if(e.length)throw new Gn("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,r){let n=e.log?.newScope("noise")??this.log,o=hs(e,{lengthEncoder:jr,lengthDecoder:Gr,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,r?.remotePeer,r);return{connection:vc(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:s.remotePeer,streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Gl({connection:e,privateKey:r,remotePeer:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Yl({connection:e,privateKey:r,remotePeer:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function Xl(t={}){return e=>new Ns(e,t)}var Cc=Object.values(Qt).map(t=>t.decoder).reduce((t,e)=>t.or(e)),kg=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m,Mg=/^a=ice-ufrag:(?<ufrag>[^\r\n]+)$/m,Fg=/^a=ice-pwd:(?<pwd>[^\r\n]+)$/m;function Zl(t){return t?.match(kg)?.groups?.fingerprint}function Ql(t){if(t!=null)return t.match(Mg)?.groups?.ufrag}function _c(t){if(t!=null)return t.match(Fg)?.groups?.pwd}function Tc(t){let r=t.getComponents().find(n=>n.code===466)?.value;if(r===void 0||r==="")throw new Z(`Couldn't find a certhash component of multiaddr: ${t.toString()}`);return r}function Kg(t){return Xe.decode(Cc.decode(t))}function Hg(t){let e=Kg(Tc(t)),r=$g(e.code),n=e.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new vs(n,t.toString());return`${r} ${o.join(":").toUpperCase()}`}function Jl(t){let e=t.split(":").map(o=>parseInt(o,16)),r=Uint8Array.from(e),n=Ne(mt.code,r);return Kr(`/certhash/${rn.encode(n.bytes)}`)}function $g(t){switch(t){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new _s(t)}}function ed(t,e){let{host:r,port:n,type:o}=Ya(t);if(o!=="ip4"&&o!=="ip6")throw new Z(`Multiaddr ${t} was not an IPv4 or IPv6 address`);let s=Hg(t);return{type:"answer",sdp:`v=0
3
3
  o=- 0 0 IN IP${o==="ip4"?4:6} ${r}
4
4
  s=-
5
5
  t=0 0
@@ -13,10 +13,10 @@ a=ice-pwd:${e}
13
13
  a=fingerprint:${s}
14
14
  a=setup:passive
15
15
  a=sctp-port:5000
16
- a=max-message-size:${ur}
16
+ a=max-message-size:${lr}
17
17
  a=candidate:1467250027 1 UDP 1467250027 ${r} ${n} typ host
18
18
  a=end-of-candidates
19
- `}}function ed(t,e,r=e){let{host:n,port:o,type:s}=Za(t);if(s!=="ip4"&&s!=="ip6")throw new Z(`Multiaddr ${t} was not an IPv4 or IPv6 address`);return{type:"offer",sdp:`v=0
19
+ `}}function td(t,e,r=e){let{host:n,port:o,type:s}=Ya(t);if(s!=="ip4"&&s!=="ip6")throw new Z(`Multiaddr ${t} was not an IPv4 or IPv6 address`);return{type:"offer",sdp:`v=0
20
20
  o=- 0 0 IN IP${s==="ip4"?4:6} ${n}
21
21
  s=-
22
22
  c=IN IP${s==="ip4"?4:6} ${n}
@@ -29,15 +29,15 @@ a=ice-ufrag:${e}
29
29
  a=ice-pwd:${r}
30
30
  a=fingerprint:sha-256 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00
31
31
  a=sctp-port:5000
32
- a=max-message-size:${ur}
32
+ a=max-message-size:${lr}
33
33
  a=candidate:1467250027 1 UDP 1467250027 ${n} ${o} typ host
34
34
  a=end-of-candidates
35
- `}}function td(t,e){if(t.sdp===void 0)throw new Z("Can't munge a missing SDP");let r=t.sdp.includes(`\r
35
+ `}}function rd(t,e){if(t.sdp===void 0)throw new Z("Can't munge a missing SDP");let r=t.sdp.includes(`\r
36
36
  `)?`\r
37
37
  `:`
38
38
  `;try{t.sdp=t.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
39
39
  a=ice-ufrag:`+e+r).replace(/\na=ice-pwd:[^\n]*\n/,`
40
- a=ice-pwd:`+e+r)}catch{}return t}var Dc=Q("libp2p-webrtc-noise:");function nd(t,e,r){let n=t.trim().toLowerCase().replaceAll(":",""),o=Q(n,"hex"),s=Ne(mt.code,o),i=Tc.decode(Bc(e)),a=Dc.byteLength+s.bytes.byteLength+i.byteLength;return r==="server"?Ue([Dc,i,s.bytes],a):Ue([Dc,s.bytes,i],a)}var od=/^[A-Za-z0-9+/]+$/,Ug=4,kg=22,sd=256;function id(t){return t.length>=Ug&&t.length<=sd&&od.test(t)}function ad(t){return t.length>=kg&&t.length<=sd&&od.test(t)}function cd(t){return`${fl}${t}`}function Mg(t,e){return t.role==="server"}async function Fg(t,e,r,n){let o=td({type:e.type,sdp:e.sdp},r);try{n.trace("client setting munged local offer %s",o.sdp),await t.setLocalDescription(o)}catch(i){if(i.name!=="InvalidModificationError")throw i;return n("runtime rejected the munged local offer - %e",i),!1}let s=t.localDescription?.sdp;return Zl(s)===r&&Lc(s)===r}async function Kg(t,e,r,n){if(n.version===1){let i=await Fg(t,e,r,n.log);if(n.onMungeable?.(i),i)return r;if(n.fallback!==!0)throw new st("SDP munging is not available in this runtime so WebRTC Direct v1 cannot be used");n.log("SDP munging is not available in this runtime, continuing as WebRTC Direct v2")}t.localDescription==null&&(n.log.trace("client setting local offer %s",e.sdp),await t.setLocalDescription(e));let o=Lc(t.localDescription?.sdp);if(o==null||!ad(o))throw new st("Could not read a valid local ICE password from local description for v2 dial");let s=cd(o);if(!id(s))throw new st("Local ICE password is too long to encode in a v2 server ufrag");return s}async function fd(t,e,r,n){let o=t.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let u=await t.createOffer();n.log.trace("client created local offer %s",u.sdp);let d=await Kg(t,u,r,n),p=Jl(n.remoteAddr,d);n.log.trace("client setting server description %s",p.sdp),await t.setRemoteDescription(p)}else{let u=n.remoteUfrag??r,d=n.remotePwd??u,p=ed(n.remoteAddr,u,d);n.log.trace("server setting client %s %s",p.type,p.sdp),await t.setRemoteDescription(p),n.log.trace("server creating local answer");let w=await t.createAnswer();n.log.trace("server created local answer"),n.log.trace("server setting local description %s",w.sdp),await t.setLocalDescription(w)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await Te(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),Mg(n,t)){let u=t.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(Ql(u))}let s=Xl(t.localDescription?.sdp);if(s==null)throw new st("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=nd(s,n.remoteAddr,n.role),a=Yl({prologueBytes:i})(n),c=Kn({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),f=Hn({peerConnection:t,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(t.addEventListener("connectionstatechange",()=>{switch(t.connectionState){case"failed":case"disconnected":case"closed":f.close().catch(u=>{n.log.error("error closing connection - %e",u),f.abort(u)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let u=await a.secureInbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});return n.log.trace("%s upgrade outbound",n.role),await n.upgrader.upgradeOutbound(f,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let l=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});f.remoteAddr=f.remoteAddr.encapsulate(`/p2p/${l.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(f,{skipProtection:!0,skipEncryption:!0,remotePeer:l.remotePeer,muxerFactory:e,signal:n.signal})}catch(s){throw e.close(),o.close(),t.close(),s}}async function ud(t,e,r={}){let n=r.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof r.rtcConfiguration=="function"?await r.rtcConfiguration():r.rtcConfiguration,s=new RTCPeerConnection({...o??{},certificates:[n]}),i=new qt({peerConnection:s,metrics:r.events,log:r.log,dataChannelOptions:r.dataChannel,maxEarlyStreams:r.maxEarlyStreams});return{peerConnection:s,muxerFactory:i}}var Ms=class{log;metrics;components;init;mungeable;constructor(e,r={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=r;let n=r.dialerVersion;if(n!=null&&n!==1&&n!==2)throw new Z(`Unknown WebRTC Direct dialer version "${String(n)}"`);e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[io]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[wr]=["@libp2p/transport"];async dial(e,r){this.log("dial %a",e),r.signal.throwIfAborted();let n,o=e.getComponents().findLast(u=>u.code===421)?.value;o!=null&&(n=Nr(o));let s=this.init.dialerVersion??(this.mungeable===!1?2:1),i=s===2?As(32,""):As(32,Pn),a=s===2?As(22,""):i,c=s;this.log("dial %a starting as WebRTC Direct v%d",e,s);let{peerConnection:f,muxerFactory:l}=await ud("client",i,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},events:this.metrics?.dialerEvents,log:this.log,dataChannel:this.init.dataChannel,maxEarlyStreams:this.init.maxEarlyStreams,pwd:a});try{return await fd(f,l,i,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:r.signal,version:s,fallback:this.init.dialerVersion==null,onMungeable:d=>{this.mungeable??=d,!d&&this.init.dialerVersion==null&&(c=2)},remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:r.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(u){throw this.log("dial %a failed as WebRTC Direct v%d - %e",e,c,u),f.close(),u}}createListener(e){throw new Ts("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(ol.exactMatch)}};function Hg(t){return e=>new Ms(e,t)}function $g(t){return e=>new Rs(e,t)}return bd(zg);})();
40
+ a=ice-pwd:`+e+r)}catch{}return t}var Lc=Q("libp2p-webrtc-noise:");function od(t,e,r){let n=t.trim().toLowerCase().replaceAll(":",""),o=Q(n,"hex"),s=Ne(mt.code,o),i=Cc.decode(Tc(e)),a=Lc.byteLength+s.bytes.byteLength+i.byteLength;return r==="server"?Ue([Lc,i,s.bytes],a):Ue([Lc,s.bytes,i],a)}var sd=/^[A-Za-z0-9+/]+$/,zg=4,qg=22,id=256;function ad(t){return t.length>=zg&&t.length<=id&&sd.test(t)}function cd(t){return t.length>=qg&&t.length<=id&&sd.test(t)}function fd(t){return`${fl}${t}`}function Vg(t,e){return t.role==="server"}async function Wg(t,e,r,n){let o=rd({type:e.type,sdp:e.sdp},r);try{n.trace("client setting munged local offer %s",o.sdp),await t.setLocalDescription(o)}catch(i){if(i.name!=="InvalidModificationError")throw i;return n("runtime rejected the munged local offer - %e",i),!1}let s=t.localDescription?.sdp;return Ql(s)===r&&_c(s)===r}async function jg(t,e,r,n){if(n.version===1){let i=await Wg(t,e,r,n.log);if(n.onMungeable?.(i),i)return r;if(n.fallback!==!0)throw new st("SDP munging is not available in this runtime so WebRTC Direct v1 cannot be used");n.log("SDP munging is not available in this runtime, continuing as WebRTC Direct v2")}t.localDescription==null&&(n.log.trace("client setting local offer %s",e.sdp),await t.setLocalDescription(e));let o=_c(t.localDescription?.sdp);if(o==null||!cd(o))throw new st("Could not read a valid local ICE password from local description for v2 dial");let s=fd(o);if(!ad(s))throw new st("Local ICE password is too long to encode in a v2 server ufrag");return s}async function ud(t,e,r,n){let o=t.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let u=await t.createOffer();n.log.trace("client created local offer %s",u.sdp);let d=await jg(t,u,r,n),p=ed(n.remoteAddr,d);n.log.trace("client setting server description %s",p.sdp),await t.setRemoteDescription(p)}else{let u=n.remoteUfrag??r,d=n.remotePwd??u,p=td(n.remoteAddr,u,d);n.log.trace("server setting client %s %s",p.type,p.sdp),await t.setRemoteDescription(p),n.log.trace("server creating local answer");let x=await t.createAnswer();n.log.trace("server created local answer"),n.log.trace("server setting local description %s",x.sdp),await t.setLocalDescription(x)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await Te(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),Vg(n,t)){let u=t.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(Jl(u))}let s=Zl(t.localDescription?.sdp);if(s==null)throw new st("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=od(s,n.remoteAddr,n.role),a=Xl({prologueBytes:i})(n),c=Mn({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),f=Fn({peerConnection:t,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(t.addEventListener("connectionstatechange",()=>{switch(t.connectionState){case"failed":case"disconnected":case"closed":f.close().catch(u=>{n.log.error("error closing connection - %e",u),f.abort(u)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let u=await a.secureInbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});return n.log.trace("%s upgrade outbound",n.role),await n.upgrader.upgradeOutbound(f,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let l=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});f.remoteAddr=f.remoteAddr.encapsulate(`/p2p/${l.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(f,{skipProtection:!0,skipEncryption:!0,remotePeer:l.remotePeer,muxerFactory:e,signal:n.signal})}catch(s){throw e.close(),o.close(),t.close(),s}}async function ld(t,e,r={}){let n=r.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof r.rtcConfiguration=="function"?await r.rtcConfiguration():r.rtcConfiguration,s=new RTCPeerConnection({...o??{},certificates:[n]}),i=new Vt({peerConnection:s,metrics:r.events,log:r.log,dataChannelOptions:r.dataChannel,maxEarlyStreams:r.maxEarlyStreams});return{peerConnection:s,muxerFactory:i}}var Us=class{log;metrics;components;init;mungeable;constructor(e,r={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=r;let n=r.dialerVersion;if(n!=null&&n!==1&&n!==2)throw new Z(`Unknown WebRTC Direct dialer version "${String(n)}"`);e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[oo]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[wr]=["@libp2p/transport"];async dial(e,r){this.log("dial %a",e),r.signal.throwIfAborted();let n,o=e.getComponents().findLast(u=>u.code===421)?.value;o!=null&&(n=Nr(o));let s=this.init.dialerVersion??(this.mungeable===!1?2:1),i=s===2?Es(32,""):Es(32,Rn),a=s===2?Es(22,""):i,c=s;this.log("dial %a starting as WebRTC Direct v%d",e,s);let{peerConnection:f,muxerFactory:l}=await ld("client",i,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},events:this.metrics?.dialerEvents,log:this.log,dataChannel:this.init.dataChannel,maxEarlyStreams:this.init.maxEarlyStreams,pwd:a});try{return await ud(f,l,i,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:r.signal,version:s,fallback:this.init.dialerVersion==null,onMungeable:d=>{this.mungeable??=d,!d&&this.init.dialerVersion==null&&(c=2)},remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:r.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(u){throw this.log("dial %a failed as WebRTC Direct v%d - %e",e,c,u),f.close(),u}}createListener(e){throw new Cs("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(ol.exactMatch)}};function Gg(t){return e=>new Us(e,t)}function Yg(t){return e=>new Ds(e,t)}return wd(Xg);})();
41
41
  /*! Bundled license information:
42
42
 
43
43
  @noble/curves/utils.js: