@libp2p/webrtc 6.0.24-a34745c01 → 6.0.25

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,43 +1,43 @@
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 Ni=Object.defineProperty;var am=Object.getOwnPropertyDescriptor;var cm=Object.getOwnPropertyNames;var fm=Object.prototype.hasOwnProperty;var z=(t,e)=>{for(var r in e)Ni(t,r,{get:e[r],enumerable:!0})},um=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of cm(e))!fm.call(t,o)&&o!==r&&Ni(t,o,{get:()=>e[o],enumerable:!(n=am(e,o))||n.enumerable});return t};var hm=t=>um(Ni({},"__esModule",{value:!0}),t);var Yw={};z(Yw,{webRTC:()=>Xw,webRTCDirect:()=>Ww});var jo=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},Go=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},j=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},Or=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var Wo=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},Xo=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},Pr=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var rt=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Un=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var Yo=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},Zo=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Jo=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Qo=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var or=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var es=class extends Event{data;constructor(e,r){super("message",r),this.data=e}},Ur=class extends Event{error;local;constructor(e,r,n){super("close",n),this.error=r,this.local=e}},ts=class extends Ur{constructor(e,r){super(!0,e,r)}},rs=class extends Ur{constructor(e,r){super(!1,e,r)}};var Fi=Symbol.for("@libp2p/peer-id");var ns=Symbol.for("@libp2p/transport");var Vu;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Vu||(Vu={}));function lm(t){return typeof t?.handleEvent=="function"}function dm(t){return(t!==!0&&t!==!1&&t?.once)??!1}var Bt=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=dm(n);super.addEventListener(e,i=>{if(o){let a=this.#e.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==r),this.#e.set(i.type,a))}lm(r)?r.handleEvent(i):r(i)},n);let s=this.#e.get(e);s==null&&(s=[],this.#e.set(e,s)),s.push({callback:r,once:o})}removeEventListener(e,r,n){super.removeEventListener(e.toString(),r??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==r),this.#e.set(e,o))}safeDispatchEvent(e,r={}){return this.dispatchEvent(new CustomEvent(e,r))}};var Nr=Symbol.for("@libp2p/service-capabilities"),$u=Symbol.for("@libp2p/service-dependencies");var zi={};z(zi,{base58btc:()=>le,base58flickr:()=>Em});var T1=new Uint8Array(0);function qu(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 mt(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return sr(t);if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return sr(new Uint8Array(t.buffer,t.byteOffset,t.byteLength));throw new Error("Unknown type, must be binary type")}function ju(t){return new TextEncoder().encode(t)}function Gu(t){return new TextDecoder().decode(t)}function pm(t){return t?.buffer instanceof ArrayBuffer}function sr(t){return pm(t)?t:t.slice()}function mm(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=t.length,c=t.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var y=0,l=0,g=0,E=d.length;g!==E&&d[g]===0;)g++,y++;for(var C=(E-g)*u+1>>>0,_=new Uint8Array(C);g!==E;){for(var B=d[g],R=0,D=C-1;(B!==0||R<l)&&D!==-1;D--,R++)B+=256*_[D]>>>0,_[D]=B%a>>>0,B=B/a>>>0;if(B!==0)throw new Error("Non-zero carry");l=R,g++}for(var I=C-l;I!==C&&_[I]===0;)I++;for(var U=c.repeat(y);I<C;++I)U+=t.charAt(_[I]);return U}function m(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var y=0;if(d[y]!==" "){for(var l=0,g=0;d[y]===c;)l++,y++;for(var E=(d.length-y)*f+1>>>0,C=new Uint8Array(E);d[y];){var _=r[d.charCodeAt(y)];if(_===255)return;for(var B=0,R=E-1;(_!==0||B<g)&&R!==-1;R--,B++)_+=a*C[R]>>>0,C[R]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");g=B,y++}if(d[y]!==" "){for(var D=E-g;D!==E&&C[D]===0;)D++;for(var I=new Uint8Array(l+(E-D)),U=l;D!==E;)I[U++]=C[D++];return I}}}function p(d){var y=m(d);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:m,decode:p}}var gm=mm,ym=gm,Xu=ym;var Mi=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")}},ki=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 Yu(this,e)}},Ki=class{decoders;constructor(e){this.decoders=e}or(e){return Yu(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 Yu(t,e){return new Ki({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var Hi=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 Mi(e,r,n),this.decoder=new ki(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Fr({name:t,prefix:e,encode:r,decode:n}){return new Hi(t,e,r,n)}function Rt({name:t,prefix:e,alphabet:r}){let{encode:n,decode:o}=Xu(r,t);return Fr({prefix:e,name:t,encode:n,decode:s=>mt(o(s))})}function bm(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 u=e[t[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|u,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 xm(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 wm(t){let e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function he({name:t,prefix:e,bitsPerChar:r,alphabet:n}){let o=wm(n);return Fr({prefix:e,name:t,encode(s){return xm(s,n,r)},decode(s){return bm(s,o,r,t)}})}var le=Rt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Em=Rt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Vi={};z(Vi,{base32:()=>Ot,base32hex:()=>Cm,base32hexpad:()=>Im,base32hexpadupper:()=>Tm,base32hexupper:()=>Lm,base32pad:()=>Am,base32padupper:()=>vm,base32upper:()=>Sm,base32z:()=>_m});var Ot=he({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Sm=he({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Am=he({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),vm=he({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Cm=he({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Lm=he({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Im=he({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Tm=he({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),_m=he({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var $i={};z($i,{base36:()=>Nn,base36upper:()=>Dm});var Nn=Rt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Dm=Rt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var je={};z(je,{Digest:()=>ir,create:()=>Oe,decode:()=>Kr,equals:()=>ji,hasCode:()=>Xm});var Bm=Qu,Zu=128,Rm=127,Om=~Rm,Pm=Math.pow(2,31);function Qu(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Pm;)e[r++]=t&255|Zu,t/=128;for(;t&Om;)e[r++]=t&255|Zu,t>>>=7;return e[r]=t|0,Qu.bytes=r-n+1,e}var Um=qi,Nm=128,Ju=127;function qi(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw qi.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&Ju)<<o:(i&Ju)*Math.pow(2,o),o+=7}while(i>=Nm);return qi.bytes=s-n,r}var Fm=Math.pow(2,7),Mm=Math.pow(2,14),km=Math.pow(2,21),Km=Math.pow(2,28),Hm=Math.pow(2,35),zm=Math.pow(2,42),Vm=Math.pow(2,49),$m=Math.pow(2,56),qm=Math.pow(2,63),jm=function(t){return t<Fm?1:t<Mm?2:t<km?3:t<Km?4:t<Hm?5:t<zm?6:t<Vm?7:t<$m?8:t<qm?9:10},Gm={encode:Bm,decode:Um,encodingLength:jm},Wm=Gm,Fn=Wm;function Mn(t,e=0){return[Fn.decode(t,e),Fn.decode.bytes]}function Mr(t,e,r=0){return Fn.encode(t,e,r),e}function kr(t){return Fn.encodingLength(t)}function Oe(t,e){let r=e.byteLength,n=kr(t),o=n+kr(r),s=new Uint8Array(o+r);return Mr(t,s,0),Mr(r,s,n),s.set(e,o),new ir(t,r,e,s)}function Kr(t){let e=mt(t),[r,n]=Mn(e),[o,s]=Mn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new ir(r,o,i,e)}function ji(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&qu(t.bytes,r.bytes)}}var ir=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=sr(n),this.bytes=sr(o)}};function Xm(t,e){return t.code===e}function eh(t,e){let{bytes:r,version:n}=t;return n===0?Zm(r,Gi(t),e??le.encoder):Jm(r,Gi(t),e??Ot.encoder)}var th=new WeakMap;function Gi(t){let e=th.get(t);if(e==null){let r=new Map;return th.set(t,r),r}return e}var ge=class t{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=sr(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!==kn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Qm)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=Oe(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&&ji(e.multihash,n.multihash)}toString(e){return eh(this,e)}toJSON(){return{"/":eh(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??rh(n,o,s.bytes))}else if(r[e0]===!0){let{version:n,multihash:o,code:s}=r,i=Kr(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!==kn)throw new Error(`Version 0 CID must use dag-pb (code: ${kn}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=rh(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,kn,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=mt(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 ir(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[h,m]=Mn(e.subarray(r));return r+=m,h},o=n(),s=kn;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,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,r){let[n,o]=Ym(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 Gi(s).set(n,e),s}};function Ym(t,e){switch(t[0]){case"Q":{let r=e??le;return[le.prefix,r.decode(`${le.prefix}${t}`)]}case le.prefix:{let r=e??le;return[le.prefix,r.decode(t)]}case Ot.prefix:{let r=e??Ot;return[Ot.prefix,r.decode(t)]}case Nn.prefix:{let r=e??Nn;return[Nn.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 Zm(t,e,r){let{prefix:n}=r;if(n!==le.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 Jm(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 kn=112,Qm=18;function rh(t,e,r){let n=kr(t),o=n+kr(e),s=new Uint8Array(o+r.byteLength);return Mr(t,s,0),Mr(e,s,n),s.set(r,o),s}var e0=Symbol.for("@ipld/js-cid/CID");var Wi={};z(Wi,{identity:()=>Ge});var nh=0,t0="identity",oh=mt;function r0(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 Oe(nh,oh(t))}var Ge={code:nh,name:t0,encode:oh,digest:r0};function Pe(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 n0(t){return t.buffer instanceof ArrayBuffer}function Ue(t){return n0(t)?t:t.slice()}async function sh(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,Ue(e),Ue(r.subarray()));return n?.signal?.throwIfAborted(),s}function gt(t=0){return new Uint8Array(t)}function Kn(t=0){return new Uint8Array(t)}function Xi(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=Kn(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}function ih(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 ch=Symbol.for("@achingbrain/uint8arraylist");function ah(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 ss(t){return!!t?.[ch]}var V=class t{bufs;length;[ch]=!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(ss(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(ss(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=ah(this.bufs,e);return r.buf[r.index]}set(e,r){let n=ah(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(ss(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 Xi(n,o)}subarray(e,r){let{bufs:n,length:o}=this._subList(e,r);return n.length===1?n[0]:Xi(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,u=r>a&&r<=c;if(f&&u){if(e===a&&r===c){n.push(i);break}let h=e-a;n.push(i.subarray(h,h+(r-e)));break}if(f){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){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(!ss(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 h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let h=r;h<=c;h+=u){u=0;for(let m=f;m>=0;m--){let p=this.get(h+m);if(n[m]!==p){u=Math.max(1,m-a[p]);break}}if(u===0)return h}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=Kn(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=gt(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=gt(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=gt(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=Kn(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=gt(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=gt(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=gt(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=gt(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=gt(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(!ih(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 Yi={};z(Yi,{base10:()=>o0});var o0=Rt({prefix:"9",name:"base10",alphabet:"0123456789"});var Zi={};z(Zi,{base16:()=>s0,base16upper:()=>i0});var s0=he({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),i0=he({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ji={};z(Ji,{base2:()=>a0});var a0=he({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Qi={};z(Qi,{base256emoji:()=>l0});var fh=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}"),c0=fh.reduce((t,e,r)=>(t[r]=e,t),[]),f0=fh.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function u0(t){return t.reduce((e,r)=>(e+=c0[r],e),"")}function h0(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=f0[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var l0=Fr({prefix:"\u{1F680}",name:"base256emoji",encode:u0,decode:h0});var ea={};z(ea,{base64:()=>d0,base64pad:()=>p0,base64url:()=>Hn,base64urlpad:()=>m0});var d0=he({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),p0=he({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Hn=he({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),m0=he({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ta={};z(ta,{base8:()=>g0});var g0=he({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ra={};z(ra,{identity:()=>y0});var y0=Fr({prefix:"\0",name:"identity",encode:t=>Gu(t),decode:t=>ju(t)});var m2=new TextEncoder,g2=new TextDecoder;var sa={};z(sa,{sha256:()=>yt,sha512:()=>E0});var w0=20;function oa({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new na(t,e,r,n,o)}var na=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??w0,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?uh(n,this.code,r?.truncate):n.then(o=>uh(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function uh(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 Oe(e,t)}function lh(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var yt=oa({name:"sha2-256",code:18,encode:lh("SHA-256")}),E0=oa({name:"sha2-512",code:19,encode:lh("SHA-512")});var ar={...ra,...Ji,...ta,...Yi,...Zi,...Vi,...$i,...zi,...ea,...Qi},T2={...sa,...Wi};function cr(t=0){return new Uint8Array(t)}function ph(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var dh=ph("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ia=ph("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=cr(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),S0={utf8:dh,"utf-8":dh,hex:ar.base16,latin1:ia,ascii:ia,binary:ia,...ar},is=S0;function re(t,e="utf8"){let r=is[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function X(t,e="utf8"){let r=is[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}var A0=parseInt("11111",2),aa=parseInt("10000000",2),v0=parseInt("01111111",2),mh={0:zn,1:zn,2:C0,3:T0,4:_0,5:I0,6:L0,16:zn,22:zn,48:zn};function bt(t,e={offset:0}){let r=t[e.offset]&A0;if(e.offset++,mh[r]!=null)return mh[r](t,e);throw new Error("No decoder for tag "+r)}function Vn(t,e){let r=0;if((t[e.offset]&aa)===aa){let n=t[e.offset]&v0,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=t[e.offset].toString(16).padStart(2,"0");r=parseInt(o,16)}else r=t[e.offset],e.offset++;return r}function zn(t,e){Vn(t,e);let r=[];for(;!(e.offset>=t.byteLength);){let n=bt(t,e);if(n===null)break;r.push(n)}return r}function C0(t,e){let r=Vn(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 L0(t,e){let r=Vn(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 u=0;for(let h=0;h<c.length;h++)u+=c[h]<<h*7;a+=`.${u}`,c=[]}}return a}function I0(t,e){return e.offset++,null}function T0(t,e){let r=Vn(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 _0(t,e){let r=Vn(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function D0(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);let r=new V;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function ca(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);let e=D0(t.byteLength);return new V(Uint8Array.from([e.byteLength|aa]),e)}function Ne(t){let e=new V,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new V(Uint8Array.from([2]),ca(e),e)}function as(t){let e=Uint8Array.from([0]),r=new V(e,t);return new V(Uint8Array.from([3]),ca(r),r)}function Pt(t,e=48){let r=new V;for(let n of t)r.append(n);return new V(Uint8Array.from([e]),ca(r),r)}var B0=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),R0=Uint8Array.from([6,5,43,129,4,0,34]),O0=Uint8Array.from([6,5,43,129,4,0,35]),P0={ext:!0,kty:"EC",crv:"P-256"},U0={ext:!0,kty:"EC",crv:"P-384"},N0={ext:!0,kty:"EC",crv:"P-521"},fa=32,ua=48,ha=66;function la(t){let e=bt(t);return gh(e)}function gh(t){let e=t[1][1][0],r=1,n,o;if(e.byteLength===fa*2+1)return n=X(e.subarray(r,r+fa),"base64url"),o=X(e.subarray(r+fa),"base64url"),new Hr({...P0,key_ops:["verify"],x:n,y:o});if(e.byteLength===ua*2+1)return n=X(e.subarray(r,r+ua),"base64url"),o=X(e.subarray(r+ua),"base64url"),new Hr({...U0,key_ops:["verify"],x:n,y:o});if(e.byteLength===ha*2+1)return n=X(e.subarray(r,r+ha),"base64url"),o=X(e.subarray(r+ha),"base64url"),new Hr({...N0,key_ops:["verify"],x:n,y:o});throw new j(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function yh(t){return Pt([Ne(Uint8Array.from([1])),Pt([F0(t.crv)],160),Pt([as(new V(Uint8Array.from([4]),re(t.x??"","base64url"),re(t.y??"","base64url")))],161)]).subarray()}function F0(t){if(t==="P-256")return B0;if(t==="P-384")return R0;if(t==="P-521")return O0;throw new j(`Invalid curve ${t}`)}var Hr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=yh(this.jwk)),this._raw}toMultihash(){return Ge.digest(Ut(this))}toCID(){return ge.createV1(114,this.toMultihash())}toString(){return le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}async verify(e,r,n){return sh(this.jwk,r,e,n)}};function da(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function nt(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(`${r}expected number, got ${typeof t}`)}if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new RangeError(`${r}expected integer >= 0, got ${t}`)}}function Le(t,e,r=""){let n=da(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){let i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return t}function fr(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(nt(t.outputLen),nt(t.blockLen),t.outputLen<1)throw new Error('"outputLen" must be >= 1');if(t.blockLen<1)throw new Error('"blockLen" must be >= 1')}function zr(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function cs(t,e){Le(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function We(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function fs(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Xe(t,e){return t<<32-e|t>>>e}var xh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",M0=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function us(t){if(Le(t),xh)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=M0[t[r]];return e}var xt={_0:48,_9:57,A:65,F:70,a:97,f:102};function bh(t){if(t>=xt._0&&t<=xt._9)return t-xt._0;if(t>=xt.A&&t<=xt.F)return t-(xt.A-10);if(t>=xt.a&&t<=xt.f)return t-(xt.a-10)}function $n(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(xh)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=bh(t.charCodeAt(s)),a=bh(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 pa(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];Le(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 ma(t,e={}){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 wh(t=32){nt(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 ga=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Eh(t,e,r){return t&e^~t&r}function Sh(t,e,r){return t&e^t&r^e&r}var qn=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=fs(this.buffer)}update(e){zr(this),Le(e);let{view:r,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=fs(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){zr(this),cs(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,We(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let h=i;h<o;h++)r[h]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=fs(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,u=this.get();if(f>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<f;h++)a.setUint32(4*h,u[h],s)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},wt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Ee=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var hs=BigInt(4294967295),Ah=BigInt(32);function k0(t,e=!1){return e?{h:Number(t&hs),l:Number(t>>Ah&hs)}:{h:Number(t>>Ah&hs)|0,l:Number(t&hs)|0}}function vh(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}=k0(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var ya=(t,e,r)=>t>>>r,ba=(t,e,r)=>t<<32-r|e>>>r,ur=(t,e,r)=>t>>>r|e<<32-r,hr=(t,e,r)=>t<<32-r|e>>>r,jn=(t,e,r)=>t<<64-r|e>>>r-32,Gn=(t,e,r)=>t>>>r-32|e<<64-r;function ot(t,e,r,n){let o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}var Ch=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Lh=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Ih=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Th=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0,_h=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0),Dh=(t,e,r,n,o,s)=>e+r+n+o+s+(t/2**32|0)|0;var H0=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]),Nt=new Uint32Array(64),xa=class extends qn{constructor(e){super(64,e,8,!1)}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}process(e,r){for(let h=0;h<16;h++,r+=4)Nt[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){let m=Nt[h-15],p=Nt[h-2],d=Xe(m,7)^Xe(m,18)^m>>>3,y=Xe(p,17)^Xe(p,19)^p>>>10;Nt[h]=y+Nt[h-7]+d+Nt[h-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:f,H:u}=this;for(let h=0;h<64;h++){let m=Xe(a,6)^Xe(a,11)^Xe(a,25),p=u+m+Eh(a,c,f)+H0[h]+Nt[h]|0,y=(Xe(n,2)^Xe(n,13)^Xe(n,22))+Sh(n,o,s)|0;u=f,f=c,c=a,a=i+p|0,i=s,s=o,o=n,n=p+y|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,u=u+this.H|0,this.set(n,o,s,i,a,c,f,u)}roundClean(){We(Nt)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),We(this.buffer)}},wa=class extends xa{A=wt[0]|0;B=wt[1]|0;C=wt[2]|0;D=wt[3]|0;E=wt[4]|0;F=wt[5]|0;G=wt[6]|0;H=wt[7]|0;constructor(){super(32)}};var Bh=vh(["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))),z0=Bh[0],V0=Bh[1],Ft=new Uint32Array(80),Mt=new Uint32Array(80),Ea=class extends qn{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:u,Fh:h,Fl:m,Gh:p,Gl:d,Hh:y,Hl:l}=this;return[e,r,n,o,s,i,a,c,f,u,h,m,p,d,y,l]}set(e,r,n,o,s,i,a,c,f,u,h,m,p,d,y,l){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=u|0,this.Fh=h|0,this.Fl=m|0,this.Gh=p|0,this.Gl=d|0,this.Hh=y|0,this.Hl=l|0}process(e,r){for(let C=0;C<16;C++,r+=4)Ft[C]=e.getUint32(r),Mt[C]=e.getUint32(r+=4);for(let C=16;C<80;C++){let _=Ft[C-15]|0,B=Mt[C-15]|0,R=ur(_,B,1)^ur(_,B,8)^ya(_,B,7),D=hr(_,B,1)^hr(_,B,8)^ba(_,B,7),I=Ft[C-2]|0,U=Mt[C-2]|0,M=ur(I,U,19)^jn(I,U,61)^ya(I,U,6),N=hr(I,U,19)^Gn(I,U,61)^ba(I,U,6),b=Ih(D,N,Mt[C-7],Mt[C-16]),v=Th(b,R,M,Ft[C-7],Ft[C-16]);Ft[C]=v|0,Mt[C]=b|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:u,Eh:h,El:m,Fh:p,Fl:d,Gh:y,Gl:l,Hh:g,Hl:E}=this;for(let C=0;C<80;C++){let _=ur(h,m,14)^ur(h,m,18)^jn(h,m,41),B=hr(h,m,14)^hr(h,m,18)^Gn(h,m,41),R=h&p^~h&y,D=m&d^~m&l,I=_h(E,B,D,V0[C],Mt[C]),U=Dh(I,g,_,R,z0[C],Ft[C]),M=I|0,N=ur(n,o,28)^jn(n,o,34)^jn(n,o,39),b=hr(n,o,28)^Gn(n,o,34)^Gn(n,o,39),v=n&s^n&a^s&a,A=o&i^o&c^i&c;g=y|0,E=l|0,y=p|0,l=d|0,p=h|0,d=m|0,{h,l:m}=ot(f|0,u|0,U|0,M|0),f=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let w=Ch(M,b,A);n=Lh(w,U,N,v),o=w|0}({h:n,l:o}=ot(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ot(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ot(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:u}=ot(this.Dh|0,this.Dl|0,f|0,u|0),{h,l:m}=ot(this.Eh|0,this.El|0,h|0,m|0),{h:p,l:d}=ot(this.Fh|0,this.Fl|0,p|0,d|0),{h:y,l}=ot(this.Gh|0,this.Gl|0,y|0,l|0),{h:g,l:E}=ot(this.Hh|0,this.Hl|0,g|0,E|0),this.set(n,o,s,i,a,c,f,u,h,m,p,d,y,l,g,E)}roundClean(){We(Ft,Mt)}destroy(){this.destroyed=!0,We(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Sa=class extends Ea{Ah=Ee[0]|0;Al=Ee[1]|0;Bh=Ee[2]|0;Bl=Ee[3]|0;Ch=Ee[4]|0;Cl=Ee[5]|0;Dh=Ee[6]|0;Dl=Ee[7]|0;Eh=Ee[8]|0;El=Ee[9]|0;Fh=Ee[10]|0;Fl=Ee[11]|0;Gh=Ee[12]|0;Gl=Ee[13]|0;Hh=Ee[14]|0;Hl=Ee[15]|0;constructor(){super(64)}};var st=ma(()=>new wa,ga(1));var ls=ma(()=>new Sa,ga(3));var $=(t,e,r)=>Le(t,e,r),va=nt,Vr=us,ye=(...t)=>pa(...t),$r=t=>$n(t),lr=da,dr=t=>wh(t),ps=BigInt(0),Aa=BigInt(1);function Ye(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new TypeError(r+"expected boolean, got type="+typeof t)}return t}function ms(t){if(typeof t=="bigint"){if(!ds(t))throw new RangeError("positive bigint expected, got "+t)}else va(t);return t}function Ze(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 Wn(t){let e=ms(t).toString(16);return e.length&1?"0"+e:e}function Rh(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?ps:BigInt("0x"+t)}function pr(t){return Rh(us(t))}function Me(t){return Rh(us(kt(Le(t)).reverse()))}function gs(t,e){if(nt(e),e===0)throw new RangeError("zero length");t=ms(t);let r=t.toString(16);if(r.length>e*2)throw new RangeError("number too large");return $n(r.padStart(e*2,"0"))}function Xn(t,e){return gs(t,e).reverse()}function Oh(t,e){if(t=$(t),e=$(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 kt(t){return Uint8Array.from($(t))}function ys(t){if(typeof t!="string")throw new TypeError("ascii string expected, got "+typeof t);return Uint8Array.from(t,(e,r)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${t[r]}" with code ${n} at position ${r}`);return n})}var ds=t=>typeof t=="bigint"&&ps<=t;function $0(t,e,r){return ds(t)&&ds(e)&&ds(r)&&e<=t&&t<r}function Et(t,e,r,n){if(!$0(e,r,n))throw new RangeError("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function qr(t){if(t<ps)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>ps;t>>=Aa,e+=1);return e}var Yn=t=>(Aa<<BigInt(t))-Aa;function Ph(t,e,r){if(nt(t,"hashLen"),nt(e,"qByteLen"),typeof r!="function")throw new TypeError("hmacFn must be a function");let n=l=>new Uint8Array(l),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(t),f=n(t),u=0,h=()=>{c.fill(1),f.fill(0),u=0},m=(...l)=>r(f,ye(c,...l)),p=(l=o)=>{f=m(s,l),c=m(),l.length!==0&&(f=m(i,l),c=m())},d=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let l=0,g=[];for(;l<e;){c=m();let E=c.slice();g.push(E),l+=c.length}return ye(...g)};return(l,g)=>{h(),p(l);let E;for(;(E=g(d()))===void 0;)p();return h(),E}}function ke(t,e={},r={}){if(Object.prototype.toString.call(t)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(t,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=t[s];if(a&&c===void 0)return;let f=typeof c;if(f!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${f}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(r,!0)}var Ca=()=>{throw new Error("not implemented")};var Se=BigInt(0),de=BigInt(1),mr=BigInt(2),Mh=BigInt(3),kh=BigInt(4),Kh=BigInt(5),q0=BigInt(7),Hh=BigInt(8),j0=BigInt(9),zh=BigInt(16);function ae(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 se(t,e,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 Uh(t,e){if(t===Se)throw new Error("invert: expected non-zero number");if(e<=Se)throw new Error("invert: expected positive modulus, got "+e);let r=ae(t,e),n=e,o=Se,s=de,i=de,a=Se;for(;r!==Se;){let f=n/r,u=n-r*f,h=o-i*f,m=s-a*f;n=r,r=u,o=i,s=a,i=h,a=m}if(n!==de)throw new Error("invert: does not exist");return ae(o,e)}function La(t,e,r){let n=t;if(!n.eql(n.sqr(e),r))throw new Error("Cannot find square root")}function Vh(t,e){let r=t,n=(r.ORDER+de)/kh,o=r.pow(e,n);return La(r,o,e),o}function G0(t,e){let r=t,n=(r.ORDER-Kh)/Hh,o=r.mul(e,mr),s=r.pow(o,n),i=r.mul(e,s),a=r.mul(r.mul(i,mr),s),c=r.mul(i,r.sub(a,r.ONE));return La(r,c,e),c}function W0(t){let e=jr(t),r=$h(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+q0)/zh;return((a,c)=>{let f=a,u=f.pow(c,i),h=f.mul(u,n),m=f.mul(u,o),p=f.mul(u,s),d=f.eql(f.sqr(h),c),y=f.eql(f.sqr(m),c);u=f.cmov(u,h,d),h=f.cmov(p,m,y);let l=f.eql(f.sqr(h),c),g=f.cmov(u,h,l);return La(f,g,c),g})}function $h(t){if(t<Mh)throw new Error("sqrt is not defined for small field");let e=t-de,r=0;for(;e%mr===Se;)e/=mr,r++;let n=mr,o=jr(t);for(;Nh(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Vh;let s=o.pow(n,e),i=(e+de)/mr;return function(c,f){let u=c;if(u.is0(f))return f;if(Nh(u,f)!==1)throw new Error("Cannot find square root");let h=r,m=u.mul(u.ONE,s),p=u.pow(f,e),d=u.pow(f,i);for(;!u.eql(p,u.ONE);){if(u.is0(p))return u.ZERO;let y=1,l=u.sqr(p);for(;!u.eql(l,u.ONE);)if(y++,l=u.sqr(l),y===h)throw new Error("Cannot find square root");let g=de<<BigInt(h-y-1),E=u.pow(m,g);h=y,m=u.sqr(E),p=u.mul(p,m),d=u.mul(d,E)}return d}}function X0(t){return t%kh===Mh?Vh:t%Hh===Kh?G0:t%zh===j0?W0(t):$h(t)}var St=(t,e)=>(ae(t,e)&de)===de,Y0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ia(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=Y0.reduce((n,o)=>(n[o]="function",n),e);if(ke(t,r),Ze(t.BYTES,"BYTES"),Ze(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=de)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function Z0(t,e,r){let n=t;if(r<Se)throw new Error("invalid exponent, negatives unsupported");if(r===Se)return n.ONE;if(r===de)return e;let o=n.ONE,s=e;for(;r>Se;)r&de&&(o=n.mul(o,s)),s=n.sqr(s),r>>=de;return o}function Zn(t,e,r=!1){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 Nh(t,e){let r=t,n=(r.ORDER-de)/mr,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 J0(t,e){if(e!==void 0&&va(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=qr(t);if(e!==void 0&&e<r)throw new Error(`invalid n length: expected bit length (${r}) >= n.length (${e})`);let n=e!==void 0?e:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Fh=new WeakMap,bs=class{ORDER;BITS;BYTES;isLE;ZERO=Se;ONE=de;_lengths;_mod;constructor(e,r={}){if(e<=de)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}=J0(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 ae(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&de)===de}neg(e){return ae(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return ae(e*e,this.ORDER)}add(e,r){return ae(e+r,this.ORDER)}sub(e,r){return ae(e-r,this.ORDER)}mul(e,r){return ae(e*r,this.ORDER)}pow(e,r){return Z0(this,e,r)}div(e,r){return ae(e*Uh(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 Uh(e,this.ORDER)}sqrt(e){let r=Fh.get(this);return r||Fh.set(this,r=X0(this.ORDER)),r(this,e)}toBytes(e){return this.isLE?Xn(e,this.BYTES):gs(e,this.BYTES)}fromBytes(e,r=!1){$(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?Me(e):pr(e);if(a&&(c=ae(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Zn(this,e)}cmov(e,r,n){return Ye(n,"condition"),n?r:e}};Object.freeze(bs.prototype);function jr(t,e={}){return new bs(t,e)}function qh(t){if(typeof t!="bigint")throw new Error("field order must be bigint");if(t<=de)throw new Error("field order must be greater than 1");let e=qr(t-de);return Math.ceil(e/8)}function Ta(t){let e=qh(t);return e+Math.ceil(e/2)}function _a(t,e,r=!1){$(t);let n=t.length,o=qh(e),s=Math.max(Ta(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?Me(t):pr(t),a=ae(i,e-de)+de;return r?Xn(a,o):gs(a,o)}var Gr=BigInt(0),gr=BigInt(1);function Jn(t,e){let r=e.negate();return t?r:e}function yr(t,e){let r=Zn(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function Xh(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Da(t,e){Xh(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),o=2**t,s=Yn(t),i=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function jh(t,e,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(t&o),c=t>>i;a>n&&(a-=s,c+=gr);let f=e*n,u=f+Math.abs(a)-1,h=a===0,m=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:m,isNegF:p,offsetF:f}}var Ba=new WeakMap,Yh=new WeakMap;function Ra(t){return Yh.get(t)||1}function Gh(t){if(t!==Gr)throw new Error("invalid wNAF")}var Wr=class{BASE;ZERO;Fn;bits;constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let o=e;for(;r>Gr;)r&gr&&(n=n.add(o)),o=o.double(),r>>=gr;return n}precomputeWindow(e,r){let{windows:n,windowSize:o}=Da(r,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let f=1;f<o;f++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=Da(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:u,isNeg:h,isNegF:m,offsetF:p}=jh(n,a,i);n=c,u?s=s.add(Jn(m,r[p])):o=o.add(Jn(h,r[f]))}return Gh(n),{p:o,f:s}}wNAFUnsafe(e,r,n,o=this.ZERO){let s=Da(e,this.bits);for(let i=0;i<s.windows&&n!==Gr;i++){let{nextN:a,offset:c,isZero:f,isNeg:u}=jh(n,i,s);if(n=a,!f){let h=r[c];o=o.add(u?h.negate():h)}}return Gh(n),o}getPrecomputes(e,r,n){let o=Ba.get(r);return o||(o=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(o=n(o)),Ba.set(r,o))),o}cached(e,r,n){let o=Ra(e);return this.wNAF(o,this.getPrecomputes(o,e,n),r)}unsafe(e,r,n,o){let s=Ra(e);return s===1?this._unsafeLadder(e,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),r,o)}createCache(e,r){Xh(r,this.bits),Yh.set(e,r),Ba.delete(e)}hasCache(e){return Ra(e)!==1}};function Zh(t,e,r,n){let o=e,s=t.ZERO,i=t.ZERO;for(;r>Gr||n>Gr;)r&gr&&(s=s.add(o)),n&gr&&(i=i.add(o)),o=o.double(),r>>=gr,n>>=gr;return{p1:s,p2:i}}function Wh(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ia(e),e}else return jr(t,{isLE:r})}function xs(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let f=e[c];if(!(typeof f=="bigint"&&f>Gr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Wh(e.p,r.Fp,n),s=Wh(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 Xr(t,e){return function(n){let o=t(n);return{secretKey:o,publicKey:e(o)}}}var Kt=BigInt(0),xe=BigInt(1),Oa=BigInt(2),Q0=BigInt(8);function eg(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 Jh(t,e={}){let r=e,n=xs("edwards",t,r,r.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;ke(r,{},{uvRatio:"function"});let c=Oa<<BigInt(s.BYTES*8)-xe,f=y=>o.create(y),u=r.uvRatio===void 0?(y,l)=>{try{return{isValid:!0,value:o.sqrt(o.div(y,l))}}catch{return{isValid:!1,value:Kt}}}:r.uvRatio;if(!eg(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function h(y,l,g=!1){let E=g?xe:Kt;return Et("coordinate "+y,l,E,c),l}function m(y){if(!(y instanceof p))throw new Error("EdwardsPoint expected")}class p{static BASE=new p(i.Gx,i.Gy,xe,f(i.Gx*i.Gy));static ZERO=new p(Kt,xe,xe,Kt);static Fp=o;static Fn=s;X;Y;Z;T;constructor(l,g,E,C){this.X=h("x",l),this.Y=h("y",g),this.Z=h("z",E,!0),this.T=h("t",C),Object.freeze(this)}static CURVE(){return i}static fromAffine(l){if(l instanceof p)throw new Error("extended point not allowed");let{x:g,y:E}=l||{};return h("x",g),h("y",E),new p(g,E,xe,f(g*E))}static fromBytes(l,g=!1){let E=o.BYTES,{a:C,d:_}=i;l=kt($(l,E,"point")),Ye(g,"zip215");let B=kt(l),R=l[E-1];B[E-1]=R&-129;let D=Me(B),I=g?c:o.ORDER;Et("point.y",D,Kt,I);let U=f(D*D),M=f(U-xe),N=f(_*U-C),{isValid:b,value:v}=u(M,N);if(!b)throw new Error("bad point: invalid y coordinate");let A=(v&xe)===xe,w=(R&128)!==0;if(!g&&v===Kt&&w)throw new Error("bad point: x=0 and x_0=1");return w!==A&&(v=f(-v)),p.fromAffine({x:v,y:D})}static fromHex(l,g=!1){return p.fromBytes($r(l),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(l=8,g=!0){return d.createCache(this,l),g||this.multiply(Oa),this}assertValidity(){let l=this,{a:g,d:E}=i;if(l.is0())throw new Error("bad point: ZERO");let{X:C,Y:_,Z:B,T:R}=l,D=f(C*C),I=f(_*_),U=f(B*B),M=f(U*U),N=f(D*g),b=f(U*f(N+I)),v=f(M+f(E*f(D*I)));if(b!==v)throw new Error("bad point: equation left != right (1)");let A=f(C*_),w=f(B*R);if(A!==w)throw new Error("bad point: equation left != right (2)")}equals(l){m(l);let{X:g,Y:E,Z:C}=this,{X:_,Y:B,Z:R}=l,D=f(g*R),I=f(_*C),U=f(E*R),M=f(B*C);return D===I&&U===M}is0(){return this.equals(p.ZERO)}negate(){return new p(f(-this.X),this.Y,this.Z,f(-this.T))}double(){let{a:l}=i,{X:g,Y:E,Z:C}=this,_=f(g*g),B=f(E*E),R=f(Oa*f(C*C)),D=f(l*_),I=g+E,U=f(f(I*I)-_-B),M=D+B,N=M-R,b=D-B,v=f(U*N),A=f(M*b),w=f(U*b),x=f(N*M);return new p(v,A,x,w)}add(l){m(l);let{a:g,d:E}=i,{X:C,Y:_,Z:B,T:R}=this,{X:D,Y:I,Z:U,T:M}=l,N=f(C*D),b=f(_*I),v=f(R*E*M),A=f(B*U),w=f((C+_)*(D+I)-N-b),x=A-v,L=A+v,T=f(b-g*N),S=f(w*x),O=f(L*T),P=f(w*T),F=f(x*L);return new p(S,O,F,P)}subtract(l){return m(l),this.add(l.negate())}multiply(l){if(!s.isValidNot0(l))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:g,f:E}=d.cached(this,l,C=>yr(p,C));return yr(p,[g,E])[0]}multiplyUnsafe(l){if(!s.isValid(l))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return l===Kt?p.ZERO:this.is0()||l===xe?this:d.unsafe(this,l,g=>yr(p,g))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return d.unsafe(this,i.n).is0()}toAffine(l){let g=this,E=l,{X:C,Y:_,Z:B}=g,R=g.is0();E==null&&(E=R?Q0:o.inv(B));let D=f(C*E),I=f(_*E),U=o.mul(B,E);if(R)return{x:Kt,y:xe};if(U!==xe)throw new Error("invZ was invalid");return{x:D,y:I}}clearCofactor(){return a===xe?this:this.multiplyUnsafe(a)}toBytes(){let{x:l,y:g}=this.toAffine(),E=o.toBytes(g);return E[E.length-1]|=l&xe?128:0,E}toHex(){return Vr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let d=new Wr(p,s.BITS);return s.BITS>=8&&p.BASE.precompute(8),Object.freeze(p.prototype),Object.freeze(p),p}var ws=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Ca()}static fromHex(e){Ca()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Vr(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,r){return this.ep.precompute(e,r),this}};function Qh(t,e,r={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=r;ke(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=t,f=n.outputLen,u=2*a.BYTES;if(f!==void 0&&(Ze(f,"hash.outputLen"),f!==u))throw new Error(`hash.outputLen must be ${u}, got ${f}`);let h=o.randomBytes===void 0?dr:o.randomBytes,m=o.adjustScalarBytes===void 0?b=>b:o.adjustScalarBytes,p=o.domain===void 0?(b,v,A)=>{if(Ye(A,"phflag"),v.length||A)throw new Error("Contexts/pre-hash are not supported");return b}:o.domain;function d(b){return c.create(Me(b))}function y(b){let v=D.secretKey;$(b,D.secretKey,"secretKey");let A=$(n(b),2*v,"hashedSecretKey"),w=m(A.slice(0,v)),x=A.slice(v,2*v),L=d(w);return{head:w,prefix:x,scalar:L}}function l(b){let{head:v,prefix:A,scalar:w}=y(b),x=i.multiply(w),L=x.toBytes();return{head:v,prefix:A,scalar:w,point:x,pointBytes:L}}function g(b){return l(b).pointBytes}function E(b=Uint8Array.of(),...v){let A=ye(...v);return d(n(p(A,$(b,void 0,"context"),!!s)))}function C(b,v,A={}){b=$(b,void 0,"message"),s&&(b=s(b));let{prefix:w,scalar:x,pointBytes:L}=l(v),T=E(A.context,w,b),S=i.multiply(T).toBytes(),O=E(A.context,S,L,b),P=c.create(T+O*x);if(!c.isValid(P))throw new Error("sign failed: invalid s");let F=ye(S,c.toBytes(P));return $(F,D.signature,"result")}let _={zip215:o.zip215};function B(b,v,A,w=_){let{context:x}=w,L=w.zip215===void 0?!!_.zip215:w.zip215,T=D.signature;b=$(b,T,"signature"),v=$(v,void 0,"message"),A=$(A,D.publicKey,"publicKey"),L!==void 0&&Ye(L,"zip215"),s&&(v=s(v));let S=T/2,O=b.subarray(0,S),P=Me(b.subarray(S,T)),F,H,K;try{F=t.fromBytes(A,L),H=t.fromBytes(O,L),K=i.multiplyUnsafe(P)}catch{return!1}if(!L&&F.isSmallOrder())return!1;let Q=E(x,O,A,v);return H.add(F.multiplyUnsafe(Q)).subtract(K).clearCofactor().is0()}let R=a.BYTES,D={secretKey:R,publicKey:R,signature:2*R,seed:R};function I(b){return b=b===void 0?h(D.seed):b,$(b,D.seed,"seed")}function U(b){return lr(b)&&b.length===D.secretKey}function M(b,v){try{return!!t.fromBytes(b,v===void 0?_.zip215:v)}catch{return!1}}let N={getExtendedPublicKey:l,randomSecretKey:I,isValidSecretKey:U,isValidPublicKey:M,toMontgomery(b){let{y:v}=t.fromBytes(b),A=D.publicKey,w=A===32;if(!w&&A!==57)throw new Error("only defined for 25519 and 448");let x=w?a.div(xe+v,xe-v):a.div(v-xe,v+xe);return a.toBytes(x)},toMontgomerySecret(b){let v=D.secretKey;$(b,v);let A=n(b.subarray(0,v));return m(A).subarray(0,v)}};return Object.freeze(D),Object.freeze(N),Object.freeze({keygen:Xr(I,g),getPublicKey:g,sign:C,verify:B,utils:N,Point:t,lengths:D})}function Qn(t,e){if(Ze(t),Ze(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(t<0||t>2**(8*e)-1)throw new Error("invalid I2OSP input: "+t);let r=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)r[n]=t&255,t>>>=8;return new Uint8Array(r)}function tg(t,e){let r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t[n]^e[n];return r}function rg(t){if(!lr(t)&&typeof t!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof t=="string"?ys(t):t;if(e.length===0)throw new Error("DST must be non-empty");return e}function Pa(t,e,r,n){$(t),Ze(r),e=rg(e),e.length>255&&(e=n(ye(ys("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(r/o);if(r>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=ye(e,Qn(e.length,1)),c=new Uint8Array(s),f=Qn(r,2),u=new Array(i),h=n(ye(c,t,f,Qn(0,1),a));u[0]=n(ye(h,Qn(1,1),a));for(let p=1;p<i;p++){let d=[tg(h,u[p-1]),Qn(p+1,1),a];u[p]=n(ye(...d))}return ye(...u).slice(0,r)}var el="HashToScalar-";var eo=BigInt(0),Yr=BigInt(1),Es=BigInt(2);function ng(t){return ke(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...t})}function tl(t){let e=ng(t),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i===void 0?dr:i,f=a?255:448,u=a?32:56,h=BigInt(a?9:5),m=BigInt(a?121665:39081),p=a?Es**BigInt(254):Es**BigInt(447),d=a?BigInt(8)*Es**BigInt(251)-Yr:BigInt(4)*Es**BigInt(445)-Yr,y=p+d+Yr,l=A=>ae(A,r),g=E(h);function E(A){return Xn(l(A),u)}function C(A){let w=kt($(A,u,"uCoordinate"));return a&&(w[31]&=127),l(Me(w))}function _(A){return Me(o(kt($(A,u,"scalar"))))}function B(A,w){let x=M(C(w),_(A));if(x===eo)throw new Error("invalid private or public key received");return E(x)}function R(A){return B(A,g)}let D=R,I=B;function U(A,w,x){let L=l(A*(w-x));return w=l(w-L),x=l(x+L),{x_2:w,x_3:x}}function M(A,w){Et("u",A,eo,r),Et("scalar",w,p,y);let x=w,L=A,T=Yr,S=eo,O=A,P=Yr,F=eo;for(let K=BigInt(f-1);K>=eo;K--){let Q=x>>K&Yr;F^=Q,{x_2:T,x_3:O}=U(F,T,O),{x_2:S,x_3:P}=U(F,S,P),F=Q;let ee=T+S,te=l(ee*ee),W=T-S,ie=l(W*W),pt=te-ie,nr=O+P,Rr=O-P,On=l(Rr*ee),Pn=l(nr*W),Hu=On+Pn,zu=On-Pn;O=l(Hu*Hu),P=l(L*l(zu*zu)),T=l(te*ie),S=l(pt*(te+l(m*pt)))}({x_2:T,x_3:O}=U(F,T,O)),{x_2:S,x_3:P}=U(F,S,P);let H=s(S);return l(T*H)}let N={secretKey:u,publicKey:u,seed:u},b=A=>(A=A===void 0?c(u):A,$(A,N.seed,"seed"),A),v={randomSecretKey:b};return Object.freeze(N),Object.freeze(v),Object.freeze({keygen:Xr(b,D),getSharedSecret:I,getPublicKey:D,scalarMult:B,scalarMultBase:R,utils:v,GuBytes:g.slice(),lengths:N})}var og=BigInt(0),At=BigInt(1),rl=BigInt(2),sg=BigInt(3),ig=BigInt(5),ag=BigInt(8),br=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ma={p:br,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ag,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function sl(t){let e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=br,a=t*t%s*t%s,c=se(a,rl,s)*a%s,f=se(c,At,s)*t%s,u=se(f,ig,s)*f%s,h=se(u,e,s)*u%s,m=se(h,r,s)*h%s,p=se(m,n,s)*m%s,d=se(p,o,s)*p%s,y=se(d,o,s)*p%s,l=se(y,e,s)*u%s;return{pow_p_5_8:se(l,rl,s)*t%s,b2:a}}function il(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var Ua=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ka(t,e){let r=br,n=ae(e*e*e,r),o=ae(n*n*e,r),s=sl(t*o).pow_p_5_8,i=ae(t*n*s,r),a=ae(e*i*i,r),c=i,f=ae(i*Ua,r),u=a===t,h=a===ae(-t,r),m=a===ae(-t*Ua,r);return u&&(i=c),(h||m)&&(i=f),St(i,r)&&(i=ae(-i,r)),{isValid:u||h,value:i}}var zt=Jh(Ma,{uvRatio:ka}),Ht=zt.Fp,al=zt.Fn;function cg(t){return Qh(zt,ls,Object.assign({adjustScalarBytes:il,zip215:!0},t))}var cl=cg({});var to=(()=>{let t=br;return tl({P:t,type:"x25519",powPminus2:e=>{let{pow_p_5_8:r,b2:n}=sl(e);return ae(se(r,sg,t)*n,t)},adjustScalarBytes:il})})();var Na=Ua,fg=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),ug=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),hg=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),lg=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),nl=t=>ka(At,t),dg=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Fa=t=>Ht.create(Me(t)&dg);function ol(t){let{d:e}=Ma,r=br,n=g=>Ht.create(g),o=n(Na*t*t),s=n((o+At)*hg),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:f}=ka(s,a),u=n(f*t);St(u,r)||(u=n(-u)),c||(f=u),c||(i=o);let h=n(i*(o-At)*lg-a),m=f*f,p=n((f+f)*a),d=n(h*fg),y=n(At-m),l=n(At+m);return new zt(n(p*l),n(y*d),n(d*l),n(p*y))}var Vt=class t extends ws{static BASE=new t(zt.BASE);static ZERO=new t(zt.ZERO);static Fp=Ht;static Fn=al;constructor(e){super(e)}static fromAffine(e){return new t(zt.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoPoint expected")}init(e){return new t(e)}static fromBytes(e){Le(e,32);let{a:r,d:n}=Ma,o=br,s=_=>Ht.create(_),i=Fa(e);if(!Oh(Ht.toBytes(i),e)||St(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(At+r*a),f=s(At-r*a),u=s(c*c),h=s(f*f),m=s(r*n*u-h),{isValid:p,value:d}=nl(s(m*h)),y=s(d*f),l=s(d*y*m),g=s((i+i)*y);St(g,o)&&(g=s(-g));let E=s(c*l),C=s(g*E);if(!p||St(C,o)||E===og)throw new Error("invalid ristretto255 encoding 2");return new t(new zt(g,E,At,C))}static fromHex(e){return t.fromBytes($n(e))}toBytes(){let{X:e,Y:r,Z:n,T:o}=this.ep,s=br,i=l=>Ht.create(l),a=i(i(n+r)*i(n-r)),c=i(e*r),f=i(c*c),{value:u}=nl(i(a*f)),h=i(u*a),m=i(u*c),p=i(h*m*o),d;if(St(o*p,s)){let l=i(r*Na),g=i(e*Na);e=l,r=g,d=i(h*ug)}else d=m;St(e*p,s)&&(r=i(-r));let y=i((n-r)*d);return St(y,s)&&(y=i(-y)),Ht.toBytes(y)}equals(e){this.assertSame(e);let{X:r,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=f=>Ht.create(f),a=i(r*s)===i(n*o),c=i(n*s)===i(r*o);return a||c}is0(){return this.equals(t.ZERO)}};Object.freeze(Vt.BASE);Object.freeze(Vt.ZERO);Object.freeze(Vt.prototype);Object.freeze(Vt);var pg=Object.freeze({Point:Vt,hashToCurve(t,e){let r=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=Pa(t,r,64,ls);return pg.deriveToCurve(n)},hashToScalar(t,e={DST:el}){let r=Pa(t,e.DST,64,ls);return al.create(Me(r))},deriveToCurve(t){Le(t,64);let e=Fa(t.subarray(0,32)),r=ol(e),n=Fa(t.subarray(32,64)),o=ol(n);return new Vt(r.add(o))}});var ro=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Ss=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ve={get(t=globalThis){let e=t.crypto;if(e?.subtle==null)throw new Ss("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var As=32;var Ka,mg=(async()=>{try{return await Ve.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function gg(t,e,r){if(t.buffer instanceof ArrayBuffer){let n=await Ve.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await Ve.get().subtle.verify({name:"Ed25519"},n,Ue(e),Ue(r instanceof Uint8Array?r:r.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function yg(t,e,r){return cl.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}async function fl(t,e,r){return Ka==null&&(Ka=await mg),Ka?gg(t,e,r):yg(t,e,r)}function bg(t){return t?.buffer instanceof ArrayBuffer}function Ha(t){if(bg(t))return t;let e=t.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function it(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=cr(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return Ha(r)}function vs(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var Cs=class{type="Ed25519";raw;constructor(e){this.raw=za(e,As)}toMultihash(){return Ge.digest(Ut(this))}toCID(){return ge.createV1(114,this.toMultihash())}toString(){return le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();let o=fl(this.raw,r,e);return vs(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Va(t){return t=za(t,As),new Cs(t)}function za(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new j(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}function hl(t=0){return new Uint8Array(t)}var wg=Math.pow(2,7),Eg=Math.pow(2,14),Sg=Math.pow(2,21),$a=Math.pow(2,28),qa=Math.pow(2,35),ja=Math.pow(2,42),Ga=Math.pow(2,49),Z=128,Ie=127;function ce(t){if(t<wg)return 1;if(t<Eg)return 2;if(t<Sg)return 3;if(t<$a)return 4;if(t<qa)return 5;if(t<ja)return 6;if(t<Ga)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function no(t,e,r=0){switch(ce(t)){case 8:e[r++]=t&255|Z,t/=128;case 7:e[r++]=t&255|Z,t/=128;case 6:e[r++]=t&255|Z,t/=128;case 5:e[r++]=t&255|Z,t/=128;case 4:e[r++]=t&255|Z,t>>>=7;case 3:e[r++]=t&255|Z,t>>>=7;case 2:e[r++]=t&255|Z,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function Ag(t,e,r=0){switch(ce(t)){case 8:e.set(r++,t&255|Z),t/=128;case 7:e.set(r++,t&255|Z),t/=128;case 6:e.set(r++,t&255|Z),t/=128;case 5:e.set(r++,t&255|Z),t/=128;case 4:e.set(r++,t&255|Z),t>>>=7;case 3:e.set(r++,t&255|Z),t>>>=7;case 2:e.set(r++,t&255|Z),t>>>=7;case 1:{e.set(r++,t&255),t>>>=7;break}default:throw new Error("unreachable")}return e}function oo(t,e){let r=t[e],n=0;if(n+=r&Ie,r<Z||(r=t[e+1],n+=(r&Ie)<<7,r<Z)||(r=t[e+2],n+=(r&Ie)<<14,r<Z)||(r=t[e+3],n+=(r&Ie)<<21,r<Z)||(r=t[e+4],n+=(r&Ie)*$a,r<Z)||(r=t[e+5],n+=(r&Ie)*qa,r<Z)||(r=t[e+6],n+=(r&Ie)*ja,r<Z)||(r=t[e+7],n+=(r&Ie)*Ga,r<Z))return n;throw new RangeError("Could not decode varint")}function vg(t,e){let r=t.get(e),n=0;if(n+=r&Ie,r<Z||(r=t.get(e+1),n+=(r&Ie)<<7,r<Z)||(r=t.get(e+2),n+=(r&Ie)<<14,r<Z)||(r=t.get(e+3),n+=(r&Ie)<<21,r<Z)||(r=t.get(e+4),n+=(r&Ie)*$a,r<Z)||(r=t.get(e+5),n+=(r&Ie)*qa,r<Z)||(r=t.get(e+6),n+=(r&Ie)*ja,r<Z)||(r=t.get(e+7),n+=(r&Ie)*Ga,r<Z))return n;throw new RangeError("Could not decode varint")}function Ls(t,e,r=0){return e==null&&(e=hl(ce(t))),e instanceof Uint8Array?no(t,e,r):Ag(t,e,r)}function Zr(t,e=0){return t instanceof Uint8Array?oo(t,e):vg(t,e)}var Wa=new Float32Array([-0]),$t=new Uint8Array(Wa.buffer);function ll(t,e,r){Wa[0]=t,e[r]=$t[0],e[r+1]=$t[1],e[r+2]=$t[2],e[r+3]=$t[3]}function dl(t,e){return $t[0]=t[e],$t[1]=t[e+1],$t[2]=t[e+2],$t[3]=t[e+3],Wa[0]}var Xa=new Float64Array([-0]),Te=new Uint8Array(Xa.buffer);function pl(t,e,r){Xa[0]=t,e[r]=Te[0],e[r+1]=Te[1],e[r+2]=Te[2],e[r+3]=Te[3],e[r+4]=Te[4],e[r+5]=Te[5],e[r+6]=Te[6],e[r+7]=Te[7]}function ml(t,e){return Te[0]=t[e],Te[1]=t[e+1],Te[2]=t[e+2],Te[3]=t[e+3],Te[4]=t[e+4],Te[5]=t[e+5],Te[6]=t[e+6],Te[7]=t[e+7],Xa[0]}var Cg=BigInt(Number.MAX_SAFE_INTEGER),Lg=BigInt(Number.MIN_SAFE_INTEGER),Ke=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 xr;if(e<Cg&&e>Lg)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>gl&&(o=0n,++n>gl&&(n=0n))),new t(Number(o),Number(n))}static fromNumber(e){if(e===0)return xr;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):xr}},xr=new Ke(0,0);xr.toBigInt=function(){return 0n};xr.zzEncode=xr.zzDecode=function(){return this};xr.length=function(){return 1};var gl=4294967296n;function yl(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 bl(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 Ya(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 Je(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function Ts(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}var Za=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=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,Je(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 Je(this,4);return Ts(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Je(this,4);return Ts(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Je(this,4);let e=dl(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Je(this,4);let e=ml(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 Je(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let e=this.bytes();return bl(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Je(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Je(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 Ke(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 Je(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 Je(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 Je(this,8);let e=Ts(this.buf,this.pos+=4),r=Ts(this.buf,this.pos+=4);return new Ke(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=oo(this.buf,this.pos);return this.pos+=ce(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 so(t){return new Za(t instanceof Uint8Array?t:t.subarray())}function qt(t,e,r){let n=so(t);return e.decode(n,void 0,r)}function wr(t=0){return new Uint8Array(t)}var rc={};z(rc,{base10:()=>Og});var CS=new Uint8Array(0);function wl(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 vt(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function El(t){return new TextEncoder().encode(t)}function Sl(t){return new TextDecoder().decode(t)}function Ig(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=t.length,c=t.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var y=0,l=0,g=0,E=d.length;g!==E&&d[g]===0;)g++,y++;for(var C=(E-g)*u+1>>>0,_=new Uint8Array(C);g!==E;){for(var B=d[g],R=0,D=C-1;(B!==0||R<l)&&D!==-1;D--,R++)B+=256*_[D]>>>0,_[D]=B%a>>>0,B=B/a>>>0;if(B!==0)throw new Error("Non-zero carry");l=R,g++}for(var I=C-l;I!==C&&_[I]===0;)I++;for(var U=c.repeat(y);I<C;++I)U+=t.charAt(_[I]);return U}function m(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var y=0;if(d[y]!==" "){for(var l=0,g=0;d[y]===c;)l++,y++;for(var E=(d.length-y)*f+1>>>0,C=new Uint8Array(E);d[y];){var _=r[d.charCodeAt(y)];if(_===255)return;for(var B=0,R=E-1;(_!==0||B<g)&&R!==-1;R--,B++)_+=a*C[R]>>>0,C[R]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");g=B,y++}if(d[y]!==" "){for(var D=E-g;D!==E&&C[D]===0;)D++;for(var I=new Uint8Array(l+(E-D)),U=l;D!==E;)I[U++]=C[D++];return I}}}function p(d){var y=m(d);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:m,decode:p}}var Tg=Ig,_g=Tg,vl=_g;var Ja=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")}},Qa=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 Cl(this,e)}},ec=class{decoders;constructor(e){this.decoders=e}or(e){return Cl(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 Cl(t,e){return new ec({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var tc=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 Ja(e,r,n),this.decoder=new Qa(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Jr({name:t,prefix:e,encode:r,decode:n}){return new tc(t,e,r,n)}function jt({name:t,prefix:e,alphabet:r}){let{encode:n,decode:o}=vl(r,t);return Jr({prefix:e,name:t,encode:n,decode:s=>vt(o(s))})}function Dg(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 u=e[t[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|u,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 Bg(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 Rg(t){let e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function pe({name:t,prefix:e,bitsPerChar:r,alphabet:n}){let o=Rg(n);return Jr({prefix:e,name:t,encode(s){return Bg(s,n,r)},decode(s){return Dg(s,o,r,t)}})}var Og=jt({prefix:"9",name:"base10",alphabet:"0123456789"});var nc={};z(nc,{base16:()=>Pg,base16upper:()=>Ug});var Pg=pe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ug=pe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var oc={};z(oc,{base2:()=>Ng});var Ng=pe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var sc={};z(sc,{base256emoji:()=>Hg});var Ll=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Fg=Ll.reduce((t,e,r)=>(t[r]=e,t),[]),Mg=Ll.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function kg(t){return t.reduce((e,r)=>(e+=Fg[r],e),"")}function Kg(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=Mg[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var Hg=Jr({prefix:"\u{1F680}",name:"base256emoji",encode:kg,decode:Kg});var ic={};z(ic,{base32:()=>Qr,base32hex:()=>qg,base32hexpad:()=>Gg,base32hexpadupper:()=>Wg,base32hexupper:()=>jg,base32pad:()=>Vg,base32padupper:()=>$g,base32upper:()=>zg,base32z:()=>Xg});var Qr=pe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),zg=pe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Vg=pe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),$g=pe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),qg=pe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),jg=pe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Gg=pe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Wg=pe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Xg=pe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ac={};z(ac,{base36:()=>io,base36upper:()=>Yg});var io=jt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Yg=jt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var cc={};z(cc,{base58btc:()=>at,base58flickr:()=>Zg});var at=jt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Zg=jt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var fc={};z(fc,{base64:()=>Jg,base64pad:()=>Qg,base64url:()=>ey,base64urlpad:()=>ty});var Jg=pe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Qg=pe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ey=pe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ty=pe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var uc={};z(uc,{base8:()=>ry});var ry=pe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var hc={};z(hc,{identity:()=>ny});var ny=Jr({prefix:"\0",name:"identity",encode:t=>Sl(t),decode:t=>El(t)});var HS=new TextEncoder,zS=new TextDecoder;var dc={};z(dc,{identity:()=>Ly});var iy=_l,Il=128,ay=127,cy=~ay,fy=Math.pow(2,31);function _l(t,e,r){e=e||[],r=r||0;for(var n=r;t>=fy;)e[r++]=t&255|Il,t/=128;for(;t&cy;)e[r++]=t&255|Il,t>>>=7;return e[r]=t|0,_l.bytes=r-n+1,e}var uy=lc,hy=128,Tl=127;function lc(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw lc.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&Tl)<<o:(i&Tl)*Math.pow(2,o),o+=7}while(i>=hy);return lc.bytes=s-n,r}var ly=Math.pow(2,7),dy=Math.pow(2,14),py=Math.pow(2,21),my=Math.pow(2,28),gy=Math.pow(2,35),yy=Math.pow(2,42),by=Math.pow(2,49),xy=Math.pow(2,56),wy=Math.pow(2,63),Ey=function(t){return t<ly?1:t<dy?2:t<py?3:t<my?4:t<gy?5:t<yy?6:t<by?7:t<xy?8:t<wy?9:10},Sy={encode:iy,decode:uy,encodingLength:Ey},Ay=Sy,ao=Ay;function co(t,e=0){return[ao.decode(t,e),ao.decode.bytes]}function en(t,e,r=0){return ao.encode(t,e,r),e}function tn(t){return ao.encodingLength(t)}function nn(t,e){let r=e.byteLength,n=tn(t),o=n+tn(r),s=new Uint8Array(o+r);return en(t,s,0),en(r,s,n),s.set(e,o),new rn(t,r,e,s)}function Dl(t){let e=vt(t),[r,n]=co(e),[o,s]=co(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new rn(r,o,i,e)}function Bl(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&wl(t.bytes,r.bytes)}}var rn=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}};var Rl=0,vy="identity",Ol=vt;function Cy(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 nn(Rl,Ol(t))}var Ly={code:Rl,name:vy,encode:Ol,digest:Cy};var gc={};z(gc,{sha256:()=>Ty,sha512:()=>_y});var Iy=20;function mc({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new pc(t,e,r,n,o)}var pc=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??Iy,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?Pl(n,this.code,r?.truncate):n.then(o=>Pl(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function Pl(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 nn(e,t)}function Nl(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var Ty=mc({name:"sha2-256",code:18,encode:Nl("SHA-256")}),_y=mc({name:"sha2-512",code:19,encode:Nl("SHA-512")});function Fl(t,e){let{bytes:r,version:n}=t;return n===0?By(r,yc(t),e??at.encoder):Ry(r,yc(t),e??Qr.encoder)}var Ml=new WeakMap;function yc(t){let e=Ml.get(t);if(e==null){let r=new Map;return Ml.set(t,r),r}return e}var Ds=class t{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:r}=this;if(e!==uo)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Oy)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=nn(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&&Bl(e.multihash,n.multihash)}toString(e){return Fl(this,e)}toJSON(){return{"/":Fl(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??kl(n,o,s.bytes))}else if(r[Py]===!0){let{version:n,multihash:o,code:s}=r,i=Dl(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!==uo)throw new Error(`Version 0 CID must use dag-pb (code: ${uo}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=kl(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,uo,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=vt(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 rn(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[h,m]=co(e.subarray(r));return r+=m,h},o=n(),s=uo;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,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,r){let[n,o]=Dy(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 yc(s).set(n,e),s}};function Dy(t,e){switch(t[0]){case"Q":{let r=e??at;return[at.prefix,r.decode(`${at.prefix}${t}`)]}case at.prefix:{let r=e??at;return[at.prefix,r.decode(t)]}case Qr.prefix:{let r=e??Qr;return[Qr.prefix,r.decode(t)]}case io.prefix:{let r=e??io;return[io.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 By(t,e,r){let{prefix:n}=r;if(n!==at.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 Ry(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 uo=112,Oy=18;function kl(t,e,r){let n=tn(t),o=n+tn(e),s=new Uint8Array(o+r.byteLength);return en(t,s,0),en(e,s,n),s.set(r,o),s}var Py=Symbol.for("@ipld/js-cid/CID");var bc={...hc,...oc,...uc,...rc,...nc,...ic,...ac,...cc,...fc,...sc},u6={...gc,...dc};function Hl(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var Kl=Hl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),xc=Hl("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=wr(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Uy={utf8:Kl,"utf-8":Kl,hex:bc.base16,latin1:xc,ascii:xc,binary:xc,...bc},zl=Uy;function Vl(t,e="utf8"){let r=zl[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function wc(t){let e=t??8192,r=e>>>1,n,o=e;return function(i){if(i<1||i>r)return wr(i);o+i>e&&(n=wr(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Er=class{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}};function Ec(){}var Ac=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Ny=wc();function Fy(t){return globalThis.Buffer!=null?wr(t):Ny(t)}var lo=class{len;head;tail;states;constructor(){this.len=0,this.head=new Er(Ec,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new Er(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new vc((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(Bs,10,Ke.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let r=Ke.fromBigInt(e);return this._push(Bs,r.length(),r)}uint64Number(e){return this._push(no,ce(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=Ke.fromBigInt(e).zzEncode();return this._push(Bs,r.length(),r)}sint64Number(e){let r=Ke.fromNumber(e).zzEncode();return this._push(Bs,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Sc,1,e?1:0)}fixed32(e){return this._push(ho,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let r=Ke.fromBigInt(e);return this._push(ho,4,r.lo)._push(ho,4,r.hi)}fixed64Number(e){let r=Ke.fromNumber(e);return this._push(ho,4,r.lo)._push(ho,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(ll,4,e)}double(e){return this._push(pl,8,e)}bytes(e){let r=e.length>>>0;return r===0?this._push(Sc,1,0):this.uint32(r)._push(ky,r,e)}string(e){let r=yl(e);return r!==0?this.uint32(r)._push(Ya,r,e):this._push(Sc,1,0)}fork(){return this.states=new Ac(this),this.head=this.tail=new Er(Ec,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 Er(Ec,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=Fy(this.len),n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}};function Sc(t,e,r){e[r]=t&255}function My(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}var vc=class extends Er{next;constructor(e,r){super(My,e,r),this.next=void 0}};function Bs(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 ho(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 ky(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(lo.prototype.bytes=function(t){let e=t.length>>>0;return this.uint32(e),e>0&&this._push(Ky,e,t),this},lo.prototype.string=function(t){let e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(Hy,e,t),this});function Ky(t,e,r){e.set(t,r)}function Hy(t,e,r){t.length<40?Ya(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(Vl(t),r)}function Cc(){return new lo}function Gt(t,e){let r=Cc();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}function*Wt(t,e,r){let n=so(t);yield*e.stream(n,void 0,"$",r)}var Rs={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function Os(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){let a=i.int32();yield e(a)};return Os("enum",Rs.VARINT,r,n,o)}function Xt(t,e,r){return Os("message",Rs.LENGTH_DELIMITED,t,e,r)}var fe;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(fe||(fe={}));var Lc;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(Lc||(Lc={}));(function(t){t.codec=()=>Sr(Lc)})(fe||(fe={}));var ct;(function(t){let e;t.codec=()=>(e==null&&(e=Xt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),fe.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 u=s.uint32();switch(u>>>3){case 1:{c.Type=fe.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:fe.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function r(s){return Gt(s,t.codec())}t.encode=r;function n(s,i){return qt(s,t.codec(),i)}t.decode=n;function o(s,i){return Wt(s,t.codec(),i)}t.stream=o})(ct||(ct={}));var Ic;(function(t){let e;t.codec=()=>(e==null&&(e=Xt((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),fe.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 u=s.uint32();switch(u>>>3){case 1:{c.Type=fe.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:fe.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),e);function r(s){return Gt(s,t.codec())}t.encode=r;function n(s,i){return qt(s,t.codec(),i)}t.decode=n;function o(s,i){return Wt(s,t.codec(),i)}t.stream=o})(Ic||(Ic={}));var mo={};z(mo,{MAX_RSA_KEY_SIZE:()=>Tc,generateRSAKeyPair:()=>Wl,jwkToJWKKeyPair:()=>Xl,jwkToPkcs1:()=>qy,jwkToPkix:()=>Rc,jwkToRSAPrivateKey:()=>Nc,pkcs1MessageToJwk:()=>Dc,pkcs1MessageToRSAPrivateKey:()=>Oc,pkcs1ToJwk:()=>$y,pkcs1ToRSAPrivateKey:()=>Gl,pkixMessageToJwk:()=>Bc,pkixMessageToRSAPublicKey:()=>Uc,pkixToJwk:()=>jy,pkixToRSAPublicKey:()=>Pc});var on=class{type="RSA";jwk;_raw;_multihash;constructor(e,r){this.jwk=e,this._multihash=r}get raw(){return this._raw==null&&(this._raw=mo.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return ge.createV1(114,this._multihash)}toString(){return le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}verify(e,r,n){return jl(this.jwk,r,e,n)}},po=class{type="RSA";jwk;_raw;publicKey;constructor(e,r){this.jwk=e,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=mo.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}sign(e,r){return ql(this.jwk,e,r)}};var Tc=8192,_c=18,zy=1062,Vy=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function $y(t){let e=bt(t);return Dc(e)}function Dc(t){return{n:X(t[1],"base64url"),e:X(t[2],"base64url"),d:X(t[3],"base64url"),p:X(t[4],"base64url"),q:X(t[5],"base64url"),dp:X(t[6],"base64url"),dq:X(t[7],"base64url"),qi:X(t[8],"base64url"),kty:"RSA"}}function qy(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 j("JWK was missing components");return Pt([Ne(Uint8Array.from([0])),Ne(re(t.n,"base64url")),Ne(re(t.e,"base64url")),Ne(re(t.d,"base64url")),Ne(re(t.p,"base64url")),Ne(re(t.q,"base64url")),Ne(re(t.dp,"base64url")),Ne(re(t.dq,"base64url")),Ne(re(t.qi,"base64url"))]).subarray()}function jy(t){let e=bt(t,{offset:0});return Bc(e)}function Bc(t){let e=bt(t[1],{offset:0});return{kty:"RSA",n:X(e[0],"base64url"),e:X(e[1],"base64url")}}function Rc(t){if(t.n==null||t.e==null)throw new j("JWK was missing components");return Pt([Vy,as(Pt([Ne(re(t.n,"base64url")),Ne(re(t.e,"base64url"))]))]).subarray()}function Gl(t){let e=bt(t);return Oc(e)}function Oc(t){let e=Dc(t);return Nc(e)}function Pc(t,e){if(t.byteLength>=zy)throw new Or("Key size is too large");let r=bt(t,{offset:0});return Uc(r,t,e)}function Uc(t,e,r){let n=Bc(t);if(r==null){let o=st(ct.encode({Type:fe.RSA,Data:e}));r=Oe(_c,o)}return new on(n,r)}function Nc(t){if(Zl(t)>Tc)throw new j("Key size is too large");let e=Xl(t),r=st(ct.encode({Type:fe.RSA,Data:Rc(e.publicKey)})),n=Oe(_c,r);return new po(e.privateKey,new on(e.publicKey,n))}async function Wl(t){if(t>Tc)throw new j("Key size is too large");let e=await Yl(t),r=st(ct.encode({Type:fe.RSA,Data:Rc(e.publicKey)})),n=Oe(_c,r);return new po(e.privateKey,new on(e.publicKey,n))}function Xl(t){if(t==null)throw new j("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function Yl(t,e){let r=await Ve.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 Gy(r,e);return{privateKey:n[0],publicKey:n[1]}}async function ql(t,e,r){let n=await Ve.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let o=await Ve.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,Ue(e instanceof Uint8Array?e:e.subarray()));return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function jl(t,e,r,n){let o=await Ve.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ve.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,Ue(e),Ue(r instanceof Uint8Array?r:r.subarray()));return n?.signal?.throwIfAborted(),s}async function Gy(t,e){if(t.privateKey==null||t.publicKey==null)throw new j("Private and public key are required");let r=await Promise.all([Ve.get().subtle.exportKey("jwk",t.privateKey),Ve.get().subtle.exportKey("jwk",t.publicKey)]);return e?.signal?.throwIfAborted(),r}function Zl(t){if(t.kty!=="RSA")throw new j("invalid key type");if(t.n==null)throw new j("invalid key modulus");return re(t.n,"base64url").length*8}var Ps=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(fr(e),Le(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let 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),We(o)}update(e){return zr(this),this.iHash.update(e),this}digestInto(e){zr(this),cs(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}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,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()}},go=(()=>{let t=((e,r,n)=>new Ps(e,r).update(n).digest());return t.create=(e,r)=>new Ps(e,r),t})();var Jl=(t,e)=>(t+(t>=0?e:-e)/Ql)/e;function Wy(t,e,r){Et("scalar",t,ft,r);let[[n,o],[s,i]]=e,a=Jl(i*t,r),c=Jl(-o*t,r),f=t-a*n-c*s,u=-a*o-c*i,h=f<ft,m=u<ft;h&&(f=-f),m&&(u=-u);let p=Yn(Math.ceil(qr(r)/2))+Yt;if(f<ft||f>=p||u<ft||u>=p)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:h,k1:f,k2neg:m,k2:u}}function Mc(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Fc(t,e){ke(t);let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Ye(r.lowS,"lowS"),Ye(r.prehash,"prehash"),r.format!==void 0&&Mc(r.format),r}var kc=class extends Error{constructor(e=""){super(e)}},Qe={Err:kc,_tlv:{encode:(t,e)=>{let{Err:r}=Qe;if(Ze(t,"tag"),t<0||t>255)throw new r("tlv.encode: wrong tag");if(typeof e!="string")throw new TypeError('"data" expected string, got type='+typeof e);if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,o=Wn(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?Wn(o.length/2|128):"";return Wn(t)+s+o+e},decode(t,e){let{Err:r}=Qe;e=$(e,void 0,"DER data");let n=0;if(t<0||t>255)throw new r("tlv.encode: 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 u of f)i=i<<8|u;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}=Qe;if(ms(t),t<ft)throw new e("integer: negative integers are not allowed");let r=Wn(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}=Qe;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 pr(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=Qe,o=$(t,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:f,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(f)}},hexFromSig(t){let{_tlv:e,_int:r}=Qe,n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),s=n+o;return e.encode(48,s)}};Object.freeze(Qe._tlv);Object.freeze(Qe._int);Object.freeze(Qe);var ft=BigInt(0),Yt=BigInt(1),Ql=BigInt(2),Us=BigInt(3),Xy=BigInt(4);function ed(t,e={}){let r=xs("weierstrass",t,e),n=r.Fp,o=r.Fn,s=r.CURVE,{h:i,n:a}=s;ke(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:f}=e;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 u=rd(n,o);function h(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function m(N,b,v){if(f&&b.is0())return Uint8Array.of(0);let{x:A,y:w}=b.toAffine(),x=n.toBytes(A);if(Ye(v,"isCompressed"),v){h();let L=!n.isOdd(w);return ye(td(L),x)}else return ye(Uint8Array.of(4),x,n.toBytes(w))}function p(N){$(N,void 0,"Point");let{publicKey:b,publicKeyUncompressed:v}=u,A=N.length,w=N[0],x=N.subarray(1);if(f&&A===1&&w===0)return{x:n.ZERO,y:n.ZERO};if(A===b&&(w===2||w===3)){let L=n.fromBytes(x);if(!n.isValid(L))throw new Error("bad point: is not on curve, wrong x");let T=l(L),S;try{S=n.sqrt(T)}catch(F){let H=F instanceof Error?": "+F.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}h();let O=n.isOdd(S);return(w&1)===1!==O&&(S=n.neg(S)),{x:L,y:S}}else if(A===v&&w===4){let L=n.BYTES,T=n.fromBytes(x.subarray(0,L)),S=n.fromBytes(x.subarray(L,L*2));if(!g(T,S))throw new Error("bad point: is not on curve");return{x:T,y:S}}else throw new Error(`bad point: got length ${A}, expected compressed=${b} or uncompressed=${v}`)}let d=e.toBytes===void 0?m:e.toBytes,y=e.fromBytes===void 0?p:e.fromBytes;function l(N){let b=n.sqr(N),v=n.mul(b,N);return n.add(n.add(v,n.mul(N,s.a)),s.b)}function g(N,b){let v=n.sqr(b),A=l(N);return n.eql(v,A)}if(!g(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let E=n.mul(n.pow(s.a,Us),Xy),C=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(E,C)))throw new Error("bad curve params: a or b");function _(N,b,v=!1){if(!n.isValid(b)||v&&n.is0(b))throw new Error(`bad point coordinate ${N}`);return b}function B(N){if(!(N instanceof I))throw new Error("Weierstrass Point expected")}function R(N){if(!c||!c.basises)throw new Error("no endo");return Wy(N,c.basises,o.ORDER)}function D(N,b,v,A,w){return v=new I(n.mul(v.X,N),v.Y,v.Z),b=Jn(A,b),v=Jn(w,v),b.add(v)}class I{static BASE=new I(s.Gx,s.Gy,n.ONE);static ZERO=new I(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(b,v,A){this.X=_("x",b),this.Y=_("y",v,!0),this.Z=_("z",A),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){let{x:v,y:A}=b||{};if(!b||!n.isValid(v)||!n.isValid(A))throw new Error("invalid affine point");if(b instanceof I)throw new Error("projective point not allowed");return n.is0(v)&&n.is0(A)?I.ZERO:new I(v,A,n.ONE)}static fromBytes(b){let v=I.fromAffine(y($(b,void 0,"point")));return v.assertValidity(),v}static fromHex(b){return I.fromBytes($r(b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,v=!0){return M.createCache(this,b),v||this.multiply(Us),this}assertValidity(){let b=this;if(b.is0()){if(e.allowInfinityPoint&&n.is0(b.X)&&n.eql(b.Y,n.ONE)&&n.is0(b.Z))return;throw new Error("bad point: ZERO")}let{x:v,y:A}=b.toAffine();if(!n.isValid(v)||!n.isValid(A))throw new Error("bad point: x or y not field elements");if(!g(v,A))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){B(b);let{X:v,Y:A,Z:w}=this,{X:x,Y:L,Z:T}=b,S=n.eql(n.mul(v,T),n.mul(x,w)),O=n.eql(n.mul(A,T),n.mul(L,w));return S&&O}negate(){return new I(this.X,n.neg(this.Y),this.Z)}double(){let{a:b,b:v}=s,A=n.mul(v,Us),{X:w,Y:x,Z:L}=this,T=n.ZERO,S=n.ZERO,O=n.ZERO,P=n.mul(w,w),F=n.mul(x,x),H=n.mul(L,L),K=n.mul(w,x);return K=n.add(K,K),O=n.mul(w,L),O=n.add(O,O),T=n.mul(b,O),S=n.mul(A,H),S=n.add(T,S),T=n.sub(F,S),S=n.add(F,S),S=n.mul(T,S),T=n.mul(K,T),O=n.mul(A,O),H=n.mul(b,H),K=n.sub(P,H),K=n.mul(b,K),K=n.add(K,O),O=n.add(P,P),P=n.add(O,P),P=n.add(P,H),P=n.mul(P,K),S=n.add(S,P),H=n.mul(x,L),H=n.add(H,H),P=n.mul(H,K),T=n.sub(T,P),O=n.mul(H,F),O=n.add(O,O),O=n.add(O,O),new I(T,S,O)}add(b){B(b);let{X:v,Y:A,Z:w}=this,{X:x,Y:L,Z:T}=b,S=n.ZERO,O=n.ZERO,P=n.ZERO,F=s.a,H=n.mul(s.b,Us),K=n.mul(v,x),Q=n.mul(A,L),ee=n.mul(w,T),te=n.add(v,A),W=n.add(x,L);te=n.mul(te,W),W=n.add(K,Q),te=n.sub(te,W),W=n.add(v,w);let ie=n.add(x,T);return W=n.mul(W,ie),ie=n.add(K,ee),W=n.sub(W,ie),ie=n.add(A,w),S=n.add(L,T),ie=n.mul(ie,S),S=n.add(Q,ee),ie=n.sub(ie,S),P=n.mul(F,W),S=n.mul(H,ee),P=n.add(S,P),S=n.sub(Q,P),P=n.add(Q,P),O=n.mul(S,P),Q=n.add(K,K),Q=n.add(Q,K),ee=n.mul(F,ee),W=n.mul(H,W),Q=n.add(Q,ee),ee=n.sub(K,ee),ee=n.mul(F,ee),W=n.add(W,ee),K=n.mul(Q,W),O=n.add(O,K),K=n.mul(ie,W),S=n.mul(te,S),S=n.sub(S,K),K=n.mul(te,Q),P=n.mul(ie,P),P=n.add(P,K),new I(S,O,P)}subtract(b){return B(b),this.add(b.negate())}is0(){return this.equals(I.ZERO)}multiply(b){let{endo:v}=e;if(!o.isValidNot0(b))throw new RangeError("invalid scalar: out of range");let A,w,x=L=>M.cached(this,L,T=>yr(I,T));if(v){let{k1neg:L,k1:T,k2neg:S,k2:O}=R(b),{p:P,f:F}=x(T),{p:H,f:K}=x(O);w=F.add(K),A=D(v.beta,P,H,L,S)}else{let{p:L,f:T}=x(b);A=L,w=T}return yr(I,[A,w])[0]}multiplyUnsafe(b){let{endo:v}=e,A=this,w=b;if(!o.isValid(w))throw new RangeError("invalid scalar: out of range");if(w===ft||A.is0())return I.ZERO;if(w===Yt)return A;if(M.hasCache(this))return this.multiply(w);if(v){let{k1neg:x,k1:L,k2neg:T,k2:S}=R(w),{p1:O,p2:P}=Zh(I,A,L,S);return D(v.beta,O,P,x,T)}else return M.unsafe(A,w)}toAffine(b){let v=this,A=b,{X:w,Y:x,Z:L}=v;if(n.eql(L,n.ONE))return{x:w,y:x};let T=v.is0();A==null&&(A=T?n.ONE:n.inv(L));let S=n.mul(w,A),O=n.mul(x,A),P=n.mul(L,A);if(T)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:S,y:O}}isTorsionFree(){let{isTorsionFree:b}=e;return i===Yt?!0:b?b(I,this):M.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=e;return i===Yt?this:b?b(I,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Yt?this.is0():this.clearCofactor().is0()}toBytes(b=!0){return Ye(b,"isCompressed"),this.assertValidity(),d(I,this,b)}toHex(b=!0){return Vr(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let U=o.BITS,M=new Wr(I,e.endo?Math.ceil(U/2):U);return U>=8&&I.BASE.precompute(8),Object.freeze(I.prototype),Object.freeze(I),I}function td(t){return Uint8Array.of(t?2:3)}function rd(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Yy(t,e={}){let{Fn:r}=t,n=e.randomBytes===void 0?dr:e.randomBytes,o=Object.assign(rd(t.Fp,r),{seed:Math.max(Ta(r.ORDER),16)});function s(p){try{let d=r.fromBytes(p);return r.isValidNot0(d)}catch{return!1}}function i(p,d){let{publicKey:y,publicKeyUncompressed:l}=o;try{let g=p.length;return d===!0&&g!==y||d===!1&&g!==l?!1:!!t.fromBytes(p)}catch{return!1}}function a(p){return p=p===void 0?n(o.seed):p,_a($(p,o.seed,"seed"),r.ORDER)}function c(p,d=!0){return t.BASE.multiply(r.fromBytes(p)).toBytes(d)}function f(p){let{secretKey:d,publicKey:y,publicKeyUncompressed:l}=o,g=r._lengths;if(!lr(p))return;let E=$(p,void 0,"key").length,C=E===y||E===l,_=E===d||!!g?.includes(E);if(!(C&&_))return C}function u(p,d,y=!0){if(f(p)===!0)throw new Error("first arg must be private key");if(f(d)===!1)throw new Error("second arg must be public key");let l=r.fromBytes(p);return t.fromBytes(d).multiply(l).toBytes(y)}let h={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},m=Xr(a,c);return Object.freeze(h),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:m,Point:t,utils:h,lengths:o})}function nd(t,e,r={}){let n=e;fr(n),ke(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let o=r.randomBytes===void 0?dr:r.randomBytes,s=r.hmac===void 0?(w,x)=>go(n,w,x):r.hmac,{Fp:i,Fn:a}=t,{ORDER:c,BITS:f}=a,{keygen:u,getPublicKey:h,getSharedSecret:m,utils:p,lengths:d}=Yy(t,r),y={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},l=c*Ql+Yt<i.ORDER;function g(w){let x=c>>Yt;return w>x}function E(w,x){if(!a.isValidNot0(x))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return x}function C(){if(l)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function _(w,x){Mc(x);let L=d.signature,T=x==="compact"?L:x==="recovered"?L+1:void 0;return $(w,T)}class B{r;s;recovery;constructor(x,L,T){if(this.r=E("r",x),this.s=E("s",L),T!=null){if(C(),![0,1,2,3].includes(T))throw new Error("invalid recovery id");this.recovery=T}Object.freeze(this)}static fromBytes(x,L=y.format){_(x,L);let T;if(L==="der"){let{r:F,s:H}=Qe.toSig($(x));return new B(F,H)}L==="recovered"&&(T=x[0],L="compact",x=x.subarray(1));let S=d.signature/2,O=x.subarray(0,S),P=x.subarray(S,S*2);return new B(a.fromBytes(O),a.fromBytes(P),T)}static fromHex(x,L){return this.fromBytes($r(x),L)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new B(this.r,this.s,x)}recoverPublicKey(x){let{r:L,s:T}=this,S=this.assertRecovery(),O=S===2||S===3?L+c:L;if(!i.isValid(O))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let P=i.toBytes(O),F=t.fromBytes(ye(td((S&1)===0),P)),H=a.inv(O),K=D($(x,void 0,"msgHash")),Q=a.create(-K*H),ee=a.create(T*H),te=t.BASE.multiplyUnsafe(Q).add(F.multiplyUnsafe(ee));if(te.is0())throw new Error("invalid recovery: point at infinify");return te.assertValidity(),te}hasHighS(){return g(this.s)}toBytes(x=y.format){if(Mc(x),x==="der")return $r(Qe.hexFromSig(this));let{r:L,s:T}=this,S=a.toBytes(L),O=a.toBytes(T);return x==="recovered"?(C(),ye(Uint8Array.of(this.assertRecovery()),S,O)):ye(S,O)}toHex(x){return Vr(this.toBytes(x))}}Object.freeze(B.prototype),Object.freeze(B);let R=r.bits2int===void 0?function(x){if(x.length>8192)throw new Error("input is too large");let L=pr(x),T=x.length*8-f;return T>0?L>>BigInt(T):L}:r.bits2int,D=r.bits2int_modN===void 0?function(x){return a.create(R(x))}:r.bits2int_modN,I=Yn(f);function U(w){return Et("num < 2^"+f,w,ft,I),a.toBytes(w)}function M(w,x){return $(w,void 0,"message"),x?$(n(w),void 0,"prehashed message"):w}function N(w,x,L){let{lowS:T,prehash:S,extraEntropy:O}=Fc(L,y);w=M(w,S);let P=D(w),F=a.fromBytes(x);if(!a.isValidNot0(F))throw new Error("invalid private key");let H=[U(F),U(P)];if(O!=null&&O!==!1){let te=O===!0?o(d.secretKey):O;H.push($(te,void 0,"extraEntropy"))}let K=ye(...H),Q=P;function ee(te){let W=R(te);if(!a.isValidNot0(W))return;let ie=a.inv(W),pt=t.BASE.multiply(W).toAffine(),nr=a.create(pt.x);if(nr===ft)return;let Rr=a.create(ie*a.create(Q+nr*F));if(Rr===ft)return;let On=(pt.x===nr?0:2)|Number(pt.y&Yt),Pn=Rr;return T&&g(Rr)&&(Pn=a.neg(Rr),On^=1),new B(nr,Pn,l?void 0:On)}return{seed:K,k2sig:ee}}function b(w,x,L={}){let{seed:T,k2sig:S}=N(w,x,L);return Ph(n.outputLen,a.BYTES,s)(T,S).toBytes(L.format)}function v(w,x,L,T={}){let{lowS:S,prehash:O,format:P}=Fc(T,y);if(L=$(L,void 0,"publicKey"),x=M(x,O),!lr(w)){let F=w instanceof B?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+F)}_(w,P);try{let F=B.fromBytes(w,P),H=t.fromBytes(L);if(S&&F.hasHighS())return!1;let{r:K,s:Q}=F,ee=D(x),te=a.inv(Q),W=a.create(ee*te),ie=a.create(K*te),pt=t.BASE.multiplyUnsafe(W).add(H.multiplyUnsafe(ie));return pt.is0()?!1:a.create(pt.x)===K}catch{return!1}}function A(w,x,L={}){let{prehash:T}=Fc(L,y);return x=M(x,T),B.fromBytes(w,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:u,getPublicKey:h,getSharedSecret:m,utils:p,lengths:d,Point:t,sign:b,verify:v,recoverPublicKey:A,Signature:B,hash:n})}var Hc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Zy={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var od=BigInt(2);function Jy(t){let e=Hc.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,u=f*f*t%e,h=se(u,r,e)*u%e,m=se(h,r,e)*u%e,p=se(m,od,e)*f%e,d=se(p,o,e)*p%e,y=se(d,s,e)*d%e,l=se(y,a,e)*y%e,g=se(l,c,e)*l%e,E=se(g,a,e)*y%e,C=se(E,r,e)*u%e,_=se(C,i,e)*d%e,B=se(_,n,e)*f%e,R=se(B,od,e);if(!Kc.eql(Kc.sqr(R),t))throw new Error("Cannot find square root");return R}var Kc=jr(Hc.p,{sqrt:Jy}),Qy=ed(Hc,{Fp:Kc,endo:Zy}),sn=nd(Qy,st);function sd(t,e,r,n){let o=yt.digest(r instanceof Uint8Array?r:r.subarray());if(vs(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),sn.verify(e,s,t,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new ro(String(s))});try{return n?.signal?.throwIfAborted(),sn.verify(e,o.digest,t,{prehash:!1,format:"der"})}catch(s){throw new ro(String(s))}}var Ns=class{type="secp256k1";raw;_key;constructor(e){this._key=ad(e),this.raw=id(this._key)}toMultihash(){return Ge.digest(Ut(this))}toCID(){return ge.createV1(114,this.toMultihash())}toString(){return le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Pe(this.raw,e.raw)}verify(e,r,n){return sd(this._key,r,e,n)}};function zc(t){return new Ns(t)}function id(t){return sn.Point.fromBytes(t).toBytes()}function ad(t){try{return sn.Point.fromBytes(t),t}catch(e){throw new Or(String(e))}}function yo(t,e){let{Type:r,Data:n}=ct.decode(t),o=n??new Uint8Array;switch(r){case fe.RSA:return Pc(o,e);case fe.Ed25519:return Va(o);case fe.secp256k1:return zc(o);case fe.ECDSA:return la(o);default:throw new or}}function cd(t){let{Type:e,Data:r}=ct.decode(t.digest),n=r??new Uint8Array;switch(e){case fe.Ed25519:return Va(n);case fe.secp256k1:return zc(n);case fe.ECDSA:return la(n);default:throw new or}}function Ut(t){return ct.encode({Type:fe[t.type],Data:t.raw})}var fd=Symbol.for("nodejs.util.inspect.custom"),eb=114,bo=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()})`}[Fi]=!0;toString(){return this.string==null&&(this.string=le.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ge.createV1(eb,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return Pe(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return Pe(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[fd](){return`PeerId(${this.toString()})`}},xo=class extends bo{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},wo=class extends bo{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Eo=class extends bo{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},tb=2336,So=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ge.digest(re(this.url))}[fd](){return`PeerId(${this.url})`}[Fi]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ge.createV1(tb,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=X(e)),e.toString()===this.toString())}};var rb=114,ud=2336;function an(t,e){let r;if(t.charAt(0)==="1"||t.charAt(0)==="Q")r=Kr(le.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return nb(ge.parse(t));if(e==null)throw new j('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=Kr(e.decode(t))}return hd(r)}function Vc(t){if(t.type==="Ed25519")return new wo({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new Eo({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new xo({multihash:t.toCID().multihash,publicKey:t});throw new or}function hd(t){if(sb(t))return new xo({multihash:t});if(ob(t))try{let e=cd(t);if(e.type==="Ed25519")return new wo({multihash:t,publicKey:e});if(e.type==="secp256k1")return new Eo({multihash:t,publicKey:e})}catch{let r=X(t.digest);return new So(new URL(r))}throw new Jo("Supplied PeerID Multihash is invalid")}function nb(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==rb&&t.code!==ud)throw new Zo("Supplied PeerID CID is invalid");if(t.code===ud){let e=X(t.multihash.digest);return new So(new URL(e))}return hd(t.multihash)}function ob(t){return t.code===Ge.code}function sb(t){return t.code===yt.code}var ib=Math.pow(2,7),ab=Math.pow(2,14),cb=Math.pow(2,21),$c=Math.pow(2,28),qc=Math.pow(2,35),jc=Math.pow(2,42),Gc=Math.pow(2,49),ue=128,_e=127;function cn(t){if(t<ib)return 1;if(t<ab)return 2;if(t<cb)return 3;if(t<$c)return 4;if(t<qc)return 5;if(t<jc)return 6;if(t<Gc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Wc(t,e,r=0){switch(cn(t)){case 8:e[r++]=t&255|ue,t/=128;case 7:e[r++]=t&255|ue,t/=128;case 6:e[r++]=t&255|ue,t/=128;case 5:e[r++]=t&255|ue,t/=128;case 4:e[r++]=t&255|ue,t>>>=7;case 3:e[r++]=t&255|ue,t>>>=7;case 2:e[r++]=t&255|ue,t>>>=7;case 1:{e[r++]=t&255,t>>>=7;break}default:throw new Error("unreachable")}return e}function fb(t,e){let r=t[e],n=0;if(n+=r&_e,r<ue||(r=t[e+1],n+=(r&_e)<<7,r<ue)||(r=t[e+2],n+=(r&_e)<<14,r<ue)||(r=t[e+3],n+=(r&_e)<<21,r<ue)||(r=t[e+4],n+=(r&_e)*$c,r<ue)||(r=t[e+5],n+=(r&_e)*qc,r<ue)||(r=t[e+6],n+=(r&_e)*jc,r<ue)||(r=t[e+7],n+=(r&_e)*Gc,r<ue))return n;throw new RangeError("Could not decode varint")}function ub(t,e){let r=t.get(e),n=0;if(n+=r&_e,r<ue||(r=t.get(e+1),n+=(r&_e)<<7,r<ue)||(r=t.get(e+2),n+=(r&_e)<<14,r<ue)||(r=t.get(e+3),n+=(r&_e)<<21,r<ue)||(r=t.get(e+4),n+=(r&_e)*$c,r<ue)||(r=t.get(e+5),n+=(r&_e)*qc,r<ue)||(r=t.get(e+6),n+=(r&_e)*jc,r<ue)||(r=t.get(e+7),n+=(r&_e)*Gc,r<ue))return n;throw new RangeError("Could not decode varint")}function Xc(t,e=0){return t instanceof Uint8Array?fb(t,e):ub(t,e)}var Ae=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Ct=class extends Error{static name="ValidationError";name="ValidationError"},Fs=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Ms=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var ks=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 u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let m=Number.parseInt(h,e);if(!Number.isNaN(m))return m});if(u===void 0)break;if(s*=e,s+=u,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 lb=45,db=15,Ks=new ks;function ld(t){if(!(t.length>db))return Ks.new(t).parseWith(()=>Ks.readIPv4Addr())}function dd(t){if(t.includes("%")&&(t=t.split("%")[0]),!(t.length>lb))return Ks.new(t).parseWith(()=>Ks.readIPv6Addr())}function Hs(t){return!!ld(t)}function pd(t){return!!dd(t)}function Zc(t){return e=>X(e,t)}function Jc(t){return e=>re(e,t)}function fn(t){return new DataView(t.buffer).getUint16(t.byteOffset).toString()}function Ar(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof t=="string"?parseInt(t):t),new Uint8Array(e)}function md(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=re(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=Ar(n);return it([r,o],r.length+o.length)}function gd(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=Ot.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=Ar(n);return it([r,o],r.length+o.length)}function Qc(t){let e=t.subarray(0,t.length-2),r=t.subarray(t.length-2),n=X(e,"base32"),o=fn(r);return`${n}:${o}`}var ef=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 Ae("Invalid byte value in IP address");e[n]=o}),e},yd=function(t){let e=0;t=t.toString().trim();let r=t.split(":",8),n;for(n=0;n<r.length;n++){let s=Hs(r[n]),i;s&&(i=ef(r[n]),r[n]=X(i.subarray(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,X(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 Ae("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},bd=function(t){if(t.byteLength!==4)throw new Ae("IPv4 address was incorrect length");let e=[];for(let r=0;r<t.byteLength;r++)e.push(t[r]);return e.join(".")},xd=function(t){if(t.byteLength!==16)throw new Ae("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 Ae(`Invalid IPv6 address "${r}"`)}};function wd(t){try{let e=new URL(`http://[${t}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ae(`Invalid IPv6 address "${t}"`)}}var Yc=Object.values(ar).map(t=>t.decoder),pb=(function(){let t=Yc[0].or(Yc[1]);return Yc.slice(2).forEach(e=>t=t.or(e)),t})();function Ed(t){return pb.decode(t)}function Sd(t){return e=>t.encoder.encode(e)}function mb(t){if(parseInt(t).toString()!==t)throw new Ct("Value must be an integer")}function gb(t){if(t<0)throw new Ct("Value must be a positive integer, or zero")}function yb(t){return e=>{if(e>t)throw new Ct(`Value must be smaller than or equal to ${t}`)}}function bb(...t){return e=>{for(let r of t)r(e)}}var Ao=bb(mb,gb,yb(65535));var we=-1,tf=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 Ms(`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)}))}},It=new tf,Rb=[{code:4,name:"ip4",size:32,valueToBytes:ef,bytesToValue:bd,validate:t=>{if(!Hs(t))throw new Ct(`Invalid IPv4 address "${t}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ar,bytesToValue:fn,validate:Ao},{code:273,name:"udp",size:16,valueToBytes:Ar,bytesToValue:fn,validate:Ao},{code:33,name:"dccp",size:16,valueToBytes:Ar,bytesToValue:fn,validate:Ao},{code:41,name:"ip6",size:128,valueToBytes:yd,bytesToValue:xd,stringToValue:wd,validate:t=>{if(!pd(t))throw new Ct(`Invalid IPv6 address "${t}"`)}},{code:42,name:"ip6zone",size:we},{code:43,name:"ipcidr",size:8,bytesToValue:Zc("base10"),valueToBytes:Jc("base10")},{code:53,name:"dns",size:we},{code:54,name:"dns4",size:we},{code:55,name:"dns6",size:we},{code:56,name:"dnsaddr",size:we},{code:132,name:"sctp",size:16,valueToBytes:Ar,bytesToValue:fn,validate:Ao},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:we,stringToValue:t=>decodeURIComponent(t),valueToString:t=>encodeURIComponent(t)},{code:421,name:"p2p",aliases:["ipfs"],size:we,bytesToValue:Zc("base58btc"),valueToBytes:t=>t.startsWith("Q")||t.startsWith("1")?Jc("base58btc")(t):ge.parse(t).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Qc,valueToBytes:md},{code:445,name:"onion3",size:296,bytesToValue:Qc,valueToBytes:gd},{code:446,name:"garlic64",size:we},{code:447,name:"garlic32",size:we},{code:448,name:"tls"},{code:449,name:"sni",size:we},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:we,bytesToValue:Sd(Hn),valueToBytes:Ed},{code:480,name:"http"},{code:481,name:"http-path",size:we,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:we}];Rb.forEach(t=>{It.addProtocol(t)});function Ad(t){let e=[],r=0;for(;r<t.length;){let n=Xc(t,r),o=It.getProtocol(n),s=cn(n),i=Ob(o,t,r+s),a=0;i>0&&o.size===we&&(a=cn(i));let c=s+a+i,f={code:n,name:o.name,bytes:Ue(t.subarray(r,r+c))};if(i>0){let u=r+s+a,h=t.subarray(u,u+i);f.value=o.bytesToValue?.(h)??X(h)}e.push(f),r+=c}return e}function vd(t){let e=0,r=[];for(let n of t){if(n.bytes==null){let o=It.getProtocol(n.code),s=cn(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??re(n.value),a=i.byteLength,o.size===we&&(c=cn(a)));let f=new Uint8Array(s+c+a),u=0;Wc(n.code,f,u),u+=s,i!=null&&(o.size===we&&(Wc(a,f,u),u+=c),f.set(i,u)),n.bytes=f}r.push(n.bytes),e+=n.bytes.byteLength}return it(r,e)}function Cd(t){if(t.charAt(0)!=="/")throw new Ae('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=It.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 Ae(`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 Ae(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}e.push(f),n="",o="",r="protocol"}}}if(o!==""&&n!=="")throw new Ae("Incomplete multiaddr");return e}function Ld(t){return`/${t.flatMap(e=>{if(e.value==null)return e.name;let r=It.getProtocol(e.code);if(r==null)throw new Ae(`Unknown protocol code ${e.code}`);return[e.name,r.valueToString?.(e.value)??e.value]}).join("/")}`}function Ob(t,e,r){return t.size==null||t.size===0?0:t.size>0?t.size/8:Xc(e,r)}var Pb=Symbol.for("nodejs.util.inspect.custom"),xf=Symbol.for("@multiformats/multiaddr");function Ub(t){if(t==null&&(t="/"),Id(t))return t.getComponents();if(t instanceof Uint8Array)return Ad(t);if(typeof t=="string")return t=t.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),t===""&&(t="/"),Cd(t);if(Array.isArray(t))return t;throw new Ae("Must be a string, Uint8Array, Component[], or another Multiaddr")}var js=class t{[xf]=!0;#e;#t;#r;constructor(e="/",r={}){this.#e=Ub(e),r.validate!==!1&&Nb(this)}get bytes(){return this.#r==null&&(this.#r=vd(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=Ld(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 Fs(`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 Pe(this.bytes,e.bytes)}[Pb](){return`Multiaddr(${this.toString()})`}};function Nb(t){t.getComponents().forEach(e=>{let r=It.getProtocol(e.code);e.value!=null&&r.validate?.(e.value)})}function Id(t){return!!t?.[xf]}function dn(t){return new js(t)}var ne=t=>({match:e=>{let r=e[0];return r==null||r.code!==t||r.value!=null?!1:e.slice(1)}}),k=(t,e)=>({match:r=>{let n=r[0];return n?.code!==t||n.value==null||e!=null&&n.value!==e?!1:r.slice(1)}}),Td=t=>({match:e=>t.match(e)===!1?e:!1}),q=t=>({match:e=>{let r=t.match(e);return r===!1?e:r}}),De=(...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}}),Y=(...t)=>({match:e=>{for(let r of t){let n=r.match(e);if(n===!1)return!1;e=n}return e}});function oe(...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 Fb=k(421),Pv=oe(Fb),Ws=k(54),Xs=k(55),Ys=k(56),Ef=k(53),Uv=oe(Ws,q(k(421))),Nv=oe(Xs,q(k(421))),Fv=oe(Ys,q(k(421))),Mv=oe(De(Ef,Ys,Ws,Xs),q(k(421))),_d=Y(k(4),q(k(43))),Dd=Y(q(k(42)),k(41),q(k(43))),Sf=De(_d,Dd),pn=De(Sf,Ef,Ws,Xs,Ys),kv=oe(De(Sf,Y(De(Ef,Ys,Ws,Xs),q(k(421))))),Kv=oe(_d),Hv=oe(Dd),zv=oe(Sf),Af=Y(pn,k(6)),vo=Y(pn,k(273)),Vv=oe(Y(Af,q(k(421)))),$v=oe(vo),vf=Y(vo,ne(460),q(k(421))),Zs=Y(vo,ne(461),q(k(421))),Mb=De(vf,Zs),qv=oe(vf),jv=oe(Zs),wf=De(pn,Af,vo,vf,Zs),Bd=De(Y(wf,ne(477),q(k(421)))),Gv=oe(Bd),Rd=De(Y(wf,ne(478),q(k(421))),Y(wf,ne(448),q(k(449)),ne(477),q(k(421)))),Wv=oe(Rd),Od=Y(vo,ne(280),q(k(466)),q(k(466)),q(k(421))),Pd=oe(Od),Ud=Y(Zs,ne(465),q(k(466)),q(k(466)),q(k(421))),Xv=oe(Ud),Gs=De(Bd,Rd,Y(Af,q(k(421))),Y(Mb,q(k(421))),Y(pn,q(k(421))),Od,Ud,k(421)),Nd=oe(Gs),kb=Y(q(Gs),ne(290),Td(ne(281)),q(k(421))),Yv=oe(kb),Kb=De(Y(Gs,ne(290),ne(281),q(k(421))),Y(Gs,ne(281),q(k(421))),Y(ne(281),q(k(421)))),Fd=oe(Kb),Hb=Y(pn,De(Y(k(6,"80")),Y(k(6),ne(480)),ne(480)),q(k(481)),q(k(421))),Zv=oe(Hb),zb=Y(pn,De(Y(k(6,"443")),Y(k(6,"443"),ne(480)),Y(k(6),ne(443)),Y(k(6),ne(448),ne(480)),Y(ne(448),ne(480)),ne(448),ne(443)),q(k(481)),q(k(421))),Jv=oe(zb),Vb=De(Y(k(777),q(k(421)))),Qv=oe(Vb),$b=De(Y(k(400),q(k(421)))),e4=oe($b);var Be;(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=Xt((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 u={},h=c==null?a.len:a.pos+c;for(;a.pos<h;){let m=a.uint32();switch(m>>>3){case 1:{u.flag=t.Flag.codec().decode(a);break}case 2:{u.message=a.bytes();break}default:{a.skipType(m&7);break}}}return u},function*(a,c,f,u={}){let h=c==null?a.len:a.pos+c;for(;a.pos<h;){let m=a.uint32();switch(m>>>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(m&7);break}}}})),n);function o(a){return Gt(a,t.codec())}t.encode=o;function s(a,c){return qt(a,t.codec(),c)}t.decode=s;function i(a,c){return Wt(a,t.codec(),c)}t.stream=i})(Be||(Be={}));var Md=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],Cf=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),kd="libp2p+webrtc+v1/",Kd=2*1024*1024,mn=16*1024;function qb(t=mn){let e=ce(t-ce(t)),r=1+ce(Object.keys(Be.Flag).length-1),n=1,o=t-e-r-n,s=ce(o);return e+r+n+s}var Hd=qb();var zd=1e4,Lf="/webrtc",Co="/webrtc-signaling/0.0.1";function jb(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 If(t){let e=jb(t);if(e==null)throw new j(`Multiaddr ${t} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function Js(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var Qs=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}},gn=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Qs(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 Qs(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 Tf=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function yn(t={}){return Gb(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 Gb(t,e){e=e??{};let r=e.onEnd,n=new gn,o,s,i,a=Js(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((l,g)=>{s=E=>{s=null,n.push(E);try{l(t(n))}catch(C){g(C)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Js()})}},f=l=>s!=null?s(l):(n.push(l),o),u=l=>(n=new gn,s!=null?s({error:l}):(n.push({error:l}),o)),h=l=>{if(i)return o;if(e?.objectMode!==!0&&l?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:l})},m=l=>i?o:(i=!0,l!=null?u(l):f({done:!0})),p=()=>(n=new gn,m(),{done:!0}),d=l=>(m(l),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:d,push:h,end:m,get readableLength(){return n.size},onEmpty:async l=>{let g=l?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let E,C;g!=null&&(E=new Promise((_,B)=>{C=()=>{B(new Tf)},g.addEventListener("abort",C)}));try{await Promise.race([a.promise,E])}finally{C!=null&&g!=null&&g?.removeEventListener("abort",C)}}},r==null)return o;let y=o;return o={[Symbol.asyncIterator](){return this},next(){return y.next()},throw(l){return y.throw(l),r!=null&&(r(l),r=void 0),{done:!0}},return(){return y.return(),r!=null&&(r(),r=void 0),{done:!0}},push:h,end(l){return y.end(l),r!=null&&(r(l),r=void 0),o},get readableLength(){return y.readableLength},onEmpty:l=>y.onEmpty(l)},o}var _f=class t extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,t)}},Vd=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function Df(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((h,m)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){m(Vd(i));return}if(i&&(c=()=>{m(Vd(i))},i.addEventListener("abort",c,{once:!0})),t.then(h,m),r===Number.POSITIVE_INFINITY)return;let p=new _f;a=s.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(d){m(d)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?h():o instanceof Error?m(o):(p.message=o??`Promise timed out after ${r} milliseconds`,m(p))},r)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var Wb=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 Xb(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:u}=Wb(t),h=async(...p)=>{let d=r.multiArgs?p:p[0];if(r.filter)try{if(!await r.filter(d))return}catch(y){n(),i(y);return}c.push(d),r.count===c.length&&(n(),s(c))},m=(...p)=>{n(),i(r.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)u(p,h);for(let p of r.rejectionEvents)a.includes(p)||u(p,m)};for(let p of a)f(p,h);for(let p of r.rejectionEvents)a.includes(p)||f(p,m);r.signal&&r.signal.addEventListener("abort",()=>{m(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){let s=Df(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function ve(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Xb(t,e,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var Cr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},ei=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},ti=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Yb(t){return t.reason}async function Tt(t,e,r){if(e==null)return t;let n=r?.translateError??Yb;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([t,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var Zb=Math.pow(2,20)*4,Jt=class extends Bt{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;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??Zb,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new V,this.writeBuffer=new V,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 ti)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Tt(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=yn(),r=s=>{e.push(s.data)};this.addEventListener("message",r);let n=s=>{e.end(s.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new rt(`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.log.error("abort with error - %e",e),this.status="aborted",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();try{this.sendReset(e)}catch(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new ts(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new rt("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 rt("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 rt(`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 rt(`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(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new Pr;this.dispatchEvent(new rs(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.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new Ur))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),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 V(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}}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 es(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.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Un(`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 Un(`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 ri=class extends Jt{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 ve(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 ve(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function $d(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var ni=class extends Bt{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 Tt(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 Xo;let r=this.onCreateStream({...this.streamOptions,...e});return $d(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 ei(`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 oi=class extends Jt{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 ve(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 ve(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){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};var Jb=4194304,si=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Lo=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Rf=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Of=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Qb(t){return typeof t?.closeRead=="function"}function ex(t){return typeof t?.close=="function"}function Bf(t){return Qb(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:ex(t)?t.status!=="open":!1}function tx(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function rx(t,e){let r=e?.maxBufferSize??Jb,n=new V,o,s=!1;if(!tx(t))throw new j("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>r){let h=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${h} > ${r}`))}o?.resolve()};t.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};t.addEventListener("close",a);let c=()=>{o?.resolve()};t.addEventListener("remoteCloseWrite",c);let f={readBuffer:n,async read(u){if(s===!0)throw new si("Stream was unwrapped");if(Bf(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 Cr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let h=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=h){o.resolve();break}if(await Tt(o.promise,u?.signal),Bf(t)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let m=u?.bytes??n.byteLength;if(n.byteLength<m){if(Bf(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,m),new Cr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${m} bytes`);return f.read(u)}let p=n.sublist(0,m);return n.consume(m),p},async write(u,h){if(s===!0)throw new si("Stream was unwrapped");t.send(u)||await ve(t,"drain",{signal:h?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,t.removeEventListener("message",i),t.removeEventListener("close",a),t.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(t.log("stream unwrapped with %d unread bytes",n.byteLength),t.unshift(n))),t}};return f}function ii(t,e={}){let r=rx(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=ce(e.maxDataLength));let n=e?.lengthDecoder??Zr,o=e?.lengthEncoder??Ls;return{async read(i){let a=-1,c=new V;for(;;){let u=await r.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(h){if(h instanceof RangeError)continue;throw h}if(a<0)throw new Lo("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Of(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Rf(`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 Cr(`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 Cr(`Unexpected EOF - read ${f.byteLength}/${a} bytes before the stream closed`);return f},async write(i,a){await r.write(new V(o(i.byteLength),i),a)},async writeV(i,a){let c=new V(...i.flatMap(f=>[o(f.byteLength),f]));await r.write(c,a)},unwrap(){return r.unwrap()}}}function ai(t,e){let r=ii(t,e),n={read:async(o,s)=>{let i=await r.read(s);return o.decode(i)},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 nx=1024*1024*4,ox=1024*1024*4,ci=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new V,this.maxBufferSize=e.maxBufferSize??nx,this.maxDataLength=e.maxDataLength??ox,this.lengthDecoder=e.lengthDecoder??Zr,this.encodingLength=e.encodingLength??ce}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new j(`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 Lo("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}}};function qd(t=0){return new Uint8Array(t)}var fi=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},bn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ui=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Io=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function hi(t){return t[Symbol.asyncIterator]!=null}function jd(t,e){if(t.byteLength>e)throw new bn("Message length too long")}var di=t=>{let e=ce(t),r=qd(e);return Ls(t,r),di.bytes=e,r};di.bytes=0;function To(t,e){e=e??{};let r=e.lengthEncoder??di,n=e?.maxDataLength??4194304;function*o(s){jd(s,n);let i=r(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return hi(t)?(async function*(){for await(let s of t)yield*o(s)})():(function*(){for(let s of t)yield*o(s)})()}To.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??di,n=e?.maxDataLength??4194304;return jd(t,n),new V(r(t.byteLength),t)};var Lr;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(Lr||(Lr={}));var Pf=t=>{let e=Zr(t);return Pf.bytes=ce(e),e};Pf.bytes=0;function _o(t,e){let r=new V,n=Lr.LENGTH,o=-1,s=e?.lengthDecoder??Pf,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===Lr.LENGTH)try{if(o=s(r),o<0)throw new fi("Invalid message length");if(o>a)throw new bn("Message length too long");let f=s.bytes;r.consume(f),e?.onLength!=null&&e.onLength(o),n=Lr.DATA}catch(f){if(f instanceof RangeError){if(r.byteLength>i)throw new ui("Message length length too long");break}throw f}if(n===Lr.DATA){if(r.byteLength<o)break;let f=r.sublist(0,o);r.consume(o),e?.onData!=null&&e.onData(f),yield f,n=Lr.LENGTH}}}return hi(t)?(async function*(){for await(let f of t)r.append(f),yield*c();if(r.byteLength>0)throw new Io("Unexpected end of input")})():(function*(){for(let f of t)r.append(f),yield*c();if(r.byteLength>0)throw new Io("Unexpected end of input")})()}_o.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 _o(n,{...e??{},onLength:s=>{r=s}})};var Uf=class extends oi{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(e){super({...e,maxMessageSize:(e.maxMessageSize??mn)-Hd}),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=yn(),this.maxBufferedAmount=e.maxBufferedAmount??Kd,this.finAckTimeout=e.finAckTimeout??zd,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 _o(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),ve(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 rt(`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(Ue(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(To.single(Be.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(Be.Flag.RESET),this.receivedFinAck?.reject(e)}catch(r){this.log.error("failed to send reset - %e",r)}}async sendCloseWrite(e){this._sendFlag(Be.Flag.FIN),e?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let r=e?.signal??AbortSignal.timeout(this.finAckTimeout),n=[ve(this.channel,"close",{signal:r}),ve(this.channel,"error",{signal:r})];await Promise.any([Tt(this.receivedFinAck.promise,r),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(e){this._sendFlag(Be.Flag.STOP_SENDING),e?.signal?.throwIfAborted()}processIncomingProtobuf(e){let r=Be.decode(e);r.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new V(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===Be.Flag.FIN&&(this._sendFlag(Be.Flag.FIN_ACK),this.onRemoteCloseWrite()),r.flag===Be.Flag.RESET&&(this.receivedFinAck?.reject(new Pr("The stream was reset")),this.onRemoteReset()),r.flag===Be.Flag.STOP_SENDING&&this.onRemoteCloseRead(),r.flag===Be.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=Be.encode({flag:e}),n=To.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 Do(t){let{channel:e,direction:r,isHandshake:n}=t;return new Uf({...t,id:`${e.id}`,log:t.log.newScope(`${n===!0?"handshake":r}:${e.id}`),protocol:""})}var Qt=class{protocol;peerConnection;metrics;dataChannelOptions;earlyDataChannels;constructor(e){this.onEarlyDataChannel=this.onEarlyDataChannel.bind(this),this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??Lf,this.dataChannelOptions=e.dataChannelOptions??{},this.peerConnection.addEventListener("datachannel",this.onEarlyDataChannel),this.earlyDataChannels=[]}onEarlyDataChannel(e){this.earlyDataChannels.push(e.channel)}createStreamMuxer(e){return this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel),new Nf(e,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,earlyDataChannels:this.earlyDataChannels})}},Nf=class extends ni{peerConnection;dataChannelOptions;constructor(e,r){super(e,{...r,name:"muxer"}),this.peerConnection=r.peerConnection,this.protocol=r.protocol??Lf,this.dataChannelOptions=r.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{this.onDataChannel(n)},queueMicrotask(()=>{if(this.status!=="open"){r.earlyDataChannels.forEach(n=>{n.close()});return}r.earlyDataChannels.forEach(n=>{this.onDataChannel(n)})})}onDataChannel(e){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),e.close();return}let r=Do({...this.streamOptions,...this.dataChannelOptions,channel:e,direction:"inbound",log:this.log});this.onRemoteStream(r)}async onCreateStream(e){let r=this.peerConnection.createDataChannel("",{});return this.log("open channel %d for protocol %s",r.id,e?.protocol),Do({...e,...this.dataChannelOptions,channel:r,direction:"outbound",log:this.log})}onData(){}};var Ff=class extends ri{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(){}},Bo=t=>new Ff(t);async function Mf(t){return t=t??{},typeof t=="function"&&(t=await t()),t.iceServers=t.iceServers??Md.map(e=>({urls:[e]})),t}var Gd=(t=32)=>kd+[...Array(t)].map(()=>Cf.at(Math.floor(Math.random()*Cf.length))).join("");var pi=globalThis.RTCPeerConnection,mi=globalThis.RTCSessionDescription,Wd=globalThis.RTCIceCandidate;var He=class extends Event{type;detail;constructor(e,r){super(e),this.type=e,this.detail=r}};var er=class extends Error{constructor(e){super(`WebRTC transport error: ${e}`),this.name="WebRTCTransportError"}},$e=class extends er{constructor(e="SDP handshake failed"){super(e),this.name="SDPHandshakeFailedError"}};var gi=class extends er{constructor(e,r){super(`Invalid fingerprint "${e}" within ${r}`),this.name="WebRTC/InvalidFingerprintError"}};var yi=class extends er{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},bi=class extends er{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 Fe;(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=Xt((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 u={},h=c==null?a.len:a.pos+c;for(;a.pos<h;){let m=a.uint32();switch(m>>>3){case 1:{u.type=t.Type.codec().decode(a);break}case 2:{u.data=a.string();break}default:{a.skipType(m&7);break}}}return u},function*(a,c,f,u={}){let h=c==null?a.len:a.pos+c;for(;a.pos<h;){let m=a.uint32();switch(m>>>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(m&7);break}}}})),n);function o(a){return Gt(a,t.codec())}t.encode=o;function s(a,c){return qt(a,t.codec(),c)}t.decode=s;function i(a,c){return Wt(a,t.codec(),c)}t.stream=i})(Fe||(Fe={}));var xi=async(t,e,r)=>{try{let n=Promise.withResolvers();for(ax(t,n);;){let o=await Promise.race([n.promise,e.read({signal:r.signal})]);if(o==null){r.signal?.throwIfAborted();break}if(o.type!==Fe.Type.ICE_CANDIDATE)throw new Qo("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){r.onProgress?.(new He("webrtc:end-of-ice-candidates")),r.log.trace("end-of-candidates received");continue}let i=new Wd(s);r.log.trace("%s received new ICE candidate %o",r.direction,s);try{r.onProgress?.(new He("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 ax(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 Wo(`RTCPeerConnection connection state became "${t.connectionState}"`));break;default:break}}}function wi(t){let e;for(let r of t.getComponents())r.name==="p2p"&&(e=an(r.value??""));if(e==null)throw new Yo("Remote peerId must be present in multiaddr");return e}async function Xd({rtcConfiguration:t,dataChannel:e,signal:r,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:f}){let{circuitAddress:u,targetPeer:h}=Yd(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing circuit address: %a",u);let m=s.getConnections(h),p;m.length===0?(f?.(new He("webrtc:dial-relay")),p=await i.dial(u,{signal:r,onProgress:f})):(f?.(new He("webrtc:reuse-relay-connection")),p=m[0]),f?.(new He("webrtc:open-signaling-stream"));let d=await p.newStream(Co,{signal:r,runOnLimitedConnection:!0}),y=ai(d).pb(Fe),l=new pi(t);l.addEventListener("connectionstatechange",()=>{l.connectionState==="closed"&&l.close()});let g=new Qt({peerConnection:l,dataChannelOptions:e});try{let E=l.createDataChannel("init");l.onicecandidate=({candidate:R})=>{if(l.connectionState==="connected"){a.trace("ignore new ice candidate as peer connection is already connected");return}if(R==null||R?.candidate===""){a.trace("initiator detected end of ICE candidates");return}let D=JSON.stringify(R?.toJSON()??null);a.trace("initiator sending ICE candidate %o",R),y.write({type:Fe.Type.ICE_CANDIDATE,data:D},{signal:r}).catch(I=>{a.error("error sending ICE candidate - %e",I)})},l.onicecandidateerror=R=>{a.error("initiator ICE candidate error",R)};let C=await l.createOffer().catch(R=>{throw a.error("could not execute createOffer - %e",R),new $e("Failed to set createOffer")});a.trace("initiator send SDP offer %s",C.sdp),f?.(new He("webrtc:send-sdp-offer")),await y.write({type:Fe.Type.SDP_OFFER,data:C.sdp},{signal:r}),await l.setLocalDescription(C).catch(R=>{throw a.error("could not execute setLocalDescription - %e",R),new $e("Failed to set localDescription")}),f?.(new He("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let _=await y.read({signal:r});if(_.type!==Fe.Type.SDP_ANSWER)throw new $e("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",_.data);let B=new mi({type:"answer",sdp:_.data});return await l.setRemoteDescription(B).catch(R=>{throw a.error("could not execute setRemoteDescription - %e",R),new $e("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),f?.(new He("webrtc:read-ice-candidates")),await xi(l,y,{direction:"initiator",signal:r,log:a,onProgress:f}),a.trace("initiator connected"),E.readyState!=="open"&&(a.trace("wait for init channel to open"),await ve(E,"open",{signal:r})),a.trace("closing init channel"),E.close(),a.trace("waiting for init channel to close"),await ve(E,"close",{signal:r}),f?.(new He("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await d.close({signal:r}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:l,muxerFactory:g}}catch(E){throw a.error("outgoing signaling error - %e",E),l.close(),d.abort(E),E}finally{l.onicecandidate=null,l.onicecandidateerror=null}}var Zd=oe(Nd.matchers[0],ne(290)),Ei=class t extends Bt{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=>Zd.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=>Zd.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 Jd(t,e,{peerConnection:r,signal:n,log:o}){o.trace("new inbound signaling stream");let s=ai(t).pb(Fe);try{r.onicecandidate=({candidate:h})=>{if(r.connectionState==="connected"){o.trace("ignore new ice candidate as peer connection is already connected");return}if(h==null||h?.candidate===""){o.trace("recipient detected end of ICE candidates");return}let m=JSON.stringify(h?.toJSON()??null);o.trace("recipient sending ICE candidate %s",m),s.write({type:Fe.Type.ICE_CANDIDATE,data:m},{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!==Fe.Type.SDP_OFFER)throw new $e(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let f=new mi({type:"offer",sdp:c.data});await r.setRemoteDescription(f).catch(h=>{throw o.error("could not execute setRemoteDescription - %e",h),new $e("Failed to set remoteDescription")});let u=await r.createAnswer().catch(h=>{throw o.error("could not execute createAnswer - %e",h),new $e("Failed to create answer")});o.trace("recipient send SDP answer %s",u.sdp),await s.write({type:Fe.Type.SDP_ANSWER,data:u.sdp},{signal:n}),await r.setLocalDescription(u).catch(h=>{throw o.error("could not execute setLocalDescription - %e",h),new $e("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await xi(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=wi(e.remoteAddr),a=dn(`/webrtc/p2p/${i}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:i}}var Si=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"})})}[ns]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Nr]=["@libp2p/transport"];[$u]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(Co,(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(Co),this._started=!1}createListener(e){return new Ei(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(Fd.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 Xd({rtcConfiguration:await Mf(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:e,dataChannelOptions:this.init.dataChannel,signal:r.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:r.onProgress}),i=Bo({peerConnection:o,remoteAddr:n,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")}),a=await r.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,remotePeer:wi(e),muxerFactory:s,onProgress:r.onProgress,signal:r.signal});return this._closeOnShutdown(o,i),a}async _onProtocol(e,r,n){let o=new pi(await Mf(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{o.connectionState==="closed"&&o.close()});let s=new Qt({peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i,remotePeer:a}=await Jd(e,r,{peerConnection:o,signal:n,log:this.log});await e.close({signal:n});let c=Bo({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),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 Yd(t){let e=t.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(e==null)throw new j("Destination peer id was missing");return{circuitAddress:dn(t.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:an(e)}}function ut(t=0){return new Uint8Array(t)}function qe(t=0){return new Uint8Array(t)}var xn=!!globalThis.process?.env?.DUMP_SESSION_KEYS,kf=16;function cx(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function Ai(t){if(typeof t!="boolean")throw new TypeError(`boolean expected, not ${t}`)}function wn(t){if(typeof t!="number")throw new TypeError("number expected, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError("positive integer expected, got "+t)}function be(t,e,r=""){let n=cx(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){let i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return t}function Kf(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Qd(t,e,r=!1){be(t,void 0,"output");let n=e.outputLen;if(t.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(r&&!En(t))throw new Error("invalid output, must be aligned")}function ht(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function et(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function fx(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Ir=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,ux=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;var hx=t=>{for(let e=0;e<t.length;e++)t[e]=ux(t[e]);return t},_t=Ir?t=>t:hx;function ep(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function tp(t,e){if(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 rp(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 np=(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;s&&o[1]!==void 0&&be(o[1],void 0,"AAD");let i=e(n,...o),a=(u,h)=>{if(h!==void 0){if(u!==2)throw new Error("cipher output not supported");be(h,void 0,"output")}},c=!1;return{encrypt(u,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,be(u),a(i.encrypt.length,h),i.encrypt(u,h)},decrypt(u,h){if(be(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,h),i.decrypt(u,h)}}}return Object.assign(r,t),r};function Ro(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(be(e,void 0,"output"),e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(r&&!En(e))throw new Error("invalid output, must be aligned");return e}function op(t,e,r){wn(t),wn(e),Ai(r);let n=new Uint8Array(16),o=fx(n);return o.setBigUint64(0,BigInt(e),r),o.setBigUint64(8,BigInt(t),r),n}function En(t){return t.byteOffset%4===0}function Sn(t){return Uint8Array.from(be(t))}var ip=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),lx=_t(ht(ip("expand 16-byte k"))),dx=_t(ht(ip("expand 32-byte k")));function G(t,e){return t<<e|t>>>32-e}var Oo=64,px=16,Hf=2**32-1,sp=Uint32Array.of();function mx(t,e,r,n,o,s,i,a){let c=o.length,f=new Uint8Array(Oo),u=ht(f),h=Ir&&En(o)&&En(s),m=h?ht(o):sp,p=h?ht(s):sp;if(!Ir){for(let d=0;d<c;i++){if(t(e,r,n,u,i,a),_t(u),i>=Hf)throw new Error("arx: counter overflow");let y=Math.min(Oo,c-d);for(let l=0,g;l<y;l++)g=d+l,s[g]=o[g]^f[l];d+=y}return}for(let d=0;d<c;i++){if(t(e,r,n,u,i,a),i>=Hf)throw new Error("arx: counter overflow");let y=Math.min(Oo,c-d);if(h&&y===Oo){let l=d/4;if(d%4!==0)throw new Error("arx: invalid block position");for(let g=0,E;g<px;g++)E=l+g,p[E]=m[E]^u[g];d+=Oo;continue}for(let l=0,g;l<y;l++)g=d+l,s[g]=o[g]^f[l];d+=y}}function ap(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=ep({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return wn(o),wn(i),Ai(s),Ai(r),(a,c,f,u,h=0)=>{be(a,void 0,"key"),be(c,void 0,"nonce"),be(f,void 0,"data");let m=f.length;if(u=Ro(m,u,!1),wn(h),h<0||h>=Hf)throw new Error("arx: counter overflow");let p=[],d=a.length,y,l;if(d===32)p.push(y=Sn(a)),l=dx;else if(d===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),l=lx,p.push(y);else throw be(a,32,"arx key"),new Error("invalid key size");(!Ir||!En(c))&&p.push(c=Sn(c));let g=ht(y);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let _=c.subarray(0,16);if(Ir)n(l,g,ht(_),g);else{let B=_t(Uint32Array.from(l));n(B,g,ht(_),g),et(B),_t(g)}c=c.subarray(16)}else Ir||_t(g);let E=16-o;if(E!==c.length)throw new Error(`arx: nonce must be ${E} or 16 bytes`);if(E!==12){let _=new Uint8Array(12);_.set(c,s?0:12-c.length),c=_,p.push(c)}let C=_t(ht(c));try{return mx(t,l,g,C,f,u,h,i),u}finally{et(...p)}}}function Ce(t,e){return t[e++]&255|(t[e++]&255)<<8}var zf=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=Sn(be(e,32,"key"));let r=Ce(e,0),n=Ce(e,2),o=Ce(e,4),s=Ce(e,6),i=Ce(e,8),a=Ce(e,10),c=Ce(e,12),f=Ce(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 u=0;u<8;u++)this.pad[u]=Ce(e,16+2*u)}process(e,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],f=i[2],u=i[3],h=i[4],m=i[5],p=i[6],d=i[7],y=i[8],l=i[9],g=Ce(e,r+0),E=Ce(e,r+2),C=Ce(e,r+4),_=Ce(e,r+6),B=Ce(e,r+8),R=Ce(e,r+10),D=Ce(e,r+12),I=Ce(e,r+14),U=s[0]+(g&8191),M=s[1]+((g>>>13|E<<3)&8191),N=s[2]+((E>>>10|C<<6)&8191),b=s[3]+((C>>>7|_<<9)&8191),v=s[4]+((_>>>4|B<<12)&8191),A=s[5]+(B>>>1&8191),w=s[6]+((B>>>14|R<<2)&8191),x=s[7]+((R>>>11|D<<5)&8191),L=s[8]+((D>>>8|I<<8)&8191),T=s[9]+(I>>>5|o),S=0,O=S+U*a+M*(5*l)+N*(5*y)+b*(5*d)+v*(5*p);S=O>>>13,O&=8191,O+=A*(5*m)+w*(5*h)+x*(5*u)+L*(5*f)+T*(5*c),S+=O>>>13,O&=8191;let P=S+U*c+M*a+N*(5*l)+b*(5*y)+v*(5*d);S=P>>>13,P&=8191,P+=A*(5*p)+w*(5*m)+x*(5*h)+L*(5*u)+T*(5*f),S+=P>>>13,P&=8191;let F=S+U*f+M*c+N*a+b*(5*l)+v*(5*y);S=F>>>13,F&=8191,F+=A*(5*d)+w*(5*p)+x*(5*m)+L*(5*h)+T*(5*u),S+=F>>>13,F&=8191;let H=S+U*u+M*f+N*c+b*a+v*(5*l);S=H>>>13,H&=8191,H+=A*(5*y)+w*(5*d)+x*(5*p)+L*(5*m)+T*(5*h),S+=H>>>13,H&=8191;let K=S+U*h+M*u+N*f+b*c+v*a;S=K>>>13,K&=8191,K+=A*(5*l)+w*(5*y)+x*(5*d)+L*(5*p)+T*(5*m),S+=K>>>13,K&=8191;let Q=S+U*m+M*h+N*u+b*f+v*c;S=Q>>>13,Q&=8191,Q+=A*a+w*(5*l)+x*(5*y)+L*(5*d)+T*(5*p),S+=Q>>>13,Q&=8191;let ee=S+U*p+M*m+N*h+b*u+v*f;S=ee>>>13,ee&=8191,ee+=A*c+w*a+x*(5*l)+L*(5*y)+T*(5*d),S+=ee>>>13,ee&=8191;let te=S+U*d+M*p+N*m+b*h+v*u;S=te>>>13,te&=8191,te+=A*f+w*c+x*a+L*(5*l)+T*(5*y),S+=te>>>13,te&=8191;let W=S+U*y+M*d+N*p+b*m+v*h;S=W>>>13,W&=8191,W+=A*u+w*f+x*c+L*a+T*(5*l),S+=W>>>13,W&=8191;let ie=S+U*l+M*y+N*d+b*p+v*m;S=ie>>>13,ie&=8191,ie+=A*h+w*u+x*f+L*c+T*a,S+=ie>>>13,ie&=8191,S=(S<<2)+S|0,S=S+O|0,O=S&8191,S=S>>>13,P+=S,s[0]=O,s[1]=P,s[2]=F,s[3]=H,s[4]=K,s[5]=Q,s[6]=ee,s[7]=te,s[8]=W,s[9]=ie}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;et(n)}update(e){Kf(this),be(e),e=Sn(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,et(this.h,this.r,this.buffer,this.pad)}digestInto(e){Kf(this),Qd(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}},cp=rp(32,t=>new zf(t));function gx(t,e,r,n,o,s=20){let i=t[0],a=t[1],c=t[2],f=t[3],u=e[0],h=e[1],m=e[2],p=e[3],d=e[4],y=e[5],l=e[6],g=e[7],E=o,C=r[0],_=r[1],B=r[2],R=i,D=a,I=c,U=f,M=u,N=h,b=m,v=p,A=d,w=y,x=l,L=g,T=E,S=C,O=_,P=B;for(let H=0;H<s;H+=2)R=R+M|0,T=G(T^R,16),A=A+T|0,M=G(M^A,12),R=R+M|0,T=G(T^R,8),A=A+T|0,M=G(M^A,7),D=D+N|0,S=G(S^D,16),w=w+S|0,N=G(N^w,12),D=D+N|0,S=G(S^D,8),w=w+S|0,N=G(N^w,7),I=I+b|0,O=G(O^I,16),x=x+O|0,b=G(b^x,12),I=I+b|0,O=G(O^I,8),x=x+O|0,b=G(b^x,7),U=U+v|0,P=G(P^U,16),L=L+P|0,v=G(v^L,12),U=U+v|0,P=G(P^U,8),L=L+P|0,v=G(v^L,7),R=R+N|0,P=G(P^R,16),x=x+P|0,N=G(N^x,12),R=R+N|0,P=G(P^R,8),x=x+P|0,N=G(N^x,7),D=D+b|0,T=G(T^D,16),L=L+T|0,b=G(b^L,12),D=D+b|0,T=G(T^D,8),L=L+T|0,b=G(b^L,7),I=I+v|0,S=G(S^I,16),A=A+S|0,v=G(v^A,12),I=I+v|0,S=G(S^I,8),A=A+S|0,v=G(v^A,7),U=U+M|0,O=G(O^U,16),w=w+O|0,M=G(M^w,12),U=U+M|0,O=G(O^U,8),w=w+O|0,M=G(M^w,7);let F=0;n[F++]=i+R|0,n[F++]=a+D|0,n[F++]=c+I|0,n[F++]=f+U|0,n[F++]=u+M|0,n[F++]=h+N|0,n[F++]=m+b|0,n[F++]=p+v|0,n[F++]=d+A|0,n[F++]=y+w|0,n[F++]=l+x|0,n[F++]=g+L|0,n[F++]=E+T|0,n[F++]=C+S|0,n[F++]=_+O|0,n[F++]=B+P|0}var yx=ap(gx,{counterRight:!1,counterLength:4,allowShortKeys:!1});var bx=new Uint8Array(16),fp=(t,e)=>{t.update(e);let r=e.length%16;r&&t.update(bx.subarray(r))},xx=new Uint8Array(32);function up(t,e,r,n,o){o!==void 0&&be(o,void 0,"AAD");let s=t(e,r,xx),i=op(n.length,o?o.length:0,!0),a=cp.create(s);o&&fp(a,o),fp(a,n),a.update(i);let c=a.digest();return et(s,i),c}var wx=t=>(e,r,n)=>({encrypt(s,i){let a=s.length;i=Ro(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);t(e,r,c,c,1);let f=up(t,e,r,c,n);return i.set(f,a),et(f),i},decrypt(s,i){i=Ro(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),f=up(t,e,r,a,n);if(!tp(c,f))throw et(f),new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,r,i,i,1),et(f),i}}),Vf=np({blockSize:64,nonceLength:12,tagLength:16},wx(yx));function lp(t,e,r){return fr(t),r===void 0&&(r=new Uint8Array(t.outputLen)),go(t,r,e)}var $f=Uint8Array.of(0),hp=Uint8Array.of();function dp(t,e,r,n=32){fr(t),nt(n,"length"),Le(e,void 0,"prk");let o=t.outputLen;if(e.length<o)throw new Error('"prk" must be at least HashLen octets');if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);r===void 0?r=hp:Le(r,void 0,"info");let i=new Uint8Array(s*o),a=go.create(t,e),c=a._cloneInto(),f=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)$f[0]=u+1,c.update(u===0?hp:f).update(r).update($f).digestInto(f),i.set(f,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),We(f,$f),i.slice(0,n)}var qf={hashSHA256(t){return st(t.subarray())},getHKDF(t,e){let r=lp(st,e,t),o=dp(st,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=to.utils.randomSecretKey();return{publicKey:to.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:to.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return to.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,r,n){return Vf(n,e,r).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,r,n,o){return Vf(n,e,r).decrypt(t.subarray(),o)}};var pp=qf;function mp(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 An=t=>{let e=qe(2);return e[0]=t>>8,e[1]=t,e};An.bytes=2;var vn=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)};vn.bytes=2;function gp(t){return{xxHandshakeSuccesses:t.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:t.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:t.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:t.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:t.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}var Yf={};z(Yf,{base10:()=>Ix});var gC=new Uint8Array(0);function yp(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 Dt(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function bp(t){return new TextEncoder().encode(t)}function xp(t){return new TextDecoder().decode(t)}function Ex(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<t.length;o++){var s=t.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=t.length,c=t.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var y=0,l=0,g=0,E=d.length;g!==E&&d[g]===0;)g++,y++;for(var C=(E-g)*u+1>>>0,_=new Uint8Array(C);g!==E;){for(var B=d[g],R=0,D=C-1;(B!==0||R<l)&&D!==-1;D--,R++)B+=256*_[D]>>>0,_[D]=B%a>>>0,B=B/a>>>0;if(B!==0)throw new Error("Non-zero carry");l=R,g++}for(var I=C-l;I!==C&&_[I]===0;)I++;for(var U=c.repeat(y);I<C;++I)U+=t.charAt(_[I]);return U}function m(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var y=0;if(d[y]!==" "){for(var l=0,g=0;d[y]===c;)l++,y++;for(var E=(d.length-y)*f+1>>>0,C=new Uint8Array(E);d[y];){var _=r[d.charCodeAt(y)];if(_===255)return;for(var B=0,R=E-1;(_!==0||B<g)&&R!==-1;R--,B++)_+=a*C[R]>>>0,C[R]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");g=B,y++}if(d[y]!==" "){for(var D=E-g;D!==E&&C[D]===0;)D++;for(var I=new Uint8Array(l+(E-D)),U=l;D!==E;)I[U++]=C[D++];return I}}}function p(d){var y=m(d);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:m,decode:p}}var Sx=Ex,Ax=Sx,Ep=Ax;var jf=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")}},Gf=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 Sp(this,e)}},Wf=class{decoders;constructor(e){this.decoders=e}or(e){return Sp(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 Sp(t,e){return new Wf({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var Xf=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 jf(e,r,n),this.decoder=new Gf(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Cn({name:t,prefix:e,encode:r,decode:n}){return new Xf(t,e,r,n)}function tr({name:t,prefix:e,alphabet:r}){let{encode:n,decode:o}=Ep(r,t);return Cn({prefix:e,name:t,encode:n,decode:s=>Dt(o(s))})}function vx(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 u=e[t[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|u,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 Cx(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 Lx(t){let e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function me({name:t,prefix:e,bitsPerChar:r,alphabet:n}){let o=Lx(n);return Cn({prefix:e,name:t,encode(s){return Cx(s,n,r)},decode(s){return vx(s,o,r,t)}})}var Ix=tr({prefix:"9",name:"base10",alphabet:"0123456789"});var Zf={};z(Zf,{base16:()=>Tx,base16upper:()=>_x});var Tx=me({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),_x=me({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Jf={};z(Jf,{base2:()=>Dx});var Dx=me({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Qf={};z(Qf,{base256emoji:()=>Ux});var Ap=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}"),Bx=Ap.reduce((t,e,r)=>(t[r]=e,t),[]),Rx=Ap.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function Ox(t){return t.reduce((e,r)=>(e+=Bx[r],e),"")}function Px(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=Rx[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var Ux=Cn({prefix:"\u{1F680}",name:"base256emoji",encode:Ox,decode:Px});var eu={};z(eu,{base32:()=>Ln,base32hex:()=>kx,base32hexpad:()=>Hx,base32hexpadupper:()=>zx,base32hexupper:()=>Kx,base32pad:()=>Fx,base32padupper:()=>Mx,base32upper:()=>Nx,base32z:()=>Vx});var Ln=me({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Nx=me({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Fx=me({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Mx=me({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),kx=me({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Kx=me({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Hx=me({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zx=me({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Vx=me({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var tu={};z(tu,{base36:()=>Po,base36upper:()=>$x});var Po=tr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),$x=tr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ru={};z(ru,{base58btc:()=>lt,base58flickr:()=>qx});var lt=tr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),qx=tr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var nu={};z(nu,{base64:()=>jx,base64pad:()=>Gx,base64url:()=>Wx,base64urlpad:()=>Xx});var jx=me({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Gx=me({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Wx=me({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Xx=me({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ou={};z(ou,{base8:()=>Yx});var Yx=me({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var su={};z(su,{identity:()=>Zx});var Zx=Cn({prefix:"\0",name:"identity",encode:t=>xp(t),decode:t=>bp(t)});var RC=new TextEncoder,OC=new TextDecoder;var au={};z(au,{identity:()=>ww});var ew=Lp,vp=128,tw=127,rw=~tw,nw=Math.pow(2,31);function Lp(t,e,r){e=e||[],r=r||0;for(var n=r;t>=nw;)e[r++]=t&255|vp,t/=128;for(;t&rw;)e[r++]=t&255|vp,t>>>=7;return e[r]=t|0,Lp.bytes=r-n+1,e}var ow=iu,sw=128,Cp=127;function iu(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw iu.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&Cp)<<o:(i&Cp)*Math.pow(2,o),o+=7}while(i>=sw);return iu.bytes=s-n,r}var iw=Math.pow(2,7),aw=Math.pow(2,14),cw=Math.pow(2,21),fw=Math.pow(2,28),uw=Math.pow(2,35),hw=Math.pow(2,42),lw=Math.pow(2,49),dw=Math.pow(2,56),pw=Math.pow(2,63),mw=function(t){return t<iw?1:t<aw?2:t<cw?3:t<fw?4:t<uw?5:t<hw?6:t<lw?7:t<dw?8:t<pw?9:10},gw={encode:ew,decode:ow,encodingLength:mw},yw=gw,Uo=yw;function No(t,e=0){return[Uo.decode(t,e),Uo.decode.bytes]}function In(t,e,r=0){return Uo.encode(t,e,r),e}function Tn(t){return Uo.encodingLength(t)}function Dn(t,e){let r=e.byteLength,n=Tn(t),o=n+Tn(r),s=new Uint8Array(o+r);return In(t,s,0),In(r,s,n),s.set(e,o),new _n(t,r,e,s)}function Ip(t){let e=Dt(t),[r,n]=No(e),[o,s]=No(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new _n(r,o,i,e)}function Tp(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&yp(t.bytes,r.bytes)}}var _n=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}};var _p=0,bw="identity",Dp=Dt;function xw(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 Dn(_p,Dp(t))}var ww={code:_p,name:bw,encode:Dp,digest:xw};var uu={};z(uu,{sha256:()=>Sw,sha512:()=>Aw});var Ew=20;function fu({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new cu(t,e,r,n,o)}var cu=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??Ew,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?Bp(n,this.code,r?.truncate):n.then(o=>Bp(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function Bp(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 Dn(e,t)}function Op(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var Sw=fu({name:"sha2-256",code:18,encode:Op("SHA-256")}),Aw=fu({name:"sha2-512",code:19,encode:Op("SHA-512")});function Pp(t,e){let{bytes:r,version:n}=t;return n===0?Cw(r,hu(t),e??lt.encoder):Lw(r,hu(t),e??Ln.encoder)}var Up=new WeakMap;function hu(t){let e=Up.get(t);if(e==null){let r=new Map;return Up.set(t,r),r}return e}var Ci=class t{code;version;multihash;bytes;"/";constructor(e,r,n,o){this.code=r,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:r}=this;if(e!==Mo)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Iw)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=Dn(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&&Tp(e.multihash,n.multihash)}toString(e){return Pp(this,e)}toJSON(){return{"/":Pp(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??Np(n,o,s.bytes))}else if(r[Tw]===!0){let{version:n,multihash:o,code:s}=r,i=Ip(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!==Mo)throw new Error(`Version 0 CID must use dag-pb (code: ${Mo}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=Np(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,Mo,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=Dt(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 _n(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[h,m]=No(e.subarray(r));return r+=m,h},o=n(),s=Mo;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,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(e,r){let[n,o]=vw(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 hu(s).set(n,e),s}};function vw(t,e){switch(t[0]){case"Q":{let r=e??lt;return[lt.prefix,r.decode(`${lt.prefix}${t}`)]}case lt.prefix:{let r=e??lt;return[lt.prefix,r.decode(t)]}case Ln.prefix:{let r=e??Ln;return[Ln.prefix,r.decode(t)]}case Po.prefix:{let r=e??Po;return[Po.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 Cw(t,e,r){let{prefix:n}=r;if(n!==lt.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 Lw(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 Mo=112,Iw=18;function Np(t,e,r){let n=Tn(t),o=n+Tn(e),s=new Uint8Array(o+r.byteLength);return In(t,s,0),In(e,s,n),s.set(r,o),s}var Tw=Symbol.for("@ipld/js-cid/CID");var lu={...su,...Jf,...ou,...Yf,...Zf,...eu,...tu,...ru,...nu,...Qf},tL={...uu,...au};function Mp(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var Fp=Mp("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),du=Mp("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=qe(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),_w={utf8:Fp,"utf-8":Fp,hex:lu.base16,latin1:du,ascii:du,binary:du,...lu},Li=_w;function dt(t,e="utf8"){let r=Li[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}function pu(t,e){!e.enabled||!xn||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${dt(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${dt(t.privateKey,"hex")}`)):e("Missing local static keys."))}function mu(t,e){!e.enabled||!xn||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${dt(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${dt(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function kp(t,e){!e.enabled||!xn||e(t?`REMOTE_STATIC_PUBLIC_KEY ${dt(t.subarray(),"hex")}`:"Missing remote static public key.")}function gu(t,e){!e.enabled||!xn||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${dt(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function yu(t,e,r){!r.enabled||!xn||(r(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&dt(t.k,"hex")}`),r(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&dt(e.k,"hex")}`))}function bu(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=qe(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}function Tr(t,e="utf8"){let r=Li[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}var Bn=class t extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=t.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var Bw=0,Rw=4294967295,Ow="Cipherstate has reached maximum n, a new handshake must be performed",Ii=class{n;bytes;view;constructor(e=Bw){this.n=e,this.bytes=ut(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>Rw)throw new Error(Ow)}};var _r=ut(0),Rn=class{k;n;crypto;constructor(e,r=void 0,n=0){this.crypto=e,this.k=r,this.n=new Ii(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}},xu=class{cs;ck;h;crypto;constructor(e,r){this.crypto=e;let n=Tr(r,"utf-8");this.h=Pw(e,n),this.ck=this.h,this.cs=new Rn(e)}mixKey(e){let[r,n]=this.crypto.hkdf(this.ck,e);this.ck=r,this.cs=new Rn(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new V(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,_r);return[new Rn(this.crypto,e),new Rn(this.crypto,r)]}},wu=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 xu(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()}},ko=class extends wu{writeMessageA(e){return new V(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let r=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new V(r,n,this.ss.encryptAndHash(e))}writeMessageC(e){let r=this.writeS();return this.writeSE(),new V(r,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(r){throw new Bn(`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 Bn(`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 Bn(`handshake stage 2 validation fail: ${r.message}`)}}};function Pw(t,e){if(e.length<=32){let r=ut(32);return r.set(e),r}else return t.hash(e)}var Eu=new Float32Array([-0]),rr=new Uint8Array(Eu.buffer);function Kp(t,e,r){Eu[0]=t,e[r]=rr[0],e[r+1]=rr[1],e[r+2]=rr[2],e[r+3]=rr[3]}function Hp(t,e){return rr[0]=t[e],rr[1]=t[e+1],rr[2]=t[e+2],rr[3]=t[e+3],Eu[0]}var Su=new Float64Array([-0]),Re=new Uint8Array(Su.buffer);function zp(t,e,r){Su[0]=t,e[r]=Re[0],e[r+1]=Re[1],e[r+2]=Re[2],e[r+3]=Re[3],e[r+4]=Re[4],e[r+5]=Re[5],e[r+6]=Re[6],e[r+7]=Re[7]}function Vp(t,e){return Re[0]=t[e],Re[1]=t[e+1],Re[2]=t[e+2],Re[3]=t[e+3],Re[4]=t[e+4],Re[5]=t[e+5],Re[6]=t[e+6],Re[7]=t[e+7],Su[0]}var Uw=BigInt(Number.MAX_SAFE_INTEGER),Nw=BigInt(Number.MIN_SAFE_INTEGER),ze=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 Dr;if(e<Uw&&e>Nw)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>$p&&(o=0n,++n>$p&&(n=0n))),new t(Number(o),Number(n))}static fromNumber(e){if(e===0)return Dr;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):Dr}},Dr=new ze(0,0);Dr.toBigInt=function(){return 0n};Dr.zzEncode=Dr.zzDecode=function(){return this};Dr.length=function(){return 1};var $p=4294967296n;function qp(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 jp(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 Au(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 tt(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function Ti(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}var vu=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=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,tt(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 tt(this,4);return Ti(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw tt(this,4);return Ti(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw tt(this,4);let e=Hp(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw tt(this,4);let e=Vp(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 tt(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let e=this.bytes();return jp(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw tt(this,e);this.pos+=e}else do if(this.pos>=this.len)throw tt(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 ze(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 tt(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 tt(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 tt(this,8);let e=Ti(this.buf,this.pos+=4),r=Ti(this.buf,this.pos+=4);return new ze(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=oo(this.buf,this.pos);return this.pos+=ce(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 Cu(t){return new vu(t instanceof Uint8Array?t:t.subarray())}function _i(t,e,r){let n=Cu(t);return e.decode(n,void 0,r)}function Lu(t){let e=t??8192,r=e>>>1,n,o=e;return function(i){if(i<1||i>r)return qe(i);o+i>e&&(n=qe(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Br=class{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}};function Iu(){}var _u=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Fw=Lu();function Mw(t){return globalThis.Buffer!=null?qe(t):Fw(t)}var Ho=class{len;head;tail;states;constructor(){this.len=0,this.head=new Br(Iu,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new Br(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Du((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(Di,10,ze.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let r=ze.fromBigInt(e);return this._push(Di,r.length(),r)}uint64Number(e){return this._push(no,ce(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=ze.fromBigInt(e).zzEncode();return this._push(Di,r.length(),r)}sint64Number(e){let r=ze.fromNumber(e).zzEncode();return this._push(Di,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Tu,1,e?1:0)}fixed32(e){return this._push(Ko,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let r=ze.fromBigInt(e);return this._push(Ko,4,r.lo)._push(Ko,4,r.hi)}fixed64Number(e){let r=ze.fromNumber(e);return this._push(Ko,4,r.lo)._push(Ko,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(Kp,4,e)}double(e){return this._push(zp,8,e)}bytes(e){let r=e.length>>>0;return r===0?this._push(Tu,1,0):this.uint32(r)._push(Kw,r,e)}string(e){let r=qp(e);return r!==0?this.uint32(r)._push(Au,r,e):this._push(Tu,1,0)}fork(){return this.states=new _u(this),this.head=this.tail=new Br(Iu,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 Br(Iu,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=Mw(this.len),n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}};function Tu(t,e,r){e[r]=t&255}function kw(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}var Du=class extends Br{next;constructor(e,r){super(kw,e,r),this.next=void 0}};function Di(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 Ko(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 Kw(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(Ho.prototype.bytes=function(t){let e=t.length>>>0;return this.uint32(e),e>0&&this._push(Hw,e,t),this},Ho.prototype.string=function(t){let e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(zw,e,t),this});function Hw(t,e,r){e.set(t,r)}function zw(t,e,r){t.length<40?Au(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(Tr(t),r)}function Bu(){return new Ho}function Bi(t,e){let r=Bu();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var zo;(function(t){t[t.VARINT=0]="VARINT",t[t.BIT64=1]="BIT64",t[t.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",t[t.START_GROUP=3]="START_GROUP",t[t.END_GROUP=4]="END_GROUP",t[t.BIT32=5]="BIT32"})(zo||(zo={}));function Ru(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function Ri(t,e){return Ru("message",zo.LENGTH_DELIMITED,t,e)}var Vo=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var Oi;(function(t){let e;t.codec=()=>(e==null&&(e=Ri((r,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),r.webtransportCerthashes!=null)for(let s of r.webtransportCerthashes)n.uint32(10),n.bytes(s);if(r.streamMuxers!=null)for(let s of r.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new Vo('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(r.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new Vo('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(r.string());break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Bi(r,t.codec()),t.decode=(r,n)=>_i(r,t.codec(),n)})(Oi||(Oi={}));var $o;(function(t){let e;t.codec=()=>(e==null&&(e=Ri((r,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),r.identityKey!=null&&r.identityKey.byteLength>0&&(n.uint32(10),n.bytes(r.identityKey)),r.identitySig!=null&&r.identitySig.byteLength>0&&(n.uint32(18),n.bytes(r.identitySig)),r.extensions!=null&&(n.uint32(34),Oi.codec().encode(r.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={identityKey:ut(0),identitySig:ut(0)},i=n==null?r.len:r.pos+n;for(;r.pos<i;){let a=r.uint32();switch(a>>>3){case 1:{s.identityKey=r.bytes();break}case 2:{s.identitySig=r.bytes();break}case 4:{s.extensions=Oi.codec().decode(r,r.uint32(),{limits:o.limits?.extensions});break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Bi(r,t.codec()),t.decode=(r,n)=>_i(r,t.codec(),n)})($o||($o={}));async function Pu(t,e,r){let n=await t.sign(Xp(e));return $o.encode({identityKey:Ut(t.publicKey),identitySig:n,extensions:r})}async function Uu(t,e,r){try{let n=$o.decode(t),o=yo(n.identityKey);if(r?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${r}`);if(!e)throw new Error("Remote static does not exist");let s=Xp(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new jo(n.message)}}function Xp(t){let e=Tr("noise-libp2p-static-key:");return t instanceof Uint8Array?bu([e,t],e.length+t.length):(t.prepend(e),t)}var Ou=class extends Jt{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 ci({lengthDecoder:vn,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 V;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(An(s.byteLength)),r.append(s)}return r}decrypt(e){let r=new V;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-kf<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-kf);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 Nu(t,e,r){return new Ou(t,e,r)}async function Yp(t,e){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=t,u=await Pu(s,a.publicKey,f),h=new ko({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});pu(h.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(h.writeMessageA(_r),e),r.trace("Stage 0 - Initiator finished sending first message."),mu(h.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");let m=h.readMessageB(await n.read(e));r.trace("Stage 1 - Initiator received the message."),gu(h.re,r),kp(h.rs,r),r.trace("Initiator going to check remote's signature...");let p=await Uu(m,h.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(h.writeMessageC(u),e),r.trace("Stage 2 - Initiator sent message with signed payload.");let[d,y]=h.ss.split();return yu(d,y,r),{payload:p,encrypt:l=>d.encryptWithAd(_r,l),decrypt:(l,g)=>y.decryptWithAd(_r,l,g)}}async function Zp(t,e){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=t,u=await Pu(s,a.publicKey,f),h=new ko({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});pu(h.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await n.read(e)),r.trace("Stage 0 - Responder received first message."),gu(h.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(h.writeMessageB(u),e),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),mu(h.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");let m=h.readMessageC(await n.read(e));r.trace("Stage 2 - Responder received the message, finished handshake.");let p=await Uu(m,h.rs,c),[d,y]=h.ss.split();return yu(d,y,r),{payload:p,encrypt:l=>y.encryptWithAd(_r,l),decrypt:(l,g)=>d.decryptWithAd(_r,l,g)}}var Pi=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??pp;this.crypto=mp(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?gp(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??ut(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Nr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,r){let n=e.log?.newScope("noise")??this.log,o=ii(e,{lengthEncoder:An,lengthDecoder:vn,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=yo(s.payload.identityKey);return{connection:Nu(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Vc(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 Go("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=ii(e,{lengthEncoder:An,lengthDecoder:vn,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=yo(s.payload.identityKey);return{connection:Nu(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Vc(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 Yp({connection:e,privateKey:r,remoteIdentityKey: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 Zp({connection:e,privateKey:r,remoteIdentityKey: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 Jp(t={}){return e=>new Pi(e,t)}var Fu=Object.values(ar).map(t=>t.decoder).reduce((t,e)=>t.or(e)),Vw=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function Qp(t){return t?.match(Vw)?.groups?.fingerprint}function Mu(t){let r=t.getComponents().find(n=>n.code===466)?.value;if(r===void 0||r==="")throw new j(`Couldn't find a certhash component of multiaddr: ${t.toString()}`);return r}function $w(t){return je.decode(Fu.decode(t))}function qw(t){let e=$w(Mu(t)),r=jw(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 gi(n,t.toString());return`${r} ${o.join(":").toUpperCase()}`}function em(t){let e=t.split(":").map(o=>parseInt(o,16)),r=Uint8Array.from(e),n=Oe(yt.code,r);return dn(`/certhash/${Hn.encode(n.bytes)}`)}function jw(t){switch(t){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new bi(t)}}function tm(t,e){let{host:r,port:n,type:o}=If(t);if(o!=="ip4"&&o!=="ip6")throw new j(`Multiaddr ${t} was not an IPv4 or IPv6 address`);let s=qw(t);return{type:"answer",sdp:`v=0
3
- o=- 0 0 IN IP${o==="ip4"?4:6} ${r}
2
+ "use strict";var Libp2PWebrtc=(()=>{var wi=Object.defineProperty;var Zd=Object.getOwnPropertyDescriptor;var Jd=Object.getOwnPropertyNames;var Qd=Object.prototype.hasOwnProperty;var rt=(r,t)=>{for(var e in t)wi(r,e,{get:t[e],enumerable:!0})},tp=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Jd(t))!Qd.call(r,o)&&o!==e&&wi(r,o,{get:()=>t[o],enumerable:!(n=Zd(t,o))||n.enumerable});return r};var ep=r=>tp(wi({},"__esModule",{value:!0}),r);var Ib={};rt(Ib,{webRTC:()=>_b,webRTCDirect:()=>Lb});var Do=class extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}},Ro=class extends Error{static name="InvalidCryptoExchangeError";constructor(t="Invalid crypto exchange"){super(t),this.name="InvalidCryptoExchangeError"}},$=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Tr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Oo=class extends Error{static name="ConnectionFailedError";constructor(t="Connection failed"){super(t),this.name="ConnectionFailedError"}},Po=class extends Error{static name="MuxerClosedError";constructor(t="The muxer is closed"){super(t),this.name="MuxerClosedError"}},Dr=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}};var ne=class extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}},Ln=class extends Error{static name="StreamBufferError";constructor(t="The stream buffer was full"){super(t),this.name="StreamBufferError"}};var Uo=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},No=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Fo=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var ko=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var nr=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Mo=class extends Event{data;constructor(t,e){super("message",e),this.data=t}},Rr=class extends Event{error;local;constructor(t,e,n){super("close",n),this.error=e,this.local=t}},Ko=class extends Rr{constructor(t,e){super(!0,t,e)}},Ho=class extends Rr{constructor(t,e){super(!1,t,e)}};var xi=Symbol.for("@libp2p/peer-id");var Vo=Symbol.for("@libp2p/transport");var Jf;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Jf||(Jf={}));function rp(r){return typeof r?.handleEvent=="function"}function np(r){return(r!==!0&&r!==!1&&r?.once)??!1}var Te=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){let o=np(n);super.addEventListener(t,i=>{if(o){let a=this.#t.get(i.type);a!=null&&(a=a.filter(({callback:c})=>c!==e),this.#t.set(i.type,a))}rp(e)?e.handleEvent(i):e(i)},n);let s=this.#t.get(t);s==null&&(s=[],this.#t.set(t,s)),s.push({callback:e,once:o})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};var Or=Symbol.for("@libp2p/service-capabilities"),Qf=Symbol.for("@libp2p/service-dependencies");var Ci={};rt(Ci,{base58btc:()=>ht,base58flickr:()=>hp});var iw=new Uint8Array(0);function tu(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function me(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return or(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return or(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function eu(r){return new TextEncoder().encode(r)}function ru(r){return new TextDecoder().decode(r)}function op(r){return r?.buffer instanceof ArrayBuffer}function or(r){return op(r)?r:r.slice()}function sp(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var b=0,l=0,y=0,v=m.length;y!==v&&m[y]===0;)y++,b++;for(var L=(v-y)*u+1>>>0,D=new Uint8Array(L);y!==v;){for(var R=m[y],O=0,T=L-1;(R!==0||O<l)&&T!==-1;T--,O++)R+=256*D[T]>>>0,D[T]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");l=O,y++}for(var I=L-l;I!==L&&D[I]===0;)I++;for(var U=c.repeat(b);I<L;++I)U+=r.charAt(D[I]);return U}function p(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var b=0;if(m[b]!==" "){for(var l=0,y=0;m[b]===c;)l++,b++;for(var v=(m.length-b)*f+1>>>0,L=new Uint8Array(v);m[b];){var D=e[m.charCodeAt(b)];if(D===255)return;for(var R=0,O=v-1;(D!==0||R<y)&&O!==-1;O--,R++)D+=a*L[O]>>>0,L[O]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");y=R,b++}if(m[b]!==" "){for(var T=v-y;T!==v&&L[T]===0;)T++;for(var I=new Uint8Array(l+(v-T)),U=l;T!==v;)I[U++]=L[T++];return I}}}function d(m){var b=p(m);if(b)return b;throw new Error(`Non-${t} character`)}return{encode:h,decodeUnsafe:p,decode:d}}var ip=sp,ap=ip,ou=ap;var Ei=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Si=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return su(this,t)}},Ai=class{decoders;constructor(t){this.decoders=t}or(t){return su(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function su(r,t){return new Ai({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var vi=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new Ei(t,e,n),this.decoder=new Si(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Pr({name:r,prefix:t,encode:e,decode:n}){return new vi(r,t,e,n)}function De({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=ou(e,r);return Pr({prefix:t,name:r,encode:n,decode:s=>me(o(s))})}function cp(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=t[r[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|u,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function fp(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function up(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function ut({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=up(n);return Pr({prefix:t,name:r,encode(s){return fp(s,n,e)},decode(s){return cp(s,o,e,r)}})}var ht=De({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),hp=De({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Li={};rt(Li,{base32:()=>Re,base32hex:()=>mp,base32hexpad:()=>yp,base32hexpadupper:()=>bp,base32hexupper:()=>gp,base32pad:()=>dp,base32padupper:()=>pp,base32upper:()=>lp,base32z:()=>wp});var Re=ut({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),lp=ut({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),dp=ut({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pp=ut({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),mp=ut({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),gp=ut({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),yp=ut({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),bp=ut({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),wp=ut({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var _i={};rt(_i,{base36:()=>_n,base36upper:()=>xp});var _n=De({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),xp=De({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Gt={};rt(Gt,{Digest:()=>sr,create:()=>Ut,decode:()=>Fr,equals:()=>Bi,hasCode:()=>Mp});var Ep=cu,iu=128,Sp=127,Ap=~Sp,vp=Math.pow(2,31);function cu(r,t,e){t=t||[],e=e||0;for(var n=e;r>=vp;)t[e++]=r&255|iu,r/=128;for(;r&Ap;)t[e++]=r&255|iu,r>>>=7;return t[e]=r|0,cu.bytes=e-n+1,t}var Cp=Ii,Lp=128,au=127;function Ii(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ii.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&au)<<o:(i&au)*Math.pow(2,o),o+=7}while(i>=Lp);return Ii.bytes=s-n,e}var _p=Math.pow(2,7),Ip=Math.pow(2,14),Bp=Math.pow(2,21),Tp=Math.pow(2,28),Dp=Math.pow(2,35),Rp=Math.pow(2,42),Op=Math.pow(2,49),Pp=Math.pow(2,56),Up=Math.pow(2,63),Np=function(r){return r<_p?1:r<Ip?2:r<Bp?3:r<Tp?4:r<Dp?5:r<Rp?6:r<Op?7:r<Pp?8:r<Up?9:10},Fp={encode:Ep,decode:Cp,encodingLength:Np},kp=Fp,In=kp;function Bn(r,t=0){return[In.decode(r,t),In.decode.bytes]}function Ur(r,t,e=0){return In.encode(r,t,e),t}function Nr(r){return In.encodingLength(r)}function Ut(r,t){let e=t.byteLength,n=Nr(r),o=n+Nr(e),s=new Uint8Array(o+e);return Ur(r,s,0),Ur(e,s,n),s.set(t,o),new sr(r,e,t,s)}function Fr(r){let t=me(r),[e,n]=Bn(t),[o,s]=Bn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new sr(e,o,i,t)}function Bi(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&tu(r.bytes,e.bytes)}}var sr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=or(n),this.bytes=or(o)}};function Mp(r,t){return r.code===t}function fu(r,t){let{bytes:e,version:n}=r;return n===0?Hp(e,Ti(r),t??ht.encoder):Vp(e,Ti(r),t??Re.encoder)}var uu=new WeakMap;function Ti(r){let t=uu.get(r);if(t==null){let e=new Map;return uu.set(r,e),e}return t}var pt=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=or(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:t,multihash:e}=this;if(t!==Tn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==zp)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=Ut(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Bi(t.multihash,n.multihash)}toString(t){return fu(this,t)}toJSON(){return{"/":fu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??hu(n,o,s.bytes))}else if(e[$p]===!0){let{version:n,multihash:o,code:s}=e,i=Fr(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Tn)throw new Error(`Version 0 CID must use dag-pb (code: ${Tn}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=hu(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Tn,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=me(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new sr(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[h,p]=Bn(t.subarray(e));return e+=p,h},o=n(),s=Tn;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),f=e+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(t,e){let[n,o]=Kp(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ti(s).set(n,t),s}};function Kp(r,t){switch(r[0]){case"Q":{let e=t??ht;return[ht.prefix,e.decode(`${ht.prefix}${r}`)]}case ht.prefix:{let e=t??ht;return[ht.prefix,e.decode(r)]}case Re.prefix:{let e=t??Re;return[Re.prefix,e.decode(r)]}case _n.prefix:{let e=t??_n;return[_n.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Hp(r,t,e){let{prefix:n}=e;if(n!==ht.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Vp(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var Tn=112,zp=18;function hu(r,t,e){let n=Nr(r),o=n+Nr(t),s=new Uint8Array(o+e.byteLength);return Ur(r,s,0),Ur(t,s,n),s.set(e,o),s}var $p=Symbol.for("@ipld/js-cid/CID");var Di={};rt(Di,{identity:()=>Wt});var lu=0,qp="identity",du=me;function jp(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return Ut(lu,du(r))}var Wt={code:lu,name:qp,encode:du,digest:jp};function Et(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Gp(r){return r.buffer instanceof ArrayBuffer}function St(r){return Gp(r)?r:r.slice()}async function pu(r,t,e,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,St(t),St(e.subarray()));return n?.signal?.throwIfAborted(),s}function oe(r=0){return new Uint8Array(r)}function bt(r=0){return new Uint8Array(r)}function Wp(r){return r?.buffer instanceof ArrayBuffer}function Ri(r){if(Wp(r))return r;let t=r.slice();return new Uint8Array(t.buffer,0,t.byteLength)}function Mt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=bt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return Ri(e)}var gu=Symbol.for("@achingbrain/uint8arraylist");function mu(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function $o(r){return!!r?.[gu]}var X=class r{bufs;length;[gu]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if($o(n)){e+=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+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if($o(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=mu(this.bufs,t);return e.buf[e.index]}set(t,e){let n=mu(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if($o(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Mt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Mt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=n,s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let f=t>=a&&t<c,u=e>a&&e<=c;if(f&&u){if(t===a&&e===c){n.push(i);break}let h=t-a;n.push(i.subarray(h,h+(e-t)));break}if(f){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!$o(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let h=e;h<=c;h+=u){u=0;for(let p=f;p>=0;p--){let d=this.get(h+p);if(n[p]!==d){u=Math.max(1,p-a[d]);break}}if(u===0)return h}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=bt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=oe(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=oe(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=oe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=bt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=oe(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=oe(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=oe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=oe(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=oe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Et(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var Oi={};rt(Oi,{base10:()=>Xp});var Xp=De({prefix:"9",name:"base10",alphabet:"0123456789"});var Pi={};rt(Pi,{base16:()=>Yp,base16upper:()=>Zp});var Yp=ut({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Zp=ut({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ui={};rt(Ui,{base2:()=>Jp});var Jp=ut({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ni={};rt(Ni,{base256emoji:()=>nm});var yu=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}"),Qp=yu.reduce((r,t,e)=>(r[e]=t,r),[]),tm=yu.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function em(r){return r.reduce((t,e)=>(t+=Qp[e],t),"")}function rm(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=tm[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var nm=Pr({prefix:"\u{1F680}",name:"base256emoji",encode:em,decode:rm});var Fi={};rt(Fi,{base64:()=>om,base64pad:()=>sm,base64url:()=>Dn,base64urlpad:()=>im});var om=ut({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),sm=ut({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Dn=ut({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),im=ut({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ki={};rt(ki,{base8:()=>am});var am=ut({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Mi={};rt(Mi,{identity:()=>cm});var cm=Pr({prefix:"\0",name:"identity",encode:r=>ru(r),decode:r=>eu(r)});var qw=new TextEncoder,jw=new TextDecoder;var Vi={};rt(Vi,{sha256:()=>ge,sha512:()=>lm});var hm=20;function Hi({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new Ki(r,t,e,n,o)}var Ki=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??hm,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?bu(n,this.code,e?.truncate):n.then(o=>bu(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function bu(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Ut(t,r)}function xu(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var ge=Hi({name:"sha2-256",code:18,encode:xu("SHA-256")}),lm=Hi({name:"sha2-512",code:19,encode:xu("SHA-512")});var ir={...Mi,...Ui,...ki,...Oi,...Pi,...Li,..._i,...Ci,...Fi,...Ni},ox={...Vi,...Di};function Su(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Eu=Su("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),zi=Su("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=bt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),dm={utf8:Eu,"utf-8":Eu,hex:ir.base16,latin1:zi,ascii:zi,binary:zi,...ir},qo=dm;function Y(r,t="utf8"){let e=qo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function G(r,t="utf8"){let e=qo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var pm=parseInt("11111",2),$i=parseInt("10000000",2),mm=parseInt("01111111",2),Au={0:Rn,1:Rn,2:gm,3:wm,4:xm,5:bm,6:ym,16:Rn,22:Rn,48:Rn};function ye(r,t={offset:0}){let e=r[t.offset]&pm;if(t.offset++,Au[e]!=null)return Au[e](r,t);throw new Error("No decoder for tag "+e)}function On(r,t){let e=0;if((r[t.offset]&$i)===$i){let n=r[t.offset]&mm,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function Rn(r,t){On(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=ye(r,t);if(n===null)break;e.push(n)}return e}function gm(r,t){let e=On(r,t),n=t.offset,o=t.offset+e,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return t.offset+=e,Uint8Array.from(s)}function ym(r,t){let e=On(r,t),n=t.offset+e,o=r[t.offset];t.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(;t.offset<n;){let f=r[t.offset];if(t.offset++,c.push(f&127),f<128){c.reverse();let u=0;for(let h=0;h<c.length;h++)u+=c[h]<<h*7;a+=`.${u}`,c=[]}}return a}function bm(r,t){return t.offset++,null}function wm(r,t){let e=On(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function xm(r,t){let e=On(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function Em(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new X;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function qi(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=Em(r.byteLength);return new X(Uint8Array.from([t.byteLength|$i]),t)}function Ft(r){let t=new X,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new X(Uint8Array.from([2]),qi(t),t)}function jo(r){let t=Uint8Array.from([0]),e=new X(t,r);return new X(Uint8Array.from([3]),qi(e),e)}function Oe(r,t=48){let e=new X;for(let n of r)e.append(n);return new X(Uint8Array.from([t]),qi(e),e)}var Sm=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Am=Uint8Array.from([6,5,43,129,4,0,34]),vm=Uint8Array.from([6,5,43,129,4,0,35]),Cm={ext:!0,kty:"EC",crv:"P-256"},Lm={ext:!0,kty:"EC",crv:"P-384"},_m={ext:!0,kty:"EC",crv:"P-521"},ji=32,Gi=48,Wi=66;function Xi(r){let t=ye(r);return vu(t)}function vu(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===ji*2+1)return n=G(t.subarray(e,e+ji),"base64url"),o=G(t.subarray(e+ji),"base64url"),new kr({...Cm,key_ops:["verify"],x:n,y:o});if(t.byteLength===Gi*2+1)return n=G(t.subarray(e,e+Gi),"base64url"),o=G(t.subarray(e+Gi),"base64url"),new kr({...Lm,key_ops:["verify"],x:n,y:o});if(t.byteLength===Wi*2+1)return n=G(t.subarray(e,e+Wi),"base64url"),o=G(t.subarray(e+Wi),"base64url"),new kr({..._m,key_ops:["verify"],x:n,y:o});throw new $(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function Cu(r){return Oe([Ft(Uint8Array.from([1])),Oe([Im(r.crv)],160),Oe([jo(new X(Uint8Array.from([4]),Y(r.x??"","base64url"),Y(r.y??"","base64url")))],161)]).subarray()}function Im(r){if(r==="P-256")return Sm;if(r==="P-384")return Am;if(r==="P-521")return vm;throw new $(`Invalid curve ${r}`)}var kr=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=Cu(this.jwk)),this._raw}toMultihash(){return Wt.digest(Pe(this))}toCID(){return pt.createV1(114,this.toMultihash())}toString(){return ht.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}async verify(t,e,n){return pu(this.jwk,e,t,n)}};function Yi(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function se(r,t=""){if(typeof r!="number"){let e=t&&`"${t}" `;throw new TypeError(`${e}expected number, got ${typeof r}`)}if(!Number.isSafeInteger(r)||r<0){let e=t&&`"${t}" `;throw new RangeError(`${e}expected integer >= 0, got ${r}`)}}function It(r,t,e=""){let n=Yi(r),o=r?.length,s=t!==void 0;if(!n||s&&o!==t){let i=e&&`"${e}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof r}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return r}function ar(r){if(typeof r!="function"||typeof r.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(se(r.outputLen),se(r.blockLen),r.outputLen<1)throw new Error('"outputLen" must be >= 1');if(r.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Mr(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function Go(r,t){It(r,void 0,"digestInto() output");let e=t.outputLen;if(r.length<e)throw new RangeError('"digestInto() output" expected to be of length >='+e)}function Xt(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function Wo(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Yt(r,t){return r<<32-t|r>>>t}var _u=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Bm=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Xo(r){if(It(r),_u)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=Bm[r[e]];return t}var be={_0:48,_9:57,A:65,F:70,a:97,f:102};function Lu(r){if(r>=be._0&&r<=be._9)return r-be._0;if(r>=be.A&&r<=be.F)return r-(be.A-10);if(r>=be.a&&r<=be.f)return r-(be.a-10)}function Pn(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);if(_u)try{return Uint8Array.fromHex(r)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let t=r.length,e=t/2;if(t%2)throw new RangeError("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=Lu(r.charCodeAt(s)),a=Lu(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Zi(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];It(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function Ji(r,t={}){let e=(o,s)=>r(s).update(o).digest(),n=r(void 0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.canXOF=n.canXOF,e.create=o=>r(o),Object.assign(e,t),Object.freeze(e)}function Iu(r=32){se(r,"bytesLength");let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(r>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${r}`);return t.getRandomValues(new Uint8Array(r))}var Qi=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Bu(r,t,e){return r&t^~r&e}function Tu(r,t,e){return r&t^r&e^t&e}var Un=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,n,o){this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Wo(this.buffer)}update(t){Mr(this),It(t);let{view:e,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Wo(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Mr(this),Go(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,Xt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let h=i;h<o;h++)e[h]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Wo(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,u=this.get();if(f>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<f;h++)a.setUint32(4*h,u[h],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},we=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var At=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Yo=BigInt(4294967295),Du=BigInt(32);function Tm(r,t=!1){return t?{h:Number(r&Yo),l:Number(r>>Du&Yo)}:{h:Number(r>>Du&Yo)|0,l:Number(r&Yo)|0}}function Ru(r,t=!1){let e=r.length,n=new Uint32Array(e),o=new Uint32Array(e);for(let s=0;s<e;s++){let{h:i,l:a}=Tm(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var ta=(r,t,e)=>r>>>e,ea=(r,t,e)=>r<<32-e|t>>>e,cr=(r,t,e)=>r>>>e|t<<32-e,fr=(r,t,e)=>r<<32-e|t>>>e,Nn=(r,t,e)=>r<<64-e|t>>>e-32,Fn=(r,t,e)=>r>>>e-32|t<<64-e;function ie(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Ou=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),Pu=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,Uu=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),Nu=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,Fu=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),ku=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var Rm=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]),Ue=new Uint32Array(64),ra=class extends Un{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let h=0;h<16;h++,e+=4)Ue[h]=t.getUint32(e,!1);for(let h=16;h<64;h++){let p=Ue[h-15],d=Ue[h-2],m=Yt(p,7)^Yt(p,18)^p>>>3,b=Yt(d,17)^Yt(d,19)^d>>>10;Ue[h]=b+Ue[h-7]+m+Ue[h-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:f,H:u}=this;for(let h=0;h<64;h++){let p=Yt(a,6)^Yt(a,11)^Yt(a,25),d=u+p+Bu(a,c,f)+Rm[h]+Ue[h]|0,b=(Yt(n,2)^Yt(n,13)^Yt(n,22))+Tu(n,o,s)|0;u=f,f=c,c=a,a=i+d|0,i=s,s=o,o=n,n=d+b|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,u=u+this.H|0,this.set(n,o,s,i,a,c,f,u)}roundClean(){Xt(Ue)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Xt(this.buffer)}},na=class extends ra{A=we[0]|0;B=we[1]|0;C=we[2]|0;D=we[3]|0;E=we[4]|0;F=we[5]|0;G=we[6]|0;H=we[7]|0;constructor(){super(32)}};var Mu=Ru(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Om=Mu[0],Pm=Mu[1],Ne=new Uint32Array(80),Fe=new Uint32Array(80),oa=class extends Un{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:u,Fh:h,Fl:p,Gh:d,Gl:m,Hh:b,Hl:l}=this;return[t,e,n,o,s,i,a,c,f,u,h,p,d,m,b,l]}set(t,e,n,o,s,i,a,c,f,u,h,p,d,m,b,l){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=f|0,this.El=u|0,this.Fh=h|0,this.Fl=p|0,this.Gh=d|0,this.Gl=m|0,this.Hh=b|0,this.Hl=l|0}process(t,e){for(let L=0;L<16;L++,e+=4)Ne[L]=t.getUint32(e),Fe[L]=t.getUint32(e+=4);for(let L=16;L<80;L++){let D=Ne[L-15]|0,R=Fe[L-15]|0,O=cr(D,R,1)^cr(D,R,8)^ta(D,R,7),T=fr(D,R,1)^fr(D,R,8)^ea(D,R,7),I=Ne[L-2]|0,U=Fe[L-2]|0,k=cr(I,U,19)^Nn(I,U,61)^ta(I,U,6),N=fr(I,U,19)^Fn(I,U,61)^ea(I,U,6),g=Uu(T,N,Fe[L-7],Fe[L-16]),A=Nu(g,O,k,Ne[L-7],Ne[L-16]);Ne[L]=A|0,Fe[L]=g|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:u,Eh:h,El:p,Fh:d,Fl:m,Gh:b,Gl:l,Hh:y,Hl:v}=this;for(let L=0;L<80;L++){let D=cr(h,p,14)^cr(h,p,18)^Nn(h,p,41),R=fr(h,p,14)^fr(h,p,18)^Fn(h,p,41),O=h&d^~h&b,T=p&m^~p&l,I=Fu(v,R,T,Pm[L],Fe[L]),U=ku(I,y,D,O,Om[L],Ne[L]),k=I|0,N=cr(n,o,28)^Nn(n,o,34)^Nn(n,o,39),g=fr(n,o,28)^Fn(n,o,34)^Fn(n,o,39),A=n&s^n&a^s&a,S=o&i^o&c^i&c;y=b|0,v=l|0,b=d|0,l=m|0,d=h|0,m=p|0,{h,l:p}=ie(f|0,u|0,U|0,k|0),f=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let x=Ou(k,g,S);n=Pu(x,U,N,A),o=x|0}({h:n,l:o}=ie(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ie(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ie(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:u}=ie(this.Dh|0,this.Dl|0,f|0,u|0),{h,l:p}=ie(this.Eh|0,this.El|0,h|0,p|0),{h:d,l:m}=ie(this.Fh|0,this.Fl|0,d|0,m|0),{h:b,l}=ie(this.Gh|0,this.Gl|0,b|0,l|0),{h:y,l:v}=ie(this.Hh|0,this.Hl|0,y|0,v|0),this.set(n,o,s,i,a,c,f,u,h,p,d,m,b,l,y,v)}roundClean(){Xt(Ne,Fe)}destroy(){this.destroyed=!0,Xt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},sa=class extends oa{Ah=At[0]|0;Al=At[1]|0;Bh=At[2]|0;Bl=At[3]|0;Ch=At[4]|0;Cl=At[5]|0;Dh=At[6]|0;Dl=At[7]|0;Eh=At[8]|0;El=At[9]|0;Fh=At[10]|0;Fl=At[11]|0;Gh=At[12]|0;Gl=At[13]|0;Hh=At[14]|0;Hl=At[15]|0;constructor(){super(64)}};var ae=Ji(()=>new na,Qi(1));var Zo=Ji(()=>new sa,Qi(3));var V=(r,t,e)=>It(r,t,e),aa=se,Kr=Xo,mt=(...r)=>Zi(...r),Hr=r=>Pn(r),ur=Yi,hr=r=>Iu(r),Qo=BigInt(0),ia=BigInt(1);function Zt(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}" `;throw new TypeError(e+"expected boolean, got type="+typeof r)}return r}function ts(r){if(typeof r=="bigint"){if(!Jo(r))throw new RangeError("positive bigint expected, got "+r)}else aa(r);return r}function Jt(r,t=""){if(typeof r!="number"){let e=t&&`"${t}" `;throw new TypeError(e+"expected number, got type="+typeof r)}if(!Number.isSafeInteger(r)){let e=t&&`"${t}" `;throw new RangeError(e+"expected safe integer, got "+r)}}function kn(r){let t=ts(r).toString(16);return t.length&1?"0"+t:t}function Ku(r){if(typeof r!="string")throw new TypeError("hex string expected, got "+typeof r);return r===""?Qo:BigInt("0x"+r)}function lr(r){return Ku(Xo(r))}function Kt(r){return Ku(Xo(ke(It(r)).reverse()))}function es(r,t){if(se(t),t===0)throw new RangeError("zero length");r=ts(r);let e=r.toString(16);if(e.length>t*2)throw new RangeError("number too large");return Pn(e.padStart(t*2,"0"))}function Mn(r,t){return es(r,t).reverse()}function Hu(r,t){if(r=V(r),t=V(t),r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function ke(r){return Uint8Array.from(V(r))}function rs(r){if(typeof r!="string")throw new TypeError("ascii string expected, got "+typeof r);return Uint8Array.from(r,(t,e)=>{let n=t.charCodeAt(0);if(t.length!==1||n>127)throw new RangeError(`string contains non-ASCII character "${r[e]}" with code ${n} at position ${e}`);return n})}var Jo=r=>typeof r=="bigint"&&Qo<=r;function Um(r,t,e){return Jo(r)&&Jo(t)&&Jo(e)&&t<=r&&r<e}function xe(r,t,e,n){if(!Um(t,e,n))throw new RangeError("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Vr(r){if(r<Qo)throw new Error("expected non-negative bigint, got "+r);let t;for(t=0;r>Qo;r>>=ia,t+=1);return t}var Kn=r=>(ia<<BigInt(r))-ia;function Vu(r,t,e){if(se(r,"hashLen"),se(t,"qByteLen"),typeof e!="function")throw new TypeError("hmacFn must be a function");let n=l=>new Uint8Array(l),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),f=n(r),u=0,h=()=>{c.fill(1),f.fill(0),u=0},p=(...l)=>e(f,mt(c,...l)),d=(l=o)=>{f=p(s,l),c=p(),l.length!==0&&(f=p(i,l),c=p())},m=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let l=0,y=[];for(;l<t;){c=p();let v=c.slice();y.push(v),l+=c.length}return mt(...y)};return(l,y)=>{h(),d(l);let v;for(;(v=y(m()))===void 0;)d();return h(),v}}function Ht(r,t={},e={}){if(Object.prototype.toString.call(r)!=="[object Object]")throw new TypeError("expected valid options object");function n(s,i,a){if(!a&&i!=="function"&&!Object.hasOwn(r,s))throw new TypeError(`param "${s}" is invalid: expected own property`);let c=r[s];if(a&&c===void 0)return;let f=typeof c;if(f!==i||c===null)throw new TypeError(`param "${s}" is invalid: expected ${i}, got ${f}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(t,!1),o(e,!0)}var ca=()=>{throw new Error("not implemented")};var vt=BigInt(0),lt=BigInt(1),dr=BigInt(2),ju=BigInt(3),Gu=BigInt(4),Wu=BigInt(5),Nm=BigInt(7),Xu=BigInt(8),Fm=BigInt(9),Yu=BigInt(16);function ct(r,t){if(t<=vt)throw new Error("mod: expected positive modulus, got "+t);let e=r%t;return e>=vt?e:t+e}function st(r,t,e){if(t<vt)throw new Error("pow2: expected non-negative exponent, got "+t);let n=r;for(;t-- >vt;)n*=n,n%=e;return n}function zu(r,t){if(r===vt)throw new Error("invert: expected non-zero number");if(t<=vt)throw new Error("invert: expected positive modulus, got "+t);let e=ct(r,t),n=t,o=vt,s=lt,i=lt,a=vt;for(;e!==vt;){let f=n/e,u=n-e*f,h=o-i*f,p=s-a*f;n=e,e=u,o=i,s=a,i=h,a=p}if(n!==lt)throw new Error("invert: does not exist");return ct(o,t)}function fa(r,t,e){let n=r;if(!n.eql(n.sqr(t),e))throw new Error("Cannot find square root")}function Zu(r,t){let e=r,n=(e.ORDER+lt)/Gu,o=e.pow(t,n);return fa(e,o,t),o}function km(r,t){let e=r,n=(e.ORDER-Wu)/Xu,o=e.mul(t,dr),s=e.pow(o,n),i=e.mul(t,s),a=e.mul(e.mul(i,dr),s),c=e.mul(i,e.sub(a,e.ONE));return fa(e,c,t),c}function Mm(r){let t=zr(r),e=Ju(r),n=e(t,t.neg(t.ONE)),o=e(t,n),s=e(t,t.neg(n)),i=(r+Nm)/Yu;return((a,c)=>{let f=a,u=f.pow(c,i),h=f.mul(u,n),p=f.mul(u,o),d=f.mul(u,s),m=f.eql(f.sqr(h),c),b=f.eql(f.sqr(p),c);u=f.cmov(u,h,m),h=f.cmov(d,p,b);let l=f.eql(f.sqr(h),c),y=f.cmov(u,h,l);return fa(f,y,c),y})}function Ju(r){if(r<ju)throw new Error("sqrt is not defined for small field");let t=r-lt,e=0;for(;t%dr===vt;)t/=dr,e++;let n=dr,o=zr(r);for(;$u(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return Zu;let s=o.pow(n,t),i=(t+lt)/dr;return function(c,f){let u=c;if(u.is0(f))return f;if($u(u,f)!==1)throw new Error("Cannot find square root");let h=e,p=u.mul(u.ONE,s),d=u.pow(f,t),m=u.pow(f,i);for(;!u.eql(d,u.ONE);){if(u.is0(d))return u.ZERO;let b=1,l=u.sqr(d);for(;!u.eql(l,u.ONE);)if(b++,l=u.sqr(l),b===h)throw new Error("Cannot find square root");let y=lt<<BigInt(h-b-1),v=u.pow(p,y);h=b,p=u.sqr(v),d=u.mul(d,p),m=u.mul(m,v)}return m}}function Km(r){return r%Gu===ju?Zu:r%Xu===Wu?km:r%Yu===Fm?Mm(r):Ju(r)}var Ee=(r,t)=>(ct(r,t)&lt)===lt,Hm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ua(r){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},e=Hm.reduce((n,o)=>(n[o]="function",n),t);if(Ht(r,e),Jt(r.BYTES,"BYTES"),Jt(r.BITS,"BITS"),r.BYTES<1||r.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(r.ORDER<=lt)throw new Error("invalid field: expected ORDER > 1, got "+r.ORDER);return r}function Vm(r,t,e){let n=r;if(e<vt)throw new Error("invalid exponent, negatives unsupported");if(e===vt)return n.ONE;if(e===lt)return t;let o=n.ONE,s=t;for(;e>vt;)e&lt&&(o=n.mul(o,s)),s=n.sqr(s),e>>=lt;return o}function Hn(r,t,e=!1){let n=r,o=new Array(t.length).fill(e?n.ZERO:void 0),s=t.reduce((a,c,f)=>n.is0(c)?a:(o[f]=a,n.mul(a,c)),n.ONE),i=n.inv(s);return t.reduceRight((a,c,f)=>n.is0(c)?a:(o[f]=n.mul(a,o[f]),n.mul(a,c)),i),o}function $u(r,t){let e=r,n=(e.ORDER-lt)/dr,o=e.pow(t,n),s=e.eql(o,e.ONE),i=e.eql(o,e.ZERO),a=e.eql(o,e.neg(e.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function zm(r,t){if(t!==void 0&&aa(t),r<=vt)throw new Error("invalid n length: expected positive n, got "+r);if(t!==void 0&&t<1)throw new Error("invalid n length: expected positive bit length, got "+t);let e=Vr(r);if(t!==void 0&&t<e)throw new Error(`invalid n length: expected bit length (${e}) >= n.length (${t})`);let n=t!==void 0?t:e,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var qu=new WeakMap,ns=class{ORDER;BITS;BYTES;isLE;ZERO=vt;ONE=lt;_lengths;_mod;constructor(t,e={}){if(t<=lt)throw new Error("invalid field: expected ORDER > 1, got "+t);let n;this.isLE=!1,e!=null&&typeof e=="object"&&(typeof e.BITS=="number"&&(n=e.BITS),typeof e.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:e.sqrt,enumerable:!0}),typeof e.isLE=="boolean"&&(this.isLE=e.isLE),e.allowedLengths&&(this._lengths=Object.freeze(e.allowedLengths.slice())),typeof e.modFromBytes=="boolean"&&(this._mod=e.modFromBytes));let{nBitLength:o,nByteLength:s}=zm(t,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(t){return ct(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof t);return vt<=t&&t<this.ORDER}is0(t){return t===vt}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&lt)===lt}neg(t){return ct(-t,this.ORDER)}eql(t,e){return t===e}sqr(t){return ct(t*t,this.ORDER)}add(t,e){return ct(t+e,this.ORDER)}sub(t,e){return ct(t-e,this.ORDER)}mul(t,e){return ct(t*e,this.ORDER)}pow(t,e){return Vm(this,t,e)}div(t,e){return ct(t*zu(e,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,e){return t+e}subN(t,e){return t-e}mulN(t,e){return t*e}inv(t){return zu(t,this.ORDER)}sqrt(t){let e=qu.get(this);return e||qu.set(this,e=Km(this.ORDER)),e(this,t)}toBytes(t){return this.isLE?Mn(t,this.BYTES):es(t,this.BYTES)}fromBytes(t,e=!1){V(t);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(t.length<1||!n.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let f=new Uint8Array(o);f.set(t,s?0:f.length-t.length),t=f}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=s?Kt(t):lr(t);if(a&&(c=ct(c,i)),!e&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Hn(this,t)}cmov(t,e,n){return Zt(n,"condition"),n?e:t}};Object.freeze(ns.prototype);function zr(r,t={}){return new ns(r,t)}function Qu(r){if(typeof r!="bigint")throw new Error("field order must be bigint");if(r<=lt)throw new Error("field order must be greater than 1");let t=Vr(r-lt);return Math.ceil(t/8)}function ha(r){let t=Qu(r);return t+Math.ceil(t/2)}function la(r,t,e=!1){V(r);let n=r.length,o=Qu(t),s=Math.max(ha(t),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?Kt(r):lr(r),a=ct(i,t-lt)+lt;return e?Mn(a,o):es(a,o)}var $r=BigInt(0),pr=BigInt(1);function Vn(r,t){let e=t.negate();return r?e:t}function mr(r,t){let e=Hn(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function nh(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function da(r,t){nh(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=Kn(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function th(r,t,e){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=e,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=pr);let f=t*n,u=f+Math.abs(a)-1,h=a===0,p=a<0,d=t%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:p,isNegF:d,offsetF:f}}var pa=new WeakMap,oh=new WeakMap;function ma(r){return oh.get(r)||1}function eh(r){if(r!==$r)throw new Error("invalid wNAF")}var qr=class{BASE;ZERO;Fn;bits;constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let o=t;for(;e>$r;)e&pr&&(n=n.add(o)),o=o.double(),e>>=pr;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=da(e,this.bits),s=[],i=t,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let f=1;f<o;f++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=da(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:u,isNeg:h,isNegF:p,offsetF:d}=th(n,a,i);n=c,u?s=s.add(Vn(p,e[d])):o=o.add(Vn(h,e[f]))}return eh(n),{p:o,f:s}}wNAFUnsafe(t,e,n,o=this.ZERO){let s=da(t,this.bits);for(let i=0;i<s.windows&&n!==$r;i++){let{nextN:a,offset:c,isZero:f,isNeg:u}=th(n,i,s);if(n=a,!f){let h=e[c];o=o.add(u?h.negate():h)}}return eh(n),o}getPrecomputes(t,e,n){let o=pa.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),pa.set(e,o))),o}cached(t,e,n){let o=ma(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let s=ma(t);return s===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),e,o)}createCache(t,e){nh(e,this.bits),oh.set(t,e),pa.delete(t)}hasCache(t){return ma(t)!==1}};function sh(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>$r||n>$r;)e&pr&&(s=s.add(o)),n&pr&&(i=i.add(o)),o=o.double(),e>>=pr,n>>=pr;return{p1:s,p2:i}}function rh(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ua(t),t}else return zr(r,{isLE:e})}function os(r,t,e={},n){if(n===void 0&&(n=r==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let f=t[c];if(!(typeof f=="bigint"&&f>$r))throw new Error(`CURVE.${c} must be positive bigint`)}let o=rh(t.p,e.Fp,n),s=rh(t.n,e.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function jr(r,t){return function(n){let o=r(n);return{secretKey:o,publicKey:t(o)}}}var Me=BigInt(0),wt=BigInt(1),ga=BigInt(2),$m=BigInt(8);function qm(r,t,e,n){let o=r.sqr(e),s=r.sqr(n),i=r.add(r.mul(t.a,o),s),a=r.add(r.ONE,r.mul(t.d,r.mul(o,s)));return r.eql(i,a)}function ih(r,t={}){let e=t,n=os("edwards",r,e,e.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;Ht(e,{},{uvRatio:"function"});let c=ga<<BigInt(s.BYTES*8)-wt,f=b=>o.create(b),u=e.uvRatio===void 0?(b,l)=>{try{return{isValid:!0,value:o.sqrt(o.div(b,l))}}catch{return{isValid:!1,value:Me}}}:e.uvRatio;if(!qm(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function h(b,l,y=!1){let v=y?wt:Me;return xe("coordinate "+b,l,v,c),l}function p(b){if(!(b instanceof d))throw new Error("EdwardsPoint expected")}class d{static BASE=new d(i.Gx,i.Gy,wt,f(i.Gx*i.Gy));static ZERO=new d(Me,wt,wt,Me);static Fp=o;static Fn=s;X;Y;Z;T;constructor(l,y,v,L){this.X=h("x",l),this.Y=h("y",y),this.Z=h("z",v,!0),this.T=h("t",L),Object.freeze(this)}static CURVE(){return i}static fromAffine(l){if(l instanceof d)throw new Error("extended point not allowed");let{x:y,y:v}=l||{};return h("x",y),h("y",v),new d(y,v,wt,f(y*v))}static fromBytes(l,y=!1){let v=o.BYTES,{a:L,d:D}=i;l=ke(V(l,v,"point")),Zt(y,"zip215");let R=ke(l),O=l[v-1];R[v-1]=O&-129;let T=Kt(R),I=y?c:o.ORDER;xe("point.y",T,Me,I);let U=f(T*T),k=f(U-wt),N=f(D*U-L),{isValid:g,value:A}=u(k,N);if(!g)throw new Error("bad point: invalid y coordinate");let S=(A&wt)===wt,x=(O&128)!==0;if(!y&&A===Me&&x)throw new Error("bad point: x=0 and x_0=1");return x!==S&&(A=f(-A)),d.fromAffine({x:A,y:T})}static fromHex(l,y=!1){return d.fromBytes(Hr(l),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(l=8,y=!0){return m.createCache(this,l),y||this.multiply(ga),this}assertValidity(){let l=this,{a:y,d:v}=i;if(l.is0())throw new Error("bad point: ZERO");let{X:L,Y:D,Z:R,T:O}=l,T=f(L*L),I=f(D*D),U=f(R*R),k=f(U*U),N=f(T*y),g=f(U*f(N+I)),A=f(k+f(v*f(T*I)));if(g!==A)throw new Error("bad point: equation left != right (1)");let S=f(L*D),x=f(R*O);if(S!==x)throw new Error("bad point: equation left != right (2)")}equals(l){p(l);let{X:y,Y:v,Z:L}=this,{X:D,Y:R,Z:O}=l,T=f(y*O),I=f(D*L),U=f(v*O),k=f(R*L);return T===I&&U===k}is0(){return this.equals(d.ZERO)}negate(){return new d(f(-this.X),this.Y,this.Z,f(-this.T))}double(){let{a:l}=i,{X:y,Y:v,Z:L}=this,D=f(y*y),R=f(v*v),O=f(ga*f(L*L)),T=f(l*D),I=y+v,U=f(f(I*I)-D-R),k=T+R,N=k-O,g=T-R,A=f(U*N),S=f(k*g),x=f(U*g),w=f(N*k);return new d(A,S,w,x)}add(l){p(l);let{a:y,d:v}=i,{X:L,Y:D,Z:R,T:O}=this,{X:T,Y:I,Z:U,T:k}=l,N=f(L*T),g=f(D*I),A=f(O*v*k),S=f(R*U),x=f((L+D)*(T+I)-N-g),w=S-A,C=S+A,_=f(g-y*N),E=f(x*w),B=f(C*_),P=f(x*_),F=f(w*C);return new d(E,B,F,P)}subtract(l){return p(l),this.add(l.negate())}multiply(l){if(!s.isValidNot0(l))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:y,f:v}=m.cached(this,l,L=>mr(d,L));return mr(d,[y,v])[0]}multiplyUnsafe(l){if(!s.isValid(l))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return l===Me?d.ZERO:this.is0()||l===wt?this:m.unsafe(this,l,y=>mr(d,y))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return m.unsafe(this,i.n).is0()}toAffine(l){let y=this,v=l,{X:L,Y:D,Z:R}=y,O=y.is0();v==null&&(v=O?$m:o.inv(R));let T=f(L*v),I=f(D*v),U=o.mul(R,v);if(O)return{x:Me,y:wt};if(U!==wt)throw new Error("invZ was invalid");return{x:T,y:I}}clearCofactor(){return a===wt?this:this.multiplyUnsafe(a)}toBytes(){let{x:l,y}=this.toAffine(),v=o.toBytes(y);return v[v.length-1]|=l&wt?128:0,v}toHex(){return Kr(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let m=new qr(d,s.BITS);return s.BITS>=8&&d.BASE.precompute(8),Object.freeze(d.prototype),Object.freeze(d),d}var ss=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(t){this.ep=t}static fromBytes(t){ca()}static fromHex(t){ca()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return Kr(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,e){return this.ep.precompute(t,e),this}};function ah(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');let n=t,o=e;Ht(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=r,f=n.outputLen,u=2*a.BYTES;if(f!==void 0&&(Jt(f,"hash.outputLen"),f!==u))throw new Error(`hash.outputLen must be ${u}, got ${f}`);let h=o.randomBytes===void 0?hr:o.randomBytes,p=o.adjustScalarBytes===void 0?g=>g:o.adjustScalarBytes,d=o.domain===void 0?(g,A,S)=>{if(Zt(S,"phflag"),A.length||S)throw new Error("Contexts/pre-hash are not supported");return g}:o.domain;function m(g){return c.create(Kt(g))}function b(g){let A=T.secretKey;V(g,T.secretKey,"secretKey");let S=V(n(g),2*A,"hashedSecretKey"),x=p(S.slice(0,A)),w=S.slice(A,2*A),C=m(x);return{head:x,prefix:w,scalar:C}}function l(g){let{head:A,prefix:S,scalar:x}=b(g),w=i.multiply(x),C=w.toBytes();return{head:A,prefix:S,scalar:x,point:w,pointBytes:C}}function y(g){return l(g).pointBytes}function v(g=Uint8Array.of(),...A){let S=mt(...A);return m(n(d(S,V(g,void 0,"context"),!!s)))}function L(g,A,S={}){g=V(g,void 0,"message"),s&&(g=s(g));let{prefix:x,scalar:w,pointBytes:C}=l(A),_=v(S.context,x,g),E=i.multiply(_).toBytes(),B=v(S.context,E,C,g),P=c.create(_+B*w);if(!c.isValid(P))throw new Error("sign failed: invalid s");let F=mt(E,c.toBytes(P));return V(F,T.signature,"result")}let D={zip215:o.zip215};function R(g,A,S,x=D){let{context:w}=x,C=x.zip215===void 0?!!D.zip215:x.zip215,_=T.signature;g=V(g,_,"signature"),A=V(A,void 0,"message"),S=V(S,T.publicKey,"publicKey"),C!==void 0&&Zt(C,"zip215"),s&&(A=s(A));let E=_/2,B=g.subarray(0,E),P=Kt(g.subarray(E,_)),F,H,K;try{F=r.fromBytes(S,C),H=r.fromBytes(B,C),K=i.multiplyUnsafe(P)}catch{return!1}if(!C&&F.isSmallOrder())return!1;let Q=v(w,B,S,A);return H.add(F.multiplyUnsafe(Q)).subtract(K).clearCofactor().is0()}let O=a.BYTES,T={secretKey:O,publicKey:O,signature:2*O,seed:O};function I(g){return g=g===void 0?h(T.seed):g,V(g,T.seed,"seed")}function U(g){return ur(g)&&g.length===T.secretKey}function k(g,A){try{return!!r.fromBytes(g,A===void 0?D.zip215:A)}catch{return!1}}let N={getExtendedPublicKey:l,randomSecretKey:I,isValidSecretKey:U,isValidPublicKey:k,toMontgomery(g){let{y:A}=r.fromBytes(g),S=T.publicKey,x=S===32;if(!x&&S!==57)throw new Error("only defined for 25519 and 448");let w=x?a.div(wt+A,wt-A):a.div(A-wt,A+wt);return a.toBytes(w)},toMontgomerySecret(g){let A=T.secretKey;V(g,A);let S=n(g.subarray(0,A));return p(S).subarray(0,A)}};return Object.freeze(T),Object.freeze(N),Object.freeze({keygen:jr(I,y),getPublicKey:y,sign:L,verify:R,utils:N,Point:r,lengths:T})}function zn(r,t){if(Jt(r),Jt(t),t<0||t>4)throw new Error("invalid I2OSP length: "+t);if(r<0||r>2**(8*t)-1)throw new Error("invalid I2OSP input: "+r);let e=Array.from({length:t}).fill(0);for(let n=t-1;n>=0;n--)e[n]=r&255,r>>>=8;return new Uint8Array(e)}function jm(r,t){let e=new Uint8Array(r.length);for(let n=0;n<r.length;n++)e[n]=r[n]^t[n];return e}function Gm(r){if(!ur(r)&&typeof r!="string")throw new Error("DST must be Uint8Array or ascii string");let t=typeof r=="string"?rs(r):r;if(t.length===0)throw new Error("DST must be non-empty");return t}function ya(r,t,e,n){V(r),Jt(e),t=Gm(t),t.length>255&&(t=n(mt(rs("H2C-OVERSIZE-DST-"),t)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(e/o);if(e>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=mt(t,zn(t.length,1)),c=new Uint8Array(s),f=zn(e,2),u=new Array(i),h=n(mt(c,r,f,zn(0,1),a));u[0]=n(mt(h,zn(1,1),a));for(let d=1;d<i;d++){let m=[jm(h,u[d-1]),zn(d+1,1),a];u[d]=n(mt(...m))}return mt(...u).slice(0,e)}var ch="HashToScalar-";var $n=BigInt(0),Gr=BigInt(1),is=BigInt(2);function Wm(r){return Ht(r,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...r})}function fh(r){let t=Wm(r),{P:e,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=t,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i===void 0?hr:i,f=a?255:448,u=a?32:56,h=BigInt(a?9:5),p=BigInt(a?121665:39081),d=a?is**BigInt(254):is**BigInt(447),m=a?BigInt(8)*is**BigInt(251)-Gr:BigInt(4)*is**BigInt(445)-Gr,b=d+m+Gr,l=S=>ct(S,e),y=v(h);function v(S){return Mn(l(S),u)}function L(S){let x=ke(V(S,u,"uCoordinate"));return a&&(x[31]&=127),l(Kt(x))}function D(S){return Kt(o(ke(V(S,u,"scalar"))))}function R(S,x){let w=k(L(x),D(S));if(w===$n)throw new Error("invalid private or public key received");return v(w)}function O(S){return R(S,y)}let T=O,I=R;function U(S,x,w){let C=l(S*(x-w));return x=l(x-C),w=l(w+C),{x_2:x,x_3:w}}function k(S,x){xe("u",S,$n,e),xe("scalar",x,d,b);let w=x,C=S,_=Gr,E=$n,B=S,P=Gr,F=$n;for(let K=BigInt(f-1);K>=$n;K--){let Q=w>>K&Gr;F^=Q,{x_2:_,x_3:B}=U(F,_,B),{x_2:E,x_3:P}=U(F,E,P),F=Q;let tt=_+E,et=l(tt*tt),j=_-E,at=l(j*j),pe=et-at,rr=B+P,Br=B-P,vn=l(Br*tt),Cn=l(rr*j),Yf=vn+Cn,Zf=vn-Cn;B=l(Yf*Yf),P=l(C*l(Zf*Zf)),_=l(et*at),E=l(pe*(et+l(p*pe)))}({x_2:_,x_3:B}=U(F,_,B)),{x_2:E,x_3:P}=U(F,E,P);let H=s(E);return l(_*H)}let N={secretKey:u,publicKey:u,seed:u},g=S=>(S=S===void 0?c(u):S,V(S,N.seed,"seed"),S),A={randomSecretKey:g};return Object.freeze(N),Object.freeze(A),Object.freeze({keygen:jr(g,T),getSharedSecret:I,getPublicKey:T,scalarMult:R,scalarMultBase:O,utils:A,GuBytes:y.slice(),lengths:N})}var Xm=BigInt(0),Se=BigInt(1),uh=BigInt(2),Ym=BigInt(3),Zm=BigInt(5),Jm=BigInt(8),gr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ea={p:gr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Jm,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function dh(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=gr,a=r*r%s*r%s,c=st(a,uh,s)*a%s,f=st(c,Se,s)*r%s,u=st(f,Zm,s)*f%s,h=st(u,t,s)*u%s,p=st(h,e,s)*h%s,d=st(p,n,s)*p%s,m=st(d,o,s)*d%s,b=st(m,o,s)*d%s,l=st(b,t,s)*u%s;return{pow_p_5_8:st(l,uh,s)*r%s,b2:a}}function ph(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var ba=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Sa(r,t){let e=gr,n=ct(t*t*t,e),o=ct(n*n*t,e),s=dh(r*o).pow_p_5_8,i=ct(r*n*s,e),a=ct(t*i*i,e),c=i,f=ct(i*ba,e),u=a===r,h=a===ct(-r,e),p=a===ct(-r*ba,e);return u&&(i=c),(h||p)&&(i=f),Ee(i,e)&&(i=ct(-i,e)),{isValid:u||h,value:i}}var He=ih(Ea,{uvRatio:Sa}),Ke=He.Fp,mh=He.Fn;function Qm(r){return ah(He,Zo,Object.assign({adjustScalarBytes:ph,zip215:!0},r))}var gh=Qm({});var qn=(()=>{let r=gr;return fh({P:r,type:"x25519",powPminus2:t=>{let{pow_p_5_8:e,b2:n}=dh(t);return ct(st(e,Ym,r)*n,r)},adjustScalarBytes:ph})})();var wa=ba,t0=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),e0=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),r0=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),n0=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),hh=r=>Sa(Se,r),o0=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),xa=r=>Ke.create(Kt(r)&o0);function lh(r){let{d:t}=Ea,e=gr,n=y=>Ke.create(y),o=n(wa*r*r),s=n((o+Se)*r0),i=BigInt(-1),a=n((i-t*o)*n(o+t)),{isValid:c,value:f}=Sa(s,a),u=n(f*r);Ee(u,e)||(u=n(-u)),c||(f=u),c||(i=o);let h=n(i*(o-Se)*n0-a),p=f*f,d=n((f+f)*a),m=n(h*t0),b=n(Se-p),l=n(Se+p);return new He(n(d*l),n(b*m),n(m*l),n(d*b))}var Ve=class r extends ss{static BASE=new r(He.BASE);static ZERO=new r(He.ZERO);static Fp=Ke;static Fn=mh;constructor(t){super(t)}static fromAffine(t){return new r(He.fromAffine(t))}assertSame(t){if(!(t instanceof r))throw new Error("RistrettoPoint expected")}init(t){return new r(t)}static fromBytes(t){It(t,32);let{a:e,d:n}=Ea,o=gr,s=D=>Ke.create(D),i=xa(t);if(!Hu(Ke.toBytes(i),t)||Ee(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(Se+e*a),f=s(Se-e*a),u=s(c*c),h=s(f*f),p=s(e*n*u-h),{isValid:d,value:m}=hh(s(p*h)),b=s(m*f),l=s(m*b*p),y=s((i+i)*b);Ee(y,o)&&(y=s(-y));let v=s(c*l),L=s(y*v);if(!d||Ee(L,o)||v===Xm)throw new Error("invalid ristretto255 encoding 2");return new r(new He(y,v,Se,L))}static fromHex(t){return r.fromBytes(Pn(t))}toBytes(){let{X:t,Y:e,Z:n,T:o}=this.ep,s=gr,i=l=>Ke.create(l),a=i(i(n+e)*i(n-e)),c=i(t*e),f=i(c*c),{value:u}=hh(i(a*f)),h=i(u*a),p=i(u*c),d=i(h*p*o),m;if(Ee(o*d,s)){let l=i(e*wa),y=i(t*wa);t=l,e=y,m=i(h*e0)}else m=p;Ee(t*d,s)&&(e=i(-e));let b=i((n-e)*m);return Ee(b,s)&&(b=i(-b)),Ke.toBytes(b)}equals(t){this.assertSame(t);let{X:e,Y:n}=this.ep,{X:o,Y:s}=t.ep,i=f=>Ke.create(f),a=i(e*s)===i(n*o),c=i(n*s)===i(e*o);return a||c}is0(){return this.equals(r.ZERO)}};Object.freeze(Ve.BASE);Object.freeze(Ve.ZERO);Object.freeze(Ve.prototype);Object.freeze(Ve);var s0=Object.freeze({Point:Ve,hashToCurve(r,t){let e=t?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":t.DST,n=ya(r,e,64,Zo);return s0.deriveToCurve(n)},hashToScalar(r,t={DST:ch}){let e=ya(r,t.DST,64,Zo);return mh.create(Kt(e))},deriveToCurve(r){It(r,64);let t=xa(r.subarray(0,32)),e=lh(t),n=xa(r.subarray(32,64)),o=lh(n);return new Ve(e.add(o))}});var jn=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},as=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var qt={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new as("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var cs=32;var Aa,i0=(async()=>{try{return await qt.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function a0(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await qt.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await qt.get().subtle.verify({name:"Ed25519"},n,St(t),St(e instanceof Uint8Array?e:e.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function c0(r,t,e){return gh.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function yh(r,t,e){return Aa==null&&(Aa=await i0),Aa?a0(r,t,e):c0(r,t,e)}function fs(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var us=class{type="Ed25519";raw;constructor(t){this.raw=va(t,cs)}toMultihash(){return Wt.digest(Pe(this))}toCID(){return pt.createV1(114,this.toMultihash())}toString(){return ht.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=yh(this.raw,e,t);return fs(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Ca(r){return r=va(r,cs),new us(r)}function va(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new $(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var u0=Math.pow(2,7),h0=Math.pow(2,14),l0=Math.pow(2,21),La=Math.pow(2,28),_a=Math.pow(2,35),Ia=Math.pow(2,42),Ba=Math.pow(2,49),Z=128,Bt=127;function it(r){if(r<u0)return 1;if(r<h0)return 2;if(r<l0)return 3;if(r<La)return 4;if(r<_a)return 5;if(r<Ia)return 6;if(r<Ba)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Wr(r,t,e=0){switch(it(r)){case 8:t[e++]=r&255|Z,r/=128;case 7:t[e++]=r&255|Z,r/=128;case 6:t[e++]=r&255|Z,r/=128;case 5:t[e++]=r&255|Z,r/=128;case 4:t[e++]=r&255|Z,r>>>=7;case 3:t[e++]=r&255|Z,r>>>=7;case 2:t[e++]=r&255|Z,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function d0(r,t,e=0){switch(it(r)){case 8:t.set(e++,r&255|Z),r/=128;case 7:t.set(e++,r&255|Z),r/=128;case 6:t.set(e++,r&255|Z),r/=128;case 5:t.set(e++,r&255|Z),r/=128;case 4:t.set(e++,r&255|Z),r>>>=7;case 3:t.set(e++,r&255|Z),r>>>=7;case 2:t.set(e++,r&255|Z),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Ta(r,t){let e=r[t],n=0;if(n+=e&Bt,e<Z||(e=r[t+1],n+=(e&Bt)<<7,e<Z)||(e=r[t+2],n+=(e&Bt)<<14,e<Z)||(e=r[t+3],n+=(e&Bt)<<21,e<Z)||(e=r[t+4],n+=(e&Bt)*La,e<Z)||(e=r[t+5],n+=(e&Bt)*_a,e<Z)||(e=r[t+6],n+=(e&Bt)*Ia,e<Z)||(e=r[t+7],n+=(e&Bt)*Ba,e<Z))return n;throw new RangeError("Could not decode varint")}function p0(r,t){let e=r.get(t),n=0;if(n+=e&Bt,e<Z||(e=r.get(t+1),n+=(e&Bt)<<7,e<Z)||(e=r.get(t+2),n+=(e&Bt)<<14,e<Z)||(e=r.get(t+3),n+=(e&Bt)<<21,e<Z)||(e=r.get(t+4),n+=(e&Bt)*La,e<Z)||(e=r.get(t+5),n+=(e&Bt)*_a,e<Z)||(e=r.get(t+6),n+=(e&Bt)*Ia,e<Z)||(e=r.get(t+7),n+=(e&Bt)*Ba,e<Z))return n;throw new RangeError("Could not decode varint")}function hs(r,t,e=0){return t==null&&(t=bt(it(r))),t instanceof Uint8Array?Wr(r,t,e):d0(r,t,e)}function Ae(r,t=0){return r instanceof Uint8Array?Ta(r,t):p0(r,t)}var Da=new Float32Array([-0]),ze=new Uint8Array(Da.buffer);function wh(r,t,e){Da[0]=r,t[e]=ze[0],t[e+1]=ze[1],t[e+2]=ze[2],t[e+3]=ze[3]}function xh(r,t){return ze[0]=r[t],ze[1]=r[t+1],ze[2]=r[t+2],ze[3]=r[t+3],Da[0]}var Ra=new Float64Array([-0]),Tt=new Uint8Array(Ra.buffer);function Eh(r,t,e){Ra[0]=r,t[e]=Tt[0],t[e+1]=Tt[1],t[e+2]=Tt[2],t[e+3]=Tt[3],t[e+4]=Tt[4],t[e+5]=Tt[5],t[e+6]=Tt[6],t[e+7]=Tt[7]}function Sh(r,t){return Tt[0]=r[t],Tt[1]=r[t+1],Tt[2]=r[t+2],Tt[3]=r[t+3],Tt[4]=r[t+4],Tt[5]=r[t+5],Tt[6]=r[t+6],Tt[7]=r[t+7],Ra[0]}var m0=BigInt(Number.MAX_SAFE_INTEGER),g0=BigInt(Number.MIN_SAFE_INTEGER),Vt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return yr;if(t<m0&&t>g0)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>Ah&&(o=0n,++n>Ah&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return yr;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):yr}},yr=new Vt(0,0);yr.toBigInt=function(){return 0n};yr.zzEncode=yr.zzDecode=function(){return this};yr.length=function(){return 1};var Ah=4294967296n;function vh(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Ch(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Oa(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function Qt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function ls(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Pa=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=St(t),this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Qt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Qt(this,4);return ls(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Qt(this,4);return ls(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Qt(this,4);let t=xh(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Qt(this,4);let t=Sh(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw Qt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Ch(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Qt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Qt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Vt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Qt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Qt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Qt(this,8);let t=ls(this.buf,this.pos+=4),e=ls(this.buf,this.pos+=4);return new Vt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Ta(this.buf,this.pos);return this.pos+=it(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Wn(r){return new Pa(r instanceof Uint8Array?r:r.subarray())}function $e(r,t,e){let n=Wn(r);return t.decode(n,void 0,e)}function Ua(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return bt(i);o+i>t&&(n=bt(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var br=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Na(){}var ka=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},y0=Ua();function b0(r){return globalThis.Buffer!=null?bt(r):y0(r)}var Yn=class{len;head;tail;states;constructor(){this.len=0,this.head=new br(Na,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new br(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Ma((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(ds,10,Vt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Vt.fromBigInt(t);return this._push(ds,e.length(),e)}uint64Number(t){return this._push(Wr,it(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Vt.fromBigInt(t).zzEncode();return this._push(ds,e.length(),e)}sint64Number(t){let e=Vt.fromNumber(t).zzEncode();return this._push(ds,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Fa,1,t?1:0)}fixed32(t){return this._push(Xn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Vt.fromBigInt(t);return this._push(Xn,4,e.lo)._push(Xn,4,e.hi)}fixed64Number(t){let e=Vt.fromNumber(t);return this._push(Xn,4,e.lo)._push(Xn,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(wh,4,t)}double(t){return this._push(Eh,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Fa,1,0):this.uint32(e)._push(x0,e,t)}string(t){let e=vh(t);return e!==0?this.uint32(e)._push(Oa,e,t):this._push(Fa,1,0)}fork(){return this.states=new ka(this),this.head=this.tail=new br(Na,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new br(Na,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=b0(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Fa(r,t,e){t[e]=r&255}function w0(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Ma=class extends br{next;constructor(t,e){super(w0,t,e),this.next=void 0}};function ds(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Xn(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function x0(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Yn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(E0,t,r),this},Yn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(S0,t,r),this});function E0(r,t,e){t.set(r,e)}function S0(r,t,e){r.length<40?Oa(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Y(r),e)}function Ka(){return new Yn}function qe(r,t){let e=Ka();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}function*je(r,t,e){let n=Wn(r);yield*t.stream(n,void 0,"$",e)}var ps={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function ms(r,t,e,n,o){return{name:r,type:t,encode:e,decode:n,stream:o}}function wr(r){function t(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let e=function(i,a){let c=t(i);a.int32(c)},n=function(i){let a=i.int32();return t(a)},o=function*(i){let a=i.int32();yield t(a)};return ms("enum",ps.VARINT,e,n,o)}function Ge(r,t,e){return ms("message",ps.LENGTH_DELIMITED,r,t,e)}var ft;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ft||(ft={}));var Ha;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Ha||(Ha={}));(function(r){r.codec=()=>wr(Ha)})(ft||(ft={}));var ce;(function(r){let t;r.codec=()=>(t==null&&(t=Ge((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ft.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 u=s.uint32();switch(u>>>3){case 1:{c.Type=ft.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:ft.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),t);function e(s){return qe(s,r.codec())}r.encode=e;function n(s,i){return $e(s,r.codec(),i)}r.decode=n;function o(s,i){return je(s,r.codec(),i)}r.stream=o})(ce||(ce={}));var Va;(function(r){let t;r.codec=()=>(t==null&&(t=Ge((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ft.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 u=s.uint32();switch(u>>>3){case 1:{c.Type=ft.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(u&7);break}}}return c},function*(s,i,a,c={}){let f=i==null?s.len:s.pos+i;for(;s.pos<f;){let u=s.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:ft.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(u&7);break}}}})),t);function e(s){return qe(s,r.codec())}r.encode=e;function n(s,i){return $e(s,r.codec(),i)}r.decode=n;function o(s,i){return je(s,r.codec(),i)}r.stream=o})(Va||(Va={}));var Jn={};rt(Jn,{MAX_RSA_KEY_SIZE:()=>za,generateRSAKeyPair:()=>Dh,jwkToJWKKeyPair:()=>Rh,jwkToPkcs1:()=>L0,jwkToPkix:()=>Ga,jwkToRSAPrivateKey:()=>Za,pkcs1MessageToJwk:()=>qa,pkcs1MessageToRSAPrivateKey:()=>Wa,pkcs1ToJwk:()=>C0,pkcs1ToRSAPrivateKey:()=>Th,pkixMessageToJwk:()=>ja,pkixMessageToRSAPublicKey:()=>Ya,pkixToJwk:()=>_0,pkixToRSAPublicKey:()=>Xa});var Xr=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=Jn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return pt.createV1(114,this._multihash)}toString(){return ht.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e,n){return Bh(this.jwk,e,t,n)}},Zn=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=Jn.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}sign(t,e){return Ih(this.jwk,t,e)}};var za=8192,$a=18,A0=1062,v0=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function C0(r){let t=ye(r);return qa(t)}function qa(r){return{n:G(r[1],"base64url"),e:G(r[2],"base64url"),d:G(r[3],"base64url"),p:G(r[4],"base64url"),q:G(r[5],"base64url"),dp:G(r[6],"base64url"),dq:G(r[7],"base64url"),qi:G(r[8],"base64url"),kty:"RSA"}}function L0(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new $("JWK was missing components");return Oe([Ft(Uint8Array.from([0])),Ft(Y(r.n,"base64url")),Ft(Y(r.e,"base64url")),Ft(Y(r.d,"base64url")),Ft(Y(r.p,"base64url")),Ft(Y(r.q,"base64url")),Ft(Y(r.dp,"base64url")),Ft(Y(r.dq,"base64url")),Ft(Y(r.qi,"base64url"))]).subarray()}function _0(r){let t=ye(r,{offset:0});return ja(t)}function ja(r){let t=ye(r[1],{offset:0});return{kty:"RSA",n:G(t[0],"base64url"),e:G(t[1],"base64url")}}function Ga(r){if(r.n==null||r.e==null)throw new $("JWK was missing components");return Oe([v0,jo(Oe([Ft(Y(r.n,"base64url")),Ft(Y(r.e,"base64url"))]))]).subarray()}function Th(r){let t=ye(r);return Wa(t)}function Wa(r){let t=qa(r);return Za(t)}function Xa(r,t){if(r.byteLength>=A0)throw new Tr("Key size is too large");let e=ye(r,{offset:0});return Ya(e,r,t)}function Ya(r,t,e){let n=ja(r);if(e==null){let o=ae(ce.encode({Type:ft.RSA,Data:t}));e=Ut($a,o)}return new Xr(n,e)}function Za(r){if(Ph(r)>za)throw new $("Key size is too large");let t=Rh(r),e=ae(ce.encode({Type:ft.RSA,Data:Ga(t.publicKey)})),n=Ut($a,e);return new Zn(t.privateKey,new Xr(t.publicKey,n))}async function Dh(r){if(r>za)throw new $("Key size is too large");let t=await Oh(r),e=ae(ce.encode({Type:ft.RSA,Data:Ga(t.publicKey)})),n=Ut($a,e);return new Zn(t.privateKey,new Xr(t.publicKey,n))}function Rh(r){if(r==null)throw new $("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Oh(r,t){let e=await qt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);t?.signal?.throwIfAborted();let n=await I0(e,t);return{privateKey:n[0],publicKey:n[1]}}async function Ih(r,t,e){let n=await qt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);e?.signal?.throwIfAborted();let o=await qt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,St(t instanceof Uint8Array?t:t.subarray()));return e?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Bh(r,t,e,n){let o=await qt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await qt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,St(t),St(e instanceof Uint8Array?e:e.subarray()));return n?.signal?.throwIfAborted(),s}async function I0(r,t){if(r.privateKey==null||r.publicKey==null)throw new $("Private and public key are required");let e=await Promise.all([qt.get().subtle.exportKey("jwk",r.privateKey),qt.get().subtle.exportKey("jwk",r.publicKey)]);return t?.signal?.throwIfAborted(),e}function Ph(r){if(r.kty!=="RSA")throw new $("invalid key type");if(r.n==null)throw new $("invalid key modulus");return Y(r.n,"base64url").length*8}var gs=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(t,e){if(ar(t),It(e,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(e.length>n?t.create().update(e).digest():e);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Xt(o)}update(t){return Mr(this),this.iHash.update(t),this}digestInto(t){Mr(this),Go(t,this),this.finished=!0;let e=t.subarray(0,this.outputLen);this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Qn=(()=>{let r=((t,e,n)=>new gs(t,e).update(n).digest());return r.create=(t,e)=>new gs(t,e),r})();var Uh=(r,t)=>(r+(r>=0?t:-t)/Nh)/t;function B0(r,t,e){xe("scalar",r,fe,e);let[[n,o],[s,i]]=t,a=Uh(i*r,e),c=Uh(-o*r,e),f=r-a*n-c*s,u=-a*o-c*i,h=f<fe,p=u<fe;h&&(f=-f),p&&(u=-u);let d=Kn(Math.ceil(Vr(e)/2))+We;if(f<fe||f>=d||u<fe||u>=d)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:h,k1:f,k2neg:p,k2:u}}function Qa(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Ja(r,t){Ht(r);let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return Zt(e.lowS,"lowS"),Zt(e.prehash,"prehash"),e.format!==void 0&&Qa(e.format),e}var tc=class extends Error{constructor(t=""){super(t)}},te={Err:tc,_tlv:{encode:(r,t)=>{let{Err:e}=te;if(Jt(r,"tag"),r<0||r>255)throw new e("tlv.encode: wrong tag");if(typeof t!="string")throw new TypeError('"data" expected string, got type='+typeof t);if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=kn(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?kn(o.length/2|128):"";return kn(r)+s+o+t},decode(r,t){let{Err:e}=te;t=V(t,void 0,"DER data");let n=0;if(r<0||r>255)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let f=t.subarray(n,n+c);if(f.length!==c)throw new e("tlv.decode: length bytes not complete");if(f[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of f)i=i<<8|u;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=te;if(ts(r),r<fe)throw new t("integer: negative integers are not allowed");let e=kn(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=te;if(r.length<1)throw new t("invalid signature integer: empty");if(r[0]&128)throw new t("invalid signature integer: negative");if(r.length>1&&r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return lr(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=te,o=V(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:f,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(f)}},hexFromSig(r){let{_tlv:t,_int:e}=te,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}};Object.freeze(te._tlv);Object.freeze(te._int);Object.freeze(te);var fe=BigInt(0),We=BigInt(1),Nh=BigInt(2),ys=BigInt(3),T0=BigInt(4);function Fh(r,t={}){let e=os("weierstrass",r,t),n=e.Fp,o=e.Fn,s=e.CURVE,{h:i,n:a}=s;Ht(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:f}=t;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 u=Mh(n,o);function h(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(N,g,A){if(f&&g.is0())return Uint8Array.of(0);let{x:S,y:x}=g.toAffine(),w=n.toBytes(S);if(Zt(A,"isCompressed"),A){h();let C=!n.isOdd(x);return mt(kh(C),w)}else return mt(Uint8Array.of(4),w,n.toBytes(x))}function d(N){V(N,void 0,"Point");let{publicKey:g,publicKeyUncompressed:A}=u,S=N.length,x=N[0],w=N.subarray(1);if(f&&S===1&&x===0)return{x:n.ZERO,y:n.ZERO};if(S===g&&(x===2||x===3)){let C=n.fromBytes(w);if(!n.isValid(C))throw new Error("bad point: is not on curve, wrong x");let _=l(C),E;try{E=n.sqrt(_)}catch(F){let H=F instanceof Error?": "+F.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}h();let B=n.isOdd(E);return(x&1)===1!==B&&(E=n.neg(E)),{x:C,y:E}}else if(S===A&&x===4){let C=n.BYTES,_=n.fromBytes(w.subarray(0,C)),E=n.fromBytes(w.subarray(C,C*2));if(!y(_,E))throw new Error("bad point: is not on curve");return{x:_,y:E}}else throw new Error(`bad point: got length ${S}, expected compressed=${g} or uncompressed=${A}`)}let m=t.toBytes===void 0?p:t.toBytes,b=t.fromBytes===void 0?d:t.fromBytes;function l(N){let g=n.sqr(N),A=n.mul(g,N);return n.add(n.add(A,n.mul(N,s.a)),s.b)}function y(N,g){let A=n.sqr(g),S=l(N);return n.eql(A,S)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let v=n.mul(n.pow(s.a,ys),T0),L=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(v,L)))throw new Error("bad curve params: a or b");function D(N,g,A=!1){if(!n.isValid(g)||A&&n.is0(g))throw new Error(`bad point coordinate ${N}`);return g}function R(N){if(!(N instanceof I))throw new Error("Weierstrass Point expected")}function O(N){if(!c||!c.basises)throw new Error("no endo");return B0(N,c.basises,o.ORDER)}function T(N,g,A,S,x){return A=new I(n.mul(A.X,N),A.Y,A.Z),g=Vn(S,g),A=Vn(x,A),g.add(A)}class I{static BASE=new I(s.Gx,s.Gy,n.ONE);static ZERO=new I(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(g,A,S){this.X=D("x",g),this.Y=D("y",A,!0),this.Z=D("z",S),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){let{x:A,y:S}=g||{};if(!g||!n.isValid(A)||!n.isValid(S))throw new Error("invalid affine point");if(g instanceof I)throw new Error("projective point not allowed");return n.is0(A)&&n.is0(S)?I.ZERO:new I(A,S,n.ONE)}static fromBytes(g){let A=I.fromAffine(b(V(g,void 0,"point")));return A.assertValidity(),A}static fromHex(g){return I.fromBytes(Hr(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,A=!0){return k.createCache(this,g),A||this.multiply(ys),this}assertValidity(){let g=this;if(g.is0()){if(t.allowInfinityPoint&&n.is0(g.X)&&n.eql(g.Y,n.ONE)&&n.is0(g.Z))return;throw new Error("bad point: ZERO")}let{x:A,y:S}=g.toAffine();if(!n.isValid(A)||!n.isValid(S))throw new Error("bad point: x or y not field elements");if(!y(A,S))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:g}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(g)}equals(g){R(g);let{X:A,Y:S,Z:x}=this,{X:w,Y:C,Z:_}=g,E=n.eql(n.mul(A,_),n.mul(w,x)),B=n.eql(n.mul(S,_),n.mul(C,x));return E&&B}negate(){return new I(this.X,n.neg(this.Y),this.Z)}double(){let{a:g,b:A}=s,S=n.mul(A,ys),{X:x,Y:w,Z:C}=this,_=n.ZERO,E=n.ZERO,B=n.ZERO,P=n.mul(x,x),F=n.mul(w,w),H=n.mul(C,C),K=n.mul(x,w);return K=n.add(K,K),B=n.mul(x,C),B=n.add(B,B),_=n.mul(g,B),E=n.mul(S,H),E=n.add(_,E),_=n.sub(F,E),E=n.add(F,E),E=n.mul(_,E),_=n.mul(K,_),B=n.mul(S,B),H=n.mul(g,H),K=n.sub(P,H),K=n.mul(g,K),K=n.add(K,B),B=n.add(P,P),P=n.add(B,P),P=n.add(P,H),P=n.mul(P,K),E=n.add(E,P),H=n.mul(w,C),H=n.add(H,H),P=n.mul(H,K),_=n.sub(_,P),B=n.mul(H,F),B=n.add(B,B),B=n.add(B,B),new I(_,E,B)}add(g){R(g);let{X:A,Y:S,Z:x}=this,{X:w,Y:C,Z:_}=g,E=n.ZERO,B=n.ZERO,P=n.ZERO,F=s.a,H=n.mul(s.b,ys),K=n.mul(A,w),Q=n.mul(S,C),tt=n.mul(x,_),et=n.add(A,S),j=n.add(w,C);et=n.mul(et,j),j=n.add(K,Q),et=n.sub(et,j),j=n.add(A,x);let at=n.add(w,_);return j=n.mul(j,at),at=n.add(K,tt),j=n.sub(j,at),at=n.add(S,x),E=n.add(C,_),at=n.mul(at,E),E=n.add(Q,tt),at=n.sub(at,E),P=n.mul(F,j),E=n.mul(H,tt),P=n.add(E,P),E=n.sub(Q,P),P=n.add(Q,P),B=n.mul(E,P),Q=n.add(K,K),Q=n.add(Q,K),tt=n.mul(F,tt),j=n.mul(H,j),Q=n.add(Q,tt),tt=n.sub(K,tt),tt=n.mul(F,tt),j=n.add(j,tt),K=n.mul(Q,j),B=n.add(B,K),K=n.mul(at,j),E=n.mul(et,E),E=n.sub(E,K),K=n.mul(et,Q),P=n.mul(at,P),P=n.add(P,K),new I(E,B,P)}subtract(g){return R(g),this.add(g.negate())}is0(){return this.equals(I.ZERO)}multiply(g){let{endo:A}=t;if(!o.isValidNot0(g))throw new RangeError("invalid scalar: out of range");let S,x,w=C=>k.cached(this,C,_=>mr(I,_));if(A){let{k1neg:C,k1:_,k2neg:E,k2:B}=O(g),{p:P,f:F}=w(_),{p:H,f:K}=w(B);x=F.add(K),S=T(A.beta,P,H,C,E)}else{let{p:C,f:_}=w(g);S=C,x=_}return mr(I,[S,x])[0]}multiplyUnsafe(g){let{endo:A}=t,S=this,x=g;if(!o.isValid(x))throw new RangeError("invalid scalar: out of range");if(x===fe||S.is0())return I.ZERO;if(x===We)return S;if(k.hasCache(this))return this.multiply(x);if(A){let{k1neg:w,k1:C,k2neg:_,k2:E}=O(x),{p1:B,p2:P}=sh(I,S,C,E);return T(A.beta,B,P,w,_)}else return k.unsafe(S,x)}toAffine(g){let A=this,S=g,{X:x,Y:w,Z:C}=A;if(n.eql(C,n.ONE))return{x,y:w};let _=A.is0();S==null&&(S=_?n.ONE:n.inv(C));let E=n.mul(x,S),B=n.mul(w,S),P=n.mul(C,S);if(_)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:E,y:B}}isTorsionFree(){let{isTorsionFree:g}=t;return i===We?!0:g?g(I,this):k.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:g}=t;return i===We?this:g?g(I,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===We?this.is0():this.clearCofactor().is0()}toBytes(g=!0){return Zt(g,"isCompressed"),this.assertValidity(),m(I,this,g)}toHex(g=!0){return Kr(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let U=o.BITS,k=new qr(I,t.endo?Math.ceil(U/2):U);return U>=8&&I.BASE.precompute(8),Object.freeze(I.prototype),Object.freeze(I),I}function kh(r){return Uint8Array.of(r?2:3)}function Mh(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function D0(r,t={}){let{Fn:e}=r,n=t.randomBytes===void 0?hr:t.randomBytes,o=Object.assign(Mh(r.Fp,e),{seed:Math.max(ha(e.ORDER),16)});function s(d){try{let m=e.fromBytes(d);return e.isValidNot0(m)}catch{return!1}}function i(d,m){let{publicKey:b,publicKeyUncompressed:l}=o;try{let y=d.length;return m===!0&&y!==b||m===!1&&y!==l?!1:!!r.fromBytes(d)}catch{return!1}}function a(d){return d=d===void 0?n(o.seed):d,la(V(d,o.seed,"seed"),e.ORDER)}function c(d,m=!0){return r.BASE.multiply(e.fromBytes(d)).toBytes(m)}function f(d){let{secretKey:m,publicKey:b,publicKeyUncompressed:l}=o,y=e._lengths;if(!ur(d))return;let v=V(d,void 0,"key").length,L=v===b||v===l,D=v===m||!!y?.includes(v);if(!(L&&D))return L}function u(d,m,b=!0){if(f(d)===!0)throw new Error("first arg must be private key");if(f(m)===!1)throw new Error("second arg must be public key");let l=e.fromBytes(d);return r.fromBytes(m).multiply(l).toBytes(b)}let h={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},p=jr(a,c);return Object.freeze(h),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:p,Point:r,utils:h,lengths:o})}function Kh(r,t,e={}){let n=t;ar(n),Ht(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),e=Object.assign({},e);let o=e.randomBytes===void 0?hr:e.randomBytes,s=e.hmac===void 0?(x,w)=>Qn(n,x,w):e.hmac,{Fp:i,Fn:a}=r,{ORDER:c,BITS:f}=a,{keygen:u,getPublicKey:h,getSharedSecret:p,utils:d,lengths:m}=D0(r,e),b={prehash:!0,lowS:typeof e.lowS=="boolean"?e.lowS:!0,format:"compact",extraEntropy:!1},l=c*Nh+We<i.ORDER;function y(x){let w=c>>We;return x>w}function v(x,w){if(!a.isValidNot0(w))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return w}function L(){if(l)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function D(x,w){Qa(w);let C=m.signature,_=w==="compact"?C:w==="recovered"?C+1:void 0;return V(x,_)}class R{r;s;recovery;constructor(w,C,_){if(this.r=v("r",w),this.s=v("s",C),_!=null){if(L(),![0,1,2,3].includes(_))throw new Error("invalid recovery id");this.recovery=_}Object.freeze(this)}static fromBytes(w,C=b.format){D(w,C);let _;if(C==="der"){let{r:F,s:H}=te.toSig(V(w));return new R(F,H)}C==="recovered"&&(_=w[0],C="compact",w=w.subarray(1));let E=m.signature/2,B=w.subarray(0,E),P=w.subarray(E,E*2);return new R(a.fromBytes(B),a.fromBytes(P),_)}static fromHex(w,C){return this.fromBytes(Hr(w),C)}assertRecovery(){let{recovery:w}=this;if(w==null)throw new Error("invalid recovery id: must be present");return w}addRecoveryBit(w){return new R(this.r,this.s,w)}recoverPublicKey(w){let{r:C,s:_}=this,E=this.assertRecovery(),B=E===2||E===3?C+c:C;if(!i.isValid(B))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let P=i.toBytes(B),F=r.fromBytes(mt(kh((E&1)===0),P)),H=a.inv(B),K=T(V(w,void 0,"msgHash")),Q=a.create(-K*H),tt=a.create(_*H),et=r.BASE.multiplyUnsafe(Q).add(F.multiplyUnsafe(tt));if(et.is0())throw new Error("invalid recovery: point at infinify");return et.assertValidity(),et}hasHighS(){return y(this.s)}toBytes(w=b.format){if(Qa(w),w==="der")return Hr(te.hexFromSig(this));let{r:C,s:_}=this,E=a.toBytes(C),B=a.toBytes(_);return w==="recovered"?(L(),mt(Uint8Array.of(this.assertRecovery()),E,B)):mt(E,B)}toHex(w){return Kr(this.toBytes(w))}}Object.freeze(R.prototype),Object.freeze(R);let O=e.bits2int===void 0?function(w){if(w.length>8192)throw new Error("input is too large");let C=lr(w),_=w.length*8-f;return _>0?C>>BigInt(_):C}:e.bits2int,T=e.bits2int_modN===void 0?function(w){return a.create(O(w))}:e.bits2int_modN,I=Kn(f);function U(x){return xe("num < 2^"+f,x,fe,I),a.toBytes(x)}function k(x,w){return V(x,void 0,"message"),w?V(n(x),void 0,"prehashed message"):x}function N(x,w,C){let{lowS:_,prehash:E,extraEntropy:B}=Ja(C,b);x=k(x,E);let P=T(x),F=a.fromBytes(w);if(!a.isValidNot0(F))throw new Error("invalid private key");let H=[U(F),U(P)];if(B!=null&&B!==!1){let et=B===!0?o(m.secretKey):B;H.push(V(et,void 0,"extraEntropy"))}let K=mt(...H),Q=P;function tt(et){let j=O(et);if(!a.isValidNot0(j))return;let at=a.inv(j),pe=r.BASE.multiply(j).toAffine(),rr=a.create(pe.x);if(rr===fe)return;let Br=a.create(at*a.create(Q+rr*F));if(Br===fe)return;let vn=(pe.x===rr?0:2)|Number(pe.y&We),Cn=Br;return _&&y(Br)&&(Cn=a.neg(Br),vn^=1),new R(rr,Cn,l?void 0:vn)}return{seed:K,k2sig:tt}}function g(x,w,C={}){let{seed:_,k2sig:E}=N(x,w,C);return Vu(n.outputLen,a.BYTES,s)(_,E).toBytes(C.format)}function A(x,w,C,_={}){let{lowS:E,prehash:B,format:P}=Ja(_,b);if(C=V(C,void 0,"publicKey"),w=k(w,B),!ur(x)){let F=x instanceof R?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+F)}D(x,P);try{let F=R.fromBytes(x,P),H=r.fromBytes(C);if(E&&F.hasHighS())return!1;let{r:K,s:Q}=F,tt=T(w),et=a.inv(Q),j=a.create(tt*et),at=a.create(K*et),pe=r.BASE.multiplyUnsafe(j).add(H.multiplyUnsafe(at));return pe.is0()?!1:a.create(pe.x)===K}catch{return!1}}function S(x,w,C={}){let{prehash:_}=Ja(C,b);return w=k(w,_),R.fromBytes(x,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:u,getPublicKey:h,getSharedSecret:p,utils:d,lengths:m,Point:r,sign:g,verify:A,recoverPublicKey:S,Signature:R,hash:n})}var rc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},R0={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Hh=BigInt(2);function O0(r){let t=rc.p,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=r*r*r%t,u=f*f*r%t,h=st(u,e,t)*u%t,p=st(h,e,t)*u%t,d=st(p,Hh,t)*f%t,m=st(d,o,t)*d%t,b=st(m,s,t)*m%t,l=st(b,a,t)*b%t,y=st(l,c,t)*l%t,v=st(y,a,t)*b%t,L=st(v,e,t)*u%t,D=st(L,i,t)*m%t,R=st(D,n,t)*f%t,O=st(R,Hh,t);if(!ec.eql(ec.sqr(O),r))throw new Error("Cannot find square root");return O}var ec=zr(rc.p,{sqrt:O0}),P0=Fh(rc,{Fp:ec,endo:R0}),Yr=Kh(P0,ae);function Vh(r,t,e,n){let o=ge.digest(e instanceof Uint8Array?e:e.subarray());if(fs(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Yr.verify(t,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new jn(String(s))});try{return n?.signal?.throwIfAborted(),Yr.verify(t,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new jn(String(s))}}var bs=class{type="secp256k1";raw;_key;constructor(t){this._key=$h(t),this.raw=zh(this._key)}toMultihash(){return Wt.digest(Pe(this))}toCID(){return pt.createV1(114,this.toMultihash())}toString(){return ht.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e,n){return Vh(this._key,e,t,n)}};function nc(r){return new bs(r)}function zh(r){return Yr.Point.fromBytes(r).toBytes()}function $h(r){try{return Yr.Point.fromBytes(r),r}catch(t){throw new Tr(String(t))}}function to(r,t){let{Type:e,Data:n}=ce.decode(r),o=n??new Uint8Array;switch(e){case ft.RSA:return Xa(o,t);case ft.Ed25519:return Ca(o);case ft.secp256k1:return nc(o);case ft.ECDSA:return Xi(o);default:throw new nr}}function qh(r){let{Type:t,Data:e}=ce.decode(r.digest),n=e??new Uint8Array;switch(t){case ft.Ed25519:return Ca(n);case ft.secp256k1:return nc(n);case ft.ECDSA:return Xi(n);default:throw new nr}}function Pe(r){return ce.encode({Type:ft[r.type],Data:r.raw})}var jh=Symbol.for("nodejs.util.inspect.custom"),U0=114,eo=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[xi]=!0;toString(){return this.string==null&&(this.string=ht.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return pt.createV1(U0,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Et(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Et(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[jh](){return`PeerId(${this.toString()})`}},ro=class extends eo{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},no=class extends eo{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},oo=class extends eo{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},N0=2336,so=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Wt.digest(Y(this.url))}[jh](){return`PeerId(${this.url})`}[xi]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return pt.createV1(N0,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=G(t)),t.toString()===this.toString())}};var F0=114,Gh=2336;function Zr(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Fr(ht.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return k0(pt.parse(r));if(t==null)throw new $('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Fr(t.decode(r))}return Wh(e)}function oc(r){if(r.type==="Ed25519")return new no({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new oo({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new ro({multihash:r.toCID().multihash,publicKey:r});throw new nr}function Wh(r){if(K0(r))return new ro({multihash:r});if(M0(r))try{let t=qh(r);if(t.type==="Ed25519")return new no({multihash:r,publicKey:t});if(t.type==="secp256k1")return new oo({multihash:r,publicKey:t})}catch{let e=G(r.digest);return new so(new URL(e))}throw new Fo("Supplied PeerID Multihash is invalid")}function k0(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==F0&&r.code!==Gh)throw new No("Supplied PeerID CID is invalid");if(r.code===Gh){let t=G(r.multihash.digest);return new so(new URL(t))}return Wh(r.multihash)}function M0(r){return r.code===Wt.code}function K0(r){return r.code===ge.code}var Ct=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},ve=class extends Error{static name="ValidationError";name="ValidationError"},ws=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},xs=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Es=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",f=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let h=this.readChar();if(h===void 0)return;let p=Number.parseInt(h,t);if(!Number.isNaN(p))return p});if(u===void 0)break;if(s*=t,s+=u,s>f||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var H0=45,V0=15,Ss=new Es;function Xh(r){if(!(r.length>V0))return Ss.new(r).parseWith(()=>Ss.readIPv4Addr())}function Yh(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>H0))return Ss.new(r).parseWith(()=>Ss.readIPv6Addr())}function As(r){return!!Xh(r)}function Zh(r){return!!Yh(r)}function ic(r){return t=>G(t,r)}function ac(r){return t=>Y(t,r)}function Jr(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function xr(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function Jh(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=Y(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=xr(n);return Mt([e,o],e.length+o.length)}function Qh(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=Re.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=xr(n);return Mt([e,o],e.length+o.length)}function cc(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=G(t,"base32"),o=Jr(e);return`${n}:${o}`}var fc=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let o=parseInt(e,10);if(isNaN(o)||o<0||o>255)throw new Ct("Invalid byte value in IP address");t[n]=o}),t},tl=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=As(e[n]),i;s&&(i=fc(e[n]),e[n]=G(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,G(i.subarray(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let s=parseInt(e[n],16);if(isNaN(s)||s<0||s>65535)throw new Ct("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},el=function(r){if(r.byteLength!==4)throw new Ct("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},rl=function(r){if(r.byteLength!==16)throw new Ct("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}let e=t.join(":");try{let n=new URL(`http://[${e}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Ct(`Invalid IPv6 address "${e}"`)}};function nl(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new Ct(`Invalid IPv6 address "${r}"`)}}var sc=Object.values(ir).map(r=>r.decoder),z0=(function(){let r=sc[0].or(sc[1]);return sc.slice(2).forEach(t=>r=r.or(t)),r})();function ol(r){return z0.decode(r)}function sl(r){return t=>r.encoder.encode(t)}function $0(r){if(parseInt(r).toString()!==r)throw new ve("Value must be an integer")}function q0(r){if(r<0)throw new ve("Value must be a positive integer, or zero")}function j0(r){return t=>{if(t>r)throw new ve(`Value must be smaller than or equal to ${r}`)}}function G0(...r){return t=>{for(let e of r)e(t)}}var io=G0($0,q0,j0(65535));var xt=-1,uc=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new xs(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){let e=this.protocolsByCode.get(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},Le=new uc,ag=[{code:4,name:"ip4",size:32,valueToBytes:fc,bytesToValue:el,validate:r=>{if(!As(r))throw new ve(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:xr,bytesToValue:Jr,validate:io},{code:273,name:"udp",size:16,valueToBytes:xr,bytesToValue:Jr,validate:io},{code:33,name:"dccp",size:16,valueToBytes:xr,bytesToValue:Jr,validate:io},{code:41,name:"ip6",size:128,valueToBytes:tl,bytesToValue:rl,stringToValue:nl,validate:r=>{if(!Zh(r))throw new ve(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:xt},{code:43,name:"ipcidr",size:8,bytesToValue:ic("base10"),valueToBytes:ac("base10")},{code:53,name:"dns",size:xt},{code:54,name:"dns4",size:xt},{code:55,name:"dns6",size:xt},{code:56,name:"dnsaddr",size:xt},{code:132,name:"sctp",size:16,valueToBytes:xr,bytesToValue:Jr,validate:io},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:xt,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:xt,bytesToValue:ic("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?ac("base58btc")(r):pt.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:cc,valueToBytes:Jh},{code:445,name:"onion3",size:296,bytesToValue:cc,valueToBytes:Qh},{code:446,name:"garlic64",size:xt},{code:447,name:"garlic32",size:xt},{code:448,name:"tls"},{code:449,name:"sni",size:xt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:xt,bytesToValue:sl(Dn),valueToBytes:ol},{code:480,name:"http"},{code:481,name:"http-path",size:xt,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.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:xt}];ag.forEach(r=>{Le.addProtocol(r)});function il(r){let t=[],e=0;for(;e<r.length;){let n=Ae(r,e),o=Le.getProtocol(n),s=it(n),i=cg(o,r,e+s),a=0;i>0&&o.size===xt&&(a=it(i));let c=s+a+i,f={code:n,name:o.name,bytes:St(r.subarray(e,e+c))};if(i>0){let u=e+s+a,h=r.subarray(u,u+i);f.value=o.bytesToValue?.(h)??G(h)}t.push(f),e+=c}return t}function al(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=Le.getProtocol(n.code),s=it(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Y(n.value),a=i.byteLength,o.size===xt&&(c=it(a)));let f=new Uint8Array(s+c+a),u=0;Wr(n.code,f,u),u+=s,i!=null&&(o.size===xt&&(Wr(a,f,u),u+=c),f.set(i,u)),n.bytes=f}e.push(n.bytes),t+=n.bytes.byteLength}return Mt(e,t)}function cl(r){if(r.charAt(0)!=="/")throw new Ct('String multiaddr must start with "/"');let t=[],e="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(e==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Le.getProtocol(o);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",e="protocol";continue}else if(a)throw new Ct(`Component ${o} was missing value`);e="value"}else if(e==="value"){let f={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Ct(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}t.push(f),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new Ct("Incomplete multiaddr");return t}function fl(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=Le.getProtocol(t.code);if(e==null)throw new Ct(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function cg(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:Ae(t,e)}var fg=Symbol.for("nodejs.util.inspect.custom"),_c=Symbol.for("@multiformats/multiaddr");function ug(r){if(r==null&&(r="/"),ul(r))return r.getComponents();if(r instanceof Uint8Array)return il(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),cl(r);if(Array.isArray(r))return r;throw new Ct("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Is=class r{[_c]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=ug(t),e.validate!==!1&&hg(this)}get bytes(){return this.#r==null&&(this.#r=al(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=fl(this.#t)),this.#e}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new ws(`Address ${this.toString()} does not contain subaddress: ${e}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}equals(t){return Et(this.bytes,t.bytes)}[fg](){return`Multiaddr(${this.toString()})`}};function hg(r){r.getComponents().forEach(t=>{let e=Le.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}function ul(r){return!!r?.[_c]}function rn(r){return new Is(r)}var nt=r=>({match:t=>{let e=t[0];return e==null||e.code!==r||e.value!=null?!1:t.slice(1)}}),M=(r,t)=>({match:e=>{let n=e[0];return n?.code!==r||n.value==null||t!=null&&n.value!==t?!1:e.slice(1)}}),hl=r=>({match:t=>r.match(t)===!1?t:!1}),z=r=>({match:t=>{let e=r.match(t);return e===!1?t:e}}),Dt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1}}),W=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t}});function ot(...r){function t(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:r,matches:e,exactMatch:n}}var lg=M(421),u6=ot(lg),Ts=M(54),Ds=M(55),Rs=M(56),Bc=M(53),h6=ot(Ts,z(M(421))),l6=ot(Ds,z(M(421))),d6=ot(Rs,z(M(421))),p6=ot(Dt(Bc,Rs,Ts,Ds),z(M(421))),ll=W(M(4),z(M(43))),dl=W(z(M(42)),M(41),z(M(43))),Tc=Dt(ll,dl),nn=Dt(Tc,Bc,Ts,Ds,Rs),m6=ot(Dt(Tc,W(Dt(Bc,Rs,Ts,Ds),z(M(421))))),g6=ot(ll),y6=ot(dl),b6=ot(Tc),Dc=W(nn,M(6)),ao=W(nn,M(273)),w6=ot(W(Dc,z(M(421)))),x6=ot(ao),Rc=W(ao,nt(460),z(M(421))),Os=W(ao,nt(461),z(M(421))),dg=Dt(Rc,Os),E6=ot(Rc),S6=ot(Os),Ic=Dt(nn,Dc,ao,Rc,Os),pl=Dt(W(Ic,nt(477),z(M(421)))),A6=ot(pl),ml=Dt(W(Ic,nt(478),z(M(421))),W(Ic,nt(448),z(M(449)),nt(477),z(M(421)))),v6=ot(ml),gl=W(ao,nt(280),z(M(466)),z(M(466)),z(M(421))),yl=ot(gl),bl=W(Os,nt(465),z(M(466)),z(M(466)),z(M(421))),C6=ot(bl),Bs=Dt(pl,ml,W(Dc,z(M(421))),W(dg,z(M(421))),W(nn,z(M(421))),gl,bl,M(421)),wl=ot(Bs),pg=W(z(Bs),nt(290),hl(nt(281)),z(M(421))),L6=ot(pg),mg=Dt(W(Bs,nt(290),nt(281),z(M(421))),W(Bs,nt(281),z(M(421))),W(nt(281),z(M(421)))),xl=ot(mg),gg=W(nn,Dt(W(M(6,"80")),W(M(6),nt(480)),nt(480)),z(M(481)),z(M(421))),_6=ot(gg),yg=W(nn,Dt(W(M(6,"443")),W(M(6,"443"),nt(480)),W(M(6),nt(443)),W(M(6),nt(448),nt(480)),W(nt(448),nt(480)),nt(448),nt(443)),z(M(481)),z(M(421))),I6=ot(yg),bg=Dt(W(M(777),z(M(421)))),B6=ot(bg),wg=Dt(W(M(400),z(M(421)))),T6=ot(wg);var Rt;(function(r){let t;(function(a){a.FIN="FIN",a.STOP_SENDING="STOP_SENDING",a.RESET="RESET",a.FIN_ACK="FIN_ACK"})(t=r.Flag||(r.Flag={}));let e;(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"})(e||(e={})),(function(a){a.codec=()=>wr(e)})(t=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=Ge((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.flag!=null&&(c.uint32(8),r.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 u={},h=c==null?a.len:a.pos+c;for(;a.pos<h;){let p=a.uint32();switch(p>>>3){case 1:{u.flag=r.Flag.codec().decode(a);break}case 2:{u.message=a.bytes();break}default:{a.skipType(p&7);break}}}return u},function*(a,c,f,u={}){let h=c==null?a.len:a.pos+c;for(;a.pos<h;){let p=a.uint32();switch(p>>>3){case 1:{yield{field:`${f}.flag`,value:r.Flag.codec().decode(a)};break}case 2:{yield{field:`${f}.message`,value:a.bytes()};break}default:{a.skipType(p&7);break}}}})),n);function o(a){return qe(a,r.codec())}r.encode=o;function s(a,c){return $e(a,r.codec(),c)}r.decode=s;function i(a,c){return je(a,r.codec(),c)}r.stream=i})(Rt||(Rt={}));var El=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],Oc=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Sl="libp2p+webrtc+v1/",Al=2*1024*1024,on=16*1024;function xg(r=on){let t=it(r-it(r)),e=1+it(Object.keys(Rt.Flag).length-1),n=1,o=r-t-e-n,s=it(o);return t+e+n+s}var vl=xg();var Cl=1e4,Pc="/webrtc",co="/webrtc-signaling/0.0.1";function Eg(r){let t=r.getComponents(),e={},n=0;return t[n]?.name==="ip6zone"&&(e.zone=`${t[n].value}`,n++),t[n]?.name==="ip4"||t[n]?.name==="ip6"||t[n]?.name==="dns"||t[n]?.name==="dns4"||t[n]?.name==="dns6"?(e.type=t[n].name,e.host=t[n].value,n++):t[n]?.name==="dnsaddr"&&(e.type=t[n].name,e.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(e.protocol=t[n].name==="tcp"?"tcp":"udp",e.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(e.type==="ip4"?e.cidr=parseInt(`${t[n].value}`):e.type==="ip6"&&(e.cidr=`${t[n].value}`),n++),e.type==null||e.host==null?null:(t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(e.sni=t[n+1].value,n+=2),e)}function Uc(r){let t=Eg(r);if(t==null)throw new $(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t}function Ps(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Us=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},sn=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Us(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new Us(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Nc=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function an(r={}){return Sg(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Sg(r,t){t=t??{};let e=t.onEnd,n=new sn,o,s,i,a=Ps(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((l,y)=>{s=v=>{s=null,n.push(v);try{l(r(n))}catch(L){y(L)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ps()})}},f=l=>s!=null?s(l):(n.push(l),o),u=l=>(n=new sn,s!=null?s({error:l}):(n.push({error:l}),o)),h=l=>{if(i)return o;if(t?.objectMode!==!0&&l?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:l})},p=l=>i?o:(i=!0,l!=null?u(l):f({done:!0})),d=()=>(n=new sn,p(),{done:!0}),m=l=>(p(l),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:m,push:h,end:p,get readableLength(){return n.size},onEmpty:async l=>{let y=l?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let v,L;y!=null&&(v=new Promise((D,R)=>{L=()=>{R(new Nc)},y.addEventListener("abort",L)}));try{await Promise.race([a.promise,v])}finally{L!=null&&y!=null&&y?.removeEventListener("abort",L)}}},e==null)return o;let b=o;return o={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(l){return b.throw(l),e!=null&&(e(l),e=void 0),{done:!0}},return(){return b.return(),e!=null&&(e(),e=void 0),{done:!0}},push:h,end(l){return b.end(l),e!=null&&(e(l),e=void 0),o},get readableLength(){return b.readableLength},onEmpty:l=>b.onEmpty(l)},o}var Fc=class r extends Error{name="TimeoutError";constructor(t,e){super(t,e),Error.captureStackTrace?.(this,r)}},Ll=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function kc(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=t,a,c,u=new Promise((h,p)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(i?.aborted){p(Ll(i));return}if(i&&(c=()=>{p(Ll(i))},i.addEventListener("abort",c,{once:!0})),r.then(h,p),e===Number.POSITIVE_INFINITY)return;let d=new Fc;a=s.setTimeout.call(void 0,()=>{if(n){try{h(n())}catch(m){p(m)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?h():o instanceof Error?p(o):(d.message=o??`Promise timed out after ${e} milliseconds`,p(d))},e)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var Ag=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function vg(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:f,removeListener:u}=Ag(r),h=async(...d)=>{let m=e.multiArgs?d:d[0];if(e.filter)try{if(!await e.filter(m))return}catch(b){n(),i(b);return}c.push(m),e.count===c.length&&(n(),s(c))},p=(...d)=>{n(),i(e.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)u(d,h);for(let d of e.rejectionEvents)a.includes(d)||u(d,p)};for(let d of a)f(d,h);for(let d of e.rejectionEvents)a.includes(d)||f(d,p);e.signal&&e.signal.addEventListener("abort",()=>{p(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=kc(o,{milliseconds:e.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Lt(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=vg(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var Sr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},Ns=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},Fs=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Cg(r){return r.reason}async function _e(r,t,e){if(t==null)return r;let n=e?.translateError??Cg;if(t.aborted)return r.catch(()=>{}),Promise.reject(n(t));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(t))},t.addEventListener("abort",o)})])}finally{o!=null&&t.removeEventListener("abort",o)}}var Lg=Math.pow(2,20)*4,Ye=class extends Te{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(t){super(),this.status="open",this.log=t.log,this.direction=t.direction??"outbound",this.inactivityTimeout=t.inactivityTimeout??12e4,this.maxReadBufferLength=t.maxReadBufferLength??Lg,this.maxWriteBufferLength=t.maxWriteBufferLength,this.maxMessageSize=t.maxMessageSize,this.readBuffer=new X,this.writeBuffer=new X,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 e=()=>{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",e);let n=o=>{this.onDrainPromise?.reject(o.error??new Fs)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(t){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),_e(this.onDrainPromise.promise,t?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let t=an(),e=s=>{t.push(s.data)};this.addEventListener("message",e);let n=s=>{t.end(s.error)};this.addEventListener("close",n);let o=()=>{t.end()};this.addEventListener("remoteCloseWrite",o);try{yield*t}finally{this.removeEventListener("message",e),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(t){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new ne(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",t.byteLength),this.writeBuffer.append(t),this.processSendQueue()}abort(t){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",t),this.status="aborted",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();try{this.sendReset(t)}catch(e){this.log("failed to send reset to remote - %e",e)}this.dispatchEvent(new Ko(t))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ne("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 ne("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ne(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.append(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(t){if(this.readStatus==="closed"||this.readStatus==="closing")throw new ne(`Cannot push data onto a stream that is ${this.readStatus}`);if(t.byteLength!==0){if(this.readBuffer.prepend(t),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(t){if(t.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(t),this.dispatchReadBuffer()}}addEventListener(...t){super.addEventListener.apply(this,t),t[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let t=new Dr;this.dispatchEvent(new Ho(t))}onTransportClosed(t){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"),t!=null?this.abort(t):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new Rr))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),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 t=!0,e=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){t=!1;break}let s=this.writeBuffer.sublist(0,o),i=new X(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(t=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!t)break}return t||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,e,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),t}finally{this.sendingData=!1}}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 t=this.readBuffer.sublist();this.readBuffer.consume(t.byteLength),this.dispatchEvent(new Mo(t))}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.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Ln(`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 Ln(`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 ks=class extends Ye{remoteAddr;metricPrefix;metrics;constructor(t){super(t),this.metricPrefix=t.metricPrefix??"",this.metrics=t.metrics,this.remoteAddr=t.remoteAddr,this.addEventListener("close",e=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),e.error!=null?e.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):e.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(t){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 Lt(this,"idle",{...t,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 Lt(this,"drain",{...t,rejectionEvents:["close"]})),await this.sendClose(t),this.onTransportClosed())}};function _l(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ms=class extends Te{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(t,e){super(),this.maConn=t,this.protocol=e.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=t.log.newScope(e.name),this.streamOptions=e.streamOptions,this.maxEarlyStreams=e.maxEarlyStreams??10,this.metrics=e.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(t){let e=this.maConn.send(t);return e===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(n=>{n.onMuxerNeedsDrain()})),e}async close(t){this.status==="closed"||this.status==="closing"||(this.status="closing",await _e(Promise.all([...this.streams].map(async e=>{await e.close(t)})),t?.signal),this.status="closed")}abort(t){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(e=>{e.abort(t)}),this.status="closed")}onTransportClosed(t){this.status="closing";try{[...this.streams].forEach(e=>{e.onTransportClosed(t)})}catch(e){this.abort(e)}this.status="closed"}async createStream(t){if(this.status!=="open")throw new Po;let e=this.onCreateStream({...this.streamOptions,...t});return _l(e)&&(e=await e),this.streams.push(e),this.cleanUpStream(e),e}onRemoteStream(t){if(this.streams.push(t),this.cleanUpStream(t),this.listenerCount("stream")===0){this.earlyStreams.push(t),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new Ns(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:t})}cleanUpStream(t){let e=n=>{let o=this.streams.findIndex(s=>s===t);o!==-1&&this.streams.splice(o,1),n.error!=null?n.local?this.metrics?.increment({[`${t.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${t.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${t.direction}_stream_end`]:!0})};t.addEventListener("close",e),this.metrics?.increment({[`${t.direction}_stream`]:!0})}addEventListener(...t){super.addEventListener.apply(this,t),t[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(e=>{this.safeDispatchEvent("stream",{detail:e})}),this.earlyStreams=[]})}};var Ks=class extends Ye{id;protocol;constructor(t){super(t),this.id=t.id,this.protocol=t.protocol??""}async close(t){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 Lt(this,"idle",{...t,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 Lt(this,"drain",{...t,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(t),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(t){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(t),this.readStatus="closed",this.log("closed readable end gracefully"))}};var _g=4194304,Hs=class extends Error{static name="UnwrappedError";name="UnwrappedError"},fo=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Kc=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Hc=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Ig(r){return typeof r?.closeRead=="function"}function Bg(r){return typeof r?.close=="function"}function Mc(r){return Ig(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:Bg(r)?r.status!=="open":!1}function Tg(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Dg(r,t){let e=t?.maxBufferSize??_g,n=new X,o,s=!1;if(!Tg(r))throw new $("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>e){let h=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${h} > ${e}`))}o?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let f={readBuffer:n,async read(u){if(s===!0)throw new Hs("Stream was unwrapped");if(Mc(r)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new Sr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let h=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=h){o.resolve();break}if(await _e(o.promise,u?.signal),Mc(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let p=u?.bytes??n.byteLength;if(n.byteLength<p){if(Mc(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,p),new Sr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${p} bytes`);return f.read(u)}let d=n.sublist(0,p);return n.consume(p),d},async write(u,h){if(s===!0)throw new Hs("Stream was unwrapped");r.send(u)||await Lt(r,"drain",{signal:h?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return f}function Vs(r,t={}){let e=Dg(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=it(t.maxDataLength));let n=t?.lengthDecoder??Ae,o=t?.lengthEncoder??hs;return{async read(i){let a=-1,c=new X;for(;;){let u=await e.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(h){if(h instanceof RangeError)continue;throw h}if(a<0)throw new fo("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Hc(`Message length length too long - ${c.byteLength} > ${t.maxLengthLength}`);if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Kc(`Message length too long - ${a} > ${t.maxDataLength}`);let f=await e.read({...i,bytes:a});if(f==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Sr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(f.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",f.byteLength,a),new Sr(`Unexpected EOF - read ${f.byteLength}/${a} bytes before the stream closed`);return f},async write(i,a){await e.write(new X(o(i.byteLength),i),a)},async writeV(i,a){let c=new X(...i.flatMap(f=>[o(f.byteLength),f]));await e.write(c,a)},unwrap(){return e.unwrap()}}}function zs(r,t){let e=Vs(r,t),n={read:async(o,s)=>{let i=await e.read(s);return o.decode(i)},write:async(o,s,i)=>{await e.write(s.encode(o),i)},writeV:async(o,s,i)=>{await e.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>e.unwrap()};return n}var Rg=1024*1024*4,Og=1024*1024*4,$s=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(t={}){this.buffer=new X,this.maxBufferSize=t.maxBufferSize??Rg,this.maxDataLength=t.maxDataLength??Og,this.lengthDecoder=t.lengthDecoder??Ae,this.encodingLength=t.encodingLength??it}*decode(t){if(this.buffer.append(t),this.buffer.byteLength>this.maxBufferSize)throw new $(`Buffer length limit exceeded - ${this.buffer.byteLength}/${this.maxBufferSize}`);for(;;){let e;try{e=this.lengthDecoder(this.buffer)}catch(s){if(s instanceof RangeError)break;throw s}if(e<0||e>this.maxDataLength)throw new fo("Invalid message length");let n=this.encodingLength(e),o=n+e;if(this.buffer.byteLength>=o){let s=this.buffer.sublist(n,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}};var qs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},cn=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},js=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},uo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Gs(r){return r[Symbol.asyncIterator]!=null}function Il(r,t){if(r.byteLength>t)throw new cn("Message length too long")}var Xs=r=>{let t=it(r),e=bt(t);return hs(r,e),Xs.bytes=t,e};Xs.bytes=0;function ho(r,t){t=t??{};let e=t.lengthEncoder??Xs,n=t?.maxDataLength??4194304;function*o(s){Il(s,n);let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Gs(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}ho.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Xs,n=t?.maxDataLength??4194304;return Il(r,n),new X(e(r.byteLength),r)};var Ar;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Ar||(Ar={}));var Vc=r=>{let t=Ae(r);return Vc.bytes=it(t),t};Vc.bytes=0;function lo(r,t){let e=new X,n=Ar.LENGTH,o=-1,s=t?.lengthDecoder??Vc,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===Ar.LENGTH)try{if(o=s(e),o<0)throw new qs("Invalid message length");if(o>a)throw new cn("Message length too long");let f=s.bytes;e.consume(f),t?.onLength!=null&&t.onLength(o),n=Ar.DATA}catch(f){if(f instanceof RangeError){if(e.byteLength>i)throw new js("Message length length too long");break}throw f}if(n===Ar.DATA){if(e.byteLength<o)break;let f=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(f),yield f,n=Ar.LENGTH}}}return Gs(r)?(async function*(){for await(let f of r)e.append(f),yield*c();if(e.byteLength>0)throw new uo("Unexpected end of input")})():(function*(){for(let f of r)e.append(f),yield*c();if(e.byteLength>0)throw new uo("Unexpected end of input")})()}lo.fromReader=(r,t)=>{let e=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}})();return lo(n,{...t??{},onLength:s=>{e=s}})};var zc=class extends Ks{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(t){super({...t,maxMessageSize:(t.maxMessageSize??on)-vl}),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=an(),this.maxBufferedAmount=t.maxBufferedAmount??Al,this.finAckTimeout=t.finAckTimeout??Cl,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 lo(this.incomingData))this.processIncomingProtobuf(n)}).catch(n=>{this.log.error("error processing incoming data channel messages - %e",n)});let e=()=>{this.channel.readyState==="open"&&(this.log.trace("stream closed, closing underlying datachannel"),this.channel.close())};this.addEventListener("close",e),this.channel.readyState!=="open"&&(this.log('channel ready state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),Lt(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(t){if(this.channel.readyState!=="open")throw new ne(`Invalid datachannel state - ${this.channel.readyState}`);this.log.trace('sending message, channel state "%s"',this.channel.readyState);try{for(let e of t)this.channel.send(St(e))}catch(e){this.log.error("error sending datachannel message - %e",e),this.abort(e)}}sendData(t){return this.channel.readyState!=="open"?{sentBytes:0,canSendMore:!1}:(this._sendMessage(ho.single(Rt.encode({message:t.subarray()}))),{sentBytes:t.byteLength,canSendMore:this.channel.bufferedAmount<this.maxBufferedAmount})}sendReset(t){try{this.log.error("sending reset - %e",t),this._sendFlag(Rt.Flag.RESET),this.receivedFinAck?.reject(t)}catch(e){this.log.error("failed to send reset - %e",e)}}async sendCloseWrite(t){this._sendFlag(Rt.Flag.FIN),t?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let e=t?.signal??AbortSignal.timeout(this.finAckTimeout),n=[Lt(this.channel,"close",{signal:e}),Lt(this.channel,"error",{signal:e})];await Promise.any([_e(this.receivedFinAck.promise,e),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(t){this._sendFlag(Rt.Flag.STOP_SENDING),t?.signal?.throwIfAborted()}processIncomingProtobuf(t){let e=Rt.decode(t);e.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new X(e.message)),e.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',e.flag,this.writeStatus,this.readStatus),e.flag===Rt.Flag.FIN&&(this._sendFlag(Rt.Flag.FIN_ACK),this.onRemoteCloseWrite()),e.flag===Rt.Flag.RESET&&(this.receivedFinAck?.reject(new Dr("The stream was reset")),this.onRemoteReset()),e.flag===Rt.Flag.STOP_SENDING&&this.onRemoteCloseRead(),e.flag===Rt.Flag.FIN_ACK&&this.receivedFinAck?.resolve())}_sendFlag(t){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',t.toString(),this.channel.readyState),!1;this.log.trace("sending flag %s",t.toString());let e=Rt.encode({flag:t}),n=ho.single(e);try{return this._sendMessage(n),!0}catch(o){this.log.error("could not send flag %s - %e",t.toString(),o)}return!1}sendPause(){}sendResume(){}};function po(r){let{channel:t,direction:e,isHandshake:n}=r;return new zc({...r,id:`${t.id}`,log:r.log.newScope(`${n===!0?"handshake":e}:${t.id}`),protocol:""})}var Ze=class{protocol;peerConnection;metrics;dataChannelOptions;earlyDataChannels;constructor(t){this.onEarlyDataChannel=this.onEarlyDataChannel.bind(this),this.peerConnection=t.peerConnection,this.metrics=t.metrics,this.protocol=t.protocol??Pc,this.dataChannelOptions=t.dataChannelOptions??{},this.peerConnection.addEventListener("datachannel",this.onEarlyDataChannel),this.earlyDataChannels=[]}onEarlyDataChannel(t){this.earlyDataChannels.push(t.channel)}createStreamMuxer(t){return this.peerConnection.removeEventListener("datachannel",this.onEarlyDataChannel),new $c(t,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,earlyDataChannels:this.earlyDataChannels})}},$c=class extends Ms{peerConnection;dataChannelOptions;constructor(t,e){super(t,{...e,name:"muxer"}),this.peerConnection=e.peerConnection,this.protocol=e.protocol??Pc,this.dataChannelOptions=e.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{this.onDataChannel(n)},queueMicrotask(()=>{if(this.status!=="open"){e.earlyDataChannels.forEach(n=>{n.close()});return}e.earlyDataChannels.forEach(n=>{this.onDataChannel(n)})})}onDataChannel(t){if(this.log("incoming datachannel with channel id %d, protocol %s and status %s",t.id,t.protocol,t.readyState),t.label==="init"){this.log.trace("closing init channel %d",t.id),t.close();return}let e=po({...this.streamOptions,...this.dataChannelOptions,channel:t,direction:"inbound",log:this.log});this.onRemoteStream(e)}async onCreateStream(t){let e=this.peerConnection.createDataChannel("",{});return this.log("open channel %d for protocol %s",e.id,t?.protocol),po({...t,...this.dataChannelOptions,channel:e,direction:"outbound",log:this.log})}onData(){}};var qc=class extends ks{peerConnection;constructor(t){super(t),this.peerConnection=t.peerConnection;let e=t.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change %s initial state %s",this.peerConnection.connectionState,e),(this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.onTransportClosed(),this.peerConnection.close())}}sendData(t){return{sentBytes:t.byteLength,canSendMore:!0}}async sendClose(t){this.peerConnection.close(),t?.signal?.throwIfAborted()}sendReset(){this.peerConnection.close()}sendPause(){}sendResume(){}},mo=r=>new qc(r);async function jc(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??El.map(t=>({urls:[t]})),r}var Bl=(r=32)=>Sl+[...Array(r)].map(()=>Oc.at(Math.floor(Math.random()*Oc.length))).join("");var Ys=globalThis.RTCPeerConnection,Zs=globalThis.RTCSessionDescription,Tl=globalThis.RTCIceCandidate;var zt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Je=class extends Error{constructor(t){super(`WebRTC transport error: ${t}`),this.name="WebRTCTransportError"}},jt=class extends Je{constructor(t="SDP handshake failed"){super(t),this.name="SDPHandshakeFailedError"}};var Js=class extends Je{constructor(t,e){super(`Invalid fingerprint "${t}" within ${e}`),this.name="WebRTC/InvalidFingerprintError"}};var Qs=class extends Je{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},ti=class extends Je{constructor(t){super(`unsupported hash algorithm code: ${t} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var kt;(function(r){let t;(function(a){a.SDP_OFFER="SDP_OFFER",a.SDP_ANSWER="SDP_ANSWER",a.ICE_CANDIDATE="ICE_CANDIDATE"})(t=r.Type||(r.Type={}));let e;(function(a){a[a.SDP_OFFER=0]="SDP_OFFER",a[a.SDP_ANSWER=1]="SDP_ANSWER",a[a.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(e||(e={})),(function(a){a.codec=()=>wr(e)})(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Ge((a,c,f={})=>{f.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.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 u={},h=c==null?a.len:a.pos+c;for(;a.pos<h;){let p=a.uint32();switch(p>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{u.data=a.string();break}default:{a.skipType(p&7);break}}}return u},function*(a,c,f,u={}){let h=c==null?a.len:a.pos+c;for(;a.pos<h;){let p=a.uint32();switch(p>>>3){case 1:{yield{field:`${f}.type`,value:r.Type.codec().decode(a)};break}case 2:{yield{field:`${f}.data`,value:a.string()};break}default:{a.skipType(p&7);break}}}})),n);function o(a){return qe(a,r.codec())}r.encode=o;function s(a,c){return $e(a,r.codec(),c)}r.decode=s;function i(a,c){return je(a,r.codec(),c)}r.stream=i})(kt||(kt={}));var ei=async(r,t,e)=>{try{let n=Promise.withResolvers();for(Ng(r,n);;){let o=await Promise.race([n.promise,t.read({signal:e.signal})]);if(o==null){e.signal?.throwIfAborted();break}if(o.type!==kt.Type.ICE_CANDIDATE)throw new ko("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){e.onProgress?.(new zt("webrtc:end-of-ice-candidates")),e.log.trace("end-of-candidates received");continue}let i=new Tl(s);e.log.trace("%s received new ICE candidate %o",e.direction,s);try{e.onProgress?.(new zt("webrtc:add-ice-candidate",i.candidate)),await r.addIceCandidate(i)}catch(a){e.log.error("%s bad candidate received %o - %e",e.direction,s,a)}}}catch(n){if(e.log.error("%s error parsing ICE candidate - %e",e.direction,n),e.signal?.aborted===!0&&r.connectionState!=="connected")throw n}};function Ng(r,t){if(r.connectionState==="connected"){t.resolve();return}r.onconnectionstatechange=e=>{switch(r.connectionState){case"connected":t.resolve();break;case"failed":case"closed":t.reject(new Oo(`RTCPeerConnection connection state became "${r.connectionState}"`));break;default:break}}}function ri(r){let t;for(let e of r.getComponents())e.name==="p2p"&&(t=Zr(e.value??""));if(t==null)throw new Uo("Remote peerId must be present in multiaddr");return t}async function Dl({rtcConfiguration:r,dataChannel:t,signal:e,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:f}){let{circuitAddress:u,targetPeer:h}=Rl(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing circuit address: %a",u);let p=s.getConnections(h),d;p.length===0?(f?.(new zt("webrtc:dial-relay")),d=await i.dial(u,{signal:e,onProgress:f})):(f?.(new zt("webrtc:reuse-relay-connection")),d=p[0]),f?.(new zt("webrtc:open-signaling-stream"));let m=await d.newStream(co,{signal:e,runOnLimitedConnection:!0}),b=zs(m).pb(kt),l=new Ys(r);l.addEventListener("connectionstatechange",()=>{l.connectionState==="closed"&&l.close()});let y=new Ze({peerConnection:l,dataChannelOptions:t});try{let v=l.createDataChannel("init");l.onicecandidate=({candidate:O})=>{if(l.connectionState==="connected"){a.trace("ignore new ice candidate as peer connection is already connected");return}if(O==null||O?.candidate===""){a.trace("initiator detected end of ICE candidates");return}let T=JSON.stringify(O?.toJSON()??null);a.trace("initiator sending ICE candidate %o",O),b.write({type:kt.Type.ICE_CANDIDATE,data:T},{signal:e}).catch(I=>{a.error("error sending ICE candidate - %e",I)})},l.onicecandidateerror=O=>{a.error("initiator ICE candidate error",O)};let L=await l.createOffer().catch(O=>{throw a.error("could not execute createOffer - %e",O),new jt("Failed to set createOffer")});a.trace("initiator send SDP offer %s",L.sdp),f?.(new zt("webrtc:send-sdp-offer")),await b.write({type:kt.Type.SDP_OFFER,data:L.sdp},{signal:e}),await l.setLocalDescription(L).catch(O=>{throw a.error("could not execute setLocalDescription - %e",O),new jt("Failed to set localDescription")}),f?.(new zt("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let D=await b.read({signal:e});if(D.type!==kt.Type.SDP_ANSWER)throw new jt("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",D.data);let R=new Zs({type:"answer",sdp:D.data});return await l.setRemoteDescription(R).catch(O=>{throw a.error("could not execute setRemoteDescription - %e",O),new jt("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),f?.(new zt("webrtc:read-ice-candidates")),await ei(l,b,{direction:"initiator",signal:e,log:a,onProgress:f}),a.trace("initiator connected"),v.readyState!=="open"&&(a.trace("wait for init channel to open"),await Lt(v,"open",{signal:e})),a.trace("closing init channel"),v.close(),a.trace("waiting for init channel to close"),await Lt(v,"close",{signal:e}),f?.(new zt("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await m.close({signal:e}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:l,muxerFactory:y}}catch(v){throw a.error("outgoing signaling error - %e",v),l.close(),m.abort(v),v}finally{l.onicecandidate=null,l.onicecandidateerror=null}}var Ol=ot(wl.matchers[0],nt(290)),ni=class r extends Te{transportManager;shutdownController;events;constructor(t,e){super(),this.transportManager=t.transportManager,this.events=t.events,this.shutdownController=e.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(t){t.detail.getAddrs().filter(n=>Ol.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(t=>!(t instanceof r)).map(t=>t.getAddrs().filter(e=>Ol.exactMatch(e)).map(e=>e.encapsulate("/webrtc"))).flat()}updateAnnounceAddrs(){}async close(){this.events.removeEventListener("transport:listening",this.onTransportListening),this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function Pl(r,t,{peerConnection:e,signal:n,log:o}){o.trace("new inbound signaling stream");let s=zs(r).pb(kt);try{e.onicecandidate=({candidate:h})=>{if(e.connectionState==="connected"){o.trace("ignore new ice candidate as peer connection is already connected");return}if(h==null||h?.candidate===""){o.trace("recipient detected end of ICE candidates");return}let p=JSON.stringify(h?.toJSON()??null);o.trace("recipient sending ICE candidate %s",p),s.write({type:kt.Type.ICE_CANDIDATE,data:p},{signal:n}).catch(d=>{o.error("error sending ICE candidate - %e",d)})},o.trace("recipient read SDP offer");let c=await s.read({signal:n});if(c.type!==kt.Type.SDP_OFFER)throw new jt(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let f=new Zs({type:"offer",sdp:c.data});await e.setRemoteDescription(f).catch(h=>{throw o.error("could not execute setRemoteDescription - %e",h),new jt("Failed to set remoteDescription")});let u=await e.createAnswer().catch(h=>{throw o.error("could not execute createAnswer - %e",h),new jt("Failed to create answer")});o.trace("recipient send SDP answer %s",u.sdp),await s.write({type:kt.Type.SDP_ANSWER,data:u.sdp},{signal:n}),await e.setLocalDescription(u).catch(h=>{throw o.error("could not execute setLocalDescription - %e",h),new jt("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await ei(e,s,{direction:"recipient",signal:n,log:o})}catch(c){if(e.connectionState!=="connected")throw o.error("error while handling signaling stream from peer %a - %e",t.remoteAddr,c),e.close(),c;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",t.remoteAddr,c)}let i=ri(t.remoteAddr),a=rn(`/webrtc/p2p/${i}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:i}}var oi=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,e={}){this.components=t,this.init=e,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[Vo]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Or]=["@libp2p/transport"];[Qf]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(co,(t,e)=>{let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(t,e,n).catch(o=>{this.log.error("failed to handle incoming connect from %p - %e",e.remotePeer,o)}).finally(()=>{n.clear()})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(co),this._started=!1}createListener(t){return new ni(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(xl.exactMatch)}dialFilter(t){return this.listenFilter(t)}async dial(t,e){this.log.trace("dialing address: %a",t);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await Dl({rtcConfiguration:await jc(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:t,dataChannelOptions:this.init.dataChannel,signal:e.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:e.onProgress}),i=mo({peerConnection:o,remoteAddr:n,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:webrtc:connection")}),a=await e.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,remotePeer:ri(t),muxerFactory:s,onProgress:e.onProgress,signal:e.signal});return this._closeOnShutdown(o,i),a}async _onProtocol(t,e,n){let o=new Ys(await jc(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{o.connectionState==="closed"&&o.close()});let s=new Ze({peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i,remotePeer:a}=await Pl(t,e,{peerConnection:o,signal:n,log:this.log});await t.close({signal:n});let c=mo({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),o.close(),t.abort(i),i}}_closeOnShutdown(t,e){let n=()=>{e.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection - %e",o)})};this.shutdownController.signal.addEventListener("abort",n),t.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function Rl(r){let t=r.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(t==null)throw new $("Destination peer id was missing");return{circuitAddress:rn(r.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:Zr(t)}}function gt(r=0){return new Uint8Array(r)}function Ot(r=0){return new Uint8Array(r)}var fn=!!globalThis.process?.env?.DUMP_SESSION_KEYS,Gc=16;function Fg(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function si(r){if(typeof r!="boolean")throw new TypeError(`boolean expected, not ${r}`)}function un(r){if(typeof r!="number")throw new TypeError("number expected, got "+typeof r);if(!Number.isSafeInteger(r)||r<0)throw new RangeError("positive integer expected, got "+r)}function yt(r,t,e=""){let n=Fg(r),o=r?.length,s=t!==void 0;if(!n||s&&o!==t){let i=e&&`"${e}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof r}`,f=i+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(f):new TypeError(f)}return r}function Wc(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function Ul(r,t,e=!1){yt(r,void 0,"output");let n=t.outputLen;if(r.length<n)throw new RangeError("digestInto() expects output buffer of length at least "+n);if(e&&!hn(r))throw new Error("invalid output, must be aligned")}function ue(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function ee(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function kg(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var vr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,Mg=r=>r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255;var Kg=r=>{for(let t=0;t<r.length;t++)r[t]=Mg(r[t]);return r},Ie=vr?r=>r:Kg;function Nl(r,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(r,t)}function Fl(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function kl(r,t,e){let n=t,o=e||(()=>[]),s=(a,c)=>n(c,...o(a)).update(a).digest(),i=n(new Uint8Array(r),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>n(a,...c),s}var Ml=(r,t)=>{function e(n,...o){if(yt(n,void 0,"key"),r.nonceLength!==void 0){let u=o[0];yt(u,r.varSizeNonce?void 0:r.nonceLength,"nonce")}let s=r.tagLength;s&&o[1]!==void 0&&yt(o[1],void 0,"AAD");let i=t(n,...o),a=(u,h)=>{if(h!==void 0){if(u!==2)throw new Error("cipher output not supported");yt(h,void 0,"output")}},c=!1;return{encrypt(u,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,yt(u),a(i.encrypt.length,h),i.encrypt(u,h)},decrypt(u,h){if(yt(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,h),i.decrypt(u,h)}}}return Object.assign(e,r),e};function go(r,t,e=!0){if(t===void 0)return new Uint8Array(r);if(yt(t,void 0,"output"),t.length!==r)throw new Error('"output" expected Uint8Array of length '+r+", got: "+t.length);if(e&&!hn(t))throw new Error("invalid output, must be aligned");return t}function Kl(r,t,e){un(r),un(t),si(e);let n=new Uint8Array(16),o=kg(n);return o.setBigUint64(0,BigInt(t),e),o.setBigUint64(8,BigInt(r),e),n}function hn(r){return r.byteOffset%4===0}function ln(r){return Uint8Array.from(yt(r))}var Vl=r=>Uint8Array.from(r.split(""),t=>t.charCodeAt(0)),Hg=Ie(ue(Vl("expand 16-byte k"))),Vg=Ie(ue(Vl("expand 32-byte k")));function q(r,t){return r<<t|r>>>32-t}var yo=64,zg=16,Xc=2**32-1,Hl=Uint32Array.of();function $g(r,t,e,n,o,s,i,a){let c=o.length,f=new Uint8Array(yo),u=ue(f),h=vr&&hn(o)&&hn(s),p=h?ue(o):Hl,d=h?ue(s):Hl;if(!vr){for(let m=0;m<c;i++){if(r(t,e,n,u,i,a),Ie(u),i>=Xc)throw new Error("arx: counter overflow");let b=Math.min(yo,c-m);for(let l=0,y;l<b;l++)y=m+l,s[y]=o[y]^f[l];m+=b}return}for(let m=0;m<c;i++){if(r(t,e,n,u,i,a),i>=Xc)throw new Error("arx: counter overflow");let b=Math.min(yo,c-m);if(h&&b===yo){let l=m/4;if(m%4!==0)throw new Error("arx: invalid block position");for(let y=0,v;y<zg;y++)v=l+y,d[v]=p[v]^u[y];m+=yo;continue}for(let l=0,y;l<b;l++)y=m+l,s[y]=o[y]^f[l];m+=b}}function zl(r,t){let{allowShortKeys:e,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Nl({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof r!="function")throw new Error("core must be a function");return un(o),un(i),si(s),si(e),(a,c,f,u,h=0)=>{yt(a,void 0,"key"),yt(c,void 0,"nonce"),yt(f,void 0,"data");let p=f.length;if(u=go(p,u,!1),un(h),h<0||h>=Xc)throw new Error("arx: counter overflow");let d=[],m=a.length,b,l;if(m===32)d.push(b=ln(a)),l=Vg;else if(m===16&&e)b=new Uint8Array(32),b.set(a),b.set(a,16),l=Hg,d.push(b);else throw yt(a,32,"arx key"),new Error("invalid key size");(!vr||!hn(c))&&d.push(c=ln(c));let y=ue(b);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let D=c.subarray(0,16);if(vr)n(l,y,ue(D),y);else{let R=Ie(Uint32Array.from(l));n(R,y,ue(D),y),ee(R),Ie(y)}c=c.subarray(16)}else vr||Ie(y);let v=16-o;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let D=new Uint8Array(12);D.set(c,s?0:12-c.length),c=D,d.push(c)}let L=Ie(ue(c));try{return $g(r,l,y,L,f,u,h,i),u}finally{ee(...d)}}}function _t(r,t){return r[t++]&255|(r[t++]&255)<<8}var Yc=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(t){t=ln(yt(t,32,"key"));let e=_t(t,0),n=_t(t,2),o=_t(t,4),s=_t(t,6),i=_t(t,8),a=_t(t,10),c=_t(t,12),f=_t(t,14);this.r[0]=e&8191,this.r[1]=(e>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|f<<8)&8191,this.r[9]=f>>>5&127;for(let u=0;u<8;u++)this.pad[u]=_t(t,16+2*u)}process(t,e,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],f=i[2],u=i[3],h=i[4],p=i[5],d=i[6],m=i[7],b=i[8],l=i[9],y=_t(t,e+0),v=_t(t,e+2),L=_t(t,e+4),D=_t(t,e+6),R=_t(t,e+8),O=_t(t,e+10),T=_t(t,e+12),I=_t(t,e+14),U=s[0]+(y&8191),k=s[1]+((y>>>13|v<<3)&8191),N=s[2]+((v>>>10|L<<6)&8191),g=s[3]+((L>>>7|D<<9)&8191),A=s[4]+((D>>>4|R<<12)&8191),S=s[5]+(R>>>1&8191),x=s[6]+((R>>>14|O<<2)&8191),w=s[7]+((O>>>11|T<<5)&8191),C=s[8]+((T>>>8|I<<8)&8191),_=s[9]+(I>>>5|o),E=0,B=E+U*a+k*(5*l)+N*(5*b)+g*(5*m)+A*(5*d);E=B>>>13,B&=8191,B+=S*(5*p)+x*(5*h)+w*(5*u)+C*(5*f)+_*(5*c),E+=B>>>13,B&=8191;let P=E+U*c+k*a+N*(5*l)+g*(5*b)+A*(5*m);E=P>>>13,P&=8191,P+=S*(5*d)+x*(5*p)+w*(5*h)+C*(5*u)+_*(5*f),E+=P>>>13,P&=8191;let F=E+U*f+k*c+N*a+g*(5*l)+A*(5*b);E=F>>>13,F&=8191,F+=S*(5*m)+x*(5*d)+w*(5*p)+C*(5*h)+_*(5*u),E+=F>>>13,F&=8191;let H=E+U*u+k*f+N*c+g*a+A*(5*l);E=H>>>13,H&=8191,H+=S*(5*b)+x*(5*m)+w*(5*d)+C*(5*p)+_*(5*h),E+=H>>>13,H&=8191;let K=E+U*h+k*u+N*f+g*c+A*a;E=K>>>13,K&=8191,K+=S*(5*l)+x*(5*b)+w*(5*m)+C*(5*d)+_*(5*p),E+=K>>>13,K&=8191;let Q=E+U*p+k*h+N*u+g*f+A*c;E=Q>>>13,Q&=8191,Q+=S*a+x*(5*l)+w*(5*b)+C*(5*m)+_*(5*d),E+=Q>>>13,Q&=8191;let tt=E+U*d+k*p+N*h+g*u+A*f;E=tt>>>13,tt&=8191,tt+=S*c+x*a+w*(5*l)+C*(5*b)+_*(5*m),E+=tt>>>13,tt&=8191;let et=E+U*m+k*d+N*p+g*h+A*u;E=et>>>13,et&=8191,et+=S*f+x*c+w*a+C*(5*l)+_*(5*b),E+=et>>>13,et&=8191;let j=E+U*b+k*m+N*d+g*p+A*h;E=j>>>13,j&=8191,j+=S*u+x*f+w*c+C*a+_*(5*l),E+=j>>>13,j&=8191;let at=E+U*l+k*b+N*m+g*d+A*p;E=at>>>13,at&=8191,at+=S*h+x*u+w*f+C*c+_*a,E+=at>>>13,at&=8191,E=(E<<2)+E|0,E=E+B|0,B=E&8191,E=E>>>13,P+=E,s[0]=B,s[1]=P,s[2]=F,s[3]=H,s[4]=K,s[5]=Q,s[6]=tt,s[7]=et,s[8]=j,s[9]=at}finalize(){let{h:t,pad:e}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+e[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+e[a]|0)+(i>>>16)|0,t[a]=i&65535;ee(n)}update(t){Wc(this),yt(t),t=ln(t);let{buffer:e,blockLen:n}=this,o=t.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(t,s);continue}e.set(t.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(e,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,ee(this.h,this.r,this.buffer,this.pad)}digestInto(t){Wc(this),Ul(t,this),this.finished=!0;let{buffer:e,h:n}=this,{pos:o}=this;if(o){for(e[o++]=1;o<16;o++)e[o]=0;this.process(e,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)t[s++]=n[i]>>>0,t[s++]=n[i]>>>8}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}},$l=kl(32,r=>new Yc(r));function qg(r,t,e,n,o,s=20){let i=r[0],a=r[1],c=r[2],f=r[3],u=t[0],h=t[1],p=t[2],d=t[3],m=t[4],b=t[5],l=t[6],y=t[7],v=o,L=e[0],D=e[1],R=e[2],O=i,T=a,I=c,U=f,k=u,N=h,g=p,A=d,S=m,x=b,w=l,C=y,_=v,E=L,B=D,P=R;for(let H=0;H<s;H+=2)O=O+k|0,_=q(_^O,16),S=S+_|0,k=q(k^S,12),O=O+k|0,_=q(_^O,8),S=S+_|0,k=q(k^S,7),T=T+N|0,E=q(E^T,16),x=x+E|0,N=q(N^x,12),T=T+N|0,E=q(E^T,8),x=x+E|0,N=q(N^x,7),I=I+g|0,B=q(B^I,16),w=w+B|0,g=q(g^w,12),I=I+g|0,B=q(B^I,8),w=w+B|0,g=q(g^w,7),U=U+A|0,P=q(P^U,16),C=C+P|0,A=q(A^C,12),U=U+A|0,P=q(P^U,8),C=C+P|0,A=q(A^C,7),O=O+N|0,P=q(P^O,16),w=w+P|0,N=q(N^w,12),O=O+N|0,P=q(P^O,8),w=w+P|0,N=q(N^w,7),T=T+g|0,_=q(_^T,16),C=C+_|0,g=q(g^C,12),T=T+g|0,_=q(_^T,8),C=C+_|0,g=q(g^C,7),I=I+A|0,E=q(E^I,16),S=S+E|0,A=q(A^S,12),I=I+A|0,E=q(E^I,8),S=S+E|0,A=q(A^S,7),U=U+k|0,B=q(B^U,16),x=x+B|0,k=q(k^x,12),U=U+k|0,B=q(B^U,8),x=x+B|0,k=q(k^x,7);let F=0;n[F++]=i+O|0,n[F++]=a+T|0,n[F++]=c+I|0,n[F++]=f+U|0,n[F++]=u+k|0,n[F++]=h+N|0,n[F++]=p+g|0,n[F++]=d+A|0,n[F++]=m+S|0,n[F++]=b+x|0,n[F++]=l+w|0,n[F++]=y+C|0,n[F++]=v+_|0,n[F++]=L+E|0,n[F++]=D+B|0,n[F++]=R+P|0}var jg=zl(qg,{counterRight:!1,counterLength:4,allowShortKeys:!1});var Gg=new Uint8Array(16),ql=(r,t)=>{r.update(t);let e=t.length%16;e&&r.update(Gg.subarray(e))},Wg=new Uint8Array(32);function jl(r,t,e,n,o){o!==void 0&&yt(o,void 0,"AAD");let s=r(t,e,Wg),i=Kl(n.length,o?o.length:0,!0),a=$l.create(s);o&&ql(a,o),ql(a,n),a.update(i);let c=a.digest();return ee(s,i),c}var Xg=r=>(t,e,n)=>({encrypt(s,i){let a=s.length;i=go(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);r(t,e,c,c,1);let f=jl(r,t,e,c,n);return i.set(f,a),ee(f),i},decrypt(s,i){i=go(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),f=jl(r,t,e,a,n);if(!Fl(c,f))throw ee(f),new Error("invalid tag");return i.set(s.subarray(0,-16)),r(t,e,i,i,1),ee(f),i}}),Zc=Ml({blockSize:64,nonceLength:12,tagLength:16},Xg(jg));function Wl(r,t,e){return ar(r),e===void 0&&(e=new Uint8Array(r.outputLen)),Qn(r,e,t)}var Jc=Uint8Array.of(0),Gl=Uint8Array.of();function Xl(r,t,e,n=32){ar(r),se(n,"length"),It(t,void 0,"prk");let o=r.outputLen;if(t.length<o)throw new Error('"prk" must be at least HashLen octets');if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);e===void 0?e=Gl:It(e,void 0,"info");let i=new Uint8Array(s*o),a=Qn.create(r,t),c=a._cloneInto(),f=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)Jc[0]=u+1,c.update(u===0?Gl:f).update(e).update(Jc).digestInto(f),i.set(f,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),Xt(f,Jc),i.slice(0,n)}var Qc={hashSHA256(r){return ae(r.subarray())},getHKDF(r,t){let e=Wl(ae,t,r),o=Xl(ae,e,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=qn.utils.randomSecretKey();return{publicKey:qn.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:qn.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,t){return qn.getSharedSecret(r.subarray(),t.subarray())},chaCha20Poly1305Encrypt(r,t,e,n){return Zc(n,t,e).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,t,e,n,o){return Zc(n,t,e).decrypt(r.subarray(),o)}};var Yl=Qc;function Zl(r){return{generateKeypair:r.generateX25519KeyPair,dh:(t,e)=>r.generateX25519SharedKey(t.privateKey,e).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var dn=r=>{let t=Ot(2);return t[0]=r>>8,t[1]=r,t};dn.bytes=2;var pn=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let t=0;return t+=r[0]<<8,t+=r[1],t}return r.getUint16(0)};pn.bytes=2;function Jl(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}var of={};rt(of,{base10:()=>ry});var q4=new Uint8Array(0);function Ql(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Be(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function td(r){return new TextEncoder().encode(r)}function ed(r){return new TextDecoder().decode(r)}function Yg(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var b=0,l=0,y=0,v=m.length;y!==v&&m[y]===0;)y++,b++;for(var L=(v-y)*u+1>>>0,D=new Uint8Array(L);y!==v;){for(var R=m[y],O=0,T=L-1;(R!==0||O<l)&&T!==-1;T--,O++)R+=256*D[T]>>>0,D[T]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");l=O,y++}for(var I=L-l;I!==L&&D[I]===0;)I++;for(var U=c.repeat(b);I<L;++I)U+=r.charAt(D[I]);return U}function p(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var b=0;if(m[b]!==" "){for(var l=0,y=0;m[b]===c;)l++,b++;for(var v=(m.length-b)*f+1>>>0,L=new Uint8Array(v);m[b];){var D=e[m.charCodeAt(b)];if(D===255)return;for(var R=0,O=v-1;(D!==0||R<y)&&O!==-1;O--,R++)D+=a*L[O]>>>0,L[O]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");y=R,b++}if(m[b]!==" "){for(var T=v-y;T!==v&&L[T]===0;)T++;for(var I=new Uint8Array(l+(v-T)),U=l;T!==v;)I[U++]=L[T++];return I}}}function d(m){var b=p(m);if(b)return b;throw new Error(`Non-${t} character`)}return{encode:h,decodeUnsafe:p,decode:d}}var Zg=Yg,Jg=Zg,nd=Jg;var tf=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},ef=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return od(this,t)}},rf=class{decoders;constructor(t){this.decoders=t}or(t){return od(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function od(r,t){return new rf({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var nf=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new tf(t,e,n),this.decoder=new ef(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function mn({name:r,prefix:t,encode:e,decode:n}){return new nf(r,t,e,n)}function Qe({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=nd(e,r);return mn({prefix:t,name:r,encode:n,decode:s=>Be(o(s))})}function Qg(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let u=t[r[f]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|u,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function ty(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function ey(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function dt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=ey(n);return mn({prefix:t,name:r,encode(s){return ty(s,n,e)},decode(s){return Qg(s,o,e,r)}})}var ry=Qe({prefix:"9",name:"base10",alphabet:"0123456789"});var sf={};rt(sf,{base16:()=>ny,base16upper:()=>oy});var ny=dt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),oy=dt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var af={};rt(af,{base2:()=>sy});var sy=dt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var cf={};rt(cf,{base256emoji:()=>uy});var sd=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}"),iy=sd.reduce((r,t,e)=>(r[e]=t,r),[]),ay=sd.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function cy(r){return r.reduce((t,e)=>(t+=iy[e],t),"")}function fy(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=ay[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var uy=mn({prefix:"\u{1F680}",name:"base256emoji",encode:cy,decode:fy});var ff={};rt(ff,{base32:()=>gn,base32hex:()=>py,base32hexpad:()=>gy,base32hexpadupper:()=>yy,base32hexupper:()=>my,base32pad:()=>ly,base32padupper:()=>dy,base32upper:()=>hy,base32z:()=>by});var gn=dt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),hy=dt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ly=dt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),dy=dt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),py=dt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),my=dt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),gy=dt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),yy=dt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),by=dt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var uf={};rt(uf,{base36:()=>bo,base36upper:()=>wy});var bo=Qe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),wy=Qe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var hf={};rt(hf,{base58btc:()=>he,base58flickr:()=>xy});var he=Qe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xy=Qe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var lf={};rt(lf,{base64:()=>Ey,base64pad:()=>Sy,base64url:()=>Ay,base64urlpad:()=>vy});var Ey=dt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Sy=dt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ay=dt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),vy=dt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var df={};rt(df,{base8:()=>Cy});var Cy=dt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var pf={};rt(pf,{identity:()=>Ly});var Ly=mn({prefix:"\0",name:"identity",encode:r=>ed(r),decode:r=>td(r)});var av=new TextEncoder,cv=new TextDecoder;var gf={};rt(gf,{identity:()=>Xy});var By=cd,id=128,Ty=127,Dy=~Ty,Ry=Math.pow(2,31);function cd(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Ry;)t[e++]=r&255|id,r/=128;for(;r&Dy;)t[e++]=r&255|id,r>>>=7;return t[e]=r|0,cd.bytes=e-n+1,t}var Oy=mf,Py=128,ad=127;function mf(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw mf.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&ad)<<o:(i&ad)*Math.pow(2,o),o+=7}while(i>=Py);return mf.bytes=s-n,e}var Uy=Math.pow(2,7),Ny=Math.pow(2,14),Fy=Math.pow(2,21),ky=Math.pow(2,28),My=Math.pow(2,35),Ky=Math.pow(2,42),Hy=Math.pow(2,49),Vy=Math.pow(2,56),zy=Math.pow(2,63),$y=function(r){return r<Uy?1:r<Ny?2:r<Fy?3:r<ky?4:r<My?5:r<Ky?6:r<Hy?7:r<Vy?8:r<zy?9:10},qy={encode:By,decode:Oy,encodingLength:$y},jy=qy,wo=jy;function xo(r,t=0){return[wo.decode(r,t),wo.decode.bytes]}function yn(r,t,e=0){return wo.encode(r,t,e),t}function bn(r){return wo.encodingLength(r)}function xn(r,t){let e=t.byteLength,n=bn(r),o=n+bn(e),s=new Uint8Array(o+e);return yn(r,s,0),yn(e,s,n),s.set(t,o),new wn(r,e,t,s)}function fd(r){let t=Be(r),[e,n]=xo(t),[o,s]=xo(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new wn(e,o,i,t)}function ud(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Ql(r.bytes,e.bytes)}}var wn=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};var hd=0,Gy="identity",ld=Be;function Wy(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return xn(hd,ld(r))}var Xy={code:hd,name:Gy,encode:ld,digest:Wy};var wf={};rt(wf,{sha256:()=>Zy,sha512:()=>Jy});var Yy=20;function bf({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new yf(r,t,e,n,o)}var yf=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??Yy,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?dd(n,this.code,e?.truncate):n.then(o=>dd(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function dd(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return xn(t,r)}function md(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Zy=bf({name:"sha2-256",code:18,encode:md("SHA-256")}),Jy=bf({name:"sha2-512",code:19,encode:md("SHA-512")});function gd(r,t){let{bytes:e,version:n}=r;return n===0?tb(e,xf(r),t??he.encoder):eb(e,xf(r),t??gn.encoder)}var yd=new WeakMap;function xf(r){let t=yd.get(r);if(t==null){let e=new Map;return yd.set(r,e),e}return t}var ai=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==So)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==rb)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=xn(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&ud(t.multihash,n.multihash)}toString(t){return gd(this,t)}toJSON(){return{"/":gd(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??bd(n,o,s.bytes))}else if(e[nb]===!0){let{version:n,multihash:o,code:s}=e,i=fd(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==So)throw new Error(`Version 0 CID must use dag-pb (code: ${So}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=bd(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,So,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Be(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new wn(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[h,p]=xo(t.subarray(e));return e+=p,h},o=n(),s=So;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),f=e+c,u=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:f}}static parse(t,e){let[n,o]=Qy(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return xf(s).set(n,t),s}};function Qy(r,t){switch(r[0]){case"Q":{let e=t??he;return[he.prefix,e.decode(`${he.prefix}${r}`)]}case he.prefix:{let e=t??he;return[he.prefix,e.decode(r)]}case gn.prefix:{let e=t??gn;return[gn.prefix,e.decode(r)]}case bo.prefix:{let e=t??bo;return[bo.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function tb(r,t,e){let{prefix:n}=e;if(n!==he.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function eb(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var So=112,rb=18;function bd(r,t,e){let n=bn(r),o=n+bn(t),s=new Uint8Array(o+e.byteLength);return yn(r,s,0),yn(t,s,n),s.set(e,o),s}var nb=Symbol.for("@ipld/js-cid/CID");var Ef={...pf,...af,...df,...of,...sf,...ff,...uf,...hf,...lf,...cf},Tv={...wf,...gf};function xd(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var wd=xd("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Sf=xd("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=Ot(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),ob={utf8:wd,"utf-8":wd,hex:Ef.base16,latin1:Sf,ascii:Sf,binary:Sf,...Ef},ci=ob;function le(r,t="utf8"){let e=ci[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}function Af(r,t){!t.enabled||!fn||(r?(t(`LOCAL_STATIC_PUBLIC_KEY ${le(r.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${le(r.privateKey,"hex")}`)):t("Missing local static keys."))}function vf(r,t){!t.enabled||!fn||(r?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${le(r.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${le(r.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function Ed(r,t){!t.enabled||!fn||t(r?`REMOTE_STATIC_PUBLIC_KEY ${le(r.subarray(),"hex")}`:"Missing remote static public key.")}function Cf(r,t){!t.enabled||!fn||t(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${le(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Lf(r,t,e){!e.enabled||!fn||(e(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&le(r.k,"hex")}`),e(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&le(t.k,"hex")}`))}function En(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=Ot(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}function _f(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}var Ad=Symbol.for("@achingbrain/uint8arraylist");function Sd(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function fi(r){return!!r?.[Ad]}var de=class r{bufs;length;[Ad]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(fi(n)){e+=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+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(fi(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Sd(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Sd(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(fi(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return En(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:En(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=n,s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let f=t>=a&&t<c,u=e>a&&e<=c;if(f&&u){if(t===a&&e===c){n.push(i);break}let h=t-a;n.push(i.subarray(h,h+(e-t)));break}if(f){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!fi(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let h=0;h<s;h++)i[h]=-1;for(let h=0;h<o;h++)i[n[h]]=h;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let h=e;h<=c;h+=u){u=0;for(let p=f;p>=0;p--){let d=this.get(h+p);if(n[p]!==d){u=Math.max(1,p-a[d]);break}}if(u===0)return h}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=Ot(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=gt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=gt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=gt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=Ot(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=gt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=gt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=gt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=gt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=gt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!_f(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};function Cr(r,t="utf8"){let e=ci[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}var Sn=class r extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var ib=0,ab=4294967295,cb="Cipherstate has reached maximum n, a new handshake must be performed",ui=class{n;bytes;view;constructor(t=ib){this.n=t,this.bytes=gt(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>ab)throw new Error(cb)}};var Lr=gt(0),An=class{k;n;crypto;constructor(t,e=void 0,n=0){this.crypto=t,this.k=e,this.n=new ui(n)}hasKey(){return!!this.k}encryptWithAd(t,e){if(!this.hasKey())return e;this.n.assertValue();let n=this.crypto.encrypt(e,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,e,n){if(!this.hasKey())return e;this.n.assertValue();let o=this.crypto.decrypt(e,this.n.getBytes(),t,this.k,n);return this.n.increment(),o}},If=class{cs;ck;h;crypto;constructor(t,e){this.crypto=t;let n=Cr(e,"utf-8");this.h=fb(t,n),this.ck=this.h,this.cs=new An(t)}mixKey(t){let[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new An(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new de(this.h,t))}encryptAndHash(t){let e=this.cs.encryptWithAd(this.h,t);return this.mixHash(e),e}decryptAndHash(t){let e=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),e}split(){let[t,e]=this.crypto.hkdf(this.ck,Lr);return[new An(this.crypto,t),new An(this.crypto,e)]}},Bf=class{ss;s;e;rs;re;initiator;crypto;constructor(t){let{crypto:e,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:f}=t;this.crypto=e,this.ss=new If(e,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 t=this.crypto.generateKeypair();return this.ss.mixHash(t.publicKey),this.e=t,t.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(t,e=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<e+32)throw new Error("message is not long enough");this.re=t.sublist(e,e+32),this.ss.mixHash(this.re)}readS(t,e=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(t.byteLength<e+n)throw new Error("message is not long enough");let o=t.sublist(e,e+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Ao=class extends Bf{writeMessageA(t){return new de(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let e=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new de(e,n,this.ss.encryptAndHash(t))}writeMessageC(t){let e=this.writeS();return this.writeSE(),new de(e,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(e){throw new Sn(`handshake stage 0 validation fail: ${e.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();let e=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+e))}catch(e){throw new Sn(`handshake stage 1 validation fail: ${e.message}`)}}readMessageC(t){try{let e=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(e))}catch(e){throw new Sn(`handshake stage 2 validation fail: ${e.message}`)}}};function fb(r,t){if(t.length<=32){let e=gt(32);return e.set(t),e}else return r.hash(t)}var ub=Math.pow(2,7),hb=Math.pow(2,14),lb=Math.pow(2,21),vd=Math.pow(2,28),Cd=Math.pow(2,35),Ld=Math.pow(2,42),_d=Math.pow(2,49),Nt=128,tr=127;function vo(r){if(r<ub)return 1;if(r<hb)return 2;if(r<lb)return 3;if(r<vd)return 4;if(r<Cd)return 5;if(r<Ld)return 6;if(r<_d)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Id(r,t,e=0){switch(vo(r)){case 8:t[e++]=r&255|Nt,r/=128;case 7:t[e++]=r&255|Nt,r/=128;case 6:t[e++]=r&255|Nt,r/=128;case 5:t[e++]=r&255|Nt,r/=128;case 4:t[e++]=r&255|Nt,r>>>=7;case 3:t[e++]=r&255|Nt,r>>>=7;case 2:t[e++]=r&255|Nt,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Bd(r,t){let e=r[t],n=0;if(n+=e&tr,e<Nt||(e=r[t+1],n+=(e&tr)<<7,e<Nt)||(e=r[t+2],n+=(e&tr)<<14,e<Nt)||(e=r[t+3],n+=(e&tr)<<21,e<Nt)||(e=r[t+4],n+=(e&tr)*vd,e<Nt)||(e=r[t+5],n+=(e&tr)*Cd,e<Nt)||(e=r[t+6],n+=(e&tr)*Ld,e<Nt)||(e=r[t+7],n+=(e&tr)*_d,e<Nt))return n;throw new RangeError("Could not decode varint")}var Tf=new Float32Array([-0]),er=new Uint8Array(Tf.buffer);function Td(r,t,e){Tf[0]=r,t[e]=er[0],t[e+1]=er[1],t[e+2]=er[2],t[e+3]=er[3]}function Dd(r,t){return er[0]=r[t],er[1]=r[t+1],er[2]=r[t+2],er[3]=r[t+3],Tf[0]}var Df=new Float64Array([-0]),Pt=new Uint8Array(Df.buffer);function Rd(r,t,e){Df[0]=r,t[e]=Pt[0],t[e+1]=Pt[1],t[e+2]=Pt[2],t[e+3]=Pt[3],t[e+4]=Pt[4],t[e+5]=Pt[5],t[e+6]=Pt[6],t[e+7]=Pt[7]}function Od(r,t){return Pt[0]=r[t],Pt[1]=r[t+1],Pt[2]=r[t+2],Pt[3]=r[t+3],Pt[4]=r[t+4],Pt[5]=r[t+5],Pt[6]=r[t+6],Pt[7]=r[t+7],Df[0]}var db=BigInt(Number.MAX_SAFE_INTEGER),pb=BigInt(Number.MIN_SAFE_INTEGER),$t=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return _r;if(t<db&&t>pb)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>Pd&&(o=0n,++n>Pd&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return _r;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):_r}},_r=new $t(0,0);_r.toBigInt=function(){return 0n};_r.zzEncode=_r.zzDecode=function(){return this};_r.length=function(){return 1};var Pd=4294967296n;function Ud(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Nd(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Rf(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function re(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function hi(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Of=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,re(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw re(this,4);return hi(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw re(this,4);return hi(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw re(this,4);let t=Dd(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw re(this,4);let t=Od(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw re(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Nd(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw re(this,t);this.pos+=t}else do if(this.pos>=this.len)throw re(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new $t(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw re(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw re(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw re(this,8);let t=hi(this.buf,this.pos+=4),e=hi(this.buf,this.pos+=4);return new $t(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Bd(this.buf,this.pos);return this.pos+=vo(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Pf(r){return new Of(r instanceof Uint8Array?r:r.subarray())}function li(r,t,e){let n=Pf(r);return t.decode(n,void 0,e)}function Uf(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return Ot(i);o+i>t&&(n=Ot(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Ir=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Nf(){}var kf=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},mb=Uf();function gb(r){return globalThis.Buffer!=null?Ot(r):mb(r)}var Lo=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ir(Nf,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Ir(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Mf((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(di,10,$t.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=$t.fromBigInt(t);return this._push(di,e.length(),e)}uint64Number(t){return this._push(Id,vo(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=$t.fromBigInt(t).zzEncode();return this._push(di,e.length(),e)}sint64Number(t){let e=$t.fromNumber(t).zzEncode();return this._push(di,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Ff,1,t?1:0)}fixed32(t){return this._push(Co,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=$t.fromBigInt(t);return this._push(Co,4,e.lo)._push(Co,4,e.hi)}fixed64Number(t){let e=$t.fromNumber(t);return this._push(Co,4,e.lo)._push(Co,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Td,4,t)}double(t){return this._push(Rd,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Ff,1,0):this.uint32(e)._push(bb,e,t)}string(t){let e=Ud(t);return e!==0?this.uint32(e)._push(Rf,e,t):this._push(Ff,1,0)}fork(){return this.states=new kf(this),this.head=this.tail=new Ir(Nf,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 Ir(Nf,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=gb(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Ff(r,t,e){t[e]=r&255}function yb(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Mf=class extends Ir{next;constructor(t,e){super(yb,t,e),this.next=void 0}};function di(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Co(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function bb(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Lo.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(wb,t,r),this},Lo.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(xb,t,r),this});function wb(r,t,e){t.set(r,e)}function xb(r,t,e){r.length<40?Rf(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Cr(r),e)}function Kf(){return new Lo}function pi(r,t){let e=Kf();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var _o;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(_o||(_o={}));function Hf(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function mi(r,t){return Hf("message",_o.LENGTH_DELIMITED,r,t)}var Io=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var gi;(function(r){let t;r.codec=()=>(t==null&&(t=mi((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.webtransportCerthashes!=null)for(let s of e.webtransportCerthashes)n.uint32(10),n.bytes(s);if(e.streamMuxers!=null)for(let s of e.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new Io('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(e.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new Io('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(e.string());break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>pi(e,r.codec()),r.decode=(e,n)=>li(e,r.codec(),n)})(gi||(gi={}));var Bo;(function(r){let t;r.codec=()=>(t==null&&(t=mi((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.identityKey!=null&&e.identityKey.byteLength>0&&(n.uint32(10),n.bytes(e.identityKey)),e.identitySig!=null&&e.identitySig.byteLength>0&&(n.uint32(18),n.bytes(e.identitySig)),e.extensions!=null&&(n.uint32(34),gi.codec().encode(e.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={identityKey:gt(0),identitySig:gt(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.identityKey=e.bytes();break}case 2:{s.identitySig=e.bytes();break}case 4:{s.extensions=gi.codec().decode(e,e.uint32(),{limits:o.limits?.extensions});break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>pi(e,r.codec()),r.decode=(e,n)=>li(e,r.codec(),n)})(Bo||(Bo={}));async function zf(r,t,e){let n=await r.sign(Md(t));return Bo.encode({identityKey:Pe(r.publicKey),identitySig:n,extensions:e})}async function $f(r,t,e){try{let n=Bo.decode(r),o=to(n.identityKey);if(e?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${e}`);if(!t)throw new Error("Remote static does not exist");let s=Md(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Do(n.message)}}function Md(r){let t=Cr("noise-libp2p-static-key:");return r instanceof Uint8Array?En([t,r],t.length+r.length):(r.prepend(t),r)}var Vf=class extends Ye{stream;handshake;metrics;decoder;constructor(t,e,n){super({log:t.log,inactivityTimeout:t.inactivityTimeout,maxReadBufferLength:t.maxReadBufferLength,direction:t.direction}),this.stream=t,this.handshake=e,this.metrics=n,this.decoder=new $s({lengthDecoder:pn,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(t){let e=new de;for(let n=0;n<t.byteLength;n+=65519){let o=n+65519;o>t.byteLength&&(o=t.byteLength);let s;t instanceof Uint8Array?s=this.handshake.encrypt(t.subarray(n,o)):s=this.handshake.encrypt(t.sublist(n,o)),this.metrics?.encryptedPackets.increment(),e.append(dn(s.byteLength)),e.append(s)}return e}decrypt(t){let e=new de;for(let n=0;n<t.byteLength;n+=65535){let o=n+65535;if(o>t.byteLength&&(o=t.byteLength),o-Gc<n)throw new Error("Invalid chunk");let s;t instanceof Uint8Array?s=t.subarray(n,o):s=t.sublist(n,o);let i=t.subarray(n,o-Gc);try{let a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),e.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return e}close(t){return this.stream.close(t)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(t){this.stream.abort(t)}sendData(t){return{sentBytes:t.byteLength,canSendMore:this.stream.send(this.encrypt(t))}}};function qf(r,t,e){return new Vf(r,t,e)}async function Kd(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=r,u=await zf(s,a.publicKey,f),h=new Ao({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Af(h.s,e),e.trace("Stage 0 - Initiator starting to send first message."),await n.write(h.writeMessageA(Lr),t),e.trace("Stage 0 - Initiator finished sending first message."),vf(h.e,e),e.trace("Stage 1 - Initiator waiting to receive first message from responder...");let p=h.readMessageB(await n.read(t));e.trace("Stage 1 - Initiator received the message."),Cf(h.re,e),Ed(h.rs,e),e.trace("Initiator going to check remote's signature...");let d=await $f(p,h.rs,c);e.trace("All good with the signature!"),e.trace("Stage 2 - Initiator sending third handshake message."),await n.write(h.writeMessageC(u),t),e.trace("Stage 2 - Initiator sent message with signed payload.");let[m,b]=h.ss.split();return Lf(m,b,e),{payload:d,encrypt:l=>m.encryptWithAd(Lr,l),decrypt:(l,y)=>b.decryptWithAd(Lr,l,y)}}async function Hd(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=r,u=await zf(s,a.publicKey,f),h=new Ao({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Af(h.s,e),e.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await n.read(t)),e.trace("Stage 0 - Responder received first message."),Cf(h.re,e),e.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(h.writeMessageB(u),t),e.trace("Stage 1 - Responder sent the second handshake message with signed payload."),vf(h.e,e),e.trace("Stage 2 - Responder waiting for third handshake message...");let p=h.readMessageC(await n.read(t));e.trace("Stage 2 - Responder received the message, finished handshake.");let d=await $f(p,h.rs,c),[m,b]=h.ss.split();return Lf(m,b,e),{payload:d,encrypt:l=>b.encryptWithAd(Lr,l),decrypt:(l,y)=>m.decryptWithAd(Lr,l,y)}}var yi=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(t,e={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=e,{metrics:a}=t;this.components=t,this.log=t.logger.forComponent("libp2p:noise");let c=s??Yl;this.crypto=Zl(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?Jl(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??gt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Or]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,e){let n=t.log?.newScope("noise")??this.log,o=Vs(t,{lengthEncoder:dn,lengthDecoder:pn,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,e?.remotePeer?.publicKey,e),i=to(s.payload.identityKey);return{connection:qf(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:oc(i),streamMuxer:e?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(t){if(t==null||t.length===0)return;let e=this.components.upgrader.getStreamMuxers();if(e!=null)for(let n of t){let o=e.get(n);if(o!=null)return o}if(t.length)throw new Ro("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(t,e){let n=t.log?.newScope("noise")??this.log,o=Vs(t,{lengthEncoder:dn,lengthDecoder:pn,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,e?.remotePeer?.publicKey,e),i=to(s.payload.identityKey);return{connection:qf(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:oc(i),streamMuxer:e?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(t,e,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Kd({connection:t,privateKey:e,remoteIdentityKey: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(t,e,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Hd({connection:t,privateKey:e,remoteIdentityKey: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 Vd(r={}){return t=>new yi(t,r)}var jf=Object.values(ir).map(r=>r.decoder).reduce((r,t)=>r.or(t)),Eb=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function zd(r){return r?.match(Eb)?.groups?.fingerprint}function Gf(r){let e=r.getComponents().find(n=>n.code===466)?.value;if(e===void 0||e==="")throw new $(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return e}function Sb(r){return Gt.decode(jf.decode(r))}function Ab(r){let t=Sb(Gf(r)),e=vb(t.code),n=t.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new Js(n,r.toString());return`${e} ${o.join(":").toUpperCase()}`}function $d(r){let t=r.split(":").map(o=>parseInt(o,16)),e=Uint8Array.from(t),n=Ut(ge.code,e);return rn(`/certhash/${Dn.encode(n.bytes)}`)}function vb(r){switch(r){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new ti(r)}}function qd(r,t){let{host:e,port:n,type:o}=Uc(r);if(o!=="ip4"&&o!=="ip6")throw new $(`Multiaddr ${r} was not an IPv4 or IPv6 address`);let s=Ab(r);return{type:"answer",sdp:`v=0
3
+ o=- 0 0 IN IP${o==="ip4"?4:6} ${e}
4
4
  s=-
5
5
  t=0 0
6
6
  a=ice-lite
7
7
  m=application ${n} UDP/DTLS/SCTP webrtc-datachannel
8
- c=IN IP${o==="ip4"?4:6} ${r}
8
+ c=IN IP${o==="ip4"?4:6} ${e}
9
9
  a=mid:0
10
10
  a=ice-options:ice2
11
- a=ice-ufrag:${e}
12
- a=ice-pwd:${e}
11
+ a=ice-ufrag:${t}
12
+ a=ice-pwd:${t}
13
13
  a=fingerprint:${s}
14
14
  a=setup:passive
15
15
  a=sctp-port:5000
16
- a=max-message-size:${mn}
17
- a=candidate:1467250027 1 UDP 1467250027 ${r} ${n} typ host
16
+ a=max-message-size:${on}
17
+ a=candidate:1467250027 1 UDP 1467250027 ${e} ${n} typ host
18
18
  a=end-of-candidates
19
- `}}function rm(t,e){let{host:r,port:n,type:o}=If(t);if(o!=="ip4"&&o!=="ip6")throw new j(`Multiaddr ${t} was not an IPv4 or IPv6 address`);return{type:"offer",sdp:`v=0
20
- o=- 0 0 IN IP${o==="ip4"?4:6} ${r}
19
+ `}}function jd(r,t){let{host:e,port:n,type:o}=Uc(r);if(o!=="ip4"&&o!=="ip6")throw new $(`Multiaddr ${r} was not an IPv4 or IPv6 address`);return{type:"offer",sdp:`v=0
20
+ o=- 0 0 IN IP${o==="ip4"?4:6} ${e}
21
21
  s=-
22
- c=IN IP${o==="ip4"?4:6} ${r}
22
+ c=IN IP${o==="ip4"?4:6} ${e}
23
23
  t=0 0
24
24
  a=ice-options:ice2,trickle
25
25
  m=application ${n} UDP/DTLS/SCTP webrtc-datachannel
26
26
  a=mid:0
27
27
  a=setup:active
28
- a=ice-ufrag:${e}
29
- a=ice-pwd:${e}
28
+ a=ice-ufrag:${t}
29
+ a=ice-pwd:${t}
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:${mn}
33
- a=candidate:1467250027 1 UDP 1467250027 ${r} ${n} typ host
32
+ a=max-message-size:${on}
33
+ a=candidate:1467250027 1 UDP 1467250027 ${e} ${n} typ host
34
34
  a=end-of-candidates
35
- `}}function ku(t,e){if(t.sdp===void 0)throw new j("Can't munge a missing SDP");let r=t.sdp.includes(`\r
35
+ `}}function Wf(r,t){if(r.sdp===void 0)throw new $("Can't munge a missing SDP");let e=r.sdp.includes(`\r
36
36
  `)?`\r
37
37
  `:`
38
- `;try{t.sdp=t.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
39
- a=ice-ufrag:`+e+r).replace(/\na=ice-pwd:[^\n]*\n/,`
40
- a=ice-pwd:`+e+r)}catch{}return t}var Ku=re("libp2p-webrtc-noise:");function om(t,e,r){let n=t.trim().toLowerCase().replaceAll(":",""),o=re(n,"hex"),s=Oe(yt.code,o),i=Fu.decode(Mu(e)),a=Ku.byteLength+s.bytes.byteLength+i.byteLength;return r==="server"?it([Ku,i,s.bytes],a):it([Ku,s.bytes,i],a)}function Gw(t,e){return t.role==="server"}async function sm(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 h=await t.createOffer();n.log.trace("client created local offer %s",h.sdp);let m=ku(h,r);n.log.trace("client setting local offer %s",m.sdp),await t.setLocalDescription(m);let p=tm(n.remoteAddr,r);n.log.trace("client setting server description %s",p.sdp),await t.setRemoteDescription(p)}else{let h=rm(n.remoteAddr,r);n.log.trace("server setting client %s %s",h.type,h.sdp),await t.setRemoteDescription(h),n.log.trace("server creating local answer");let m=await t.createAnswer();n.log.trace("server created local answer");let p=ku(m,r);n.log.trace("server setting local description %s",m.sdp),await t.setLocalDescription(p)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await ve(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),Gw(n,t)){let h=t.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(em(h))}let s=Qp(t.localDescription?.sdp);if(s==null)throw new er("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=om(s,n.remoteAddr,n.role),a=Jp({prologueBytes:i})(n),c=Do({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),f=Bo({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(h=>{n.log.error("error closing connection - %e",h),f.abort(h)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let h=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:h.remotePeer,muxerFactory:e,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let u=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});f.remoteAddr=f.remoteAddr.encapsulate(`/p2p/${u.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(f,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:e,signal:n.signal})}catch(s){throw o.close(),t.close(),s}}async function im(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,dataChannelOptions:r.dataChannel});return{peerConnection:s,muxerFactory:i}}var Ui=class{log;metrics;components;init;constructor(e,r={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=r,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"})})}[ns]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Nr]=["@libp2p/transport"];async dial(e,r){this.log("dial %a",e),r.signal.throwIfAborted();let n,o=e.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=an(o));let s=Gd(),{peerConnection:i,muxerFactory:a}=await im("client",s,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await sm(i,a,s,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:r.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:r.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw i.close(),c}}createListener(e){throw new yi("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(Pd.exactMatch)}};function Ww(t){return e=>new Ui(e,t)}function Xw(t){return e=>new Si(e,t)}return hm(Yw);})();
38
+ `;try{r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
39
+ a=ice-ufrag:`+t+e).replace(/\na=ice-pwd:[^\n]*\n/,`
40
+ a=ice-pwd:`+t+e)}catch{}return r}var Xf=Y("libp2p-webrtc-noise:");function Wd(r,t,e){let n=r.trim().toLowerCase().replaceAll(":",""),o=Y(n,"hex"),s=Ut(ge.code,o),i=jf.decode(Gf(t)),a=Xf.byteLength+s.bytes.byteLength+i.byteLength;return e==="server"?Mt([Xf,i,s.bytes],a):Mt([Xf,s.bytes,i],a)}function Cb(r,t){return r.role==="server"}async function Xd(r,t,e,n){let o=r.createDataChannel("",{negotiated:!0,id:0});try{if(n.role==="client"){n.log.trace("client creating local offer");let h=await r.createOffer();n.log.trace("client created local offer %s",h.sdp);let p=Wf(h,e);n.log.trace("client setting local offer %s",p.sdp),await r.setLocalDescription(p);let d=qd(n.remoteAddr,e);n.log.trace("client setting server description %s",d.sdp),await r.setRemoteDescription(d)}else{let h=jd(n.remoteAddr,e);n.log.trace("server setting client %s %s",h.type,h.sdp),await r.setRemoteDescription(h),n.log.trace("server creating local answer");let p=await r.createAnswer();n.log.trace("server created local answer");let d=Wf(p,e);n.log.trace("server setting local description %s",p.sdp),await r.setLocalDescription(d)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await Lt(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),Cb(n,r)){let h=r.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate($d(h))}let s=zd(r.localDescription?.sdp);if(s==null)throw new Je("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=Wd(s,n.remoteAddr,n.role),a=Vd({prologueBytes:i})(n),c=po({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),f=mo({peerConnection:r,remoteAddr:n.remoteAddr,metrics:n.events,direction:n.role==="client"?"outbound":"inbound",log:n.logger.forComponent("libp2p:webrtc-direct:connection")});if(r.addEventListener("connectionstatechange",()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":f.close().catch(h=>{n.log.error("error closing connection - %e",h),f.abort(h)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let h=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:h.remotePeer,muxerFactory:t,signal:n.signal})}n.log.trace("%s secure outbound",n.role);let u=await a.secureOutbound(c,{remotePeer:n.remotePeer,signal:n.signal,skipStreamMuxerNegotiation:!0});f.remoteAddr=f.remoteAddr.encapsulate(`/p2p/${u.remotePeer}`),n.log.trace("%s upgrade inbound",n.role),await n.upgrader.upgradeInbound(f,{skipProtection:!0,skipEncryption:!0,remotePeer:u.remotePeer,muxerFactory:t,signal:n.signal})}catch(s){throw o.close(),r.close(),s}}async function Yd(r,t,e={}){let n=e.certificate;n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof e.rtcConfiguration=="function"?await e.rtcConfiguration():e.rtcConfiguration,s=new RTCPeerConnection({...o??{},certificates:[n]}),i=new Ze({peerConnection:s,metrics:e.events,dataChannelOptions:e.dataChannel});return{peerConnection:s,muxerFactory:i}}var bi=class{log;metrics;components;init;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:webrtc-direct"),this.components=t,this.init=e,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[Vo]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Or]=["@libp2p/transport"];async dial(t,e){this.log("dial %a",t),e.signal.throwIfAborted();let n,o=t.getComponents().findLast(c=>c.code===421)?.value;o!=null&&(n=Zr(o));let s=Bl(),{peerConnection:i,muxerFactory:a}=await Yd("client",s,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await Xd(i,a,s,{role:"client",log:this.log,logger:this.components.logger,events:this.metrics?.dialerEvents,signal:e.signal,remoteAddr:t,dataChannel:this.init.dataChannel,upgrader:e.upgrader,peerId:this.components.peerId,remotePeer:n,privateKey:this.components.privateKey})}catch(c){throw i.close(),c}}createListener(t){throw new Qs("WebRTCDirectTransport.createListener")}listenFilter(t){return[]}dialFilter(t){return t.filter(yl.exactMatch)}};function Lb(r){return t=>new bi(t,r)}function _b(r){return t=>new oi(t,r)}return ep(Ib);})();
41
41
  /*! Bundled license information:
42
42
 
43
43
  @noble/curves/utils.js: