@libp2p/webrtc 6.0.16-f60bd85b0 → 6.0.18
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 +12 -15
- package/dist/index.min.js.map +4 -4
- package/dist/src/constants.js +1 -1
- package/dist/src/index.d.ts +2 -2
- package/dist/src/index.js +2 -2
- package/dist/src/muxer.d.ts +2 -2
- package/dist/src/muxer.js +2 -2
- package/dist/src/private-to-private/initiate-connection.d.ts +1 -1
- package/dist/src/private-to-private/initiate-connection.js +3 -3
- package/dist/src/private-to-private/signaling-stream-handler.js +2 -2
- package/dist/src/private-to-private/transport.js +3 -3
- package/dist/src/private-to-private/util.d.ts +2 -2
- package/dist/src/private-to-private/util.js +1 -1
- package/dist/src/private-to-public/listener.d.ts +1 -1
- package/dist/src/private-to-public/listener.js +3 -3
- package/dist/src/private-to-public/transport.browser.js +2 -2
- package/dist/src/private-to-public/transport.d.ts +1 -1
- package/dist/src/private-to-public/transport.js +3 -3
- package/dist/src/private-to-public/utils/connect.d.ts +1 -1
- package/dist/src/private-to-public/utils/connect.js +2 -2
- package/dist/src/private-to-public/utils/generate-noise-prologue.js +1 -1
- package/dist/src/private-to-public/utils/get-rtcpeerconnection.js +1 -1
- package/dist/src/stream.d.ts +1 -1
- package/dist/src/stream.js +3 -3
- package/dist/src/util.js +1 -1
- package/dist/typedoc-urls.json +14 -0
- package/package.json +10 -9
- package/src/constants.ts +1 -1
- package/src/index.ts +4 -4
- package/src/muxer.ts +3 -3
- package/src/private-to-private/initiate-connection.ts +4 -4
- package/src/private-to-private/signaling-stream-handler.ts +2 -2
- package/src/private-to-private/transport.ts +3 -3
- package/src/private-to-private/util.ts +2 -2
- package/src/private-to-public/listener.ts +6 -6
- package/src/private-to-public/transport.browser.ts +2 -2
- package/src/private-to-public/transport.ts +3 -3
- package/src/private-to-public/utils/connect.ts +3 -3
- package/src/private-to-public/utils/generate-noise-prologue.ts +1 -1
- package/src/private-to-public/utils/get-rtcpeerconnection.ts +1 -1
- package/src/stream.ts +4 -4
- package/src/util.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PWebrtc = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2PWebrtc=(()=>{var As=Object.defineProperty;var rh=Object.getOwnPropertyDescriptor;var nh=Object.getOwnPropertyNames;var oh=Object.prototype.hasOwnProperty;var Bt=(e,t)=>{for(var r in t)As(e,r,{get:t[r],enumerable:!0})},sh=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of nh(t))!oh.call(e,o)&&o!==r&&As(e,o,{get:()=>t[o],enumerable:!(n=rh(t,o))||n.enumerable});return e};var ih=e=>sh(As({},"__esModule",{value:!0}),e);var _0={};Bt(_0,{webRTC:()=>C0,webRTCDirect:()=>v0});var Vn=class extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}},$n=class extends Error{static name="InvalidCryptoExchangeError";constructor(t="Invalid crypto exchange"){super(t),this.name="InvalidCryptoExchangeError"}},Y=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},ar=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Wn=class extends Error{static name="ConnectionFailedError";constructor(t="Connection failed"){super(t),this.name="ConnectionFailedError"}},qn=class extends Error{static name="MuxerClosedError";constructor(t="The muxer is closed"){super(t),this.name="MuxerClosedError"}},cr=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}};var jt=class extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}},Gr=class extends Error{static name="StreamBufferError";constructor(t="The stream buffer was full"){super(t),this.name="StreamBufferError"}};var Gn=class extends Error{static name="InvalidMultiaddrError";constructor(t="Invalid multiaddr"){super(t),this.name="InvalidMultiaddrError"}},zn=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},jn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var Xn=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var Ke=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Yn=class extends Event{data;constructor(t,r){super("message",r),this.data=t}},ur=class extends Event{error;local;constructor(t,r,n){super("close",n),this.error=r,this.local=t}},Zn=class extends ur{constructor(t,r){super(!0,t,r)}},Qn=class extends ur{constructor(t,r){super(!1,t,r)}};var vs=Symbol.for("@libp2p/peer-id");var Jn=Symbol.for("@libp2p/transport");var Ic;(function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"})(Ic||(Ic={}));var ge=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let r=this.#t.get(t);return r==null?0:r.length}addEventListener(t,r,n){super.addEventListener(t,r,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:r,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,r,n){super.removeEventListener(t.toString(),r??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==r),this.#t.set(t,o))}dispatchEvent(t){let r=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),r}safeDispatchEvent(t,r={}){return this.dispatchEvent(new CustomEvent(t,r))}};var fr=Symbol.for("@libp2p/service-capabilities"),Lc=Symbol.for("@libp2p/service-dependencies");var Bs={};Bt(Bs,{base58btc:()=>ft,base58flickr:()=>dh});var og=new Uint8Array(0);function Bc(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function te(e){if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}function Dc(e){return new TextEncoder().encode(e)}function Tc(e){return new TextDecoder().decode(e)}function ah(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var o=0;o<e.length;o++){var s=e.charAt(o),i=s.charCodeAt(0);if(r[i]!==255)throw new TypeError(s+" is ambiguous");r[i]=o}var a=e.length,c=e.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var E=0,h=0,b=0,v=p.length;b!==v&&p[b]===0;)b++,E++;for(var x=(v-b)*f+1>>>0,D=new Uint8Array(x);b!==v;){for(var k=p[b],O=0,K=x-1;(k!==0||O<h)&&K!==-1;K--,O++)k+=256*D[K]>>>0,D[K]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");h=O,b++}for(var _=x-h;_!==x&&D[_]===0;)_++;for(var A=c.repeat(E);_<x;++_)A+=e.charAt(D[_]);return A}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var E=0;if(p[E]!==" "){for(var h=0,b=0;p[E]===c;)h++,E++;for(var v=(p.length-E)*u+1>>>0,x=new Uint8Array(v);p[E];){var D=r[p.charCodeAt(E)];if(D===255)return;for(var k=0,O=v-1;(D!==0||k<b)&&O!==-1;O--,k++)D+=a*x[O]>>>0,x[O]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");b=k,E++}if(p[E]!==" "){for(var K=v-b;K!==v&&x[K]===0;)K++;for(var _=new Uint8Array(h+(v-K)),A=h;K!==v;)_[A++]=x[K++];return _}}}function m(p){var E=d(p);if(E)return E;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:d,decode:m}}var ch=ah,uh=ch,Pc=uh;var Cs=class{name;prefix;baseEncode;constructor(t,r,n){this.name=t,this.prefix=r,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},_s=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,r,n){this.name=t,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(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 Oc(this,t)}},Is=class{decoders;constructor(t){this.decoders=t}or(t){return Oc(this,t)}decode(t){let r=t[0],n=this.decoders[r];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 Oc(e,t){return new Is({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var Ls=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,r,n,o){this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=o,this.encoder=new Cs(t,r,n),this.decoder=new _s(t,r,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function lr({name:e,prefix:t,encode:r,decode:n}){return new Ls(e,t,r,n)}function ye({name:e,prefix:t,alphabet:r}){let{encode:n,decode:o}=Pc(r,e);return lr({prefix:t,name:e,encode:n,decode:s=>te(o(s))})}function fh(e,t,r,n){let o=e.length;for(;e[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let f=t[e[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|f,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 lh(e,t,r){let n=t[t.length-1]==="=",o=(1<<r)-1,s="",i=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],i+=8;i>r;)i-=r,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<r-i]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function hh(e){let t={};for(let r=0;r<e.length;++r)t[e[r]]=r;return t}function ut({name:e,prefix:t,bitsPerChar:r,alphabet:n}){let o=hh(n);return lr({prefix:t,name:e,encode(s){return lh(s,n,r)},decode(s){return fh(s,o,r,e)}})}var ft=ye({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),dh=ye({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ds={};Bt(Ds,{base32:()=>be,base32hex:()=>yh,base32hexpad:()=>wh,base32hexpadupper:()=>xh,base32hexupper:()=>bh,base32pad:()=>mh,base32padupper:()=>gh,base32upper:()=>ph,base32z:()=>Eh});var be=ut({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ph=ut({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),mh=ut({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),gh=ut({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),yh=ut({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),bh=ut({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),wh=ut({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),xh=ut({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Eh=ut({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ts={};Bt(Ts,{base36:()=>zr,base36upper:()=>Sh});var zr=ye({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Sh=ye({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Vt={};Bt(Vt,{Digest:()=>He,create:()=>Dt,decode:()=>pr,equals:()=>Ps,hasCode:()=>Fh});var Ah=kc,Nc=128,vh=127,Ch=~vh,_h=Math.pow(2,31);function kc(e,t,r){t=t||[],r=r||0;for(var n=r;e>=_h;)t[r++]=e&255|Nc,e/=128;for(;e&Ch;)t[r++]=e&255|Nc,e>>>=7;return t[r]=e|0,kc.bytes=r-n+1,t}var Ih=Rs,Lh=128,Uc=127;function Rs(e,n){var r=0,n=n||0,o=0,s=n,i,a=e.length;do{if(s>=a)throw Rs.bytes=0,new RangeError("Could not decode varint");i=e[s++],r+=o<28?(i&Uc)<<o:(i&Uc)*Math.pow(2,o),o+=7}while(i>=Lh);return Rs.bytes=s-n,r}var Bh=Math.pow(2,7),Dh=Math.pow(2,14),Th=Math.pow(2,21),Rh=Math.pow(2,28),Ph=Math.pow(2,35),Oh=Math.pow(2,42),Nh=Math.pow(2,49),Uh=Math.pow(2,56),kh=Math.pow(2,63),Mh=function(e){return e<Bh?1:e<Dh?2:e<Th?3:e<Rh?4:e<Ph?5:e<Oh?6:e<Nh?7:e<Uh?8:e<kh?9:10},Kh={encode:Ah,decode:Ih,encodingLength:Mh},Hh=Kh,jr=Hh;function Xr(e,t=0){return[jr.decode(e,t),jr.decode.bytes]}function hr(e,t,r=0){return jr.encode(e,t,r),t}function dr(e){return jr.encodingLength(e)}function Dt(e,t){let r=t.byteLength,n=dr(e),o=n+dr(r),s=new Uint8Array(o+r);return hr(e,s,0),hr(r,s,n),s.set(t,o),new He(e,r,t,s)}function pr(e){let t=te(e),[r,n]=Xr(t),[o,s]=Xr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new He(r,o,i,t)}function Ps(e,t){if(e===t)return!0;{let r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&Bc(e.bytes,r.bytes)}}var He=class{code;size;digest;bytes;constructor(t,r,n,o){this.code=t,this.size=r,this.digest=n,this.bytes=o}};function Fh(e,t){return e.code===t}function Mc(e,t){let{bytes:r,version:n}=e;switch(n){case 0:return $h(r,Os(e),t??ft.encoder);default:return Wh(r,Os(e),t??be.encoder)}}var Kc=new WeakMap;function Os(e){let t=Kc.get(e);if(t==null){let r=new Map;return Kc.set(e,r),r}return t}var dt=class e{code;version;multihash;bytes;"/";constructor(t,r,n,o){this.code=r,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:r}=this;if(t!==Yr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==qh)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return e.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:r}=this.multihash,n=Dt(t,r);return e.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return e.equals(this,t)}static equals(t,r){let n=r;return n!=null&&t.code===n.code&&t.version===n.version&&Ps(t.multihash,n.multihash)}toString(t){return Mc(this,t)}toJSON(){return{"/":Mc(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 r=t;if(r instanceof e)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:o,multihash:s,bytes:i}=r;return new e(n,o,s,i??Hc(n,o,s.bytes))}else if(r[Gh]===!0){let{version:n,multihash:o,code:s}=r,i=pr(o);return e.create(n,s,i)}else return null}static create(t,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(r!==Yr)throw new Error(`Version 0 CID must use dag-pb (code: ${Yr}) block encoding`);return new e(t,r,n,n.bytes)}case 1:{let o=Hc(t,r,n.bytes);return new e(t,r,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return e.create(0,Yr,t)}static createV1(t,r){return e.create(1,t,r)}static decode(t){let[r,n]=e.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(t){let r=e.inspectBytes(t),n=r.size-r.multihashSize,o=te(t.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 He(r.multihashCode,r.digestSize,s,o);return[r.version===0?e.createV0(i):e.createV1(r.codec,i),t.subarray(r.size)]}static inspectBytes(t){let r=0,n=()=>{let[l,d]=Xr(t.subarray(r));return r+=d,l},o=n(),s=Yr;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(),u=r+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(t,r){let[n,o]=Vh(t,r),s=e.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Os(s).set(n,t),s}};function Vh(e,t){switch(e[0]){case"Q":{let r=t??ft;return[ft.prefix,r.decode(`${ft.prefix}${e}`)]}case ft.prefix:{let r=t??ft;return[ft.prefix,r.decode(e)]}case be.prefix:{let r=t??be;return[be.prefix,r.decode(e)]}case zr.prefix:{let r=t??zr;return[zr.prefix,r.decode(e)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}}function $h(e,t,r){let{prefix:n}=r;if(n!==ft.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let o=t.get(n);if(o==null){let s=r.encode(e).slice(1);return t.set(n,s),s}else return o}function Wh(e,t,r){let{prefix:n}=r,o=t.get(n);if(o==null){let s=r.encode(e);return t.set(n,s),s}else return o}var Yr=112,qh=18;function Hc(e,t,r){let n=dr(e),o=n+dr(t),s=new Uint8Array(o+r.byteLength);return hr(e,s,0),hr(t,s,n),s.set(r,o),s}var Gh=Symbol.for("@ipld/js-cid/CID");var Ns={};Bt(Ns,{identity:()=>$t});var Fc=0,zh="identity",Vc=te;function jh(e,t){if(t?.truncate!=null&&t.truncate!==e.byteLength){if(t.truncate<0||t.truncate>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,t.truncate)}return Dt(Fc,Vc(e))}var $t={code:Fc,name:zh,encode:Vc,digest:jh};function wt(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}function pt(e=0){return new Uint8Array(e)}function it(e=0){return new Uint8Array(e)}function Tt(e,t){t==null&&(t=e.reduce((o,s)=>o+s.length,0));let r=it(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}var Wc=Symbol.for("@achingbrain/uint8arraylist");function $c(e,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let r=0;for(let n of e){let o=r+n.byteLength;if(t<o)return{buf:n,index:t-r};r=o}throw new RangeError("index is out of bounds")}function eo(e){return!!e?.[Wc]}var W=class e{bufs;length;[Wc]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let r=0;for(let n of t)if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.push(n);else if(eo(n))r+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}prepend(...t){this.prependAll(t)}prependAll(t){let r=0;for(let n of t.reverse())if(n instanceof Uint8Array)r+=n.byteLength,this.bufs.unshift(n);else if(eo(n))r+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=r}get(t){let r=$c(this.bufs,t);return r.buf[r.index]}set(t,r){let n=$c(this.bufs,t);n.buf[n.index]=r}write(t,r=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(r+n,t[n]);else if(eo(t))for(let n=0;n<t.length;n++)this.set(r+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,r){let{bufs:n,length:o}=this._subList(t,r);return Tt(n,o)}subarray(t,r){let{bufs:n,length:o}=this._subList(t,r);return n.length===1?n[0]:Tt(n,o)}sublist(t,r){let{bufs:n,length:o}=this._subList(t,r),s=new e;return s.length=o,s.bufs=[...n],s}_subList(t,r){if(t=t??0,r=r??this.length,t<0&&(t=this.length+t),r<0&&(r=this.length+r),t<0||r>this.length)throw new RangeError("index is out of bounds");if(t===r)return{bufs:[],length:0};if(t===0&&r===this.length)return{bufs:this.bufs,length:this.length};let n=[],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 u=t>=a&&t<c,f=r>a&&r<=c;if(u&&f){if(t===a&&r===c){n.push(i);break}let l=t-a;n.push(i.subarray(l,l+(r-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(f){if(r===c){n.push(i);break}n.push(i.subarray(0,r-a));break}n.push(i)}return{bufs:n,length:r-t}}indexOf(t,r=0){if(!eo(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(r=Number(r??0),isNaN(r)&&(r=0),r<0&&(r=this.length+r),r<0&&(r=0),t.length===0)return r>this.length?this.length:r;let 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 l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=r;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let m=this.get(l+d);if(n[d]!==m){f=Math.max(1,d-a[m]);break}}if(f===0)return l}return-1}getInt8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(t,r){let n=it(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,r),this.write(n,t)}getInt16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,r)}setInt16(t,r,n){let o=pt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,r,n),this.write(o,t)}getInt32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,r)}setInt32(t,r,n){let o=pt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,r,n),this.write(o,t)}getBigInt64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,r)}setBigInt64(t,r,n){let o=pt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,r,n),this.write(o,t)}getUint8(t){let r=this.subarray(t,t+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint8(0)}setUint8(t,r){let n=it(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,r),this.write(n,t)}getUint16(t,r){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,r)}setUint16(t,r,n){let o=pt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,r,n),this.write(o,t)}getUint32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,r)}setUint32(t,r,n){let o=pt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,r,n),this.write(o,t)}getBigUint64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,r)}setBigUint64(t,r,n){let o=pt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,r,n),this.write(o,t)}getFloat32(t,r){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,r)}setFloat32(t,r,n){let o=pt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,r,n),this.write(o,t)}getFloat64(t,r){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,r)}setFloat64(t,r,n){let o=pt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,r,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof e)||t.bufs.length!==this.bufs.length)return!1;for(let r=0;r<this.bufs.length;r++)if(!wt(this.bufs[r],t.bufs[r]))return!1;return!0}static fromUint8Arrays(t,r){let n=new e;return n.bufs=t,r==null&&(r=t.reduce((o,s)=>o+s.byteLength,0)),n.length=r,n}};var Us={};Bt(Us,{base10:()=>Yh});var Yh=ye({prefix:"9",name:"base10",alphabet:"0123456789"});var ks={};Bt(ks,{base16:()=>Zh,base16upper:()=>Qh});var Zh=ut({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Qh=ut({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ms={};Bt(Ms,{base2:()=>Jh});var Jh=ut({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ks={};Bt(Ks,{base256emoji:()=>od});var qc=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),td=qc.reduce((e,t,r)=>(e[r]=t,e),[]),ed=qc.reduce((e,t,r)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return e[n]=r,e},[]);function rd(e){return e.reduce((t,r)=>(t+=td[r],t),"")}function nd(e){let t=[];for(let r of e){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=ed[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);t.push(o)}return new Uint8Array(t)}var od=lr({prefix:"\u{1F680}",name:"base256emoji",encode:rd,decode:nd});var Hs={};Bt(Hs,{base64:()=>sd,base64pad:()=>id,base64url:()=>Zr,base64urlpad:()=>ad});var sd=ut({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),id=ut({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Zr=ut({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ad=ut({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Fs={};Bt(Fs,{base8:()=>cd});var cd=ut({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Vs={};Bt(Vs,{identity:()=>ud});var ud=lr({prefix:"\0",name:"identity",encode:e=>Tc(e),decode:e=>Dc(e)});var Hg=new TextEncoder,Fg=new TextDecoder;var qs={};Bt(qs,{sha256:()=>ee,sha512:()=>dd});var hd=20;function Ws({name:e,code:t,encode:r,minDigestLength:n,maxDigestLength:o}){return new $s(e,t,r,n,o)}var $s=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,r,n,o,s){this.name=t,this.code=r,this.encode=n,this.minDigestLength=o??hd,this.maxDigestLength=s}digest(t,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(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?Gc(n,this.code,r?.truncate):n.then(o=>Gc(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function Gc(e,t,r){if(r!=null&&r!==e.byteLength){if(r>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,r)}return Dt(t,e)}function jc(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}var ee=Ws({name:"sha2-256",code:18,encode:jc("SHA-256")}),dd=Ws({name:"sha2-512",code:19,encode:jc("SHA-512")});var Fe={...Vs,...Ms,...Fs,...Us,...ks,...Ds,...Ts,...Bs,...Hs,...Ks},Jg={...qs,...Ns};function Yc(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}var Xc=Yc("utf8","u",e=>"u"+new TextDecoder("utf8").decode(e),e=>new TextEncoder().encode(e.substring(1))),Gs=Yc("ascii","a",e=>{let t="a";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},e=>{e=e.substring(1);let t=it(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}),pd={utf8:Xc,"utf-8":Xc,hex:Fe.base16,latin1:Gs,ascii:Gs,binary:Gs,...Fe},ro=pd;function q(e,t="utf8"){let r=ro[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return r.decoder.decode(`${r.prefix}${e}`)}function $(e,t="utf8"){let r=ro[t];if(r==null)throw new Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}var md=parseInt("11111",2),zs=parseInt("10000000",2),gd=parseInt("01111111",2),Zc={0:Qr,1:Qr,2:yd,3:xd,4:Ed,5:wd,6:bd,16:Qr,22:Qr,48:Qr};function re(e,t={offset:0}){let r=e[t.offset]&md;if(t.offset++,Zc[r]!=null)return Zc[r](e,t);throw new Error("No decoder for tag "+r)}function Jr(e,t){let r=0;if((e[t.offset]&zs)===zs){let n=e[t.offset]&gd,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(o,16)}else r=e[t.offset],t.offset++;return r}function Qr(e,t){Jr(e,t);let r=[];for(;!(t.offset>=e.byteLength);){let n=re(e,t);if(n===null)break;r.push(n)}return r}function yd(e,t){let r=Jr(e,t),n=t.offset,o=t.offset+r,s=[];for(let i=n;i<o;i++)i===n&&e[i]===0||s.push(e[i]);return t.offset+=r,Uint8Array.from(s)}function bd(e,t){let r=Jr(e,t),n=t.offset+r,o=e[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 u=e[t.offset];if(t.offset++,c.push(u&127),u<128){c.reverse();let f=0;for(let l=0;l<c.length;l++)f+=c[l]<<l*7;a+=`.${f}`,c=[]}}return a}function wd(e,t){return t.offset++,null}function xd(e,t){let r=Jr(e,t),n=e[t.offset];t.offset++;let o=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Ed(e,t){let r=Jr(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n}function Sd(e){let t=e.toString(16);t.length%2===1&&(t="0"+t);let r=new W;for(let n=0;n<t.length;n+=2)r.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return r}function js(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);let t=Sd(e.byteLength);return new W(Uint8Array.from([t.byteLength|zs]),t)}function Pt(e){let t=new W,r=128;return(e.subarray()[0]&r)===r&&t.append(Uint8Array.from([0])),t.append(e),new W(Uint8Array.from([2]),js(t),t)}function no(e){let t=Uint8Array.from([0]),r=new W(t,e);return new W(Uint8Array.from([3]),js(r),r)}function we(e,t=48){let r=new W;for(let n of e)r.append(n);return new W(Uint8Array.from([t]),js(r),r)}async function Qc(e,t,r,n){let o=await crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:e.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,r.subarray());return n?.signal?.throwIfAborted(),s}var Ad=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),vd=Uint8Array.from([6,5,43,129,4,0,34]),Cd=Uint8Array.from([6,5,43,129,4,0,35]),_d={ext:!0,kty:"EC",crv:"P-256"},Id={ext:!0,kty:"EC",crv:"P-384"},Ld={ext:!0,kty:"EC",crv:"P-521"},Xs=32,Ys=48,Zs=66;function Qs(e){let t=re(e);return Jc(t)}function Jc(e){let t=e[1][1][0],r=1,n,o;if(t.byteLength===Xs*2+1)return n=$(t.subarray(r,r+Xs),"base64url"),o=$(t.subarray(r+Xs),"base64url"),new mr({..._d,key_ops:["verify"],x:n,y:o});if(t.byteLength===Ys*2+1)return n=$(t.subarray(r,r+Ys),"base64url"),o=$(t.subarray(r+Ys),"base64url"),new mr({...Id,key_ops:["verify"],x:n,y:o});if(t.byteLength===Zs*2+1)return n=$(t.subarray(r,r+Zs),"base64url"),o=$(t.subarray(r+Zs),"base64url"),new mr({...Ld,key_ops:["verify"],x:n,y:o});throw new Y(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function tu(e){return we([Pt(Uint8Array.from([1])),we([Bd(e.crv)],160),we([no(new W(Uint8Array.from([4]),q(e.x??"","base64url"),q(e.y??"","base64url")))],161)]).subarray()}function Bd(e){if(e==="P-256")return Ad;if(e==="P-384")return vd;if(e==="P-521")return Cd;throw new Y(`Invalid curve ${e}`)}var mr=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=tu(this.jwk)),this._raw}toMultihash(){return $t.digest(xe(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return ft.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}async verify(t,r,n){return Qc(this.jwk,r,t,n)}};function Ve(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Kt(e,t=""){if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw new Error(`${r}expected integer >= 0, got ${e}`)}}function F(e,t,r=""){let n=Ve(e),o=e?.length,s=t!==void 0;if(!n||s&&o!==t){let i=r&&`"${r}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function $e(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Kt(e.outputLen),Kt(e.blockLen)}function gr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ru(e,t){F(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Wt(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function oo(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function qt(e,t){return e<<32-t|e>>>t}var nu=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Dd=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function oe(e){if(F(e),nu)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Dd[e[r]];return t}var ne={_0:48,_9:57,A:65,F:70,a:97,f:102};function eu(e){if(e>=ne._0&&e<=ne._9)return e-ne._0;if(e>=ne.A&&e<=ne.F)return e-(ne.A-10);if(e>=ne.a&&e<=ne.f)return e-(ne.a-10)}function se(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(nu)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=eu(e.charCodeAt(s)),a=eu(e.charCodeAt(s+1));if(i===void 0||a===void 0){let c=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ot(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];F(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let s=e[n];r.set(s,o),o+=s.length}return r}function Js(e,t={}){let r=(o,s)=>e(s).update(o).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.create=o=>e(o),Object.assign(r,t),Object.freeze(r)}function Ee(e=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}var ti=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function ou(e,t,r){return e&t^~e&r}function su(e,t,r){return e&t^e&r^t&r}var tn=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,r,n,o){this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=oo(this.buffer)}update(t){gr(this),F(t);let{view:r,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=oo(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(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){gr(this),ru(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,Wt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)r[l]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=oo(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:r,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%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ie=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var xt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var so=BigInt(4294967295),iu=BigInt(32);function Td(e,t=!1){return t?{h:Number(e&so),l:Number(e>>iu&so)}:{h:Number(e>>iu&so)|0,l:Number(e&so)|0}}function au(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=Td(e[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var ei=(e,t,r)=>e>>>r,ri=(e,t,r)=>e<<32-r|t>>>r,We=(e,t,r)=>e>>>r|t<<32-r,qe=(e,t,r)=>e<<32-r|t>>>r,en=(e,t,r)=>e<<64-r|t>>>r-32,rn=(e,t,r)=>e>>>r-32|t<<64-r;function Xt(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var cu=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),uu=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,fu=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),lu=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,hu=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),du=(e,t,r,n,o,s)=>t+r+n+o+s+(e/2**32|0)|0;var Pd=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]),Se=new Uint32Array(64),ni=class extends tn{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,r,n,o,s,i,a,c]}set(t,r,n,o,s,i,a,c){this.A=t|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(t,r){for(let l=0;l<16;l++,r+=4)Se[l]=t.getUint32(r,!1);for(let l=16;l<64;l++){let d=Se[l-15],m=Se[l-2],p=qt(d,7)^qt(d,18)^d>>>3,E=qt(m,17)^qt(m,19)^m>>>10;Se[l]=E+Se[l-7]+p+Se[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let d=qt(a,6)^qt(a,11)^qt(a,25),m=f+d+ou(a,c,u)+Pd[l]+Se[l]|0,E=(qt(n,2)^qt(n,13)^qt(n,22))+su(n,o,s)|0;f=u,u=c,c=a,a=i+m|0,i=s,s=o,o=n,n=m+E|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,u=u+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){Wt(Se)}destroy(){this.set(0,0,0,0,0,0,0,0),Wt(this.buffer)}},oi=class extends ni{A=ie[0]|0;B=ie[1]|0;C=ie[2]|0;D=ie[3]|0;E=ie[4]|0;F=ie[5]|0;G=ie[6]|0;H=ie[7]|0;constructor(){super(32)}};var pu=au(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Od=pu[0],Nd=pu[1],Ae=new Uint32Array(80),ve=new Uint32Array(80),si=class extends tn{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:d,Gh:m,Gl:p,Hh:E,Hl:h}=this;return[t,r,n,o,s,i,a,c,u,f,l,d,m,p,E,h]}set(t,r,n,o,s,i,a,c,u,f,l,d,m,p,E,h){this.Ah=t|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=u|0,this.El=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=m|0,this.Gl=p|0,this.Hh=E|0,this.Hl=h|0}process(t,r){for(let x=0;x<16;x++,r+=4)Ae[x]=t.getUint32(r),ve[x]=t.getUint32(r+=4);for(let x=16;x<80;x++){let D=Ae[x-15]|0,k=ve[x-15]|0,O=We(D,k,1)^We(D,k,8)^ei(D,k,7),K=qe(D,k,1)^qe(D,k,8)^ri(D,k,7),_=Ae[x-2]|0,A=ve[x-2]|0,N=We(_,A,19)^en(_,A,61)^ei(_,A,6),M=qe(_,A,19)^rn(_,A,61)^ri(_,A,6),T=fu(K,M,ve[x-7],ve[x-16]),w=lu(T,O,N,Ae[x-7],Ae[x-16]);Ae[x]=w|0,ve[x]=T|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:m,Fl:p,Gh:E,Gl:h,Hh:b,Hl:v}=this;for(let x=0;x<80;x++){let D=We(l,d,14)^We(l,d,18)^en(l,d,41),k=qe(l,d,14)^qe(l,d,18)^rn(l,d,41),O=l&m^~l&E,K=d&p^~d&h,_=hu(v,k,K,Nd[x],ve[x]),A=du(_,b,D,O,Od[x],Ae[x]),N=_|0,M=We(n,o,28)^en(n,o,34)^en(n,o,39),T=qe(n,o,28)^rn(n,o,34)^rn(n,o,39),w=n&s^n&a^s&a,g=o&i^o&c^i&c;b=E|0,v=h|0,E=m|0,h=p|0,m=l|0,p=d|0,{h:l,l:d}=Xt(u|0,f|0,A|0,N|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let y=cu(N,T,g);n=uu(y,A,M,w),o=y|0}({h:n,l:o}=Xt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Xt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Xt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=Xt(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=Xt(this.Eh|0,this.El|0,l|0,d|0),{h:m,l:p}=Xt(this.Fh|0,this.Fl|0,m|0,p|0),{h:E,l:h}=Xt(this.Gh|0,this.Gl|0,E|0,h|0),{h:b,l:v}=Xt(this.Hh|0,this.Hl|0,b|0,v|0),this.set(n,o,s,i,a,c,u,f,l,d,m,p,E,h,b,v)}roundClean(){Wt(Ae,ve)}destroy(){Wt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},ii=class extends si{Ah=xt[0]|0;Al=xt[1]|0;Bh=xt[2]|0;Bl=xt[3]|0;Ch=xt[4]|0;Cl=xt[5]|0;Dh=xt[6]|0;Dl=xt[7]|0;Eh=xt[8]|0;El=xt[9]|0;Fh=xt[10]|0;Fl=xt[11]|0;Gh=xt[12]|0;Gl=xt[13]|0;Hh=xt[14]|0;Hl=xt[15]|0;constructor(){super(64)}};var Yt=Js(()=>new oi,ti(1));var mu=Js(()=>new ii,ti(3));var ci=BigInt(0),ai=BigInt(1);function ae(e,t=""){if(typeof e!="boolean"){let r=t&&`"${t}" `;throw new Error(r+"expected boolean, got type="+typeof e)}return e}function gu(e){if(typeof e=="bigint"){if(!io(e))throw new Error("positive bigint expected, got "+e)}else Kt(e);return e}function nn(e){let t=gu(e).toString(16);return t.length&1?"0"+t:t}function yu(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?ci:BigInt("0x"+e)}function yr(e){return yu(oe(e))}function Zt(e){return yu(oe(Ge(F(e)).reverse()))}function ao(e,t){Kt(t),e=gu(e);let r=se(e.toString(16).padStart(t*2,"0"));if(r.length!==t)throw new Error("number too large");return r}function on(e,t){return ao(e,t).reverse()}function Ge(e){return Uint8Array.from(e)}var io=e=>typeof e=="bigint"&&ci<=e;function Ud(e,t,r){return io(e)&&io(t)&&io(r)&&t<=e&&e<r}function Ce(e,t,r,n){if(!Ud(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function ui(e){let t;for(t=0;e>ci;e>>=ai,t+=1);return t}var sn=e=>(ai<<BigInt(e))-ai;function bu(e,t,r){if(Kt(e,"hashLen"),Kt(t,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");let n=h=>new Uint8Array(h),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(e),u=n(e),f=0,l=()=>{c.fill(1),u.fill(0),f=0},d=(...h)=>r(u,Ot(c,...h)),m=(h=o)=>{u=d(s,h),c=d(),h.length!==0&&(u=d(i,h),c=d())},p=()=>{if(f++>=a)throw new Error("drbg: tried max amount of iterations");let h=0,b=[];for(;h<t;){c=d();let v=c.slice();b.push(v),h+=c.length}return Ot(...b)};return(h,b)=>{l(),m(h);let v;for(;!(v=b(p()));)m();return l(),v}}function Qt(e,t={},r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(s,i,a){let c=e[s];if(a&&c===void 0)return;let u=typeof c;if(u!==i||c===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${u}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(t,!1),o(r,!0)}function br(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let s=e(r,...n);return t.set(r,s),s}}var Rt=BigInt(0),mt=BigInt(1),ze=BigInt(2),Eu=BigInt(3),Su=BigInt(4),Au=BigInt(5),kd=BigInt(7),vu=BigInt(8),Md=BigInt(9),Cu=BigInt(16);function at(e,t){let r=e%t;return r>=Rt?r:t+r}function st(e,t,r){let n=e;for(;t-- >Rt;)n*=n,n%=r;return n}function wu(e,t){if(e===Rt)throw new Error("invert: expected non-zero number");if(t<=Rt)throw new Error("invert: expected positive modulus, got "+t);let r=at(e,t),n=t,o=Rt,s=mt,i=mt,a=Rt;for(;r!==Rt;){let u=n/r,f=n%r,l=o-i*u,d=s-a*u;n=r,r=f,o=i,s=a,i=l,a=d}if(n!==mt)throw new Error("invert: does not exist");return at(o,t)}function li(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function _u(e,t){let r=(e.ORDER+mt)/Su,n=e.pow(t,r);return li(e,n,t),n}function Kd(e,t){let r=(e.ORDER-Au)/vu,n=e.mul(t,ze),o=e.pow(n,r),s=e.mul(t,o),i=e.mul(e.mul(s,ze),o),a=e.mul(s,e.sub(i,e.ONE));return li(e,a,t),a}function Hd(e){let t=wr(e),r=Iu(e),n=r(t,t.neg(t.ONE)),o=r(t,n),s=r(t,t.neg(n)),i=(e+kd)/Cu;return(a,c)=>{let u=a.pow(c,i),f=a.mul(u,n),l=a.mul(u,o),d=a.mul(u,s),m=a.eql(a.sqr(f),c),p=a.eql(a.sqr(l),c);u=a.cmov(u,f,m),f=a.cmov(d,l,p);let E=a.eql(a.sqr(f),c),h=a.cmov(u,f,E);return li(a,h,c),h}}function Iu(e){if(e<Eu)throw new Error("sqrt is not defined for small field");let t=e-mt,r=0;for(;t%ze===Rt;)t/=ze,r++;let n=ze,o=wr(e);for(;xu(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return _u;let s=o.pow(n,t),i=(t+mt)/ze;return function(c,u){if(c.is0(u))return u;if(xu(c,u)!==1)throw new Error("Cannot find square root");let f=r,l=c.mul(c.ONE,s),d=c.pow(u,t),m=c.pow(u,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,E=c.sqr(d);for(;!c.eql(E,c.ONE);)if(p++,E=c.sqr(E),p===f)throw new Error("Cannot find square root");let h=mt<<BigInt(f-p-1),b=c.pow(l,h);f=p,l=c.sqr(b),d=c.mul(d,l),m=c.mul(m,b)}return m}}function Fd(e){return e%Su===Eu?_u:e%vu===Au?Kd:e%Cu===Md?Hd(e):Iu(e)}var Lu=(e,t)=>(at(e,t)&mt)===mt,Vd=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hi(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=Vd.reduce((n,o)=>(n[o]="function",n),t);return Qt(e,r),e}function $d(e,t,r){if(r<Rt)throw new Error("invalid exponent, negatives unsupported");if(r===Rt)return e.ONE;if(r===mt)return t;let n=e.ONE,o=t;for(;r>Rt;)r&mt&&(n=e.mul(n,o)),o=e.sqr(o),r>>=mt;return n}function an(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((i,a,c)=>e.is0(a)?i:(n[c]=i,e.mul(i,a)),e.ONE),s=e.inv(o);return t.reduceRight((i,a,c)=>e.is0(a)?i:(n[c]=e.mul(i,n[c]),e.mul(i,a)),s),n}function xu(e,t){let r=(e.ORDER-mt)/ze,n=e.pow(t,r),o=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function Wd(e,t){t!==void 0&&Kt(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var fi=class{ORDER;BITS;BYTES;isLE;ZERO=Rt;ONE=mt;_lengths;_sqrt;_mod;constructor(t,r={}){if(t<=Rt)throw new Error("invalid field: expected ORDER > 0, got "+t);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=r.allowedLengths?.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:o,nByteLength:s}=Wd(t,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(t){return at(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof t);return Rt<=t&&t<this.ORDER}is0(t){return t===Rt}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&mt)===mt}neg(t){return at(-t,this.ORDER)}eql(t,r){return t===r}sqr(t){return at(t*t,this.ORDER)}add(t,r){return at(t+r,this.ORDER)}sub(t,r){return at(t-r,this.ORDER)}mul(t,r){return at(t*r,this.ORDER)}pow(t,r){return $d(this,t,r)}div(t,r){return at(t*wu(r,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,r){return t+r}subN(t,r){return t-r}mulN(t,r){return t*r}inv(t){return wu(t,this.ORDER)}sqrt(t){return this._sqrt||(this._sqrt=Fd(this.ORDER)),this._sqrt(this,t)}toBytes(t){return this.isLE?on(t,this.BYTES):ao(t,this.BYTES)}fromBytes(t,r=!1){F(t);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let u=new Uint8Array(o);u.set(t,s?0:u.length-t.length),t=u}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=s?Zt(t):yr(t);if(a&&(c=at(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return an(this,t)}cmov(t,r,n){return n?r:t}};function wr(e,t={}){return new fi(e,t)}function Bu(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function di(e){let t=Bu(e);return t+Math.ceil(t/2)}function pi(e,t,r=!1){F(e);let n=e.length,o=Bu(t),s=di(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?Zt(e):yr(e),a=at(i,t-mt)+mt;return r?on(a,o):ao(a,o)}var xr=BigInt(0),je=BigInt(1);function cn(e,t){let r=t.negate();return e?r:t}function Xe(e,t){let r=an(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function Pu(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function mi(e,t){Pu(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,s=sn(e),i=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Du(e,t,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(e&o),c=e>>i;a>n&&(a-=s,c+=je);let u=t*n,f=u+Math.abs(a)-1,l=a===0,d=a<0,m=t%2!==0;return{nextN:c,offset:f,isZero:l,isNeg:d,isNegF:m,offsetF:u}}var gi=new WeakMap,Ou=new WeakMap;function yi(e){return Ou.get(e)||1}function Tu(e){if(e!==xr)throw new Error("invalid wNAF")}var Er=class{BASE;ZERO;Fn;bits;constructor(t,r){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=r}_unsafeLadder(t,r,n=this.ZERO){let o=t;for(;r>xr;)r&je&&(n=n.add(o)),o=o.double(),r>>=je;return n}precomputeWindow(t,r){let{windows:n,windowSize:o}=mi(r,this.bits),s=[],i=t,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let u=1;u<o;u++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(t,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=mi(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:f,isNeg:l,isNegF:d,offsetF:m}=Du(n,a,i);n=c,f?s=s.add(cn(d,r[m])):o=o.add(cn(l,r[u]))}return Tu(n),{p:o,f:s}}wNAFUnsafe(t,r,n,o=this.ZERO){let s=mi(t,this.bits);for(let i=0;i<s.windows&&n!==xr;i++){let{nextN:a,offset:c,isZero:u,isNeg:f}=Du(n,i,s);if(n=a,!u){let l=r[c];o=o.add(f?l.negate():l)}}return Tu(n),o}getPrecomputes(t,r,n){let o=gi.get(r);return o||(o=this.precomputeWindow(r,t),t!==1&&(typeof n=="function"&&(o=n(o)),gi.set(r,o))),o}cached(t,r,n){let o=yi(t);return this.wNAF(o,this.getPrecomputes(o,t,n),r)}unsafe(t,r,n,o){let s=yi(t);return s===1?this._unsafeLadder(t,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),r,o)}createCache(t,r){Pu(r,this.bits),Ou.set(t,r),gi.delete(t)}hasCache(t){return yi(t)!==1}};function Nu(e,t,r,n){let o=t,s=e.ZERO,i=e.ZERO;for(;r>xr||n>xr;)r&je&&(s=s.add(o)),n&je&&(i=i.add(o)),o=o.double(),r>>=je,n>>=je;return{p1:s,p2:i}}function Ru(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return hi(t),t}else return wr(e,{isLE:r})}function co(e,t,r={},n){if(n===void 0&&(n=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let u=t[c];if(!(typeof u=="bigint"&&u>xr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Ru(t.p,r.Fp,n),s=Ru(t.n,r.Fn,n),a=["Gx","Gy","a",e==="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 Sr(e,t){return function(n){let o=e(n);return{secretKey:o,publicKey:t(o)}}}var _e=BigInt(0),gt=BigInt(1),bi=BigInt(2),qd=BigInt(8);function Gd(e,t,r,n){let o=e.sqr(r),s=e.sqr(n),i=e.add(e.mul(t.a,o),s),a=e.add(e.ONE,e.mul(t.d,e.mul(o,s)));return e.eql(i,a)}function Uu(e,t={}){let r=co("edwards",e,t,t.FpFnLE),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i}=s;Qt(t,{},{uvRatio:"function"});let a=bi<<BigInt(o.BYTES*8)-gt,c=h=>n.create(h),u=t.uvRatio||((h,b)=>{try{return{isValid:!0,value:n.sqrt(n.div(h,b))}}catch{return{isValid:!1,value:_e}}});if(!Gd(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function f(h,b,v=!1){let x=v?gt:_e;return Ce("coordinate "+h,b,x,a),b}function l(h){if(!(h instanceof p))throw new Error("EdwardsPoint expected")}let d=br((h,b)=>{let{X:v,Y:x,Z:D}=h,k=h.is0();b==null&&(b=k?qd:n.inv(D));let O=c(v*b),K=c(x*b),_=n.mul(D,b);if(k)return{x:_e,y:gt};if(_!==gt)throw new Error("invZ was invalid");return{x:O,y:K}}),m=br(h=>{let{a:b,d:v}=s;if(h.is0())throw new Error("bad point: ZERO");let{X:x,Y:D,Z:k,T:O}=h,K=c(x*x),_=c(D*D),A=c(k*k),N=c(A*A),M=c(K*b),T=c(A*c(M+_)),w=c(N+c(v*c(K*_)));if(T!==w)throw new Error("bad point: equation left != right (1)");let g=c(x*D),y=c(k*O);if(g!==y)throw new Error("bad point: equation left != right (2)");return!0});class p{static BASE=new p(s.Gx,s.Gy,gt,c(s.Gx*s.Gy));static ZERO=new p(_e,gt,gt,_e);static Fp=n;static Fn=o;X;Y;Z;T;constructor(b,v,x,D){this.X=f("x",b),this.Y=f("y",v),this.Z=f("z",x,!0),this.T=f("t",D),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){if(b instanceof p)throw new Error("extended point not allowed");let{x:v,y:x}=b||{};return f("x",v),f("y",x),new p(v,x,gt,c(v*x))}static fromBytes(b,v=!1){let x=n.BYTES,{a:D,d:k}=s;b=Ge(F(b,x,"point")),ae(v,"zip215");let O=Ge(b),K=b[x-1];O[x-1]=K&-129;let _=Zt(O),A=v?a:n.ORDER;Ce("point.y",_,_e,A);let N=c(_*_),M=c(N-gt),T=c(k*N-D),{isValid:w,value:g}=u(M,T);if(!w)throw new Error("bad point: invalid y coordinate");let y=(g>)===gt,C=(K&128)!==0;if(!v&&g===_e&&C)throw new Error("bad point: x=0 and x_0=1");return C!==y&&(g=c(-g)),p.fromAffine({x:g,y:_})}static fromHex(b,v=!1){return p.fromBytes(se(b),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,v=!0){return E.createCache(this,b),v||this.multiply(bi),this}assertValidity(){m(this)}equals(b){l(b);let{X:v,Y:x,Z:D}=this,{X:k,Y:O,Z:K}=b,_=c(v*K),A=c(k*D),N=c(x*K),M=c(O*D);return _===A&&N===M}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:b}=s,{X:v,Y:x,Z:D}=this,k=c(v*v),O=c(x*x),K=c(bi*c(D*D)),_=c(b*k),A=v+x,N=c(c(A*A)-k-O),M=_+O,T=M-K,w=_-O,g=c(N*T),y=c(M*w),C=c(N*w),L=c(T*M);return new p(g,y,L,C)}add(b){l(b);let{a:v,d:x}=s,{X:D,Y:k,Z:O,T:K}=this,{X:_,Y:A,Z:N,T:M}=b,T=c(D*_),w=c(k*A),g=c(K*x*M),y=c(O*N),C=c((D+k)*(_+A)-T-w),L=y-g,I=y+g,S=c(w-v*T),B=c(C*L),R=c(I*S),P=c(C*S),j=c(L*I);return new p(B,R,j,P)}subtract(b){return this.add(b.negate())}multiply(b){if(!o.isValidNot0(b))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:x}=E.cached(this,b,D=>Xe(p,D));return Xe(p,[v,x])[0]}multiplyUnsafe(b,v=p.ZERO){if(!o.isValid(b))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return b===_e?p.ZERO:this.is0()||b===gt?this:E.unsafe(this,b,x=>Xe(p,x),v)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return E.unsafe(this,s.n).is0()}toAffine(b){return d(this,b)}clearCofactor(){return i===gt?this:this.multiplyUnsafe(i)}toBytes(){let{x:b,y:v}=this.toAffine(),x=n.toBytes(v);return x[x.length-1]|=b>?128:0,x}toHex(){return oe(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let E=new Er(p,o.BITS);return p.BASE.precompute(8),p}function ku(e,t,r={}){if(typeof t!="function")throw new Error('"hash" function param is required');Qt(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=r,{BASE:o,Fp:s,Fn:i}=e,a=r.randomBytes||Ee,c=r.adjustScalarBytes||(_=>_),u=r.domain||((_,A,N)=>{if(ae(N,"phflag"),A.length||N)throw new Error("Contexts/pre-hash are not supported");return _});function f(_){return i.create(Zt(_))}function l(_){let A=x.secretKey;F(_,x.secretKey,"secretKey");let N=F(t(_),2*A,"hashedSecretKey"),M=c(N.slice(0,A)),T=N.slice(A,2*A),w=f(M);return{head:M,prefix:T,scalar:w}}function d(_){let{head:A,prefix:N,scalar:M}=l(_),T=o.multiply(M),w=T.toBytes();return{head:A,prefix:N,scalar:M,point:T,pointBytes:w}}function m(_){return d(_).pointBytes}function p(_=Uint8Array.of(),...A){let N=Ot(...A);return f(t(u(N,F(_,void 0,"context"),!!n)))}function E(_,A,N={}){_=F(_,void 0,"message"),n&&(_=n(_));let{prefix:M,scalar:T,pointBytes:w}=d(A),g=p(N.context,M,_),y=o.multiply(g).toBytes(),C=p(N.context,y,w,_),L=i.create(g+C*T);if(!i.isValid(L))throw new Error("sign failed: invalid s");let I=Ot(y,i.toBytes(L));return F(I,x.signature,"result")}let h={zip215:!0};function b(_,A,N,M=h){let{context:T,zip215:w}=M,g=x.signature;_=F(_,g,"signature"),A=F(A,void 0,"message"),N=F(N,x.publicKey,"publicKey"),w!==void 0&&ae(w,"zip215"),n&&(A=n(A));let y=g/2,C=_.subarray(0,y),L=Zt(_.subarray(y,g)),I,S,B;try{I=e.fromBytes(N,w),S=e.fromBytes(C,w),B=o.multiplyUnsafe(L)}catch{return!1}if(!w&&I.isSmallOrder())return!1;let R=p(T,S.toBytes(),I.toBytes(),A);return S.add(I.multiplyUnsafe(R)).subtract(B).clearCofactor().is0()}let v=s.BYTES,x={secretKey:v,publicKey:v,signature:2*v,seed:v};function D(_=a(x.seed)){return F(_,x.seed,"seed")}function k(_){return Ve(_)&&_.length===i.BYTES}function O(_,A){try{return!!e.fromBytes(_,A)}catch{return!1}}let K={getExtendedPublicKey:d,randomSecretKey:D,isValidSecretKey:k,isValidPublicKey:O,toMontgomery(_){let{y:A}=e.fromBytes(_),N=x.publicKey,M=N===32;if(!M&&N!==57)throw new Error("only defined for 25519 and 448");let T=M?s.div(gt+A,gt-A):s.div(A-gt,A+gt);return s.toBytes(T)},toMontgomerySecret(_){let A=x.secretKey;F(_,A);let N=t(_.subarray(0,A));return c(N).subarray(0,A)}};return Object.freeze({keygen:Sr(D,m),getPublicKey:m,sign:E,verify:b,utils:K,Point:e,lengths:x})}var un=BigInt(0),Ar=BigInt(1),uo=BigInt(2);function zd(e){return Qt(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function Mu(e){let t=zd(e),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=t,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||Ee,u=a?255:448,f=a?32:56,l=BigInt(a?9:5),d=BigInt(a?121665:39081),m=a?uo**BigInt(254):uo**BigInt(447),p=a?BigInt(8)*uo**BigInt(251)-Ar:BigInt(4)*uo**BigInt(445)-Ar,E=m+p+Ar,h=g=>at(g,r),b=v(l);function v(g){return on(h(g),f)}function x(g){let y=Ge(F(g,f,"uCoordinate"));return a&&(y[31]&=127),h(Zt(y))}function D(g){return Zt(o(Ge(F(g,f,"scalar"))))}function k(g,y){let C=N(x(y),D(g));if(C===un)throw new Error("invalid private or public key received");return v(C)}function O(g){return k(g,b)}let K=O,_=k;function A(g,y,C){let L=h(g*(y-C));return y=h(y-L),C=h(C+L),{x_2:y,x_3:C}}function N(g,y){Ce("u",g,un,r),Ce("scalar",y,m,E);let C=y,L=g,I=Ar,S=un,B=g,R=Ar,P=un;for(let z=BigInt(u-1);z>=un;z--){let V=C>>z&Ar;P^=V,{x_2:I,x_3:B}=A(P,I,B),{x_2:S,x_3:R}=A(P,S,R),P=V;let X=I+S,rt=h(X*X),lt=I-S,Z=h(lt*lt),ht=rt-Z,ir=B+R,Fn=B-R,qr=h(Fn*X),vc=h(ir*lt),Cc=qr+vc,_c=qr-vc;B=h(Cc*Cc),R=h(L*h(_c*_c)),I=h(rt*Z),S=h(ht*(rt+h(d*ht)))}({x_2:I,x_3:B}=A(P,I,B)),{x_2:S,x_3:R}=A(P,S,R);let j=s(S);return h(I*j)}let M={secretKey:f,publicKey:f,seed:f},T=(g=c(f))=>(F(g,M.seed,"seed"),g),w={randomSecretKey:T};return Object.freeze({keygen:Sr(T,K),getSharedSecret:_,getPublicKey:K,scalarMult:k,scalarMultBase:O,utils:w,GuBytes:b.slice(),lengths:M})}var jd=BigInt(1),Ku=BigInt(2),Xd=BigInt(3),Yd=BigInt(5),Zd=BigInt(8),fo=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Qd={p:fo,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Zd,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Fu(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=fo,a=e*e%s*e%s,c=st(a,Ku,s)*a%s,u=st(c,jd,s)*e%s,f=st(u,Yd,s)*u%s,l=st(f,t,s)*f%s,d=st(l,r,s)*l%s,m=st(d,n,s)*d%s,p=st(m,o,s)*m%s,E=st(p,o,s)*m%s,h=st(E,t,s)*f%s;return{pow_p_5_8:st(h,Ku,s)*e%s,b2:a}}function Vu(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var Hu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Jd(e,t){let r=fo,n=at(t*t*t,r),o=at(n*n*t,r),s=Fu(e*o).pow_p_5_8,i=at(e*n*s,r),a=at(t*i*i,r),c=i,u=at(i*Hu,r),f=a===e,l=a===at(-e,r),d=a===at(-e*Hu,r);return f&&(i=c),(l||d)&&(i=u),Lu(i,r)&&(i=at(-i,r)),{isValid:f||l,value:i}}var tp=Uu(Qd,{uvRatio:Jd});function ep(e){return ku(tp,mu,Object.assign({adjustScalarBytes:Vu},e))}var $u=ep({});var fn=(()=>{let e=fo;return Mu({P:e,type:"x25519",powPminus2:t=>{let{pow_p_5_8:r,b2:n}=Fu(t);return at(st(r,Xd,e)*n,e)},adjustScalarBytes:Vu})})();var ln=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},lo=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Wu={get(e=globalThis){let t=e.crypto;if(t?.subtle==null)throw new lo("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 Ht=Wu;var ho=32;var wi,rp=(async()=>{try{return await Ht.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function np(e,t,r){if(e.buffer instanceof ArrayBuffer){let n=await Ht.get().subtle.importKey("raw",e.buffer,{name:"Ed25519"},!1,["verify"]);return await Ht.get().subtle.verify({name:"Ed25519"},n,t,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function op(e,t,r){return $u.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}async function qu(e,t,r){return wi==null&&(wi=await rp),wi?np(e,t,r):op(e,t,r)}function po(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}var mo=class{type="Ed25519";raw;constructor(t){this.raw=xi(t,ho)}toMultihash(){return $t.digest(xe(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return ft.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}verify(t,r,n){n?.signal?.throwIfAborted();let o=qu(this.raw,r,t);return po(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Ei(e){return e=xi(e,ho),new mo(e)}function xi(e,t){if(e=Uint8Array.from(e??[]),e.length!==t)throw new Y(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var ip=Math.pow(2,7),ap=Math.pow(2,14),cp=Math.pow(2,21),Si=Math.pow(2,28),Ai=Math.pow(2,35),vi=Math.pow(2,42),Ci=Math.pow(2,49),J=128,vt=127;function et(e){if(e<ip)return 1;if(e<ap)return 2;if(e<cp)return 3;if(e<Si)return 4;if(e<Ai)return 5;if(e<vi)return 6;if(e<Ci)return 7;if(Number.MAX_SAFE_INTEGER!=null&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ie(e,t,r=0){switch(et(e)){case 8:t[r++]=e&255|J,e/=128;case 7:t[r++]=e&255|J,e/=128;case 6:t[r++]=e&255|J,e/=128;case 5:t[r++]=e&255|J,e/=128;case 4:t[r++]=e&255|J,e>>>=7;case 3:t[r++]=e&255|J,e>>>=7;case 2:t[r++]=e&255|J,e>>>=7;case 1:{t[r++]=e&255,e>>>=7;break}default:throw new Error("unreachable")}return t}function up(e,t,r=0){switch(et(e)){case 8:t.set(r++,e&255|J),e/=128;case 7:t.set(r++,e&255|J),e/=128;case 6:t.set(r++,e&255|J),e/=128;case 5:t.set(r++,e&255|J),e/=128;case 4:t.set(r++,e&255|J),e>>>=7;case 3:t.set(r++,e&255|J),e>>>=7;case 2:t.set(r++,e&255|J),e>>>=7;case 1:{t.set(r++,e&255),e>>>=7;break}default:throw new Error("unreachable")}return t}function hn(e,t){let r=e[t],n=0;if(n+=r&vt,r<J||(r=e[t+1],n+=(r&vt)<<7,r<J)||(r=e[t+2],n+=(r&vt)<<14,r<J)||(r=e[t+3],n+=(r&vt)<<21,r<J)||(r=e[t+4],n+=(r&vt)*Si,r<J)||(r=e[t+5],n+=(r&vt)*Ai,r<J)||(r=e[t+6],n+=(r&vt)*vi,r<J)||(r=e[t+7],n+=(r&vt)*Ci,r<J))return n;throw new RangeError("Could not decode varint")}function fp(e,t){let r=e.get(t),n=0;if(n+=r&vt,r<J||(r=e.get(t+1),n+=(r&vt)<<7,r<J)||(r=e.get(t+2),n+=(r&vt)<<14,r<J)||(r=e.get(t+3),n+=(r&vt)<<21,r<J)||(r=e.get(t+4),n+=(r&vt)*Si,r<J)||(r=e.get(t+5),n+=(r&vt)*Ai,r<J)||(r=e.get(t+6),n+=(r&vt)*vi,r<J)||(r=e.get(t+7),n+=(r&vt)*Ci,r<J))return n;throw new RangeError("Could not decode varint")}function go(e,t,r=0){return t==null&&(t=it(et(e))),t instanceof Uint8Array?Ie(e,t,r):up(e,t,r)}function ce(e,t=0){return e instanceof Uint8Array?hn(e,t):fp(e,t)}var _i=new Float32Array([-0]),Le=new Uint8Array(_i.buffer);function zu(e,t,r){_i[0]=e,t[r]=Le[0],t[r+1]=Le[1],t[r+2]=Le[2],t[r+3]=Le[3]}function ju(e,t){return Le[0]=e[t],Le[1]=e[t+1],Le[2]=e[t+2],Le[3]=e[t+3],_i[0]}var Ii=new Float64Array([-0]),Ct=new Uint8Array(Ii.buffer);function Xu(e,t,r){Ii[0]=e,t[r]=Ct[0],t[r+1]=Ct[1],t[r+2]=Ct[2],t[r+3]=Ct[3],t[r+4]=Ct[4],t[r+5]=Ct[5],t[r+6]=Ct[6],t[r+7]=Ct[7]}function Yu(e,t){return Ct[0]=e[t],Ct[1]=e[t+1],Ct[2]=e[t+2],Ct[3]=e[t+3],Ct[4]=e[t+4],Ct[5]=e[t+5],Ct[6]=e[t+6],Ct[7]=e[t+7],Ii[0]}var lp=BigInt(Number.MAX_SAFE_INTEGER),hp=BigInt(Number.MIN_SAFE_INTEGER),Ut=class e{lo;hi;constructor(t,r){this.lo=t|0,this.hi=r|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?t<16384?t<128?1:2:t<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return Ye;if(t<lp&&t>hp)return this.fromNumber(Number(t));let r=t<0n;r&&(t=-t);let n=t>>32n,o=t-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>Zu&&(o=0n,++n>Zu&&(n=0n))),new e(Number(o),Number(n))}static fromNumber(t){if(t===0)return Ye;let r=t<0;r&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new e(n,o)}static from(t){return typeof t=="number"?e.fromNumber(t):typeof t=="bigint"?e.fromBigInt(t):typeof t=="string"?e.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new e(t.low>>>0,t.high>>>0):Ye}},Ye=new Ut(0,0);Ye.toBigInt=function(){return 0n};Ye.zzEncode=Ye.zzDecode=function(){return this};Ye.length=function(){return 1};var Zu=4294967296n;function Qu(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:(r&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Ju(e,t,r){if(r-t<1)return"";let o,s=[],i=0,a;for(;t<r;)a=e[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(e[t++]&63)<<6|e[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 Li(e,t,r){let n=r,o,s;for(let i=0;i<e.length;++i)o=e.charCodeAt(i),o<128?t[r++]=o:o<2048?(t[r++]=o>>6|192,t[r++]=o&63|128):(o&64512)===55296&&((s=e.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[r++]=o>>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=o&63|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=o&63|128);return r-n}function Gt(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function yo(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}var Bi=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,Gt(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 Gt(this,4);return yo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Gt(this,4);return yo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Gt(this,4);let t=ju(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Gt(this,4);let t=Yu(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),r=this.pos,n=this.pos+t;if(n>this.len)throw Gt(this,t);return this.pos+=t,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let t=this.bytes();return Ju(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Gt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Gt(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 Ut(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw Gt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,t}if(this.len-this.pos>4){for(;r<5;++r)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;r<5;++r){if(this.pos>=this.len)throw Gt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Gt(this,8);let t=yo(this.buf,this.pos+=4),r=yo(this.buf,this.pos+=4);return new Ut(t,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=hn(this.buf,this.pos);return this.pos+=et(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 pn(e){return new Bi(e instanceof Uint8Array?e:e.subarray())}function Be(e,t,r){let n=pn(e);return t.decode(n,void 0,r)}function Di(e){let t=e??8192,r=t>>>1,n,o=t;return function(i){if(i<1||i>r)return it(i);o+i>t&&(n=it(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Ze=class{fn;len;next;val;constructor(t,r,n){this.fn=t,this.len=r,this.next=void 0,this.val=n}};function Ti(){}var Pi=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},dp=Di();function pp(e){return globalThis.Buffer!=null?it(e):dp(e)}var gn=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ze(Ti,0,0),this.tail=this.head,this.states=null}_push(t,r,n){return this.tail=this.tail.next=new Ze(t,r,n),this.len+=r,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Oi((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(bo,10,Ut.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let r=Ut.fromBigInt(t);return this._push(bo,r.length(),r)}uint64Number(t){return this._push(Ie,et(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 r=Ut.fromBigInt(t).zzEncode();return this._push(bo,r.length(),r)}sint64Number(t){let r=Ut.fromNumber(t).zzEncode();return this._push(bo,r.length(),r)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Ri,1,t?1:0)}fixed32(t){return this._push(mn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let r=Ut.fromBigInt(t);return this._push(mn,4,r.lo)._push(mn,4,r.hi)}fixed64Number(t){let r=Ut.fromNumber(t);return this._push(mn,4,r.lo)._push(mn,4,r.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(zu,4,t)}double(t){return this._push(Xu,8,t)}bytes(t){let r=t.length>>>0;return r===0?this._push(Ri,1,0):this.uint32(r)._push(gp,r,t)}string(t){let r=Qu(t);return r!==0?this.uint32(r)._push(Li,r,t):this._push(Ri,1,0)}fork(){return this.states=new Pi(this),this.head=this.tail=new Ze(Ti,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 Ze(Ti,0,0),this.len=0),this}ldelim(){let t=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=r,this.len+=n),this}finish(){let t=this.head.next,r=pp(this.len),n=0;for(;t!=null;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}};function Ri(e,t,r){t[r]=e&255}function mp(e,t,r){for(;e>127;)t[r++]=e&127|128,e>>>=7;t[r]=e}var Oi=class extends Ze{next;constructor(t,r){super(mp,t,r),this.next=void 0}};function bo(e,t,r){for(;e.hi!==0;)t[r++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=e.lo&127|128,e.lo=e.lo>>>7;t[r++]=e.lo}function mn(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function gp(e,t,r){t.set(e,r)}globalThis.Buffer!=null&&(gn.prototype.bytes=function(e){let t=e.length>>>0;return this.uint32(t),t>0&&this._push(yp,t,e),this},gn.prototype.string=function(e){let t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(bp,t,e),this});function yp(e,t,r){t.set(e,r)}function bp(e,t,r){e.length<40?Li(e,t,r):t.utf8Write!=null?t.utf8Write(e,r):t.set(q(e),r)}function Ni(){return new gn}function De(e,t){let r=Ni();return t.encode(e,r,{lengthDelimited:!1}),r.finish()}function*Te(e,t,r){let n=pn(e);yield*t.stream(n,void 0,"$",r)}var wo={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function xo(e,t,r,n,o){return{name:e,type:t,encode:r,decode:n,stream:o}}function Qe(e){function t(s){if(e[s.toString()]==null)throw new Error("Invalid enum value");return e[s]}let r=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 xo("enum",wo.VARINT,r,n,o)}function Re(e,t,r){return xo("message",wo.LENGTH_DELIMITED,e,t,r)}var ct;(function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"})(ct||(ct={}));var Ui;(function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"})(Ui||(Ui={}));(function(e){e.codec=()=>Qe(Ui)})(ct||(ct={}));var Jt;(function(e){let t;e.codec=()=>(t==null&&(t=Re((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ct.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={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.Type=ct.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.Type`,value:ct.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(f&7);break}}}})),t);function r(s){return De(s,e.codec())}e.encode=r;function n(s,i){return Be(s,e.codec(),i)}e.decode=n;function o(s,i){return Te(s,e.codec(),i)}e.stream=o})(Jt||(Jt={}));var ki;(function(e){let t;e.codec=()=>(t==null&&(t=Re((s,i,a={})=>{a.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),ct.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={},u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{c.Type=ct.codec().decode(s);break}case 2:{c.Data=s.bytes();break}default:{s.skipType(f&7);break}}}return c},function*(s,i,a,c={}){let u=i==null?s.len:s.pos+i;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{yield{field:`${a}.Type`,value:ct.codec().decode(s)};break}case 2:{yield{field:`${a}.Data`,value:s.bytes()};break}default:{s.skipType(f&7);break}}}})),t);function r(s){return De(s,e.codec())}e.encode=r;function n(s,i){return Be(s,e.codec(),i)}e.decode=n;function o(s,i){return Te(s,e.codec(),i)}e.stream=o})(ki||(ki={}));var bn={};Bt(bn,{MAX_RSA_KEY_SIZE:()=>Mi,generateRSAKeyPair:()=>sf,jwkToJWKKeyPair:()=>af,jwkToPkcs1:()=>Sp,jwkToPkix:()=>Vi,jwkToRSAPrivateKey:()=>Gi,pkcs1MessageToJwk:()=>Hi,pkcs1MessageToRSAPrivateKey:()=>$i,pkcs1ToJwk:()=>Ep,pkcs1ToRSAPrivateKey:()=>of,pkixMessageToJwk:()=>Fi,pkixMessageToRSAPublicKey:()=>qi,pkixToJwk:()=>Ap,pkixToRSAPublicKey:()=>Wi});var vr=class{type="RSA";jwk;_raw;_multihash;constructor(t,r){this.jwk=t,this._multihash=r}get raw(){return this._raw==null&&(this._raw=bn.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return dt.createV1(114,this._multihash)}toString(){return ft.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}verify(t,r,n){return nf(this.jwk,r,t,n)}},yn=class{type="RSA";jwk;_raw;publicKey;constructor(t,r){this.jwk=t,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=bn.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}sign(t,r){return rf(this.jwk,t,r)}};var Mi=8192,Ki=18,wp=1062,xp=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function Ep(e){let t=re(e);return Hi(t)}function Hi(e){return{n:$(e[1],"base64url"),e:$(e[2],"base64url"),d:$(e[3],"base64url"),p:$(e[4],"base64url"),q:$(e[5],"base64url"),dp:$(e[6],"base64url"),dq:$(e[7],"base64url"),qi:$(e[8],"base64url"),kty:"RSA"}}function Sp(e){if(e.n==null||e.e==null||e.d==null||e.p==null||e.q==null||e.dp==null||e.dq==null||e.qi==null)throw new Y("JWK was missing components");return we([Pt(Uint8Array.from([0])),Pt(q(e.n,"base64url")),Pt(q(e.e,"base64url")),Pt(q(e.d,"base64url")),Pt(q(e.p,"base64url")),Pt(q(e.q,"base64url")),Pt(q(e.dp,"base64url")),Pt(q(e.dq,"base64url")),Pt(q(e.qi,"base64url"))]).subarray()}function Ap(e){let t=re(e,{offset:0});return Fi(t)}function Fi(e){let t=re(e[1],{offset:0});return{kty:"RSA",n:$(t[0],"base64url"),e:$(t[1],"base64url")}}function Vi(e){if(e.n==null||e.e==null)throw new Y("JWK was missing components");return we([xp,no(we([Pt(q(e.n,"base64url")),Pt(q(e.e,"base64url"))]))]).subarray()}function of(e){let t=re(e);return $i(t)}function $i(e){let t=Hi(e);return Gi(t)}function Wi(e,t){if(e.byteLength>=wp)throw new ar("Key size is too large");let r=re(e,{offset:0});return qi(r,e,t)}function qi(e,t,r){let n=Fi(e);if(r==null){let o=Yt(Jt.encode({Type:ct.RSA,Data:t}));r=Dt(Ki,o)}return new vr(n,r)}function Gi(e){if(uf(e)>Mi)throw new Y("Key size is too large");let t=af(e),r=Yt(Jt.encode({Type:ct.RSA,Data:Vi(t.publicKey)})),n=Dt(Ki,r);return new yn(t.privateKey,new vr(t.publicKey,n))}async function sf(e){if(e>Mi)throw new Y("Key size is too large");let t=await cf(e),r=Yt(Jt.encode({Type:ct.RSA,Data:Vi(t.publicKey)})),n=Dt(Ki,r);return new yn(t.privateKey,new vr(t.publicKey,n))}function af(e){if(e==null)throw new Y("Missing key parameter");return{privateKey:e,publicKey:{kty:e.kty,n:e.n,e:e.e}}}async function cf(e,t){let r=await Ht.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);t?.signal?.throwIfAborted();let n=await vp(r,t);return{privateKey:n[0],publicKey:n[1]}}async function rf(e,t,r){let n=await Ht.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let o=await Ht.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,t instanceof Uint8Array?t:t.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function nf(e,t,r,n){let o=await Ht.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ht.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,t,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),s}async function vp(e,t){if(e.privateKey==null||e.publicKey==null)throw new Y("Private and public key are required");let r=await Promise.all([Ht.get().subtle.exportKey("jwk",e.privateKey),Ht.get().subtle.exportKey("jwk",e.publicKey)]);return t?.signal?.throwIfAborted(),r}function uf(e){if(e.kty!=="RSA")throw new Y("invalid key type");if(e.n==null)throw new Y("invalid key modulus");return q(e.n,"base64url").length*8}var Eo=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,r){if($e(t),F(r,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(r.length>n?t.create().update(r).digest():r);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),Wt(o)}update(t){return gr(this),this.iHash.update(t),this}digestInto(t){gr(this),F(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,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=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Cr=(e,t,r)=>new Eo(e,t).update(r).digest();Cr.create=(e,t)=>new Eo(e,t);var ff=(e,t)=>(e+(e>=0?t:-t)/lf)/t;function Cp(e,t,r){let[[n,o],[s,i]]=t,a=ff(i*e,r),c=ff(-o*e,r),u=e-a*n-c*s,f=-a*o-c*i,l=u<ue,d=f<ue;l&&(u=-u),d&&(f=-f);let m=sn(Math.ceil(ui(r)/2))+_r;if(u<ue||u>=m||f<ue||f>=m)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:l,k1:u,k2neg:d,k2:f}}function ji(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function zi(e,t){let r={};for(let n of Object.keys(t))r[n]=e[n]===void 0?t[n]:e[n];return ae(r.lowS,"lowS"),ae(r.prehash,"prehash"),r.format!==void 0&&ji(r.format),r}var Xi=class extends Error{constructor(t=""){super(t)}},Pe={Err:Xi,_tlv:{encode:(e,t)=>{let{Err:r}=Pe;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let n=t.length/2,o=nn(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?nn(o.length/2|128):"";return nn(e)+s+o+t},decode(e,t){let{Err:r}=Pe,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("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 r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let f of u)i=i<<8|f;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(e){let{Err:t}=Pe;if(e<ue)throw new t("integer: negative integers are not allowed");let r=nn(e);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){let{Err:t}=Pe;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return yr(e)}},toSig(e){let{Err:t,_int:r,_tlv:n}=Pe,o=F(e,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:u,l:f}=n.decode(2,c);if(f.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:r}=Pe,n=t.encode(2,r.encode(e.r)),o=t.encode(2,r.encode(e.s)),s=n+o;return t.encode(48,s)}},ue=BigInt(0),_r=BigInt(1),lf=BigInt(2),So=BigInt(3),_p=BigInt(4);function hf(e,t={}){let r=co("weierstrass",e,t),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i,n:a}=s;Qt(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=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=pf(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(T,w,g){let{x:y,y:C}=w.toAffine(),L=n.toBytes(y);if(ae(g,"isCompressed"),g){f();let I=!n.isOdd(C);return Ot(df(I),L)}else return Ot(Uint8Array.of(4),L,n.toBytes(C))}function d(T){F(T,void 0,"Point");let{publicKey:w,publicKeyUncompressed:g}=u,y=T.length,C=T[0],L=T.subarray(1);if(y===w&&(C===2||C===3)){let I=n.fromBytes(L);if(!n.isValid(I))throw new Error("bad point: is not on curve, wrong x");let S=E(I),B;try{B=n.sqrt(S)}catch(j){let z=j instanceof Error?": "+j.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}f();let R=n.isOdd(B);return(C&1)===1!==R&&(B=n.neg(B)),{x:I,y:B}}else if(y===g&&C===4){let I=n.BYTES,S=n.fromBytes(L.subarray(0,I)),B=n.fromBytes(L.subarray(I,I*2));if(!h(S,B))throw new Error("bad point: is not on curve");return{x:S,y:B}}else throw new Error(`bad point: got length ${y}, expected compressed=${w} or uncompressed=${g}`)}let m=t.toBytes||l,p=t.fromBytes||d;function E(T){let w=n.sqr(T),g=n.mul(w,T);return n.add(n.add(g,n.mul(T,s.a)),s.b)}function h(T,w){let g=n.sqr(w),y=E(T);return n.eql(g,y)}if(!h(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let b=n.mul(n.pow(s.a,So),_p),v=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(b,v)))throw new Error("bad curve params: a or b");function x(T,w,g=!1){if(!n.isValid(w)||g&&n.is0(w))throw new Error(`bad point coordinate ${T}`);return w}function D(T){if(!(T instanceof A))throw new Error("Weierstrass Point expected")}function k(T){if(!c||!c.basises)throw new Error("no endo");return Cp(T,c.basises,o.ORDER)}let O=br((T,w)=>{let{X:g,Y:y,Z:C}=T;if(n.eql(C,n.ONE))return{x:g,y};let L=T.is0();w==null&&(w=L?n.ONE:n.inv(C));let I=n.mul(g,w),S=n.mul(y,w),B=n.mul(C,w);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(B,n.ONE))throw new Error("invZ was invalid");return{x:I,y:S}}),K=br(T=>{if(T.is0()){if(t.allowInfinityPoint&&!n.is0(T.Y))return;throw new Error("bad point: ZERO")}let{x:w,y:g}=T.toAffine();if(!n.isValid(w)||!n.isValid(g))throw new Error("bad point: x or y not field elements");if(!h(w,g))throw new Error("bad point: equation left != right");if(!T.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function _(T,w,g,y,C){return g=new A(n.mul(g.X,T),g.Y,g.Z),w=cn(y,w),g=cn(C,g),w.add(g)}class A{static BASE=new A(s.Gx,s.Gy,n.ONE);static ZERO=new A(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(w,g,y){this.X=x("x",w),this.Y=x("y",g,!0),this.Z=x("z",y),Object.freeze(this)}static CURVE(){return s}static fromAffine(w){let{x:g,y}=w||{};if(!w||!n.isValid(g)||!n.isValid(y))throw new Error("invalid affine point");if(w instanceof A)throw new Error("projective point not allowed");return n.is0(g)&&n.is0(y)?A.ZERO:new A(g,y,n.ONE)}static fromBytes(w){let g=A.fromAffine(p(F(w,void 0,"point")));return g.assertValidity(),g}static fromHex(w){return A.fromBytes(se(w))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,g=!0){return M.createCache(this,w),g||this.multiply(So),this}assertValidity(){K(this)}hasEvenY(){let{y:w}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(w)}equals(w){D(w);let{X:g,Y:y,Z:C}=this,{X:L,Y:I,Z:S}=w,B=n.eql(n.mul(g,S),n.mul(L,C)),R=n.eql(n.mul(y,S),n.mul(I,C));return B&&R}negate(){return new A(this.X,n.neg(this.Y),this.Z)}double(){let{a:w,b:g}=s,y=n.mul(g,So),{X:C,Y:L,Z:I}=this,S=n.ZERO,B=n.ZERO,R=n.ZERO,P=n.mul(C,C),j=n.mul(L,L),z=n.mul(I,I),V=n.mul(C,L);return V=n.add(V,V),R=n.mul(C,I),R=n.add(R,R),S=n.mul(w,R),B=n.mul(y,z),B=n.add(S,B),S=n.sub(j,B),B=n.add(j,B),B=n.mul(S,B),S=n.mul(V,S),R=n.mul(y,R),z=n.mul(w,z),V=n.sub(P,z),V=n.mul(w,V),V=n.add(V,R),R=n.add(P,P),P=n.add(R,P),P=n.add(P,z),P=n.mul(P,V),B=n.add(B,P),z=n.mul(L,I),z=n.add(z,z),P=n.mul(z,V),S=n.sub(S,P),R=n.mul(z,j),R=n.add(R,R),R=n.add(R,R),new A(S,B,R)}add(w){D(w);let{X:g,Y:y,Z:C}=this,{X:L,Y:I,Z:S}=w,B=n.ZERO,R=n.ZERO,P=n.ZERO,j=s.a,z=n.mul(s.b,So),V=n.mul(g,L),X=n.mul(y,I),rt=n.mul(C,S),lt=n.add(g,y),Z=n.add(L,I);lt=n.mul(lt,Z),Z=n.add(V,X),lt=n.sub(lt,Z),Z=n.add(g,C);let ht=n.add(L,S);return Z=n.mul(Z,ht),ht=n.add(V,rt),Z=n.sub(Z,ht),ht=n.add(y,C),B=n.add(I,S),ht=n.mul(ht,B),B=n.add(X,rt),ht=n.sub(ht,B),P=n.mul(j,Z),B=n.mul(z,rt),P=n.add(B,P),B=n.sub(X,P),P=n.add(X,P),R=n.mul(B,P),X=n.add(V,V),X=n.add(X,V),rt=n.mul(j,rt),Z=n.mul(z,Z),X=n.add(X,rt),rt=n.sub(V,rt),rt=n.mul(j,rt),Z=n.add(Z,rt),V=n.mul(X,Z),R=n.add(R,V),V=n.mul(ht,Z),B=n.mul(lt,B),B=n.sub(B,V),V=n.mul(lt,X),P=n.mul(ht,P),P=n.add(P,V),new A(B,R,P)}subtract(w){return this.add(w.negate())}is0(){return this.equals(A.ZERO)}multiply(w){let{endo:g}=t;if(!o.isValidNot0(w))throw new Error("invalid scalar: out of range");let y,C,L=I=>M.cached(this,I,S=>Xe(A,S));if(g){let{k1neg:I,k1:S,k2neg:B,k2:R}=k(w),{p:P,f:j}=L(S),{p:z,f:V}=L(R);C=j.add(V),y=_(g.beta,P,z,I,B)}else{let{p:I,f:S}=L(w);y=I,C=S}return Xe(A,[y,C])[0]}multiplyUnsafe(w){let{endo:g}=t,y=this;if(!o.isValid(w))throw new Error("invalid scalar: out of range");if(w===ue||y.is0())return A.ZERO;if(w===_r)return y;if(M.hasCache(this))return this.multiply(w);if(g){let{k1neg:C,k1:L,k2neg:I,k2:S}=k(w),{p1:B,p2:R}=Nu(A,y,L,S);return _(g.beta,B,R,C,I)}else return M.unsafe(y,w)}toAffine(w){return O(this,w)}isTorsionFree(){let{isTorsionFree:w}=t;return i===_r?!0:w?w(A,this):M.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:w}=t;return i===_r?this:w?w(A,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(w=!0){return ae(w,"isCompressed"),this.assertValidity(),m(A,this,w)}toHex(w=!0){return oe(this.toBytes(w))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=o.BITS,M=new Er(A,t.endo?Math.ceil(N/2):N);return A.BASE.precompute(8),A}function df(e){return Uint8Array.of(e?2:3)}function pf(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Ip(e,t={}){let{Fn:r}=e,n=t.randomBytes||Ee,o=Object.assign(pf(e.Fp,r),{seed:di(r.ORDER)});function s(m){try{let p=r.fromBytes(m);return r.isValidNot0(p)}catch{return!1}}function i(m,p){let{publicKey:E,publicKeyUncompressed:h}=o;try{let b=m.length;return p===!0&&b!==E||p===!1&&b!==h?!1:!!e.fromBytes(m)}catch{return!1}}function a(m=n(o.seed)){return pi(F(m,o.seed,"seed"),r.ORDER)}function c(m,p=!0){return e.BASE.multiply(r.fromBytes(m)).toBytes(p)}function u(m){let{secretKey:p,publicKey:E,publicKeyUncompressed:h}=o;if(!Ve(m)||"_lengths"in r&&r._lengths||p===E)return;let b=F(m,void 0,"key").length;return b===E||b===h}function f(m,p,E=!0){if(u(m)===!0)throw new Error("first arg must be private key");if(u(p)===!1)throw new Error("second arg must be public key");let h=r.fromBytes(m);return e.fromBytes(p).multiply(h).toBytes(E)}let l={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=Sr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:d,Point:e,utils:l,lengths:o})}function mf(e,t,r={}){$e(t),Qt(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes||Ee,o=r.hmac||((g,y)=>Cr(t,g,y)),{Fp:s,Fn:i}=e,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:f,getSharedSecret:l,utils:d,lengths:m}=Ip(e,r),p={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},E=a*lf<s.ORDER;function h(g){let y=a>>_r;return g>y}function b(g,y){if(!i.isValidNot0(y))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return y}function v(){if(E)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function x(g,y){ji(y);let C=m.signature,L=y==="compact"?C:y==="recovered"?C+1:void 0;return F(g,L)}class D{r;s;recovery;constructor(y,C,L){if(this.r=b("r",y),this.s=b("s",C),L!=null){if(v(),![0,1,2,3].includes(L))throw new Error("invalid recovery id");this.recovery=L}Object.freeze(this)}static fromBytes(y,C=p.format){x(y,C);let L;if(C==="der"){let{r:R,s:P}=Pe.toSig(F(y));return new D(R,P)}C==="recovered"&&(L=y[0],C="compact",y=y.subarray(1));let I=m.signature/2,S=y.subarray(0,I),B=y.subarray(I,I*2);return new D(i.fromBytes(S),i.fromBytes(B),L)}static fromHex(y,C){return this.fromBytes(se(y),C)}assertRecovery(){let{recovery:y}=this;if(y==null)throw new Error("invalid recovery id: must be present");return y}addRecoveryBit(y){return new D(this.r,this.s,y)}recoverPublicKey(y){let{r:C,s:L}=this,I=this.assertRecovery(),S=I===2||I===3?C+a:C;if(!s.isValid(S))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let B=s.toBytes(S),R=e.fromBytes(Ot(df((I&1)===0),B)),P=i.inv(S),j=O(F(y,void 0,"msgHash")),z=i.create(-j*P),V=i.create(L*P),X=e.BASE.multiplyUnsafe(z).add(R.multiplyUnsafe(V));if(X.is0())throw new Error("invalid recovery: point at infinify");return X.assertValidity(),X}hasHighS(){return h(this.s)}toBytes(y=p.format){if(ji(y),y==="der")return se(Pe.hexFromSig(this));let{r:C,s:L}=this,I=i.toBytes(C),S=i.toBytes(L);return y==="recovered"?(v(),Ot(Uint8Array.of(this.assertRecovery()),I,S)):Ot(I,S)}toHex(y){return oe(this.toBytes(y))}}let k=r.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");let C=yr(y),L=y.length*8-c;return L>0?C>>BigInt(L):C},O=r.bits2int_modN||function(y){return i.create(k(y))},K=sn(c);function _(g){return Ce("num < 2^"+c,g,ue,K),i.toBytes(g)}function A(g,y){return F(g,void 0,"message"),y?F(t(g),void 0,"prehashed message"):g}function N(g,y,C){let{lowS:L,prehash:I,extraEntropy:S}=zi(C,p);g=A(g,I);let B=O(g),R=i.fromBytes(y);if(!i.isValidNot0(R))throw new Error("invalid private key");let P=[_(R),_(B)];if(S!=null&&S!==!1){let X=S===!0?n(m.secretKey):S;P.push(F(X,void 0,"extraEntropy"))}let j=Ot(...P),z=B;function V(X){let rt=k(X);if(!i.isValidNot0(rt))return;let lt=i.inv(rt),Z=e.BASE.multiply(rt).toAffine(),ht=i.create(Z.x);if(ht===ue)return;let ir=i.create(lt*i.create(z+ht*R));if(ir===ue)return;let Fn=(Z.x===ht?0:2)|Number(Z.y&_r),qr=ir;return L&&h(ir)&&(qr=i.neg(ir),Fn^=1),new D(ht,qr,E?void 0:Fn)}return{seed:j,k2sig:V}}function M(g,y,C={}){let{seed:L,k2sig:I}=N(g,y,C);return bu(t.outputLen,i.BYTES,o)(L,I).toBytes(C.format)}function T(g,y,C,L={}){let{lowS:I,prehash:S,format:B}=zi(L,p);if(C=F(C,void 0,"publicKey"),y=A(y,S),!Ve(g)){let R=g instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+R)}x(g,B);try{let R=D.fromBytes(g,B),P=e.fromBytes(C);if(I&&R.hasHighS())return!1;let{r:j,s:z}=R,V=O(y),X=i.inv(z),rt=i.create(V*X),lt=i.create(j*X),Z=e.BASE.multiplyUnsafe(rt).add(P.multiplyUnsafe(lt));return Z.is0()?!1:i.create(Z.x)===j}catch{return!1}}function w(g,y,C={}){let{prehash:L}=zi(C,p);return y=A(y,L),D.fromBytes(g,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:u,getPublicKey:f,getSharedSecret:l,utils:d,lengths:m,Point:e,sign:M,verify:T,recoverPublicKey:w,Signature:D,hash:t})}var Zi={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Lp={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var gf=BigInt(2);function Bp(e){let t=Zi.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=e*e*e%t,f=u*u*e%t,l=st(f,r,t)*f%t,d=st(l,r,t)*f%t,m=st(d,gf,t)*u%t,p=st(m,o,t)*m%t,E=st(p,s,t)*p%t,h=st(E,a,t)*E%t,b=st(h,c,t)*h%t,v=st(b,a,t)*E%t,x=st(v,r,t)*f%t,D=st(x,i,t)*p%t,k=st(D,n,t)*u%t,O=st(k,gf,t);if(!Yi.eql(Yi.sqr(O),e))throw new Error("Cannot find square root");return O}var Yi=wr(Zi.p,{sqrt:Bp}),Dp=hf(Zi,{Fp:Yi,endo:Lp}),Ir=mf(Dp,Yt);function yf(e,t,r,n){let o=ee.digest(r instanceof Uint8Array?r:r.subarray());if(po(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Ir.verify(t,s,e,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new ln(String(s))});try{return n?.signal?.throwIfAborted(),Ir.verify(t,o.digest,e,{prehash:!1,format:"der"})}catch(s){throw new ln(String(s))}}var Ao=class{type="secp256k1";raw;_key;constructor(t){this._key=wf(t),this.raw=bf(this._key)}toMultihash(){return $t.digest(xe(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return ft.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:wt(this.raw,t.raw)}verify(t,r,n){return yf(this._key,r,t,n)}};function Qi(e){return new Ao(e)}function bf(e){return Ir.Point.fromBytes(e).toBytes()}function wf(e){try{return Ir.Point.fromBytes(e),e}catch(t){throw new ar(String(t))}}function wn(e,t){let{Type:r,Data:n}=Jt.decode(e),o=n??new Uint8Array;switch(r){case ct.RSA:return Wi(o,t);case ct.Ed25519:return Ei(o);case ct.secp256k1:return Qi(o);case ct.ECDSA:return Qs(o);default:throw new Ke}}function xf(e){let{Type:t,Data:r}=Jt.decode(e.digest),n=r??new Uint8Array;switch(t){case ct.Ed25519:return Ei(n);case ct.secp256k1:return Qi(n);case ct.ECDSA:return Qs(n);default:throw new Ke}}function xe(e){return Jt.encode({Type:ct[e.type],Data:e.raw})}var Ef=Symbol.for("nodejs.util.inspect.custom"),Tp=114,xn=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()})`}[vs]=!0;toString(){return this.string==null&&(this.string=ft.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return dt.createV1(Tp,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return wt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return wt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Ef](){return`PeerId(${this.toString()})`}},En=class extends xn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Sn=class extends xn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},An=class extends xn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Rp=2336,vn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=$t.digest(q(this.url))}[Ef](){return`PeerId(${this.url})`}[vs]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return dt.createV1(Rp,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=$(t)),t.toString()===this.toString())}};var Pp=114,Sf=2336;function Lr(e,t){let r;if(e.charAt(0)==="1"||e.charAt(0)==="Q")r=pr(ft.decode(`z${e}`));else{if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return Op(dt.parse(e));if(t==null)throw new Y('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=pr(t.decode(e))}return Af(r)}function Ji(e){if(e.type==="Ed25519")return new Sn({multihash:e.toCID().multihash,publicKey:e});if(e.type==="secp256k1")return new An({multihash:e.toCID().multihash,publicKey:e});if(e.type==="RSA")return new En({multihash:e.toCID().multihash,publicKey:e});throw new Ke}function Af(e){if(Up(e))return new En({multihash:e});if(Np(e))try{let t=xf(e);if(t.type==="Ed25519")return new Sn({multihash:e,publicKey:t});if(t.type==="secp256k1")return new An({multihash:e,publicKey:t})}catch{let r=$(e.digest);return new vn(new URL(r))}throw new jn("Supplied PeerID Multihash is invalid")}function Op(e){if(e?.multihash==null||e.version==null||e.version===1&&e.code!==Pp&&e.code!==Sf)throw new zn("Supplied PeerID CID is invalid");if(e.code===Sf){let t=$(e.multihash.digest);return new vn(new URL(t))}return Af(e.multihash)}function Np(e){return e.code===$t.code}function Up(e){return e.code===ee.code}var Et=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},fe=class extends Error{static name="ValidationError";name="ValidationError"},vo=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Co=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var _o=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let r=this.index,n=t();return n===void 0&&(this.index=r),n}parseWith(t){let r=t();if(this.index===this.input.length)return r}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let r=this.readChar();if(r===t)return r})}readSeparator(t,r,n){return this.readAtomically(()=>{if(!(r>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,r,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,t);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=t,s+=f,s>u||(i+=1,r!==void 0&&i>r))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let r=0;r<t.length;r++){let n=this.readSeparator(".",r,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[r]=n}return t})}readIPv6Addr(){let t=r=>{for(let n=0;n<r.length/2;n++){let 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]=t(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]=t(s.subarray(0,i));return r.set(s.subarray(0,a),16-a),r})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var kp=45,Mp=15,Io=new _o;function vf(e){if(!(e.length>Mp))return Io.new(e).parseWith(()=>Io.readIPv4Addr())}function Cf(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>kp))return Io.new(e).parseWith(()=>Io.readIPv6Addr())}function Lo(e){return!!vf(e)}function _f(e){return!!Cf(e)}function ea(e){return t=>$(t,e)}function ra(e){return t=>q(t,e)}function Br(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function Je(e){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof e=="string"?parseInt(e):e),new Uint8Array(t)}function If(e){let t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let r=q(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=Je(n);return Tt([r,o],r.length+o.length)}function Lf(e){let t=e.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let r=be.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=Je(n);return Tt([r,o],r.length+o.length)}function na(e){let t=e.subarray(0,e.length-2),r=e.subarray(e.length-2),n=$(t,"base32"),o=Br(r);return`${n}:${o}`}var oa=function(e){e=e.toString().trim();let t=new Uint8Array(4);return e.split(/\./g).forEach((r,n)=>{let o=parseInt(r,10);if(isNaN(o)||o<0||o>255)throw new Et("Invalid byte value in IP address");t[n]=o}),t},Bf=function(e){let t=0;e=e.toString().trim();let r=e.split(":",8),n;for(n=0;n<r.length;n++){let s=Lo(r[n]),i;s&&(i=oa(r[n]),r[n]=$(i.subarray(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,$(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(t+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 Et("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},Df=function(e){if(e.byteLength!==4)throw new Et("IPv4 address was incorrect length");let t=[];for(let r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},Tf=function(e){if(e.byteLength!==16)throw new Et("IPv6 address was incorrect length");let t=[];for(let n=0;n<e.byteLength;n+=2){let o=e[n],s=e[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}let r=t.join(":");try{let n=new URL(`http://[${r}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Et(`Invalid IPv6 address "${r}"`)}};function Rf(e){try{let t=new URL(`http://[${e}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new Et(`Invalid IPv6 address "${e}"`)}}var ta=Object.values(Fe).map(e=>e.decoder),Kp=(function(){let e=ta[0].or(ta[1]);return ta.slice(2).forEach(t=>e=e.or(t)),e})();function Pf(e){return Kp.decode(e)}function Of(e){return t=>e.encoder.encode(t)}function Hp(e){if(parseInt(e).toString()!==e)throw new fe("Value must be an integer")}function Fp(e){if(e<0)throw new fe("Value must be a positive integer, or zero")}function Vp(e){return t=>{if(t>e)throw new fe(`Value must be smaller than or equal to ${e}`)}}function $p(...e){return t=>{for(let r of e)r(t)}}var Cn=$p(Hp,Fp,Vp(65535));var yt=-1,sa=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let r;if(typeof t=="string"?r=this.protocolsByName.get(t):r=this.protocolsByCode.get(t),r==null)throw new Co(`Protocol ${t} was unknown`);return r}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(r=>{this.protocolsByName.set(r,t)})}removeProtocol(t){let r=this.protocolsByCode.get(t);r!=null&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),r.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},he=new sa,nm=[{code:4,name:"ip4",size:32,valueToBytes:oa,bytesToValue:Df,validate:e=>{if(!Lo(e))throw new fe(`Invalid IPv4 address "${e}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Je,bytesToValue:Br,validate:Cn},{code:273,name:"udp",size:16,valueToBytes:Je,bytesToValue:Br,validate:Cn},{code:33,name:"dccp",size:16,valueToBytes:Je,bytesToValue:Br,validate:Cn},{code:41,name:"ip6",size:128,valueToBytes:Bf,bytesToValue:Tf,stringToValue:Rf,validate:e=>{if(!_f(e))throw new fe(`Invalid IPv6 address "${e}"`)}},{code:42,name:"ip6zone",size:yt},{code:43,name:"ipcidr",size:8,bytesToValue:ea("base10"),valueToBytes:ra("base10")},{code:53,name:"dns",size:yt},{code:54,name:"dns4",size:yt},{code:55,name:"dns6",size:yt},{code:56,name:"dnsaddr",size:yt},{code:132,name:"sctp",size:16,valueToBytes:Je,bytesToValue:Br,validate:Cn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:yt,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:yt,bytesToValue:ea("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?ra("base58btc")(e):dt.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:na,valueToBytes:If},{code:445,name:"onion3",size:296,bytesToValue:na,valueToBytes:Lf},{code:446,name:"garlic64",size:yt},{code:447,name:"garlic32",size:yt},{code:448,name:"tls"},{code:449,name:"sni",size:yt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:yt,bytesToValue:Of(Zr),valueToBytes:Pf},{code:480,name:"http"},{code:481,name:"http-path",size:yt,stringToValue:e=>`/${decodeURIComponent(e)}`,valueToString:e=>encodeURIComponent(e.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:yt}];nm.forEach(e=>{he.addProtocol(e)});function Nf(e){let t=[],r=0;for(;r<e.length;){let n=ce(e,r),o=he.getProtocol(n),s=et(n),i=om(o,e,r+s),a=0;i>0&&o.size===yt&&(a=et(i));let c=s+a+i,u={code:n,name:o.name,bytes:e.subarray(r,r+c)};if(i>0){let f=r+s+a,l=e.subarray(f,f+i);u.value=o.bytesToValue?.(l)??$(l)}t.push(u),r+=c}return t}function Uf(e){let t=0,r=[];for(let n of e){if(n.bytes==null){let o=he.getProtocol(n.code),s=et(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??q(n.value),a=i.byteLength,o.size===yt&&(c=et(a)));let u=new Uint8Array(s+c+a),f=0;Ie(n.code,u,f),f+=s,i!=null&&(o.size===yt&&(Ie(a,u,f),f+=c),u.set(i,f)),n.bytes=u}r.push(n.bytes),t+=n.bytes.byteLength}return Tt(r,t)}function kf(e){if(e.charAt(0)!=="/")throw new Et('String multiaddr must start with "/"');let t=[],r="protocol",n="",o="";for(let s=1;s<e.length;s++){let i=e.charAt(s);i!=="/"&&(r==="protocol"?o+=e.charAt(s):n+=e.charAt(s));let a=s===e.length-1;if(i==="/"||a){let c=he.getProtocol(o);if(r==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",r="protocol";continue}else if(a)throw new Et(`Component ${o} was missing value`);r="value"}else if(r==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Et(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}t.push(u),n="",o="",r="protocol"}}}if(o!==""&&n!=="")throw new Et("Incomplete multiaddr");return t}function Mf(e){return`/${e.flatMap(t=>{if(t.value==null)return t.name;let r=he.getProtocol(t.code);if(r==null)throw new Et(`Unknown protocol code ${t.code}`);return[t.name,r.valueToString?.(t.value)??t.value]}).join("/")}`}function om(e,t,r){return e.size==null||e.size===0?0:e.size>0?e.size/8:ce(t,r)}var sm=Symbol.for("nodejs.util.inspect.custom"),Sa=Symbol.for("@multiformats/multiaddr");function im(e){if(e==null&&(e="/"),Kf(e))return e.getComponents();if(e instanceof Uint8Array)return Nf(e);if(typeof e=="string")return e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),e===""&&(e="/"),kf(e);if(Array.isArray(e))return e;throw new Et("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Po=class e{[Sa]=!0;#t;#e;#r;constructor(t="/",r={}){this.#t=im(t),r.validate!==!1&&am(this)}get bytes(){return this.#r==null&&(this.#r=Uf(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=Mf(this.#t)),this.#e}toJSON(){return this.toString()}getComponents(){return[...this.#t.map(t=>({...t}))]}encapsulate(t){let r=new e(t);return new e([...this.#t,...r.getComponents()],{validate:!1})}decapsulate(t){let r=t.toString(),n=this.toString(),o=n.lastIndexOf(r);if(o<0)throw new vo(`Address ${this.toString()} does not contain subaddress: ${r}`);return new e(n.slice(0,o),{validate:!1})}decapsulateCode(t){let r;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){r=n;break}return new e(this.#t.slice(0,r),{validate:!1})}equals(t){return wt(this.bytes,t.bytes)}[sm](){return`Multiaddr(${this.toString()})`}};function am(e){e.getComponents().forEach(t=>{let r=he.getProtocol(t.code);t.value!=null&&r.validate?.(t.value)})}function Kf(e){return!!e?.[Sa]}function Pr(e){return new Po(e)}var nt=e=>({match:t=>{let r=t[0];return r==null||r.code!==e||r.value!=null?!1:t.slice(1)}}),H=(e,t)=>({match:r=>{let n=r[0];return n?.code!==e||n.value==null||t!=null&&n.value!==t?!1:r.slice(1)}}),Hf=e=>({match:t=>e.match(t)===!1?t:!1}),G=e=>({match:t=>{let r=e.match(t);return r===!1?t:r}}),_t=(...e)=>({match:t=>{let r;for(let n of e){let o=n.match(t);o!==!1&&(r==null||o.length<r.length)&&(r=o)}return r??!1}}),Q=(...e)=>({match:t=>{for(let r of e){let n=r.match(t);if(n===!1)return!1;t=n}return t}});function ot(...e){function t(o){if(o==null)return!1;let s=o.getComponents();for(let i of e){let a=i.match(s);if(a===!1)return!1;s=a}return s}function r(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matchers:e,matches:r,exactMatch:n}}var cm=H(421),U1=ot(cm),No=H(54),Uo=H(55),ko=H(56),va=H(53),k1=ot(No,G(H(421))),M1=ot(Uo,G(H(421))),K1=ot(ko,G(H(421))),H1=ot(_t(va,ko,No,Uo),G(H(421))),Ff=Q(H(4),G(H(43))),Vf=Q(G(H(42)),H(41),G(H(43))),Ca=_t(Ff,Vf),Or=_t(Ca,va,No,Uo,ko),F1=ot(_t(Ca,Q(_t(va,ko,No,Uo),G(H(421))))),V1=ot(Ff),$1=ot(Vf),W1=ot(Ca),_a=Q(Or,H(6)),_n=Q(Or,H(273)),q1=ot(Q(_a,G(H(421)))),G1=ot(_n),Ia=Q(_n,nt(460),G(H(421))),Mo=Q(_n,nt(461),G(H(421))),um=_t(Ia,Mo),z1=ot(Ia),j1=ot(Mo),Aa=_t(Or,_a,_n,Ia,Mo),$f=_t(Q(Aa,nt(477),G(H(421)))),X1=ot($f),Wf=_t(Q(Aa,nt(478),G(H(421))),Q(Aa,nt(448),G(H(449)),nt(477),G(H(421)))),Y1=ot(Wf),qf=Q(_n,nt(280),G(H(466)),G(H(466)),G(H(421))),Gf=ot(qf),zf=Q(Mo,nt(465),G(H(466)),G(H(466)),G(H(421))),Z1=ot(zf),Oo=_t($f,Wf,Q(_a,G(H(421))),Q(um,G(H(421))),Q(Or,G(H(421))),qf,zf,H(421)),jf=ot(Oo),fm=Q(G(Oo),nt(290),Hf(nt(281)),G(H(421))),Q1=ot(fm),lm=_t(Q(Oo,nt(290),nt(281),G(H(421))),Q(Oo,nt(281),G(H(421))),Q(nt(281),G(H(421)))),Xf=ot(lm),hm=Q(Or,_t(Q(H(6,"80")),Q(H(6),nt(480)),nt(480)),G(H(481)),G(H(421))),J1=ot(hm),dm=Q(Or,_t(Q(H(6,"443")),Q(H(6,"443"),nt(480)),Q(H(6),nt(443)),Q(H(6),nt(448),nt(480)),Q(nt(448),nt(480)),nt(448),nt(443)),G(H(481)),G(H(421))),t2=ot(dm),pm=_t(Q(H(777),G(H(421)))),e2=ot(pm),mm=_t(Q(H(400),G(H(421)))),r2=ot(mm);var It;(function(e){let t;(function(a){a.FIN="FIN",a.STOP_SENDING="STOP_SENDING",a.RESET="RESET",a.FIN_ACK="FIN_ACK"})(t=e.Flag||(e.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=()=>Qe(r)})(t=e.Flag||(e.Flag={}));let n;e.codec=()=>(n==null&&(n=Re((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.flag!=null&&(c.uint32(8),e.Flag.codec().encode(a.flag,c)),a.message!=null&&(c.uint32(18),c.bytes(a.message)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let f={},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let d=a.uint32();switch(d>>>3){case 1:{f.flag=e.Flag.codec().decode(a);break}case 2:{f.message=a.bytes();break}default:{a.skipType(d&7);break}}}return f},function*(a,c,u,f={}){let l=c==null?a.len:a.pos+c;for(;a.pos<l;){let d=a.uint32();switch(d>>>3){case 1:{yield{field:`${u}.flag`,value:e.Flag.codec().decode(a)};break}case 2:{yield{field:`${u}.message`,value:a.bytes()};break}default:{a.skipType(d&7);break}}}})),n);function o(a){return De(a,e.codec())}e.encode=o;function s(a,c){return Be(a,e.codec(),c)}e.decode=s;function i(a,c){return Te(a,e.codec(),c)}e.stream=i})(It||(It={}));var Yf=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],La=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Zf="libp2p+webrtc+v1/",Qf=2*1024*1024,Nr=16*1024;function gm(e=Nr){let t=et(e-et(e)),r=1+et(Object.keys(It.Flag).length-1),n=1,o=e-t-r-n,s=et(o);return t+r+n+s}var Jf=gm();var tl=1e4,Ba="/webrtc",In="/webrtc-signaling/0.0.1";function Da(e){let t=e.getComponents(),r={},n=0;if(t[n]?.name==="ip6zone"&&(r.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"?(r.type=t[n].name,r.host=t[n].value,n++):t[n].name==="dnsaddr"&&(r.type=t[n].name,r.host=`_dnsaddr.${t[n].value}`,n++),(t[n]?.name==="tcp"||t[n]?.name==="udp")&&(r.protocol=t[n].name==="tcp"?"tcp":"udp",r.port=parseInt(`${t[n].value}`),n++),t[n]?.name==="ipcidr"&&(r.type==="ip4"?r.cidr=parseInt(`${t[n].value}`):r.type==="ip6"&&(r.cidr=`${t[n].value}`),n++),r.type==null||r.host==null)throw new Y(`Multiaddr ${e} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return t[n]?.name==="tls"&&t[n+1]?.name==="sni"&&(r.sni=t[n+1].value,n+=2),r}function Ko(){let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e}var Ho=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}},Ur=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Ho(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let r=this.head;this.head=r.next=new Ho(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var Ta=class extends Error{type;code;constructor(t,r){super(t??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function kr(e={}){return ym(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},e)}function ym(e,t){t=t??{};let r=t.onEnd,n=new Ur,o,s,i,a=Ko(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,b)=>{s=v=>{s=null,n.push(v);try{h(e(n))}catch(x){b(x)}return o}}):e(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Ko()})}},u=h=>s!=null?s(h):(n.push(h),o),f=h=>(n=new Ur,s!=null?s({error:h}):(n.push({error:h}),o)),l=h=>{if(i)return o;if(t?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:h})},d=h=>i?o:(i=!0,h!=null?f(h):u({done:!0})),m=()=>(n=new Ur,d(),{done:!0}),p=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:p,push:l,end:d,get readableLength(){return n.size},onEmpty:async h=>{let b=h?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let v,x;b!=null&&(v=new Promise((D,k)=>{x=()=>{k(new Ta)},b.addEventListener("abort",x)}));try{await Promise.race([a.promise,v])}finally{x!=null&&b!=null&&b?.removeEventListener("abort",x)}}},r==null)return o;let E=o;return o={[Symbol.asyncIterator](){return this},next(){return E.next()},throw(h){return E.throw(h),r!=null&&(r(h),r=void 0),{done:!0}},return(){return E.return(),r!=null&&(r(),r=void 0),{done:!0}},push:l,end(h){return E.end(h),r!=null&&(r(h),r=void 0),o},get readableLength(){return E.readableLength},onEmpty:h=>E.onEmpty(h)},o}var Ra=class e extends Error{name="TimeoutError";constructor(t,r){super(t,r),Error.captureStackTrace?.(this,e)}},el=e=>e.reason??new DOMException("This operation was aborted.","AbortError");function Pa(e,t){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=t,a,c,f=new Promise((l,d)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){d(el(i));return}if(i&&(c=()=>{d(el(i))},i.addEventListener("abort",c,{once:!0})),e.then(l,d),r===Number.POSITIVE_INFINITY)return;let m=new Ra;a=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(p){d(p)}return}typeof e.cancel=="function"&&e.cancel(),o===!1?l():o instanceof Error?d(o):(m.message=o??`Promise timed out after ${r} milliseconds`,d(m))},r)}).finally(()=>{f.clear(),c&&i&&i.removeEventListener("abort",c)});return f.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},f}var bm=e=>{let t=e.addEventListener||e.on||e.addListener,r=e.removeEventListener||e.off||e.removeListener;if(!t||!r)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}};function wm(e,t,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=[t].flat(),c=[],{addListener:u,removeListener:f}=bm(e),l=async(...m)=>{let p=r.multiArgs?m:m[0];if(r.filter)try{if(!await r.filter(p))return}catch(E){n(),i(E);return}c.push(p),r.count===c.length&&(n(),s(c))},d=(...m)=>{n(),i(r.rejectionMultiArgs?m:m[0])};n=()=>{for(let m of a)f(m,l);for(let m of r.rejectionEvents)a.includes(m)||f(m,d)};for(let m of a)u(m,l);for(let m of r.rejectionEvents)a.includes(m)||u(m,d);r.signal&&r.signal.addEventListener("abort",()=>{d(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){let s=Pa(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function St(e,t,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=wm(e,t,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var er=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},Fo=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},Vo=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function xm(e){return e.reason}async function de(e,t,r){if(t==null)return e;let n=r?.translateError??xm;if(t.aborted)return e.catch(()=>{}),Promise.reject(n(t));let o;try{return await Promise.race([e,new Promise((s,i)=>{o=()=>{i(n(t))},t.addEventListener("abort",o)})])}finally{o!=null&&t.removeEventListener("abort",o)}}var Em=Math.pow(2,20)*4,Ne=class extends ge{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??Em,this.maxWriteBufferLength=t.maxWriteBufferLength,this.maxMessageSize=t.maxMessageSize,this.readBuffer=new W,this.writeBuffer=new W,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,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",r);let n=o=>{this.onDrainPromise?.reject(o.error??new Vo)};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()),de(this.onDrainPromise.promise,t?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let t=kr(),r=s=>{t.push(s.data)};this.addEventListener("message",r);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",r),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(t){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new jt(`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(r){this.log("failed to send reset to remote - %e",r)}this.dispatchEvent(new Zn(t))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new jt("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 jt("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 jt(`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 jt(`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 cr;this.dispatchEvent(new Qn(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 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;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let t=!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){t=!1;break}let s=this.writeBuffer.sublist(0,o),i=new W(s);this.writeBuffer.consume(s.byteLength);let a=this.sendData(s);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,r,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 Yn(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 Gr(`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 Gr(`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 $o=class extends Ne{remoteAddr;metricPrefix;metrics;constructor(t){super(t),this.metricPrefix=t.metricPrefix??"",this.metrics=t.metrics,this.remoteAddr=t.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(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 St(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 St(this,"drain",{...t,rejectionEvents:["close"]})),await this.sendClose(t),this.onTransportClosed())}};function rl(e){return e==null?!1:typeof e.then=="function"&&typeof e.catch=="function"&&typeof e.finally=="function"}var Wo=class extends ge{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(t,r){super(),this.maConn=t,this.protocol=r.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=t.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(t){let r=this.maConn.send(t);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(t){this.status==="closed"||this.status==="closing"||(this.status="closing",await de(Promise.all([...this.streams].map(async r=>{await r.close(t)})),t?.signal),this.status="closed")}abort(t){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(r=>{r.abort(t)}),this.status="closed")}onTransportClosed(t){this.status="closing";try{[...this.streams].forEach(r=>{r.onTransportClosed(t)})}catch(r){this.abort(r)}this.status="closed"}async createStream(t){if(this.status!=="open")throw new qn;let r=this.onCreateStream({...this.streamOptions,...t});return rl(r)&&(r=await r),this.streams.push(r),this.cleanUpStream(r),r}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 Fo(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:t})}cleanUpStream(t){let r=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",r),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(r=>{this.safeDispatchEvent("stream",{detail:r})}),this.earlyStreams=[]})}};var qo=class extends Ne{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 St(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 St(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 Sm=4194304,Go=class extends Error{static name="UnwrappedError";name="UnwrappedError"},Ln=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Na=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ua=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Am(e){return typeof e?.closeRead=="function"}function vm(e){return typeof e?.close=="function"}function Oa(e){return Am(e)?e.remoteWriteStatus!=="writable"&&e.readBufferLength===0:vm(e)?e.status!=="open":!1}function Cm(e){return e?.addEventListener!=null&&e?.removeEventListener!=null&&e?.send!=null&&e?.push!=null&&e?.log!=null}function _m(e,t){let r=t?.maxBufferSize??Sm,n=new W,o,s=!1;if(!Cm(e))throw new Y("Argument should be a Stream or a Multiaddr");let i=f=>{if(n.append(f.data),n.byteLength>r){let l=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${l} > ${r}`))}o?.resolve()};e.addEventListener("message",i);let a=f=>{f.error!=null?o?.reject(f.error):o?.resolve()};e.addEventListener("close",a);let c=()=>{o?.resolve()};e.addEventListener("remoteCloseWrite",c);let u={readBuffer:n,async read(f){if(s===!0)throw new Go("Stream was unwrapped");if(Oa(e)){if(n.byteLength===0&&f?.bytes==null)return null;if(f?.bytes!=null&&n.byteLength<f.bytes)throw e.log.error("closed after reading %d/%d bytes",n.byteLength,f.bytes),new er(`Unexpected EOF - stream closed after reading ${n.byteLength}/${f.bytes} bytes`)}let l=f?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=l){o.resolve();break}if(await de(o.promise,f?.signal),Oa(e)){if(n.byteLength===0&&f?.bytes==null)return null;break}o=Promise.withResolvers()}let d=f?.bytes??n.byteLength;if(n.byteLength<d){if(Oa(e))throw e.log.error("closed while reading %d/%d bytes",n.byteLength,d),new er(`Unexpected EOF - stream closed while reading ${n.byteLength}/${d} bytes`);return u.read(f)}let m=n.sublist(0,d);return n.consume(d),m},async write(f,l){if(s===!0)throw new Go("Stream was unwrapped");e.send(f)||await St(e,"drain",{signal:l?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,e.removeEventListener("message",i),e.removeEventListener("close",a),e.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(e.log("stream unwrapped with %d unread bytes",n.byteLength),e.push(n))),e}};return u}function zo(e,t={}){let r=_m(e,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=et(t.maxDataLength));let n=t?.lengthDecoder??ce,o=t?.lengthEncoder??go;return{async read(i){let a=-1,c=new W;for(;;){let f=await r.read({...i,bytes:1});if(f==null)break;c.append(f);try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Ln("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ua(`Message length length too long - ${c.byteLength} > ${t.maxLengthLength}`);if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Na(`Message length too long - ${a} > ${t.maxDataLength}`);let u=await r.read({...i,bytes:a});if(u==null)throw e.log.error("tried to read %d bytes but the stream closed",a),new er(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(u.byteLength!==a)throw e.log.error("read %d/%d bytes before the stream closed",u.byteLength,a),new er(`Unexpected EOF - read ${u.byteLength}/${a} bytes before the stream closed`);return u},async write(i,a){await r.write(new W(o(i.byteLength),i),a)},async writeV(i,a){let c=new W(...i.flatMap(u=>[o(u.byteLength),u]));await r.write(c,a)},unwrap(){return r.unwrap()}}}function jo(e,t){let r=zo(e,t),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 Im=1024*1024*4,Lm=1024*1024*4,Xo=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(t={}){this.buffer=new W,this.maxBufferSize=t.maxBufferSize??Im,this.maxDataLength=t.maxDataLength??Lm,this.lengthDecoder=t.lengthDecoder??ce,this.encodingLength=t.encodingLength??et}*decode(t){if(this.buffer.append(t),this.buffer.byteLength>this.maxBufferSize)throw new Y(`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 Ln("Invalid message length");let n=this.encodingLength(r),o=n+r;if(this.buffer.byteLength>=o){let s=this.buffer.sublist(n,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}};var Yo=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Mr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Zo=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Bn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Qo(e){return e[Symbol.asyncIterator]!=null}function nl(e,t){if(e.byteLength>t)throw new Mr("Message length too long")}var ts=e=>{let t=et(e),r=it(t);return go(e,r),ts.bytes=t,r};ts.bytes=0;function Dn(e,t){t=t??{};let r=t.lengthEncoder??ts,n=t?.maxDataLength??4194304;function*o(s){nl(s,n);let i=r(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Qo(e)?(async function*(){for await(let s of e)yield*o(s)})():(function*(){for(let s of e)yield*o(s)})()}Dn.single=(e,t)=>{t=t??{};let r=t.lengthEncoder??ts,n=t?.maxDataLength??4194304;return nl(e,n),new W(r(e.byteLength),e)};var rr;(function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"})(rr||(rr={}));var ka=e=>{let t=ce(e);return ka.bytes=et(t),t};ka.bytes=0;function Tn(e,t){let r=new W,n=rr.LENGTH,o=-1,s=t?.lengthDecoder??ka,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===rr.LENGTH)try{if(o=s(r),o<0)throw new Yo("Invalid message length");if(o>a)throw new Mr("Message length too long");let u=s.bytes;r.consume(u),t?.onLength!=null&&t.onLength(o),n=rr.DATA}catch(u){if(u instanceof RangeError){if(r.byteLength>i)throw new Zo("Message length length too long");break}throw u}if(n===rr.DATA){if(r.byteLength<o)break;let u=r.sublist(0,o);r.consume(o),t?.onData!=null&&t.onData(u),yield u,n=rr.LENGTH}}}return Qo(e)?(async function*(){for await(let u of e)r.append(u),yield*c();if(r.byteLength>0)throw new Bn("Unexpected end of input")})():(function*(){for(let u of e)r.append(u),yield*c();if(r.byteLength>0)throw new Bn("Unexpected end of input")})()}Tn.fromReader=(e,t)=>{let r=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await e.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 Tn(n,{...t??{},onLength:s=>{r=s}})};var ol=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},Tm=(function(){function e(t,r,n){this.name=t,this.version=r,this.os=n,this.type="browser"}return e})();var Rm=(function(){function e(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return e})();var Pm=(function(){function e(t,r,n,o){this.name=t,this.version=r,this.os=n,this.bot=o,this.type="bot-device"}return e})();var Om=(function(){function e(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return e})();var Nm=(function(){function e(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return e})();var Um=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,km=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,sl=3,Mm=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",Um]],il=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function cl(e){return e?al(e):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Nm:typeof navigator<"u"?al(navigator.userAgent):Fm()}function Km(e){return e!==""&&Mm.reduce(function(t,r){var n=r[0],o=r[1];if(t)return t;var s=o.exec(e);return!!s&&[n,s]},!1)}function al(e){var t=Km(e);if(!t)return null;var r=t[0],n=t[1];if(r==="searchbot")return new Om;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<sl&&(o=ol(ol([],o,!0),Vm(sl-o.length),!0)):o=[];var s=o.join("."),i=Hm(e),a=km.exec(e);return a&&a[1]?new Pm(r,s,i,a[1]):new Tm(r,s,i)}function Hm(e){for(var t=0,r=il.length;t<r;t++){var n=il[t],o=n[0],s=n[1],i=s.exec(e);if(i)return o}return null}function Fm(){var e=typeof process<"u"&&process.version;return e?new Rm(process.version.slice(1)):null}function Vm(e){for(var t=[],r=0;r<e;r++)t.push("0");return t}var ul=cl(),es=ul!=null&&ul.name==="firefox";async function Ma(e){return e=e??{},typeof e=="function"&&(e=await e()),e.iceServers=e.iceServers??Yf.map(t=>({urls:[t]})),e}var fl=(e=32)=>Zf+[...Array(e)].map(()=>La.at(Math.floor(Math.random()*La.length))).join("");var Ka=class extends qo{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(t){super({...t,maxMessageSize:(t.maxMessageSize??Nr)-Jf}),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=kr(),this.maxBufferedAmount=t.maxBufferedAmount??Qf,this.finAckTimeout=t.finAckTimeout??tl,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 Tn(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),St(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 jt(`Invalid datachannel state - ${this.channel.readyState}`);if(this.log.trace('sending message, channel state "%s"',this.channel.readyState),es){this.channel.send(t.subarray());return}for(let r of t)this.channel.send(r)}sendData(t){return this.channel.readyState!=="open"?{sentBytes:0,canSendMore:!1}:(this._sendMessage(Dn.single(It.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(It.Flag.RESET),this.receivedFinAck?.reject(t)}catch(r){this.log.error("failed to send reset - %e",r)}}async sendCloseWrite(t){this._sendFlag(It.Flag.FIN),t?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let r=t?.signal??AbortSignal.timeout(this.finAckTimeout),n=[St(this.channel,"close",{signal:r}),St(this.channel,"error",{signal:r})];await Promise.any([de(this.receivedFinAck.promise,r),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(t){this._sendFlag(It.Flag.STOP_SENDING),t?.signal?.throwIfAborted()}processIncomingProtobuf(t){let r=It.decode(t);r.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new W(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===It.Flag.FIN&&(this._sendFlag(It.Flag.FIN_ACK),this.onRemoteCloseWrite()),r.flag===It.Flag.RESET&&(this.receivedFinAck?.reject(new cr("The stream was reset")),this.onRemoteReset()),r.flag===It.Flag.STOP_SENDING&&this.onRemoteCloseRead(),r.flag===It.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 r=It.encode({flag:t}),n=Dn.single(r);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 Rn(e){let{channel:t,direction:r,isHandshake:n}=e;return new Ka({...e,id:`${t.id}`,log:e.log.newScope(`${n===!0?"handshake":r}:${t.id}`),protocol:""})}var Ue=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??Ba,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 Ha(t,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,earlyDataChannels:this.earlyDataChannels})}},Ha=class extends Wo{peerConnection;dataChannelOptions;constructor(t,r){super(t,{...r,name:"muxer"}),this.peerConnection=r.peerConnection,this.protocol=r.protocol??Ba,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(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 r=Rn({...this.streamOptions,...this.dataChannelOptions,channel:t,direction:"inbound",log:this.log});this.onRemoteStream(r)}async onCreateStream(t){let r=this.peerConnection.createDataChannel("",{});return this.log("open channel %d for protocol %s",r.id,t?.protocol),Rn({...t,...this.dataChannelOptions,channel:r,direction:"outbound",log:this.log})}onData(){}};var Fa=class extends $o{peerConnection;constructor(t){super(t),this.peerConnection=t.peerConnection;let r=t.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change %s initial state %s",this.peerConnection.connectionState,r),(this.peerConnection.connectionState==="disconnected"||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(){}},Pn=e=>new Fa(e);var rs=globalThis.RTCPeerConnection,ns=globalThis.RTCSessionDescription,ll=globalThis.RTCIceCandidate;var kt=class extends Event{type;detail;constructor(t,r){super(t),this.type=t,this.detail=r}};var ke=class extends Error{constructor(t){super(`WebRTC transport error: ${t}`),this.name="WebRTCTransportError"}},Ft=class extends ke{constructor(t="SDP handshake failed"){super(t),this.name="SDPHandshakeFailedError"}};var os=class extends ke{constructor(t,r){super(`Invalid fingerprint "${t}" within ${r}`),this.name="WebRTC/InvalidFingerprintError"}};var ss=class extends ke{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},is=class extends ke{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 Nt;(function(e){let t;(function(a){a.SDP_OFFER="SDP_OFFER",a.SDP_ANSWER="SDP_ANSWER",a.ICE_CANDIDATE="ICE_CANDIDATE"})(t=e.Type||(e.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=()=>Qe(r)})(t=e.Type||(e.Type={}));let n;e.codec=()=>(n==null&&(n=Re((a,c,u={})=>{u.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),e.Type.codec().encode(a.type,c)),a.data!=null&&(c.uint32(18),c.string(a.data)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let f={},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let d=a.uint32();switch(d>>>3){case 1:{f.type=e.Type.codec().decode(a);break}case 2:{f.data=a.string();break}default:{a.skipType(d&7);break}}}return f},function*(a,c,u,f={}){let l=c==null?a.len:a.pos+c;for(;a.pos<l;){let d=a.uint32();switch(d>>>3){case 1:{yield{field:`${u}.type`,value:e.Type.codec().decode(a)};break}case 2:{yield{field:`${u}.data`,value:a.string()};break}default:{a.skipType(d&7);break}}}})),n);function o(a){return De(a,e.codec())}e.encode=o;function s(a,c){return Be(a,e.codec(),c)}e.decode=s;function i(a,c){return Te(a,e.codec(),c)}e.stream=i})(Nt||(Nt={}));var as=async(e,t,r)=>{try{let n=Promise.withResolvers();for($m(e,n);;){let o=await Promise.race([n.promise,t.read({signal:r.signal})]);if(o==null){r.signal?.throwIfAborted();break}if(o.type!==Nt.Type.ICE_CANDIDATE)throw new Xn("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){r.onProgress?.(new kt("webrtc:end-of-ice-candidates")),r.log.trace("end-of-candidates received");continue}let i=new ll(s);r.log.trace("%s received new ICE candidate %o",r.direction,s);try{r.onProgress?.(new kt("webrtc:add-ice-candidate",i.candidate)),await e.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&&e.connectionState!=="connected")throw n}};function $m(e,t){if(e.connectionState==="connected"){t.resolve();return}e.onconnectionstatechange=r=>{switch(e.connectionState){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new Wn(`RTCPeerConnection connection state became "${e.connectionState}"`));break;default:break}}}function cs(e){let t;for(let r of e.getComponents())r.name==="p2p"&&(t=Lr(r.value??""));if(t==null)throw new Gn("Remote peerId must be present in multiaddr");return t}async function hl({rtcConfiguration:e,dataChannel:t,signal:r,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:u}){let{circuitAddress:f,targetPeer:l}=dl(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing circuit address: %a",f);let d=s.getConnections(l),m;d.length===0?(u?.(new kt("webrtc:dial-relay")),m=await i.dial(f,{signal:r,onProgress:u})):(u?.(new kt("webrtc:reuse-relay-connection")),m=d[0]),u?.(new kt("webrtc:open-signaling-stream"));let p=await m.newStream(In,{signal:r,runOnLimitedConnection:!0}),E=jo(p).pb(Nt),h=new rs(e);h.addEventListener("connectionstatechange",()=>{switch(h.connectionState){case"closed":h.close();break;default:break}});let b=new Ue({peerConnection:h,dataChannelOptions:t});try{let v=h.createDataChannel("init");h.onicecandidate=({candidate:O})=>{if(h.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 K=JSON.stringify(O?.toJSON()??null);a.trace("initiator sending ICE candidate %o",O),E.write({type:Nt.Type.ICE_CANDIDATE,data:K},{signal:r}).catch(_=>{a.error("error sending ICE candidate - %e",_)})},h.onicecandidateerror=O=>{a.error("initiator ICE candidate error",O)};let x=await h.createOffer().catch(O=>{throw a.error("could not execute createOffer - %e",O),new Ft("Failed to set createOffer")});a.trace("initiator send SDP offer %s",x.sdp),u?.(new kt("webrtc:send-sdp-offer")),await E.write({type:Nt.Type.SDP_OFFER,data:x.sdp},{signal:r}),await h.setLocalDescription(x).catch(O=>{throw a.error("could not execute setLocalDescription - %e",O),new Ft("Failed to set localDescription")}),u?.(new kt("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let D=await E.read({signal:r});if(D.type!==Nt.Type.SDP_ANSWER)throw new Ft("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",D.data);let k=new ns({type:"answer",sdp:D.data});return await h.setRemoteDescription(k).catch(O=>{throw a.error("could not execute setRemoteDescription - %e",O),new Ft("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),u?.(new kt("webrtc:read-ice-candidates")),await as(h,E,{direction:"initiator",signal:r,log:a,onProgress:u}),a.trace("initiator connected"),v.readyState!=="open"&&(a.trace("wait for init channel to open"),await St(v,"open",{signal:r})),a.trace("closing init channel"),v.close(),a.trace("waiting for init channel to close"),await St(v,"close",{signal:r}),u?.(new kt("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await p.close({signal:r}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:h,muxerFactory:b}}catch(v){throw a.error("outgoing signaling error - %e",v),h.close(),p.abort(v),v}finally{h.onicecandidate=null,h.onicecandidateerror=null}}var pl=ot(jf.matchers[0],nt(290)),us=class e extends ge{transportManager;shutdownController;events;constructor(t,r){super(),this.transportManager=t.transportManager,this.events=t.events,this.shutdownController=r.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(t){t.detail.getAddrs().filter(n=>pl.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(t=>!(t instanceof e)).map(t=>t.getAddrs().filter(r=>pl.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 ml(e,t,{peerConnection:r,signal:n,log:o}){o.trace("new inbound signaling stream");let s=jo(e).pb(Nt);try{r.onicecandidate=({candidate:l})=>{if(r.connectionState==="connected"){o.trace("ignore new ice candidate as peer connection is already connected");return}if(l==null||l?.candidate===""){o.trace("recipient detected end of ICE candidates");return}let d=JSON.stringify(l?.toJSON()??null);o.trace("recipient sending ICE candidate %s",d),s.write({type:Nt.Type.ICE_CANDIDATE,data:d},{signal:n}).catch(m=>{o.error("error sending ICE candidate - %e",m)})},o.trace("recipient read SDP offer");let c=await s.read({signal:n});if(c.type!==Nt.Type.SDP_OFFER)throw new Ft(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let u=new ns({type:"offer",sdp:c.data});await r.setRemoteDescription(u).catch(l=>{throw o.error("could not execute setRemoteDescription - %e",l),new Ft("Failed to set remoteDescription")});let f=await r.createAnswer().catch(l=>{throw o.error("could not execute createAnswer - %e",l),new Ft("Failed to create answer")});o.trace("recipient send SDP answer %s",f.sdp),await s.write({type:Nt.Type.SDP_ANSWER,data:f.sdp},{signal:n}),await r.setLocalDescription(f).catch(l=>{throw o.error("could not execute setLocalDescription - %e",l),new Ft("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await as(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",t.remoteAddr,c),r.close(),c;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",t.remoteAddr,c)}let i=cs(t.remoteAddr),a=Pr(`/webrtc/p2p/${i}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:i}}var fs=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,r={}){this.components=t,this.init=r,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,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"})})}[Jn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[fr]=["@libp2p/transport"];[Lc]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(In,(t,r)=>{let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(t,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(In),this._started=!1}createListener(t){return new us(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(Xf.exactMatch)}dialFilter(t){return this.listenFilter(t)}async dial(t,r){this.log.trace("dialing address: %a",t);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await hl({rtcConfiguration:await Ma(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:t,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=Pn({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:cs(t),muxerFactory:s,onProgress:r.onProgress,signal:r.signal});return this._closeOnShutdown(o,i),a}async _onProtocol(t,r,n){let o=new rs(await Ma(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{switch(o.connectionState){case"closed":o.close();break;default:break}});let s=new Ue({peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i,remotePeer:a}=await ml(t,r,{peerConnection:o,signal:n,log:this.log});await t.close({signal:n});let c=Pn({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,r){let n=()=>{r.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 dl(e){let t=e.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(t==null)throw new Y("Destination peer id was missing");return{circuitAddress:Pr(e.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:Lr(t)}}var Kr=!!globalThis.process?.env?.DUMP_SESSION_KEYS,Va=16;function Wm(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function ls(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function hs(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function bt(e,t,r=""){let n=Wm(e),o=e?.length,s=t!==void 0;if(!n||s&&o!==t){let i=r&&`"${r}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return e}function $a(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function gl(e,t){bt(e,void 0,"output");let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function pe(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function me(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function qm(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var Gm=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function yl(e,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(e,t)}function bl(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}var Wa=(e,t)=>{function r(n,...o){if(bt(n,void 0,"key"),!Gm)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){let f=o[0];bt(f,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let s=e.tagLength;s&&o[1]!==void 0&&bt(o[1],void 0,"AAD");let i=t(n,...o),a=(f,l)=>{if(l!==void 0){if(f!==2)throw new Error("cipher output not supported");bt(l,void 0,"output")}},c=!1;return{encrypt(f,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,bt(f),a(i.encrypt.length,l),i.encrypt(f,l)},decrypt(f,l){if(bt(f),s&&f.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,l),i.decrypt(f,l)}}}return Object.assign(r,e),r};function qa(e,t,r=!0){if(t===void 0)return new Uint8Array(e);if(t.length!==e)throw new Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(r&&!zm(t))throw new Error("invalid output, must be aligned");return t}function wl(e,t,r){ls(r);let n=new Uint8Array(16),o=qm(n);return o.setBigUint64(0,BigInt(t),r),o.setBigUint64(8,BigInt(e),r),n}function zm(e){return e.byteOffset%4===0}function Hr(e){return Uint8Array.from(e)}var El=e=>Uint8Array.from(e.split(""),t=>t.charCodeAt(0)),jm=El("expand 16-byte k"),Xm=El("expand 32-byte k"),Ym=pe(jm),Zm=pe(Xm);function U(e,t){return e<<t|e>>>32-t}function Ga(e){return e.byteOffset%4===0}var ds=64,Qm=16,Sl=2**32-1,xl=Uint32Array.of();function Jm(e,t,r,n,o,s,i,a){let c=o.length,u=new Uint8Array(ds),f=pe(u),l=Ga(o)&&Ga(s),d=l?pe(o):xl,m=l?pe(s):xl;for(let p=0;p<c;i++){if(e(t,r,n,f,i,a),i>=Sl)throw new Error("arx: counter overflow");let E=Math.min(ds,c-p);if(l&&E===ds){let h=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let b=0,v;b<Qm;b++)v=h+b,m[v]=d[v]^f[b];p+=ds;continue}for(let h=0,b;h<E;h++)b=p+h,s[b]=o[b]^u[h];p+=E}}function za(e,t){let{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=yl({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!="function")throw new Error("core must be a function");return hs(o),hs(i),ls(s),ls(r),(a,c,u,f,l=0)=>{bt(a,void 0,"key"),bt(c,void 0,"nonce"),bt(u,void 0,"data");let d=u.length;if(f===void 0&&(f=new Uint8Array(d)),bt(f,void 0,"output"),hs(l),l<0||l>=Sl)throw new Error("arx: counter overflow");if(f.length<d)throw new Error(`arx: output (${f.length}) is shorter than data (${d})`);let m=[],p=a.length,E,h;if(p===32)m.push(E=Hr(a)),h=Zm;else if(p===16&&r)E=new Uint8Array(32),E.set(a),E.set(a,16),h=Ym,m.push(E);else throw bt(a,32,"arx key"),new Error("invalid key size");Ga(c)||m.push(c=Hr(c));let b=pe(E);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,b,pe(c.subarray(0,16)),b),c=c.subarray(16)}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,m.push(c)}let x=pe(c);return Jm(e,h,b,x,u,f,l,i),me(...m),f}}function At(e,t){return e[t++]&255|(e[t++]&255)<<8}var ja=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;constructor(t){t=Hr(bt(t,32,"key"));let r=At(t,0),n=At(t,2),o=At(t,4),s=At(t,6),i=At(t,8),a=At(t,10),c=At(t,12),u=At(t,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|u<<8)&8191,this.r[9]=u>>>5&127;for(let f=0;f<8;f++)this.pad[f]=At(t,16+2*f)}process(t,r,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],u=i[2],f=i[3],l=i[4],d=i[5],m=i[6],p=i[7],E=i[8],h=i[9],b=At(t,r+0),v=At(t,r+2),x=At(t,r+4),D=At(t,r+6),k=At(t,r+8),O=At(t,r+10),K=At(t,r+12),_=At(t,r+14),A=s[0]+(b&8191),N=s[1]+((b>>>13|v<<3)&8191),M=s[2]+((v>>>10|x<<6)&8191),T=s[3]+((x>>>7|D<<9)&8191),w=s[4]+((D>>>4|k<<12)&8191),g=s[5]+(k>>>1&8191),y=s[6]+((k>>>14|O<<2)&8191),C=s[7]+((O>>>11|K<<5)&8191),L=s[8]+((K>>>8|_<<8)&8191),I=s[9]+(_>>>5|o),S=0,B=S+A*a+N*(5*h)+M*(5*E)+T*(5*p)+w*(5*m);S=B>>>13,B&=8191,B+=g*(5*d)+y*(5*l)+C*(5*f)+L*(5*u)+I*(5*c),S+=B>>>13,B&=8191;let R=S+A*c+N*a+M*(5*h)+T*(5*E)+w*(5*p);S=R>>>13,R&=8191,R+=g*(5*m)+y*(5*d)+C*(5*l)+L*(5*f)+I*(5*u),S+=R>>>13,R&=8191;let P=S+A*u+N*c+M*a+T*(5*h)+w*(5*E);S=P>>>13,P&=8191,P+=g*(5*p)+y*(5*m)+C*(5*d)+L*(5*l)+I*(5*f),S+=P>>>13,P&=8191;let j=S+A*f+N*u+M*c+T*a+w*(5*h);S=j>>>13,j&=8191,j+=g*(5*E)+y*(5*p)+C*(5*m)+L*(5*d)+I*(5*l),S+=j>>>13,j&=8191;let z=S+A*l+N*f+M*u+T*c+w*a;S=z>>>13,z&=8191,z+=g*(5*h)+y*(5*E)+C*(5*p)+L*(5*m)+I*(5*d),S+=z>>>13,z&=8191;let V=S+A*d+N*l+M*f+T*u+w*c;S=V>>>13,V&=8191,V+=g*a+y*(5*h)+C*(5*E)+L*(5*p)+I*(5*m),S+=V>>>13,V&=8191;let X=S+A*m+N*d+M*l+T*f+w*u;S=X>>>13,X&=8191,X+=g*c+y*a+C*(5*h)+L*(5*E)+I*(5*p),S+=X>>>13,X&=8191;let rt=S+A*p+N*m+M*d+T*l+w*f;S=rt>>>13,rt&=8191,rt+=g*u+y*c+C*a+L*(5*h)+I*(5*E),S+=rt>>>13,rt&=8191;let lt=S+A*E+N*p+M*m+T*d+w*l;S=lt>>>13,lt&=8191,lt+=g*f+y*u+C*c+L*a+I*(5*h),S+=lt>>>13,lt&=8191;let Z=S+A*h+N*E+M*p+T*m+w*d;S=Z>>>13,Z&=8191,Z+=g*l+y*f+C*u+L*c+I*a,S+=Z>>>13,Z&=8191,S=(S<<2)+S|0,S=S+B|0,B=S&8191,S=S>>>13,R+=S,s[0]=B,s[1]=R,s[2]=P,s[3]=j,s[4]=z,s[5]=V,s[6]=X,s[7]=rt,s[8]=lt,s[9]=Z}finalize(){let{h:t,pad:r}=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]+r[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+r[a]|0)+(i>>>16)|0,t[a]=i&65535;me(n)}update(t){$a(this),bt(t),t=Hr(t);let{buffer:r,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}r.set(t.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(){me(this.h,this.r,this.buffer,this.pad)}digestInto(t){$a(this),gl(t,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++)t[s++]=n[i]>>>0,t[s++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}};function t0(e){let t=(n,o)=>e(o).update(n).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>e(n),t}var Al=t0(e=>new ja(e));function _l(e,t,r,n,o,s=20){let i=e[0],a=e[1],c=e[2],u=e[3],f=t[0],l=t[1],d=t[2],m=t[3],p=t[4],E=t[5],h=t[6],b=t[7],v=o,x=r[0],D=r[1],k=r[2],O=i,K=a,_=c,A=u,N=f,M=l,T=d,w=m,g=p,y=E,C=h,L=b,I=v,S=x,B=D,R=k;for(let j=0;j<s;j+=2)O=O+N|0,I=U(I^O,16),g=g+I|0,N=U(N^g,12),O=O+N|0,I=U(I^O,8),g=g+I|0,N=U(N^g,7),K=K+M|0,S=U(S^K,16),y=y+S|0,M=U(M^y,12),K=K+M|0,S=U(S^K,8),y=y+S|0,M=U(M^y,7),_=_+T|0,B=U(B^_,16),C=C+B|0,T=U(T^C,12),_=_+T|0,B=U(B^_,8),C=C+B|0,T=U(T^C,7),A=A+w|0,R=U(R^A,16),L=L+R|0,w=U(w^L,12),A=A+w|0,R=U(R^A,8),L=L+R|0,w=U(w^L,7),O=O+M|0,R=U(R^O,16),C=C+R|0,M=U(M^C,12),O=O+M|0,R=U(R^O,8),C=C+R|0,M=U(M^C,7),K=K+T|0,I=U(I^K,16),L=L+I|0,T=U(T^L,12),K=K+T|0,I=U(I^K,8),L=L+I|0,T=U(T^L,7),_=_+w|0,S=U(S^_,16),g=g+S|0,w=U(w^g,12),_=_+w|0,S=U(S^_,8),g=g+S|0,w=U(w^g,7),A=A+N|0,B=U(B^A,16),y=y+B|0,N=U(N^y,12),A=A+N|0,B=U(B^A,8),y=y+B|0,N=U(N^y,7);let P=0;n[P++]=i+O|0,n[P++]=a+K|0,n[P++]=c+_|0,n[P++]=u+A|0,n[P++]=f+N|0,n[P++]=l+M|0,n[P++]=d+T|0,n[P++]=m+w|0,n[P++]=p+g|0,n[P++]=E+y|0,n[P++]=h+C|0,n[P++]=b+L|0,n[P++]=v+I|0,n[P++]=x+S|0,n[P++]=D+B|0,n[P++]=k+R|0}function e0(e,t,r,n){let o=e[0],s=e[1],i=e[2],a=e[3],c=t[0],u=t[1],f=t[2],l=t[3],d=t[4],m=t[5],p=t[6],E=t[7],h=r[0],b=r[1],v=r[2],x=r[3];for(let k=0;k<20;k+=2)o=o+c|0,h=U(h^o,16),d=d+h|0,c=U(c^d,12),o=o+c|0,h=U(h^o,8),d=d+h|0,c=U(c^d,7),s=s+u|0,b=U(b^s,16),m=m+b|0,u=U(u^m,12),s=s+u|0,b=U(b^s,8),m=m+b|0,u=U(u^m,7),i=i+f|0,v=U(v^i,16),p=p+v|0,f=U(f^p,12),i=i+f|0,v=U(v^i,8),p=p+v|0,f=U(f^p,7),a=a+l|0,x=U(x^a,16),E=E+x|0,l=U(l^E,12),a=a+l|0,x=U(x^a,8),E=E+x|0,l=U(l^E,7),o=o+u|0,x=U(x^o,16),p=p+x|0,u=U(u^p,12),o=o+u|0,x=U(x^o,8),p=p+x|0,u=U(u^p,7),s=s+f|0,h=U(h^s,16),E=E+h|0,f=U(f^E,12),s=s+f|0,h=U(h^s,8),E=E+h|0,f=U(f^E,7),i=i+l|0,b=U(b^i,16),d=d+b|0,l=U(l^d,12),i=i+l|0,b=U(b^i,8),d=d+b|0,l=U(l^d,7),a=a+c|0,v=U(v^a,16),m=m+v|0,c=U(c^m,12),a=a+c|0,v=U(v^a,8),m=m+v|0,c=U(c^m,7);let D=0;n[D++]=o,n[D++]=s,n[D++]=i,n[D++]=a,n[D++]=h,n[D++]=b,n[D++]=v,n[D++]=x}var r0=za(_l,{counterRight:!1,counterLength:4,allowShortKeys:!1}),n0=za(_l,{counterRight:!1,counterLength:8,extendNonceFn:e0,allowShortKeys:!1});var o0=new Uint8Array(16),vl=(e,t)=>{e.update(t);let r=t.length%16;r&&e.update(o0.subarray(r))},s0=new Uint8Array(32);function Cl(e,t,r,n,o){o!==void 0&&bt(o,void 0,"AAD");let s=e(t,r,s0),i=wl(n.length,o?o.length:0,!0),a=Al.create(s);o&&vl(a,o),vl(a,n),a.update(i);let c=a.digest();return me(s,i),c}var Il=e=>(t,r,n)=>({encrypt(s,i){let a=s.length;i=qa(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);e(t,r,c,c,1);let u=Cl(e,t,r,c,n);return i.set(u,a),me(u),i},decrypt(s,i){i=qa(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),u=Cl(e,t,r,a,n);if(!bl(c,u))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),e(t,r,i,i,1),me(u),i}}),Xa=Wa({blockSize:64,nonceLength:12,tagLength:16},Il(r0)),r6=Wa({blockSize:64,nonceLength:24,tagLength:16},Il(n0));function Bl(e,t,r){return $e(e),r===void 0&&(r=new Uint8Array(e.outputLen)),Cr(e,r,t)}var Ya=Uint8Array.of(0),Ll=Uint8Array.of();function Dl(e,t,r,n=32){$e(e),Kt(n,"length");let o=e.outputLen;if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);r===void 0?r=Ll:F(r,void 0,"info");let i=new Uint8Array(s*o),a=Cr.create(e,t),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let f=0;f<s;f++)Ya[0]=f+1,c.update(f===0?Ll:u).update(r).update(Ya).digestInto(u),i.set(u,o*f),a._cloneInto(c);return a.destroy(),c.destroy(),Wt(u,Ya),i.slice(0,n)}var Za={hashSHA256(e){return Yt(e.subarray())},getHKDF(e,t){let r=Bl(Yt,t,e),o=Dl(Yt,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 e=fn.utils.randomSecretKey();return{publicKey:fn.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed(e){return{publicKey:fn.getPublicKey(e),privateKey:e}},generateX25519SharedKey(e,t){return fn.getSharedSecret(e.subarray(),t.subarray())},chaCha20Poly1305Encrypt(e,t,r,n){return Xa(n,t,r).encrypt(e.subarray())},chaCha20Poly1305Decrypt(e,t,r,n,o){return Xa(n,t,r).decrypt(e.subarray(),o)}};var Tl=Za;function Rl(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}var Fr=e=>{let t=it(2);return t[0]=e>>8,t[1]=e,t};Fr.bytes=2;var Vr=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};Vr.bytes=2;function Pl(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Qa(e,t){!t.enabled||!Kr||(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${$(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${$(e.privateKey,"hex")}`)):t("Missing local static keys."))}function Ja(e,t){!t.enabled||!Kr||(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${$(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${$(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function Ol(e,t){!t.enabled||!Kr||t(e?`REMOTE_STATIC_PUBLIC_KEY ${$(e.subarray(),"hex")}`:"Missing remote static public key.")}function tc(e,t){!t.enabled||!Kr||t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${$(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function ec(e,t,r){!r.enabled||!Kr||(r(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&$(e.k,"hex")}`),r(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&$(t.k,"hex")}`))}var $r=class e extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=e.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var i0=0,a0=4294967295,c0="Cipherstate has reached maximum n, a new handshake must be performed",ps=class{n;bytes;view;constructor(t=i0){this.n=t,this.bytes=pt(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>a0)throw new Error(c0)}};var nr=pt(0),Wr=class{k;n;crypto;constructor(t,r=void 0,n=0){this.crypto=t,this.k=r,this.n=new ps(n)}hasKey(){return!!this.k}encryptWithAd(t,r){if(!this.hasKey())return r;this.n.assertValue();let n=this.crypto.encrypt(r,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,r,n){if(!this.hasKey())return r;this.n.assertValue();let o=this.crypto.decrypt(r,this.n.getBytes(),t,this.k,n);return this.n.increment(),o}},rc=class{cs;ck;h;crypto;constructor(t,r){this.crypto=t;let n=q(r,"utf-8");this.h=u0(t,n),this.ck=this.h,this.cs=new Wr(t)}mixKey(t){let[r,n]=this.crypto.hkdf(this.ck,t);this.ck=r,this.cs=new Wr(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new W(this.h,t))}encryptAndHash(t){let r=this.cs.encryptWithAd(this.h,t);return this.mixHash(r),r}decryptAndHash(t){let r=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),r}split(){let[t,r]=this.crypto.hkdf(this.ck,nr);return[new Wr(this.crypto,t),new Wr(this.crypto,r)]}},nc=class{ss;s;e;rs;re;initiator;crypto;constructor(t){let{crypto:r,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:u}=t;this.crypto=r,this.ss=new rc(r,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=u}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,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<r+32)throw new Error("message is not long enough");this.re=t.sublist(r,r+32),this.ss.mixHash(this.re)}readS(t,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(t.byteLength<r+n)throw new Error("message is not long enough");let o=t.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},On=class extends nc{writeMessageA(t){return new W(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let r=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new W(r,n,this.ss.encryptAndHash(t))}writeMessageC(t){let r=this.writeS();return this.writeSE(),new W(r,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(r){throw new $r(`handshake stage 0 validation fail: ${r.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();let r=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+r))}catch(r){throw new $r(`handshake stage 1 validation fail: ${r.message}`)}}readMessageC(t){try{let r=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(r))}catch(r){throw new $r(`handshake stage 2 validation fail: ${r.message}`)}}};function u0(e,t){if(t.length<=32){let r=pt(32);return r.set(t),r}else return e.hash(t)}var oc=new Float32Array([-0]),Me=new Uint8Array(oc.buffer);function Nl(e,t,r){oc[0]=e,t[r]=Me[0],t[r+1]=Me[1],t[r+2]=Me[2],t[r+3]=Me[3]}function Ul(e,t){return Me[0]=e[t],Me[1]=e[t+1],Me[2]=e[t+2],Me[3]=e[t+3],oc[0]}var sc=new Float64Array([-0]),Lt=new Uint8Array(sc.buffer);function kl(e,t,r){sc[0]=e,t[r]=Lt[0],t[r+1]=Lt[1],t[r+2]=Lt[2],t[r+3]=Lt[3],t[r+4]=Lt[4],t[r+5]=Lt[5],t[r+6]=Lt[6],t[r+7]=Lt[7]}function Ml(e,t){return Lt[0]=e[t],Lt[1]=e[t+1],Lt[2]=e[t+2],Lt[3]=e[t+3],Lt[4]=e[t+4],Lt[5]=e[t+5],Lt[6]=e[t+6],Lt[7]=e[t+7],sc[0]}var f0=BigInt(Number.MAX_SAFE_INTEGER),l0=BigInt(Number.MIN_SAFE_INTEGER),Mt=class e{lo;hi;constructor(t,r){this.lo=t|0,this.hi=r|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(r+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let r=~this.lo+1>>>0,n=~this.hi>>>0;return r===0&&(n=n+1>>>0),-(BigInt(r)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,r=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?r===0?t<16384?t<128?1:2:t<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return or;if(t<f0&&t>l0)return this.fromNumber(Number(t));let r=t<0n;r&&(t=-t);let n=t>>32n,o=t-(n<<32n);return r&&(n=~n|0n,o=~o|0n,++o>Kl&&(o=0n,++n>Kl&&(n=0n))),new e(Number(o),Number(n))}static fromNumber(t){if(t===0)return or;let r=t<0;r&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return r&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new e(n,o)}static from(t){return typeof t=="number"?e.fromNumber(t):typeof t=="bigint"?e.fromBigInt(t):typeof t=="string"?e.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new e(t.low>>>0,t.high>>>0):or}},or=new Mt(0,0);or.toBigInt=function(){return 0n};or.zzEncode=or.zzDecode=function(){return this};or.length=function(){return 1};var Kl=4294967296n;function Hl(e){let t=0,r=0;for(let n=0;n<e.length;++n)r=e.charCodeAt(n),r<128?t+=1:r<2048?t+=2:(r&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Fl(e,t,r){if(r-t<1)return"";let o,s=[],i=0,a;for(;t<r;)a=e[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|e[t++]&63:a>239&&a<365?(a=((a&7)<<18|(e[t++]&63)<<12|(e[t++]&63)<<6|e[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(e[t++]&63)<<6|e[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 ic(e,t,r){let n=r,o,s;for(let i=0;i<e.length;++i)o=e.charCodeAt(i),o<128?t[r++]=o:o<2048?(t[r++]=o>>6|192,t[r++]=o&63|128):(o&64512)===55296&&((s=e.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[r++]=o>>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=o&63|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=o&63|128);return r-n}function zt(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function ms(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}var ac=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,zt(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 zt(this,4);return ms(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw zt(this,4);return ms(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw zt(this,4);let t=Ul(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw zt(this,4);let t=Ml(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),r=this.pos,n=this.pos+t;if(n>this.len)throw zt(this,t);return this.pos+=t,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let t=this.bytes();return Fl(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw zt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw zt(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 Mt(0,0),r=0;if(this.len-this.pos>4){for(;r<4;++r)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;r=0}else{for(;r<3;++r){if(this.pos>=this.len)throw zt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<r*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<r*7)>>>0,t}if(this.len-this.pos>4){for(;r<5;++r)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;r<5;++r){if(this.pos>=this.len)throw zt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<r*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw zt(this,8);let t=ms(this.buf,this.pos+=4),r=ms(this.buf,this.pos+=4);return new Mt(t,r)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=hn(this.buf,this.pos);return this.pos+=et(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 cc(e){return new ac(e instanceof Uint8Array?e:e.subarray())}function gs(e,t,r){let n=cc(e);return t.decode(n,void 0,r)}function uc(e){let t=e??8192,r=t>>>1,n,o=t;return function(i){if(i<1||i>r)return it(i);o+i>t&&(n=it(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var sr=class{fn;len;next;val;constructor(t,r,n){this.fn=t,this.len=r,this.next=void 0,this.val=n}};function fc(){}var hc=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},h0=uc();function d0(e){return globalThis.Buffer!=null?it(e):h0(e)}var Un=class{len;head;tail;states;constructor(){this.len=0,this.head=new sr(fc,0,0),this.tail=this.head,this.states=null}_push(t,r,n){return this.tail=this.tail.next=new sr(t,r,n),this.len+=r,this}uint32(t){return this.len+=(this.tail=this.tail.next=new dc((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(ys,10,Mt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let r=Mt.fromBigInt(t);return this._push(ys,r.length(),r)}uint64Number(t){return this._push(Ie,et(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 r=Mt.fromBigInt(t).zzEncode();return this._push(ys,r.length(),r)}sint64Number(t){let r=Mt.fromNumber(t).zzEncode();return this._push(ys,r.length(),r)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(lc,1,t?1:0)}fixed32(t){return this._push(Nn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let r=Mt.fromBigInt(t);return this._push(Nn,4,r.lo)._push(Nn,4,r.hi)}fixed64Number(t){let r=Mt.fromNumber(t);return this._push(Nn,4,r.lo)._push(Nn,4,r.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Nl,4,t)}double(t){return this._push(kl,8,t)}bytes(t){let r=t.length>>>0;return r===0?this._push(lc,1,0):this.uint32(r)._push(m0,r,t)}string(t){let r=Hl(t);return r!==0?this.uint32(r)._push(ic,r,t):this._push(lc,1,0)}fork(){return this.states=new hc(this),this.head=this.tail=new sr(fc,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new sr(fc,0,0),this.len=0),this}ldelim(){let t=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=r,this.len+=n),this}finish(){let t=this.head.next,r=d0(this.len),n=0;for(;t!=null;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}};function lc(e,t,r){t[r]=e&255}function p0(e,t,r){for(;e>127;)t[r++]=e&127|128,e>>>=7;t[r]=e}var dc=class extends sr{next;constructor(t,r){super(p0,t,r),this.next=void 0}};function ys(e,t,r){for(;e.hi!==0;)t[r++]=e.lo&127|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=e.lo&127|128,e.lo=e.lo>>>7;t[r++]=e.lo}function Nn(e,t,r){t[r]=e&255,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function m0(e,t,r){t.set(e,r)}globalThis.Buffer!=null&&(Un.prototype.bytes=function(e){let t=e.length>>>0;return this.uint32(t),t>0&&this._push(g0,t,e),this},Un.prototype.string=function(e){let t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(y0,t,e),this});function g0(e,t,r){t.set(e,r)}function y0(e,t,r){e.length<40?ic(e,t,r):t.utf8Write!=null?t.utf8Write(e,r):t.set(q(e),r)}function pc(){return new Un}function bs(e,t){let r=pc();return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var kn;(function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"})(kn||(kn={}));function mc(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function ws(e,t){return mc("message",kn.LENGTH_DELIMITED,e,t)}var Mn=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var xs;(function(e){let t;e.codec=()=>(t==null&&(t=ws((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 Mn('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 Mn('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(r.string());break}default:{r.skipType(a&7);break}}}return s})),t),e.encode=r=>bs(r,e.codec()),e.decode=(r,n)=>gs(r,e.codec(),n)})(xs||(xs={}));var Kn;(function(e){let t;e.codec=()=>(t==null&&(t=ws((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),xs.codec().encode(r.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={identityKey:pt(0),identitySig:pt(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=xs.codec().decode(r,r.uint32(),{limits:o.limits?.extensions});break}default:{r.skipType(a&7);break}}}return s})),t),e.encode=r=>bs(r,e.codec()),e.decode=(r,n)=>gs(r,e.codec(),n)})(Kn||(Kn={}));async function yc(e,t,r){let n=await e.sign(Wl(t));return Kn.encode({identityKey:xe(e.publicKey),identitySig:n,extensions:r})}async function bc(e,t,r){try{let n=Kn.decode(e),o=wn(n.identityKey);if(r?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${r}`);if(!t)throw new Error("Remote static does not exist");let s=Wl(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Vn(n.message)}}function Wl(e){let t=q("noise-libp2p-static-key:");return e instanceof Uint8Array?Tt([t,e],t.length+e.length):(e.prepend(t),e)}var gc=class extends Ne{stream;handshake;metrics;decoder;constructor(t,r,n){super({log:t.log,inactivityTimeout:t.inactivityTimeout,maxReadBufferLength:t.maxReadBufferLength,direction:t.direction}),this.stream=t,this.handshake=r,this.metrics=n,this.decoder=new Xo({lengthDecoder:Vr,maxBufferSize:16*1024*1024,encodingLength:()=>2});let o=c=>{try{for(let u of this.decoder.decode(c.data))this.onData(this.decrypt(u))}catch(u){this.abort(u)}};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 r=new W;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(),r.append(Fr(s.byteLength)),r.append(s)}return r}decrypt(t){let r=new W;for(let n=0;n<t.byteLength;n+=65535){let o=n+65535;if(o>t.byteLength&&(o=t.byteLength),o-Va<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-Va);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(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 wc(e,t,r){return new gc(e,t,r)}async function ql(e,t){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:u}=e,f=await yc(s,a.publicKey,u),l=new On({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Qa(l.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(l.writeMessageA(nr),t),r.trace("Stage 0 - Initiator finished sending first message."),Ja(l.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");let d=l.readMessageB(await n.read(t));r.trace("Stage 1 - Initiator received the message."),tc(l.re,r),Ol(l.rs,r),r.trace("Initiator going to check remote's signature...");let m=await bc(d,l.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(l.writeMessageC(f),t),r.trace("Stage 2 - Initiator sent message with signed payload.");let[p,E]=l.ss.split();return ec(p,E,r),{payload:m,encrypt:h=>p.encryptWithAd(nr,h),decrypt:(h,b)=>E.decryptWithAd(nr,h,b)}}async function Gl(e,t){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:u}=e,f=await yc(s,a.publicKey,u),l=new On({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Qa(l.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),l.readMessageA(await n.read(t)),r.trace("Stage 0 - Responder received first message."),tc(l.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(l.writeMessageB(f),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Ja(l.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");let d=l.readMessageC(await n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");let m=await bc(d,l.rs,c),[p,E]=l.ss.split();return ec(p,E,r),{payload:m,encrypt:h=>E.encryptWithAd(nr,h),decrypt:(h,b)=>p.decryptWithAd(nr,h,b)}}var Es=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(t,r={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=r,{metrics:a}=t;this.components=t,this.log=t.logger.forComponent("libp2p:noise");let c=s??Tl;this.crypto=Rl(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?Pl(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??pt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[fr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,r){let n=t.log?.newScope("noise")??this.log,o=zo(t,{lengthEncoder:Fr,lengthDecoder:Vr,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=wn(s.payload.identityKey);return{connection:wc(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Ji(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(t){if(t==null||t.length===0)return;let r=this.components.upgrader.getStreamMuxers();if(r!=null)for(let n of t){let o=r.get(n);if(o!=null)return o}if(t.length)throw new $n("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(t,r){let n=t.log?.newScope("noise")??this.log,o=zo(t,{lengthEncoder:Fr,lengthDecoder:Vr,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=wn(s.payload.identityKey);return{connection:wc(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Ji(i),streamMuxer:r?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(t,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await ql({connection:t,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(t,r,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await Gl({connection:t,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 zl(e={}){return t=>new Es(t,e)}var xc=Object.values(Fe).map(e=>e.decoder).reduce((e,t)=>e.or(t)),b0=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function jl(e){return e?.match(b0)?.groups?.fingerprint}function Ec(e){let r=e.getComponents().find(n=>n.code===466)?.value;if(r===void 0||r==="")throw new Y(`Couldn't find a certhash component of multiaddr: ${e.toString()}`);return r}function w0(e){return Vt.decode(xc.decode(e))}function x0(e){let t=w0(Ec(e)),r=E0(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 os(n,e.toString());return`${r} ${o.join(":").toUpperCase()}`}function Xl(e){let t=e.split(":").map(o=>parseInt(o,16)),r=Uint8Array.from(t),n=Dt(ee.code,r);return Pr(`/certhash/${Zr.encode(n.bytes)}`)}function E0(e){switch(e){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new is(e)}}function Yl(e,t){let{host:r,port:n,type:o}=Da(e);if(o!=="ip4"&&o!=="ip6")throw new Y(`Multiaddr ${e} was not an IPv4 or IPv6 address`);let s=x0(e);return{type:"answer",sdp:`v=0
|
|
2
|
+
"use strict";var Libp2PWebrtc=(()=>{var Ws=Object.defineProperty;var Lh=Object.getOwnPropertyDescriptor;var Bh=Object.getOwnPropertyNames;var Dh=Object.prototype.hasOwnProperty;var De=(t,e)=>{for(var r in e)Ws(t,r,{get:e[r],enumerable:!0})},Rh=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Bh(e))!Dh.call(t,o)&&o!==r&&Ws(t,o,{get:()=>e[o],enumerable:!(n=Lh(e,o))||n.enumerable});return t};var Oh=t=>Rh(Ws({},"__esModule",{value:!0}),t);var ng={};De(ng,{webRTC:()=>rg,webRTCDirect:()=>tg});var so=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},io=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},G=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},br=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var ao=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},co=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},wr=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var Je=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},sn=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var fo=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},uo=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},lo=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var ho=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Gt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var po=class extends Event{data;constructor(e,r){super("message",r),this.data=e}},xr=class extends Event{error;local;constructor(e,r,n){super("close",n),this.error=r,this.local=e}},mo=class extends xr{constructor(e,r){super(!0,e,r)}},go=class extends xr{constructor(e,r){super(!1,e,r)}};var qs=Symbol.for("@libp2p/peer-id");var yo=Symbol.for("@libp2p/transport");var Qc;(function(t){t[t.FATAL_ALL=0]="FATAL_ALL",t[t.NO_FATAL=1]="NO_FATAL"})(Qc||(Qc={}));function Ph(t){return typeof t?.handleEvent=="function"}function Nh(t){return(t!==!0&&t!==!1&&t?.once)??!1}var Et=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=Nh(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))}Ph(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 Er=Symbol.for("@libp2p/service-capabilities"),Jc=Symbol.for("@libp2p/service-dependencies");var Zs={};De(Zs,{base58btc:()=>le,base58flickr:()=>Vh});var Ng=new Uint8Array(0);function ef(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 at(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 tf(t){return new TextEncoder().encode(t)}function rf(t){return new TextDecoder().decode(t)}function Uh(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 l(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var S=0,h=0,y=0,v=g.length;y!==v&&g[y]===0;)y++,S++;for(var T=(v-y)*u+1>>>0,P=new Uint8Array(T);y!==v;){for(var D=g[y],O=0,R=T-1;(D!==0||O<h)&&R!==-1;R--,O++)D+=256*P[R]>>>0,P[R]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");h=O,y++}for(var L=T-h;L!==T&&P[L]===0;)L++;for(var N=c.repeat(S);L<T;++L)N+=t.charAt(P[L]);return N}function p(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var S=0;if(g[S]!==" "){for(var h=0,y=0;g[S]===c;)h++,S++;for(var v=(g.length-S)*f+1>>>0,T=new Uint8Array(v);g[S];){var P=r[g.charCodeAt(S)];if(P===255)return;for(var D=0,O=v-1;(P!==0||D<y)&&O!==-1;O--,D++)P+=a*T[O]>>>0,T[O]=P%256>>>0,P=P/256>>>0;if(P!==0)throw new Error("Non-zero carry");y=D,S++}if(g[S]!==" "){for(var R=v-y;R!==v&&T[R]===0;)R++;for(var L=new Uint8Array(h+(v-R)),N=h;R!==v;)L[N++]=T[R++];return L}}}function d(g){var S=p(g);if(S)return S;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:p,decode:d}}var Fh=Uh,kh=Fh,of=kh;var Gs=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")}},js=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 sf(this,e)}},Xs=class{decoders;constructor(e){this.decoders=e}or(e){return sf(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 sf(t,e){return new Xs({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var Ys=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 Gs(e,r,n),this.decoder=new js(e,r,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Sr({name:t,prefix:e,encode:r,decode:n}){return new Ys(t,e,r,n)}function St({name:t,prefix:e,alphabet:r}){let{encode:n,decode:o}=of(r,t);return Sr({prefix:e,name:t,encode:n,decode:s=>at(o(s))})}function Mh(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 Kh(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 Hh(t){let e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function ue({name:t,prefix:e,bitsPerChar:r,alphabet:n}){let o=Hh(n);return Sr({prefix:e,name:t,encode(s){return Kh(s,n,r)},decode(s){return Mh(s,o,r,t)}})}var le=St({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Vh=St({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Qs={};De(Qs,{base32:()=>At,base32hex:()=>qh,base32hexpad:()=>jh,base32hexpadupper:()=>Xh,base32hexupper:()=>Gh,base32pad:()=>zh,base32padupper:()=>Wh,base32upper:()=>$h,base32z:()=>Yh});var At=ue({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$h=ue({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),zh=ue({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Wh=ue({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),qh=ue({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Gh=ue({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),jh=ue({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Xh=ue({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Yh=ue({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Js={};De(Js,{base36:()=>an,base36upper:()=>Zh});var an=St({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Zh=St({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var $e={};De($e,{Digest:()=>jt,create:()=>Re,decode:()=>_r,equals:()=>ti,hasCode:()=>gd});var Qh=ff,af=128,Jh=127,ed=~Jh,td=Math.pow(2,31);function ff(t,e,r){e=e||[],r=r||0;for(var n=r;t>=td;)e[r++]=t&255|af,t/=128;for(;t&ed;)e[r++]=t&255|af,t>>>=7;return e[r]=t|0,ff.bytes=r-n+1,e}var rd=ei,nd=128,cf=127;function ei(t,n){var r=0,n=n||0,o=0,s=n,i,a=t.length;do{if(s>=a)throw ei.bytes=0,new RangeError("Could not decode varint");i=t[s++],r+=o<28?(i&cf)<<o:(i&cf)*Math.pow(2,o),o+=7}while(i>=nd);return ei.bytes=s-n,r}var od=Math.pow(2,7),sd=Math.pow(2,14),id=Math.pow(2,21),ad=Math.pow(2,28),cd=Math.pow(2,35),fd=Math.pow(2,42),ud=Math.pow(2,49),ld=Math.pow(2,56),hd=Math.pow(2,63),dd=function(t){return t<od?1:t<sd?2:t<id?3:t<ad?4:t<cd?5:t<fd?6:t<ud?7:t<ld?8:t<hd?9:10},pd={encode:Qh,decode:rd,encodingLength:dd},md=pd,cn=md;function fn(t,e=0){return[cn.decode(t,e),cn.decode.bytes]}function Ar(t,e,r=0){return cn.encode(t,e,r),e}function vr(t){return cn.encodingLength(t)}function Re(t,e){let r=e.byteLength,n=vr(t),o=n+vr(r),s=new Uint8Array(o+r);return Ar(t,s,0),Ar(r,s,n),s.set(e,o),new jt(t,r,e,s)}function _r(t){let e=at(t),[r,n]=fn(e),[o,s]=fn(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new jt(r,o,i,e)}function ti(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&ef(t.bytes,r.bytes)}}var jt=class{code;size;digest;bytes;constructor(e,r,n,o){this.code=e,this.size=r,this.digest=n,this.bytes=o}};function gd(t,e){return t.code===e}function uf(t,e){let{bytes:r,version:n}=t;return n===0?bd(r,ri(t),e??le.encoder):wd(r,ri(t),e??At.encoder)}var lf=new WeakMap;function ri(t){let e=lf.get(t);if(e==null){let r=new Map;return lf.set(t,r),r}return e}var de=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!==un)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==xd)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=Re(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&&ti(e.multihash,n.multihash)}toString(e){return uf(this,e)}toJSON(){return{"/":uf(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??hf(n,o,s.bytes))}else if(r[Ed]===!0){let{version:n,multihash:o,code:s}=r,i=_r(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!==un)throw new Error(`Version 0 CID must use dag-pb (code: ${un}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let o=hf(e,r,n.bytes);return new t(e,r,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,un,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=at(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 jt(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[l,p]=fn(e.subarray(r));return r+=p,l},o=n(),s=un;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]=yd(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 ri(s).set(n,e),s}};function yd(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 At.prefix:{let r=e??At;return[At.prefix,r.decode(t)]}case an.prefix:{let r=e??an;return[an.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 bd(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 wd(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 un=112,xd=18;function hf(t,e,r){let n=vr(t),o=n+vr(e),s=new Uint8Array(o+r.byteLength);return Ar(t,s,0),Ar(e,s,n),s.set(r,o),s}var Ed=Symbol.for("@ipld/js-cid/CID");var ni={};De(ni,{identity:()=>ze});var df=0,Sd="identity",pf=at;function Ad(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 Re(df,pf(t))}var ze={code:df,name:Sd,encode:pf,digest:Ad};function we(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}async function mf(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,e,r.subarray());return n?.signal?.throwIfAborted(),s}function pe(t=0){return new Uint8Array(t)}function ae(t=0){return new Uint8Array(t)}function Oe(t,e){e==null&&(e=t.reduce((o,s)=>o+s.length,0));let r=ae(e),n=0;for(let o of t)r.set(o,n),n+=o.length;return r}var yf=Symbol.for("@achingbrain/uint8arraylist");function gf(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 wo(t){return!!t?.[yf]}var $=class t{bufs;length;[yf]=!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(wo(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(wo(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=gf(this.bufs,e);return r.buf[r.index]}set(e,r){let n=gf(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(wo(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 Oe(n,o)}subarray(e,r){let{bufs:n,length:o}=this._subList(e,r);return n.length===1?n[0]:Oe(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 l=e-a;n.push(i.subarray(l,l+(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(!wo(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 l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,u;for(let l=r;l<=c;l+=u){u=0;for(let p=f;p>=0;p--){let d=this.get(l+p);if(n[p]!==d){u=Math.max(1,p-a[d]);break}}if(u===0)return l}return-1}getInt8(e){let r=this.subarray(e,e+1);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt8(0)}setInt8(e,r){let n=ae(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=pe(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=pe(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=pe(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=ae(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=pe(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=pe(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=pe(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=pe(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=pe(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(!we(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 oi={};De(oi,{base10:()=>_d});var _d=St({prefix:"9",name:"base10",alphabet:"0123456789"});var si={};De(si,{base16:()=>Cd,base16upper:()=>Td});var Cd=ue({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Td=ue({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ii={};De(ii,{base2:()=>Id});var Id=ue({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ai={};De(ai,{base256emoji:()=>Od});var bf=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}"),Ld=bf.reduce((t,e,r)=>(t[r]=e,t),[]),Bd=bf.reduce((t,e,r)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return t[n]=r,t},[]);function Dd(t){return t.reduce((e,r)=>(e+=Ld[r],e),"")}function Rd(t){let e=[];for(let r of t){let n=r.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${r}`);let o=Bd[n];if(o==null)throw new Error(`Non-base256emoji character: ${r}`);e.push(o)}return new Uint8Array(e)}var Od=Sr({prefix:"\u{1F680}",name:"base256emoji",encode:Dd,decode:Rd});var ci={};De(ci,{base64:()=>Pd,base64pad:()=>Nd,base64url:()=>ln,base64urlpad:()=>Ud});var Pd=ue({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Nd=ue({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ln=ue({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ud=ue({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var fi={};De(fi,{base8:()=>Fd});var Fd=ue({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ui={};De(ui,{identity:()=>kd});var kd=Sr({prefix:"\0",name:"identity",encode:t=>rf(t),decode:t=>tf(t)});var by=new TextEncoder,wy=new TextDecoder;var di={};De(di,{sha256:()=>ct,sha512:()=>Vd});var Hd=20;function hi({name:t,code:e,encode:r,minDigestLength:n,maxDigestLength:o}){return new li(t,e,r,n,o)}var li=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,r,n,o,s){this.name=e,this.code=r,this.encode=n,this.minDigestLength=o??Hd,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?wf(n,this.code,r?.truncate):n.then(o=>wf(o,this.code,r?.truncate))}else throw Error("Unknown type, must be binary type")}};function wf(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 Re(e,t)}function Ef(t){return async e=>new Uint8Array(await crypto.subtle.digest(t,e))}var ct=hi({name:"sha2-256",code:18,encode:Ef("SHA-256")}),Vd=hi({name:"sha2-512",code:19,encode:Ef("SHA-512")});var Xt={...ui,...ii,...fi,...oi,...si,...Qs,...Js,...Zs,...ci,...ai},Dy={...di,...ni};function Af(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}var Sf=Af("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),pi=Af("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=ae(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),$d={utf8:Sf,"utf-8":Sf,hex:Xt.base16,latin1:pi,ascii:pi,binary:pi,...Xt},xo=$d;function W(t,e="utf8"){let r=xo[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.decoder.decode(`${r.prefix}${t}`)}function V(t,e="utf8"){let r=xo[e];if(r==null)throw new Error(`Unsupported encoding "${e}"`);return r.encoder.encode(t).substring(1)}var zd=parseInt("11111",2),mi=parseInt("10000000",2),Wd=parseInt("01111111",2),vf={0:hn,1:hn,2:qd,3:Xd,4:Yd,5:jd,6:Gd,16:hn,22:hn,48:hn};function ft(t,e={offset:0}){let r=t[e.offset]&zd;if(e.offset++,vf[r]!=null)return vf[r](t,e);throw new Error("No decoder for tag "+r)}function dn(t,e){let r=0;if((t[e.offset]&mi)===mi){let n=t[e.offset]&Wd,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 hn(t,e){dn(t,e);let r=[];for(;!(e.offset>=t.byteLength);){let n=ft(t,e);if(n===null)break;r.push(n)}return r}function qd(t,e){let r=dn(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 Gd(t,e){let r=dn(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 l=0;l<c.length;l++)u+=c[l]<<l*7;a+=`.${u}`,c=[]}}return a}function jd(t,e){return e.offset++,null}function Xd(t,e){let r=dn(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 Yd(t,e){let r=dn(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function Zd(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);let r=new $;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function gi(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);let e=Zd(t.byteLength);return new $(Uint8Array.from([e.byteLength|mi]),e)}function Pe(t){let e=new $,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new $(Uint8Array.from([2]),gi(e),e)}function Eo(t){let e=Uint8Array.from([0]),r=new $(e,t);return new $(Uint8Array.from([3]),gi(r),r)}function vt(t,e=48){let r=new $;for(let n of t)r.append(n);return new $(Uint8Array.from([e]),gi(r),r)}var Qd=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Jd=Uint8Array.from([6,5,43,129,4,0,34]),ep=Uint8Array.from([6,5,43,129,4,0,35]),tp={ext:!0,kty:"EC",crv:"P-256"},rp={ext:!0,kty:"EC",crv:"P-384"},np={ext:!0,kty:"EC",crv:"P-521"},yi=32,bi=48,wi=66;function xi(t){let e=ft(t);return _f(e)}function _f(t){let e=t[1][1][0],r=1,n,o;if(e.byteLength===yi*2+1)return n=V(e.subarray(r,r+yi),"base64url"),o=V(e.subarray(r+yi),"base64url"),new Cr({...tp,key_ops:["verify"],x:n,y:o});if(e.byteLength===bi*2+1)return n=V(e.subarray(r,r+bi),"base64url"),o=V(e.subarray(r+bi),"base64url"),new Cr({...rp,key_ops:["verify"],x:n,y:o});if(e.byteLength===wi*2+1)return n=V(e.subarray(r,r+wi),"base64url"),o=V(e.subarray(r+wi),"base64url"),new Cr({...np,key_ops:["verify"],x:n,y:o});throw new G(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Cf(t){return vt([Pe(Uint8Array.from([1])),vt([op(t.crv)],160),vt([Eo(new $(Uint8Array.from([4]),W(t.x??"","base64url"),W(t.y??"","base64url")))],161)]).subarray()}function op(t){if(t==="P-256")return Qd;if(t==="P-384")return Jd;if(t==="P-521")return ep;throw new G(`Invalid curve ${t}`)}var Cr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Cf(this.jwk)),this._raw}toMultihash(){return ze.digest(_t(this))}toCID(){return de.createV1(114,this.toMultihash())}toString(){return le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}async verify(e,r,n){return mf(this.jwk,r,e,n)}};function Ei(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function et(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 _e(t,e,r=""){let n=Ei(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 Yt(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(et(t.outputLen),et(t.blockLen),t.outputLen<1)throw new Error('"outputLen" must be >= 1');if(t.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Tr(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 So(t,e){_e(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 Ao(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function qe(t,e){return t<<32-e|t>>>e}var If=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",sp=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function vo(t){if(_e(t),If)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=sp[t[r]];return e}var ut={_0:48,_9:57,A:65,F:70,a:97,f:102};function Tf(t){if(t>=ut._0&&t<=ut._9)return t-ut._0;if(t>=ut.A&&t<=ut.F)return t-(ut.A-10);if(t>=ut.a&&t<=ut.f)return t-(ut.a-10)}function pn(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(If)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=Tf(t.charCodeAt(s)),a=Tf(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 Si(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];_e(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 Ai(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 Lf(t=32){et(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 vi=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Bf(t,e,r){return t&e^~t&r}function Df(t,e,r){return t&e^t&r^e&r}var mn=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=Ao(this.buffer)}update(e){Tr(this),_e(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=Ao(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){Tr(this),So(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 l=i;l<o;l++)r[l]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Ao(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 l=0;l<f;l++)a.setUint32(4*l,u[l],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()}},lt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var xe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var _o=BigInt(4294967295),Rf=BigInt(32);function ip(t,e=!1){return e?{h:Number(t&_o),l:Number(t>>Rf&_o)}:{h:Number(t>>Rf&_o)|0,l:Number(t&_o)|0}}function Of(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}=ip(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var _i=(t,e,r)=>t>>>r,Ci=(t,e,r)=>t<<32-r|e>>>r,Zt=(t,e,r)=>t>>>r|e<<32-r,Qt=(t,e,r)=>t<<32-r|e>>>r,gn=(t,e,r)=>t<<64-r|e>>>r-32,yn=(t,e,r)=>t>>>r-32|e<<64-r;function tt(t,e,r,n){let o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}var Pf=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Nf=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Uf=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Ff=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0,kf=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0),Mf=(t,e,r,n,o,s)=>e+r+n+o+s+(t/2**32|0)|0;var cp=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]),Ct=new Uint32Array(64),Ti=class extends mn{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 l=0;l<16;l++,r+=4)Ct[l]=e.getUint32(r,!1);for(let l=16;l<64;l++){let p=Ct[l-15],d=Ct[l-2],g=qe(p,7)^qe(p,18)^p>>>3,S=qe(d,17)^qe(d,19)^d>>>10;Ct[l]=S+Ct[l-7]+g+Ct[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:f,H:u}=this;for(let l=0;l<64;l++){let p=qe(a,6)^qe(a,11)^qe(a,25),d=u+p+Bf(a,c,f)+cp[l]+Ct[l]|0,S=(qe(n,2)^qe(n,13)^qe(n,22))+Df(n,o,s)|0;u=f,f=c,c=a,a=i+d|0,i=s,s=o,o=n,n=d+S|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(Ct)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),We(this.buffer)}},Ii=class extends Ti{A=lt[0]|0;B=lt[1]|0;C=lt[2]|0;D=lt[3]|0;E=lt[4]|0;F=lt[5]|0;G=lt[6]|0;H=lt[7]|0;constructor(){super(32)}};var Kf=Of(["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))),fp=Kf[0],up=Kf[1],Tt=new Uint32Array(80),It=new Uint32Array(80),Li=class extends mn{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:l,Fl:p,Gh:d,Gl:g,Hh:S,Hl:h}=this;return[e,r,n,o,s,i,a,c,f,u,l,p,d,g,S,h]}set(e,r,n,o,s,i,a,c,f,u,l,p,d,g,S,h){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=l|0,this.Fl=p|0,this.Gh=d|0,this.Gl=g|0,this.Hh=S|0,this.Hl=h|0}process(e,r){for(let T=0;T<16;T++,r+=4)Tt[T]=e.getUint32(r),It[T]=e.getUint32(r+=4);for(let T=16;T<80;T++){let P=Tt[T-15]|0,D=It[T-15]|0,O=Zt(P,D,1)^Zt(P,D,8)^_i(P,D,7),R=Qt(P,D,1)^Qt(P,D,8)^Ci(P,D,7),L=Tt[T-2]|0,N=It[T-2]|0,k=Zt(L,N,19)^gn(L,N,61)^_i(L,N,6),U=Qt(L,N,19)^yn(L,N,61)^Ci(L,N,6),m=Uf(R,U,It[T-7],It[T-16]),A=Ff(m,O,k,Tt[T-7],Tt[T-16]);Tt[T]=A|0,It[T]=m|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:u,Eh:l,El:p,Fh:d,Fl:g,Gh:S,Gl:h,Hh:y,Hl:v}=this;for(let T=0;T<80;T++){let P=Zt(l,p,14)^Zt(l,p,18)^gn(l,p,41),D=Qt(l,p,14)^Qt(l,p,18)^yn(l,p,41),O=l&d^~l&S,R=p&g^~p&h,L=kf(v,D,R,up[T],It[T]),N=Mf(L,y,P,O,fp[T],Tt[T]),k=L|0,U=Zt(n,o,28)^gn(n,o,34)^gn(n,o,39),m=Qt(n,o,28)^yn(n,o,34)^yn(n,o,39),A=n&s^n&a^s&a,E=o&i^o&c^i&c;y=S|0,v=h|0,S=d|0,h=g|0,d=l|0,g=p|0,{h:l,l:p}=tt(f|0,u|0,N|0,k|0),f=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let w=Pf(k,m,E);n=Nf(w,N,U,A),o=w|0}({h:n,l:o}=tt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=tt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=tt(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:u}=tt(this.Dh|0,this.Dl|0,f|0,u|0),{h:l,l:p}=tt(this.Eh|0,this.El|0,l|0,p|0),{h:d,l:g}=tt(this.Fh|0,this.Fl|0,d|0,g|0),{h:S,l:h}=tt(this.Gh|0,this.Gl|0,S|0,h|0),{h:y,l:v}=tt(this.Hh|0,this.Hl|0,y|0,v|0),this.set(n,o,s,i,a,c,f,u,l,p,d,g,S,h,y,v)}roundClean(){We(Tt,It)}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)}},Bi=class extends Li{Ah=xe[0]|0;Al=xe[1]|0;Bh=xe[2]|0;Bl=xe[3]|0;Ch=xe[4]|0;Cl=xe[5]|0;Dh=xe[6]|0;Dl=xe[7]|0;Eh=xe[8]|0;El=xe[9]|0;Fh=xe[10]|0;Fl=xe[11]|0;Gh=xe[12]|0;Gl=xe[13]|0;Hh=xe[14]|0;Hl=xe[15]|0;constructor(){super(64)}};var rt=Ai(()=>new Ii,vi(1));var Co=Ai(()=>new Bi,vi(3));var z=(t,e,r)=>_e(t,e,r),Ri=et,Ir=vo,me=(...t)=>Si(...t),Lr=t=>pn(t),Jt=Ei,er=t=>Lf(t),Io=BigInt(0),Di=BigInt(1);function Ge(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new TypeError(r+"expected boolean, got type="+typeof t)}return t}function Lo(t){if(typeof t=="bigint"){if(!To(t))throw new RangeError("positive bigint expected, got "+t)}else Ri(t);return t}function je(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 bn(t){let e=Lo(t).toString(16);return e.length&1?"0"+e:e}function Hf(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Io:BigInt("0x"+t)}function tr(t){return Hf(vo(t))}function Ue(t){return Hf(vo(Lt(_e(t)).reverse()))}function Bo(t,e){if(et(e),e===0)throw new RangeError("zero length");t=Lo(t);let r=t.toString(16);if(r.length>e*2)throw new RangeError("number too large");return pn(r.padStart(e*2,"0"))}function wn(t,e){return Bo(t,e).reverse()}function Vf(t,e){if(t=z(t),e=z(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 Lt(t){return Uint8Array.from(z(t))}function Do(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 To=t=>typeof t=="bigint"&&Io<=t;function lp(t,e,r){return To(t)&&To(e)&&To(r)&&e<=t&&t<r}function ht(t,e,r,n){if(!lp(e,r,n))throw new RangeError("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Br(t){if(t<Io)throw new Error("expected non-negative bigint, got "+t);let e;for(e=0;t>Io;t>>=Di,e+=1);return e}var xn=t=>(Di<<BigInt(t))-Di;function $f(t,e,r){if(et(t,"hashLen"),et(e,"qByteLen"),typeof r!="function")throw new TypeError("hmacFn must be a function");let n=h=>new Uint8Array(h),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(t),f=n(t),u=0,l=()=>{c.fill(1),f.fill(0),u=0},p=(...h)=>r(f,me(c,...h)),d=(h=o)=>{f=p(s,h),c=p(),h.length!==0&&(f=p(i,h),c=p())},g=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let h=0,y=[];for(;h<e;){c=p();let v=c.slice();y.push(v),h+=c.length}return me(...y)};return(h,y)=>{l(),d(h);let v;for(;(v=y(g()))===void 0;)d();return l(),v}}function Fe(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 Oi=()=>{throw new Error("not implemented")};var Ee=BigInt(0),he=BigInt(1),rr=BigInt(2),Gf=BigInt(3),jf=BigInt(4),Xf=BigInt(5),hp=BigInt(7),Yf=BigInt(8),dp=BigInt(9),Zf=BigInt(16);function ce(t,e){if(e<=Ee)throw new Error("mod: expected positive modulus, got "+e);let r=t%e;return r>=Ee?r:e+r}function se(t,e,r){if(e<Ee)throw new Error("pow2: expected non-negative exponent, got "+e);let n=t;for(;e-- >Ee;)n*=n,n%=r;return n}function zf(t,e){if(t===Ee)throw new Error("invert: expected non-zero number");if(e<=Ee)throw new Error("invert: expected positive modulus, got "+e);let r=ce(t,e),n=e,o=Ee,s=he,i=he,a=Ee;for(;r!==Ee;){let f=n/r,u=n-r*f,l=o-i*f,p=s-a*f;n=r,r=u,o=i,s=a,i=l,a=p}if(n!==he)throw new Error("invert: does not exist");return ce(o,e)}function Pi(t,e,r){let n=t;if(!n.eql(n.sqr(e),r))throw new Error("Cannot find square root")}function Qf(t,e){let r=t,n=(r.ORDER+he)/jf,o=r.pow(e,n);return Pi(r,o,e),o}function pp(t,e){let r=t,n=(r.ORDER-Xf)/Yf,o=r.mul(e,rr),s=r.pow(o,n),i=r.mul(e,s),a=r.mul(r.mul(i,rr),s),c=r.mul(i,r.sub(a,r.ONE));return Pi(r,c,e),c}function mp(t){let e=Dr(t),r=Jf(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+hp)/Zf;return((a,c)=>{let f=a,u=f.pow(c,i),l=f.mul(u,n),p=f.mul(u,o),d=f.mul(u,s),g=f.eql(f.sqr(l),c),S=f.eql(f.sqr(p),c);u=f.cmov(u,l,g),l=f.cmov(d,p,S);let h=f.eql(f.sqr(l),c),y=f.cmov(u,l,h);return Pi(f,y,c),y})}function Jf(t){if(t<Gf)throw new Error("sqrt is not defined for small field");let e=t-he,r=0;for(;e%rr===Ee;)e/=rr,r++;let n=rr,o=Dr(t);for(;Wf(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Qf;let s=o.pow(n,e),i=(e+he)/rr;return function(c,f){let u=c;if(u.is0(f))return f;if(Wf(u,f)!==1)throw new Error("Cannot find square root");let l=r,p=u.mul(u.ONE,s),d=u.pow(f,e),g=u.pow(f,i);for(;!u.eql(d,u.ONE);){if(u.is0(d))return u.ZERO;let S=1,h=u.sqr(d);for(;!u.eql(h,u.ONE);)if(S++,h=u.sqr(h),S===l)throw new Error("Cannot find square root");let y=he<<BigInt(l-S-1),v=u.pow(p,y);l=S,p=u.sqr(v),d=u.mul(d,p),g=u.mul(g,v)}return g}}function gp(t){return t%jf===Gf?Qf:t%Yf===Xf?pp:t%Zf===dp?mp(t):Jf(t)}var dt=(t,e)=>(ce(t,e)&he)===he,yp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ni(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=yp.reduce((n,o)=>(n[o]="function",n),e);if(Fe(t,r),je(t.BYTES,"BYTES"),je(t.BITS,"BITS"),t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=he)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function bp(t,e,r){let n=t;if(r<Ee)throw new Error("invalid exponent, negatives unsupported");if(r===Ee)return n.ONE;if(r===he)return e;let o=n.ONE,s=e;for(;r>Ee;)r&he&&(o=n.mul(o,s)),s=n.sqr(s),r>>=he;return o}function En(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 Wf(t,e){let r=t,n=(r.ORDER-he)/rr,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 wp(t,e){if(e!==void 0&&Ri(e),t<=Ee)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=Br(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 qf=new WeakMap,Ro=class{ORDER;BITS;BYTES;isLE;ZERO=Ee;ONE=he;_lengths;_mod;constructor(e,r={}){if(e<=he)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}=wp(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 ce(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Ee<=e&&e<this.ORDER}is0(e){return e===Ee}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&he)===he}neg(e){return ce(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return ce(e*e,this.ORDER)}add(e,r){return ce(e+r,this.ORDER)}sub(e,r){return ce(e-r,this.ORDER)}mul(e,r){return ce(e*r,this.ORDER)}pow(e,r){return bp(this,e,r)}div(e,r){return ce(e*zf(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 zf(e,this.ORDER)}sqrt(e){let r=qf.get(this);return r||qf.set(this,r=gp(this.ORDER)),r(this,e)}toBytes(e){return this.isLE?wn(e,this.BYTES):Bo(e,this.BYTES)}fromBytes(e,r=!1){z(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?Ue(e):tr(e);if(a&&(c=ce(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return En(this,e)}cmov(e,r,n){return Ge(n,"condition"),n?r:e}};Object.freeze(Ro.prototype);function Dr(t,e={}){return new Ro(t,e)}function eu(t){if(typeof t!="bigint")throw new Error("field order must be bigint");if(t<=he)throw new Error("field order must be greater than 1");let e=Br(t-he);return Math.ceil(e/8)}function Ui(t){let e=eu(t);return e+Math.ceil(e/2)}function Fi(t,e,r=!1){z(t);let n=t.length,o=eu(e),s=Math.max(Ui(e),16);if(n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?Ue(t):tr(t),a=ce(i,e-he)+he;return r?wn(a,o):Bo(a,o)}var Rr=BigInt(0),nr=BigInt(1);function Sn(t,e){let r=e.negate();return t?r:e}function or(t,e){let r=En(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function ou(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ki(t,e){ou(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),o=2**t,s=xn(t),i=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function tu(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+=nr);let f=e*n,u=f+Math.abs(a)-1,l=a===0,p=a<0,d=e%2!==0;return{nextN:c,offset:u,isZero:l,isNeg:p,isNegF:d,offsetF:f}}var Mi=new WeakMap,su=new WeakMap;function Ki(t){return su.get(t)||1}function ru(t){if(t!==Rr)throw new Error("invalid wNAF")}var Or=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>Rr;)r&nr&&(n=n.add(o)),o=o.double(),r>>=nr;return n}precomputeWindow(e,r){let{windows:n,windowSize:o}=ki(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=ki(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:u,isNeg:l,isNegF:p,offsetF:d}=tu(n,a,i);n=c,u?s=s.add(Sn(p,r[d])):o=o.add(Sn(l,r[f]))}return ru(n),{p:o,f:s}}wNAFUnsafe(e,r,n,o=this.ZERO){let s=ki(e,this.bits);for(let i=0;i<s.windows&&n!==Rr;i++){let{nextN:a,offset:c,isZero:f,isNeg:u}=tu(n,i,s);if(n=a,!f){let l=r[c];o=o.add(u?l.negate():l)}}return ru(n),o}getPrecomputes(e,r,n){let o=Mi.get(r);return o||(o=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(o=n(o)),Mi.set(r,o))),o}cached(e,r,n){let o=Ki(e);return this.wNAF(o,this.getPrecomputes(o,e,n),r)}unsafe(e,r,n,o){let s=Ki(e);return s===1?this._unsafeLadder(e,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),r,o)}createCache(e,r){ou(r,this.bits),su.set(e,r),Mi.delete(e)}hasCache(e){return Ki(e)!==1}};function iu(t,e,r,n){let o=e,s=t.ZERO,i=t.ZERO;for(;r>Rr||n>Rr;)r&nr&&(s=s.add(o)),n&nr&&(i=i.add(o)),o=o.double(),r>>=nr,n>>=nr;return{p1:s,p2:i}}function nu(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ni(e),e}else return Dr(t,{isLE:r})}function Oo(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>Rr))throw new Error(`CURVE.${c} must be positive bigint`)}let o=nu(e.p,r.Fp,n),s=nu(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 Pr(t,e){return function(n){let o=t(n);return{secretKey:o,publicKey:e(o)}}}var Bt=BigInt(0),ye=BigInt(1),Hi=BigInt(2),xp=BigInt(8);function Ep(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 au(t,e={}){let r=e,n=Oo("edwards",t,r,r.FpFnLE),{Fp:o,Fn:s}=n,i=n.CURVE,{h:a}=i;Fe(r,{},{uvRatio:"function"});let c=Hi<<BigInt(s.BYTES*8)-ye,f=S=>o.create(S),u=r.uvRatio===void 0?(S,h)=>{try{return{isValid:!0,value:o.sqrt(o.div(S,h))}}catch{return{isValid:!1,value:Bt}}}:r.uvRatio;if(!Ep(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function l(S,h,y=!1){let v=y?ye:Bt;return ht("coordinate "+S,h,v,c),h}function p(S){if(!(S instanceof d))throw new Error("EdwardsPoint expected")}class d{static BASE=new d(i.Gx,i.Gy,ye,f(i.Gx*i.Gy));static ZERO=new d(Bt,ye,ye,Bt);static Fp=o;static Fn=s;X;Y;Z;T;constructor(h,y,v,T){this.X=l("x",h),this.Y=l("y",y),this.Z=l("z",v,!0),this.T=l("t",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(h){if(h instanceof d)throw new Error("extended point not allowed");let{x:y,y:v}=h||{};return l("x",y),l("y",v),new d(y,v,ye,f(y*v))}static fromBytes(h,y=!1){let v=o.BYTES,{a:T,d:P}=i;h=Lt(z(h,v,"point")),Ge(y,"zip215");let D=Lt(h),O=h[v-1];D[v-1]=O&-129;let R=Ue(D),L=y?c:o.ORDER;ht("point.y",R,Bt,L);let N=f(R*R),k=f(N-ye),U=f(P*N-T),{isValid:m,value:A}=u(k,U);if(!m)throw new Error("bad point: invalid y coordinate");let E=(A&ye)===ye,w=(O&128)!==0;if(!y&&A===Bt&&w)throw new Error("bad point: x=0 and x_0=1");return w!==E&&(A=f(-A)),d.fromAffine({x:A,y:R})}static fromHex(h,y=!1){return d.fromBytes(Lr(h),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,y=!0){return g.createCache(this,h),y||this.multiply(Hi),this}assertValidity(){let h=this,{a:y,d:v}=i;if(h.is0())throw new Error("bad point: ZERO");let{X:T,Y:P,Z:D,T:O}=h,R=f(T*T),L=f(P*P),N=f(D*D),k=f(N*N),U=f(R*y),m=f(N*f(U+L)),A=f(k+f(v*f(R*L)));if(m!==A)throw new Error("bad point: equation left != right (1)");let E=f(T*P),w=f(D*O);if(E!==w)throw new Error("bad point: equation left != right (2)")}equals(h){p(h);let{X:y,Y:v,Z:T}=this,{X:P,Y:D,Z:O}=h,R=f(y*O),L=f(P*T),N=f(v*O),k=f(D*T);return R===L&&N===k}is0(){return this.equals(d.ZERO)}negate(){return new d(f(-this.X),this.Y,this.Z,f(-this.T))}double(){let{a:h}=i,{X:y,Y:v,Z:T}=this,P=f(y*y),D=f(v*v),O=f(Hi*f(T*T)),R=f(h*P),L=y+v,N=f(f(L*L)-P-D),k=R+D,U=k-O,m=R-D,A=f(N*U),E=f(k*m),w=f(N*m),b=f(U*k);return new d(A,E,b,w)}add(h){p(h);let{a:y,d:v}=i,{X:T,Y:P,Z:D,T:O}=this,{X:R,Y:L,Z:N,T:k}=h,U=f(T*R),m=f(P*L),A=f(O*v*k),E=f(D*N),w=f((T+P)*(R+L)-U-m),b=E-A,_=E+A,C=f(m-y*U),x=f(w*b),I=f(_*C),B=f(w*C),F=f(b*_);return new d(x,I,F,B)}subtract(h){return p(h),this.add(h.negate())}multiply(h){if(!s.isValidNot0(h))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:y,f:v}=g.cached(this,h,T=>or(d,T));return or(d,[y,v])[0]}multiplyUnsafe(h){if(!s.isValid(h))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return h===Bt?d.ZERO:this.is0()||h===ye?this:g.unsafe(this,h,y=>or(d,y))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return g.unsafe(this,i.n).is0()}toAffine(h){let y=this,v=h,{X:T,Y:P,Z:D}=y,O=y.is0();v==null&&(v=O?xp:o.inv(D));let R=f(T*v),L=f(P*v),N=o.mul(D,v);if(O)return{x:Bt,y:ye};if(N!==ye)throw new Error("invZ was invalid");return{x:R,y:L}}clearCofactor(){return a===ye?this:this.multiplyUnsafe(a)}toBytes(){let{x:h,y}=this.toAffine(),v=o.toBytes(y);return v[v.length-1]|=h&ye?128:0,v}toHex(){return Ir(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new Or(d,s.BITS);return s.BITS>=8&&d.BASE.precompute(8),Object.freeze(d.prototype),Object.freeze(d),d}var Po=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Oi()}static fromHex(e){Oi()}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 Ir(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 cu(t,e,r={}){if(typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=r;Fe(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&&(je(f,"hash.outputLen"),f!==u))throw new Error(`hash.outputLen must be ${u}, got ${f}`);let l=o.randomBytes===void 0?er:o.randomBytes,p=o.adjustScalarBytes===void 0?m=>m:o.adjustScalarBytes,d=o.domain===void 0?(m,A,E)=>{if(Ge(E,"phflag"),A.length||E)throw new Error("Contexts/pre-hash are not supported");return m}:o.domain;function g(m){return c.create(Ue(m))}function S(m){let A=R.secretKey;z(m,R.secretKey,"secretKey");let E=z(n(m),2*A,"hashedSecretKey"),w=p(E.slice(0,A)),b=E.slice(A,2*A),_=g(w);return{head:w,prefix:b,scalar:_}}function h(m){let{head:A,prefix:E,scalar:w}=S(m),b=i.multiply(w),_=b.toBytes();return{head:A,prefix:E,scalar:w,point:b,pointBytes:_}}function y(m){return h(m).pointBytes}function v(m=Uint8Array.of(),...A){let E=me(...A);return g(n(d(E,z(m,void 0,"context"),!!s)))}function T(m,A,E={}){m=z(m,void 0,"message"),s&&(m=s(m));let{prefix:w,scalar:b,pointBytes:_}=h(A),C=v(E.context,w,m),x=i.multiply(C).toBytes(),I=v(E.context,x,_,m),B=c.create(C+I*b);if(!c.isValid(B))throw new Error("sign failed: invalid s");let F=me(x,c.toBytes(B));return z(F,R.signature,"result")}let P={zip215:o.zip215};function D(m,A,E,w=P){let{context:b}=w,_=w.zip215===void 0?!!P.zip215:w.zip215,C=R.signature;m=z(m,C,"signature"),A=z(A,void 0,"message"),E=z(E,R.publicKey,"publicKey"),_!==void 0&&Ge(_,"zip215"),s&&(A=s(A));let x=C/2,I=m.subarray(0,x),B=Ue(m.subarray(x,C)),F,H,K;try{F=t.fromBytes(E,_),H=t.fromBytes(I,_),K=i.multiplyUnsafe(B)}catch{return!1}if(!_&&F.isSmallOrder())return!1;let J=v(b,I,E,A);return H.add(F.multiplyUnsafe(J)).subtract(K).clearCofactor().is0()}let O=a.BYTES,R={secretKey:O,publicKey:O,signature:2*O,seed:O};function L(m){return m=m===void 0?l(R.seed):m,z(m,R.seed,"seed")}function N(m){return Jt(m)&&m.length===R.secretKey}function k(m,A){try{return!!t.fromBytes(m,A===void 0?P.zip215:A)}catch{return!1}}let U={getExtendedPublicKey:h,randomSecretKey:L,isValidSecretKey:N,isValidPublicKey:k,toMontgomery(m){let{y:A}=t.fromBytes(m),E=R.publicKey,w=E===32;if(!w&&E!==57)throw new Error("only defined for 25519 and 448");let b=w?a.div(ye+A,ye-A):a.div(A-ye,A+ye);return a.toBytes(b)},toMontgomerySecret(m){let A=R.secretKey;z(m,A);let E=n(m.subarray(0,A));return p(E).subarray(0,A)}};return Object.freeze(R),Object.freeze(U),Object.freeze({keygen:Pr(L,y),getPublicKey:y,sign:T,verify:D,utils:U,Point:t,lengths:R})}function An(t,e){if(je(t),je(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 Sp(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 Ap(t){if(!Jt(t)&&typeof t!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof t=="string"?Do(t):t;if(e.length===0)throw new Error("DST must be non-empty");return e}function Vi(t,e,r,n){z(t),je(r),e=Ap(e),e.length>255&&(e=n(me(Do("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=me(e,An(e.length,1)),c=new Uint8Array(s),f=An(r,2),u=new Array(i),l=n(me(c,t,f,An(0,1),a));u[0]=n(me(l,An(1,1),a));for(let d=1;d<i;d++){let g=[Sp(l,u[d-1]),An(d+1,1),a];u[d]=n(me(...g))}return me(...u).slice(0,r)}var fu="HashToScalar-";var vn=BigInt(0),Nr=BigInt(1),No=BigInt(2);function vp(t){return Fe(t,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...t})}function uu(t){let e=vp(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?er:i,f=a?255:448,u=a?32:56,l=BigInt(a?9:5),p=BigInt(a?121665:39081),d=a?No**BigInt(254):No**BigInt(447),g=a?BigInt(8)*No**BigInt(251)-Nr:BigInt(4)*No**BigInt(445)-Nr,S=d+g+Nr,h=E=>ce(E,r),y=v(l);function v(E){return wn(h(E),u)}function T(E){let w=Lt(z(E,u,"uCoordinate"));return a&&(w[31]&=127),h(Ue(w))}function P(E){return Ue(o(Lt(z(E,u,"scalar"))))}function D(E,w){let b=k(T(w),P(E));if(b===vn)throw new Error("invalid private or public key received");return v(b)}function O(E){return D(E,y)}let R=O,L=D;function N(E,w,b){let _=h(E*(w-b));return w=h(w-_),b=h(b+_),{x_2:w,x_3:b}}function k(E,w){ht("u",E,vn,r),ht("scalar",w,d,S);let b=w,_=E,C=Nr,x=vn,I=E,B=Nr,F=vn;for(let K=BigInt(f-1);K>=vn;K--){let J=b>>K&Nr;F^=J,{x_2:C,x_3:I}=N(F,C,I),{x_2:x,x_3:B}=N(F,x,B),F=J;let ee=C+x,te=h(ee*ee),X=C-x,ie=h(X*X),it=te-ie,qt=I+B,yr=I-B,nn=h(yr*ee),on=h(qt*X),Yc=nn+on,Zc=nn-on;I=h(Yc*Yc),B=h(_*h(Zc*Zc)),C=h(te*ie),x=h(it*(te+h(p*it)))}({x_2:C,x_3:I}=N(F,C,I)),{x_2:x,x_3:B}=N(F,x,B);let H=s(x);return h(C*H)}let U={secretKey:u,publicKey:u,seed:u},m=E=>(E=E===void 0?c(u):E,z(E,U.seed,"seed"),E),A={randomSecretKey:m};return Object.freeze(U),Object.freeze(A),Object.freeze({keygen:Pr(m,R),getSharedSecret:L,getPublicKey:R,scalarMult:D,scalarMultBase:O,utils:A,GuBytes:y.slice(),lengths:U})}var _p=BigInt(0),pt=BigInt(1),lu=BigInt(2),Cp=BigInt(3),Tp=BigInt(5),Ip=BigInt(8),sr=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),qi={p:sr,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ip,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function pu(t){let e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=sr,a=t*t%s*t%s,c=se(a,lu,s)*a%s,f=se(c,pt,s)*t%s,u=se(f,Tp,s)*f%s,l=se(u,e,s)*u%s,p=se(l,r,s)*l%s,d=se(p,n,s)*p%s,g=se(d,o,s)*d%s,S=se(g,o,s)*d%s,h=se(S,e,s)*u%s;return{pow_p_5_8:se(h,lu,s)*t%s,b2:a}}function mu(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var $i=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Gi(t,e){let r=sr,n=ce(e*e*e,r),o=ce(n*n*e,r),s=pu(t*o).pow_p_5_8,i=ce(t*n*s,r),a=ce(e*i*i,r),c=i,f=ce(i*$i,r),u=a===t,l=a===ce(-t,r),p=a===ce(-t*$i,r);return u&&(i=c),(l||p)&&(i=f),dt(i,r)&&(i=ce(-i,r)),{isValid:u||l,value:i}}var Rt=au(qi,{uvRatio:Gi}),Dt=Rt.Fp,gu=Rt.Fn;function Lp(t){return cu(Rt,Co,Object.assign({adjustScalarBytes:mu,zip215:!0},t))}var yu=Lp({});var _n=(()=>{let t=sr;return uu({P:t,type:"x25519",powPminus2:e=>{let{pow_p_5_8:r,b2:n}=pu(e);return ce(se(r,Cp,t)*n,t)},adjustScalarBytes:mu})})();var zi=$i,Bp=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Dp=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Rp=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Op=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),hu=t=>Gi(pt,t),Pp=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Wi=t=>Dt.create(Ue(t)&Pp);function du(t){let{d:e}=qi,r=sr,n=y=>Dt.create(y),o=n(zi*t*t),s=n((o+pt)*Rp),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:f}=Gi(s,a),u=n(f*t);dt(u,r)||(u=n(-u)),c||(f=u),c||(i=o);let l=n(i*(o-pt)*Op-a),p=f*f,d=n((f+f)*a),g=n(l*Bp),S=n(pt-p),h=n(pt+p);return new Rt(n(d*h),n(S*g),n(g*h),n(d*S))}var Ot=class t extends Po{static BASE=new t(Rt.BASE);static ZERO=new t(Rt.ZERO);static Fp=Dt;static Fn=gu;constructor(e){super(e)}static fromAffine(e){return new t(Rt.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoPoint expected")}init(e){return new t(e)}static fromBytes(e){_e(e,32);let{a:r,d:n}=qi,o=sr,s=P=>Dt.create(P),i=Wi(e);if(!Vf(Dt.toBytes(i),e)||dt(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(pt+r*a),f=s(pt-r*a),u=s(c*c),l=s(f*f),p=s(r*n*u-l),{isValid:d,value:g}=hu(s(p*l)),S=s(g*f),h=s(g*S*p),y=s((i+i)*S);dt(y,o)&&(y=s(-y));let v=s(c*h),T=s(y*v);if(!d||dt(T,o)||v===_p)throw new Error("invalid ristretto255 encoding 2");return new t(new Rt(y,v,pt,T))}static fromHex(e){return t.fromBytes(pn(e))}toBytes(){let{X:e,Y:r,Z:n,T:o}=this.ep,s=sr,i=h=>Dt.create(h),a=i(i(n+r)*i(n-r)),c=i(e*r),f=i(c*c),{value:u}=hu(i(a*f)),l=i(u*a),p=i(u*c),d=i(l*p*o),g;if(dt(o*d,s)){let h=i(r*zi),y=i(e*zi);e=h,r=y,g=i(l*Dp)}else g=p;dt(e*d,s)&&(r=i(-r));let S=i((n-r)*g);return dt(S,s)&&(S=i(-S)),Dt.toBytes(S)}equals(e){this.assertSame(e);let{X:r,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=f=>Dt.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(Ot.BASE);Object.freeze(Ot.ZERO);Object.freeze(Ot.prototype);Object.freeze(Ot);var Np=Object.freeze({Point:Ot,hashToCurve(t,e){let r=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,n=Vi(t,r,64,Co);return Np.deriveToCurve(n)},hashToScalar(t,e={DST:fu}){let r=Vi(t,e.DST,64,Co);return gu.create(Ue(r))},deriveToCurve(t){_e(t,64);let e=Wi(t.subarray(0,32)),r=du(e),n=Wi(t.subarray(32,64)),o=du(n);return new Ot(r.add(o))}});var Cn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},Uo=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var bu={get(t=globalThis){let e=t.crypto;if(e?.subtle==null)throw new Uo("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 He=bu;var Fo=32;var ji,Up=(async()=>{try{return await He.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Fp(t,e,r){if(t.buffer instanceof ArrayBuffer){let n=await He.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await He.get().subtle.verify({name:"Ed25519"},n,e,r instanceof Uint8Array?r:r.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function kp(t,e,r){return yu.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}async function wu(t,e,r){return ji==null&&(ji=await Up),ji?Fp(t,e,r):kp(t,e,r)}function ko(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var Mo=class{type="Ed25519";raw;constructor(e){this.raw=Xi(e,Fo)}toMultihash(){return ze.digest(_t(this))}toCID(){return de.createV1(114,this.toMultihash())}toString(){return le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();let o=wu(this.raw,r,e);return ko(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Yi(t){return t=Xi(t,Fo),new Mo(t)}function Xi(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new G(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}var Kp=Math.pow(2,7),Hp=Math.pow(2,14),Vp=Math.pow(2,21),Zi=Math.pow(2,28),Qi=Math.pow(2,35),Ji=Math.pow(2,42),ea=Math.pow(2,49),Z=128,Ce=127;function re(t){if(t<Kp)return 1;if(t<Hp)return 2;if(t<Vp)return 3;if(t<Zi)return 4;if(t<Qi)return 5;if(t<Ji)return 6;if(t<ea)return 7;if(Number.MAX_SAFE_INTEGER!=null&&t>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Pt(t,e,r=0){switch(re(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 $p(t,e,r=0){switch(re(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 Tn(t,e){let r=t[e],n=0;if(n+=r&Ce,r<Z||(r=t[e+1],n+=(r&Ce)<<7,r<Z)||(r=t[e+2],n+=(r&Ce)<<14,r<Z)||(r=t[e+3],n+=(r&Ce)<<21,r<Z)||(r=t[e+4],n+=(r&Ce)*Zi,r<Z)||(r=t[e+5],n+=(r&Ce)*Qi,r<Z)||(r=t[e+6],n+=(r&Ce)*Ji,r<Z)||(r=t[e+7],n+=(r&Ce)*ea,r<Z))return n;throw new RangeError("Could not decode varint")}function zp(t,e){let r=t.get(e),n=0;if(n+=r&Ce,r<Z||(r=t.get(e+1),n+=(r&Ce)<<7,r<Z)||(r=t.get(e+2),n+=(r&Ce)<<14,r<Z)||(r=t.get(e+3),n+=(r&Ce)<<21,r<Z)||(r=t.get(e+4),n+=(r&Ce)*Zi,r<Z)||(r=t.get(e+5),n+=(r&Ce)*Qi,r<Z)||(r=t.get(e+6),n+=(r&Ce)*Ji,r<Z)||(r=t.get(e+7),n+=(r&Ce)*ea,r<Z))return n;throw new RangeError("Could not decode varint")}function Ko(t,e,r=0){return e==null&&(e=ae(re(t))),e instanceof Uint8Array?Pt(t,e,r):$p(t,e,r)}function mt(t,e=0){return t instanceof Uint8Array?Tn(t,e):zp(t,e)}var ta=new Float32Array([-0]),Nt=new Uint8Array(ta.buffer);function Eu(t,e,r){ta[0]=t,e[r]=Nt[0],e[r+1]=Nt[1],e[r+2]=Nt[2],e[r+3]=Nt[3]}function Su(t,e){return Nt[0]=t[e],Nt[1]=t[e+1],Nt[2]=t[e+2],Nt[3]=t[e+3],ta[0]}var ra=new Float64Array([-0]),Te=new Uint8Array(ra.buffer);function Au(t,e,r){ra[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 vu(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],ra[0]}var Wp=BigInt(Number.MAX_SAFE_INTEGER),qp=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 ir;if(e<Wp&&e>qp)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>_u&&(o=0n,++n>_u&&(n=0n))),new t(Number(o),Number(n))}static fromNumber(e){if(e===0)return ir;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):ir}},ir=new ke(0,0);ir.toBigInt=function(){return 0n};ir.zzEncode=ir.zzDecode=function(){return this};ir.length=function(){return 1};var _u=4294967296n;function Cu(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 Tu(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 na(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 Xe(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function Ho(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}var oa=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,Xe(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 Xe(this,4);return Ho(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Xe(this,4);return Ho(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Xe(this,4);let e=Su(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Xe(this,4);let e=vu(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 Xe(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let e=this.bytes();return Tu(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Xe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Xe(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 Xe(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 Xe(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 Xe(this,8);let e=Ho(this.buf,this.pos+=4),r=Ho(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=Tn(this.buf,this.pos);return this.pos+=re(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 Ln(t){return new oa(t instanceof Uint8Array?t:t.subarray())}function Ut(t,e,r){let n=Ln(t);return e.decode(n,void 0,r)}function sa(t){let e=t??8192,r=e>>>1,n,o=e;return function(i){if(i<1||i>r)return ae(i);o+i>e&&(n=ae(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var ar=class{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}};function ia(){}var ca=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Gp=sa();function jp(t){return globalThis.Buffer!=null?ae(t):Gp(t)}var Dn=class{len;head;tail;states;constructor(){this.len=0,this.head=new ar(ia,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new ar(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new fa((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(Vo,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(Vo,r.length(),r)}uint64Number(e){return this._push(Pt,re(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(Vo,r.length(),r)}sint64Number(e){let r=ke.fromNumber(e).zzEncode();return this._push(Vo,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(aa,1,e?1:0)}fixed32(e){return this._push(Bn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let r=ke.fromBigInt(e);return this._push(Bn,4,r.lo)._push(Bn,4,r.hi)}fixed64Number(e){let r=ke.fromNumber(e);return this._push(Bn,4,r.lo)._push(Bn,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(Eu,4,e)}double(e){return this._push(Au,8,e)}bytes(e){let r=e.length>>>0;return r===0?this._push(aa,1,0):this.uint32(r)._push(Yp,r,e)}string(e){let r=Cu(e);return r!==0?this.uint32(r)._push(na,r,e):this._push(aa,1,0)}fork(){return this.states=new ca(this),this.head=this.tail=new ar(ia,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 ar(ia,0,0),this.len=0),this}ldelim(){let e=this.head,r=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=r,this.len+=n),this}finish(){let e=this.head.next,r=jp(this.len),n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}};function aa(t,e,r){e[r]=t&255}function Xp(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}var fa=class extends ar{next;constructor(e,r){super(Xp,e,r),this.next=void 0}};function Vo(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 Bn(t,e,r){e[r]=t&255,e[r+1]=t>>>8&255,e[r+2]=t>>>16&255,e[r+3]=t>>>24}function Yp(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(Dn.prototype.bytes=function(t){let e=t.length>>>0;return this.uint32(e),e>0&&this._push(Zp,e,t),this},Dn.prototype.string=function(t){let e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(Qp,e,t),this});function Zp(t,e,r){e.set(t,r)}function Qp(t,e,r){t.length<40?na(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(W(t),r)}function ua(){return new Dn}function Ft(t,e){let r=ua();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}function*kt(t,e,r){let n=Ln(t);yield*e.stream(n,void 0,"$",r)}var $o={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5};function zo(t,e,r,n,o){return{name:t,type:e,encode:r,decode:n,stream:o}}function cr(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 zo("enum",$o.VARINT,r,n,o)}function Mt(t,e,r){return zo("message",$o.LENGTH_DELIMITED,t,e,r)}var fe;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(fe||(fe={}));var la;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(la||(la={}));(function(t){t.codec=()=>cr(la)})(fe||(fe={}));var nt;(function(t){let e;t.codec=()=>(e==null&&(e=Mt((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 Ft(s,t.codec())}t.encode=r;function n(s,i){return Ut(s,t.codec(),i)}t.decode=n;function o(s,i){return kt(s,t.codec(),i)}t.stream=o})(nt||(nt={}));var ha;(function(t){let e;t.codec=()=>(e==null&&(e=Mt((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 Ft(s,t.codec())}t.encode=r;function n(s,i){return Ut(s,t.codec(),i)}t.decode=n;function o(s,i){return kt(s,t.codec(),i)}t.stream=o})(ha||(ha={}));var On={};De(On,{MAX_RSA_KEY_SIZE:()=>da,generateRSAKeyPair:()=>Ou,jwkToJWKKeyPair:()=>Pu,jwkToPkcs1:()=>rm,jwkToPkix:()=>ya,jwkToRSAPrivateKey:()=>Ea,pkcs1MessageToJwk:()=>ma,pkcs1MessageToRSAPrivateKey:()=>ba,pkcs1ToJwk:()=>tm,pkcs1ToRSAPrivateKey:()=>Ru,pkixMessageToJwk:()=>ga,pkixMessageToRSAPublicKey:()=>xa,pkixToJwk:()=>nm,pkixToRSAPublicKey:()=>wa});var Ur=class{type="RSA";jwk;_raw;_multihash;constructor(e,r){this.jwk=e,this._multihash=r}get raw(){return this._raw==null&&(this._raw=On.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return de.createV1(114,this._multihash)}toString(){return le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}verify(e,r,n){return Du(this.jwk,r,e,n)}},Rn=class{type="RSA";jwk;_raw;publicKey;constructor(e,r){this.jwk=e,this.publicKey=r}get raw(){return this._raw==null&&(this._raw=On.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}sign(e,r){return Bu(this.jwk,e,r)}};var da=8192,pa=18,Jp=1062,em=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function tm(t){let e=ft(t);return ma(e)}function ma(t){return{n:V(t[1],"base64url"),e:V(t[2],"base64url"),d:V(t[3],"base64url"),p:V(t[4],"base64url"),q:V(t[5],"base64url"),dp:V(t[6],"base64url"),dq:V(t[7],"base64url"),qi:V(t[8],"base64url"),kty:"RSA"}}function rm(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 G("JWK was missing components");return vt([Pe(Uint8Array.from([0])),Pe(W(t.n,"base64url")),Pe(W(t.e,"base64url")),Pe(W(t.d,"base64url")),Pe(W(t.p,"base64url")),Pe(W(t.q,"base64url")),Pe(W(t.dp,"base64url")),Pe(W(t.dq,"base64url")),Pe(W(t.qi,"base64url"))]).subarray()}function nm(t){let e=ft(t,{offset:0});return ga(e)}function ga(t){let e=ft(t[1],{offset:0});return{kty:"RSA",n:V(e[0],"base64url"),e:V(e[1],"base64url")}}function ya(t){if(t.n==null||t.e==null)throw new G("JWK was missing components");return vt([em,Eo(vt([Pe(W(t.n,"base64url")),Pe(W(t.e,"base64url"))]))]).subarray()}function Ru(t){let e=ft(t);return ba(e)}function ba(t){let e=ma(t);return Ea(e)}function wa(t,e){if(t.byteLength>=Jp)throw new br("Key size is too large");let r=ft(t,{offset:0});return xa(r,t,e)}function xa(t,e,r){let n=ga(t);if(r==null){let o=rt(nt.encode({Type:fe.RSA,Data:e}));r=Re(pa,o)}return new Ur(n,r)}function Ea(t){if(Uu(t)>da)throw new G("Key size is too large");let e=Pu(t),r=rt(nt.encode({Type:fe.RSA,Data:ya(e.publicKey)})),n=Re(pa,r);return new Rn(e.privateKey,new Ur(e.publicKey,n))}async function Ou(t){if(t>da)throw new G("Key size is too large");let e=await Nu(t),r=rt(nt.encode({Type:fe.RSA,Data:ya(e.publicKey)})),n=Re(pa,r);return new Rn(e.privateKey,new Ur(e.publicKey,n))}function Pu(t){if(t==null)throw new G("Missing key parameter");return{privateKey:t,publicKey:{kty:t.kty,n:t.n,e:t.e}}}async function Nu(t,e){let r=await He.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 om(r,e);return{privateKey:n[0],publicKey:n[1]}}async function Bu(t,e,r){let n=await He.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);r?.signal?.throwIfAborted();let o=await He.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return r?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Du(t,e,r,n){let o=await He.get().subtle.importKey("jwk",t,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await He.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,r instanceof Uint8Array?r:r.subarray());return n?.signal?.throwIfAborted(),s}async function om(t,e){if(t.privateKey==null||t.publicKey==null)throw new G("Private and public key are required");let r=await Promise.all([He.get().subtle.exportKey("jwk",t.privateKey),He.get().subtle.exportKey("jwk",t.publicKey)]);return e?.signal?.throwIfAborted(),r}function Uu(t){if(t.kty!=="RSA")throw new G("invalid key type");if(t.n==null)throw new G("invalid key modulus");return W(t.n,"base64url").length*8}var Wo=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(Yt(e),_e(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 Tr(this),this.iHash.update(e),this}digestInto(e){Tr(this),So(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()}},Pn=(()=>{let t=((e,r,n)=>new Wo(e,r).update(n).digest());return t.create=(e,r)=>new Wo(e,r),t})();var Fu=(t,e)=>(t+(t>=0?e:-e)/ku)/e;function sm(t,e,r){ht("scalar",t,ot,r);let[[n,o],[s,i]]=e,a=Fu(i*t,r),c=Fu(-o*t,r),f=t-a*n-c*s,u=-a*o-c*i,l=f<ot,p=u<ot;l&&(f=-f),p&&(u=-u);let d=xn(Math.ceil(Br(r)/2))+Kt;if(f<ot||f>=d||u<ot||u>=d)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:l,k1:f,k2neg:p,k2:u}}function Aa(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Sa(t,e){Fe(t);let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Ge(r.lowS,"lowS"),Ge(r.prehash,"prehash"),r.format!==void 0&&Aa(r.format),r}var va=class extends Error{constructor(e=""){super(e)}},Ye={Err:va,_tlv:{encode:(t,e)=>{let{Err:r}=Ye;if(je(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=bn(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?bn(o.length/2|128):"";return bn(t)+s+o+e},decode(t,e){let{Err:r}=Ye;e=z(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}=Ye;if(Lo(t),t<ot)throw new e("integer: negative integers are not allowed");let r=bn(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}=Ye;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 tr(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=Ye,o=z(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}=Ye,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(Ye._tlv);Object.freeze(Ye._int);Object.freeze(Ye);var ot=BigInt(0),Kt=BigInt(1),ku=BigInt(2),qo=BigInt(3),im=BigInt(4);function Mu(t,e={}){let r=Oo("weierstrass",t,e),n=r.Fp,o=r.Fn,s=r.CURVE,{h:i,n:a}=s;Fe(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=Hu(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(U,m,A){if(f&&m.is0())return Uint8Array.of(0);let{x:E,y:w}=m.toAffine(),b=n.toBytes(E);if(Ge(A,"isCompressed"),A){l();let _=!n.isOdd(w);return me(Ku(_),b)}else return me(Uint8Array.of(4),b,n.toBytes(w))}function d(U){z(U,void 0,"Point");let{publicKey:m,publicKeyUncompressed:A}=u,E=U.length,w=U[0],b=U.subarray(1);if(f&&E===1&&w===0)return{x:n.ZERO,y:n.ZERO};if(E===m&&(w===2||w===3)){let _=n.fromBytes(b);if(!n.isValid(_))throw new Error("bad point: is not on curve, wrong x");let C=h(_),x;try{x=n.sqrt(C)}catch(F){let H=F instanceof Error?": "+F.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}l();let I=n.isOdd(x);return(w&1)===1!==I&&(x=n.neg(x)),{x:_,y:x}}else if(E===A&&w===4){let _=n.BYTES,C=n.fromBytes(b.subarray(0,_)),x=n.fromBytes(b.subarray(_,_*2));if(!y(C,x))throw new Error("bad point: is not on curve");return{x:C,y:x}}else throw new Error(`bad point: got length ${E}, expected compressed=${m} or uncompressed=${A}`)}let g=e.toBytes===void 0?p:e.toBytes,S=e.fromBytes===void 0?d:e.fromBytes;function h(U){let m=n.sqr(U),A=n.mul(m,U);return n.add(n.add(A,n.mul(U,s.a)),s.b)}function y(U,m){let A=n.sqr(m),E=h(U);return n.eql(A,E)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let v=n.mul(n.pow(s.a,qo),im),T=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(v,T)))throw new Error("bad curve params: a or b");function P(U,m,A=!1){if(!n.isValid(m)||A&&n.is0(m))throw new Error(`bad point coordinate ${U}`);return m}function D(U){if(!(U instanceof L))throw new Error("Weierstrass Point expected")}function O(U){if(!c||!c.basises)throw new Error("no endo");return sm(U,c.basises,o.ORDER)}function R(U,m,A,E,w){return A=new L(n.mul(A.X,U),A.Y,A.Z),m=Sn(E,m),A=Sn(w,A),m.add(A)}class L{static BASE=new L(s.Gx,s.Gy,n.ONE);static ZERO=new L(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(m,A,E){this.X=P("x",m),this.Y=P("y",A,!0),this.Z=P("z",E),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){let{x:A,y:E}=m||{};if(!m||!n.isValid(A)||!n.isValid(E))throw new Error("invalid affine point");if(m instanceof L)throw new Error("projective point not allowed");return n.is0(A)&&n.is0(E)?L.ZERO:new L(A,E,n.ONE)}static fromBytes(m){let A=L.fromAffine(S(z(m,void 0,"point")));return A.assertValidity(),A}static fromHex(m){return L.fromBytes(Lr(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,A=!0){return k.createCache(this,m),A||this.multiply(qo),this}assertValidity(){let m=this;if(m.is0()){if(e.allowInfinityPoint&&n.is0(m.X)&&n.eql(m.Y,n.ONE)&&n.is0(m.Z))return;throw new Error("bad point: ZERO")}let{x:A,y:E}=m.toAffine();if(!n.isValid(A)||!n.isValid(E))throw new Error("bad point: x or y not field elements");if(!y(A,E))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:m}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(m)}equals(m){D(m);let{X:A,Y:E,Z:w}=this,{X:b,Y:_,Z:C}=m,x=n.eql(n.mul(A,C),n.mul(b,w)),I=n.eql(n.mul(E,C),n.mul(_,w));return x&&I}negate(){return new L(this.X,n.neg(this.Y),this.Z)}double(){let{a:m,b:A}=s,E=n.mul(A,qo),{X:w,Y:b,Z:_}=this,C=n.ZERO,x=n.ZERO,I=n.ZERO,B=n.mul(w,w),F=n.mul(b,b),H=n.mul(_,_),K=n.mul(w,b);return K=n.add(K,K),I=n.mul(w,_),I=n.add(I,I),C=n.mul(m,I),x=n.mul(E,H),x=n.add(C,x),C=n.sub(F,x),x=n.add(F,x),x=n.mul(C,x),C=n.mul(K,C),I=n.mul(E,I),H=n.mul(m,H),K=n.sub(B,H),K=n.mul(m,K),K=n.add(K,I),I=n.add(B,B),B=n.add(I,B),B=n.add(B,H),B=n.mul(B,K),x=n.add(x,B),H=n.mul(b,_),H=n.add(H,H),B=n.mul(H,K),C=n.sub(C,B),I=n.mul(H,F),I=n.add(I,I),I=n.add(I,I),new L(C,x,I)}add(m){D(m);let{X:A,Y:E,Z:w}=this,{X:b,Y:_,Z:C}=m,x=n.ZERO,I=n.ZERO,B=n.ZERO,F=s.a,H=n.mul(s.b,qo),K=n.mul(A,b),J=n.mul(E,_),ee=n.mul(w,C),te=n.add(A,E),X=n.add(b,_);te=n.mul(te,X),X=n.add(K,J),te=n.sub(te,X),X=n.add(A,w);let ie=n.add(b,C);return X=n.mul(X,ie),ie=n.add(K,ee),X=n.sub(X,ie),ie=n.add(E,w),x=n.add(_,C),ie=n.mul(ie,x),x=n.add(J,ee),ie=n.sub(ie,x),B=n.mul(F,X),x=n.mul(H,ee),B=n.add(x,B),x=n.sub(J,B),B=n.add(J,B),I=n.mul(x,B),J=n.add(K,K),J=n.add(J,K),ee=n.mul(F,ee),X=n.mul(H,X),J=n.add(J,ee),ee=n.sub(K,ee),ee=n.mul(F,ee),X=n.add(X,ee),K=n.mul(J,X),I=n.add(I,K),K=n.mul(ie,X),x=n.mul(te,x),x=n.sub(x,K),K=n.mul(te,J),B=n.mul(ie,B),B=n.add(B,K),new L(x,I,B)}subtract(m){return D(m),this.add(m.negate())}is0(){return this.equals(L.ZERO)}multiply(m){let{endo:A}=e;if(!o.isValidNot0(m))throw new RangeError("invalid scalar: out of range");let E,w,b=_=>k.cached(this,_,C=>or(L,C));if(A){let{k1neg:_,k1:C,k2neg:x,k2:I}=O(m),{p:B,f:F}=b(C),{p:H,f:K}=b(I);w=F.add(K),E=R(A.beta,B,H,_,x)}else{let{p:_,f:C}=b(m);E=_,w=C}return or(L,[E,w])[0]}multiplyUnsafe(m){let{endo:A}=e,E=this,w=m;if(!o.isValid(w))throw new RangeError("invalid scalar: out of range");if(w===ot||E.is0())return L.ZERO;if(w===Kt)return E;if(k.hasCache(this))return this.multiply(w);if(A){let{k1neg:b,k1:_,k2neg:C,k2:x}=O(w),{p1:I,p2:B}=iu(L,E,_,x);return R(A.beta,I,B,b,C)}else return k.unsafe(E,w)}toAffine(m){let A=this,E=m,{X:w,Y:b,Z:_}=A;if(n.eql(_,n.ONE))return{x:w,y:b};let C=A.is0();E==null&&(E=C?n.ONE:n.inv(_));let x=n.mul(w,E),I=n.mul(b,E),B=n.mul(_,E);if(C)return{x:n.ZERO,y:n.ZERO};if(!n.eql(B,n.ONE))throw new Error("invZ was invalid");return{x,y:I}}isTorsionFree(){let{isTorsionFree:m}=e;return i===Kt?!0:m?m(L,this):k.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:m}=e;return i===Kt?this:m?m(L,this):this.multiplyUnsafe(i)}isSmallOrder(){return i===Kt?this.is0():this.clearCofactor().is0()}toBytes(m=!0){return Ge(m,"isCompressed"),this.assertValidity(),g(L,this,m)}toHex(m=!0){return Ir(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=o.BITS,k=new Or(L,e.endo?Math.ceil(N/2):N);return N>=8&&L.BASE.precompute(8),Object.freeze(L.prototype),Object.freeze(L),L}function Ku(t){return Uint8Array.of(t?2:3)}function Hu(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function am(t,e={}){let{Fn:r}=t,n=e.randomBytes===void 0?er:e.randomBytes,o=Object.assign(Hu(t.Fp,r),{seed:Math.max(Ui(r.ORDER),16)});function s(d){try{let g=r.fromBytes(d);return r.isValidNot0(g)}catch{return!1}}function i(d,g){let{publicKey:S,publicKeyUncompressed:h}=o;try{let y=d.length;return g===!0&&y!==S||g===!1&&y!==h?!1:!!t.fromBytes(d)}catch{return!1}}function a(d){return d=d===void 0?n(o.seed):d,Fi(z(d,o.seed,"seed"),r.ORDER)}function c(d,g=!0){return t.BASE.multiply(r.fromBytes(d)).toBytes(g)}function f(d){let{secretKey:g,publicKey:S,publicKeyUncompressed:h}=o,y=r._lengths;if(!Jt(d))return;let v=z(d,void 0,"key").length,T=v===S||v===h,P=v===g||!!y?.includes(v);if(!(T&&P))return T}function u(d,g,S=!0){if(f(d)===!0)throw new Error("first arg must be private key");if(f(g)===!1)throw new Error("second arg must be public key");let h=r.fromBytes(d);return t.fromBytes(g).multiply(h).toBytes(S)}let l={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},p=Pr(a,c);return Object.freeze(l),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:p,Point:t,utils:l,lengths:o})}function Vu(t,e,r={}){let n=e;Yt(n),Fe(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let o=r.randomBytes===void 0?er:r.randomBytes,s=r.hmac===void 0?(w,b)=>Pn(n,w,b):r.hmac,{Fp:i,Fn:a}=t,{ORDER:c,BITS:f}=a,{keygen:u,getPublicKey:l,getSharedSecret:p,utils:d,lengths:g}=am(t,r),S={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},h=c*ku+Kt<i.ORDER;function y(w){let b=c>>Kt;return w>b}function v(w,b){if(!a.isValidNot0(b))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return b}function T(){if(h)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function P(w,b){Aa(b);let _=g.signature,C=b==="compact"?_:b==="recovered"?_+1:void 0;return z(w,C)}class D{r;s;recovery;constructor(b,_,C){if(this.r=v("r",b),this.s=v("s",_),C!=null){if(T(),![0,1,2,3].includes(C))throw new Error("invalid recovery id");this.recovery=C}Object.freeze(this)}static fromBytes(b,_=S.format){P(b,_);let C;if(_==="der"){let{r:F,s:H}=Ye.toSig(z(b));return new D(F,H)}_==="recovered"&&(C=b[0],_="compact",b=b.subarray(1));let x=g.signature/2,I=b.subarray(0,x),B=b.subarray(x,x*2);return new D(a.fromBytes(I),a.fromBytes(B),C)}static fromHex(b,_){return this.fromBytes(Lr(b),_)}assertRecovery(){let{recovery:b}=this;if(b==null)throw new Error("invalid recovery id: must be present");return b}addRecoveryBit(b){return new D(this.r,this.s,b)}recoverPublicKey(b){let{r:_,s:C}=this,x=this.assertRecovery(),I=x===2||x===3?_+c:_;if(!i.isValid(I))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let B=i.toBytes(I),F=t.fromBytes(me(Ku((x&1)===0),B)),H=a.inv(I),K=R(z(b,void 0,"msgHash")),J=a.create(-K*H),ee=a.create(C*H),te=t.BASE.multiplyUnsafe(J).add(F.multiplyUnsafe(ee));if(te.is0())throw new Error("invalid recovery: point at infinify");return te.assertValidity(),te}hasHighS(){return y(this.s)}toBytes(b=S.format){if(Aa(b),b==="der")return Lr(Ye.hexFromSig(this));let{r:_,s:C}=this,x=a.toBytes(_),I=a.toBytes(C);return b==="recovered"?(T(),me(Uint8Array.of(this.assertRecovery()),x,I)):me(x,I)}toHex(b){return Ir(this.toBytes(b))}}Object.freeze(D.prototype),Object.freeze(D);let O=r.bits2int===void 0?function(b){if(b.length>8192)throw new Error("input is too large");let _=tr(b),C=b.length*8-f;return C>0?_>>BigInt(C):_}:r.bits2int,R=r.bits2int_modN===void 0?function(b){return a.create(O(b))}:r.bits2int_modN,L=xn(f);function N(w){return ht("num < 2^"+f,w,ot,L),a.toBytes(w)}function k(w,b){return z(w,void 0,"message"),b?z(n(w),void 0,"prehashed message"):w}function U(w,b,_){let{lowS:C,prehash:x,extraEntropy:I}=Sa(_,S);w=k(w,x);let B=R(w),F=a.fromBytes(b);if(!a.isValidNot0(F))throw new Error("invalid private key");let H=[N(F),N(B)];if(I!=null&&I!==!1){let te=I===!0?o(g.secretKey):I;H.push(z(te,void 0,"extraEntropy"))}let K=me(...H),J=B;function ee(te){let X=O(te);if(!a.isValidNot0(X))return;let ie=a.inv(X),it=t.BASE.multiply(X).toAffine(),qt=a.create(it.x);if(qt===ot)return;let yr=a.create(ie*a.create(J+qt*F));if(yr===ot)return;let nn=(it.x===qt?0:2)|Number(it.y&Kt),on=yr;return C&&y(yr)&&(on=a.neg(yr),nn^=1),new D(qt,on,h?void 0:nn)}return{seed:K,k2sig:ee}}function m(w,b,_={}){let{seed:C,k2sig:x}=U(w,b,_);return $f(n.outputLen,a.BYTES,s)(C,x).toBytes(_.format)}function A(w,b,_,C={}){let{lowS:x,prehash:I,format:B}=Sa(C,S);if(_=z(_,void 0,"publicKey"),b=k(b,I),!Jt(w)){let F=w instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+F)}P(w,B);try{let F=D.fromBytes(w,B),H=t.fromBytes(_);if(x&&F.hasHighS())return!1;let{r:K,s:J}=F,ee=R(b),te=a.inv(J),X=a.create(ee*te),ie=a.create(K*te),it=t.BASE.multiplyUnsafe(X).add(H.multiplyUnsafe(ie));return it.is0()?!1:a.create(it.x)===K}catch{return!1}}function E(w,b,_={}){let{prehash:C}=Sa(_,S);return b=k(b,C),D.fromBytes(w,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:p,utils:d,lengths:g,Point:t,sign:m,verify:A,recoverPublicKey:E,Signature:D,hash:n})}var Ca={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},cm={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var $u=BigInt(2);function fm(t){let e=Ca.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,l=se(u,r,e)*u%e,p=se(l,r,e)*u%e,d=se(p,$u,e)*f%e,g=se(d,o,e)*d%e,S=se(g,s,e)*g%e,h=se(S,a,e)*S%e,y=se(h,c,e)*h%e,v=se(y,a,e)*S%e,T=se(v,r,e)*u%e,P=se(T,i,e)*g%e,D=se(P,n,e)*f%e,O=se(D,$u,e);if(!_a.eql(_a.sqr(O),t))throw new Error("Cannot find square root");return O}var _a=Dr(Ca.p,{sqrt:fm}),um=Mu(Ca,{Fp:_a,endo:cm}),Fr=Vu(um,rt);function zu(t,e,r,n){let o=ct.digest(r instanceof Uint8Array?r:r.subarray());if(ko(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Fr.verify(e,s,t,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new Cn(String(s))});try{return n?.signal?.throwIfAborted(),Fr.verify(e,o.digest,t,{prehash:!1,format:"der"})}catch(s){throw new Cn(String(s))}}var Go=class{type="secp256k1";raw;_key;constructor(e){this._key=qu(e),this.raw=Wu(this._key)}toMultihash(){return ze.digest(_t(this))}toCID(){return de.createV1(114,this.toMultihash())}toString(){return le.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:we(this.raw,e.raw)}verify(e,r,n){return zu(this._key,r,e,n)}};function Ta(t){return new Go(t)}function Wu(t){return Fr.Point.fromBytes(t).toBytes()}function qu(t){try{return Fr.Point.fromBytes(t),t}catch(e){throw new br(String(e))}}function Nn(t,e){let{Type:r,Data:n}=nt.decode(t),o=n??new Uint8Array;switch(r){case fe.RSA:return wa(o,e);case fe.Ed25519:return Yi(o);case fe.secp256k1:return Ta(o);case fe.ECDSA:return xi(o);default:throw new Gt}}function Gu(t){let{Type:e,Data:r}=nt.decode(t.digest),n=r??new Uint8Array;switch(e){case fe.Ed25519:return Yi(n);case fe.secp256k1:return Ta(n);case fe.ECDSA:return xi(n);default:throw new Gt}}function _t(t){return nt.encode({Type:fe[t.type],Data:t.raw})}var ju=Symbol.for("nodejs.util.inspect.custom"),lm=114,Un=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()})`}[qs]=!0;toString(){return this.string==null&&(this.string=le.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return de.createV1(lm,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return we(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return we(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[ju](){return`PeerId(${this.toString()})`}},Fn=class extends Un{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},kn=class extends Un{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Mn=class extends Un{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},hm=2336,Kn=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ze.digest(W(this.url))}[ju](){return`PeerId(${this.url})`}[qs]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return de.createV1(hm,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=V(e)),e.toString()===this.toString())}};var dm=114,Xu=2336;function kr(t,e){let r;if(t.charAt(0)==="1"||t.charAt(0)==="Q")r=_r(le.decode(`z${t}`));else{if(t.startsWith("k51qzi5uqu5")||t.startsWith("kzwfwjn5ji4")||t.startsWith("k2k4r8")||t.startsWith("bafz"))return pm(de.parse(t));if(e==null)throw new G('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=_r(e.decode(t))}return Yu(r)}function Ia(t){if(t.type==="Ed25519")return new kn({multihash:t.toCID().multihash,publicKey:t});if(t.type==="secp256k1")return new Mn({multihash:t.toCID().multihash,publicKey:t});if(t.type==="RSA")return new Fn({multihash:t.toCID().multihash,publicKey:t});throw new Gt}function Yu(t){if(gm(t))return new Fn({multihash:t});if(mm(t))try{let e=Gu(t);if(e.type==="Ed25519")return new kn({multihash:t,publicKey:e});if(e.type==="secp256k1")return new Mn({multihash:t,publicKey:e})}catch{let r=V(t.digest);return new Kn(new URL(r))}throw new lo("Supplied PeerID Multihash is invalid")}function pm(t){if(t?.multihash==null||t.version==null||t.version===1&&t.code!==dm&&t.code!==Xu)throw new uo("Supplied PeerID CID is invalid");if(t.code===Xu){let e=V(t.multihash.digest);return new Kn(new URL(e))}return Yu(t.multihash)}function mm(t){return t.code===ze.code}function gm(t){return t.code===ct.code}var Se=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},gt=class extends Error{static name="ValidationError";name="ValidationError"},jo=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},Xo=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var Yo=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 l=this.readChar();if(l===void 0)return;let p=Number.parseInt(l,e);if(!Number.isNaN(p))return p});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 ym=45,bm=15,Zo=new Yo;function Zu(t){if(!(t.length>bm))return Zo.new(t).parseWith(()=>Zo.readIPv4Addr())}function Qu(t){if(t.includes("%")&&(t=t.split("%")[0]),!(t.length>ym))return Zo.new(t).parseWith(()=>Zo.readIPv6Addr())}function Qo(t){return!!Zu(t)}function Ju(t){return!!Qu(t)}function Ba(t){return e=>V(e,t)}function Da(t){return e=>W(e,t)}function Mr(t){return new DataView(t.buffer).getUint16(t.byteOffset).toString()}function fr(t){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof t=="string"?parseInt(t):t),new Uint8Array(e)}function el(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=W(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=fr(n);return Oe([r,o],r.length+o.length)}function tl(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=At.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=fr(n);return Oe([r,o],r.length+o.length)}function Ra(t){let e=t.subarray(0,t.length-2),r=t.subarray(t.length-2),n=V(e,"base32"),o=Mr(r);return`${n}:${o}`}var Oa=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 Se("Invalid byte value in IP address");e[n]=o}),e},rl=function(t){let e=0;t=t.toString().trim();let r=t.split(":",8),n;for(n=0;n<r.length;n++){let s=Qo(r[n]),i;s&&(i=Oa(r[n]),r[n]=V(i.subarray(0,2),"base16")),i!=null&&++n<8&&r.splice(n,0,V(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 Se("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},nl=function(t){if(t.byteLength!==4)throw new Se("IPv4 address was incorrect length");let e=[];for(let r=0;r<t.byteLength;r++)e.push(t[r]);return e.join(".")},ol=function(t){if(t.byteLength!==16)throw new Se("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 Se(`Invalid IPv6 address "${r}"`)}};function sl(t){try{let e=new URL(`http://[${t}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Se(`Invalid IPv6 address "${t}"`)}}var La=Object.values(Xt).map(t=>t.decoder),wm=(function(){let t=La[0].or(La[1]);return La.slice(2).forEach(e=>t=t.or(e)),t})();function il(t){return wm.decode(t)}function al(t){return e=>t.encoder.encode(e)}function xm(t){if(parseInt(t).toString()!==t)throw new gt("Value must be an integer")}function Em(t){if(t<0)throw new gt("Value must be a positive integer, or zero")}function Sm(t){return e=>{if(e>t)throw new gt(`Value must be smaller than or equal to ${t}`)}}function Am(...t){return e=>{for(let r of t)r(e)}}var Hn=Am(xm,Em,Sm(65535));var be=-1,Pa=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 Xo(`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)}))}},bt=new Pa,Fm=[{code:4,name:"ip4",size:32,valueToBytes:Oa,bytesToValue:nl,validate:t=>{if(!Qo(t))throw new gt(`Invalid IPv4 address "${t}"`)}},{code:6,name:"tcp",size:16,valueToBytes:fr,bytesToValue:Mr,validate:Hn},{code:273,name:"udp",size:16,valueToBytes:fr,bytesToValue:Mr,validate:Hn},{code:33,name:"dccp",size:16,valueToBytes:fr,bytesToValue:Mr,validate:Hn},{code:41,name:"ip6",size:128,valueToBytes:rl,bytesToValue:ol,stringToValue:sl,validate:t=>{if(!Ju(t))throw new gt(`Invalid IPv6 address "${t}"`)}},{code:42,name:"ip6zone",size:be},{code:43,name:"ipcidr",size:8,bytesToValue:Ba("base10"),valueToBytes:Da("base10")},{code:53,name:"dns",size:be},{code:54,name:"dns4",size:be},{code:55,name:"dns6",size:be},{code:56,name:"dnsaddr",size:be},{code:132,name:"sctp",size:16,valueToBytes:fr,bytesToValue:Mr,validate:Hn},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:be,stringToValue:t=>decodeURIComponent(t),valueToString:t=>encodeURIComponent(t)},{code:421,name:"p2p",aliases:["ipfs"],size:be,bytesToValue:Ba("base58btc"),valueToBytes:t=>t.startsWith("Q")||t.startsWith("1")?Da("base58btc")(t):de.parse(t).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Ra,valueToBytes:el},{code:445,name:"onion3",size:296,bytesToValue:Ra,valueToBytes:tl},{code:446,name:"garlic64",size:be},{code:447,name:"garlic32",size:be},{code:448,name:"tls"},{code:449,name:"sni",size:be},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:be,bytesToValue:al(ln),valueToBytes:il},{code:480,name:"http"},{code:481,name:"http-path",size:be,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:be}];Fm.forEach(t=>{bt.addProtocol(t)});function cl(t){let e=[],r=0;for(;r<t.length;){let n=mt(t,r),o=bt.getProtocol(n),s=re(n),i=km(o,t,r+s),a=0;i>0&&o.size===be&&(a=re(i));let c=s+a+i,f={code:n,name:o.name,bytes:t.subarray(r,r+c)};if(i>0){let u=r+s+a,l=t.subarray(u,u+i);f.value=o.bytesToValue?.(l)??V(l)}e.push(f),r+=c}return e}function fl(t){let e=0,r=[];for(let n of t){if(n.bytes==null){let o=bt.getProtocol(n.code),s=re(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??W(n.value),a=i.byteLength,o.size===be&&(c=re(a)));let f=new Uint8Array(s+c+a),u=0;Pt(n.code,f,u),u+=s,i!=null&&(o.size===be&&(Pt(a,f,u),u+=c),f.set(i,u)),n.bytes=f}r.push(n.bytes),e+=n.bytes.byteLength}return Oe(r,e)}function ul(t){if(t.charAt(0)!=="/")throw new Se('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=bt.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 Se(`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 Se(`Component ${o} was missing value`);f.value=c.stringToValue?.(n)??n}e.push(f),n="",o="",r="protocol"}}}if(o!==""&&n!=="")throw new Se("Incomplete multiaddr");return e}function ll(t){return`/${t.flatMap(e=>{if(e.value==null)return e.name;let r=bt.getProtocol(e.code);if(r==null)throw new Se(`Unknown protocol code ${e.code}`);return[e.name,r.valueToString?.(e.value)??e.value]}).join("/")}`}function km(t,e,r){return t.size==null||t.size===0?0:t.size>0?t.size/8:mt(e,r)}var Mm=Symbol.for("nodejs.util.inspect.custom"),Za=Symbol.for("@multiformats/multiaddr");function Km(t){if(t==null&&(t="/"),hl(t))return t.getComponents();if(t instanceof Uint8Array)return cl(t);if(typeof t=="string")return t=t.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),t===""&&(t="/"),ul(t);if(Array.isArray(t))return t;throw new Se("Must be a string, Uint8Array, Component[], or another Multiaddr")}var ns=class t{[Za]=!0;#e;#t;#r;constructor(e="/",r={}){this.#e=Km(e),r.validate!==!1&&Hm(this)}get bytes(){return this.#r==null&&(this.#r=fl(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=ll(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 jo(`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 we(this.bytes,e.bytes)}[Mm](){return`Multiaddr(${this.toString()})`}};function Hm(t){t.getComponents().forEach(e=>{let r=bt.getProtocol(e.code);e.value!=null&&r.validate?.(e.value)})}function hl(t){return!!t?.[Za]}function $r(t){return new ns(t)}var ne=t=>({match:e=>{let r=e[0];return r==null||r.code!==t||r.value!=null?!1:e.slice(1)}}),M=(t,e)=>({match:r=>{let n=r[0];return n?.code!==t||n.value==null||e!=null&&n.value!==e?!1:r.slice(1)}}),dl=t=>({match:e=>t.match(e)===!1?e:!1}),q=t=>({match:e=>{let r=t.match(e);return r===!1?e:r}}),Ie=(...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 Vm=M(421),y2=oe(Vm),ss=M(54),is=M(55),as=M(56),Ja=M(53),b2=oe(ss,q(M(421))),w2=oe(is,q(M(421))),x2=oe(as,q(M(421))),E2=oe(Ie(Ja,as,ss,is),q(M(421))),pl=Y(M(4),q(M(43))),ml=Y(q(M(42)),M(41),q(M(43))),ec=Ie(pl,ml),zr=Ie(ec,Ja,ss,is,as),S2=oe(Ie(ec,Y(Ie(Ja,as,ss,is),q(M(421))))),A2=oe(pl),v2=oe(ml),_2=oe(ec),tc=Y(zr,M(6)),Vn=Y(zr,M(273)),C2=oe(Y(tc,q(M(421)))),T2=oe(Vn),rc=Y(Vn,ne(460),q(M(421))),cs=Y(Vn,ne(461),q(M(421))),$m=Ie(rc,cs),I2=oe(rc),L2=oe(cs),Qa=Ie(zr,tc,Vn,rc,cs),gl=Ie(Y(Qa,ne(477),q(M(421)))),B2=oe(gl),yl=Ie(Y(Qa,ne(478),q(M(421))),Y(Qa,ne(448),q(M(449)),ne(477),q(M(421)))),D2=oe(yl),bl=Y(Vn,ne(280),q(M(466)),q(M(466)),q(M(421))),wl=oe(bl),xl=Y(cs,ne(465),q(M(466)),q(M(466)),q(M(421))),R2=oe(xl),os=Ie(gl,yl,Y(tc,q(M(421))),Y($m,q(M(421))),Y(zr,q(M(421))),bl,xl,M(421)),El=oe(os),zm=Y(q(os),ne(290),dl(ne(281)),q(M(421))),O2=oe(zm),Wm=Ie(Y(os,ne(290),ne(281),q(M(421))),Y(os,ne(281),q(M(421))),Y(ne(281),q(M(421)))),Sl=oe(Wm),qm=Y(zr,Ie(Y(M(6,"80")),Y(M(6),ne(480)),ne(480)),q(M(481)),q(M(421))),P2=oe(qm),Gm=Y(zr,Ie(Y(M(6,"443")),Y(M(6,"443"),ne(480)),Y(M(6),ne(443)),Y(M(6),ne(448),ne(480)),Y(ne(448),ne(480)),ne(448),ne(443)),q(M(481)),q(M(421))),N2=oe(Gm),jm=Ie(Y(M(777),q(M(421)))),U2=oe(jm),Xm=Ie(Y(M(400),q(M(421)))),F2=oe(Xm);var Le;(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=()=>cr(r)})(e=t.Flag||(t.Flag={}));let n;t.codec=()=>(n==null&&(n=Mt((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={},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let p=a.uint32();switch(p>>>3){case 1:{u.flag=t.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 l=c==null?a.len:a.pos+c;for(;a.pos<l;){let p=a.uint32();switch(p>>>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(p&7);break}}}})),n);function o(a){return Ft(a,t.codec())}t.encode=o;function s(a,c){return Ut(a,t.codec(),c)}t.decode=s;function i(a,c){return kt(a,t.codec(),c)}t.stream=i})(Le||(Le={}));var Al=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],nc=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),vl="libp2p+webrtc+v1/",_l=2*1024*1024,Wr=16*1024;function Ym(t=Wr){let e=re(t-re(t)),r=1+re(Object.keys(Le.Flag).length-1),n=1,o=t-e-r-n,s=re(o);return e+r+n+s}var Cl=Ym();var Tl=1e4,oc="/webrtc",$n="/webrtc-signaling/0.0.1";function sc(t){let e=t.getComponents(),r={},n=0;if(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)throw new G(`Multiaddr ${t} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(r.sni=e[n+1].value,n+=2),r}function fs(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var us=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}},qr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new us(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 us(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 ic=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function Gr(t={}){return Zm(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function Zm(t,e){e=e??{};let r=e.onEnd,n=new qr,o,s,i,a=fs(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,y)=>{s=v=>{s=null,n.push(v);try{h(t(n))}catch(T){y(T)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=fs()})}},f=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new qr,s!=null?s({error:h}):(n.push({error:h}),o)),l=h=>{if(i)return o;if(e?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:h})},p=h=>i?o:(i=!0,h!=null?u(h):f({done:!0})),d=()=>(n=new qr,p(),{done:!0}),g=h=>(p(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:d,throw:g,push:l,end:p,get readableLength(){return n.size},onEmpty:async h=>{let y=h?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let v,T;y!=null&&(v=new Promise((P,D)=>{T=()=>{D(new ic)},y.addEventListener("abort",T)}));try{await Promise.race([a.promise,v])}finally{T!=null&&y!=null&&y?.removeEventListener("abort",T)}}},r==null)return o;let S=o;return o={[Symbol.asyncIterator](){return this},next(){return S.next()},throw(h){return S.throw(h),r!=null&&(r(h),r=void 0),{done:!0}},return(){return S.return(),r!=null&&(r(),r=void 0),{done:!0}},push:l,end(h){return S.end(h),r!=null&&(r(h),r=void 0),o},get readableLength(){return S.readableLength},onEmpty:h=>S.onEmpty(h)},o}var ac=class t extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,t)}},Il=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function cc(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((l,p)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(i?.aborted){p(Il(i));return}if(i&&(c=()=>{p(Il(i))},i.addEventListener("abort",c,{once:!0})),t.then(l,p),r===Number.POSITIVE_INFINITY)return;let d=new ac;a=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(g){p(g)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?l():o instanceof Error?p(o):(d.message=o??`Promise timed out after ${r} milliseconds`,p(d))},r)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var Qm=t=>{let e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function Jm(t,e,r){let n,o=new Promise((s,i)=>{if(r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:f,removeListener:u}=Qm(t),l=async(...d)=>{let g=r.multiArgs?d:d[0];if(r.filter)try{if(!await r.filter(g))return}catch(S){n(),i(S);return}c.push(g),r.count===c.length&&(n(),s(c))},p=(...d)=>{n(),i(r.rejectionMultiArgs?d:d[0])};n=()=>{for(let d of a)u(d,l);for(let d of r.rejectionEvents)a.includes(d)||u(d,p)};for(let d of a)f(d,l);for(let d of r.rejectionEvents)a.includes(d)||f(d,p);r.signal&&r.signal.addEventListener("abort",()=>{p(r.signal.reason)},{once:!0}),r.resolveImmediately&&s(c)});if(o.cancel=n,typeof r.timeout=="number"){let s=cc(o,{milliseconds:r.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function Ae(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Jm(t,e,r),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var lr=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"},ls=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},hs=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function e0(t){return t.reason}async function wt(t,e,r){if(e==null)return t;let n=r?.translateError??e0;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 t0=Math.pow(2,20)*4,Vt=class extends Et{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??t0,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new $,this.writeBuffer=new $,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,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",r);let n=o=>{this.onDrainPromise?.reject(o.error??new hs)};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()),wt(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Gr(),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 Je(`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 mo(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new Je("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 Je("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 Je(`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 Je(`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 wr;this.dispatchEvent(new go(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 xr))}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;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 $(s);this.writeBuffer.consume(s.byteLength);let a=this.sendData(s);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 po(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 sn(`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 sn(`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 ds=class extends Vt{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",r=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),r.error!=null?r.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):r.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Ae(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 Ae(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function Ll(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var ps=class extends Et{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 wt(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 co;let r=this.onCreateStream({...this.streamOptions,...e});return Ll(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 ls(`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 ms=class extends Vt{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await Ae(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 Ae(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 r0=4194304,gs=class extends Error{static name="UnwrappedError";name="UnwrappedError"},zn=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},uc=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},lc=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function n0(t){return typeof t?.closeRead=="function"}function o0(t){return typeof t?.close=="function"}function fc(t){return n0(t)?t.remoteWriteStatus!=="writable"&&t.readBufferLength===0:o0(t)?t.status!=="open":!1}function s0(t){return t?.addEventListener!=null&&t?.removeEventListener!=null&&t?.send!=null&&t?.push!=null&&t?.log!=null}function i0(t,e){let r=e?.maxBufferSize??r0,n=new $,o,s=!1;if(!s0(t))throw new G("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>r){let l=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${l} > ${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 gs("Stream was unwrapped");if(fc(t)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw t.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new lr(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let l=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=l){o.resolve();break}if(await wt(o.promise,u?.signal),fc(t)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let p=u?.bytes??n.byteLength;if(n.byteLength<p){if(fc(t))throw t.log.error("closed while reading %d/%d bytes",n.byteLength,p),new lr(`Unexpected EOF - stream closed while reading ${n.byteLength}/${p} bytes`);return f.read(u)}let d=n.sublist(0,p);return n.consume(p),d},async write(u,l){if(s===!0)throw new gs("Stream was unwrapped");t.send(u)||await Ae(t,"drain",{signal:l?.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.push(n))),t}};return f}function ys(t,e={}){let r=i0(t,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=re(e.maxDataLength));let n=e?.lengthDecoder??mt,o=e?.lengthEncoder??Ko;return{async read(i){let a=-1,c=new $;for(;;){let u=await r.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new zn("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new lc(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new uc(`Message length too long - ${a} > ${e.maxDataLength}`);let f=await r.read({...i,bytes:a});if(f==null)throw t.log.error("tried to read %d bytes but the stream closed",a),new lr(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(f.byteLength!==a)throw t.log.error("read %d/%d bytes before the stream closed",f.byteLength,a),new lr(`Unexpected EOF - read ${f.byteLength}/${a} bytes before the stream closed`);return f},async write(i,a){await r.write(new $(o(i.byteLength),i),a)},async writeV(i,a){let c=new $(...i.flatMap(f=>[o(f.byteLength),f]));await r.write(c,a)},unwrap(){return r.unwrap()}}}function bs(t,e){let r=ys(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 a0=1024*1024*4,c0=1024*1024*4,ws=class{buffer;maxBufferSize;lengthDecoder;maxDataLength;encodingLength;constructor(e={}){this.buffer=new $,this.maxBufferSize=e.maxBufferSize??a0,this.maxDataLength=e.maxDataLength??c0,this.lengthDecoder=e.lengthDecoder??mt,this.encodingLength=e.encodingLength??re}*decode(e){if(this.buffer.append(e),this.buffer.byteLength>this.maxBufferSize)throw new G(`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 zn("Invalid message length");let n=this.encodingLength(r),o=n+r;if(this.buffer.byteLength>=o){let s=this.buffer.sublist(n,o);this.buffer.consume(o),s.byteLength>0&&(yield s)}else break}}};var xs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},jr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Es=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Wn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Ss(t){return t[Symbol.asyncIterator]!=null}function Bl(t,e){if(t.byteLength>e)throw new jr("Message length too long")}var vs=t=>{let e=re(t),r=ae(e);return Ko(t,r),vs.bytes=e,r};vs.bytes=0;function qn(t,e){e=e??{};let r=e.lengthEncoder??vs,n=e?.maxDataLength??4194304;function*o(s){Bl(s,n);let i=r(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Ss(t)?(async function*(){for await(let s of t)yield*o(s)})():(function*(){for(let s of t)yield*o(s)})()}qn.single=(t,e)=>{e=e??{};let r=e.lengthEncoder??vs,n=e?.maxDataLength??4194304;return Bl(t,n),new $(r(t.byteLength),t)};var hr;(function(t){t[t.LENGTH=0]="LENGTH",t[t.DATA=1]="DATA"})(hr||(hr={}));var hc=t=>{let e=mt(t);return hc.bytes=re(e),e};hc.bytes=0;function Gn(t,e){let r=new $,n=hr.LENGTH,o=-1,s=e?.lengthDecoder??hc,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===hr.LENGTH)try{if(o=s(r),o<0)throw new xs("Invalid message length");if(o>a)throw new jr("Message length too long");let f=s.bytes;r.consume(f),e?.onLength!=null&&e.onLength(o),n=hr.DATA}catch(f){if(f instanceof RangeError){if(r.byteLength>i)throw new Es("Message length length too long");break}throw f}if(n===hr.DATA){if(r.byteLength<o)break;let f=r.sublist(0,o);r.consume(o),e?.onData!=null&&e.onData(f),yield f,n=hr.LENGTH}}}return Ss(t)?(async function*(){for await(let f of t)r.append(f),yield*c();if(r.byteLength>0)throw new Wn("Unexpected end of input")})():(function*(){for(let f of t)r.append(f),yield*c();if(r.byteLength>0)throw new Wn("Unexpected end of input")})()}Gn.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 Gn(n,{...e??{},onLength:s=>{r=s}})};var Dl=function(t,e,r){if(r||arguments.length===2)for(var n=0,o=e.length,s;n<o;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))},l0=(function(){function t(e,r,n){this.name=e,this.version=r,this.os=n,this.type="browser"}return t})();var h0=(function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t})();var d0=(function(){function t(e,r,n,o){this.name=e,this.version=r,this.os=n,this.bot=o,this.type="bot-device"}return t})();var p0=(function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t})();var m0=(function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t})();var g0=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,y0=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Rl=3,b0=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",g0]],Ol=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function Nl(t){return t?Pl(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new m0:typeof navigator<"u"?Pl(navigator.userAgent):E0()}function w0(t){return t!==""&&b0.reduce(function(e,r){var n=r[0],o=r[1];if(e)return e;var s=o.exec(t);return!!s&&[n,s]},!1)}function Pl(t){var e=w0(t);if(!e)return null;var r=e[0],n=e[1];if(r==="searchbot")return new p0;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<Rl&&(o=Dl(Dl([],o,!0),S0(Rl-o.length),!0)):o=[];var s=o.join("."),i=x0(t),a=y0.exec(t);return a&&a[1]?new d0(r,s,i,a[1]):new l0(r,s,i)}function x0(t){for(var e=0,r=Ol.length;e<r;e++){var n=Ol[e],o=n[0],s=n[1],i=s.exec(t);if(i)return o}return null}function E0(){var t=typeof process<"u"&&process.version;return t?new h0(process.version.slice(1)):null}function S0(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var Ul=Nl(),_s=Ul!=null&&Ul.name==="firefox";async function dc(t){return t=t??{},typeof t=="function"&&(t=await t()),t.iceServers=t.iceServers??Al.map(e=>({urls:[e]})),t}var Fl=(t=32)=>vl+[...Array(t)].map(()=>nc.at(Math.floor(Math.random()*nc.length))).join("");var pc=class extends ms{channel;incomingData;maxBufferedAmount;receivedFinAck;finAckTimeout;constructor(e){super({...e,maxMessageSize:(e.maxMessageSize??Wr)-Cl}),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=Gr(),this.maxBufferedAmount=e.maxBufferedAmount??_l,this.finAckTimeout=e.finAckTimeout??Tl,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 Gn(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),Ae(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 Je(`Invalid datachannel state - ${this.channel.readyState}`);if(this.log.trace('sending message, channel state "%s"',this.channel.readyState),_s){this.channel.send(e.subarray());return}for(let r of e)this.channel.send(r)}sendData(e){return this.channel.readyState!=="open"?{sentBytes:0,canSendMore:!1}:(this._sendMessage(qn.single(Le.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(Le.Flag.RESET),this.receivedFinAck?.reject(e)}catch(r){this.log.error("failed to send reset - %e",r)}}async sendCloseWrite(e){this._sendFlag(Le.Flag.FIN),e?.signal?.throwIfAborted(),this.receivedFinAck=Promise.withResolvers();let r=e?.signal??AbortSignal.timeout(this.finAckTimeout),n=[Ae(this.channel,"close",{signal:r}),Ae(this.channel,"error",{signal:r})];await Promise.any([wt(this.receivedFinAck.promise,r),...n]).finally(()=>{n.forEach(o=>o.cancel())})}async sendCloseRead(e){this._sendFlag(Le.Flag.STOP_SENDING),e?.signal?.throwIfAborted()}processIncomingProtobuf(e){let r=Le.decode(e);r.message!=null&&(this.readStatus==="readable"||this.readStatus==="paused")&&this.onData(new $(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===Le.Flag.FIN&&(this._sendFlag(Le.Flag.FIN_ACK),this.onRemoteCloseWrite()),r.flag===Le.Flag.RESET&&(this.receivedFinAck?.reject(new wr("The stream was reset")),this.onRemoteReset()),r.flag===Le.Flag.STOP_SENDING&&this.onRemoteCloseRead(),r.flag===Le.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=Le.encode({flag:e}),n=qn.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 jn(t){let{channel:e,direction:r,isHandshake:n}=t;return new pc({...t,id:`${e.id}`,log:t.log.newScope(`${n===!0?"handshake":r}:${e.id}`),protocol:""})}var $t=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??oc,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 mc(e,{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,protocol:this.protocol,earlyDataChannels:this.earlyDataChannels})}},mc=class extends ps{peerConnection;dataChannelOptions;constructor(e,r){super(e,{...r,name:"muxer"}),this.peerConnection=r.peerConnection,this.protocol=r.protocol??oc,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=jn({...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),jn({...e,...this.dataChannelOptions,channel:r,direction:"outbound",log:this.log})}onData(){}};var gc=class extends ds{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==="disconnected"||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(){}},Xn=t=>new gc(t);var Cs=globalThis.RTCPeerConnection,Ts=globalThis.RTCSessionDescription,kl=globalThis.RTCIceCandidate;var Me=class extends Event{type;detail;constructor(e,r){super(e),this.type=e,this.detail=r}};var zt=class extends Error{constructor(e){super(`WebRTC transport error: ${e}`),this.name="WebRTCTransportError"}},Ve=class extends zt{constructor(e="SDP handshake failed"){super(e),this.name="SDPHandshakeFailedError"}};var Is=class extends zt{constructor(e,r){super(`Invalid fingerprint "${e}" within ${r}`),this.name="WebRTC/InvalidFingerprintError"}};var Ls=class extends zt{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},Bs=class extends zt{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 Ne;(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=()=>cr(r)})(e=t.Type||(t.Type={}));let n;t.codec=()=>(n==null&&(n=Mt((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={},l=c==null?a.len:a.pos+c;for(;a.pos<l;){let p=a.uint32();switch(p>>>3){case 1:{u.type=t.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 l=c==null?a.len:a.pos+c;for(;a.pos<l;){let p=a.uint32();switch(p>>>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(p&7);break}}}})),n);function o(a){return Ft(a,t.codec())}t.encode=o;function s(a,c){return Ut(a,t.codec(),c)}t.decode=s;function i(a,c){return kt(a,t.codec(),c)}t.stream=i})(Ne||(Ne={}));var Ds=async(t,e,r)=>{try{let n=Promise.withResolvers();for(A0(t,n);;){let o=await Promise.race([n.promise,e.read({signal:r.signal})]);if(o==null){r.signal?.throwIfAborted();break}if(o.type!==Ne.Type.ICE_CANDIDATE)throw new ho("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){r.onProgress?.(new Me("webrtc:end-of-ice-candidates")),r.log.trace("end-of-candidates received");continue}let i=new kl(s);r.log.trace("%s received new ICE candidate %o",r.direction,s);try{r.onProgress?.(new Me("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 A0(t,e){if(t.connectionState==="connected"){e.resolve();return}t.onconnectionstatechange=r=>{switch(t.connectionState){case"connected":e.resolve();break;case"failed":case"disconnected":case"closed":e.reject(new ao(`RTCPeerConnection connection state became "${t.connectionState}"`));break;default:break}}}function Rs(t){let e;for(let r of t.getComponents())r.name==="p2p"&&(e=kr(r.value??""));if(e==null)throw new fo("Remote peerId must be present in multiaddr");return e}async function Ml({rtcConfiguration:t,dataChannel:e,signal:r,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:f}){let{circuitAddress:u,targetPeer:l}=Kl(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing circuit address: %a",u);let p=s.getConnections(l),d;p.length===0?(f?.(new Me("webrtc:dial-relay")),d=await i.dial(u,{signal:r,onProgress:f})):(f?.(new Me("webrtc:reuse-relay-connection")),d=p[0]),f?.(new Me("webrtc:open-signaling-stream"));let g=await d.newStream($n,{signal:r,runOnLimitedConnection:!0}),S=bs(g).pb(Ne),h=new Cs(t);h.addEventListener("connectionstatechange",()=>{h.connectionState==="closed"&&h.close()});let y=new $t({peerConnection:h,dataChannelOptions:e});try{let v=h.createDataChannel("init");h.onicecandidate=({candidate:O})=>{if(h.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 R=JSON.stringify(O?.toJSON()??null);a.trace("initiator sending ICE candidate %o",O),S.write({type:Ne.Type.ICE_CANDIDATE,data:R},{signal:r}).catch(L=>{a.error("error sending ICE candidate - %e",L)})},h.onicecandidateerror=O=>{a.error("initiator ICE candidate error",O)};let T=await h.createOffer().catch(O=>{throw a.error("could not execute createOffer - %e",O),new Ve("Failed to set createOffer")});a.trace("initiator send SDP offer %s",T.sdp),f?.(new Me("webrtc:send-sdp-offer")),await S.write({type:Ne.Type.SDP_OFFER,data:T.sdp},{signal:r}),await h.setLocalDescription(T).catch(O=>{throw a.error("could not execute setLocalDescription - %e",O),new Ve("Failed to set localDescription")}),f?.(new Me("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let P=await S.read({signal:r});if(P.type!==Ne.Type.SDP_ANSWER)throw new Ve("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",P.data);let D=new Ts({type:"answer",sdp:P.data});return await h.setRemoteDescription(D).catch(O=>{throw a.error("could not execute setRemoteDescription - %e",O),new Ve("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),f?.(new Me("webrtc:read-ice-candidates")),await Ds(h,S,{direction:"initiator",signal:r,log:a,onProgress:f}),a.trace("initiator connected"),v.readyState!=="open"&&(a.trace("wait for init channel to open"),await Ae(v,"open",{signal:r})),a.trace("closing init channel"),v.close(),a.trace("waiting for init channel to close"),await Ae(v,"close",{signal:r}),f?.(new Me("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await g.close({signal:r}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:h,muxerFactory:y}}catch(v){throw a.error("outgoing signaling error - %e",v),h.close(),g.abort(v),v}finally{h.onicecandidate=null,h.onicecandidateerror=null}}var Hl=oe(El.matchers[0],ne(290)),Os=class t extends Et{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=>Hl.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=>Hl.exactMatch(r)).map(r=>r.encapsulate("/webrtc"))).flat()}updateAnnounceAddrs(){}async close(){this.events.removeEventListener("transport:listening",this.onTransportListening),this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function Vl(t,e,{peerConnection:r,signal:n,log:o}){o.trace("new inbound signaling stream");let s=bs(t).pb(Ne);try{r.onicecandidate=({candidate:l})=>{if(r.connectionState==="connected"){o.trace("ignore new ice candidate as peer connection is already connected");return}if(l==null||l?.candidate===""){o.trace("recipient detected end of ICE candidates");return}let p=JSON.stringify(l?.toJSON()??null);o.trace("recipient sending ICE candidate %s",p),s.write({type:Ne.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!==Ne.Type.SDP_OFFER)throw new Ve(`expected message type SDP_OFFER, received: ${c.type??"undefined"} `);o.trace("recipient received SDP offer %s",c.data);let f=new Ts({type:"offer",sdp:c.data});await r.setRemoteDescription(f).catch(l=>{throw o.error("could not execute setRemoteDescription - %e",l),new Ve("Failed to set remoteDescription")});let u=await r.createAnswer().catch(l=>{throw o.error("could not execute createAnswer - %e",l),new Ve("Failed to create answer")});o.trace("recipient send SDP answer %s",u.sdp),await s.write({type:Ne.Type.SDP_ANSWER,data:u.sdp},{signal:n}),await r.setLocalDescription(u).catch(l=>{throw o.error("could not execute setLocalDescription - %e",l),new Ve("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await Ds(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=Rs(e.remoteAddr),a=$r(`/webrtc/p2p/${i}`);return o.trace("recipient connected to remote address %s",a),{remoteAddress:a,remotePeer:i}}var Ps=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"})})}[yo]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Er]=["@libp2p/transport"];[Jc]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle($n,(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($n),this._started=!1}createListener(e){return new Os(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(Sl.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 Ml({rtcConfiguration:await dc(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=Xn({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:Rs(e),muxerFactory:s,onProgress:r.onProgress,signal:r.signal});return this._closeOnShutdown(o,i),a}async _onProtocol(e,r,n){let o=new Cs(await dc(this.init.rtcConfiguration));o.addEventListener("connectionstatechange",()=>{o.connectionState==="closed"&&o.close()});let s=new $t({peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i,remotePeer:a}=await Vl(e,r,{peerConnection:o,signal:n,log:this.log});await e.close({signal:n});let c=Xn({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 Kl(t){let e=t.getComponents().filter(({name:n})=>n==="p2p").map(({value:n})=>n).pop();if(e==null)throw new G("Destination peer id was missing");return{circuitAddress:$r(t.getComponents().filter(({name:n})=>n!=="webrtc")),targetPeer:kr(e)}}var Xr=!!globalThis.process?.env?.DUMP_SESSION_KEYS,yc=16;function v0(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}function Ns(t){if(typeof t!="boolean")throw new TypeError(`boolean expected, not ${t}`)}function Yr(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 ge(t,e,r=""){let n=v0(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 bc(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 $l(t,e,r=!1){ge(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&&!Zr(t))throw new Error("invalid output, must be aligned")}function st(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ze(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function _0(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var dr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,C0=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;var T0=t=>{for(let e=0;e<t.length;e++)t[e]=C0(t[e]);return t},xt=dr?t=>t:T0;function zl(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Wl(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 ql(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 Gl=(t,e)=>{function r(n,...o){if(ge(n,void 0,"key"),t.nonceLength!==void 0){let u=o[0];ge(u,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let s=t.tagLength;s&&o[1]!==void 0&&ge(o[1],void 0,"AAD");let i=e(n,...o),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");ge(l,void 0,"output")}},c=!1;return{encrypt(u,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,ge(u),a(i.encrypt.length,l),i.encrypt(u,l)},decrypt(u,l){if(ge(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,l),i.decrypt(u,l)}}}return Object.assign(r,t),r};function Yn(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(ge(e,void 0,"output"),e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(r&&!Zr(e))throw new Error("invalid output, must be aligned");return e}function jl(t,e,r){Yr(t),Yr(e),Ns(r);let n=new Uint8Array(16),o=_0(n);return o.setBigUint64(0,BigInt(e),r),o.setBigUint64(8,BigInt(t),r),n}function Zr(t){return t.byteOffset%4===0}function Qr(t){return Uint8Array.from(ge(t))}var Yl=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),I0=xt(st(Yl("expand 16-byte k"))),L0=xt(st(Yl("expand 32-byte k")));function j(t,e){return t<<e|t>>>32-e}var Zn=64,B0=16,wc=2**32-1,Xl=Uint32Array.of();function D0(t,e,r,n,o,s,i,a){let c=o.length,f=new Uint8Array(Zn),u=st(f),l=dr&&Zr(o)&&Zr(s),p=l?st(o):Xl,d=l?st(s):Xl;if(!dr){for(let g=0;g<c;i++){if(t(e,r,n,u,i,a),xt(u),i>=wc)throw new Error("arx: counter overflow");let S=Math.min(Zn,c-g);for(let h=0,y;h<S;h++)y=g+h,s[y]=o[y]^f[h];g+=S}return}for(let g=0;g<c;i++){if(t(e,r,n,u,i,a),i>=wc)throw new Error("arx: counter overflow");let S=Math.min(Zn,c-g);if(l&&S===Zn){let h=g/4;if(g%4!==0)throw new Error("arx: invalid block position");for(let y=0,v;y<B0;y++)v=h+y,d[v]=p[v]^u[y];g+=Zn;continue}for(let h=0,y;h<S;h++)y=g+h,s[y]=o[y]^f[h];g+=S}}function Zl(t,e){let{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=zl({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Yr(o),Yr(i),Ns(s),Ns(r),(a,c,f,u,l=0)=>{ge(a,void 0,"key"),ge(c,void 0,"nonce"),ge(f,void 0,"data");let p=f.length;if(u=Yn(p,u,!1),Yr(l),l<0||l>=wc)throw new Error("arx: counter overflow");let d=[],g=a.length,S,h;if(g===32)d.push(S=Qr(a)),h=L0;else if(g===16&&r)S=new Uint8Array(32),S.set(a),S.set(a,16),h=I0,d.push(S);else throw ge(a,32,"arx key"),new Error("invalid key size");(!dr||!Zr(c))&&d.push(c=Qr(c));let y=st(S);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let P=c.subarray(0,16);if(dr)n(h,y,st(P),y);else{let D=xt(Uint32Array.from(h));n(D,y,st(P),y),Ze(D),xt(y)}c=c.subarray(16)}else dr||xt(y);let v=16-o;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let P=new Uint8Array(12);P.set(c,s?0:12-c.length),c=P,d.push(c)}let T=xt(st(c));try{return D0(t,h,y,T,f,u,l,i),u}finally{Ze(...d)}}}function ve(t,e){return t[e++]&255|(t[e++]&255)<<8}var xc=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=Qr(ge(e,32,"key"));let r=ve(e,0),n=ve(e,2),o=ve(e,4),s=ve(e,6),i=ve(e,8),a=ve(e,10),c=ve(e,12),f=ve(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]=ve(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],l=i[4],p=i[5],d=i[6],g=i[7],S=i[8],h=i[9],y=ve(e,r+0),v=ve(e,r+2),T=ve(e,r+4),P=ve(e,r+6),D=ve(e,r+8),O=ve(e,r+10),R=ve(e,r+12),L=ve(e,r+14),N=s[0]+(y&8191),k=s[1]+((y>>>13|v<<3)&8191),U=s[2]+((v>>>10|T<<6)&8191),m=s[3]+((T>>>7|P<<9)&8191),A=s[4]+((P>>>4|D<<12)&8191),E=s[5]+(D>>>1&8191),w=s[6]+((D>>>14|O<<2)&8191),b=s[7]+((O>>>11|R<<5)&8191),_=s[8]+((R>>>8|L<<8)&8191),C=s[9]+(L>>>5|o),x=0,I=x+N*a+k*(5*h)+U*(5*S)+m*(5*g)+A*(5*d);x=I>>>13,I&=8191,I+=E*(5*p)+w*(5*l)+b*(5*u)+_*(5*f)+C*(5*c),x+=I>>>13,I&=8191;let B=x+N*c+k*a+U*(5*h)+m*(5*S)+A*(5*g);x=B>>>13,B&=8191,B+=E*(5*d)+w*(5*p)+b*(5*l)+_*(5*u)+C*(5*f),x+=B>>>13,B&=8191;let F=x+N*f+k*c+U*a+m*(5*h)+A*(5*S);x=F>>>13,F&=8191,F+=E*(5*g)+w*(5*d)+b*(5*p)+_*(5*l)+C*(5*u),x+=F>>>13,F&=8191;let H=x+N*u+k*f+U*c+m*a+A*(5*h);x=H>>>13,H&=8191,H+=E*(5*S)+w*(5*g)+b*(5*d)+_*(5*p)+C*(5*l),x+=H>>>13,H&=8191;let K=x+N*l+k*u+U*f+m*c+A*a;x=K>>>13,K&=8191,K+=E*(5*h)+w*(5*S)+b*(5*g)+_*(5*d)+C*(5*p),x+=K>>>13,K&=8191;let J=x+N*p+k*l+U*u+m*f+A*c;x=J>>>13,J&=8191,J+=E*a+w*(5*h)+b*(5*S)+_*(5*g)+C*(5*d),x+=J>>>13,J&=8191;let ee=x+N*d+k*p+U*l+m*u+A*f;x=ee>>>13,ee&=8191,ee+=E*c+w*a+b*(5*h)+_*(5*S)+C*(5*g),x+=ee>>>13,ee&=8191;let te=x+N*g+k*d+U*p+m*l+A*u;x=te>>>13,te&=8191,te+=E*f+w*c+b*a+_*(5*h)+C*(5*S),x+=te>>>13,te&=8191;let X=x+N*S+k*g+U*d+m*p+A*l;x=X>>>13,X&=8191,X+=E*u+w*f+b*c+_*a+C*(5*h),x+=X>>>13,X&=8191;let ie=x+N*h+k*S+U*g+m*d+A*p;x=ie>>>13,ie&=8191,ie+=E*l+w*u+b*f+_*c+C*a,x+=ie>>>13,ie&=8191,x=(x<<2)+x|0,x=x+I|0,I=x&8191,x=x>>>13,B+=x,s[0]=I,s[1]=B,s[2]=F,s[3]=H,s[4]=K,s[5]=J,s[6]=ee,s[7]=te,s[8]=X,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;Ze(n)}update(e){bc(this),ge(e),e=Qr(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,Ze(this.h,this.r,this.buffer,this.pad)}digestInto(e){bc(this),$l(e,this),this.finished=!0;let{buffer:r,h:n}=this,{pos:o}=this;if(o){for(r[o++]=1;o<16;o++)r[o]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}},Ql=ql(32,t=>new xc(t));function R0(t,e,r,n,o,s=20){let i=t[0],a=t[1],c=t[2],f=t[3],u=e[0],l=e[1],p=e[2],d=e[3],g=e[4],S=e[5],h=e[6],y=e[7],v=o,T=r[0],P=r[1],D=r[2],O=i,R=a,L=c,N=f,k=u,U=l,m=p,A=d,E=g,w=S,b=h,_=y,C=v,x=T,I=P,B=D;for(let H=0;H<s;H+=2)O=O+k|0,C=j(C^O,16),E=E+C|0,k=j(k^E,12),O=O+k|0,C=j(C^O,8),E=E+C|0,k=j(k^E,7),R=R+U|0,x=j(x^R,16),w=w+x|0,U=j(U^w,12),R=R+U|0,x=j(x^R,8),w=w+x|0,U=j(U^w,7),L=L+m|0,I=j(I^L,16),b=b+I|0,m=j(m^b,12),L=L+m|0,I=j(I^L,8),b=b+I|0,m=j(m^b,7),N=N+A|0,B=j(B^N,16),_=_+B|0,A=j(A^_,12),N=N+A|0,B=j(B^N,8),_=_+B|0,A=j(A^_,7),O=O+U|0,B=j(B^O,16),b=b+B|0,U=j(U^b,12),O=O+U|0,B=j(B^O,8),b=b+B|0,U=j(U^b,7),R=R+m|0,C=j(C^R,16),_=_+C|0,m=j(m^_,12),R=R+m|0,C=j(C^R,8),_=_+C|0,m=j(m^_,7),L=L+A|0,x=j(x^L,16),E=E+x|0,A=j(A^E,12),L=L+A|0,x=j(x^L,8),E=E+x|0,A=j(A^E,7),N=N+k|0,I=j(I^N,16),w=w+I|0,k=j(k^w,12),N=N+k|0,I=j(I^N,8),w=w+I|0,k=j(k^w,7);let F=0;n[F++]=i+O|0,n[F++]=a+R|0,n[F++]=c+L|0,n[F++]=f+N|0,n[F++]=u+k|0,n[F++]=l+U|0,n[F++]=p+m|0,n[F++]=d+A|0,n[F++]=g+E|0,n[F++]=S+w|0,n[F++]=h+b|0,n[F++]=y+_|0,n[F++]=v+C|0,n[F++]=T+x|0,n[F++]=P+I|0,n[F++]=D+B|0}var O0=Zl(R0,{counterRight:!1,counterLength:4,allowShortKeys:!1});var P0=new Uint8Array(16),Jl=(t,e)=>{t.update(e);let r=e.length%16;r&&t.update(P0.subarray(r))},N0=new Uint8Array(32);function eh(t,e,r,n,o){o!==void 0&&ge(o,void 0,"AAD");let s=t(e,r,N0),i=jl(n.length,o?o.length:0,!0),a=Ql.create(s);o&&Jl(a,o),Jl(a,n),a.update(i);let c=a.digest();return Ze(s,i),c}var U0=t=>(e,r,n)=>({encrypt(s,i){let a=s.length;i=Yn(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);t(e,r,c,c,1);let f=eh(t,e,r,c,n);return i.set(f,a),Ze(f),i},decrypt(s,i){i=Yn(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),f=eh(t,e,r,a,n);if(!Wl(c,f))throw Ze(f),new Error("invalid tag");return i.set(s.subarray(0,-16)),t(e,r,i,i,1),Ze(f),i}}),Ec=Gl({blockSize:64,nonceLength:12,tagLength:16},U0(O0));function rh(t,e,r){return Yt(t),r===void 0&&(r=new Uint8Array(t.outputLen)),Pn(t,r,e)}var Sc=Uint8Array.of(0),th=Uint8Array.of();function nh(t,e,r,n=32){Yt(t),et(n,"length"),_e(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=th:_e(r,void 0,"info");let i=new Uint8Array(s*o),a=Pn.create(t,e),c=a._cloneInto(),f=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)Sc[0]=u+1,c.update(u===0?th:f).update(r).update(Sc).digestInto(f),i.set(f,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),We(f,Sc),i.slice(0,n)}var Ac={hashSHA256(t){return rt(t.subarray())},getHKDF(t,e){let r=rh(rt,e,t),o=nh(rt,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=_n.utils.randomSecretKey();return{publicKey:_n.getPublicKey(t),privateKey:t}},generateX25519KeyPairFromSeed(t){return{publicKey:_n.getPublicKey(t),privateKey:t}},generateX25519SharedKey(t,e){return _n.getSharedSecret(t.subarray(),e.subarray())},chaCha20Poly1305Encrypt(t,e,r,n){return Ec(n,e,r).encrypt(t.subarray())},chaCha20Poly1305Decrypt(t,e,r,n,o){return Ec(n,e,r).decrypt(t.subarray(),o)}};var oh=Ac;function sh(t){return{generateKeypair:t.generateX25519KeyPair,dh:(e,r)=>t.generateX25519SharedKey(e.privateKey,r).subarray(0,32),encrypt:t.chaCha20Poly1305Encrypt,decrypt:t.chaCha20Poly1305Decrypt,hash:t.hashSHA256,hkdf:t.getHKDF}}var Jr=t=>{let e=ae(2);return e[0]=t>>8,e[1]=t,e};Jr.bytes=2;var en=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)};en.bytes=2;function ih(t){return{xxHandshakeSuccesses:t.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:t.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:t.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:t.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:t.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function vc(t,e){!e.enabled||!Xr||(t?(e(`LOCAL_STATIC_PUBLIC_KEY ${V(t.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${V(t.privateKey,"hex")}`)):e("Missing local static keys."))}function _c(t,e){!e.enabled||!Xr||(t?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${V(t.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${V(t.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function ah(t,e){!e.enabled||!Xr||e(t?`REMOTE_STATIC_PUBLIC_KEY ${V(t.subarray(),"hex")}`:"Missing remote static public key.")}function Cc(t,e){!e.enabled||!Xr||e(t?`REMOTE_EPHEMERAL_PUBLIC_KEY ${V(t.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Tc(t,e,r){!r.enabled||!Xr||(r(`CIPHER_STATE_1 ${t.n.getUint64()} ${t.k&&V(t.k,"hex")}`),r(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&V(e.k,"hex")}`))}var tn=class t extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=t.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var F0=0,k0=4294967295,M0="Cipherstate has reached maximum n, a new handshake must be performed",Us=class{n;bytes;view;constructor(e=F0){this.n=e,this.bytes=pe(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>k0)throw new Error(M0)}};var pr=pe(0),rn=class{k;n;crypto;constructor(e,r=void 0,n=0){this.crypto=e,this.k=r,this.n=new Us(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}},Ic=class{cs;ck;h;crypto;constructor(e,r){this.crypto=e;let n=W(r,"utf-8");this.h=K0(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 $(this.h,e))}encryptAndHash(e){let r=this.cs.encryptWithAd(this.h,e);return this.mixHash(r),r}decryptAndHash(e){let r=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),r}split(){let[e,r]=this.crypto.hkdf(this.ck,pr);return[new rn(this.crypto,e),new rn(this.crypto,r)]}},Lc=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 Ic(r,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=f}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,r=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<r+32)throw new Error("message is not long enough");this.re=e.sublist(r,r+32),this.ss.mixHash(this.re)}readS(e,r=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<r+n)throw new Error("message is not long enough");let o=e.sublist(r,r+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Qn=class extends Lc{writeMessageA(e){return new $(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let r=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new $(r,n,this.ss.encryptAndHash(e))}writeMessageC(e){let r=this.writeS();return this.writeSE(),new $(r,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(r){throw new tn(`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 tn(`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 tn(`handshake stage 2 validation fail: ${r.message}`)}}};function K0(t,e){if(e.length<=32){let r=pe(32);return r.set(e),r}else return t.hash(e)}var Bc=new Float32Array([-0]),Wt=new Uint8Array(Bc.buffer);function ch(t,e,r){Bc[0]=t,e[r]=Wt[0],e[r+1]=Wt[1],e[r+2]=Wt[2],e[r+3]=Wt[3]}function fh(t,e){return Wt[0]=t[e],Wt[1]=t[e+1],Wt[2]=t[e+2],Wt[3]=t[e+3],Bc[0]}var Dc=new Float64Array([-0]),Be=new Uint8Array(Dc.buffer);function uh(t,e,r){Dc[0]=t,e[r]=Be[0],e[r+1]=Be[1],e[r+2]=Be[2],e[r+3]=Be[3],e[r+4]=Be[4],e[r+5]=Be[5],e[r+6]=Be[6],e[r+7]=Be[7]}function lh(t,e){return Be[0]=t[e],Be[1]=t[e+1],Be[2]=t[e+2],Be[3]=t[e+3],Be[4]=t[e+4],Be[5]=t[e+5],Be[6]=t[e+6],Be[7]=t[e+7],Dc[0]}var H0=BigInt(Number.MAX_SAFE_INTEGER),V0=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 mr;if(e<H0&&e>V0)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>hh&&(o=0n,++n>hh&&(n=0n))),new t(Number(o),Number(n))}static fromNumber(e){if(e===0)return mr;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):mr}},mr=new Ke(0,0);mr.toBigInt=function(){return 0n};mr.zzEncode=mr.zzDecode=function(){return this};mr.length=function(){return 1};var hh=4294967296n;function dh(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 ph(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 Rc(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 Qe(t,e){return RangeError(`index out of range: ${t.pos} + ${e??1} > ${t.len}`)}function Fs(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}var Oc=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,Qe(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 Qe(this,4);return Fs(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Qe(this,4);return Fs(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Qe(this,4);let e=fh(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Qe(this,4);let e=lh(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 Qe(this,e);return this.pos+=e,r===n?new Uint8Array(0):this.buf.subarray(r,n)}string(){let e=this.bytes();return ph(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Qe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Qe(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 Qe(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 Qe(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 Qe(this,8);let e=Fs(this.buf,this.pos+=4),r=Fs(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=Tn(this.buf,this.pos);return this.pos+=re(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 Pc(t){return new Oc(t instanceof Uint8Array?t:t.subarray())}function ks(t,e,r){let n=Pc(t);return e.decode(n,void 0,r)}function Nc(t){let e=t??8192,r=e>>>1,n,o=e;return function(i){if(i<1||i>r)return ae(i);o+i>e&&(n=ae(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var gr=class{fn;len;next;val;constructor(e,r,n){this.fn=e,this.len=r,this.next=void 0,this.val=n}};function Uc(){}var kc=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},$0=Nc();function z0(t){return globalThis.Buffer!=null?ae(t):$0(t)}var eo=class{len;head;tail;states;constructor(){this.len=0,this.head=new gr(Uc,0,0),this.tail=this.head,this.states=null}_push(e,r,n){return this.tail=this.tail.next=new gr(e,r,n),this.len+=r,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Mc((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(Ms,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(Ms,r.length(),r)}uint64Number(e){return this._push(Pt,re(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(Ms,r.length(),r)}sint64Number(e){let r=Ke.fromNumber(e).zzEncode();return this._push(Ms,r.length(),r)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Fc,1,e?1:0)}fixed32(e){return this._push(Jn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let r=Ke.fromBigInt(e);return this._push(Jn,4,r.lo)._push(Jn,4,r.hi)}fixed64Number(e){let r=Ke.fromNumber(e);return this._push(Jn,4,r.lo)._push(Jn,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(ch,4,e)}double(e){return this._push(uh,8,e)}bytes(e){let r=e.length>>>0;return r===0?this._push(Fc,1,0):this.uint32(r)._push(q0,r,e)}string(e){let r=dh(e);return r!==0?this.uint32(r)._push(Rc,r,e):this._push(Fc,1,0)}fork(){return this.states=new kc(this),this.head=this.tail=new gr(Uc,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 gr(Uc,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=z0(this.len),n=0;for(;e!=null;)e.fn(e.val,r,n),n+=e.len,e=e.next;return r}};function Fc(t,e,r){e[r]=t&255}function W0(t,e,r){for(;t>127;)e[r++]=t&127|128,t>>>=7;e[r]=t}var Mc=class extends gr{next;constructor(e,r){super(W0,e,r),this.next=void 0}};function Ms(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 Jn(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 q0(t,e,r){e.set(t,r)}globalThis.Buffer!=null&&(eo.prototype.bytes=function(t){let e=t.length>>>0;return this.uint32(e),e>0&&this._push(G0,e,t),this},eo.prototype.string=function(t){let e=globalThis.Buffer.byteLength(t);return this.uint32(e),e>0&&this._push(j0,e,t),this});function G0(t,e,r){e.set(t,r)}function j0(t,e,r){t.length<40?Rc(t,e,r):e.utf8Write!=null?e.utf8Write(t,r):e.set(W(t),r)}function Kc(){return new eo}function Ks(t,e){let r=Kc();return e.encode(t,r,{lengthDelimited:!1}),r.finish()}var to;(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"})(to||(to={}));function Hc(t,e,r,n){return{name:t,type:e,encode:r,decode:n}}function Hs(t,e){return Hc("message",to.LENGTH_DELIMITED,t,e)}var ro=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var Vs;(function(t){let e;t.codec=()=>(e==null&&(e=Hs((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 ro('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 ro('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=>Ks(r,t.codec()),t.decode=(r,n)=>ks(r,t.codec(),n)})(Vs||(Vs={}));var no;(function(t){let e;t.codec=()=>(e==null&&(e=Hs((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),Vs.codec().encode(r.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(r,n,o={})=>{let s={identityKey:pe(0),identitySig:pe(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=Vs.codec().decode(r,r.uint32(),{limits:o.limits?.extensions});break}default:{r.skipType(a&7);break}}}return s})),e),t.encode=r=>Ks(r,t.codec()),t.decode=(r,n)=>ks(r,t.codec(),n)})(no||(no={}));async function $c(t,e,r){let n=await t.sign(yh(e));return no.encode({identityKey:_t(t.publicKey),identitySig:n,extensions:r})}async function zc(t,e,r){try{let n=no.decode(t),o=Nn(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=yh(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new so(n.message)}}function yh(t){let e=W("noise-libp2p-static-key:");return t instanceof Uint8Array?Oe([e,t],e.length+t.length):(t.prepend(e),t)}var Vc=class extends Vt{stream;handshake;metrics;decoder;constructor(e,r,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=r,this.metrics=n,this.decoder=new ws({lengthDecoder:en,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 $;for(let n=0;n<e.byteLength;n+=65519){let o=n+65519;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),r.append(Jr(s.byteLength)),r.append(s)}return r}decrypt(e){let r=new $;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-yc<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-yc);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 Wc(t,e,r){return new Vc(t,e,r)}async function bh(t,e){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=t,u=await $c(s,a.publicKey,f),l=new Qn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});vc(l.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(l.writeMessageA(pr),e),r.trace("Stage 0 - Initiator finished sending first message."),_c(l.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");let p=l.readMessageB(await n.read(e));r.trace("Stage 1 - Initiator received the message."),Cc(l.re,r),ah(l.rs,r),r.trace("Initiator going to check remote's signature...");let d=await zc(p,l.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(l.writeMessageC(u),e),r.trace("Stage 2 - Initiator sent message with signed payload.");let[g,S]=l.ss.split();return Tc(g,S,r),{payload:d,encrypt:h=>g.encryptWithAd(pr,h),decrypt:(h,y)=>S.decryptWithAd(pr,h,y)}}async function wh(t,e){let{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:f}=t,u=await $c(s,a.publicKey,f),l=new Qn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});vc(l.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),l.readMessageA(await n.read(e)),r.trace("Stage 0 - Responder received first message."),Cc(l.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(l.writeMessageB(u),e),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),_c(l.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");let p=l.readMessageC(await n.read(e));r.trace("Stage 2 - Responder received the message, finished handshake.");let d=await zc(p,l.rs,c),[g,S]=l.ss.split();return Tc(g,S,r),{payload:d,encrypt:h=>S.encryptWithAd(pr,h),decrypt:(h,y)=>g.decryptWithAd(pr,h,y)}}var $s=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??oh;this.crypto=sh(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?ih(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??pe(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Er]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,r){let n=e.log?.newScope("noise")??this.log,o=ys(e,{lengthEncoder:Jr,lengthDecoder:en,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=Nn(s.payload.identityKey);return{connection:Wc(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Ia(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 io("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=ys(e,{lengthEncoder:Jr,lengthDecoder:en,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,r?.remotePeer?.publicKey,r),i=Nn(s.payload.identityKey);return{connection:Wc(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:Ia(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 bh({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 wh({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 xh(t={}){return e=>new $s(e,t)}var qc=Object.values(Xt).map(t=>t.decoder).reduce((t,e)=>t.or(e)),X0=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function Eh(t){return t?.match(X0)?.groups?.fingerprint}function Gc(t){let r=t.getComponents().find(n=>n.code===466)?.value;if(r===void 0||r==="")throw new G(`Couldn't find a certhash component of multiaddr: ${t.toString()}`);return r}function Y0(t){return $e.decode(qc.decode(t))}function Z0(t){let e=Y0(Gc(t)),r=Q0(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 Is(n,t.toString());return`${r} ${o.join(":").toUpperCase()}`}function Sh(t){let e=t.split(":").map(o=>parseInt(o,16)),r=Uint8Array.from(e),n=Re(ct.code,r);return $r(`/certhash/${ln.encode(n.bytes)}`)}function Q0(t){switch(t){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new Bs(t)}}function Ah(t,e){let{host:r,port:n,type:o}=sc(t);if(o!=="ip4"&&o!=="ip6")throw new G(`Multiaddr ${t} was not an IPv4 or IPv6 address`);let s=Z0(t);return{type:"answer",sdp:`v=0
|
|
3
3
|
o=- 0 0 IN IP${o==="ip4"?4:6} ${r}
|
|
4
4
|
s=-
|
|
5
5
|
t=0 0
|
|
@@ -8,15 +8,15 @@ m=application ${n} UDP/DTLS/SCTP webrtc-datachannel
|
|
|
8
8
|
c=IN IP${o==="ip4"?4:6} ${r}
|
|
9
9
|
a=mid:0
|
|
10
10
|
a=ice-options:ice2
|
|
11
|
-
a=ice-ufrag:${
|
|
12
|
-
a=ice-pwd:${
|
|
11
|
+
a=ice-ufrag:${e}
|
|
12
|
+
a=ice-pwd:${e}
|
|
13
13
|
a=fingerprint:${s}
|
|
14
14
|
a=setup:passive
|
|
15
15
|
a=sctp-port:5000
|
|
16
|
-
a=max-message-size:${
|
|
16
|
+
a=max-message-size:${Wr}
|
|
17
17
|
a=candidate:1467250027 1 UDP 1467250027 ${r} ${n} typ host
|
|
18
18
|
a=end-of-candidates
|
|
19
|
-
`}}function
|
|
19
|
+
`}}function vh(t,e){let{host:r,port:n,type:o}=sc(t);if(o!=="ip4"&&o!=="ip6")throw new G(`Multiaddr ${t} was not an IPv4 or IPv6 address`);return{type:"offer",sdp:`v=0
|
|
20
20
|
o=- 0 0 IN IP${o==="ip4"?4:6} ${r}
|
|
21
21
|
s=-
|
|
22
22
|
c=IN IP${o==="ip4"?4:6} ${r}
|
|
@@ -25,24 +25,21 @@ 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:${
|
|
29
|
-
a=ice-pwd:${
|
|
28
|
+
a=ice-ufrag:${e}
|
|
29
|
+
a=ice-pwd:${e}
|
|
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:${
|
|
32
|
+
a=max-message-size:${Wr}
|
|
33
33
|
a=candidate:1467250027 1 UDP 1467250027 ${r} ${n} typ host
|
|
34
34
|
a=end-of-candidates
|
|
35
|
-
`}}function
|
|
35
|
+
`}}function jc(t,e){if(t.sdp===void 0)throw new G("Can't munge a missing SDP");let r=t.sdp.includes(`\r
|
|
36
36
|
`)?`\r
|
|
37
37
|
`:`
|
|
38
|
-
`;try{
|
|
39
|
-
a=ice-ufrag:`+
|
|
40
|
-
a=ice-pwd:`+
|
|
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 Xc=W("libp2p-webrtc-noise:");function Ch(t,e,r){let n=t.trim().toLowerCase().replaceAll(":",""),o=W(n,"hex"),s=Re(ct.code,o),i=qc.decode(Gc(e)),a=Xc.byteLength+s.bytes.byteLength+i.byteLength;return r==="server"?Oe([Xc,i,s.bytes],a):Oe([Xc,s.bytes,i],a)}var J0=_s?"iceconnectionstatechange":"connectionstatechange";function eg(t,e){return t.role==="server"}async function Th(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 l=await t.createOffer();n.log.trace("client created local offer %s",l.sdp);let p=jc(l,r);n.log.trace("client setting local offer %s",p.sdp),await t.setLocalDescription(p);let d=Ah(n.remoteAddr,r);n.log.trace("client setting server description %s",d.sdp),await t.setRemoteDescription(d)}else{let l=vh(n.remoteAddr,r);n.log.trace("server setting client %s %s",l.type,l.sdp),await t.setRemoteDescription(l),n.log.trace("server creating local answer");let p=await t.createAnswer();n.log.trace("server created local answer");let d=jc(p,r);n.log.trace("server setting local description %s",p.sdp),await t.setLocalDescription(d)}if(o.readyState!=="open"&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,o.readyState),await Ae(o,"open",n)),n.log.trace("%s handshake channel opened",n.role),eg(n,t)){let l=t.remoteFingerprint()?.value??"";n.remoteAddr=n.remoteAddr.encapsulate(Sh(l))}let s=Eh(t.localDescription?.sdp);if(s==null)throw new zt("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);let i=Ch(s,n.remoteAddr,n.role),a=xh({prologueBytes:i})(n),c=jn({channel:o,direction:"outbound",isHandshake:!0,log:n.log,...n.dataChannel??{}}),f=Xn({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(J0,()=>{switch(t.connectionState){case"failed":case"disconnected":case"closed":f.close().catch(l=>{n.log.error("error closing connection - %e",l),f.abort(l)});break;default:break}}),n.events?.increment({peer_connection:!0}),n.role==="client"){n.log.trace("%s secure inbound",n.role);let l=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:l.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 Ih(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 $t({peerConnection:s,metrics:r.events,dataChannelOptions:r.dataChannel});return{peerConnection:s,muxerFactory:i}}var zs=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"})})}[yo]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Er]=["@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=kr(o));let s=Fl(),{peerConnection:i,muxerFactory:a}=await Ih("client",s,{rtcConfiguration:typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{},dataChannel:this.init.dataChannel});try{return await Th(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 Ls("WebRTCDirectTransport.createListener")}listenFilter(e){return[]}dialFilter(e){return e.filter(wl.exactMatch)}};function tg(t){return e=>new zs(e,t)}function rg(t){return e=>new Ps(e,t)}return Oh(ng);})();
|
|
41
41
|
/*! Bundled license information:
|
|
42
42
|
|
|
43
|
-
@noble/hashes/utils.js:
|
|
44
|
-
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
45
|
-
|
|
46
43
|
@noble/curves/utils.js:
|
|
47
44
|
@noble/curves/abstract/modular.js:
|
|
48
45
|
@noble/curves/abstract/curve.js:
|