@libp2p/webrtc 5.2.2 → 5.2.3-5b084e968
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/README.md +1 -1
- package/dist/index.min.js +4 -4
- package/dist/src/constants.d.ts +6 -0
- package/dist/src/constants.d.ts.map +1 -1
- package/dist/src/constants.js +6 -0
- package/dist/src/constants.js.map +1 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/maconn.d.ts +1 -1
- package/dist/src/maconn.js +1 -1
- package/dist/src/muxer.js +1 -1
- package/dist/src/muxer.js.map +1 -1
- package/dist/src/private-to-public/listener.d.ts.map +1 -1
- package/dist/src/private-to-public/listener.js +3 -8
- package/dist/src/private-to-public/listener.js.map +1 -1
- package/dist/src/private-to-public/transport.d.ts +0 -12
- package/dist/src/private-to-public/transport.d.ts.map +1 -1
- package/dist/src/private-to-public/transport.js +1 -17
- package/dist/src/private-to-public/transport.js.map +1 -1
- package/dist/src/private-to-public/utils/connect.js +13 -4
- package/dist/src/private-to-public/utils/connect.js.map +1 -1
- package/dist/src/private-to-public/utils/generate-noise-prologue.js +1 -1
- package/dist/src/private-to-public/utils/generate-noise-prologue.js.map +1 -1
- package/dist/src/private-to-public/utils/sdp.d.ts +1 -1
- package/dist/src/private-to-public/utils/sdp.d.ts.map +1 -1
- package/dist/src/private-to-public/utils/sdp.js +10 -10
- package/dist/src/private-to-public/utils/sdp.js.map +1 -1
- package/dist/src/stream.js +5 -5
- package/dist/src/stream.js.map +1 -1
- package/package.json +8 -8
- package/src/constants.ts +7 -0
- package/src/index.ts +1 -1
- package/src/maconn.ts +1 -1
- package/src/muxer.ts +1 -1
- package/src/private-to-public/listener.ts +3 -9
- package/src/private-to-public/transport.ts +1 -20
- package/src/private-to-public/utils/connect.ts +13 -4
- package/src/private-to-public/utils/generate-noise-prologue.ts +1 -1
- package/src/private-to-public/utils/sdp.ts +10 -10
- package/src/stream.ts +5 -5
- package/dist/typedoc-urls.json +0 -14
package/dist/index.min.js
CHANGED
@@ -1,9 +1,9 @@
|
|
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 Zh=Object.create;var Gn=Object.defineProperty;var Xh=Object.getOwnPropertyDescriptor;var Yh=Object.getOwnPropertyNames;var Jh=Object.getPrototypeOf,Qh=Object.prototype.hasOwnProperty;var ed=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ce=(r,e)=>{for(var t in e)Gn(r,t,{get:e[t],enumerable:!0})},jc=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Yh(e))!Qh.call(r,o)&&o!==t&&Gn(r,o,{get:()=>e[o],enumerable:!(n=Xh(e,o))||n.enumerable});return r};var td=(r,e,t)=>(t=r!=null?Zh(Jh(r)):{},jc(e||!r||!r.__esModule?Gn(t,"default",{value:r,enumerable:!0}):t,r)),rd=r=>jc(Gn({},"__esModule",{value:!0}),r);var Xl=ed(Nr=>{"use strict";var S0="[object ArrayBuffer]",At=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===S0}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let i of t)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of t){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},Ea="string",I0=/^[0-9a-f\s]+$/i,C0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,k0=/^[a-zA-Z0-9-_]+$/,wo=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=At.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},je=class{static toString(e,t=!1){let n=At.toArrayBuffer(e),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,t);s+=String.fromCharCode(a)}return s}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let s=0;s<e.length;s++)o.setUint16(s*2,e.charCodeAt(s),t);return n}},bo=class r{static isHex(e){return typeof e===Ea&&I0.test(e)}static isBase64(e){return typeof e===Ea&&C0.test(e)}static isBase64Url(e){return typeof e===Ea&&k0.test(e)}static ToString(e,t="utf8"){let n=At.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return je.toString(n,!0);case"utf16":case"utf16be":return je.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return je.fromString(e,!0);case"utf16":case"utf16be":return je.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=At.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return wo.fromString(e);case"utf16":case"utf16be":return je.fromString(e);case"utf16le":case"usc2":return je.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return wo.toString(e);case"utf16":case"utf16be":return je.toString(e);case"utf16le":case"usc2":return je.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){let t=At.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=At.toUint8Array(e),n="",o=t.length;for(let s=0;s<o;s++){let i=t[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o=o+2){let s=t.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(e,t=!1){return je.toString(e,t)}static FromUtf16String(e,t=!1){return je.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};bo.DEFAULT_UTF8_ENCODING="utf8";function T0(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)t[s]=o[s]}return t}function L0(...r){let e=r.map(o=>o.byteLength).reduce((o,s)=>o+s),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)t[n++]=s}),t.buffer}function N0(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}Nr.BufferSourceConverter=At;Nr.Convert=bo;Nr.assign=T0;Nr.combine=L0;Nr.isEqual=N0});var Ug={};Ce(Ug,{webRTC:()=>Rg,webRTCDirect:()=>_g});var hi=Symbol.for("@libp2p/peer-id");var Wn=Symbol.for("@libp2p/transport");var Zc;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Zc||(Zc={}));var qn=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}};var oe=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},yr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var zn=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}};var jn=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}},Yt=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}};var Zn=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Xn=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Yn=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}};var Jt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var wr=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var br=Symbol.for("@libp2p/service-capabilities"),Xc=Symbol.for("@libp2p/service-dependencies");var yi={};Ce(yi,{base58btc:()=>se,base58flickr:()=>cd});var cy=new Uint8Array(0);function Yc(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function pt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Jc(r){return new TextEncoder().encode(r)}function Qc(r){return new TextDecoder().decode(r)}function nd(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var g=0,h=0,b=0,x=y.length;b!==x&&y[b]===0;)b++,g++;for(var p=(x-b)*u+1>>>0,S=new Uint8Array(p);b!==x;){for(var N=y[b],L=0,B=p-1;(N!==0||L<h)&&B!==-1;B--,L++)N+=256*S[B]>>>0,S[B]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");h=L,b++}for(var T=p-h;T!==p&&S[T]===0;)T++;for(var C=c.repeat(g);T<p;++T)C+=r.charAt(S[T]);return C}function d(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var g=0;if(y[g]!==" "){for(var h=0,b=0;y[g]===c;)h++,g++;for(var x=(y.length-g)*l+1>>>0,p=new Uint8Array(x);y[g];){var S=t[y.charCodeAt(g)];if(S===255)return;for(var N=0,L=x-1;(S!==0||N<b)&&L!==-1;L--,N++)S+=a*p[L]>>>0,p[L]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");b=N,g++}if(y[g]!==" "){for(var B=x-b;B!==x&&p[B]===0;)B++;for(var T=new Uint8Array(h+(x-B)),C=h;B!==x;)T[C++]=p[B++];return T}}}function m(y){var g=d(y);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:m}}var od=nd,sd=od,tl=sd;var di=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},pi=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.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 rl(this,e)}},mi=class{decoders;constructor(e){this.decoders=e}or(e){return rl(this,e)}decode(e){let t=e[0],n=this.decoders[t];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 rl(r,e){return new mi({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var gi=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new di(e,t,n),this.decoder=new pi(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function xr({name:r,prefix:e,encode:t,decode:n}){return new gi(r,e,t,n)}function Ut({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=tl(t,r);return xr({prefix:e,name:r,encode:n,decode:s=>pt(o(s))})}function id(r,e,t,n){let o={};for(let u=0;u<e.length;++u)o[e[u]]=u;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),a=0,c=0,l=0;for(let u=0;u<s;++u){let f=o[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|f,a+=t,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function ad(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;s.length*t&7;)s+="=";return s}function de({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return xr({prefix:e,name:r,encode(o){return ad(o,n,t)},decode(o){return id(o,n,t,r)}})}var se=Ut({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),cd=Ut({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var wi={};Ce(wi,{base32:()=>mt,base32hex:()=>hd,base32hexpad:()=>pd,base32hexpadupper:()=>md,base32hexupper:()=>dd,base32pad:()=>ud,base32padupper:()=>fd,base32upper:()=>ld,base32z:()=>gd});var mt=de({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ld=de({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ud=de({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),fd=de({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),hd=de({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),dd=de({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),pd=de({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),md=de({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),gd=de({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var bi={};Ce(bi,{base36:()=>Xr,base36upper:()=>yd});var Xr=Ut({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),yd=Ut({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var We={};Ce(We,{Digest:()=>Qt,create:()=>ke,decode:()=>Dt,equals:()=>Ei,hasCode:()=>Pd});var wd=sl,nl=128,bd=127,xd=~bd,Ed=Math.pow(2,31);function sl(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Ed;)e[t++]=r&255|nl,r/=128;for(;r&xd;)e[t++]=r&255|nl,r>>>=7;return e[t]=r|0,sl.bytes=t-n+1,e}var vd=xi,Ad=128,ol=127;function xi(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw xi.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&ol)<<o:(i&ol)*Math.pow(2,o),o+=7}while(i>=Ad);return xi.bytes=s-n,t}var Bd=Math.pow(2,7),Sd=Math.pow(2,14),Id=Math.pow(2,21),Cd=Math.pow(2,28),kd=Math.pow(2,35),Td=Math.pow(2,42),Ld=Math.pow(2,49),Nd=Math.pow(2,56),_d=Math.pow(2,63),Rd=function(r){return r<Bd?1:r<Sd?2:r<Id?3:r<Cd?4:r<kd?5:r<Td?6:r<Ld?7:r<Nd?8:r<_d?9:10},Ud={encode:wd,decode:vd,encodingLength:Rd},Dd=Ud,Yr=Dd;function Jr(r,e=0){return[Yr.decode(r,e),Yr.decode.bytes]}function Er(r,e,t=0){return Yr.encode(r,e,t),e}function vr(r){return Yr.encodingLength(r)}function ke(r,e){let t=e.byteLength,n=vr(r),o=n+vr(t),s=new Uint8Array(o+t);return Er(r,s,0),Er(t,s,n),s.set(e,o),new Qt(r,t,e,s)}function Dt(r){let e=pt(r),[t,n]=Jr(e),[o,s]=Jr(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Qt(t,o,i,e)}function Ei(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Yc(r.bytes,t.bytes)}}var Qt=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function Pd(r,e){return r.code===e}function il(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Md(t,vi(r),e??se.encoder);default:return Hd(t,vi(r),e??mt.encoder)}}var al=new WeakMap;function vi(r){let e=al.get(r);if(e==null){let t=new Map;return al.set(r,t),t}return e}var Ee=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,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:t}=this;if(e!==Qr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Fd)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}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:t}=this.multihash,n=ke(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Ei(e.multihash,n.multihash)}toString(e){return il(this,e)}toJSON(){return{"/":il(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 t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??cl(n,o,s.bytes))}else if(t[Vd]===!0){let{version:n,multihash:o,code:s}=t,i=Dt(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="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(t!==Qr)throw new Error(`Version 0 CID must use dag-pb (code: ${Qr}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=cl(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Qr,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=pt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Qt(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=Jr(e.subarray(t));return t+=d,f},o=n(),s=Qr;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=Od(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return vi(s).set(n,e),s}};function Od(r,e){switch(r[0]){case"Q":{let t=e??se;return[se.prefix,t.decode(`${se.prefix}${r}`)]}case se.prefix:{let t=e??se;return[se.prefix,t.decode(r)]}case mt.prefix:{let t=e??mt;return[mt.prefix,t.decode(r)]}case Xr.prefix:{let t=e??Xr;return[Xr.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Md(r,e,t){let{prefix:n}=t;if(n!==se.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Hd(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Qr=112,Fd=18;function cl(r,e,t){let n=vr(r),o=n+vr(e),s=new Uint8Array(o+t.byteLength);return Er(r,s,0),Er(e,s,n),s.set(t,o),s}var Vd=Symbol.for("@ipld/js-cid/CID");var Ai={};Ce(Ai,{identity:()=>gt});var ll=0,Kd="identity",ul=pt;function $d(r){return ke(ll,ul(r))}var gt={code:ll,name:Kd,encode:ul,digest:$d};function De(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Qn(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Gd(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ar(r,...e){if(!Gd(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function en(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Qn(r.outputLen),Qn(r.blockLen)}function Br(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function fl(r,e){Ar(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var er=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function eo(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Xe(r,e){return r<<32-e|r>>>e}function hl(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function Pt(r){return typeof r=="string"&&(r=hl(r)),Ar(r),r}function Bi(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Ar(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}var Sr=class{clone(){return this._cloneInto()}};function to(r){let e=n=>r().update(Pt(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function tn(r=32){if(er&&typeof er.getRandomValues=="function")return er.getRandomValues(new Uint8Array(r));if(er&&typeof er.randomBytes=="function")return er.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function Wd(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,l=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+l,a,n)}function dl(r,e,t){return r&e^~r&t}function pl(r,e,t){return r&e^r&t^e&t}var Ir=class extends Sr{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=eo(this.buffer)}update(e){Br(this);let{view:t,buffer:n,blockLen:o}=this;e=Pt(e);let s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=eo(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(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Br(this),fl(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)t[f]=0;Wd(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=eo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.length=o,e.pos=a,e.finished=s,e.destroyed=i,o%t&&e.buffer.set(n),e}};var ro=BigInt(4294967295),Si=BigInt(32);function ml(r,e=!1){return e?{h:Number(r&ro),l:Number(r>>Si&ro)}:{h:Number(r>>Si&ro)|0,l:Number(r&ro)|0}}function qd(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=ml(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var zd=(r,e)=>BigInt(r>>>0)<<Si|BigInt(e>>>0),jd=(r,e,t)=>r>>>t,Zd=(r,e,t)=>r<<32-t|e>>>t,Xd=(r,e,t)=>r>>>t|e<<32-t,Yd=(r,e,t)=>r<<32-t|e>>>t,Jd=(r,e,t)=>r<<64-t|e>>>t-32,Qd=(r,e,t)=>r>>>t-32|e<<64-t,ep=(r,e)=>e,tp=(r,e)=>r,rp=(r,e,t)=>r<<t|e>>>32-t,np=(r,e,t)=>e<<t|r>>>32-t,op=(r,e,t)=>e<<t-32|r>>>64-t,sp=(r,e,t)=>r<<t-32|e>>>64-t;function ip(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var ap=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),cp=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,lp=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),up=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,fp=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),hp=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var dp={fromBig:ml,split:qd,toBig:zd,shrSH:jd,shrSL:Zd,rotrSH:Xd,rotrSL:Yd,rotrBH:Jd,rotrBL:Qd,rotr32H:ep,rotr32L:tp,rotlSH:rp,rotlSL:np,rotlBH:op,rotlBL:sp,add:ip,add3L:ap,add3H:cp,add4L:lp,add4H:up,add5H:hp,add5L:fp},$=dp;var[pp,mp]=$.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Ot=new Uint32Array(80),Mt=new Uint32Array(80),Ii=class extends Ir{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:m,Gl:y,Hh:g,Hl:h}=this;return[e,t,n,o,s,i,a,c,l,u,f,d,m,y,g,h]}set(e,t,n,o,s,i,a,c,l,u,f,d,m,y,g,h){this.Ah=e|0,this.Al=t|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=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=m|0,this.Gl=y|0,this.Hh=g|0,this.Hl=h|0}process(e,t){for(let p=0;p<16;p++,t+=4)Ot[p]=e.getUint32(t),Mt[p]=e.getUint32(t+=4);for(let p=16;p<80;p++){let S=Ot[p-15]|0,N=Mt[p-15]|0,L=$.rotrSH(S,N,1)^$.rotrSH(S,N,8)^$.shrSH(S,N,7),B=$.rotrSL(S,N,1)^$.rotrSL(S,N,8)^$.shrSL(S,N,7),T=Ot[p-2]|0,C=Mt[p-2]|0,H=$.rotrSH(T,C,19)^$.rotrBH(T,C,61)^$.shrSH(T,C,6),U=$.rotrSL(T,C,19)^$.rotrBL(T,C,61)^$.shrSL(T,C,6),M=$.add4L(B,U,Mt[p-7],Mt[p-16]),V=$.add4H(M,L,H,Ot[p-7],Ot[p-16]);Ot[p]=V|0,Mt[p]=M|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:m,Fl:y,Gh:g,Gl:h,Hh:b,Hl:x}=this;for(let p=0;p<80;p++){let S=$.rotrSH(f,d,14)^$.rotrSH(f,d,18)^$.rotrBH(f,d,41),N=$.rotrSL(f,d,14)^$.rotrSL(f,d,18)^$.rotrBL(f,d,41),L=f&m^~f&g,B=d&y^~d&h,T=$.add5L(x,N,B,mp[p],Mt[p]),C=$.add5H(T,b,S,L,pp[p],Ot[p]),H=T|0,U=$.rotrSH(n,o,28)^$.rotrBH(n,o,34)^$.rotrBH(n,o,39),M=$.rotrSL(n,o,28)^$.rotrBL(n,o,34)^$.rotrBL(n,o,39),V=n&s^n&a^s&a,I=o&i^o&c^i&c;b=g|0,x=h|0,g=m|0,h=y|0,m=f|0,y=d|0,{h:f,l:d}=$.add(l|0,u|0,C|0,H|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let k=$.add3L(H,M,I);n=$.add3H(k,C,U,V),o=k|0}({h:n,l:o}=$.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=$.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=$.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=$.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=$.add(this.Eh|0,this.El|0,f|0,d|0),{h:m,l:y}=$.add(this.Fh|0,this.Fl|0,m|0,y|0),{h:g,l:h}=$.add(this.Gh|0,this.Gl|0,g|0,h|0),{h:b,l:x}=$.add(this.Hh|0,this.Hl|0,b|0,x|0),this.set(n,o,s,i,a,c,l,u,f,d,m,y,g,h,b,x)}roundClean(){Ot.fill(0),Mt.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var gl=to(()=>new Ii);var so={};Ce(so,{aInRange:()=>ve,abool:()=>Ye,abytes:()=>Cr,bitGet:()=>Ep,bitLen:()=>Li,bitMask:()=>nn,bitSet:()=>vp,bytesToHex:()=>wt,bytesToNumberBE:()=>bt,bytesToNumberLE:()=>Je,concatBytes:()=>Et,createHmacDrbg:()=>Ni,ensureBytes:()=>ie,equalBytes:()=>bp,hexToBytes:()=>rr,hexToNumber:()=>Ti,inRange:()=>rn,isBytes:()=>Ht,memoized:()=>nr,notImplemented:()=>Bp,numberToBytesBE:()=>Ft,numberToBytesLE:()=>xt,numberToHexUnpadded:()=>tr,numberToVarBytesBE:()=>wp,utf8ToBytes:()=>xp,validateObject:()=>qe});var no=BigInt(0),oo=BigInt(1),gp=BigInt(2);function Ht(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Cr(r){if(!Ht(r))throw new Error("Uint8Array expected")}function Ye(r,e){if(typeof e!="boolean")throw new Error(r+" boolean expected, got "+e)}var yp=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function wt(r){Cr(r);let e="";for(let t=0;t<r.length;t++)e+=yp[r[t]];return e}function tr(r){let e=r.toString(16);return e.length&1?"0"+e:e}function Ti(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?no:BigInt("0x"+r)}var yt={_0:48,_9:57,A:65,F:70,a:97,f:102};function yl(r){if(r>=yt._0&&r<=yt._9)return r-yt._0;if(r>=yt.A&&r<=yt.F)return r-(yt.A-10);if(r>=yt.a&&r<=yt.f)return r-(yt.a-10)}function rr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=yl(r.charCodeAt(s)),a=yl(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function bt(r){return Ti(wt(r))}function Je(r){return Cr(r),Ti(wt(Uint8Array.from(r).reverse()))}function Ft(r,e){return rr(r.toString(16).padStart(e*2,"0"))}function xt(r,e){return Ft(r,e).reverse()}function wp(r){return rr(tr(r))}function ie(r,e,t){let n;if(typeof e=="string")try{n=rr(e)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Ht(e))n=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(r+" of length "+t+" expected, got "+o);return n}function Et(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Cr(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function bp(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function xp(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var Ci=r=>typeof r=="bigint"&&no<=r;function rn(r,e,t){return Ci(r)&&Ci(e)&&Ci(t)&&e<=r&&r<t}function ve(r,e,t,n){if(!rn(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Li(r){let e;for(e=0;r>no;r>>=oo,e+=1);return e}function Ep(r,e){return r>>BigInt(e)&oo}function vp(r,e,t){return r|(t?oo:no)<<BigInt(e)}var nn=r=>(gp<<BigInt(r-1))-oo,ki=r=>new Uint8Array(r),wl=r=>Uint8Array.from(r);function Ni(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=ki(r),o=ki(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>t(o,n,...f),c=(f=ki())=>{o=a(wl([0]),f),n=a(),f.length!==0&&(o=a(wl([1]),f),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<e;){n=a();let m=n.slice();d.push(m),f+=n.length}return Et(...d)};return(f,d)=>{i(),c(f);let m;for(;!(m=d(l()));)c();return i(),m}}var Ap={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Ht(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function qe(r,e,t={}){let n=(o,s,i)=>{let a=Ap[s];if(typeof a!="function")throw new Error("invalid validator function");let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(e))n(o,s,!1);for(let[o,s]of Object.entries(t))n(o,s,!0);return r}var Bp=()=>{throw new Error("not implemented")};function nr(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var ge=BigInt(0),he=BigInt(1),or=BigInt(2),Sp=BigInt(3),_i=BigInt(4),bl=BigInt(5),xl=BigInt(8),Ip=BigInt(9),Cp=BigInt(16);function Z(r,e){let t=r%e;return t>=ge?t:e+t}function Ri(r,e,t){if(e<ge)throw new Error("invalid exponent, negatives unsupported");if(t<=ge)throw new Error("invalid modulus");if(t===he)return ge;let n=he;for(;e>ge;)e&he&&(n=n*r%t),r=r*r%t,e>>=he;return n}function le(r,e,t){let n=r;for(;e-- >ge;)n*=n,n%=t;return n}function io(r,e){if(r===ge)throw new Error("invert: expected non-zero number");if(e<=ge)throw new Error("invert: expected positive modulus, got "+e);let t=Z(r,e),n=e,o=ge,s=he,i=he,a=ge;for(;t!==ge;){let l=n/t,u=n%t,f=o-i*l,d=s-a*l;n=t,t=u,o=i,s=a,i=f,a=d}if(n!==he)throw new Error("invert: does not exist");return Z(o,e)}function kp(r){let e=(r-he)/or,t,n,o;for(t=r-he,n=0;t%or===ge;t/=or,n++);for(o=or;o<r&&Ri(o,e,r)!==r-he;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(r+he)/_i;return function(c,l){let u=c.pow(l,i);if(!c.eql(c.sqr(u),l))throw new Error("Cannot find square root");return u}}let s=(t+he)/or;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),t),f=a.pow(c,s),d=a.pow(c,t);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let m=1;for(let g=a.sqr(d);m<l&&!a.eql(g,a.ONE);m++)g=a.sqr(g);let y=a.pow(u,he<<BigInt(l-m-1));u=a.sqr(y),f=a.mul(f,y),d=a.mul(d,u),l=m}return f}}function Tp(r){if(r%_i===Sp){let e=(r+he)/_i;return function(n,o){let s=n.pow(o,e);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%xl===bl){let e=(r-bl)/xl;return function(n,o){let s=n.mul(o,or),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,or),i),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%Cp,kp(r)}var El=(r,e)=>(Z(r,e)&he)===he,Lp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ui(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Lp.reduce((n,o)=>(n[o]="function",n),e);return qe(r,t)}function Np(r,e,t){if(t<ge)throw new Error("invalid exponent, negatives unsupported");if(t===ge)return r.ONE;if(t===he)return e;let n=r.ONE,o=e;for(;t>ge;)t&he&&(n=r.mul(n,o)),o=r.sqr(o),t>>=he;return n}function _p(r,e){let t=new Array(e.length),n=e.reduce((s,i,a)=>r.is0(i)?s:(t[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return e.reduceRight((s,i,a)=>r.is0(i)?s:(t[a]=r.mul(s,t[a]),r.mul(s,i)),o),t}function Di(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Vt(r,e,t=!1,n={}){if(r<=ge)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=Di(r,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:r,isLE:t,BITS:o,BYTES:s,MASK:nn(o),ZERO:ge,ONE:he,create:c=>Z(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return ge<=c&&c<r},is0:c=>c===ge,isOdd:c=>(c&he)===he,neg:c=>Z(-c,r),eql:(c,l)=>c===l,sqr:c=>Z(c*c,r),add:(c,l)=>Z(c+l,r),sub:(c,l)=>Z(c-l,r),mul:(c,l)=>Z(c*l,r),pow:(c,l)=>Np(a,c,l),div:(c,l)=>Z(c*io(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>io(c,r),sqrt:n.sqrt||(c=>(i||(i=Tp(r)),i(a,c))),invertBatch:c=>_p(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>t?xt(c,s):Ft(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return t?Je(c):bt(c)}});return Object.freeze(a)}function vl(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function Pi(r){let e=vl(r);return e+Math.ceil(e/2)}function Al(r,e,t=!1){let n=r.length,o=vl(e),s=Pi(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?Je(r):bt(r),a=Z(i,e-he)+he;return t?xt(a,o):Ft(a,o)}var Bl=BigInt(0),ao=BigInt(1);function Oi(r,e){let t=e.negate();return r?t:e}function Sl(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Mi(r,e){Sl(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1);return{windows:t,windowSize:n}}function Rp(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function Up(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)})}var Hi=new WeakMap,Il=new WeakMap;function Fi(r){return Il.get(r)||1}function co(r,e){return{constTimeNegate:Oi,hasPrecomputes(t){return Fi(t)!==1},unsafeLadder(t,n,o=r.ZERO){let s=t;for(;n>Bl;)n&ao&&(o=o.add(s)),s=s.double(),n>>=ao;return o},precomputeWindow(t,n){let{windows:o,windowSize:s}=Mi(n,e),i=[],a=t,c=a;for(let l=0;l<o;l++){c=a,i.push(c);for(let u=1;u<s;u++)c=c.add(a),i.push(c);a=c.double()}return i},wNAF(t,n,o){let{windows:s,windowSize:i}=Mi(t,e),a=r.ZERO,c=r.BASE,l=BigInt(2**t-1),u=2**t,f=BigInt(t);for(let d=0;d<s;d++){let m=d*i,y=Number(o&l);o>>=f,y>i&&(y-=u,o+=ao);let g=m,h=m+Math.abs(y)-1,b=d%2!==0,x=y<0;y===0?c=c.add(Oi(b,n[g])):a=a.add(Oi(x,n[h]))}return{p:a,f:c}},wNAFUnsafe(t,n,o,s=r.ZERO){let{windows:i,windowSize:a}=Mi(t,e),c=BigInt(2**t-1),l=2**t,u=BigInt(t);for(let f=0;f<i;f++){let d=f*a;if(o===Bl)break;let m=Number(o&c);if(o>>=u,m>a&&(m-=l,o+=ao),m===0)continue;let y=n[d+Math.abs(m)-1];m<0&&(y=y.negate()),s=s.add(y)}return s},getPrecomputes(t,n,o){let s=Hi.get(n);return s||(s=this.precomputeWindow(n,t),t!==1&&Hi.set(n,o(s))),s},wNAFCached(t,n,o){let s=Fi(t);return this.wNAF(s,this.getPrecomputes(s,t,o),n)},wNAFCachedUnsafe(t,n,o,s){let i=Fi(t);return i===1?this.unsafeLadder(t,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,t,o),n,s)},setWindowSize(t,n){Sl(n,e),Il.set(t,n),Hi.delete(t)}}}function lo(r,e,t,n){if(Rp(t,r),Up(n,e),t.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,s=Li(BigInt(t.length)),i=s>12?s-3:s>4?s-2:s?2:1,a=(1<<i)-1,c=new Array(a+1).fill(o),l=Math.floor((e.BITS-1)/i)*i,u=o;for(let f=l;f>=0;f-=i){c.fill(o);for(let m=0;m<n.length;m++){let y=n[m],g=Number(y>>BigInt(f)&BigInt(a));c[g]=c[g].add(t[m])}let d=o;for(let m=c.length-1,y=o;m>0;m--)y=y.add(c[m]),d=d.add(y);if(u=u.add(d),f!==0)for(let m=0;m<i;m++)u=u.double()}return u}function on(r){return Ui(r.Fp),qe(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Di(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Qe=BigInt(0),He=BigInt(1),uo=BigInt(2),Dp=BigInt(8),Pp={zip215:!0};function Op(r){let e=on(r);return qe(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Cl(r){let e=Op(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,l=uo<<BigInt(a*8)-He,u=t.create,f=Vt(e.n,e.nBitLength),d=e.uvRatio||((E,w)=>{try{return{isValid:!0,value:t.sqrt(E*t.inv(w))}}catch{return{isValid:!1,value:Qe}}}),m=e.adjustScalarBytes||(E=>E),y=e.domain||((E,w,A)=>{if(Ye("phflag",A),w.length||A)throw new Error("Contexts/pre-hash are not supported");return E});function g(E,w){ve("coordinate "+E,w,Qe,l)}function h(E){if(!(E instanceof p))throw new Error("ExtendedPoint expected")}let b=nr((E,w)=>{let{ex:A,ey:v,ez:_}=E,R=E.is0();w==null&&(w=R?Dp:t.inv(_));let O=u(A*w),K=u(v*w),F=u(_*w);if(R)return{x:Qe,y:He};if(F!==He)throw new Error("invZ was invalid");return{x:O,y:K}}),x=nr(E=>{let{a:w,d:A}=e;if(E.is0())throw new Error("bad point: ZERO");let{ex:v,ey:_,ez:R,et:O}=E,K=u(v*v),F=u(_*_),G=u(R*R),j=u(G*G),ae=u(K*w),ce=u(G*u(ae+F)),fe=u(j+u(A*u(K*F)));if(ce!==fe)throw new Error("bad point: equation left != right (1)");let Ie=u(v*_),Me=u(R*O);if(Ie!==Me)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(w,A,v,_){this.ex=w,this.ey=A,this.ez=v,this.et=_,g("x",w),g("y",A),g("z",v),g("t",_),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(w){if(w instanceof p)throw new Error("extended point not allowed");let{x:A,y:v}=w||{};return g("x",A),g("y",v),new p(A,v,He,u(A*v))}static normalizeZ(w){let A=t.invertBatch(w.map(v=>v.ez));return w.map((v,_)=>v.toAffine(A[_])).map(p.fromAffine)}static msm(w,A){return lo(p,f,w,A)}_setWindowSize(w){L.setWindowSize(this,w)}assertValidity(){x(this)}equals(w){h(w);let{ex:A,ey:v,ez:_}=this,{ex:R,ey:O,ez:K}=w,F=u(A*K),G=u(R*_),j=u(v*K),ae=u(O*_);return F===G&&j===ae}is0(){return this.equals(p.ZERO)}negate(){return new p(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:w}=e,{ex:A,ey:v,ez:_}=this,R=u(A*A),O=u(v*v),K=u(uo*u(_*_)),F=u(w*R),G=A+v,j=u(u(G*G)-R-O),ae=F+O,ce=ae-K,fe=F-O,Ie=u(j*ce),Me=u(ae*fe),Ue=u(j*fe),it=u(ce*ae);return new p(Ie,Me,it,Ue)}add(w){h(w);let{a:A,d:v}=e,{ex:_,ey:R,ez:O,et:K}=this,{ex:F,ey:G,ez:j,et:ae}=w;if(A===BigInt(-1)){let Vc=u((R-_)*(G+F)),Kc=u((R+_)*(G-F)),fi=u(Kc-Vc);if(fi===Qe)return this.double();let $c=u(O*uo*ae),Gc=u(K*uo*j),Wc=Gc+$c,qc=Kc+Vc,zc=Gc-$c,Wh=u(Wc*fi),qh=u(qc*zc),zh=u(Wc*zc),jh=u(fi*qc);return new p(Wh,qh,jh,zh)}let ce=u(_*F),fe=u(R*G),Ie=u(K*v*ae),Me=u(O*j),Ue=u((_+R)*(F+G)-ce-fe),it=Me-Ie,dt=Me+Ie,Zr=u(fe-A*ce),Vh=u(Ue*it),Kh=u(dt*Zr),$h=u(Ue*Zr),Gh=u(it*dt);return new p(Vh,Kh,Gh,$h)}subtract(w){return this.add(w.negate())}wNAF(w){return L.wNAFCached(this,w,p.normalizeZ)}multiply(w){let A=w;ve("scalar",A,He,n);let{p:v,f:_}=this.wNAF(A);return p.normalizeZ([v,_])[0]}multiplyUnsafe(w,A=p.ZERO){let v=w;return ve("scalar",v,Qe,n),v===Qe?N:this.is0()||v===He?this:L.wNAFCachedUnsafe(this,v,p.normalizeZ,A)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return L.unsafeLadder(this,n).is0()}toAffine(w){return b(this,w)}clearCofactor(){let{h:w}=e;return w===He?this:this.multiplyUnsafe(w)}static fromHex(w,A=!1){let{d:v,a:_}=e,R=t.BYTES;w=ie("pointHex",w,R),Ye("zip215",A);let O=w.slice(),K=w[R-1];O[R-1]=K&-129;let F=Je(O),G=A?l:t.ORDER;ve("pointHex.y",F,Qe,G);let j=u(F*F),ae=u(j-He),ce=u(v*j-_),{isValid:fe,value:Ie}=d(ae,ce);if(!fe)throw new Error("Point.fromHex: invalid y coordinate");let Me=(Ie&He)===He,Ue=(K&128)!==0;if(!A&&Ie===Qe&&Ue)throw new Error("Point.fromHex: x=0 and x_0=1");return Ue!==Me&&(Ie=u(-Ie)),p.fromAffine({x:Ie,y:F})}static fromPrivateKey(w){return C(w).point}toRawBytes(){let{x:w,y:A}=this.toAffine(),v=xt(A,t.BYTES);return v[v.length-1]|=w&He?128:0,v}toHex(){return wt(this.toRawBytes())}}p.BASE=new p(e.Gx,e.Gy,He,u(e.Gx*e.Gy)),p.ZERO=new p(Qe,He,He,Qe);let{BASE:S,ZERO:N}=p,L=co(p,a*8);function B(E){return Z(E,n)}function T(E){return B(Je(E))}function C(E){let w=t.BYTES;E=ie("private key",E,w);let A=ie("hashed private key",s(E),2*w),v=m(A.slice(0,w)),_=A.slice(w,2*w),R=T(v),O=S.multiply(R),K=O.toRawBytes();return{head:v,prefix:_,scalar:R,point:O,pointBytes:K}}function H(E){return C(E).pointBytes}function U(E=new Uint8Array,...w){let A=Et(...w);return T(s(y(A,ie("context",E),!!o)))}function M(E,w,A={}){E=ie("message",E),o&&(E=o(E));let{prefix:v,scalar:_,pointBytes:R}=C(w),O=U(A.context,v,E),K=S.multiply(O).toRawBytes(),F=U(A.context,K,R,E),G=B(O+F*_);ve("signature.s",G,Qe,n);let j=Et(K,xt(G,t.BYTES));return ie("result",j,t.BYTES*2)}let V=Pp;function I(E,w,A,v=V){let{context:_,zip215:R}=v,O=t.BYTES;E=ie("signature",E,2*O),w=ie("message",w),A=ie("publicKey",A,O),R!==void 0&&Ye("zip215",R),o&&(w=o(w));let K=Je(E.slice(O,2*O)),F,G,j;try{F=p.fromHex(A,R),G=p.fromHex(E.slice(0,O),R),j=S.multiplyUnsafe(K)}catch{return!1}if(!R&&F.isSmallOrder())return!1;let ae=U(_,G.toRawBytes(),F.toRawBytes(),w);return G.add(F.multiplyUnsafe(ae)).subtract(j).clearCofactor().equals(p.ZERO)}return S._setWindowSize(8),{CURVE:e,getPublicKey:H,sign:M,verify:I,ExtendedPoint:p,utils:{getExtendedPublicKey:C,randomPrivateKey:()=>i(t.BYTES),precompute(E=8,w=p.BASE){return w._setWindowSize(E),w.multiply(BigInt(3)),w}}}}var kr=BigInt(0),Vi=BigInt(1);function Mp(r){return qe(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function kl(r){let e=Mp(r),{P:t}=e,n=x=>Z(x,t),o=e.montgomeryBits,s=Math.ceil(o/8),i=e.nByteLength,a=e.adjustScalarBytes||(x=>x),c=e.powPminus2||(x=>Ri(x,t-BigInt(2),t));function l(x,p,S){let N=n(x*(p-S));return p=n(p-N),S=n(S+N),[p,S]}let u=(e.a-BigInt(2))/BigInt(4);function f(x,p){ve("u",x,kr,t),ve("scalar",p,kr,t);let S=p,N=x,L=Vi,B=kr,T=x,C=Vi,H=kr,U;for(let V=BigInt(o-1);V>=kr;V--){let I=S>>V&Vi;H^=I,U=l(H,L,T),L=U[0],T=U[1],U=l(H,B,C),B=U[0],C=U[1],H=I;let k=L+B,E=n(k*k),w=L-B,A=n(w*w),v=E-A,_=T+C,R=T-C,O=n(R*k),K=n(_*w),F=O+K,G=O-K;T=n(F*F),C=n(N*n(G*G)),L=n(E*A),B=n(v*(E+n(u*v)))}U=l(H,L,T),L=U[0],T=U[1],U=l(H,B,C),B=U[0],C=U[1];let M=c(B);return n(L*M)}function d(x){return xt(n(x),s)}function m(x){let p=ie("u coordinate",x,s);return i===32&&(p[31]&=127),Je(p)}function y(x){let p=ie("scalar",x),S=p.length;if(S!==s&&S!==i){let N=""+s+" or "+i;throw new Error("invalid scalar, expected "+N+" bytes, got "+S)}return Je(a(p))}function g(x,p){let S=m(p),N=y(x),L=f(S,N);if(L===kr)throw new Error("invalid private or public key received");return d(L)}let h=d(e.Gu);function b(x){return g(x,h)}return{scalarMult:g,scalarMultBase:b,getSharedSecret:(x,p)=>g(x,p),getPublicKey:x=>b(x),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:h}}var sn=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Tl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),ow=BigInt(0),Hp=BigInt(1),Ll=BigInt(2),Fp=BigInt(3),Vp=BigInt(5),Kp=BigInt(8);function Nl(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=sn,a=r*r%s*r%s,c=le(a,Ll,s)*a%s,l=le(c,Hp,s)*r%s,u=le(l,Vp,s)*l%s,f=le(u,e,s)*u%s,d=le(f,t,s)*f%s,m=le(d,n,s)*d%s,y=le(m,o,s)*m%s,g=le(y,o,s)*m%s,h=le(g,e,s)*u%s;return{pow_p_5_8:le(h,Ll,s)*r%s,b2:a}}function _l(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function $p(r,e){let t=sn,n=Z(e*e*e,t),o=Z(n*n*e,t),s=Nl(r*o).pow_p_5_8,i=Z(r*n*s,t),a=Z(e*i*i,t),c=i,l=Z(i*Tl,t),u=a===r,f=a===Z(-r,t),d=a===Z(-r*Tl,t);return u&&(i=c),(f||d)&&(i=l),El(i,t)&&(i=Z(-i,t)),{isValid:u||f,value:i}}var Gp=Vt(sn,void 0,!0),Wp={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Gp,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Kp,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:gl,randomBytes:tn,adjustScalarBytes:_l,uvRatio:$p},Rl=Cl(Wp);var an=kl({P:sn,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let e=sn,{pow_p_5_8:t,b2:n}=Nl(r);return Z(le(t,Fp,e)*n,e)},adjustScalarBytes:_l,randomBytes:tn});var fo=32;function Ul(r,e,t){return Rl.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}var ho=class{type="Ed25519";raw;constructor(e){this.raw=Ki(e,fo)}toMultihash(){return gt.digest(Tr(this))}toCID(){return Ee.createV1(114,this.toMultihash())}toString(){return se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:De(this.raw,e.raw)}verify(e,t){return Ul(this.raw,t,e)}};function $i(r){return r=Ki(r,fo),new ho(r)}function Ki(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new oe(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}function ye(r=0){return new Uint8Array(r)}function me(r=0){return new Uint8Array(r)}var zp=Math.pow(2,7),jp=Math.pow(2,14),Zp=Math.pow(2,21),Gi=Math.pow(2,28),Wi=Math.pow(2,35),qi=Math.pow(2,42),zi=Math.pow(2,49),J=128,Te=127;function te(r){if(r<zp)return 1;if(r<jp)return 2;if(r<Zp)return 3;if(r<Gi)return 4;if(r<Wi)return 5;if(r<qi)return 6;if(r<zi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ji(r,e,t=0){switch(te(r)){case 8:e[t++]=r&255|J,r/=128;case 7:e[t++]=r&255|J,r/=128;case 6:e[t++]=r&255|J,r/=128;case 5:e[t++]=r&255|J,r/=128;case 4:e[t++]=r&255|J,r>>>=7;case 3:e[t++]=r&255|J,r>>>=7;case 2:e[t++]=r&255|J,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Xp(r,e,t=0){switch(te(r)){case 8:e.set(t++,r&255|J),r/=128;case 7:e.set(t++,r&255|J),r/=128;case 6:e.set(t++,r&255|J),r/=128;case 5:e.set(t++,r&255|J),r/=128;case 4:e.set(t++,r&255|J),r>>>=7;case 3:e.set(t++,r&255|J),r>>>=7;case 2:e.set(t++,r&255|J),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Zi(r,e){let t=r[e],n=0;if(n+=t&Te,t<J||(t=r[e+1],n+=(t&Te)<<7,t<J)||(t=r[e+2],n+=(t&Te)<<14,t<J)||(t=r[e+3],n+=(t&Te)<<21,t<J)||(t=r[e+4],n+=(t&Te)*Gi,t<J)||(t=r[e+5],n+=(t&Te)*Wi,t<J)||(t=r[e+6],n+=(t&Te)*qi,t<J)||(t=r[e+7],n+=(t&Te)*zi,t<J))return n;throw new RangeError("Could not decode varint")}function Yp(r,e){let t=r.get(e),n=0;if(n+=t&Te,t<J||(t=r.get(e+1),n+=(t&Te)<<7,t<J)||(t=r.get(e+2),n+=(t&Te)<<14,t<J)||(t=r.get(e+3),n+=(t&Te)<<21,t<J)||(t=r.get(e+4),n+=(t&Te)*Gi,t<J)||(t=r.get(e+5),n+=(t&Te)*Wi,t<J)||(t=r.get(e+6),n+=(t&Te)*qi,t<J)||(t=r.get(e+7),n+=(t&Te)*zi,t<J))return n;throw new RangeError("Could not decode varint")}function ze(r,e,t=0){return e==null&&(e=me(te(r))),e instanceof Uint8Array?ji(r,e,t):Xp(r,e,t)}function Ke(r,e=0){return r instanceof Uint8Array?Zi(r,e):Yp(r,e)}var Xi=new Float32Array([-0]),Kt=new Uint8Array(Xi.buffer);function Pl(r,e,t){Xi[0]=r,e[t]=Kt[0],e[t+1]=Kt[1],e[t+2]=Kt[2],e[t+3]=Kt[3]}function Ol(r,e){return Kt[0]=r[e],Kt[1]=r[e+1],Kt[2]=r[e+2],Kt[3]=r[e+3],Xi[0]}var Yi=new Float64Array([-0]),Le=new Uint8Array(Yi.buffer);function Ml(r,e,t){Yi[0]=r,e[t]=Le[0],e[t+1]=Le[1],e[t+2]=Le[2],e[t+3]=Le[3],e[t+4]=Le[4],e[t+5]=Le[5],e[t+6]=Le[6],e[t+7]=Le[7]}function Hl(r,e){return Le[0]=r[e],Le[1]=r[e+1],Le[2]=r[e+2],Le[3]=r[e+3],Le[4]=r[e+4],Le[5]=r[e+5],Le[6]=r[e+6],Le[7]=r[e+7],Yi[0]}var Jp=BigInt(Number.MAX_SAFE_INTEGER),Qp=BigInt(Number.MIN_SAFE_INTEGER),$e=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+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 t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(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,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return ir;if(e<Jp&&e>Qp)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Fl&&(o=0n,++n>Fl&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return ir;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):ir}},ir=new $e(0,0);ir.toBigInt=function(){return 0n};ir.zzEncode=ir.zzDecode=function(){return this};ir.length=function(){return 1};var Fl=4294967296n;function Vl(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Kl(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Ji(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function et(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function po(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Qi=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,et(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw et(this,4);return po(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw et(this,4);return po(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw et(this,4);let e=Ol(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw et(this,4);let e=Hl(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw et(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Kl(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw et(this,e);this.pos+=e}else do if(this.pos>=this.len)throw et(this);while(this.buf[this.pos++]&128);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new $e(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*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;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw et(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw et(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw et(this,8);let e=po(this.buf,this.pos+=4),t=po(this.buf,this.pos+=4);return new $e(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Zi(this.buf,this.pos);return this.pos+=te(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 ea(r){return new Qi(r instanceof Uint8Array?r:r.subarray())}function tt(r,e,t){let n=ea(r);return e.decode(n,void 0,t)}var ta={};Ce(ta,{base10:()=>e0});var e0=Ut({prefix:"9",name:"base10",alphabet:"0123456789"});var ra={};Ce(ra,{base16:()=>t0,base16upper:()=>r0});var t0=de({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),r0=de({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var na={};Ce(na,{base2:()=>n0});var n0=de({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var oa={};Ce(oa,{base256emoji:()=>c0});var Gl=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}"),o0=Gl.reduce((r,e,t)=>(r[t]=e,r),[]),s0=Gl.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function i0(r){return r.reduce((e,t)=>(e+=o0[t],e),"")}function a0(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=s0[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var c0=xr({prefix:"\u{1F680}",name:"base256emoji",encode:i0,decode:a0});var sa={};Ce(sa,{base64:()=>l0,base64pad:()=>u0,base64url:()=>cn,base64urlpad:()=>f0});var l0=de({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),u0=de({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cn=de({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),f0=de({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ia={};Ce(ia,{base8:()=>h0});var h0=de({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var aa={};Ce(aa,{identity:()=>d0});var d0=xr({prefix:"\0",name:"identity",encode:r=>Qc(r),decode:r=>Jc(r)});var Fw=new TextEncoder,Vw=new TextDecoder;var ua={};Ce(ua,{sha256:()=>vt,sha512:()=>g0});function la({name:r,code:e,encode:t}){return new ca(r,e,t)}var ca=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?ke(this.code,t):t.then(n=>ke(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ql(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var vt=la({name:"sha2-256",code:18,encode:ql("SHA-256")}),g0=la({name:"sha2-512",code:19,encode:ql("SHA-512")});var ar={...aa,...na,...ia,...ta,...ra,...wi,...bi,...yi,...sa,...oa},Qw={...ua,...Ai};function jl(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var zl=jl("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),fa=jl("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=me(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),y0={utf8:zl,"utf-8":zl,hex:ar.base16,latin1:fa,ascii:fa,binary:fa,...ar},mo=y0;function Q(r,e="utf8"){let t=mo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function ha(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return me(i);o+i>e&&(n=me(e),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var cr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function da(){}var ma=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},w0=ha();function b0(r){return globalThis.Buffer!=null?me(r):w0(r)}var un=class{len;head;tail;states;constructor(){this.len=0,this.head=new cr(da,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new cr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new ga((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(go,10,$e.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=$e.fromBigInt(e);return this._push(go,t.length(),t)}uint64Number(e){return this._push(ji,te(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 t=$e.fromBigInt(e).zzEncode();return this._push(go,t.length(),t)}sint64Number(e){let t=$e.fromNumber(e).zzEncode();return this._push(go,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(pa,1,e?1:0)}fixed32(e){return this._push(ln,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=$e.fromBigInt(e);return this._push(ln,4,t.lo)._push(ln,4,t.hi)}fixed64Number(e){let t=$e.fromNumber(e);return this._push(ln,4,t.lo)._push(ln,4,t.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(Pl,4,e)}double(e){return this._push(Ml,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(pa,1,0):this.uint32(t)._push(E0,t,e)}string(e){let t=Vl(e);return t!==0?this.uint32(t)._push(Ji,t,e):this._push(pa,1,0)}fork(){return this.states=new ma(this),this.head=this.tail=new cr(da,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 cr(da,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=b0(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function pa(r,e,t){e[t]=r&255}function x0(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var ga=class extends cr{next;constructor(e,t){super(x0,e,t),this.next=void 0}};function go(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function ln(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function E0(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(un.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(v0,e,r),this},un.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(A0,e,r),this});function v0(r,e,t){e.set(r,t)}function A0(r,e,t){r.length<40?Ji(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Q(r),t)}function ya(){return new un}function rt(r,e){let t=ya();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Lr;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Lr||(Lr={}));function yo(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function lr(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return yo("enum",Lr.VARINT,t,n)}function nt(r,e){return yo("message",Lr.LENGTH_DELIMITED,r,e)}var we;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(we||(we={}));var wa;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(wa||(wa={}));(function(r){r.codec=()=>lr(wa)})(we||(we={}));var at;(function(r){let e;r.codec=()=>(e==null&&(e=nt((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),we.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=we.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>rt(t,r.codec()),r.decode=(t,n)=>tt(t,r.codec(),n)})(at||(at={}));var ba;(function(r){let e;r.codec=()=>(e==null&&(e=nt((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),we.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=we.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>rt(t,r.codec()),r.decode=(t,n)=>tt(t,r.codec(),n)})(ba||(ba={}));var xn={};Ce(xn,{MAX_RSA_KEY_SIZE:()=>cs,generateRSAKeyPair:()=>Wu,jwkToJWKKeyPair:()=>qu,jwkToPkcs1:()=>H0,jwkToPkix:()=>ka,jwkToRSAPrivateKey:()=>Gu,pkcs1ToJwk:()=>Vu,pkcs1ToRSAPrivateKey:()=>$u,pkixToJwk:()=>Ku,pkixToRSAPublicKey:()=>Ta});var B0=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),$t=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Gt=new Uint32Array(64),xa=class extends Ir{constructor(){super(64,32,8,!1),this.A=$t[0]|0,this.B=$t[1]|0,this.C=$t[2]|0,this.D=$t[3]|0,this.E=$t[4]|0,this.F=$t[5]|0,this.G=$t[6]|0,this.H=$t[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|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,t){for(let f=0;f<16;f++,t+=4)Gt[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=Gt[f-15],m=Gt[f-2],y=Xe(d,7)^Xe(d,18)^d>>>3,g=Xe(m,17)^Xe(m,19)^m>>>10;Gt[f]=g+Gt[f-7]+y+Gt[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=Xe(a,6)^Xe(a,11)^Xe(a,25),m=u+d+dl(a,c,l)+B0[f]+Gt[f]|0,g=(Xe(n,2)^Xe(n,13)^Xe(n,22))+pl(n,o,s)|0;u=l,l=c,c=a,a=i+m|0,i=s,s=o,o=n,n=m+g|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,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){Gt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ct=to(()=>new xa);var q=td(Xl());function ur(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function Wt(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let f=Math.pow(2,u*e);l[s-u-1]=Math.floor(o/f),o-=l[s-u-1]*f}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function xo(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function va(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=ur(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,ur(s,8)-n}function Yl(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=Wt(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Wt(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function Jl(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function Fe(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var Ub=Math.log(2);function Eo(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Aa(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function Ct(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var hn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Aa(this.items)}},fn=[new Uint8Array([1])],Ql="0123456789";var Dr="",ot=new ArrayBuffer(0),Ba=new Uint8Array(0),dn="EndOfContent",tu="OCTET STRING",ru="BIT STRING";function kt(r){var e;return e=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?q.BufferSourceConverter.toUint8Array(s.valueHex):Ba}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Ct(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",ot)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:q.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Bt=class{constructor({blockLength:e=0,error:t=Dr,warnings:n=[],valueBeforeDecode:o=Ba}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=q.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:q.Convert.ToHex(this.valueBeforeDecodeView)}}};Bt.NAME="baseBlock";var Ne=class extends Bt{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Ne.NAME="valueBlock";var vo=class extends kt(Bt){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?q.BufferSourceConverter.toUint8Array(e.valueHex):Ba,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",ot}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=Wt(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Ct(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,l=this.valueHexView=new Uint8Array(255),u=255;for(;s[c]&128;){if(l[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===u){u+=255;let d=new Uint8Array(u);for(let m=0;m<l.length;m++)d[m]=l[m];l=this.valueHexView=new Uint8Array(u)}}this.blockLength=c+1,l[c-1]=s[c]&127;let f=new Uint8Array(c);for(let d=0;d<c;d++)f[d]=l[d];l=this.valueHexView=new Uint8Array(c),l.set(f),this.blockLength<=9?this.tagNumber=ur(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};vo.NAME="identificationBlock";var Ao=class extends Bt{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Ct(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=ur(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=Wt(this.length,8);if(o.byteLength>127)return this.error="Too big length",ot;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Ao.NAME="lengthBlock";var D={},Ae=class extends Bt{constructor({name:e=Dr,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new vo(o),this.lenBlock=new Ao(o),this.valueBlock=s?new s(o):new Ne(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new hn;t||nu(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?ot:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():q.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return Jl(t,n)}};Ae.NAME="BaseBlock";function nu(r){if(r instanceof D.Constructed)for(let e of r.valueBlock.value)nu(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var Bo=class extends Ae{constructor({value:e=Dr,...t}={},n){super(t,n),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};Bo.NAME="BaseStringBlock";var So=class extends kt(Ne){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};So.NAME="PrimitiveValueBlock";var ou,Io=class extends Ae{constructor(e={}){super(e,So),this.idBlock.isConstructed=!1}};ou=Io;D.Primitive=ou;Io.NAME="PRIMITIVE";function R0(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function is(r,e=0,t=r.length){let n=e,o=new Ae({},Ne),s=new Bt;if(!Ct(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Ae;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=D.EndOfContent;break;case 1:c=D.Boolean;break;case 2:c=D.Integer;break;case 3:c=D.BitString;break;case 4:c=D.OctetString;break;case 5:c=D.Null;break;case 6:c=D.ObjectIdentifier;break;case 10:c=D.Enumerated;break;case 12:c=D.Utf8String;break;case 13:c=D.RelativeObjectIdentifier;break;case 14:c=D.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=D.Sequence;break;case 17:c=D.Set;break;case 18:c=D.NumericString;break;case 19:c=D.PrintableString;break;case 20:c=D.TeletexString;break;case 21:c=D.VideotexString;break;case 22:c=D.IA5String;break;case 23:c=D.UTCTime;break;case 24:c=D.GeneralizedTime;break;case 25:c=D.GraphicString;break;case 26:c=D.VisibleString;break;case 27:c=D.GeneralString;break;case 28:c=D.UniversalString;break;case 29:c=D.CharacterString;break;case 30:c=D.BmpString;break;case 31:c=D.DATE;break;case 32:c=D.TimeOfDay;break;case 33:c=D.DateTime;break;case 34:c=D.Duration;break;default:{let l=o.idBlock.isConstructed?new D.Constructed:new D.Primitive;l.idBlock=o.idBlock,l.lenBlock=o.lenBlock,l.warnings=o.warnings,o=l}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?D.Constructed:D.Primitive}return o=R0(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function Sa(r){if(!r.byteLength){let e=new Ae({},Ne);return e.error="Input buffer has zero length",{offset:-1,result:e}}return is(q.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function U0(r,e){return r?1:e}var lt=class extends Ne{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Ct(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;U0(this.isIndefiniteForm,n)>0;){let i=is(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===dn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===dn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new hn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?ot:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};lt.NAME="ConstructedValueBlock";var su,qt=class extends Ae{constructor(e={}){super(e,lt),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
2
|
+
"use strict";var Libp2PWebrtc=(()=>{var Xh=Object.create;var Gn=Object.defineProperty;var Yh=Object.getOwnPropertyDescriptor;var Jh=Object.getOwnPropertyNames;var Qh=Object.getPrototypeOf,ed=Object.prototype.hasOwnProperty;var td=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ce=(r,e)=>{for(var t in e)Gn(r,t,{get:e[t],enumerable:!0})},jc=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Jh(e))!ed.call(r,o)&&o!==t&&Gn(r,o,{get:()=>e[o],enumerable:!(n=Yh(e,o))||n.enumerable});return r};var rd=(r,e,t)=>(t=r!=null?Xh(Qh(r)):{},jc(e||!r||!r.__esModule?Gn(t,"default",{value:r,enumerable:!0}):t,r)),nd=r=>jc(Gn({},"__esModule",{value:!0}),r);var Xl=td(Nr=>{"use strict";var I0="[object ArrayBuffer]",At=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===I0}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let i of t)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of t){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}},Ea="string",C0=/^[0-9a-f\s]+$/i,k0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,T0=/^[a-zA-Z0-9-_]+$/,wo=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n.buffer}static toString(e){let t=At.toUint8Array(e),n="";for(let s=0;s<t.length;s++)n+=String.fromCharCode(t[s]);return decodeURIComponent(escape(n))}},je=class{static toString(e,t=!1){let n=At.toArrayBuffer(e),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,t);s+=String.fromCharCode(a)}return s}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let s=0;s<e.length;s++)o.setUint16(s*2,e.charCodeAt(s),t);return n}},bo=class r{static isHex(e){return typeof e===Ea&&C0.test(e)}static isBase64(e){return typeof e===Ea&&k0.test(e)}static isBase64Url(e){return typeof e===Ea&&T0.test(e)}static ToString(e,t="utf8"){let n=At.toUint8Array(e);switch(t.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return je.toString(n,!0);case"utf16":case"utf16be":return je.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return je.fromString(e,!0);case"utf16":case"utf16be":return je.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=At.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return wo.fromString(e);case"utf16":case"utf16be":return je.fromString(e);case"utf16le":case"usc2":return je.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return wo.toString(e);case"utf16":case"utf16be":return je.toString(e);case"utf16le":case"usc2":return je.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){let t=At.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return n}static ToHex(e){let t=At.toUint8Array(e),n="",o=t.length;for(let s=0;s<o;s++){let i=t[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let o=0;o<t.length;o=o+2){let s=t.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(e,t=!1){return je.toString(e,t)}static FromUtf16String(e,t=!1){return je.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};bo.DEFAULT_UTF8_ENCODING="utf8";function L0(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)t[s]=o[s]}return t}function N0(...r){let e=r.map(o=>o.byteLength).reduce((o,s)=>o+s),t=new Uint8Array(e),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)t[n++]=s}),t.buffer}function _0(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<r.byteLength;o++)if(t[o]!==n[o])return!1;return!0}Nr.BufferSourceConverter=At;Nr.Convert=bo;Nr.assign=L0;Nr.combine=N0;Nr.isEqual=_0});var Ug={};Ce(Ug,{webRTC:()=>Rg,webRTCDirect:()=>_g});var hi=Symbol.for("@libp2p/peer-id");var Wn=Symbol.for("@libp2p/transport");var Zc;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Zc||(Zc={}));var qn=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}};var oe=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},yr=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var zn=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}};var jn=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}},Yt=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}};var Zn=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var Xn=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var Yn=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}};var Jt=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var wr=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var br=Symbol.for("@libp2p/service-capabilities"),Xc=Symbol.for("@libp2p/service-dependencies");var yi={};Ce(yi,{base58btc:()=>se,base58flickr:()=>ld});var cy=new Uint8Array(0);function Yc(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function pt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Jc(r){return new TextEncoder().encode(r)}function Qc(r){return new TextDecoder().decode(r)}function od(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var g=0,h=0,b=0,x=y.length;b!==x&&y[b]===0;)b++,g++;for(var p=(x-b)*u+1>>>0,S=new Uint8Array(p);b!==x;){for(var N=y[b],L=0,B=p-1;(N!==0||L<h)&&B!==-1;B--,L++)N+=256*S[B]>>>0,S[B]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");h=L,b++}for(var T=p-h;T!==p&&S[T]===0;)T++;for(var C=c.repeat(g);T<p;++T)C+=r.charAt(S[T]);return C}function d(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var g=0;if(y[g]!==" "){for(var h=0,b=0;y[g]===c;)h++,g++;for(var x=(y.length-g)*l+1>>>0,p=new Uint8Array(x);y[g];){var S=t[y.charCodeAt(g)];if(S===255)return;for(var N=0,L=x-1;(S!==0||N<b)&&L!==-1;L--,N++)S+=a*p[L]>>>0,p[L]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");b=N,g++}if(y[g]!==" "){for(var B=x-b;B!==x&&p[B]===0;)B++;for(var T=new Uint8Array(h+(x-B)),C=h;B!==x;)T[C++]=p[B++];return T}}}function m(y){var g=d(y);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:m}}var sd=od,id=sd,tl=id;var di=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},pi=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.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 rl(this,e)}},mi=class{decoders;constructor(e){this.decoders=e}or(e){return rl(this,e)}decode(e){let t=e[0],n=this.decoders[t];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 rl(r,e){return new mi({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var gi=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new di(e,t,n),this.decoder=new pi(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function xr({name:r,prefix:e,encode:t,decode:n}){return new gi(r,e,t,n)}function Ut({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=tl(t,r);return xr({prefix:e,name:r,encode:n,decode:s=>pt(o(s))})}function ad(r,e,t,n){let o={};for(let u=0;u<e.length;++u)o[e[u]]=u;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),a=0,c=0,l=0;for(let u=0;u<s;++u){let f=o[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|f,a+=t,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=t||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return i}function cd(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function de({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return xr({prefix:e,name:r,encode(o){return cd(o,n,t)},decode(o){return ad(o,n,t,r)}})}var se=Ut({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ld=Ut({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var wi={};Ce(wi,{base32:()=>mt,base32hex:()=>dd,base32hexpad:()=>md,base32hexpadupper:()=>gd,base32hexupper:()=>pd,base32pad:()=>fd,base32padupper:()=>hd,base32upper:()=>ud,base32z:()=>yd});var mt=de({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ud=de({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),fd=de({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),hd=de({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),dd=de({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),pd=de({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),md=de({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),gd=de({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),yd=de({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var bi={};Ce(bi,{base36:()=>Xr,base36upper:()=>wd});var Xr=Ut({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),wd=Ut({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var We={};Ce(We,{Digest:()=>Qt,create:()=>ke,decode:()=>Dt,equals:()=>Ei,hasCode:()=>Od});var bd=sl,nl=128,xd=127,Ed=~xd,vd=Math.pow(2,31);function sl(r,e,t){e=e||[],t=t||0;for(var n=t;r>=vd;)e[t++]=r&255|nl,r/=128;for(;r&Ed;)e[t++]=r&255|nl,r>>>=7;return e[t]=r|0,sl.bytes=t-n+1,e}var Ad=xi,Bd=128,ol=127;function xi(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw xi.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&ol)<<o:(i&ol)*Math.pow(2,o),o+=7}while(i>=Bd);return xi.bytes=s-n,t}var Sd=Math.pow(2,7),Id=Math.pow(2,14),Cd=Math.pow(2,21),kd=Math.pow(2,28),Td=Math.pow(2,35),Ld=Math.pow(2,42),Nd=Math.pow(2,49),_d=Math.pow(2,56),Rd=Math.pow(2,63),Ud=function(r){return r<Sd?1:r<Id?2:r<Cd?3:r<kd?4:r<Td?5:r<Ld?6:r<Nd?7:r<_d?8:r<Rd?9:10},Dd={encode:bd,decode:Ad,encodingLength:Ud},Pd=Dd,Yr=Pd;function Jr(r,e=0){return[Yr.decode(r,e),Yr.decode.bytes]}function Er(r,e,t=0){return Yr.encode(r,e,t),e}function vr(r){return Yr.encodingLength(r)}function ke(r,e){let t=e.byteLength,n=vr(r),o=n+vr(t),s=new Uint8Array(o+t);return Er(r,s,0),Er(t,s,n),s.set(e,o),new Qt(r,t,e,s)}function Dt(r){let e=pt(r),[t,n]=Jr(e),[o,s]=Jr(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Qt(t,o,i,e)}function Ei(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Yc(r.bytes,t.bytes)}}var Qt=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function Od(r,e){return r.code===e}function il(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return Hd(t,vi(r),e??se.encoder);default:return Fd(t,vi(r),e??mt.encoder)}}var al=new WeakMap;function vi(r){let e=al.get(r);if(e==null){let t=new Map;return al.set(r,t),t}return e}var Ee=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,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:t}=this;if(e!==Qr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Vd)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}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:t}=this.multihash,n=ke(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&Ei(e.multihash,n.multihash)}toString(e){return il(this,e)}toJSON(){return{"/":il(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 t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??cl(n,o,s.bytes))}else if(t[Kd]===!0){let{version:n,multihash:o,code:s}=t,i=Dt(o);return r.create(n,s,i)}else return null}static create(e,t,n){if(typeof t!="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(t!==Qr)throw new Error(`Version 0 CID must use dag-pb (code: ${Qr}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=cl(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Qr,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,o=pt(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Qt(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=Jr(e.subarray(t));return t+=d,f},o=n(),s=Qr;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=Md(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return vi(s).set(n,e),s}};function Md(r,e){switch(r[0]){case"Q":{let t=e??se;return[se.prefix,t.decode(`${se.prefix}${r}`)]}case se.prefix:{let t=e??se;return[se.prefix,t.decode(r)]}case mt.prefix:{let t=e??mt;return[mt.prefix,t.decode(r)]}case Xr.prefix:{let t=e??Xr;return[Xr.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Hd(r,e,t){let{prefix:n}=t;if(n!==se.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Fd(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var Qr=112,Vd=18;function cl(r,e,t){let n=vr(r),o=n+vr(e),s=new Uint8Array(o+t.byteLength);return Er(r,s,0),Er(e,s,n),s.set(t,o),s}var Kd=Symbol.for("@ipld/js-cid/CID");var Ai={};Ce(Ai,{identity:()=>gt});var ll=0,$d="identity",ul=pt;function Gd(r){return ke(ll,ul(r))}var gt={code:ll,name:$d,encode:ul,digest:Gd};function De(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Qn(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Wd(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ar(r,...e){if(!Wd(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function en(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Qn(r.outputLen),Qn(r.blockLen)}function Br(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function fl(r,e){Ar(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}var er=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function eo(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Xe(r,e){return r<<32-e|r>>>e}function hl(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function Pt(r){return typeof r=="string"&&(r=hl(r)),Ar(r),r}function Bi(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Ar(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}var Sr=class{clone(){return this._cloneInto()}};function to(r){let e=n=>r().update(Pt(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function tn(r=32){if(er&&typeof er.getRandomValues=="function")return er.getRandomValues(new Uint8Array(r));if(er&&typeof er.randomBytes=="function")return er.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function qd(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,l=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+l,a,n)}function dl(r,e,t){return r&e^~r&t}function pl(r,e,t){return r&e^r&t^e&t}var Ir=class extends Sr{constructor(e,t,n,o){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=eo(this.buffer)}update(e){Br(this);let{view:t,buffer:n,blockLen:o}=this;e=Pt(e);let s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=eo(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(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Br(this),fl(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)t[f]=0;qd(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=eo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.length=o,e.pos=a,e.finished=s,e.destroyed=i,o%t&&e.buffer.set(n),e}};var ro=BigInt(4294967295),Si=BigInt(32);function ml(r,e=!1){return e?{h:Number(r&ro),l:Number(r>>Si&ro)}:{h:Number(r>>Si&ro)|0,l:Number(r&ro)|0}}function zd(r,e=!1){let t=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=ml(r[o],e);[t[o],n[o]]=[s,i]}return[t,n]}var jd=(r,e)=>BigInt(r>>>0)<<Si|BigInt(e>>>0),Zd=(r,e,t)=>r>>>t,Xd=(r,e,t)=>r<<32-t|e>>>t,Yd=(r,e,t)=>r>>>t|e<<32-t,Jd=(r,e,t)=>r<<32-t|e>>>t,Qd=(r,e,t)=>r<<64-t|e>>>t-32,ep=(r,e,t)=>r>>>t-32|e<<64-t,tp=(r,e)=>e,rp=(r,e)=>r,np=(r,e,t)=>r<<t|e>>>32-t,op=(r,e,t)=>e<<t|r>>>32-t,sp=(r,e,t)=>e<<t-32|r>>>64-t,ip=(r,e,t)=>r<<t-32|e>>>64-t;function ap(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var cp=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),lp=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,up=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),fp=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,hp=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),dp=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var pp={fromBig:ml,split:zd,toBig:jd,shrSH:Zd,shrSL:Xd,rotrSH:Yd,rotrSL:Jd,rotrBH:Qd,rotrBL:ep,rotr32H:tp,rotr32L:rp,rotlSH:np,rotlSL:op,rotlBH:sp,rotlBL:ip,add:ap,add3L:cp,add3H:lp,add4L:up,add4H:fp,add5H:dp,add5L:hp},$=pp;var[mp,gp]=$.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Ot=new Uint32Array(80),Mt=new Uint32Array(80),Ii=class extends Ir{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:m,Gl:y,Hh:g,Hl:h}=this;return[e,t,n,o,s,i,a,c,l,u,f,d,m,y,g,h]}set(e,t,n,o,s,i,a,c,l,u,f,d,m,y,g,h){this.Ah=e|0,this.Al=t|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=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=m|0,this.Gl=y|0,this.Hh=g|0,this.Hl=h|0}process(e,t){for(let p=0;p<16;p++,t+=4)Ot[p]=e.getUint32(t),Mt[p]=e.getUint32(t+=4);for(let p=16;p<80;p++){let S=Ot[p-15]|0,N=Mt[p-15]|0,L=$.rotrSH(S,N,1)^$.rotrSH(S,N,8)^$.shrSH(S,N,7),B=$.rotrSL(S,N,1)^$.rotrSL(S,N,8)^$.shrSL(S,N,7),T=Ot[p-2]|0,C=Mt[p-2]|0,H=$.rotrSH(T,C,19)^$.rotrBH(T,C,61)^$.shrSH(T,C,6),U=$.rotrSL(T,C,19)^$.rotrBL(T,C,61)^$.shrSL(T,C,6),M=$.add4L(B,U,Mt[p-7],Mt[p-16]),V=$.add4H(M,L,H,Ot[p-7],Ot[p-16]);Ot[p]=V|0,Mt[p]=M|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:m,Fl:y,Gh:g,Gl:h,Hh:b,Hl:x}=this;for(let p=0;p<80;p++){let S=$.rotrSH(f,d,14)^$.rotrSH(f,d,18)^$.rotrBH(f,d,41),N=$.rotrSL(f,d,14)^$.rotrSL(f,d,18)^$.rotrBL(f,d,41),L=f&m^~f&g,B=d&y^~d&h,T=$.add5L(x,N,B,gp[p],Mt[p]),C=$.add5H(T,b,S,L,mp[p],Ot[p]),H=T|0,U=$.rotrSH(n,o,28)^$.rotrBH(n,o,34)^$.rotrBH(n,o,39),M=$.rotrSL(n,o,28)^$.rotrBL(n,o,34)^$.rotrBL(n,o,39),V=n&s^n&a^s&a,I=o&i^o&c^i&c;b=g|0,x=h|0,g=m|0,h=y|0,m=f|0,y=d|0,{h:f,l:d}=$.add(l|0,u|0,C|0,H|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let k=$.add3L(H,M,I);n=$.add3H(k,C,U,V),o=k|0}({h:n,l:o}=$.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=$.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=$.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=$.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=$.add(this.Eh|0,this.El|0,f|0,d|0),{h:m,l:y}=$.add(this.Fh|0,this.Fl|0,m|0,y|0),{h:g,l:h}=$.add(this.Gh|0,this.Gl|0,g|0,h|0),{h:b,l:x}=$.add(this.Hh|0,this.Hl|0,b|0,x|0),this.set(n,o,s,i,a,c,l,u,f,d,m,y,g,h,b,x)}roundClean(){Ot.fill(0),Mt.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var gl=to(()=>new Ii);var so={};Ce(so,{aInRange:()=>ve,abool:()=>Ye,abytes:()=>Cr,bitGet:()=>vp,bitLen:()=>Li,bitMask:()=>nn,bitSet:()=>Ap,bytesToHex:()=>wt,bytesToNumberBE:()=>bt,bytesToNumberLE:()=>Je,concatBytes:()=>Et,createHmacDrbg:()=>Ni,ensureBytes:()=>ie,equalBytes:()=>xp,hexToBytes:()=>rr,hexToNumber:()=>Ti,inRange:()=>rn,isBytes:()=>Ht,memoized:()=>nr,notImplemented:()=>Sp,numberToBytesBE:()=>Ft,numberToBytesLE:()=>xt,numberToHexUnpadded:()=>tr,numberToVarBytesBE:()=>bp,utf8ToBytes:()=>Ep,validateObject:()=>qe});var no=BigInt(0),oo=BigInt(1),yp=BigInt(2);function Ht(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Cr(r){if(!Ht(r))throw new Error("Uint8Array expected")}function Ye(r,e){if(typeof e!="boolean")throw new Error(r+" boolean expected, got "+e)}var wp=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function wt(r){Cr(r);let e="";for(let t=0;t<r.length;t++)e+=wp[r[t]];return e}function tr(r){let e=r.toString(16);return e.length&1?"0"+e:e}function Ti(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?no:BigInt("0x"+r)}var yt={_0:48,_9:57,A:65,F:70,a:97,f:102};function yl(r){if(r>=yt._0&&r<=yt._9)return r-yt._0;if(r>=yt.A&&r<=yt.F)return r-(yt.A-10);if(r>=yt.a&&r<=yt.f)return r-(yt.a-10)}function rr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let i=yl(r.charCodeAt(s)),a=yl(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function bt(r){return Ti(wt(r))}function Je(r){return Cr(r),Ti(wt(Uint8Array.from(r).reverse()))}function Ft(r,e){return rr(r.toString(16).padStart(e*2,"0"))}function xt(r,e){return Ft(r,e).reverse()}function bp(r){return rr(tr(r))}function ie(r,e,t){let n;if(typeof e=="string")try{n=rr(e)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Ht(e))n=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");let o=n.length;if(typeof t=="number"&&o!==t)throw new Error(r+" of length "+t+" expected, got "+o);return n}function Et(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Cr(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function xp(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function Ep(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var Ci=r=>typeof r=="bigint"&&no<=r;function rn(r,e,t){return Ci(r)&&Ci(e)&&Ci(t)&&e<=r&&r<t}function ve(r,e,t,n){if(!rn(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function Li(r){let e;for(e=0;r>no;r>>=oo,e+=1);return e}function vp(r,e){return r>>BigInt(e)&oo}function Ap(r,e,t){return r|(t?oo:no)<<BigInt(e)}var nn=r=>(yp<<BigInt(r-1))-oo,ki=r=>new Uint8Array(r),wl=r=>Uint8Array.from(r);function Ni(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=ki(r),o=ki(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>t(o,n,...f),c=(f=ki())=>{o=a(wl([0]),f),n=a(),f.length!==0&&(o=a(wl([1]),f),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<e;){n=a();let m=n.slice();d.push(m),f+=n.length}return Et(...d)};return(f,d)=>{i(),c(f);let m;for(;!(m=d(l()));)c();return i(),m}}var Bp={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Ht(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,e)=>e.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function qe(r,e,t={}){let n=(o,s,i)=>{let a=Bp[s];if(typeof a!="function")throw new Error("invalid validator function");let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(e))n(o,s,!1);for(let[o,s]of Object.entries(t))n(o,s,!0);return r}var Sp=()=>{throw new Error("not implemented")};function nr(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var ge=BigInt(0),he=BigInt(1),or=BigInt(2),Ip=BigInt(3),_i=BigInt(4),bl=BigInt(5),xl=BigInt(8),Cp=BigInt(9),kp=BigInt(16);function Z(r,e){let t=r%e;return t>=ge?t:e+t}function Ri(r,e,t){if(e<ge)throw new Error("invalid exponent, negatives unsupported");if(t<=ge)throw new Error("invalid modulus");if(t===he)return ge;let n=he;for(;e>ge;)e&he&&(n=n*r%t),r=r*r%t,e>>=he;return n}function le(r,e,t){let n=r;for(;e-- >ge;)n*=n,n%=t;return n}function io(r,e){if(r===ge)throw new Error("invert: expected non-zero number");if(e<=ge)throw new Error("invert: expected positive modulus, got "+e);let t=Z(r,e),n=e,o=ge,s=he,i=he,a=ge;for(;t!==ge;){let l=n/t,u=n%t,f=o-i*l,d=s-a*l;n=t,t=u,o=i,s=a,i=f,a=d}if(n!==he)throw new Error("invert: does not exist");return Z(o,e)}function Tp(r){let e=(r-he)/or,t,n,o;for(t=r-he,n=0;t%or===ge;t/=or,n++);for(o=or;o<r&&Ri(o,e,r)!==r-he;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(r+he)/_i;return function(c,l){let u=c.pow(l,i);if(!c.eql(c.sqr(u),l))throw new Error("Cannot find square root");return u}}let s=(t+he)/or;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),t),f=a.pow(c,s),d=a.pow(c,t);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let m=1;for(let g=a.sqr(d);m<l&&!a.eql(g,a.ONE);m++)g=a.sqr(g);let y=a.pow(u,he<<BigInt(l-m-1));u=a.sqr(y),f=a.mul(f,y),d=a.mul(d,u),l=m}return f}}function Lp(r){if(r%_i===Ip){let e=(r+he)/_i;return function(n,o){let s=n.pow(o,e);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%xl===bl){let e=(r-bl)/xl;return function(n,o){let s=n.mul(o,or),i=n.pow(s,e),a=n.mul(o,i),c=n.mul(n.mul(a,or),i),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%kp,Tp(r)}var El=(r,e)=>(Z(r,e)&he)===he,Np=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ui(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=Np.reduce((n,o)=>(n[o]="function",n),e);return qe(r,t)}function _p(r,e,t){if(t<ge)throw new Error("invalid exponent, negatives unsupported");if(t===ge)return r.ONE;if(t===he)return e;let n=r.ONE,o=e;for(;t>ge;)t&he&&(n=r.mul(n,o)),o=r.sqr(o),t>>=he;return n}function Rp(r,e){let t=new Array(e.length),n=e.reduce((s,i,a)=>r.is0(i)?s:(t[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return e.reduceRight((s,i,a)=>r.is0(i)?s:(t[a]=r.mul(s,t[a]),r.mul(s,i)),o),t}function Di(r,e){let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function Vt(r,e,t=!1,n={}){if(r<=ge)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=Di(r,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:r,isLE:t,BITS:o,BYTES:s,MASK:nn(o),ZERO:ge,ONE:he,create:c=>Z(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return ge<=c&&c<r},is0:c=>c===ge,isOdd:c=>(c&he)===he,neg:c=>Z(-c,r),eql:(c,l)=>c===l,sqr:c=>Z(c*c,r),add:(c,l)=>Z(c+l,r),sub:(c,l)=>Z(c-l,r),mul:(c,l)=>Z(c*l,r),pow:(c,l)=>_p(a,c,l),div:(c,l)=>Z(c*io(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>io(c,r),sqrt:n.sqrt||(c=>(i||(i=Lp(r)),i(a,c))),invertBatch:c=>Rp(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>t?xt(c,s):Ft(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return t?Je(c):bt(c)}});return Object.freeze(a)}function vl(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function Pi(r){let e=vl(r);return e+Math.ceil(e/2)}function Al(r,e,t=!1){let n=r.length,o=vl(e),s=Pi(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?Je(r):bt(r),a=Z(i,e-he)+he;return t?xt(a,o):Ft(a,o)}var Bl=BigInt(0),ao=BigInt(1);function Oi(r,e){let t=e.negate();return r?t:e}function Sl(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Mi(r,e){Sl(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1);return{windows:t,windowSize:n}}function Up(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function Dp(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)})}var Hi=new WeakMap,Il=new WeakMap;function Fi(r){return Il.get(r)||1}function co(r,e){return{constTimeNegate:Oi,hasPrecomputes(t){return Fi(t)!==1},unsafeLadder(t,n,o=r.ZERO){let s=t;for(;n>Bl;)n&ao&&(o=o.add(s)),s=s.double(),n>>=ao;return o},precomputeWindow(t,n){let{windows:o,windowSize:s}=Mi(n,e),i=[],a=t,c=a;for(let l=0;l<o;l++){c=a,i.push(c);for(let u=1;u<s;u++)c=c.add(a),i.push(c);a=c.double()}return i},wNAF(t,n,o){let{windows:s,windowSize:i}=Mi(t,e),a=r.ZERO,c=r.BASE,l=BigInt(2**t-1),u=2**t,f=BigInt(t);for(let d=0;d<s;d++){let m=d*i,y=Number(o&l);o>>=f,y>i&&(y-=u,o+=ao);let g=m,h=m+Math.abs(y)-1,b=d%2!==0,x=y<0;y===0?c=c.add(Oi(b,n[g])):a=a.add(Oi(x,n[h]))}return{p:a,f:c}},wNAFUnsafe(t,n,o,s=r.ZERO){let{windows:i,windowSize:a}=Mi(t,e),c=BigInt(2**t-1),l=2**t,u=BigInt(t);for(let f=0;f<i;f++){let d=f*a;if(o===Bl)break;let m=Number(o&c);if(o>>=u,m>a&&(m-=l,o+=ao),m===0)continue;let y=n[d+Math.abs(m)-1];m<0&&(y=y.negate()),s=s.add(y)}return s},getPrecomputes(t,n,o){let s=Hi.get(n);return s||(s=this.precomputeWindow(n,t),t!==1&&Hi.set(n,o(s))),s},wNAFCached(t,n,o){let s=Fi(t);return this.wNAF(s,this.getPrecomputes(s,t,o),n)},wNAFCachedUnsafe(t,n,o,s){let i=Fi(t);return i===1?this.unsafeLadder(t,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,t,o),n,s)},setWindowSize(t,n){Sl(n,e),Il.set(t,n),Hi.delete(t)}}}function lo(r,e,t,n){if(Up(t,r),Dp(n,e),t.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,s=Li(BigInt(t.length)),i=s>12?s-3:s>4?s-2:s?2:1,a=(1<<i)-1,c=new Array(a+1).fill(o),l=Math.floor((e.BITS-1)/i)*i,u=o;for(let f=l;f>=0;f-=i){c.fill(o);for(let m=0;m<n.length;m++){let y=n[m],g=Number(y>>BigInt(f)&BigInt(a));c[g]=c[g].add(t[m])}let d=o;for(let m=c.length-1,y=o;m>0;m--)y=y.add(c[m]),d=d.add(y);if(u=u.add(d),f!==0)for(let m=0;m<i;m++)u=u.double()}return u}function on(r){return Ui(r.Fp),qe(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Di(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var Qe=BigInt(0),He=BigInt(1),uo=BigInt(2),Pp=BigInt(8),Op={zip215:!0};function Mp(r){let e=on(r);return qe(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Cl(r){let e=Mp(r),{Fp:t,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=e,l=uo<<BigInt(a*8)-He,u=t.create,f=Vt(e.n,e.nBitLength),d=e.uvRatio||((E,w)=>{try{return{isValid:!0,value:t.sqrt(E*t.inv(w))}}catch{return{isValid:!1,value:Qe}}}),m=e.adjustScalarBytes||(E=>E),y=e.domain||((E,w,A)=>{if(Ye("phflag",A),w.length||A)throw new Error("Contexts/pre-hash are not supported");return E});function g(E,w){ve("coordinate "+E,w,Qe,l)}function h(E){if(!(E instanceof p))throw new Error("ExtendedPoint expected")}let b=nr((E,w)=>{let{ex:A,ey:v,ez:_}=E,R=E.is0();w==null&&(w=R?Pp:t.inv(_));let O=u(A*w),K=u(v*w),F=u(_*w);if(R)return{x:Qe,y:He};if(F!==He)throw new Error("invZ was invalid");return{x:O,y:K}}),x=nr(E=>{let{a:w,d:A}=e;if(E.is0())throw new Error("bad point: ZERO");let{ex:v,ey:_,ez:R,et:O}=E,K=u(v*v),F=u(_*_),G=u(R*R),j=u(G*G),ae=u(K*w),ce=u(G*u(ae+F)),fe=u(j+u(A*u(K*F)));if(ce!==fe)throw new Error("bad point: equation left != right (1)");let Ie=u(v*_),Me=u(R*O);if(Ie!==Me)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(w,A,v,_){this.ex=w,this.ey=A,this.ez=v,this.et=_,g("x",w),g("y",A),g("z",v),g("t",_),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(w){if(w instanceof p)throw new Error("extended point not allowed");let{x:A,y:v}=w||{};return g("x",A),g("y",v),new p(A,v,He,u(A*v))}static normalizeZ(w){let A=t.invertBatch(w.map(v=>v.ez));return w.map((v,_)=>v.toAffine(A[_])).map(p.fromAffine)}static msm(w,A){return lo(p,f,w,A)}_setWindowSize(w){L.setWindowSize(this,w)}assertValidity(){x(this)}equals(w){h(w);let{ex:A,ey:v,ez:_}=this,{ex:R,ey:O,ez:K}=w,F=u(A*K),G=u(R*_),j=u(v*K),ae=u(O*_);return F===G&&j===ae}is0(){return this.equals(p.ZERO)}negate(){return new p(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:w}=e,{ex:A,ey:v,ez:_}=this,R=u(A*A),O=u(v*v),K=u(uo*u(_*_)),F=u(w*R),G=A+v,j=u(u(G*G)-R-O),ae=F+O,ce=ae-K,fe=F-O,Ie=u(j*ce),Me=u(ae*fe),Ue=u(j*fe),it=u(ce*ae);return new p(Ie,Me,it,Ue)}add(w){h(w);let{a:A,d:v}=e,{ex:_,ey:R,ez:O,et:K}=this,{ex:F,ey:G,ez:j,et:ae}=w;if(A===BigInt(-1)){let Vc=u((R-_)*(G+F)),Kc=u((R+_)*(G-F)),fi=u(Kc-Vc);if(fi===Qe)return this.double();let $c=u(O*uo*ae),Gc=u(K*uo*j),Wc=Gc+$c,qc=Kc+Vc,zc=Gc-$c,qh=u(Wc*fi),zh=u(qc*zc),jh=u(Wc*zc),Zh=u(fi*qc);return new p(qh,zh,Zh,jh)}let ce=u(_*F),fe=u(R*G),Ie=u(K*v*ae),Me=u(O*j),Ue=u((_+R)*(F+G)-ce-fe),it=Me-Ie,dt=Me+Ie,Zr=u(fe-A*ce),Kh=u(Ue*it),$h=u(dt*Zr),Gh=u(Ue*Zr),Wh=u(it*dt);return new p(Kh,$h,Wh,Gh)}subtract(w){return this.add(w.negate())}wNAF(w){return L.wNAFCached(this,w,p.normalizeZ)}multiply(w){let A=w;ve("scalar",A,He,n);let{p:v,f:_}=this.wNAF(A);return p.normalizeZ([v,_])[0]}multiplyUnsafe(w,A=p.ZERO){let v=w;return ve("scalar",v,Qe,n),v===Qe?N:this.is0()||v===He?this:L.wNAFCachedUnsafe(this,v,p.normalizeZ,A)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return L.unsafeLadder(this,n).is0()}toAffine(w){return b(this,w)}clearCofactor(){let{h:w}=e;return w===He?this:this.multiplyUnsafe(w)}static fromHex(w,A=!1){let{d:v,a:_}=e,R=t.BYTES;w=ie("pointHex",w,R),Ye("zip215",A);let O=w.slice(),K=w[R-1];O[R-1]=K&-129;let F=Je(O),G=A?l:t.ORDER;ve("pointHex.y",F,Qe,G);let j=u(F*F),ae=u(j-He),ce=u(v*j-_),{isValid:fe,value:Ie}=d(ae,ce);if(!fe)throw new Error("Point.fromHex: invalid y coordinate");let Me=(Ie&He)===He,Ue=(K&128)!==0;if(!A&&Ie===Qe&&Ue)throw new Error("Point.fromHex: x=0 and x_0=1");return Ue!==Me&&(Ie=u(-Ie)),p.fromAffine({x:Ie,y:F})}static fromPrivateKey(w){return C(w).point}toRawBytes(){let{x:w,y:A}=this.toAffine(),v=xt(A,t.BYTES);return v[v.length-1]|=w&He?128:0,v}toHex(){return wt(this.toRawBytes())}}p.BASE=new p(e.Gx,e.Gy,He,u(e.Gx*e.Gy)),p.ZERO=new p(Qe,He,He,Qe);let{BASE:S,ZERO:N}=p,L=co(p,a*8);function B(E){return Z(E,n)}function T(E){return B(Je(E))}function C(E){let w=t.BYTES;E=ie("private key",E,w);let A=ie("hashed private key",s(E),2*w),v=m(A.slice(0,w)),_=A.slice(w,2*w),R=T(v),O=S.multiply(R),K=O.toRawBytes();return{head:v,prefix:_,scalar:R,point:O,pointBytes:K}}function H(E){return C(E).pointBytes}function U(E=new Uint8Array,...w){let A=Et(...w);return T(s(y(A,ie("context",E),!!o)))}function M(E,w,A={}){E=ie("message",E),o&&(E=o(E));let{prefix:v,scalar:_,pointBytes:R}=C(w),O=U(A.context,v,E),K=S.multiply(O).toRawBytes(),F=U(A.context,K,R,E),G=B(O+F*_);ve("signature.s",G,Qe,n);let j=Et(K,xt(G,t.BYTES));return ie("result",j,t.BYTES*2)}let V=Op;function I(E,w,A,v=V){let{context:_,zip215:R}=v,O=t.BYTES;E=ie("signature",E,2*O),w=ie("message",w),A=ie("publicKey",A,O),R!==void 0&&Ye("zip215",R),o&&(w=o(w));let K=Je(E.slice(O,2*O)),F,G,j;try{F=p.fromHex(A,R),G=p.fromHex(E.slice(0,O),R),j=S.multiplyUnsafe(K)}catch{return!1}if(!R&&F.isSmallOrder())return!1;let ae=U(_,G.toRawBytes(),F.toRawBytes(),w);return G.add(F.multiplyUnsafe(ae)).subtract(j).clearCofactor().equals(p.ZERO)}return S._setWindowSize(8),{CURVE:e,getPublicKey:H,sign:M,verify:I,ExtendedPoint:p,utils:{getExtendedPublicKey:C,randomPrivateKey:()=>i(t.BYTES),precompute(E=8,w=p.BASE){return w._setWindowSize(E),w.multiply(BigInt(3)),w}}}}var kr=BigInt(0),Vi=BigInt(1);function Hp(r){return qe(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function kl(r){let e=Hp(r),{P:t}=e,n=x=>Z(x,t),o=e.montgomeryBits,s=Math.ceil(o/8),i=e.nByteLength,a=e.adjustScalarBytes||(x=>x),c=e.powPminus2||(x=>Ri(x,t-BigInt(2),t));function l(x,p,S){let N=n(x*(p-S));return p=n(p-N),S=n(S+N),[p,S]}let u=(e.a-BigInt(2))/BigInt(4);function f(x,p){ve("u",x,kr,t),ve("scalar",p,kr,t);let S=p,N=x,L=Vi,B=kr,T=x,C=Vi,H=kr,U;for(let V=BigInt(o-1);V>=kr;V--){let I=S>>V&Vi;H^=I,U=l(H,L,T),L=U[0],T=U[1],U=l(H,B,C),B=U[0],C=U[1],H=I;let k=L+B,E=n(k*k),w=L-B,A=n(w*w),v=E-A,_=T+C,R=T-C,O=n(R*k),K=n(_*w),F=O+K,G=O-K;T=n(F*F),C=n(N*n(G*G)),L=n(E*A),B=n(v*(E+n(u*v)))}U=l(H,L,T),L=U[0],T=U[1],U=l(H,B,C),B=U[0],C=U[1];let M=c(B);return n(L*M)}function d(x){return xt(n(x),s)}function m(x){let p=ie("u coordinate",x,s);return i===32&&(p[31]&=127),Je(p)}function y(x){let p=ie("scalar",x),S=p.length;if(S!==s&&S!==i){let N=""+s+" or "+i;throw new Error("invalid scalar, expected "+N+" bytes, got "+S)}return Je(a(p))}function g(x,p){let S=m(p),N=y(x),L=f(S,N);if(L===kr)throw new Error("invalid private or public key received");return d(L)}let h=d(e.Gu);function b(x){return g(x,h)}return{scalarMult:g,scalarMultBase:b,getSharedSecret:(x,p)=>g(x,p),getPublicKey:x=>b(x),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:h}}var sn=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Tl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),ow=BigInt(0),Fp=BigInt(1),Ll=BigInt(2),Vp=BigInt(3),Kp=BigInt(5),$p=BigInt(8);function Nl(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=sn,a=r*r%s*r%s,c=le(a,Ll,s)*a%s,l=le(c,Fp,s)*r%s,u=le(l,Kp,s)*l%s,f=le(u,e,s)*u%s,d=le(f,t,s)*f%s,m=le(d,n,s)*d%s,y=le(m,o,s)*m%s,g=le(y,o,s)*m%s,h=le(g,e,s)*u%s;return{pow_p_5_8:le(h,Ll,s)*r%s,b2:a}}function _l(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Gp(r,e){let t=sn,n=Z(e*e*e,t),o=Z(n*n*e,t),s=Nl(r*o).pow_p_5_8,i=Z(r*n*s,t),a=Z(e*i*i,t),c=i,l=Z(i*Tl,t),u=a===r,f=a===Z(-r,t),d=a===Z(-r*Tl,t);return u&&(i=c),(f||d)&&(i=l),El(i,t)&&(i=Z(-i,t)),{isValid:u||f,value:i}}var Wp=Vt(sn,void 0,!0),qp={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Wp,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:$p,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:gl,randomBytes:tn,adjustScalarBytes:_l,uvRatio:Gp},Rl=Cl(qp);var an=kl({P:sn,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let e=sn,{pow_p_5_8:t,b2:n}=Nl(r);return Z(le(t,Vp,e)*n,e)},adjustScalarBytes:_l,randomBytes:tn});var fo=32;function Ul(r,e,t){return Rl.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}var ho=class{type="Ed25519";raw;constructor(e){this.raw=Ki(e,fo)}toMultihash(){return gt.digest(Tr(this))}toCID(){return Ee.createV1(114,this.toMultihash())}toString(){return se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:De(this.raw,e.raw)}verify(e,t){return Ul(this.raw,t,e)}};function $i(r){return r=Ki(r,fo),new ho(r)}function Ki(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new oe(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}function ye(r=0){return new Uint8Array(r)}function me(r=0){return new Uint8Array(r)}var jp=Math.pow(2,7),Zp=Math.pow(2,14),Xp=Math.pow(2,21),Gi=Math.pow(2,28),Wi=Math.pow(2,35),qi=Math.pow(2,42),zi=Math.pow(2,49),J=128,Te=127;function ee(r){if(r<jp)return 1;if(r<Zp)return 2;if(r<Xp)return 3;if(r<Gi)return 4;if(r<Wi)return 5;if(r<qi)return 6;if(r<zi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ji(r,e,t=0){switch(ee(r)){case 8:e[t++]=r&255|J,r/=128;case 7:e[t++]=r&255|J,r/=128;case 6:e[t++]=r&255|J,r/=128;case 5:e[t++]=r&255|J,r/=128;case 4:e[t++]=r&255|J,r>>>=7;case 3:e[t++]=r&255|J,r>>>=7;case 2:e[t++]=r&255|J,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Yp(r,e,t=0){switch(ee(r)){case 8:e.set(t++,r&255|J),r/=128;case 7:e.set(t++,r&255|J),r/=128;case 6:e.set(t++,r&255|J),r/=128;case 5:e.set(t++,r&255|J),r/=128;case 4:e.set(t++,r&255|J),r>>>=7;case 3:e.set(t++,r&255|J),r>>>=7;case 2:e.set(t++,r&255|J),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Zi(r,e){let t=r[e],n=0;if(n+=t&Te,t<J||(t=r[e+1],n+=(t&Te)<<7,t<J)||(t=r[e+2],n+=(t&Te)<<14,t<J)||(t=r[e+3],n+=(t&Te)<<21,t<J)||(t=r[e+4],n+=(t&Te)*Gi,t<J)||(t=r[e+5],n+=(t&Te)*Wi,t<J)||(t=r[e+6],n+=(t&Te)*qi,t<J)||(t=r[e+7],n+=(t&Te)*zi,t<J))return n;throw new RangeError("Could not decode varint")}function Jp(r,e){let t=r.get(e),n=0;if(n+=t&Te,t<J||(t=r.get(e+1),n+=(t&Te)<<7,t<J)||(t=r.get(e+2),n+=(t&Te)<<14,t<J)||(t=r.get(e+3),n+=(t&Te)<<21,t<J)||(t=r.get(e+4),n+=(t&Te)*Gi,t<J)||(t=r.get(e+5),n+=(t&Te)*Wi,t<J)||(t=r.get(e+6),n+=(t&Te)*qi,t<J)||(t=r.get(e+7),n+=(t&Te)*zi,t<J))return n;throw new RangeError("Could not decode varint")}function ze(r,e,t=0){return e==null&&(e=me(ee(r))),e instanceof Uint8Array?ji(r,e,t):Yp(r,e,t)}function Ke(r,e=0){return r instanceof Uint8Array?Zi(r,e):Jp(r,e)}var Xi=new Float32Array([-0]),Kt=new Uint8Array(Xi.buffer);function Pl(r,e,t){Xi[0]=r,e[t]=Kt[0],e[t+1]=Kt[1],e[t+2]=Kt[2],e[t+3]=Kt[3]}function Ol(r,e){return Kt[0]=r[e],Kt[1]=r[e+1],Kt[2]=r[e+2],Kt[3]=r[e+3],Xi[0]}var Yi=new Float64Array([-0]),Le=new Uint8Array(Yi.buffer);function Ml(r,e,t){Yi[0]=r,e[t]=Le[0],e[t+1]=Le[1],e[t+2]=Le[2],e[t+3]=Le[3],e[t+4]=Le[4],e[t+5]=Le[5],e[t+6]=Le[6],e[t+7]=Le[7]}function Hl(r,e){return Le[0]=r[e],Le[1]=r[e+1],Le[2]=r[e+2],Le[3]=r[e+3],Le[4]=r[e+4],Le[5]=r[e+5],Le[6]=r[e+6],Le[7]=r[e+7],Yi[0]}var Qp=BigInt(Number.MAX_SAFE_INTEGER),e0=BigInt(Number.MIN_SAFE_INTEGER),$e=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+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 t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(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,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return ir;if(e<Qp&&e>e0)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Fl&&(o=0n,++n>Fl&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return ir;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):ir}},ir=new $e(0,0);ir.toBigInt=function(){return 0n};ir.zzEncode=ir.zzDecode=function(){return this};ir.length=function(){return 1};var Fl=4294967296n;function Vl(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Kl(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Ji(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function et(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function po(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var Qi=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,et(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw et(this,4);return po(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw et(this,4);return po(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw et(this,4);let e=Ol(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw et(this,4);let e=Hl(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw et(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Kl(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw et(this,e);this.pos+=e}else do if(this.pos>=this.len)throw et(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new $e(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*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;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw et(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw et(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw et(this,8);let e=po(this.buf,this.pos+=4),t=po(this.buf,this.pos+=4);return new $e(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Zi(this.buf,this.pos);return this.pos+=ee(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 ea(r){return new Qi(r instanceof Uint8Array?r:r.subarray())}function tt(r,e,t){let n=ea(r);return e.decode(n,void 0,t)}var ta={};Ce(ta,{base10:()=>t0});var t0=Ut({prefix:"9",name:"base10",alphabet:"0123456789"});var ra={};Ce(ra,{base16:()=>r0,base16upper:()=>n0});var r0=de({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),n0=de({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var na={};Ce(na,{base2:()=>o0});var o0=de({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var oa={};Ce(oa,{base256emoji:()=>l0});var Gl=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}"),s0=Gl.reduce((r,e,t)=>(r[t]=e,r),[]),i0=Gl.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function a0(r){return r.reduce((e,t)=>(e+=s0[t],e),"")}function c0(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=i0[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var l0=xr({prefix:"\u{1F680}",name:"base256emoji",encode:a0,decode:c0});var sa={};Ce(sa,{base64:()=>u0,base64pad:()=>f0,base64url:()=>cn,base64urlpad:()=>h0});var u0=de({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),f0=de({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cn=de({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),h0=de({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ia={};Ce(ia,{base8:()=>d0});var d0=de({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var aa={};Ce(aa,{identity:()=>p0});var p0=xr({prefix:"\0",name:"identity",encode:r=>Qc(r),decode:r=>Jc(r)});var Fw=new TextEncoder,Vw=new TextDecoder;var ua={};Ce(ua,{sha256:()=>vt,sha512:()=>y0});function la({name:r,code:e,encode:t}){return new ca(r,e,t)}var ca=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?ke(this.code,t):t.then(n=>ke(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ql(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var vt=la({name:"sha2-256",code:18,encode:ql("SHA-256")}),y0=la({name:"sha2-512",code:19,encode:ql("SHA-512")});var ar={...aa,...na,...ia,...ta,...ra,...wi,...bi,...yi,...sa,...oa},Qw={...ua,...Ai};function jl(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var zl=jl("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),fa=jl("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=me(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),w0={utf8:zl,"utf-8":zl,hex:ar.base16,latin1:fa,ascii:fa,binary:fa,...ar},mo=w0;function Q(r,e="utf8"){let t=mo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function ha(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return me(i);o+i>e&&(n=me(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var cr=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function da(){}var ma=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},b0=ha();function x0(r){return globalThis.Buffer!=null?me(r):b0(r)}var un=class{len;head;tail;states;constructor(){this.len=0,this.head=new cr(da,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new cr(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new ga((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(go,10,$e.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=$e.fromBigInt(e);return this._push(go,t.length(),t)}uint64Number(e){return this._push(ji,ee(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 t=$e.fromBigInt(e).zzEncode();return this._push(go,t.length(),t)}sint64Number(e){let t=$e.fromNumber(e).zzEncode();return this._push(go,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(pa,1,e?1:0)}fixed32(e){return this._push(ln,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=$e.fromBigInt(e);return this._push(ln,4,t.lo)._push(ln,4,t.hi)}fixed64Number(e){let t=$e.fromNumber(e);return this._push(ln,4,t.lo)._push(ln,4,t.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(Pl,4,e)}double(e){return this._push(Ml,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(pa,1,0):this.uint32(t)._push(v0,t,e)}string(e){let t=Vl(e);return t!==0?this.uint32(t)._push(Ji,t,e):this._push(pa,1,0)}fork(){return this.states=new ma(this),this.head=this.tail=new cr(da,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 cr(da,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=x0(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function pa(r,e,t){e[t]=r&255}function E0(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var ga=class extends cr{next;constructor(e,t){super(E0,e,t),this.next=void 0}};function go(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function ln(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function v0(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(un.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(A0,e,r),this},un.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(B0,e,r),this});function A0(r,e,t){e.set(r,t)}function B0(r,e,t){r.length<40?Ji(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Q(r),t)}function ya(){return new un}function rt(r,e){let t=ya();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Lr;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Lr||(Lr={}));function yo(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function lr(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return yo("enum",Lr.VARINT,t,n)}function nt(r,e){return yo("message",Lr.LENGTH_DELIMITED,r,e)}var we;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(we||(we={}));var wa;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(wa||(wa={}));(function(r){r.codec=()=>lr(wa)})(we||(we={}));var at;(function(r){let e;r.codec=()=>(e==null&&(e=nt((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),we.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=we.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>rt(t,r.codec()),r.decode=(t,n)=>tt(t,r.codec(),n)})(at||(at={}));var ba;(function(r){let e;r.codec=()=>(e==null&&(e=nt((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),we.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=we.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>rt(t,r.codec()),r.decode=(t,n)=>tt(t,r.codec(),n)})(ba||(ba={}));var xn={};Ce(xn,{MAX_RSA_KEY_SIZE:()=>cs,generateRSAKeyPair:()=>Wu,jwkToJWKKeyPair:()=>qu,jwkToPkcs1:()=>F0,jwkToPkix:()=>ka,jwkToRSAPrivateKey:()=>Gu,pkcs1ToJwk:()=>Vu,pkcs1ToRSAPrivateKey:()=>$u,pkixToJwk:()=>Ku,pkixToRSAPublicKey:()=>Ta});var S0=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),$t=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Gt=new Uint32Array(64),xa=class extends Ir{constructor(){super(64,32,8,!1),this.A=$t[0]|0,this.B=$t[1]|0,this.C=$t[2]|0,this.D=$t[3]|0,this.E=$t[4]|0,this.F=$t[5]|0,this.G=$t[6]|0,this.H=$t[7]|0}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|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,t){for(let f=0;f<16;f++,t+=4)Gt[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=Gt[f-15],m=Gt[f-2],y=Xe(d,7)^Xe(d,18)^d>>>3,g=Xe(m,17)^Xe(m,19)^m>>>10;Gt[f]=g+Gt[f-7]+y+Gt[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=Xe(a,6)^Xe(a,11)^Xe(a,25),m=u+d+dl(a,c,l)+S0[f]+Gt[f]|0,g=(Xe(n,2)^Xe(n,13)^Xe(n,22))+pl(n,o,s)|0;u=l,l=c,c=a,a=i+m|0,i=s,s=o,o=n,n=m+g|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,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){Gt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ct=to(()=>new xa);var q=rd(Xl());function ur(r,e){let t=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)t+=r[r.length-1-n]*Math.pow(2,e*n);return t}function Wt(r,e,t=-1){let n=t,o=r,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let f=Math.pow(2,u*e);l[s-u-1]=Math.floor(o/f),o-=l[s-u-1]*f}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function xo(...r){let e=0,t=0;for(let s of r)e+=s.length;let n=new ArrayBuffer(e),o=new Uint8Array(n);for(let s of r)o.set(s,t),t+=s.length;return o}function va(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let e=new ArrayBuffer(this.valueHex.byteLength),t=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)t[a]=0;t[0]=r[0]&128;let n=ur(t,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,ur(s,8)-n}function Yl(r){let e=r<0?r*-1:r,t=128;for(let n=1;n<8;n++){if(e<=t){if(r<0){let i=t-e,a=Wt(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Wt(e,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}t*=Math.pow(2,8)}return new ArrayBuffer(0)}function Jl(r,e){if(r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let o=0;o<t.length;o++)if(t[o]!==n[o])return!1;return!0}function Fe(r,e){let t=r.toString(10);if(e<t.length)return"";let n=e-t.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(t)}var Ub=Math.log(2);function Eo(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Aa(r){let e=0,t=0;for(let o=0;o<r.length;o++){let s=r[o];e+=s.byteLength}let n=new Uint8Array(e);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),t),t+=s.byteLength}return n.buffer}function Ct(r,e,t,n){return e instanceof Uint8Array?e.byteLength?t<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-t-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var hn=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Aa(this.items)}},fn=[new Uint8Array([1])],Ql="0123456789";var Dr="",ot=new ArrayBuffer(0),Ba=new Uint8Array(0),dn="EndOfContent",tu="OCTET STRING",ru="BIT STRING";function kt(r){var e;return e=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?q.BufferSourceConverter.toUint8Array(s.valueHex):Ba}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Ct(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",ot)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:q.Convert.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}var Bt=class{constructor({blockLength:e=0,error:t=Dr,warnings:n=[],valueBeforeDecode:o=Ba}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=q.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:q.Convert.ToHex(this.valueBeforeDecodeView)}}};Bt.NAME="baseBlock";var Ne=class extends Bt{fromBER(e,t,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Ne.NAME="valueBlock";var vo=class extends kt(Bt){constructor({idBlock:e={}}={}){var t,n,o,s;super(),e?(this.isHexOnly=(t=e.isHexOnly)!==null&&t!==void 0?t:!1,this.valueHexView=e.valueHex?q.BufferSourceConverter.toUint8Array(e.valueHex):Ba,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",ot}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,t|=s,o[0]=t}return o.buffer}if(!this.isHexOnly){let o=Wt(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=t|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Ct(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,l=this.valueHexView=new Uint8Array(255),u=255;for(;s[c]&128;){if(l[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===u){u+=255;let d=new Uint8Array(u);for(let m=0;m<l.length;m++)d[m]=l[m];l=this.valueHexView=new Uint8Array(u)}}this.blockLength=c+1,l[c-1]=s[c]&127;let f=new Uint8Array(c);for(let d=0;d<c;d++)f[d]=l[d];l=this.valueHexView=new Uint8Array(c),l.set(f),this.blockLength<=9?this.tagNumber=ur(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};vo.NAME="identificationBlock";var Ao=class extends Bt{constructor({lenBlock:e={}}={}){var t,n,o;super(),this.isIndefiniteForm=(t=e.isIndefiniteForm)!==null&&t!==void 0?t:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Ct(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,t+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=t+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=ur(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let o=Wt(this.length,8);if(o.byteLength>127)return this.error="Too big length",ot;if(t=new ArrayBuffer(o.byteLength+1),e)return t;let s=new Uint8Array(o);n=new Uint8Array(t),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};Ao.NAME="lengthBlock";var D={},Ae=class extends Bt{constructor({name:e=Dr,optional:t=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new vo(o),this.lenBlock=new Ao(o),this.valueBlock=s?new s(o):new Ne(o)}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,t){let n=t||new hn;t||nu(this);let o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return t?ot:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():q.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return Jl(t,n)}};Ae.NAME="BaseBlock";function nu(r){if(r instanceof D.Constructed)for(let e of r.valueBlock.value)nu(e)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var Bo=class extends Ae{constructor({value:e=Dr,...t}={},n){super(t,n),e&&this.fromString(e)}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}fromBER(e,t,n){let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};Bo.NAME="BaseStringBlock";var So=class extends kt(Ne){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};So.NAME="PrimitiveValueBlock";var ou,Io=class extends Ae{constructor(e={}){super(e,So),this.idBlock.isConstructed=!1}};ou=Io;D.Primitive=ou;Io.NAME="PRIMITIVE";function U0(r,e){if(r instanceof e)return r;let t=new e;return t.idBlock=r.idBlock,t.lenBlock=r.lenBlock,t.warnings=r.warnings,t.valueBeforeDecodeView=r.valueBeforeDecodeView,t}function is(r,e=0,t=r.length){let n=e,o=new Ae({},Ne),s=new Bt;if(!Ct(s,r,e,t))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(e,e+t).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,e,t);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=a,t-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,e,t),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(e=a,t-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Ae;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=D.EndOfContent;break;case 1:c=D.Boolean;break;case 2:c=D.Integer;break;case 3:c=D.BitString;break;case 4:c=D.OctetString;break;case 5:c=D.Null;break;case 6:c=D.ObjectIdentifier;break;case 10:c=D.Enumerated;break;case 12:c=D.Utf8String;break;case 13:c=D.RelativeObjectIdentifier;break;case 14:c=D.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=D.Sequence;break;case 17:c=D.Set;break;case 18:c=D.NumericString;break;case 19:c=D.PrintableString;break;case 20:c=D.TeletexString;break;case 21:c=D.VideotexString;break;case 22:c=D.IA5String;break;case 23:c=D.UTCTime;break;case 24:c=D.GeneralizedTime;break;case 25:c=D.GraphicString;break;case 26:c=D.VisibleString;break;case 27:c=D.GeneralString;break;case 28:c=D.UniversalString;break;case 29:c=D.CharacterString;break;case 30:c=D.BmpString;break;case 31:c=D.DATE;break;case 32:c=D.TimeOfDay;break;case 33:c=D.DateTime;break;case 34:c=D.Duration;break;default:{let l=o.idBlock.isConstructed?new D.Constructed:new D.Primitive;l.idBlock=o.idBlock,l.lenBlock=o.lenBlock,l.warnings=o.warnings,o=l}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?D.Constructed:D.Primitive}return o=U0(o,c),a=o.fromBER(r,e,o.lenBlock.isIndefiniteForm?t:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function Sa(r){if(!r.byteLength){let e=new Ae({},Ne);return e.error="Input buffer has zero length",{offset:-1,result:e}}return is(q.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function D0(r,e){return r?1:e}var lt=class extends Ne{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);if(!Ct(this,o,t,n))return-1;if(this.valueBeforeDecodeView=o.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),t;let s=t;for(;D0(this.isIndefiniteForm,n)>0;){let i=is(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===dn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===dn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){let n=t||new hn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return t?ot:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};lt.NAME="ConstructedValueBlock";var su,qt=class extends Ae{constructor(e={}){super(e,lt),this.idBlock.isConstructed=!0}fromBER(e,t,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let e=[];for(let n of this.valueBlock.value)e.push(n.toString("ascii").split(`
|
3
3
|
`).map(o=>` ${o}`).join(`
|
4
4
|
`));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :
|
5
5
|
${e.join(`
|
6
|
-
`)}`:`${t} :`}};su=qt;D.Constructed=su;qt.NAME="CONSTRUCTED";var Co=class extends Ne{fromBER(e,t,n){return t}toBER(e){return ot}};Co.override="EndOfContentValueBlock";var iu,ko=class extends Ae{constructor(e={}){super(e,Co),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};iu=ko;D.EndOfContent=iu;ko.NAME=dn;var au,_r=class extends Ae{constructor(e={}){super(e,Ne),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};au=_r;D.Null=au;_r.NAME="NULL";var To=class extends kt(Ne){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=q.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);return Ct(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,va.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};To.NAME="BooleanValueBlock";var cu,Lo=class extends Ae{constructor(e={}){super(e,To),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};cu=Lo;D.Boolean=cu;Lo.NAME="BOOLEAN";var No=class extends kt(lt){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=lt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===dn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==tu)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?lt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};No.NAME="OctetStringValueBlock";var lu,_o=class r extends Ae{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},No),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=is(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?qt.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return q.BufferSourceConverter.concat(e)}};lu=_o;D.OctetString=lu;_o.NAME=tu;var Ro=class extends kt(lt){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=lt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===dn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==ru)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let s=q.BufferSourceConverter.toUint8Array(e);if(!Ct(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=is(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return lt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ot;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Ro.NAME="BitStringValueBlock";var uu,Rr=class extends Ae{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Ro),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return qt.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};uu=Rr;D.BitString=uu;Rr.NAME=ru;var fu;function D0(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<i?i:c,f=0;for(let d=u;d>=0;d--,f++){switch(!0){case f<a.length:l=s[i-f]+a[c-f]+t[0];break;default:l=s[i-f]+t[0]}switch(t[0]=l/10,!0){case f>=s.length:s=xo(new Uint8Array([l%10]),s);break;default:s[i-f]=l%10}}return t[0]>0&&(s=xo(t,s)),s}function eu(r){if(r>=fn.length)for(let e=fn.length;e<=r;e++){let t=new Uint8Array([0]),n=fn[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=xo(t,n)),fn.push(n)}return fn[r]}function P0(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let f=c;f>=0;f--,u++)switch(l=s[i-u]-a[c-u]-t,!0){case l<0:t=1,s[i-u]=l+10;break;default:t=0,s[i-u]=l}if(t>0)for(let f=i-c+1;f>=0;f--,u++)if(l=s[i-u]-t,l<0)t=1,s[i-u]=l+10;else{t=0,s[i-u]=l;break}return s.slice()}var pn=class extends kt(Ne){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=va.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Yl(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case e:t=P0(eu(n),t),i="-";break;default:t=D0(t,eu(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=Ql.charAt(t[c]));return a===!1&&(i+=Ql.charAt(0)),i}};fu=pn;pn.NAME="IntegerValueBlock";Object.defineProperty(fu.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var hu,Be=class r extends Ae{constructor(e={}){super(e,pn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Eo(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Eo();let t=BigInt(e),n=new hn,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(q.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${q.Convert.ToHex(a)}`)+t,u=q.BufferSourceConverter.toUint8Array(q.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};hu=Be;D.Integer=hu;Be.NAME="INTEGER";var du,Uo=class extends Be{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};du=Uo;D.Enumerated=du;Uo.NAME="ENUMERATED";var mn=class extends kt(Ne){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=q.BufferSourceConverter.toUint8Array(e);if(!Ct(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=ur(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Eo();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Wt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ot;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=q.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};mn.NAME="sidBlock";var Do=class extends Ne{constructor({value:e=Dr,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new mn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,ot;t.push(o)}return Aa(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new mn;if(o>Number.MAX_SAFE_INTEGER){Eo();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Do.NAME="ObjectIdentifierValueBlock";var pu,Ur=class extends Ae{constructor(e={}){super(e,Do),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};pu=Ur;D.ObjectIdentifier=pu;Ur.NAME="OBJECT IDENTIFIER";var gn=class extends kt(Bt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=q.BufferSourceConverter.toUint8Array(e);if(!Ct(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=ur(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Wt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ot;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=q.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};gn.NAME="relativeSidBlock";var Po=class extends Ne{constructor({value:e=Dr,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new gn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,ot;n.push(s)}return Aa(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new gn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Po.NAME="RelativeObjectIdentifierValueBlock";var mu,Oo=class extends Ae{constructor(e={}){super(e,Po),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};mu=Oo;D.RelativeObjectIdentifier=mu;Oo.NAME="RelativeObjectIdentifier";var gu,St=class extends qt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};gu=St;D.Sequence=gu;St.NAME="SEQUENCE";var yu,Mo=class extends qt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};yu=Mo;D.Set=yu;Mo.NAME="SET";var Ho=class extends kt(Ne){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Dr}toJSON(){return{...super.toJSON(),value:this.value}}};Ho.NAME="StringValueBlock";var Fo=class extends Ho{};Fo.NAME="SimpleStringValueBlock";var Pe=class extends Bo{constructor({...e}={}){super(e,Fo)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};Pe.NAME="SIMPLE STRING";var Vo=class extends Pe{fromBuffer(e){this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=q.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=q.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf8String(e)),this.valueBlock.value=e}};Vo.NAME="Utf8StringValueBlock";var wu,It=class extends Vo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};wu=It;D.Utf8String=wu;It.NAME="UTF8String";var Ko=class extends Pe{fromBuffer(e){this.valueBlock.value=q.Convert.ToUtf16String(e),this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf16String(e))}};Ko.NAME="BmpStringValueBlock";var bu,$o=class extends Ko{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};bu=$o;D.BmpString=bu;$o.NAME="BMPString";var Go=class extends Pe{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=Wt(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};Go.NAME="UniversalStringValueBlock";var xu,Wo=class extends Go{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};xu=Wo;D.UniversalString=xu;Wo.NAME="UniversalString";var Eu,qo=class extends Pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Eu=qo;D.NumericString=Eu;qo.NAME="NumericString";var vu,zo=class extends Pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};vu=zo;D.PrintableString=vu;zo.NAME="PrintableString";var Au,jo=class extends Pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Au=jo;D.TeletexString=Au;jo.NAME="TeletexString";var Bu,Zo=class extends Pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Bu=Zo;D.VideotexString=Bu;Zo.NAME="VideotexString";var Su,Xo=class extends Pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Su=Xo;D.IA5String=Su;Xo.NAME="IA5String";var Iu,Yo=class extends Pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Iu=Yo;D.GraphicString=Iu;Yo.NAME="GraphicString";var Cu,yn=class extends Pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Cu=yn;D.VisibleString=Cu;yn.NAME="VisibleString";var ku,Jo=class extends Pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};ku=Jo;D.GeneralString=ku;Jo.NAME="GeneralString";var Tu,Qo=class extends Pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Tu=Qo;D.CharacterString=Tu;Qo.NAME="CharacterString";var Lu,wn=class extends yn{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=Fe(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=Fe(this.month,2),t[2]=Fe(this.day,2),t[3]=Fe(this.hour,2),t[4]=Fe(this.minute,2),t[5]=Fe(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};Lu=wn;D.UTCTime=Lu;wn.NAME="UTCTime";var Nu,es=class extends wn{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let f=new Number(e[e.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,d=n.indexOf("+"),m="";if(d===-1&&(d=n.indexOf("-"),f=-1),d!==-1){if(m=n.substring(d+1),n=n.substring(0,d),m.length!==2&&m.length!==4)throw new Error("Wrong input string for conversion");let y=parseInt(m.substring(0,2),10);if(isNaN(y.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*y,m.length===4){if(y=parseInt(m.substring(2,4),10),isNaN(y.valueOf()))throw new Error("Wrong input string for conversion");c=f*y}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let f=new Number(`0${n.substring(l)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");s=f.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=1e3*s;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=i.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(Fe(this.year,4)),t.push(Fe(this.month,2)),t.push(Fe(this.day,2)),t.push(Fe(this.hour,2)),t.push(Fe(this.minute,2)),t.push(Fe(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(Fe(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Nu=es;D.GeneralizedTime=Nu;es.NAME="GeneralizedTime";var _u,ts=class extends It{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};_u=ts;D.DATE=_u;ts.NAME="DATE";var Ru,rs=class extends It{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Ru=rs;D.TimeOfDay=Ru;rs.NAME="TimeOfDay";var Uu,ns=class extends It{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Uu=ns;D.DateTime=Uu;ns.NAME="DateTime";var Du,os=class extends It{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Du=os;D.Duration=Du;os.NAME="Duration";var Pu,ss=class extends It{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Pu=ss;D.TIME=Pu;ss.NAME="TIME";function X(r,e="utf8"){let t=mo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var bn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},as=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ou={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new as("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var zt=Ou;async function Mu(r){let e=await zt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await M0(e);return{privateKey:t[0],publicKey:t[1]}}async function Hu(r,e){let t=await zt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await zt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Fu(r,e,t){let n=await zt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return zt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function M0(r){if(r.privateKey==null||r.publicKey==null)throw new oe("Private and public key are required");return Promise.all([zt.get().subtle.exportKey("jwk",r.privateKey),zt.get().subtle.exportKey("jwk",r.publicKey)])}function Ia(r){if(r.kty!=="RSA")throw new oe("invalid key type");if(r.n==null)throw new oe("invalid key modulus");return Q(r.n,"base64url").length*8}var Pr=class{type="RSA";_key;_raw;_multihash;constructor(e,t){this._key=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=xn.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return Ee.createV1(114,this._multihash)}toString(){return se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:De(this.raw,e.raw)}verify(e,t){return Fu(this._key,t,e)}},En=class{type="RSA";_key;_raw;publicKey;constructor(e,t){this._key=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=xn.jwkToPkcs1(this._key)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:De(this.raw,e.raw)}sign(e){return Hu(this._key,e)}};var cs=8192,Ca=18;function Vu(r){let{result:e}=Sa(r),t=e.valueBlock.value;return{n:ut(t[1]),e:ut(t[2]),d:ut(t[3]),p:ut(t[4]),q:ut(t[5]),dp:ut(t[6]),dq:ut(t[7]),qi:ut(t[8]),kty:"RSA",alg:"RS256"}}function H0(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new oe("JWK was missing components");let t=new St({value:[new Be({value:0}),Be.fromBigInt(ft(Q(r.n,"base64url"))),Be.fromBigInt(ft(Q(r.e,"base64url"))),Be.fromBigInt(ft(Q(r.d,"base64url"))),Be.fromBigInt(ft(Q(r.p,"base64url"))),Be.fromBigInt(ft(Q(r.q,"base64url"))),Be.fromBigInt(ft(Q(r.dp,"base64url"))),Be.fromBigInt(ft(Q(r.dq,"base64url"))),Be.fromBigInt(ft(Q(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function Ku(r){let{result:e}=Sa(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:ut(t[0]),e:ut(t[1])}}function ka(r){if(r.n==null||r.e==null)throw new oe("JWK was missing components");let t=new St({value:[new St({value:[new Ur({value:"1.2.840.113549.1.1.1"}),new _r]}),new Rr({valueHex:new St({value:[Be.fromBigInt(ft(Q(r.n,"base64url"))),Be.fromBigInt(ft(Q(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function ut(r){let e=r.valueBlock.valueHexView;for(;e[0]===0;)e=e.subarray(1);return X(e,"base64url")}function ft(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}function $u(r){let e=Vu(r);return Gu(e)}function Ta(r){let e=Ku(r);if(Ia(e)>cs)throw new yr("Key size is too large");let t=ct(at.encode({Type:we.RSA,Data:r})),n=ke(Ca,t);return new Pr(e,n)}function Gu(r){if(Ia(r)>cs)throw new oe("Key size is too large");let e=qu(r),t=ct(at.encode({Type:we.RSA,Data:ka(e.publicKey)})),n=ke(Ca,t);return new En(e.privateKey,new Pr(e.publicKey,n))}async function Wu(r){if(r>cs)throw new oe("Key size is too large");let e=await Mu(r),t=ct(at.encode({Type:we.RSA,Data:ka(e.publicKey)})),n=ke(Ca,t);return new En(e.privateKey,new Pr(e.publicKey,n))}function qu(r){if(r==null)throw new oe("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var ls=class extends Sr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,en(e);let n=Pt(t);if(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 o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Br(this),this.iHash.update(e),this}digestInto(e){Br(this),Ar(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,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=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Or=(r,e,t)=>new ls(r,e).update(t).digest();Or.create=(r,e)=>new ls(r,e);function zu(r){r.lowS!==void 0&&Ye("lowS",r.lowS),r.prehash!==void 0&&Ye("prehash",r.prehash)}function F0(r){let e=on(r);qe(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:V0,hexToBytes:K0}=so,La=class extends Error{constructor(e=""){super(e)}},Tt={Err:La,_tlv:{encode:(r,e)=>{let{Err:t}=Tt;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=tr(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?tr(o.length/2|128):"";return tr(r)+s+o+e},decode(r,e){let{Err:t}=Tt,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("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 t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Tt;if(r<Lt)throw new e("integer: negative integers are not allowed");let t=tr(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Tt;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return V0(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Tt,o=typeof r=="string"?K0(r):r;Cr(o);let{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:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=Tt,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},Lt=BigInt(0),xe=BigInt(1),hx=BigInt(2),ju=BigInt(3),dx=BigInt(4);function $0(r){let e=F0(r),{Fp:t}=e,n=Vt(e.n,e.nBitLength),o=e.toBytes||((g,h,b)=>{let x=h.toAffine();return Et(Uint8Array.from([4]),t.toBytes(x.x),t.toBytes(x.y))}),s=e.fromBytes||(g=>{let h=g.subarray(1),b=t.fromBytes(h.subarray(0,t.BYTES)),x=t.fromBytes(h.subarray(t.BYTES,2*t.BYTES));return{x:b,y:x}});function i(g){let{a:h,b}=e,x=t.sqr(g),p=t.mul(x,g);return t.add(t.add(p,t.mul(g,h)),b)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return rn(g,xe,e.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:b,wrapPrivateKey:x,n:p}=e;if(h&&typeof g!="bigint"){if(Ht(g)&&(g=wt(g)),typeof g!="string"||!h.includes(g.length))throw new Error("invalid private key");g=g.padStart(b*2,"0")}let S;try{S=typeof g=="bigint"?g:bt(ie("private key",g,b))}catch{throw new Error("invalid private key, expected hex or "+b+" bytes, got "+typeof g)}return x&&(S=Z(S,p)),ve("private key",S,xe,p),S}function l(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let u=nr((g,h)=>{let{px:b,py:x,pz:p}=g;if(t.eql(p,t.ONE))return{x:b,y:x};let S=g.is0();h==null&&(h=S?t.ONE:t.inv(p));let N=t.mul(b,h),L=t.mul(x,h),B=t.mul(p,h);if(S)return{x:t.ZERO,y:t.ZERO};if(!t.eql(B,t.ONE))throw new Error("invZ was invalid");return{x:N,y:L}}),f=nr(g=>{if(g.is0()){if(e.allowInfinityPoint&&!t.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:h,y:b}=g.toAffine();if(!t.isValid(h)||!t.isValid(b))throw new Error("bad point: x or y not FE");let x=t.sqr(b),p=i(h);if(!t.eql(x,p))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,b,x){if(this.px=h,this.py=b,this.pz=x,h==null||!t.isValid(h))throw new Error("x required");if(b==null||!t.isValid(b))throw new Error("y required");if(x==null||!t.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:b,y:x}=h||{};if(!h||!t.isValid(b)||!t.isValid(x))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let p=S=>t.eql(S,t.ZERO);return p(b)&&p(x)?d.ZERO:new d(b,x,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let b=t.invertBatch(h.map(x=>x.pz));return h.map((x,p)=>x.toAffine(b[p])).map(d.fromAffine)}static fromHex(h){let b=d.fromAffine(s(ie("pointHex",h)));return b.assertValidity(),b}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,b){return lo(d,n,h,b)}_setWindowSize(h){y.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(t.isOdd)return!t.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:b,py:x,pz:p}=this,{px:S,py:N,pz:L}=h,B=t.eql(t.mul(b,L),t.mul(S,p)),T=t.eql(t.mul(x,L),t.mul(N,p));return B&&T}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){let{a:h,b}=e,x=t.mul(b,ju),{px:p,py:S,pz:N}=this,L=t.ZERO,B=t.ZERO,T=t.ZERO,C=t.mul(p,p),H=t.mul(S,S),U=t.mul(N,N),M=t.mul(p,S);return M=t.add(M,M),T=t.mul(p,N),T=t.add(T,T),L=t.mul(h,T),B=t.mul(x,U),B=t.add(L,B),L=t.sub(H,B),B=t.add(H,B),B=t.mul(L,B),L=t.mul(M,L),T=t.mul(x,T),U=t.mul(h,U),M=t.sub(C,U),M=t.mul(h,M),M=t.add(M,T),T=t.add(C,C),C=t.add(T,C),C=t.add(C,U),C=t.mul(C,M),B=t.add(B,C),U=t.mul(S,N),U=t.add(U,U),C=t.mul(U,M),L=t.sub(L,C),T=t.mul(U,H),T=t.add(T,T),T=t.add(T,T),new d(L,B,T)}add(h){l(h);let{px:b,py:x,pz:p}=this,{px:S,py:N,pz:L}=h,B=t.ZERO,T=t.ZERO,C=t.ZERO,H=e.a,U=t.mul(e.b,ju),M=t.mul(b,S),V=t.mul(x,N),I=t.mul(p,L),k=t.add(b,x),E=t.add(S,N);k=t.mul(k,E),E=t.add(M,V),k=t.sub(k,E),E=t.add(b,p);let w=t.add(S,L);return E=t.mul(E,w),w=t.add(M,I),E=t.sub(E,w),w=t.add(x,p),B=t.add(N,L),w=t.mul(w,B),B=t.add(V,I),w=t.sub(w,B),C=t.mul(H,E),B=t.mul(U,I),C=t.add(B,C),B=t.sub(V,C),C=t.add(V,C),T=t.mul(B,C),V=t.add(M,M),V=t.add(V,M),I=t.mul(H,I),E=t.mul(U,E),V=t.add(V,I),I=t.sub(M,I),I=t.mul(H,I),E=t.add(E,I),M=t.mul(V,E),T=t.add(T,M),M=t.mul(w,E),B=t.mul(k,B),B=t.sub(B,M),M=t.mul(k,V),C=t.mul(w,C),C=t.add(C,M),new d(B,T,C)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return y.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){let{endo:b,n:x}=e;ve("scalar",h,Lt,x);let p=d.ZERO;if(h===Lt)return p;if(this.is0()||h===xe)return this;if(!b||y.hasPrecomputes(this))return y.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:S,k1:N,k2neg:L,k2:B}=b.splitScalar(h),T=p,C=p,H=this;for(;N>Lt||B>Lt;)N&xe&&(T=T.add(H)),B&xe&&(C=C.add(H)),H=H.double(),N>>=xe,B>>=xe;return S&&(T=T.negate()),L&&(C=C.negate()),C=new d(t.mul(C.px,b.beta),C.py,C.pz),T.add(C)}multiply(h){let{endo:b,n:x}=e;ve("scalar",h,xe,x);let p,S;if(b){let{k1neg:N,k1:L,k2neg:B,k2:T}=b.splitScalar(h),{p:C,f:H}=this.wNAF(L),{p:U,f:M}=this.wNAF(T);C=y.constTimeNegate(N,C),U=y.constTimeNegate(B,U),U=new d(t.mul(U.px,b.beta),U.py,U.pz),p=C.add(U),S=H.add(M)}else{let{p:N,f:L}=this.wNAF(h);p=N,S=L}return d.normalizeZ([p,S])[0]}multiplyAndAddUnsafe(h,b,x){let p=d.BASE,S=(L,B)=>B===Lt||B===xe||!L.equals(p)?L.multiplyUnsafe(B):L.multiply(B),N=S(this,b).add(S(h,x));return N.is0()?void 0:N}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:b}=e;if(h===xe)return!0;if(b)return b(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:b}=e;return h===xe?this:b?b(d,this):this.multiplyUnsafe(e.h)}toRawBytes(h=!0){return Ye("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return Ye("isCompressed",h),wt(this.toRawBytes(h))}}d.BASE=new d(e.Gx,e.Gy,t.ONE),d.ZERO=new d(t.ZERO,t.ONE,t.ZERO);let m=e.nBitLength,y=co(d,e.endo?Math.ceil(m/2):m);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function G0(r){let e=on(r);return qe(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Zu(r){let e=G0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(I){return Z(I,n)}function a(I){return io(I,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=$0({...e,toBytes(I,k,E){let w=k.toAffine(),A=t.toBytes(w.x),v=Et;return Ye("isCompressed",E),E?v(Uint8Array.from([k.hasEvenY()?2:3]),A):v(Uint8Array.from([4]),A,t.toBytes(w.y))},fromBytes(I){let k=I.length,E=I[0],w=I.subarray(1);if(k===o&&(E===2||E===3)){let A=bt(w);if(!rn(A,xe,t.ORDER))throw new Error("Point is not on curve");let v=u(A),_;try{_=t.sqrt(v)}catch(K){let F=K instanceof Error?": "+K.message:"";throw new Error("Point is not on curve"+F)}let R=(_&xe)===xe;return(E&1)===1!==R&&(_=t.neg(_)),{x:A,y:_}}else if(k===s&&E===4){let A=t.fromBytes(w.subarray(0,t.BYTES)),v=t.fromBytes(w.subarray(t.BYTES,2*t.BYTES));return{x:A,y:v}}else{let A=o,v=s;throw new Error("invalid Point, expected length of "+A+", or uncompressed "+v+", got "+k)}}}),d=I=>wt(Ft(I,e.nByteLength));function m(I){let k=n>>xe;return I>k}function y(I){return m(I)?i(-I):I}let g=(I,k,E)=>bt(I.slice(k,E));class h{constructor(k,E,w){this.r=k,this.s=E,this.recovery=w,this.assertValidity()}static fromCompact(k){let E=e.nByteLength;return k=ie("compactSignature",k,E*2),new h(g(k,0,E),g(k,E,2*E))}static fromDER(k){let{r:E,s:w}=Tt.toSig(ie("DER",k));return new h(E,w)}assertValidity(){ve("r",this.r,xe,n),ve("s",this.s,xe,n)}addRecoveryBit(k){return new h(this.r,this.s,k)}recoverPublicKey(k){let{r:E,s:w,recovery:A}=this,v=L(ie("msgHash",k));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let _=A===2||A===3?E+e.n:E;if(_>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let R=A&1?"03":"02",O=c.fromHex(R+d(_)),K=a(_),F=i(-v*K),G=i(w*K),j=c.BASE.multiplyAndAddUnsafe(O,F,G);if(!j)throw new Error("point at infinify");return j.assertValidity(),j}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return rr(this.toDERHex())}toDERHex(){return Tt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return rr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let b={isValidPrivateKey(I){try{return l(I),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let I=Pi(e.n);return Al(e.randomBytes(I),e.n)},precompute(I=8,k=c.BASE){return k._setWindowSize(I),k.multiply(BigInt(3)),k}};function x(I,k=!0){return c.fromPrivateKey(I).toRawBytes(k)}function p(I){let k=Ht(I),E=typeof I=="string",w=(k||E)&&I.length;return k?w===o||w===s:E?w===2*o||w===2*s:I instanceof c}function S(I,k,E=!0){if(p(I))throw new Error("first arg must be private key");if(!p(k))throw new Error("second arg must be public key");return c.fromHex(k).multiply(l(I)).toRawBytes(E)}let N=e.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");let k=bt(I),E=I.length*8-e.nBitLength;return E>0?k>>BigInt(E):k},L=e.bits2int_modN||function(I){return i(N(I))},B=nn(e.nBitLength);function T(I){return ve("num < 2^"+e.nBitLength,I,Lt,B),Ft(I,e.nByteLength)}function C(I,k,E=H){if(["recovered","canonical"].some(ce=>ce in E))throw new Error("sign() legacy options not supported");let{hash:w,randomBytes:A}=e,{lowS:v,prehash:_,extraEntropy:R}=E;v==null&&(v=!0),I=ie("msgHash",I),zu(E),_&&(I=ie("prehashed msgHash",w(I)));let O=L(I),K=l(k),F=[T(K),T(O)];if(R!=null&&R!==!1){let ce=R===!0?A(t.BYTES):R;F.push(ie("extraEntropy",ce))}let G=Et(...F),j=O;function ae(ce){let fe=N(ce);if(!f(fe))return;let Ie=a(fe),Me=c.BASE.multiply(fe).toAffine(),Ue=i(Me.x);if(Ue===Lt)return;let it=i(Ie*i(j+Ue*K));if(it===Lt)return;let dt=(Me.x===Ue?0:2)|Number(Me.y&xe),Zr=it;return v&&m(it)&&(Zr=y(it),dt^=1),new h(Ue,Zr,dt)}return{seed:G,k2sig:ae}}let H={lowS:e.lowS,prehash:!1},U={lowS:e.lowS,prehash:!1};function M(I,k,E=H){let{seed:w,k2sig:A}=C(I,k,E),v=e;return Ni(v.hash.outputLen,v.nByteLength,v.hmac)(w,A)}c.BASE._setWindowSize(8);function V(I,k,E,w=U){let A=I;k=ie("msgHash",k),E=ie("publicKey",E);let{lowS:v,prehash:_,format:R}=w;if(zu(w),"strict"in w)throw new Error("options.strict was renamed to lowS");if(R!==void 0&&R!=="compact"&&R!=="der")throw new Error("format must be compact or der");let O=typeof A=="string"||Ht(A),K=!O&&!R&&typeof A=="object"&&A!==null&&typeof A.r=="bigint"&&typeof A.s=="bigint";if(!O&&!K)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let F,G;try{if(K&&(F=new h(A.r,A.s)),O){try{R!=="compact"&&(F=h.fromDER(A))}catch(dt){if(!(dt instanceof Tt.Err))throw dt}!F&&R!=="der"&&(F=h.fromCompact(A))}G=c.fromHex(E)}catch{return!1}if(!F||v&&F.hasHighS())return!1;_&&(k=e.hash(k));let{r:j,s:ae}=F,ce=L(k),fe=a(ae),Ie=i(ce*fe),Me=i(j*fe),Ue=c.BASE.multiplyAndAddUnsafe(G,Ie,Me)?.toAffine();return Ue?i(Ue.x)===j:!1}return{CURVE:e,getPublicKey:x,getSharedSecret:S,sign:M,verify:V,ProjectivePoint:c,Signature:h,utils:b}}function W0(r){return{hash:r,hmac:(e,...t)=>Or(r,e,Bi(...t)),randomBytes:tn}}function Xu(r,e){let t=n=>Zu({...r,...W0(n)});return{...t(e),create:t}}var Qu=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Yu=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),q0=BigInt(1),Na=BigInt(2),Ju=(r,e)=>(r+e/Na)/e;function z0(r){let e=Qu,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=le(u,t,e)*u%e,d=le(f,t,e)*u%e,m=le(d,Na,e)*l%e,y=le(m,o,e)*m%e,g=le(y,s,e)*y%e,h=le(g,a,e)*g%e,b=le(h,c,e)*h%e,x=le(b,a,e)*g%e,p=le(x,t,e)*u%e,S=le(p,i,e)*y%e,N=le(S,n,e)*l%e,L=le(N,Na,e);if(!_a.eql(_a.sqr(L),r))throw new Error("Cannot find square root");return L}var _a=Vt(Qu,void 0,void 0,{sqrt:z0}),fr=Xu({a:BigInt(0),b:BigInt(7),Fp:_a,n:Yu,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Yu,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-q0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=Ju(s*r,e),c=Ju(-n*r,e),l=Z(r-a*t-c*o,e),u=Z(-a*n-c*s,e),f=l>i,d=u>i;if(f&&(l=e-l),d&&(u=e-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},ct),vx=BigInt(0);var Ax=fr.ProjectivePoint;function be(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=me(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function ef(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function tf(r,e,t){let n=vt.digest(t instanceof Uint8Array?t:t.subarray());if(ef(n))return n.then(({digest:o})=>fr.verify(e,o,r)).catch(o=>{throw new bn(String(o))});try{return fr.verify(e,n.digest,r)}catch(o){throw new bn(String(o))}}var us=class{type="secp256k1";raw;_key;constructor(e){this._key=nf(e),this.raw=rf(this._key)}toMultihash(){return gt.digest(Tr(this))}toCID(){return Ee.createV1(114,this.toMultihash())}toString(){return se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:De(this.raw,e.raw)}verify(e,t){return tf(this._key,t,e)}};function Ra(r){return new us(r)}function rf(r){return fr.ProjectivePoint.fromHex(r).toRawBytes(!0)}function nf(r){try{return fr.ProjectivePoint.fromHex(r),r}catch(e){throw new yr(String(e))}}function vn(r){let{Type:e,Data:t}=at.decode(r),n=t??new Uint8Array;switch(e){case we.RSA:return Ta(n);case we.Ed25519:return $i(n);case we.secp256k1:return Ra(n);default:throw new Jt}}function of(r){let{Type:e,Data:t}=at.decode(r.digest),n=t??new Uint8Array;switch(e){case we.Ed25519:return $i(n);case we.secp256k1:return Ra(n);default:throw new Jt}}function Tr(r){return at.encode({Type:we[r.type],Data:r.raw})}var sf=Symbol.for("nodejs.util.inspect.custom"),Z0=114,An=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()})`}[hi]=!0;toString(){return this.string==null&&(this.string=se.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Ee.createV1(Z0,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return De(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return De(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[sf](){return`PeerId(${this.toString()})`}},Bn=class extends An{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Sn=class extends An{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},In=class extends An{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},X0=2336,fs=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=gt.digest(Q(this.url))}[sf](){return`PeerId(${this.url})`}[hi]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Ee.createV1(X0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=X(e)),e.toString()===this.toString())}};function Mr(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Dt(se.decode(`z${r}`));else{if(e==null)throw new oe('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Dt(e.decode(r))}return Y0(t)}function Ua(r){if(r.type==="Ed25519")return new Sn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new In({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Bn({multihash:r.toCID().multihash,publicKey:r});throw new Jt}function Y0(r){if(Q0(r))return new Bn({multihash:r});if(J0(r))try{let e=of(r);if(e.type==="Ed25519")return new Sn({multihash:r,publicKey:e});if(e.type==="secp256k1")return new In({multihash:r,publicKey:e})}catch{let t=X(r.digest);return new fs(new URL(t))}throw new Zn("Supplied PeerID Multihash is invalid")}function J0(r){return r.code===gt.code}function Q0(r){return r.code===vt.code}var hs=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}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 t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=e,s+=u,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[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];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;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 t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var af=45,em=15,Hr=new hs;function Da(r){if(!(r.length>em))return Hr.new(r).parseWith(()=>Hr.readIPv4Addr())}function Pa(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>af))return Hr.new(r).parseWith(()=>Hr.readIPv6Addr())}function ds(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>af)return;let t=Hr.new(r).parseWith(()=>Hr.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}var M1=parseInt("0xFFFF",16),H1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function ps(r){return!!Da(r)}function ms(r){return!!Pa(r)}function gs(r){return!!ds(r)}var uf=ps,sm=ms,Oa=function(r){let e=0;if(r=r.toString().trim(),uf(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(sm(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=uf(t[n]),i;s&&(i=Oa(t[n]),t[n]=X(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,X(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},ff=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Fr={},Ma={},am=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];am.forEach(r=>{let e=cm(...r);Ma[e.code]=e,Fr[e.name]=e});function cm(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function ee(r){if(typeof r=="number"){if(Ma[r]!=null)return Ma[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Fr[r]!=null)return Fr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var v2=ee("ip4"),A2=ee("ip6"),B2=ee("ipcidr");function Ka(r,e){switch(ee(r).code){case 4:case 41:return um(e);case 42:return Va(e);case 43:return X(e,"base10");case 6:case 273:case 33:case 132:return pf(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Va(e);case 421:return pm(e);case 444:return df(e);case 445:return df(e);case 466:return dm(e);case 481:return globalThis.encodeURIComponent(Va(e));default:return X(e,"base16")}}function $a(r,e){switch(ee(r).code){case 4:return hf(e);case 41:return hf(e);case 42:return Fa(e);case 43:return Q(e,"base10");case 6:case 273:case 33:case 132:return Ga(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Fa(e);case 421:return fm(e);case 444:return mm(e);case 445:return gm(e);case 466:return hm(e);case 481:return Fa(globalThis.decodeURIComponent(e));default:return Q(e,"base16")}}var Ha=Object.values(ar).map(r=>r.decoder),lm=function(){let r=Ha[0].or(Ha[1]);return Ha.slice(2).forEach(e=>r=r.or(e)),r}();function hf(r){if(!gs(r))throw new Error("invalid ip address");return Oa(r)}function um(r){let e=ff(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!gs(e))throw new Error("invalid ip address");return e}function Ga(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function pf(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Fa(r){let e=Q(r),t=Uint8Array.from(ze(e.length));return be([t,e],t.length+e.length)}function Va(r){let e=Ke(r);if(r=r.slice(te(e)),r.length!==e)throw new Error("inconsistent lengths");return X(r)}function fm(r){let e;r[0]==="Q"||r[0]==="1"?e=Dt(se.decode(`z${r}`)).bytes:e=Ee.parse(r).multihash.bytes;let t=Uint8Array.from(ze(e.length));return be([t,e],t.length+e.length)}function hm(r){let e=lm.decode(r),t=Uint8Array.from(ze(e.length));return be([t,e],t.length+e.length)}function dm(r){let e=Ke(r),t=r.slice(te(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+X(t,"base64url")}function pm(r){let e=Ke(r),t=r.slice(te(e));if(t.length!==e)throw new Error("inconsistent lengths");return X(t,"base58btc")}function mm(r){let e=r.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 t=mt.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ga(n);return be([t,o],t.length+o.length)}function gm(r){let e=r.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 t=mt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ga(n);return be([t,o],t.length+o.length)}function df(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=X(e,"base32"),o=pf(t);return`${n}:${o}`}function mf(r){r=Wa(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=ee(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw new ys("invalid address: "+r);if(a.path===!0){n=Wa(o.slice(s).join("/")),e.push([a.code,$a(a.code,n)]),t.push([a.code,n]);break}let c=$a(a.code,o[s]);e.push([a.code,c]),t.push([a.code,Ka(a.code,c)])}return{string:gf(t),bytes:ws(e),tuples:e,stringTuples:t,path:n}}function qa(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=Ke(r,o),i=te(s),a=ee(s),c=ym(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let l=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw new ys("Invalid address Uint8Array: "+X(r,"base16"));e.push([s,l]);let u=Ka(s,l);if(t.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:gf(t),tuples:e,stringTuples:t,path:n}}function gf(r){let e=[];return r.map(t=>{let n=ee(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Wa(e.join("/"))}function ws(r){return be(r.map(e=>{let t=ee(e[0]),n=Uint8Array.from(ze(t.code));return e.length>1&&e[1]!=null&&(n=be([n,e[1]])),n}))}function ym(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=Ke(e instanceof Uint8Array?e:Uint8Array.from(e));return t+te(t)}}function Wa(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}var ys=class extends Error{static name="ParseError";name="ParseError";constructor(e){super(`Error parsing address: ${e}`)}};var wm=Symbol.for("nodejs.util.inspect.custom"),ja=Symbol.for("@multiformats/js-multiaddr/multiaddr"),bm=[ee("dns").code,ee("dns4").code,ee("dns6").code,ee("dnsaddr").code],za=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},bs=class r{bytes;#e;#t;#r;#n;[ja]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=qa(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=mf(e)}else if(wf(e))t=qa(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#r=t.stringTuples,this.#n=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=ee("tcp"),a=ee("udp"),c=ee("ip4"),l=ee("ip6"),u=ee("dns6"),f=ee("ip6zone");for(let[m,y]of this.stringTuples())m===f.code&&(s=`%${y??""}`),bm.includes(m)&&(t=i.name==="tcp"?"tcp":"udp",o=443,n=`${y??""}${s}`,e=m===u.code?6:4),(m===i.code||m===a.code)&&(t=ee(m).name==="tcp"?"tcp":"udp",o=parseInt(y??"")),(m===c.code||m===l.code)&&(t=ee(m).name==="tcp"?"tcp":"udp",n=`${y??""}${s}`,e=m===l.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},ee(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>ee(e).name)}tuples(){return this.#t.map(([e,t])=>t==null?[e]:[e,t])}stringTuples(){return this.#r.map(([e,t])=>t==null?[e]:[e,t])}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(ws(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===Fr.p2p.code&&e.push([n,o]),n===Fr["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?X(se.decode(`z${n}`),"base58btc"):X(Ee.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(e){return De(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=yf.get(t.name);if(n==null)throw new za(`no available resolver for ${t.name}`);return(await n(this,e)).map(s=>ht(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[wm](){return`Multiaddr(${this.#e})`}};var yf=new Map;function wf(r){return!!r?.[ja]}function ht(r){return new bs(r)}var xm=r=>r.toString().split("/").slice(1),Vr=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),W=r=>({match:e=>Vr(t=>t===r).match(e),pattern:r}),hr=()=>({match:r=>Vr(e=>typeof e=="string").match(r),pattern:"{string}"}),Cn=()=>({match:r=>Vr(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),re=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{se.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),kn=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{cn.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Y=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),_e=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),z=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function ue(...r){function e(o){let s=xm(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var Es=z(W("dns4"),hr()),vs=z(W("dns6"),hr()),As=z(W("dnsaddr"),hr()),Xa=z(W("dns"),hr()),tE=ue(Es,Y(re())),rE=ue(vs,Y(re())),nE=ue(As,Y(re())),oE=ue(_e(Xa,As,Es,vs),Y(re())),bf=z(W("ip4"),Vr(ps)),xf=z(W("ip6"),Vr(ms)),Ya=_e(bf,xf),Nt=_e(Ya,Xa,Es,vs,As),sE=ue(_e(Ya,z(_e(Xa,As,Es,vs),Y(re())))),iE=ue(bf),aE=ue(xf),cE=ue(Ya),Ja=z(Nt,W("tcp"),Cn()),Tn=z(Nt,W("udp"),Cn()),lE=ue(z(Ja,Y(re()))),uE=ue(Tn),Qa=z(Tn,W("quic"),Y(re())),Bs=z(Tn,W("quic-v1"),Y(re())),Em=_e(Qa,Bs),fE=ue(Qa),hE=ue(Bs),Za=_e(Nt,Ja,Tn,Qa,Bs),Ef=_e(z(Za,W("ws"),Y(re()))),dE=ue(Ef),vf=_e(z(Za,W("wss"),Y(re())),z(Za,W("tls"),Y(z(W("sni"),hr())),W("ws"),Y(re()))),pE=ue(vf),Af=z(Tn,W("webrtc-direct"),Y(kn()),Y(kn()),Y(re())),Bf=ue(Af),Sf=z(Bs,W("webtransport"),Y(kn()),Y(kn()),Y(re())),mE=ue(Sf),xs=_e(Ef,vf,z(Ja,Y(re())),z(Em,Y(re())),z(Nt,Y(re())),Af,Sf,re()),If=ue(xs),vm=z(xs,W("p2p-circuit"),re()),gE=ue(vm),Am=_e(z(xs,W("p2p-circuit"),W("webrtc"),Y(re())),z(xs,W("webrtc"),Y(re())),z(W("webrtc"),Y(re()))),Cf=ue(Am),Bm=_e(z(Nt,W("tcp"),Cn(),W("http"),Y(re())),z(Nt,W("http"),Y(re()))),yE=ue(Bm),Sm=_e(z(Nt,W("tcp"),_e(z(W("443"),W("http")),z(Cn(),W("https"))),Y(re())),z(Nt,W("tls"),W("http"),Y(re())),z(Nt,W("https"),Y(re()))),wE=ue(Sm),Im=_e(z(W("memory"),hr(),Y(re()))),bE=ue(Im);var kf=function(r,e,t){if(t||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 r.concat(s||Array.prototype.slice.call(e))},Cm=function(){function r(e,t,n){this.name=e,this.version=t,this.os=n,this.type="browser"}return r}();var km=function(){function r(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return r}();var Tm=function(){function r(e,t,n,o){this.name=e,this.version=t,this.os=n,this.bot=o,this.type="bot-device"}return r}();var Lm=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var Nm=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var _m=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Rm=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Tf=3,Um=[["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",_m]],Lf=[["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 _f(r){return r?Nf(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Nm:typeof navigator<"u"?Nf(navigator.userAgent):Om()}function Dm(r){return r!==""&&Um.reduce(function(e,t){var n=t[0],o=t[1];if(e)return e;var s=o.exec(r);return!!s&&[n,s]},!1)}function Nf(r){var e=Dm(r);if(!e)return null;var t=e[0],n=e[1];if(t==="searchbot")return new Lm;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<Tf&&(o=kf(kf([],o,!0),Mm(Tf-o.length),!0)):o=[];var s=o.join("."),i=Pm(r),a=Rm.exec(r);return a&&a[1]?new Tm(t,s,i,a[1]):new Cm(t,s,i)}function Pm(r){for(var e=0,t=Lf.length;e<t;e++){var n=Lf[e],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function Om(){var r=typeof process<"u"&&process.version;return r?new km(process.version.slice(1)):null}function Mm(r){for(var e=[],t=0;t<r;t++)e.push("0");return e}function pe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ec=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},tc=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Rf=r=>globalThis.DOMException===void 0?new tc(r):new DOMException(r),Uf=r=>{let e=r.reason===void 0?Rf("This operation was aborted."):r.reason;return e instanceof Error?e:Rf(e)};function Ln(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,a,l=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:m}=e;m.aborted&&f(Uf(m)),a=()=>{f(Uf(m))},m.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new ec;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(m){f(m)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(d.message=o??`Promise timed out after ${t} milliseconds`,f(d))},t),(async()=>{try{u(await r)}catch(m){f(m)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},l}var Df=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],rc=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Pf="libp2p+webrtc+v1/";var Of=_f(),Nn=Of!=null&&Of.name==="firefox",Ss=async function*(){},Is=async r=>{},Hm=30*1e3;function Mf(r,e,t=Hm,n){r.readyState==="open"&&Promise.resolve().then(async()=>{if(r.bufferedAmount>0){n.log("%s drain channel with %d buffered bytes",e,r.bufferedAmount);let o=pe(),s=!1;r.bufferedAmountLowThreshold=0;let i=()=>{s||(n.log("%s drain channel closed before drain",e),o.resolve())};r.addEventListener("close",i,{once:!0}),r.addEventListener("bufferedamountlow",()=>{s=!0,r.removeEventListener("close",i),o.resolve()}),await Ln(o.promise,{milliseconds:t})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function nc(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??Df.map(e=>({urls:[e]})),r}var Hf=(r=32)=>Pf+[...Array(r)].map(()=>rc.at(Math.floor(Math.random()*rc.length))).join("");var dr=class{log;peerConnection;remoteAddr;timeline;metrics;source=Ss();sink=Is;constructor(e,t){this.log=e.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=t.remoteAddr,this.timeline=t.timeline,this.peerConnection=t.peerConnection;let n=this.peerConnection,o=n.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",n.connectionState,"initial state",o),(n.connectionState==="disconnected"||n.connectionState==="failed"||n.connectionState==="closed")&&(this.timeline.close=Date.now())}}async close(e){this.log.trace("closing connection"),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({close:!0})}abort(e){this.log.error("closing connection due to error",e),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({abort:!0})}};var Cs=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Kr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Cs(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Cs(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var oc=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function jt(r={}){return Fm(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Fm(r,e){e=e??{};let t=e.onEnd,n=new Kr,o,s,i,a=pe(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,b)=>{s=x=>{s=null,n.push(x);try{h(r(n))}catch(p){b(p)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=pe()})}},l=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new Kr,s!=null?s({error:h}):(n.push({error:h}),o)),f=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 l({done:!1,value:h})},d=h=>i?o:(i=!0,h!=null?u(h):l({done:!0})),m=()=>(n=new Kr,d(),{done:!0}),y=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:y,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let b=h?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let x,p;b!=null&&(x=new Promise((S,N)=>{p=()=>{N(new oc)},b.addEventListener("abort",p)}));try{await Promise.race([a.promise,x])}finally{p!=null&&b!=null&&b?.removeEventListener("abort",p)}}},t==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(h){return g.throw(h),t!=null&&(t(h),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(h){return g.end(h),t!=null&&(t(h),t=void 0),o},get readableLength(){return g.readableLength},onEmpty:h=>g.onEmpty(h)},o}var ks=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function st(r,e,t){if(e==null)return r;if(e.aborted){let s=Promise.reject(new ks(t?.errorMessage,t?.errorCode,t?.errorName));return Promise.race([s,Promise.resolve().then(async()=>{try{await r}catch{}return s})])}let n,o=new ks(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Vf=Symbol.for("@achingbrain/uint8arraylist");function Ff(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Ts(r){return!!r?.[Vf]}var ne=class r{bufs;length;[Vf]=!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 t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Ts(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Ts(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Ff(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Ff(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Ts(e))for(let n=0;n<e.length;n++)this.set(t+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,t){let{bufs:n,length:o}=this._subList(e,t);return be(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:be(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===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 l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Ts(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(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;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 f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let m=this.get(f+d);if(n[d]!==m){u=Math.max(1,d-a[m]);break}}if(u===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=me(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=ye(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=ye(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=ye(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=me(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=ye(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=ye(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=ye(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=ye(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=ye(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!De(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};function Kf(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function $f(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Gf(r,e){let t=Kf(r).return?.();$f(t)&&t.catch(n=>{e.error("could not cause iterator to return",n)})}var Vm=5e3;function sc(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ls=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=pe(),this.closed=pe(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??Vm,this.onEnd=e.onEnd,this.onCloseRead=e?.onCloseRead,this.onCloseWrite=e?.onCloseWrite,this.onReset=e?.onReset,this.onAbort=e?.onAbort,this.source=this.streamSource=jt({onEnd:t=>{t!=null?this.log.trace("source ended with error",t):this.log.trace("source ended"),this.onSourceEnd(t)}}),this.sink=this.sink.bind(this)}async sink(e){if(this.writeStatus!=="ready")throw new Yt(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";let t={signal:this.sinkController.signal};if(this.direction==="outbound"){let o=this.sendNewStream(t);sc(o)&&await o}let n=()=>{Gf(e,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let o of e){o=o instanceof Uint8Array?new ne(o):o;let s=this.sendData(o,t);sc(s)&&(this.sendingData=pe(),await s,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",n)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(t){throw this.log.trace("sink ended with error, calling abort with error",t),this.abort(t),t}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){this.status==="open"&&(this.log.trace("closing gracefully"),this.status="closing",await st(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(e={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let t=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),t==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await st(this.sink([]),e.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await st(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await st(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",e),this.log("try to send reset to remote");let t=this.sendReset();sc(t)&&t.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let e=new jn("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}};function ic(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var Ns=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},$r=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},_s=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},_n=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Rs(r){return r[Symbol.asyncIterator]!=null}function Wf(r,e){if(r.byteLength>e)throw new $r("Message length too long")}var Ds=r=>{let e=te(r),t=me(e);return ze(r,t),Ds.bytes=e,t};Ds.bytes=0;function Rn(r,e){e=e??{};let t=e.lengthEncoder??Ds,n=e?.maxDataLength??4194304;function*o(s){Wf(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Rs(r)?async function*(){for await(let s of r)yield*o(s)}():function*(){for(let s of r)yield*o(s)}()}Rn.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Ds,n=e?.maxDataLength??4194304;return Wf(r,n),new ne(t(r.byteLength),r)};var pr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(pr||(pr={}));var ac=r=>{let e=Ke(r);return ac.bytes=te(e),e};ac.bytes=0;function Un(r,e){let t=new ne,n=pr.LENGTH,o=-1,s=e?.lengthDecoder??ac,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===pr.LENGTH)try{if(o=s(t),o<0)throw new Ns("Invalid message length");if(o>a)throw new $r("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=pr.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new _s("Message length length too long");break}throw l}if(n===pr.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=pr.LENGTH}}}return Rs(r)?async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new _n("Unexpected end of input")}():function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new _n("Unexpected end of input")}()}Un.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return Un(n,{...e??{},onLength:s=>{t=s}})};var cc=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Dn(r,e,t,n){let o=new cc(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){t?.removeEventListener("abort",u),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),i(d);return}a(),s(f)},l=f=>{a(),i(f.detail)},u=()=>{a(),i(o)};t?.addEventListener("abort",u),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var Oe;(function(r){let e;(function(o){o.FIN="FIN",o.STOP_SENDING="STOP_SENDING",o.RESET="RESET",o.FIN_ACK="FIN_ACK"})(e=r.Flag||(r.Flag={}));let t;(function(o){o[o.FIN=0]="FIN",o[o.STOP_SENDING=1]="STOP_SENDING",o[o.RESET=2]="RESET",o[o.FIN_ACK=3]="FIN_ACK"})(t||(t={})),function(o){o.codec=()=>lr(t)}(e=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=nt((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.flag!=null&&(s.uint32(8),r.Flag.codec().encode(o.flag,s)),o.message!=null&&(s.uint32(18),s.bytes(o.message)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.flag=r.Flag.codec().decode(o);break}case 2:{a.message=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>rt(o,r.codec()),r.decode=(o,s)=>tt(o,r.codec(),s)})(Oe||(Oe={}));var Gm=2*1024*1024,Wm=30*1e3,Pn=16*1024;function qm(r=Pn){let e=te(r-te(r)),t=1+te(Object.keys(Oe.Flag).length-1),n=1,o=r-e-t-n,s=te(o);return e+t+n+s}var zm=qm(),jm=5e3,Zm=5e3,lc=class extends Ls{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;closeController;constructor(e){let t=e.onEnd;switch(e.onEnd=o=>{this.log.trace("readable and writeable ends closed",this.status),Promise.resolve(async()=>{if(!(this.timeline.abort!=null||this.timeline.reset!==null))try{await Ln(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(s){this.log.error("error receiving FIN_ACK",s)}}).then(()=>{this.incomingData.end(),this.channel.close(),t?.(o)}).catch(s=>{this.log.error("error ending stream",s)})},super(e),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=jt(),this.bufferedAmountLowEventTimeout=e.bufferedAmountLowEventTimeout??Wm,this.maxBufferedAmount=e.maxBufferedAmount??Gm,this.maxMessageSize=(e.maxMessageSize??Pn)-zm,this.receiveFinAck=pe(),this.finAckTimeout=e.closeTimeout??jm,this.openTimeout=e.openTimeout??Zm,this.closeController=new AbortController,this.channel.readyState){case"open":this.timeline.open=new Date().getTime();break;case"closed":case"closing":(this.timeline.close===void 0||this.timeline.close===0)&&(this.timeline.close=Date.now());break;case"connecting":break;default:throw this.log.error("unknown datachannel state %s",this.channel.readyState),new Yt("Unknown datachannel state")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime()},this.channel.onclose=o=>{this.log.trace("received onclose event"),this.closeController.abort(),this.receiveFinAck.resolve(),this.close().catch(s=>{this.log.error("error closing stream after channel closed",s)})},this.channel.onerror=o=>{this.log.trace("received onerror event"),this.closeController.abort();let s=o.error;this.abort(s)},this.channel.onmessage=async o=>{let{data:s}=o;s===null||s.byteLength===0||this.incomingData.push(new Uint8Array(s,0,s.byteLength))};let n=this;Promise.resolve().then(async()=>{for await(let o of Un(this.incomingData)){let s=n.processIncomingProtobuf(o);s!=null&&n.sourcePush(new ne(s))}}).catch(o=>{this.log.error("error processing incoming data channel messages",o)})}sendNewStream(){}async _sendMessage(e,t=!0){if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new Yt(`Invalid datachannel state - ${this.channel.readyState}`);if(this.channel.readyState!=="open"){let n=AbortSignal.timeout(this.openTimeout),o=ic([this.closeController.signal,n]);try{this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await Dn(this.channel,"open",o)}finally{o.clear()}this.log('channel state is now "%s", sending data',this.channel.readyState)}if(t&&this.channel.bufferedAmount>this.maxBufferedAmount){let n=AbortSignal.timeout(this.bufferedAmountLowEventTimeout),o=ic([this.closeController.signal,n]);try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await Dn(this.channel,"bufferedamountlow",o)}catch(s){throw n.aborted?new Yn(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`):s}finally{o.clear()}}try{this.channel.send(e.subarray())}catch(n){this.log.error("error while sending message",n)}}async sendData(e){for(this.log.trace("-> will send %d bytes",e.byteLength),e=e.sublist();e.byteLength>0;){let t=Math.min(e.byteLength,this.maxMessageSize),n=e.subarray(0,t),o=Oe.encode({message:n}),s=Rn.single(o);this.log.trace("-> sending message %s",this.channel.readyState),await this._sendMessage(s),this.log.trace("-> sent message %s",this.channel.readyState),e.consume(t)}this.log.trace("-> sent data %s",this.channel.readyState)}async sendReset(){try{await this._sendFlag(Oe.Flag.RESET)}catch(e){this.log.error("failed to send reset - %e",e)}}async sendCloseWrite(e){if(this.channel.readyState!=="open"){this.receiveFinAck.resolve();return}if(await this._sendFlag(Oe.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await st(this.receiveFinAck.promise,e?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorName:"FinAckNotReceivedError"})}catch(n){this.log.error("failed to await FIN_ACK",n)}}else this.log.trace("sending FIN failed, not awaiting FIN_ACK");this.receiveFinAck.resolve()}async sendCloseRead(){this.channel.readyState==="open"&&await this._sendFlag(Oe.Flag.STOP_SENDING)}processIncomingProtobuf(e){let t=Oe.decode(e);if(t.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',t.flag,this.writeStatus,this.readStatus),t.flag===Oe.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Oe.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),t.flag===Oe.Flag.RESET&&this.reset(),t.flag===Oe.Flag.STOP_SENDING&&this.remoteCloseRead(),t.flag===Oe.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),this.readStatus==="ready")return t.message}async _sendFlag(e){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',this.channel.readyState,e.toString()),!1;this.log.trace("sending flag %s",e.toString());let t=Oe.encode({flag:e}),n=Rn.single(t);try{return await this._sendMessage(n,!1),!0}catch(o){this.log.error("could not send flag %s - %e",e.toString(),o)}return!1}};function Gr(r){let{channel:e,direction:t}=r;return new lc({id:t==="inbound"?`i${e.id}`:`r${e.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${t}:${e.id}`),...r})}var qf="/webrtc",Zt=class{protocol;peerConnection;bufferedStreams=[];metrics;dataChannelOptions;components;log;constructor(e,t){this.components=e,this.peerConnection=t.peerConnection,this.metrics=t.metrics,this.protocol=t.protocol??qf,this.dataChannelOptions=t.dataChannelOptions??{},this.log=e.logger.forComponent("libp2p:webrtc:muxerfactory"),this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace('incoming early datachannel with channel id %d and label "%s"',n.id),n.label==="init"){this.log.trace("closing early init channel"),n.close();return}let o={},s=Gr({channel:n,direction:"inbound",onEnd:i=>{o.onEnd(i)},logger:e.logger,...this.dataChannelOptions});o.stream=s,o.channel=n,o.onEnd=()=>{this.bufferedStreams=this.bufferedStreams.filter(i=>i.stream.id!==s.id)},this.bufferedStreams.push(o)}}createStreamMuxer(e){return new uc(this.components,{...e,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},uc=class{init;streams;protocol;log;peerConnection;dataChannelOptions;metrics;logger;constructor(e,t){this.init=t,this.log=e.logger.forComponent("libp2p:webrtc:muxer"),this.logger=e.logger,this.streams=t.streams.map(n=>n.stream),this.peerConnection=t.peerConnection,this.protocol=t.protocol??qf,this.metrics=t.metrics,this.dataChannelOptions=t.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace("incoming datachannel with channel id %d",n.id),n.label==="init"){this.log.trace("closing init channel"),n.close();return}let o=n.id,s=Gr({channel:n,direction:"inbound",onEnd:()=>{this.#e(s,n),this.log("incoming channel %s ended",o)},logger:this.logger,...this.dataChannelOptions});this.streams.push(s),this.metrics?.increment({incoming_stream:!0}),t?.onIncomingStream?.(s)},this.init.streams.length>0&&queueMicrotask(()=>{this.init.streams.forEach(n=>{n.onEnd=()=>{this.log("incoming early channel %s ended with state %s",n.channel.id,n.channel.readyState),this.#e(n.stream,n.channel)},this.metrics?.increment({incoming_stream:!0}),this.init?.onIncomingStream?.(n.stream)})})}#e(e,t){this.log.trace("stream %s %s %s onEnd",e.direction,e.id,e.protocol),Mf(t,`${e.direction} ${e.id} ${e.protocol}`,this.dataChannelOptions.drainTimeout,{log:this.log}),this.streams=this.streams.filter(n=>n.id!==e.id),this.metrics?.increment({stream_end:!0}),this.init?.onStreamEnd?.(e)}async close(e){try{await Promise.all(this.streams.map(async t=>t.close(e)))}catch(t){this.abort(t)}}abort(e){for(let t of this.streams)t.abort(e)}source=Ss();sink=Is;newStream(){let e=this.peerConnection.createDataChannel(""),t=e.id;this.log.trace("opened outgoing datachannel with channel id %s",t);let n=Gr({channel:e,direction:"outbound",onEnd:()=>{this.#e(n,e),this.log("outgoing channel %s ended",t)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(n),this.metrics?.increment({outgoing_stream:!0}),n}};var Ps=globalThis.RTCPeerConnection,Os=globalThis.RTCSessionDescription,zf=globalThis.RTCIceCandidate;var fc=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=pe(),this.haveNext=pe()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=pe(),e}async throw(e){return this.ended=!0,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=pe(),await st(this.readNext.promise,t?.signal,t)}};function jf(){return new fc}var Ms=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var hc=class extends Error{code;constructor(e,t){super(e),this.code=t}},dc=class extends hc{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Zf(r,e){let t=jf();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new ne;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new dc("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:d}=await Promise.race([n.next(),l]);return f===!0?new ne:d}for(;o.byteLength<i;){let{value:f,done:d}=await Promise.race([n.next(),l]);if(d===!0)throw new Ms("unexpected end of input");o.append(f)}let u=o.sublist(0,i);return o.consume(i),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Hs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Fs=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Vs=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function On(r,e={}){let t=Zf(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=te(e.maxDataLength));let n=e?.lengthDecoder??Ke,o=e?.lengthEncoder??ze;return{read:async i=>{let a=-1,c=new ne;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Hs("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Vs("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Fs("message length too long");return t.read(a,i)},write:async(i,a)=>{await t.write(new ne(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new ne(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap:()=>t.unwrap()}}function Ks(r,e){let t=On(r,e),n={read:async(o,s)=>{let i=await t.read(s);return o.decode(i)},write:async(o,s,i)=>{await t.write(s.encode(o),i)},writeV:async(o,s,i)=>{await t.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:()=>t.unwrap()};return n}var Ge=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Xt=class extends Error{constructor(e){super(`WebRTC transport error: ${e}`),this.name="WebRTCTransportError"}},Ze=class extends Xt{constructor(e="SDP handshake failed"){super(e),this.name="SDPHandshakeFailedError"}};var $s=class extends Xt{constructor(e,t){super(`Invalid fingerprint "${e}" within ${t}`),this.name="WebRTC/InvalidFingerprintError"}};var Gs=class extends Xt{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},Ws=class extends Xt{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 Ve;(function(r){let e;(function(o){o.SDP_OFFER="SDP_OFFER",o.SDP_ANSWER="SDP_ANSWER",o.ICE_CANDIDATE="ICE_CANDIDATE"})(e=r.Type||(r.Type={}));let t;(function(o){o[o.SDP_OFFER=0]="SDP_OFFER",o[o.SDP_ANSWER=1]="SDP_ANSWER",o[o.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(t||(t={})),function(o){o.codec=()=>lr(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=nt((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.data!=null&&(s.uint32(18),s.string(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.data=o.string();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>rt(o,r.codec()),r.decode=(o,s)=>tt(o,r.codec(),s)})(Ve||(Ve={}));var qs=async(r,e,t)=>{try{let n=pe();for(Xm(r,n);;){let o=await Promise.race([n.promise,e.read({signal:t.signal}).catch(()=>{})]);if(o==null){t.signal?.throwIfAborted();break}if(o.type!==Ve.Type.ICE_CANDIDATE)throw new Xn("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){t.onProgress?.(new Ge("webrtc:end-of-ice-candidates")),t.log.trace("end-of-candidates received");continue}let i=new zf(s);t.log.trace("%s received new ICE candidate %o",t.direction,s);try{t.onProgress?.(new Ge("webrtc:add-ice-candidate",i.candidate)),await r.addIceCandidate(i)}catch(a){t.log.error("%s bad candidate received",t.direction,s,a)}}}catch(n){if(t.log.error("%s error parsing ICE candidate",t.direction,n),t.signal?.aborted===!0&&zs(r)!=="connected")throw n}};function zs(r){return Nn?r.iceConnectionState:r.connectionState}function Xm(r,e){r[Nn?"oniceconnectionstatechange":"onconnectionstatechange"]=t=>{switch(zs(r)){case"connected":e.resolve();break;case"failed":case"disconnected":case"closed":e.reject(new zn("RTCPeerConnection was closed"));break;default:break}}}async function Xf({rtcConfiguration:r,dataChannel:e,signal:t,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=Yf(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",u);let f=u.getPeerId();if(f==null)throw new oe("Relay peer was missing");let d=s.getConnections(Mr(f)),m,y=!1;d.length===0?(l?.(new Ge("webrtc:dial-relay")),m=await i.dial(u,{signal:t,onProgress:l}),y=!0):(l?.(new Ge("webrtc:reuse-relay-connection")),m=d[0]);try{l?.(new Ge("webrtc:open-signaling-stream"));let g=await m.newStream(js,{signal:t,runOnLimitedConnection:!0}),h=Ks(g).pb(Ve),b=new Ps(r),x=new Zt({logger:c},{peerConnection:b,dataChannelOptions:e});try{let p=b.createDataChannel("init");b.onicecandidate=({candidate:B})=>{let T=JSON.stringify(B?.toJSON()??null);a.trace("initiator sending ICE candidate %o",B),h.write({type:Ve.Type.ICE_CANDIDATE,data:T},{signal:t}).catch(C=>{a.error("error sending ICE candidate",C)})},b.onicecandidateerror=B=>{a.error("initiator ICE candidate error",B)};let S=await b.createOffer().catch(B=>{throw a.error("could not execute createOffer",B),new Ze("Failed to set createOffer")});a.trace("initiator send SDP offer %s",S.sdp),l?.(new Ge("webrtc:send-sdp-offer")),await h.write({type:Ve.Type.SDP_OFFER,data:S.sdp},{signal:t}),await b.setLocalDescription(S).catch(B=>{throw a.error("could not execute setLocalDescription",B),new Ze("Failed to set localDescription")}),l?.(new Ge("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let N=await h.read({signal:t});if(N.type!==Ve.Type.SDP_ANSWER)throw new Ze("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",N.data);let L=new Os({type:"answer",sdp:N.data});return await b.setRemoteDescription(L).catch(B=>{throw a.error("could not execute setRemoteDescription",B),new Ze("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),l?.(new Ge("webrtc:read-ice-candidates")),await qs(b,h,{direction:"initiator",signal:t,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),p.close(),l?.(new Ge("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await g.close({signal:t}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:b,muxerFactory:x}}catch(p){throw a.error("outgoing signaling error",p),b.close(),g.abort(p),p}finally{b.onicecandidate=null,b.onicecandidateerror=null}}finally{if(y)try{await m.close({signal:t})}catch(g){m.abort(g)}}}var Ym=ue(If.matchers[0],W("p2p-circuit")),Zs=class r extends wr{transportManager;shutdownController;constructor(e,t){super(),this.transportManager=e.transportManager,this.shutdownController=t.shutdownController}async listen(){queueMicrotask(()=>{this.safeDispatchEvent("listening")})}getAddrs(){return this.transportManager.getListeners().filter(e=>!(e instanceof r)).map(e=>e.getAddrs().filter(t=>Ym.exactMatch(t)).map(t=>t.encapsulate("/webrtc"))).flat()}updateAnnounceAddrs(){}async close(){this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function Jf({peerConnection:r,stream:e,signal:t,connection:n,log:o}){o.trace("new inbound signaling stream");let s=Ks(e).pb(Ve);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:Ve.Type.ICE_CANDIDATE,data:f},{signal:t}).catch(d=>{o.error("error sending ICE candidate",d)})},o.trace("recipient read SDP offer");let a=await s.read({signal:t});if(a.type!==Ve.Type.SDP_OFFER)throw new Ze(`expected message type SDP_OFFER, received: ${a.type??"undefined"} `);o.trace("recipient received SDP offer %s",a.data);let c=new Os({type:"offer",sdp:a.data});await r.setRemoteDescription(c).catch(u=>{throw o.error("could not execute setRemoteDescription",u),new Ze("Failed to set remoteDescription")});let l=await r.createAnswer().catch(u=>{throw o.error("could not execute createAnswer",u),new Ze("Failed to create answer")});o.trace("recipient send SDP answer %s",l.sdp),await s.write({type:Ve.Type.SDP_ANSWER,data:l.sdp},{signal:t}),await r.setLocalDescription(l).catch(u=>{throw o.error("could not execute setLocalDescription",u),new Ze("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await qs(r,s,{direction:"recipient",signal:t,log:o})}catch(a){if(zs(r)!=="connected")throw o.error("error while handling signaling stream from peer %a",n.remoteAddr,a),r.close(),a;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",n.remoteAddr,a)}let i=ht(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return o.trace("recipient connected to remote address %s",i),{remoteAddress:i}}var Jm="/webrtc",Qm="/p2p-circuit",js="/webrtc-signaling/0.0.1",eg=30*1e3,Xs=class{components;init;log;_started=!1;metrics;shutdownController;constructor(e,t={}){this.components=e,this.init=t,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"})})}[Wn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[br]=["@libp2p/transport"];[Xc]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(js,e=>{this._onProtocol(e).catch(t=>{this.log.error("failed to handle incoming connect from %p",e.connection.remotePeer,t)})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(js),this._started=!1}createListener(e){return new Zs(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(Cf.exactMatch)}dialFilter(e){return this.listenFilter(e)}async dial(e,t){this.log.trace("dialing address: %a",e);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await Xf({rtcConfiguration:await nc(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:e,dataChannelOptions:this.init.dataChannel,signal:t.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:t.onProgress}),i=new dr(this.components,{peerConnection:o,timeline:{open:Date.now()},remoteAddr:n,metrics:this.metrics?.dialerEvents}),a=await t.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,muxerFactory:s,onProgress:t.onProgress});return this._closeOnShutdown(o,i),a}async _onProtocol({connection:e,stream:t}){let n=AbortSignal.timeout(this.init.inboundConnectionTimeout??eg),o=new Ps(await nc(this.init.rtcConfiguration)),s=new Zt(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await Jf({peerConnection:o,connection:e,stream:t,signal:n,log:this.log});await t.close({signal:n});let a=new dr(this.components,{peerConnection:o,timeline:{open:new Date().getTime()},remoteAddr:i,metrics:this.metrics?.listenerEvents});await this.components.upgrader.upgradeInbound(a,{skipEncryption:!0,skipProtection:!0,muxerFactory:s}),this._closeOnShutdown(o,a)}catch(i){throw this.log.error("incoming signaling error",i),o.close(),t.abort(i),i}}_closeOnShutdown(e,t){let n=()=>{t.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection",o)})};this.shutdownController.signal.addEventListener("abort",n),e.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function Yf(r){let e=r.toString().split(Jm+"/");if(e.length!==2)throw new oe("webrtc protocol was not present in multiaddr");if(!e[0].includes(Qm))throw new oe("p2p-circuit protocol was not present in multiaddr");let t=ht(e[0]),o=ht("/"+e[1]).getPeerId();if(o==null)throw new oe("destination peer id was missing");let s=t.protos().pop();if(s===void 0)throw new oe("invalid multiaddr");return s.name!=="p2p"&&(t=t.encapsulate(`/p2p/${o}`)),{baseAddr:t,peerId:Mr(o)}}var Ys=class extends wr{async listen(){throw new Gs("WebRTCTransport.createListener")}getAddrs(){return[]}updateAnnounceAddrs(){}async close(){}};function Js(r){return r[Symbol.asyncIterator]!=null}var Qs=r=>{let e=te(r),t=me(e);return ze(r,t),Qs.bytes=e,t};Qs.bytes=0;function Qf(r,e){e=e??{};let t=e.lengthEncoder??Qs;function*n(o){let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Js(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Qf.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Qs;return new ne(t(r.byteLength),r)};var ei=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ti=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ri=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Mn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var tg=8,rg=1024*1024*4,mr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(mr||(mr={}));var pc=r=>{let e=Ke(r);return pc.bytes=te(e),e};pc.bytes=0;function Hn(r,e){let t=new ne,n=mr.LENGTH,o=-1,s=e?.lengthDecoder??pc,i=e?.maxLengthLength??tg,a=e?.maxDataLength??rg;function*c(){for(;t.byteLength>0;){if(n===mr.LENGTH)try{if(o=s(t),o<0)throw new ei("Invalid message length");if(o>a)throw new ti("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=mr.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new ri("Message length length too long");break}throw l}if(n===mr.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=mr.LENGTH}}}return Js(r)?async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Mn("Unexpected end of input")}():function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Mn("Unexpected end of input")}()}Hn.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return Hn(n,{...e??{},onLength:s=>{t=s}})};function mc(){let r=pe(),e=!1;return{sink:async t=>{if(e)throw new Error("already piped");e=!0,r.resolve(t)},source:async function*(){yield*await r.promise}()}}function eh(){let r=mc(),e=mc();return[{source:r.source,sink:e.sink},{source:e.source,sink:r.sink}]}function ng(r){return r[Symbol.asyncIterator]!=null}function og(...r){let e=[];for(let t of r)ng(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=jt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var th=og;function rh(r,...e){if(r==null)throw new Error("Empty pipeline");if(gc(r)){let n=r;r=()=>n.source}else if(oh(r)||nh(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&gc(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)gc(t[n])&&(t[n]=ig(t[n]));return sg(...t)}var sg=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},nh=r=>r?.[Symbol.asyncIterator]!=null,oh=r=>r?.[Symbol.iterator]!=null,gc=r=>r==null?!1:r.sink!=null&&r.source!=null,ig=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=jt({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(nh(s))o=async function*(){yield*s,n.end()};else if(oh(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return th(n,o())}return r.source};var Wr=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function ni(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function yc(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Re(r,...e){if(!yc(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function wc(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function sh(r,e){Re(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function bc(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}var _t=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),ih=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ag=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!ag)throw new Error("Non little-endian hardware is not supported");function cg(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function oi(r){if(typeof r=="string")r=cg(r);else if(yc(r))r=si(r);else throw new Error("Uint8Array expected, got "+typeof r);return r}function ah(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function ch(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}var xc=(r,e)=>{function t(n,...o){if(Re(n),r.nonceLength!==void 0){let u=o[0];if(!u)throw new Error("nonce / iv required");r.varSizeNonce?Re(u):Re(u,r.nonceLength)}let s=r.tagLength;s&&o[1]!==void 0&&Re(o[1]);let i=e(n,...o),a=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");Re(f)}},c=!1;return{encrypt(u,f){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Re(u),a(i.encrypt.length,f),i.encrypt(u,f)},decrypt(u,f){if(Re(u),s&&u.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(i.decrypt.length,f),i.decrypt(u,f)}}}return Object.assign(t,r),t};function Ec(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(e.length!==r)throw new Error("invalid output length, expected "+r+", got: "+e.length);if(t&&!lg(e))throw new Error("invalid output, must be aligned");return e}function vc(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,l=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+l,a,n)}function lg(r){return r.byteOffset%4===0}function si(r){return Uint8Array.from(r)}function Rt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}var uh=r=>Uint8Array.from(r.split("").map(e=>e.charCodeAt(0))),ug=uh("expand 16-byte k"),fg=uh("expand 32-byte k"),hg=_t(ug),dg=_t(fg);function P(r,e){return r<<e|r>>>32-e}function Ac(r){return r.byteOffset%4===0}var ii=64,pg=16,fh=2**32-1,lh=new Uint32Array;function mg(r,e,t,n,o,s,i,a){let c=o.length,l=new Uint8Array(ii),u=_t(l),f=Ac(o)&&Ac(s),d=f?_t(o):lh,m=f?_t(s):lh;for(let y=0;y<c;i++){if(r(e,t,n,u,i,a),i>=fh)throw new Error("arx: counter overflow");let g=Math.min(ii,c-y);if(f&&g===ii){let h=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let b=0,x;b<pg;b++)x=h+b,m[x]=d[x]^u[b];y+=ii;continue}for(let h=0,b;h<g;h++)b=y+h,s[b]=o[b]^l[h];y+=g}}function Bc(r,e){let{allowShortKeys:t,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=ah({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return ni(o),ni(i),bc(s),bc(t),(a,c,l,u,f=0)=>{Re(a),Re(c),Re(l);let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),Re(u),ni(f),f<0||f>=fh)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let m=[],y=a.length,g,h;if(y===32)m.push(g=si(a)),h=dg;else if(y===16&&t)g=new Uint8Array(32),g.set(a),g.set(a,16),h=hg,m.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${y}`);Ac(c)||m.push(c=si(c));let b=_t(g);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,b,_t(c.subarray(0,16)),b),c=c.subarray(16)}let x=16-o;if(x!==c.length)throw new Error(`arx: nonce must be ${x} or 16 bytes`);if(x!==12){let S=new Uint8Array(12);S.set(c,s?0:12-c.length),c=S,m.push(c)}let p=_t(c);return mg(r,h,b,p,l,u,f,i),Rt(...m),u}}var Se=(r,e)=>r[e++]&255|(r[e++]&255)<<8,Sc=class{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=oi(e),Re(e,32);let t=Se(e,0),n=Se(e,2),o=Se(e,4),s=Se(e,6),i=Se(e,8),a=Se(e,10),c=Se(e,12),l=Se(e,14);this.r[0]=t&8191,this.r[1]=(t>>>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|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Se(e,16+2*u)}process(e,t,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],d=i[5],m=i[6],y=i[7],g=i[8],h=i[9],b=Se(e,t+0),x=Se(e,t+2),p=Se(e,t+4),S=Se(e,t+6),N=Se(e,t+8),L=Se(e,t+10),B=Se(e,t+12),T=Se(e,t+14),C=s[0]+(b&8191),H=s[1]+((b>>>13|x<<3)&8191),U=s[2]+((x>>>10|p<<6)&8191),M=s[3]+((p>>>7|S<<9)&8191),V=s[4]+((S>>>4|N<<12)&8191),I=s[5]+(N>>>1&8191),k=s[6]+((N>>>14|L<<2)&8191),E=s[7]+((L>>>11|B<<5)&8191),w=s[8]+((B>>>8|T<<8)&8191),A=s[9]+(T>>>5|o),v=0,_=v+C*a+H*(5*h)+U*(5*g)+M*(5*y)+V*(5*m);v=_>>>13,_&=8191,_+=I*(5*d)+k*(5*f)+E*(5*u)+w*(5*l)+A*(5*c),v+=_>>>13,_&=8191;let R=v+C*c+H*a+U*(5*h)+M*(5*g)+V*(5*y);v=R>>>13,R&=8191,R+=I*(5*m)+k*(5*d)+E*(5*f)+w*(5*u)+A*(5*l),v+=R>>>13,R&=8191;let O=v+C*l+H*c+U*a+M*(5*h)+V*(5*g);v=O>>>13,O&=8191,O+=I*(5*y)+k*(5*m)+E*(5*d)+w*(5*f)+A*(5*u),v+=O>>>13,O&=8191;let K=v+C*u+H*l+U*c+M*a+V*(5*h);v=K>>>13,K&=8191,K+=I*(5*g)+k*(5*y)+E*(5*m)+w*(5*d)+A*(5*f),v+=K>>>13,K&=8191;let F=v+C*f+H*u+U*l+M*c+V*a;v=F>>>13,F&=8191,F+=I*(5*h)+k*(5*g)+E*(5*y)+w*(5*m)+A*(5*d),v+=F>>>13,F&=8191;let G=v+C*d+H*f+U*u+M*l+V*c;v=G>>>13,G&=8191,G+=I*a+k*(5*h)+E*(5*g)+w*(5*y)+A*(5*m),v+=G>>>13,G&=8191;let j=v+C*m+H*d+U*f+M*u+V*l;v=j>>>13,j&=8191,j+=I*c+k*a+E*(5*h)+w*(5*g)+A*(5*y),v+=j>>>13,j&=8191;let ae=v+C*y+H*m+U*d+M*f+V*u;v=ae>>>13,ae&=8191,ae+=I*l+k*c+E*a+w*(5*h)+A*(5*g),v+=ae>>>13,ae&=8191;let ce=v+C*g+H*y+U*m+M*d+V*f;v=ce>>>13,ce&=8191,ce+=I*u+k*l+E*c+w*a+A*(5*h),v+=ce>>>13,ce&=8191;let fe=v+C*h+H*g+U*y+M*m+V*d;v=fe>>>13,fe&=8191,fe+=I*f+k*u+E*l+w*c+A*a,v+=fe>>>13,fe&=8191,v=(v<<2)+v|0,v=v+_|0,_=v&8191,v=v>>>13,R+=v,s[0]=_,s[1]=R,s[2]=O,s[3]=K,s[4]=F,s[5]=G,s[6]=j,s[7]=ae,s[8]=ce,s[9]=fe}finalize(){let{h:e,pad:t}=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]+t[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+t[a]|0)+(i>>>16)|0,e[a]=i&65535;Rt(n)}update(e){wc(this);let{buffer:t,blockLen:n}=this;e=oi(e);let 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}t.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Rt(this.h,this.r,this.buffer,this.pad)}digestInto(e){wc(this),sh(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:o}=this;if(o){for(t[o++]=1;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}};function gg(r){let e=(n,o)=>r(o).update(oi(n)).digest(),t=r(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=n=>r(n),e}var hh=gg(r=>new Sc(r));function mh(r,e,t,n,o,s=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=e[0],f=e[1],d=e[2],m=e[3],y=e[4],g=e[5],h=e[6],b=e[7],x=o,p=t[0],S=t[1],N=t[2],L=i,B=a,T=c,C=l,H=u,U=f,M=d,V=m,I=y,k=g,E=h,w=b,A=x,v=p,_=S,R=N;for(let K=0;K<s;K+=2)L=L+H|0,A=P(A^L,16),I=I+A|0,H=P(H^I,12),L=L+H|0,A=P(A^L,8),I=I+A|0,H=P(H^I,7),B=B+U|0,v=P(v^B,16),k=k+v|0,U=P(U^k,12),B=B+U|0,v=P(v^B,8),k=k+v|0,U=P(U^k,7),T=T+M|0,_=P(_^T,16),E=E+_|0,M=P(M^E,12),T=T+M|0,_=P(_^T,8),E=E+_|0,M=P(M^E,7),C=C+V|0,R=P(R^C,16),w=w+R|0,V=P(V^w,12),C=C+V|0,R=P(R^C,8),w=w+R|0,V=P(V^w,7),L=L+U|0,R=P(R^L,16),E=E+R|0,U=P(U^E,12),L=L+U|0,R=P(R^L,8),E=E+R|0,U=P(U^E,7),B=B+M|0,A=P(A^B,16),w=w+A|0,M=P(M^w,12),B=B+M|0,A=P(A^B,8),w=w+A|0,M=P(M^w,7),T=T+V|0,v=P(v^T,16),I=I+v|0,V=P(V^I,12),T=T+V|0,v=P(v^T,8),I=I+v|0,V=P(V^I,7),C=C+H|0,_=P(_^C,16),k=k+_|0,H=P(H^k,12),C=C+H|0,_=P(_^C,8),k=k+_|0,H=P(H^k,7);let O=0;n[O++]=i+L|0,n[O++]=a+B|0,n[O++]=c+T|0,n[O++]=l+C|0,n[O++]=u+H|0,n[O++]=f+U|0,n[O++]=d+M|0,n[O++]=m+V|0,n[O++]=y+I|0,n[O++]=g+k|0,n[O++]=h+E|0,n[O++]=b+w|0,n[O++]=x+A|0,n[O++]=p+v|0,n[O++]=S+_|0,n[O++]=N+R|0}function yg(r,e,t,n){let o=r[0],s=r[1],i=r[2],a=r[3],c=e[0],l=e[1],u=e[2],f=e[3],d=e[4],m=e[5],y=e[6],g=e[7],h=t[0],b=t[1],x=t[2],p=t[3];for(let N=0;N<20;N+=2)o=o+c|0,h=P(h^o,16),d=d+h|0,c=P(c^d,12),o=o+c|0,h=P(h^o,8),d=d+h|0,c=P(c^d,7),s=s+l|0,b=P(b^s,16),m=m+b|0,l=P(l^m,12),s=s+l|0,b=P(b^s,8),m=m+b|0,l=P(l^m,7),i=i+u|0,x=P(x^i,16),y=y+x|0,u=P(u^y,12),i=i+u|0,x=P(x^i,8),y=y+x|0,u=P(u^y,7),a=a+f|0,p=P(p^a,16),g=g+p|0,f=P(f^g,12),a=a+f|0,p=P(p^a,8),g=g+p|0,f=P(f^g,7),o=o+l|0,p=P(p^o,16),y=y+p|0,l=P(l^y,12),o=o+l|0,p=P(p^o,8),y=y+p|0,l=P(l^y,7),s=s+u|0,h=P(h^s,16),g=g+h|0,u=P(u^g,12),s=s+u|0,h=P(h^s,8),g=g+h|0,u=P(u^g,7),i=i+f|0,b=P(b^i,16),d=d+b|0,f=P(f^d,12),i=i+f|0,b=P(b^i,8),d=d+b|0,f=P(f^d,7),a=a+c|0,x=P(x^a,16),m=m+x|0,c=P(c^m,12),a=a+c|0,x=P(x^a,8),m=m+x|0,c=P(c^m,7);let S=0;n[S++]=o,n[S++]=s,n[S++]=i,n[S++]=a,n[S++]=h,n[S++]=b,n[S++]=x,n[S++]=p}var wg=Bc(mh,{counterRight:!1,counterLength:4,allowShortKeys:!1}),bg=Bc(mh,{counterRight:!1,counterLength:8,extendNonceFn:yg,allowShortKeys:!1});var xg=new Uint8Array(16),dh=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(xg.subarray(t))},Eg=new Uint8Array(32);function ph(r,e,t,n,o){let s=r(e,t,Eg),i=hh.create(s);o&&dh(i,o),dh(i,n);let a=new Uint8Array(16),c=ih(a);vc(c,0,BigInt(o?o.length:0),!0),vc(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return Rt(s,a),l}var gh=r=>(e,t,n)=>({encrypt(s,i){let a=s.length;i=Ec(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);r(e,t,c,c,1);let l=ph(r,e,t,c,n);return i.set(l,a),Rt(l),i},decrypt(s,i){i=Ec(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=ph(r,e,t,a,n);if(!ch(c,l))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),r(e,t,i,i,1),Rt(l),i}}),Ic=xc({blockSize:64,nonceLength:12,tagLength:16},gh(wg)),kB=xc({blockSize:64,nonceLength:24,tagLength:16},gh(bg));function wh(r,e,t){return en(r),t===void 0&&(t=new Uint8Array(r.outputLen)),Or(r,Pt(t),Pt(e))}var Cc=new Uint8Array([0]),yh=new Uint8Array;function bh(r,e,t,n=32){if(en(r),Qn(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);t===void 0&&(t=yh);let s=new Uint8Array(o*r.outputLen),i=Or.create(r,e),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)Cc[0]=l+1,a.update(l===0?yh:c).update(t).update(Cc).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),Cc.fill(0),s.slice(0,n)}var kc={hashSHA256(r){return ct(r.subarray())},getHKDF(r,e){let t=wh(ct,e,r),o=bh(ct,t,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=an.utils.randomPrivateKey();return{publicKey:an.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:an.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return an.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return Ic(n,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,n,o){return Ic(n,e,t).decrypt(r.subarray(),o)}};var xh=kc;function Eh(r){return{generateKeypair:r.generateX25519KeyPair,dh:(e,t)=>r.generateX25519SharedKey(e.privateKey,t).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var qr=r=>{let e=me(2);return e[0]=r>>8,e[1]=r,e};qr.bytes=2;var Fn=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let e=0;return e+=r[0]<<8,e+=r[1],e}return r.getUint16(0)};Fn.bytes=2;function vh(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Tc(r,e){!e.enabled||!Wr||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${X(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${X(r.privateKey,"hex")}`)):e("Missing local static keys."))}function Lc(r,e){!e.enabled||!Wr||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${X(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${X(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Ah(r,e){!e.enabled||!Wr||e(r?`REMOTE_STATIC_PUBLIC_KEY ${X(r.subarray(),"hex")}`:"Missing remote static public key.")}function Nc(r,e){!e.enabled||!Wr||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${X(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function _c(r,e,t){!t.enabled||!Wr||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&X(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&X(e.k,"hex")}`))}var zr=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var vg=0,Ag=4294967295,Bg="Cipherstate has reached maximum n, a new handshake must be performed",ai=class{n;bytes;view;constructor(e=vg){this.n=e,this.bytes=ye(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>Ag)throw new Error(Bg)}};var gr=ye(0),jr=class{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new ai(n)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,t,n){if(!this.hasKey())return t;this.n.assertValue();let o=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},Rc=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let n=Q(t,"utf-8");this.h=Sg(e,n),this.ck=this.h,this.cs=new jr(e)}mixKey(e){let[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new jr(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new ne(this.h,e))}encryptAndHash(e){let t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){let[e,t]=this.crypto.hkdf(this.ck,gr);return[new jr(this.crypto,e),new jr(this.crypto,t)]}},Uc=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=e;this.crypto=t,this.ss=new Rc(t,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}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,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=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<t+n)throw new Error("message is not long enough");let o=e.sublist(t,t+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Vn=class extends Uc{writeMessageA(e){return new ne(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new ne(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new ne(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new zr(`handshake stage 0 validation fail: ${t.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(t){throw new zr(`handshake stage 1 validation fail: ${t.message}`)}}readMessageC(e){try{let t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(t){throw new zr(`handshake stage 2 validation fail: ${t.message}`)}}};function Sg(r,e){if(e.length<=32){let t=ye(32);return t.set(e),t}else return r.hash(e)}var ci;(function(r){let e;r.codec=()=>(e==null&&(e=nt((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let s of t.webtransportCerthashes)n.uint32(10),n.bytes(s);o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={webtransportCerthashes:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:{o.webtransportCerthashes.push(t.bytes());break}default:{t.skipType(i&7);break}}}return o})),e),r.encode=t=>rt(t,r.codec()),r.decode=t=>tt(t,r.codec())})(ci||(ci={}));var Kn;(function(r){let e;r.codec=()=>(e==null&&(e=nt((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(n.uint32(10),n.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(n.uint32(18),n.bytes(t.identitySig)),t.extensions!=null&&(n.uint32(34),ci.codec().encode(t.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={identityKey:ye(0),identitySig:ye(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:{o.identityKey=t.bytes();break}case 2:{o.identitySig=t.bytes();break}case 4:{o.extensions=ci.codec().decode(t,t.uint32());break}default:{t.skipType(i&7);break}}}return o})),e),r.encode=t=>rt(t,r.codec()),r.decode=t=>tt(t,r.codec())})(Kn||(Kn={}));async function Dc(r,e,t){let n=await r.sign(Bh(e));return Kn.encode({identityKey:Tr(r.publicKey),identitySig:n,extensions:t})}async function Pc(r,e,t){try{let n=Kn.decode(r),o=vn(n.identityKey);if(t?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let s=Bh(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new qn(n.message)}}function Bh(r){let e=Q("noise-libp2p-static-key:");return r instanceof Uint8Array?be([e,r],e.length+r.length):(r.prepend(e),r)}async function Sh(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Dc(s,a.publicKey,l),f=new Vn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Tc(f.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await n.write(f.writeMessageA(gr),e),t.trace("Stage 0 - Initiator finished sending first message."),Lc(f.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let d=f.readMessageB(await n.read(e));t.trace("Stage 1 - Initiator received the message."),Nc(f.re,t),Ah(f.rs,t),t.trace("Initiator going to check remote's signature...");let m=await Pc(d,f.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await n.write(f.writeMessageC(u),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[y,g]=f.ss.split();return _c(y,g,t),{payload:m,encrypt:h=>y.encryptWithAd(gr,h),decrypt:(h,b)=>g.decryptWithAd(gr,h,b)}}async function Ih(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Dc(s,a.publicKey,l),f=new Vn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Tc(f.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),f.readMessageA(await n.read(e)),t.trace("Stage 0 - Responder received first message."),Nc(f.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(f.writeMessageB(u),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Lc(f.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let d=f.readMessageC(await n.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let m=await Pc(d,f.rs,c),[y,g]=f.ss.split();return _c(y,g,t),{payload:m,encrypt:h=>g.encryptWithAd(gr,h),decrypt:(h,b)=>y.decryptWithAd(gr,h,b)}}var kh=16;function Th(r,e){return async function*(t){for await(let n of t)for(let o=0;o<n.length;o+=65519){let s=o+65519;s>n.length&&(s=n.length);let i;n instanceof Uint8Array?i=r.encrypt(n.subarray(o,s)):i=r.encrypt(n.sublist(o,s)),e?.encryptedPackets.increment(),yield new ne(qr(i.byteLength),i)}}}function Lh(r,e){return async function*(t){for await(let n of t)for(let o=0;o<n.length;o+=65535){let s=o+65535;if(s>n.length&&(s=n.length),s-kh<o)throw new Error("Invalid chunk");let i=n.sublist(o,s),a=n.subarray(o,s-kh);try{let c=r.decrypt(i,a);e?.decryptedPackets.increment(),yield c}catch(c){throw e?.decryptErrors.increment(),c}}}}var li=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(e,t={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=t,{metrics:a}=e;this.components=e;let c=s??xh;this.crypto=Eh(c),this.extensions=o,this.metrics=a?vh(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??ye(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[br]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let n=On(e,{lengthEncoder:qr,lengthDecoder:Fn,maxDataLength:65535}),o=await this.performHandshakeInitiator(n,this.components.privateKey,t?.remotePeer?.publicKey,t),s=await this.createSecureConnection(n,o);e.source=s.source,e.sink=s.sink;let i=vn(o.payload.identityKey);return{conn:e,remoteExtensions:o.payload.extensions,remotePeer:Ua(i)}}async secureInbound(e,t){let n=On(e,{lengthEncoder:qr,lengthDecoder:Fn,maxDataLength:65535}),o=await this.performHandshakeResponder(n,this.components.privateKey,t?.remotePeer?.publicKey,t),s=await this.createSecureConnection(n,o);e.source=s.source,e.sink=s.sink;let i=vn(o.payload.identityKey);return{conn:e,remoteExtensions:o.payload.extensions,remotePeer:Ua(i)}}async performHandshakeInitiator(e,t,n,o){let s;try{s=await Sh({connection:e,privateKey:t,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async performHandshakeResponder(e,t,n,o){let s;try{s=await Ih({connection:e,privateKey:t,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async createSecureConnection(e,t){let[n,o]=eh(),s=e.unwrap();return await rh(n,Th(t,this.metrics),s,i=>Hn(i,{lengthDecoder:Fn}),Lh(t,this.metrics),n),o}};function Nh(r={}){return e=>new li(e,r)}var Oc=Object.values(ar).map(r=>r.decoder).reduce((r,e)=>r.or(e)),Ig=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function _h(r){return r?.match(Ig)?.groups?.fingerprint}function Mc(r){let t=r.stringTuples().filter(n=>n[0]===Oh).map(n=>n[1])[0];if(t===void 0||t==="")throw new oe(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return t}function Cg(r){return We.decode(Oc.decode(r))}function kg(r){let e=Cg(Mc(r)),t=Tg(e.code),n=e.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new $s(n,r.toString());return`${t} ${o.join(":").toUpperCase()}`}function Rh(r){let e=r.split(":").map(o=>parseInt(o,16)),t=Uint8Array.from(e),n=ke(vt.code,t);return ht(`/certhash/${cn.encode(n.bytes)}`)}function Tg(r){switch(r){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new Ws(r)}}function Uh(r,e){let{host:t,port:n,family:o}=r.toOptions(),s=kg(r);return{type:"answer",sdp:`v=0
|
6
|
+
`)}`:`${t} :`}};su=qt;D.Constructed=su;qt.NAME="CONSTRUCTED";var Co=class extends Ne{fromBER(e,t,n){return t}toBER(e){return ot}};Co.override="EndOfContentValueBlock";var iu,ko=class extends Ae{constructor(e={}){super(e,Co),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};iu=ko;D.EndOfContent=iu;ko.NAME=dn;var au,_r=class extends Ae{constructor(e={}){super(e,Ne),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let o=new Uint8Array(n);o[0]=5,o[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};au=_r;D.Null=au;_r.NAME="NULL";var To=class extends kt(Ne){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=q.BufferSourceConverter.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,n){let o=q.BufferSourceConverter.toUint8Array(e);return Ct(this,o,t,n)?(this.valueHexView=o.subarray(t,t+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,va.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};To.NAME="BooleanValueBlock";var cu,Lo=class extends Ae{constructor(e={}){super(e,To),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};cu=Lo;D.Boolean=cu;Lo.NAME="BOOLEAN";var No=class extends kt(lt){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=lt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===dn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==tu)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,t,n),this.blockLength=n;return o}toBER(e,t){return this.isConstructed?lt.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};No.NAME="OctetStringValueBlock";var lu,_o=class r extends Ae{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},No),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let s=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(s.byteLength){let i=is(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(e,t,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?qt.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${q.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof r&&e.push(t.valueBlock.valueHexView);return q.BufferSourceConverter.concat(e)}};lu=_o;D.OctetString=lu;_o.NAME=tu;var Ro=class extends kt(lt){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n){if(!n)return t;let o=-1;if(this.isConstructed){if(o=lt.prototype.fromBER.call(this,e,t,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===dn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==ru)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let s=q.BufferSourceConverter.toUint8Array(e);if(!Ct(this,s,t,n))return-1;let i=s.subarray(t,t+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=is(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,t+n}toBER(e,t){if(this.isConstructed)return lt.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ot;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Ro.NAME="BitStringValueBlock";var uu,Rr=class extends Ae{constructor({idBlock:e={},lenBlock:t={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},Ro),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return qt.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let o of t)e.push(o.toString(2).padStart(8,"0"));let n=e.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};uu=Rr;D.BitString=uu;Rr.NAME=ru;var fu;function P0(r,e){let t=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<i?i:c,f=0;for(let d=u;d>=0;d--,f++){switch(!0){case f<a.length:l=s[i-f]+a[c-f]+t[0];break;default:l=s[i-f]+t[0]}switch(t[0]=l/10,!0){case f>=s.length:s=xo(new Uint8Array([l%10]),s);break;default:s[i-f]=l%10}}return t[0]>0&&(s=xo(t,s)),s}function eu(r){if(r>=fn.length)for(let e=fn.length;e<=r;e++){let t=new Uint8Array([0]),n=fn[e-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+t[0]]);t[0]=s[0]/10,n[o]=s[0]%10}t[0]>0&&(n=xo(t,n)),fn.push(n)}return fn[r]}function O0(r,e){let t=0,n=new Uint8Array(r),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let f=c;f>=0;f--,u++)switch(l=s[i-u]-a[c-u]-t,!0){case l<0:t=1,s[i-u]=l+10;break;default:t=0,s[i-u]=l}if(t>0)for(let f=i-c+1;f>=0;f--,u++)if(l=s[i-u]-t,l<0)t=1,s[i-u]=l+10;else{t=0,s[i-u]=l;break}return s.slice()}var pn=class extends kt(Ne){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=va.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(Yl(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,o=0){let s=this.fromBER(e,t,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&(i[1]&128)!==0?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){let t=this.valueHexView;switch(!0){case(t[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(t,1),this.valueHexView=n}break;case(t[0]===0&&(t[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,t,n){let o=super.fromBER(e,t,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case e:t=O0(eu(n),t),i="-";break;default:t=P0(t,eu(n))}n++,o>>=1}}for(let c=0;c<t.length;c++)t[c]&&(a=!0),a&&(i+=Ql.charAt(t[c]));return a===!1&&(i+=Ql.charAt(0)),i}};fu=pn;pn.NAME="IntegerValueBlock";Object.defineProperty(fu.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var hu,Be=class r extends Ae{constructor(e={}){super(e,pn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Eo(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Eo();let t=BigInt(e),n=new hn,o=t.toString(16).replace(/^-/,""),s=new Uint8Array(q.Convert.FromHex(o));if(t<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${q.Convert.ToHex(a)}`)+t,u=q.BufferSourceConverter.toUint8Array(q.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let e=new r({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};hu=Be;D.Integer=hu;Be.NAME="INTEGER";var du,Uo=class extends Be{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};du=Uo;D.Enumerated=du;Uo.NAME="ENUMERATED";var mn=class extends kt(Ne){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let o=q.BufferSourceConverter.toUint8Array(e);if(!Ct(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,(s[a]&128)!==0);a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=ur(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){Eo();let t=BigInt(e).toString(2);for(;t.length%7;)t="0"+t;let n=new Uint8Array(t.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Wt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ot;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=q.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};mn.NAME="sidBlock";var Do=class extends Ne{constructor({value:e=Dr,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new mn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,ot;t.push(o)}return Aa(t)}fromString(e){this.value=[];let t=0,n=0,o="",s=!1;do if(n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new mn;if(o>Number.MAX_SAFE_INTEGER){Eo();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Do.NAME="ObjectIdentifierValueBlock";var pu,Ur=class extends Ae{constructor(e={}){super(e,Do),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};pu=Ur;D.ObjectIdentifier=pu;Ur.NAME="OBJECT IDENTIFIER";var gn=class extends kt(Bt){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let o=q.BufferSourceConverter.toUint8Array(e);if(!Ct(this,o,t,n))return-1;let s=o.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,(s[a]&128)!==0);a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=ur(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let t=Wt(this.valueDec,7);if(t.byteLength===0)return this.error="Error during encoding SID value",ot;let n=new Uint8Array(t.byteLength);if(!e){let o=new Uint8Array(t),s=t.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=q.Convert.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};gn.NAME="relativeSidBlock";var Po=class extends Ne{constructor({value:e=Dr,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let o=t;for(;n>0;){let s=new gn;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,t){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,ot;n.push(s)}return Aa(n)}fromString(e){this.value=[];let t=0,n=0,o="";do{n=e.indexOf(".",t),n===-1?o=e.substring(t):o=e.substring(t,n),t=n+1;let s=new gn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(o=`{${o}}`),e+=o}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};Po.NAME="RelativeObjectIdentifierValueBlock";var mu,Oo=class extends Ae{constructor(e={}){super(e,Po),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};mu=Oo;D.RelativeObjectIdentifier=mu;Oo.NAME="RelativeObjectIdentifier";var gu,St=class extends qt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};gu=St;D.Sequence=gu;St.NAME="SEQUENCE";var yu,Mo=class extends qt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};yu=Mo;D.Set=yu;Mo.NAME="SET";var Ho=class extends kt(Ne){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Dr}toJSON(){return{...super.toJSON(),value:this.value}}};Ho.NAME="StringValueBlock";var Fo=class extends Ho{};Fo.NAME="SimpleStringValueBlock";var Pe=class extends Bo{constructor({...e}={}){super(e,Fo)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let o=0;o<t;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}};Pe.NAME="SIMPLE STRING";var Vo=class extends Pe{fromBuffer(e){this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=q.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=q.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf8String(e)),this.valueBlock.value=e}};Vo.NAME="Utf8StringValueBlock";var wu,It=class extends Vo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};wu=It;D.Utf8String=wu;It.NAME="UTF8String";var Ko=class extends Pe{fromBuffer(e){this.valueBlock.value=q.Convert.ToUtf16String(e),this.valueBlock.valueHexView=q.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(q.Convert.FromUtf16String(e))}};Ko.NAME="BmpStringValueBlock";var bu,$o=class extends Ko{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};bu=$o;D.BmpString=bu;$o.NAME="BMPString";var Go=class extends Pe{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let o=0;o<t;o++){let s=Wt(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}};Go.NAME="UniversalStringValueBlock";var xu,Wo=class extends Go{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};xu=Wo;D.UniversalString=xu;Wo.NAME="UniversalString";var Eu,qo=class extends Pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Eu=qo;D.NumericString=Eu;qo.NAME="NumericString";var vu,zo=class extends Pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};vu=zo;D.PrintableString=vu;zo.NAME="PrintableString";var Au,jo=class extends Pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Au=jo;D.TeletexString=Au;jo.NAME="TeletexString";var Bu,Zo=class extends Pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Bu=Zo;D.VideotexString=Bu;Zo.NAME="VideotexString";var Su,Xo=class extends Pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Su=Xo;D.IA5String=Su;Xo.NAME="IA5String";var Iu,Yo=class extends Pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Iu=Yo;D.GraphicString=Iu;Yo.NAME="GraphicString";var Cu,yn=class extends Pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Cu=yn;D.VisibleString=Cu;yn.NAME="VisibleString";var ku,Jo=class extends Pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};ku=Jo;D.GeneralString=ku;Jo.NAME="GeneralString";var Tu,Qo=class extends Pe{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Tu=Qo;D.CharacterString=Tu;Qo.NAME="CharacterString";var Lu,wn=class extends yn{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,q.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){let t=new Array(7);return t[0]=Fe(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=Fe(this.month,2),t[2]=Fe(this.day,2),t[3]=Fe(this.hour,2),t[4]=Fe(this.minute,2),t[5]=Fe(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};Lu=wn;D.UTCTime=Lu;wn.NAME="UTCTime";var Nu,es=class extends wn{constructor(e={}){var t;super(e),(t=this.millisecond)!==null&&t!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),t=!0;else{let f=new Number(e[e.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(t){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,d=n.indexOf("+"),m="";if(d===-1&&(d=n.indexOf("-"),f=-1),d!==-1){if(m=n.substring(d+1),n=n.substring(0,d),m.length!==2&&m.length!==4)throw new Error("Wrong input string for conversion");let y=parseInt(m.substring(0,2),10);if(isNaN(y.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*y,m.length===4){if(y=parseInt(m.substring(2,4),10),isNaN(y.valueOf()))throw new Error("Wrong input string for conversion");c=f*y}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let f=new Number(`0${n.substring(l)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");s=f.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=1e3*s;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=i.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(t===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){let t=[];return t.push(Fe(this.year,4)),t.push(Fe(this.month,2)),t.push(Fe(this.day,2)),t.push(Fe(this.hour,2)),t.push(Fe(this.minute,2)),t.push(Fe(this.second,2)),this.millisecond!==0&&(t.push("."),t.push(Fe(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Nu=es;D.GeneralizedTime=Nu;es.NAME="GeneralizedTime";var _u,ts=class extends It{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};_u=ts;D.DATE=_u;ts.NAME="DATE";var Ru,rs=class extends It{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Ru=rs;D.TimeOfDay=Ru;rs.NAME="TimeOfDay";var Uu,ns=class extends It{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Uu=ns;D.DateTime=Uu;ns.NAME="DateTime";var Du,os=class extends It{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Du=os;D.Duration=Du;os.NAME="Duration";var Pu,ss=class extends It{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Pu=ss;D.TIME=Pu;ss.NAME="TIME";function X(r,e="utf8"){let t=mo[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var bn=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},as=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Ou={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new as("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var zt=Ou;async function Mu(r){let e=await zt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),t=await H0(e);return{privateKey:t[0],publicKey:t[1]}}async function Hu(r,e){let t=await zt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await zt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},t,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(n,0,n.byteLength)}async function Fu(r,e,t){let n=await zt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return zt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,e,t instanceof Uint8Array?t:t.subarray())}async function H0(r){if(r.privateKey==null||r.publicKey==null)throw new oe("Private and public key are required");return Promise.all([zt.get().subtle.exportKey("jwk",r.privateKey),zt.get().subtle.exportKey("jwk",r.publicKey)])}function Ia(r){if(r.kty!=="RSA")throw new oe("invalid key type");if(r.n==null)throw new oe("invalid key modulus");return Q(r.n,"base64url").length*8}var Pr=class{type="RSA";_key;_raw;_multihash;constructor(e,t){this._key=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=xn.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return Ee.createV1(114,this._multihash)}toString(){return se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:De(this.raw,e.raw)}verify(e,t){return Fu(this._key,t,e)}},En=class{type="RSA";_key;_raw;publicKey;constructor(e,t){this._key=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=xn.jwkToPkcs1(this._key)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:De(this.raw,e.raw)}sign(e){return Hu(this._key,e)}};var cs=8192,Ca=18;function Vu(r){let{result:e}=Sa(r),t=e.valueBlock.value;return{n:ut(t[1]),e:ut(t[2]),d:ut(t[3]),p:ut(t[4]),q:ut(t[5]),dp:ut(t[6]),dq:ut(t[7]),qi:ut(t[8]),kty:"RSA",alg:"RS256"}}function F0(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new oe("JWK was missing components");let t=new St({value:[new Be({value:0}),Be.fromBigInt(ft(Q(r.n,"base64url"))),Be.fromBigInt(ft(Q(r.e,"base64url"))),Be.fromBigInt(ft(Q(r.d,"base64url"))),Be.fromBigInt(ft(Q(r.p,"base64url"))),Be.fromBigInt(ft(Q(r.q,"base64url"))),Be.fromBigInt(ft(Q(r.dp,"base64url"))),Be.fromBigInt(ft(Q(r.dq,"base64url"))),Be.fromBigInt(ft(Q(r.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}function Ku(r){let{result:e}=Sa(r),t=e.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:ut(t[0]),e:ut(t[1])}}function ka(r){if(r.n==null||r.e==null)throw new oe("JWK was missing components");let t=new St({value:[new St({value:[new Ur({value:"1.2.840.113549.1.1.1"}),new _r]}),new Rr({valueHex:new St({value:[Be.fromBigInt(ft(Q(r.n,"base64url"))),Be.fromBigInt(ft(Q(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(t,0,t.byteLength)}function ut(r){let e=r.valueBlock.valueHexView;for(;e[0]===0;)e=e.subarray(1);return X(e,"base64url")}function ft(r){let e=[];return r.forEach(function(t){let n=t.toString(16);n.length%2>0&&(n=`0${n}`),e.push(n)}),BigInt("0x"+e.join(""))}function $u(r){let e=Vu(r);return Gu(e)}function Ta(r){let e=Ku(r);if(Ia(e)>cs)throw new yr("Key size is too large");let t=ct(at.encode({Type:we.RSA,Data:r})),n=ke(Ca,t);return new Pr(e,n)}function Gu(r){if(Ia(r)>cs)throw new oe("Key size is too large");let e=qu(r),t=ct(at.encode({Type:we.RSA,Data:ka(e.publicKey)})),n=ke(Ca,t);return new En(e.privateKey,new Pr(e.publicKey,n))}async function Wu(r){if(r>cs)throw new oe("Key size is too large");let e=await Mu(r),t=ct(at.encode({Type:we.RSA,Data:ka(e.publicKey)})),n=ke(Ca,t);return new En(e.privateKey,new Pr(e.publicKey,n))}function qu(r){if(r==null)throw new oe("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var ls=class extends Sr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,en(e);let n=Pt(t);if(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 o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(e){return Br(this),this.iHash.update(e),this}digestInto(e){Br(this),Ar(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,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=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Or=(r,e,t)=>new ls(r,e).update(t).digest();Or.create=(r,e)=>new ls(r,e);function zu(r){r.lowS!==void 0&&Ye("lowS",r.lowS),r.prehash!==void 0&&Ye("prehash",r.prehash)}function V0(r){let e=on(r);qe(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:t,Fp:n,a:o}=e;if(t){if(!n.eql(o,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:K0,hexToBytes:$0}=so,La=class extends Error{constructor(e=""){super(e)}},Tt={Err:La,_tlv:{encode:(r,e)=>{let{Err:t}=Tt;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,o=tr(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?tr(o.length/2|128):"";return tr(r)+s+o+e},decode(r,e){let{Err:t}=Tt,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("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 t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Tt;if(r<Lt)throw new e("integer: negative integers are not allowed");let t=tr(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Tt;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return K0(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Tt,o=typeof r=="string"?$0(r):r;Cr(o);let{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:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=Tt,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},Lt=BigInt(0),xe=BigInt(1),hx=BigInt(2),ju=BigInt(3),dx=BigInt(4);function G0(r){let e=V0(r),{Fp:t}=e,n=Vt(e.n,e.nBitLength),o=e.toBytes||((g,h,b)=>{let x=h.toAffine();return Et(Uint8Array.from([4]),t.toBytes(x.x),t.toBytes(x.y))}),s=e.fromBytes||(g=>{let h=g.subarray(1),b=t.fromBytes(h.subarray(0,t.BYTES)),x=t.fromBytes(h.subarray(t.BYTES,2*t.BYTES));return{x:b,y:x}});function i(g){let{a:h,b}=e,x=t.sqr(g),p=t.mul(x,g);return t.add(t.add(p,t.mul(g,h)),b)}if(!t.eql(t.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return rn(g,xe,e.n)}function c(g){let{allowedPrivateKeyLengths:h,nByteLength:b,wrapPrivateKey:x,n:p}=e;if(h&&typeof g!="bigint"){if(Ht(g)&&(g=wt(g)),typeof g!="string"||!h.includes(g.length))throw new Error("invalid private key");g=g.padStart(b*2,"0")}let S;try{S=typeof g=="bigint"?g:bt(ie("private key",g,b))}catch{throw new Error("invalid private key, expected hex or "+b+" bytes, got "+typeof g)}return x&&(S=Z(S,p)),ve("private key",S,xe,p),S}function l(g){if(!(g instanceof d))throw new Error("ProjectivePoint expected")}let u=nr((g,h)=>{let{px:b,py:x,pz:p}=g;if(t.eql(p,t.ONE))return{x:b,y:x};let S=g.is0();h==null&&(h=S?t.ONE:t.inv(p));let N=t.mul(b,h),L=t.mul(x,h),B=t.mul(p,h);if(S)return{x:t.ZERO,y:t.ZERO};if(!t.eql(B,t.ONE))throw new Error("invZ was invalid");return{x:N,y:L}}),f=nr(g=>{if(g.is0()){if(e.allowInfinityPoint&&!t.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:h,y:b}=g.toAffine();if(!t.isValid(h)||!t.isValid(b))throw new Error("bad point: x or y not FE");let x=t.sqr(b),p=i(h);if(!t.eql(x,p))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,b,x){if(this.px=h,this.py=b,this.pz=x,h==null||!t.isValid(h))throw new Error("x required");if(b==null||!t.isValid(b))throw new Error("y required");if(x==null||!t.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:b,y:x}=h||{};if(!h||!t.isValid(b)||!t.isValid(x))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let p=S=>t.eql(S,t.ZERO);return p(b)&&p(x)?d.ZERO:new d(b,x,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let b=t.invertBatch(h.map(x=>x.pz));return h.map((x,p)=>x.toAffine(b[p])).map(d.fromAffine)}static fromHex(h){let b=d.fromAffine(s(ie("pointHex",h)));return b.assertValidity(),b}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,b){return lo(d,n,h,b)}_setWindowSize(h){y.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(t.isOdd)return!t.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:b,py:x,pz:p}=this,{px:S,py:N,pz:L}=h,B=t.eql(t.mul(b,L),t.mul(S,p)),T=t.eql(t.mul(x,L),t.mul(N,p));return B&&T}negate(){return new d(this.px,t.neg(this.py),this.pz)}double(){let{a:h,b}=e,x=t.mul(b,ju),{px:p,py:S,pz:N}=this,L=t.ZERO,B=t.ZERO,T=t.ZERO,C=t.mul(p,p),H=t.mul(S,S),U=t.mul(N,N),M=t.mul(p,S);return M=t.add(M,M),T=t.mul(p,N),T=t.add(T,T),L=t.mul(h,T),B=t.mul(x,U),B=t.add(L,B),L=t.sub(H,B),B=t.add(H,B),B=t.mul(L,B),L=t.mul(M,L),T=t.mul(x,T),U=t.mul(h,U),M=t.sub(C,U),M=t.mul(h,M),M=t.add(M,T),T=t.add(C,C),C=t.add(T,C),C=t.add(C,U),C=t.mul(C,M),B=t.add(B,C),U=t.mul(S,N),U=t.add(U,U),C=t.mul(U,M),L=t.sub(L,C),T=t.mul(U,H),T=t.add(T,T),T=t.add(T,T),new d(L,B,T)}add(h){l(h);let{px:b,py:x,pz:p}=this,{px:S,py:N,pz:L}=h,B=t.ZERO,T=t.ZERO,C=t.ZERO,H=e.a,U=t.mul(e.b,ju),M=t.mul(b,S),V=t.mul(x,N),I=t.mul(p,L),k=t.add(b,x),E=t.add(S,N);k=t.mul(k,E),E=t.add(M,V),k=t.sub(k,E),E=t.add(b,p);let w=t.add(S,L);return E=t.mul(E,w),w=t.add(M,I),E=t.sub(E,w),w=t.add(x,p),B=t.add(N,L),w=t.mul(w,B),B=t.add(V,I),w=t.sub(w,B),C=t.mul(H,E),B=t.mul(U,I),C=t.add(B,C),B=t.sub(V,C),C=t.add(V,C),T=t.mul(B,C),V=t.add(M,M),V=t.add(V,M),I=t.mul(H,I),E=t.mul(U,E),V=t.add(V,I),I=t.sub(M,I),I=t.mul(H,I),E=t.add(E,I),M=t.mul(V,E),T=t.add(T,M),M=t.mul(w,E),B=t.mul(k,B),B=t.sub(B,M),M=t.mul(k,V),C=t.mul(w,C),C=t.add(C,M),new d(B,T,C)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return y.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){let{endo:b,n:x}=e;ve("scalar",h,Lt,x);let p=d.ZERO;if(h===Lt)return p;if(this.is0()||h===xe)return this;if(!b||y.hasPrecomputes(this))return y.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:S,k1:N,k2neg:L,k2:B}=b.splitScalar(h),T=p,C=p,H=this;for(;N>Lt||B>Lt;)N&xe&&(T=T.add(H)),B&xe&&(C=C.add(H)),H=H.double(),N>>=xe,B>>=xe;return S&&(T=T.negate()),L&&(C=C.negate()),C=new d(t.mul(C.px,b.beta),C.py,C.pz),T.add(C)}multiply(h){let{endo:b,n:x}=e;ve("scalar",h,xe,x);let p,S;if(b){let{k1neg:N,k1:L,k2neg:B,k2:T}=b.splitScalar(h),{p:C,f:H}=this.wNAF(L),{p:U,f:M}=this.wNAF(T);C=y.constTimeNegate(N,C),U=y.constTimeNegate(B,U),U=new d(t.mul(U.px,b.beta),U.py,U.pz),p=C.add(U),S=H.add(M)}else{let{p:N,f:L}=this.wNAF(h);p=N,S=L}return d.normalizeZ([p,S])[0]}multiplyAndAddUnsafe(h,b,x){let p=d.BASE,S=(L,B)=>B===Lt||B===xe||!L.equals(p)?L.multiplyUnsafe(B):L.multiply(B),N=S(this,b).add(S(h,x));return N.is0()?void 0:N}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:b}=e;if(h===xe)return!0;if(b)return b(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:b}=e;return h===xe?this:b?b(d,this):this.multiplyUnsafe(e.h)}toRawBytes(h=!0){return Ye("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return Ye("isCompressed",h),wt(this.toRawBytes(h))}}d.BASE=new d(e.Gx,e.Gy,t.ONE),d.ZERO=new d(t.ZERO,t.ONE,t.ZERO);let m=e.nBitLength,y=co(d,e.endo?Math.ceil(m/2):m);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function W0(r){let e=on(r);return qe(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function Zu(r){let e=W0(r),{Fp:t,n}=e,o=t.BYTES+1,s=2*t.BYTES+1;function i(I){return Z(I,n)}function a(I){return io(I,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=G0({...e,toBytes(I,k,E){let w=k.toAffine(),A=t.toBytes(w.x),v=Et;return Ye("isCompressed",E),E?v(Uint8Array.from([k.hasEvenY()?2:3]),A):v(Uint8Array.from([4]),A,t.toBytes(w.y))},fromBytes(I){let k=I.length,E=I[0],w=I.subarray(1);if(k===o&&(E===2||E===3)){let A=bt(w);if(!rn(A,xe,t.ORDER))throw new Error("Point is not on curve");let v=u(A),_;try{_=t.sqrt(v)}catch(K){let F=K instanceof Error?": "+K.message:"";throw new Error("Point is not on curve"+F)}let R=(_&xe)===xe;return(E&1)===1!==R&&(_=t.neg(_)),{x:A,y:_}}else if(k===s&&E===4){let A=t.fromBytes(w.subarray(0,t.BYTES)),v=t.fromBytes(w.subarray(t.BYTES,2*t.BYTES));return{x:A,y:v}}else{let A=o,v=s;throw new Error("invalid Point, expected length of "+A+", or uncompressed "+v+", got "+k)}}}),d=I=>wt(Ft(I,e.nByteLength));function m(I){let k=n>>xe;return I>k}function y(I){return m(I)?i(-I):I}let g=(I,k,E)=>bt(I.slice(k,E));class h{constructor(k,E,w){this.r=k,this.s=E,this.recovery=w,this.assertValidity()}static fromCompact(k){let E=e.nByteLength;return k=ie("compactSignature",k,E*2),new h(g(k,0,E),g(k,E,2*E))}static fromDER(k){let{r:E,s:w}=Tt.toSig(ie("DER",k));return new h(E,w)}assertValidity(){ve("r",this.r,xe,n),ve("s",this.s,xe,n)}addRecoveryBit(k){return new h(this.r,this.s,k)}recoverPublicKey(k){let{r:E,s:w,recovery:A}=this,v=L(ie("msgHash",k));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let _=A===2||A===3?E+e.n:E;if(_>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");let R=(A&1)===0?"02":"03",O=c.fromHex(R+d(_)),K=a(_),F=i(-v*K),G=i(w*K),j=c.BASE.multiplyAndAddUnsafe(O,F,G);if(!j)throw new Error("point at infinify");return j.assertValidity(),j}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return rr(this.toDERHex())}toDERHex(){return Tt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return rr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let b={isValidPrivateKey(I){try{return l(I),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let I=Pi(e.n);return Al(e.randomBytes(I),e.n)},precompute(I=8,k=c.BASE){return k._setWindowSize(I),k.multiply(BigInt(3)),k}};function x(I,k=!0){return c.fromPrivateKey(I).toRawBytes(k)}function p(I){let k=Ht(I),E=typeof I=="string",w=(k||E)&&I.length;return k?w===o||w===s:E?w===2*o||w===2*s:I instanceof c}function S(I,k,E=!0){if(p(I))throw new Error("first arg must be private key");if(!p(k))throw new Error("second arg must be public key");return c.fromHex(k).multiply(l(I)).toRawBytes(E)}let N=e.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");let k=bt(I),E=I.length*8-e.nBitLength;return E>0?k>>BigInt(E):k},L=e.bits2int_modN||function(I){return i(N(I))},B=nn(e.nBitLength);function T(I){return ve("num < 2^"+e.nBitLength,I,Lt,B),Ft(I,e.nByteLength)}function C(I,k,E=H){if(["recovered","canonical"].some(ce=>ce in E))throw new Error("sign() legacy options not supported");let{hash:w,randomBytes:A}=e,{lowS:v,prehash:_,extraEntropy:R}=E;v==null&&(v=!0),I=ie("msgHash",I),zu(E),_&&(I=ie("prehashed msgHash",w(I)));let O=L(I),K=l(k),F=[T(K),T(O)];if(R!=null&&R!==!1){let ce=R===!0?A(t.BYTES):R;F.push(ie("extraEntropy",ce))}let G=Et(...F),j=O;function ae(ce){let fe=N(ce);if(!f(fe))return;let Ie=a(fe),Me=c.BASE.multiply(fe).toAffine(),Ue=i(Me.x);if(Ue===Lt)return;let it=i(Ie*i(j+Ue*K));if(it===Lt)return;let dt=(Me.x===Ue?0:2)|Number(Me.y&xe),Zr=it;return v&&m(it)&&(Zr=y(it),dt^=1),new h(Ue,Zr,dt)}return{seed:G,k2sig:ae}}let H={lowS:e.lowS,prehash:!1},U={lowS:e.lowS,prehash:!1};function M(I,k,E=H){let{seed:w,k2sig:A}=C(I,k,E),v=e;return Ni(v.hash.outputLen,v.nByteLength,v.hmac)(w,A)}c.BASE._setWindowSize(8);function V(I,k,E,w=U){let A=I;k=ie("msgHash",k),E=ie("publicKey",E);let{lowS:v,prehash:_,format:R}=w;if(zu(w),"strict"in w)throw new Error("options.strict was renamed to lowS");if(R!==void 0&&R!=="compact"&&R!=="der")throw new Error("format must be compact or der");let O=typeof A=="string"||Ht(A),K=!O&&!R&&typeof A=="object"&&A!==null&&typeof A.r=="bigint"&&typeof A.s=="bigint";if(!O&&!K)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let F,G;try{if(K&&(F=new h(A.r,A.s)),O){try{R!=="compact"&&(F=h.fromDER(A))}catch(dt){if(!(dt instanceof Tt.Err))throw dt}!F&&R!=="der"&&(F=h.fromCompact(A))}G=c.fromHex(E)}catch{return!1}if(!F||v&&F.hasHighS())return!1;_&&(k=e.hash(k));let{r:j,s:ae}=F,ce=L(k),fe=a(ae),Ie=i(ce*fe),Me=i(j*fe),Ue=c.BASE.multiplyAndAddUnsafe(G,Ie,Me)?.toAffine();return Ue?i(Ue.x)===j:!1}return{CURVE:e,getPublicKey:x,getSharedSecret:S,sign:M,verify:V,ProjectivePoint:c,Signature:h,utils:b}}function q0(r){return{hash:r,hmac:(e,...t)=>Or(r,e,Bi(...t)),randomBytes:tn}}function Xu(r,e){let t=n=>Zu({...r,...q0(n)});return{...t(e),create:t}}var Qu=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Yu=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),z0=BigInt(1),Na=BigInt(2),Ju=(r,e)=>(r+e/Na)/e;function j0(r){let e=Qu,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=le(u,t,e)*u%e,d=le(f,t,e)*u%e,m=le(d,Na,e)*l%e,y=le(m,o,e)*m%e,g=le(y,s,e)*y%e,h=le(g,a,e)*g%e,b=le(h,c,e)*h%e,x=le(b,a,e)*g%e,p=le(x,t,e)*u%e,S=le(p,i,e)*y%e,N=le(S,n,e)*l%e,L=le(N,Na,e);if(!_a.eql(_a.sqr(L),r))throw new Error("Cannot find square root");return L}var _a=Vt(Qu,void 0,void 0,{sqrt:j0}),fr=Xu({a:BigInt(0),b:BigInt(7),Fp:_a,n:Yu,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let e=Yu,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-z0*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=t,i=BigInt("0x100000000000000000000000000000000"),a=Ju(s*r,e),c=Ju(-n*r,e),l=Z(r-a*t-c*o,e),u=Z(-a*n-c*s,e),f=l>i,d=u>i;if(f&&(l=e-l),d&&(u=e-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},ct),vx=BigInt(0);var Ax=fr.ProjectivePoint;function be(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=me(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function ef(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function tf(r,e,t){let n=vt.digest(t instanceof Uint8Array?t:t.subarray());if(ef(n))return n.then(({digest:o})=>fr.verify(e,o,r)).catch(o=>{throw new bn(String(o))});try{return fr.verify(e,n.digest,r)}catch(o){throw new bn(String(o))}}var us=class{type="secp256k1";raw;_key;constructor(e){this._key=nf(e),this.raw=rf(this._key)}toMultihash(){return gt.digest(Tr(this))}toCID(){return Ee.createV1(114,this.toMultihash())}toString(){return se.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:De(this.raw,e.raw)}verify(e,t){return tf(this._key,t,e)}};function Ra(r){return new us(r)}function rf(r){return fr.ProjectivePoint.fromHex(r).toRawBytes(!0)}function nf(r){try{return fr.ProjectivePoint.fromHex(r),r}catch(e){throw new yr(String(e))}}function vn(r){let{Type:e,Data:t}=at.decode(r),n=t??new Uint8Array;switch(e){case we.RSA:return Ta(n);case we.Ed25519:return $i(n);case we.secp256k1:return Ra(n);default:throw new Jt}}function of(r){let{Type:e,Data:t}=at.decode(r.digest),n=t??new Uint8Array;switch(e){case we.Ed25519:return $i(n);case we.secp256k1:return Ra(n);default:throw new Jt}}function Tr(r){return at.encode({Type:we[r.type],Data:r.raw})}var sf=Symbol.for("nodejs.util.inspect.custom"),X0=114,An=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()})`}[hi]=!0;toString(){return this.string==null&&(this.string=se.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Ee.createV1(X0,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return De(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return De(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[sf](){return`PeerId(${this.toString()})`}},Bn=class extends An{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Sn=class extends An{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},In=class extends An{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Y0=2336,fs=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=gt.digest(Q(this.url))}[sf](){return`PeerId(${this.url})`}[hi]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Ee.createV1(Y0,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=X(e)),e.toString()===this.toString())}};function Mr(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Dt(se.decode(`z${r}`));else{if(e==null)throw new oe('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Dt(e.decode(r))}return J0(t)}function Ua(r){if(r.type==="Ed25519")return new Sn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new In({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Bn({multihash:r.toCID().multihash,publicKey:r});throw new Jt}function J0(r){if(em(r))return new Bn({multihash:r});if(Q0(r))try{let e=of(r);if(e.type==="Ed25519")return new Sn({multihash:r,publicKey:e});if(e.type==="secp256k1")return new In({multihash:r,publicKey:e})}catch{let t=X(r.digest);return new fs(new URL(t))}throw new Zn("Supplied PeerID Multihash is invalid")}function Q0(r){return r.code===gt.code}function em(r){return r.code===vt.code}var hs=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}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 t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=e,s+=u,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[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];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;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 t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var af=45,tm=15,Hr=new hs;function Da(r){if(!(r.length>tm))return Hr.new(r).parseWith(()=>Hr.readIPv4Addr())}function Pa(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>af))return Hr.new(r).parseWith(()=>Hr.readIPv6Addr())}function ds(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>af)return;let t=Hr.new(r).parseWith(()=>Hr.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}var M1=parseInt("0xFFFF",16),H1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function ps(r){return!!Da(r)}function ms(r){return!!Pa(r)}function gs(r){return!!ds(r)}var uf=ps,im=ms,Oa=function(r){let e=0;if(r=r.toString().trim(),uf(r)){let t=new Uint8Array(e+4);return r.split(/\./g).forEach(n=>{t[e++]=parseInt(n,10)&255}),t}if(im(r)){let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=uf(t[n]),i;s&&(i=Oa(t[n]),t[n]=X(i.slice(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,X(i.slice(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){let s=parseInt(t[n],16);o[e++]=s>>8&255,o[e++]=s&255}return o}throw new Error("invalid ip address")},ff=function(r,e=0,t){e=~~e,t=t??r.length-e;let n=new DataView(r.buffer);if(t===4){let o=[];for(let s=0;s<t;s++)o.push(r[e+s]);return o.join(".")}if(t===16){let o=[];for(let s=0;s<t;s+=2)o.push(n.getUint16(e+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Fr={},Ma={},cm=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];cm.forEach(r=>{let e=lm(...r);Ma[e.code]=e,Fr[e.name]=e});function lm(r,e,t,n,o){return{code:r,size:e,name:t,resolvable:!!n,path:!!o}}function ne(r){if(typeof r=="number"){if(Ma[r]!=null)return Ma[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Fr[r]!=null)return Fr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var v2=ne("ip4"),A2=ne("ip6"),B2=ne("ipcidr");function Ka(r,e){switch(ne(r).code){case 4:case 41:return fm(e);case 42:return Va(e);case 43:return X(e,"base10");case 6:case 273:case 33:case 132:return pf(e).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Va(e);case 421:return mm(e);case 444:return df(e);case 445:return df(e);case 466:return pm(e);case 481:return globalThis.encodeURIComponent(Va(e));default:return X(e,"base16")}}function $a(r,e){switch(ne(r).code){case 4:return hf(e);case 41:return hf(e);case 42:return Fa(e);case 43:return Q(e,"base10");case 6:case 273:case 33:case 132:return Ga(parseInt(e,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Fa(e);case 421:return hm(e);case 444:return gm(e);case 445:return ym(e);case 466:return dm(e);case 481:return Fa(globalThis.decodeURIComponent(e));default:return Q(e,"base16")}}var Ha=Object.values(ar).map(r=>r.decoder),um=function(){let r=Ha[0].or(Ha[1]);return Ha.slice(2).forEach(e=>r=r.or(e)),r}();function hf(r){if(!gs(r))throw new Error("invalid ip address");return Oa(r)}function fm(r){let e=ff(r,0,r.length);if(e==null)throw new Error("ipBuff is required");if(!gs(e))throw new Error("invalid ip address");return e}function Ga(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,r),new Uint8Array(e)}function pf(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Fa(r){let e=Q(r),t=Uint8Array.from(ze(e.length));return be([t,e],t.length+e.length)}function Va(r){let e=Ke(r);if(r=r.slice(ee(e)),r.length!==e)throw new Error("inconsistent lengths");return X(r)}function hm(r){let e;r[0]==="Q"||r[0]==="1"?e=Dt(se.decode(`z${r}`)).bytes:e=Ee.parse(r).multihash.bytes;let t=Uint8Array.from(ze(e.length));return be([t,e],t.length+e.length)}function dm(r){let e=um.decode(r),t=Uint8Array.from(ze(e.length));return be([t,e],t.length+e.length)}function pm(r){let e=Ke(r),t=r.slice(ee(e));if(t.length!==e)throw new Error("inconsistent lengths");return"u"+X(t,"base64url")}function mm(r){let e=Ke(r),t=r.slice(ee(e));if(t.length!==e)throw new Error("inconsistent lengths");return X(t,"base58btc")}function gm(r){let e=r.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 t=mt.decode("b"+e[0]),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ga(n);return be([t,o],t.length+o.length)}function ym(r){let e=r.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 t=mt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ga(n);return be([t,o],t.length+o.length)}function df(r){let e=r.slice(0,r.length-2),t=r.slice(r.length-2),n=X(e,"base32"),o=pf(t);return`${n}:${o}`}function mf(r){r=Wa(r);let e=[],t=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=ne(i);if(a.size===0){e.push([a.code]),t.push([a.code]);continue}if(s++,s>=o.length)throw new ys("invalid address: "+r);if(a.path===!0){n=Wa(o.slice(s).join("/")),e.push([a.code,$a(a.code,n)]),t.push([a.code,n]);break}let c=$a(a.code,o[s]);e.push([a.code,c]),t.push([a.code,Ka(a.code,c)])}return{string:gf(t),bytes:ws(e),tuples:e,stringTuples:t,path:n}}function qa(r){let e=[],t=[],n=null,o=0;for(;o<r.length;){let s=Ke(r,o),i=ee(s),a=ne(s),c=wm(a,r.slice(o+i));if(c===0){e.push([s]),t.push([s]),o+=i;continue}let l=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw new ys("Invalid address Uint8Array: "+X(r,"base16"));e.push([s,l]);let u=Ka(s,l);if(t.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:gf(t),tuples:e,stringTuples:t,path:n}}function gf(r){let e=[];return r.map(t=>{let n=ne(t[0]);return e.push(n.name),t.length>1&&t[1]!=null&&e.push(t[1]),null}),Wa(e.join("/"))}function ws(r){return be(r.map(e=>{let t=ne(e[0]),n=Uint8Array.from(ze(t.code));return e.length>1&&e[1]!=null&&(n=be([n,e[1]])),n}))}function wm(r,e){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let t=Ke(e instanceof Uint8Array?e:Uint8Array.from(e));return t+ee(t)}}function Wa(r){return"/"+r.trim().split("/").filter(e=>e).join("/")}var ys=class extends Error{static name="ParseError";name="ParseError";constructor(e){super(`Error parsing address: ${e}`)}};var bm=Symbol.for("nodejs.util.inspect.custom"),ja=Symbol.for("@multiformats/js-multiaddr/multiaddr"),xm=[ne("dns").code,ne("dns4").code,ne("dns6").code,ne("dnsaddr").code],za=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}},bs=class r{bytes;#e;#t;#r;#n;[ja]=!0;constructor(e){e==null&&(e="");let t;if(e instanceof Uint8Array)t=qa(e);else if(typeof e=="string"){if(e.length>0&&e.charAt(0)!=="/")throw new Error(`multiaddr "${e}" must start with a "/"`);t=mf(e)}else if(wf(e))t=qa(e.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=t.bytes,this.#e=t.string,this.#t=t.tuples,this.#r=t.stringTuples,this.#n=t.path}toString(){return this.#e}toJSON(){return this.toString()}toOptions(){let e,t,n,o,s="",i=ne("tcp"),a=ne("udp"),c=ne("ip4"),l=ne("ip6"),u=ne("dns6"),f=ne("ip6zone");for(let[m,y]of this.stringTuples())m===f.code&&(s=`%${y??""}`),xm.includes(m)&&(t=i.name==="tcp"?"tcp":"udp",o=443,n=`${y??""}${s}`,e=m===u.code?6:4),(m===i.code||m===a.code)&&(t=ne(m).name==="tcp"?"tcp":"udp",o=parseInt(y??"")),(m===c.code||m===l.code)&&(t=ne(m).name==="tcp"?"tcp":"udp",n=`${y??""}${s}`,e=m===l.code?6:4);if(e==null||t==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:o}}protos(){return this.#t.map(([e])=>Object.assign({},ne(e)))}protoCodes(){return this.#t.map(([e])=>e)}protoNames(){return this.#t.map(([e])=>ne(e).name)}tuples(){return this.#t.map(([e,t])=>t==null?[e]:[e,t])}stringTuples(){return this.#r.map(([e,t])=>t==null?[e]:[e,t])}encapsulate(e){return e=new r(e),new r(this.toString()+e.toString())}decapsulate(e){let t=e.toString(),n=this.toString(),o=n.lastIndexOf(t);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,o))}decapsulateCode(e){let t=this.tuples();for(let n=t.length-1;n>=0;n--)if(t[n][0]===e)return new r(ws(t.slice(0,n)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach(([n,o])=>{n===Fr.p2p.code&&e.push([n,o]),n===Fr["p2p-circuit"].code&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?X(se.decode(`z${n}`),"base58btc"):X(Ee.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(e){return De(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(s=>s.resolvable);if(t==null)return[this];let n=yf.get(t.name);if(n==null)throw new za(`no available resolver for ${t.name}`);return(await n(this,e)).map(s=>ht(s))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){let t=(e??this).protos();return!(t.length!==2||t[0].code!==4&&t[0].code!==41||t[1].code!==6&&t[1].code!==273)}[bm](){return`Multiaddr(${this.#e})`}};var yf=new Map;function wf(r){return!!r?.[ja]}function ht(r){return new bs(r)}var Em=r=>r.toString().split("/").slice(1),Vr=r=>({match:e=>e.length<1?!1:r(e[0])?e.slice(1):!1,pattern:"fn"}),W=r=>({match:e=>Vr(t=>t===r).match(e),pattern:r}),hr=()=>({match:r=>Vr(e=>typeof e=="string").match(r),pattern:"{string}"}),Cn=()=>({match:r=>Vr(e=>!isNaN(parseInt(e))).match(r),pattern:"{number}"}),te=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{se.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),kn=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{cn.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Y=r=>({match:e=>{let t=r.match(e);return t===!1?e:t},pattern:`optional(${r.pattern})`}),_e=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1},pattern:`or(${r.map(e=>e.pattern).join(", ")})`}),z=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e},pattern:`and(${r.map(e=>e.pattern).join(", ")})`});function ue(...r){function e(o){let s=Em(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var Es=z(W("dns4"),hr()),vs=z(W("dns6"),hr()),As=z(W("dnsaddr"),hr()),Xa=z(W("dns"),hr()),tE=ue(Es,Y(te())),rE=ue(vs,Y(te())),nE=ue(As,Y(te())),oE=ue(_e(Xa,As,Es,vs),Y(te())),bf=z(W("ip4"),Vr(ps)),xf=z(W("ip6"),Vr(ms)),Ya=_e(bf,xf),Nt=_e(Ya,Xa,Es,vs,As),sE=ue(_e(Ya,z(_e(Xa,As,Es,vs),Y(te())))),iE=ue(bf),aE=ue(xf),cE=ue(Ya),Ja=z(Nt,W("tcp"),Cn()),Tn=z(Nt,W("udp"),Cn()),lE=ue(z(Ja,Y(te()))),uE=ue(Tn),Qa=z(Tn,W("quic"),Y(te())),Bs=z(Tn,W("quic-v1"),Y(te())),vm=_e(Qa,Bs),fE=ue(Qa),hE=ue(Bs),Za=_e(Nt,Ja,Tn,Qa,Bs),Ef=_e(z(Za,W("ws"),Y(te()))),dE=ue(Ef),vf=_e(z(Za,W("wss"),Y(te())),z(Za,W("tls"),Y(z(W("sni"),hr())),W("ws"),Y(te()))),pE=ue(vf),Af=z(Tn,W("webrtc-direct"),Y(kn()),Y(kn()),Y(te())),Bf=ue(Af),Sf=z(Bs,W("webtransport"),Y(kn()),Y(kn()),Y(te())),mE=ue(Sf),xs=_e(Ef,vf,z(Ja,Y(te())),z(vm,Y(te())),z(Nt,Y(te())),Af,Sf,te()),If=ue(xs),Am=z(xs,W("p2p-circuit"),te()),gE=ue(Am),Bm=_e(z(xs,W("p2p-circuit"),W("webrtc"),Y(te())),z(xs,W("webrtc"),Y(te())),z(W("webrtc"),Y(te()))),Cf=ue(Bm),Sm=_e(z(Nt,W("tcp"),Cn(),W("http"),Y(te())),z(Nt,W("http"),Y(te()))),yE=ue(Sm),Im=_e(z(Nt,W("tcp"),_e(z(W("443"),W("http")),z(Cn(),W("https"))),Y(te())),z(Nt,W("tls"),W("http"),Y(te())),z(Nt,W("https"),Y(te()))),wE=ue(Im),Cm=_e(z(W("memory"),hr(),Y(te()))),bE=ue(Cm);var kf=function(r,e,t){if(t||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 r.concat(s||Array.prototype.slice.call(e))},km=function(){function r(e,t,n){this.name=e,this.version=t,this.os=n,this.type="browser"}return r}();var Tm=function(){function r(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return r}();var Lm=function(){function r(e,t,n,o){this.name=e,this.version=t,this.os=n,this.bot=o,this.type="bot-device"}return r}();var Nm=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var _m=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var Rm=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Um=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Tf=3,Dm=[["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",Rm]],Lf=[["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 _f(r){return r?Nf(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new _m:typeof navigator<"u"?Nf(navigator.userAgent):Mm()}function Pm(r){return r!==""&&Dm.reduce(function(e,t){var n=t[0],o=t[1];if(e)return e;var s=o.exec(r);return!!s&&[n,s]},!1)}function Nf(r){var e=Pm(r);if(!e)return null;var t=e[0],n=e[1];if(t==="searchbot")return new Nm;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<Tf&&(o=kf(kf([],o,!0),Hm(Tf-o.length),!0)):o=[];var s=o.join("."),i=Om(r),a=Um.exec(r);return a&&a[1]?new Lm(t,s,i,a[1]):new km(t,s,i)}function Om(r){for(var e=0,t=Lf.length;e<t;e++){var n=Lf[e],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function Mm(){var r=typeof process<"u"&&process.version;return r?new Tm(process.version.slice(1)):null}function Hm(r){for(var e=[],t=0;t<r;t++)e.push("0");return e}function pe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ec=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},tc=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},Rf=r=>globalThis.DOMException===void 0?new tc(r):new DOMException(r),Uf=r=>{let e=r.reason===void 0?Rf("This operation was aborted."):r.reason;return e instanceof Error?e:Rf(e)};function Ln(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,a,l=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:m}=e;m.aborted&&f(Uf(m)),a=()=>{f(Uf(m))},m.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new ec;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(m){f(m)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(d.message=o??`Promise timed out after ${t} milliseconds`,f(d))},t),(async()=>{try{u(await r)}catch(m){f(m)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},l}var Df=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],rc=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Pf="libp2p+webrtc+v1/",Of=1e4;var Mf=466;var Hf=_f(),Nn=Hf!=null&&Hf.name==="firefox",Ss=async function*(){},Is=async r=>{},Fm=30*1e3;function Ff(r,e,t=Fm,n){r.readyState==="open"&&Promise.resolve().then(async()=>{if(r.bufferedAmount>0){n.log("%s drain channel with %d buffered bytes",e,r.bufferedAmount);let o=pe(),s=!1;r.bufferedAmountLowThreshold=0;let i=()=>{s||(n.log("%s drain channel closed before drain",e),o.resolve())};r.addEventListener("close",i,{once:!0}),r.addEventListener("bufferedamountlow",()=>{s=!0,r.removeEventListener("close",i),o.resolve()}),await Ln(o.promise,{milliseconds:t})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function nc(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??Df.map(e=>({urls:[e]})),r}var Vf=(r=32)=>Pf+[...Array(r)].map(()=>rc.at(Math.floor(Math.random()*rc.length))).join("");var dr=class{log;peerConnection;remoteAddr;timeline;metrics;source=Ss();sink=Is;constructor(e,t){this.log=e.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=t.remoteAddr,this.timeline=t.timeline,this.peerConnection=t.peerConnection;let n=this.peerConnection,o=n.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",n.connectionState,"initial state",o),(n.connectionState==="disconnected"||n.connectionState==="failed"||n.connectionState==="closed")&&(this.timeline.close=Date.now())}}async close(e){this.log.trace("closing connection"),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({close:!0})}abort(e){this.log.error("closing connection due to error",e),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({abort:!0})}};var Cs=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Kr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Cs(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new Cs(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var oc=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function jt(r={}){return Vm(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Vm(r,e){e=e??{};let t=e.onEnd,n=new Kr,o,s,i,a=pe(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,b)=>{s=x=>{s=null,n.push(x);try{h(r(n))}catch(p){b(p)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=pe()})}},l=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new Kr,s!=null?s({error:h}):(n.push({error:h}),o)),f=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 l({done:!1,value:h})},d=h=>i?o:(i=!0,h!=null?u(h):l({done:!0})),m=()=>(n=new Kr,d(),{done:!0}),y=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:y,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let b=h?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let x,p;b!=null&&(x=new Promise((S,N)=>{p=()=>{N(new oc)},b.addEventListener("abort",p)}));try{await Promise.race([a.promise,x])}finally{p!=null&&b!=null&&b?.removeEventListener("abort",p)}}},t==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(h){return g.throw(h),t!=null&&(t(h),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(h){return g.end(h),t!=null&&(t(h),t=void 0),o},get readableLength(){return g.readableLength},onEmpty:h=>g.onEmpty(h)},o}var ks=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function st(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new ks(t?.errorMessage,t?.errorCode,t?.errorName));let n,o=new ks(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var $f=Symbol.for("@achingbrain/uint8arraylist");function Kf(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function Ts(r){return!!r?.[$f]}var re=class r{bufs;length;[$f]=!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 t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(Ts(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(Ts(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Kf(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Kf(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(Ts(e))for(let n=0;n<e.length;n++)this.set(t+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,t){let{bufs:n,length:o}=this._subList(e,t);return be(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:be(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===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 l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let f=e-a;n.push(i.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!Ts(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(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;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 f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let m=this.get(f+d);if(n[d]!==m){u=Math.max(1,d-a[m]);break}}if(u===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=me(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let o=ye(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let o=ye(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let o=ye(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=me(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let o=ye(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let o=ye(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let o=ye(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let o=ye(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let o=ye(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!De(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((o,s)=>o+s.byteLength,0)),n.length=t,n}};function Gf(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function Wf(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function qf(r,e){let t=Gf(r).return?.();Wf(t)&&t.catch(n=>{e.error("could not cause iterator to return",n)})}var Km=5e3;function sc(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ls=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=pe(),this.closed=pe(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??Km,this.onEnd=e.onEnd,this.onCloseRead=e?.onCloseRead,this.onCloseWrite=e?.onCloseWrite,this.onReset=e?.onReset,this.onAbort=e?.onAbort,this.source=this.streamSource=jt({onEnd:t=>{t!=null?this.log.trace("source ended with error",t):this.log.trace("source ended"),this.onSourceEnd(t)}}),this.sink=this.sink.bind(this)}async sink(e){if(this.writeStatus!=="ready")throw new Yt(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";let t={signal:this.sinkController.signal};if(this.direction==="outbound"){let o=this.sendNewStream(t);sc(o)&&await o}let n=()=>{qf(e,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let o of e){o=o instanceof Uint8Array?new re(o):o;let s=this.sendData(o,t);sc(s)&&(this.sendingData=pe(),await s,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",n)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(t){throw this.log.trace("sink ended with error, calling abort with error",t),this.abort(t),t}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){this.status==="open"&&(this.log.trace("closing gracefully"),this.status="closing",await st(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(e={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let t=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),t==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await st(this.sink([]),e.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await st(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await st(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",e),this.log("try to send reset to remote");let t=this.sendReset();sc(t)&&t.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let e=new jn("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}};function ic(r){let e=new globalThis.AbortController;function t(){e.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var Ns=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},$r=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},_s=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},_n=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Rs(r){return r[Symbol.asyncIterator]!=null}function zf(r,e){if(r.byteLength>e)throw new $r("Message length too long")}var Ds=r=>{let e=ee(r),t=me(e);return ze(r,t),Ds.bytes=e,t};Ds.bytes=0;function Rn(r,e){e=e??{};let t=e.lengthEncoder??Ds,n=e?.maxDataLength??4194304;function*o(s){zf(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return Rs(r)?async function*(){for await(let s of r)yield*o(s)}():function*(){for(let s of r)yield*o(s)}()}Rn.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Ds,n=e?.maxDataLength??4194304;return zf(r,n),new re(t(r.byteLength),r)};var pr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(pr||(pr={}));var ac=r=>{let e=Ke(r);return ac.bytes=ee(e),e};ac.bytes=0;function Un(r,e){let t=new re,n=pr.LENGTH,o=-1,s=e?.lengthDecoder??ac,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===pr.LENGTH)try{if(o=s(t),o<0)throw new Ns("Invalid message length");if(o>a)throw new $r("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=pr.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new _s("Message length length too long");break}throw l}if(n===pr.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=pr.LENGTH}}}return Rs(r)?async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new _n("Unexpected end of input")}():function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new _n("Unexpected end of input")}()}Un.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return Un(n,{...e??{},onLength:s=>{t=s}})};var cc=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function Dn(r,e,t,n){let o=new cc(n?.errorMessage,n?.errorCode);return t?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){t?.removeEventListener("abort",u),r.removeEventListener(e,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),i(d);return}a(),s(f)},l=f=>{a(),i(f.detail)},u=()=>{a(),i(o)};t?.addEventListener("abort",u),r.addEventListener(e,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var Oe;(function(r){let e;(function(o){o.FIN="FIN",o.STOP_SENDING="STOP_SENDING",o.RESET="RESET",o.FIN_ACK="FIN_ACK"})(e=r.Flag||(r.Flag={}));let t;(function(o){o[o.FIN=0]="FIN",o[o.STOP_SENDING=1]="STOP_SENDING",o[o.RESET=2]="RESET",o[o.FIN_ACK=3]="FIN_ACK"})(t||(t={})),function(o){o.codec=()=>lr(t)}(e=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=nt((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.flag!=null&&(s.uint32(8),r.Flag.codec().encode(o.flag,s)),o.message!=null&&(s.uint32(18),s.bytes(o.message)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.flag=r.Flag.codec().decode(o);break}case 2:{a.message=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>rt(o,r.codec()),r.decode=(o,s)=>tt(o,r.codec(),s)})(Oe||(Oe={}));var Wm=2*1024*1024,qm=30*1e3,Pn=16*1024;function zm(r=Pn){let e=ee(r-ee(r)),t=1+ee(Object.keys(Oe.Flag).length-1),n=1,o=r-e-t-n,s=ee(o);return e+t+n+s}var jm=zm(),Zm=5e3,Xm=5e3,lc=class extends Ls{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;closeController;constructor(e){let t=e.onEnd;switch(e.onEnd=o=>{this.log.trace("readable and writeable ends closed",this.status),Promise.resolve(async()=>{if(!(this.timeline.abort!=null||this.timeline.reset!==null))try{await Ln(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(s){this.log.error("error receiving FIN_ACK",s)}}).then(()=>{this.incomingData.end(),this.channel.close(),t?.(o)}).catch(s=>{this.log.error("error ending stream",s)})},super(e),this.channel=e.channel,this.channel.binaryType="arraybuffer",this.incomingData=jt(),this.bufferedAmountLowEventTimeout=e.bufferedAmountLowEventTimeout??qm,this.maxBufferedAmount=e.maxBufferedAmount??Wm,this.maxMessageSize=(e.maxMessageSize??Pn)-jm,this.receiveFinAck=pe(),this.finAckTimeout=e.closeTimeout??Zm,this.openTimeout=e.openTimeout??Xm,this.closeController=new AbortController,this.channel.readyState){case"open":this.timeline.open=new Date().getTime();break;case"closed":case"closing":(this.timeline.close===void 0||this.timeline.close===0)&&(this.timeline.close=Date.now());break;case"connecting":break;default:throw this.log.error("unknown datachannel state %s",this.channel.readyState),new Yt("Unknown datachannel state")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime()},this.channel.onclose=o=>{this.log.trace("received onclose event"),this.closeController.abort(),this.receiveFinAck.resolve(),this.close().catch(s=>{this.log.error("error closing stream after channel closed",s)})},this.channel.onerror=o=>{this.log.trace("received onerror event"),this.closeController.abort();let s=o.error;this.abort(s)},this.channel.onmessage=async o=>{let{data:s}=o;s===null||s.byteLength===0||this.incomingData.push(new Uint8Array(s,0,s.byteLength))};let n=this;Promise.resolve().then(async()=>{for await(let o of Un(this.incomingData)){let s=n.processIncomingProtobuf(o);s!=null&&n.sourcePush(new re(s))}}).catch(o=>{this.log.error("error processing incoming data channel messages",o)})}sendNewStream(){}async _sendMessage(e,t=!0){if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new Yt(`Invalid datachannel state - ${this.channel.readyState}`);if(this.channel.readyState!=="open"){let n=AbortSignal.timeout(this.openTimeout),o=ic([this.closeController.signal,n]);try{this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await Dn(this.channel,"open",o)}finally{o.clear()}this.log('channel state is now "%s", sending data',this.channel.readyState)}if(t&&this.channel.bufferedAmount>this.maxBufferedAmount){let n=AbortSignal.timeout(this.bufferedAmountLowEventTimeout),o=ic([this.closeController.signal,n]);try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await Dn(this.channel,"bufferedamountlow",o)}catch(s){throw n.aborted?new Yn(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`):s}finally{o.clear()}}try{this.channel.send(e.subarray())}catch(n){this.log.error("error while sending message",n)}}async sendData(e){for(this.log.trace("-> will send %d bytes",e.byteLength),e=e.sublist();e.byteLength>0;){let t=Math.min(e.byteLength,this.maxMessageSize),n=e.subarray(0,t),o=Oe.encode({message:n}),s=Rn.single(o);this.log.trace("-> sending message %s",this.channel.readyState),await this._sendMessage(s),this.log.trace("-> sent message %s",this.channel.readyState),e.consume(t)}this.log.trace("-> sent data %s",this.channel.readyState)}async sendReset(){try{await this._sendFlag(Oe.Flag.RESET)}catch(e){this.log.error("failed to send reset - %e",e)}}async sendCloseWrite(e){if(this.channel.readyState!=="open"){this.receiveFinAck.resolve();return}if(await this._sendFlag(Oe.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await st(this.receiveFinAck.promise,e?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorName:"FinAckNotReceivedError"})}catch(n){this.log.error("failed to await FIN_ACK",n)}}else this.log.trace("sending FIN failed, not awaiting FIN_ACK");this.receiveFinAck.resolve()}async sendCloseRead(){this.channel.readyState==="open"&&await this._sendFlag(Oe.Flag.STOP_SENDING)}processIncomingProtobuf(e){let t=Oe.decode(e);if(t.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',t.flag,this.writeStatus,this.readStatus),t.flag===Oe.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Oe.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),t.flag===Oe.Flag.RESET&&this.reset(),t.flag===Oe.Flag.STOP_SENDING&&this.remoteCloseRead(),t.flag===Oe.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),this.readStatus==="ready")return t.message}async _sendFlag(e){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',this.channel.readyState,e.toString()),!1;this.log.trace("sending flag %s",e.toString());let t=Oe.encode({flag:e}),n=Rn.single(t);try{return await this._sendMessage(n,!1),!0}catch(o){this.log.error("could not send flag %s - %e",e.toString(),o)}return!1}};function Gr(r){let{channel:e,direction:t}=r;return new lc({id:t==="inbound"?`i${e.id}`:`r${e.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${t}:${e.id}`),...r})}var jf="/webrtc",Zt=class{protocol;peerConnection;bufferedStreams=[];metrics;dataChannelOptions;components;log;constructor(e,t){this.components=e,this.peerConnection=t.peerConnection,this.metrics=t.metrics,this.protocol=t.protocol??jf,this.dataChannelOptions=t.dataChannelOptions??{},this.log=e.logger.forComponent("libp2p:webrtc:muxerfactory"),this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace('incoming early datachannel with channel id %d and label "%s"',n.id),n.label==="init"){this.log.trace("closing early init channel"),n.close();return}let o={},s=Gr({channel:n,direction:"inbound",onEnd:i=>{o.onEnd(i)},logger:e.logger,...this.dataChannelOptions});o.stream=s,o.channel=n,o.onEnd=()=>{this.bufferedStreams=this.bufferedStreams.filter(i=>i.stream.id!==s.id)},this.bufferedStreams.push(o)}}createStreamMuxer(e){return new uc(this.components,{...e,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},uc=class{init;streams;protocol;log;peerConnection;dataChannelOptions;metrics;logger;constructor(e,t){this.init=t,this.log=e.logger.forComponent("libp2p:webrtc:muxer"),this.logger=e.logger,this.streams=t.streams.map(n=>n.stream),this.peerConnection=t.peerConnection,this.protocol=t.protocol??jf,this.metrics=t.metrics,this.dataChannelOptions=t.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace("incoming datachannel with channel id %d",n.id),n.label==="init"){this.log.trace("closing init channel"),n.close();return}let o=n.id,s=Gr({channel:n,direction:"inbound",onEnd:()=>{this.#e(s,n),this.log("incoming channel %s ended",o)},logger:this.logger,...this.dataChannelOptions});this.streams.push(s),this.metrics?.increment({incoming_stream:!0}),t?.onIncomingStream?.(s)},this.init.streams.length>0&&queueMicrotask(()=>{this.init.streams.forEach(n=>{n.onEnd=()=>{this.log("incoming early channel %s ended with state %s",n.channel.id,n.channel.readyState),this.#e(n.stream,n.channel)},this.metrics?.increment({incoming_stream:!0}),this.init?.onIncomingStream?.(n.stream)})})}#e(e,t){this.log.trace("stream %s %s %s onEnd",e.direction,e.id,e.protocol),Ff(t,`${e.direction} ${e.id} ${e.protocol}`,this.dataChannelOptions.drainTimeout,{log:this.log}),this.streams=this.streams.filter(n=>n.id!==e.id),this.metrics?.increment({stream_end:!0}),this.init?.onStreamEnd?.(e)}async close(e){try{await Promise.all(this.streams.map(async t=>t.close(e)))}catch(t){this.abort(t)}}abort(e){for(let t of this.streams)t.abort(e)}source=Ss();sink=Is;newStream(){let e=this.peerConnection.createDataChannel(""),t=e.id;this.log.trace("opened outgoing datachannel with channel id %s",t);let n=Gr({channel:e,direction:"outbound",onEnd:()=>{this.#e(n,e),this.log("outgoing channel %s ended",t)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(n),this.metrics?.increment({outgoing_stream:!0}),n}};var Ps=globalThis.RTCPeerConnection,Os=globalThis.RTCSessionDescription,Zf=globalThis.RTCIceCandidate;var fc=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=pe(),this.haveNext=pe()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=pe(),e}async throw(e){return this.ended=!0,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return await this._push(void 0),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=pe(),await st(this.readNext.promise,t?.signal,t)}};function Xf(){return new fc}var Ms=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var hc=class extends Error{code;constructor(e,t){super(e),this.code=t}},dc=class extends hc{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Yf(r,e){let t=Xf();r.sink(t).catch(async i=>{await t.end(i)}),r.sink=async i=>{for await(let a of i)await t.push(a);await t.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new re;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new dc("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:d}=await Promise.race([n.next(),l]);return f===!0?new re:d}for(;o.byteLength<i;){let{value:f,done:d}=await Promise.race([n.next(),l]);if(d===!0)throw new Ms("unexpected end of input");o.append(f)}let u=o.sublist(0,i);return o.consume(i),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await t.push(i,a):await t.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){e?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Hs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Fs=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Vs=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function On(r,e={}){let t=Yf(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=ee(e.maxDataLength));let n=e?.lengthDecoder??Ke,o=e?.lengthEncoder??ze;return{read:async i=>{let a=-1,c=new re;for(;;){c.append(await t.read(1,i));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Hs("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new Vs("message length length too long");if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new Fs("message length too long");return t.read(a,i)},write:async(i,a)=>{await t.write(new re(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new re(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap:()=>t.unwrap()}}function Ks(r,e){let t=On(r,e),n={read:async(o,s)=>{let i=await t.read(s);return o.decode(i)},write:async(o,s,i)=>{await t.write(s.encode(o),i)},writeV:async(o,s,i)=>{await t.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:()=>t.unwrap()};return n}var Ge=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};var Xt=class extends Error{constructor(e){super(`WebRTC transport error: ${e}`),this.name="WebRTCTransportError"}},Ze=class extends Xt{constructor(e="SDP handshake failed"){super(e),this.name="SDPHandshakeFailedError"}};var $s=class extends Xt{constructor(e,t){super(`Invalid fingerprint "${e}" within ${t}`),this.name="WebRTC/InvalidFingerprintError"}};var Gs=class extends Xt{constructor(e){super(`A method (${e}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},Ws=class extends Xt{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 Ve;(function(r){let e;(function(o){o.SDP_OFFER="SDP_OFFER",o.SDP_ANSWER="SDP_ANSWER",o.ICE_CANDIDATE="ICE_CANDIDATE"})(e=r.Type||(r.Type={}));let t;(function(o){o[o.SDP_OFFER=0]="SDP_OFFER",o[o.SDP_ANSWER=1]="SDP_ANSWER",o[o.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(t||(t={})),function(o){o.codec=()=>lr(t)}(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=nt((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.data!=null&&(s.uint32(18),s.string(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.data=o.string();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>rt(o,r.codec()),r.decode=(o,s)=>tt(o,r.codec(),s)})(Ve||(Ve={}));var qs=async(r,e,t)=>{try{let n=pe();for(Ym(r,n);;){let o=await Promise.race([n.promise,e.read({signal:t.signal}).catch(()=>{})]);if(o==null){t.signal?.throwIfAborted();break}if(o.type!==Ve.Type.ICE_CANDIDATE)throw new Xn("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){t.onProgress?.(new Ge("webrtc:end-of-ice-candidates")),t.log.trace("end-of-candidates received");continue}let i=new Zf(s);t.log.trace("%s received new ICE candidate %o",t.direction,s);try{t.onProgress?.(new Ge("webrtc:add-ice-candidate",i.candidate)),await r.addIceCandidate(i)}catch(a){t.log.error("%s bad candidate received",t.direction,s,a)}}}catch(n){if(t.log.error("%s error parsing ICE candidate",t.direction,n),t.signal?.aborted===!0&&zs(r)!=="connected")throw n}};function zs(r){return Nn?r.iceConnectionState:r.connectionState}function Ym(r,e){r[Nn?"oniceconnectionstatechange":"onconnectionstatechange"]=t=>{switch(zs(r)){case"connected":e.resolve();break;case"failed":case"disconnected":case"closed":e.reject(new zn("RTCPeerConnection was closed"));break;default:break}}}async function Jf({rtcConfiguration:r,dataChannel:e,signal:t,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=Qf(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",u);let f=u.getPeerId();if(f==null)throw new oe("Relay peer was missing");let d=s.getConnections(Mr(f)),m,y=!1;d.length===0?(l?.(new Ge("webrtc:dial-relay")),m=await i.dial(u,{signal:t,onProgress:l}),y=!0):(l?.(new Ge("webrtc:reuse-relay-connection")),m=d[0]);try{l?.(new Ge("webrtc:open-signaling-stream"));let g=await m.newStream(js,{signal:t,runOnLimitedConnection:!0}),h=Ks(g).pb(Ve),b=new Ps(r),x=new Zt({logger:c},{peerConnection:b,dataChannelOptions:e});try{let p=b.createDataChannel("init");b.onicecandidate=({candidate:B})=>{let T=JSON.stringify(B?.toJSON()??null);a.trace("initiator sending ICE candidate %o",B),h.write({type:Ve.Type.ICE_CANDIDATE,data:T},{signal:t}).catch(C=>{a.error("error sending ICE candidate",C)})},b.onicecandidateerror=B=>{a.error("initiator ICE candidate error",B)};let S=await b.createOffer().catch(B=>{throw a.error("could not execute createOffer",B),new Ze("Failed to set createOffer")});a.trace("initiator send SDP offer %s",S.sdp),l?.(new Ge("webrtc:send-sdp-offer")),await h.write({type:Ve.Type.SDP_OFFER,data:S.sdp},{signal:t}),await b.setLocalDescription(S).catch(B=>{throw a.error("could not execute setLocalDescription",B),new Ze("Failed to set localDescription")}),l?.(new Ge("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let N=await h.read({signal:t});if(N.type!==Ve.Type.SDP_ANSWER)throw new Ze("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",N.data);let L=new Os({type:"answer",sdp:N.data});return await b.setRemoteDescription(L).catch(B=>{throw a.error("could not execute setRemoteDescription",B),new Ze("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),l?.(new Ge("webrtc:read-ice-candidates")),await qs(b,h,{direction:"initiator",signal:t,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),p.close(),l?.(new Ge("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await g.close({signal:t}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:b,muxerFactory:x}}catch(p){throw a.error("outgoing signaling error",p),b.close(),g.abort(p),p}finally{b.onicecandidate=null,b.onicecandidateerror=null}}finally{if(y)try{await m.close({signal:t})}catch(g){m.abort(g)}}}var Jm=ue(If.matchers[0],W("p2p-circuit")),Zs=class r extends wr{transportManager;shutdownController;constructor(e,t){super(),this.transportManager=e.transportManager,this.shutdownController=t.shutdownController}async listen(){queueMicrotask(()=>{this.safeDispatchEvent("listening")})}getAddrs(){return this.transportManager.getListeners().filter(e=>!(e instanceof r)).map(e=>e.getAddrs().filter(t=>Jm.exactMatch(t)).map(t=>t.encapsulate("/webrtc"))).flat()}updateAnnounceAddrs(){}async close(){this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function eh({peerConnection:r,stream:e,signal:t,connection:n,log:o}){o.trace("new inbound signaling stream");let s=Ks(e).pb(Ve);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:Ve.Type.ICE_CANDIDATE,data:f},{signal:t}).catch(d=>{o.error("error sending ICE candidate",d)})},o.trace("recipient read SDP offer");let a=await s.read({signal:t});if(a.type!==Ve.Type.SDP_OFFER)throw new Ze(`expected message type SDP_OFFER, received: ${a.type??"undefined"} `);o.trace("recipient received SDP offer %s",a.data);let c=new Os({type:"offer",sdp:a.data});await r.setRemoteDescription(c).catch(u=>{throw o.error("could not execute setRemoteDescription",u),new Ze("Failed to set remoteDescription")});let l=await r.createAnswer().catch(u=>{throw o.error("could not execute createAnswer",u),new Ze("Failed to create answer")});o.trace("recipient send SDP answer %s",l.sdp),await s.write({type:Ve.Type.SDP_ANSWER,data:l.sdp},{signal:t}),await r.setLocalDescription(l).catch(u=>{throw o.error("could not execute setLocalDescription",u),new Ze("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await qs(r,s,{direction:"recipient",signal:t,log:o})}catch(a){if(zs(r)!=="connected")throw o.error("error while handling signaling stream from peer %a",n.remoteAddr,a),r.close(),a;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",n.remoteAddr,a)}let i=ht(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return o.trace("recipient connected to remote address %s",i),{remoteAddress:i}}var Qm="/webrtc",eg="/p2p-circuit",js="/webrtc-signaling/0.0.1",tg=30*1e3,Xs=class{components;init;log;_started=!1;metrics;shutdownController;constructor(e,t={}){this.components=e,this.init=t,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"})})}[Wn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[br]=["@libp2p/transport"];[Xc]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(js,e=>{this._onProtocol(e).catch(t=>{this.log.error("failed to handle incoming connect from %p",e.connection.remotePeer,t)})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(js),this._started=!1}createListener(e){return new Zs(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(Cf.exactMatch)}dialFilter(e){return this.listenFilter(e)}async dial(e,t){this.log.trace("dialing address: %a",e);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await Jf({rtcConfiguration:await nc(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:e,dataChannelOptions:this.init.dataChannel,signal:t.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:t.onProgress}),i=new dr(this.components,{peerConnection:o,timeline:{open:Date.now()},remoteAddr:n,metrics:this.metrics?.dialerEvents}),a=await t.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,muxerFactory:s,onProgress:t.onProgress});return this._closeOnShutdown(o,i),a}async _onProtocol({connection:e,stream:t}){let n=AbortSignal.timeout(this.init.inboundConnectionTimeout??tg),o=new Ps(await nc(this.init.rtcConfiguration)),s=new Zt(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await eh({peerConnection:o,connection:e,stream:t,signal:n,log:this.log});await t.close({signal:n});let a=new dr(this.components,{peerConnection:o,timeline:{open:new Date().getTime()},remoteAddr:i,metrics:this.metrics?.listenerEvents});await this.components.upgrader.upgradeInbound(a,{skipEncryption:!0,skipProtection:!0,muxerFactory:s}),this._closeOnShutdown(o,a)}catch(i){throw this.log.error("incoming signaling error",i),o.close(),t.abort(i),i}}_closeOnShutdown(e,t){let n=()=>{t.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection",o)})};this.shutdownController.signal.addEventListener("abort",n),e.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function Qf(r){let e=r.toString().split(Qm+"/");if(e.length!==2)throw new oe("webrtc protocol was not present in multiaddr");if(!e[0].includes(eg))throw new oe("p2p-circuit protocol was not present in multiaddr");let t=ht(e[0]),o=ht("/"+e[1]).getPeerId();if(o==null)throw new oe("destination peer id was missing");let s=t.protos().pop();if(s===void 0)throw new oe("invalid multiaddr");return s.name!=="p2p"&&(t=t.encapsulate(`/p2p/${o}`)),{baseAddr:t,peerId:Mr(o)}}var Ys=class extends wr{async listen(){throw new Gs("WebRTCTransport.createListener")}getAddrs(){return[]}updateAnnounceAddrs(){}async close(){}};function Js(r){return r[Symbol.asyncIterator]!=null}var Qs=r=>{let e=ee(r),t=me(e);return ze(r,t),Qs.bytes=e,t};Qs.bytes=0;function th(r,e){e=e??{};let t=e.lengthEncoder??Qs;function*n(o){let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Js(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}th.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Qs;return new re(t(r.byteLength),r)};var ei=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ti=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},ri=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Mn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var rg=8,ng=1024*1024*4,mr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(mr||(mr={}));var pc=r=>{let e=Ke(r);return pc.bytes=ee(e),e};pc.bytes=0;function Hn(r,e){let t=new re,n=mr.LENGTH,o=-1,s=e?.lengthDecoder??pc,i=e?.maxLengthLength??rg,a=e?.maxDataLength??ng;function*c(){for(;t.byteLength>0;){if(n===mr.LENGTH)try{if(o=s(t),o<0)throw new ei("Invalid message length");if(o>a)throw new ti("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=mr.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new ri("Message length length too long");break}throw l}if(n===mr.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=mr.LENGTH}}}return Js(r)?async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Mn("Unexpected end of input")}():function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new Mn("Unexpected end of input")}()}Hn.fromReader=(r,e)=>{let t=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}}();return Hn(n,{...e??{},onLength:s=>{t=s}})};function mc(){let r=pe(),e=!1;return{sink:async t=>{if(e)throw new Error("already piped");e=!0,r.resolve(t)},source:async function*(){yield*await r.promise}()}}function rh(){let r=mc(),e=mc();return[{source:r.source,sink:e.sink},{source:e.source,sink:r.sink}]}function og(r){return r[Symbol.asyncIterator]!=null}function sg(...r){let e=[];for(let t of r)og(t)||e.push(t);return e.length===r.length?function*(){for(let t of e)yield*t}():async function*(){let t=jt({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)t.push(o)})),t.end()}catch(n){t.end(n)}}),yield*t}()}var nh=sg;function oh(r,...e){if(r==null)throw new Error("Empty pipeline");if(gc(r)){let n=r;r=()=>n.source}else if(ih(r)||sh(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&gc(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)gc(t[n])&&(t[n]=ag(t[n]));return ig(...t)}var ig=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},sh=r=>r?.[Symbol.asyncIterator]!=null,ih=r=>r?.[Symbol.iterator]!=null,gc=r=>r==null?!1:r.sink!=null&&r.source!=null,ag=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=jt({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(sh(s))o=async function*(){yield*s,n.end()};else if(ih(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return nh(n,o())}return r.source};var Wr=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function ni(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function yc(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Re(r,...e){if(!yc(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function wc(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function ah(r,e){Re(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function bc(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}var _t=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),ch=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),cg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!cg)throw new Error("Non little-endian hardware is not supported");function lg(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function oi(r){if(typeof r=="string")r=lg(r);else if(yc(r))r=si(r);else throw new Error("Uint8Array expected, got "+typeof r);return r}function lh(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function uh(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}var xc=(r,e)=>{function t(n,...o){if(Re(n),r.nonceLength!==void 0){let u=o[0];if(!u)throw new Error("nonce / iv required");r.varSizeNonce?Re(u):Re(u,r.nonceLength)}let s=r.tagLength;s&&o[1]!==void 0&&Re(o[1]);let i=e(n,...o),a=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");Re(f)}},c=!1;return{encrypt(u,f){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Re(u),a(i.encrypt.length,f),i.encrypt(u,f)},decrypt(u,f){if(Re(u),s&&u.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(i.decrypt.length,f),i.decrypt(u,f)}}}return Object.assign(t,r),t};function Ec(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(e.length!==r)throw new Error("invalid output length, expected "+r+", got: "+e.length);if(t&&!ug(e))throw new Error("invalid output, must be aligned");return e}function vc(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(t>>o&s),a=Number(t&s),c=n?4:0,l=n?0:4;r.setUint32(e+c,i,n),r.setUint32(e+l,a,n)}function ug(r){return r.byteOffset%4===0}function si(r){return Uint8Array.from(r)}function Rt(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}var hh=r=>Uint8Array.from(r.split("").map(e=>e.charCodeAt(0))),fg=hh("expand 16-byte k"),hg=hh("expand 32-byte k"),dg=_t(fg),pg=_t(hg);function P(r,e){return r<<e|r>>>32-e}function Ac(r){return r.byteOffset%4===0}var ii=64,mg=16,dh=2**32-1,fh=new Uint32Array;function gg(r,e,t,n,o,s,i,a){let c=o.length,l=new Uint8Array(ii),u=_t(l),f=Ac(o)&&Ac(s),d=f?_t(o):fh,m=f?_t(s):fh;for(let y=0;y<c;i++){if(r(e,t,n,u,i,a),i>=dh)throw new Error("arx: counter overflow");let g=Math.min(ii,c-y);if(f&&g===ii){let h=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let b=0,x;b<mg;b++)x=h+b,m[x]=d[x]^u[b];y+=ii;continue}for(let h=0,b;h<g;h++)b=y+h,s[b]=o[b]^l[h];y+=g}}function Bc(r,e){let{allowShortKeys:t,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=lh({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return ni(o),ni(i),bc(s),bc(t),(a,c,l,u,f=0)=>{Re(a),Re(c),Re(l);let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),Re(u),ni(f),f<0||f>=dh)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let m=[],y=a.length,g,h;if(y===32)m.push(g=si(a)),h=pg;else if(y===16&&t)g=new Uint8Array(32),g.set(a),g.set(a,16),h=dg,m.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${y}`);Ac(c)||m.push(c=si(c));let b=_t(g);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,b,_t(c.subarray(0,16)),b),c=c.subarray(16)}let x=16-o;if(x!==c.length)throw new Error(`arx: nonce must be ${x} or 16 bytes`);if(x!==12){let S=new Uint8Array(12);S.set(c,s?0:12-c.length),c=S,m.push(c)}let p=_t(c);return gg(r,h,b,p,l,u,f,i),Rt(...m),u}}var Se=(r,e)=>r[e++]&255|(r[e++]&255)<<8,Sc=class{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=oi(e),Re(e,32);let t=Se(e,0),n=Se(e,2),o=Se(e,4),s=Se(e,6),i=Se(e,8),a=Se(e,10),c=Se(e,12),l=Se(e,14);this.r[0]=t&8191,this.r[1]=(t>>>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|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Se(e,16+2*u)}process(e,t,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],d=i[5],m=i[6],y=i[7],g=i[8],h=i[9],b=Se(e,t+0),x=Se(e,t+2),p=Se(e,t+4),S=Se(e,t+6),N=Se(e,t+8),L=Se(e,t+10),B=Se(e,t+12),T=Se(e,t+14),C=s[0]+(b&8191),H=s[1]+((b>>>13|x<<3)&8191),U=s[2]+((x>>>10|p<<6)&8191),M=s[3]+((p>>>7|S<<9)&8191),V=s[4]+((S>>>4|N<<12)&8191),I=s[5]+(N>>>1&8191),k=s[6]+((N>>>14|L<<2)&8191),E=s[7]+((L>>>11|B<<5)&8191),w=s[8]+((B>>>8|T<<8)&8191),A=s[9]+(T>>>5|o),v=0,_=v+C*a+H*(5*h)+U*(5*g)+M*(5*y)+V*(5*m);v=_>>>13,_&=8191,_+=I*(5*d)+k*(5*f)+E*(5*u)+w*(5*l)+A*(5*c),v+=_>>>13,_&=8191;let R=v+C*c+H*a+U*(5*h)+M*(5*g)+V*(5*y);v=R>>>13,R&=8191,R+=I*(5*m)+k*(5*d)+E*(5*f)+w*(5*u)+A*(5*l),v+=R>>>13,R&=8191;let O=v+C*l+H*c+U*a+M*(5*h)+V*(5*g);v=O>>>13,O&=8191,O+=I*(5*y)+k*(5*m)+E*(5*d)+w*(5*f)+A*(5*u),v+=O>>>13,O&=8191;let K=v+C*u+H*l+U*c+M*a+V*(5*h);v=K>>>13,K&=8191,K+=I*(5*g)+k*(5*y)+E*(5*m)+w*(5*d)+A*(5*f),v+=K>>>13,K&=8191;let F=v+C*f+H*u+U*l+M*c+V*a;v=F>>>13,F&=8191,F+=I*(5*h)+k*(5*g)+E*(5*y)+w*(5*m)+A*(5*d),v+=F>>>13,F&=8191;let G=v+C*d+H*f+U*u+M*l+V*c;v=G>>>13,G&=8191,G+=I*a+k*(5*h)+E*(5*g)+w*(5*y)+A*(5*m),v+=G>>>13,G&=8191;let j=v+C*m+H*d+U*f+M*u+V*l;v=j>>>13,j&=8191,j+=I*c+k*a+E*(5*h)+w*(5*g)+A*(5*y),v+=j>>>13,j&=8191;let ae=v+C*y+H*m+U*d+M*f+V*u;v=ae>>>13,ae&=8191,ae+=I*l+k*c+E*a+w*(5*h)+A*(5*g),v+=ae>>>13,ae&=8191;let ce=v+C*g+H*y+U*m+M*d+V*f;v=ce>>>13,ce&=8191,ce+=I*u+k*l+E*c+w*a+A*(5*h),v+=ce>>>13,ce&=8191;let fe=v+C*h+H*g+U*y+M*m+V*d;v=fe>>>13,fe&=8191,fe+=I*f+k*u+E*l+w*c+A*a,v+=fe>>>13,fe&=8191,v=(v<<2)+v|0,v=v+_|0,_=v&8191,v=v>>>13,R+=v,s[0]=_,s[1]=R,s[2]=O,s[3]=K,s[4]=F,s[5]=G,s[6]=j,s[7]=ae,s[8]=ce,s[9]=fe}finalize(){let{h:e,pad:t}=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]+t[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+t[a]|0)+(i>>>16)|0,e[a]=i&65535;Rt(n)}update(e){wc(this);let{buffer:t,blockLen:n}=this;e=oi(e);let 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}t.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){Rt(this.h,this.r,this.buffer,this.pad)}digestInto(e){wc(this),ah(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:o}=this;if(o){for(t[o++]=1;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}};function yg(r){let e=(n,o)=>r(o).update(oi(n)).digest(),t=r(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=n=>r(n),e}var ph=yg(r=>new Sc(r));function yh(r,e,t,n,o,s=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=e[0],f=e[1],d=e[2],m=e[3],y=e[4],g=e[5],h=e[6],b=e[7],x=o,p=t[0],S=t[1],N=t[2],L=i,B=a,T=c,C=l,H=u,U=f,M=d,V=m,I=y,k=g,E=h,w=b,A=x,v=p,_=S,R=N;for(let K=0;K<s;K+=2)L=L+H|0,A=P(A^L,16),I=I+A|0,H=P(H^I,12),L=L+H|0,A=P(A^L,8),I=I+A|0,H=P(H^I,7),B=B+U|0,v=P(v^B,16),k=k+v|0,U=P(U^k,12),B=B+U|0,v=P(v^B,8),k=k+v|0,U=P(U^k,7),T=T+M|0,_=P(_^T,16),E=E+_|0,M=P(M^E,12),T=T+M|0,_=P(_^T,8),E=E+_|0,M=P(M^E,7),C=C+V|0,R=P(R^C,16),w=w+R|0,V=P(V^w,12),C=C+V|0,R=P(R^C,8),w=w+R|0,V=P(V^w,7),L=L+U|0,R=P(R^L,16),E=E+R|0,U=P(U^E,12),L=L+U|0,R=P(R^L,8),E=E+R|0,U=P(U^E,7),B=B+M|0,A=P(A^B,16),w=w+A|0,M=P(M^w,12),B=B+M|0,A=P(A^B,8),w=w+A|0,M=P(M^w,7),T=T+V|0,v=P(v^T,16),I=I+v|0,V=P(V^I,12),T=T+V|0,v=P(v^T,8),I=I+v|0,V=P(V^I,7),C=C+H|0,_=P(_^C,16),k=k+_|0,H=P(H^k,12),C=C+H|0,_=P(_^C,8),k=k+_|0,H=P(H^k,7);let O=0;n[O++]=i+L|0,n[O++]=a+B|0,n[O++]=c+T|0,n[O++]=l+C|0,n[O++]=u+H|0,n[O++]=f+U|0,n[O++]=d+M|0,n[O++]=m+V|0,n[O++]=y+I|0,n[O++]=g+k|0,n[O++]=h+E|0,n[O++]=b+w|0,n[O++]=x+A|0,n[O++]=p+v|0,n[O++]=S+_|0,n[O++]=N+R|0}function wg(r,e,t,n){let o=r[0],s=r[1],i=r[2],a=r[3],c=e[0],l=e[1],u=e[2],f=e[3],d=e[4],m=e[5],y=e[6],g=e[7],h=t[0],b=t[1],x=t[2],p=t[3];for(let N=0;N<20;N+=2)o=o+c|0,h=P(h^o,16),d=d+h|0,c=P(c^d,12),o=o+c|0,h=P(h^o,8),d=d+h|0,c=P(c^d,7),s=s+l|0,b=P(b^s,16),m=m+b|0,l=P(l^m,12),s=s+l|0,b=P(b^s,8),m=m+b|0,l=P(l^m,7),i=i+u|0,x=P(x^i,16),y=y+x|0,u=P(u^y,12),i=i+u|0,x=P(x^i,8),y=y+x|0,u=P(u^y,7),a=a+f|0,p=P(p^a,16),g=g+p|0,f=P(f^g,12),a=a+f|0,p=P(p^a,8),g=g+p|0,f=P(f^g,7),o=o+l|0,p=P(p^o,16),y=y+p|0,l=P(l^y,12),o=o+l|0,p=P(p^o,8),y=y+p|0,l=P(l^y,7),s=s+u|0,h=P(h^s,16),g=g+h|0,u=P(u^g,12),s=s+u|0,h=P(h^s,8),g=g+h|0,u=P(u^g,7),i=i+f|0,b=P(b^i,16),d=d+b|0,f=P(f^d,12),i=i+f|0,b=P(b^i,8),d=d+b|0,f=P(f^d,7),a=a+c|0,x=P(x^a,16),m=m+x|0,c=P(c^m,12),a=a+c|0,x=P(x^a,8),m=m+x|0,c=P(c^m,7);let S=0;n[S++]=o,n[S++]=s,n[S++]=i,n[S++]=a,n[S++]=h,n[S++]=b,n[S++]=x,n[S++]=p}var bg=Bc(yh,{counterRight:!1,counterLength:4,allowShortKeys:!1}),xg=Bc(yh,{counterRight:!1,counterLength:8,extendNonceFn:wg,allowShortKeys:!1});var Eg=new Uint8Array(16),mh=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(Eg.subarray(t))},vg=new Uint8Array(32);function gh(r,e,t,n,o){let s=r(e,t,vg),i=ph.create(s);o&&mh(i,o),mh(i,n);let a=new Uint8Array(16),c=ch(a);vc(c,0,BigInt(o?o.length:0),!0),vc(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return Rt(s,a),l}var wh=r=>(e,t,n)=>({encrypt(s,i){let a=s.length;i=Ec(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);r(e,t,c,c,1);let l=gh(r,e,t,c,n);return i.set(l,a),Rt(l),i},decrypt(s,i){i=Ec(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=gh(r,e,t,a,n);if(!uh(c,l))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),r(e,t,i,i,1),Rt(l),i}}),Ic=xc({blockSize:64,nonceLength:12,tagLength:16},wh(bg)),kB=xc({blockSize:64,nonceLength:24,tagLength:16},wh(xg));function xh(r,e,t){return en(r),t===void 0&&(t=new Uint8Array(r.outputLen)),Or(r,Pt(t),Pt(e))}var Cc=new Uint8Array([0]),bh=new Uint8Array;function Eh(r,e,t,n=32){if(en(r),Qn(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);t===void 0&&(t=bh);let s=new Uint8Array(o*r.outputLen),i=Or.create(r,e),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)Cc[0]=l+1,a.update(l===0?bh:c).update(t).update(Cc).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),Cc.fill(0),s.slice(0,n)}var kc={hashSHA256(r){return ct(r.subarray())},getHKDF(r,e){let t=xh(ct,e,r),o=Eh(ct,t,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=an.utils.randomPrivateKey();return{publicKey:an.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:an.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return an.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return Ic(n,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,n,o){return Ic(n,e,t).decrypt(r.subarray(),o)}};var vh=kc;function Ah(r){return{generateKeypair:r.generateX25519KeyPair,dh:(e,t)=>r.generateX25519SharedKey(e.privateKey,t).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var qr=r=>{let e=me(2);return e[0]=r>>8,e[1]=r,e};qr.bytes=2;var Fn=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let e=0;return e+=r[0]<<8,e+=r[1],e}return r.getUint16(0)};Fn.bytes=2;function Bh(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Tc(r,e){!e.enabled||!Wr||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${X(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${X(r.privateKey,"hex")}`)):e("Missing local static keys."))}function Lc(r,e){!e.enabled||!Wr||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${X(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${X(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function Sh(r,e){!e.enabled||!Wr||e(r?`REMOTE_STATIC_PUBLIC_KEY ${X(r.subarray(),"hex")}`:"Missing remote static public key.")}function Nc(r,e){!e.enabled||!Wr||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${X(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function _c(r,e,t){!t.enabled||!Wr||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&X(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&X(e.k,"hex")}`))}var zr=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var Ag=0,Bg=4294967295,Sg="Cipherstate has reached maximum n, a new handshake must be performed",ai=class{n;bytes;view;constructor(e=Ag){this.n=e,this.bytes=ye(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>Bg)throw new Error(Sg)}};var gr=ye(0),jr=class{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new ai(n)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,t,n){if(!this.hasKey())return t;this.n.assertValue();let o=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},Rc=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let n=Q(t,"utf-8");this.h=Ig(e,n),this.ck=this.h,this.cs=new jr(e)}mixKey(e){let[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new jr(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new re(this.h,e))}encryptAndHash(e){let t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){let[e,t]=this.crypto.hkdf(this.ck,gr);return[new jr(this.crypto,e),new jr(this.crypto,t)]}},Uc=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=e;this.crypto=t,this.ss=new Rc(t,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}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,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=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<t+n)throw new Error("message is not long enough");let o=e.sublist(t,t+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Vn=class extends Uc{writeMessageA(e){return new re(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new re(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new re(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new zr(`handshake stage 0 validation fail: ${t.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(t){throw new zr(`handshake stage 1 validation fail: ${t.message}`)}}readMessageC(e){try{let t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(t){throw new zr(`handshake stage 2 validation fail: ${t.message}`)}}};function Ig(r,e){if(e.length<=32){let t=ye(32);return t.set(e),t}else return r.hash(e)}var ci;(function(r){let e;r.codec=()=>(e==null&&(e=nt((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let s of t.webtransportCerthashes)n.uint32(10),n.bytes(s);o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={webtransportCerthashes:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:{o.webtransportCerthashes.push(t.bytes());break}default:{t.skipType(i&7);break}}}return o})),e),r.encode=t=>rt(t,r.codec()),r.decode=t=>tt(t,r.codec())})(ci||(ci={}));var Kn;(function(r){let e;r.codec=()=>(e==null&&(e=nt((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(n.uint32(10),n.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(n.uint32(18),n.bytes(t.identitySig)),t.extensions!=null&&(n.uint32(34),ci.codec().encode(t.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let o={identityKey:ye(0),identitySig:ye(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let i=t.uint32();switch(i>>>3){case 1:{o.identityKey=t.bytes();break}case 2:{o.identitySig=t.bytes();break}case 4:{o.extensions=ci.codec().decode(t,t.uint32());break}default:{t.skipType(i&7);break}}}return o})),e),r.encode=t=>rt(t,r.codec()),r.decode=t=>tt(t,r.codec())})(Kn||(Kn={}));async function Dc(r,e,t){let n=await r.sign(Ih(e));return Kn.encode({identityKey:Tr(r.publicKey),identitySig:n,extensions:t})}async function Pc(r,e,t){try{let n=Kn.decode(r),o=vn(n.identityKey);if(t?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let s=Ih(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new qn(n.message)}}function Ih(r){let e=Q("noise-libp2p-static-key:");return r instanceof Uint8Array?be([e,r],e.length+r.length):(r.prepend(e),r)}async function Ch(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Dc(s,a.publicKey,l),f=new Vn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Tc(f.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await n.write(f.writeMessageA(gr),e),t.trace("Stage 0 - Initiator finished sending first message."),Lc(f.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let d=f.readMessageB(await n.read(e));t.trace("Stage 1 - Initiator received the message."),Nc(f.re,t),Sh(f.rs,t),t.trace("Initiator going to check remote's signature...");let m=await Pc(d,f.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await n.write(f.writeMessageC(u),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[y,g]=f.ss.split();return _c(y,g,t),{payload:m,encrypt:h=>y.encryptWithAd(gr,h),decrypt:(h,b)=>g.decryptWithAd(gr,h,b)}}async function kh(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Dc(s,a.publicKey,l),f=new Vn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Tc(f.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),f.readMessageA(await n.read(e)),t.trace("Stage 0 - Responder received first message."),Nc(f.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(f.writeMessageB(u),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Lc(f.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let d=f.readMessageC(await n.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let m=await Pc(d,f.rs,c),[y,g]=f.ss.split();return _c(y,g,t),{payload:m,encrypt:h=>g.encryptWithAd(gr,h),decrypt:(h,b)=>y.decryptWithAd(gr,h,b)}}var Lh=16;function Nh(r,e){return async function*(t){for await(let n of t)for(let o=0;o<n.length;o+=65519){let s=o+65519;s>n.length&&(s=n.length);let i;n instanceof Uint8Array?i=r.encrypt(n.subarray(o,s)):i=r.encrypt(n.sublist(o,s)),e?.encryptedPackets.increment(),yield new re(qr(i.byteLength),i)}}}function _h(r,e){return async function*(t){for await(let n of t)for(let o=0;o<n.length;o+=65535){let s=o+65535;if(s>n.length&&(s=n.length),s-Lh<o)throw new Error("Invalid chunk");let i=n.sublist(o,s),a=n.subarray(o,s-Lh);try{let c=r.decrypt(i,a);e?.decryptedPackets.increment(),yield c}catch(c){throw e?.decryptErrors.increment(),c}}}}var li=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(e,t={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=t,{metrics:a}=e;this.components=e;let c=s??vh;this.crypto=Ah(c),this.extensions=o,this.metrics=a?Bh(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??ye(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[br]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let n=On(e,{lengthEncoder:qr,lengthDecoder:Fn,maxDataLength:65535}),o=await this.performHandshakeInitiator(n,this.components.privateKey,t?.remotePeer?.publicKey,t),s=await this.createSecureConnection(n,o);e.source=s.source,e.sink=s.sink;let i=vn(o.payload.identityKey);return{conn:e,remoteExtensions:o.payload.extensions,remotePeer:Ua(i)}}async secureInbound(e,t){let n=On(e,{lengthEncoder:qr,lengthDecoder:Fn,maxDataLength:65535}),o=await this.performHandshakeResponder(n,this.components.privateKey,t?.remotePeer?.publicKey,t),s=await this.createSecureConnection(n,o);e.source=s.source,e.sink=s.sink;let i=vn(o.payload.identityKey);return{conn:e,remoteExtensions:o.payload.extensions,remotePeer:Ua(i)}}async performHandshakeInitiator(e,t,n,o){let s;try{s=await Ch({connection:e,privateKey:t,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async performHandshakeResponder(e,t,n,o){let s;try{s=await kh({connection:e,privateKey:t,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async createSecureConnection(e,t){let[n,o]=rh(),s=e.unwrap();return await oh(n,Nh(t,this.metrics),s,i=>Hn(i,{lengthDecoder:Fn}),_h(t,this.metrics),n),o}};function Rh(r={}){return e=>new li(e,r)}var Oc=Object.values(ar).map(r=>r.decoder).reduce((r,e)=>r.or(e)),Cg=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function Uh(r){return r?.match(Cg)?.groups?.fingerprint}function Mc(r){let t=r.stringTuples().filter(n=>n[0]===Mf).map(n=>n[1])[0];if(t===void 0||t==="")throw new oe(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return t}function kg(r){return We.decode(Oc.decode(r))}function Tg(r){let e=kg(Mc(r)),t=Lg(e.code),n=e.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new $s(n,r.toString());return`${t} ${o.join(":").toUpperCase()}`}function Dh(r){let e=r.split(":").map(o=>parseInt(o,16)),t=Uint8Array.from(e),n=ke(vt.code,t);return ht(`/certhash/${cn.encode(n.bytes)}`)}function Lg(r){switch(r){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new Ws(r)}}function Ph(r,e){let{host:t,port:n,family:o}=r.toOptions(),s=Tg(r);return{type:"answer",sdp:`v=0
|
7
7
|
o=- 0 0 IN IP${o} ${t}
|
8
8
|
s=-
|
9
9
|
t=0 0
|
@@ -20,7 +20,7 @@ a=sctp-port:5000
|
|
20
20
|
a=max-message-size:${Pn}
|
21
21
|
a=candidate:1467250027 1 UDP 1467250027 ${t} ${n} typ host
|
22
22
|
a=end-of-candidates
|
23
|
-
`}}function
|
23
|
+
`}}function Oh(r,e){let{host:t,port:n,family:o}=r.toOptions();return{type:"offer",sdp:`v=0
|
24
24
|
o=- 0 0 IN IP${o} ${t}
|
25
25
|
s=-
|
26
26
|
c=IN IP${o} ${t}
|
@@ -41,7 +41,7 @@ a=end-of-candidates
|
|
41
41
|
`:`
|
42
42
|
`;return r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
|
43
43
|
a=ice-ufrag:`+e+t).replace(/\na=ice-pwd:[^\n]*\n/,`
|
44
|
-
a=ice-pwd:`+e+t),r}var Fc=Q("libp2p-webrtc-noise:");function
|
44
|
+
a=ice-pwd:`+e+t),r}var Fc=Q("libp2p-webrtc-noise:");function Hh(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),o=Q(n,"hex"),s=ke(vt.code,o),i=Oc.decode(Mc(e)),a=Fc.byteLength+s.bytes.byteLength+i.byteLength;return t==="server"?be([Fc,i,s.bytes],a):be([Fc,s.bytes,i],a)}var Ng=Nn?"iceconnectionstatechange":"connectionstatechange";async function Fh(r,e,t){let n=r.createDataChannel("",{negotiated:!0,id:0});if(t.role==="client"){t.log.trace("client creating local offer");let d=await r.createOffer();t.log.trace("client created local offer %s",d.sdp);let m=Hc(d,e);t.log.trace("client setting local offer %s",m.sdp),await r.setLocalDescription(m);let y=Ph(t.remoteAddr,e);t.log.trace("client setting server description %s",y.sdp),await r.setRemoteDescription(y)}else{let d=Oh(t.remoteAddr,e);t.log.trace("server setting client %s %s",d.type,d.sdp),await r.setRemoteDescription(d),t.log.trace("server creating local answer");let m=await r.createAnswer();t.log.trace("server created local answer");let y=Hc(m,e);t.log.trace("server setting local description %s",m.sdp),await r.setLocalDescription(y)}if(t.log.trace("%s wait for handshake channel to open",t.role),await Dn(n,"open",t.signal),t.log.trace("%s handshake channel opened",t.role),t.role==="server"){let d=r.remoteFingerprint()?.value??"";t.remoteAddr=t.remoteAddr.encapsulate(Dh(d))}let o=Uh(r.localDescription?.sdp);if(o==null)throw new Xt("Could not get fingerprint from local description sdp");t.log.trace("%s performing noise handshake",t.role);let s=Hh(o,t.remoteAddr,t.role),i=Rh({prologueBytes:s})(t),a=Gr({channel:n,direction:"inbound",logger:t.logger,...t.dataChannel??{}}),c={...a,sink:a.sink.bind(a),source:async function*(){for await(let d of a.source)for(let m of d)yield m}()},l=new dr(t,{peerConnection:r,remoteAddr:t.remoteAddr,timeline:{open:Date.now()},metrics:t.events});r.addEventListener(Ng,()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(d=>{t.log.error("error closing connection",d),l.abort(d)});break;default:break}}),t.events?.increment({peer_connection:!0});let u=new Zt(t,{peerConnection:r,metrics:t.events,dataChannelOptions:t.dataChannel});if(t.role==="client")return t.log.trace("%s secure inbound",t.role),await i.secureInbound(c,{remotePeer:t.remotePeerId,signal:t.signal}),t.log.trace("%s upgrade outbound",t.role),t.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,muxerFactory:u,signal:t.signal});t.log.trace("%s secure outbound",t.role);let f=await i.secureOutbound(c,{remotePeer:t.remotePeerId,signal:t.signal});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${f.remotePeer}`),t.log.trace("%s upgrade inbound",t.role),await t.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,muxerFactory:u,signal:t.signal})}async function Vh(r,e,t,n){n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof t=="function"?await t():t;return new RTCPeerConnection({...o??{},certificates:[n]})}var ui=class{log;metrics;components;init;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,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"})})}[Wn]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[br]=["@libp2p/transport"];async dial(e,t){t?.signal?.throwIfAborted();let n=await this._connect(e,t);return this.log("dialing address: %a",e),n}createListener(e){return new Ys(this.components,{...this.init,...e})}listenFilter(e){return e.filter(Bf.exactMatch)}dialFilter(e){return this.listenFilter(e)}async _connect(e,t){let n,o=e.getPeerId();o!=null&&(n=Mr(o));let s=Vf(),i=await Vh("client",s,typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{});try{return await st(Fh(i,s,{role:"client",log:this.log,logger:this.components.logger,metrics:this.components.metrics,events:this.metrics?.dialerEvents,signal:t.signal??AbortSignal.timeout(Of),remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeerId:n,privateKey:this.components.privateKey}),t.signal)}catch(a){throw i.close(),a}}};function _g(r){return e=>new ui(e,r)}function Rg(r){return e=>new Xs(e,r)}return nd(Ug);})();
|
45
45
|
/*! Bundled license information:
|
46
46
|
|
47
47
|
pvtsutils/build/index.js:
|