@libp2p/webrtc 4.1.3 → 4.1.4
Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.min.js
CHANGED
@@ -1,10 +1,10 @@
|
|
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 rd=Object.create;var Xn=Object.defineProperty;var nd=Object.getOwnPropertyDescriptor;var od=Object.getOwnPropertyNames;var sd=Object.getPrototypeOf,id=Object.prototype.hasOwnProperty;var Fc=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),xt=(r,t)=>{for(var e in t)Xn(r,e,{get:t[e],enumerable:!0})},Kc=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of od(t))!id.call(r,o)&&o!==e&&Xn(r,o,{get:()=>t[o],enumerable:!(n=nd(t,o))||n.enumerable});return r};var $c=(r,t,e)=>(e=r!=null?rd(sd(r)):{},Kc(t||!r||!r.__esModule?Xn(e,"default",{value:r,enumerable:!0}):e,r)),ad=r=>Kc(Xn({},"__esModule",{value:!0}),r);var ru=Fc((T1,eu)=>{"use strict";function tu(r,t){for(let e in t)Object.defineProperty(r,e,{value:t[e],enumerable:!0,configurable:!0});return r}function f0(r,t,e){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");e||(e={}),typeof t=="object"&&(e=t,t=""),t&&(e.code=t);try{return tu(r,e)}catch{e.message=r.message,e.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),tu(new o,e)}}eu.exports=f0});var rf=Fc(en=>{"use strict";var tg="[object ArrayBuffer]",De=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===tg}static toArrayBuffer(t){return this.isArrayBuffer(t)?t:t.byteLength===t.buffer.byteLength||t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:this.toUint8Array(t.buffer).slice(t.byteOffset,t.byteOffset+t.byteLength).buffer}static toUint8Array(t){return this.toView(t,Uint8Array)}static toView(t,e){if(t.constructor===e)return t;if(this.isArrayBuffer(t))return new e(t);if(this.isArrayBufferView(t))return new e(t.buffer,t.byteOffset,t.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(t){return this.isArrayBufferView(t)||this.isArrayBuffer(t)}static isArrayBufferView(t){return ArrayBuffer.isView(t)||t&&this.isArrayBuffer(t.buffer)}static isEqual(t,e){let n=r.toUint8Array(t),o=r.toUint8Array(e);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(...t){let e;Array.isArray(t[0])&&!(t[1]instanceof Function)||Array.isArray(t[0])&&t[1]instanceof Function?e=t[0]:t[t.length-1]instanceof Function?e=t.slice(0,t.length-1):e=t;let n=0;for(let i of e)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of e){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return t[t.length-1]instanceof Function?this.toView(o,t[t.length-1]):o.buffer}},za="string",eg=/^[0-9a-f]+$/i,rg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,ng=/^[a-zA-Z0-9-_]+$/,Xo=class{static fromString(t){let e=unescape(encodeURIComponent(t)),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n.buffer}static toString(t){let e=De.toUint8Array(t),n="";for(let s=0;s<e.length;s++)n+=String.fromCharCode(e[s]);return decodeURIComponent(escape(n))}},Jt=class{static toString(t,e=!1){let n=De.toArrayBuffer(t),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,e);s+=String.fromCharCode(a)}return s}static fromString(t,e=!1){let n=new ArrayBuffer(t.length*2),o=new DataView(n);for(let s=0;s<t.length;s++)o.setUint16(s*2,t.charCodeAt(s),e);return n}},Jo=class r{static isHex(t){return typeof t===za&&eg.test(t)}static isBase64(t){return typeof t===za&&rg.test(t)}static isBase64Url(t){return typeof t===za&&ng.test(t)}static ToString(t,e="utf8"){let n=De.toUint8Array(t);switch(e.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 Jt.toString(n,!0);case"utf16":case"utf16be":return Jt.toString(n);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromString(t,e="utf8"){if(!t)return new ArrayBuffer(0);switch(e.toLowerCase()){case"utf8":return this.FromUtf8String(t);case"binary":return this.FromBinary(t);case"hex":return this.FromHex(t);case"base64":return this.FromBase64(t);case"base64url":return this.FromBase64Url(t);case"utf16le":return Jt.fromString(t,!0);case"utf16":case"utf16be":return Jt.fromString(t);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToBase64(t){let e=De.toUint8Array(t);if(typeof btoa<"u"){let n=this.ToString(e,"binary");return btoa(n)}else return Buffer.from(e).toString("base64")}static FromBase64(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64(e))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(e)):new Uint8Array(Buffer.from(e,"base64")).buffer}static FromBase64Url(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64Url(e))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(e.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(t){return this.ToBase64(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.FromBinary(t);case"utf8":return Xo.fromString(t);case"utf16":case"utf16be":return Jt.fromString(t);case"utf16le":case"usc2":return Jt.fromString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.ToBinary(t);case"utf8":return Xo.toString(t);case"utf16":case"utf16be":return Jt.toString(t);case"utf16le":case"usc2":return Jt.toString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromBinary(t){let e=t.length,n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);return n.buffer}static ToBinary(t){let e=De.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=De.toUint8Array(t),n="",o=e.length;for(let s=0;s<o;s++){let i=e[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isHex(e))throw new TypeError("Argument 'hexString' is not HEX encoded");e.length%2&&(e=`0${e}`);let n=new Uint8Array(e.length/2);for(let o=0;o<e.length;o=o+2){let s=e.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(t,e=!1){return Jt.toString(t,e)}static FromUtf16String(t,e=!1){return Jt.fromString(t,e)}static Base64Padding(t){let e=4-t.length%4;if(e<4)for(let n=0;n<e;n++)t+="=";return t}static formatString(t){return t?.replace(/[\n\r\t ]/g,"")||""}};Jo.DEFAULT_UTF8_ENCODING="utf8";function og(r,...t){let e=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)e[s]=o[s]}return e}function sg(...r){let t=r.map(o=>o.byteLength).reduce((o,s)=>o+s),e=new Uint8Array(t),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)e[n++]=s}),e.buffer}function ig(r,t){if(!(r&&t)||r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)if(e[o]!==n[o])return!1;return!0}en.BufferSourceConverter=De;en.Convert=Jo;en.assign=og;en.combine=sg;en.isEqual=ig});var my={};xt(my,{webRTC:()=>py,webRTCDirect:()=>dy});var Zs=Symbol.for("@libp2p/peer-id");var Jn=Symbol.for("@libp2p/transport");var Wc;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Wc||(Wc={}));var D=class extends Error{code;props;constructor(t,e,n){super(t),this.code=e,this.name=n?.name??"CodeError",this.props=n??{}}};var Qn=(r,...t)=>{try{[...t]}catch{}};var to=class extends EventTarget{#t=new Map;constructor(){super(),Qn(1/0,this)}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new cd(t,e))}},Xs=class extends Event{detail;constructor(t,e){super(t,e),this.detail=e?.detail}},cd=globalThis.CustomEvent??Xs;var Rr=Symbol.for("@libp2p/service-capabilities"),Gc=Symbol.for("@libp2p/service-dependencies");var ri={};xt(ri,{base58btc:()=>dt,base58flickr:()=>pd});var qy=new Uint8Array(0);function qc(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Ae(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 zc(r){return new TextDecoder().decode(r)}function ld(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var h=0,d=0,b=0,E=m.length;b!==E&&m[b]===0;)b++,h++;for(var w=(E-b)*u+1>>>0,S=new Uint8Array(w);b!==E;){for(var x=m[b],B=0,I=w-1;(x!==0||B<d)&&I!==-1;I--,B++)x+=256*S[I]>>>0,S[I]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");d=B,b++}for(var _=w-d;_!==w&&S[_]===0;)_++;for(var N=c.repeat(h);_<w;++_)N+=r.charAt(S[_]);return N}function p(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var h=0;if(m[h]!==" "){for(var d=0,b=0;m[h]===c;)d++,h++;for(var E=(m.length-h)*l+1>>>0,w=new Uint8Array(E);m[h];){var S=e[m.charCodeAt(h)];if(S===255)return;for(var x=0,B=E-1;(S!==0||x<b)&&B!==-1;B--,x++)S+=a*w[B]>>>0,w[B]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");b=x,h++}if(m[h]!==" "){for(var I=E-b;I!==E&&w[I]===0;)I++;for(var _=new Uint8Array(d+(E-I)),N=d;I!==E;)_[N++]=w[I++];return _}}}function y(m){var h=p(m);if(h)return h;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:p,decode:y}}var ud=ld,fd=ud,Zc=fd;var Js=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Qs=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Xc(this,t)}},ti=class{decoders;constructor(t){this.decoders=t}or(t){return Xc(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Xc(r,t){return new ti({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ei=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new Js(t,e,n),this.decoder=new Qs(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Tr({name:r,prefix:t,encode:e,decode:n}){return new ei(r,t,e,n)}function Ke({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Zc(e,r);return Tr({prefix:t,name:r,encode:n,decode:s=>Ae(o(s))})}function hd(r,t,e,n){let o={};for(let u=0;u<t.length;++u)o[t[u]]=u;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*e/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<<e|f,a+=e,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function dd(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;s.length*e&7;)s+="=";return s}function ft({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Tr({prefix:t,name:r,encode(o){return dd(o,n,e)},decode(o){return hd(o,n,e,r)}})}var dt=Ke({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),pd=Ke({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ni={};xt(ni,{base10:()=>md});var md=Ke({prefix:"9",name:"base10",alphabet:"0123456789"});var oi={};xt(oi,{base16:()=>gd,base16upper:()=>yd});var gd=ft({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),yd=ft({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var si={};xt(si,{base2:()=>wd});var wd=ft({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ii={};xt(ii,{base256emoji:()=>Ad});var Jc=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}"),bd=Jc.reduce((r,t,e)=>(r[e]=t,r),[]),xd=Jc.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function Ed(r){return r.reduce((t,e)=>(t+=bd[e],t),"")}function vd(r){let t=[];for(let e of r){let n=xd[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var Ad=Tr({prefix:"\u{1F680}",name:"base256emoji",encode:Ed,decode:vd});var ai={};xt(ai,{base32:()=>Se,base32hex:()=>_d,base32hexpad:()=>Cd,base32hexpadupper:()=>Rd,base32hexupper:()=>kd,base32pad:()=>Bd,base32padupper:()=>Id,base32upper:()=>Sd,base32z:()=>Td});var Se=ft({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Sd=ft({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Bd=ft({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Id=ft({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),_d=ft({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),kd=ft({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Cd=ft({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Rd=ft({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Td=ft({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ci={};xt(ci,{base36:()=>Nd,base36upper:()=>Ld});var Nd=Ke({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ld=Ke({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var fi={};xt(fi,{base64:()=>li,base64pad:()=>Dd,base64url:()=>ui,base64urlpad:()=>Ud});var li=ft({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Dd=ft({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ui=ft({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ud=ft({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var hi={};xt(hi,{base8:()=>Pd});var Pd=ft({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var di={};xt(di,{identity:()=>Od});var Od=Tr({prefix:"\0",name:"identity",encode:r=>zc(r),decode:r=>jc(r)});var cw=new TextEncoder,lw=new TextDecoder;var gi={};xt(gi,{identity:()=>Be});var te={};xt(te,{Digest:()=>cr,create:()=>$t,decode:()=>$e,equals:()=>mi});var Vd=el,Qc=128,Fd=127,Kd=~Fd,$d=Math.pow(2,31);function el(r,t,e){t=t||[],e=e||0;for(var n=e;r>=$d;)t[e++]=r&255|Qc,r/=128;for(;r&Kd;)t[e++]=r&255|Qc,r>>>=7;return t[e]=r|0,el.bytes=e-n+1,t}var Wd=pi,Gd=128,tl=127;function pi(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw pi.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&tl)<<o:(i&tl)*Math.pow(2,o),o+=7}while(i>=Gd);return pi.bytes=s-n,e}var qd=Math.pow(2,7),jd=Math.pow(2,14),zd=Math.pow(2,21),Yd=Math.pow(2,28),Zd=Math.pow(2,35),Xd=Math.pow(2,42),Jd=Math.pow(2,49),Qd=Math.pow(2,56),tp=Math.pow(2,63),ep=function(r){return r<qd?1:r<jd?2:r<zd?3:r<Yd?4:r<Zd?5:r<Xd?6:r<Jd?7:r<Qd?8:r<tp?9:10},rp={encode:Vd,decode:Wd,encodingLength:ep},np=rp,dn=np;function pn(r,t=0){return[dn.decode(r,t),dn.decode.bytes]}function Nr(r,t,e=0){return dn.encode(r,t,e),t}function Lr(r){return dn.encodingLength(r)}function $t(r,t){let e=t.byteLength,n=Lr(r),o=n+Lr(e),s=new Uint8Array(o+e);return Nr(r,s,0),Nr(e,s,n),s.set(t,o),new cr(r,e,t,s)}function $e(r){let t=Ae(r),[e,n]=pn(t),[o,s]=pn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new cr(e,o,i,t)}function mi(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&qc(r.bytes,e.bytes)}}var cr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};var rl=0,op="identity",nl=Ae;function sp(r){return $t(rl,nl(r))}var Be={code:rl,name:op,encode:nl,digest:sp};var bi={};xt(bi,{sha256:()=>Ct,sha512:()=>ip});function wi({name:r,code:t,encode:e}){return new yi(r,t,e)}var yi=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?$t(this.code,e):e.then(n=>$t(this.code,n))}else throw Error("Unknown type, must be binary type")}};function sl(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Ct=wi({name:"sha2-256",code:18,encode:sl("SHA-256")}),ip=wi({name:"sha2-512",code:19,encode:sl("SHA-512")});function il(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return cp(e,xi(r),t??dt.encoder);default:return lp(e,xi(r),t??Se.encoder)}}var al=new WeakMap;function xi(r){let t=al.get(r);if(t==null){let e=new Map;return al.set(r,e),e}return t}var zt=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==mn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==up)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=$t(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&mi(t.multihash,n.multihash)}toString(t){return il(this,t)}toJSON(){return{"/":il(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??cl(n,o,s.bytes))}else if(e[fp]===!0){let{version:n,multihash:o,code:s}=e,i=$e(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==mn)throw new Error(`Version 0 CID must use dag-pb (code: ${mn}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=cl(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,mn,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Ae(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new cr(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,p]=pn(t.subarray(e));return e+=p,f},o=n(),s=mn;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=ap(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return xi(s).set(n,t),s}};function ap(r,t){switch(r[0]){case"Q":{let e=t??dt;return[dt.prefix,e.decode(`${dt.prefix}${r}`)]}case dt.prefix:{let e=t??dt;return[dt.prefix,e.decode(r)]}case Se.prefix:{let e=t??Se;return[Se.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function cp(r,t,e){let{prefix:n}=e;if(n!==dt.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function lp(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var mn=112,up=18;function cl(r,t,e){let n=Lr(r),o=n+Lr(t),s=new Uint8Array(o+e.byteLength);return Nr(r,s,0),Nr(t,s,n),s.set(e,o),s}var fp=Symbol.for("@ipld/js-cid/CID");var pe={...di,...si,...hi,...ni,...oi,...ai,...ci,...ri,...fi,...ii},Rw={...bi,...gi};function Et(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function vt(r=0){return new Uint8Array(r)}function At(r=0){return new Uint8Array(r)}function ul(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var ll=ul("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ei=ul("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=At(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),hp={utf8:ll,"utf-8":ll,hex:pe.base16,latin1:Ei,ascii:Ei,binary:Ei,...pe},ro=hp;function J(r,t="utf8"){let e=ro[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function G(r,t="utf8"){let e=ro[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var hl=Symbol.for("nodejs.util.inspect.custom"),fl=Object.values(pe).map(r=>r.decoder).reduce((r,t)=>r.or(t),pe.identity.decoder),dl=114,Si=36,Bi=37,gn=class{type;multihash;privateKey;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,this.privateKey=t.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Zs]=!0;toString(){return this.string==null&&(this.string=dt.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return zt.createV1(dl,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Et(this.multihash.bytes,t);if(typeof t=="string")return lr(t).equals(this);if(t?.multihash?.bytes!=null)return Et(this.multihash.bytes,t.multihash.bytes);throw new Error("not valid Id")}[hl](){return`PeerId(${this.toString()})`}},Dr=class extends gn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Ur=class extends gn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.multihash.digest}},Pr=class extends gn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.multihash.digest}},vi=2336,Ai=class{type="url";multihash;privateKey;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Be.digest(J(this.url))}[hl](){return`PeerId(${this.url})`}[Zs]=!0;toString(){return this.toCID().toString()}toCID(){return zt.createV1(vi,this.multihash)}toBytes(){return this.toCID().bytes}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=G(t)),t.toString()===this.toString())}};function lr(r,t){if(t=t??fl,r.charAt(0)==="1"||r.charAt(0)==="Q"){let e=$e(dt.decode(`z${r}`));return r.startsWith("12D")?new Ur({multihash:e}):r.startsWith("16U")?new Pr({multihash:e}):new Dr({multihash:e})}return dp(fl.decode(r))}function dp(r){try{let t=$e(r);if(t.code===Be.code){if(t.digest.length===Si)return new Ur({multihash:t});if(t.digest.length===Bi)return new Pr({multihash:t})}if(t.code===Ct.code)return new Dr({multihash:t})}catch{return pp(zt.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function pp(r){if(r==null||r.multihash==null||r.version==null||r.version===1&&r.code!==dl&&r.code!==vi)throw new Error("Supplied PeerID CID is invalid");if(r.code===vi){let e=G(r.multihash.digest);return new Ai(new URL(e))}let t=r.multihash;if(t.code===Ct.code)return new Dr({multihash:r.multihash});if(t.code===Be.code){if(t.digest.length===Si)return new Ur({multihash:r.multihash});if(t.digest.length===Bi)return new Pr({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function Ii(r,t){return r.length===Si?new Ur({multihash:$t(Be.code,r),privateKey:t}):r.length===Bi?new Pr({multihash:$t(Be.code,r),privateKey:t}):new Dr({multihash:await Ct.digest(r),publicKey:r,privateKey:t})}var gp=Math.pow(2,7),yp=Math.pow(2,14),wp=Math.pow(2,21),_i=Math.pow(2,28),ki=Math.pow(2,35),Ci=Math.pow(2,42),Ri=Math.pow(2,49),et=128,Dt=127;function gt(r){if(r<gp)return 1;if(r<yp)return 2;if(r<wp)return 3;if(r<_i)return 4;if(r<ki)return 5;if(r<Ci)return 6;if(r<Ri)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ti(r,t,e=0){switch(gt(r)){case 8:t[e++]=r&255|et,r/=128;case 7:t[e++]=r&255|et,r/=128;case 6:t[e++]=r&255|et,r/=128;case 5:t[e++]=r&255|et,r/=128;case 4:t[e++]=r&255|et,r>>>=7;case 3:t[e++]=r&255|et,r>>>=7;case 2:t[e++]=r&255|et,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function bp(r,t,e=0){switch(gt(r)){case 8:t.set(e++,r&255|et),r/=128;case 7:t.set(e++,r&255|et),r/=128;case 6:t.set(e++,r&255|et),r/=128;case 5:t.set(e++,r&255|et),r/=128;case 4:t.set(e++,r&255|et),r>>>=7;case 3:t.set(e++,r&255|et),r>>>=7;case 2:t.set(e++,r&255|et),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Ni(r,t){let e=r[t],n=0;if(n+=e&Dt,e<et||(e=r[t+1],n+=(e&Dt)<<7,e<et)||(e=r[t+2],n+=(e&Dt)<<14,e<et)||(e=r[t+3],n+=(e&Dt)<<21,e<et)||(e=r[t+4],n+=(e&Dt)*_i,e<et)||(e=r[t+5],n+=(e&Dt)*ki,e<et)||(e=r[t+6],n+=(e&Dt)*Ci,e<et)||(e=r[t+7],n+=(e&Dt)*Ri,e<et))return n;throw new RangeError("Could not decode varint")}function xp(r,t){let e=r.get(t),n=0;if(n+=e&Dt,e<et||(e=r.get(t+1),n+=(e&Dt)<<7,e<et)||(e=r.get(t+2),n+=(e&Dt)<<14,e<et)||(e=r.get(t+3),n+=(e&Dt)<<21,e<et)||(e=r.get(t+4),n+=(e&Dt)*_i,e<et)||(e=r.get(t+5),n+=(e&Dt)*ki,e<et)||(e=r.get(t+6),n+=(e&Dt)*Ci,e<et)||(e=r.get(t+7),n+=(e&Dt)*Ri,e<et))return n;throw new RangeError("Could not decode varint")}function me(r,t,e=0){return t==null&&(t=At(gt(r))),t instanceof Uint8Array?Ti(r,t,e):bp(r,t,e)}function ee(r,t=0){return r instanceof Uint8Array?Ni(r,t):xp(r,t)}function yt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=At(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var no=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let p=Number.parseInt(f,t);if(!Number.isNaN(p))return p});if(u===void 0)break;if(s*=t,s+=u,s>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var pl=45,vp=15,Or=new no;function Li(r){if(!(r.length>vp))return Or.new(r).parseWith(()=>Or.readIPv4Addr())}function Di(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>pl))return Or.new(r).parseWith(()=>Or.readIPv6Addr())}function oo(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>pl))return Or.new(r).parseWith(()=>Or.readIPAddr())}var ub=parseInt("0xFFFF",16),fb=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function so(r){return!!Li(r)}function io(r){return!!Di(r)}function ao(r){return!!oo(r)}var yl=so,_p=io,Ui=function(r){let t=0;if(r=r.toString().trim(),yl(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(_p(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=yl(e[n]),i;s&&(i=Ui(e[n]),e[n]=G(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,G(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let s=parseInt(e[n],16);o[t++]=s>>8&255,o[t++]=s&255}return o}throw new Error("invalid ip address")},wl=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Hr={},Pi={},Cp=[[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"]];Cp.forEach(r=>{let t=Rp(...r);Pi[t.code]=t,Hr[t.name]=t});function Rp(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function rt(r){if(typeof r=="number"){if(Pi[r]!=null)return Pi[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Hr[r]!=null)return Hr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var zb=rt("ip4"),Yb=rt("ip6"),Zb=rt("ipcidr");function Vi(r,t){switch(rt(r).code){case 4:case 41:return Np(t);case 42:return Mi(t);case 6:case 273:case 33:case 132:return El(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Mi(t);case 421:return Pp(t);case 444:return xl(t);case 445:return xl(t);case 466:return Up(t);case 481:return globalThis.encodeURIComponent(Mi(t));default:return G(t,"base16")}}function Fi(r,t){switch(rt(r).code){case 4:return bl(t);case 41:return bl(t);case 42:return Hi(t);case 6:case 273:case 33:case 132:return Ki(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Hi(t);case 421:return Lp(t);case 444:return Op(t);case 445:return Hp(t);case 466:return Dp(t);case 481:return Hi(globalThis.decodeURIComponent(t));default:return J(t,"base16")}}var Oi=Object.values(pe).map(r=>r.decoder),Tp=function(){let r=Oi[0].or(Oi[1]);return Oi.slice(2).forEach(t=>r=r.or(t)),r}();function bl(r){if(!ao(r))throw new Error("invalid ip address");return Ui(r)}function Np(r){let t=wl(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!ao(t))throw new Error("invalid ip address");return t}function Ki(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function El(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Hi(r){let t=J(r),e=Uint8Array.from(me(t.length));return yt([e,t],e.length+t.length)}function Mi(r){let t=ee(r);if(r=r.slice(gt(t)),r.length!==t)throw new Error("inconsistent lengths");return G(r)}function Lp(r){let t;r[0]==="Q"||r[0]==="1"?t=$e(dt.decode(`z${r}`)).bytes:t=zt.parse(r).multihash.bytes;let e=Uint8Array.from(me(t.length));return yt([e,t],e.length+t.length)}function Dp(r){let t=Tp.decode(r),e=Uint8Array.from(me(t.length));return yt([e,t],e.length+t.length)}function Up(r){let t=ee(r),e=r.slice(gt(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+G(e,"base64url")}function Pp(r){let t=ee(r),e=r.slice(gt(t));if(e.length!==t)throw new Error("inconsistent lengths");return G(e,"base58btc")}function Op(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=Se.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ki(n);return yt([e,o],e.length+o.length)}function Hp(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=Se.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ki(n);return yt([e,o],e.length+o.length)}function xl(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=G(t,"base32"),o=El(e);return`${n}:${o}`}function vl(r){r=$i(r);let t=[],e=[],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=rt(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw Sl("invalid address: "+r);if(a.path===!0){n=$i(o.slice(s).join("/")),t.push([a.code,Fi(a.code,n)]),e.push([a.code,n]);break}let c=Fi(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Vi(a.code,c)])}return{string:Al(e),bytes:Gi(t),tuples:t,stringTuples:e,path:n}}function Wi(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=ee(r,o),i=gt(s),a=rt(s),c=Mp(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let l=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw Sl("Invalid address Uint8Array: "+G(r,"base16"));t.push([s,l]);let u=Vi(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:Al(e),tuples:t,stringTuples:e,path:n}}function Al(r){let t=[];return r.map(e=>{let n=rt(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),$i(t.join("/"))}function Gi(r){return yt(r.map(t=>{let e=rt(t[0]),n=Uint8Array.from(me(e.code));return t.length>1&&t[1]!=null&&(n=yt([n,t[1]])),n}))}function Mp(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=ee(t instanceof Uint8Array?t:Uint8Array.from(t));return e+gt(e)}}function $i(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function Sl(r){return new Error("Error parsing address: "+r)}var Vp=Symbol.for("nodejs.util.inspect.custom"),qi=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Fp=[rt("dns").code,rt("dns4").code,rt("dns6").code,rt("dnsaddr").code],co=class r{bytes;#t;#e;#r;#n;[qi]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Wi(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=vl(t)}else if(Il(t))e=Wi(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="",i=rt("tcp"),a=rt("udp"),c=rt("ip4"),l=rt("ip6"),u=rt("dns6"),f=rt("ip6zone");for(let[y,m]of this.stringTuples())y===f.code&&(s=`%${m??""}`),Fp.includes(y)&&(e=i.name,o=443,n=`${m??""}${s}`,t=y===u.code?6:4),(y===i.code||y===a.code)&&(e=rt(y).name,o=parseInt(m??"")),(y===c.code||y===l.code)&&(e=rt(y).name,n=`${m??""}${s}`,t=y===l.code?6:4);if(t==null||e==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:t,host:n,transport:e,port:o}}protos(){return this.#e.map(([t])=>Object.assign({},rt(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>rt(t).name)}tuples(){return this.#e}stringTuples(){return this.#r}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(Gi(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Hr.p2p.code&&t.push([n,o]),n===Hr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?G(dt.decode(`z${n}`),"base58btc"):G(zt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return Et(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=Bl.get(e.name);if(n==null)throw new D(`no available resolver for ${e.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,t)).map(s=>re(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[Vp](){return`Multiaddr(${this.#t})`}};var Bl=new Map;function Il(r){return!!r?.[qi]}function re(r){return new co(r)}var Kp=r=>r.toString().split("/").slice(1),wn=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),Q=r=>({match:t=>wn(e=>e===r).match(t),pattern:r}),fo=()=>({match:r=>wn(t=>typeof t=="string").match(r),pattern:"{string}"}),ho=()=>({match:r=>wn(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),Rt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{dt.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),lo=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{ui.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),St=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Yt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),ot=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function pt(...r){function t(o){let s=Kp(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matches:e,exactMatch:n}}var zi=ot(Q("dns4"),fo()),Yi=ot(Q("dns6"),fo()),Zi=ot(Q("dnsaddr"),fo()),_l=ot(Q("dns"),fo()),Bx=pt(zi),Ix=pt(Yi),_x=pt(Zi),kx=pt(Yt(_l,Zi,zi,Yi)),kl=ot(Q("ip4"),wn(so)),Cl=ot(Q("ip6"),wn(io)),Rl=Yt(kl,Cl),ge=Yt(Rl,_l,zi,Yi,Zi),Cx=pt(ge),Rx=pt(kl),Tx=pt(Cl),Nx=pt(Rl),Xi=ot(ge,Q("tcp"),ho()),bn=ot(ge,Q("udp"),ho()),Lx=pt(Xi),Dx=pt(bn),Ji=ot(bn,Q("quic")),po=ot(bn,Q("quic-v1")),$p=Yt(Ji,po),Ux=pt(Ji),Px=pt(po),ji=Yt(ge,Xi,bn,Ji,po),Tl=Yt(ot(ji,Q("ws"),St(Rt()))),Ox=pt(Tl),Nl=Yt(ot(ji,Q("wss"),St(Rt())),ot(ji,Q("tls"),Q("ws"),St(Rt()))),Hx=pt(Nl),Ll=ot(bn,Q("webrtc-direct"),St(lo()),St(lo()),St(Rt())),Dl=pt(Ll),Ul=ot(po,Q("webtransport"),St(lo()),St(lo()),St(Rt())),Mx=pt(Ul),uo=Yt(Tl,Nl,ot(Xi,St(Rt())),ot($p,St(Rt())),ot(ge,St(Rt())),Ll,Ul,Rt()),Vx=pt(uo),Wp=ot(uo,Q("p2p-circuit"),Rt()),Fx=pt(Wp),Gp=Yt(ot(uo,Q("p2p-circuit"),Q("webrtc"),St(Rt())),ot(uo,Q("webrtc"),St(Rt())),Q("webrtc")),Pl=pt(Gp),qp=Yt(ot(ge,Q("tcp"),ho(),Q("http"),St(Rt())),ot(ge,Q("http"),St(Rt()))),Kx=pt(qp),jp=Yt(ot(ge,Q("tcp"),Yt(ot(Q("443"),Q("http")),ot(ho(),Q("https"))),St(Rt())),ot(ge,Q("tls"),Q("http"),St(Rt())),ot(ge,Q("https"),St(Rt()))),$x=pt(jp);var Wt;(function(r){r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_DATA_CHANNEL="ERR_DATA_CHANNEL",r.ERR_CONNECTION_CLOSED="ERR_CONNECTION_CLOSED",r.ERR_HASH_NOT_SUPPORTED="ERR_HASH_NOT_SUPPORTED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_INVALID_FINGERPRINT="ERR_INVALID_FINGERPRINT",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS"})(Wt||(Wt={}));var We=class extends D{constructor(t,e){super(`WebRTC transport error: ${t}`,e??""),this.name="WebRTCTransportError"}};var Qi=class extends We{constructor(t,e){super(`[stream: ${t}] data channel error: ${e}`,Wt.ERR_DATA_CHANNEL),this.name="WebRTC/DataChannelError"}};function sa(r,t){return new Qi(r,t)}var ta=class extends We{constructor(t){super(`There was a problem with the Multiaddr which was passed in: ${t}`,Wt.ERR_INVALID_MULTIADDR),this.name="WebRTC/InappropriateMultiaddrError"}};function mo(r){return new ta(r)}var ea=class extends We{constructor(t){super(`There was a problem with a provided argument: ${t}`,Wt.ERR_INVALID_PARAMETERS),this.name="WebRTC/InvalidArgumentError"}};function xn(r){return new ea(r)}var ra=class extends We{constructor(t,e){super(`Invalid fingerprint "${t}" within ${e}`,Wt.ERR_INVALID_FINGERPRINT),this.name="WebRTC/InvalidFingerprintError"}};function ia(r,t){return new ra(r,t)}var na=class extends We{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`,Wt.ERR_NOT_IMPLEMENTED),this.name="WebRTC/UnimplementedError"}};function Ol(r){return new na(r)}var oa=class extends We{constructor(t){super(`unsupported hash algorithm code: ${t} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `,Wt.ERR_HASH_NOT_SUPPORTED),this.name="WebRTC/UnsupportedHashAlgorithmError"}};function Hl(r){return new oa(r)}var Ml=function(r,t,e){if(e||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return r.concat(s||Array.prototype.slice.call(t))},zp=function(){function r(t,e,n){this.name=t,this.version=e,this.os=n,this.type="browser"}return r}();var Yp=function(){function r(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return r}();var Zp=function(){function r(t,e,n,o){this.name=t,this.version=e,this.os=n,this.bot=o,this.type="bot-device"}return r}();var Xp=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var Jp=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var Qp=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,t0=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Vl=3,e0=[["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",Qp]],Fl=[["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 $l(r){return r?Kl(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Jp:typeof navigator<"u"?Kl(navigator.userAgent):o0()}function r0(r){return r!==""&&e0.reduce(function(t,e){var n=e[0],o=e[1];if(t)return t;var s=o.exec(r);return!!s&&[n,s]},!1)}function Kl(r){var t=r0(r);if(!t)return null;var e=t[0],n=t[1];if(e==="searchbot")return new Xp;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<Vl&&(o=Ml(Ml([],o,!0),s0(Vl-o.length),!0)):o=[];var s=o.join("."),i=n0(r),a=t0.exec(r);return a&&a[1]?new Zp(e,s,i,a[1]):new zp(e,s,i)}function n0(r){for(var t=0,e=Fl.length;t<e;t++){var n=Fl[t],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function o0(){var r=typeof process<"u"&&process.version;return r?new Yp(process.version.slice(1)):null}function s0(r){for(var t=[],e=0;e<r;e++)t.push("0");return t}function ht(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Mr=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},aa=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Wl=r=>globalThis.DOMException===void 0?new aa(r):new DOMException(r),Gl=r=>{let t=r.reason===void 0?Wl("This operation was aborted."):r.reason;return t instanceof Error?t:Wl(t)};function ur(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,c=new Promise((l,u)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:p}=t;p.aborted&&u(Gl(p)),p.addEventListener("abort",()=>{u(Gl(p))})}if(e===Number.POSITIVE_INFINITY){r.then(l,u);return}let f=new Mr;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(p){u(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?u(o):(f.message=o??`Promise timed out after ${e} milliseconds`,u(f))},e),(async()=>{try{l(await r)}catch(p){u(p)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}var ql=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"];var jl=$l(),En=jl!=null&&jl.name==="firefox",go=async function*(){},yo=async r=>{},i0=30*1e3;function zl(r,t,e=i0,n){r.readyState==="open"&&Promise.resolve().then(async()=>{if(r.bufferedAmount>0){n.log("%s drain channel with %d buffered bytes",t,r.bufferedAmount);let o=ht(),s=!1;r.bufferedAmountLowThreshold=0;let i=()=>{s||(n.log("%s drain channel closed before drain",t),o.resolve())};r.addEventListener("close",i,{once:!0}),r.addEventListener("bufferedamountlow",()=>{s=!0,r.removeEventListener("close",i),o.resolve()}),await ur(o.promise,{milliseconds:e})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function vn(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??ql.map(t=>({urls:[t]})),r}var fr=class{log;peerConnection;remoteAddr;timeline;metrics;source=go();sink=yo;constructor(t,e){this.log=t.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=e.remoteAddr,this.timeline=e.timeline,this.peerConnection=e.peerConnection;let n=this.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",this.peerConnection.connectionState,"initial state",n),(this.peerConnection.connectionState==="disconnected"||this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.timeline.close=Date.now())}}async close(t){this.log.trace("closing connection"),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({close:!0})}abort(t){this.log.error("closing connection due to error",t),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({abort:!0})}};var wo=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Vr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new wo(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new wo(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var ca=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Ge(r={}){return a0(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function a0(r,t){t=t??{};let e=t.onEnd,n=new Vr,o,s,i,a=ht(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((d,b)=>{s=E=>{s=null,n.push(E);try{d(r(n))}catch(w){b(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ht()})}},l=d=>s!=null?s(d):(n.push(d),o),u=d=>(n=new Vr,s!=null?s({error:d}):(n.push({error:d}),o)),f=d=>{if(i)return o;if(t?.objectMode!==!0&&d?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:d})},p=d=>i?o:(i=!0,d!=null?u(d):l({done:!0})),y=()=>(n=new Vr,p(),{done:!0}),m=d=>(p(d),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:y,throw:m,push:f,end:p,get readableLength(){return n.size},onEmpty:async d=>{let b=d?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let E,w;b!=null&&(E=new Promise((S,x)=>{w=()=>{x(new ca)},b.addEventListener("abort",w)}));try{await Promise.race([a.promise,E])}finally{w!=null&&b!=null&&b?.removeEventListener("abort",w)}}},e==null)return o;let h=o;return o={[Symbol.asyncIterator](){return this},next(){return h.next()},throw(d){return h.throw(d),e!=null&&(e(d),e=void 0),{done:!0}},return(){return h.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(d){return h.end(d),e!=null&&(e(d),e=void 0),o},get readableLength(){return h.readableLength},onEmpty:d=>h.onEmpty(d)},o}var bo=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function Ie(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new bo(e?.errorMessage,e?.errorCode));let n,o=new bo(e?.errorMessage,e?.errorCode);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var Zl=Symbol.for("@achingbrain/uint8arraylist");function Yl(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function xo(r){return!!r?.[Zl]}var ct=class r{bufs;length;[Zl]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(xo(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(xo(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Yl(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Yl(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(xo(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return yt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:yt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!xo(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let 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=e;f<=c;f+=u){u=0;for(let p=l;p>=0;p--){let y=this.get(f+p);if(n[p]!==y){u=Math.max(1,p-a[y]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=At(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=vt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=vt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=vt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=At(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=vt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=vt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=vt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=vt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=vt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Et(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};function Xl(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 Jl(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Ql(r,t){let e=Xl(r).return?.();Jl(e)&&e.catch(n=>{t.error("could not cause iterator to return",n)})}var c0="ERR_STREAM_RESET",l0="ERR_SINK_INVALID_STATE",u0=5e3;function la(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Eo=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(t){this.sinkController=new AbortController,this.sinkEnd=ht(),this.closed=ht(),this.log=t.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=t.id,this.metadata=t.metadata??{},this.direction=t.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=t.sendCloseWriteTimeout??u0,this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=Ge({onEnd:e=>{e!=null?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(t){if(this.writeStatus!=="ready")throw new D(`writable end state is "${this.writeStatus}" not "ready"`,l0);try{this.writeStatus="writing";let e={signal:this.sinkController.signal};if(this.direction==="outbound"){let o=this.sendNewStream(e);la(o)&&await o}let n=()=>{Ql(t,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let o of t){o=o instanceof Uint8Array?new ct(o):o;let s=this.sendData(o,e);la(s)&&(this.sendingData=ht(),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(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(t){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),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(t){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),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(t){this.log.trace("closing gracefully"),this.status="closing",await Ie(Promise.all([this.closeWrite(t),this.closeRead(t),this.closed.promise]),t?.signal),this.status="closed",this.log.trace("closed gracefully")}async closeRead(t={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let e=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(t)),e==="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(t={}){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 Ie(this.sink([]),t.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await Ie(this.sendingData.promise,t.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await Ie(this.sinkEnd.promise,t.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(t){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",t),this.log("try to send reset to remote");let e=this.sendReset();la(e)&&e.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(t),this.onAbort?.(t)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let t=new D("stream reset",c0);this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(t),this.onReset?.()}_closeSinkAndSource(t){this._closeSink(t),this._closeSource(t)}_closeSink(t){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(t)}_closeSource(t){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(t))}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(t){this.streamSource.push(t)}sourceReadableLength(){return this.streamSource.readableLength}};function vo(r){return r[Symbol.asyncIterator]!=null}var Ao=r=>{let t=gt(r),e=At(t);return me(r,e),Ao.bytes=t,e};Ao.bytes=0;function An(r,t){t=t??{};let e=t.lengthEncoder??Ao;function*n(o){let s=e(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return vo(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}An.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Ao;return new ct(e(r.byteLength),r)};var Fr=$c(ru(),1);var h0=8,d0=1024*1024*4,hr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(hr||(hr={}));var ua=r=>{let t=ee(r);return ua.bytes=gt(t),t};ua.bytes=0;function dr(r,t){let e=new ct,n=hr.LENGTH,o=-1,s=t?.lengthDecoder??ua,i=t?.maxLengthLength??h0,a=t?.maxDataLength??d0;function*c(){for(;e.byteLength>0;){if(n===hr.LENGTH)try{if(o=s(e),o<0)throw(0,Fr.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(o>a)throw(0,Fr.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=hr.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw(0,Fr.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw l}if(n===hr.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=hr.LENGTH}}}return vo(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw(0,Fr.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw(0,Fr.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}dr.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return dr(n,{...t??{},onLength:s=>{e=s}})};var m0=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function g0(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:u}=m0(r),f=(...y)=>{let m=e.multiArgs?y:y[0];e.filter&&!e.filter(m)||(c.push(m),e.count===c.length&&(n(),s(c)))},p=y=>{n(),i(y)};n=()=>{for(let y of a)u(y,f);for(let y of e.rejectionEvents)u(y,p)};for(let y of a)l(y,f);for(let y of e.rejectionEvents)l(y,p);e.signal&&e.signal.addEventListener("abort",()=>{p(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=ur(o,{milliseconds:e.timeout});return s.cancel=n,s}return o}function fa(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=g0(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var ha=new Float32Array([-0]),qe=new Uint8Array(ha.buffer);function nu(r,t,e){ha[0]=r,t[e]=qe[0],t[e+1]=qe[1],t[e+2]=qe[2],t[e+3]=qe[3]}function ou(r,t){return qe[0]=r[t],qe[1]=r[t+1],qe[2]=r[t+2],qe[3]=r[t+3],ha[0]}var da=new Float64Array([-0]),Ut=new Uint8Array(da.buffer);function su(r,t,e){da[0]=r,t[e]=Ut[0],t[e+1]=Ut[1],t[e+2]=Ut[2],t[e+3]=Ut[3],t[e+4]=Ut[4],t[e+5]=Ut[5],t[e+6]=Ut[6],t[e+7]=Ut[7]}function iu(r,t){return Ut[0]=r[t],Ut[1]=r[t+1],Ut[2]=r[t+2],Ut[3]=r[t+3],Ut[4]=r[t+4],Ut[5]=r[t+5],Ut[6]=r[t+6],Ut[7]=r[t+7],da[0]}var y0=BigInt(Number.MAX_SAFE_INTEGER),w0=BigInt(Number.MIN_SAFE_INTEGER),Gt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return pr;if(t<y0&&t>w0)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>au&&(o=0n,++n>au&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return pr;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):pr}},pr=new Gt(0,0);pr.toBigInt=function(){return 0n};pr.zzEncode=pr.zzDecode=function(){return this};pr.length=function(){return 1};var au=4294967296n;function cu(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function lu(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function pa(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function ne(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function So(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var ma=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,ne(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ne(this,4);return So(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ne(this,4);return So(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ne(this,4);let t=ou(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw ne(this,4);let t=iu(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw ne(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return lu(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw ne(this,t);this.pos+=t}else do if(this.pos>=this.len)throw ne(this);while(this.buf[this.pos++]&128);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Gt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw ne(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw ne(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ne(this,8);let t=So(this.buf,this.pos+=4),e=So(this.buf,this.pos+=4);return new Gt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Ni(this.buf,this.pos);return this.pos+=gt(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function ga(r){return new ma(r instanceof Uint8Array?r:r.subarray())}function oe(r,t,e){let n=ga(r);return t.decode(n,void 0,e)}function ya(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return At(i);o+i>t&&(n=At(t),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var mr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function wa(){}var xa=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},b0=ya();function x0(r){return globalThis.Buffer!=null?At(r):b0(r)}var Bn=class{len;head;tail;states;constructor(){this.len=0,this.head=new mr(wa,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new mr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Ea((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Bo,10,Gt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Gt.fromBigInt(t);return this._push(Bo,e.length(),e)}uint64Number(t){return this._push(Ti,gt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Gt.fromBigInt(t).zzEncode();return this._push(Bo,e.length(),e)}sint64Number(t){let e=Gt.fromNumber(t).zzEncode();return this._push(Bo,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ba,1,t?1:0)}fixed32(t){return this._push(Sn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Gt.fromBigInt(t);return this._push(Sn,4,e.lo)._push(Sn,4,e.hi)}fixed64Number(t){let e=Gt.fromNumber(t);return this._push(Sn,4,e.lo)._push(Sn,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(nu,4,t)}double(t){return this._push(su,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ba,1,0):this.uint32(e)._push(v0,e,t)}string(t){let e=cu(t);return e!==0?this.uint32(e)._push(pa,e,t):this._push(ba,1,0)}fork(){return this.states=new xa(this),this.head=this.tail=new mr(wa,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 mr(wa,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=x0(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ba(r,t,e){t[e]=r&255}function E0(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Ea=class extends mr{next;constructor(t,e){super(E0,t,e),this.next=void 0}};function Bo(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Sn(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function v0(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Bn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(A0,t,r),this},Bn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(S0,t,r),this});function A0(r,t,e){t.set(r,e)}function S0(r,t,e){r.length<40?pa(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(J(r),e)}function va(){return new Bn}function se(r,t){let e=va();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Kr;(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"})(Kr||(Kr={}));function Io(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function gr(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return Io("enum",Kr.VARINT,e,n)}function ie(r,t){return Io("message",Kr.LENGTH_DELIMITED,r,t)}var Mt;(function(r){let t;(function(o){o.FIN="FIN",o.STOP_SENDING="STOP_SENDING",o.RESET="RESET",o.FIN_ACK="FIN_ACK"})(t=r.Flag||(r.Flag={}));let e;(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"})(e||(e={})),function(o){o.codec=()=>gr(e)}(t=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=ie((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)=>{let i={},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.flag=r.Flag.codec().decode(o);break;case 2:i.message=o.bytes();break;default:o.skipType(c&7);break}}return i})),n),r.encode=o=>se(o,r.codec()),r.decode=o=>oe(o,r.codec())})(Mt||(Mt={}));var B0=2*1024*1024,I0=30*1e3,_0=7,k0=2,C0=256*1024,R0=5e3,T0=5e3,Aa=class extends Eo{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;constructor(t){let e=t.onEnd;switch(t.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 ur(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(s){this.log.error("error receiving FIN_ACK",s)}}).then(()=>{this.incomingData.end(),e?.(o)}).catch(s=>{this.log.error("error ending stream",s)})},super(t),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=Ge(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??I0,this.maxBufferedAmount=t.maxBufferedAmount??B0,this.maxMessageSize=(t.maxMessageSize??C0)-_0-k0,this.receiveFinAck=ht(),this.finAckTimeout=t.closeTimeout??R0,this.openTimeout=t.openTimeout??T0,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 D("Unknown datachannel state","ERR_INVALID_STATE")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime()},this.channel.onclose=o=>{this.receiveFinAck.resolve(),this.close().catch(s=>{this.log.error("error closing stream after channel closed",s)})},this.channel.onerror=o=>{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 dr(this.incomingData)){let s=n.processIncomingProtobuf(o);s!=null&&n.sourcePush(new ct(s))}}).catch(o=>{this.log.error("error processing incoming data channel messages",o)})}sendNewStream(){}async _sendMessage(t,e=!0){if(e&&this.channel.bufferedAmount>this.maxBufferedAmount)try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await fa(this.channel,"bufferedamountlow",{timeout:this.bufferedAmountLowEventTimeout})}catch(n){throw n instanceof Mr?new D(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`,"ERR_BUFFER_CLEAR_TIMEOUT"):n}if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new D(`Invalid datachannel state - ${this.channel.readyState}`,"ERR_INVALID_STATE");this.channel.readyState!=="open"&&(this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await fa(this.channel,"open",{timeout:this.openTimeout}),this.log('channel state is now "%s", sending data',this.channel.readyState)),this.channel.send(t.subarray())}async sendData(t){for(t=t.sublist();t.byteLength>0;){let e=Math.min(t.byteLength,this.maxMessageSize),n=t.subarray(0,e),o=Mt.encode({message:n}),s=An.single(o);await this._sendMessage(s),t.consume(e)}}async sendReset(){await this._sendFlag(Mt.Flag.RESET)}async sendCloseWrite(t){if(await this._sendFlag(Mt.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await Ie(this.receiveFinAck.promise,t?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorCode:"ERR_FIN_ACK_NOT_RECEIVED"})}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(){await this._sendFlag(Mt.Flag.STOP_SENDING)}processIncomingProtobuf(t){let e=Mt.decode(t);if(e.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',e.flag,this.writeStatus,this.readStatus),e.flag===Mt.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Mt.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),e.flag===Mt.Flag.RESET&&this.reset(),e.flag===Mt.Flag.STOP_SENDING&&this.remoteCloseRead(),e.flag===Mt.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),this.readStatus==="ready")return e.message}async _sendFlag(t){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',this.channel.readyState,t.toString()),!1;this.log.trace("sending flag %s",t.toString());let e=Mt.encode({flag:t}),n=An.single(e);try{return await this._sendMessage(n,!1),!0}catch(o){this.log.error("could not send flag %s",t.toString(),o)}return!1}};function $r(r){let{channel:t,direction:e}=r;return new Aa({id:e==="inbound"?`i${t.id}`:`r${t.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${e}:${t.id}`),...r})}var fu="/webrtc",je=class{protocol;peerConnection;bufferedStreams=[];metrics;dataChannelOptions;components;log;constructor(t,e){this.components=t,this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??fu,this.dataChannelOptions=e.dataChannelOptions??{},this.log=t.logger.forComponent("libp2p:webrtc:datachannelmuxerfactory"),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=$r({channel:n,direction:"inbound",onEnd:i=>{o.onEnd(i)},logger:t.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(t){return new Sa(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},Sa=class{init;streams;protocol;log;peerConnection;dataChannelOptions;metrics;logger;constructor(t,e){this.init=e,this.log=t.logger.forComponent("libp2p:webrtc:muxer"),this.logger=t.logger,this.streams=e.streams.map(n=>n.stream),this.peerConnection=e.peerConnection,this.protocol=e.protocol??fu,this.metrics=e.metrics,this.dataChannelOptions=e.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=$r({channel:n,direction:"inbound",onEnd:()=>{this.log("incoming channel %s ended with state %s",n.id,n.readyState),this.#t(o,n)},logger:this.logger,...this.dataChannelOptions});this.streams.push(o),this.metrics?.increment({incoming_stream:!0}),e?.onIncomingStream?.(o)},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.#t(n.stream,n.channel)},this.metrics?.increment({incoming_stream:!0}),this.init?.onIncomingStream?.(n.stream)})})}#t(t,e){this.log.trace("stream %s %s %s onEnd",t.direction,t.id,t.protocol),zl(e,`${t.direction} ${t.id} ${t.protocol}`,this.dataChannelOptions.drainTimeout,{log:this.log}),this.streams=this.streams.filter(n=>n.id!==t.id),this.metrics?.increment({stream_end:!0}),this.init?.onStreamEnd?.(t)}async close(t){try{await Promise.all(this.streams.map(async e=>e.close(t)))}catch(e){this.abort(e)}}abort(t){for(let e of this.streams)e.abort(t)}source=go();sink=yo;newStream(){let t=this.peerConnection.createDataChannel("");this.log.trace("opened outgoing datachannel with channel id %s",t.id);let e=$r({channel:t,direction:"outbound",onEnd:()=>{this.log("outgoing channel %s ended with state %s",t.id,t.readyState),this.#t(e,t)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(e),this.metrics?.increment({outgoing_stream:!0}),e}};var yr=globalThis.RTCPeerConnection,_o=globalThis.RTCSessionDescription,hu=globalThis.RTCIceCandidate;var Ba=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=ht(),this.haveNext=ht()}[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 t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ht(),t}async throw(t){return this.ended=!0,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return await this._push(void 0),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ht(),await Ie(this.readNext.promise,e?.signal,e)}};function du(){return new Ba}var ko=class extends Error{code;constructor(t,e){super(t),this.code=e}},Ia=class extends ko{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted"}};function pu(r,t){let e=du();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.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 ct;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new Ia("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:p}=await Promise.race([n.next(),l]);return f===!0?new ct:p}for(;o.byteLength<i;){let{value:f,done:p}=await Promise.race([n.next(),l]);if(p===!0)throw new ko("unexpected end of input","ERR_UNEXPECTED_EOF");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 e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Co=class extends Error{code;constructor(t,e){super(t),this.code=e}};function In(r,t={}){let e=pu(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=gt(t.maxDataLength));let n=t?.lengthDecoder??ee,o=t?.lengthEncoder??me;return{read:async i=>{let a=-1,c=new ct;for(;;){c.append(await e.read(1,i));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Co("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Co("message length too long","ERR_MSG_DATA_TOO_LONG");return e.read(a,i)},write:async(i,a)=>{await e.write(new ct(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new ct(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Ro(r,t){let e=In(r,t),n={read:async(o,s)=>{let i=await e.read(s);return o.decode(i)},write:async(o,s,i)=>{await e.write(s.encode(o),i)},writeV:async(o,s,i)=>{await e.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>e.unwrap()};return n}var qt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Vt;(function(r){let t;(function(o){o.SDP_OFFER="SDP_OFFER",o.SDP_ANSWER="SDP_ANSWER",o.ICE_CANDIDATE="ICE_CANDIDATE"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.SDP_OFFER=0]="SDP_OFFER",o[o.SDP_ANSWER=1]="SDP_ANSWER",o[o.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(e||(e={})),function(o){o.codec=()=>gr(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ie((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)=>{let i={},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.type=r.Type.codec().decode(o);break;case 2:i.data=o.string();break;default:o.skipType(c&7);break}}return i})),n),r.encode=o=>se(o,r.codec()),r.decode=o=>oe(o,r.codec())})(Vt||(Vt={}));var To=async(r,t,e)=>{try{let n=ht();for(L0(r,n);;){let o=await Promise.race([n.promise,t.read({signal:e.signal}).catch(()=>{})]);if(o==null){e.signal?.throwIfAborted();break}if(o.type!==Vt.Type.ICE_CANDIDATE)throw new D("ICE candidate message expected","ERR_NOT_ICE_CANDIDATE");let s=JSON.parse(o.data??"null");if(s===""||s===null){e.onProgress?.(new qt("webrtc:end-of-ice-candidates")),e.log.trace("end-of-candidates received");continue}let i=new hu(s);e.log.trace("%s received new ICE candidate %o",e.direction,s);try{e.onProgress?.(new qt("webrtc:add-ice-candidate",i.candidate)),await r.addIceCandidate(i)}catch(a){e.log.error("%s bad candidate received",e.direction,s,a)}}}catch(n){if(e.log.error("%s error parsing ICE candidate",e.direction,n),e.signal?.aborted===!0)throw n}};function N0(r){return En?r.iceConnectionState:r.connectionState}function L0(r,t){r[En?"oniceconnectionstatechange":"onconnectionstatechange"]=e=>{switch(N0(r)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new D("RTCPeerConnection was closed","ERR_CONNECTION_CLOSED_BEFORE_CONNECTED"));break;default:break}}}async function mu({rtcConfiguration:r,dataChannel:t,signal:e,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=gu(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",u);let f=u.getPeerId();if(f==null)throw new D("Relay peer was missing","ERR_INVALID_ADDRESS");let p=s.getConnections(lr(f)),y,m=!1;p.length===0?(l?.(new qt("webrtc:dial-relay")),y=await i.dial(u,{signal:e,onProgress:l}),m=!0):(l?.(new qt("webrtc:reuse-relay-connection")),y=p[0]);try{l?.(new qt("webrtc:open-signaling-stream"));let h=await y.newStream(No,{signal:e,runOnTransientConnection:!0}),d=Ro(h).pb(Vt),b=new yr(r),E=new je({logger:c},{peerConnection:b,dataChannelOptions:t});try{let w=b.createDataChannel("init");b.onicecandidate=({candidate:I})=>{let _=JSON.stringify(I?.toJSON()??null);a.trace("initiator sending ICE candidate %o",I),d.write({type:Vt.Type.ICE_CANDIDATE,data:_},{signal:e}).catch(N=>{a.error("error sending ICE candidate",N)})},b.onicecandidateerror=I=>{a.error("initiator ICE candidate error",I)};let S=await b.createOffer().catch(I=>{throw a.error("could not execute createOffer",I),new D("Failed to set createOffer","ERR_SDP_HANDSHAKE_FAILED")});a.trace("initiator send SDP offer %s",S.sdp),l?.(new qt("webrtc:send-sdp-offer")),await d.write({type:Vt.Type.SDP_OFFER,data:S.sdp},{signal:e}),await b.setLocalDescription(S).catch(I=>{throw a.error("could not execute setLocalDescription",I),new D("Failed to set localDescription","ERR_SDP_HANDSHAKE_FAILED")}),l?.(new qt("webrtc:read-sdp-answer"));let x=await d.read({signal:e});if(x.type!==Vt.Type.SDP_ANSWER)throw new D("Remote should send an SDP answer","ERR_SDP_HANDSHAKE_FAILED");a.trace("initiator receive SDP answer %s",x.data);let B=new _o({type:"answer",sdp:x.data});return await b.setRemoteDescription(B).catch(I=>{throw a.error("could not execute setRemoteDescription",I),new D("Failed to set remoteDescription","ERR_SDP_HANDSHAKE_FAILED")}),a.trace("initiator read candidates until connected"),l?.(new qt("webrtc:read-ice-candidates")),await To(b,d,{direction:"initiator",signal:e,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),w.close(),l?.(new qt("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await h.close({signal:e}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:b,muxerFactory:E}}catch(w){throw a.error("outgoing signaling error",w),b.close(),h.abort(w),w}finally{b.onicecandidate=null,b.onicecandidateerror=null}}finally{if(m)try{await y.close({signal:e})}catch(h){y.abort(h)}}}var D0=U("dns4"),U0=U("dns6"),P0=U("dnsaddr"),wr=mt(U("dns"),P0,D0,U0),Uo=mt(U("ip4"),U("ip6")),Wr=mt(K(Uo,U("tcp")),K(wr,U("tcp"))),Po=K(Uo,U("udp")),O0=K(Po,U("utp")),H0=K(Po,U("quic")),M0=K(Po,U("quic-v1")),_a=mt(K(Wr,U("ws")),K(wr,U("ws"))),Lo=mt(K(_a,U("p2p")),_a),ka=mt(K(Wr,U("wss")),K(wr,U("wss")),K(Wr,U("tls"),U("ws")),K(wr,U("tls"),U("ws"))),Do=mt(K(ka,U("p2p")),ka),Ca=mt(K(Wr,U("http")),K(Uo,U("http")),K(wr,U("http"))),Ra=mt(K(Wr,U("https")),K(Uo,U("https")),K(wr,U("https"))),yu=K(Po,U("webrtc-direct"),U("certhash")),xu=mt(K(yu,U("p2p")),yu),wu=K(M0,U("webtransport"),U("certhash"),U("certhash")),Eu=mt(K(wu,U("p2p")),wu),vu=mt(K(Lo,U("p2p-webrtc-star"),U("p2p")),K(Do,U("p2p-webrtc-star"),U("p2p")),K(Lo,U("p2p-webrtc-star")),K(Do,U("p2p-webrtc-star"))),f2=mt(K(Lo,U("p2p-websocket-star"),U("p2p")),K(Do,U("p2p-websocket-star"),U("p2p")),K(Lo,U("p2p-websocket-star")),K(Do,U("p2p-websocket-star"))),Au=mt(K(Ca,U("p2p-webrtc-direct"),U("p2p")),K(Ra,U("p2p-webrtc-direct"),U("p2p")),K(Ca,U("p2p-webrtc-direct")),K(Ra,U("p2p-webrtc-direct"))),br=mt(_a,ka,Ca,Ra,vu,Au,Wr,O0,H0,wr,xu,Eu),h2=mt(K(br,U("p2p-stardust"),U("p2p")),K(br,U("p2p-stardust"))),ze=mt(K(br,U("p2p")),vu,Au,xu,Eu,U("p2p")),bu=mt(K(ze,U("p2p-circuit"),ze),K(ze,U("p2p-circuit")),K(U("p2p-circuit"),ze),K(br,U("p2p-circuit")),K(U("p2p-circuit"),br),U("p2p-circuit")),Su=()=>mt(K(bu,Su),bu),_e=Su(),d2=mt(K(_e,ze,_e),K(ze,_e),K(_e,ze),_e,ze);var p2=mt(K(_e,U("webrtc"),U("p2p")),K(_e,U("webrtc")),K(br,U("webrtc"),U("p2p")),K(br,U("webrtc")),U("webrtc"));function Bu(r){function t(e){let n;try{n=re(e)}catch{return!1}let o=r(n.protoNames());return o===null?!1:o===!0||o===!1?o:o.length===0}return t}function K(...r){function t(e){if(e.length<r.length)return null;let n=e;return r.some(o=>(n=typeof o=="function"?o().partialMatch(e):o.partialMatch(e),Array.isArray(n)&&(e=n),n===null)),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:Bu(t),partialMatch:t}}function mt(...r){function t(n){let o=null;return r.some(s=>{let i=typeof s=="function"?s().partialMatch(n):s.partialMatch(n);return i!=null?(o=i,!0):!1}),o}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:Bu(t),partialMatch:t}}function U(r){let t=r;function e(o){let s;try{s=re(o)}catch{return!1}let i=s.protoNames();return i.length===1&&i[0]===t}function n(o){return o.length===0?null:o[0]===t?o.slice(1):null}return{toString:function(){return t},matches:e,partialMatch:n}}var Oo=class extends to{peerId;transportManager;shutdownController;constructor(t,e){super(),this.peerId=t.peerId,this.transportManager=t.transportManager,this.shutdownController=e.shutdownController}async listen(){this.safeDispatchEvent("listening",{})}getAddrs(){return this.transportManager.getListeners().filter(t=>t!==this).map(t=>t.getAddrs().filter(e=>_e.matches(e)).map(e=>e.encapsulate(`/webrtc/p2p/${this.peerId}`))).flat()}async close(){this.shutdownController.abort(),this.safeDispatchEvent("close",{})}};async function Iu({peerConnection:r,stream:t,signal:e,connection:n,log:o}){o.trace("new inbound signaling stream");let s=Ro(t).pb(Vt);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:Vt.Type.ICE_CANDIDATE,data:f},{signal:e}).catch(p=>{o.error("error sending ICE candidate",p)})};let a=await s.read({signal:e});if(a.type!==Vt.Type.SDP_OFFER)throw new D(`expected message type SDP_OFFER, received: ${a.type??"undefined"} `,"ERR_SDP_HANDSHAKE_FAILED");o.trace("recipient receive SDP offer %s",a.data);let c=new _o({type:"offer",sdp:a.data});await r.setRemoteDescription(c).catch(u=>{throw o.error("could not execute setRemoteDescription",u),new D("Failed to set remoteDescription","ERR_SDP_HANDSHAKE_FAILED")});let l=await r.createAnswer().catch(u=>{throw o.error("could not execute createAnswer",u),new D("Failed to create answer","ERR_SDP_HANDSHAKE_FAILED")});o.trace("recipient send SDP answer %s",l.sdp),await s.write({type:Vt.Type.SDP_ANSWER,data:l.sdp},{signal:e}),await r.setLocalDescription(l).catch(u=>{throw o.error("could not execute setLocalDescription",u),new D("Failed to set localDescription","ERR_SDP_HANDSHAKE_FAILED")}),o.trace("recipient read candidates until connected"),await To(r,s,{direction:"recipient",signal:e,log:o})}catch(a){if(r.connectionState!=="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=re(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return o.trace("recipient connected to remote address %s",i),{remoteAddress:i}}var V0="/webrtc",F0="/p2p-circuit",No="/webrtc-signaling/0.0.1",K0=30*1e3,Ho=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,e={}){this.components=t,this.init=e,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,Qn(1/0,this.shutdownController.signal),t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[Jn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Rr]=["@libp2p/transport"];[Gc]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(No,t=>{this._onProtocol(t).catch(e=>{this.log.error("failed to handle incoming connect from %p",t.connection.remotePeer,e)})},{runOnTransientConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(No),this._started=!1}createListener(t){return new Oo(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(Pl.exactMatch)}dialFilter(t){return this.listenFilter(t)}async dial(t,e){this.log.trace("dialing address: %a",t);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await mu({rtcConfiguration:await vn(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:t,dataChannelOptions:this.init.dataChannel,signal:e.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:e.onProgress}),i=new fr(this.components,{peerConnection:o,timeline:{open:Date.now()},remoteAddr:n,metrics:this.metrics?.dialerEvents}),a=await e.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,muxerFactory:s,onProgress:e.onProgress});return this._closeOnShutdown(o,i),a}async _onProtocol({connection:t,stream:e}){let n=AbortSignal.timeout(this.init.inboundConnectionTimeout??K0),o=new yr(await vn(this.init.rtcConfiguration)),s=new je(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await Iu({peerConnection:o,connection:t,stream:e,signal:n,log:this.log});await e.close({signal:n});let a=new fr(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(),e.abort(i),i}}_closeOnShutdown(t,e){let n=()=>{e.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection",o)})};this.shutdownController.signal.addEventListener("abort",n),t.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function gu(r){let t=r.toString().split(V0+"/");if(t.length!==2)throw new D("webrtc protocol was not present in multiaddr",Wt.ERR_INVALID_MULTIADDR);if(!t[0].includes(F0))throw new D("p2p-circuit protocol was not present in multiaddr",Wt.ERR_INVALID_MULTIADDR);let e=re(t[0]),o=re("/"+t[1]).getPeerId();if(o==null)throw new D("destination peer id was missing",Wt.ERR_INVALID_MULTIADDR);let s=e.protos().pop();if(s===void 0)throw new D("invalid multiaddr",Wt.ERR_INVALID_MULTIADDR);return s.name!=="p2p"&&(e=e.encapsulate(`/p2p/${o}`)),{baseAddr:e,peerId:lr(o)}}var qa={};xt(qa,{Ed25519PrivateKey:()=>Sr,Ed25519PublicKey:()=>Ln,generateKeyPair:()=>Xm,generateKeyPairFromSeed:()=>ef,unmarshalEd25519PrivateKey:()=>Ym,unmarshalEd25519PublicKey:()=>Zm});function Zt(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Ye(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function $0(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Gr(r,...t){if(!$0(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function xr(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ye(r.outputLen),Ye(r.blockLen)}function qr(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function _u(r,t){Gr(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var Mo=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var zr=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ae=(r,t)=>r<<32-t|r>>>t;var q2=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var W0=async()=>{};async function ku(r,t,e){let n=Date.now();for(let o=0;o<r;o++){e(o);let s=Date.now()-n;s>=0&&s<t||(await W0(),n+=s)}}function Cu(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function ce(r){return typeof r=="string"&&(r=Cu(r)),Gr(r),r}function Ta(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Gr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}var jr=class{clone(){return this._cloneInto()}},G0={}.toString;function Ru(r,t){if(t!==void 0&&G0.call(t)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,t)}function Vo(r){let t=n=>r().update(ce(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Er(r=32){if(Mo&&typeof Mo.getRandomValues=="function")return Mo.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function q0(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}var Tu=(r,t,e)=>r&t^~r&e,Nu=(r,t,e)=>r&t^r&e^t&e,Yr=class extends jr{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=zr(this.buffer)}update(t){qr(this);let{view:e,buffer:n,blockLen:o}=this;t=ce(t);let s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=zr(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){qr(this),_u(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[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++)e[f]=0;q0(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=zr(t),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:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.length=o,t.pos=a,t.finished=s,t.destroyed=i,o%e&&t.buffer.set(n),t}};var Fo=BigInt(4294967295),Na=BigInt(32);function Lu(r,t=!1){return t?{h:Number(r&Fo),l:Number(r>>Na&Fo)}:{h:Number(r>>Na&Fo)|0,l:Number(r&Fo)|0}}function j0(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=Lu(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var z0=(r,t)=>BigInt(r>>>0)<<Na|BigInt(t>>>0),Y0=(r,t,e)=>r>>>e,Z0=(r,t,e)=>r<<32-e|t>>>e,X0=(r,t,e)=>r>>>e|t<<32-e,J0=(r,t,e)=>r<<32-e|t>>>e,Q0=(r,t,e)=>r<<64-e|t>>>e-32,tm=(r,t,e)=>r>>>e-32|t<<64-e,em=(r,t)=>t,rm=(r,t)=>r,nm=(r,t,e)=>r<<e|t>>>32-e,om=(r,t,e)=>t<<e|r>>>32-e,sm=(r,t,e)=>t<<e-32|r>>>64-e,im=(r,t,e)=>r<<e-32|t>>>64-e;function am(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var cm=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),lm=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,um=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),fm=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,hm=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),dm=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var pm={fromBig:Lu,split:j0,toBig:z0,shrSH:Y0,shrSL:Z0,rotrSH:X0,rotrSL:J0,rotrBH:Q0,rotrBL:tm,rotr32H:em,rotr32L:rm,rotlSH:nm,rotlSL:om,rotlBH:sm,rotlBL:im,add:am,add3L:cm,add3H:lm,add4L:um,add4H:fm,add5H:dm,add5L:hm},Z=pm;var[mm,gm]=Z.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))),Ze=new Uint32Array(80),Xe=new Uint32Array(80),La=class extends Yr{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:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:p,Gh:y,Gl:m,Hh:h,Hl:d}=this;return[t,e,n,o,s,i,a,c,l,u,f,p,y,m,h,d]}set(t,e,n,o,s,i,a,c,l,u,f,p,y,m,h,d){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=p|0,this.Gh=y|0,this.Gl=m|0,this.Hh=h|0,this.Hl=d|0}process(t,e){for(let w=0;w<16;w++,e+=4)Ze[w]=t.getUint32(e),Xe[w]=t.getUint32(e+=4);for(let w=16;w<80;w++){let S=Ze[w-15]|0,x=Xe[w-15]|0,B=Z.rotrSH(S,x,1)^Z.rotrSH(S,x,8)^Z.shrSH(S,x,7),I=Z.rotrSL(S,x,1)^Z.rotrSL(S,x,8)^Z.shrSL(S,x,7),_=Ze[w-2]|0,N=Xe[w-2]|0,P=Z.rotrSH(_,N,19)^Z.rotrBH(_,N,61)^Z.shrSH(_,N,6),T=Z.rotrSL(_,N,19)^Z.rotrBL(_,N,61)^Z.shrSL(_,N,6),F=Z.add4L(I,T,Xe[w-7],Xe[w-16]),V=Z.add4H(F,B,P,Ze[w-7],Ze[w-16]);Ze[w]=V|0,Xe[w]=F|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:p,Fh:y,Fl:m,Gh:h,Gl:d,Hh:b,Hl:E}=this;for(let w=0;w<80;w++){let S=Z.rotrSH(f,p,14)^Z.rotrSH(f,p,18)^Z.rotrBH(f,p,41),x=Z.rotrSL(f,p,14)^Z.rotrSL(f,p,18)^Z.rotrBL(f,p,41),B=f&y^~f&h,I=p&m^~p&d,_=Z.add5L(E,x,I,gm[w],Xe[w]),N=Z.add5H(_,b,S,B,mm[w],Ze[w]),P=_|0,T=Z.rotrSH(n,o,28)^Z.rotrBH(n,o,34)^Z.rotrBH(n,o,39),F=Z.rotrSL(n,o,28)^Z.rotrBL(n,o,34)^Z.rotrBL(n,o,39),V=n&s^n&a^s&a,j=o&i^o&c^i&c;b=h|0,E=d|0,h=y|0,d=m|0,y=f|0,m=p|0,{h:f,l:p}=Z.add(l|0,u|0,N|0,P|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let v=Z.add3L(P,F,j);n=Z.add3H(v,N,T,V),o=v|0}({h:n,l:o}=Z.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Z.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Z.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Z.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:p}=Z.add(this.Eh|0,this.El|0,f|0,p|0),{h:y,l:m}=Z.add(this.Fh|0,this.Fl|0,y|0,m|0),{h,l:d}=Z.add(this.Gh|0,this.Gl|0,h|0,d|0),{h:b,l:E}=Z.add(this.Hh|0,this.Hl|0,b|0,E|0),this.set(n,o,s,i,a,c,l,u,f,p,y,m,h,d,b,E)}roundClean(){Ze.fill(0),Xe.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 _n=Vo(()=>new La);var $o={};xt($o,{abytes:()=>Zr,bitGet:()=>Am,bitLen:()=>vm,bitMask:()=>kn,bitSet:()=>Sm,bytesToHex:()=>Ce,bytesToNumberBE:()=>Re,bytesToNumberLE:()=>le,concatBytes:()=>Ne,createHmacDrbg:()=>Pa,ensureBytes:()=>it,equalBytes:()=>xm,hexToBytes:()=>vr,hexToNumber:()=>Ua,isBytes:()=>Je,numberToBytesBE:()=>Qe,numberToBytesLE:()=>Te,numberToHexUnpadded:()=>Ou,numberToVarBytesBE:()=>bm,utf8ToBytes:()=>Em,validateObject:()=>Xt});var Pu=BigInt(0),Ko=BigInt(1),ym=BigInt(2);function Je(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Zr(r){if(!Je(r))throw new Error("Uint8Array expected")}var wm=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Ce(r){Zr(r);let t="";for(let e=0;e<r.length;e++)t+=wm[r[e]];return t}function Ou(r){let t=r.toString(16);return t.length&1?`0${t}`:t}function Ua(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var ke={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Du(r){if(r>=ke._0&&r<=ke._9)return r-ke._0;if(r>=ke._A&&r<=ke._F)return r-(ke._A-10);if(r>=ke._a&&r<=ke._f)return r-(ke._a-10)}function vr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=Du(r.charCodeAt(s)),a=Du(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 Re(r){return Ua(Ce(r))}function le(r){return Zr(r),Ua(Ce(Uint8Array.from(r).reverse()))}function Qe(r,t){return vr(r.toString(16).padStart(t*2,"0"))}function Te(r,t){return Qe(r,t).reverse()}function bm(r){return vr(Ou(r))}function it(r,t,e){let n;if(typeof t=="string")try{n=vr(t)}catch(s){throw new Error(`${r} must be valid hex string, got "${t}". Cause: ${s}`)}else if(Je(t))n=Uint8Array.from(t);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(`${r} expected ${e} bytes, got ${o}`);return n}function Ne(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Zr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function xm(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function Em(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function vm(r){let t;for(t=0;r>Pu;r>>=Ko,t+=1);return t}function Am(r,t){return r>>BigInt(t)&Ko}function Sm(r,t,e){return r|(e?Ko:Pu)<<BigInt(t)}var kn=r=>(ym<<BigInt(r-1))-Ko,Da=r=>new Uint8Array(r),Uu=r=>Uint8Array.from(r);function Pa(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=Da(r),o=Da(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=Da())=>{o=a(Uu([0]),f),n=a(),f.length!==0&&(o=a(Uu([1]),f),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f<t;){n=a();let y=n.slice();p.push(y),f+=n.length}return Ne(...p)};return(f,p)=>{i(),c(f);let y;for(;!(y=p(l()));)c();return i(),y}}var Bm={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"||Je(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function Xt(r,t,e={}){let n=(o,s,i)=>{let a=Bm[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(e))n(o,s,!0);return r}var Bt=BigInt(0),lt=BigInt(1),Ar=BigInt(2),Im=BigInt(3),Oa=BigInt(4),Hu=BigInt(5),Mu=BigInt(8),_m=BigInt(9),km=BigInt(16);function tt(r,t){let e=r%t;return e>=Bt?e:t+e}function Ha(r,t,e){if(e<=Bt||t<Bt)throw new Error("Expected power/modulo > 0");if(e===lt)return Bt;let n=lt;for(;t>Bt;)t<&&(n=n*r%e),r=r*r%e,t>>=lt;return n}function at(r,t,e){let n=r;for(;t-- >Bt;)n*=n,n%=e;return n}function Wo(r,t){if(r===Bt||t<=Bt)throw new Error(`invert: expected positive integers, got n=${r} mod=${t}`);let e=tt(r,t),n=t,o=Bt,s=lt,i=lt,a=Bt;for(;e!==Bt;){let l=n/e,u=n%e,f=o-i*l,p=s-a*l;n=e,e=u,o=i,s=a,i=f,a=p}if(n!==lt)throw new Error("invert: does not exist");return tt(o,t)}function Cm(r){let t=(r-lt)/Ar,e,n,o;for(e=r-lt,n=0;e%Ar===Bt;e/=Ar,n++);for(o=Ar;o<r&&Ha(o,t,r)!==r-lt;o++);if(n===1){let i=(r+lt)/Oa;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=(e+lt)/Ar;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),e),f=a.pow(c,s),p=a.pow(c,e);for(;!a.eql(p,a.ONE);){if(a.eql(p,a.ZERO))return a.ZERO;let y=1;for(let h=a.sqr(p);y<l&&!a.eql(h,a.ONE);y++)h=a.sqr(h);let m=a.pow(u,lt<<BigInt(l-y-1));u=a.sqr(m),f=a.mul(f,m),p=a.mul(p,u),l=y}return f}}function Rm(r){if(r%Oa===Im){let t=(r+lt)/Oa;return function(n,o){let s=n.pow(o,t);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%Mu===Hu){let t=(r-Hu)/Mu;return function(n,o){let s=n.mul(o,Ar),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,Ar),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%km,Cm(r)}var Vu=(r,t)=>(tt(r,t)<)===lt,Tm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ma(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Tm.reduce((n,o)=>(n[o]="function",n),t);return Xt(r,e)}function Nm(r,t,e){if(e<Bt)throw new Error("Expected power > 0");if(e===Bt)return r.ONE;if(e===lt)return t;let n=r.ONE,o=t;for(;e>Bt;)e<&&(n=r.mul(n,o)),o=r.sqr(o),e>>=lt;return n}function Lm(r,t){let e=new Array(t.length),n=t.reduce((s,i,a)=>r.is0(i)?s:(e[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return t.reduceRight((s,i,a)=>r.is0(i)?s:(e[a]=r.mul(s,e[a]),r.mul(s,i)),o),e}function Va(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Go(r,t,e=!1,n={}){if(r<=Bt)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=Va(r,t);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=Rm(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:kn(o),ZERO:Bt,ONE:lt,create:c=>tt(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return Bt<=c&&c<r},is0:c=>c===Bt,isOdd:c=>(c<)===lt,neg:c=>tt(-c,r),eql:(c,l)=>c===l,sqr:c=>tt(c*c,r),add:(c,l)=>tt(c+l,r),sub:(c,l)=>tt(c-l,r),mul:(c,l)=>tt(c*l,r),pow:(c,l)=>Nm(a,c,l),div:(c,l)=>tt(c*Wo(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Wo(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>Lm(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?Te(c,s):Qe(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return e?le(c):Re(c)}});return Object.freeze(a)}function Fu(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Fa(r){let t=Fu(r);return t+Math.ceil(t/2)}function Ku(r,t,e=!1){let n=r.length,o=Fu(t),s=Fa(t);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=e?Re(r):le(r),a=tt(i,t-lt)+lt;return e?Te(a,o):Qe(a,o)}var Um=BigInt(0),Ka=BigInt(1);function qo(r,t){let e=(o,s)=>{let i=s.negate();return o?i:s},n=o=>{let s=Math.ceil(t/o)+1,i=2**(o-1);return{windows:s,windowSize:i}};return{constTimeNegate:e,unsafeLadder(o,s){let i=r.ZERO,a=o;for(;s>Um;)s&Ka&&(i=i.add(a)),a=a.double(),s>>=Ka;return i},precomputeWindow(o,s){let{windows:i,windowSize:a}=n(s),c=[],l=o,u=l;for(let f=0;f<i;f++){u=l,c.push(u);for(let p=1;p<a;p++)u=u.add(l),c.push(u);l=u.double()}return c},wNAF(o,s,i){let{windows:a,windowSize:c}=n(o),l=r.ZERO,u=r.BASE,f=BigInt(2**o-1),p=2**o,y=BigInt(o);for(let m=0;m<a;m++){let h=m*c,d=Number(i&f);i>>=y,d>c&&(d-=p,i+=Ka);let b=h,E=h+Math.abs(d)-1,w=m%2!==0,S=d<0;d===0?u=u.add(e(w,s[b])):l=l.add(e(S,s[E]))}return{p:l,f:u}},wNAFCached(o,s,i,a){let c=o._WINDOW_SIZE||1,l=s.get(o);return l||(l=this.precomputeWindow(o,c),c!==1&&s.set(o,a(l))),this.wNAF(c,l,i)}}}function Cn(r){return Ma(r.Fp),Xt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Va(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var ue=BigInt(0),jt=BigInt(1),jo=BigInt(2),Pm=BigInt(8),Om={zip215:!0};function Hm(r){let t=Cn(r);return Xt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function $u(r){let t=Hm(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=jo<<BigInt(a*8)-jt,u=e.create,f=t.uvRatio||((A,g)=>{try{return{isValid:!0,value:e.sqrt(A*e.inv(g))}}catch{return{isValid:!1,value:ue}}}),p=t.adjustScalarBytes||(A=>A),y=t.domain||((A,g,k)=>{if(g.length||k)throw new Error("Contexts/pre-hash are not supported");return A}),m=A=>typeof A=="bigint"&&ue<A,h=(A,g)=>m(A)&&m(g)&&A<g,d=A=>A===ue||h(A,l);function b(A,g){if(h(A,g))return A;throw new Error(`Expected valid scalar < ${g}, got ${typeof A} ${A}`)}function E(A){return A===ue?A:b(A,n)}let w=new Map;function S(A){if(!(A instanceof x))throw new Error("ExtendedPoint expected")}class x{constructor(g,k,R,L){if(this.ex=g,this.ey=k,this.ez=R,this.et=L,!d(g))throw new Error("x required");if(!d(k))throw new Error("y required");if(!d(R))throw new Error("z required");if(!d(L))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(g){if(g instanceof x)throw new Error("extended point not allowed");let{x:k,y:R}=g||{};if(!d(k)||!d(R))throw new Error("invalid affine point");return new x(k,R,jt,u(k*R))}static normalizeZ(g){let k=e.invertBatch(g.map(R=>R.ez));return g.map((R,L)=>R.toAffine(k[L])).map(x.fromAffine)}_setWindowSize(g){this._WINDOW_SIZE=g,w.delete(this)}assertValidity(){let{a:g,d:k}=t;if(this.is0())throw new Error("bad point: ZERO");let{ex:R,ey:L,ez:$,et:W}=this,Y=u(R*R),q=u(L*L),z=u($*$),st=u(z*z),nt=u(Y*g),_t=u(z*u(nt+q)),kt=u(st+u(k*u(Y*q)));if(_t!==kt)throw new Error("bad point: equation left != right (1)");let bt=u(R*L),Lt=u($*W);if(bt!==Lt)throw new Error("bad point: equation left != right (2)")}equals(g){S(g);let{ex:k,ey:R,ez:L}=this,{ex:$,ey:W,ez:Y}=g,q=u(k*Y),z=u($*L),st=u(R*Y),nt=u(W*L);return q===z&&st===nt}is0(){return this.equals(x.ZERO)}negate(){return new x(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:g}=t,{ex:k,ey:R,ez:L}=this,$=u(k*k),W=u(R*R),Y=u(jo*u(L*L)),q=u(g*$),z=k+R,st=u(u(z*z)-$-W),nt=q+W,_t=nt-Y,kt=q-W,bt=u(st*_t),Lt=u(nt*kt),ve=u(st*kt),ar=u(_t*nt);return new x(bt,Lt,ar,ve)}add(g){S(g);let{a:k,d:R}=t,{ex:L,ey:$,ez:W,et:Y}=this,{ex:q,ey:z,ez:st,et:nt}=g;if(k===BigInt(-1)){let Dc=u(($-L)*(z+q)),Uc=u(($+L)*(z-q)),Ys=u(Uc-Dc);if(Ys===ue)return this.double();let Pc=u(W*jo*nt),Oc=u(Y*jo*st),Hc=Oc+Pc,Mc=Uc+Dc,Vc=Oc-Pc,Jh=u(Hc*Ys),Qh=u(Mc*Vc),td=u(Hc*Vc),ed=u(Ys*Mc);return new x(Jh,Qh,ed,td)}let _t=u(L*q),kt=u($*z),bt=u(Y*R*nt),Lt=u(W*st),ve=u((L+$)*(q+z)-_t-kt),ar=Lt-bt,hn=Lt+bt,Lc=u(kt-k*_t),zh=u(ve*ar),Yh=u(hn*Lc),Zh=u(ve*Lc),Xh=u(ar*hn);return new x(zh,Yh,Xh,Zh)}subtract(g){return this.add(g.negate())}wNAF(g){return _.wNAFCached(this,w,g,x.normalizeZ)}multiply(g){let{p:k,f:R}=this.wNAF(b(g,n));return x.normalizeZ([k,R])[0]}multiplyUnsafe(g){let k=E(g);return k===ue?I:this.equals(I)||k===jt?this:this.equals(B)?this.wNAF(k).p:_.unsafeLadder(this,k)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return _.unsafeLadder(this,n).is0()}toAffine(g){let{ex:k,ey:R,ez:L}=this,$=this.is0();g==null&&(g=$?Pm:e.inv(L));let W=u(k*g),Y=u(R*g),q=u(L*g);if($)return{x:ue,y:jt};if(q!==jt)throw new Error("invZ was invalid");return{x:W,y:Y}}clearCofactor(){let{h:g}=t;return g===jt?this:this.multiplyUnsafe(g)}static fromHex(g,k=!1){let{d:R,a:L}=t,$=e.BYTES;g=it("pointHex",g,$);let W=g.slice(),Y=g[$-1];W[$-1]=Y&-129;let q=le(W);q===ue||(k?b(q,l):b(q,e.ORDER));let z=u(q*q),st=u(z-jt),nt=u(R*z-L),{isValid:_t,value:kt}=f(st,nt);if(!_t)throw new Error("Point.fromHex: invalid y coordinate");let bt=(kt&jt)===jt,Lt=(Y&128)!==0;if(!k&&kt===ue&&Lt)throw new Error("Point.fromHex: x=0 and x_0=1");return Lt!==bt&&(kt=u(-kt)),x.fromAffine({x:kt,y:q})}static fromPrivateKey(g){return T(g).point}toRawBytes(){let{x:g,y:k}=this.toAffine(),R=Te(k,e.BYTES);return R[R.length-1]|=g&jt?128:0,R}toHex(){return Ce(this.toRawBytes())}}x.BASE=new x(t.Gx,t.Gy,jt,u(t.Gx*t.Gy)),x.ZERO=new x(ue,jt,jt,ue);let{BASE:B,ZERO:I}=x,_=qo(x,a*8);function N(A){return tt(A,n)}function P(A){return N(le(A))}function T(A){let g=a;A=it("private key",A,g);let k=it("hashed private key",s(A),2*g),R=p(k.slice(0,g)),L=k.slice(g,2*g),$=P(R),W=B.multiply($),Y=W.toRawBytes();return{head:R,prefix:L,scalar:$,point:W,pointBytes:Y}}function F(A){return T(A).pointBytes}function V(A=new Uint8Array,...g){let k=Ne(...g);return P(s(y(k,it("context",A),!!o)))}function j(A,g,k={}){A=it("message",A),o&&(A=o(A));let{prefix:R,scalar:L,pointBytes:$}=T(g),W=V(k.context,R,A),Y=B.multiply(W).toRawBytes(),q=V(k.context,Y,$,A),z=N(W+q*L);E(z);let st=Ne(Y,Te(z,e.BYTES));return it("result",st,a*2)}let v=Om;function C(A,g,k,R=v){let{context:L,zip215:$}=R,W=e.BYTES;A=it("signature",A,2*W),g=it("message",g),o&&(g=o(g));let Y=le(A.slice(W,2*W)),q,z,st;try{q=x.fromHex(k,$),z=x.fromHex(A.slice(0,W),$),st=B.multiplyUnsafe(Y)}catch{return!1}if(!$&&q.isSmallOrder())return!1;let nt=V(L,z.toRawBytes(),q.toRawBytes(),g);return z.add(q.multiplyUnsafe(nt)).subtract(st).clearCofactor().equals(x.ZERO)}return B._setWindowSize(8),{CURVE:t,getPublicKey:F,sign:j,verify:C,ExtendedPoint:x,utils:{getExtendedPublicKey:T,randomPrivateKey:()=>i(e.BYTES),precompute(A=8,g=x.BASE){return g._setWindowSize(A),g.multiply(BigInt(3)),g}}}}var Rn=BigInt(0),$a=BigInt(1);function Mm(r){return Xt(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function Wu(r){let t=Mm(r),{P:e}=t,n=w=>tt(w,e),o=t.montgomeryBits,s=Math.ceil(o/8),i=t.nByteLength,a=t.adjustScalarBytes||(w=>w),c=t.powPminus2||(w=>Ha(w,e-BigInt(2),e));function l(w,S,x){let B=n(w*(S-x));return S=n(S-B),x=n(x+B),[S,x]}function u(w){if(typeof w=="bigint"&&Rn<=w&&w<e)return w;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let f=(t.a-BigInt(2))/BigInt(4);function p(w,S){let x=u(w),B=u(S),I=x,_=$a,N=Rn,P=x,T=$a,F=Rn,V;for(let v=BigInt(o-1);v>=Rn;v--){let C=B>>v&$a;F^=C,V=l(F,_,P),_=V[0],P=V[1],V=l(F,N,T),N=V[0],T=V[1],F=C;let O=_+N,A=n(O*O),g=_-N,k=n(g*g),R=A-k,L=P+T,$=P-T,W=n($*O),Y=n(L*g),q=W+Y,z=W-Y;P=n(q*q),T=n(I*n(z*z)),_=n(A*k),N=n(R*(A+n(f*R)))}V=l(F,_,P),_=V[0],P=V[1],V=l(F,N,T),N=V[0],T=V[1];let j=c(N);return n(_*j)}function y(w){return Te(n(w),s)}function m(w){let S=it("u coordinate",w,s);return i===32&&(S[31]&=127),le(S)}function h(w){let S=it("scalar",w),x=S.length;if(x!==s&&x!==i)throw new Error(`Expected ${s} or ${i} bytes, got ${x}`);return le(a(S))}function d(w,S){let x=m(S),B=h(w),I=p(x,B);if(I===Rn)throw new Error("Invalid private or public key received");return y(I)}let b=y(t.Gu);function E(w){return d(w,b)}return{scalarMult:d,scalarMultBase:E,getSharedSecret:(w,S)=>d(w,S),getPublicKey:w=>E(w),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:b}}var Tn=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Gu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),bv=BigInt(0),Vm=BigInt(1),qu=BigInt(2),Fm=BigInt(3),Km=BigInt(5),$m=BigInt(8);function ju(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=Tn,a=r*r%s*r%s,c=at(a,qu,s)*a%s,l=at(c,Vm,s)*r%s,u=at(l,Km,s)*l%s,f=at(u,t,s)*u%s,p=at(f,e,s)*f%s,y=at(p,n,s)*p%s,m=at(y,o,s)*y%s,h=at(m,o,s)*y%s,d=at(h,t,s)*u%s;return{pow_p_5_8:at(d,qu,s)*r%s,b2:a}}function zu(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Wm(r,t){let e=Tn,n=tt(t*t*t,e),o=tt(n*n*t,e),s=ju(r*o).pow_p_5_8,i=tt(r*n*s,e),a=tt(t*i*i,e),c=i,l=tt(i*Gu,e),u=a===r,f=a===tt(-r,e),p=a===tt(-r*Gu,e);return u&&(i=c),(f||p)&&(i=l),Vu(i,e)&&(i=tt(-i,e)),{isValid:u||f,value:i}}var Gm=Go(Tn,void 0,!0),qm={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Gm,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:$m,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:_n,randomBytes:Er,adjustScalarBytes:zu,uvRatio:Wm},Xr=$u(qm);var Nn=Wu({P:Tn,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let t=Tn,{pow_p_5_8:e,b2:n}=ju(r);return tt(at(e,Fm,t)*n,t)},adjustScalarBytes:zu,randomBytes:Er});var Jr=32,Le=64,zo=32;function Yu(){let r=Xr.utils.randomPrivateKey(),t=Xr.getPublicKey(r);return{privateKey:Qu(r,t),publicKey:t}}function Zu(r){if(r.length!==zo)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let t=r,e=Xr.getPublicKey(t);return{privateKey:Qu(t,e),publicKey:e}}function Xu(r,t){let e=r.subarray(0,zo);return Xr.sign(t instanceof Uint8Array?t:t.subarray(),e)}function Ju(r,t,e){return Xr.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}function Qu(r,t){let e=new Uint8Array(Le);for(let n=0;n<zo;n++)e[n]=r[n],e[zo+n]=t[n];return e}var Ot={get(r=globalThis){let t=r.crypto;if(t==null||t.subtle==null)throw Object.assign(new Error("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"),{code:"ERR_MISSING_WEB_CRYPTO"});return t}};var Wa={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function tf(r){let t=r?.algorithm??"AES-GCM",e=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=Ot.get();e*=8;async function c(f,p){let y=a.getRandomValues(new Uint8Array(s)),m=a.getRandomValues(new Uint8Array(n)),h={name:t,iv:m};typeof p=="string"&&(p=J(p));let d;if(p.length===0){d=await a.subtle.importKey("jwk",Wa,{name:"AES-GCM"},!0,["encrypt"]);try{let E={name:"PBKDF2",salt:y,iterations:i,hash:{name:o}},w=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);d=await a.subtle.deriveKey(E,w,{name:t,length:e},!0,["encrypt"])}catch{d=await a.subtle.importKey("jwk",Wa,{name:"AES-GCM"},!0,["encrypt"])}}else{let E={name:"PBKDF2",salt:y,iterations:i,hash:{name:o}},w=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);d=await a.subtle.deriveKey(E,w,{name:t,length:e},!0,["encrypt"])}let b=await a.subtle.encrypt(h,d,f);return yt([y,h.iv,new Uint8Array(b)])}async function l(f,p){let y=f.subarray(0,s),m=f.subarray(s,s+n),h=f.subarray(s+n),d={name:t,iv:m};typeof p=="string"&&(p=J(p));let b;if(p.length===0)try{let w={name:"PBKDF2",salt:y,iterations:i,hash:{name:o}},S=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);b=await a.subtle.deriveKey(w,S,{name:t,length:e},!0,["decrypt"])}catch{b=await a.subtle.importKey("jwk",Wa,{name:"AES-GCM"},!0,["decrypt"])}else{let w={name:"PBKDF2",salt:y,iterations:i,hash:{name:o}},S=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);b=await a.subtle.deriveKey(w,S,{name:t,length:e},!0,["decrypt"])}let E=await a.subtle.decrypt(d,b,h);return new Uint8Array(E)}return{encrypt:c,decrypt:l}}async function Qr(r,t){let n=await tf().encrypt(r,t);return li.encode(n)}var ut;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(ut||(ut={}));var Ga;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(Ga||(Ga={}));(function(r){r.codec=()=>gr(Ga)})(ut||(ut={}));var ye;(function(r){let t;r.codec=()=>(t==null&&(t=ie((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ut.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:o.Type=ut.codec().decode(e);break;case 2:o.Data=e.bytes();break;default:e.skipType(i&7);break}}return o})),t),r.encode=e=>se(e,r.codec()),r.decode=e=>oe(e,r.codec())})(ye||(ye={}));var we;(function(r){let t;r.codec=()=>(t==null&&(t=ie((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ut.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:o.Type=ut.codec().decode(e);break;case 2:o.Data=e.bytes();break;default:e.skipType(i&7);break}}return o})),t),r.encode=e=>se(e,r.codec()),r.decode=e=>oe(e,r.codec())})(we||(we={}));var Ln=class{_key;constructor(t){this._key=tn(t,Jr)}verify(t,e){return Ju(this._key,e,t)}marshal(){return this._key}get bytes(){return ye.encode({Type:ut.Ed25519,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}hash(){let t=Ct.digest(this.bytes);return Zt(t)?t.then(({bytes:e})=>e):t.bytes}},Sr=class{_key;_publicKey;constructor(t,e){this._key=tn(t,Le),this._publicKey=tn(e,Jr)}sign(t){return Xu(this._key,t)}get public(){return new Ln(this._publicKey)}marshal(){return this._key}get bytes(){return we.encode({Type:ut.Ed25519,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}async hash(){let t=Ct.digest(this.bytes),e;return Zt(t)?{bytes:e}=await t:e=t.bytes,e}async id(){let t=Be.digest(this.public.bytes);return dt.encode(t.bytes).substring(1)}async export(t,e="libp2p-key"){if(e==="libp2p-key")return Qr(this.bytes,t);throw new D(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Ym(r){if(r.length>Le){r=tn(r,Le+Jr);let n=r.subarray(0,Le),o=r.subarray(Le,r.length);return new Sr(n,o)}r=tn(r,Le);let t=r.subarray(0,Le),e=r.subarray(Jr);return new Sr(t,e)}function Zm(r){return r=tn(r,Jr),new Ln(r)}async function Xm(){let{privateKey:r,publicKey:t}=Yu();return new Sr(r,t)}async function ef(r){let{privateKey:t,publicKey:e}=Zu(r);return new Sr(t,e)}function tn(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new D(`Key must be a Uint8Array of length ${t}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}var rc={};xt(rc,{MAX_RSA_KEY_SIZE:()=>Wn,RsaPrivateKey:()=>sn,RsaPublicKey:()=>$n,fromJwk:()=>Sg,generateKeyPair:()=>Bg,unmarshalRsaPrivateKey:()=>tc,unmarshalRsaPublicKey:()=>Ag});function Br(r){if(isNaN(r)||r<=0)throw new D("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Er(r)}var or={};xt(or,{exportToPem:()=>wg,importFromPem:()=>bg,jwkToPkcs1:()=>pg,jwkToPkix:()=>gg,pkcs1ToJwk:()=>dg,pkixToJwk:()=>mg});var Zo=class extends jr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,xr(t);let n=ce(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(t){return qr(this),this.iHash.update(t),this}digestInto(t){qr(this),Gr(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},tr=(r,t,e)=>new Zo(r,t).update(e).digest();tr.create=(r,t)=>new Zo(r,t);function Jm(r,t,e,n){xr(r);let o=Ru({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(Ye(s),Ye(i),Ye(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=ce(t),l=ce(e),u=new Uint8Array(i),f=tr.create(r,c),p=f._cloneInto().update(l);return{c:s,dkLen:i,asyncTick:a,DK:u,PRF:f,PRFSalt:p}}function Qm(r,t,e,n,o){return r.destroy(),t.destroy(),n&&n.destroy(),o.fill(0),e}async function ja(r,t,e,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:l}=Jm(r,t,e,n),u,f=new Uint8Array(4),p=zr(f),y=new Uint8Array(c.outputLen);for(let m=1,h=0;h<s;m++,h+=c.outputLen){let d=a.subarray(h,h+c.outputLen);p.setInt32(0,m,!1),(u=l._cloneInto(u)).update(f).digestInto(y),d.set(y.subarray(0,d.length)),await ku(o-1,i,()=>{c._cloneInto(u).update(y).digestInto(y);for(let b=0;b<d.length;b++)d[b]^=y[b]})}return Qm(c,l,a,u,y)}var X=$c(rf());function Ir(r,t){let e=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)e+=r[r.length-1-n]*Math.pow(2,t*n);return e}function er(r,t,e=-1){let n=e,o=r,s=0,i=Math.pow(2,t);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*t);l[s-u-1]=Math.floor(o/f),o-=l[s-u-1]*f}return c}i*=Math.pow(2,t)}return new ArrayBuffer(0)}function Qo(...r){let t=0,e=0;for(let s of r)t+=s.length;let n=new ArrayBuffer(t),o=new Uint8Array(n);for(let s of r)o.set(s,e),e+=s.length;return o}function Ya(){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 t=new ArrayBuffer(this.valueHex.byteLength),e=new Uint8Array(t);for(let a=0;a<this.valueHex.byteLength;a++)e[a]=0;e[0]=r[0]&128;let n=Ir(e,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,Ir(s,8)-n}function nf(r){let t=r<0?r*-1:r,e=128;for(let n=1;n<8;n++){if(t<=e){if(r<0){let i=e-t,a=er(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=er(t,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}e*=Math.pow(2,8)}return new ArrayBuffer(0)}function of(r,t){if(r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<e.length;o++)if(e[o]!==n[o])return!1;return!0}function Ft(r,t){let e=r.toString(10);if(t<e.length)return"";let n=t-e.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(e)}var jv=Math.log(2);function ts(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Za(r){let t=0,e=0;for(let o=0;o<r.length;o++){let s=r[o];t+=s.byteLength}let n=new Uint8Array(t);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),e),e+=s.byteLength}return n.buffer}function He(r,t,e,n){return t instanceof Uint8Array?t.byteLength?e<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):t.byteLength-e-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 Un=class{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return Za(this.items)}},Dn=[new Uint8Array([1])],sf="0123456789";var nn="",he=new ArrayBuffer(0),Xa=new Uint8Array(0),Pn="EndOfContent",cf="OCTET STRING",lf="BIT STRING";function Me(r){var t;return t=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?X.BufferSourceConverter.toUint8Array(s.valueHex):Xa}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(!He(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",he)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:X.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var Ue=class{constructor({blockLength:t=0,error:e=nn,warnings:n=[],valueBeforeDecode:o=Xa}={}){this.blockLength=t,this.error=e,this.warnings=n,this.valueBeforeDecodeView=X.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(t){this.valueBeforeDecodeView=new Uint8Array(t)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:X.Convert.ToHex(this.valueBeforeDecodeView)}}};Ue.NAME="baseBlock";var Pt=class extends Ue{fromBER(t,e,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(t,e){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Pt.NAME="valueBlock";var es=class extends Me(Ue){constructor({idBlock:t={}}={}){var e,n,o,s;super(),t?(this.isHexOnly=(e=t.isHexOnly)!==null&&e!==void 0?e:!1,this.valueHexView=t.valueHex?X.BufferSourceConverter.toUint8Array(t.valueHex):Xa,this.tagClass=(n=t.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=t.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=t.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(t=!1){let e=0;switch(this.tagClass){case 1:e|=0;break;case 2:e|=64;break;case 3:e|=128;break;case 4:e|=192;break;default:return this.error="Unknown tag class",he}if(this.isConstructed&&(e|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!t){let s=this.tagNumber;s&=31,e|=s,o[0]=e}return o.buffer}if(!this.isHexOnly){let o=er(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=e|31,!t){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]=e|31,!t){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(t,e,n){let o=X.BufferSourceConverter.toUint8Array(t);if(!He(this,o,e,n))return-1;let s=o.subarray(e,e+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 p=new Uint8Array(u);for(let y=0;y<l.length;y++)p[y]=l[y];l=this.valueHexView=new Uint8Array(u)}}this.blockLength=c+1,l[c-1]=s[c]&127;let f=new Uint8Array(c);for(let p=0;p<c;p++)f[p]=l[p];l=this.valueHexView=new Uint8Array(c),l.set(f),this.blockLength<=9?this.tagNumber=Ir(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 e+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};es.NAME="identificationBlock";var rs=class extends Ue{constructor({lenBlock:t={}}={}){var e,n,o;super(),this.isIndefiniteForm=(e=t.isIndefiniteForm)!==null&&e!==void 0?e:!1,this.longFormUsed=(n=t.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=t.length)!==null&&o!==void 0?o:0}fromBER(t,e,n){let o=X.BufferSourceConverter.toUint8Array(t);if(!He(this,o,e,n))return-1;let s=o.subarray(e,e+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,e+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,e+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=e+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Ir(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,e+this.blockLength}toBER(t=!1){let e,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=128),e;if(this.longFormUsed){let o=er(this.length,8);if(o.byteLength>127)return this.error="Too big length",he;if(e=new ArrayBuffer(o.byteLength+1),t)return e;let s=new Uint8Array(o);n=new Uint8Array(e),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return e}return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=this.length),e}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};rs.NAME="lengthBlock";var H={},Tt=class extends Ue{constructor({name:t=nn,optional:e=!1,primitiveSchema:n,...o}={},s){super(o),this.name=t,this.optional=e,n&&(this.primitiveSchema=n),this.idBlock=new es(o),this.lenBlock=new rs(o),this.valueBlock=s?new s(o):new Pt(o)}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,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(t,e){let n=e||new Un;e||uf(this);let o=this.idBlock.toBER(t);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(t,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(t);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(t);n.write(i),n.write(s)}return e?he:n.final()}toJSON(){let t={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(t="ascii"){return t==="ascii"?this.onAsciiEncoding():X.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${X.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(t){if(this===t)return!0;if(!(t instanceof this.constructor))return!1;let e=this.toBER(),n=t.toBER();return of(e,n)}};Tt.NAME="BaseBlock";function uf(r){if(r instanceof H.Constructed)for(let t of r.valueBlock.value)uf(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ns=class extends Tt{constructor({value:t=nn,...e}={},n){super(e,n),t&&this.fromString(t)}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,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}'`}};ns.NAME="BaseStringBlock";var os=class extends Me(Pt){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};os.NAME="PrimitiveValueBlock";var ff,ss=class extends Tt{constructor(t={}){super(t,os),this.idBlock.isConstructed=!1}};ff=ss;H.Primitive=ff;ss.NAME="PRIMITIVE";function cg(r,t){if(r instanceof t)return r;let e=new t;return e.idBlock=r.idBlock,e.lenBlock=r.lenBlock,e.warnings=r.warnings,e.valueBeforeDecodeView=r.valueBeforeDecodeView,e}function Hs(r,t=0,e=r.length){let n=t,o=new Tt({},Pt),s=new Ue;if(!He(s,r,t,e))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(t,t+e).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,t,e);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(t=a,e-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,t,e),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(t=a,e-=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=Tt;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=H.EndOfContent;break;case 1:c=H.Boolean;break;case 2:c=H.Integer;break;case 3:c=H.BitString;break;case 4:c=H.OctetString;break;case 5:c=H.Null;break;case 6:c=H.ObjectIdentifier;break;case 10:c=H.Enumerated;break;case 12:c=H.Utf8String;break;case 13:c=H.RelativeObjectIdentifier;break;case 14:c=H.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=H.Sequence;break;case 17:c=H.Set;break;case 18:c=H.NumericString;break;case 19:c=H.PrintableString;break;case 20:c=H.TeletexString;break;case 21:c=H.VideotexString;break;case 22:c=H.IA5String;break;case 23:c=H.UTCTime;break;case 24:c=H.GeneralizedTime;break;case 25:c=H.GraphicString;break;case 26:c=H.VisibleString;break;case 27:c=H.GeneralString;break;case 28:c=H.UniversalString;break;case 29:c=H.CharacterString;break;case 30:c=H.BmpString;break;case 31:c=H.DATE;break;case 32:c=H.TimeOfDay;break;case 33:c=H.DateTime;break;case 34:c=H.Duration;break;default:{let l=o.idBlock.isConstructed?new H.Constructed:new H.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?H.Constructed:H.Primitive}return o=cg(o,c),a=o.fromBER(r,t,o.lenBlock.isIndefiniteForm?e:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function on(r){if(!r.byteLength){let t=new Tt({},Pt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return Hs(X.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function lg(r,t){return r?1:t}var be=class extends Pt{constructor({value:t=[],isIndefiniteForm:e=!1,...n}={}){super(n),this.value=t,this.isIndefiniteForm=e}fromBER(t,e,n){let o=X.BufferSourceConverter.toUint8Array(t);if(!He(this,o,e,n))return-1;if(this.valueBeforeDecodeView=o.subarray(e,e+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),e;let s=e;for(;lg(this.isIndefiniteForm,n)>0;){let i=Hs(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===Pn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Pn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(t,e){let n=e||new Un;for(let o=0;o<this.value.length;o++)this.value[o].toBER(t,n);return e?he:n.final()}toJSON(){let t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let e of this.value)t.value.push(e.toJSON());return t}};be.NAME="ConstructedValueBlock";var hf,rr=class extends Tt{constructor(t={}){super(t,be),this.idBlock.isConstructed=!0}fromBER(t,e,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(t,e,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 t=[];for(let n of this.valueBlock.value)t.push(n.toString("ascii").split(`
|
2
|
+
"use strict";var Libp2PWebrtc=(()=>{var rd=Object.create;var Xn=Object.defineProperty;var nd=Object.getOwnPropertyDescriptor;var od=Object.getOwnPropertyNames;var sd=Object.getPrototypeOf,id=Object.prototype.hasOwnProperty;var Fc=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),xt=(r,t)=>{for(var e in t)Xn(r,e,{get:t[e],enumerable:!0})},Kc=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of od(t))!id.call(r,o)&&o!==e&&Xn(r,o,{get:()=>t[o],enumerable:!(n=nd(t,o))||n.enumerable});return r};var $c=(r,t,e)=>(e=r!=null?rd(sd(r)):{},Kc(t||!r||!r.__esModule?Xn(e,"default",{value:r,enumerable:!0}):e,r)),ad=r=>Kc(Xn({},"__esModule",{value:!0}),r);var ru=Fc((T1,eu)=>{"use strict";function tu(r,t){for(let e in t)Object.defineProperty(r,e,{value:t[e],enumerable:!0,configurable:!0});return r}function f0(r,t,e){if(!r||typeof r=="string")throw new TypeError("Please pass an Error to err-code");e||(e={}),typeof t=="object"&&(e=t,t=""),t&&(e.code=t);try{return tu(r,e)}catch{e.message=r.message,e.stack=r.stack;let o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(r)),tu(new o,e)}}eu.exports=f0});var rf=Fc(en=>{"use strict";var tg="[object ArrayBuffer]",De=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===tg}static toArrayBuffer(t){return this.isArrayBuffer(t)?t:t.byteLength===t.buffer.byteLength||t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:this.toUint8Array(t.buffer).slice(t.byteOffset,t.byteOffset+t.byteLength).buffer}static toUint8Array(t){return this.toView(t,Uint8Array)}static toView(t,e){if(t.constructor===e)return t;if(this.isArrayBuffer(t))return new e(t);if(this.isArrayBufferView(t))return new e(t.buffer,t.byteOffset,t.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(t){return this.isArrayBufferView(t)||this.isArrayBuffer(t)}static isArrayBufferView(t){return ArrayBuffer.isView(t)||t&&this.isArrayBuffer(t.buffer)}static isEqual(t,e){let n=r.toUint8Array(t),o=r.toUint8Array(e);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(...t){let e;Array.isArray(t[0])&&!(t[1]instanceof Function)||Array.isArray(t[0])&&t[1]instanceof Function?e=t[0]:t[t.length-1]instanceof Function?e=t.slice(0,t.length-1):e=t;let n=0;for(let i of e)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of e){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return t[t.length-1]instanceof Function?this.toView(o,t[t.length-1]):o.buffer}},za="string",eg=/^[0-9a-f]+$/i,rg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,ng=/^[a-zA-Z0-9-_]+$/,Xo=class{static fromString(t){let e=unescape(encodeURIComponent(t)),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n.buffer}static toString(t){let e=De.toUint8Array(t),n="";for(let s=0;s<e.length;s++)n+=String.fromCharCode(e[s]);return decodeURIComponent(escape(n))}},Jt=class{static toString(t,e=!1){let n=De.toArrayBuffer(t),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,e);s+=String.fromCharCode(a)}return s}static fromString(t,e=!1){let n=new ArrayBuffer(t.length*2),o=new DataView(n);for(let s=0;s<t.length;s++)o.setUint16(s*2,t.charCodeAt(s),e);return n}},Jo=class r{static isHex(t){return typeof t===za&&eg.test(t)}static isBase64(t){return typeof t===za&&rg.test(t)}static isBase64Url(t){return typeof t===za&&ng.test(t)}static ToString(t,e="utf8"){let n=De.toUint8Array(t);switch(e.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 Jt.toString(n,!0);case"utf16":case"utf16be":return Jt.toString(n);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromString(t,e="utf8"){if(!t)return new ArrayBuffer(0);switch(e.toLowerCase()){case"utf8":return this.FromUtf8String(t);case"binary":return this.FromBinary(t);case"hex":return this.FromHex(t);case"base64":return this.FromBase64(t);case"base64url":return this.FromBase64Url(t);case"utf16le":return Jt.fromString(t,!0);case"utf16":case"utf16be":return Jt.fromString(t);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToBase64(t){let e=De.toUint8Array(t);if(typeof btoa<"u"){let n=this.ToString(e,"binary");return btoa(n)}else return Buffer.from(e).toString("base64")}static FromBase64(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64(e))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(e)):new Uint8Array(Buffer.from(e,"base64")).buffer}static FromBase64Url(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64Url(e))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(e.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(t){return this.ToBase64(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.FromBinary(t);case"utf8":return Xo.fromString(t);case"utf16":case"utf16be":return Jt.fromString(t);case"utf16le":case"usc2":return Jt.fromString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.ToBinary(t);case"utf8":return Xo.toString(t);case"utf16":case"utf16be":return Jt.toString(t);case"utf16le":case"usc2":return Jt.toString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromBinary(t){let e=t.length,n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);return n.buffer}static ToBinary(t){let e=De.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=De.toUint8Array(t),n="",o=e.length;for(let s=0;s<o;s++){let i=e[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isHex(e))throw new TypeError("Argument 'hexString' is not HEX encoded");e.length%2&&(e=`0${e}`);let n=new Uint8Array(e.length/2);for(let o=0;o<e.length;o=o+2){let s=e.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(t,e=!1){return Jt.toString(t,e)}static FromUtf16String(t,e=!1){return Jt.fromString(t,e)}static Base64Padding(t){let e=4-t.length%4;if(e<4)for(let n=0;n<e;n++)t+="=";return t}static formatString(t){return t?.replace(/[\n\r\t ]/g,"")||""}};Jo.DEFAULT_UTF8_ENCODING="utf8";function og(r,...t){let e=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)e[s]=o[s]}return e}function sg(...r){let t=r.map(o=>o.byteLength).reduce((o,s)=>o+s),e=new Uint8Array(t),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)e[n++]=s}),e.buffer}function ig(r,t){if(!(r&&t)||r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)if(e[o]!==n[o])return!1;return!0}en.BufferSourceConverter=De;en.Convert=Jo;en.assign=og;en.combine=sg;en.isEqual=ig});var my={};xt(my,{webRTC:()=>py,webRTCDirect:()=>dy});var Zs=Symbol.for("@libp2p/peer-id");var Jn=Symbol.for("@libp2p/transport");var Wc;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Wc||(Wc={}));var D=class extends Error{code;props;constructor(t,e,n){super(t),this.code=e,this.name=n?.name??"CodeError",this.props=n??{}}};var Qn=(r,...t)=>{try{[...t]}catch{}};var to=class extends EventTarget{#t=new Map;constructor(){super(),Qn(1/0,this)}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new cd(t,e))}},Xs=class extends Event{detail;constructor(t,e){super(t,e),this.detail=e?.detail}},cd=globalThis.CustomEvent??Xs;var Rr=Symbol.for("@libp2p/service-capabilities"),Gc=Symbol.for("@libp2p/service-dependencies");var ri={};xt(ri,{base58btc:()=>dt,base58flickr:()=>pd});var qy=new Uint8Array(0);function qc(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Ae(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 zc(r){return new TextDecoder().decode(r)}function ld(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var h=0,d=0,b=0,E=m.length;b!==E&&m[b]===0;)b++,h++;for(var w=(E-b)*u+1>>>0,S=new Uint8Array(w);b!==E;){for(var x=m[b],B=0,I=w-1;(x!==0||B<d)&&I!==-1;I--,B++)x+=256*S[I]>>>0,S[I]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");d=B,b++}for(var _=w-d;_!==w&&S[_]===0;)_++;for(var N=c.repeat(h);_<w;++_)N+=r.charAt(S[_]);return N}function p(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var h=0;if(m[h]!==" "){for(var d=0,b=0;m[h]===c;)d++,h++;for(var E=(m.length-h)*l+1>>>0,w=new Uint8Array(E);m[h];){var S=e[m.charCodeAt(h)];if(S===255)return;for(var x=0,B=E-1;(S!==0||x<b)&&B!==-1;B--,x++)S+=a*w[B]>>>0,w[B]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");b=x,h++}if(m[h]!==" "){for(var I=E-b;I!==E&&w[I]===0;)I++;for(var _=new Uint8Array(d+(E-I)),N=d;I!==E;)_[N++]=w[I++];return _}}}function y(m){var h=p(m);if(h)return h;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:p,decode:y}}var ud=ld,fd=ud,Zc=fd;var Js=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Qs=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Xc(this,t)}},ti=class{decoders;constructor(t){this.decoders=t}or(t){return Xc(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Xc(r,t){return new ti({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ei=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new Js(t,e,n),this.decoder=new Qs(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Tr({name:r,prefix:t,encode:e,decode:n}){return new ei(r,t,e,n)}function Ke({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Zc(e,r);return Tr({prefix:t,name:r,encode:n,decode:s=>Ae(o(s))})}function hd(r,t,e,n){let o={};for(let u=0;u<t.length;++u)o[t[u]]=u;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*e/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<<e|f,a+=e,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function dd(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;s.length*e&7;)s+="=";return s}function ft({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Tr({prefix:t,name:r,encode(o){return dd(o,n,e)},decode(o){return hd(o,n,e,r)}})}var dt=Ke({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),pd=Ke({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ni={};xt(ni,{base10:()=>md});var md=Ke({prefix:"9",name:"base10",alphabet:"0123456789"});var oi={};xt(oi,{base16:()=>gd,base16upper:()=>yd});var gd=ft({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),yd=ft({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var si={};xt(si,{base2:()=>wd});var wd=ft({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ii={};xt(ii,{base256emoji:()=>Ad});var Jc=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}"),bd=Jc.reduce((r,t,e)=>(r[e]=t,r),[]),xd=Jc.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function Ed(r){return r.reduce((t,e)=>(t+=bd[e],t),"")}function vd(r){let t=[];for(let e of r){let n=xd[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var Ad=Tr({prefix:"\u{1F680}",name:"base256emoji",encode:Ed,decode:vd});var ai={};xt(ai,{base32:()=>Se,base32hex:()=>_d,base32hexpad:()=>Cd,base32hexpadupper:()=>Rd,base32hexupper:()=>kd,base32pad:()=>Bd,base32padupper:()=>Id,base32upper:()=>Sd,base32z:()=>Td});var Se=ft({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Sd=ft({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Bd=ft({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Id=ft({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),_d=ft({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),kd=ft({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Cd=ft({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Rd=ft({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Td=ft({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ci={};xt(ci,{base36:()=>Nd,base36upper:()=>Ld});var Nd=Ke({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ld=Ke({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var fi={};xt(fi,{base64:()=>li,base64pad:()=>Dd,base64url:()=>ui,base64urlpad:()=>Ud});var li=ft({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Dd=ft({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ui=ft({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ud=ft({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var hi={};xt(hi,{base8:()=>Pd});var Pd=ft({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var di={};xt(di,{identity:()=>Od});var Od=Tr({prefix:"\0",name:"identity",encode:r=>zc(r),decode:r=>jc(r)});var cw=new TextEncoder,lw=new TextDecoder;var gi={};xt(gi,{identity:()=>Be});var te={};xt(te,{Digest:()=>cr,create:()=>$t,decode:()=>$e,equals:()=>mi});var Vd=el,Qc=128,Fd=127,Kd=~Fd,$d=Math.pow(2,31);function el(r,t,e){t=t||[],e=e||0;for(var n=e;r>=$d;)t[e++]=r&255|Qc,r/=128;for(;r&Kd;)t[e++]=r&255|Qc,r>>>=7;return t[e]=r|0,el.bytes=e-n+1,t}var Wd=pi,Gd=128,tl=127;function pi(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw pi.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&tl)<<o:(i&tl)*Math.pow(2,o),o+=7}while(i>=Gd);return pi.bytes=s-n,e}var qd=Math.pow(2,7),jd=Math.pow(2,14),zd=Math.pow(2,21),Yd=Math.pow(2,28),Zd=Math.pow(2,35),Xd=Math.pow(2,42),Jd=Math.pow(2,49),Qd=Math.pow(2,56),tp=Math.pow(2,63),ep=function(r){return r<qd?1:r<jd?2:r<zd?3:r<Yd?4:r<Zd?5:r<Xd?6:r<Jd?7:r<Qd?8:r<tp?9:10},rp={encode:Vd,decode:Wd,encodingLength:ep},np=rp,dn=np;function pn(r,t=0){return[dn.decode(r,t),dn.decode.bytes]}function Nr(r,t,e=0){return dn.encode(r,t,e),t}function Lr(r){return dn.encodingLength(r)}function $t(r,t){let e=t.byteLength,n=Lr(r),o=n+Lr(e),s=new Uint8Array(o+e);return Nr(r,s,0),Nr(e,s,n),s.set(t,o),new cr(r,e,t,s)}function $e(r){let t=Ae(r),[e,n]=pn(t),[o,s]=pn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new cr(e,o,i,t)}function mi(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&qc(r.bytes,e.bytes)}}var cr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};var rl=0,op="identity",nl=Ae;function sp(r){return $t(rl,nl(r))}var Be={code:rl,name:op,encode:nl,digest:sp};var bi={};xt(bi,{sha256:()=>Ct,sha512:()=>ip});function wi({name:r,code:t,encode:e}){return new yi(r,t,e)}var yi=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?$t(this.code,e):e.then(n=>$t(this.code,n))}else throw Error("Unknown type, must be binary type")}};function sl(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Ct=wi({name:"sha2-256",code:18,encode:sl("SHA-256")}),ip=wi({name:"sha2-512",code:19,encode:sl("SHA-512")});function il(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return cp(e,xi(r),t??dt.encoder);default:return lp(e,xi(r),t??Se.encoder)}}var al=new WeakMap;function xi(r){let t=al.get(r);if(t==null){let e=new Map;return al.set(r,e),e}return t}var zt=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==mn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==up)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=$t(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&mi(t.multihash,n.multihash)}toString(t){return il(this,t)}toJSON(){return{"/":il(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??cl(n,o,s.bytes))}else if(e[fp]===!0){let{version:n,multihash:o,code:s}=e,i=$e(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==mn)throw new Error(`Version 0 CID must use dag-pb (code: ${mn}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=cl(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,mn,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Ae(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new cr(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,p]=pn(t.subarray(e));return e+=p,f},o=n(),s=mn;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=ap(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return xi(s).set(n,t),s}};function ap(r,t){switch(r[0]){case"Q":{let e=t??dt;return[dt.prefix,e.decode(`${dt.prefix}${r}`)]}case dt.prefix:{let e=t??dt;return[dt.prefix,e.decode(r)]}case Se.prefix:{let e=t??Se;return[Se.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function cp(r,t,e){let{prefix:n}=e;if(n!==dt.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function lp(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var mn=112,up=18;function cl(r,t,e){let n=Lr(r),o=n+Lr(t),s=new Uint8Array(o+e.byteLength);return Nr(r,s,0),Nr(t,s,n),s.set(e,o),s}var fp=Symbol.for("@ipld/js-cid/CID");var pe={...di,...si,...hi,...ni,...oi,...ai,...ci,...ri,...fi,...ii},Rw={...bi,...gi};function Et(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function vt(r=0){return new Uint8Array(r)}function At(r=0){return new Uint8Array(r)}function ul(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var ll=ul("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ei=ul("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=At(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),hp={utf8:ll,"utf-8":ll,hex:pe.base16,latin1:Ei,ascii:Ei,binary:Ei,...pe},ro=hp;function J(r,t="utf8"){let e=ro[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function G(r,t="utf8"){let e=ro[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var hl=Symbol.for("nodejs.util.inspect.custom"),fl=Object.values(pe).map(r=>r.decoder).reduce((r,t)=>r.or(t),pe.identity.decoder),dl=114,Si=36,Bi=37,gn=class{type;multihash;privateKey;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,this.privateKey=t.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Zs]=!0;toString(){return this.string==null&&(this.string=dt.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return zt.createV1(dl,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Et(this.multihash.bytes,t);if(typeof t=="string")return lr(t).equals(this);if(t?.multihash?.bytes!=null)return Et(this.multihash.bytes,t.multihash.bytes);throw new Error("not valid Id")}[hl](){return`PeerId(${this.toString()})`}},Dr=class extends gn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Ur=class extends gn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.multihash.digest}},Pr=class extends gn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.multihash.digest}},vi=2336,Ai=class{type="url";multihash;privateKey;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Be.digest(J(this.url))}[hl](){return`PeerId(${this.url})`}[Zs]=!0;toString(){return this.toCID().toString()}toCID(){return zt.createV1(vi,this.multihash)}toBytes(){return this.toCID().bytes}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=G(t)),t.toString()===this.toString())}};function lr(r,t){if(t=t??fl,r.charAt(0)==="1"||r.charAt(0)==="Q"){let e=$e(dt.decode(`z${r}`));return r.startsWith("12D")?new Ur({multihash:e}):r.startsWith("16U")?new Pr({multihash:e}):new Dr({multihash:e})}return dp(fl.decode(r))}function dp(r){try{let t=$e(r);if(t.code===Be.code){if(t.digest.length===Si)return new Ur({multihash:t});if(t.digest.length===Bi)return new Pr({multihash:t})}if(t.code===Ct.code)return new Dr({multihash:t})}catch{return pp(zt.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function pp(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==dl&&r.code!==vi)throw new Error("Supplied PeerID CID is invalid");if(r.code===vi){let e=G(r.multihash.digest);return new Ai(new URL(e))}let t=r.multihash;if(t.code===Ct.code)return new Dr({multihash:r.multihash});if(t.code===Be.code){if(t.digest.length===Si)return new Ur({multihash:r.multihash});if(t.digest.length===Bi)return new Pr({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function Ii(r,t){return r.length===Si?new Ur({multihash:$t(Be.code,r),privateKey:t}):r.length===Bi?new Pr({multihash:$t(Be.code,r),privateKey:t}):new Dr({multihash:await Ct.digest(r),publicKey:r,privateKey:t})}var gp=Math.pow(2,7),yp=Math.pow(2,14),wp=Math.pow(2,21),_i=Math.pow(2,28),ki=Math.pow(2,35),Ci=Math.pow(2,42),Ri=Math.pow(2,49),et=128,Dt=127;function gt(r){if(r<gp)return 1;if(r<yp)return 2;if(r<wp)return 3;if(r<_i)return 4;if(r<ki)return 5;if(r<Ci)return 6;if(r<Ri)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ti(r,t,e=0){switch(gt(r)){case 8:t[e++]=r&255|et,r/=128;case 7:t[e++]=r&255|et,r/=128;case 6:t[e++]=r&255|et,r/=128;case 5:t[e++]=r&255|et,r/=128;case 4:t[e++]=r&255|et,r>>>=7;case 3:t[e++]=r&255|et,r>>>=7;case 2:t[e++]=r&255|et,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function bp(r,t,e=0){switch(gt(r)){case 8:t.set(e++,r&255|et),r/=128;case 7:t.set(e++,r&255|et),r/=128;case 6:t.set(e++,r&255|et),r/=128;case 5:t.set(e++,r&255|et),r/=128;case 4:t.set(e++,r&255|et),r>>>=7;case 3:t.set(e++,r&255|et),r>>>=7;case 2:t.set(e++,r&255|et),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Ni(r,t){let e=r[t],n=0;if(n+=e&Dt,e<et||(e=r[t+1],n+=(e&Dt)<<7,e<et)||(e=r[t+2],n+=(e&Dt)<<14,e<et)||(e=r[t+3],n+=(e&Dt)<<21,e<et)||(e=r[t+4],n+=(e&Dt)*_i,e<et)||(e=r[t+5],n+=(e&Dt)*ki,e<et)||(e=r[t+6],n+=(e&Dt)*Ci,e<et)||(e=r[t+7],n+=(e&Dt)*Ri,e<et))return n;throw new RangeError("Could not decode varint")}function xp(r,t){let e=r.get(t),n=0;if(n+=e&Dt,e<et||(e=r.get(t+1),n+=(e&Dt)<<7,e<et)||(e=r.get(t+2),n+=(e&Dt)<<14,e<et)||(e=r.get(t+3),n+=(e&Dt)<<21,e<et)||(e=r.get(t+4),n+=(e&Dt)*_i,e<et)||(e=r.get(t+5),n+=(e&Dt)*ki,e<et)||(e=r.get(t+6),n+=(e&Dt)*Ci,e<et)||(e=r.get(t+7),n+=(e&Dt)*Ri,e<et))return n;throw new RangeError("Could not decode varint")}function me(r,t,e=0){return t==null&&(t=At(gt(r))),t instanceof Uint8Array?Ti(r,t,e):bp(r,t,e)}function ee(r,t=0){return r instanceof Uint8Array?Ni(r,t):xp(r,t)}function yt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=At(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var no=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let p=Number.parseInt(f,t);if(!Number.isNaN(p))return p});if(u===void 0)break;if(s*=t,s+=u,s>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var pl=45,vp=15,Or=new no;function Li(r){if(!(r.length>vp))return Or.new(r).parseWith(()=>Or.readIPv4Addr())}function Di(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>pl))return Or.new(r).parseWith(()=>Or.readIPv6Addr())}function oo(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>pl))return Or.new(r).parseWith(()=>Or.readIPAddr())}var ub=parseInt("0xFFFF",16),fb=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function so(r){return!!Li(r)}function io(r){return!!Di(r)}function ao(r){return!!oo(r)}var yl=so,_p=io,Ui=function(r){let t=0;if(r=r.toString().trim(),yl(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(_p(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=yl(e[n]),i;s&&(i=Ui(e[n]),e[n]=G(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,G(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let s=parseInt(e[n],16);o[t++]=s>>8&255,o[t++]=s&255}return o}throw new Error("invalid ip address")},wl=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Hr={},Pi={},Cp=[[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"]];Cp.forEach(r=>{let t=Rp(...r);Pi[t.code]=t,Hr[t.name]=t});function Rp(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function rt(r){if(typeof r=="number"){if(Pi[r]!=null)return Pi[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Hr[r]!=null)return Hr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var zb=rt("ip4"),Yb=rt("ip6"),Zb=rt("ipcidr");function Vi(r,t){switch(rt(r).code){case 4:case 41:return Np(t);case 42:return Mi(t);case 6:case 273:case 33:case 132:return El(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Mi(t);case 421:return Pp(t);case 444:return xl(t);case 445:return xl(t);case 466:return Up(t);case 481:return globalThis.encodeURIComponent(Mi(t));default:return G(t,"base16")}}function Fi(r,t){switch(rt(r).code){case 4:return bl(t);case 41:return bl(t);case 42:return Hi(t);case 6:case 273:case 33:case 132:return Ki(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Hi(t);case 421:return Lp(t);case 444:return Op(t);case 445:return Hp(t);case 466:return Dp(t);case 481:return Hi(globalThis.decodeURIComponent(t));default:return J(t,"base16")}}var Oi=Object.values(pe).map(r=>r.decoder),Tp=function(){let r=Oi[0].or(Oi[1]);return Oi.slice(2).forEach(t=>r=r.or(t)),r}();function bl(r){if(!ao(r))throw new Error("invalid ip address");return Ui(r)}function Np(r){let t=wl(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!ao(t))throw new Error("invalid ip address");return t}function Ki(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function El(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Hi(r){let t=J(r),e=Uint8Array.from(me(t.length));return yt([e,t],e.length+t.length)}function Mi(r){let t=ee(r);if(r=r.slice(gt(t)),r.length!==t)throw new Error("inconsistent lengths");return G(r)}function Lp(r){let t;r[0]==="Q"||r[0]==="1"?t=$e(dt.decode(`z${r}`)).bytes:t=zt.parse(r).multihash.bytes;let e=Uint8Array.from(me(t.length));return yt([e,t],e.length+t.length)}function Dp(r){let t=Tp.decode(r),e=Uint8Array.from(me(t.length));return yt([e,t],e.length+t.length)}function Up(r){let t=ee(r),e=r.slice(gt(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+G(e,"base64url")}function Pp(r){let t=ee(r),e=r.slice(gt(t));if(e.length!==t)throw new Error("inconsistent lengths");return G(e,"base58btc")}function Op(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=Se.decode("b"+t[0]),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ki(n);return yt([e,o],e.length+o.length)}function Hp(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=Se.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=Ki(n);return yt([e,o],e.length+o.length)}function xl(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=G(t,"base32"),o=El(e);return`${n}:${o}`}function vl(r){r=$i(r);let t=[],e=[],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=rt(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw Sl("invalid address: "+r);if(a.path===!0){n=$i(o.slice(s).join("/")),t.push([a.code,Fi(a.code,n)]),e.push([a.code,n]);break}let c=Fi(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Vi(a.code,c)])}return{string:Al(e),bytes:Gi(t),tuples:t,stringTuples:e,path:n}}function Wi(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=ee(r,o),i=gt(s),a=rt(s),c=Mp(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let l=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw Sl("Invalid address Uint8Array: "+G(r,"base16"));t.push([s,l]);let u=Vi(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:Al(e),tuples:t,stringTuples:e,path:n}}function Al(r){let t=[];return r.map(e=>{let n=rt(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),$i(t.join("/"))}function Gi(r){return yt(r.map(t=>{let e=rt(t[0]),n=Uint8Array.from(me(e.code));return t.length>1&&t[1]!=null&&(n=yt([n,t[1]])),n}))}function Mp(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=ee(t instanceof Uint8Array?t:Uint8Array.from(t));return e+gt(e)}}function $i(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function Sl(r){return new Error("Error parsing address: "+r)}var Vp=Symbol.for("nodejs.util.inspect.custom"),qi=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Fp=[rt("dns").code,rt("dns4").code,rt("dns6").code,rt("dnsaddr").code],co=class r{bytes;#t;#e;#r;#n;[qi]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Wi(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=vl(t)}else if(Il(t))e=Wi(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="",i=rt("tcp"),a=rt("udp"),c=rt("ip4"),l=rt("ip6"),u=rt("dns6"),f=rt("ip6zone");for(let[y,m]of this.stringTuples())y===f.code&&(s=`%${m??""}`),Fp.includes(y)&&(e=i.name,o=443,n=`${m??""}${s}`,t=y===u.code?6:4),(y===i.code||y===a.code)&&(e=rt(y).name,o=parseInt(m??"")),(y===c.code||y===l.code)&&(e=rt(y).name,n=`${m??""}${s}`,t=y===l.code?6:4);if(t==null||e==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:t,host:n,transport:e,port:o}}protos(){return this.#e.map(([t])=>Object.assign({},rt(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>rt(t).name)}tuples(){return this.#e}stringTuples(){return this.#r}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(Gi(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Hr.p2p.code&&t.push([n,o]),n===Hr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?G(dt.decode(`z${n}`),"base58btc"):G(zt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return Et(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=Bl.get(e.name);if(n==null)throw new D(`no available resolver for ${e.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,t)).map(s=>re(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[Vp](){return`Multiaddr(${this.#t})`}};var Bl=new Map;function Il(r){return!!r?.[qi]}function re(r){return new co(r)}var Kp=r=>r.toString().split("/").slice(1),wn=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),Q=r=>({match:t=>wn(e=>e===r).match(t),pattern:r}),fo=()=>({match:r=>wn(t=>typeof t=="string").match(r),pattern:"{string}"}),ho=()=>({match:r=>wn(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),Rt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{dt.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),lo=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{ui.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),St=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Yt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),ot=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function pt(...r){function t(o){let s=Kp(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matches:e,exactMatch:n}}var zi=ot(Q("dns4"),fo()),Yi=ot(Q("dns6"),fo()),Zi=ot(Q("dnsaddr"),fo()),_l=ot(Q("dns"),fo()),Bx=pt(zi),Ix=pt(Yi),_x=pt(Zi),kx=pt(Yt(_l,Zi,zi,Yi)),kl=ot(Q("ip4"),wn(so)),Cl=ot(Q("ip6"),wn(io)),Rl=Yt(kl,Cl),ge=Yt(Rl,_l,zi,Yi,Zi),Cx=pt(ge),Rx=pt(kl),Tx=pt(Cl),Nx=pt(Rl),Xi=ot(ge,Q("tcp"),ho()),bn=ot(ge,Q("udp"),ho()),Lx=pt(Xi),Dx=pt(bn),Ji=ot(bn,Q("quic")),po=ot(bn,Q("quic-v1")),$p=Yt(Ji,po),Ux=pt(Ji),Px=pt(po),ji=Yt(ge,Xi,bn,Ji,po),Tl=Yt(ot(ji,Q("ws"),St(Rt()))),Ox=pt(Tl),Nl=Yt(ot(ji,Q("wss"),St(Rt())),ot(ji,Q("tls"),Q("ws"),St(Rt()))),Hx=pt(Nl),Ll=ot(bn,Q("webrtc-direct"),St(lo()),St(lo()),St(Rt())),Dl=pt(Ll),Ul=ot(po,Q("webtransport"),St(lo()),St(lo()),St(Rt())),Mx=pt(Ul),uo=Yt(Tl,Nl,ot(Xi,St(Rt())),ot($p,St(Rt())),ot(ge,St(Rt())),Ll,Ul,Rt()),Vx=pt(uo),Wp=ot(uo,Q("p2p-circuit"),Rt()),Fx=pt(Wp),Gp=Yt(ot(uo,Q("p2p-circuit"),Q("webrtc"),St(Rt())),ot(uo,Q("webrtc"),St(Rt())),Q("webrtc")),Pl=pt(Gp),qp=Yt(ot(ge,Q("tcp"),ho(),Q("http"),St(Rt())),ot(ge,Q("http"),St(Rt()))),Kx=pt(qp),jp=Yt(ot(ge,Q("tcp"),Yt(ot(Q("443"),Q("http")),ot(ho(),Q("https"))),St(Rt())),ot(ge,Q("tls"),Q("http"),St(Rt())),ot(ge,Q("https"),St(Rt()))),$x=pt(jp);var Wt;(function(r){r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_DATA_CHANNEL="ERR_DATA_CHANNEL",r.ERR_CONNECTION_CLOSED="ERR_CONNECTION_CLOSED",r.ERR_HASH_NOT_SUPPORTED="ERR_HASH_NOT_SUPPORTED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_INVALID_FINGERPRINT="ERR_INVALID_FINGERPRINT",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS"})(Wt||(Wt={}));var We=class extends D{constructor(t,e){super(`WebRTC transport error: ${t}`,e??""),this.name="WebRTCTransportError"}};var Qi=class extends We{constructor(t,e){super(`[stream: ${t}] data channel error: ${e}`,Wt.ERR_DATA_CHANNEL),this.name="WebRTC/DataChannelError"}};function sa(r,t){return new Qi(r,t)}var ta=class extends We{constructor(t){super(`There was a problem with the Multiaddr which was passed in: ${t}`,Wt.ERR_INVALID_MULTIADDR),this.name="WebRTC/InappropriateMultiaddrError"}};function mo(r){return new ta(r)}var ea=class extends We{constructor(t){super(`There was a problem with a provided argument: ${t}`,Wt.ERR_INVALID_PARAMETERS),this.name="WebRTC/InvalidArgumentError"}};function xn(r){return new ea(r)}var ra=class extends We{constructor(t,e){super(`Invalid fingerprint "${t}" within ${e}`,Wt.ERR_INVALID_FINGERPRINT),this.name="WebRTC/InvalidFingerprintError"}};function ia(r,t){return new ra(r,t)}var na=class extends We{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`,Wt.ERR_NOT_IMPLEMENTED),this.name="WebRTC/UnimplementedError"}};function Ol(r){return new na(r)}var oa=class extends We{constructor(t){super(`unsupported hash algorithm code: ${t} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `,Wt.ERR_HASH_NOT_SUPPORTED),this.name="WebRTC/UnsupportedHashAlgorithmError"}};function Hl(r){return new oa(r)}var Ml=function(r,t,e){if(e||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return r.concat(s||Array.prototype.slice.call(t))},zp=function(){function r(t,e,n){this.name=t,this.version=e,this.os=n,this.type="browser"}return r}();var Yp=function(){function r(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return r}();var Zp=function(){function r(t,e,n,o){this.name=t,this.version=e,this.os=n,this.bot=o,this.type="bot-device"}return r}();var Xp=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var Jp=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var Qp=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,t0=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Vl=3,e0=[["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",Qp]],Fl=[["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 $l(r){return r?Kl(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Jp:typeof navigator<"u"?Kl(navigator.userAgent):o0()}function r0(r){return r!==""&&e0.reduce(function(t,e){var n=e[0],o=e[1];if(t)return t;var s=o.exec(r);return!!s&&[n,s]},!1)}function Kl(r){var t=r0(r);if(!t)return null;var e=t[0],n=t[1];if(e==="searchbot")return new Xp;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<Vl&&(o=Ml(Ml([],o,!0),s0(Vl-o.length),!0)):o=[];var s=o.join("."),i=n0(r),a=t0.exec(r);return a&&a[1]?new Zp(e,s,i,a[1]):new zp(e,s,i)}function n0(r){for(var t=0,e=Fl.length;t<e;t++){var n=Fl[t],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function o0(){var r=typeof process<"u"&&process.version;return r?new Yp(process.version.slice(1)):null}function s0(r){for(var t=[],e=0;e<r;e++)t.push("0");return t}function ht(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Mr=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},aa=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Wl=r=>globalThis.DOMException===void 0?new aa(r):new DOMException(r),Gl=r=>{let t=r.reason===void 0?Wl("This operation was aborted."):r.reason;return t instanceof Error?t:Wl(t)};function ur(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,c=new Promise((l,u)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:p}=t;p.aborted&&u(Gl(p)),p.addEventListener("abort",()=>{u(Gl(p))})}if(e===Number.POSITIVE_INFINITY){r.then(l,u);return}let f=new Mr;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(p){u(p)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?u(o):(f.message=o??`Promise timed out after ${e} milliseconds`,u(f))},e),(async()=>{try{l(await r)}catch(p){u(p)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}var ql=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"];var jl=$l(),En=jl!=null&&jl.name==="firefox",go=async function*(){},yo=async r=>{},i0=30*1e3;function zl(r,t,e=i0,n){r.readyState==="open"&&Promise.resolve().then(async()=>{if(r.bufferedAmount>0){n.log("%s drain channel with %d buffered bytes",t,r.bufferedAmount);let o=ht(),s=!1;r.bufferedAmountLowThreshold=0;let i=()=>{s||(n.log("%s drain channel closed before drain",t),o.resolve())};r.addEventListener("close",i,{once:!0}),r.addEventListener("bufferedamountlow",()=>{s=!0,r.removeEventListener("close",i),o.resolve()}),await ur(o.promise,{milliseconds:e})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function vn(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??ql.map(t=>({urls:[t]})),r}var fr=class{log;peerConnection;remoteAddr;timeline;metrics;source=go();sink=yo;constructor(t,e){this.log=t.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=e.remoteAddr,this.timeline=e.timeline,this.peerConnection=e.peerConnection;let n=this.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",this.peerConnection.connectionState,"initial state",n),(this.peerConnection.connectionState==="disconnected"||this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.timeline.close=Date.now())}}async close(t){this.log.trace("closing connection"),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({close:!0})}abort(t){this.log.error("closing connection due to error",t),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({abort:!0})}};var wo=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Vr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new wo(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new wo(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var ca=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Ge(r={}){return a0(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function a0(r,t){t=t??{};let e=t.onEnd,n=new Vr,o,s,i,a=ht(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((d,b)=>{s=E=>{s=null,n.push(E);try{d(r(n))}catch(w){b(w)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ht()})}},l=d=>s!=null?s(d):(n.push(d),o),u=d=>(n=new Vr,s!=null?s({error:d}):(n.push({error:d}),o)),f=d=>{if(i)return o;if(t?.objectMode!==!0&&d?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:d})},p=d=>i?o:(i=!0,d!=null?u(d):l({done:!0})),y=()=>(n=new Vr,p(),{done:!0}),m=d=>(p(d),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:y,throw:m,push:f,end:p,get readableLength(){return n.size},onEmpty:async d=>{let b=d?.signal;if(b?.throwIfAborted(),n.isEmpty())return;let E,w;b!=null&&(E=new Promise((S,x)=>{w=()=>{x(new ca)},b.addEventListener("abort",w)}));try{await Promise.race([a.promise,E])}finally{w!=null&&b!=null&&b?.removeEventListener("abort",w)}}},e==null)return o;let h=o;return o={[Symbol.asyncIterator](){return this},next(){return h.next()},throw(d){return h.throw(d),e!=null&&(e(d),e=void 0),{done:!0}},return(){return h.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(d){return h.end(d),e!=null&&(e(d),e=void 0),o},get readableLength(){return h.readableLength},onEmpty:d=>h.onEmpty(d)},o}var bo=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=e??"ABORT_ERR"}};async function Ie(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new bo(e?.errorMessage,e?.errorCode));let n,o=new bo(e?.errorMessage,e?.errorCode);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var Zl=Symbol.for("@achingbrain/uint8arraylist");function Yl(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function xo(r){return!!r?.[Zl]}var ct=class r{bufs;length;[Zl]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(xo(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(xo(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Yl(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Yl(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(xo(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return yt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:yt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!xo(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let 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=e;f<=c;f+=u){u=0;for(let p=l;p>=0;p--){let y=this.get(f+p);if(n[p]!==y){u=Math.max(1,p-a[y]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=At(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=vt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=vt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=vt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=At(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=vt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=vt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=vt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=vt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=vt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Et(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};function Xl(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 Jl(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Ql(r,t){let e=Xl(r).return?.();Jl(e)&&e.catch(n=>{t.error("could not cause iterator to return",n)})}var c0="ERR_STREAM_RESET",l0="ERR_SINK_INVALID_STATE",u0=5e3;function la(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Eo=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(t){this.sinkController=new AbortController,this.sinkEnd=ht(),this.closed=ht(),this.log=t.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=t.id,this.metadata=t.metadata??{},this.direction=t.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=t.sendCloseWriteTimeout??u0,this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=Ge({onEnd:e=>{e!=null?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(t){if(this.writeStatus!=="ready")throw new D(`writable end state is "${this.writeStatus}" not "ready"`,l0);try{this.writeStatus="writing";let e={signal:this.sinkController.signal};if(this.direction==="outbound"){let o=this.sendNewStream(e);la(o)&&await o}let n=()=>{Ql(t,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let o of t){o=o instanceof Uint8Array?new ct(o):o;let s=this.sendData(o,e);la(s)&&(this.sendingData=ht(),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(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(t){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),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(t){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),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(t){this.log.trace("closing gracefully"),this.status="closing",await Ie(Promise.all([this.closeWrite(t),this.closeRead(t),this.closed.promise]),t?.signal),this.status="closed",this.log.trace("closed gracefully")}async closeRead(t={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let e=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(t)),e==="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(t={}){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 Ie(this.sink([]),t.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await Ie(this.sendingData.promise,t.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await Ie(this.sinkEnd.promise,t.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(t){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",t),this.log("try to send reset to remote");let e=this.sendReset();la(e)&&e.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(t),this.onAbort?.(t)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let t=new D("stream reset",c0);this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(t),this.onReset?.()}_closeSinkAndSource(t){this._closeSink(t),this._closeSource(t)}_closeSink(t){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(t)}_closeSource(t){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(t))}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(t){this.streamSource.push(t)}sourceReadableLength(){return this.streamSource.readableLength}};function vo(r){return r[Symbol.asyncIterator]!=null}var Ao=r=>{let t=gt(r),e=At(t);return me(r,e),Ao.bytes=t,e};Ao.bytes=0;function An(r,t){t=t??{};let e=t.lengthEncoder??Ao;function*n(o){let s=e(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return vo(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}An.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Ao;return new ct(e(r.byteLength),r)};var Fr=$c(ru(),1);var h0=8,d0=1024*1024*4,hr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(hr||(hr={}));var ua=r=>{let t=ee(r);return ua.bytes=gt(t),t};ua.bytes=0;function dr(r,t){let e=new ct,n=hr.LENGTH,o=-1,s=t?.lengthDecoder??ua,i=t?.maxLengthLength??h0,a=t?.maxDataLength??d0;function*c(){for(;e.byteLength>0;){if(n===hr.LENGTH)try{if(o=s(e),o<0)throw(0,Fr.default)(new Error("invalid message length"),"ERR_INVALID_MSG_LENGTH");if(o>a)throw(0,Fr.default)(new Error("message length too long"),"ERR_MSG_DATA_TOO_LONG");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=hr.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw(0,Fr.default)(new Error("message length length too long"),"ERR_MSG_LENGTH_TOO_LONG");break}throw l}if(n===hr.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=hr.LENGTH}}}return vo(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw(0,Fr.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw(0,Fr.default)(new Error("unexpected end of input"),"ERR_UNEXPECTED_EOF")}()}dr.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return dr(n,{...t??{},onLength:s=>{e=s}})};var m0=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function g0(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:u}=m0(r),f=(...y)=>{let m=e.multiArgs?y:y[0];e.filter&&!e.filter(m)||(c.push(m),e.count===c.length&&(n(),s(c)))},p=y=>{n(),i(y)};n=()=>{for(let y of a)u(y,f);for(let y of e.rejectionEvents)u(y,p)};for(let y of a)l(y,f);for(let y of e.rejectionEvents)l(y,p);e.signal&&e.signal.addEventListener("abort",()=>{p(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=ur(o,{milliseconds:e.timeout});return s.cancel=n,s}return o}function fa(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=g0(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var ha=new Float32Array([-0]),qe=new Uint8Array(ha.buffer);function nu(r,t,e){ha[0]=r,t[e]=qe[0],t[e+1]=qe[1],t[e+2]=qe[2],t[e+3]=qe[3]}function ou(r,t){return qe[0]=r[t],qe[1]=r[t+1],qe[2]=r[t+2],qe[3]=r[t+3],ha[0]}var da=new Float64Array([-0]),Ut=new Uint8Array(da.buffer);function su(r,t,e){da[0]=r,t[e]=Ut[0],t[e+1]=Ut[1],t[e+2]=Ut[2],t[e+3]=Ut[3],t[e+4]=Ut[4],t[e+5]=Ut[5],t[e+6]=Ut[6],t[e+7]=Ut[7]}function iu(r,t){return Ut[0]=r[t],Ut[1]=r[t+1],Ut[2]=r[t+2],Ut[3]=r[t+3],Ut[4]=r[t+4],Ut[5]=r[t+5],Ut[6]=r[t+6],Ut[7]=r[t+7],da[0]}var y0=BigInt(Number.MAX_SAFE_INTEGER),w0=BigInt(Number.MIN_SAFE_INTEGER),Gt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return pr;if(t<y0&&t>w0)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>au&&(o=0n,++n>au&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return pr;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):pr}},pr=new Gt(0,0);pr.toBigInt=function(){return 0n};pr.zzEncode=pr.zzDecode=function(){return this};pr.length=function(){return 1};var au=4294967296n;function cu(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function lu(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function pa(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function ne(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function So(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var ma=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,ne(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ne(this,4);return So(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ne(this,4);return So(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ne(this,4);let t=ou(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw ne(this,4);let t=iu(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw ne(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return lu(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw ne(this,t);this.pos+=t}else do if(this.pos>=this.len)throw ne(this);while(this.buf[this.pos++]&128);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Gt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw ne(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw ne(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ne(this,8);let t=So(this.buf,this.pos+=4),e=So(this.buf,this.pos+=4);return new Gt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Ni(this.buf,this.pos);return this.pos+=gt(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function ga(r){return new ma(r instanceof Uint8Array?r:r.subarray())}function oe(r,t,e){let n=ga(r);return t.decode(n,void 0,e)}function ya(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return At(i);o+i>t&&(n=At(t),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var mr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function wa(){}var xa=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},b0=ya();function x0(r){return globalThis.Buffer!=null?At(r):b0(r)}var Bn=class{len;head;tail;states;constructor(){this.len=0,this.head=new mr(wa,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new mr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Ea((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Bo,10,Gt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Gt.fromBigInt(t);return this._push(Bo,e.length(),e)}uint64Number(t){return this._push(Ti,gt(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Gt.fromBigInt(t).zzEncode();return this._push(Bo,e.length(),e)}sint64Number(t){let e=Gt.fromNumber(t).zzEncode();return this._push(Bo,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ba,1,t?1:0)}fixed32(t){return this._push(Sn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Gt.fromBigInt(t);return this._push(Sn,4,e.lo)._push(Sn,4,e.hi)}fixed64Number(t){let e=Gt.fromNumber(t);return this._push(Sn,4,e.lo)._push(Sn,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(nu,4,t)}double(t){return this._push(su,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ba,1,0):this.uint32(e)._push(v0,e,t)}string(t){let e=cu(t);return e!==0?this.uint32(e)._push(pa,e,t):this._push(ba,1,0)}fork(){return this.states=new xa(this),this.head=this.tail=new mr(wa,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 mr(wa,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=x0(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ba(r,t,e){t[e]=r&255}function E0(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Ea=class extends mr{next;constructor(t,e){super(E0,t,e),this.next=void 0}};function Bo(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Sn(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function v0(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Bn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(A0,t,r),this},Bn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(S0,t,r),this});function A0(r,t,e){t.set(r,e)}function S0(r,t,e){r.length<40?pa(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(J(r),e)}function va(){return new Bn}function se(r,t){let e=va();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Kr;(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"})(Kr||(Kr={}));function Io(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function gr(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return Io("enum",Kr.VARINT,e,n)}function ie(r,t){return Io("message",Kr.LENGTH_DELIMITED,r,t)}var Mt;(function(r){let t;(function(o){o.FIN="FIN",o.STOP_SENDING="STOP_SENDING",o.RESET="RESET",o.FIN_ACK="FIN_ACK"})(t=r.Flag||(r.Flag={}));let e;(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"})(e||(e={})),function(o){o.codec=()=>gr(e)}(t=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=ie((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)=>{let i={},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.flag=r.Flag.codec().decode(o);break;case 2:i.message=o.bytes();break;default:o.skipType(c&7);break}}return i})),n),r.encode=o=>se(o,r.codec()),r.decode=o=>oe(o,r.codec())})(Mt||(Mt={}));var B0=2*1024*1024,I0=30*1e3,_0=7,k0=2,C0=256*1024,R0=5e3,T0=5e3,Aa=class extends Eo{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;constructor(t){let e=t.onEnd;switch(t.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 ur(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(s){this.log.error("error receiving FIN_ACK",s)}}).then(()=>{this.incomingData.end(),e?.(o)}).catch(s=>{this.log.error("error ending stream",s)})},super(t),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=Ge(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??I0,this.maxBufferedAmount=t.maxBufferedAmount??B0,this.maxMessageSize=(t.maxMessageSize??C0)-_0-k0,this.receiveFinAck=ht(),this.finAckTimeout=t.closeTimeout??R0,this.openTimeout=t.openTimeout??T0,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 D("Unknown datachannel state","ERR_INVALID_STATE")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime()},this.channel.onclose=o=>{this.receiveFinAck.resolve(),this.close().catch(s=>{this.log.error("error closing stream after channel closed",s)})},this.channel.onerror=o=>{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 dr(this.incomingData)){let s=n.processIncomingProtobuf(o);s!=null&&n.sourcePush(new ct(s))}}).catch(o=>{this.log.error("error processing incoming data channel messages",o)})}sendNewStream(){}async _sendMessage(t,e=!0){if(e&&this.channel.bufferedAmount>this.maxBufferedAmount)try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await fa(this.channel,"bufferedamountlow",{timeout:this.bufferedAmountLowEventTimeout})}catch(n){throw n instanceof Mr?new D(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`,"ERR_BUFFER_CLEAR_TIMEOUT"):n}if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new D(`Invalid datachannel state - ${this.channel.readyState}`,"ERR_INVALID_STATE");this.channel.readyState!=="open"&&(this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await fa(this.channel,"open",{timeout:this.openTimeout}),this.log('channel state is now "%s", sending data',this.channel.readyState)),this.channel.send(t.subarray())}async sendData(t){for(t=t.sublist();t.byteLength>0;){let e=Math.min(t.byteLength,this.maxMessageSize),n=t.subarray(0,e),o=Mt.encode({message:n}),s=An.single(o);await this._sendMessage(s),t.consume(e)}}async sendReset(){await this._sendFlag(Mt.Flag.RESET)}async sendCloseWrite(t){if(await this._sendFlag(Mt.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await Ie(this.receiveFinAck.promise,t?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorCode:"ERR_FIN_ACK_NOT_RECEIVED"})}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(){await this._sendFlag(Mt.Flag.STOP_SENDING)}processIncomingProtobuf(t){let e=Mt.decode(t);if(e.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',e.flag,this.writeStatus,this.readStatus),e.flag===Mt.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Mt.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),e.flag===Mt.Flag.RESET&&this.reset(),e.flag===Mt.Flag.STOP_SENDING&&this.remoteCloseRead(),e.flag===Mt.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),this.readStatus==="ready")return e.message}async _sendFlag(t){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',this.channel.readyState,t.toString()),!1;this.log.trace("sending flag %s",t.toString());let e=Mt.encode({flag:t}),n=An.single(e);try{return await this._sendMessage(n,!1),!0}catch(o){this.log.error("could not send flag %s",t.toString(),o)}return!1}};function $r(r){let{channel:t,direction:e}=r;return new Aa({id:e==="inbound"?`i${t.id}`:`r${t.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${e}:${t.id}`),...r})}var fu="/webrtc",je=class{protocol;peerConnection;bufferedStreams=[];metrics;dataChannelOptions;components;log;constructor(t,e){this.components=t,this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??fu,this.dataChannelOptions=e.dataChannelOptions??{},this.log=t.logger.forComponent("libp2p:webrtc:datachannelmuxerfactory"),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=$r({channel:n,direction:"inbound",onEnd:i=>{o.onEnd(i)},logger:t.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(t){return new Sa(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},Sa=class{init;streams;protocol;log;peerConnection;dataChannelOptions;metrics;logger;constructor(t,e){this.init=e,this.log=t.logger.forComponent("libp2p:webrtc:muxer"),this.logger=t.logger,this.streams=e.streams.map(n=>n.stream),this.peerConnection=e.peerConnection,this.protocol=e.protocol??fu,this.metrics=e.metrics,this.dataChannelOptions=e.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=$r({channel:n,direction:"inbound",onEnd:()=>{this.log("incoming channel %s ended with state %s",n.id,n.readyState),this.#t(o,n)},logger:this.logger,...this.dataChannelOptions});this.streams.push(o),this.metrics?.increment({incoming_stream:!0}),e?.onIncomingStream?.(o)},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.#t(n.stream,n.channel)},this.metrics?.increment({incoming_stream:!0}),this.init?.onIncomingStream?.(n.stream)})})}#t(t,e){this.log.trace("stream %s %s %s onEnd",t.direction,t.id,t.protocol),zl(e,`${t.direction} ${t.id} ${t.protocol}`,this.dataChannelOptions.drainTimeout,{log:this.log}),this.streams=this.streams.filter(n=>n.id!==t.id),this.metrics?.increment({stream_end:!0}),this.init?.onStreamEnd?.(t)}async close(t){try{await Promise.all(this.streams.map(async e=>e.close(t)))}catch(e){this.abort(e)}}abort(t){for(let e of this.streams)e.abort(t)}source=go();sink=yo;newStream(){let t=this.peerConnection.createDataChannel("");this.log.trace("opened outgoing datachannel with channel id %s",t.id);let e=$r({channel:t,direction:"outbound",onEnd:()=>{this.log("outgoing channel %s ended with state %s",t.id,t.readyState),this.#t(e,t)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(e),this.metrics?.increment({outgoing_stream:!0}),e}};var yr=globalThis.RTCPeerConnection,_o=globalThis.RTCSessionDescription,hu=globalThis.RTCIceCandidate;var Ba=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=ht(),this.haveNext=ht()}[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 t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ht(),t}async throw(t){return this.ended=!0,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return await this._push(void 0),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ht(),await Ie(this.readNext.promise,e?.signal,e)}};function du(){return new Ba}var ko=class extends Error{code;constructor(t,e){super(t),this.code=e}},Ia=class extends ko{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted"}};function pu(r,t){let e=du();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.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 ct;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new Ia("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:p}=await Promise.race([n.next(),l]);return f===!0?new ct:p}for(;o.byteLength<i;){let{value:f,done:p}=await Promise.race([n.next(),l]);if(p===!0)throw new ko("unexpected end of input","ERR_UNEXPECTED_EOF");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 e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Co=class extends Error{code;constructor(t,e){super(t),this.code=e}};function In(r,t={}){let e=pu(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=gt(t.maxDataLength));let n=t?.lengthDecoder??ee,o=t?.lengthEncoder??me;return{read:async i=>{let a=-1,c=new ct;for(;;){c.append(await e.read(1,i));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Co("message length length too long","ERR_MSG_LENGTH_TOO_LONG");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Co("message length too long","ERR_MSG_DATA_TOO_LONG");return e.read(a,i)},write:async(i,a)=>{await e.write(new ct(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new ct(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Ro(r,t){let e=In(r,t),n={read:async(o,s)=>{let i=await e.read(s);return o.decode(i)},write:async(o,s,i)=>{await e.write(s.encode(o),i)},writeV:async(o,s,i)=>{await e.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>e.unwrap()};return n}var qt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Vt;(function(r){let t;(function(o){o.SDP_OFFER="SDP_OFFER",o.SDP_ANSWER="SDP_ANSWER",o.ICE_CANDIDATE="ICE_CANDIDATE"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.SDP_OFFER=0]="SDP_OFFER",o[o.SDP_ANSWER=1]="SDP_ANSWER",o[o.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(e||(e={})),function(o){o.codec=()=>gr(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ie((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)=>{let i={},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.type=r.Type.codec().decode(o);break;case 2:i.data=o.string();break;default:o.skipType(c&7);break}}return i})),n),r.encode=o=>se(o,r.codec()),r.decode=o=>oe(o,r.codec())})(Vt||(Vt={}));var To=async(r,t,e)=>{try{let n=ht();for(L0(r,n);;){let o=await Promise.race([n.promise,t.read({signal:e.signal}).catch(()=>{})]);if(o==null){e.signal?.throwIfAborted();break}if(o.type!==Vt.Type.ICE_CANDIDATE)throw new D("ICE candidate message expected","ERR_NOT_ICE_CANDIDATE");let s=JSON.parse(o.data??"null");if(s===""||s===null){e.onProgress?.(new qt("webrtc:end-of-ice-candidates")),e.log.trace("end-of-candidates received");continue}let i=new hu(s);e.log.trace("%s received new ICE candidate %o",e.direction,s);try{e.onProgress?.(new qt("webrtc:add-ice-candidate",i.candidate)),await r.addIceCandidate(i)}catch(a){e.log.error("%s bad candidate received",e.direction,s,a)}}}catch(n){if(e.log.error("%s error parsing ICE candidate",e.direction,n),e.signal?.aborted===!0)throw n}};function N0(r){return En?r.iceConnectionState:r.connectionState}function L0(r,t){r[En?"oniceconnectionstatechange":"onconnectionstatechange"]=e=>{switch(N0(r)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new D("RTCPeerConnection was closed","ERR_CONNECTION_CLOSED_BEFORE_CONNECTED"));break;default:break}}}async function mu({rtcConfiguration:r,dataChannel:t,signal:e,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=gu(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",u);let f=u.getPeerId();if(f==null)throw new D("Relay peer was missing","ERR_INVALID_ADDRESS");let p=s.getConnections(lr(f)),y,m=!1;p.length===0?(l?.(new qt("webrtc:dial-relay")),y=await i.dial(u,{signal:e,onProgress:l}),m=!0):(l?.(new qt("webrtc:reuse-relay-connection")),y=p[0]);try{l?.(new qt("webrtc:open-signaling-stream"));let h=await y.newStream(No,{signal:e,runOnTransientConnection:!0}),d=Ro(h).pb(Vt),b=new yr(r),E=new je({logger:c},{peerConnection:b,dataChannelOptions:t});try{let w=b.createDataChannel("init");b.onicecandidate=({candidate:I})=>{let _=JSON.stringify(I?.toJSON()??null);a.trace("initiator sending ICE candidate %o",I),d.write({type:Vt.Type.ICE_CANDIDATE,data:_},{signal:e}).catch(N=>{a.error("error sending ICE candidate",N)})},b.onicecandidateerror=I=>{a.error("initiator ICE candidate error",I)};let S=await b.createOffer().catch(I=>{throw a.error("could not execute createOffer",I),new D("Failed to set createOffer","ERR_SDP_HANDSHAKE_FAILED")});a.trace("initiator send SDP offer %s",S.sdp),l?.(new qt("webrtc:send-sdp-offer")),await d.write({type:Vt.Type.SDP_OFFER,data:S.sdp},{signal:e}),await b.setLocalDescription(S).catch(I=>{throw a.error("could not execute setLocalDescription",I),new D("Failed to set localDescription","ERR_SDP_HANDSHAKE_FAILED")}),l?.(new qt("webrtc:read-sdp-answer"));let x=await d.read({signal:e});if(x.type!==Vt.Type.SDP_ANSWER)throw new D("Remote should send an SDP answer","ERR_SDP_HANDSHAKE_FAILED");a.trace("initiator receive SDP answer %s",x.data);let B=new _o({type:"answer",sdp:x.data});return await b.setRemoteDescription(B).catch(I=>{throw a.error("could not execute setRemoteDescription",I),new D("Failed to set remoteDescription","ERR_SDP_HANDSHAKE_FAILED")}),a.trace("initiator read candidates until connected"),l?.(new qt("webrtc:read-ice-candidates")),await To(b,d,{direction:"initiator",signal:e,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),w.close(),l?.(new qt("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await h.close({signal:e}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:b,muxerFactory:E}}catch(w){throw a.error("outgoing signaling error",w),b.close(),h.abort(w),w}finally{b.onicecandidate=null,b.onicecandidateerror=null}}finally{if(m)try{await y.close({signal:e})}catch(h){y.abort(h)}}}var D0=U("dns4"),U0=U("dns6"),P0=U("dnsaddr"),wr=mt(U("dns"),P0,D0,U0),Uo=mt(U("ip4"),U("ip6")),Wr=mt(K(Uo,U("tcp")),K(wr,U("tcp"))),Po=K(Uo,U("udp")),O0=K(Po,U("utp")),H0=K(Po,U("quic")),M0=K(Po,U("quic-v1")),_a=mt(K(Wr,U("ws")),K(wr,U("ws"))),Lo=mt(K(_a,U("p2p")),_a),ka=mt(K(Wr,U("wss")),K(wr,U("wss")),K(Wr,U("tls"),U("ws")),K(wr,U("tls"),U("ws"))),Do=mt(K(ka,U("p2p")),ka),Ca=mt(K(Wr,U("http")),K(Uo,U("http")),K(wr,U("http"))),Ra=mt(K(Wr,U("https")),K(Uo,U("https")),K(wr,U("https"))),yu=K(Po,U("webrtc-direct"),U("certhash")),xu=mt(K(yu,U("p2p")),yu),wu=K(M0,U("webtransport"),U("certhash"),U("certhash")),Eu=mt(K(wu,U("p2p")),wu),vu=mt(K(Lo,U("p2p-webrtc-star"),U("p2p")),K(Do,U("p2p-webrtc-star"),U("p2p")),K(Lo,U("p2p-webrtc-star")),K(Do,U("p2p-webrtc-star"))),f2=mt(K(Lo,U("p2p-websocket-star"),U("p2p")),K(Do,U("p2p-websocket-star"),U("p2p")),K(Lo,U("p2p-websocket-star")),K(Do,U("p2p-websocket-star"))),Au=mt(K(Ca,U("p2p-webrtc-direct"),U("p2p")),K(Ra,U("p2p-webrtc-direct"),U("p2p")),K(Ca,U("p2p-webrtc-direct")),K(Ra,U("p2p-webrtc-direct"))),br=mt(_a,ka,Ca,Ra,vu,Au,Wr,O0,H0,wr,xu,Eu),h2=mt(K(br,U("p2p-stardust"),U("p2p")),K(br,U("p2p-stardust"))),ze=mt(K(br,U("p2p")),vu,Au,xu,Eu,U("p2p")),bu=mt(K(ze,U("p2p-circuit"),ze),K(ze,U("p2p-circuit")),K(U("p2p-circuit"),ze),K(br,U("p2p-circuit")),K(U("p2p-circuit"),br),U("p2p-circuit")),Su=()=>mt(K(bu,Su),bu),_e=Su(),d2=mt(K(_e,ze,_e),K(ze,_e),K(_e,ze),_e,ze);var p2=mt(K(_e,U("webrtc"),U("p2p")),K(_e,U("webrtc")),K(br,U("webrtc"),U("p2p")),K(br,U("webrtc")),U("webrtc"));function Bu(r){function t(e){let n;try{n=re(e)}catch{return!1}let o=r(n.protoNames());return o===null?!1:o===!0||o===!1?o:o.length===0}return t}function K(...r){function t(e){if(e.length<r.length)return null;let n=e;return r.some(o=>(n=typeof o=="function"?o().partialMatch(e):o.partialMatch(e),Array.isArray(n)&&(e=n),n===null)),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:Bu(t),partialMatch:t}}function mt(...r){function t(n){let o=null;return r.some(s=>{let i=typeof s=="function"?s().partialMatch(n):s.partialMatch(n);return i!=null?(o=i,!0):!1}),o}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:Bu(t),partialMatch:t}}function U(r){let t=r;function e(o){let s;try{s=re(o)}catch{return!1}let i=s.protoNames();return i.length===1&&i[0]===t}function n(o){return o.length===0?null:o[0]===t?o.slice(1):null}return{toString:function(){return t},matches:e,partialMatch:n}}var Oo=class extends to{peerId;transportManager;shutdownController;constructor(t,e){super(),this.peerId=t.peerId,this.transportManager=t.transportManager,this.shutdownController=e.shutdownController}async listen(){this.safeDispatchEvent("listening",{})}getAddrs(){return this.transportManager.getListeners().filter(t=>t!==this).map(t=>t.getAddrs().filter(e=>_e.matches(e)).map(e=>e.encapsulate(`/webrtc/p2p/${this.peerId}`))).flat()}async close(){this.shutdownController.abort(),this.safeDispatchEvent("close",{})}};async function Iu({peerConnection:r,stream:t,signal:e,connection:n,log:o}){o.trace("new inbound signaling stream");let s=Ro(t).pb(Vt);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:Vt.Type.ICE_CANDIDATE,data:f},{signal:e}).catch(p=>{o.error("error sending ICE candidate",p)})};let a=await s.read({signal:e});if(a.type!==Vt.Type.SDP_OFFER)throw new D(`expected message type SDP_OFFER, received: ${a.type??"undefined"} `,"ERR_SDP_HANDSHAKE_FAILED");o.trace("recipient receive SDP offer %s",a.data);let c=new _o({type:"offer",sdp:a.data});await r.setRemoteDescription(c).catch(u=>{throw o.error("could not execute setRemoteDescription",u),new D("Failed to set remoteDescription","ERR_SDP_HANDSHAKE_FAILED")});let l=await r.createAnswer().catch(u=>{throw o.error("could not execute createAnswer",u),new D("Failed to create answer","ERR_SDP_HANDSHAKE_FAILED")});o.trace("recipient send SDP answer %s",l.sdp),await s.write({type:Vt.Type.SDP_ANSWER,data:l.sdp},{signal:e}),await r.setLocalDescription(l).catch(u=>{throw o.error("could not execute setLocalDescription",u),new D("Failed to set localDescription","ERR_SDP_HANDSHAKE_FAILED")}),o.trace("recipient read candidates until connected"),await To(r,s,{direction:"recipient",signal:e,log:o})}catch(a){if(r.connectionState!=="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=re(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return o.trace("recipient connected to remote address %s",i),{remoteAddress:i}}var V0="/webrtc",F0="/p2p-circuit",No="/webrtc-signaling/0.0.1",K0=30*1e3,Ho=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,e={}){this.components=t,this.init=e,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,Qn(1/0,this.shutdownController.signal),t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[Jn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Rr]=["@libp2p/transport"];[Gc]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(No,t=>{this._onProtocol(t).catch(e=>{this.log.error("failed to handle incoming connect from %p",t.connection.remotePeer,e)})},{runOnTransientConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(No),this._started=!1}createListener(t){return new Oo(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(Pl.exactMatch)}dialFilter(t){return this.listenFilter(t)}async dial(t,e){this.log.trace("dialing address: %a",t);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await mu({rtcConfiguration:await vn(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:t,dataChannelOptions:this.init.dataChannel,signal:e.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:e.onProgress}),i=new fr(this.components,{peerConnection:o,timeline:{open:Date.now()},remoteAddr:n,metrics:this.metrics?.dialerEvents}),a=await e.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,muxerFactory:s,onProgress:e.onProgress});return this._closeOnShutdown(o,i),a}async _onProtocol({connection:t,stream:e}){let n=AbortSignal.timeout(this.init.inboundConnectionTimeout??K0),o=new yr(await vn(this.init.rtcConfiguration)),s=new je(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await Iu({peerConnection:o,connection:t,stream:e,signal:n,log:this.log});await e.close({signal:n});let a=new fr(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(),e.abort(i),i}}_closeOnShutdown(t,e){let n=()=>{e.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection",o)})};this.shutdownController.signal.addEventListener("abort",n),t.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function gu(r){let t=r.toString().split(V0+"/");if(t.length!==2)throw new D("webrtc protocol was not present in multiaddr",Wt.ERR_INVALID_MULTIADDR);if(!t[0].includes(F0))throw new D("p2p-circuit protocol was not present in multiaddr",Wt.ERR_INVALID_MULTIADDR);let e=re(t[0]),o=re("/"+t[1]).getPeerId();if(o==null)throw new D("destination peer id was missing",Wt.ERR_INVALID_MULTIADDR);let s=e.protos().pop();if(s===void 0)throw new D("invalid multiaddr",Wt.ERR_INVALID_MULTIADDR);return s.name!=="p2p"&&(e=e.encapsulate(`/p2p/${o}`)),{baseAddr:e,peerId:lr(o)}}var qa={};xt(qa,{Ed25519PrivateKey:()=>Sr,Ed25519PublicKey:()=>Ln,generateKeyPair:()=>Xm,generateKeyPairFromSeed:()=>ef,unmarshalEd25519PrivateKey:()=>Ym,unmarshalEd25519PublicKey:()=>Zm});function Zt(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Ye(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function $0(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Gr(r,...t){if(!$0(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function xr(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ye(r.outputLen),Ye(r.blockLen)}function qr(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function _u(r,t){Gr(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var Mo=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var zr=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ae=(r,t)=>r<<32-t|r>>>t;var q2=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var W0=async()=>{};async function ku(r,t,e){let n=Date.now();for(let o=0;o<r;o++){e(o);let s=Date.now()-n;s>=0&&s<t||(await W0(),n+=s)}}function Cu(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function ce(r){return typeof r=="string"&&(r=Cu(r)),Gr(r),r}function Ta(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Gr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}var jr=class{clone(){return this._cloneInto()}},G0={}.toString;function Ru(r,t){if(t!==void 0&&G0.call(t)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,t)}function Vo(r){let t=n=>r().update(ce(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Er(r=32){if(Mo&&typeof Mo.getRandomValues=="function")return Mo.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function q0(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}var Tu=(r,t,e)=>r&t^~r&e,Nu=(r,t,e)=>r&t^r&e^t&e,Yr=class extends jr{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=zr(this.buffer)}update(t){qr(this);let{view:e,buffer:n,blockLen:o}=this;t=ce(t);let s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=zr(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){qr(this),_u(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[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++)e[f]=0;q0(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=zr(t),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:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.length=o,t.pos=a,t.finished=s,t.destroyed=i,o%e&&t.buffer.set(n),t}};var Fo=BigInt(4294967295),Na=BigInt(32);function Lu(r,t=!1){return t?{h:Number(r&Fo),l:Number(r>>Na&Fo)}:{h:Number(r>>Na&Fo)|0,l:Number(r&Fo)|0}}function j0(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=Lu(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var z0=(r,t)=>BigInt(r>>>0)<<Na|BigInt(t>>>0),Y0=(r,t,e)=>r>>>e,Z0=(r,t,e)=>r<<32-e|t>>>e,X0=(r,t,e)=>r>>>e|t<<32-e,J0=(r,t,e)=>r<<32-e|t>>>e,Q0=(r,t,e)=>r<<64-e|t>>>e-32,tm=(r,t,e)=>r>>>e-32|t<<64-e,em=(r,t)=>t,rm=(r,t)=>r,nm=(r,t,e)=>r<<e|t>>>32-e,om=(r,t,e)=>t<<e|r>>>32-e,sm=(r,t,e)=>t<<e-32|r>>>64-e,im=(r,t,e)=>r<<e-32|t>>>64-e;function am(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var cm=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),lm=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,um=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),fm=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,hm=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),dm=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var pm={fromBig:Lu,split:j0,toBig:z0,shrSH:Y0,shrSL:Z0,rotrSH:X0,rotrSL:J0,rotrBH:Q0,rotrBL:tm,rotr32H:em,rotr32L:rm,rotlSH:nm,rotlSL:om,rotlBH:sm,rotlBL:im,add:am,add3L:cm,add3H:lm,add4L:um,add4H:fm,add5H:dm,add5L:hm},Z=pm;var[mm,gm]=Z.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))),Ze=new Uint32Array(80),Xe=new Uint32Array(80),La=class extends Yr{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:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:p,Gh:y,Gl:m,Hh:h,Hl:d}=this;return[t,e,n,o,s,i,a,c,l,u,f,p,y,m,h,d]}set(t,e,n,o,s,i,a,c,l,u,f,p,y,m,h,d){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=p|0,this.Gh=y|0,this.Gl=m|0,this.Hh=h|0,this.Hl=d|0}process(t,e){for(let w=0;w<16;w++,e+=4)Ze[w]=t.getUint32(e),Xe[w]=t.getUint32(e+=4);for(let w=16;w<80;w++){let S=Ze[w-15]|0,x=Xe[w-15]|0,B=Z.rotrSH(S,x,1)^Z.rotrSH(S,x,8)^Z.shrSH(S,x,7),I=Z.rotrSL(S,x,1)^Z.rotrSL(S,x,8)^Z.shrSL(S,x,7),_=Ze[w-2]|0,N=Xe[w-2]|0,P=Z.rotrSH(_,N,19)^Z.rotrBH(_,N,61)^Z.shrSH(_,N,6),T=Z.rotrSL(_,N,19)^Z.rotrBL(_,N,61)^Z.shrSL(_,N,6),F=Z.add4L(I,T,Xe[w-7],Xe[w-16]),V=Z.add4H(F,B,P,Ze[w-7],Ze[w-16]);Ze[w]=V|0,Xe[w]=F|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:p,Fh:y,Fl:m,Gh:h,Gl:d,Hh:b,Hl:E}=this;for(let w=0;w<80;w++){let S=Z.rotrSH(f,p,14)^Z.rotrSH(f,p,18)^Z.rotrBH(f,p,41),x=Z.rotrSL(f,p,14)^Z.rotrSL(f,p,18)^Z.rotrBL(f,p,41),B=f&y^~f&h,I=p&m^~p&d,_=Z.add5L(E,x,I,gm[w],Xe[w]),N=Z.add5H(_,b,S,B,mm[w],Ze[w]),P=_|0,T=Z.rotrSH(n,o,28)^Z.rotrBH(n,o,34)^Z.rotrBH(n,o,39),F=Z.rotrSL(n,o,28)^Z.rotrBL(n,o,34)^Z.rotrBL(n,o,39),V=n&s^n&a^s&a,j=o&i^o&c^i&c;b=h|0,E=d|0,h=y|0,d=m|0,y=f|0,m=p|0,{h:f,l:p}=Z.add(l|0,u|0,N|0,P|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let v=Z.add3L(P,F,j);n=Z.add3H(v,N,T,V),o=v|0}({h:n,l:o}=Z.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Z.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Z.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Z.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:p}=Z.add(this.Eh|0,this.El|0,f|0,p|0),{h:y,l:m}=Z.add(this.Fh|0,this.Fl|0,y|0,m|0),{h,l:d}=Z.add(this.Gh|0,this.Gl|0,h|0,d|0),{h:b,l:E}=Z.add(this.Hh|0,this.Hl|0,b|0,E|0),this.set(n,o,s,i,a,c,l,u,f,p,y,m,h,d,b,E)}roundClean(){Ze.fill(0),Xe.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 _n=Vo(()=>new La);var $o={};xt($o,{abytes:()=>Zr,bitGet:()=>Am,bitLen:()=>vm,bitMask:()=>kn,bitSet:()=>Sm,bytesToHex:()=>Ce,bytesToNumberBE:()=>Re,bytesToNumberLE:()=>le,concatBytes:()=>Ne,createHmacDrbg:()=>Pa,ensureBytes:()=>it,equalBytes:()=>xm,hexToBytes:()=>vr,hexToNumber:()=>Ua,isBytes:()=>Je,numberToBytesBE:()=>Qe,numberToBytesLE:()=>Te,numberToHexUnpadded:()=>Ou,numberToVarBytesBE:()=>bm,utf8ToBytes:()=>Em,validateObject:()=>Xt});var Pu=BigInt(0),Ko=BigInt(1),ym=BigInt(2);function Je(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Zr(r){if(!Je(r))throw new Error("Uint8Array expected")}var wm=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Ce(r){Zr(r);let t="";for(let e=0;e<r.length;e++)t+=wm[r[e]];return t}function Ou(r){let t=r.toString(16);return t.length&1?`0${t}`:t}function Ua(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var ke={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Du(r){if(r>=ke._0&&r<=ke._9)return r-ke._0;if(r>=ke._A&&r<=ke._F)return r-(ke._A-10);if(r>=ke._a&&r<=ke._f)return r-(ke._a-10)}function vr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=Du(r.charCodeAt(s)),a=Du(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 Re(r){return Ua(Ce(r))}function le(r){return Zr(r),Ua(Ce(Uint8Array.from(r).reverse()))}function Qe(r,t){return vr(r.toString(16).padStart(t*2,"0"))}function Te(r,t){return Qe(r,t).reverse()}function bm(r){return vr(Ou(r))}function it(r,t,e){let n;if(typeof t=="string")try{n=vr(t)}catch(s){throw new Error(`${r} must be valid hex string, got "${t}". Cause: ${s}`)}else if(Je(t))n=Uint8Array.from(t);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(`${r} expected ${e} bytes, got ${o}`);return n}function Ne(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Zr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function xm(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function Em(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function vm(r){let t;for(t=0;r>Pu;r>>=Ko,t+=1);return t}function Am(r,t){return r>>BigInt(t)&Ko}function Sm(r,t,e){return r|(e?Ko:Pu)<<BigInt(t)}var kn=r=>(ym<<BigInt(r-1))-Ko,Da=r=>new Uint8Array(r),Uu=r=>Uint8Array.from(r);function Pa(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=Da(r),o=Da(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=Da())=>{o=a(Uu([0]),f),n=a(),f.length!==0&&(o=a(Uu([1]),f),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f<t;){n=a();let y=n.slice();p.push(y),f+=n.length}return Ne(...p)};return(f,p)=>{i(),c(f);let y;for(;!(y=p(l()));)c();return i(),y}}var Bm={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"||Je(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function Xt(r,t,e={}){let n=(o,s,i)=>{let a=Bm[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(e))n(o,s,!0);return r}var Bt=BigInt(0),lt=BigInt(1),Ar=BigInt(2),Im=BigInt(3),Oa=BigInt(4),Hu=BigInt(5),Mu=BigInt(8),_m=BigInt(9),km=BigInt(16);function tt(r,t){let e=r%t;return e>=Bt?e:t+e}function Ha(r,t,e){if(e<=Bt||t<Bt)throw new Error("Expected power/modulo > 0");if(e===lt)return Bt;let n=lt;for(;t>Bt;)t<&&(n=n*r%e),r=r*r%e,t>>=lt;return n}function at(r,t,e){let n=r;for(;t-- >Bt;)n*=n,n%=e;return n}function Wo(r,t){if(r===Bt||t<=Bt)throw new Error(`invert: expected positive integers, got n=${r} mod=${t}`);let e=tt(r,t),n=t,o=Bt,s=lt,i=lt,a=Bt;for(;e!==Bt;){let l=n/e,u=n%e,f=o-i*l,p=s-a*l;n=e,e=u,o=i,s=a,i=f,a=p}if(n!==lt)throw new Error("invert: does not exist");return tt(o,t)}function Cm(r){let t=(r-lt)/Ar,e,n,o;for(e=r-lt,n=0;e%Ar===Bt;e/=Ar,n++);for(o=Ar;o<r&&Ha(o,t,r)!==r-lt;o++);if(n===1){let i=(r+lt)/Oa;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=(e+lt)/Ar;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),e),f=a.pow(c,s),p=a.pow(c,e);for(;!a.eql(p,a.ONE);){if(a.eql(p,a.ZERO))return a.ZERO;let y=1;for(let h=a.sqr(p);y<l&&!a.eql(h,a.ONE);y++)h=a.sqr(h);let m=a.pow(u,lt<<BigInt(l-y-1));u=a.sqr(m),f=a.mul(f,m),p=a.mul(p,u),l=y}return f}}function Rm(r){if(r%Oa===Im){let t=(r+lt)/Oa;return function(n,o){let s=n.pow(o,t);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%Mu===Hu){let t=(r-Hu)/Mu;return function(n,o){let s=n.mul(o,Ar),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,Ar),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%km,Cm(r)}var Vu=(r,t)=>(tt(r,t)<)===lt,Tm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ma(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Tm.reduce((n,o)=>(n[o]="function",n),t);return Xt(r,e)}function Nm(r,t,e){if(e<Bt)throw new Error("Expected power > 0");if(e===Bt)return r.ONE;if(e===lt)return t;let n=r.ONE,o=t;for(;e>Bt;)e<&&(n=r.mul(n,o)),o=r.sqr(o),e>>=lt;return n}function Lm(r,t){let e=new Array(t.length),n=t.reduce((s,i,a)=>r.is0(i)?s:(e[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return t.reduceRight((s,i,a)=>r.is0(i)?s:(e[a]=r.mul(s,e[a]),r.mul(s,i)),o),e}function Va(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Go(r,t,e=!1,n={}){if(r<=Bt)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=Va(r,t);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=Rm(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:kn(o),ZERO:Bt,ONE:lt,create:c=>tt(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return Bt<=c&&c<r},is0:c=>c===Bt,isOdd:c=>(c<)===lt,neg:c=>tt(-c,r),eql:(c,l)=>c===l,sqr:c=>tt(c*c,r),add:(c,l)=>tt(c+l,r),sub:(c,l)=>tt(c-l,r),mul:(c,l)=>tt(c*l,r),pow:(c,l)=>Nm(a,c,l),div:(c,l)=>tt(c*Wo(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Wo(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>Lm(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?Te(c,s):Qe(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return e?le(c):Re(c)}});return Object.freeze(a)}function Fu(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Fa(r){let t=Fu(r);return t+Math.ceil(t/2)}function Ku(r,t,e=!1){let n=r.length,o=Fu(t),s=Fa(t);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=e?Re(r):le(r),a=tt(i,t-lt)+lt;return e?Te(a,o):Qe(a,o)}var Um=BigInt(0),Ka=BigInt(1);function qo(r,t){let e=(o,s)=>{let i=s.negate();return o?i:s},n=o=>{let s=Math.ceil(t/o)+1,i=2**(o-1);return{windows:s,windowSize:i}};return{constTimeNegate:e,unsafeLadder(o,s){let i=r.ZERO,a=o;for(;s>Um;)s&Ka&&(i=i.add(a)),a=a.double(),s>>=Ka;return i},precomputeWindow(o,s){let{windows:i,windowSize:a}=n(s),c=[],l=o,u=l;for(let f=0;f<i;f++){u=l,c.push(u);for(let p=1;p<a;p++)u=u.add(l),c.push(u);l=u.double()}return c},wNAF(o,s,i){let{windows:a,windowSize:c}=n(o),l=r.ZERO,u=r.BASE,f=BigInt(2**o-1),p=2**o,y=BigInt(o);for(let m=0;m<a;m++){let h=m*c,d=Number(i&f);i>>=y,d>c&&(d-=p,i+=Ka);let b=h,E=h+Math.abs(d)-1,w=m%2!==0,S=d<0;d===0?u=u.add(e(w,s[b])):l=l.add(e(S,s[E]))}return{p:l,f:u}},wNAFCached(o,s,i,a){let c=o._WINDOW_SIZE||1,l=s.get(o);return l||(l=this.precomputeWindow(o,c),c!==1&&s.set(o,a(l))),this.wNAF(c,l,i)}}}function Cn(r){return Ma(r.Fp),Xt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Va(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var ue=BigInt(0),jt=BigInt(1),jo=BigInt(2),Pm=BigInt(8),Om={zip215:!0};function Hm(r){let t=Cn(r);return Xt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function $u(r){let t=Hm(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=jo<<BigInt(a*8)-jt,u=e.create,f=t.uvRatio||((A,g)=>{try{return{isValid:!0,value:e.sqrt(A*e.inv(g))}}catch{return{isValid:!1,value:ue}}}),p=t.adjustScalarBytes||(A=>A),y=t.domain||((A,g,k)=>{if(g.length||k)throw new Error("Contexts/pre-hash are not supported");return A}),m=A=>typeof A=="bigint"&&ue<A,h=(A,g)=>m(A)&&m(g)&&A<g,d=A=>A===ue||h(A,l);function b(A,g){if(h(A,g))return A;throw new Error(`Expected valid scalar < ${g}, got ${typeof A} ${A}`)}function E(A){return A===ue?A:b(A,n)}let w=new Map;function S(A){if(!(A instanceof x))throw new Error("ExtendedPoint expected")}class x{constructor(g,k,R,L){if(this.ex=g,this.ey=k,this.ez=R,this.et=L,!d(g))throw new Error("x required");if(!d(k))throw new Error("y required");if(!d(R))throw new Error("z required");if(!d(L))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(g){if(g instanceof x)throw new Error("extended point not allowed");let{x:k,y:R}=g||{};if(!d(k)||!d(R))throw new Error("invalid affine point");return new x(k,R,jt,u(k*R))}static normalizeZ(g){let k=e.invertBatch(g.map(R=>R.ez));return g.map((R,L)=>R.toAffine(k[L])).map(x.fromAffine)}_setWindowSize(g){this._WINDOW_SIZE=g,w.delete(this)}assertValidity(){let{a:g,d:k}=t;if(this.is0())throw new Error("bad point: ZERO");let{ex:R,ey:L,ez:$,et:W}=this,Y=u(R*R),q=u(L*L),z=u($*$),st=u(z*z),nt=u(Y*g),_t=u(z*u(nt+q)),kt=u(st+u(k*u(Y*q)));if(_t!==kt)throw new Error("bad point: equation left != right (1)");let bt=u(R*L),Lt=u($*W);if(bt!==Lt)throw new Error("bad point: equation left != right (2)")}equals(g){S(g);let{ex:k,ey:R,ez:L}=this,{ex:$,ey:W,ez:Y}=g,q=u(k*Y),z=u($*L),st=u(R*Y),nt=u(W*L);return q===z&&st===nt}is0(){return this.equals(x.ZERO)}negate(){return new x(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:g}=t,{ex:k,ey:R,ez:L}=this,$=u(k*k),W=u(R*R),Y=u(jo*u(L*L)),q=u(g*$),z=k+R,st=u(u(z*z)-$-W),nt=q+W,_t=nt-Y,kt=q-W,bt=u(st*_t),Lt=u(nt*kt),ve=u(st*kt),ar=u(_t*nt);return new x(bt,Lt,ar,ve)}add(g){S(g);let{a:k,d:R}=t,{ex:L,ey:$,ez:W,et:Y}=this,{ex:q,ey:z,ez:st,et:nt}=g;if(k===BigInt(-1)){let Dc=u(($-L)*(z+q)),Uc=u(($+L)*(z-q)),Ys=u(Uc-Dc);if(Ys===ue)return this.double();let Pc=u(W*jo*nt),Oc=u(Y*jo*st),Hc=Oc+Pc,Mc=Uc+Dc,Vc=Oc-Pc,Jh=u(Hc*Ys),Qh=u(Mc*Vc),td=u(Hc*Vc),ed=u(Ys*Mc);return new x(Jh,Qh,ed,td)}let _t=u(L*q),kt=u($*z),bt=u(Y*R*nt),Lt=u(W*st),ve=u((L+$)*(q+z)-_t-kt),ar=Lt-bt,hn=Lt+bt,Lc=u(kt-k*_t),zh=u(ve*ar),Yh=u(hn*Lc),Zh=u(ve*Lc),Xh=u(ar*hn);return new x(zh,Yh,Xh,Zh)}subtract(g){return this.add(g.negate())}wNAF(g){return _.wNAFCached(this,w,g,x.normalizeZ)}multiply(g){let{p:k,f:R}=this.wNAF(b(g,n));return x.normalizeZ([k,R])[0]}multiplyUnsafe(g){let k=E(g);return k===ue?I:this.equals(I)||k===jt?this:this.equals(B)?this.wNAF(k).p:_.unsafeLadder(this,k)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return _.unsafeLadder(this,n).is0()}toAffine(g){let{ex:k,ey:R,ez:L}=this,$=this.is0();g==null&&(g=$?Pm:e.inv(L));let W=u(k*g),Y=u(R*g),q=u(L*g);if($)return{x:ue,y:jt};if(q!==jt)throw new Error("invZ was invalid");return{x:W,y:Y}}clearCofactor(){let{h:g}=t;return g===jt?this:this.multiplyUnsafe(g)}static fromHex(g,k=!1){let{d:R,a:L}=t,$=e.BYTES;g=it("pointHex",g,$);let W=g.slice(),Y=g[$-1];W[$-1]=Y&-129;let q=le(W);q===ue||(k?b(q,l):b(q,e.ORDER));let z=u(q*q),st=u(z-jt),nt=u(R*z-L),{isValid:_t,value:kt}=f(st,nt);if(!_t)throw new Error("Point.fromHex: invalid y coordinate");let bt=(kt&jt)===jt,Lt=(Y&128)!==0;if(!k&&kt===ue&&Lt)throw new Error("Point.fromHex: x=0 and x_0=1");return Lt!==bt&&(kt=u(-kt)),x.fromAffine({x:kt,y:q})}static fromPrivateKey(g){return T(g).point}toRawBytes(){let{x:g,y:k}=this.toAffine(),R=Te(k,e.BYTES);return R[R.length-1]|=g&jt?128:0,R}toHex(){return Ce(this.toRawBytes())}}x.BASE=new x(t.Gx,t.Gy,jt,u(t.Gx*t.Gy)),x.ZERO=new x(ue,jt,jt,ue);let{BASE:B,ZERO:I}=x,_=qo(x,a*8);function N(A){return tt(A,n)}function P(A){return N(le(A))}function T(A){let g=a;A=it("private key",A,g);let k=it("hashed private key",s(A),2*g),R=p(k.slice(0,g)),L=k.slice(g,2*g),$=P(R),W=B.multiply($),Y=W.toRawBytes();return{head:R,prefix:L,scalar:$,point:W,pointBytes:Y}}function F(A){return T(A).pointBytes}function V(A=new Uint8Array,...g){let k=Ne(...g);return P(s(y(k,it("context",A),!!o)))}function j(A,g,k={}){A=it("message",A),o&&(A=o(A));let{prefix:R,scalar:L,pointBytes:$}=T(g),W=V(k.context,R,A),Y=B.multiply(W).toRawBytes(),q=V(k.context,Y,$,A),z=N(W+q*L);E(z);let st=Ne(Y,Te(z,e.BYTES));return it("result",st,a*2)}let v=Om;function C(A,g,k,R=v){let{context:L,zip215:$}=R,W=e.BYTES;A=it("signature",A,2*W),g=it("message",g),o&&(g=o(g));let Y=le(A.slice(W,2*W)),q,z,st;try{q=x.fromHex(k,$),z=x.fromHex(A.slice(0,W),$),st=B.multiplyUnsafe(Y)}catch{return!1}if(!$&&q.isSmallOrder())return!1;let nt=V(L,z.toRawBytes(),q.toRawBytes(),g);return z.add(q.multiplyUnsafe(nt)).subtract(st).clearCofactor().equals(x.ZERO)}return B._setWindowSize(8),{CURVE:t,getPublicKey:F,sign:j,verify:C,ExtendedPoint:x,utils:{getExtendedPublicKey:T,randomPrivateKey:()=>i(e.BYTES),precompute(A=8,g=x.BASE){return g._setWindowSize(A),g.multiply(BigInt(3)),g}}}}var Rn=BigInt(0),$a=BigInt(1);function Mm(r){return Xt(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function Wu(r){let t=Mm(r),{P:e}=t,n=w=>tt(w,e),o=t.montgomeryBits,s=Math.ceil(o/8),i=t.nByteLength,a=t.adjustScalarBytes||(w=>w),c=t.powPminus2||(w=>Ha(w,e-BigInt(2),e));function l(w,S,x){let B=n(w*(S-x));return S=n(S-B),x=n(x+B),[S,x]}function u(w){if(typeof w=="bigint"&&Rn<=w&&w<e)return w;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let f=(t.a-BigInt(2))/BigInt(4);function p(w,S){let x=u(w),B=u(S),I=x,_=$a,N=Rn,P=x,T=$a,F=Rn,V;for(let v=BigInt(o-1);v>=Rn;v--){let C=B>>v&$a;F^=C,V=l(F,_,P),_=V[0],P=V[1],V=l(F,N,T),N=V[0],T=V[1],F=C;let O=_+N,A=n(O*O),g=_-N,k=n(g*g),R=A-k,L=P+T,$=P-T,W=n($*O),Y=n(L*g),q=W+Y,z=W-Y;P=n(q*q),T=n(I*n(z*z)),_=n(A*k),N=n(R*(A+n(f*R)))}V=l(F,_,P),_=V[0],P=V[1],V=l(F,N,T),N=V[0],T=V[1];let j=c(N);return n(_*j)}function y(w){return Te(n(w),s)}function m(w){let S=it("u coordinate",w,s);return i===32&&(S[31]&=127),le(S)}function h(w){let S=it("scalar",w),x=S.length;if(x!==s&&x!==i)throw new Error(`Expected ${s} or ${i} bytes, got ${x}`);return le(a(S))}function d(w,S){let x=m(S),B=h(w),I=p(x,B);if(I===Rn)throw new Error("Invalid private or public key received");return y(I)}let b=y(t.Gu);function E(w){return d(w,b)}return{scalarMult:d,scalarMultBase:E,getSharedSecret:(w,S)=>d(w,S),getPublicKey:w=>E(w),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:b}}var Tn=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Gu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),bv=BigInt(0),Vm=BigInt(1),qu=BigInt(2),Fm=BigInt(3),Km=BigInt(5),$m=BigInt(8);function ju(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=Tn,a=r*r%s*r%s,c=at(a,qu,s)*a%s,l=at(c,Vm,s)*r%s,u=at(l,Km,s)*l%s,f=at(u,t,s)*u%s,p=at(f,e,s)*f%s,y=at(p,n,s)*p%s,m=at(y,o,s)*y%s,h=at(m,o,s)*y%s,d=at(h,t,s)*u%s;return{pow_p_5_8:at(d,qu,s)*r%s,b2:a}}function zu(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Wm(r,t){let e=Tn,n=tt(t*t*t,e),o=tt(n*n*t,e),s=ju(r*o).pow_p_5_8,i=tt(r*n*s,e),a=tt(t*i*i,e),c=i,l=tt(i*Gu,e),u=a===r,f=a===tt(-r,e),p=a===tt(-r*Gu,e);return u&&(i=c),(f||p)&&(i=l),Vu(i,e)&&(i=tt(-i,e)),{isValid:u||f,value:i}}var Gm=Go(Tn,void 0,!0),qm={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Gm,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:$m,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:_n,randomBytes:Er,adjustScalarBytes:zu,uvRatio:Wm},Xr=$u(qm);var Nn=Wu({P:Tn,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let t=Tn,{pow_p_5_8:e,b2:n}=ju(r);return tt(at(e,Fm,t)*n,t)},adjustScalarBytes:zu,randomBytes:Er});var Jr=32,Le=64,zo=32;function Yu(){let r=Xr.utils.randomPrivateKey(),t=Xr.getPublicKey(r);return{privateKey:Qu(r,t),publicKey:t}}function Zu(r){if(r.length!==zo)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let t=r,e=Xr.getPublicKey(t);return{privateKey:Qu(t,e),publicKey:e}}function Xu(r,t){let e=r.subarray(0,zo);return Xr.sign(t instanceof Uint8Array?t:t.subarray(),e)}function Ju(r,t,e){return Xr.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}function Qu(r,t){let e=new Uint8Array(Le);for(let n=0;n<zo;n++)e[n]=r[n],e[zo+n]=t[n];return e}var Ot={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw Object.assign(new Error("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"),{code:"ERR_MISSING_WEB_CRYPTO"});return t}};var Wa={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function tf(r){let t=r?.algorithm??"AES-GCM",e=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=Ot.get();e*=8;async function c(f,p){let y=a.getRandomValues(new Uint8Array(s)),m=a.getRandomValues(new Uint8Array(n)),h={name:t,iv:m};typeof p=="string"&&(p=J(p));let d;if(p.length===0){d=await a.subtle.importKey("jwk",Wa,{name:"AES-GCM"},!0,["encrypt"]);try{let E={name:"PBKDF2",salt:y,iterations:i,hash:{name:o}},w=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);d=await a.subtle.deriveKey(E,w,{name:t,length:e},!0,["encrypt"])}catch{d=await a.subtle.importKey("jwk",Wa,{name:"AES-GCM"},!0,["encrypt"])}}else{let E={name:"PBKDF2",salt:y,iterations:i,hash:{name:o}},w=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);d=await a.subtle.deriveKey(E,w,{name:t,length:e},!0,["encrypt"])}let b=await a.subtle.encrypt(h,d,f);return yt([y,h.iv,new Uint8Array(b)])}async function l(f,p){let y=f.subarray(0,s),m=f.subarray(s,s+n),h=f.subarray(s+n),d={name:t,iv:m};typeof p=="string"&&(p=J(p));let b;if(p.length===0)try{let w={name:"PBKDF2",salt:y,iterations:i,hash:{name:o}},S=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);b=await a.subtle.deriveKey(w,S,{name:t,length:e},!0,["decrypt"])}catch{b=await a.subtle.importKey("jwk",Wa,{name:"AES-GCM"},!0,["decrypt"])}else{let w={name:"PBKDF2",salt:y,iterations:i,hash:{name:o}},S=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);b=await a.subtle.deriveKey(w,S,{name:t,length:e},!0,["decrypt"])}let E=await a.subtle.decrypt(d,b,h);return new Uint8Array(E)}return{encrypt:c,decrypt:l}}async function Qr(r,t){let n=await tf().encrypt(r,t);return li.encode(n)}var ut;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(ut||(ut={}));var Ga;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(Ga||(Ga={}));(function(r){r.codec=()=>gr(Ga)})(ut||(ut={}));var ye;(function(r){let t;r.codec=()=>(t==null&&(t=ie((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ut.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:o.Type=ut.codec().decode(e);break;case 2:o.Data=e.bytes();break;default:e.skipType(i&7);break}}return o})),t),r.encode=e=>se(e,r.codec()),r.decode=e=>oe(e,r.codec())})(ye||(ye={}));var we;(function(r){let t;r.codec=()=>(t==null&&(t=ie((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ut.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:o.Type=ut.codec().decode(e);break;case 2:o.Data=e.bytes();break;default:e.skipType(i&7);break}}return o})),t),r.encode=e=>se(e,r.codec()),r.decode=e=>oe(e,r.codec())})(we||(we={}));var Ln=class{_key;constructor(t){this._key=tn(t,Jr)}verify(t,e){return Ju(this._key,e,t)}marshal(){return this._key}get bytes(){return ye.encode({Type:ut.Ed25519,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}hash(){let t=Ct.digest(this.bytes);return Zt(t)?t.then(({bytes:e})=>e):t.bytes}},Sr=class{_key;_publicKey;constructor(t,e){this._key=tn(t,Le),this._publicKey=tn(e,Jr)}sign(t){return Xu(this._key,t)}get public(){return new Ln(this._publicKey)}marshal(){return this._key}get bytes(){return we.encode({Type:ut.Ed25519,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}async hash(){let t=Ct.digest(this.bytes),e;return Zt(t)?{bytes:e}=await t:e=t.bytes,e}async id(){let t=Be.digest(this.public.bytes);return dt.encode(t.bytes).substring(1)}async export(t,e="libp2p-key"){if(e==="libp2p-key")return Qr(this.bytes,t);throw new D(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Ym(r){if(r.length>Le){r=tn(r,Le+Jr);let n=r.subarray(0,Le),o=r.subarray(Le,r.length);return new Sr(n,o)}r=tn(r,Le);let t=r.subarray(0,Le),e=r.subarray(Jr);return new Sr(t,e)}function Zm(r){return r=tn(r,Jr),new Ln(r)}async function Xm(){let{privateKey:r,publicKey:t}=Yu();return new Sr(r,t)}async function ef(r){let{privateKey:t,publicKey:e}=Zu(r);return new Sr(t,e)}function tn(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new D(`Key must be a Uint8Array of length ${t}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}var rc={};xt(rc,{MAX_RSA_KEY_SIZE:()=>Wn,RsaPrivateKey:()=>sn,RsaPublicKey:()=>$n,fromJwk:()=>Sg,generateKeyPair:()=>Bg,unmarshalRsaPrivateKey:()=>tc,unmarshalRsaPublicKey:()=>Ag});function Br(r){if(isNaN(r)||r<=0)throw new D("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Er(r)}var or={};xt(or,{exportToPem:()=>wg,importFromPem:()=>bg,jwkToPkcs1:()=>pg,jwkToPkix:()=>gg,pkcs1ToJwk:()=>dg,pkixToJwk:()=>mg});var Zo=class extends jr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,xr(t);let n=ce(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(t){return qr(this),this.iHash.update(t),this}digestInto(t){qr(this),Gr(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},tr=(r,t,e)=>new Zo(r,t).update(e).digest();tr.create=(r,t)=>new Zo(r,t);function Jm(r,t,e,n){xr(r);let o=Ru({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(Ye(s),Ye(i),Ye(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=ce(t),l=ce(e),u=new Uint8Array(i),f=tr.create(r,c),p=f._cloneInto().update(l);return{c:s,dkLen:i,asyncTick:a,DK:u,PRF:f,PRFSalt:p}}function Qm(r,t,e,n,o){return r.destroy(),t.destroy(),n&&n.destroy(),o.fill(0),e}async function ja(r,t,e,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:l}=Jm(r,t,e,n),u,f=new Uint8Array(4),p=zr(f),y=new Uint8Array(c.outputLen);for(let m=1,h=0;h<s;m++,h+=c.outputLen){let d=a.subarray(h,h+c.outputLen);p.setInt32(0,m,!1),(u=l._cloneInto(u)).update(f).digestInto(y),d.set(y.subarray(0,d.length)),await ku(o-1,i,()=>{c._cloneInto(u).update(y).digestInto(y);for(let b=0;b<d.length;b++)d[b]^=y[b]})}return Qm(c,l,a,u,y)}var X=$c(rf());function Ir(r,t){let e=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)e+=r[r.length-1-n]*Math.pow(2,t*n);return e}function er(r,t,e=-1){let n=e,o=r,s=0,i=Math.pow(2,t);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*t);l[s-u-1]=Math.floor(o/f),o-=l[s-u-1]*f}return c}i*=Math.pow(2,t)}return new ArrayBuffer(0)}function Qo(...r){let t=0,e=0;for(let s of r)t+=s.length;let n=new ArrayBuffer(t),o=new Uint8Array(n);for(let s of r)o.set(s,e),e+=s.length;return o}function Ya(){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 t=new ArrayBuffer(this.valueHex.byteLength),e=new Uint8Array(t);for(let a=0;a<this.valueHex.byteLength;a++)e[a]=0;e[0]=r[0]&128;let n=Ir(e,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,Ir(s,8)-n}function nf(r){let t=r<0?r*-1:r,e=128;for(let n=1;n<8;n++){if(t<=e){if(r<0){let i=e-t,a=er(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=er(t,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}e*=Math.pow(2,8)}return new ArrayBuffer(0)}function of(r,t){if(r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<e.length;o++)if(e[o]!==n[o])return!1;return!0}function Ft(r,t){let e=r.toString(10);if(t<e.length)return"";let n=t-e.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(e)}var jv=Math.log(2);function ts(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Za(r){let t=0,e=0;for(let o=0;o<r.length;o++){let s=r[o];t+=s.byteLength}let n=new Uint8Array(t);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),e),e+=s.byteLength}return n.buffer}function He(r,t,e,n){return t instanceof Uint8Array?t.byteLength?e<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):t.byteLength-e-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 Un=class{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return Za(this.items)}},Dn=[new Uint8Array([1])],sf="0123456789";var nn="",he=new ArrayBuffer(0),Xa=new Uint8Array(0),Pn="EndOfContent",cf="OCTET STRING",lf="BIT STRING";function Me(r){var t;return t=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?X.BufferSourceConverter.toUint8Array(s.valueHex):Xa}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(!He(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",he)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:X.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var Ue=class{constructor({blockLength:t=0,error:e=nn,warnings:n=[],valueBeforeDecode:o=Xa}={}){this.blockLength=t,this.error=e,this.warnings=n,this.valueBeforeDecodeView=X.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(t){this.valueBeforeDecodeView=new Uint8Array(t)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:X.Convert.ToHex(this.valueBeforeDecodeView)}}};Ue.NAME="baseBlock";var Pt=class extends Ue{fromBER(t,e,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(t,e){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Pt.NAME="valueBlock";var es=class extends Me(Ue){constructor({idBlock:t={}}={}){var e,n,o,s;super(),t?(this.isHexOnly=(e=t.isHexOnly)!==null&&e!==void 0?e:!1,this.valueHexView=t.valueHex?X.BufferSourceConverter.toUint8Array(t.valueHex):Xa,this.tagClass=(n=t.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=t.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=t.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(t=!1){let e=0;switch(this.tagClass){case 1:e|=0;break;case 2:e|=64;break;case 3:e|=128;break;case 4:e|=192;break;default:return this.error="Unknown tag class",he}if(this.isConstructed&&(e|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!t){let s=this.tagNumber;s&=31,e|=s,o[0]=e}return o.buffer}if(!this.isHexOnly){let o=er(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=e|31,!t){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]=e|31,!t){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(t,e,n){let o=X.BufferSourceConverter.toUint8Array(t);if(!He(this,o,e,n))return-1;let s=o.subarray(e,e+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 p=new Uint8Array(u);for(let y=0;y<l.length;y++)p[y]=l[y];l=this.valueHexView=new Uint8Array(u)}}this.blockLength=c+1,l[c-1]=s[c]&127;let f=new Uint8Array(c);for(let p=0;p<c;p++)f[p]=l[p];l=this.valueHexView=new Uint8Array(c),l.set(f),this.blockLength<=9?this.tagNumber=Ir(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 e+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};es.NAME="identificationBlock";var rs=class extends Ue{constructor({lenBlock:t={}}={}){var e,n,o;super(),this.isIndefiniteForm=(e=t.isIndefiniteForm)!==null&&e!==void 0?e:!1,this.longFormUsed=(n=t.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=t.length)!==null&&o!==void 0?o:0}fromBER(t,e,n){let o=X.BufferSourceConverter.toUint8Array(t);if(!He(this,o,e,n))return-1;let s=o.subarray(e,e+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,e+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,e+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=e+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Ir(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,e+this.blockLength}toBER(t=!1){let e,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=128),e;if(this.longFormUsed){let o=er(this.length,8);if(o.byteLength>127)return this.error="Too big length",he;if(e=new ArrayBuffer(o.byteLength+1),t)return e;let s=new Uint8Array(o);n=new Uint8Array(e),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return e}return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=this.length),e}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};rs.NAME="lengthBlock";var H={},Tt=class extends Ue{constructor({name:t=nn,optional:e=!1,primitiveSchema:n,...o}={},s){super(o),this.name=t,this.optional=e,n&&(this.primitiveSchema=n),this.idBlock=new es(o),this.lenBlock=new rs(o),this.valueBlock=s?new s(o):new Pt(o)}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,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(t,e){let n=e||new Un;e||uf(this);let o=this.idBlock.toBER(t);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(t,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(t);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(t);n.write(i),n.write(s)}return e?he:n.final()}toJSON(){let t={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(t="ascii"){return t==="ascii"?this.onAsciiEncoding():X.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${X.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(t){if(this===t)return!0;if(!(t instanceof this.constructor))return!1;let e=this.toBER(),n=t.toBER();return of(e,n)}};Tt.NAME="BaseBlock";function uf(r){if(r instanceof H.Constructed)for(let t of r.valueBlock.value)uf(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ns=class extends Tt{constructor({value:t=nn,...e}={},n){super(e,n),t&&this.fromString(t)}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,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}'`}};ns.NAME="BaseStringBlock";var os=class extends Me(Pt){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};os.NAME="PrimitiveValueBlock";var ff,ss=class extends Tt{constructor(t={}){super(t,os),this.idBlock.isConstructed=!1}};ff=ss;H.Primitive=ff;ss.NAME="PRIMITIVE";function cg(r,t){if(r instanceof t)return r;let e=new t;return e.idBlock=r.idBlock,e.lenBlock=r.lenBlock,e.warnings=r.warnings,e.valueBeforeDecodeView=r.valueBeforeDecodeView,e}function Hs(r,t=0,e=r.length){let n=t,o=new Tt({},Pt),s=new Ue;if(!He(s,r,t,e))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(t,t+e).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,t,e);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(t=a,e-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,t,e),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(t=a,e-=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=Tt;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=H.EndOfContent;break;case 1:c=H.Boolean;break;case 2:c=H.Integer;break;case 3:c=H.BitString;break;case 4:c=H.OctetString;break;case 5:c=H.Null;break;case 6:c=H.ObjectIdentifier;break;case 10:c=H.Enumerated;break;case 12:c=H.Utf8String;break;case 13:c=H.RelativeObjectIdentifier;break;case 14:c=H.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=H.Sequence;break;case 17:c=H.Set;break;case 18:c=H.NumericString;break;case 19:c=H.PrintableString;break;case 20:c=H.TeletexString;break;case 21:c=H.VideotexString;break;case 22:c=H.IA5String;break;case 23:c=H.UTCTime;break;case 24:c=H.GeneralizedTime;break;case 25:c=H.GraphicString;break;case 26:c=H.VisibleString;break;case 27:c=H.GeneralString;break;case 28:c=H.UniversalString;break;case 29:c=H.CharacterString;break;case 30:c=H.BmpString;break;case 31:c=H.DATE;break;case 32:c=H.TimeOfDay;break;case 33:c=H.DateTime;break;case 34:c=H.Duration;break;default:{let l=o.idBlock.isConstructed?new H.Constructed:new H.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?H.Constructed:H.Primitive}return o=cg(o,c),a=o.fromBER(r,t,o.lenBlock.isIndefiniteForm?e:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function on(r){if(!r.byteLength){let t=new Tt({},Pt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return Hs(X.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function lg(r,t){return r?1:t}var be=class extends Pt{constructor({value:t=[],isIndefiniteForm:e=!1,...n}={}){super(n),this.value=t,this.isIndefiniteForm=e}fromBER(t,e,n){let o=X.BufferSourceConverter.toUint8Array(t);if(!He(this,o,e,n))return-1;if(this.valueBeforeDecodeView=o.subarray(e,e+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),e;let s=e;for(;lg(this.isIndefiniteForm,n)>0;){let i=Hs(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===Pn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Pn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(t,e){let n=e||new Un;for(let o=0;o<this.value.length;o++)this.value[o].toBER(t,n);return e?he:n.final()}toJSON(){let t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let e of this.value)t.value.push(e.toJSON());return t}};be.NAME="ConstructedValueBlock";var hf,rr=class extends Tt{constructor(t={}){super(t,be),this.idBlock.isConstructed=!0}fromBER(t,e,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(t,e,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 t=[];for(let n of this.valueBlock.value)t.push(n.toString("ascii").split(`
|
3
3
|
`).map(o=>` ${o}`).join(`
|
4
4
|
`));let e=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return t.length?`${e} :
|
5
5
|
${t.join(`
|
6
6
|
`)}`:`${e} :`}};hf=rr;H.Constructed=hf;rr.NAME="CONSTRUCTED";var is=class extends Pt{fromBER(t,e,n){return e}toBER(t){return he}};is.override="EndOfContentValueBlock";var df,as=class extends Tt{constructor(t={}){super(t,is),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};df=as;H.EndOfContent=df;as.NAME=Pn;var pf,nr=class extends Tt{constructor(t={}){super(t,Pt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(t,e,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,e+n>t.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):e+n}toBER(t,e){let n=new ArrayBuffer(2);if(!t){let o=new Uint8Array(n);o[0]=5,o[1]=0}return e&&e.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};pf=nr;H.Null=pf;nr.NAME="NULL";var cs=class extends Me(Pt){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=X.BufferSourceConverter.toUint8Array(e.valueHex):this.valueHexView=new Uint8Array(1),t&&(this.value=t)}get value(){for(let t of this.valueHexView)if(t>0)return!0;return!1}set value(t){this.valueHexView[0]=t?255:0}fromBER(t,e,n){let o=X.BufferSourceConverter.toUint8Array(t);return He(this,o,e,n)?(this.valueHexView=o.subarray(e,e+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Ya.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};cs.NAME="BooleanValueBlock";var mf,ls=class extends Tt{constructor(t={}){super(t,cs),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};mf=ls;H.Boolean=mf;ls.NAME="BOOLEAN";var us=class extends Me(be){constructor({isConstructed:t=!1,...e}={}){super(e),this.isConstructed=t}fromBER(t,e,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=be.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===Pn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==cf)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(t,e,n),this.blockLength=n;return o}toBER(t,e){return this.isConstructed?be.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};us.NAME="OctetStringValueBlock";var gf,Pe=class r extends Tt{constructor({idBlock:t={},lenBlock:e={},...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,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},us),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(t,e,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),e;if(!this.valueBlock.isConstructed){let s=(t instanceof ArrayBuffer?new Uint8Array(t):t).subarray(e,e+n);try{if(s.byteLength){let i=Hs(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(t,e,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?rr.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${X.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let t=[];for(let e of this.valueBlock.value)e instanceof r&&t.push(e.valueBlock.valueHexView);return X.BufferSourceConverter.concat(t)}};gf=Pe;H.OctetString=gf;Pe.NAME=cf;var fs=class extends Me(be){constructor({unusedBits:t=0,isConstructed:e=!1,...n}={}){super(n),this.unusedBits=t,this.isConstructed=e,this.blockLength=this.valueHexView.byteLength}fromBER(t,e,n){if(!n)return e;let o=-1;if(this.isConstructed){if(o=be.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===Pn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==lf)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=X.BufferSourceConverter.toUint8Array(t);if(!He(this,s,e,n))return-1;let i=s.subarray(e,e+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=Hs(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,e+n}toBER(t,e){if(this.isConstructed)return be.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return he;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}}};fs.NAME="BitStringValueBlock";var yf,rn=class extends Tt{constructor({idBlock:t={},lenBlock:e={},...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,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},fs),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(t,e,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(t,e,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return rr.prototype.onAsciiEncoding.call(this);{let t=[],e=this.valueBlock.valueHexView;for(let o of e)t.push(o.toString(2).padStart(8,"0"));let n=t.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};yf=rn;H.BitString=yf;rn.NAME=lf;var wf;function ug(r,t){let e=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(t),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 p=u;p>=0;p--,f++){switch(!0){case f<a.length:l=s[i-f]+a[c-f]+e[0];break;default:l=s[i-f]+e[0]}switch(e[0]=l/10,!0){case f>=s.length:s=Qo(new Uint8Array([l%10]),s);break;default:s[i-f]=l%10}}return e[0]>0&&(s=Qo(e,s)),s}function af(r){if(r>=Dn.length)for(let t=Dn.length;t<=r;t++){let e=new Uint8Array([0]),n=Dn[t-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+e[0]]);e[0]=s[0]/10,n[o]=s[0]%10}e[0]>0&&(n=Qo(e,n)),Dn.push(n)}return Dn[r]}function fg(r,t){let e=0,n=new Uint8Array(r),o=new Uint8Array(t),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]-e,!0){case l<0:e=1,s[i-u]=l+10;break;default:e=0,s[i-u]=l}if(e>0)for(let f=i-c+1;f>=0;f--,u++)if(l=s[i-u]-e,l<0)e=1,s[i-u]=l+10;else{e=0,s[i-u]=l;break}return s.slice()}var On=class extends Me(Pt){constructor({value:t,...e}={}){super(e),this._valueDec=0,e.valueHex&&this.setValueHex(),t!==void 0&&(this.valueDec=t)}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=Ya.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(nf(t))}get valueDec(){return this._valueDec}fromDER(t,e,n,o=0){let s=this.fromBER(t,e,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(t=!1){let e=this.valueHexView;switch(!0){case(e[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(e,1),this.valueHexView=n}break;case(e[0]===0&&(e[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(t)}fromBER(t,e,n){let o=super.fromBER(t,e,n);return o===-1||this.setValueHex(),o}toBER(t){return t?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let t=this.valueHexView.length*8-1,e=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 t:e=fg(af(n),e),i="-";break;default:e=ug(e,af(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(i+=sf.charAt(e[c]));return a===!1&&(i+=sf.charAt(0)),i}};wf=On;On.NAME="IntegerValueBlock";Object.defineProperty(wf.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var bf,wt=class r extends Tt{constructor(t={}){super(t,On),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return ts(),BigInt(this.valueBlock.toString())}static fromBigInt(t){ts();let e=BigInt(t),n=new Un,o=e.toString(16).replace(/^-/,""),s=new Uint8Array(X.Convert.FromHex(o));if(e<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${X.Convert.ToHex(a)}`)+e,u=X.BufferSourceConverter.toUint8Array(X.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 t=new r({valueHex:this.valueBlock.valueHexView});return t.valueBlock.toDER(),t}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()}`}};bf=wt;H.Integer=bf;wt.NAME="INTEGER";var xf,hs=class extends wt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};xf=hs;H.Enumerated=xf;hs.NAME="ENUMERATED";var Hn=class extends Me(Pt){constructor({valueDec:t=-1,isFirstSid:e=!1,...n}={}){super(n),this.valueDec=t,this.isFirstSid=e}fromBER(t,e,n){if(!n)return e;let o=X.BufferSourceConverter.toUint8Array(t);if(!He(this,o,e,n))return-1;let s=o.subarray(e,e+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=Ir(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){ts();let e=BigInt(t).toString(2);for(;e.length%7;)e="0"+e;let n=new Uint8Array(e.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(e.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(t){if(this.isHexOnly){if(t)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 e=er(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",he;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let t="";if(this.isHexOnly)t=X.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let e=this.valueDec;this.valueDec<=39?t="0.":this.valueDec<=79?(t="1.",e-=40):(t="2.",e-=80),t+=e.toString()}else t=this.valueDec.toString();return t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Hn.NAME="sidBlock";var ds=class extends Pt{constructor({value:t=nn,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new Hn;if(o=s.fromBER(t,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(t){let e=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(t);if(o.byteLength===0)return this.error=this.value[n].error,he;e.push(o)}return Za(e)}fromString(t){this.value=[];let e=0,n=0,o="",s=!1;do if(n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=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 Hn;if(o>Number.MAX_SAFE_INTEGER){ts();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 t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e?(o=`{${o}}`,this.value[n].isFirstSid?t=`2.{${o} - 80}`:t+=o):t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};ds.NAME="ObjectIdentifierValueBlock";var Ef,fe=class extends Tt{constructor(t={}){super(t,ds),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Ef=fe;H.ObjectIdentifier=Ef;fe.NAME="OBJECT IDENTIFIER";var Mn=class extends Me(Ue){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let o=X.BufferSourceConverter.toUint8Array(t);if(!He(this,o,e,n))return-1;let s=o.subarray(e,e+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=Ir(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}toBER(t){if(this.isHexOnly){if(t)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 e=er(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",he;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let t="";return this.isHexOnly?t=X.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Mn.NAME="relativeSidBlock";var ps=class extends Pt{constructor({value:t=nn,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new Mn;if(o=s.fromBER(t,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(t,e){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(t);if(s.byteLength===0)return this.error=this.value[o].error,he;n.push(s)}return Za(n)}fromString(t){this.value=[];let e=0,n=0,o="";do{n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1;let s=new Mn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e&&(o=`{${o}}`),t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};ps.NAME="RelativeObjectIdentifierValueBlock";var vf,ms=class extends Tt{constructor(t={}){super(t,ps),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};vf=ms;H.RelativeObjectIdentifier=vf;ms.NAME="RelativeObjectIdentifier";var Af,It=class extends rr{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Af=It;H.Sequence=Af;It.NAME="SEQUENCE";var Sf,gs=class extends rr{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Sf=gs;H.Set=Sf;gs.NAME="SET";var ys=class extends Me(Pt){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=nn}toJSON(){return{...super.toJSON(),value:this.value}}};ys.NAME="StringValueBlock";var ws=class extends ys{};ws.NAME="SimpleStringValueBlock";var Ht=class extends ns{constructor({...t}={}){super(t,ws)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,X.BufferSourceConverter.toUint8Array(t))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);this.valueBlock.value=t}};Ht.NAME="SIMPLE STRING";var bs=class extends Ht{fromBuffer(t){this.valueBlock.valueHexView=X.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=X.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=X.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(X.Convert.FromUtf8String(t)),this.valueBlock.value=t}};bs.NAME="Utf8StringValueBlock";var Bf,Oe=class extends bs{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Bf=Oe;H.Utf8String=Bf;Oe.NAME="UTF8String";var xs=class extends Ht{fromBuffer(t){this.valueBlock.value=X.Convert.ToUtf16String(t),this.valueBlock.valueHexView=X.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(X.Convert.FromUtf16String(t))}};xs.NAME="BmpStringValueBlock";var If,Es=class extends xs{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};If=Es;H.BmpString=If;Es.NAME="BMPString";var vs=class extends Ht{fromBuffer(t){let e=ArrayBuffer.isView(t)?t.slice().buffer:t.slice(0),n=new Uint8Array(e);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(e))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e*4);for(let o=0;o<e;o++){let s=er(t.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=t}};vs.NAME="UniversalStringValueBlock";var _f,As=class extends vs{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};_f=As;H.UniversalString=_f;As.NAME="UniversalString";var kf,Ss=class extends Ht{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};kf=Ss;H.NumericString=kf;Ss.NAME="NumericString";var Cf,Bs=class extends Ht{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Cf=Bs;H.PrintableString=Cf;Bs.NAME="PrintableString";var Rf,Is=class extends Ht{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Rf=Is;H.TeletexString=Rf;Is.NAME="TeletexString";var Tf,_s=class extends Ht{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Tf=_s;H.VideotexString=Tf;_s.NAME="VideotexString";var Nf,ks=class extends Ht{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Nf=ks;H.IA5String=Nf;ks.NAME="IA5String";var Lf,Cs=class extends Ht{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Lf=Cs;H.GraphicString=Lf;Cs.NAME="GraphicString";var Df,Vn=class extends Ht{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Df=Vn;H.VisibleString=Df;Vn.NAME="VisibleString";var Uf,Rs=class extends Ht{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Uf=Rs;H.GeneralString=Uf;Rs.NAME="GeneralString";var Pf,Ts=class extends Ht{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Pf=Ts;H.CharacterString=Pf;Ts.NAME="CharacterString";var Of,Fn=class extends Vn{constructor({value:t,valueDate:e,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,t){this.fromString(t),this.valueBlock.valueHexView=new Uint8Array(t.length);for(let o=0;o<t.length;o++)this.valueBlock.valueHexView[o]=t.charCodeAt(o)}e&&(this.fromDate(e),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(t){this.fromString(String.fromCharCode.apply(null,X.BufferSourceConverter.toUint8Array(t)))}toBuffer(){let t=this.toString(),e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return e}fromDate(t){this.year=t.getUTCFullYear(),this.month=t.getUTCMonth()+1,this.day=t.getUTCDate(),this.hour=t.getUTCHours(),this.minute=t.getUTCMinutes(),this.second=t.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(t){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(t);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(t="iso"){if(t==="iso"){let e=new Array(7);return e[0]=Ft(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=Ft(this.month,2),e[2]=Ft(this.day,2),e[3]=Ft(this.hour,2),e[4]=Ft(this.minute,2),e[5]=Ft(this.second,2),e[6]="Z",e.join("")}return super.toString(t)}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}}};Of=Fn;H.UTCTime=Of;Fn.NAME="UTCTime";var Hf,Ns=class extends Fn{constructor(t={}){var e;super(t),(e=this.millisecond)!==null&&e!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(t){super.fromDate(t),this.millisecond=t.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(t){let e=!1,n="",o="",s=0,i,a=0,c=0;if(t[t.length-1]==="Z")n=t.substring(0,t.length-1),e=!0;else{let f=new Number(t[t.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=t}if(e){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,p=n.indexOf("+"),y="";if(p===-1&&(p=n.indexOf("-"),f=-1),p!==-1){if(y=n.substring(p+1),n=n.substring(0,p),y.length!==2&&y.length!==4)throw new Error("Wrong input string for conversion");let m=parseInt(y.substring(0,2),10);if(isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*m,y.length===4){if(m=parseInt(y.substring(2,4),10),isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");c=f*m}}}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(e===!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(t="iso"){if(t==="iso"){let e=[];return e.push(Ft(this.year,4)),e.push(Ft(this.month,2)),e.push(Ft(this.day,2)),e.push(Ft(this.hour,2)),e.push(Ft(this.minute,2)),e.push(Ft(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(Ft(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Hf=Ns;H.GeneralizedTime=Hf;Ns.NAME="GeneralizedTime";var Mf,Ls=class extends Oe{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Mf=Ls;H.DATE=Mf;Ls.NAME="DATE";var Vf,Ds=class extends Oe{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Vf=Ds;H.TimeOfDay=Vf;Ds.NAME="TimeOfDay";var Ff,Us=class extends Oe{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Ff=Us;H.DateTime=Ff;Us.NAME="DateTime";var Kf,Ps=class extends Oe{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Kf=Ps;H.Duration=Kf;Ps.NAME="Duration";var $f,Os=class extends Oe{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};$f=Os;H.TIME=$f;Os.NAME="TIME";function dg(r){let{result:t}=on(r),e=t.valueBlock.value;return{n:G(xe(e[1].toBigInt()),"base64url"),e:G(xe(e[2].toBigInt()),"base64url"),d:G(xe(e[3].toBigInt()),"base64url"),p:G(xe(e[4].toBigInt()),"base64url"),q:G(xe(e[5].toBigInt()),"base64url"),dp:G(xe(e[6].toBigInt()),"base64url"),dq:G(xe(e[7].toBigInt()),"base64url"),qi:G(xe(e[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function pg(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 D("JWK was missing components","ERR_INVALID_PARAMETERS");let e=new It({value:[new wt({value:0}),wt.fromBigInt(Ee(J(r.n,"base64url"))),wt.fromBigInt(Ee(J(r.e,"base64url"))),wt.fromBigInt(Ee(J(r.d,"base64url"))),wt.fromBigInt(Ee(J(r.p,"base64url"))),wt.fromBigInt(Ee(J(r.q,"base64url"))),wt.fromBigInt(Ee(J(r.dp,"base64url"))),wt.fromBigInt(Ee(J(r.dq,"base64url"))),wt.fromBigInt(Ee(J(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function mg(r){let{result:t}=on(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:G(xe(e[0].toBigInt()),"base64url"),e:G(xe(e[1].toBigInt()),"base64url")}}function gg(r){if(r.n==null||r.e==null)throw new D("JWK was missing components","ERR_INVALID_PARAMETERS");let e=new It({value:[new It({value:[new fe({value:"1.2.840.113549.1.1.1"}),new nr]}),new rn({valueHex:new It({value:[wt.fromBigInt(Ee(J(r.n,"base64url"))),wt.fromBigInt(Ee(J(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function xe(r){let t=r.toString(16);t.length%2>0&&(t=`0${t}`);let e=t.length/2,n=new Uint8Array(e),o=0,s=0;for(;o<e;)n[o]=parseInt(t.slice(s,s+2),16),o+=1,s+=2;return n}function Ee(r){let t=[];return r.forEach(function(e){let n=e.toString(16);n.length%2>0&&(n=`0${n}`),t.push(n)}),BigInt("0x"+t.join(""))}var yg=16,Ja=32,Qa=1e4;async function wg(r,t){let e=Ot.get(),o=new It({value:[new wt({value:0}),new It({value:[new fe({value:"1.2.840.113549.1.1.1"}),new nr]}),new Pe({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=Br(yg),a=await ja(_n,t,i,{c:Qa,dkLen:Ja}),c=Br(16),l=await e.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),u=await e.subtle.encrypt({name:"AES-CBC",iv:c},l,s),f=new It({value:[new Pe({valueHex:i}),new wt({value:Qa}),new wt({value:Ja}),new It({value:[new fe({value:"1.2.840.113549.2.11"}),new nr]})]}),p=new It({value:[new fe({value:"1.2.840.113549.1.5.13"}),new It({value:[new It({value:[new fe({value:"1.2.840.113549.1.5.12"}),f]}),new It({value:[new fe({value:"2.16.840.1.101.3.4.1.42"}),new Pe({valueHex:c})]})]})]}),m=new It({value:[p,new Pe({valueHex:u})]}).toBER(),h=new Uint8Array(m,0,m.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...G(h,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
|
7
|
-
`)}async function bg(r,t){let e=Ot.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=J(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=on(o),{iv:i,salt:a,iterations:c,keySize:l,cipherText:u}=xg(s),f=await ja(_n,t,a,{c,dkLen:l}),p=await e.subtle.importKey("raw",f,"AES-CBC",!1,["decrypt"]),y=Kn(await e.subtle.decrypt({name:"AES-CBC",iv:i},p,u)),{result:m}=on(y);n=Wf(m)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=J(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=on(o);n=Wf(s)}else throw new D("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return tc(n)}function xg(r){let t=r.valueBlock.value[0];if(t.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new D("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=t.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new D("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=Kn(s.valueBlock.value[0].getValue()),a=Qa,c=Ja;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new D("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let l=t.valueBlock.value[1].valueBlock.value[1],u=l.valueBlock.value[0].toString();if(u!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(u!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new D("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let f=Kn(l.valueBlock.value[1].getValue());return{cipherText:Kn(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:f}}function Wf(r){return Kn(r.valueBlock.value[2].getValue())}function Kn(r){return new Uint8Array(r,0,r.byteLength)}async function Gf(r){let t=await Ot.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await zf(t);return{privateKey:e[0],publicKey:e[1]}}async function ec(r){let e=[await Ot.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Eg(r)],n=await zf({privateKey:e[0],publicKey:e[1]});return{privateKey:n[0],publicKey:n[1]}}async function qf(r,t){let e=await Ot.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ot.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function jf(r,t,e){let n=await Ot.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ot.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function zf(r){if(r.privateKey==null||r.publicKey==null)throw new D("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Ot.get().subtle.exportKey("jwk",r.privateKey),Ot.get().subtle.exportKey("jwk",r.publicKey)])}async function Eg(r){return Ot.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function Ms(r){if(r.kty!=="RSA")throw new D("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new D("invalid key modulus","ERR_INVALID_KEY_MODULUS");return J(r.n,"base64url").length*8}var Wn=8192,$n=class{_key;constructor(t){this._key=t}verify(t,e){return jf(this._key,e,t)}marshal(){return or.jwkToPkix(this._key)}get bytes(){return ye.encode({Type:ut.RSA,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}hash(){let t=Ct.digest(this.bytes);return Zt(t)?t.then(({bytes:e})=>e):t.bytes}},sn=class{_key;_publicKey;constructor(t,e){this._key=t,this._publicKey=e}genSecret(){return Br(16)}sign(t){return qf(this._key,t)}get public(){if(this._publicKey==null)throw new D("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new $n(this._publicKey)}marshal(){return or.jwkToPkcs1(this._key)}get bytes(){return we.encode({Type:ut.RSA,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}hash(){let t=Ct.digest(this.bytes);return Zt(t)?t.then(({bytes:e})=>e):t.bytes}async id(){let t=await this.public.hash();return G(t,"base58btc")}async export(t,e="pkcs-8"){if(e==="pkcs-8")return or.exportToPem(this,t);if(e==="libp2p-key")return Qr(this.bytes,t);throw new D(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function tc(r){let t=or.pkcs1ToJwk(r);if(Ms(t)>Wn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await ec(t);return new sn(e.privateKey,e.publicKey)}function Ag(r){let t=or.pkixToJwk(r);if(Ms(t)>Wn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new $n(t)}async function Sg(r){if(Ms(r)>Wn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await ec(r);return new sn(t.privateKey,t.publicKey)}async function Bg(r){if(r>Wn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await Gf(r);return new sn(t.privateKey,t.publicKey)}var ac={};xt(ac,{Secp256k1PrivateKey:()=>qn,Secp256k1PublicKey:()=>Gn,generateKeyPair:()=>Hg,unmarshalSecp256k1PrivateKey:()=>Pg,unmarshalSecp256k1PublicKey:()=>Og});var Ig=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]),sr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ir=new Uint32Array(64),nc=class extends Yr{constructor(){super(64,32,8,!1),this.A=sr[0]|0,this.B=sr[1]|0,this.C=sr[2]|0,this.D=sr[3]|0,this.E=sr[4]|0,this.F=sr[5]|0,this.G=sr[6]|0,this.H=sr[7]|0}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)ir[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let p=ir[f-15],y=ir[f-2],m=ae(p,7)^ae(p,18)^p>>>3,h=ae(y,17)^ae(y,19)^y>>>10;ir[f]=h+ir[f-7]+m+ir[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 p=ae(a,6)^ae(a,11)^ae(a,25),y=u+p+Tu(a,c,l)+Ig[f]+ir[f]|0,h=(ae(n,2)^ae(n,13)^ae(n,22))+Nu(n,o,s)|0;u=l,l=c,c=a,a=i+y|0,i=s,s=o,o=n,n=y+h|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(){ir.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var an=Vo(()=>new nc);function _g(r){let t=Cn(r);Xt(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:kg,hexToBytes:Cg}=$o,_r={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(r){let{Err:t}=_r;if(r.length<2||r[0]!==2)throw new t("Invalid signature integer tag");let e=r[1],n=r.subarray(2,e+2);if(!e||n.length!==e)throw new t("Invalid signature integer: wrong length");if(n[0]&128)throw new t("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return{d:kg(n),l:r.subarray(e+2)}},toSig(r){let{Err:t}=_r,e=typeof r=="string"?Cg(r):r;Zr(e);let n=e.length;if(n<2||e[0]!=48)throw new t("Invalid signature tag");if(e[1]!==n-2)throw new t("Invalid signature: incorrect length");let{d:o,l:s}=_r._parseInt(e.subarray(2)),{d:i,l:a}=_r._parseInt(s);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:o,s:i}},hexFromSig(r){let t=l=>Number.parseInt(l[0],16)&8?"00"+l:l,e=l=>{let u=l.toString(16);return u.length&1?`0${u}`:u},n=t(e(r.s)),o=t(e(r.r)),s=n.length/2,i=o.length/2,a=e(s),c=e(i);return`30${e(i+s+4)}02${c}${o}02${a}${n}`}},Ve=BigInt(0),Qt=BigInt(1),bA=BigInt(2),Yf=BigInt(3),xA=BigInt(4);function Rg(r){let t=_g(r),{Fp:e}=t,n=t.toBytes||((m,h,d)=>{let b=h.toAffine();return Ne(Uint8Array.from([4]),e.toBytes(b.x),e.toBytes(b.y))}),o=t.fromBytes||(m=>{let h=m.subarray(1),d=e.fromBytes(h.subarray(0,e.BYTES)),b=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:d,y:b}});function s(m){let{a:h,b:d}=t,b=e.sqr(m),E=e.mul(b,m);return e.add(e.add(E,e.mul(m,h)),d)}if(!e.eql(e.sqr(t.Gy),s(t.Gx)))throw new Error("bad generator point: equation left != right");function i(m){return typeof m=="bigint"&&Ve<m&&m<t.n}function a(m){if(!i(m))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(m){let{allowedPrivateKeyLengths:h,nByteLength:d,wrapPrivateKey:b,n:E}=t;if(h&&typeof m!="bigint"){if(Je(m)&&(m=Ce(m)),typeof m!="string"||!h.includes(m.length))throw new Error("Invalid key");m=m.padStart(d*2,"0")}let w;try{w=typeof m=="bigint"?m:Re(it("private key",m,d))}catch{throw new Error(`private key must be ${d} bytes, hex or bigint, not ${typeof m}`)}return b&&(w=tt(w,E)),a(w),w}let l=new Map;function u(m){if(!(m instanceof f))throw new Error("ProjectivePoint expected")}class f{constructor(h,d,b){if(this.px=h,this.py=d,this.pz=b,h==null||!e.isValid(h))throw new Error("x required");if(d==null||!e.isValid(d))throw new Error("y required");if(b==null||!e.isValid(b))throw new Error("z required")}static fromAffine(h){let{x:d,y:b}=h||{};if(!h||!e.isValid(d)||!e.isValid(b))throw new Error("invalid affine point");if(h instanceof f)throw new Error("projective point not allowed");let E=w=>e.eql(w,e.ZERO);return E(d)&&E(b)?f.ZERO:new f(d,b,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let d=e.invertBatch(h.map(b=>b.pz));return h.map((b,E)=>b.toAffine(d[E])).map(f.fromAffine)}static fromHex(h){let d=f.fromAffine(o(it("pointHex",h)));return d.assertValidity(),d}static fromPrivateKey(h){return f.BASE.multiply(c(h))}_setWindowSize(h){this._WINDOW_SIZE=h,l.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!e.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:h,y:d}=this.toAffine();if(!e.isValid(h)||!e.isValid(d))throw new Error("bad point: x or y not FE");let b=e.sqr(d),E=s(h);if(!e.eql(b,E))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){u(h);let{px:d,py:b,pz:E}=this,{px:w,py:S,pz:x}=h,B=e.eql(e.mul(d,x),e.mul(w,E)),I=e.eql(e.mul(b,x),e.mul(S,E));return B&&I}negate(){return new f(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:d}=t,b=e.mul(d,Yf),{px:E,py:w,pz:S}=this,x=e.ZERO,B=e.ZERO,I=e.ZERO,_=e.mul(E,E),N=e.mul(w,w),P=e.mul(S,S),T=e.mul(E,w);return T=e.add(T,T),I=e.mul(E,S),I=e.add(I,I),x=e.mul(h,I),B=e.mul(b,P),B=e.add(x,B),x=e.sub(N,B),B=e.add(N,B),B=e.mul(x,B),x=e.mul(T,x),I=e.mul(b,I),P=e.mul(h,P),T=e.sub(_,P),T=e.mul(h,T),T=e.add(T,I),I=e.add(_,_),_=e.add(I,_),_=e.add(_,P),_=e.mul(_,T),B=e.add(B,_),P=e.mul(w,S),P=e.add(P,P),_=e.mul(P,T),x=e.sub(x,_),I=e.mul(P,N),I=e.add(I,I),I=e.add(I,I),new f(x,B,I)}add(h){u(h);let{px:d,py:b,pz:E}=this,{px:w,py:S,pz:x}=h,B=e.ZERO,I=e.ZERO,_=e.ZERO,N=t.a,P=e.mul(t.b,Yf),T=e.mul(d,w),F=e.mul(b,S),V=e.mul(E,x),j=e.add(d,b),v=e.add(w,S);j=e.mul(j,v),v=e.add(T,F),j=e.sub(j,v),v=e.add(d,E);let C=e.add(w,x);return v=e.mul(v,C),C=e.add(T,V),v=e.sub(v,C),C=e.add(b,E),B=e.add(S,x),C=e.mul(C,B),B=e.add(F,V),C=e.sub(C,B),_=e.mul(N,v),B=e.mul(P,V),_=e.add(B,_),B=e.sub(F,_),_=e.add(F,_),I=e.mul(B,_),F=e.add(T,T),F=e.add(F,T),V=e.mul(N,V),v=e.mul(P,v),F=e.add(F,V),V=e.sub(T,V),V=e.mul(N,V),v=e.add(v,V),T=e.mul(F,v),I=e.add(I,T),T=e.mul(C,v),B=e.mul(j,B),B=e.sub(B,T),T=e.mul(j,F),_=e.mul(C,_),_=e.add(_,T),new f(B,I,_)}subtract(h){return this.add(h.negate())}is0(){return this.equals(f.ZERO)}wNAF(h){return y.wNAFCached(this,l,h,d=>{let b=e.invertBatch(d.map(E=>E.pz));return d.map((E,w)=>E.toAffine(b[w])).map(f.fromAffine)})}multiplyUnsafe(h){let d=f.ZERO;if(h===Ve)return d;if(a(h),h===Qt)return this;let{endo:b}=t;if(!b)return y.unsafeLadder(this,h);let{k1neg:E,k1:w,k2neg:S,k2:x}=b.splitScalar(h),B=d,I=d,_=this;for(;w>Ve||x>Ve;)w&Qt&&(B=B.add(_)),x&Qt&&(I=I.add(_)),_=_.double(),w>>=Qt,x>>=Qt;return E&&(B=B.negate()),S&&(I=I.negate()),I=new f(e.mul(I.px,b.beta),I.py,I.pz),B.add(I)}multiply(h){a(h);let d=h,b,E,{endo:w}=t;if(w){let{k1neg:S,k1:x,k2neg:B,k2:I}=w.splitScalar(d),{p:_,f:N}=this.wNAF(x),{p:P,f:T}=this.wNAF(I);_=y.constTimeNegate(S,_),P=y.constTimeNegate(B,P),P=new f(e.mul(P.px,w.beta),P.py,P.pz),b=_.add(P),E=N.add(T)}else{let{p:S,f:x}=this.wNAF(d);b=S,E=x}return f.normalizeZ([b,E])[0]}multiplyAndAddUnsafe(h,d,b){let E=f.BASE,w=(x,B)=>B===Ve||B===Qt||!x.equals(E)?x.multiplyUnsafe(B):x.multiply(B),S=w(this,d).add(w(h,b));return S.is0()?void 0:S}toAffine(h){let{px:d,py:b,pz:E}=this,w=this.is0();h==null&&(h=w?e.ONE:e.inv(E));let S=e.mul(d,h),x=e.mul(b,h),B=e.mul(E,h);if(w)return{x:e.ZERO,y:e.ZERO};if(!e.eql(B,e.ONE))throw new Error("invZ was invalid");return{x:S,y:x}}isTorsionFree(){let{h,isTorsionFree:d}=t;if(h===Qt)return!0;if(d)return d(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:d}=t;return h===Qt?this:d?d(f,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return this.assertValidity(),n(f,this,h)}toHex(h=!0){return Ce(this.toRawBytes(h))}}f.BASE=new f(t.Gx,t.Gy,e.ONE),f.ZERO=new f(e.ZERO,e.ONE,e.ZERO);let p=t.nBitLength,y=qo(f,t.endo?Math.ceil(p/2):p);return{CURVE:t,ProjectivePoint:f,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:i}}function Tg(r){let t=Cn(r);return Xt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Zf(r){let t=Tg(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(v){return Ve<v&&v<e.ORDER}function a(v){return tt(v,n)}function c(v){return Wo(v,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:u,weierstrassEquation:f,isWithinCurveOrder:p}=Rg({...t,toBytes(v,C,O){let A=C.toAffine(),g=e.toBytes(A.x),k=Ne;return O?k(Uint8Array.from([C.hasEvenY()?2:3]),g):k(Uint8Array.from([4]),g,e.toBytes(A.y))},fromBytes(v){let C=v.length,O=v[0],A=v.subarray(1);if(C===o&&(O===2||O===3)){let g=Re(A);if(!i(g))throw new Error("Point is not on curve");let k=f(g),R;try{R=e.sqrt(k)}catch(W){let Y=W instanceof Error?": "+W.message:"";throw new Error("Point is not on curve"+Y)}let L=(R&Qt)===Qt;return(O&1)===1!==L&&(R=e.neg(R)),{x:g,y:R}}else if(C===s&&O===4){let g=e.fromBytes(A.subarray(0,e.BYTES)),k=e.fromBytes(A.subarray(e.BYTES,2*e.BYTES));return{x:g,y:k}}else throw new Error(`Point of length ${C} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),y=v=>Ce(Qe(v,t.nByteLength));function m(v){let C=n>>Qt;return v>C}function h(v){return m(v)?a(-v):v}let d=(v,C,O)=>Re(v.slice(C,O));class b{constructor(C,O,A){this.r=C,this.s=O,this.recovery=A,this.assertValidity()}static fromCompact(C){let O=t.nByteLength;return C=it("compactSignature",C,O*2),new b(d(C,0,O),d(C,O,2*O))}static fromDER(C){let{r:O,s:A}=_r.toSig(it("DER",C));return new b(O,A)}assertValidity(){if(!p(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!p(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(C){return new b(this.r,this.s,C)}recoverPublicKey(C){let{r:O,s:A,recovery:g}=this,k=I(it("msgHash",C));if(g==null||![0,1,2,3].includes(g))throw new Error("recovery id invalid");let R=g===2||g===3?O+t.n:O;if(R>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let L=g&1?"03":"02",$=l.fromHex(L+y(R)),W=c(R),Y=a(-k*W),q=a(A*W),z=l.BASE.multiplyAndAddUnsafe($,Y,q);if(!z)throw new Error("point at infinify");return z.assertValidity(),z}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new b(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return vr(this.toDERHex())}toDERHex(){return _r.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return vr(this.toCompactHex())}toCompactHex(){return y(this.r)+y(this.s)}}let E={isValidPrivateKey(v){try{return u(v),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let v=Fa(t.n);return Ku(t.randomBytes(v),t.n)},precompute(v=8,C=l.BASE){return C._setWindowSize(v),C.multiply(BigInt(3)),C}};function w(v,C=!0){return l.fromPrivateKey(v).toRawBytes(C)}function S(v){let C=Je(v),O=typeof v=="string",A=(C||O)&&v.length;return C?A===o||A===s:O?A===2*o||A===2*s:v instanceof l}function x(v,C,O=!0){if(S(v))throw new Error("first arg must be private key");if(!S(C))throw new Error("second arg must be public key");return l.fromHex(C).multiply(u(v)).toRawBytes(O)}let B=t.bits2int||function(v){let C=Re(v),O=v.length*8-t.nBitLength;return O>0?C>>BigInt(O):C},I=t.bits2int_modN||function(v){return a(B(v))},_=kn(t.nBitLength);function N(v){if(typeof v!="bigint")throw new Error("bigint expected");if(!(Ve<=v&&v<_))throw new Error(`bigint expected < 2^${t.nBitLength}`);return Qe(v,t.nByteLength)}function P(v,C,O=T){if(["recovered","canonical"].some(nt=>nt in O))throw new Error("sign() legacy options not supported");let{hash:A,randomBytes:g}=t,{lowS:k,prehash:R,extraEntropy:L}=O;k==null&&(k=!0),v=it("msgHash",v),R&&(v=it("prehashed msgHash",A(v)));let $=I(v),W=u(C),Y=[N(W),N($)];if(L!=null&&L!==!1){let nt=L===!0?g(e.BYTES):L;Y.push(it("extraEntropy",nt))}let q=Ne(...Y),z=$;function st(nt){let _t=B(nt);if(!p(_t))return;let kt=c(_t),bt=l.BASE.multiply(_t).toAffine(),Lt=a(bt.x);if(Lt===Ve)return;let ve=a(kt*a(z+Lt*W));if(ve===Ve)return;let ar=(bt.x===Lt?0:2)|Number(bt.y&Qt),hn=ve;return k&&m(ve)&&(hn=h(ve),ar^=1),new b(Lt,hn,ar)}return{seed:q,k2sig:st}}let T={lowS:t.lowS,prehash:!1},F={lowS:t.lowS,prehash:!1};function V(v,C,O=T){let{seed:A,k2sig:g}=P(v,C,O),k=t;return Pa(k.hash.outputLen,k.nByteLength,k.hmac)(A,g)}l.BASE._setWindowSize(8);function j(v,C,O,A=F){let g=v;if(C=it("msgHash",C),O=it("publicKey",O),"strict"in A)throw new Error("options.strict was renamed to lowS");let{lowS:k,prehash:R}=A,L,$;try{if(typeof g=="string"||Je(g))try{L=b.fromDER(g)}catch(bt){if(!(bt instanceof _r.Err))throw bt;L=b.fromCompact(g)}else if(typeof g=="object"&&typeof g.r=="bigint"&&typeof g.s=="bigint"){let{r:bt,s:Lt}=g;L=new b(bt,Lt)}else throw new Error("PARSE");$=l.fromHex(O)}catch(bt){if(bt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(k&&L.hasHighS())return!1;R&&(C=t.hash(C));let{r:W,s:Y}=L,q=I(C),z=c(Y),st=a(q*z),nt=a(W*z),_t=l.BASE.multiplyAndAddUnsafe($,st,nt)?.toAffine();return _t?a(_t.x)===W:!1}return{CURVE:t,getPublicKey:w,getSharedSecret:x,sign:V,verify:j,ProjectivePoint:l,Signature:b,utils:E}}function Ng(r){return{hash:r,hmac:(t,...e)=>tr(r,t,Ta(...e)),randomBytes:Er}}function Xf(r,t){let e=n=>Zf({...r,...Ng(n)});return Object.freeze({...e(t),create:e})}var th=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Jf=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Lg=BigInt(1),oc=BigInt(2),Qf=(r,t)=>(r+t/oc)/t;function Dg(r){let t=th,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=at(u,e,t)*u%t,p=at(f,e,t)*u%t,y=at(p,oc,t)*l%t,m=at(y,o,t)*y%t,h=at(m,s,t)*m%t,d=at(h,a,t)*h%t,b=at(d,c,t)*d%t,E=at(b,a,t)*h%t,w=at(E,e,t)*u%t,S=at(w,i,t)*m%t,x=at(S,n,t)*l%t,B=at(x,oc,t);if(!sc.eql(sc.sqr(B),r))throw new Error("Cannot find square root");return B}var sc=Go(th,void 0,void 0,{sqrt:Dg}),de=Xf({a:BigInt(0),b:BigInt(7),Fp:sc,n:Jf,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Jf,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Lg*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=Qf(s*r,t),c=Qf(-n*r,t),l=tt(r-a*e-c*o,t),u=tt(-a*n-c*s,t),f=l>i,p=u>i;if(f&&(l=t-l),p&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:p,k2:u}}}},an),CA=BigInt(0);var RA=de.ProjectivePoint;function eh(){return de.utils.randomPrivateKey()}function rh(r,t){let e=Ct.digest(t instanceof Uint8Array?t:t.subarray());if(Zt(e))return e.then(({digest:n})=>de.sign(n,r).toDERRawBytes()).catch(n=>{throw new D(String(n),"ERR_INVALID_INPUT")});try{return de.sign(e.digest,r).toDERRawBytes()}catch(n){throw new D(String(n),"ERR_INVALID_INPUT")}}function nh(r,t,e){let n=Ct.digest(e instanceof Uint8Array?e:e.subarray());if(Zt(n))return n.then(({digest:o})=>de.verify(t,o,r)).catch(o=>{throw new D(String(o),"ERR_INVALID_INPUT")});try{return de.verify(t,n.digest,r)}catch(o){throw new D(String(o),"ERR_INVALID_INPUT")}}function oh(r){return de.ProjectivePoint.fromHex(r).toRawBytes(!0)}function sh(r){try{de.getPublicKey(r,!0)}catch(t){throw new D(String(t),"ERR_INVALID_PRIVATE_KEY")}}function ic(r){try{de.ProjectivePoint.fromHex(r)}catch(t){throw new D(String(t),"ERR_INVALID_PUBLIC_KEY")}}function ih(r){try{return de.getPublicKey(r,!0)}catch(t){throw new D(String(t),"ERR_INVALID_PRIVATE_KEY")}}var Gn=class{_key;constructor(t){ic(t),this._key=t}verify(t,e){return nh(this._key,e,t)}marshal(){return oh(this._key)}get bytes(){return ye.encode({Type:ut.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}async hash(){let t=Ct.digest(this.bytes),e;return Zt(t)?{bytes:e}=await t:e=t.bytes,e}},qn=class{_key;_publicKey;constructor(t,e){this._key=t,this._publicKey=e??ih(t),sh(this._key),ic(this._publicKey)}sign(t){return rh(this._key,t)}get public(){return new Gn(this._publicKey)}marshal(){return this._key}get bytes(){return we.encode({Type:ut.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}hash(){let t=Ct.digest(this.bytes);return Zt(t)?t.then(({bytes:e})=>e):t.bytes}async id(){let t=await this.public.hash();return G(t,"base58btc")}async export(t,e="libp2p-key"){if(e==="libp2p-key")return Qr(this.bytes,t);throw new D(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Pg(r){return new qn(r)}function Og(r){return new Gn(r)}async function Hg(){let r=eh();return new qn(r)}var kr={rsa:rc,ed25519:qa,secp256k1:ac};function ah(r){let t=Object.keys(kr).join(" / ");return new D(`invalid or unsupported key type ${r}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function ch(r){let t=ye.decode(r),e=t.Data??new Uint8Array;switch(t.Type){case ut.RSA:return kr.rsa.unmarshalRsaPublicKey(e);case ut.Ed25519:return kr.ed25519.unmarshalEd25519PublicKey(e);case ut.Secp256k1:return kr.secp256k1.unmarshalSecp256k1PublicKey(e);default:throw ah(t.Type??"unknown")}}async function cc(r){let t=we.decode(r),e=t.Data??new Uint8Array;switch(t.Type){case ut.RSA:return kr.rsa.unmarshalRsaPrivateKey(e);case ut.Ed25519:return kr.ed25519.unmarshalEd25519PrivateKey(e);case ut.Secp256k1:return kr.secp256k1.unmarshalSecp256k1PrivateKey(e);default:throw ah(t.Type??"RSA")}}function lc(){let r=ht(),t=!1;return{sink:async e=>{if(t)throw new Error("already piped");t=!0,r.resolve(e)},source:async function*(){yield*await r.promise}()}}function lh(){let r=lc(),t=lc();return[{source:r.source,sink:t.sink},{source:t.source,sink:r.sink}]}function Mg(r){return r[Symbol.asyncIterator]!=null}function Vg(...r){let t=[];for(let e of r)Mg(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=Ge({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)e.push(o)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var uh=Vg;function fh(r,...t){if(r==null)throw new Error("Empty pipeline");if(uc(r)){let n=r;r=()=>n.source}else if(dh(r)||hh(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&uc(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)uc(e[n])&&(e[n]=Kg(e[n]));return Fg(...e)}var Fg=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},hh=r=>r?.[Symbol.asyncIterator]!=null,dh=r=>r?.[Symbol.iterator]!=null,uc=r=>r==null?!1:r.sink!=null&&r.source!=null,Kg=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Ge({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(hh(s))o=async function*(){yield*s,n.end()};else if(dh(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return uh(n,o())}return r.source};var cn=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function Vs(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function fc(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function hc(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Kt(r,...t){if(!hc(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function dc(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function ph(r,t){Kt(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var Fe=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),mh=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),$g=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!$g)throw new Error("Non little-endian hardware is not supported");function Wg(r){if(typeof r!="string")throw new Error(`string expected, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Fs(r){if(typeof r=="string")r=Wg(r);else if(hc(r))r=r.slice();else throw new Error(`Uint8Array expected, got ${typeof r}`);return r}function gh(r,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(r,t)}function yh(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}var pc=(r,t)=>(Object.assign(t,r),t);function mc(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}var Nt=(r,t)=>r[t++]&255|(r[t++]&255)<<8,gc=class{constructor(t){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,t=Fs(t),Kt(t,32);let e=Nt(t,0),n=Nt(t,2),o=Nt(t,4),s=Nt(t,6),i=Nt(t,8),a=Nt(t,10),c=Nt(t,12),l=Nt(t,14);this.r[0]=e&8191,this.r[1]=(e>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Nt(t,16+2*u)}process(t,e,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],p=i[5],y=i[6],m=i[7],h=i[8],d=i[9],b=Nt(t,e+0),E=Nt(t,e+2),w=Nt(t,e+4),S=Nt(t,e+6),x=Nt(t,e+8),B=Nt(t,e+10),I=Nt(t,e+12),_=Nt(t,e+14),N=s[0]+(b&8191),P=s[1]+((b>>>13|E<<3)&8191),T=s[2]+((E>>>10|w<<6)&8191),F=s[3]+((w>>>7|S<<9)&8191),V=s[4]+((S>>>4|x<<12)&8191),j=s[5]+(x>>>1&8191),v=s[6]+((x>>>14|B<<2)&8191),C=s[7]+((B>>>11|I<<5)&8191),O=s[8]+((I>>>8|_<<8)&8191),A=s[9]+(_>>>5|o),g=0,k=g+N*a+P*(5*d)+T*(5*h)+F*(5*m)+V*(5*y);g=k>>>13,k&=8191,k+=j*(5*p)+v*(5*f)+C*(5*u)+O*(5*l)+A*(5*c),g+=k>>>13,k&=8191;let R=g+N*c+P*a+T*(5*d)+F*(5*h)+V*(5*m);g=R>>>13,R&=8191,R+=j*(5*y)+v*(5*p)+C*(5*f)+O*(5*u)+A*(5*l),g+=R>>>13,R&=8191;let L=g+N*l+P*c+T*a+F*(5*d)+V*(5*h);g=L>>>13,L&=8191,L+=j*(5*m)+v*(5*y)+C*(5*p)+O*(5*f)+A*(5*u),g+=L>>>13,L&=8191;let $=g+N*u+P*l+T*c+F*a+V*(5*d);g=$>>>13,$&=8191,$+=j*(5*h)+v*(5*m)+C*(5*y)+O*(5*p)+A*(5*f),g+=$>>>13,$&=8191;let W=g+N*f+P*u+T*l+F*c+V*a;g=W>>>13,W&=8191,W+=j*(5*d)+v*(5*h)+C*(5*m)+O*(5*y)+A*(5*p),g+=W>>>13,W&=8191;let Y=g+N*p+P*f+T*u+F*l+V*c;g=Y>>>13,Y&=8191,Y+=j*a+v*(5*d)+C*(5*h)+O*(5*m)+A*(5*y),g+=Y>>>13,Y&=8191;let q=g+N*y+P*p+T*f+F*u+V*l;g=q>>>13,q&=8191,q+=j*c+v*a+C*(5*d)+O*(5*h)+A*(5*m),g+=q>>>13,q&=8191;let z=g+N*m+P*y+T*p+F*f+V*u;g=z>>>13,z&=8191,z+=j*l+v*c+C*a+O*(5*d)+A*(5*h),g+=z>>>13,z&=8191;let st=g+N*h+P*m+T*y+F*p+V*f;g=st>>>13,st&=8191,st+=j*u+v*l+C*c+O*a+A*(5*d),g+=st>>>13,st&=8191;let nt=g+N*d+P*h+T*m+F*y+V*p;g=nt>>>13,nt&=8191,nt+=j*f+v*u+C*l+O*c+A*a,g+=nt>>>13,nt&=8191,g=(g<<2)+g|0,g=g+k|0,k=g&8191,g=g>>>13,R+=g,s[0]=k,s[1]=R,s[2]=L,s[3]=$,s[4]=W,s[5]=Y,s[6]=q,s[7]=z,s[8]=st,s[9]=nt}finalize(){let{h:t,pad:e}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+e[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+e[a]|0)+(i>>>16)|0,t[a]=i&65535}update(t){dc(this);let{buffer:e,blockLen:n}=this;t=Fs(t);let o=t.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(t,s);continue}e.set(t.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(e,0,!1),this.pos=0)}return this}destroy(){this.h.fill(0),this.r.fill(0),this.buffer.fill(0),this.pad.fill(0)}digestInto(t){dc(this),ph(t,this),this.finished=!0;let{buffer:e,h:n}=this,{pos:o}=this;if(o){for(e[o++]=1;o<16;o++)e[o]=0;this.process(e,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)t[s++]=n[i]>>>0,t[s++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}};function Gg(r){let t=(n,o)=>r(o).update(Fs(n)).digest(),e=r(new Uint8Array(32));return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=n=>r(n),t}var wh=Gg(r=>new gc(r));var xh=r=>Uint8Array.from(r.split("").map(t=>t.charCodeAt(0))),qg=xh("expand 16-byte k"),jg=xh("expand 32-byte k"),zg=Fe(qg),Eh=Fe(jg),cS=Eh.slice();function M(r,t){return r<<t|r>>>32-t}function yc(r){return r.byteOffset%4===0}var Ks=64,Yg=16,vh=2**32-1,bh=new Uint32Array;function Zg(r,t,e,n,o,s,i,a){let c=o.length,l=new Uint8Array(Ks),u=Fe(l),f=yc(o)&&yc(s),p=f?Fe(o):bh,y=f?Fe(s):bh;for(let m=0;m<c;i++){if(r(t,e,n,u,i,a),i>=vh)throw new Error("arx: counter overflow");let h=Math.min(Ks,c-m);if(f&&h===Ks){let d=m/4;if(m%4!==0)throw new Error("arx: invalid block position");for(let b=0,E;b<Yg;b++)E=d+b,y[E]=p[E]^u[b];m+=Ks;continue}for(let d=0,b;d<h;d++)b=m+d,s[b]=o[b]^l[d];m+=h}}function wc(r,t){let{allowShortKeys:e,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=gh({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof r!="function")throw new Error("core must be a function");return Vs(o),Vs(i),fc(s),fc(e),(a,c,l,u,f=0)=>{Kt(a),Kt(c),Kt(l);let p=l.length;if(u||(u=new Uint8Array(p)),Kt(u),Vs(f),f<0||f>=vh)throw new Error("arx: counter overflow");if(u.length<p)throw new Error(`arx: output (${u.length}) is shorter than data (${p})`);let y=[],m=a.length,h,d;if(m===32)h=a.slice(),y.push(h),d=Eh;else if(m===16&&e)h=new Uint8Array(32),h.set(a),h.set(a,16),d=zg,y.push(h);else throw new Error(`arx: invalid 32-byte key, got length=${m}`);yc(c)||(c=c.slice(),y.push(c));let b=Fe(h);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(d,b,Fe(c.subarray(0,16)),b),c=c.subarray(16)}let E=16-o;if(E!==c.length)throw new Error(`arx: nonce must be ${E} or 16 bytes`);if(E!==12){let S=new Uint8Array(12);S.set(c,s?0:12-c.length),c=S,y.push(c)}let w=Fe(c);for(Zg(r,d,b,w,l,u,f,i);y.length>0;)y.pop().fill(0);return u}}function Bh(r,t,e,n,o,s=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=t[0],f=t[1],p=t[2],y=t[3],m=t[4],h=t[5],d=t[6],b=t[7],E=o,w=e[0],S=e[1],x=e[2],B=i,I=a,_=c,N=l,P=u,T=f,F=p,V=y,j=m,v=h,C=d,O=b,A=E,g=w,k=S,R=x;for(let $=0;$<s;$+=2)B=B+P|0,A=M(A^B,16),j=j+A|0,P=M(P^j,12),B=B+P|0,A=M(A^B,8),j=j+A|0,P=M(P^j,7),I=I+T|0,g=M(g^I,16),v=v+g|0,T=M(T^v,12),I=I+T|0,g=M(g^I,8),v=v+g|0,T=M(T^v,7),_=_+F|0,k=M(k^_,16),C=C+k|0,F=M(F^C,12),_=_+F|0,k=M(k^_,8),C=C+k|0,F=M(F^C,7),N=N+V|0,R=M(R^N,16),O=O+R|0,V=M(V^O,12),N=N+V|0,R=M(R^N,8),O=O+R|0,V=M(V^O,7),B=B+T|0,R=M(R^B,16),C=C+R|0,T=M(T^C,12),B=B+T|0,R=M(R^B,8),C=C+R|0,T=M(T^C,7),I=I+F|0,A=M(A^I,16),O=O+A|0,F=M(F^O,12),I=I+F|0,A=M(A^I,8),O=O+A|0,F=M(F^O,7),_=_+V|0,g=M(g^_,16),j=j+g|0,V=M(V^j,12),_=_+V|0,g=M(g^_,8),j=j+g|0,V=M(V^j,7),N=N+P|0,k=M(k^N,16),v=v+k|0,P=M(P^v,12),N=N+P|0,k=M(k^N,8),v=v+k|0,P=M(P^v,7);let L=0;n[L++]=i+B|0,n[L++]=a+I|0,n[L++]=c+_|0,n[L++]=l+N|0,n[L++]=u+P|0,n[L++]=f+T|0,n[L++]=p+F|0,n[L++]=y+V|0,n[L++]=m+j|0,n[L++]=h+v|0,n[L++]=d+C|0,n[L++]=b+O|0,n[L++]=E+A|0,n[L++]=w+g|0,n[L++]=S+k|0,n[L++]=x+R|0}function Xg(r,t,e,n){let o=r[0],s=r[1],i=r[2],a=r[3],c=t[0],l=t[1],u=t[2],f=t[3],p=t[4],y=t[5],m=t[6],h=t[7],d=e[0],b=e[1],E=e[2],w=e[3];for(let x=0;x<20;x+=2)o=o+c|0,d=M(d^o,16),p=p+d|0,c=M(c^p,12),o=o+c|0,d=M(d^o,8),p=p+d|0,c=M(c^p,7),s=s+l|0,b=M(b^s,16),y=y+b|0,l=M(l^y,12),s=s+l|0,b=M(b^s,8),y=y+b|0,l=M(l^y,7),i=i+u|0,E=M(E^i,16),m=m+E|0,u=M(u^m,12),i=i+u|0,E=M(E^i,8),m=m+E|0,u=M(u^m,7),a=a+f|0,w=M(w^a,16),h=h+w|0,f=M(f^h,12),a=a+f|0,w=M(w^a,8),h=h+w|0,f=M(f^h,7),o=o+l|0,w=M(w^o,16),m=m+w|0,l=M(l^m,12),o=o+l|0,w=M(w^o,8),m=m+w|0,l=M(l^m,7),s=s+u|0,d=M(d^s,16),h=h+d|0,u=M(u^h,12),s=s+u|0,d=M(d^s,8),h=h+d|0,u=M(u^h,7),i=i+f|0,b=M(b^i,16),p=p+b|0,f=M(f^p,12),i=i+f|0,b=M(b^i,8),p=p+b|0,f=M(f^p,7),a=a+c|0,E=M(E^a,16),y=y+E|0,c=M(c^y,12),a=a+c|0,E=M(E^a,8),y=y+E|0,c=M(c^y,7);let S=0;n[S++]=o,n[S++]=s,n[S++]=i,n[S++]=a,n[S++]=d,n[S++]=b,n[S++]=E,n[S++]=w}var Jg=wc(Bh,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Qg=wc(Bh,{counterRight:!1,counterLength:8,extendNonceFn:Xg,allowShortKeys:!1});var ty=new Uint8Array(16),Ah=(r,t)=>{r.update(t);let e=t.length%16;e&&r.update(ty.subarray(e))},ey=new Uint8Array(32);function Sh(r,t,e,n,o){let s=r(t,e,ey),i=wh.create(s);o&&Ah(i,o),Ah(i,n);let a=new Uint8Array(16),c=mh(a);mc(c,0,BigInt(o?o.length:0),!0),mc(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return s.fill(0),l}var Ih=r=>(t,e,n)=>(Kt(t,32),Kt(e),{encrypt:(s,i)=>{let a=s.length,c=a+16;i?Kt(i,c):i=new Uint8Array(c),r(t,e,s,i,1);let l=Sh(r,t,e,i.subarray(0,-16),n);return i.set(l,a),i},decrypt:(s,i)=>{let a=s.length,c=a-16;if(a<16)throw new Error("encrypted data must be at least 16 bytes");i?Kt(i,c):i=new Uint8Array(c);let l=s.subarray(0,-16),u=s.subarray(-16),f=Sh(r,t,e,l,n);if(!yh(u,f))throw new Error("invalid tag");return r(t,e,l,i,1),i}}),bc=pc({blockSize:64,nonceLength:12,tagLength:16},Ih(Jg)),pS=pc({blockSize:64,nonceLength:24,tagLength:16},Ih(Qg));function kh(r,t,e){return xr(r),e===void 0&&(e=new Uint8Array(r.outputLen)),tr(r,ce(e),ce(t))}var xc=new Uint8Array([0]),_h=new Uint8Array;function Ch(r,t,e,n=32){if(xr(r),Ye(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);e===void 0&&(e=_h);let s=new Uint8Array(o*r.outputLen),i=tr.create(r,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)xc[0]=l+1,a.update(l===0?_h:c).update(e).update(xc).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),xc.fill(0),s.slice(0,n)}var Ec={hashSHA256(r){return an(r.subarray())},getHKDF(r,t){let e=kh(an,t,r),o=Ch(an,e,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=Nn.utils.randomPrivateKey();return{publicKey:Nn.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:Nn.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,t){return Nn.getSharedSecret(r.subarray(),t.subarray())},chaCha20Poly1305Encrypt(r,t,e,n){return bc(n,t,e).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,t,e,n,o){return bc(n,t,e).decrypt(r.subarray(),o)}};var Rh=Ec;function Th(r){return{generateKeypair:r.generateX25519KeyPair,dh:(t,e)=>r.generateX25519SharedKey(t.privateKey,e).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var ln=r=>{let t=At(2);return t[0]=r>>8,t[1]=r,t};ln.bytes=2;var jn=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let t=0;return t+=r[0]<<8,t+=r[1],t}return r.getUint16(0)};jn.bytes=2;function Nh(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 vc(r,t){!t.enabled||!cn||(r?(t(`LOCAL_STATIC_PUBLIC_KEY ${G(r.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${G(r.privateKey,"hex")}`)):t("Missing local static keys."))}function Ac(r,t){!t.enabled||!cn||(r?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${G(r.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${G(r.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function Lh(r,t){!t.enabled||!cn||t(r?`REMOTE_STATIC_PUBLIC_KEY ${G(r.subarray(),"hex")}`:"Missing remote static public key.")}function Sc(r,t){!t.enabled||!cn||t(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${G(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Bc(r,t,e){!e.enabled||!cn||(e(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&G(r.k,"hex")}`),e(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&G(t.k,"hex")}`))}var $s=class r extends Error{code;constructor(t="Unexpected Peer"){super(t),this.code=r.code}static code="ERR_UNEXPECTED_PEER"},un=class r extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var ry=0,ny=4294967295,oy="Cipherstate has reached maximum n, a new handshake must be performed",Ws=class{n;bytes;view;constructor(t=ry){this.n=t,this.bytes=vt(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>ny)throw new Error(oy)}};var Cr=vt(0),fn=class{k;n;crypto;constructor(t,e=void 0,n=0){this.crypto=t,this.k=e,this.n=new Ws(n)}hasKey(){return!!this.k}encryptWithAd(t,e){if(!this.hasKey())return e;this.n.assertValue();let n=this.crypto.encrypt(e,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,e,n){if(!this.hasKey())return e;this.n.assertValue();let o=this.crypto.decrypt(e,this.n.getBytes(),t,this.k,n);return this.n.increment(),o}},Ic=class{cs;ck;h;crypto;constructor(t,e){this.crypto=t;let n=J(e,"utf-8");this.h=sy(t,n),this.ck=this.h,this.cs=new fn(t)}mixKey(t){let[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new fn(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new ct(this.h,t))}encryptAndHash(t){let e=this.cs.encryptWithAd(this.h,t);return this.mixHash(e),e}decryptAndHash(t){let e=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),e}split(){let[t,e]=this.crypto.hkdf(this.ck,Cr);return[new fn(this.crypto,t),new fn(this.crypto,e)]}},_c=class{ss;s;e;rs;re;initiator;crypto;constructor(t){let{crypto:e,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=t;this.crypto=e,this.ss=new Ic(e,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 t=this.crypto.generateKeypair();return this.ss.mixHash(t.publicKey),this.e=t,t.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(t,e=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<e+32)throw new Error("message is not long enough");this.re=t.sublist(e,e+32),this.ss.mixHash(this.re)}readS(t,e=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(t.byteLength<e+n)throw new Error("message is not long enough");let o=t.sublist(e,e+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},zn=class extends _c{writeMessageA(t){return new ct(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let e=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new ct(e,n,this.ss.encryptAndHash(t))}writeMessageC(t){let e=this.writeS();return this.writeSE(),new ct(e,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(e){throw new un(`handshake stage 0 validation fail: ${e.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();let e=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+e))}catch(e){throw new un(`handshake stage 1 validation fail: ${e.message}`)}}readMessageC(t){try{let e=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(e))}catch(e){throw new un(`handshake stage 2 validation fail: ${e.message}`)}}};function sy(r,t){if(t.length<=32){let e=vt(32);return e.set(t),e}else return r.hash(t)}var Gs;(function(r){let t;r.codec=()=>(t==null&&(t=ie((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.webtransportCerthashes!=null)for(let s of e.webtransportCerthashes)n.uint32(10),n.bytes(s);o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={webtransportCerthashes:[]},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:{o.webtransportCerthashes.push(e.bytes());break}default:{e.skipType(i&7);break}}}return o})),t),r.encode=e=>se(e,r.codec()),r.decode=e=>oe(e,r.codec())})(Gs||(Gs={}));var Yn;(function(r){let t;r.codec=()=>(t==null&&(t=ie((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.identityKey!=null&&e.identityKey.byteLength>0&&(n.uint32(10),n.bytes(e.identityKey)),e.identitySig!=null&&e.identitySig.byteLength>0&&(n.uint32(18),n.bytes(e.identitySig)),e.extensions!=null&&(n.uint32(34),Gs.codec().encode(e.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={identityKey:vt(0),identitySig:vt(0)},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:{o.identityKey=e.bytes();break}case 2:{o.identitySig=e.bytes();break}case 4:{o.extensions=Gs.codec().decode(e,e.uint32());break}default:{e.skipType(i&7);break}}}return o})),t),r.encode=e=>se(e,r.codec()),r.decode=e=>oe(e,r.codec())})(Yn||(Yn={}));async function kc(r,t,e){let n=await r.sign(Dh(t));return Yn.encode({identityKey:r.public.bytes,identitySig:n,extensions:e})}async function Cc(r,t,e){try{let n=Yn.decode(r);if(e){let i=e.subarray();if(!Et(i,n.identityKey))throw new Error(`Payload identity key ${G(n.identityKey,"hex")} does not match expected remote identity key ${G(i,"hex")}`)}if(!t)throw new Error("Remote static does not exist");let o=Dh(t);if(!await ch(n.identityKey).verify(o,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new $s(n.message)}}function Dh(r){let t=J("noise-libp2p-static-key:");return r instanceof Uint8Array?yt([t,r],t.length+r.length):(r.prepend(t),r)}async function Uh(r){let{log:t,connection:e,crypto:n,privateKey:o,prologue:s,s:i,remoteIdentityKey:a,extensions:c}=r,l=await kc(o,i.publicKey,c),u=new zn({crypto:n,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:s,s:i});vc(u.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await e.write(u.writeMessageA(Cr)),t.trace("Stage 0 - Initiator finished sending first message."),Ac(u.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let f=u.readMessageB(await e.read());t.trace("Stage 1 - Initiator received the message."),Sc(u.re,t),Lh(u.rs,t),t.trace("Initiator going to check remote's signature...");let p=await Cc(f,u.rs,a);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await e.write(u.writeMessageC(l)),t.trace("Stage 2 - Initiator sent message with signed payload.");let[y,m]=u.ss.split();return Bc(y,m,t),{payload:p,encrypt:h=>y.encryptWithAd(Cr,h),decrypt:(h,d)=>m.decryptWithAd(Cr,h,d)}}async function Ph(r){let{log:t,connection:e,crypto:n,privateKey:o,prologue:s,s:i,remoteIdentityKey:a,extensions:c}=r,l=await kc(o,i.publicKey,c),u=new zn({crypto:n,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:s,s:i});vc(u.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),u.readMessageA(await e.read()),t.trace("Stage 0 - Responder received first message."),Sc(u.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await e.write(u.writeMessageB(l)),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Ac(u.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let f=u.readMessageC(await e.read());t.trace("Stage 2 - Responder received the message, finished handshake.");let p=await Cc(f,u.rs,a),[y,m]=u.ss.split();return Bc(y,m,t),{payload:p,encrypt:h=>m.encryptWithAd(Cr,h),decrypt:(h,d)=>y.decryptWithAd(Cr,h,d)}}var Hh=16;function Mh(r,t){return async function*(e){for await(let n of e)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)),t?.encryptedPackets.increment(),yield new ct(ln(i.byteLength),i)}}}function Vh(r,t){return async function*(e){for await(let n of e)for(let o=0;o<n.length;o+=65535){let s=o+65535;if(s>n.length&&(s=n.length),s-Hh<o)throw new Error("Invalid chunk");let i=n.sublist(o,s),a=n.subarray(o,s-Hh);try{let c=r.decrypt(i,a);t?.decryptedPackets.increment(),yield c}catch(c){throw t?.decryptErrors.increment(),c}}}}var qs=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(t,e={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=e,{metrics:a}=t;this.components=t;let c=s??Rh;this.crypto=Th(c),this.extensions=o,this.metrics=a?Nh(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??vt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Rr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,e,n){let o=In(e,{lengthEncoder:ln,lengthDecoder:jn,maxDataLength:65535});if(!t.privateKey)throw new D("local peerId does not contain private key","ERR_NO_PRIVATE_KEY");let s=await cc(t.privateKey),i=n?.publicKey,a=await this.performHandshakeInitiator(o,s,i),c=await this.createSecureConnection(o,a);return e.source=c.source,e.sink=c.sink,{conn:e,remoteExtensions:a.payload.extensions,remotePeer:await Ii(a.payload.identityKey)}}async secureInbound(t,e,n){let o=In(e,{lengthEncoder:ln,lengthDecoder:jn,maxDataLength:65535});if(!t.privateKey)throw new D("local peerId does not contain private key","ERR_NO_PRIVATE_KEY");let s=await cc(t.privateKey),i=n?.publicKey,a=await this.performHandshakeResponder(o,s,i),c=await this.createSecureConnection(o,a);return e.source=c.source,e.sink=c.sink,{conn:e,remoteExtensions:a.payload.extensions,remotePeer:await Ii(a.payload.identityKey)}}async performHandshakeInitiator(t,e,n){let o;try{o=await Uh({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions}),this.metrics?.xxHandshakeSuccesses.increment()}catch(s){throw this.metrics?.xxHandshakeErrors.increment(),s}return o}async performHandshakeResponder(t,e,n){let o;try{o=await Ph({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions}),this.metrics?.xxHandshakeSuccesses.increment()}catch(s){throw this.metrics?.xxHandshakeErrors.increment(),s}return o}async createSecureConnection(t,e){let[n,o]=lh(),s=t.unwrap();return await fh(n,Mh(e,this.metrics),s,i=>dr(i,{lengthDecoder:jn}),Vh(e,this.metrics),n),o}};function Fh(r={}){return t=>new qs(t,r)}var Rc=Object.values(pe).map(r=>r.decoder).reduce((r,t)=>r.or(t));function Kh(r,t){let e=r.getConfiguration().certificates?.at(0);if(e==null||e.getFingerprints==null){t.log.trace("fetching fingerprint from local SDP");let o=r.localDescription;return o==null?void 0:ay(o.sdp)}if(t.log.trace("fetching fingerprint from local certificate"),e.getFingerprints().length===0)return;let n=e.getFingerprints()[0].value;if(n==null)throw ia("","no fingerprint on local certificate");return n}var iy=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function ay(r){return r.match(iy)?.groups?.fingerprint}function cy(r){for(let t of r.protoNames())if(t.startsWith("ip"))return t.toUpperCase();return"IP6"}function js(r){let e=r.stringTuples().filter(n=>n[0]===Gh).map(n=>n[1])[0];if(e===void 0||e==="")throw mo(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return e}function Tc(r){return te.decode(Rc.decode(r))}function ly(r){let t=Tc(js(r)),e=Nc(t.code),n=t.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw ia(n,r.toString());return[`${e} ${o.join(":").toUpperCase()}`,n]}function Nc(r){switch(r){case 17:return"SHA-1";case 18:return"SHA-256";case 19:return"SHA-512";default:throw Hl(r)}}function uy(r,t){let{host:e,port:n}=r.toOptions(),o=cy(r),[s]=ly(r);return`v=0
|
7
|
+
`)}async function bg(r,t){let e=Ot.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=J(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=on(o),{iv:i,salt:a,iterations:c,keySize:l,cipherText:u}=xg(s),f=await ja(_n,t,a,{c,dkLen:l}),p=await e.subtle.importKey("raw",f,"AES-CBC",!1,["decrypt"]),y=Kn(await e.subtle.decrypt({name:"AES-CBC",iv:i},p,u)),{result:m}=on(y);n=Wf(m)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=J(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=on(o);n=Wf(s)}else throw new D("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return tc(n)}function xg(r){let t=r.valueBlock.value[0];if(t.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new D("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=t.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new D("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=Kn(s.valueBlock.value[0].getValue()),a=Qa,c=Ja;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new D("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let l=t.valueBlock.value[1].valueBlock.value[1],u=l.valueBlock.value[0].toString();if(u!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(u!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new D("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let f=Kn(l.valueBlock.value[1].getValue());return{cipherText:Kn(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:f}}function Wf(r){return Kn(r.valueBlock.value[2].getValue())}function Kn(r){return new Uint8Array(r,0,r.byteLength)}async function Gf(r){let t=await Ot.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await zf(t);return{privateKey:e[0],publicKey:e[1]}}async function ec(r){let e=[await Ot.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Eg(r)],n=await zf({privateKey:e[0],publicKey:e[1]});return{privateKey:n[0],publicKey:n[1]}}async function qf(r,t){let e=await Ot.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ot.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function jf(r,t,e){let n=await Ot.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ot.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function zf(r){if(r.privateKey==null||r.publicKey==null)throw new D("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Ot.get().subtle.exportKey("jwk",r.privateKey),Ot.get().subtle.exportKey("jwk",r.publicKey)])}async function Eg(r){return Ot.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function Ms(r){if(r.kty!=="RSA")throw new D("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new D("invalid key modulus","ERR_INVALID_KEY_MODULUS");return J(r.n,"base64url").length*8}var Wn=8192,$n=class{_key;constructor(t){this._key=t}verify(t,e){return jf(this._key,e,t)}marshal(){return or.jwkToPkix(this._key)}get bytes(){return ye.encode({Type:ut.RSA,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}hash(){let t=Ct.digest(this.bytes);return Zt(t)?t.then(({bytes:e})=>e):t.bytes}},sn=class{_key;_publicKey;constructor(t,e){this._key=t,this._publicKey=e}genSecret(){return Br(16)}sign(t){return qf(this._key,t)}get public(){if(this._publicKey==null)throw new D("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new $n(this._publicKey)}marshal(){return or.jwkToPkcs1(this._key)}get bytes(){return we.encode({Type:ut.RSA,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}hash(){let t=Ct.digest(this.bytes);return Zt(t)?t.then(({bytes:e})=>e):t.bytes}async id(){let t=await this.public.hash();return G(t,"base58btc")}async export(t,e="pkcs-8"){if(e==="pkcs-8")return or.exportToPem(this,t);if(e==="libp2p-key")return Qr(this.bytes,t);throw new D(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function tc(r){let t=or.pkcs1ToJwk(r);if(Ms(t)>Wn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await ec(t);return new sn(e.privateKey,e.publicKey)}function Ag(r){let t=or.pkixToJwk(r);if(Ms(t)>Wn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new $n(t)}async function Sg(r){if(Ms(r)>Wn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await ec(r);return new sn(t.privateKey,t.publicKey)}async function Bg(r){if(r>Wn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await Gf(r);return new sn(t.privateKey,t.publicKey)}var ac={};xt(ac,{Secp256k1PrivateKey:()=>qn,Secp256k1PublicKey:()=>Gn,generateKeyPair:()=>Hg,unmarshalSecp256k1PrivateKey:()=>Pg,unmarshalSecp256k1PublicKey:()=>Og});var Ig=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]),sr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ir=new Uint32Array(64),nc=class extends Yr{constructor(){super(64,32,8,!1),this.A=sr[0]|0,this.B=sr[1]|0,this.C=sr[2]|0,this.D=sr[3]|0,this.E=sr[4]|0,this.F=sr[5]|0,this.G=sr[6]|0,this.H=sr[7]|0}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)ir[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let p=ir[f-15],y=ir[f-2],m=ae(p,7)^ae(p,18)^p>>>3,h=ae(y,17)^ae(y,19)^y>>>10;ir[f]=h+ir[f-7]+m+ir[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 p=ae(a,6)^ae(a,11)^ae(a,25),y=u+p+Tu(a,c,l)+Ig[f]+ir[f]|0,h=(ae(n,2)^ae(n,13)^ae(n,22))+Nu(n,o,s)|0;u=l,l=c,c=a,a=i+y|0,i=s,s=o,o=n,n=y+h|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(){ir.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var an=Vo(()=>new nc);function _g(r){let t=Cn(r);Xt(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:kg,hexToBytes:Cg}=$o,_r={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(r){let{Err:t}=_r;if(r.length<2||r[0]!==2)throw new t("Invalid signature integer tag");let e=r[1],n=r.subarray(2,e+2);if(!e||n.length!==e)throw new t("Invalid signature integer: wrong length");if(n[0]&128)throw new t("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return{d:kg(n),l:r.subarray(e+2)}},toSig(r){let{Err:t}=_r,e=typeof r=="string"?Cg(r):r;Zr(e);let n=e.length;if(n<2||e[0]!=48)throw new t("Invalid signature tag");if(e[1]!==n-2)throw new t("Invalid signature: incorrect length");let{d:o,l:s}=_r._parseInt(e.subarray(2)),{d:i,l:a}=_r._parseInt(s);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:o,s:i}},hexFromSig(r){let t=l=>Number.parseInt(l[0],16)&8?"00"+l:l,e=l=>{let u=l.toString(16);return u.length&1?`0${u}`:u},n=t(e(r.s)),o=t(e(r.r)),s=n.length/2,i=o.length/2,a=e(s),c=e(i);return`30${e(i+s+4)}02${c}${o}02${a}${n}`}},Ve=BigInt(0),Qt=BigInt(1),bA=BigInt(2),Yf=BigInt(3),xA=BigInt(4);function Rg(r){let t=_g(r),{Fp:e}=t,n=t.toBytes||((m,h,d)=>{let b=h.toAffine();return Ne(Uint8Array.from([4]),e.toBytes(b.x),e.toBytes(b.y))}),o=t.fromBytes||(m=>{let h=m.subarray(1),d=e.fromBytes(h.subarray(0,e.BYTES)),b=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:d,y:b}});function s(m){let{a:h,b:d}=t,b=e.sqr(m),E=e.mul(b,m);return e.add(e.add(E,e.mul(m,h)),d)}if(!e.eql(e.sqr(t.Gy),s(t.Gx)))throw new Error("bad generator point: equation left != right");function i(m){return typeof m=="bigint"&&Ve<m&&m<t.n}function a(m){if(!i(m))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(m){let{allowedPrivateKeyLengths:h,nByteLength:d,wrapPrivateKey:b,n:E}=t;if(h&&typeof m!="bigint"){if(Je(m)&&(m=Ce(m)),typeof m!="string"||!h.includes(m.length))throw new Error("Invalid key");m=m.padStart(d*2,"0")}let w;try{w=typeof m=="bigint"?m:Re(it("private key",m,d))}catch{throw new Error(`private key must be ${d} bytes, hex or bigint, not ${typeof m}`)}return b&&(w=tt(w,E)),a(w),w}let l=new Map;function u(m){if(!(m instanceof f))throw new Error("ProjectivePoint expected")}class f{constructor(h,d,b){if(this.px=h,this.py=d,this.pz=b,h==null||!e.isValid(h))throw new Error("x required");if(d==null||!e.isValid(d))throw new Error("y required");if(b==null||!e.isValid(b))throw new Error("z required")}static fromAffine(h){let{x:d,y:b}=h||{};if(!h||!e.isValid(d)||!e.isValid(b))throw new Error("invalid affine point");if(h instanceof f)throw new Error("projective point not allowed");let E=w=>e.eql(w,e.ZERO);return E(d)&&E(b)?f.ZERO:new f(d,b,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let d=e.invertBatch(h.map(b=>b.pz));return h.map((b,E)=>b.toAffine(d[E])).map(f.fromAffine)}static fromHex(h){let d=f.fromAffine(o(it("pointHex",h)));return d.assertValidity(),d}static fromPrivateKey(h){return f.BASE.multiply(c(h))}_setWindowSize(h){this._WINDOW_SIZE=h,l.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!e.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:h,y:d}=this.toAffine();if(!e.isValid(h)||!e.isValid(d))throw new Error("bad point: x or y not FE");let b=e.sqr(d),E=s(h);if(!e.eql(b,E))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){u(h);let{px:d,py:b,pz:E}=this,{px:w,py:S,pz:x}=h,B=e.eql(e.mul(d,x),e.mul(w,E)),I=e.eql(e.mul(b,x),e.mul(S,E));return B&&I}negate(){return new f(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:d}=t,b=e.mul(d,Yf),{px:E,py:w,pz:S}=this,x=e.ZERO,B=e.ZERO,I=e.ZERO,_=e.mul(E,E),N=e.mul(w,w),P=e.mul(S,S),T=e.mul(E,w);return T=e.add(T,T),I=e.mul(E,S),I=e.add(I,I),x=e.mul(h,I),B=e.mul(b,P),B=e.add(x,B),x=e.sub(N,B),B=e.add(N,B),B=e.mul(x,B),x=e.mul(T,x),I=e.mul(b,I),P=e.mul(h,P),T=e.sub(_,P),T=e.mul(h,T),T=e.add(T,I),I=e.add(_,_),_=e.add(I,_),_=e.add(_,P),_=e.mul(_,T),B=e.add(B,_),P=e.mul(w,S),P=e.add(P,P),_=e.mul(P,T),x=e.sub(x,_),I=e.mul(P,N),I=e.add(I,I),I=e.add(I,I),new f(x,B,I)}add(h){u(h);let{px:d,py:b,pz:E}=this,{px:w,py:S,pz:x}=h,B=e.ZERO,I=e.ZERO,_=e.ZERO,N=t.a,P=e.mul(t.b,Yf),T=e.mul(d,w),F=e.mul(b,S),V=e.mul(E,x),j=e.add(d,b),v=e.add(w,S);j=e.mul(j,v),v=e.add(T,F),j=e.sub(j,v),v=e.add(d,E);let C=e.add(w,x);return v=e.mul(v,C),C=e.add(T,V),v=e.sub(v,C),C=e.add(b,E),B=e.add(S,x),C=e.mul(C,B),B=e.add(F,V),C=e.sub(C,B),_=e.mul(N,v),B=e.mul(P,V),_=e.add(B,_),B=e.sub(F,_),_=e.add(F,_),I=e.mul(B,_),F=e.add(T,T),F=e.add(F,T),V=e.mul(N,V),v=e.mul(P,v),F=e.add(F,V),V=e.sub(T,V),V=e.mul(N,V),v=e.add(v,V),T=e.mul(F,v),I=e.add(I,T),T=e.mul(C,v),B=e.mul(j,B),B=e.sub(B,T),T=e.mul(j,F),_=e.mul(C,_),_=e.add(_,T),new f(B,I,_)}subtract(h){return this.add(h.negate())}is0(){return this.equals(f.ZERO)}wNAF(h){return y.wNAFCached(this,l,h,d=>{let b=e.invertBatch(d.map(E=>E.pz));return d.map((E,w)=>E.toAffine(b[w])).map(f.fromAffine)})}multiplyUnsafe(h){let d=f.ZERO;if(h===Ve)return d;if(a(h),h===Qt)return this;let{endo:b}=t;if(!b)return y.unsafeLadder(this,h);let{k1neg:E,k1:w,k2neg:S,k2:x}=b.splitScalar(h),B=d,I=d,_=this;for(;w>Ve||x>Ve;)w&Qt&&(B=B.add(_)),x&Qt&&(I=I.add(_)),_=_.double(),w>>=Qt,x>>=Qt;return E&&(B=B.negate()),S&&(I=I.negate()),I=new f(e.mul(I.px,b.beta),I.py,I.pz),B.add(I)}multiply(h){a(h);let d=h,b,E,{endo:w}=t;if(w){let{k1neg:S,k1:x,k2neg:B,k2:I}=w.splitScalar(d),{p:_,f:N}=this.wNAF(x),{p:P,f:T}=this.wNAF(I);_=y.constTimeNegate(S,_),P=y.constTimeNegate(B,P),P=new f(e.mul(P.px,w.beta),P.py,P.pz),b=_.add(P),E=N.add(T)}else{let{p:S,f:x}=this.wNAF(d);b=S,E=x}return f.normalizeZ([b,E])[0]}multiplyAndAddUnsafe(h,d,b){let E=f.BASE,w=(x,B)=>B===Ve||B===Qt||!x.equals(E)?x.multiplyUnsafe(B):x.multiply(B),S=w(this,d).add(w(h,b));return S.is0()?void 0:S}toAffine(h){let{px:d,py:b,pz:E}=this,w=this.is0();h==null&&(h=w?e.ONE:e.inv(E));let S=e.mul(d,h),x=e.mul(b,h),B=e.mul(E,h);if(w)return{x:e.ZERO,y:e.ZERO};if(!e.eql(B,e.ONE))throw new Error("invZ was invalid");return{x:S,y:x}}isTorsionFree(){let{h,isTorsionFree:d}=t;if(h===Qt)return!0;if(d)return d(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:d}=t;return h===Qt?this:d?d(f,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return this.assertValidity(),n(f,this,h)}toHex(h=!0){return Ce(this.toRawBytes(h))}}f.BASE=new f(t.Gx,t.Gy,e.ONE),f.ZERO=new f(e.ZERO,e.ONE,e.ZERO);let p=t.nBitLength,y=qo(f,t.endo?Math.ceil(p/2):p);return{CURVE:t,ProjectivePoint:f,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:i}}function Tg(r){let t=Cn(r);return Xt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function Zf(r){let t=Tg(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(v){return Ve<v&&v<e.ORDER}function a(v){return tt(v,n)}function c(v){return Wo(v,n)}let{ProjectivePoint:l,normPrivateKeyToScalar:u,weierstrassEquation:f,isWithinCurveOrder:p}=Rg({...t,toBytes(v,C,O){let A=C.toAffine(),g=e.toBytes(A.x),k=Ne;return O?k(Uint8Array.from([C.hasEvenY()?2:3]),g):k(Uint8Array.from([4]),g,e.toBytes(A.y))},fromBytes(v){let C=v.length,O=v[0],A=v.subarray(1);if(C===o&&(O===2||O===3)){let g=Re(A);if(!i(g))throw new Error("Point is not on curve");let k=f(g),R;try{R=e.sqrt(k)}catch(W){let Y=W instanceof Error?": "+W.message:"";throw new Error("Point is not on curve"+Y)}let L=(R&Qt)===Qt;return(O&1)===1!==L&&(R=e.neg(R)),{x:g,y:R}}else if(C===s&&O===4){let g=e.fromBytes(A.subarray(0,e.BYTES)),k=e.fromBytes(A.subarray(e.BYTES,2*e.BYTES));return{x:g,y:k}}else throw new Error(`Point of length ${C} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),y=v=>Ce(Qe(v,t.nByteLength));function m(v){let C=n>>Qt;return v>C}function h(v){return m(v)?a(-v):v}let d=(v,C,O)=>Re(v.slice(C,O));class b{constructor(C,O,A){this.r=C,this.s=O,this.recovery=A,this.assertValidity()}static fromCompact(C){let O=t.nByteLength;return C=it("compactSignature",C,O*2),new b(d(C,0,O),d(C,O,2*O))}static fromDER(C){let{r:O,s:A}=_r.toSig(it("DER",C));return new b(O,A)}assertValidity(){if(!p(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!p(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(C){return new b(this.r,this.s,C)}recoverPublicKey(C){let{r:O,s:A,recovery:g}=this,k=I(it("msgHash",C));if(g==null||![0,1,2,3].includes(g))throw new Error("recovery id invalid");let R=g===2||g===3?O+t.n:O;if(R>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let L=g&1?"03":"02",$=l.fromHex(L+y(R)),W=c(R),Y=a(-k*W),q=a(A*W),z=l.BASE.multiplyAndAddUnsafe($,Y,q);if(!z)throw new Error("point at infinify");return z.assertValidity(),z}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new b(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return vr(this.toDERHex())}toDERHex(){return _r.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return vr(this.toCompactHex())}toCompactHex(){return y(this.r)+y(this.s)}}let E={isValidPrivateKey(v){try{return u(v),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let v=Fa(t.n);return Ku(t.randomBytes(v),t.n)},precompute(v=8,C=l.BASE){return C._setWindowSize(v),C.multiply(BigInt(3)),C}};function w(v,C=!0){return l.fromPrivateKey(v).toRawBytes(C)}function S(v){let C=Je(v),O=typeof v=="string",A=(C||O)&&v.length;return C?A===o||A===s:O?A===2*o||A===2*s:v instanceof l}function x(v,C,O=!0){if(S(v))throw new Error("first arg must be private key");if(!S(C))throw new Error("second arg must be public key");return l.fromHex(C).multiply(u(v)).toRawBytes(O)}let B=t.bits2int||function(v){let C=Re(v),O=v.length*8-t.nBitLength;return O>0?C>>BigInt(O):C},I=t.bits2int_modN||function(v){return a(B(v))},_=kn(t.nBitLength);function N(v){if(typeof v!="bigint")throw new Error("bigint expected");if(!(Ve<=v&&v<_))throw new Error(`bigint expected < 2^${t.nBitLength}`);return Qe(v,t.nByteLength)}function P(v,C,O=T){if(["recovered","canonical"].some(nt=>nt in O))throw new Error("sign() legacy options not supported");let{hash:A,randomBytes:g}=t,{lowS:k,prehash:R,extraEntropy:L}=O;k==null&&(k=!0),v=it("msgHash",v),R&&(v=it("prehashed msgHash",A(v)));let $=I(v),W=u(C),Y=[N(W),N($)];if(L!=null&&L!==!1){let nt=L===!0?g(e.BYTES):L;Y.push(it("extraEntropy",nt))}let q=Ne(...Y),z=$;function st(nt){let _t=B(nt);if(!p(_t))return;let kt=c(_t),bt=l.BASE.multiply(_t).toAffine(),Lt=a(bt.x);if(Lt===Ve)return;let ve=a(kt*a(z+Lt*W));if(ve===Ve)return;let ar=(bt.x===Lt?0:2)|Number(bt.y&Qt),hn=ve;return k&&m(ve)&&(hn=h(ve),ar^=1),new b(Lt,hn,ar)}return{seed:q,k2sig:st}}let T={lowS:t.lowS,prehash:!1},F={lowS:t.lowS,prehash:!1};function V(v,C,O=T){let{seed:A,k2sig:g}=P(v,C,O),k=t;return Pa(k.hash.outputLen,k.nByteLength,k.hmac)(A,g)}l.BASE._setWindowSize(8);function j(v,C,O,A=F){let g=v;if(C=it("msgHash",C),O=it("publicKey",O),"strict"in A)throw new Error("options.strict was renamed to lowS");let{lowS:k,prehash:R}=A,L,$;try{if(typeof g=="string"||Je(g))try{L=b.fromDER(g)}catch(bt){if(!(bt instanceof _r.Err))throw bt;L=b.fromCompact(g)}else if(typeof g=="object"&&typeof g.r=="bigint"&&typeof g.s=="bigint"){let{r:bt,s:Lt}=g;L=new b(bt,Lt)}else throw new Error("PARSE");$=l.fromHex(O)}catch(bt){if(bt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(k&&L.hasHighS())return!1;R&&(C=t.hash(C));let{r:W,s:Y}=L,q=I(C),z=c(Y),st=a(q*z),nt=a(W*z),_t=l.BASE.multiplyAndAddUnsafe($,st,nt)?.toAffine();return _t?a(_t.x)===W:!1}return{CURVE:t,getPublicKey:w,getSharedSecret:x,sign:V,verify:j,ProjectivePoint:l,Signature:b,utils:E}}function Ng(r){return{hash:r,hmac:(t,...e)=>tr(r,t,Ta(...e)),randomBytes:Er}}function Xf(r,t){let e=n=>Zf({...r,...Ng(n)});return Object.freeze({...e(t),create:e})}var th=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Jf=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Lg=BigInt(1),oc=BigInt(2),Qf=(r,t)=>(r+t/oc)/t;function Dg(r){let t=th,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=at(u,e,t)*u%t,p=at(f,e,t)*u%t,y=at(p,oc,t)*l%t,m=at(y,o,t)*y%t,h=at(m,s,t)*m%t,d=at(h,a,t)*h%t,b=at(d,c,t)*d%t,E=at(b,a,t)*h%t,w=at(E,e,t)*u%t,S=at(w,i,t)*m%t,x=at(S,n,t)*l%t,B=at(x,oc,t);if(!sc.eql(sc.sqr(B),r))throw new Error("Cannot find square root");return B}var sc=Go(th,void 0,void 0,{sqrt:Dg}),de=Xf({a:BigInt(0),b:BigInt(7),Fp:sc,n:Jf,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=Jf,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Lg*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=Qf(s*r,t),c=Qf(-n*r,t),l=tt(r-a*e-c*o,t),u=tt(-a*n-c*s,t),f=l>i,p=u>i;if(f&&(l=t-l),p&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:p,k2:u}}}},an),CA=BigInt(0);var RA=de.ProjectivePoint;function eh(){return de.utils.randomPrivateKey()}function rh(r,t){let e=Ct.digest(t instanceof Uint8Array?t:t.subarray());if(Zt(e))return e.then(({digest:n})=>de.sign(n,r).toDERRawBytes()).catch(n=>{throw new D(String(n),"ERR_INVALID_INPUT")});try{return de.sign(e.digest,r).toDERRawBytes()}catch(n){throw new D(String(n),"ERR_INVALID_INPUT")}}function nh(r,t,e){let n=Ct.digest(e instanceof Uint8Array?e:e.subarray());if(Zt(n))return n.then(({digest:o})=>de.verify(t,o,r)).catch(o=>{throw new D(String(o),"ERR_INVALID_INPUT")});try{return de.verify(t,n.digest,r)}catch(o){throw new D(String(o),"ERR_INVALID_INPUT")}}function oh(r){return de.ProjectivePoint.fromHex(r).toRawBytes(!0)}function sh(r){try{de.getPublicKey(r,!0)}catch(t){throw new D(String(t),"ERR_INVALID_PRIVATE_KEY")}}function ic(r){try{de.ProjectivePoint.fromHex(r)}catch(t){throw new D(String(t),"ERR_INVALID_PUBLIC_KEY")}}function ih(r){try{return de.getPublicKey(r,!0)}catch(t){throw new D(String(t),"ERR_INVALID_PRIVATE_KEY")}}var Gn=class{_key;constructor(t){ic(t),this._key=t}verify(t,e){return nh(this._key,e,t)}marshal(){return oh(this._key)}get bytes(){return ye.encode({Type:ut.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}async hash(){let t=Ct.digest(this.bytes),e;return Zt(t)?{bytes:e}=await t:e=t.bytes,e}},qn=class{_key;_publicKey;constructor(t,e){this._key=t,this._publicKey=e??ih(t),sh(this._key),ic(this._publicKey)}sign(t){return rh(this._key,t)}get public(){return new Gn(this._publicKey)}marshal(){return this._key}get bytes(){return we.encode({Type:ut.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}hash(){let t=Ct.digest(this.bytes);return Zt(t)?t.then(({bytes:e})=>e):t.bytes}async id(){let t=await this.public.hash();return G(t,"base58btc")}async export(t,e="libp2p-key"){if(e==="libp2p-key")return Qr(this.bytes,t);throw new D(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function Pg(r){return new qn(r)}function Og(r){return new Gn(r)}async function Hg(){let r=eh();return new qn(r)}var kr={rsa:rc,ed25519:qa,secp256k1:ac};function ah(r){let t=Object.keys(kr).join(" / ");return new D(`invalid or unsupported key type ${r}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function ch(r){let t=ye.decode(r),e=t.Data??new Uint8Array;switch(t.Type){case ut.RSA:return kr.rsa.unmarshalRsaPublicKey(e);case ut.Ed25519:return kr.ed25519.unmarshalEd25519PublicKey(e);case ut.Secp256k1:return kr.secp256k1.unmarshalSecp256k1PublicKey(e);default:throw ah(t.Type??"unknown")}}async function cc(r){let t=we.decode(r),e=t.Data??new Uint8Array;switch(t.Type){case ut.RSA:return kr.rsa.unmarshalRsaPrivateKey(e);case ut.Ed25519:return kr.ed25519.unmarshalEd25519PrivateKey(e);case ut.Secp256k1:return kr.secp256k1.unmarshalSecp256k1PrivateKey(e);default:throw ah(t.Type??"RSA")}}function lc(){let r=ht(),t=!1;return{sink:async e=>{if(t)throw new Error("already piped");t=!0,r.resolve(e)},source:async function*(){yield*await r.promise}()}}function lh(){let r=lc(),t=lc();return[{source:r.source,sink:t.sink},{source:t.source,sink:r.sink}]}function Mg(r){return r[Symbol.asyncIterator]!=null}function Vg(...r){let t=[];for(let e of r)Mg(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=Ge({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)e.push(o)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var uh=Vg;function fh(r,...t){if(r==null)throw new Error("Empty pipeline");if(uc(r)){let n=r;r=()=>n.source}else if(dh(r)||hh(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&uc(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)uc(e[n])&&(e[n]=Kg(e[n]));return Fg(...e)}var Fg=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},hh=r=>r?.[Symbol.asyncIterator]!=null,dh=r=>r?.[Symbol.iterator]!=null,uc=r=>r==null?!1:r.sink!=null&&r.source!=null,Kg=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Ge({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(hh(s))o=async function*(){yield*s,n.end()};else if(dh(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return uh(n,o())}return r.source};var cn=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function Vs(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function fc(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function hc(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Kt(r,...t){if(!hc(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function dc(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function ph(r,t){Kt(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var Fe=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),mh=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),$g=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!$g)throw new Error("Non little-endian hardware is not supported");function Wg(r){if(typeof r!="string")throw new Error(`string expected, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Fs(r){if(typeof r=="string")r=Wg(r);else if(hc(r))r=r.slice();else throw new Error(`Uint8Array expected, got ${typeof r}`);return r}function gh(r,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(r,t)}function yh(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}var pc=(r,t)=>(Object.assign(t,r),t);function mc(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}var Nt=(r,t)=>r[t++]&255|(r[t++]&255)<<8,gc=class{constructor(t){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,t=Fs(t),Kt(t,32);let e=Nt(t,0),n=Nt(t,2),o=Nt(t,4),s=Nt(t,6),i=Nt(t,8),a=Nt(t,10),c=Nt(t,12),l=Nt(t,14);this.r[0]=e&8191,this.r[1]=(e>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Nt(t,16+2*u)}process(t,e,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],p=i[5],y=i[6],m=i[7],h=i[8],d=i[9],b=Nt(t,e+0),E=Nt(t,e+2),w=Nt(t,e+4),S=Nt(t,e+6),x=Nt(t,e+8),B=Nt(t,e+10),I=Nt(t,e+12),_=Nt(t,e+14),N=s[0]+(b&8191),P=s[1]+((b>>>13|E<<3)&8191),T=s[2]+((E>>>10|w<<6)&8191),F=s[3]+((w>>>7|S<<9)&8191),V=s[4]+((S>>>4|x<<12)&8191),j=s[5]+(x>>>1&8191),v=s[6]+((x>>>14|B<<2)&8191),C=s[7]+((B>>>11|I<<5)&8191),O=s[8]+((I>>>8|_<<8)&8191),A=s[9]+(_>>>5|o),g=0,k=g+N*a+P*(5*d)+T*(5*h)+F*(5*m)+V*(5*y);g=k>>>13,k&=8191,k+=j*(5*p)+v*(5*f)+C*(5*u)+O*(5*l)+A*(5*c),g+=k>>>13,k&=8191;let R=g+N*c+P*a+T*(5*d)+F*(5*h)+V*(5*m);g=R>>>13,R&=8191,R+=j*(5*y)+v*(5*p)+C*(5*f)+O*(5*u)+A*(5*l),g+=R>>>13,R&=8191;let L=g+N*l+P*c+T*a+F*(5*d)+V*(5*h);g=L>>>13,L&=8191,L+=j*(5*m)+v*(5*y)+C*(5*p)+O*(5*f)+A*(5*u),g+=L>>>13,L&=8191;let $=g+N*u+P*l+T*c+F*a+V*(5*d);g=$>>>13,$&=8191,$+=j*(5*h)+v*(5*m)+C*(5*y)+O*(5*p)+A*(5*f),g+=$>>>13,$&=8191;let W=g+N*f+P*u+T*l+F*c+V*a;g=W>>>13,W&=8191,W+=j*(5*d)+v*(5*h)+C*(5*m)+O*(5*y)+A*(5*p),g+=W>>>13,W&=8191;let Y=g+N*p+P*f+T*u+F*l+V*c;g=Y>>>13,Y&=8191,Y+=j*a+v*(5*d)+C*(5*h)+O*(5*m)+A*(5*y),g+=Y>>>13,Y&=8191;let q=g+N*y+P*p+T*f+F*u+V*l;g=q>>>13,q&=8191,q+=j*c+v*a+C*(5*d)+O*(5*h)+A*(5*m),g+=q>>>13,q&=8191;let z=g+N*m+P*y+T*p+F*f+V*u;g=z>>>13,z&=8191,z+=j*l+v*c+C*a+O*(5*d)+A*(5*h),g+=z>>>13,z&=8191;let st=g+N*h+P*m+T*y+F*p+V*f;g=st>>>13,st&=8191,st+=j*u+v*l+C*c+O*a+A*(5*d),g+=st>>>13,st&=8191;let nt=g+N*d+P*h+T*m+F*y+V*p;g=nt>>>13,nt&=8191,nt+=j*f+v*u+C*l+O*c+A*a,g+=nt>>>13,nt&=8191,g=(g<<2)+g|0,g=g+k|0,k=g&8191,g=g>>>13,R+=g,s[0]=k,s[1]=R,s[2]=L,s[3]=$,s[4]=W,s[5]=Y,s[6]=q,s[7]=z,s[8]=st,s[9]=nt}finalize(){let{h:t,pad:e}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+e[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+e[a]|0)+(i>>>16)|0,t[a]=i&65535}update(t){dc(this);let{buffer:e,blockLen:n}=this;t=Fs(t);let o=t.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(t,s);continue}e.set(t.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(e,0,!1),this.pos=0)}return this}destroy(){this.h.fill(0),this.r.fill(0),this.buffer.fill(0),this.pad.fill(0)}digestInto(t){dc(this),ph(t,this),this.finished=!0;let{buffer:e,h:n}=this,{pos:o}=this;if(o){for(e[o++]=1;o<16;o++)e[o]=0;this.process(e,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)t[s++]=n[i]>>>0,t[s++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}};function Gg(r){let t=(n,o)=>r(o).update(Fs(n)).digest(),e=r(new Uint8Array(32));return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=n=>r(n),t}var wh=Gg(r=>new gc(r));var xh=r=>Uint8Array.from(r.split("").map(t=>t.charCodeAt(0))),qg=xh("expand 16-byte k"),jg=xh("expand 32-byte k"),zg=Fe(qg),Eh=Fe(jg),cS=Eh.slice();function M(r,t){return r<<t|r>>>32-t}function yc(r){return r.byteOffset%4===0}var Ks=64,Yg=16,vh=2**32-1,bh=new Uint32Array;function Zg(r,t,e,n,o,s,i,a){let c=o.length,l=new Uint8Array(Ks),u=Fe(l),f=yc(o)&&yc(s),p=f?Fe(o):bh,y=f?Fe(s):bh;for(let m=0;m<c;i++){if(r(t,e,n,u,i,a),i>=vh)throw new Error("arx: counter overflow");let h=Math.min(Ks,c-m);if(f&&h===Ks){let d=m/4;if(m%4!==0)throw new Error("arx: invalid block position");for(let b=0,E;b<Yg;b++)E=d+b,y[E]=p[E]^u[b];m+=Ks;continue}for(let d=0,b;d<h;d++)b=m+d,s[b]=o[b]^l[d];m+=h}}function wc(r,t){let{allowShortKeys:e,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=gh({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof r!="function")throw new Error("core must be a function");return Vs(o),Vs(i),fc(s),fc(e),(a,c,l,u,f=0)=>{Kt(a),Kt(c),Kt(l);let p=l.length;if(u||(u=new Uint8Array(p)),Kt(u),Vs(f),f<0||f>=vh)throw new Error("arx: counter overflow");if(u.length<p)throw new Error(`arx: output (${u.length}) is shorter than data (${p})`);let y=[],m=a.length,h,d;if(m===32)h=a.slice(),y.push(h),d=Eh;else if(m===16&&e)h=new Uint8Array(32),h.set(a),h.set(a,16),d=zg,y.push(h);else throw new Error(`arx: invalid 32-byte key, got length=${m}`);yc(c)||(c=c.slice(),y.push(c));let b=Fe(h);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(d,b,Fe(c.subarray(0,16)),b),c=c.subarray(16)}let E=16-o;if(E!==c.length)throw new Error(`arx: nonce must be ${E} or 16 bytes`);if(E!==12){let S=new Uint8Array(12);S.set(c,s?0:12-c.length),c=S,y.push(c)}let w=Fe(c);for(Zg(r,d,b,w,l,u,f,i);y.length>0;)y.pop().fill(0);return u}}function Bh(r,t,e,n,o,s=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=t[0],f=t[1],p=t[2],y=t[3],m=t[4],h=t[5],d=t[6],b=t[7],E=o,w=e[0],S=e[1],x=e[2],B=i,I=a,_=c,N=l,P=u,T=f,F=p,V=y,j=m,v=h,C=d,O=b,A=E,g=w,k=S,R=x;for(let $=0;$<s;$+=2)B=B+P|0,A=M(A^B,16),j=j+A|0,P=M(P^j,12),B=B+P|0,A=M(A^B,8),j=j+A|0,P=M(P^j,7),I=I+T|0,g=M(g^I,16),v=v+g|0,T=M(T^v,12),I=I+T|0,g=M(g^I,8),v=v+g|0,T=M(T^v,7),_=_+F|0,k=M(k^_,16),C=C+k|0,F=M(F^C,12),_=_+F|0,k=M(k^_,8),C=C+k|0,F=M(F^C,7),N=N+V|0,R=M(R^N,16),O=O+R|0,V=M(V^O,12),N=N+V|0,R=M(R^N,8),O=O+R|0,V=M(V^O,7),B=B+T|0,R=M(R^B,16),C=C+R|0,T=M(T^C,12),B=B+T|0,R=M(R^B,8),C=C+R|0,T=M(T^C,7),I=I+F|0,A=M(A^I,16),O=O+A|0,F=M(F^O,12),I=I+F|0,A=M(A^I,8),O=O+A|0,F=M(F^O,7),_=_+V|0,g=M(g^_,16),j=j+g|0,V=M(V^j,12),_=_+V|0,g=M(g^_,8),j=j+g|0,V=M(V^j,7),N=N+P|0,k=M(k^N,16),v=v+k|0,P=M(P^v,12),N=N+P|0,k=M(k^N,8),v=v+k|0,P=M(P^v,7);let L=0;n[L++]=i+B|0,n[L++]=a+I|0,n[L++]=c+_|0,n[L++]=l+N|0,n[L++]=u+P|0,n[L++]=f+T|0,n[L++]=p+F|0,n[L++]=y+V|0,n[L++]=m+j|0,n[L++]=h+v|0,n[L++]=d+C|0,n[L++]=b+O|0,n[L++]=E+A|0,n[L++]=w+g|0,n[L++]=S+k|0,n[L++]=x+R|0}function Xg(r,t,e,n){let o=r[0],s=r[1],i=r[2],a=r[3],c=t[0],l=t[1],u=t[2],f=t[3],p=t[4],y=t[5],m=t[6],h=t[7],d=e[0],b=e[1],E=e[2],w=e[3];for(let x=0;x<20;x+=2)o=o+c|0,d=M(d^o,16),p=p+d|0,c=M(c^p,12),o=o+c|0,d=M(d^o,8),p=p+d|0,c=M(c^p,7),s=s+l|0,b=M(b^s,16),y=y+b|0,l=M(l^y,12),s=s+l|0,b=M(b^s,8),y=y+b|0,l=M(l^y,7),i=i+u|0,E=M(E^i,16),m=m+E|0,u=M(u^m,12),i=i+u|0,E=M(E^i,8),m=m+E|0,u=M(u^m,7),a=a+f|0,w=M(w^a,16),h=h+w|0,f=M(f^h,12),a=a+f|0,w=M(w^a,8),h=h+w|0,f=M(f^h,7),o=o+l|0,w=M(w^o,16),m=m+w|0,l=M(l^m,12),o=o+l|0,w=M(w^o,8),m=m+w|0,l=M(l^m,7),s=s+u|0,d=M(d^s,16),h=h+d|0,u=M(u^h,12),s=s+u|0,d=M(d^s,8),h=h+d|0,u=M(u^h,7),i=i+f|0,b=M(b^i,16),p=p+b|0,f=M(f^p,12),i=i+f|0,b=M(b^i,8),p=p+b|0,f=M(f^p,7),a=a+c|0,E=M(E^a,16),y=y+E|0,c=M(c^y,12),a=a+c|0,E=M(E^a,8),y=y+E|0,c=M(c^y,7);let S=0;n[S++]=o,n[S++]=s,n[S++]=i,n[S++]=a,n[S++]=d,n[S++]=b,n[S++]=E,n[S++]=w}var Jg=wc(Bh,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Qg=wc(Bh,{counterRight:!1,counterLength:8,extendNonceFn:Xg,allowShortKeys:!1});var ty=new Uint8Array(16),Ah=(r,t)=>{r.update(t);let e=t.length%16;e&&r.update(ty.subarray(e))},ey=new Uint8Array(32);function Sh(r,t,e,n,o){let s=r(t,e,ey),i=wh.create(s);o&&Ah(i,o),Ah(i,n);let a=new Uint8Array(16),c=mh(a);mc(c,0,BigInt(o?o.length:0),!0),mc(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return s.fill(0),l}var Ih=r=>(t,e,n)=>(Kt(t,32),Kt(e),{encrypt:(s,i)=>{let a=s.length,c=a+16;i?Kt(i,c):i=new Uint8Array(c),r(t,e,s,i,1);let l=Sh(r,t,e,i.subarray(0,-16),n);return i.set(l,a),i},decrypt:(s,i)=>{let a=s.length,c=a-16;if(a<16)throw new Error("encrypted data must be at least 16 bytes");i?Kt(i,c):i=new Uint8Array(c);let l=s.subarray(0,-16),u=s.subarray(-16),f=Sh(r,t,e,l,n);if(!yh(u,f))throw new Error("invalid tag");return r(t,e,l,i,1),i}}),bc=pc({blockSize:64,nonceLength:12,tagLength:16},Ih(Jg)),pS=pc({blockSize:64,nonceLength:24,tagLength:16},Ih(Qg));function kh(r,t,e){return xr(r),e===void 0&&(e=new Uint8Array(r.outputLen)),tr(r,ce(e),ce(t))}var xc=new Uint8Array([0]),_h=new Uint8Array;function Ch(r,t,e,n=32){if(xr(r),Ye(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);e===void 0&&(e=_h);let s=new Uint8Array(o*r.outputLen),i=tr.create(r,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)xc[0]=l+1,a.update(l===0?_h:c).update(e).update(xc).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),xc.fill(0),s.slice(0,n)}var Ec={hashSHA256(r){return an(r.subarray())},getHKDF(r,t){let e=kh(an,t,r),o=Ch(an,e,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=Nn.utils.randomPrivateKey();return{publicKey:Nn.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:Nn.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,t){return Nn.getSharedSecret(r.subarray(),t.subarray())},chaCha20Poly1305Encrypt(r,t,e,n){return bc(n,t,e).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,t,e,n,o){return bc(n,t,e).decrypt(r.subarray(),o)}};var Rh=Ec;function Th(r){return{generateKeypair:r.generateX25519KeyPair,dh:(t,e)=>r.generateX25519SharedKey(t.privateKey,e).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var ln=r=>{let t=At(2);return t[0]=r>>8,t[1]=r,t};ln.bytes=2;var jn=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let t=0;return t+=r[0]<<8,t+=r[1],t}return r.getUint16(0)};jn.bytes=2;function Nh(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 vc(r,t){!t.enabled||!cn||(r?(t(`LOCAL_STATIC_PUBLIC_KEY ${G(r.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${G(r.privateKey,"hex")}`)):t("Missing local static keys."))}function Ac(r,t){!t.enabled||!cn||(r?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${G(r.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${G(r.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function Lh(r,t){!t.enabled||!cn||t(r?`REMOTE_STATIC_PUBLIC_KEY ${G(r.subarray(),"hex")}`:"Missing remote static public key.")}function Sc(r,t){!t.enabled||!cn||t(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${G(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Bc(r,t,e){!e.enabled||!cn||(e(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&G(r.k,"hex")}`),e(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&G(t.k,"hex")}`))}var $s=class r extends Error{code;constructor(t="Unexpected Peer"){super(t),this.code=r.code}static code="ERR_UNEXPECTED_PEER"},un=class r extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var ry=0,ny=4294967295,oy="Cipherstate has reached maximum n, a new handshake must be performed",Ws=class{n;bytes;view;constructor(t=ry){this.n=t,this.bytes=vt(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>ny)throw new Error(oy)}};var Cr=vt(0),fn=class{k;n;crypto;constructor(t,e=void 0,n=0){this.crypto=t,this.k=e,this.n=new Ws(n)}hasKey(){return!!this.k}encryptWithAd(t,e){if(!this.hasKey())return e;this.n.assertValue();let n=this.crypto.encrypt(e,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,e,n){if(!this.hasKey())return e;this.n.assertValue();let o=this.crypto.decrypt(e,this.n.getBytes(),t,this.k,n);return this.n.increment(),o}},Ic=class{cs;ck;h;crypto;constructor(t,e){this.crypto=t;let n=J(e,"utf-8");this.h=sy(t,n),this.ck=this.h,this.cs=new fn(t)}mixKey(t){let[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new fn(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new ct(this.h,t))}encryptAndHash(t){let e=this.cs.encryptWithAd(this.h,t);return this.mixHash(e),e}decryptAndHash(t){let e=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),e}split(){let[t,e]=this.crypto.hkdf(this.ck,Cr);return[new fn(this.crypto,t),new fn(this.crypto,e)]}},_c=class{ss;s;e;rs;re;initiator;crypto;constructor(t){let{crypto:e,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=t;this.crypto=e,this.ss=new Ic(e,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 t=this.crypto.generateKeypair();return this.ss.mixHash(t.publicKey),this.e=t,t.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(t,e=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<e+32)throw new Error("message is not long enough");this.re=t.sublist(e,e+32),this.ss.mixHash(this.re)}readS(t,e=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(t.byteLength<e+n)throw new Error("message is not long enough");let o=t.sublist(e,e+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},zn=class extends _c{writeMessageA(t){return new ct(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let e=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new ct(e,n,this.ss.encryptAndHash(t))}writeMessageC(t){let e=this.writeS();return this.writeSE(),new ct(e,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(e){throw new un(`handshake stage 0 validation fail: ${e.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();let e=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+e))}catch(e){throw new un(`handshake stage 1 validation fail: ${e.message}`)}}readMessageC(t){try{let e=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(e))}catch(e){throw new un(`handshake stage 2 validation fail: ${e.message}`)}}};function sy(r,t){if(t.length<=32){let e=vt(32);return e.set(t),e}else return r.hash(t)}var Gs;(function(r){let t;r.codec=()=>(t==null&&(t=ie((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.webtransportCerthashes!=null)for(let s of e.webtransportCerthashes)n.uint32(10),n.bytes(s);o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={webtransportCerthashes:[]},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:{o.webtransportCerthashes.push(e.bytes());break}default:{e.skipType(i&7);break}}}return o})),t),r.encode=e=>se(e,r.codec()),r.decode=e=>oe(e,r.codec())})(Gs||(Gs={}));var Yn;(function(r){let t;r.codec=()=>(t==null&&(t=ie((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.identityKey!=null&&e.identityKey.byteLength>0&&(n.uint32(10),n.bytes(e.identityKey)),e.identitySig!=null&&e.identitySig.byteLength>0&&(n.uint32(18),n.bytes(e.identitySig)),e.extensions!=null&&(n.uint32(34),Gs.codec().encode(e.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={identityKey:vt(0),identitySig:vt(0)},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:{o.identityKey=e.bytes();break}case 2:{o.identitySig=e.bytes();break}case 4:{o.extensions=Gs.codec().decode(e,e.uint32());break}default:{e.skipType(i&7);break}}}return o})),t),r.encode=e=>se(e,r.codec()),r.decode=e=>oe(e,r.codec())})(Yn||(Yn={}));async function kc(r,t,e){let n=await r.sign(Dh(t));return Yn.encode({identityKey:r.public.bytes,identitySig:n,extensions:e})}async function Cc(r,t,e){try{let n=Yn.decode(r);if(e){let i=e.subarray();if(!Et(i,n.identityKey))throw new Error(`Payload identity key ${G(n.identityKey,"hex")} does not match expected remote identity key ${G(i,"hex")}`)}if(!t)throw new Error("Remote static does not exist");let o=Dh(t);if(!await ch(n.identityKey).verify(o,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new $s(n.message)}}function Dh(r){let t=J("noise-libp2p-static-key:");return r instanceof Uint8Array?yt([t,r],t.length+r.length):(r.prepend(t),r)}async function Uh(r){let{log:t,connection:e,crypto:n,privateKey:o,prologue:s,s:i,remoteIdentityKey:a,extensions:c}=r,l=await kc(o,i.publicKey,c),u=new zn({crypto:n,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:s,s:i});vc(u.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await e.write(u.writeMessageA(Cr)),t.trace("Stage 0 - Initiator finished sending first message."),Ac(u.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let f=u.readMessageB(await e.read());t.trace("Stage 1 - Initiator received the message."),Sc(u.re,t),Lh(u.rs,t),t.trace("Initiator going to check remote's signature...");let p=await Cc(f,u.rs,a);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await e.write(u.writeMessageC(l)),t.trace("Stage 2 - Initiator sent message with signed payload.");let[y,m]=u.ss.split();return Bc(y,m,t),{payload:p,encrypt:h=>y.encryptWithAd(Cr,h),decrypt:(h,d)=>m.decryptWithAd(Cr,h,d)}}async function Ph(r){let{log:t,connection:e,crypto:n,privateKey:o,prologue:s,s:i,remoteIdentityKey:a,extensions:c}=r,l=await kc(o,i.publicKey,c),u=new zn({crypto:n,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:s,s:i});vc(u.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),u.readMessageA(await e.read()),t.trace("Stage 0 - Responder received first message."),Sc(u.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await e.write(u.writeMessageB(l)),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Ac(u.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let f=u.readMessageC(await e.read());t.trace("Stage 2 - Responder received the message, finished handshake.");let p=await Cc(f,u.rs,a),[y,m]=u.ss.split();return Bc(y,m,t),{payload:p,encrypt:h=>m.encryptWithAd(Cr,h),decrypt:(h,d)=>y.decryptWithAd(Cr,h,d)}}var Hh=16;function Mh(r,t){return async function*(e){for await(let n of e)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)),t?.encryptedPackets.increment(),yield new ct(ln(i.byteLength),i)}}}function Vh(r,t){return async function*(e){for await(let n of e)for(let o=0;o<n.length;o+=65535){let s=o+65535;if(s>n.length&&(s=n.length),s-Hh<o)throw new Error("Invalid chunk");let i=n.sublist(o,s),a=n.subarray(o,s-Hh);try{let c=r.decrypt(i,a);t?.decryptedPackets.increment(),yield c}catch(c){throw t?.decryptErrors.increment(),c}}}}var qs=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(t,e={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=e,{metrics:a}=t;this.components=t;let c=s??Rh;this.crypto=Th(c),this.extensions=o,this.metrics=a?Nh(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??vt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Rr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,e,n){let o=In(e,{lengthEncoder:ln,lengthDecoder:jn,maxDataLength:65535});if(!t.privateKey)throw new D("local peerId does not contain private key","ERR_NO_PRIVATE_KEY");let s=await cc(t.privateKey),i=n?.publicKey,a=await this.performHandshakeInitiator(o,s,i),c=await this.createSecureConnection(o,a);return e.source=c.source,e.sink=c.sink,{conn:e,remoteExtensions:a.payload.extensions,remotePeer:await Ii(a.payload.identityKey)}}async secureInbound(t,e,n){let o=In(e,{lengthEncoder:ln,lengthDecoder:jn,maxDataLength:65535});if(!t.privateKey)throw new D("local peerId does not contain private key","ERR_NO_PRIVATE_KEY");let s=await cc(t.privateKey),i=n?.publicKey,a=await this.performHandshakeResponder(o,s,i),c=await this.createSecureConnection(o,a);return e.source=c.source,e.sink=c.sink,{conn:e,remoteExtensions:a.payload.extensions,remotePeer:await Ii(a.payload.identityKey)}}async performHandshakeInitiator(t,e,n){let o;try{o=await Uh({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions}),this.metrics?.xxHandshakeSuccesses.increment()}catch(s){throw this.metrics?.xxHandshakeErrors.increment(),s}return o}async performHandshakeResponder(t,e,n){let o;try{o=await Ph({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions}),this.metrics?.xxHandshakeSuccesses.increment()}catch(s){throw this.metrics?.xxHandshakeErrors.increment(),s}return o}async createSecureConnection(t,e){let[n,o]=lh(),s=t.unwrap();return await fh(n,Mh(e,this.metrics),s,i=>dr(i,{lengthDecoder:jn}),Vh(e,this.metrics),n),o}};function Fh(r={}){return t=>new qs(t,r)}var Rc=Object.values(pe).map(r=>r.decoder).reduce((r,t)=>r.or(t));function Kh(r,t){let e=r.getConfiguration().certificates?.at(0);if(e?.getFingerprints==null){t.log.trace("fetching fingerprint from local SDP");let o=r.localDescription;return o==null?void 0:ay(o.sdp)}if(t.log.trace("fetching fingerprint from local certificate"),e.getFingerprints().length===0)return;let n=e.getFingerprints()[0].value;if(n==null)throw ia("","no fingerprint on local certificate");return n}var iy=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function ay(r){return r.match(iy)?.groups?.fingerprint}function cy(r){for(let t of r.protoNames())if(t.startsWith("ip"))return t.toUpperCase();return"IP6"}function js(r){let e=r.stringTuples().filter(n=>n[0]===Gh).map(n=>n[1])[0];if(e===void 0||e==="")throw mo(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return e}function Tc(r){return te.decode(Rc.decode(r))}function ly(r){let t=Tc(js(r)),e=Nc(t.code),n=t.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw ia(n,r.toString());return[`${e} ${o.join(":").toUpperCase()}`,n]}function Nc(r){switch(r){case 17:return"SHA-1";case 18:return"SHA-256";case 19:return"SHA-512";default:throw Hl(r)}}function uy(r,t){let{host:e,port:n}=r.toOptions(),o=cy(r),[s]=ly(r);return`v=0
|
8
8
|
o=- 0 0 IN ${o} ${e}
|
9
9
|
s=-
|
10
10
|
c=IN ${o} ${e}
|