@libp2p/webrtc 5.2.9-78cd7d53e → 5.2.9-d53ef170c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,5 +1,5 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PWebrtc = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var Libp2PWebrtc=(()=>{var zo=Object.defineProperty;var uf=Object.getOwnPropertyDescriptor;var ff=Object.getOwnPropertyNames;var hf=Object.prototype.hasOwnProperty;var It=(r,t)=>{for(var e in t)zo(r,e,{get:t[e],enumerable:!0})},df=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ff(t))!hf.call(r,o)&&o!==e&&zo(r,o,{get:()=>t[o],enumerable:!(n=uf(t,o))||n.enumerable});return r};var pf=r=>df(zo({},"__esModule",{value:!0}),r);var Vm={};It(Vm,{webRTC:()=>qm,webRTCDirect:()=>Hm});var $o=Symbol.for("@libp2p/peer-id");var mn=Symbol.for("@libp2p/transport");var Oa;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Oa||(Oa={}));var gn=class extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}},yn=class extends Error{static name="InvalidCryptoExchangeError";constructor(t="Invalid crypto exchange"){super(t),this.name="InvalidCryptoExchangeError"}},Q=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Je=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var wn=class extends Error{static name="ConnectionFailedError";constructor(t="Connection failed"){super(t),this.name="ConnectionFailedError"}};var xn=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}},Ne=class extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}};var bn=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},En=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var Sn=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var An=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}};var ke=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Qe=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){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 CustomEvent(t,e))}};var tr=Symbol.for("@libp2p/service-capabilities"),Ka=Symbol.for("@libp2p/service-dependencies");async function Ma(r,t,e){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,t,e.subarray())}function mt(r=0){return new Uint8Array(r)}function gt(r=0){return new Uint8Array(r)}function yt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=gt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}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}var Ha=Symbol.for("@achingbrain/uint8arraylist");function Fa(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 vn(r){return!!r?.[Ha]}var V=class r{bufs;length;[Ha]=!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(vn(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(vn(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=Fa(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Fa(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(vn(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(!vn(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 d=l;d>=0;d--){let g=this.get(f+d);if(n[d]!==g){u=Math.max(1,d-a[g]);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=gt(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=mt(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=mt(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=mt(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=gt(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=mt(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=mt(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=mt(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=mt(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=mt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Et(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var Jo={};It(Jo,{base10:()=>Ef});var _0=new Uint8Array(0);function qa(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 oe(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 Va(r){return new TextEncoder().encode(r)}function Wa(r){return new TextDecoder().decode(r)}function gf(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(x){if(x instanceof Uint8Array||(ArrayBuffer.isView(x)?x=new Uint8Array(x.buffer,x.byteOffset,x.byteLength):Array.isArray(x)&&(x=Uint8Array.from(x))),!(x instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(x.length===0)return"";for(var m=0,h=0,w=0,b=x.length;w!==b&&x[w]===0;)w++,m++;for(var p=(b-w)*u+1>>>0,I=new Uint8Array(p);w!==b;){for(var P=x[w],B=0,v=p-1;(P!==0||B<h)&&v!==-1;v--,B++)P+=256*I[v]>>>0,I[v]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");h=B,w++}for(var L=p-h;L!==p&&I[L]===0;)L++;for(var T=c.repeat(m);L<p;++L)T+=r.charAt(I[L]);return T}function d(x){if(typeof x!="string")throw new TypeError("Expected String");if(x.length===0)return new Uint8Array;var m=0;if(x[m]!==" "){for(var h=0,w=0;x[m]===c;)h++,m++;for(var b=(x.length-m)*l+1>>>0,p=new Uint8Array(b);x[m];){var I=e[x.charCodeAt(m)];if(I===255)return;for(var P=0,B=b-1;(I!==0||P<w)&&B!==-1;B--,P++)I+=a*p[B]>>>0,p[B]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");w=P,m++}if(x[m]!==" "){for(var v=b-w;v!==b&&p[v]===0;)v++;for(var L=new Uint8Array(h+(b-v)),T=h;v!==b;)L[T++]=p[v++];return L}}}function g(x){var m=d(x);if(m)return m;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:g}}var yf=gf,wf=yf,za=wf;var jo=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")}},Xo=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return $a(this,t)}},Zo=class{decoders;constructor(t){this.decoders=t}or(t){return $a(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 $a(r,t){return new Zo({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Yo=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 jo(t,e,n),this.decoder=new Xo(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function er({name:r,prefix:t,encode:e,decode:n}){return new Yo(r,t,e,n)}function we({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=za(e,r);return er({prefix:t,name:r,encode:n,decode:s=>oe(o(s))})}function xf(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)!==0)throw new SyntaxError("Unexpected end of data");return i}function bf(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function ht({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return er({prefix:t,name:r,encode(o){return bf(o,n,e)},decode(o){return xf(o,n,e,r)}})}var Ef=we({prefix:"9",name:"base10",alphabet:"0123456789"});var Qo={};It(Qo,{base16:()=>Sf,base16upper:()=>Af});var Sf=ht({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Af=ht({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ts={};It(ts,{base2:()=>vf});var vf=ht({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var es={};It(es,{base256emoji:()=>Lf});var ja=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}"),If=ja.reduce((r,t,e)=>(r[e]=t,r),[]),Cf=ja.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Tf(r){return r.reduce((t,e)=>(t+=If[e],t),"")}function _f(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Cf[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var Lf=er({prefix:"\u{1F680}",name:"base256emoji",encode:Tf,decode:_f});var rs={};It(rs,{base32:()=>se,base32hex:()=>Df,base32hexpad:()=>kf,base32hexpadupper:()=>Uf,base32hexupper:()=>Nf,base32pad:()=>Pf,base32padupper:()=>Rf,base32upper:()=>Bf,base32z:()=>Of});var se=ht({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Bf=ht({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Pf=ht({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Rf=ht({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Df=ht({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Nf=ht({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),kf=ht({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Uf=ht({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Of=ht({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ns={};It(ns,{base36:()=>Lr,base36upper:()=>Kf});var Lr=we({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Kf=we({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var os={};It(os,{base58btc:()=>et,base58flickr:()=>Mf});var et=we({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Mf=we({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ss={};It(ss,{base64:()=>Ff,base64pad:()=>Hf,base64url:()=>Br,base64urlpad:()=>qf});var Ff=ht({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Hf=ht({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Br=ht({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),qf=ht({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var is={};It(is,{base8:()=>Vf});var Vf=ht({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var as={};It(as,{identity:()=>Wf});var Wf=er({prefix:"\0",name:"identity",encode:r=>Wa(r),decode:r=>Va(r)});var W0=new TextEncoder,G0=new TextDecoder;var us={};It(us,{identity:()=>Wt});var Ft={};It(Ft,{Digest:()=>Ue,create:()=>Ct,decode:()=>xe,equals:()=>ls,hasCode:()=>fh});var $f=Ya,Xa=128,jf=127,Xf=~jf,Zf=Math.pow(2,31);function Ya(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Zf;)t[e++]=r&255|Xa,r/=128;for(;r&Xf;)t[e++]=r&255|Xa,r>>>=7;return t[e]=r|0,Ya.bytes=e-n+1,t}var Yf=cs,Jf=128,Za=127;function cs(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw cs.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&Za)<<o:(i&Za)*Math.pow(2,o),o+=7}while(i>=Jf);return cs.bytes=s-n,e}var Qf=Math.pow(2,7),th=Math.pow(2,14),eh=Math.pow(2,21),rh=Math.pow(2,28),nh=Math.pow(2,35),oh=Math.pow(2,42),sh=Math.pow(2,49),ih=Math.pow(2,56),ah=Math.pow(2,63),ch=function(r){return r<Qf?1:r<th?2:r<eh?3:r<rh?4:r<nh?5:r<oh?6:r<sh?7:r<ih?8:r<ah?9:10},lh={encode:$f,decode:Yf,encodingLength:ch},uh=lh,Pr=uh;function Rr(r,t=0){return[Pr.decode(r,t),Pr.decode.bytes]}function rr(r,t,e=0){return Pr.encode(r,t,e),t}function nr(r){return Pr.encodingLength(r)}function Ct(r,t){let e=t.byteLength,n=nr(r),o=n+nr(e),s=new Uint8Array(o+e);return rr(r,s,0),rr(e,s,n),s.set(t,o),new Ue(r,e,t,s)}function xe(r){let t=oe(r),[e,n]=Rr(t),[o,s]=Rr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Ue(e,o,i,t)}function ls(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&qa(r.bytes,e.bytes)}}var Ue=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function fh(r,t){return r.code===t}var Ja=0,hh="identity",Qa=oe;function dh(r){return Ct(Ja,Qa(r))}var Wt={code:Ja,name:hh,encode:Qa,digest:dh};var ds={};It(ds,{sha256:()=>ie,sha512:()=>ph});function hs({name:r,code:t,encode:e}){return new fs(r,t,e)}var fs=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?Ct(this.code,e):e.then(n=>Ct(this.code,n))}else throw Error("Unknown type, must be binary type")}};function ec(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var ie=hs({name:"sha2-256",code:18,encode:ec("SHA-256")}),ph=hs({name:"sha2-512",code:19,encode:ec("SHA-512")});function rc(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return gh(e,ps(r),t??et.encoder);default:return yh(e,ps(r),t??se.encoder)}}var nc=new WeakMap;function ps(r){let t=nc.get(r);if(t==null){let e=new Map;return nc.set(r,e),e}return t}var dt=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!==Dr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==wh)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=Ct(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&&ls(t.multihash,n.multihash)}toString(t){return rc(this,t)}toJSON(){return{"/":rc(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??oc(n,o,s.bytes))}else if(e[xh]===!0){let{version:n,multihash:o,code:s}=e,i=xe(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!==Dr)throw new Error(`Version 0 CID must use dag-pb (code: ${Dr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=oc(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Dr,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=oe(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 Ue(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,d]=Rr(t.subarray(e));return e+=d,f},o=n(),s=Dr;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]=mh(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 ps(s).set(n,t),s}};function mh(r,t){switch(r[0]){case"Q":{let e=t??et;return[et.prefix,e.decode(`${et.prefix}${r}`)]}case et.prefix:{let e=t??et;return[et.prefix,e.decode(r)]}case se.prefix:{let e=t??se;return[se.prefix,e.decode(r)]}case Lr.prefix:{let e=t??Lr;return[Lr.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function gh(r,t,e){let{prefix:n}=e;if(n!==et.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 yh(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 Dr=112,wh=18;function oc(r,t,e){let n=nr(r),o=n+nr(t),s=new Uint8Array(o+e.byteLength);return rr(r,s,0),rr(t,s,n),s.set(e,o),s}var xh=Symbol.for("@ipld/js-cid/CID");var Oe={...as,...ts,...is,...Jo,...Qo,...rs,...ns,...os,...ss,...es},dg={...ds,...us};function ic(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var sc=ic("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ms=ic("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=gt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),bh={utf8:sc,"utf-8":sc,hex:Oe.base16,latin1:ms,ascii:ms,binary:ms,...Oe},Cn=bh;function X(r,t="utf8"){let e=Cn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function H(r,t="utf8"){let e=Cn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Eh=parseInt("11111",2),gs=parseInt("10000000",2),Sh=parseInt("01111111",2),ac={0:Nr,1:Nr,2:Ah,3:Ch,4:Th,5:Ih,6:vh,16:Nr,22:Nr,48:Nr};function ae(r,t={offset:0}){let e=r[t.offset]&Eh;if(t.offset++,ac[e]!=null)return ac[e](r,t);throw new Error("No decoder for tag "+e)}function kr(r,t){let e=0;if((r[t.offset]&gs)===gs){let n=r[t.offset]&Sh,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function Nr(r,t){kr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=ae(r,t);if(n===null)break;e.push(n)}return e}function Ah(r,t){let e=kr(r,t),n=t.offset,o=t.offset+e,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return t.offset+=e,Uint8Array.from(s)}function vh(r,t){let e=kr(r,t),n=t.offset+e,o=r[t.offset];t.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;t.offset<n;){let l=r[t.offset];if(t.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function Ih(r,t){return t.offset++,null}function Ch(r,t){let e=kr(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Th(r,t){let e=kr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function _h(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new V;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function ys(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=_h(r.byteLength);return new V(Uint8Array.from([t.byteLength|gs]),t)}function Nt(r){let t=new V,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new V(Uint8Array.from([2]),ys(t),t)}function Tn(r){let t=Uint8Array.from([0]),e=new V(t,r);return new V(Uint8Array.from([3]),ys(e),e)}function be(r,t=48){let e=new V;for(let n of r)e.append(n);return new V(Uint8Array.from([t]),ys(e),e)}var or=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=cc(this.jwk)),this._raw}toMultihash(){return Wt.digest(Ee(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return et.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}async verify(t,e){return Ma(this.jwk,e,t)}};var Lh=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Bh=Uint8Array.from([6,5,43,129,4,0,34]),Ph=Uint8Array.from([6,5,43,129,4,0,35]),Rh={ext:!0,kty:"EC",crv:"P-256"},Dh={ext:!0,kty:"EC",crv:"P-384"},Nh={ext:!0,kty:"EC",crv:"P-521"},ws=32,xs=48,bs=66;function Es(r){let t=ae(r);return lc(t)}function lc(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===ws*2+1)return n=H(t.subarray(e,e+ws),"base64url"),o=H(t.subarray(e+ws),"base64url"),new or({...Rh,key_ops:["verify"],x:n,y:o});if(t.byteLength===xs*2+1)return n=H(t.subarray(e,e+xs),"base64url"),o=H(t.subarray(e+xs),"base64url"),new or({...Dh,key_ops:["verify"],x:n,y:o});if(t.byteLength===bs*2+1)return n=H(t.subarray(e,e+bs),"base64url"),o=H(t.subarray(e+bs),"base64url"),new or({...Nh,key_ops:["verify"],x:n,y:o});throw new Q(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function cc(r){return be([Nt(Uint8Array.from([1])),be([kh(r.crv)],160),be([Tn(new V(Uint8Array.from([4]),X(r.x??"","base64url"),X(r.y??"","base64url")))],161)]).subarray()}function kh(r){if(r==="P-256")return Lh;if(r==="P-384")return Bh;if(r==="P-521")return Ph;throw new Q(`Invalid curve ${r}`)}function _n(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Uh(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function sr(r,...t){if(!Uh(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function Ur(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");_n(r.outputLen),_n(r.blockLen)}function ir(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 uc(r,t){sr(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}var Ke=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Ln(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Gt(r,t){return r<<32-t|r>>>t}function fc(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function Se(r){return typeof r=="string"&&(r=fc(r)),sr(r),r}function Ss(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];sr(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 ar=class{clone(){return this._cloneInto()}};function Bn(r){let t=n=>r().update(Se(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Or(r=32){if(Ke&&typeof Ke.getRandomValues=="function")return Ke.getRandomValues(new Uint8Array(r));if(Ke&&typeof Ke.randomBytes=="function")return Ke.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function Oh(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)}function hc(r,t,e){return r&t^~r&e}function dc(r,t,e){return r&t^r&e^t&e}var cr=class extends ar{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=Ln(this.buffer)}update(t){ir(this);let{view:e,buffer:n,blockLen:o}=this;t=Se(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=Ln(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){ir(this),uc(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;Oh(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Ln(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 Pn=BigInt(4294967295),As=BigInt(32);function pc(r,t=!1){return t?{h:Number(r&Pn),l:Number(r>>As&Pn)}:{h:Number(r>>As&Pn)|0,l:Number(r&Pn)|0}}function Kh(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}=pc(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var Mh=(r,t)=>BigInt(r>>>0)<<As|BigInt(t>>>0),Fh=(r,t,e)=>r>>>e,Hh=(r,t,e)=>r<<32-e|t>>>e,qh=(r,t,e)=>r>>>e|t<<32-e,Vh=(r,t,e)=>r<<32-e|t>>>e,Wh=(r,t,e)=>r<<64-e|t>>>e-32,Gh=(r,t,e)=>r>>>e-32|t<<64-e,zh=(r,t)=>t,$h=(r,t)=>r,jh=(r,t,e)=>r<<e|t>>>32-e,Xh=(r,t,e)=>t<<e|r>>>32-e,Zh=(r,t,e)=>t<<e-32|r>>>64-e,Yh=(r,t,e)=>r<<e-32|t>>>64-e;function Jh(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Qh=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),td=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,ed=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),rd=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,nd=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),od=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var sd={fromBig:pc,split:Kh,toBig:Mh,shrSH:Fh,shrSL:Hh,rotrSH:qh,rotrSL:Vh,rotrBH:Wh,rotrBL:Gh,rotr32H:zh,rotr32L:$h,rotlSH:jh,rotlSL:Xh,rotlBH:Zh,rotlBL:Yh,add:Jh,add3L:Qh,add3H:td,add4L:ed,add4H:rd,add5H:od,add5L:nd},W=sd;var[id,ad]=W.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))),Ae=new Uint32Array(80),ve=new Uint32Array(80),vs=class extends cr{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:d,Gh:g,Gl:x,Hh:m,Hl:h}=this;return[t,e,n,o,s,i,a,c,l,u,f,d,g,x,m,h]}set(t,e,n,o,s,i,a,c,l,u,f,d,g,x,m,h){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=d|0,this.Gh=g|0,this.Gl=x|0,this.Hh=m|0,this.Hl=h|0}process(t,e){for(let p=0;p<16;p++,e+=4)Ae[p]=t.getUint32(e),ve[p]=t.getUint32(e+=4);for(let p=16;p<80;p++){let I=Ae[p-15]|0,P=ve[p-15]|0,B=W.rotrSH(I,P,1)^W.rotrSH(I,P,8)^W.shrSH(I,P,7),v=W.rotrSL(I,P,1)^W.rotrSL(I,P,8)^W.shrSL(I,P,7),L=Ae[p-2]|0,T=ve[p-2]|0,K=W.rotrSH(L,T,19)^W.rotrBH(L,T,61)^W.shrSH(L,T,6),N=W.rotrSL(L,T,19)^W.rotrBL(L,T,61)^W.shrSL(L,T,6),O=W.add4L(v,N,ve[p-7],ve[p-16]),F=W.add4H(O,B,K,Ae[p-7],Ae[p-16]);Ae[p]=F|0,ve[p]=O|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:g,Fl:x,Gh:m,Gl:h,Hh:w,Hl:b}=this;for(let p=0;p<80;p++){let I=W.rotrSH(f,d,14)^W.rotrSH(f,d,18)^W.rotrBH(f,d,41),P=W.rotrSL(f,d,14)^W.rotrSL(f,d,18)^W.rotrBL(f,d,41),B=f&g^~f&m,v=d&x^~d&h,L=W.add5L(b,P,v,ad[p],ve[p]),T=W.add5H(L,w,I,B,id[p],Ae[p]),K=L|0,N=W.rotrSH(n,o,28)^W.rotrBH(n,o,34)^W.rotrBH(n,o,39),O=W.rotrSL(n,o,28)^W.rotrBL(n,o,34)^W.rotrBL(n,o,39),F=n&s^n&a^s&a,C=o&i^o&c^i&c;w=m|0,b=h|0,m=g|0,h=x|0,g=f|0,x=d|0,{h:f,l:d}=W.add(l|0,u|0,T|0,K|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let _=W.add3L(K,O,C);n=W.add3H(_,T,N,F),o=_|0}({h:n,l:o}=W.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=W.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=W.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=W.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=W.add(this.Eh|0,this.El|0,f|0,d|0),{h:g,l:x}=W.add(this.Fh|0,this.Fl|0,g|0,x|0),{h:m,l:h}=W.add(this.Gh|0,this.Gl|0,m|0,h|0),{h:w,l:b}=W.add(this.Hh|0,this.Hl|0,w|0,b|0),this.set(n,o,s,i,a,c,l,u,f,d,g,x,m,h,w,b)}roundClean(){Ae.fill(0),ve.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 mc=Bn(()=>new vs);var Nn={};It(Nn,{aInRange:()=>St,abool:()=>zt,abytes:()=>lr,bitGet:()=>dd,bitLen:()=>_s,bitMask:()=>Mr,bitSet:()=>pd,bytesToHex:()=>le,bytesToNumberBE:()=>ue,bytesToNumberLE:()=>$t,concatBytes:()=>he,createHmacDrbg:()=>Ls,ensureBytes:()=>st,equalBytes:()=>fd,hexToBytes:()=>Fe,hexToNumber:()=>Ts,inRange:()=>Kr,isBytes:()=>Ie,memoized:()=>He,notImplemented:()=>gd,numberToBytesBE:()=>Ce,numberToBytesLE:()=>fe,numberToHexUnpadded:()=>Me,numberToVarBytesBE:()=>ud,utf8ToBytes:()=>hd,validateObject:()=>Ht});var Rn=BigInt(0),Dn=BigInt(1),cd=BigInt(2);function Ie(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function lr(r){if(!Ie(r))throw new Error("Uint8Array expected")}function zt(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}var ld=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function le(r){lr(r);let t="";for(let e=0;e<r.length;e++)t+=ld[r[e]];return t}function Me(r){let t=r.toString(16);return t.length&1?"0"+t:t}function Ts(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Rn:BigInt("0x"+r)}var ce={_0:48,_9:57,A:65,F:70,a:97,f:102};function gc(r){if(r>=ce._0&&r<=ce._9)return r-ce._0;if(r>=ce.A&&r<=ce.F)return r-(ce.A-10);if(r>=ce.a&&r<=ce.f)return r-(ce.a-10)}function Fe(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("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=gc(r.charCodeAt(s)),a=gc(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 ue(r){return Ts(le(r))}function $t(r){return lr(r),Ts(le(Uint8Array.from(r).reverse()))}function Ce(r,t){return Fe(r.toString(16).padStart(t*2,"0"))}function fe(r,t){return Ce(r,t).reverse()}function ud(r){return Fe(Me(r))}function st(r,t,e){let n;if(typeof t=="string")try{n=Fe(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Ie(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+" of length "+e+" expected, got "+o);return n}function he(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];lr(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 fd(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 hd(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var Is=r=>typeof r=="bigint"&&Rn<=r;function Kr(r,t,e){return Is(r)&&Is(t)&&Is(e)&&t<=r&&r<e}function St(r,t,e,n){if(!Kr(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function _s(r){let t;for(t=0;r>Rn;r>>=Dn,t+=1);return t}function dd(r,t){return r>>BigInt(t)&Dn}function pd(r,t,e){return r|(e?Dn:Rn)<<BigInt(t)}var Mr=r=>(cd<<BigInt(r-1))-Dn,Cs=r=>new Uint8Array(r),yc=r=>Uint8Array.from(r);function Ls(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=Cs(r),o=Cs(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=Cs())=>{o=a(yc([0]),f),n=a(),f.length!==0&&(o=a(yc([1]),f),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<t;){n=a();let g=n.slice();d.push(g),f+=n.length}return he(...d)};return(f,d)=>{i(),c(f);let g;for(;!(g=d(l()));)c();return i(),g}}var md={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"||Ie(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 Ht(r,t,e={}){let n=(o,s,i)=>{let a=md[s];if(typeof a!="function")throw new Error("invalid validator function");let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(e))n(o,s,!0);return r}var gd=()=>{throw new Error("not implemented")};function He(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var wt=BigInt(0),ft=BigInt(1),qe=BigInt(2),yd=BigInt(3),Bs=BigInt(4),wc=BigInt(5),xc=BigInt(8),wd=BigInt(9),xd=BigInt(16);function Y(r,t){let e=r%t;return e>=wt?e:t+e}function Ps(r,t,e){if(t<wt)throw new Error("invalid exponent, negatives unsupported");if(e<=wt)throw new Error("invalid modulus");if(e===ft)return wt;let n=ft;for(;t>wt;)t&ft&&(n=n*r%e),r=r*r%e,t>>=ft;return n}function ct(r,t,e){let n=r;for(;t-- >wt;)n*=n,n%=e;return n}function kn(r,t){if(r===wt)throw new Error("invert: expected non-zero number");if(t<=wt)throw new Error("invert: expected positive modulus, got "+t);let e=Y(r,t),n=t,o=wt,s=ft,i=ft,a=wt;for(;e!==wt;){let l=n/e,u=n%e,f=o-i*l,d=s-a*l;n=e,e=u,o=i,s=a,i=f,a=d}if(n!==ft)throw new Error("invert: does not exist");return Y(o,t)}function bd(r){let t=(r-ft)/qe,e,n,o;for(e=r-ft,n=0;e%qe===wt;e/=qe,n++);for(o=qe;o<r&&Ps(o,t,r)!==r-ft;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(r+ft)/Bs;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+ft)/qe;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),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let g=1;for(let m=a.sqr(d);g<l&&!a.eql(m,a.ONE);g++)m=a.sqr(m);let x=a.pow(u,ft<<BigInt(l-g-1));u=a.sqr(x),f=a.mul(f,x),d=a.mul(d,u),l=g}return f}}function Ed(r){if(r%Bs===yd){let t=(r+ft)/Bs;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%xc===wc){let t=(r-wc)/xc;return function(n,o){let s=n.mul(o,qe),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,qe),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%xd,bd(r)}var bc=(r,t)=>(Y(r,t)&ft)===ft,Sd=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Rs(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Sd.reduce((n,o)=>(n[o]="function",n),t);return Ht(r,e)}function Ad(r,t,e){if(e<wt)throw new Error("invalid exponent, negatives unsupported");if(e===wt)return r.ONE;if(e===ft)return t;let n=r.ONE,o=t;for(;e>wt;)e&ft&&(n=r.mul(n,o)),o=r.sqr(o),e>>=ft;return n}function vd(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 Ds(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Te(r,t,e=!1,n={}){if(r<=wt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=Ds(r,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:r,isLE:e,BITS:o,BYTES:s,MASK:Mr(o),ZERO:wt,ONE:ft,create:c=>Y(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return wt<=c&&c<r},is0:c=>c===wt,isOdd:c=>(c&ft)===ft,neg:c=>Y(-c,r),eql:(c,l)=>c===l,sqr:c=>Y(c*c,r),add:(c,l)=>Y(c+l,r),sub:(c,l)=>Y(c-l,r),mul:(c,l)=>Y(c*l,r),pow:(c,l)=>Ad(a,c,l),div:(c,l)=>Y(c*kn(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>kn(c,r),sqrt:n.sqrt||(c=>(i||(i=Ed(r)),i(a,c))),invertBatch:c=>vd(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?fe(c,s):Ce(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return e?$t(c):ue(c)}});return Object.freeze(a)}function Ec(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 Ns(r){let t=Ec(r);return t+Math.ceil(t/2)}function Sc(r,t,e=!1){let n=r.length,o=Ec(t),s=Ns(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?$t(r):ue(r),a=Y(i,t-ft)+ft;return e?fe(a,o):Ce(a,o)}var Ac=BigInt(0),Un=BigInt(1);function ks(r,t){let e=t.negate();return r?e:t}function vc(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Us(r,t){vc(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1);return{windows:e,windowSize:n}}function Id(r,t){if(!Array.isArray(r))throw new Error("array expected");r.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}function Cd(r,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}var Os=new WeakMap,Ic=new WeakMap;function Ks(r){return Ic.get(r)||1}function On(r,t){return{constTimeNegate:ks,hasPrecomputes(e){return Ks(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>Ac;)n&Un&&(o=o.add(s)),s=s.double(),n>>=Un;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=Us(n,t),i=[],a=e,c=a;for(let l=0;l<o;l++){c=a,i.push(c);for(let u=1;u<s;u++)c=c.add(a),i.push(c);a=c.double()}return i},wNAF(e,n,o){let{windows:s,windowSize:i}=Us(e,t),a=r.ZERO,c=r.BASE,l=BigInt(2**e-1),u=2**e,f=BigInt(e);for(let d=0;d<s;d++){let g=d*i,x=Number(o&l);o>>=f,x>i&&(x-=u,o+=Un);let m=g,h=g+Math.abs(x)-1,w=d%2!==0,b=x<0;x===0?c=c.add(ks(w,n[m])):a=a.add(ks(b,n[h]))}return{p:a,f:c}},wNAFUnsafe(e,n,o,s=r.ZERO){let{windows:i,windowSize:a}=Us(e,t),c=BigInt(2**e-1),l=2**e,u=BigInt(e);for(let f=0;f<i;f++){let d=f*a;if(o===Ac)break;let g=Number(o&c);if(o>>=u,g>a&&(g-=l,o+=Un),g===0)continue;let x=n[d+Math.abs(g)-1];g<0&&(x=x.negate()),s=s.add(x)}return s},getPrecomputes(e,n,o){let s=Os.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&Os.set(n,o(s))),s},wNAFCached(e,n,o){let s=Ks(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=Ks(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){vc(n,t),Ic.set(e,n),Os.delete(e)}}}function Kn(r,t,e,n){if(Id(e,r),Cd(n,t),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,s=_s(BigInt(e.length)),i=s>12?s-3:s>4?s-2:s?2:1,a=(1<<i)-1,c=new Array(a+1).fill(o),l=Math.floor((t.BITS-1)/i)*i,u=o;for(let f=l;f>=0;f-=i){c.fill(o);for(let g=0;g<n.length;g++){let x=n[g],m=Number(x>>BigInt(f)&BigInt(a));c[m]=c[m].add(e[g])}let d=o;for(let g=c.length-1,x=o;g>0;g--)x=x.add(c[g]),d=d.add(x);if(u=u.add(d),f!==0)for(let g=0;g<i;g++)u=u.double()}return u}function Fr(r){return Rs(r.Fp),Ht(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ds(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var jt=BigInt(0),kt=BigInt(1),Mn=BigInt(2),Td=BigInt(8),_d={zip215:!0};function Ld(r){let t=Fr(r);return Ht(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Cc(r){let t=Ld(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=Mn<<BigInt(a*8)-kt,u=e.create,f=Te(t.n,t.nBitLength),d=t.uvRatio||((E,y)=>{try{return{isValid:!0,value:e.sqrt(E*e.inv(y))}}catch{return{isValid:!1,value:jt}}}),g=t.adjustScalarBytes||(E=>E),x=t.domain||((E,y,A)=>{if(zt("phflag",A),y.length||A)throw new Error("Contexts/pre-hash are not supported");return E});function m(E,y){St("coordinate "+E,y,jt,l)}function h(E){if(!(E instanceof p))throw new Error("ExtendedPoint expected")}let w=He((E,y)=>{let{ex:A,ey:S,ez:R}=E,D=E.is0();y==null&&(y=D?Td:e.inv(R));let U=u(A*y),q=u(S*y),M=u(R*y);if(D)return{x:jt,y:kt};if(M!==kt)throw new Error("invZ was invalid");return{x:U,y:q}}),b=He(E=>{let{a:y,d:A}=t;if(E.is0())throw new Error("bad point: ZERO");let{ex:S,ey:R,ez:D,et:U}=E,q=u(S*S),M=u(R*R),G=u(D*D),j=u(G*G),it=u(q*y),at=u(G*u(it+M)),ut=u(j+u(A*u(q*M)));if(at!==ut)throw new Error("bad point: equation left != right (1)");let vt=u(S*R),Dt=u(D*U);if(vt!==Dt)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(y,A,S,R){this.ex=y,this.ey=A,this.ez=S,this.et=R,m("x",y),m("y",A),m("z",S),m("t",R),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(y){if(y instanceof p)throw new Error("extended point not allowed");let{x:A,y:S}=y||{};return m("x",A),m("y",S),new p(A,S,kt,u(A*S))}static normalizeZ(y){let A=e.invertBatch(y.map(S=>S.ez));return y.map((S,R)=>S.toAffine(A[R])).map(p.fromAffine)}static msm(y,A){return Kn(p,f,y,A)}_setWindowSize(y){B.setWindowSize(this,y)}assertValidity(){b(this)}equals(y){h(y);let{ex:A,ey:S,ez:R}=this,{ex:D,ey:U,ez:q}=y,M=u(A*q),G=u(D*R),j=u(S*q),it=u(U*R);return M===G&&j===it}is0(){return this.equals(p.ZERO)}negate(){return new p(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:y}=t,{ex:A,ey:S,ez:R}=this,D=u(A*A),U=u(S*S),q=u(Mn*u(R*R)),M=u(y*D),G=A+S,j=u(u(G*G)-D-U),it=M+U,at=it-q,ut=M-U,vt=u(j*at),Dt=u(it*ut),Rt=u(j*ut),Qt=u(at*it);return new p(vt,Dt,Qt,Rt)}add(y){h(y);let{a:A,d:S}=t,{ex:R,ey:D,ez:U,et:q}=this,{ex:M,ey:G,ez:j,et:it}=y;if(A===BigInt(-1)){let Ba=u((D-R)*(G+M)),Pa=u((D+R)*(G-M)),Go=u(Pa-Ba);if(Go===jt)return this.double();let Ra=u(U*Mn*it),Da=u(q*Mn*j),Na=Da+Ra,ka=Pa+Ba,Ua=Da-Ra,sf=u(Na*Go),af=u(ka*Ua),cf=u(Na*Ua),lf=u(Go*ka);return new p(sf,af,lf,cf)}let at=u(R*M),ut=u(D*G),vt=u(q*S*it),Dt=u(U*j),Rt=u((R+D)*(M+G)-at-ut),Qt=Dt-vt,ne=Dt+vt,_r=u(ut-A*at),ef=u(Rt*Qt),rf=u(ne*_r),nf=u(Rt*_r),of=u(Qt*ne);return new p(ef,rf,of,nf)}subtract(y){return this.add(y.negate())}wNAF(y){return B.wNAFCached(this,y,p.normalizeZ)}multiply(y){let A=y;St("scalar",A,kt,n);let{p:S,f:R}=this.wNAF(A);return p.normalizeZ([S,R])[0]}multiplyUnsafe(y,A=p.ZERO){let S=y;return St("scalar",S,jt,n),S===jt?P:this.is0()||S===kt?this:B.wNAFCachedUnsafe(this,S,p.normalizeZ,A)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return B.unsafeLadder(this,n).is0()}toAffine(y){return w(this,y)}clearCofactor(){let{h:y}=t;return y===kt?this:this.multiplyUnsafe(y)}static fromHex(y,A=!1){let{d:S,a:R}=t,D=e.BYTES;y=st("pointHex",y,D),zt("zip215",A);let U=y.slice(),q=y[D-1];U[D-1]=q&-129;let M=$t(U),G=A?l:e.ORDER;St("pointHex.y",M,jt,G);let j=u(M*M),it=u(j-kt),at=u(S*j-R),{isValid:ut,value:vt}=d(it,at);if(!ut)throw new Error("Point.fromHex: invalid y coordinate");let Dt=(vt&kt)===kt,Rt=(q&128)!==0;if(!A&&vt===jt&&Rt)throw new Error("Point.fromHex: x=0 and x_0=1");return Rt!==Dt&&(vt=u(-vt)),p.fromAffine({x:vt,y:M})}static fromPrivateKey(y){return T(y).point}toRawBytes(){let{x:y,y:A}=this.toAffine(),S=fe(A,e.BYTES);return S[S.length-1]|=y&kt?128:0,S}toHex(){return le(this.toRawBytes())}}p.BASE=new p(t.Gx,t.Gy,kt,u(t.Gx*t.Gy)),p.ZERO=new p(jt,kt,kt,jt);let{BASE:I,ZERO:P}=p,B=On(p,a*8);function v(E){return Y(E,n)}function L(E){return v($t(E))}function T(E){let y=e.BYTES;E=st("private key",E,y);let A=st("hashed private key",s(E),2*y),S=g(A.slice(0,y)),R=A.slice(y,2*y),D=L(S),U=I.multiply(D),q=U.toRawBytes();return{head:S,prefix:R,scalar:D,point:U,pointBytes:q}}function K(E){return T(E).pointBytes}function N(E=new Uint8Array,...y){let A=he(...y);return L(s(x(A,st("context",E),!!o)))}function O(E,y,A={}){E=st("message",E),o&&(E=o(E));let{prefix:S,scalar:R,pointBytes:D}=T(y),U=N(A.context,S,E),q=I.multiply(U).toRawBytes(),M=N(A.context,q,D,E),G=v(U+M*R);St("signature.s",G,jt,n);let j=he(q,fe(G,e.BYTES));return st("result",j,e.BYTES*2)}let F=_d;function C(E,y,A,S=F){let{context:R,zip215:D}=S,U=e.BYTES;E=st("signature",E,2*U),y=st("message",y),A=st("publicKey",A,U),D!==void 0&&zt("zip215",D),o&&(y=o(y));let q=$t(E.slice(U,2*U)),M,G,j;try{M=p.fromHex(A,D),G=p.fromHex(E.slice(0,U),D),j=I.multiplyUnsafe(q)}catch{return!1}if(!D&&M.isSmallOrder())return!1;let it=N(R,G.toRawBytes(),M.toRawBytes(),y);return G.add(M.multiplyUnsafe(it)).subtract(j).clearCofactor().equals(p.ZERO)}return I._setWindowSize(8),{CURVE:t,getPublicKey:K,sign:O,verify:C,ExtendedPoint:p,utils:{getExtendedPublicKey:T,randomPrivateKey:()=>i(e.BYTES),precompute(E=8,y=p.BASE){return y._setWindowSize(E),y.multiply(BigInt(3)),y}}}}var ur=BigInt(0),Ms=BigInt(1);function Bd(r){return Ht(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function Tc(r){let t=Bd(r),{P:e}=t,n=b=>Y(b,e),o=t.montgomeryBits,s=Math.ceil(o/8),i=t.nByteLength,a=t.adjustScalarBytes||(b=>b),c=t.powPminus2||(b=>Ps(b,e-BigInt(2),e));function l(b,p,I){let P=n(b*(p-I));return p=n(p-P),I=n(I+P),[p,I]}let u=(t.a-BigInt(2))/BigInt(4);function f(b,p){St("u",b,ur,e),St("scalar",p,ur,e);let I=p,P=b,B=Ms,v=ur,L=b,T=Ms,K=ur,N;for(let F=BigInt(o-1);F>=ur;F--){let C=I>>F&Ms;K^=C,N=l(K,B,L),B=N[0],L=N[1],N=l(K,v,T),v=N[0],T=N[1],K=C;let _=B+v,E=n(_*_),y=B-v,A=n(y*y),S=E-A,R=L+T,D=L-T,U=n(D*_),q=n(R*y),M=U+q,G=U-q;L=n(M*M),T=n(P*n(G*G)),B=n(E*A),v=n(S*(E+n(u*S)))}N=l(K,B,L),B=N[0],L=N[1],N=l(K,v,T),v=N[0],T=N[1];let O=c(v);return n(B*O)}function d(b){return fe(n(b),s)}function g(b){let p=st("u coordinate",b,s);return i===32&&(p[31]&=127),$t(p)}function x(b){let p=st("scalar",b),I=p.length;if(I!==s&&I!==i){let P=""+s+" or "+i;throw new Error("invalid scalar, expected "+P+" bytes, got "+I)}return $t(a(p))}function m(b,p){let I=g(p),P=x(b),B=f(I,P);if(B===ur)throw new Error("invalid private or public key received");return d(B)}let h=d(t.Gu);function w(b){return m(b,h)}return{scalarMult:m,scalarMultBase:w,getSharedSecret:(b,p)=>m(b,p),getPublicKey:b=>w(b),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:h}}var Hr=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),_c=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),by=BigInt(0),Pd=BigInt(1),Lc=BigInt(2),Rd=BigInt(3),Dd=BigInt(5),Nd=BigInt(8);function Bc(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=Hr,a=r*r%s*r%s,c=ct(a,Lc,s)*a%s,l=ct(c,Pd,s)*r%s,u=ct(l,Dd,s)*l%s,f=ct(u,t,s)*u%s,d=ct(f,e,s)*f%s,g=ct(d,n,s)*d%s,x=ct(g,o,s)*g%s,m=ct(x,o,s)*g%s,h=ct(m,t,s)*u%s;return{pow_p_5_8:ct(h,Lc,s)*r%s,b2:a}}function Pc(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function kd(r,t){let e=Hr,n=Y(t*t*t,e),o=Y(n*n*t,e),s=Bc(r*o).pow_p_5_8,i=Y(r*n*s,e),a=Y(t*i*i,e),c=i,l=Y(i*_c,e),u=a===r,f=a===Y(-r,e),d=a===Y(-r*_c,e);return u&&(i=c),(f||d)&&(i=l),bc(i,e)&&(i=Y(-i,e)),{isValid:u||f,value:i}}var Ud=Te(Hr,void 0,!0),Od={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ud,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Nd,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:mc,randomBytes:Or,adjustScalarBytes:Pc,uvRatio:kd},Rc=Cc(Od);var qr=Tc({P:Hr,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let t=Hr,{pow_p_5_8:e,b2:n}=Bc(r);return Y(ct(e,Rd,t)*n,t)},adjustScalarBytes:Pc,randomBytes:Or});var Fn=32;function Dc(r,t,e){return Rc.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}var Hn=class{type="Ed25519";raw;constructor(t){this.raw=Fs(t,Fn)}toMultihash(){return Wt.digest(Ee(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return et.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e){return Dc(this.raw,e,t)}};function Hs(r){return r=Fs(r,Fn),new Hn(r)}function Fs(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new Q(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Md=Math.pow(2,7),Fd=Math.pow(2,14),Hd=Math.pow(2,21),qs=Math.pow(2,28),Vs=Math.pow(2,35),Ws=Math.pow(2,42),Gs=Math.pow(2,49),tt=128,Tt=127;function nt(r){if(r<Md)return 1;if(r<Fd)return 2;if(r<Hd)return 3;if(r<qs)return 4;if(r<Vs)return 5;if(r<Ws)return 6;if(r<Gs)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function zs(r,t,e=0){switch(nt(r)){case 8:t[e++]=r&255|tt,r/=128;case 7:t[e++]=r&255|tt,r/=128;case 6:t[e++]=r&255|tt,r/=128;case 5:t[e++]=r&255|tt,r/=128;case 4:t[e++]=r&255|tt,r>>>=7;case 3:t[e++]=r&255|tt,r>>>=7;case 2:t[e++]=r&255|tt,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function qd(r,t,e=0){switch(nt(r)){case 8:t.set(e++,r&255|tt),r/=128;case 7:t.set(e++,r&255|tt),r/=128;case 6:t.set(e++,r&255|tt),r/=128;case 5:t.set(e++,r&255|tt),r/=128;case 4:t.set(e++,r&255|tt),r>>>=7;case 3:t.set(e++,r&255|tt),r>>>=7;case 2:t.set(e++,r&255|tt),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function $s(r,t){let e=r[t],n=0;if(n+=e&Tt,e<tt||(e=r[t+1],n+=(e&Tt)<<7,e<tt)||(e=r[t+2],n+=(e&Tt)<<14,e<tt)||(e=r[t+3],n+=(e&Tt)<<21,e<tt)||(e=r[t+4],n+=(e&Tt)*qs,e<tt)||(e=r[t+5],n+=(e&Tt)*Vs,e<tt)||(e=r[t+6],n+=(e&Tt)*Ws,e<tt)||(e=r[t+7],n+=(e&Tt)*Gs,e<tt))return n;throw new RangeError("Could not decode varint")}function Vd(r,t){let e=r.get(t),n=0;if(n+=e&Tt,e<tt||(e=r.get(t+1),n+=(e&Tt)<<7,e<tt)||(e=r.get(t+2),n+=(e&Tt)<<14,e<tt)||(e=r.get(t+3),n+=(e&Tt)<<21,e<tt)||(e=r.get(t+4),n+=(e&Tt)*qs,e<tt)||(e=r.get(t+5),n+=(e&Tt)*Vs,e<tt)||(e=r.get(t+6),n+=(e&Tt)*Ws,e<tt)||(e=r.get(t+7),n+=(e&Tt)*Gs,e<tt))return n;throw new RangeError("Could not decode varint")}function qt(r,t,e=0){return t==null&&(t=gt(nt(r))),t instanceof Uint8Array?zs(r,t,e):qd(r,t,e)}function Ot(r,t=0){return r instanceof Uint8Array?$s(r,t):Vd(r,t)}var js=new Float32Array([-0]),_e=new Uint8Array(js.buffer);function kc(r,t,e){js[0]=r,t[e]=_e[0],t[e+1]=_e[1],t[e+2]=_e[2],t[e+3]=_e[3]}function Uc(r,t){return _e[0]=r[t],_e[1]=r[t+1],_e[2]=r[t+2],_e[3]=r[t+3],js[0]}var Xs=new Float64Array([-0]),_t=new Uint8Array(Xs.buffer);function Oc(r,t,e){Xs[0]=r,t[e]=_t[0],t[e+1]=_t[1],t[e+2]=_t[2],t[e+3]=_t[3],t[e+4]=_t[4],t[e+5]=_t[5],t[e+6]=_t[6],t[e+7]=_t[7]}function Kc(r,t){return _t[0]=r[t],_t[1]=r[t+1],_t[2]=r[t+2],_t[3]=r[t+3],_t[4]=r[t+4],_t[5]=r[t+5],_t[6]=r[t+6],_t[7]=r[t+7],Xs[0]}var Wd=BigInt(Number.MAX_SAFE_INTEGER),Gd=BigInt(Number.MIN_SAFE_INTEGER),Kt=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 Ve;if(t<Wd&&t>Gd)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>Mc&&(o=0n,++n>Mc&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return Ve;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):Ve}},Ve=new Kt(0,0);Ve.toBigInt=function(){return 0n};Ve.zzEncode=Ve.zzDecode=function(){return this};Ve.length=function(){return 1};var Mc=4294967296n;function Fc(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 Hc(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 Zs(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 Xt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function qn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Ys=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,Xt(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 Xt(this,4);return qn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Xt(this,4);return qn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Xt(this,4);let t=Uc(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Xt(this,4);let t=Kc(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 Xt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Hc(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Xt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Xt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Kt(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 Xt(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 Xt(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 Xt(this,8);let t=qn(this.buf,this.pos+=4),e=qn(this.buf,this.pos+=4);return new Kt(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=$s(this.buf,this.pos);return this.pos+=nt(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 Js(r){return new Ys(r instanceof Uint8Array?r:r.subarray())}function Zt(r,t,e){let n=Js(r);return t.decode(n,void 0,e)}function Qs(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return gt(i);o+i>t&&(n=gt(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var We=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function ti(){}var ri=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},zd=Qs();function $d(r){return globalThis.Buffer!=null?gt(r):zd(r)}var Wr=class{len;head;tail;states;constructor(){this.len=0,this.head=new We(ti,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new We(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ni((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(Vn,10,Kt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Kt.fromBigInt(t);return this._push(Vn,e.length(),e)}uint64Number(t){return this._push(zs,nt(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=Kt.fromBigInt(t).zzEncode();return this._push(Vn,e.length(),e)}sint64Number(t){let e=Kt.fromNumber(t).zzEncode();return this._push(Vn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ei,1,t?1:0)}fixed32(t){return this._push(Vr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Kt.fromBigInt(t);return this._push(Vr,4,e.lo)._push(Vr,4,e.hi)}fixed64Number(t){let e=Kt.fromNumber(t);return this._push(Vr,4,e.lo)._push(Vr,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(kc,4,t)}double(t){return this._push(Oc,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ei,1,0):this.uint32(e)._push(Xd,e,t)}string(t){let e=Fc(t);return e!==0?this.uint32(e)._push(Zs,e,t):this._push(ei,1,0)}fork(){return this.states=new ri(this),this.head=this.tail=new We(ti,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new We(ti,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=$d(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ei(r,t,e){t[e]=r&255}function jd(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ni=class extends We{next;constructor(t,e){super(jd,t,e),this.next=void 0}};function Vn(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 Vr(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 Xd(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Wr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Zd,t,r),this},Wr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Yd,t,r),this});function Zd(r,t,e){t.set(r,e)}function Yd(r,t,e){r.length<40?Zs(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(X(r),e)}function oi(){return new Wr}function Yt(r,t){let e=oi();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var hr;(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"})(hr||(hr={}));function Wn(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Ge(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 Wn("enum",hr.VARINT,e,n)}function Jt(r,t){return Wn("message",hr.LENGTH_DELIMITED,r,t)}var Gr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var pt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(pt||(pt={}));var si;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(si||(si={}));(function(r){r.codec=()=>Ge(si)})(pt||(pt={}));var te;(function(r){let t;r.codec=()=>(t==null&&(t=Jt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),pt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=pt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Yt(e,r.codec()),r.decode=(e,n)=>Zt(e,r.codec(),n)})(te||(te={}));var ii;(function(r){let t;r.codec=()=>(t==null&&(t=Jt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),pt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=pt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Yt(e,r.codec()),r.decode=(e,n)=>Zt(e,r.codec(),n)})(ii||(ii={}));var zr=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},Gn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Wc={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new Gn("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Le=Wc;var jr={};It(jr,{MAX_RSA_KEY_SIZE:()=>ci,generateRSAKeyPair:()=>Xc,jwkToJWKKeyPair:()=>Zc,jwkToPkcs1:()=>rp,jwkToPkix:()=>hi,jwkToRSAPrivateKey:()=>jc,pkcs1MessageToJwk:()=>ui,pkcs1MessageToRSAPrivateKey:()=>di,pkcs1ToJwk:()=>ep,pkcs1ToRSAPrivateKey:()=>$c,pkixMessageToJwk:()=>fi,pkixMessageToRSAPublicKey:()=>mi,pkixToJwk:()=>np,pkixToRSAPublicKey:()=>pi});var Jd=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]),Be=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Pe=new Uint32Array(64),ai=class extends cr{constructor(){super(64,32,8,!1),this.A=Be[0]|0,this.B=Be[1]|0,this.C=Be[2]|0,this.D=Be[3]|0,this.E=Be[4]|0,this.F=Be[5]|0,this.G=Be[6]|0,this.H=Be[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)Pe[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Pe[f-15],g=Pe[f-2],x=Gt(d,7)^Gt(d,18)^d>>>3,m=Gt(g,17)^Gt(g,19)^g>>>10;Pe[f]=m+Pe[f-7]+x+Pe[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=Gt(a,6)^Gt(a,11)^Gt(a,25),g=u+d+hc(a,c,l)+Jd[f]+Pe[f]|0,m=(Gt(n,2)^Gt(n,13)^Gt(n,22))+dc(n,o,s)|0;u=l,l=c,c=a,a=i+g|0,i=s,s=o,o=n,n=g+m|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(){Pe.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ee=Bn(()=>new ai);var dr=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=jr.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return dt.createV1(114,this._multihash)}toString(){return et.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e){return zc(this.jwk,e,t)}},$r=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=jr.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}sign(t){return Gc(this.jwk,t)}};var ci=8192,li=18,Qd=1062,tp=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function ep(r){let t=ae(r);return ui(t)}function ui(r){return{n:H(r[1],"base64url"),e:H(r[2],"base64url"),d:H(r[3],"base64url"),p:H(r[4],"base64url"),q:H(r[5],"base64url"),dp:H(r[6],"base64url"),dq:H(r[7],"base64url"),qi:H(r[8],"base64url"),kty:"RSA"}}function rp(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 Q("JWK was missing components");return be([Nt(Uint8Array.from([0])),Nt(X(r.n,"base64url")),Nt(X(r.e,"base64url")),Nt(X(r.d,"base64url")),Nt(X(r.p,"base64url")),Nt(X(r.q,"base64url")),Nt(X(r.dp,"base64url")),Nt(X(r.dq,"base64url")),Nt(X(r.qi,"base64url"))]).subarray()}function np(r){let t=ae(r,{offset:0});return fi(t)}function fi(r){let t=ae(r[1],{offset:0});return{kty:"RSA",n:H(t[0],"base64url"),e:H(t[1],"base64url")}}function hi(r){if(r.n==null||r.e==null)throw new Q("JWK was missing components");return be([tp,Tn(be([Nt(X(r.n,"base64url")),Nt(X(r.e,"base64url"))]))]).subarray()}function $c(r){let t=ae(r);return di(t)}function di(r){let t=ui(r);return jc(t)}function pi(r,t){if(r.byteLength>=Qd)throw new Je("Key size is too large");let e=ae(r,{offset:0});return mi(e,r,t)}function mi(r,t,e){let n=fi(r);if(e==null){let o=ee(te.encode({Type:pt.RSA,Data:t}));e=Ct(li,o)}return new dr(n,e)}function jc(r){if(Jc(r)>ci)throw new Q("Key size is too large");let t=Zc(r),e=ee(te.encode({Type:pt.RSA,Data:hi(t.publicKey)})),n=Ct(li,e);return new $r(t.privateKey,new dr(t.publicKey,n))}async function Xc(r){if(r>ci)throw new Q("Key size is too large");let t=await Yc(r),e=ee(te.encode({Type:pt.RSA,Data:hi(t.publicKey)})),n=Ct(li,e);return new $r(t.privateKey,new dr(t.publicKey,n))}function Zc(r){if(r==null)throw new Q("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Yc(r){let t=await Le.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 op(t);return{privateKey:e[0],publicKey:e[1]}}async function Gc(r,t){let e=await Le.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Le.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function zc(r,t,e){let n=await Le.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Le.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function op(r){if(r.privateKey==null||r.publicKey==null)throw new Q("Private and public key are required");return Promise.all([Le.get().subtle.exportKey("jwk",r.privateKey),Le.get().subtle.exportKey("jwk",r.publicKey)])}function Jc(r){if(r.kty!=="RSA")throw new Q("invalid key type");if(r.n==null)throw new Q("invalid key modulus");return X(r.n,"base64url").length*8}var zn=class extends ar{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Ur(t);let n=Se(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 ir(this),this.iHash.update(t),this}digestInto(t){ir(this),sr(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()}},pr=(r,t,e)=>new zn(r,t).update(e).digest();pr.create=(r,t)=>new zn(r,t);function Qc(r){r.lowS!==void 0&&zt("lowS",r.lowS),r.prehash!==void 0&&zt("prehash",r.prehash)}function sp(r){let t=Fr(r);Ht(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("invalid 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("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:ip,hexToBytes:ap}=Nn,gi=class extends Error{constructor(t=""){super(t)}},de={Err:gi,_tlv:{encode:(r,t)=>{let{Err:e}=de;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=Me(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Me(o.length/2|128):"";return Me(r)+s+o+t},decode(r,t){let{Err:e}=de,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=de;if(r<pe)throw new t("integer: negative integers are not allowed");let e=Me(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=de;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return ip(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=de,o=typeof r=="string"?ap(r):r;lr(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=de,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},pe=BigInt(0),xt=BigInt(1),Xw=BigInt(2),tl=BigInt(3),Zw=BigInt(4);function cp(r){let t=sp(r),{Fp:e}=t,n=Te(t.n,t.nBitLength),o=t.toBytes||((m,h,w)=>{let b=h.toAffine();return he(Uint8Array.from([4]),e.toBytes(b.x),e.toBytes(b.y))}),s=t.fromBytes||(m=>{let h=m.subarray(1),w=e.fromBytes(h.subarray(0,e.BYTES)),b=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:w,y:b}});function i(m){let{a:h,b:w}=t,b=e.sqr(m),p=e.mul(b,m);return e.add(e.add(p,e.mul(m,h)),w)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Kr(m,xt,t.n)}function c(m){let{allowedPrivateKeyLengths:h,nByteLength:w,wrapPrivateKey:b,n:p}=t;if(h&&typeof m!="bigint"){if(Ie(m)&&(m=le(m)),typeof m!="string"||!h.includes(m.length))throw new Error("invalid private key");m=m.padStart(w*2,"0")}let I;try{I=typeof m=="bigint"?m:ue(st("private key",m,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof m)}return b&&(I=Y(I,p)),St("private key",I,xt,p),I}function l(m){if(!(m instanceof d))throw new Error("ProjectivePoint expected")}let u=He((m,h)=>{let{px:w,py:b,pz:p}=m;if(e.eql(p,e.ONE))return{x:w,y:b};let I=m.is0();h==null&&(h=I?e.ONE:e.inv(p));let P=e.mul(w,h),B=e.mul(b,h),v=e.mul(p,h);if(I)return{x:e.ZERO,y:e.ZERO};if(!e.eql(v,e.ONE))throw new Error("invZ was invalid");return{x:P,y:B}}),f=He(m=>{if(m.is0()){if(t.allowInfinityPoint&&!e.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:h,y:w}=m.toAffine();if(!e.isValid(h)||!e.isValid(w))throw new Error("bad point: x or y not FE");let b=e.sqr(w),p=i(h);if(!e.eql(b,p))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,w,b){if(this.px=h,this.py=w,this.pz=b,h==null||!e.isValid(h))throw new Error("x required");if(w==null||!e.isValid(w))throw new Error("y required");if(b==null||!e.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:w,y:b}=h||{};if(!h||!e.isValid(w)||!e.isValid(b))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let p=I=>e.eql(I,e.ZERO);return p(w)&&p(b)?d.ZERO:new d(w,b,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let w=e.invertBatch(h.map(b=>b.pz));return h.map((b,p)=>b.toAffine(w[p])).map(d.fromAffine)}static fromHex(h){let w=d.fromAffine(s(st("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,w){return Kn(d,n,h,w)}_setWindowSize(h){x.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:w,py:b,pz:p}=this,{px:I,py:P,pz:B}=h,v=e.eql(e.mul(w,B),e.mul(I,p)),L=e.eql(e.mul(b,B),e.mul(P,p));return v&&L}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:w}=t,b=e.mul(w,tl),{px:p,py:I,pz:P}=this,B=e.ZERO,v=e.ZERO,L=e.ZERO,T=e.mul(p,p),K=e.mul(I,I),N=e.mul(P,P),O=e.mul(p,I);return O=e.add(O,O),L=e.mul(p,P),L=e.add(L,L),B=e.mul(h,L),v=e.mul(b,N),v=e.add(B,v),B=e.sub(K,v),v=e.add(K,v),v=e.mul(B,v),B=e.mul(O,B),L=e.mul(b,L),N=e.mul(h,N),O=e.sub(T,N),O=e.mul(h,O),O=e.add(O,L),L=e.add(T,T),T=e.add(L,T),T=e.add(T,N),T=e.mul(T,O),v=e.add(v,T),N=e.mul(I,P),N=e.add(N,N),T=e.mul(N,O),B=e.sub(B,T),L=e.mul(N,K),L=e.add(L,L),L=e.add(L,L),new d(B,v,L)}add(h){l(h);let{px:w,py:b,pz:p}=this,{px:I,py:P,pz:B}=h,v=e.ZERO,L=e.ZERO,T=e.ZERO,K=t.a,N=e.mul(t.b,tl),O=e.mul(w,I),F=e.mul(b,P),C=e.mul(p,B),_=e.add(w,b),E=e.add(I,P);_=e.mul(_,E),E=e.add(O,F),_=e.sub(_,E),E=e.add(w,p);let y=e.add(I,B);return E=e.mul(E,y),y=e.add(O,C),E=e.sub(E,y),y=e.add(b,p),v=e.add(P,B),y=e.mul(y,v),v=e.add(F,C),y=e.sub(y,v),T=e.mul(K,E),v=e.mul(N,C),T=e.add(v,T),v=e.sub(F,T),T=e.add(F,T),L=e.mul(v,T),F=e.add(O,O),F=e.add(F,O),C=e.mul(K,C),E=e.mul(N,E),F=e.add(F,C),C=e.sub(O,C),C=e.mul(K,C),E=e.add(E,C),O=e.mul(F,E),L=e.add(L,O),O=e.mul(y,E),v=e.mul(_,v),v=e.sub(v,O),O=e.mul(_,F),T=e.mul(y,T),T=e.add(T,O),new d(v,L,T)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return x.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){let{endo:w,n:b}=t;St("scalar",h,pe,b);let p=d.ZERO;if(h===pe)return p;if(this.is0()||h===xt)return this;if(!w||x.hasPrecomputes(this))return x.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:I,k1:P,k2neg:B,k2:v}=w.splitScalar(h),L=p,T=p,K=this;for(;P>pe||v>pe;)P&xt&&(L=L.add(K)),v&xt&&(T=T.add(K)),K=K.double(),P>>=xt,v>>=xt;return I&&(L=L.negate()),B&&(T=T.negate()),T=new d(e.mul(T.px,w.beta),T.py,T.pz),L.add(T)}multiply(h){let{endo:w,n:b}=t;St("scalar",h,xt,b);let p,I;if(w){let{k1neg:P,k1:B,k2neg:v,k2:L}=w.splitScalar(h),{p:T,f:K}=this.wNAF(B),{p:N,f:O}=this.wNAF(L);T=x.constTimeNegate(P,T),N=x.constTimeNegate(v,N),N=new d(e.mul(N.px,w.beta),N.py,N.pz),p=T.add(N),I=K.add(O)}else{let{p:P,f:B}=this.wNAF(h);p=P,I=B}return d.normalizeZ([p,I])[0]}multiplyAndAddUnsafe(h,w,b){let p=d.BASE,I=(B,v)=>v===pe||v===xt||!B.equals(p)?B.multiplyUnsafe(v):B.multiply(v),P=I(this,w).add(I(h,b));return P.is0()?void 0:P}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:w}=t;if(h===xt)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:w}=t;return h===xt?this:w?w(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return zt("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return zt("isCompressed",h),le(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let g=t.nBitLength,x=On(d,t.endo?Math.ceil(g/2):g);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function lp(r){let t=Fr(r);return Ht(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function el(r){let t=lp(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(C){return Y(C,n)}function a(C){return kn(C,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=cp({...t,toBytes(C,_,E){let y=_.toAffine(),A=e.toBytes(y.x),S=he;return zt("isCompressed",E),E?S(Uint8Array.from([_.hasEvenY()?2:3]),A):S(Uint8Array.from([4]),A,e.toBytes(y.y))},fromBytes(C){let _=C.length,E=C[0],y=C.subarray(1);if(_===o&&(E===2||E===3)){let A=ue(y);if(!Kr(A,xt,e.ORDER))throw new Error("Point is not on curve");let S=u(A),R;try{R=e.sqrt(S)}catch(q){let M=q instanceof Error?": "+q.message:"";throw new Error("Point is not on curve"+M)}let D=(R&xt)===xt;return(E&1)===1!==D&&(R=e.neg(R)),{x:A,y:R}}else if(_===s&&E===4){let A=e.fromBytes(y.subarray(0,e.BYTES)),S=e.fromBytes(y.subarray(e.BYTES,2*e.BYTES));return{x:A,y:S}}else{let A=o,S=s;throw new Error("invalid Point, expected length of "+A+", or uncompressed "+S+", got "+_)}}}),d=C=>le(Ce(C,t.nByteLength));function g(C){let _=n>>xt;return C>_}function x(C){return g(C)?i(-C):C}let m=(C,_,E)=>ue(C.slice(_,E));class h{constructor(_,E,y){this.r=_,this.s=E,this.recovery=y,this.assertValidity()}static fromCompact(_){let E=t.nByteLength;return _=st("compactSignature",_,E*2),new h(m(_,0,E),m(_,E,2*E))}static fromDER(_){let{r:E,s:y}=de.toSig(st("DER",_));return new h(E,y)}assertValidity(){St("r",this.r,xt,n),St("s",this.s,xt,n)}addRecoveryBit(_){return new h(this.r,this.s,_)}recoverPublicKey(_){let{r:E,s:y,recovery:A}=this,S=B(st("msgHash",_));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let R=A===2||A===3?E+t.n:E;if(R>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let D=(A&1)===0?"02":"03",U=c.fromHex(D+d(R)),q=a(R),M=i(-S*q),G=i(y*q),j=c.BASE.multiplyAndAddUnsafe(U,M,G);if(!j)throw new Error("point at infinify");return j.assertValidity(),j}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return Fe(this.toDERHex())}toDERHex(){return de.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Fe(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let w={isValidPrivateKey(C){try{return l(C),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let C=Ns(t.n);return Sc(t.randomBytes(C),t.n)},precompute(C=8,_=c.BASE){return _._setWindowSize(C),_.multiply(BigInt(3)),_}};function b(C,_=!0){return c.fromPrivateKey(C).toRawBytes(_)}function p(C){let _=Ie(C),E=typeof C=="string",y=(_||E)&&C.length;return _?y===o||y===s:E?y===2*o||y===2*s:C instanceof c}function I(C,_,E=!0){if(p(C))throw new Error("first arg must be private key");if(!p(_))throw new Error("second arg must be public key");return c.fromHex(_).multiply(l(C)).toRawBytes(E)}let P=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let _=ue(C),E=C.length*8-t.nBitLength;return E>0?_>>BigInt(E):_},B=t.bits2int_modN||function(C){return i(P(C))},v=Mr(t.nBitLength);function L(C){return St("num < 2^"+t.nBitLength,C,pe,v),Ce(C,t.nByteLength)}function T(C,_,E=K){if(["recovered","canonical"].some(at=>at in E))throw new Error("sign() legacy options not supported");let{hash:y,randomBytes:A}=t,{lowS:S,prehash:R,extraEntropy:D}=E;S==null&&(S=!0),C=st("msgHash",C),Qc(E),R&&(C=st("prehashed msgHash",y(C)));let U=B(C),q=l(_),M=[L(q),L(U)];if(D!=null&&D!==!1){let at=D===!0?A(e.BYTES):D;M.push(st("extraEntropy",at))}let G=he(...M),j=U;function it(at){let ut=P(at);if(!f(ut))return;let vt=a(ut),Dt=c.BASE.multiply(ut).toAffine(),Rt=i(Dt.x);if(Rt===pe)return;let Qt=i(vt*i(j+Rt*q));if(Qt===pe)return;let ne=(Dt.x===Rt?0:2)|Number(Dt.y&xt),_r=Qt;return S&&g(Qt)&&(_r=x(Qt),ne^=1),new h(Rt,_r,ne)}return{seed:G,k2sig:it}}let K={lowS:t.lowS,prehash:!1},N={lowS:t.lowS,prehash:!1};function O(C,_,E=K){let{seed:y,k2sig:A}=T(C,_,E),S=t;return Ls(S.hash.outputLen,S.nByteLength,S.hmac)(y,A)}c.BASE._setWindowSize(8);function F(C,_,E,y=N){let A=C;_=st("msgHash",_),E=st("publicKey",E);let{lowS:S,prehash:R,format:D}=y;if(Qc(y),"strict"in y)throw new Error("options.strict was renamed to lowS");if(D!==void 0&&D!=="compact"&&D!=="der")throw new Error("format must be compact or der");let U=typeof A=="string"||Ie(A),q=!U&&!D&&typeof A=="object"&&A!==null&&typeof A.r=="bigint"&&typeof A.s=="bigint";if(!U&&!q)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let M,G;try{if(q&&(M=new h(A.r,A.s)),U){try{D!=="compact"&&(M=h.fromDER(A))}catch(ne){if(!(ne instanceof de.Err))throw ne}!M&&D!=="der"&&(M=h.fromCompact(A))}G=c.fromHex(E)}catch{return!1}if(!M||S&&M.hasHighS())return!1;R&&(_=t.hash(_));let{r:j,s:it}=M,at=B(_),ut=a(it),vt=i(at*ut),Dt=i(j*ut),Rt=c.BASE.multiplyAndAddUnsafe(G,vt,Dt)?.toAffine();return Rt?i(Rt.x)===j:!1}return{CURVE:t,getPublicKey:b,getSharedSecret:I,sign:O,verify:F,ProjectivePoint:c,Signature:h,utils:w}}function up(r){return{hash:r,hmac:(t,...e)=>pr(r,t,Ss(...e)),randomBytes:Or}}function rl(r,t){let e=n=>el({...r,...up(n)});return{...e(t),create:e}}var sl=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),nl=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),fp=BigInt(1),yi=BigInt(2),ol=(r,t)=>(r+t/yi)/t;function hp(r){let t=sl,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=ct(u,e,t)*u%t,d=ct(f,e,t)*u%t,g=ct(d,yi,t)*l%t,x=ct(g,o,t)*g%t,m=ct(x,s,t)*x%t,h=ct(m,a,t)*m%t,w=ct(h,c,t)*h%t,b=ct(w,a,t)*m%t,p=ct(b,e,t)*u%t,I=ct(p,i,t)*x%t,P=ct(I,n,t)*l%t,B=ct(P,yi,t);if(!wi.eql(wi.sqr(B),r))throw new Error("Cannot find square root");return B}var wi=Te(sl,void 0,void 0,{sqrt:hp}),ze=rl({a:BigInt(0),b:BigInt(7),Fp:wi,n:nl,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=nl,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-fp*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=ol(s*r,t),c=ol(-n*r,t),l=Y(r-a*e-c*o,t),u=Y(-a*n-c*s,t),f=l>i,d=u>i;if(f&&(l=t-l),d&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},ee),sx=BigInt(0);var ix=ze.ProjectivePoint;function il(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function al(r,t,e){let n=ie.digest(e instanceof Uint8Array?e:e.subarray());if(il(n))return n.then(({digest:o})=>ze.verify(t,o,r)).catch(o=>{throw new zr(String(o))});try{return ze.verify(t,n.digest,r)}catch(o){throw new zr(String(o))}}var $n=class{type="secp256k1";raw;_key;constructor(t){this._key=ll(t),this.raw=cl(this._key)}toMultihash(){return Wt.digest(Ee(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return et.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e){return al(this._key,e,t)}};function xi(r){return new $n(r)}function cl(r){return ze.ProjectivePoint.fromHex(r).toRawBytes(!0)}function ll(r){try{return ze.ProjectivePoint.fromHex(r),r}catch(t){throw new Je(String(t))}}function Xr(r,t){let{Type:e,Data:n}=te.decode(r),o=n??new Uint8Array;switch(e){case pt.RSA:return pi(o,t);case pt.Ed25519:return Hs(o);case pt.secp256k1:return xi(o);case pt.ECDSA:return Es(o);default:throw new ke}}function ul(r){let{Type:t,Data:e}=te.decode(r.digest),n=e??new Uint8Array;switch(t){case pt.Ed25519:return Hs(n);case pt.secp256k1:return xi(n);case pt.ECDSA:return Es(n);default:throw new ke}}function Ee(r){return te.encode({Type:pt[r.type],Data:r.raw})}var fl=Symbol.for("nodejs.util.inspect.custom"),dp=114,Zr=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[$o]=!0;toString(){return this.string==null&&(this.string=et.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return dt.createV1(dp,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Et(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Et(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[fl](){return`PeerId(${this.toString()})`}},Yr=class extends Zr{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Jr=class extends Zr{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Qr=class extends Zr{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},pp=2336,tn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Wt.digest(X(this.url))}[fl](){return`PeerId(${this.url})`}[$o]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return dt.createV1(pp,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=H(t)),t.toString()===this.toString())}};var mp=114,hl=2336;function mr(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=xe(et.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return gp(dt.parse(r));if(t==null)throw new Q('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=xe(t.decode(r))}return dl(e)}function bi(r){if(r.type==="Ed25519")return new Jr({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Qr({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Yr({multihash:r.toCID().multihash,publicKey:r});throw new ke}function dl(r){if(wp(r))return new Yr({multihash:r});if(yp(r))try{let t=ul(r);if(t.type==="Ed25519")return new Jr({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Qr({multihash:r,publicKey:t})}catch{let e=H(r.digest);return new tn(new URL(e))}throw new En("Supplied PeerID Multihash is invalid")}function gp(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==mp&&r.code!==hl)throw new bn("Supplied PeerID CID is invalid");if(r.code===hl){let t=H(r.multihash.digest);return new tn(new URL(t))}return dl(r.multihash)}function yp(r){return r.code===Wt.code}function wp(r){return r.code===ie.code}var jn=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 d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});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,xp=15,gr=new jn;function Ei(r){if(!(r.length>xp))return gr.new(r).parseWith(()=>gr.readIPv4Addr())}function Si(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>pl))return gr.new(r).parseWith(()=>gr.readIPv6Addr())}function Xn(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>pl)return;let e=gr.new(r).parseWith(()=>gr.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}var bb=parseInt("0xFFFF",16),Eb=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Zn(r){return!!Ei(r)}function Yn(r){return!!Si(r)}function Jn(r){return!!Xn(r)}var yl=Zn,vp=Yn,Ai=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(vp(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=yl(e[n]),i;s&&(i=Ai(e[n]),e[n]=H(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,H(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 yr={},vi={},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=Tp(...r);vi[t.code]=t,yr[t.name]=t});function Tp(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function ot(r){if(typeof r=="number"){if(vi[r]!=null)return vi[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(yr[r]!=null)return yr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var o1=ot("ip4"),s1=ot("ip6"),i1=ot("ipcidr");function _i(r,t){switch(ot(r).code){case 4:case 41:return Lp(t);case 42:return Ti(t);case 43:return H(t,"base10");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 Ti(t);case 421:return Dp(t);case 444:return bl(t);case 445:return bl(t);case 466:return Rp(t);case 481:return globalThis.encodeURIComponent(Ti(t));default:return H(t,"base16")}}function Li(r,t){switch(ot(r).code){case 4:return xl(t);case 41:return xl(t);case 42:return Ci(t);case 43:return X(t,"base10");case 6:case 273:case 33:case 132:return Bi(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ci(t);case 421:return Bp(t);case 444:return Np(t);case 445:return kp(t);case 466:return Pp(t);case 481:return Ci(globalThis.decodeURIComponent(t));default:return X(t,"base16")}}var Ii=Object.values(Oe).map(r=>r.decoder),_p=function(){let r=Ii[0].or(Ii[1]);return Ii.slice(2).forEach(t=>r=r.or(t)),r}();function xl(r){if(!Jn(r))throw new Error("invalid ip address");return Ai(r)}function Lp(r){let t=wl(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!Jn(t))throw new Error("invalid ip address");return t}function Bi(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 Ci(r){let t=X(r),e=Uint8Array.from(qt(t.length));return yt([e,t],e.length+t.length)}function Ti(r){let t=Ot(r);if(r=r.slice(nt(t)),r.length!==t)throw new Error("inconsistent lengths");return H(r)}function Bp(r){let t;r[0]==="Q"||r[0]==="1"?t=xe(et.decode(`z${r}`)).bytes:t=dt.parse(r).multihash.bytes;let e=Uint8Array.from(qt(t.length));return yt([e,t],e.length+t.length)}function Pp(r){let t=_p.decode(r),e=Uint8Array.from(qt(t.length));return yt([e,t],e.length+t.length)}function Rp(r){let t=Ot(r),e=r.slice(nt(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+H(e,"base64url")}function Dp(r){let t=Ot(r),e=r.slice(nt(t));if(e.length!==t)throw new Error("inconsistent lengths");return H(e,"base58btc")}function Np(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=Bi(n);return yt([e,o],e.length+o.length)}function kp(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=Bi(n);return yt([e,o],e.length+o.length)}function bl(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=H(t,"base32"),o=El(e);return`${n}:${o}`}function Sl(r){r=Pi(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=ot(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw new Qn("invalid address: "+r);if(a.path===!0){n=Pi(o.slice(s).join("/")),t.push([a.code,Li(a.code,n)]),e.push([a.code,n]);break}let c=Li(a.code,o[s]);t.push([a.code,c]),e.push([a.code,_i(a.code,c)])}return{string:Al(e),bytes:to(t),tuples:t,stringTuples:e,path:n}}function Ri(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=Ot(r,o),i=nt(s),a=ot(s),c=Up(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 new Qn("Invalid address Uint8Array: "+H(r,"base16"));t.push([s,l]);let u=_i(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=ot(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Pi(t.join("/"))}function to(r){return yt(r.map(t=>{let e=ot(t[0]),n=Uint8Array.from(qt(e.code));return t.length>1&&t[1]!=null&&(n=yt([n,t[1]])),n}))}function Up(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=Ot(t instanceof Uint8Array?t:Uint8Array.from(t));return e+nt(e)}}function Pi(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var Qn=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var Op=Symbol.for("nodejs.util.inspect.custom"),Ni=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Kp=[ot("dns").code,ot("dns4").code,ot("dns6").code,ot("dnsaddr").code],Di=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},eo=class r{bytes;#t;#e;#r;#n;[Ni]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Ri(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Sl(t)}else if(Il(t))e=Ri(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=ot("tcp"),a=ot("udp"),c=ot("ip4"),l=ot("ip6"),u=ot("dns6"),f=ot("ip6zone");for(let[g,x]of this.stringTuples())g===f.code&&(s=`%${x??""}`),Kp.includes(g)&&(e=i.name==="tcp"?"tcp":"udp",o=443,n=`${x??""}${s}`,t=g===u.code?6:4),(g===i.code||g===a.code)&&(e=ot(g).name==="tcp"?"tcp":"udp",o=parseInt(x??"")),(g===c.code||g===l.code)&&(e=ot(g).name==="tcp"?"tcp":"udp",n=`${x??""}${s}`,t=g===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({},ot(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>ot(t).name)}tuples(){return this.#e.map(([t,e])=>e==null?[t]:[t,e])}stringTuples(){return this.#r.map(([t,e])=>e==null?[t]:[t,e])}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(to(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===yr.p2p.code&&t.push([n,o]),n===yr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?H(et.decode(`z${n}`),"base58btc"):H(dt.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=vl.get(e.name);if(n==null)throw new Di(`no available resolver for ${e.name}`);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)}[Op](){return`Multiaddr(${this.#t})`}};var vl=new Map;function Il(r){return!!r?.[Ni]}function re(r){return new eo(r)}var Mp=r=>r.toString().split("/").slice(1),wr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),z=r=>({match:t=>wr(e=>e===r).match(t),pattern:r}),$e=()=>({match:r=>wr(t=>typeof t=="string").match(r),pattern:"{string}"}),en=()=>({match:r=>wr(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{et.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),rn=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Br.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),J=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Lt=(...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(", ")})`}),$=(...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 lt(...r){function t(o){let s=Mp(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{matchers:r,matches:e,exactMatch:n}}var no=$(z("dns4"),$e()),oo=$(z("dns6"),$e()),so=$(z("dnsaddr"),$e()),Ui=$(z("dns"),$e()),O1=lt(no,J(rt())),K1=lt(oo,J(rt())),M1=lt(so,J(rt())),F1=lt(Lt(Ui,so,no,oo),J(rt())),Cl=$(z("ip4"),wr(Zn)),Tl=$(z("ip6"),wr(Yn)),Oi=Lt(Cl,Tl),me=Lt(Oi,Ui,no,oo,so),H1=lt(Lt(Oi,$(Lt(Ui,so,no,oo),J(rt())))),q1=lt(Cl),V1=lt(Tl),W1=lt(Oi),Ki=$(me,z("tcp"),en()),nn=$(me,z("udp"),en()),G1=lt($(Ki,J(rt()))),z1=lt(nn),Mi=$(nn,z("quic"),J(rt())),io=$(nn,z("quic-v1"),J(rt())),Fp=Lt(Mi,io),$1=lt(Mi),j1=lt(io),ki=Lt(me,Ki,nn,Mi,io),_l=Lt($(ki,z("ws"),J(rt()))),X1=lt(_l),Ll=Lt($(ki,z("wss"),J(rt())),$(ki,z("tls"),J($(z("sni"),$e())),z("ws"),J(rt()))),Z1=lt(Ll),Bl=$(nn,z("webrtc-direct"),J(rn()),J(rn()),J(rt())),Pl=lt(Bl),Rl=$(io,z("webtransport"),J(rn()),J(rn()),J(rt())),Y1=lt(Rl),ro=Lt(_l,Ll,$(Ki,J(rt())),$(Fp,J(rt())),$(me,J(rt())),Bl,Rl,rt()),Dl=lt(ro),Hp=$(ro,z("p2p-circuit"),rt()),J1=lt(Hp),qp=Lt($(ro,z("p2p-circuit"),z("webrtc"),J(rt())),$(ro,z("webrtc"),J(rt())),$(z("webrtc"),J(rt()))),Nl=lt(qp),Vp=Lt($(me,z("tcp"),en(),z("http"),J(rt())),$(me,z("http"),J(rt()))),Q1=lt(Vp),Wp=Lt($(me,z("tcp"),Lt($(z("443"),z("http")),$(en(),z("https"))),J(rt())),$(me,z("tls"),z("http"),J(rt())),$(me,z("https"),J(rt()))),t2=lt(Wp),Gp=Lt($(z("memory"),$e(),J(rt()))),e2=lt(Gp);var Bt;(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=()=>Ge(e)}(t=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=Jt((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.flag!=null&&(s.uint32(8),r.Flag.codec().encode(o.flag,s)),o.message!=null&&(s.uint32(18),s.bytes(o.message)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.flag=r.Flag.codec().decode(o);break}case 2:{a.message=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Yt(o,r.codec()),r.decode=(o,s)=>Zt(o,r.codec(),s)})(Bt||(Bt={}));var kl=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],Fi=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Ul="libp2p+webrtc+v1/";var Ol=466,Kl=2*1024*1024,Ml=30*1e3,xr=16*1024;function zp(r=xr){let t=nt(r-nt(r)),e=1+nt(Object.keys(Bt.Flag).length-1),n=1,o=r-t-e-n,s=nt(o);return t+e+n+s}var Fl=zp(),Hl=5e3,ql=5e3,Vl=3e4,Hi="/webrtc",on="/webrtc-signaling/0.0.1";var Wl=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))},$p=function(){function r(t,e,n){this.name=t,this.version=e,this.os=n,this.type="browser"}return r}();var jp=function(){function r(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return r}();var Xp=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 Zp=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var Yp=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var Jp=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Qp=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Gl=3,tm=[["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",Jp]],zl=[["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 jl(r){return r?$l(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Yp:typeof navigator<"u"?$l(navigator.userAgent):nm()}function em(r){return r!==""&&tm.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 $l(r){var t=em(r);if(!t)return null;var e=t[0],n=t[1];if(e==="searchbot")return new Zp;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<Gl&&(o=Wl(Wl([],o,!0),om(Gl-o.length),!0)):o=[];var s=o.join("."),i=rm(r),a=Qp.exec(r);return a&&a[1]?new Xp(e,s,i,a[1]):new $p(e,s,i)}function rm(r){for(var t=0,e=zl.length;t<e;t++){var n=zl[t],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function nm(){var r=typeof process<"u"&&process.version;return r?new jp(process.version.slice(1)):null}function om(r){for(var t=[],e=0;e<r;e++)t.push("0");return t}function Z(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var qi=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Vi=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Xl=r=>globalThis.DOMException===void 0?new Vi(r):new DOMException(r),Zl=r=>{let t=r.reason===void 0?Xl("This operation was aborted."):r.reason;return t instanceof Error?t:Xl(t)};function sn(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,a,l=new Promise((u,f)=>{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:g}=t;g.aborted&&f(Zl(g)),a=()=>{f(Zl(g))},g.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new qi;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(g){f(g)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(d.message=o??`Promise timed out after ${e} milliseconds`,f(d))},e),(async()=>{try{u(await r)}catch(g){f(g)}})()}).finally(()=>{l.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},l}var Yl=jl(),an=Yl!=null&&Yl.name==="firefox",ao=async function*(){},co=async r=>{};function Jl(r,t,e=Vl,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=Z(),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 sn(o.promise,{milliseconds:e})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function Wi(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??kl.map(t=>({urls:[t]})),r}var Ql=(r=32)=>Ul+[...Array(r)].map(()=>Fi.at(Math.floor(Math.random()*Fi.length))).join("");var je=class{log;peerConnection;remoteAddr;timeline;metrics;source=ao();sink=co;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,o=n.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",n.connectionState,"initial state",o),(n.connectionState==="disconnected"||n.connectionState==="failed"||n.connectionState==="closed")&&(this.timeline.close=Date.now())}}async close(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 lo=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},br=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new lo(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 lo(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 Gi=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Er(r={}){return sm(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 sm(r,t){t=t??{};let e=t.onEnd,n=new br,o,s,i,a=Z(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,w)=>{s=b=>{s=null,n.push(b);try{h(r(n))}catch(p){w(p)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Z()})}},l=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new br,s!=null?s({error:h}):(n.push({error:h}),o)),f=h=>{if(i)return o;if(t?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:h})},d=h=>i?o:(i=!0,h!=null?u(h):l({done:!0})),g=()=>(n=new br,d(),{done:!0}),x=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:g,throw:x,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let w=h?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let b,p;w!=null&&(b=new Promise((I,P)=>{p=()=>{P(new Gi)},w.addEventListener("abort",p)}));try{await Promise.race([a.promise,b])}finally{p!=null&&w!=null&&w?.removeEventListener("abort",p)}}},e==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(h){return m.throw(h),e!=null&&(e(h),e=void 0),{done:!0}},return(){return m.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(h){return m.end(h),e!=null&&(e(h),e=void 0),o},get readableLength(){return m.readableLength},onEmpty:h=>m.onEmpty(h)},o}var uo=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function bt(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new uo(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new uo(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}function tu(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 eu(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function ru(r,t){let e=tu(r).return?.();eu(e)&&e.catch(n=>{t.error("could not cause iterator to return",n)})}var im=5e3;function zi(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var fo=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=Z(),this.closed=Z(),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??im,this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=Er({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 Ne(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";let e={signal:this.sinkController.signal};if(this.direction==="outbound"){let o=this.sendNewStream(e);zi(o)&&await o}let n=()=>{ru(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 V(o):o;let s=this.sendData(o,e);zi(s)&&(this.sendingData=Z(),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.status==="open"&&(this.log.trace("closing gracefully"),this.status="closing",await bt(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 bt(this.sink([]),t.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await bt(this.sendingData.promise,t.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await bt(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();zi(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 xn("stream reset");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 $i(r){let t=new globalThis.AbortController;function e(){t.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}var ho=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Sr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},po=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},cn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function mo(r){return r[Symbol.asyncIterator]!=null}function nu(r,t){if(r.byteLength>t)throw new Sr("Message length too long")}var yo=r=>{let t=nt(r),e=gt(t);return qt(r,e),yo.bytes=t,e};yo.bytes=0;function ln(r,t){t=t??{};let e=t.lengthEncoder??yo,n=t?.maxDataLength??4194304;function*o(s){nu(s,n);let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return mo(r)?async function*(){for await(let s of r)yield*o(s)}():function*(){for(let s of r)yield*o(s)}()}ln.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??yo,n=t?.maxDataLength??4194304;return nu(r,n),new V(e(r.byteLength),r)};var Xe;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Xe||(Xe={}));var ji=r=>{let t=Ot(r);return ji.bytes=nt(t),t};ji.bytes=0;function Ze(r,t){let e=new V,n=Xe.LENGTH,o=-1,s=t?.lengthDecoder??ji,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===Xe.LENGTH)try{if(o=s(e),o<0)throw new ho("Invalid message length");if(o>a)throw new Sr("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=Xe.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new po("Message length length too long");break}throw l}if(n===Xe.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=Xe.LENGTH}}}return mo(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new cn("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new cn("Unexpected end of input")}()}Ze.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 Ze(n,{...t??{},onLength:s=>{e=s}})};var Xi=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 un(r,t,e,n){let o=new Xi(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){e?.removeEventListener("abort",u),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),i(d);return}a(),s(f)},l=f=>{a(),i(f.detail)},u=()=>{a(),i(o)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var Zi=class extends fo{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;closeController;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 sn(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(s){this.log.error("error receiving FIN_ACK",s)}}).then(()=>{this.incomingData.end(),this.channel.close(),e?.(o)}).catch(s=>{this.log.error("error ending stream",s)})},super(t),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=Er(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??Ml,this.maxBufferedAmount=t.maxBufferedAmount??Kl,this.maxMessageSize=(t.maxMessageSize??xr)-Fl,this.receiveFinAck=Z(),this.finAckTimeout=t.closeTimeout??Hl,this.openTimeout=t.openTimeout??ql,this.closeController=new AbortController,this.channel.readyState){case"open":this.timeline.open=new Date().getTime();break;case"closed":case"closing":(this.timeline.close===void 0||this.timeline.close===0)&&(this.timeline.close=Date.now());break;case"connecting":break;default:throw this.log.error("unknown datachannel state %s",this.channel.readyState),new Ne("Unknown datachannel state")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime()},this.channel.onclose=o=>{this.log.trace("received onclose event"),this.closeController.abort(),this.receiveFinAck.resolve(),this.close().catch(s=>{this.log.error("error closing stream after channel closed",s)})},this.channel.onerror=o=>{this.log.trace("received onerror event"),this.closeController.abort();let s=o.error;this.abort(s)},this.channel.onmessage=async o=>{let{data:s}=o;s===null||s.byteLength===0||this.incomingData.push(new Uint8Array(s,0,s.byteLength))};let n=this;Promise.resolve().then(async()=>{for await(let o of Ze(this.incomingData)){let s=n.processIncomingProtobuf(o);s!=null&&n.sourcePush(new V(s))}}).catch(o=>{this.log.error("error processing incoming data channel messages",o)})}sendNewStream(){}async _sendMessage(t,e=!0){if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new Ne(`Invalid datachannel state - ${this.channel.readyState}`);if(this.channel.readyState!=="open"){let n=AbortSignal.timeout(this.openTimeout),o=$i([this.closeController.signal,n]);try{this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await un(this.channel,"open",o)}finally{o.clear()}this.log('channel state is now "%s", sending data',this.channel.readyState)}if(e&&this.channel.bufferedAmount>this.maxBufferedAmount){let n=AbortSignal.timeout(this.bufferedAmountLowEventTimeout),o=$i([this.closeController.signal,n]);try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await un(this.channel,"bufferedamountlow",o)}catch(s){throw n.aborted?new An(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`):s}finally{o.clear()}}try{this.channel.send(t.subarray())}catch(n){this.log.error("error while sending message",n)}}async sendData(t){for(this.log.trace("-> will send %d bytes",t.byteLength),t=t.sublist();t.byteLength>0;){let e=Math.min(t.byteLength,this.maxMessageSize),n=t.subarray(0,e),o=Bt.encode({message:n}),s=ln.single(o);this.log.trace("-> sending message %s",this.channel.readyState),await this._sendMessage(s),this.log.trace("-> sent message %s",this.channel.readyState),t.consume(e)}this.log.trace("-> sent data %s",this.channel.readyState)}async sendReset(){try{await this._sendFlag(Bt.Flag.RESET)}catch(t){this.log.error("failed to send reset - %e",t)}}async sendCloseWrite(t){if(this.channel.readyState!=="open"){this.receiveFinAck.resolve();return}if(await this._sendFlag(Bt.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await bt(this.receiveFinAck.promise,t?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorName:"FinAckNotReceivedError"})}catch(n){this.log.error("failed to await FIN_ACK",n)}}else this.log.trace("sending FIN failed, not awaiting FIN_ACK");this.receiveFinAck.resolve()}async sendCloseRead(){this.channel.readyState==="open"&&await this._sendFlag(Bt.Flag.STOP_SENDING)}processIncomingProtobuf(t){let e=Bt.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===Bt.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Bt.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),e.flag===Bt.Flag.RESET&&this.reset(),e.flag===Bt.Flag.STOP_SENDING&&this.remoteCloseRead(),e.flag===Bt.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=Bt.encode({flag:t}),n=ln.single(e);try{return await this._sendMessage(n,!1),!0}catch(o){this.log.error("could not send flag %s - %e",t.toString(),o)}return!1}};function Ar(r){let{channel:t,direction:e}=r;return new Zi({id:e==="inbound"?`i${t.id}`:`r${t.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${e}:${t.id}`),...r})}var Re=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??Hi,this.dataChannelOptions=e.dataChannelOptions??{},this.log=t.logger.forComponent("libp2p:webrtc:muxerfactory"),this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace('incoming early datachannel with channel id %d and label "%s"',n.id),n.label==="init"){this.log.trace("closing early init channel"),n.close();return}let o={},s=Ar({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 Yi(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},Yi=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??Hi,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=n.id,s=Ar({channel:n,direction:"inbound",onEnd:()=>{this.#t(s,n),this.log("incoming channel %s ended",o)},logger:this.logger,...this.dataChannelOptions});this.streams.push(s),this.metrics?.increment({incoming_stream:!0}),e?.onIncomingStream?.(s)},this.init.streams.length>0&&queueMicrotask(()=>{this.init.streams.forEach(n=>{n.onEnd=()=>{this.log("incoming early channel %s ended with state %s",n.channel.id,n.channel.readyState),this.#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),Jl(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=ao();sink=co;newStream(){let t=this.peerConnection.createDataChannel(""),e=t.id;this.log.trace("opened outgoing datachannel with channel id %s",e);let n=Ar({channel:t,direction:"outbound",onEnd:()=>{this.#t(n,t),this.log("outgoing channel %s ended",e)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(n),this.metrics?.increment({outgoing_stream:!0}),n}};var wo=globalThis.RTCPeerConnection,xo=globalThis.RTCSessionDescription,ou=globalThis.RTCIceCandidate;var Ji=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Z(),this.haveNext=Z()}[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=Z(),t}async throw(t){return this.ended=!0,this.error=t,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 this.ended=!0,this.nextResult=t,this.haveNext.resolve(),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 this.error??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=Z(),await bt(this.readNext.promise,e?.signal,e)}};function su(){return new Ji}var bo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function iu(r,t){let e=su();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 V;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:l}=await bt(n.next(),i?.signal);return c===!0?null:l}for(;o.byteLength<i.bytes;){let{value:c,done:l}=await bt(n.next(),i?.signal);if(l===!0)throw new bo("unexpected end of input");o.append(c)}let a=o.sublist(0,i.bytes);return o.consume(i.bytes),a},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 Eo=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},So=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ao=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function au(r,t={}){let e=iu(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=nt(t.maxDataLength));let n=t?.lengthDecoder??Ot,o=t?.lengthEncoder??qt;return{read:async i=>{let a=-1,c=new V;for(;;){c.append(await e.read({...i,bytes:1}));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Eo("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ao("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new So("message length too long");return e.read({...i,bytes:a})},write:async(i,a)=>{await e.write(new V(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new V(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function vo(r,t){let e=au(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 Mt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var De=class extends Error{constructor(t){super(`WebRTC transport error: ${t}`),this.name="WebRTCTransportError"}},Vt=class extends De{constructor(t="SDP handshake failed"){super(t),this.name="SDPHandshakeFailedError"}};var Io=class extends De{constructor(t,e){super(`Invalid fingerprint "${t}" within ${e}`),this.name="WebRTC/InvalidFingerprintError"}};var Co=class extends De{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},To=class extends De{constructor(t){super(`unsupported hash algorithm code: ${t} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var Ut;(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=()=>Ge(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Jt((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.data!=null&&(s.uint32(18),s.string(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.data=o.string();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Yt(o,r.codec()),r.decode=(o,s)=>Zt(o,r.codec(),s)})(Ut||(Ut={}));var _o=async(r,t,e)=>{try{let n=Z();for(lm(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!==Ut.Type.ICE_CANDIDATE)throw new Sn("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){e.onProgress?.(new Mt("webrtc:end-of-ice-candidates")),e.log.trace("end-of-candidates received");continue}let i=new ou(s);e.log.trace("%s received new ICE candidate %o",e.direction,s);try{e.onProgress?.(new Mt("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&&Lo(r)!=="connected")throw n}};function Lo(r){return an?r.iceConnectionState:r.connectionState}function lm(r,t){r[an?"oniceconnectionstatechange":"onconnectionstatechange"]=e=>{switch(Lo(r)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new wn("RTCPeerConnection was closed"));break;default:break}}}async function cu({rtcConfiguration:r,dataChannel:t,signal:e,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=lu(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",u);let f=u.getPeerId();if(f==null)throw new Q("Relay peer was missing");let d=s.getConnections(mr(f)),g,x=!1;d.length===0?(l?.(new Mt("webrtc:dial-relay")),g=await i.dial(u,{signal:e,onProgress:l}),x=!0):(l?.(new Mt("webrtc:reuse-relay-connection")),g=d[0]);try{l?.(new Mt("webrtc:open-signaling-stream"));let m=await g.newStream(on,{signal:e,runOnLimitedConnection:!0}),h=vo(m).pb(Ut),w=new wo(r),b=new Re({logger:c},{peerConnection:w,dataChannelOptions:t});try{let p=w.createDataChannel("init");w.onicecandidate=({candidate:v})=>{let L=JSON.stringify(v?.toJSON()??null);a.trace("initiator sending ICE candidate %o",v),h.write({type:Ut.Type.ICE_CANDIDATE,data:L},{signal:e}).catch(T=>{a.error("error sending ICE candidate",T)})},w.onicecandidateerror=v=>{a.error("initiator ICE candidate error",v)};let I=await w.createOffer().catch(v=>{throw a.error("could not execute createOffer",v),new Vt("Failed to set createOffer")});a.trace("initiator send SDP offer %s",I.sdp),l?.(new Mt("webrtc:send-sdp-offer")),await h.write({type:Ut.Type.SDP_OFFER,data:I.sdp},{signal:e}),await w.setLocalDescription(I).catch(v=>{throw a.error("could not execute setLocalDescription",v),new Vt("Failed to set localDescription")}),l?.(new Mt("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let P=await h.read({signal:e});if(P.type!==Ut.Type.SDP_ANSWER)throw new Vt("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",P.data);let B=new xo({type:"answer",sdp:P.data});return await w.setRemoteDescription(B).catch(v=>{throw a.error("could not execute setRemoteDescription",v),new Vt("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),l?.(new Mt("webrtc:read-ice-candidates")),await _o(w,h,{direction:"initiator",signal:e,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),p.close(),l?.(new Mt("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await m.close({signal:e}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:w,muxerFactory:b}}catch(p){throw a.error("outgoing signaling error",p),w.close(),m.abort(p),p}finally{w.onicecandidate=null,w.onicecandidateerror=null}}finally{if(x)try{await g.close({signal:e})}catch(m){g.abort(m)}}}var uu=lt(Dl.matchers[0],z("p2p-circuit")),Bo=class r extends Qe{transportManager;shutdownController;events;constructor(t,e){super(),this.transportManager=t.transportManager,this.events=t.events,this.shutdownController=e.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(t){t.detail.getAddrs().filter(n=>uu.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(t=>!(t instanceof r)).map(t=>t.getAddrs().filter(e=>uu.exactMatch(e)).map(e=>e.encapsulate("/webrtc"))).flat()}updateAnnounceAddrs(){}async close(){this.events.removeEventListener("transport:listening",this.onTransportListening),this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function fu({peerConnection:r,stream:t,signal:e,connection:n,log:o}){o.trace("new inbound signaling stream");let s=vo(t).pb(Ut);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:Ut.Type.ICE_CANDIDATE,data:f},{signal:e}).catch(d=>{o.error("error sending ICE candidate",d)})},o.trace("recipient read SDP offer");let a=await s.read({signal:e});if(a.type!==Ut.Type.SDP_OFFER)throw new Vt(`expected message type SDP_OFFER, received: ${a.type??"undefined"} `);o.trace("recipient received SDP offer %s",a.data);let c=new xo({type:"offer",sdp:a.data});await r.setRemoteDescription(c).catch(u=>{throw o.error("could not execute setRemoteDescription",u),new Vt("Failed to set remoteDescription")});let l=await r.createAnswer().catch(u=>{throw o.error("could not execute createAnswer",u),new Vt("Failed to create answer")});o.trace("recipient send SDP answer %s",l.sdp),await s.write({type:Ut.Type.SDP_ANSWER,data:l.sdp},{signal:e}),await r.setLocalDescription(l).catch(u=>{throw o.error("could not execute setLocalDescription",u),new Vt("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await _o(r,s,{direction:"recipient",signal:e,log:o})}catch(a){if(Lo(r)!=="connected")throw o.error("error while handling signaling stream from peer %a",n.remoteAddr,a),r.close(),a;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",n.remoteAddr,a)}let i=re(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return o.trace("recipient connected to remote address %s",i),{remoteAddress:i}}var Po=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,e={}){this.components=t,this.init=e,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[mn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[tr]=["@libp2p/transport"];[Ka]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(on,t=>{let e=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(t,e).catch(n=>{this.log.error("failed to handle incoming connect from %p",t.connection.remotePeer,n)}).finally(()=>{e.clear()})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(on),this._started=!1}createListener(t){return new Bo(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(Nl.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 cu({rtcConfiguration:await Wi(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 je(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,signal:e.signal});return this._closeOnShutdown(o,i),a}async _onProtocol({connection:t,stream:e},n){let o=new wo(await Wi(this.init.rtcConfiguration)),s=new Re(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await fu({peerConnection:o,connection:t,stream:e,signal:n,log:this.log});await e.close({signal:n});let a=new je(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,signal:n}),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 lu(r){let t=r.toString().split("/webrtc/");if(t.length!==2)throw new Q("webrtc protocol was not present in multiaddr");if(!t[0].includes("/p2p-circuit"))throw new Q("p2p-circuit protocol was not present in multiaddr");let e=re(t[0]),o=re("/"+t[1]).getPeerId();if(o==null)throw new Q("destination peer id was missing");let s=e.protos().pop();if(s===void 0)throw new Q("invalid multiaddr");return s.name!=="p2p"&&(e=e.encapsulate(`/p2p/${o}`)),{baseAddr:e,peerId:mr(o)}}var Ro=class extends Qe{async listen(){throw new Co("WebRTCTransport.createListener")}getAddrs(){return[]}updateAnnounceAddrs(){}async close(){}};var Qi=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=Z(),this.haveNext=Z()}[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=Z(),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 this.ended=!0,this.nextResult=t,this.haveNext.resolve(),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=Z(),await bt(this.readNext.promise,e?.signal,e)}};function hu(){return new Qi}var Do=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var ta=class extends Error{code;constructor(t,e){super(t),this.code=e}},ea=class extends ta{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function du(r,t){let e=hu();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 V;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new ea("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:d}=await Promise.race([n.next(),l]);return f===!0?new V:d}for(;o.byteLength<i;){let{value:f,done:d}=await Promise.race([n.next(),l]);if(d===!0)throw new Do("unexpected end of input");o.append(f)}let u=o.sublist(0,i);return o.consume(i),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await 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 No=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ko=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Uo=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function ra(r,t={}){let e=du(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=nt(t.maxDataLength));let n=t?.lengthDecoder??Ot,o=t?.lengthEncoder??qt;return{read:async i=>{let a=-1,c=new V;for(;;){c.append(await e.read(1,i));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new No("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Uo("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new ko("message length too long");return e.read(a,i)},write:async(i,a)=>{await e.write(new V(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new V(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function na(){let r=Z(),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 pu(){let r=na(),t=na();return[{source:r.source,sink:t.sink},{source:t.source,sink:r.sink}]}var oa=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Z(),this.haveNext=Z()}[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=Z(),t}async throw(t){return this.ended=!0,this.error=t,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 this.ended=!0,this.nextResult=t,this.haveNext.resolve(),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 this.error??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=Z(),await bt(this.readNext.promise,e?.signal,e)}};function mu(){return new oa}function um(r){return r[Symbol.asyncIterator]!=null}async function fm(r,t){try{await Promise.all(r.map(async e=>{for await(let n of e)await t.push(n)})),await t.end()}catch(e){await t.end(e).catch(()=>{})}}async function*hm(r){let t=mu();fm(r,t).catch(()=>{}),yield*t}function*dm(r){for(let t of r)yield*t}function pm(...r){let t=[];for(let e of r)um(e)||t.push(e);return t.length===r.length?dm(t):hm(r)}var gu=pm;function yu(r,...t){if(r==null)throw new Error("Empty pipeline");if(sa(r)){let n=r;r=()=>n.source}else if(xu(r)||wu(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&sa(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++)sa(e[n])&&(e[n]=gm(e[n]));return mm(...e)}var mm=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},wu=r=>r?.[Symbol.asyncIterator]!=null,xu=r=>r?.[Symbol.iterator]!=null,sa=r=>r==null?!1:r.sink!=null&&r.source!=null,gm=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Er({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(wu(s))o=async function*(){yield*s,n.end()};else if(xu(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return gu(n,o())}return r.source};var vr=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function Oo(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function ia(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Pt(r,...t){if(!ia(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function aa(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 bu(r,t){Pt(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function ca(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}var ge=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),Eu=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ym=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!ym)throw new Error("Non little-endian hardware is not supported");function wm(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Ko(r){if(typeof r=="string")r=wm(r);else if(ia(r))r=Mo(r);else throw new Error("Uint8Array expected, got "+typeof r);return r}function Su(r,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(r,t)}function Au(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 la=(r,t)=>{function e(n,...o){if(Pt(n),r.nonceLength!==void 0){let u=o[0];if(!u)throw new Error("nonce / iv required");r.varSizeNonce?Pt(u):Pt(u,r.nonceLength)}let s=r.tagLength;s&&o[1]!==void 0&&Pt(o[1]);let i=t(n,...o),a=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");Pt(f)}},c=!1;return{encrypt(u,f){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Pt(u),a(i.encrypt.length,f),i.encrypt(u,f)},decrypt(u,f){if(Pt(u),s&&u.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(i.decrypt.length,f),i.decrypt(u,f)}}}return Object.assign(e,r),e};function ua(r,t,e=!0){if(t===void 0)return new Uint8Array(r);if(t.length!==r)throw new Error("invalid output length, expected "+r+", got: "+t.length);if(e&&!xm(t))throw new Error("invalid output, must be aligned");return t}function fa(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)}function xm(r){return r.byteOffset%4===0}function Mo(r){return Uint8Array.from(r)}function ye(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}var Iu=r=>Uint8Array.from(r.split("").map(t=>t.charCodeAt(0))),bm=Iu("expand 16-byte k"),Em=Iu("expand 32-byte k"),Sm=ge(bm),Am=ge(Em);function k(r,t){return r<<t|r>>>32-t}function ha(r){return r.byteOffset%4===0}var Fo=64,vm=16,Cu=2**32-1,vu=new Uint32Array;function Im(r,t,e,n,o,s,i,a){let c=o.length,l=new Uint8Array(Fo),u=ge(l),f=ha(o)&&ha(s),d=f?ge(o):vu,g=f?ge(s):vu;for(let x=0;x<c;i++){if(r(t,e,n,u,i,a),i>=Cu)throw new Error("arx: counter overflow");let m=Math.min(Fo,c-x);if(f&&m===Fo){let h=x/4;if(x%4!==0)throw new Error("arx: invalid block position");for(let w=0,b;w<vm;w++)b=h+w,g[b]=d[b]^u[w];x+=Fo;continue}for(let h=0,w;h<m;h++)w=x+h,s[w]=o[w]^l[h];x+=m}}function da(r,t){let{allowShortKeys:e,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Su({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof r!="function")throw new Error("core must be a function");return Oo(o),Oo(i),ca(s),ca(e),(a,c,l,u,f=0)=>{Pt(a),Pt(c),Pt(l);let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),Pt(u),Oo(f),f<0||f>=Cu)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let g=[],x=a.length,m,h;if(x===32)g.push(m=Mo(a)),h=Am;else if(x===16&&e)m=new Uint8Array(32),m.set(a),m.set(a,16),h=Sm,g.push(m);else throw new Error(`arx: invalid 32-byte key, got length=${x}`);ha(c)||g.push(c=Mo(c));let w=ge(m);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,w,ge(c.subarray(0,16)),w),c=c.subarray(16)}let b=16-o;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let I=new Uint8Array(12);I.set(c,s?0:12-c.length),c=I,g.push(c)}let p=ge(c);return Im(r,h,w,p,l,u,f,i),ye(...g),u}}var At=(r,t)=>r[t++]&255|(r[t++]&255)<<8,pa=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=Ko(t),Pt(t,32);let e=At(t,0),n=At(t,2),o=At(t,4),s=At(t,6),i=At(t,8),a=At(t,10),c=At(t,12),l=At(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]=At(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],d=i[5],g=i[6],x=i[7],m=i[8],h=i[9],w=At(t,e+0),b=At(t,e+2),p=At(t,e+4),I=At(t,e+6),P=At(t,e+8),B=At(t,e+10),v=At(t,e+12),L=At(t,e+14),T=s[0]+(w&8191),K=s[1]+((w>>>13|b<<3)&8191),N=s[2]+((b>>>10|p<<6)&8191),O=s[3]+((p>>>7|I<<9)&8191),F=s[4]+((I>>>4|P<<12)&8191),C=s[5]+(P>>>1&8191),_=s[6]+((P>>>14|B<<2)&8191),E=s[7]+((B>>>11|v<<5)&8191),y=s[8]+((v>>>8|L<<8)&8191),A=s[9]+(L>>>5|o),S=0,R=S+T*a+K*(5*h)+N*(5*m)+O*(5*x)+F*(5*g);S=R>>>13,R&=8191,R+=C*(5*d)+_*(5*f)+E*(5*u)+y*(5*l)+A*(5*c),S+=R>>>13,R&=8191;let D=S+T*c+K*a+N*(5*h)+O*(5*m)+F*(5*x);S=D>>>13,D&=8191,D+=C*(5*g)+_*(5*d)+E*(5*f)+y*(5*u)+A*(5*l),S+=D>>>13,D&=8191;let U=S+T*l+K*c+N*a+O*(5*h)+F*(5*m);S=U>>>13,U&=8191,U+=C*(5*x)+_*(5*g)+E*(5*d)+y*(5*f)+A*(5*u),S+=U>>>13,U&=8191;let q=S+T*u+K*l+N*c+O*a+F*(5*h);S=q>>>13,q&=8191,q+=C*(5*m)+_*(5*x)+E*(5*g)+y*(5*d)+A*(5*f),S+=q>>>13,q&=8191;let M=S+T*f+K*u+N*l+O*c+F*a;S=M>>>13,M&=8191,M+=C*(5*h)+_*(5*m)+E*(5*x)+y*(5*g)+A*(5*d),S+=M>>>13,M&=8191;let G=S+T*d+K*f+N*u+O*l+F*c;S=G>>>13,G&=8191,G+=C*a+_*(5*h)+E*(5*m)+y*(5*x)+A*(5*g),S+=G>>>13,G&=8191;let j=S+T*g+K*d+N*f+O*u+F*l;S=j>>>13,j&=8191,j+=C*c+_*a+E*(5*h)+y*(5*m)+A*(5*x),S+=j>>>13,j&=8191;let it=S+T*x+K*g+N*d+O*f+F*u;S=it>>>13,it&=8191,it+=C*l+_*c+E*a+y*(5*h)+A*(5*m),S+=it>>>13,it&=8191;let at=S+T*m+K*x+N*g+O*d+F*f;S=at>>>13,at&=8191,at+=C*u+_*l+E*c+y*a+A*(5*h),S+=at>>>13,at&=8191;let ut=S+T*h+K*m+N*x+O*g+F*d;S=ut>>>13,ut&=8191,ut+=C*f+_*u+E*l+y*c+A*a,S+=ut>>>13,ut&=8191,S=(S<<2)+S|0,S=S+R|0,R=S&8191,S=S>>>13,D+=S,s[0]=R,s[1]=D,s[2]=U,s[3]=q,s[4]=M,s[5]=G,s[6]=j,s[7]=it,s[8]=at,s[9]=ut}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;ye(n)}update(t){aa(this);let{buffer:e,blockLen:n}=this;t=Ko(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(){ye(this.h,this.r,this.buffer,this.pad)}digestInto(t){aa(this),bu(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 Cm(r){let t=(n,o)=>r(o).update(Ko(n)).digest(),e=r(new Uint8Array(32));return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=n=>r(n),t}var Tu=Cm(r=>new pa(r));function Bu(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],d=t[2],g=t[3],x=t[4],m=t[5],h=t[6],w=t[7],b=o,p=e[0],I=e[1],P=e[2],B=i,v=a,L=c,T=l,K=u,N=f,O=d,F=g,C=x,_=m,E=h,y=w,A=b,S=p,R=I,D=P;for(let q=0;q<s;q+=2)B=B+K|0,A=k(A^B,16),C=C+A|0,K=k(K^C,12),B=B+K|0,A=k(A^B,8),C=C+A|0,K=k(K^C,7),v=v+N|0,S=k(S^v,16),_=_+S|0,N=k(N^_,12),v=v+N|0,S=k(S^v,8),_=_+S|0,N=k(N^_,7),L=L+O|0,R=k(R^L,16),E=E+R|0,O=k(O^E,12),L=L+O|0,R=k(R^L,8),E=E+R|0,O=k(O^E,7),T=T+F|0,D=k(D^T,16),y=y+D|0,F=k(F^y,12),T=T+F|0,D=k(D^T,8),y=y+D|0,F=k(F^y,7),B=B+N|0,D=k(D^B,16),E=E+D|0,N=k(N^E,12),B=B+N|0,D=k(D^B,8),E=E+D|0,N=k(N^E,7),v=v+O|0,A=k(A^v,16),y=y+A|0,O=k(O^y,12),v=v+O|0,A=k(A^v,8),y=y+A|0,O=k(O^y,7),L=L+F|0,S=k(S^L,16),C=C+S|0,F=k(F^C,12),L=L+F|0,S=k(S^L,8),C=C+S|0,F=k(F^C,7),T=T+K|0,R=k(R^T,16),_=_+R|0,K=k(K^_,12),T=T+K|0,R=k(R^T,8),_=_+R|0,K=k(K^_,7);let U=0;n[U++]=i+B|0,n[U++]=a+v|0,n[U++]=c+L|0,n[U++]=l+T|0,n[U++]=u+K|0,n[U++]=f+N|0,n[U++]=d+O|0,n[U++]=g+F|0,n[U++]=x+C|0,n[U++]=m+_|0,n[U++]=h+E|0,n[U++]=w+y|0,n[U++]=b+A|0,n[U++]=p+S|0,n[U++]=I+R|0,n[U++]=P+D|0}function Tm(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],d=t[4],g=t[5],x=t[6],m=t[7],h=e[0],w=e[1],b=e[2],p=e[3];for(let P=0;P<20;P+=2)o=o+c|0,h=k(h^o,16),d=d+h|0,c=k(c^d,12),o=o+c|0,h=k(h^o,8),d=d+h|0,c=k(c^d,7),s=s+l|0,w=k(w^s,16),g=g+w|0,l=k(l^g,12),s=s+l|0,w=k(w^s,8),g=g+w|0,l=k(l^g,7),i=i+u|0,b=k(b^i,16),x=x+b|0,u=k(u^x,12),i=i+u|0,b=k(b^i,8),x=x+b|0,u=k(u^x,7),a=a+f|0,p=k(p^a,16),m=m+p|0,f=k(f^m,12),a=a+f|0,p=k(p^a,8),m=m+p|0,f=k(f^m,7),o=o+l|0,p=k(p^o,16),x=x+p|0,l=k(l^x,12),o=o+l|0,p=k(p^o,8),x=x+p|0,l=k(l^x,7),s=s+u|0,h=k(h^s,16),m=m+h|0,u=k(u^m,12),s=s+u|0,h=k(h^s,8),m=m+h|0,u=k(u^m,7),i=i+f|0,w=k(w^i,16),d=d+w|0,f=k(f^d,12),i=i+f|0,w=k(w^i,8),d=d+w|0,f=k(f^d,7),a=a+c|0,b=k(b^a,16),g=g+b|0,c=k(c^g,12),a=a+c|0,b=k(b^a,8),g=g+b|0,c=k(c^g,7);let I=0;n[I++]=o,n[I++]=s,n[I++]=i,n[I++]=a,n[I++]=h,n[I++]=w,n[I++]=b,n[I++]=p}var _m=da(Bu,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Lm=da(Bu,{counterRight:!1,counterLength:8,extendNonceFn:Tm,allowShortKeys:!1});var Bm=new Uint8Array(16),_u=(r,t)=>{r.update(t);let e=t.length%16;e&&r.update(Bm.subarray(e))},Pm=new Uint8Array(32);function Lu(r,t,e,n,o){let s=r(t,e,Pm),i=Tu.create(s);o&&_u(i,o),_u(i,n);let a=new Uint8Array(16),c=Eu(a);fa(c,0,BigInt(o?o.length:0),!0),fa(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return ye(s,a),l}var Pu=r=>(t,e,n)=>({encrypt(s,i){let a=s.length;i=ua(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);r(t,e,c,c,1);let l=Lu(r,t,e,c,n);return i.set(l,a),ye(l),i},decrypt(s,i){i=ua(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=Lu(r,t,e,a,n);if(!Au(c,l))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),r(t,e,i,i,1),ye(l),i}}),ma=la({blockSize:64,nonceLength:12,tagLength:16},Pu(_m)),m8=la({blockSize:64,nonceLength:24,tagLength:16},Pu(Lm));function Du(r,t,e){return Ur(r),e===void 0&&(e=new Uint8Array(r.outputLen)),pr(r,Se(e),Se(t))}var ga=new Uint8Array([0]),Ru=new Uint8Array;function Nu(r,t,e,n=32){if(Ur(r),_n(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);e===void 0&&(e=Ru);let s=new Uint8Array(o*r.outputLen),i=pr.create(r,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)ga[0]=l+1,a.update(l===0?Ru:c).update(e).update(ga).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),ga.fill(0),s.slice(0,n)}var ya={hashSHA256(r){return ee(r.subarray())},getHKDF(r,t){let e=Du(ee,t,r),o=Nu(ee,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=qr.utils.randomPrivateKey();return{publicKey:qr.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:qr.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,t){return qr.getSharedSecret(r.subarray(),t.subarray())},chaCha20Poly1305Encrypt(r,t,e,n){return ma(n,t,e).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,t,e,n,o){return ma(n,t,e).decrypt(r.subarray(),o)}};var ku=ya;function Uu(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 Ir=r=>{let t=gt(2);return t[0]=r>>8,t[1]=r,t};Ir.bytes=2;var fn=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)};fn.bytes=2;function Ou(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 wa(r,t){!t.enabled||!vr||(r?(t(`LOCAL_STATIC_PUBLIC_KEY ${H(r.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${H(r.privateKey,"hex")}`)):t("Missing local static keys."))}function xa(r,t){!t.enabled||!vr||(r?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${H(r.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${H(r.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function Ku(r,t){!t.enabled||!vr||t(r?`REMOTE_STATIC_PUBLIC_KEY ${H(r.subarray(),"hex")}`:"Missing remote static public key.")}function ba(r,t){!t.enabled||!vr||t(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${H(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Ea(r,t,e){!e.enabled||!vr||(e(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&H(r.k,"hex")}`),e(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&H(t.k,"hex")}`))}var Cr=class r extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var Rm=0,Dm=4294967295,Nm="Cipherstate has reached maximum n, a new handshake must be performed",Ho=class{n;bytes;view;constructor(t=Rm){this.n=t,this.bytes=mt(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>Dm)throw new Error(Nm)}};var Ye=mt(0),Tr=class{k;n;crypto;constructor(t,e=void 0,n=0){this.crypto=t,this.k=e,this.n=new Ho(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}},Sa=class{cs;ck;h;crypto;constructor(t,e){this.crypto=t;let n=X(e,"utf-8");this.h=km(t,n),this.ck=this.h,this.cs=new Tr(t)}mixKey(t){let[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new Tr(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new V(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,Ye);return[new Tr(this.crypto,t),new Tr(this.crypto,e)]}},Aa=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 Sa(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()}},hn=class extends Aa{writeMessageA(t){return new V(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let e=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new V(e,n,this.ss.encryptAndHash(t))}writeMessageC(t){let e=this.writeS();return this.writeSE(),new V(e,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(e){throw new Cr(`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 Cr(`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 Cr(`handshake stage 2 validation fail: ${e.message}`)}}};function km(r,t){if(t.length<=32){let e=mt(32);return e.set(t),e}else return r.hash(t)}var qo;(function(r){let t;r.codec=()=>(t==null&&(t=Jt((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.webtransportCerthashes!=null)for(let s of e.webtransportCerthashes)n.uint32(10),n.bytes(s);if(e.streamMuxers!=null)for(let s of e.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new Gr('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(e.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new Gr('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(e.string());break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Yt(e,r.codec()),r.decode=(e,n)=>Zt(e,r.codec(),n)})(qo||(qo={}));var dn;(function(r){let t;r.codec=()=>(t==null&&(t=Jt((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),qo.codec().encode(e.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={identityKey:mt(0),identitySig:mt(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.identityKey=e.bytes();break}case 2:{s.identitySig=e.bytes();break}case 4:{s.extensions=qo.codec().decode(e,e.uint32(),{limits:o.limits?.extensions});break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Yt(e,r.codec()),r.decode=(e,n)=>Zt(e,r.codec(),n)})(dn||(dn={}));async function va(r,t,e){let n=await r.sign(Mu(t));return dn.encode({identityKey:Ee(r.publicKey),identitySig:n,extensions:e})}async function Ia(r,t,e){try{let n=dn.decode(r),o=Xr(n.identityKey);if(e?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${e}`);if(!t)throw new Error("Remote static does not exist");let s=Mu(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new gn(n.message)}}function Mu(r){let t=X("noise-libp2p-static-key:");return r instanceof Uint8Array?yt([t,r],t.length+r.length):(r.prepend(t),r)}async function Fu(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await va(s,a.publicKey,l),f=new hn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});wa(f.s,e),e.trace("Stage 0 - Initiator starting to send first message."),await n.write(f.writeMessageA(Ye),t),e.trace("Stage 0 - Initiator finished sending first message."),xa(f.e,e),e.trace("Stage 1 - Initiator waiting to receive first message from responder...");let d=f.readMessageB(await n.read(t));e.trace("Stage 1 - Initiator received the message."),ba(f.re,e),Ku(f.rs,e),e.trace("Initiator going to check remote's signature...");let g=await Ia(d,f.rs,c);e.trace("All good with the signature!"),e.trace("Stage 2 - Initiator sending third handshake message."),await n.write(f.writeMessageC(u),t),e.trace("Stage 2 - Initiator sent message with signed payload.");let[x,m]=f.ss.split();return Ea(x,m,e),{payload:g,encrypt:h=>x.encryptWithAd(Ye,h),decrypt:(h,w)=>m.decryptWithAd(Ye,h,w)}}async function Hu(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await va(s,a.publicKey,l),f=new hn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});wa(f.s,e),e.trace("Stage 0 - Responder waiting to receive first message."),f.readMessageA(await n.read(t)),e.trace("Stage 0 - Responder received first message."),ba(f.re,e),e.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(f.writeMessageB(u),t),e.trace("Stage 1 - Responder sent the second handshake message with signed payload."),xa(f.e,e),e.trace("Stage 2 - Responder waiting for third handshake message...");let d=f.readMessageC(await n.read(t));e.trace("Stage 2 - Responder received the message, finished handshake.");let g=await Ia(d,f.rs,c),[x,m]=f.ss.split();return Ea(x,m,e),{payload:g,encrypt:h=>m.encryptWithAd(Ye,h),decrypt:(h,w)=>x.decryptWithAd(Ye,h,w)}}var Vu=16;function Wu(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 V(Ir(i.byteLength),i)}}}function Gu(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-Vu<o)throw new Error("Invalid chunk");let i=n.sublist(o,s),a=n.subarray(o,s-Vu);try{let c=r.decrypt(i,a);t?.decryptedPackets.increment(),yield c}catch(c){throw t?.decryptErrors.increment(),c}}}}var Vo=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??ku;this.crypto=Uu(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?Ou(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??mt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[tr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,e){let n=ra(t,{lengthEncoder:Ir,lengthDecoder:fn,maxDataLength:65535}),o=await this.performHandshakeInitiator(n,this.components.privateKey,e?.remotePeer?.publicKey,e),s=await this.createSecureConnection(n,o);t.source=s.source,t.sink=s.sink;let i=Xr(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:bi(i),streamMuxer:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}getStreamMuxer(t){if(t==null)return;let e=this.components.upgrader.getStreamMuxers();if(e!=null)for(let n of t){let o=e.get(n);if(o!=null)return o}if(t.length)throw new yn("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(t,e){let n=ra(t,{lengthEncoder:Ir,lengthDecoder:fn,maxDataLength:65535}),o=await this.performHandshakeResponder(n,this.components.privateKey,e?.remotePeer?.publicKey,e),s=await this.createSecureConnection(n,o);t.source=s.source,t.sink=s.sink;let i=Xr(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:bi(i),streamMuxer:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(t,e,n,o){let s;try{s=await Fu({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:[...this.components.upgrader.getStreamMuxers().keys()],webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async performHandshakeResponder(t,e,n,o){let s;try{s=await Hu({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:[...this.components.upgrader.getStreamMuxers().keys()],webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async createSecureConnection(t,e){let[n,o]=pu(),s=t.unwrap();return await yu(n,Wu(e,this.metrics),s,i=>Ze(i,{lengthDecoder:fn}),Gu(e,this.metrics),n),o}};function zu(r={}){return t=>new Vo(t,r)}var Ca=Object.values(Oe).map(r=>r.decoder).reduce((r,t)=>r.or(t)),Um=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function $u(r){return r?.match(Um)?.groups?.fingerprint}function Ta(r){let e=r.stringTuples().filter(n=>n[0]===Ol).map(n=>n[1])[0];if(e===void 0||e==="")throw new Q(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return e}function Om(r){return Ft.decode(Ca.decode(r))}function Km(r){let t=Om(Ta(r)),e=Mm(t.code),n=t.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new Io(n,r.toString());return`${e} ${o.join(":").toUpperCase()}`}function ju(r){let t=r.split(":").map(o=>parseInt(o,16)),e=Uint8Array.from(t),n=Ct(ie.code,e);return re(`/certhash/${Br.encode(n.bytes)}`)}function Mm(r){switch(r){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new To(r)}}function Xu(r,t){let{host:e,port:n,family:o}=r.toOptions(),s=Km(r);return{type:"answer",sdp:`v=0
2
+ "use strict";var Libp2PWebrtc=(()=>{var zo=Object.defineProperty;var uf=Object.getOwnPropertyDescriptor;var ff=Object.getOwnPropertyNames;var hf=Object.prototype.hasOwnProperty;var It=(r,t)=>{for(var e in t)zo(r,e,{get:t[e],enumerable:!0})},df=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ff(t))!hf.call(r,o)&&o!==e&&zo(r,o,{get:()=>t[o],enumerable:!(n=uf(t,o))||n.enumerable});return r};var pf=r=>df(zo({},"__esModule",{value:!0}),r);var Vm={};It(Vm,{webRTC:()=>qm,webRTCDirect:()=>Hm});var $o=Symbol.for("@libp2p/peer-id");var mn=Symbol.for("@libp2p/transport");var Ka;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Ka||(Ka={}));var gn=class extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}},yn=class extends Error{static name="InvalidCryptoExchangeError";constructor(t="Invalid crypto exchange"){super(t),this.name="InvalidCryptoExchangeError"}},Q=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Je=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var wn=class extends Error{static name="ConnectionFailedError";constructor(t="Connection failed"){super(t),this.name="ConnectionFailedError"}};var xn=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}},Ne=class extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}};var bn=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},En=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var Sn=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var An=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}};var ke=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Qe=class extends EventTarget{#t=new Map;constructor(){super()}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){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 CustomEvent(t,e))}};var tr=Symbol.for("@libp2p/service-capabilities"),Ma=Symbol.for("@libp2p/service-dependencies");var Jo={};It(Jo,{base58btc:()=>et,base58flickr:()=>bf});var y0=new Uint8Array(0);function Fa(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 oe(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 Ha(r){return new TextEncoder().encode(r)}function qa(r){return new TextDecoder().decode(r)}function mf(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(x){if(x instanceof Uint8Array||(ArrayBuffer.isView(x)?x=new Uint8Array(x.buffer,x.byteOffset,x.byteLength):Array.isArray(x)&&(x=Uint8Array.from(x))),!(x instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(x.length===0)return"";for(var m=0,h=0,w=0,b=x.length;w!==b&&x[w]===0;)w++,m++;for(var p=(b-w)*u+1>>>0,I=new Uint8Array(p);w!==b;){for(var P=x[w],B=0,v=p-1;(P!==0||B<h)&&v!==-1;v--,B++)P+=256*I[v]>>>0,I[v]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");h=B,w++}for(var L=p-h;L!==p&&I[L]===0;)L++;for(var T=c.repeat(m);L<p;++L)T+=r.charAt(I[L]);return T}function d(x){if(typeof x!="string")throw new TypeError("Expected String");if(x.length===0)return new Uint8Array;var m=0;if(x[m]!==" "){for(var h=0,w=0;x[m]===c;)h++,m++;for(var b=(x.length-m)*l+1>>>0,p=new Uint8Array(b);x[m];){var I=e[x.charCodeAt(m)];if(I===255)return;for(var P=0,B=b-1;(I!==0||P<w)&&B!==-1;B--,P++)I+=a*p[B]>>>0,p[B]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");w=P,m++}if(x[m]!==" "){for(var v=b-w;v!==b&&p[v]===0;)v++;for(var L=new Uint8Array(h+(b-v)),T=h;v!==b;)L[T++]=p[v++];return L}}}function g(x){var m=d(x);if(m)return m;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:g}}var gf=mf,yf=gf,Wa=yf;var jo=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")}},Xo=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Ga(this,t)}},Zo=class{decoders;constructor(t){this.decoders=t}or(t){return Ga(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 Ga(r,t){return new Zo({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Yo=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 jo(t,e,n),this.decoder=new Xo(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function er({name:r,prefix:t,encode:e,decode:n}){return new Yo(r,t,e,n)}function we({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Wa(e,r);return er({prefix:t,name:r,encode:n,decode:s=>oe(o(s))})}function wf(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)!==0)throw new SyntaxError("Unexpected end of data");return i}function xf(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function ht({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return er({prefix:t,name:r,encode(o){return xf(o,n,e)},decode(o){return wf(o,n,e,r)}})}var et=we({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),bf=we({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Qo={};It(Qo,{base32:()=>se,base32hex:()=>vf,base32hexpad:()=>Cf,base32hexpadupper:()=>Tf,base32hexupper:()=>If,base32pad:()=>Sf,base32padupper:()=>Af,base32upper:()=>Ef,base32z:()=>_f});var se=ht({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ef=ht({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Sf=ht({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Af=ht({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),vf=ht({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),If=ht({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Cf=ht({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Tf=ht({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),_f=ht({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ts={};It(ts,{base36:()=>Lr,base36upper:()=>Lf});var Lr=we({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Lf=we({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ft={};It(Ft,{Digest:()=>Ue,create:()=>Ct,decode:()=>xe,equals:()=>rs,hasCode:()=>jf});var Bf=ja,za=128,Pf=127,Rf=~Pf,Df=Math.pow(2,31);function ja(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Df;)t[e++]=r&255|za,r/=128;for(;r&Rf;)t[e++]=r&255|za,r>>>=7;return t[e]=r|0,ja.bytes=e-n+1,t}var Nf=es,kf=128,$a=127;function es(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw es.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&$a)<<o:(i&$a)*Math.pow(2,o),o+=7}while(i>=kf);return es.bytes=s-n,e}var Uf=Math.pow(2,7),Of=Math.pow(2,14),Kf=Math.pow(2,21),Mf=Math.pow(2,28),Ff=Math.pow(2,35),Hf=Math.pow(2,42),qf=Math.pow(2,49),Vf=Math.pow(2,56),Wf=Math.pow(2,63),Gf=function(r){return r<Uf?1:r<Of?2:r<Kf?3:r<Mf?4:r<Ff?5:r<Hf?6:r<qf?7:r<Vf?8:r<Wf?9:10},zf={encode:Bf,decode:Nf,encodingLength:Gf},$f=zf,Br=$f;function Pr(r,t=0){return[Br.decode(r,t),Br.decode.bytes]}function rr(r,t,e=0){return Br.encode(r,t,e),t}function nr(r){return Br.encodingLength(r)}function Ct(r,t){let e=t.byteLength,n=nr(r),o=n+nr(e),s=new Uint8Array(o+e);return rr(r,s,0),rr(e,s,n),s.set(t,o),new Ue(r,e,t,s)}function xe(r){let t=oe(r),[e,n]=Pr(t),[o,s]=Pr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Ue(e,o,i,t)}function rs(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Fa(r.bytes,e.bytes)}}var Ue=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function jf(r,t){return r.code===t}function Xa(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Zf(e,ns(r),t??et.encoder);default:return Yf(e,ns(r),t??se.encoder)}}var Za=new WeakMap;function ns(r){let t=Za.get(r);if(t==null){let e=new Map;return Za.set(r,e),e}return t}var dt=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!==Rr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Jf)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=Ct(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&&rs(t.multihash,n.multihash)}toString(t){return Xa(this,t)}toJSON(){return{"/":Xa(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??Ya(n,o,s.bytes))}else if(e[Qf]===!0){let{version:n,multihash:o,code:s}=e,i=xe(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!==Rr)throw new Error(`Version 0 CID must use dag-pb (code: ${Rr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Ya(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Rr,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=oe(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 Ue(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,d]=Pr(t.subarray(e));return e+=d,f},o=n(),s=Rr;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]=Xf(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 ns(s).set(n,t),s}};function Xf(r,t){switch(r[0]){case"Q":{let e=t??et;return[et.prefix,e.decode(`${et.prefix}${r}`)]}case et.prefix:{let e=t??et;return[et.prefix,e.decode(r)]}case se.prefix:{let e=t??se;return[se.prefix,e.decode(r)]}case Lr.prefix:{let e=t??Lr;return[Lr.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Zf(r,t,e){let{prefix:n}=e;if(n!==et.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 Yf(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 Rr=112,Jf=18;function Ya(r,t,e){let n=nr(r),o=n+nr(t),s=new Uint8Array(o+e.byteLength);return rr(r,s,0),rr(t,s,n),s.set(e,o),s}var Qf=Symbol.for("@ipld/js-cid/CID");var os={};It(os,{identity:()=>Wt});var Ja=0,th="identity",Qa=oe;function eh(r){return Ct(Ja,Qa(r))}var Wt={code:Ja,name:th,encode:Qa,digest:eh};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 mt(r=0){return new Uint8Array(r)}function gt(r=0){return new Uint8Array(r)}function yt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=gt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var ec=Symbol.for("@achingbrain/uint8arraylist");function tc(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 In(r){return!!r?.[ec]}var V=class r{bufs;length;[ec]=!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(In(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(In(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=tc(this.bufs,t);return e.buf[e.index]}set(t,e){let n=tc(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(In(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(!In(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 d=l;d>=0;d--){let g=this.get(f+d);if(n[d]!==g){u=Math.max(1,d-a[g]);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=gt(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=mt(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=mt(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=mt(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=gt(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=mt(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=mt(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=mt(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=mt(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=mt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Et(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var ss={};It(ss,{base10:()=>nh});var nh=we({prefix:"9",name:"base10",alphabet:"0123456789"});var is={};It(is,{base16:()=>oh,base16upper:()=>sh});var oh=ht({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),sh=ht({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var as={};It(as,{base2:()=>ih});var ih=ht({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var cs={};It(cs,{base256emoji:()=>fh});var rc=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}"),ah=rc.reduce((r,t,e)=>(r[e]=t,r),[]),ch=rc.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function lh(r){return r.reduce((t,e)=>(t+=ah[e],t),"")}function uh(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=ch[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var fh=er({prefix:"\u{1F680}",name:"base256emoji",encode:lh,decode:uh});var ls={};It(ls,{base64:()=>hh,base64pad:()=>dh,base64url:()=>Dr,base64urlpad:()=>ph});var hh=ht({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),dh=ht({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Dr=ht({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ph=ht({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var us={};It(us,{base8:()=>mh});var mh=ht({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var fs={};It(fs,{identity:()=>gh});var gh=er({prefix:"\0",name:"identity",encode:r=>qa(r),decode:r=>Ha(r)});var Q0=new TextEncoder,tg=new TextDecoder;var ps={};It(ps,{sha256:()=>ie,sha512:()=>xh});function ds({name:r,code:t,encode:e}){return new hs(r,t,e)}var hs=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?Ct(this.code,e):e.then(n=>Ct(this.code,n))}else throw Error("Unknown type, must be binary type")}};function oc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var ie=ds({name:"sha2-256",code:18,encode:oc("SHA-256")}),xh=ds({name:"sha2-512",code:19,encode:oc("SHA-512")});var Oe={...fs,...as,...us,...ss,...is,...Qo,...ts,...Jo,...ls,...cs},hg={...ps,...os};function ic(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var sc=ic("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ms=ic("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=gt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),bh={utf8:sc,"utf-8":sc,hex:Oe.base16,latin1:ms,ascii:ms,binary:ms,...Oe},Cn=bh;function X(r,t="utf8"){let e=Cn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function H(r,t="utf8"){let e=Cn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Eh=parseInt("11111",2),gs=parseInt("10000000",2),Sh=parseInt("01111111",2),ac={0:Nr,1:Nr,2:Ah,3:Ch,4:Th,5:Ih,6:vh,16:Nr,22:Nr,48:Nr};function ae(r,t={offset:0}){let e=r[t.offset]&Eh;if(t.offset++,ac[e]!=null)return ac[e](r,t);throw new Error("No decoder for tag "+e)}function kr(r,t){let e=0;if((r[t.offset]&gs)===gs){let n=r[t.offset]&Sh,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function Nr(r,t){kr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=ae(r,t);if(n===null)break;e.push(n)}return e}function Ah(r,t){let e=kr(r,t),n=t.offset,o=t.offset+e,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return t.offset+=e,Uint8Array.from(s)}function vh(r,t){let e=kr(r,t),n=t.offset+e,o=r[t.offset];t.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;t.offset<n;){let l=r[t.offset];if(t.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function Ih(r,t){return t.offset++,null}function Ch(r,t){let e=kr(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Th(r,t){let e=kr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function _h(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new V;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function ys(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=_h(r.byteLength);return new V(Uint8Array.from([t.byteLength|gs]),t)}function Nt(r){let t=new V,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new V(Uint8Array.from([2]),ys(t),t)}function Tn(r){let t=Uint8Array.from([0]),e=new V(t,r);return new V(Uint8Array.from([3]),ys(e),e)}function be(r,t=48){let e=new V;for(let n of r)e.append(n);return new V(Uint8Array.from([t]),ys(e),e)}async function cc(r,t,e){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},n,t,e.subarray())}var Lh=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Bh=Uint8Array.from([6,5,43,129,4,0,34]),Ph=Uint8Array.from([6,5,43,129,4,0,35]),Rh={ext:!0,kty:"EC",crv:"P-256"},Dh={ext:!0,kty:"EC",crv:"P-384"},Nh={ext:!0,kty:"EC",crv:"P-521"},ws=32,xs=48,bs=66;function Es(r){let t=ae(r);return lc(t)}function lc(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===ws*2+1)return n=H(t.subarray(e,e+ws),"base64url"),o=H(t.subarray(e+ws),"base64url"),new or({...Rh,key_ops:["verify"],x:n,y:o});if(t.byteLength===xs*2+1)return n=H(t.subarray(e,e+xs),"base64url"),o=H(t.subarray(e+xs),"base64url"),new or({...Dh,key_ops:["verify"],x:n,y:o});if(t.byteLength===bs*2+1)return n=H(t.subarray(e,e+bs),"base64url"),o=H(t.subarray(e+bs),"base64url"),new or({...Nh,key_ops:["verify"],x:n,y:o});throw new Q(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function uc(r){return be([Nt(Uint8Array.from([1])),be([kh(r.crv)],160),be([Tn(new V(Uint8Array.from([4]),X(r.x??"","base64url"),X(r.y??"","base64url")))],161)]).subarray()}function kh(r){if(r==="P-256")return Lh;if(r==="P-384")return Bh;if(r==="P-521")return Ph;throw new Q(`Invalid curve ${r}`)}var or=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=uc(this.jwk)),this._raw}toMultihash(){return Wt.digest(Ee(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return et.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}async verify(t,e){return cc(this.jwk,e,t)}};function _n(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Uh(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function sr(r,...t){if(!Uh(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function Ur(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");_n(r.outputLen),_n(r.blockLen)}function ir(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 fc(r,t){sr(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}var Ke=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Ln(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Gt(r,t){return r<<32-t|r>>>t}function hc(r){if(typeof r!="string")throw new Error("utf8ToBytes expected string, got "+typeof r);return new Uint8Array(new TextEncoder().encode(r))}function Se(r){return typeof r=="string"&&(r=hc(r)),sr(r),r}function Ss(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];sr(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 ar=class{clone(){return this._cloneInto()}};function Bn(r){let t=n=>r().update(Se(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Or(r=32){if(Ke&&typeof Ke.getRandomValues=="function")return Ke.getRandomValues(new Uint8Array(r));if(Ke&&typeof Ke.randomBytes=="function")return Ke.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function Oh(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)}function dc(r,t,e){return r&t^~r&e}function pc(r,t,e){return r&t^r&e^t&e}var cr=class extends ar{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=Ln(this.buffer)}update(t){ir(this);let{view:e,buffer:n,blockLen:o}=this;t=Se(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=Ln(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){ir(this),fc(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;Oh(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Ln(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 Pn=BigInt(4294967295),As=BigInt(32);function mc(r,t=!1){return t?{h:Number(r&Pn),l:Number(r>>As&Pn)}:{h:Number(r>>As&Pn)|0,l:Number(r&Pn)|0}}function Kh(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}=mc(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var Mh=(r,t)=>BigInt(r>>>0)<<As|BigInt(t>>>0),Fh=(r,t,e)=>r>>>e,Hh=(r,t,e)=>r<<32-e|t>>>e,qh=(r,t,e)=>r>>>e|t<<32-e,Vh=(r,t,e)=>r<<32-e|t>>>e,Wh=(r,t,e)=>r<<64-e|t>>>e-32,Gh=(r,t,e)=>r>>>e-32|t<<64-e,zh=(r,t)=>t,$h=(r,t)=>r,jh=(r,t,e)=>r<<e|t>>>32-e,Xh=(r,t,e)=>t<<e|r>>>32-e,Zh=(r,t,e)=>t<<e-32|r>>>64-e,Yh=(r,t,e)=>r<<e-32|t>>>64-e;function Jh(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var Qh=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),td=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,ed=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),rd=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,nd=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),od=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var sd={fromBig:mc,split:Kh,toBig:Mh,shrSH:Fh,shrSL:Hh,rotrSH:qh,rotrSL:Vh,rotrBH:Wh,rotrBL:Gh,rotr32H:zh,rotr32L:$h,rotlSH:jh,rotlSL:Xh,rotlBH:Zh,rotlBL:Yh,add:Jh,add3L:Qh,add3H:td,add4L:ed,add4H:rd,add5H:od,add5L:nd},W=sd;var[id,ad]=W.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))),Ae=new Uint32Array(80),ve=new Uint32Array(80),vs=class extends cr{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:d,Gh:g,Gl:x,Hh:m,Hl:h}=this;return[t,e,n,o,s,i,a,c,l,u,f,d,g,x,m,h]}set(t,e,n,o,s,i,a,c,l,u,f,d,g,x,m,h){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=d|0,this.Gh=g|0,this.Gl=x|0,this.Hh=m|0,this.Hl=h|0}process(t,e){for(let p=0;p<16;p++,e+=4)Ae[p]=t.getUint32(e),ve[p]=t.getUint32(e+=4);for(let p=16;p<80;p++){let I=Ae[p-15]|0,P=ve[p-15]|0,B=W.rotrSH(I,P,1)^W.rotrSH(I,P,8)^W.shrSH(I,P,7),v=W.rotrSL(I,P,1)^W.rotrSL(I,P,8)^W.shrSL(I,P,7),L=Ae[p-2]|0,T=ve[p-2]|0,K=W.rotrSH(L,T,19)^W.rotrBH(L,T,61)^W.shrSH(L,T,6),N=W.rotrSL(L,T,19)^W.rotrBL(L,T,61)^W.shrSL(L,T,6),O=W.add4L(v,N,ve[p-7],ve[p-16]),F=W.add4H(O,B,K,Ae[p-7],Ae[p-16]);Ae[p]=F|0,ve[p]=O|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:g,Fl:x,Gh:m,Gl:h,Hh:w,Hl:b}=this;for(let p=0;p<80;p++){let I=W.rotrSH(f,d,14)^W.rotrSH(f,d,18)^W.rotrBH(f,d,41),P=W.rotrSL(f,d,14)^W.rotrSL(f,d,18)^W.rotrBL(f,d,41),B=f&g^~f&m,v=d&x^~d&h,L=W.add5L(b,P,v,ad[p],ve[p]),T=W.add5H(L,w,I,B,id[p],Ae[p]),K=L|0,N=W.rotrSH(n,o,28)^W.rotrBH(n,o,34)^W.rotrBH(n,o,39),O=W.rotrSL(n,o,28)^W.rotrBL(n,o,34)^W.rotrBL(n,o,39),F=n&s^n&a^s&a,C=o&i^o&c^i&c;w=m|0,b=h|0,m=g|0,h=x|0,g=f|0,x=d|0,{h:f,l:d}=W.add(l|0,u|0,T|0,K|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let _=W.add3L(K,O,C);n=W.add3H(_,T,N,F),o=_|0}({h:n,l:o}=W.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=W.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=W.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=W.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=W.add(this.Eh|0,this.El|0,f|0,d|0),{h:g,l:x}=W.add(this.Fh|0,this.Fl|0,g|0,x|0),{h:m,l:h}=W.add(this.Gh|0,this.Gl|0,m|0,h|0),{h:w,l:b}=W.add(this.Hh|0,this.Hl|0,w|0,b|0),this.set(n,o,s,i,a,c,l,u,f,d,g,x,m,h,w,b)}roundClean(){Ae.fill(0),ve.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 gc=Bn(()=>new vs);var Nn={};It(Nn,{aInRange:()=>St,abool:()=>zt,abytes:()=>lr,bitGet:()=>dd,bitLen:()=>_s,bitMask:()=>Mr,bitSet:()=>pd,bytesToHex:()=>le,bytesToNumberBE:()=>ue,bytesToNumberLE:()=>$t,concatBytes:()=>he,createHmacDrbg:()=>Ls,ensureBytes:()=>st,equalBytes:()=>fd,hexToBytes:()=>Fe,hexToNumber:()=>Ts,inRange:()=>Kr,isBytes:()=>Ie,memoized:()=>He,notImplemented:()=>gd,numberToBytesBE:()=>Ce,numberToBytesLE:()=>fe,numberToHexUnpadded:()=>Me,numberToVarBytesBE:()=>ud,utf8ToBytes:()=>hd,validateObject:()=>Ht});var Rn=BigInt(0),Dn=BigInt(1),cd=BigInt(2);function Ie(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function lr(r){if(!Ie(r))throw new Error("Uint8Array expected")}function zt(r,t){if(typeof t!="boolean")throw new Error(r+" boolean expected, got "+t)}var ld=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function le(r){lr(r);let t="";for(let e=0;e<r.length;e++)t+=ld[r[e]];return t}function Me(r){let t=r.toString(16);return t.length&1?"0"+t:t}function Ts(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Rn:BigInt("0x"+r)}var ce={_0:48,_9:57,A:65,F:70,a:97,f:102};function yc(r){if(r>=ce._0&&r<=ce._9)return r-ce._0;if(r>=ce.A&&r<=ce.F)return r-(ce.A-10);if(r>=ce.a&&r<=ce.f)return r-(ce.a-10)}function Fe(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("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=yc(r.charCodeAt(s)),a=yc(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 ue(r){return Ts(le(r))}function $t(r){return lr(r),Ts(le(Uint8Array.from(r).reverse()))}function Ce(r,t){return Fe(r.toString(16).padStart(t*2,"0"))}function fe(r,t){return Ce(r,t).reverse()}function ud(r){return Fe(Me(r))}function st(r,t,e){let n;if(typeof t=="string")try{n=Fe(t)}catch(s){throw new Error(r+" must be hex string or Uint8Array, cause: "+s)}else if(Ie(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+" of length "+e+" expected, got "+o);return n}function he(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];lr(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 fd(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 hd(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}var Is=r=>typeof r=="bigint"&&Rn<=r;function Kr(r,t,e){return Is(r)&&Is(t)&&Is(e)&&t<=r&&r<e}function St(r,t,e,n){if(!Kr(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function _s(r){let t;for(t=0;r>Rn;r>>=Dn,t+=1);return t}function dd(r,t){return r>>BigInt(t)&Dn}function pd(r,t,e){return r|(e?Dn:Rn)<<BigInt(t)}var Mr=r=>(cd<<BigInt(r-1))-Dn,Cs=r=>new Uint8Array(r),wc=r=>Uint8Array.from(r);function Ls(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=Cs(r),o=Cs(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=Cs())=>{o=a(wc([0]),f),n=a(),f.length!==0&&(o=a(wc([1]),f),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<t;){n=a();let g=n.slice();d.push(g),f+=n.length}return he(...d)};return(f,d)=>{i(),c(f);let g;for(;!(g=d(l()));)c();return i(),g}}var md={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"||Ie(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 Ht(r,t,e={}){let n=(o,s,i)=>{let a=md[s];if(typeof a!="function")throw new Error("invalid validator function");let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(e))n(o,s,!0);return r}var gd=()=>{throw new Error("not implemented")};function He(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var wt=BigInt(0),ft=BigInt(1),qe=BigInt(2),yd=BigInt(3),Bs=BigInt(4),xc=BigInt(5),bc=BigInt(8),wd=BigInt(9),xd=BigInt(16);function Y(r,t){let e=r%t;return e>=wt?e:t+e}function Ps(r,t,e){if(t<wt)throw new Error("invalid exponent, negatives unsupported");if(e<=wt)throw new Error("invalid modulus");if(e===ft)return wt;let n=ft;for(;t>wt;)t&ft&&(n=n*r%e),r=r*r%e,t>>=ft;return n}function ct(r,t,e){let n=r;for(;t-- >wt;)n*=n,n%=e;return n}function kn(r,t){if(r===wt)throw new Error("invert: expected non-zero number");if(t<=wt)throw new Error("invert: expected positive modulus, got "+t);let e=Y(r,t),n=t,o=wt,s=ft,i=ft,a=wt;for(;e!==wt;){let l=n/e,u=n%e,f=o-i*l,d=s-a*l;n=e,e=u,o=i,s=a,i=f,a=d}if(n!==ft)throw new Error("invert: does not exist");return Y(o,t)}function bd(r){let t=(r-ft)/qe,e,n,o;for(e=r-ft,n=0;e%qe===wt;e/=qe,n++);for(o=qe;o<r&&Ps(o,t,r)!==r-ft;o++)if(o>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){let i=(r+ft)/Bs;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+ft)/qe;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),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let g=1;for(let m=a.sqr(d);g<l&&!a.eql(m,a.ONE);g++)m=a.sqr(m);let x=a.pow(u,ft<<BigInt(l-g-1));u=a.sqr(x),f=a.mul(f,x),d=a.mul(d,u),l=g}return f}}function Ed(r){if(r%Bs===yd){let t=(r+ft)/Bs;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%bc===xc){let t=(r-xc)/bc;return function(n,o){let s=n.mul(o,qe),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,qe),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%xd,bd(r)}var Ec=(r,t)=>(Y(r,t)&ft)===ft,Sd=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Rs(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Sd.reduce((n,o)=>(n[o]="function",n),t);return Ht(r,e)}function Ad(r,t,e){if(e<wt)throw new Error("invalid exponent, negatives unsupported");if(e===wt)return r.ONE;if(e===ft)return t;let n=r.ONE,o=t;for(;e>wt;)e&ft&&(n=r.mul(n,o)),o=r.sqr(o),e>>=ft;return n}function vd(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 Ds(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Te(r,t,e=!1,n={}){if(r<=wt)throw new Error("invalid field: expected ORDER > 0, got "+r);let{nBitLength:o,nByteLength:s}=Ds(r,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i,a=Object.freeze({ORDER:r,isLE:e,BITS:o,BYTES:s,MASK:Mr(o),ZERO:wt,ONE:ft,create:c=>Y(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return wt<=c&&c<r},is0:c=>c===wt,isOdd:c=>(c&ft)===ft,neg:c=>Y(-c,r),eql:(c,l)=>c===l,sqr:c=>Y(c*c,r),add:(c,l)=>Y(c+l,r),sub:(c,l)=>Y(c-l,r),mul:(c,l)=>Y(c*l,r),pow:(c,l)=>Ad(a,c,l),div:(c,l)=>Y(c*kn(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>kn(c,r),sqrt:n.sqrt||(c=>(i||(i=Ed(r)),i(a,c))),invertBatch:c=>vd(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?fe(c,s):Ce(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return e?$t(c):ue(c)}});return Object.freeze(a)}function Sc(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 Ns(r){let t=Sc(r);return t+Math.ceil(t/2)}function Ac(r,t,e=!1){let n=r.length,o=Sc(t),s=Ns(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?$t(r):ue(r),a=Y(i,t-ft)+ft;return e?fe(a,o):Ce(a,o)}var vc=BigInt(0),Un=BigInt(1);function ks(r,t){let e=t.negate();return r?e:t}function Ic(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function Us(r,t){Ic(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1);return{windows:e,windowSize:n}}function Id(r,t){if(!Array.isArray(r))throw new Error("array expected");r.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}function Cd(r,t){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}var Os=new WeakMap,Cc=new WeakMap;function Ks(r){return Cc.get(r)||1}function On(r,t){return{constTimeNegate:ks,hasPrecomputes(e){return Ks(e)!==1},unsafeLadder(e,n,o=r.ZERO){let s=e;for(;n>vc;)n&Un&&(o=o.add(s)),s=s.double(),n>>=Un;return o},precomputeWindow(e,n){let{windows:o,windowSize:s}=Us(n,t),i=[],a=e,c=a;for(let l=0;l<o;l++){c=a,i.push(c);for(let u=1;u<s;u++)c=c.add(a),i.push(c);a=c.double()}return i},wNAF(e,n,o){let{windows:s,windowSize:i}=Us(e,t),a=r.ZERO,c=r.BASE,l=BigInt(2**e-1),u=2**e,f=BigInt(e);for(let d=0;d<s;d++){let g=d*i,x=Number(o&l);o>>=f,x>i&&(x-=u,o+=Un);let m=g,h=g+Math.abs(x)-1,w=d%2!==0,b=x<0;x===0?c=c.add(ks(w,n[m])):a=a.add(ks(b,n[h]))}return{p:a,f:c}},wNAFUnsafe(e,n,o,s=r.ZERO){let{windows:i,windowSize:a}=Us(e,t),c=BigInt(2**e-1),l=2**e,u=BigInt(e);for(let f=0;f<i;f++){let d=f*a;if(o===vc)break;let g=Number(o&c);if(o>>=u,g>a&&(g-=l,o+=Un),g===0)continue;let x=n[d+Math.abs(g)-1];g<0&&(x=x.negate()),s=s.add(x)}return s},getPrecomputes(e,n,o){let s=Os.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&Os.set(n,o(s))),s},wNAFCached(e,n,o){let s=Ks(e);return this.wNAF(s,this.getPrecomputes(s,e,o),n)},wNAFCachedUnsafe(e,n,o,s){let i=Ks(e);return i===1?this.unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,o),n,s)},setWindowSize(e,n){Ic(n,t),Cc.set(e,n),Os.delete(e)}}}function Kn(r,t,e,n){if(Id(e,r),Cd(n,t),e.length!==n.length)throw new Error("arrays of points and scalars must have equal length");let o=r.ZERO,s=_s(BigInt(e.length)),i=s>12?s-3:s>4?s-2:s?2:1,a=(1<<i)-1,c=new Array(a+1).fill(o),l=Math.floor((t.BITS-1)/i)*i,u=o;for(let f=l;f>=0;f-=i){c.fill(o);for(let g=0;g<n.length;g++){let x=n[g],m=Number(x>>BigInt(f)&BigInt(a));c[m]=c[m].add(e[g])}let d=o;for(let g=c.length-1,x=o;g>0;g--)x=x.add(c[g]),d=d.add(x);if(u=u.add(d),f!==0)for(let g=0;g<i;g++)u=u.double()}return u}function Fr(r){return Rs(r.Fp),Ht(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ds(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var jt=BigInt(0),kt=BigInt(1),Mn=BigInt(2),Td=BigInt(8),_d={zip215:!0};function Ld(r){let t=Fr(r);return Ht(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function Tc(r){let t=Ld(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=Mn<<BigInt(a*8)-kt,u=e.create,f=Te(t.n,t.nBitLength),d=t.uvRatio||((E,y)=>{try{return{isValid:!0,value:e.sqrt(E*e.inv(y))}}catch{return{isValid:!1,value:jt}}}),g=t.adjustScalarBytes||(E=>E),x=t.domain||((E,y,A)=>{if(zt("phflag",A),y.length||A)throw new Error("Contexts/pre-hash are not supported");return E});function m(E,y){St("coordinate "+E,y,jt,l)}function h(E){if(!(E instanceof p))throw new Error("ExtendedPoint expected")}let w=He((E,y)=>{let{ex:A,ey:S,ez:R}=E,D=E.is0();y==null&&(y=D?Td:e.inv(R));let U=u(A*y),q=u(S*y),M=u(R*y);if(D)return{x:jt,y:kt};if(M!==kt)throw new Error("invZ was invalid");return{x:U,y:q}}),b=He(E=>{let{a:y,d:A}=t;if(E.is0())throw new Error("bad point: ZERO");let{ex:S,ey:R,ez:D,et:U}=E,q=u(S*S),M=u(R*R),G=u(D*D),j=u(G*G),it=u(q*y),at=u(G*u(it+M)),ut=u(j+u(A*u(q*M)));if(at!==ut)throw new Error("bad point: equation left != right (1)");let vt=u(S*R),Dt=u(D*U);if(vt!==Dt)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(y,A,S,R){this.ex=y,this.ey=A,this.ez=S,this.et=R,m("x",y),m("y",A),m("z",S),m("t",R),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(y){if(y instanceof p)throw new Error("extended point not allowed");let{x:A,y:S}=y||{};return m("x",A),m("y",S),new p(A,S,kt,u(A*S))}static normalizeZ(y){let A=e.invertBatch(y.map(S=>S.ez));return y.map((S,R)=>S.toAffine(A[R])).map(p.fromAffine)}static msm(y,A){return Kn(p,f,y,A)}_setWindowSize(y){B.setWindowSize(this,y)}assertValidity(){b(this)}equals(y){h(y);let{ex:A,ey:S,ez:R}=this,{ex:D,ey:U,ez:q}=y,M=u(A*q),G=u(D*R),j=u(S*q),it=u(U*R);return M===G&&j===it}is0(){return this.equals(p.ZERO)}negate(){return new p(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:y}=t,{ex:A,ey:S,ez:R}=this,D=u(A*A),U=u(S*S),q=u(Mn*u(R*R)),M=u(y*D),G=A+S,j=u(u(G*G)-D-U),it=M+U,at=it-q,ut=M-U,vt=u(j*at),Dt=u(it*ut),Rt=u(j*ut),Qt=u(at*it);return new p(vt,Dt,Qt,Rt)}add(y){h(y);let{a:A,d:S}=t,{ex:R,ey:D,ez:U,et:q}=this,{ex:M,ey:G,ez:j,et:it}=y;if(A===BigInt(-1)){let Pa=u((D-R)*(G+M)),Ra=u((D+R)*(G-M)),Go=u(Ra-Pa);if(Go===jt)return this.double();let Da=u(U*Mn*it),Na=u(q*Mn*j),ka=Na+Da,Ua=Ra+Pa,Oa=Na-Da,sf=u(ka*Go),af=u(Ua*Oa),cf=u(ka*Oa),lf=u(Go*Ua);return new p(sf,af,lf,cf)}let at=u(R*M),ut=u(D*G),vt=u(q*S*it),Dt=u(U*j),Rt=u((R+D)*(M+G)-at-ut),Qt=Dt-vt,ne=Dt+vt,_r=u(ut-A*at),ef=u(Rt*Qt),rf=u(ne*_r),nf=u(Rt*_r),of=u(Qt*ne);return new p(ef,rf,of,nf)}subtract(y){return this.add(y.negate())}wNAF(y){return B.wNAFCached(this,y,p.normalizeZ)}multiply(y){let A=y;St("scalar",A,kt,n);let{p:S,f:R}=this.wNAF(A);return p.normalizeZ([S,R])[0]}multiplyUnsafe(y,A=p.ZERO){let S=y;return St("scalar",S,jt,n),S===jt?P:this.is0()||S===kt?this:B.wNAFCachedUnsafe(this,S,p.normalizeZ,A)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return B.unsafeLadder(this,n).is0()}toAffine(y){return w(this,y)}clearCofactor(){let{h:y}=t;return y===kt?this:this.multiplyUnsafe(y)}static fromHex(y,A=!1){let{d:S,a:R}=t,D=e.BYTES;y=st("pointHex",y,D),zt("zip215",A);let U=y.slice(),q=y[D-1];U[D-1]=q&-129;let M=$t(U),G=A?l:e.ORDER;St("pointHex.y",M,jt,G);let j=u(M*M),it=u(j-kt),at=u(S*j-R),{isValid:ut,value:vt}=d(it,at);if(!ut)throw new Error("Point.fromHex: invalid y coordinate");let Dt=(vt&kt)===kt,Rt=(q&128)!==0;if(!A&&vt===jt&&Rt)throw new Error("Point.fromHex: x=0 and x_0=1");return Rt!==Dt&&(vt=u(-vt)),p.fromAffine({x:vt,y:M})}static fromPrivateKey(y){return T(y).point}toRawBytes(){let{x:y,y:A}=this.toAffine(),S=fe(A,e.BYTES);return S[S.length-1]|=y&kt?128:0,S}toHex(){return le(this.toRawBytes())}}p.BASE=new p(t.Gx,t.Gy,kt,u(t.Gx*t.Gy)),p.ZERO=new p(jt,kt,kt,jt);let{BASE:I,ZERO:P}=p,B=On(p,a*8);function v(E){return Y(E,n)}function L(E){return v($t(E))}function T(E){let y=e.BYTES;E=st("private key",E,y);let A=st("hashed private key",s(E),2*y),S=g(A.slice(0,y)),R=A.slice(y,2*y),D=L(S),U=I.multiply(D),q=U.toRawBytes();return{head:S,prefix:R,scalar:D,point:U,pointBytes:q}}function K(E){return T(E).pointBytes}function N(E=new Uint8Array,...y){let A=he(...y);return L(s(x(A,st("context",E),!!o)))}function O(E,y,A={}){E=st("message",E),o&&(E=o(E));let{prefix:S,scalar:R,pointBytes:D}=T(y),U=N(A.context,S,E),q=I.multiply(U).toRawBytes(),M=N(A.context,q,D,E),G=v(U+M*R);St("signature.s",G,jt,n);let j=he(q,fe(G,e.BYTES));return st("result",j,e.BYTES*2)}let F=_d;function C(E,y,A,S=F){let{context:R,zip215:D}=S,U=e.BYTES;E=st("signature",E,2*U),y=st("message",y),A=st("publicKey",A,U),D!==void 0&&zt("zip215",D),o&&(y=o(y));let q=$t(E.slice(U,2*U)),M,G,j;try{M=p.fromHex(A,D),G=p.fromHex(E.slice(0,U),D),j=I.multiplyUnsafe(q)}catch{return!1}if(!D&&M.isSmallOrder())return!1;let it=N(R,G.toRawBytes(),M.toRawBytes(),y);return G.add(M.multiplyUnsafe(it)).subtract(j).clearCofactor().equals(p.ZERO)}return I._setWindowSize(8),{CURVE:t,getPublicKey:K,sign:O,verify:C,ExtendedPoint:p,utils:{getExtendedPublicKey:T,randomPrivateKey:()=>i(e.BYTES),precompute(E=8,y=p.BASE){return y._setWindowSize(E),y.multiply(BigInt(3)),y}}}}var ur=BigInt(0),Ms=BigInt(1);function Bd(r){return Ht(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function _c(r){let t=Bd(r),{P:e}=t,n=b=>Y(b,e),o=t.montgomeryBits,s=Math.ceil(o/8),i=t.nByteLength,a=t.adjustScalarBytes||(b=>b),c=t.powPminus2||(b=>Ps(b,e-BigInt(2),e));function l(b,p,I){let P=n(b*(p-I));return p=n(p-P),I=n(I+P),[p,I]}let u=(t.a-BigInt(2))/BigInt(4);function f(b,p){St("u",b,ur,e),St("scalar",p,ur,e);let I=p,P=b,B=Ms,v=ur,L=b,T=Ms,K=ur,N;for(let F=BigInt(o-1);F>=ur;F--){let C=I>>F&Ms;K^=C,N=l(K,B,L),B=N[0],L=N[1],N=l(K,v,T),v=N[0],T=N[1],K=C;let _=B+v,E=n(_*_),y=B-v,A=n(y*y),S=E-A,R=L+T,D=L-T,U=n(D*_),q=n(R*y),M=U+q,G=U-q;L=n(M*M),T=n(P*n(G*G)),B=n(E*A),v=n(S*(E+n(u*S)))}N=l(K,B,L),B=N[0],L=N[1],N=l(K,v,T),v=N[0],T=N[1];let O=c(v);return n(B*O)}function d(b){return fe(n(b),s)}function g(b){let p=st("u coordinate",b,s);return i===32&&(p[31]&=127),$t(p)}function x(b){let p=st("scalar",b),I=p.length;if(I!==s&&I!==i){let P=""+s+" or "+i;throw new Error("invalid scalar, expected "+P+" bytes, got "+I)}return $t(a(p))}function m(b,p){let I=g(p),P=x(b),B=f(I,P);if(B===ur)throw new Error("invalid private or public key received");return d(B)}let h=d(t.Gu);function w(b){return m(b,h)}return{scalarMult:m,scalarMultBase:w,getSharedSecret:(b,p)=>m(b,p),getPublicKey:b=>w(b),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:h}}var Hr=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Lc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),by=BigInt(0),Pd=BigInt(1),Bc=BigInt(2),Rd=BigInt(3),Dd=BigInt(5),Nd=BigInt(8);function Pc(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=Hr,a=r*r%s*r%s,c=ct(a,Bc,s)*a%s,l=ct(c,Pd,s)*r%s,u=ct(l,Dd,s)*l%s,f=ct(u,t,s)*u%s,d=ct(f,e,s)*f%s,g=ct(d,n,s)*d%s,x=ct(g,o,s)*g%s,m=ct(x,o,s)*g%s,h=ct(m,t,s)*u%s;return{pow_p_5_8:ct(h,Bc,s)*r%s,b2:a}}function Rc(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function kd(r,t){let e=Hr,n=Y(t*t*t,e),o=Y(n*n*t,e),s=Pc(r*o).pow_p_5_8,i=Y(r*n*s,e),a=Y(t*i*i,e),c=i,l=Y(i*Lc,e),u=a===r,f=a===Y(-r,e),d=a===Y(-r*Lc,e);return u&&(i=c),(f||d)&&(i=l),Ec(i,e)&&(i=Y(-i,e)),{isValid:u||f,value:i}}var Ud=Te(Hr,void 0,!0),Od={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ud,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Nd,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:gc,randomBytes:Or,adjustScalarBytes:Rc,uvRatio:kd},Dc=Tc(Od);var qr=_c({P:Hr,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let t=Hr,{pow_p_5_8:e,b2:n}=Pc(r);return Y(ct(e,Rd,t)*n,t)},adjustScalarBytes:Rc,randomBytes:Or});var Fn=32;function Nc(r,t,e){return Dc.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}var Hn=class{type="Ed25519";raw;constructor(t){this.raw=Fs(t,Fn)}toMultihash(){return Wt.digest(Ee(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return et.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e){return Nc(this.raw,e,t)}};function Hs(r){return r=Fs(r,Fn),new Hn(r)}function Fs(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new Q(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Md=Math.pow(2,7),Fd=Math.pow(2,14),Hd=Math.pow(2,21),qs=Math.pow(2,28),Vs=Math.pow(2,35),Ws=Math.pow(2,42),Gs=Math.pow(2,49),tt=128,Tt=127;function nt(r){if(r<Md)return 1;if(r<Fd)return 2;if(r<Hd)return 3;if(r<qs)return 4;if(r<Vs)return 5;if(r<Ws)return 6;if(r<Gs)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function zs(r,t,e=0){switch(nt(r)){case 8:t[e++]=r&255|tt,r/=128;case 7:t[e++]=r&255|tt,r/=128;case 6:t[e++]=r&255|tt,r/=128;case 5:t[e++]=r&255|tt,r/=128;case 4:t[e++]=r&255|tt,r>>>=7;case 3:t[e++]=r&255|tt,r>>>=7;case 2:t[e++]=r&255|tt,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function qd(r,t,e=0){switch(nt(r)){case 8:t.set(e++,r&255|tt),r/=128;case 7:t.set(e++,r&255|tt),r/=128;case 6:t.set(e++,r&255|tt),r/=128;case 5:t.set(e++,r&255|tt),r/=128;case 4:t.set(e++,r&255|tt),r>>>=7;case 3:t.set(e++,r&255|tt),r>>>=7;case 2:t.set(e++,r&255|tt),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function $s(r,t){let e=r[t],n=0;if(n+=e&Tt,e<tt||(e=r[t+1],n+=(e&Tt)<<7,e<tt)||(e=r[t+2],n+=(e&Tt)<<14,e<tt)||(e=r[t+3],n+=(e&Tt)<<21,e<tt)||(e=r[t+4],n+=(e&Tt)*qs,e<tt)||(e=r[t+5],n+=(e&Tt)*Vs,e<tt)||(e=r[t+6],n+=(e&Tt)*Ws,e<tt)||(e=r[t+7],n+=(e&Tt)*Gs,e<tt))return n;throw new RangeError("Could not decode varint")}function Vd(r,t){let e=r.get(t),n=0;if(n+=e&Tt,e<tt||(e=r.get(t+1),n+=(e&Tt)<<7,e<tt)||(e=r.get(t+2),n+=(e&Tt)<<14,e<tt)||(e=r.get(t+3),n+=(e&Tt)<<21,e<tt)||(e=r.get(t+4),n+=(e&Tt)*qs,e<tt)||(e=r.get(t+5),n+=(e&Tt)*Vs,e<tt)||(e=r.get(t+6),n+=(e&Tt)*Ws,e<tt)||(e=r.get(t+7),n+=(e&Tt)*Gs,e<tt))return n;throw new RangeError("Could not decode varint")}function qt(r,t,e=0){return t==null&&(t=gt(nt(r))),t instanceof Uint8Array?zs(r,t,e):qd(r,t,e)}function Ot(r,t=0){return r instanceof Uint8Array?$s(r,t):Vd(r,t)}var js=new Float32Array([-0]),_e=new Uint8Array(js.buffer);function Uc(r,t,e){js[0]=r,t[e]=_e[0],t[e+1]=_e[1],t[e+2]=_e[2],t[e+3]=_e[3]}function Oc(r,t){return _e[0]=r[t],_e[1]=r[t+1],_e[2]=r[t+2],_e[3]=r[t+3],js[0]}var Xs=new Float64Array([-0]),_t=new Uint8Array(Xs.buffer);function Kc(r,t,e){Xs[0]=r,t[e]=_t[0],t[e+1]=_t[1],t[e+2]=_t[2],t[e+3]=_t[3],t[e+4]=_t[4],t[e+5]=_t[5],t[e+6]=_t[6],t[e+7]=_t[7]}function Mc(r,t){return _t[0]=r[t],_t[1]=r[t+1],_t[2]=r[t+2],_t[3]=r[t+3],_t[4]=r[t+4],_t[5]=r[t+5],_t[6]=r[t+6],_t[7]=r[t+7],Xs[0]}var Wd=BigInt(Number.MAX_SAFE_INTEGER),Gd=BigInt(Number.MIN_SAFE_INTEGER),Kt=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 Ve;if(t<Wd&&t>Gd)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>Fc&&(o=0n,++n>Fc&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return Ve;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):Ve}},Ve=new Kt(0,0);Ve.toBigInt=function(){return 0n};Ve.zzEncode=Ve.zzDecode=function(){return this};Ve.length=function(){return 1};var Fc=4294967296n;function Hc(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 qc(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 Zs(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 Xt(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function qn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Ys=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,Xt(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 Xt(this,4);return qn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Xt(this,4);return qn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Xt(this,4);let t=Oc(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Xt(this,4);let t=Mc(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 Xt(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return qc(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Xt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Xt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Kt(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 Xt(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 Xt(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 Xt(this,8);let t=qn(this.buf,this.pos+=4),e=qn(this.buf,this.pos+=4);return new Kt(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=$s(this.buf,this.pos);return this.pos+=nt(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 Js(r){return new Ys(r instanceof Uint8Array?r:r.subarray())}function Zt(r,t,e){let n=Js(r);return t.decode(n,void 0,e)}function Qs(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return gt(i);o+i>t&&(n=gt(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var We=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function ti(){}var ri=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},zd=Qs();function $d(r){return globalThis.Buffer!=null?gt(r):zd(r)}var Wr=class{len;head;tail;states;constructor(){this.len=0,this.head=new We(ti,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new We(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ni((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(Vn,10,Kt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Kt.fromBigInt(t);return this._push(Vn,e.length(),e)}uint64Number(t){return this._push(zs,nt(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=Kt.fromBigInt(t).zzEncode();return this._push(Vn,e.length(),e)}sint64Number(t){let e=Kt.fromNumber(t).zzEncode();return this._push(Vn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ei,1,t?1:0)}fixed32(t){return this._push(Vr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Kt.fromBigInt(t);return this._push(Vr,4,e.lo)._push(Vr,4,e.hi)}fixed64Number(t){let e=Kt.fromNumber(t);return this._push(Vr,4,e.lo)._push(Vr,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(Uc,4,t)}double(t){return this._push(Kc,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ei,1,0):this.uint32(e)._push(Xd,e,t)}string(t){let e=Hc(t);return e!==0?this.uint32(e)._push(Zs,e,t):this._push(ei,1,0)}fork(){return this.states=new ri(this),this.head=this.tail=new We(ti,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new We(ti,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=$d(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ei(r,t,e){t[e]=r&255}function jd(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ni=class extends We{next;constructor(t,e){super(jd,t,e),this.next=void 0}};function Vn(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 Vr(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 Xd(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Wr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Zd,t,r),this},Wr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Yd,t,r),this});function Zd(r,t,e){t.set(r,e)}function Yd(r,t,e){r.length<40?Zs(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(X(r),e)}function oi(){return new Wr}function Yt(r,t){let e=oi();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var hr;(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"})(hr||(hr={}));function Wn(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Ge(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 Wn("enum",hr.VARINT,e,n)}function Jt(r,t){return Wn("message",hr.LENGTH_DELIMITED,r,t)}var Gr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var pt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(pt||(pt={}));var si;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(si||(si={}));(function(r){r.codec=()=>Ge(si)})(pt||(pt={}));var te;(function(r){let t;r.codec=()=>(t==null&&(t=Jt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),pt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=pt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Yt(e,r.codec()),r.decode=(e,n)=>Zt(e,r.codec(),n)})(te||(te={}));var ii;(function(r){let t;r.codec=()=>(t==null&&(t=Jt((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),pt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=pt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Yt(e,r.codec()),r.decode=(e,n)=>Zt(e,r.codec(),n)})(ii||(ii={}));var zr=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},Gn=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var Gc={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new Gn("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Le=Gc;var jr={};It(jr,{MAX_RSA_KEY_SIZE:()=>ci,generateRSAKeyPair:()=>Xc,jwkToJWKKeyPair:()=>Zc,jwkToPkcs1:()=>rp,jwkToPkix:()=>hi,jwkToRSAPrivateKey:()=>gi,pkcs1MessageToJwk:()=>ui,pkcs1MessageToRSAPrivateKey:()=>di,pkcs1ToJwk:()=>ep,pkcs1ToRSAPrivateKey:()=>jc,pkixMessageToJwk:()=>fi,pkixMessageToRSAPublicKey:()=>mi,pkixToJwk:()=>np,pkixToRSAPublicKey:()=>pi});var Jd=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]),Be=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Pe=new Uint32Array(64),ai=class extends cr{constructor(){super(64,32,8,!1),this.A=Be[0]|0,this.B=Be[1]|0,this.C=Be[2]|0,this.D=Be[3]|0,this.E=Be[4]|0,this.F=Be[5]|0,this.G=Be[6]|0,this.H=Be[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)Pe[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=Pe[f-15],g=Pe[f-2],x=Gt(d,7)^Gt(d,18)^d>>>3,m=Gt(g,17)^Gt(g,19)^g>>>10;Pe[f]=m+Pe[f-7]+x+Pe[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=Gt(a,6)^Gt(a,11)^Gt(a,25),g=u+d+dc(a,c,l)+Jd[f]+Pe[f]|0,m=(Gt(n,2)^Gt(n,13)^Gt(n,22))+pc(n,o,s)|0;u=l,l=c,c=a,a=i+g|0,i=s,s=o,o=n,n=g+m|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(){Pe.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ee=Bn(()=>new ai);var dr=class{type="RSA";jwk;_raw;_multihash;constructor(t,e){this.jwk=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=jr.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return dt.createV1(114,this._multihash)}toString(){return et.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e){return $c(this.jwk,e,t)}},$r=class{type="RSA";jwk;_raw;publicKey;constructor(t,e){this.jwk=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=jr.jwkToPkcs1(this.jwk)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}sign(t){return zc(this.jwk,t)}};var ci=8192,li=18,Qd=1062,tp=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function ep(r){let t=ae(r);return ui(t)}function ui(r){return{n:H(r[1],"base64url"),e:H(r[2],"base64url"),d:H(r[3],"base64url"),p:H(r[4],"base64url"),q:H(r[5],"base64url"),dp:H(r[6],"base64url"),dq:H(r[7],"base64url"),qi:H(r[8],"base64url"),kty:"RSA"}}function rp(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 Q("JWK was missing components");return be([Nt(Uint8Array.from([0])),Nt(X(r.n,"base64url")),Nt(X(r.e,"base64url")),Nt(X(r.d,"base64url")),Nt(X(r.p,"base64url")),Nt(X(r.q,"base64url")),Nt(X(r.dp,"base64url")),Nt(X(r.dq,"base64url")),Nt(X(r.qi,"base64url"))]).subarray()}function np(r){let t=ae(r,{offset:0});return fi(t)}function fi(r){let t=ae(r[1],{offset:0});return{kty:"RSA",n:H(t[0],"base64url"),e:H(t[1],"base64url")}}function hi(r){if(r.n==null||r.e==null)throw new Q("JWK was missing components");return be([tp,Tn(be([Nt(X(r.n,"base64url")),Nt(X(r.e,"base64url"))]))]).subarray()}function jc(r){let t=ae(r);return di(t)}function di(r){let t=ui(r);return gi(t)}function pi(r,t){if(r.byteLength>=Qd)throw new Je("Key size is too large");let e=ae(r,{offset:0});return mi(e,r,t)}function mi(r,t,e){let n=fi(r);if(e==null){let o=ee(te.encode({Type:pt.RSA,Data:t}));e=Ct(li,o)}return new dr(n,e)}function gi(r){if(Jc(r)>ci)throw new Q("Key size is too large");let t=Zc(r),e=ee(te.encode({Type:pt.RSA,Data:hi(t.publicKey)})),n=Ct(li,e);return new $r(t.privateKey,new dr(t.publicKey,n))}async function Xc(r){if(r>ci)throw new Q("Key size is too large");let t=await Yc(r),e=ee(te.encode({Type:pt.RSA,Data:hi(t.publicKey)})),n=Ct(li,e);return new $r(t.privateKey,new dr(t.publicKey,n))}function Zc(r){if(r==null)throw new Q("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Yc(r){let t=await Le.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 op(t);return{privateKey:e[0],publicKey:e[1]}}async function zc(r,t){let e=await Le.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Le.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function $c(r,t,e){let n=await Le.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Le.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function op(r){if(r.privateKey==null||r.publicKey==null)throw new Q("Private and public key are required");return Promise.all([Le.get().subtle.exportKey("jwk",r.privateKey),Le.get().subtle.exportKey("jwk",r.publicKey)])}function Jc(r){if(r.kty!=="RSA")throw new Q("invalid key type");if(r.n==null)throw new Q("invalid key modulus");return X(r.n,"base64url").length*8}var zn=class extends ar{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Ur(t);let n=Se(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 ir(this),this.iHash.update(t),this}digestInto(t){ir(this),sr(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()}},pr=(r,t,e)=>new zn(r,t).update(e).digest();pr.create=(r,t)=>new zn(r,t);function Qc(r){r.lowS!==void 0&&zt("lowS",r.lowS),r.prehash!==void 0&&zt("prehash",r.prehash)}function sp(r){let t=Fr(r);Ht(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("invalid 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("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:ip,hexToBytes:ap}=Nn,yi=class extends Error{constructor(t=""){super(t)}},de={Err:yi,_tlv:{encode:(r,t)=>{let{Err:e}=de;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=Me(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Me(o.length/2|128):"";return Me(r)+s+o+t},decode(r,t){let{Err:e}=de,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=de;if(r<pe)throw new t("integer: negative integers are not allowed");let e=Me(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=de;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return ip(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=de,o=typeof r=="string"?ap(r):r;lr(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=de,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},pe=BigInt(0),xt=BigInt(1),Xw=BigInt(2),tl=BigInt(3),Zw=BigInt(4);function cp(r){let t=sp(r),{Fp:e}=t,n=Te(t.n,t.nBitLength),o=t.toBytes||((m,h,w)=>{let b=h.toAffine();return he(Uint8Array.from([4]),e.toBytes(b.x),e.toBytes(b.y))}),s=t.fromBytes||(m=>{let h=m.subarray(1),w=e.fromBytes(h.subarray(0,e.BYTES)),b=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:w,y:b}});function i(m){let{a:h,b:w}=t,b=e.sqr(m),p=e.mul(b,m);return e.add(e.add(p,e.mul(m,h)),w)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return Kr(m,xt,t.n)}function c(m){let{allowedPrivateKeyLengths:h,nByteLength:w,wrapPrivateKey:b,n:p}=t;if(h&&typeof m!="bigint"){if(Ie(m)&&(m=le(m)),typeof m!="string"||!h.includes(m.length))throw new Error("invalid private key");m=m.padStart(w*2,"0")}let I;try{I=typeof m=="bigint"?m:ue(st("private key",m,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof m)}return b&&(I=Y(I,p)),St("private key",I,xt,p),I}function l(m){if(!(m instanceof d))throw new Error("ProjectivePoint expected")}let u=He((m,h)=>{let{px:w,py:b,pz:p}=m;if(e.eql(p,e.ONE))return{x:w,y:b};let I=m.is0();h==null&&(h=I?e.ONE:e.inv(p));let P=e.mul(w,h),B=e.mul(b,h),v=e.mul(p,h);if(I)return{x:e.ZERO,y:e.ZERO};if(!e.eql(v,e.ONE))throw new Error("invZ was invalid");return{x:P,y:B}}),f=He(m=>{if(m.is0()){if(t.allowInfinityPoint&&!e.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:h,y:w}=m.toAffine();if(!e.isValid(h)||!e.isValid(w))throw new Error("bad point: x or y not FE");let b=e.sqr(w),p=i(h);if(!e.eql(b,p))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,w,b){if(this.px=h,this.py=w,this.pz=b,h==null||!e.isValid(h))throw new Error("x required");if(w==null||!e.isValid(w))throw new Error("y required");if(b==null||!e.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:w,y:b}=h||{};if(!h||!e.isValid(w)||!e.isValid(b))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let p=I=>e.eql(I,e.ZERO);return p(w)&&p(b)?d.ZERO:new d(w,b,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let w=e.invertBatch(h.map(b=>b.pz));return h.map((b,p)=>b.toAffine(w[p])).map(d.fromAffine)}static fromHex(h){let w=d.fromAffine(s(st("pointHex",h)));return w.assertValidity(),w}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,w){return Kn(d,n,h,w)}_setWindowSize(h){x.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:w,py:b,pz:p}=this,{px:I,py:P,pz:B}=h,v=e.eql(e.mul(w,B),e.mul(I,p)),L=e.eql(e.mul(b,B),e.mul(P,p));return v&&L}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:w}=t,b=e.mul(w,tl),{px:p,py:I,pz:P}=this,B=e.ZERO,v=e.ZERO,L=e.ZERO,T=e.mul(p,p),K=e.mul(I,I),N=e.mul(P,P),O=e.mul(p,I);return O=e.add(O,O),L=e.mul(p,P),L=e.add(L,L),B=e.mul(h,L),v=e.mul(b,N),v=e.add(B,v),B=e.sub(K,v),v=e.add(K,v),v=e.mul(B,v),B=e.mul(O,B),L=e.mul(b,L),N=e.mul(h,N),O=e.sub(T,N),O=e.mul(h,O),O=e.add(O,L),L=e.add(T,T),T=e.add(L,T),T=e.add(T,N),T=e.mul(T,O),v=e.add(v,T),N=e.mul(I,P),N=e.add(N,N),T=e.mul(N,O),B=e.sub(B,T),L=e.mul(N,K),L=e.add(L,L),L=e.add(L,L),new d(B,v,L)}add(h){l(h);let{px:w,py:b,pz:p}=this,{px:I,py:P,pz:B}=h,v=e.ZERO,L=e.ZERO,T=e.ZERO,K=t.a,N=e.mul(t.b,tl),O=e.mul(w,I),F=e.mul(b,P),C=e.mul(p,B),_=e.add(w,b),E=e.add(I,P);_=e.mul(_,E),E=e.add(O,F),_=e.sub(_,E),E=e.add(w,p);let y=e.add(I,B);return E=e.mul(E,y),y=e.add(O,C),E=e.sub(E,y),y=e.add(b,p),v=e.add(P,B),y=e.mul(y,v),v=e.add(F,C),y=e.sub(y,v),T=e.mul(K,E),v=e.mul(N,C),T=e.add(v,T),v=e.sub(F,T),T=e.add(F,T),L=e.mul(v,T),F=e.add(O,O),F=e.add(F,O),C=e.mul(K,C),E=e.mul(N,E),F=e.add(F,C),C=e.sub(O,C),C=e.mul(K,C),E=e.add(E,C),O=e.mul(F,E),L=e.add(L,O),O=e.mul(y,E),v=e.mul(_,v),v=e.sub(v,O),O=e.mul(_,F),T=e.mul(y,T),T=e.add(T,O),new d(v,L,T)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return x.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){let{endo:w,n:b}=t;St("scalar",h,pe,b);let p=d.ZERO;if(h===pe)return p;if(this.is0()||h===xt)return this;if(!w||x.hasPrecomputes(this))return x.wNAFCachedUnsafe(this,h,d.normalizeZ);let{k1neg:I,k1:P,k2neg:B,k2:v}=w.splitScalar(h),L=p,T=p,K=this;for(;P>pe||v>pe;)P&xt&&(L=L.add(K)),v&xt&&(T=T.add(K)),K=K.double(),P>>=xt,v>>=xt;return I&&(L=L.negate()),B&&(T=T.negate()),T=new d(e.mul(T.px,w.beta),T.py,T.pz),L.add(T)}multiply(h){let{endo:w,n:b}=t;St("scalar",h,xt,b);let p,I;if(w){let{k1neg:P,k1:B,k2neg:v,k2:L}=w.splitScalar(h),{p:T,f:K}=this.wNAF(B),{p:N,f:O}=this.wNAF(L);T=x.constTimeNegate(P,T),N=x.constTimeNegate(v,N),N=new d(e.mul(N.px,w.beta),N.py,N.pz),p=T.add(N),I=K.add(O)}else{let{p:P,f:B}=this.wNAF(h);p=P,I=B}return d.normalizeZ([p,I])[0]}multiplyAndAddUnsafe(h,w,b){let p=d.BASE,I=(B,v)=>v===pe||v===xt||!B.equals(p)?B.multiplyUnsafe(v):B.multiply(v),P=I(this,w).add(I(h,b));return P.is0()?void 0:P}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:w}=t;if(h===xt)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:w}=t;return h===xt?this:w?w(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return zt("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return zt("isCompressed",h),le(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let g=t.nBitLength,x=On(d,t.endo?Math.ceil(g/2):g);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function lp(r){let t=Fr(r);return Ht(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function el(r){let t=lp(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(C){return Y(C,n)}function a(C){return kn(C,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=cp({...t,toBytes(C,_,E){let y=_.toAffine(),A=e.toBytes(y.x),S=he;return zt("isCompressed",E),E?S(Uint8Array.from([_.hasEvenY()?2:3]),A):S(Uint8Array.from([4]),A,e.toBytes(y.y))},fromBytes(C){let _=C.length,E=C[0],y=C.subarray(1);if(_===o&&(E===2||E===3)){let A=ue(y);if(!Kr(A,xt,e.ORDER))throw new Error("Point is not on curve");let S=u(A),R;try{R=e.sqrt(S)}catch(q){let M=q instanceof Error?": "+q.message:"";throw new Error("Point is not on curve"+M)}let D=(R&xt)===xt;return(E&1)===1!==D&&(R=e.neg(R)),{x:A,y:R}}else if(_===s&&E===4){let A=e.fromBytes(y.subarray(0,e.BYTES)),S=e.fromBytes(y.subarray(e.BYTES,2*e.BYTES));return{x:A,y:S}}else{let A=o,S=s;throw new Error("invalid Point, expected length of "+A+", or uncompressed "+S+", got "+_)}}}),d=C=>le(Ce(C,t.nByteLength));function g(C){let _=n>>xt;return C>_}function x(C){return g(C)?i(-C):C}let m=(C,_,E)=>ue(C.slice(_,E));class h{constructor(_,E,y){this.r=_,this.s=E,this.recovery=y,this.assertValidity()}static fromCompact(_){let E=t.nByteLength;return _=st("compactSignature",_,E*2),new h(m(_,0,E),m(_,E,2*E))}static fromDER(_){let{r:E,s:y}=de.toSig(st("DER",_));return new h(E,y)}assertValidity(){St("r",this.r,xt,n),St("s",this.s,xt,n)}addRecoveryBit(_){return new h(this.r,this.s,_)}recoverPublicKey(_){let{r:E,s:y,recovery:A}=this,S=B(st("msgHash",_));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");let R=A===2||A===3?E+t.n:E;if(R>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let D=(A&1)===0?"02":"03",U=c.fromHex(D+d(R)),q=a(R),M=i(-S*q),G=i(y*q),j=c.BASE.multiplyAndAddUnsafe(U,M,G);if(!j)throw new Error("point at infinify");return j.assertValidity(),j}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return Fe(this.toDERHex())}toDERHex(){return de.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Fe(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let w={isValidPrivateKey(C){try{return l(C),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let C=Ns(t.n);return Ac(t.randomBytes(C),t.n)},precompute(C=8,_=c.BASE){return _._setWindowSize(C),_.multiply(BigInt(3)),_}};function b(C,_=!0){return c.fromPrivateKey(C).toRawBytes(_)}function p(C){let _=Ie(C),E=typeof C=="string",y=(_||E)&&C.length;return _?y===o||y===s:E?y===2*o||y===2*s:C instanceof c}function I(C,_,E=!0){if(p(C))throw new Error("first arg must be private key");if(!p(_))throw new Error("second arg must be public key");return c.fromHex(_).multiply(l(C)).toRawBytes(E)}let P=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let _=ue(C),E=C.length*8-t.nBitLength;return E>0?_>>BigInt(E):_},B=t.bits2int_modN||function(C){return i(P(C))},v=Mr(t.nBitLength);function L(C){return St("num < 2^"+t.nBitLength,C,pe,v),Ce(C,t.nByteLength)}function T(C,_,E=K){if(["recovered","canonical"].some(at=>at in E))throw new Error("sign() legacy options not supported");let{hash:y,randomBytes:A}=t,{lowS:S,prehash:R,extraEntropy:D}=E;S==null&&(S=!0),C=st("msgHash",C),Qc(E),R&&(C=st("prehashed msgHash",y(C)));let U=B(C),q=l(_),M=[L(q),L(U)];if(D!=null&&D!==!1){let at=D===!0?A(e.BYTES):D;M.push(st("extraEntropy",at))}let G=he(...M),j=U;function it(at){let ut=P(at);if(!f(ut))return;let vt=a(ut),Dt=c.BASE.multiply(ut).toAffine(),Rt=i(Dt.x);if(Rt===pe)return;let Qt=i(vt*i(j+Rt*q));if(Qt===pe)return;let ne=(Dt.x===Rt?0:2)|Number(Dt.y&xt),_r=Qt;return S&&g(Qt)&&(_r=x(Qt),ne^=1),new h(Rt,_r,ne)}return{seed:G,k2sig:it}}let K={lowS:t.lowS,prehash:!1},N={lowS:t.lowS,prehash:!1};function O(C,_,E=K){let{seed:y,k2sig:A}=T(C,_,E),S=t;return Ls(S.hash.outputLen,S.nByteLength,S.hmac)(y,A)}c.BASE._setWindowSize(8);function F(C,_,E,y=N){let A=C;_=st("msgHash",_),E=st("publicKey",E);let{lowS:S,prehash:R,format:D}=y;if(Qc(y),"strict"in y)throw new Error("options.strict was renamed to lowS");if(D!==void 0&&D!=="compact"&&D!=="der")throw new Error("format must be compact or der");let U=typeof A=="string"||Ie(A),q=!U&&!D&&typeof A=="object"&&A!==null&&typeof A.r=="bigint"&&typeof A.s=="bigint";if(!U&&!q)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let M,G;try{if(q&&(M=new h(A.r,A.s)),U){try{D!=="compact"&&(M=h.fromDER(A))}catch(ne){if(!(ne instanceof de.Err))throw ne}!M&&D!=="der"&&(M=h.fromCompact(A))}G=c.fromHex(E)}catch{return!1}if(!M||S&&M.hasHighS())return!1;R&&(_=t.hash(_));let{r:j,s:it}=M,at=B(_),ut=a(it),vt=i(at*ut),Dt=i(j*ut),Rt=c.BASE.multiplyAndAddUnsafe(G,vt,Dt)?.toAffine();return Rt?i(Rt.x)===j:!1}return{CURVE:t,getPublicKey:b,getSharedSecret:I,sign:O,verify:F,ProjectivePoint:c,Signature:h,utils:w}}function up(r){return{hash:r,hmac:(t,...e)=>pr(r,t,Ss(...e)),randomBytes:Or}}function rl(r,t){let e=n=>el({...r,...up(n)});return{...e(t),create:e}}var sl=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),nl=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),fp=BigInt(1),wi=BigInt(2),ol=(r,t)=>(r+t/wi)/t;function hp(r){let t=sl,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=ct(u,e,t)*u%t,d=ct(f,e,t)*u%t,g=ct(d,wi,t)*l%t,x=ct(g,o,t)*g%t,m=ct(x,s,t)*x%t,h=ct(m,a,t)*m%t,w=ct(h,c,t)*h%t,b=ct(w,a,t)*m%t,p=ct(b,e,t)*u%t,I=ct(p,i,t)*x%t,P=ct(I,n,t)*l%t,B=ct(P,wi,t);if(!xi.eql(xi.sqr(B),r))throw new Error("Cannot find square root");return B}var xi=Te(sl,void 0,void 0,{sqrt:hp}),ze=rl({a:BigInt(0),b:BigInt(7),Fp:xi,n:nl,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=nl,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-fp*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=ol(s*r,t),c=ol(-n*r,t),l=Y(r-a*e-c*o,t),u=Y(-a*n-c*s,t),f=l>i,d=u>i;if(f&&(l=t-l),d&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},ee),sx=BigInt(0);var ix=ze.ProjectivePoint;function il(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function al(r,t,e){let n=ie.digest(e instanceof Uint8Array?e:e.subarray());if(il(n))return n.then(({digest:o})=>ze.verify(t,o,r)).catch(o=>{throw new zr(String(o))});try{return ze.verify(t,n.digest,r)}catch(o){throw new zr(String(o))}}var $n=class{type="secp256k1";raw;_key;constructor(t){this._key=ll(t),this.raw=cl(this._key)}toMultihash(){return Wt.digest(Ee(this))}toCID(){return dt.createV1(114,this.toMultihash())}toString(){return et.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e){return al(this._key,e,t)}};function bi(r){return new $n(r)}function cl(r){return ze.ProjectivePoint.fromHex(r).toRawBytes(!0)}function ll(r){try{return ze.ProjectivePoint.fromHex(r),r}catch(t){throw new Je(String(t))}}function Xr(r,t){let{Type:e,Data:n}=te.decode(r),o=n??new Uint8Array;switch(e){case pt.RSA:return pi(o,t);case pt.Ed25519:return Hs(o);case pt.secp256k1:return bi(o);case pt.ECDSA:return Es(o);default:throw new ke}}function ul(r){let{Type:t,Data:e}=te.decode(r.digest),n=e??new Uint8Array;switch(t){case pt.Ed25519:return Hs(n);case pt.secp256k1:return bi(n);case pt.ECDSA:return Es(n);default:throw new ke}}function Ee(r){return te.encode({Type:pt[r.type],Data:r.raw})}var fl=Symbol.for("nodejs.util.inspect.custom"),dp=114,Zr=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[$o]=!0;toString(){return this.string==null&&(this.string=et.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return dt.createV1(dp,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Et(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Et(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[fl](){return`PeerId(${this.toString()})`}},Yr=class extends Zr{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Jr=class extends Zr{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},Qr=class extends Zr{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},pp=2336,tn=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Wt.digest(X(this.url))}[fl](){return`PeerId(${this.url})`}[$o]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return dt.createV1(pp,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=H(t)),t.toString()===this.toString())}};var mp=114,hl=2336;function mr(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=xe(et.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return gp(dt.parse(r));if(t==null)throw new Q('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=xe(t.decode(r))}return dl(e)}function Ei(r){if(r.type==="Ed25519")return new Jr({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Qr({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Yr({multihash:r.toCID().multihash,publicKey:r});throw new ke}function dl(r){if(wp(r))return new Yr({multihash:r});if(yp(r))try{let t=ul(r);if(t.type==="Ed25519")return new Jr({multihash:r,publicKey:t});if(t.type==="secp256k1")return new Qr({multihash:r,publicKey:t})}catch{let e=H(r.digest);return new tn(new URL(e))}throw new En("Supplied PeerID Multihash is invalid")}function gp(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==mp&&r.code!==hl)throw new bn("Supplied PeerID CID is invalid");if(r.code===hl){let t=H(r.multihash.digest);return new tn(new URL(t))}return dl(r.multihash)}function yp(r){return r.code===Wt.code}function wp(r){return r.code===ie.code}var jn=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 d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});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,xp=15,gr=new jn;function Si(r){if(!(r.length>xp))return gr.new(r).parseWith(()=>gr.readIPv4Addr())}function Ai(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>pl))return gr.new(r).parseWith(()=>gr.readIPv6Addr())}function Xn(r,t=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>pl)return;let e=gr.new(r).parseWith(()=>gr.readIPAddr());if(e)return t&&e.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,e[0],e[1],e[2],e[3]]):e}var bb=parseInt("0xFFFF",16),Eb=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function Zn(r){return!!Si(r)}function Yn(r){return!!Ai(r)}function Jn(r){return!!Xn(r)}var yl=Zn,vp=Yn,vi=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(vp(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=yl(e[n]),i;s&&(i=vi(e[n]),e[n]=H(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,H(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 yr={},Ii={},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=Tp(...r);Ii[t.code]=t,yr[t.name]=t});function Tp(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function ot(r){if(typeof r=="number"){if(Ii[r]!=null)return Ii[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(yr[r]!=null)return yr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var o1=ot("ip4"),s1=ot("ip6"),i1=ot("ipcidr");function Li(r,t){switch(ot(r).code){case 4:case 41:return Lp(t);case 42:return _i(t);case 43:return H(t,"base10");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 _i(t);case 421:return Dp(t);case 444:return bl(t);case 445:return bl(t);case 466:return Rp(t);case 481:return globalThis.encodeURIComponent(_i(t));default:return H(t,"base16")}}function Bi(r,t){switch(ot(r).code){case 4:return xl(t);case 41:return xl(t);case 42:return Ti(t);case 43:return X(t,"base10");case 6:case 273:case 33:case 132:return Pi(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ti(t);case 421:return Bp(t);case 444:return Np(t);case 445:return kp(t);case 466:return Pp(t);case 481:return Ti(globalThis.decodeURIComponent(t));default:return X(t,"base16")}}var Ci=Object.values(Oe).map(r=>r.decoder),_p=function(){let r=Ci[0].or(Ci[1]);return Ci.slice(2).forEach(t=>r=r.or(t)),r}();function xl(r){if(!Jn(r))throw new Error("invalid ip address");return vi(r)}function Lp(r){let t=wl(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!Jn(t))throw new Error("invalid ip address");return t}function Pi(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 Ti(r){let t=X(r),e=Uint8Array.from(qt(t.length));return yt([e,t],e.length+t.length)}function _i(r){let t=Ot(r);if(r=r.slice(nt(t)),r.length!==t)throw new Error("inconsistent lengths");return H(r)}function Bp(r){let t;r[0]==="Q"||r[0]==="1"?t=xe(et.decode(`z${r}`)).bytes:t=dt.parse(r).multihash.bytes;let e=Uint8Array.from(qt(t.length));return yt([e,t],e.length+t.length)}function Pp(r){let t=_p.decode(r),e=Uint8Array.from(qt(t.length));return yt([e,t],e.length+t.length)}function Rp(r){let t=Ot(r),e=r.slice(nt(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+H(e,"base64url")}function Dp(r){let t=Ot(r),e=r.slice(nt(t));if(e.length!==t)throw new Error("inconsistent lengths");return H(e,"base58btc")}function Np(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=Pi(n);return yt([e,o],e.length+o.length)}function kp(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=Pi(n);return yt([e,o],e.length+o.length)}function bl(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=H(t,"base32"),o=El(e);return`${n}:${o}`}function Sl(r){r=Ri(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=ot(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw new Qn("invalid address: "+r);if(a.path===!0){n=Ri(o.slice(s).join("/")),t.push([a.code,Bi(a.code,n)]),e.push([a.code,n]);break}let c=Bi(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Li(a.code,c)])}return{string:Al(e),bytes:to(t),tuples:t,stringTuples:e,path:n}}function Di(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=Ot(r,o),i=nt(s),a=ot(s),c=Up(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 new Qn("Invalid address Uint8Array: "+H(r,"base16"));t.push([s,l]);let u=Li(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=ot(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Ri(t.join("/"))}function to(r){return yt(r.map(t=>{let e=ot(t[0]),n=Uint8Array.from(qt(e.code));return t.length>1&&t[1]!=null&&(n=yt([n,t[1]])),n}))}function Up(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=Ot(t instanceof Uint8Array?t:Uint8Array.from(t));return e+nt(e)}}function Ri(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}var Qn=class extends Error{static name="ParseError";name="ParseError";constructor(t){super(`Error parsing address: ${t}`)}};var Op=Symbol.for("nodejs.util.inspect.custom"),ki=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Kp=[ot("dns").code,ot("dns4").code,ot("dns6").code,ot("dnsaddr").code],Ni=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},eo=class r{bytes;#t;#e;#r;#n;[ki]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Di(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Sl(t)}else if(Il(t))e=Di(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=ot("tcp"),a=ot("udp"),c=ot("ip4"),l=ot("ip6"),u=ot("dns6"),f=ot("ip6zone");for(let[g,x]of this.stringTuples())g===f.code&&(s=`%${x??""}`),Kp.includes(g)&&(e=i.name==="tcp"?"tcp":"udp",o=443,n=`${x??""}${s}`,t=g===u.code?6:4),(g===i.code||g===a.code)&&(e=ot(g).name==="tcp"?"tcp":"udp",o=parseInt(x??"")),(g===c.code||g===l.code)&&(e=ot(g).name==="tcp"?"tcp":"udp",n=`${x??""}${s}`,t=g===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({},ot(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>ot(t).name)}tuples(){return this.#e.map(([t,e])=>e==null?[t]:[t,e])}stringTuples(){return this.#r.map(([t,e])=>e==null?[t]:[t,e])}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(to(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===yr.p2p.code&&t.push([n,o]),n===yr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?H(et.decode(`z${n}`),"base58btc"):H(dt.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=vl.get(e.name);if(n==null)throw new Ni(`no available resolver for ${e.name}`);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)}[Op](){return`Multiaddr(${this.#t})`}};var vl=new Map;function Il(r){return!!r?.[ki]}function re(r){return new eo(r)}var Mp=r=>r.toString().split("/").slice(1),wr=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),z=r=>({match:t=>wr(e=>e===r).match(t),pattern:r}),$e=()=>({match:r=>wr(t=>typeof t=="string").match(r),pattern:"{string}"}),en=()=>({match:r=>wr(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{et.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),rn=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{Dr.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),J=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Lt=(...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(", ")})`}),$=(...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 lt(...r){function t(o){let s=Mp(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{matchers:r,matches:e,exactMatch:n}}var no=$(z("dns4"),$e()),oo=$(z("dns6"),$e()),so=$(z("dnsaddr"),$e()),Oi=$(z("dns"),$e()),O1=lt(no,J(rt())),K1=lt(oo,J(rt())),M1=lt(so,J(rt())),F1=lt(Lt(Oi,so,no,oo),J(rt())),Cl=$(z("ip4"),wr(Zn)),Tl=$(z("ip6"),wr(Yn)),Ki=Lt(Cl,Tl),me=Lt(Ki,Oi,no,oo,so),H1=lt(Lt(Ki,$(Lt(Oi,so,no,oo),J(rt())))),q1=lt(Cl),V1=lt(Tl),W1=lt(Ki),Mi=$(me,z("tcp"),en()),nn=$(me,z("udp"),en()),G1=lt($(Mi,J(rt()))),z1=lt(nn),Fi=$(nn,z("quic"),J(rt())),io=$(nn,z("quic-v1"),J(rt())),Fp=Lt(Fi,io),$1=lt(Fi),j1=lt(io),Ui=Lt(me,Mi,nn,Fi,io),_l=Lt($(Ui,z("ws"),J(rt()))),X1=lt(_l),Ll=Lt($(Ui,z("wss"),J(rt())),$(Ui,z("tls"),J($(z("sni"),$e())),z("ws"),J(rt()))),Z1=lt(Ll),Bl=$(nn,z("webrtc-direct"),J(rn()),J(rn()),J(rt())),Pl=lt(Bl),Rl=$(io,z("webtransport"),J(rn()),J(rn()),J(rt())),Y1=lt(Rl),ro=Lt(_l,Ll,$(Mi,J(rt())),$(Fp,J(rt())),$(me,J(rt())),Bl,Rl,rt()),Dl=lt(ro),Hp=$(ro,z("p2p-circuit"),rt()),J1=lt(Hp),qp=Lt($(ro,z("p2p-circuit"),z("webrtc"),J(rt())),$(ro,z("webrtc"),J(rt())),$(z("webrtc"),J(rt()))),Nl=lt(qp),Vp=Lt($(me,z("tcp"),en(),z("http"),J(rt())),$(me,z("http"),J(rt()))),Q1=lt(Vp),Wp=Lt($(me,z("tcp"),Lt($(z("443"),z("http")),$(en(),z("https"))),J(rt())),$(me,z("tls"),z("http"),J(rt())),$(me,z("https"),J(rt()))),t2=lt(Wp),Gp=Lt($(z("memory"),$e(),J(rt()))),e2=lt(Gp);var Bt;(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=()=>Ge(e)}(t=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=Jt((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.flag!=null&&(s.uint32(8),r.Flag.codec().encode(o.flag,s)),o.message!=null&&(s.uint32(18),s.bytes(o.message)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.flag=r.Flag.codec().decode(o);break}case 2:{a.message=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Yt(o,r.codec()),r.decode=(o,s)=>Zt(o,r.codec(),s)})(Bt||(Bt={}));var kl=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],Hi=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),Ul="libp2p+webrtc+v1/";var Ol=466,Kl=2*1024*1024,Ml=30*1e3,xr=16*1024;function zp(r=xr){let t=nt(r-nt(r)),e=1+nt(Object.keys(Bt.Flag).length-1),n=1,o=r-t-e-n,s=nt(o);return t+e+n+s}var Fl=zp(),Hl=5e3,ql=5e3,Vl=3e4,qi="/webrtc",on="/webrtc-signaling/0.0.1";var Wl=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))},$p=function(){function r(t,e,n){this.name=t,this.version=e,this.os=n,this.type="browser"}return r}();var jp=function(){function r(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return r}();var Xp=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 Zp=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var Yp=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var Jp=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Qp=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Gl=3,tm=[["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",Jp]],zl=[["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 jl(r){return r?$l(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Yp:typeof navigator<"u"?$l(navigator.userAgent):nm()}function em(r){return r!==""&&tm.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 $l(r){var t=em(r);if(!t)return null;var e=t[0],n=t[1];if(e==="searchbot")return new Zp;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<Gl&&(o=Wl(Wl([],o,!0),om(Gl-o.length),!0)):o=[];var s=o.join("."),i=rm(r),a=Qp.exec(r);return a&&a[1]?new Xp(e,s,i,a[1]):new $p(e,s,i)}function rm(r){for(var t=0,e=zl.length;t<e;t++){var n=zl[t],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function nm(){var r=typeof process<"u"&&process.version;return r?new jp(process.version.slice(1)):null}function om(r){for(var t=[],e=0;e<r;e++)t.push("0");return t}function Z(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Vi=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Wi=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Xl=r=>globalThis.DOMException===void 0?new Wi(r):new DOMException(r),Zl=r=>{let t=r.reason===void 0?Xl("This operation was aborted."):r.reason;return t instanceof Error?t:Xl(t)};function sn(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,a,l=new Promise((u,f)=>{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:g}=t;g.aborted&&f(Zl(g)),a=()=>{f(Zl(g))},g.addEventListener("abort",a,{once:!0})}if(e===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new Vi;i=s.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(g){f(g)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?u():o instanceof Error?f(o):(d.message=o??`Promise timed out after ${e} milliseconds`,f(d))},e),(async()=>{try{u(await r)}catch(g){f(g)}})()}).finally(()=>{l.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)});return l.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},l}var Yl=jl(),an=Yl!=null&&Yl.name==="firefox",ao=async function*(){},co=async r=>{};function Jl(r,t,e=Vl,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=Z(),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 sn(o.promise,{milliseconds:e})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function Gi(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??kl.map(t=>({urls:[t]})),r}var Ql=(r=32)=>Ul+[...Array(r)].map(()=>Hi.at(Math.floor(Math.random()*Hi.length))).join("");var je=class{log;peerConnection;remoteAddr;timeline;metrics;source=ao();sink=co;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,o=n.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",n.connectionState,"initial state",o),(n.connectionState==="disconnected"||n.connectionState==="failed"||n.connectionState==="closed")&&(this.timeline.close=Date.now())}}async close(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 lo=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||(t-1&t)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},br=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new lo(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 lo(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 zi=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Er(r={}){return sm(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 sm(r,t){t=t??{};let e=t.onEnd,n=new br,o,s,i,a=Z(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,w)=>{s=b=>{s=null,n.push(b);try{h(r(n))}catch(p){w(p)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=Z()})}},l=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new br,s!=null?s({error:h}):(n.push({error:h}),o)),f=h=>{if(i)return o;if(t?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:h})},d=h=>i?o:(i=!0,h!=null?u(h):l({done:!0})),g=()=>(n=new br,d(),{done:!0}),x=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:g,throw:x,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let w=h?.signal;if(w?.throwIfAborted(),n.isEmpty())return;let b,p;w!=null&&(b=new Promise((I,P)=>{p=()=>{P(new zi)},w.addEventListener("abort",p)}));try{await Promise.race([a.promise,b])}finally{p!=null&&w!=null&&w?.removeEventListener("abort",p)}}},e==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(h){return m.throw(h),e!=null&&(e(h),e=void 0),{done:!0}},return(){return m.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(h){return m.end(h),e!=null&&(e(h),e=void 0),o},get readableLength(){return m.readableLength},onEmpty:h=>m.onEmpty(h)},o}var uo=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function bt(r,t,e){if(t==null)return r;if(t.aborted)return r.catch(()=>{}),Promise.reject(new uo(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new uo(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}function tu(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 eu(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function ru(r,t){let e=tu(r).return?.();eu(e)&&e.catch(n=>{t.error("could not cause iterator to return",n)})}var im=5e3;function $i(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var fo=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=Z(),this.closed=Z(),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??im,this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=Er({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 Ne(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";let e={signal:this.sinkController.signal};if(this.direction==="outbound"){let o=this.sendNewStream(e);$i(o)&&await o}let n=()=>{ru(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 V(o):o;let s=this.sendData(o,e);$i(s)&&(this.sendingData=Z(),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.status==="open"&&(this.log.trace("closing gracefully"),this.status="closing",await bt(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 bt(this.sink([]),t.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await bt(this.sendingData.promise,t.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await bt(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();$i(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 xn("stream reset");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 ji(r){let t=new globalThis.AbortController;function e(){t.abort();for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}for(let s of r){if(s?.aborted===!0){e();break}s?.addEventListener!=null&&s.addEventListener("abort",e)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",e)}let o=t.signal;return o.clear=n,o}var ho=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Sr=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},po=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},cn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function mo(r){return r[Symbol.asyncIterator]!=null}function nu(r,t){if(r.byteLength>t)throw new Sr("Message length too long")}var yo=r=>{let t=nt(r),e=gt(t);return qt(r,e),yo.bytes=t,e};yo.bytes=0;function ln(r,t){t=t??{};let e=t.lengthEncoder??yo,n=t?.maxDataLength??4194304;function*o(s){nu(s,n);let i=e(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return mo(r)?async function*(){for await(let s of r)yield*o(s)}():function*(){for(let s of r)yield*o(s)}()}ln.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??yo,n=t?.maxDataLength??4194304;return nu(r,n),new V(e(r.byteLength),r)};var Xe;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(Xe||(Xe={}));var Xi=r=>{let t=Ot(r);return Xi.bytes=nt(t),t};Xi.bytes=0;function Ze(r,t){let e=new V,n=Xe.LENGTH,o=-1,s=t?.lengthDecoder??Xi,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;e.byteLength>0;){if(n===Xe.LENGTH)try{if(o=s(e),o<0)throw new ho("Invalid message length");if(o>a)throw new Sr("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=Xe.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new po("Message length length too long");break}throw l}if(n===Xe.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=Xe.LENGTH}}}return mo(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new cn("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new cn("Unexpected end of input")}()}Ze.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 Ze(n,{...t??{},onLength:s=>{e=s}})};var Zi=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 un(r,t,e,n){let o=new Zi(n?.errorMessage,n?.errorCode);return e?.aborted===!0?Promise.reject(o):new Promise((s,i)=>{function a(){e?.removeEventListener("abort",u),r.removeEventListener(t,c),n?.errorEvent!=null&&r.removeEventListener(n.errorEvent,l)}let c=f=>{try{if(n?.filter?.(f)===!1)return}catch(d){a(),i(d);return}a(),s(f)},l=f=>{a(),i(f.detail)},u=()=>{a(),i(o)};e?.addEventListener("abort",u),r.addEventListener(t,c),n?.errorEvent!=null&&r.addEventListener(n.errorEvent,l)})}var Yi=class extends fo{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;closeController;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 sn(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(s){this.log.error("error receiving FIN_ACK",s)}}).then(()=>{this.incomingData.end(),this.channel.close(),e?.(o)}).catch(s=>{this.log.error("error ending stream",s)})},super(t),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=Er(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??Ml,this.maxBufferedAmount=t.maxBufferedAmount??Kl,this.maxMessageSize=(t.maxMessageSize??xr)-Fl,this.receiveFinAck=Z(),this.finAckTimeout=t.closeTimeout??Hl,this.openTimeout=t.openTimeout??ql,this.closeController=new AbortController,this.channel.readyState){case"open":this.timeline.open=new Date().getTime();break;case"closed":case"closing":(this.timeline.close===void 0||this.timeline.close===0)&&(this.timeline.close=Date.now());break;case"connecting":break;default:throw this.log.error("unknown datachannel state %s",this.channel.readyState),new Ne("Unknown datachannel state")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime()},this.channel.onclose=o=>{this.log.trace("received onclose event"),this.closeController.abort(),this.receiveFinAck.resolve(),this.close().catch(s=>{this.log.error("error closing stream after channel closed",s)})},this.channel.onerror=o=>{this.log.trace("received onerror event"),this.closeController.abort();let s=o.error;this.abort(s)},this.channel.onmessage=async o=>{let{data:s}=o;s===null||s.byteLength===0||this.incomingData.push(new Uint8Array(s,0,s.byteLength))};let n=this;Promise.resolve().then(async()=>{for await(let o of Ze(this.incomingData)){let s=n.processIncomingProtobuf(o);s!=null&&n.sourcePush(new V(s))}}).catch(o=>{this.log.error("error processing incoming data channel messages",o)})}sendNewStream(){}async _sendMessage(t,e=!0){if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new Ne(`Invalid datachannel state - ${this.channel.readyState}`);if(this.channel.readyState!=="open"){let n=AbortSignal.timeout(this.openTimeout),o=ji([this.closeController.signal,n]);try{this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await un(this.channel,"open",o)}finally{o.clear()}this.log('channel state is now "%s", sending data',this.channel.readyState)}if(e&&this.channel.bufferedAmount>this.maxBufferedAmount){let n=AbortSignal.timeout(this.bufferedAmountLowEventTimeout),o=ji([this.closeController.signal,n]);try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await un(this.channel,"bufferedamountlow",o)}catch(s){throw n.aborted?new An(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`):s}finally{o.clear()}}try{this.channel.send(t.subarray())}catch(n){this.log.error("error while sending message",n)}}async sendData(t){for(this.log.trace("-> will send %d bytes",t.byteLength),t=t.sublist();t.byteLength>0;){let e=Math.min(t.byteLength,this.maxMessageSize),n=t.subarray(0,e),o=Bt.encode({message:n}),s=ln.single(o);this.log.trace("-> sending message %s",this.channel.readyState),await this._sendMessage(s),this.log.trace("-> sent message %s",this.channel.readyState),t.consume(e)}this.log.trace("-> sent data %s",this.channel.readyState)}async sendReset(){try{await this._sendFlag(Bt.Flag.RESET)}catch(t){this.log.error("failed to send reset - %e",t)}}async sendCloseWrite(t){if(this.channel.readyState!=="open"){this.receiveFinAck.resolve();return}if(await this._sendFlag(Bt.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await bt(this.receiveFinAck.promise,t?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorName:"FinAckNotReceivedError"})}catch(n){this.log.error("failed to await FIN_ACK",n)}}else this.log.trace("sending FIN failed, not awaiting FIN_ACK");this.receiveFinAck.resolve()}async sendCloseRead(){this.channel.readyState==="open"&&await this._sendFlag(Bt.Flag.STOP_SENDING)}processIncomingProtobuf(t){let e=Bt.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===Bt.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Bt.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),e.flag===Bt.Flag.RESET&&this.reset(),e.flag===Bt.Flag.STOP_SENDING&&this.remoteCloseRead(),e.flag===Bt.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=Bt.encode({flag:t}),n=ln.single(e);try{return await this._sendMessage(n,!1),!0}catch(o){this.log.error("could not send flag %s - %e",t.toString(),o)}return!1}};function Ar(r){let{channel:t,direction:e}=r;return new Yi({id:e==="inbound"?`i${t.id}`:`r${t.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${e}:${t.id}`),...r})}var Re=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??qi,this.dataChannelOptions=e.dataChannelOptions??{},this.log=t.logger.forComponent("libp2p:webrtc:muxerfactory"),this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace('incoming early datachannel with channel id %d and label "%s"',n.id),n.label==="init"){this.log.trace("closing early init channel"),n.close();return}let o={},s=Ar({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 Ji(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},Ji=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??qi,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=n.id,s=Ar({channel:n,direction:"inbound",onEnd:()=>{this.#t(s,n),this.log("incoming channel %s ended",o)},logger:this.logger,...this.dataChannelOptions});this.streams.push(s),this.metrics?.increment({incoming_stream:!0}),e?.onIncomingStream?.(s)},this.init.streams.length>0&&queueMicrotask(()=>{this.init.streams.forEach(n=>{n.onEnd=()=>{this.log("incoming early channel %s ended with state %s",n.channel.id,n.channel.readyState),this.#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),Jl(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=ao();sink=co;newStream(){let t=this.peerConnection.createDataChannel(""),e=t.id;this.log.trace("opened outgoing datachannel with channel id %s",e);let n=Ar({channel:t,direction:"outbound",onEnd:()=>{this.#t(n,t),this.log("outgoing channel %s ended",e)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(n),this.metrics?.increment({outgoing_stream:!0}),n}};var wo=globalThis.RTCPeerConnection,xo=globalThis.RTCSessionDescription,ou=globalThis.RTCIceCandidate;var Qi=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Z(),this.haveNext=Z()}[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=Z(),t}async throw(t){return this.ended=!0,this.error=t,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 this.ended=!0,this.nextResult=t,this.haveNext.resolve(),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 this.error??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=Z(),await bt(this.readNext.promise,e?.signal,e)}};function su(){return new Qi}var bo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function iu(r,t){let e=su();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 V;return{read:async i=>{if(i?.signal?.throwIfAborted(),i?.bytes==null){let{done:c,value:l}=await bt(n.next(),i?.signal);return c===!0?null:l}for(;o.byteLength<i.bytes;){let{value:c,done:l}=await bt(n.next(),i?.signal);if(l===!0)throw new bo("unexpected end of input");o.append(c)}let a=o.sublist(0,i.bytes);return o.consume(i.bytes),a},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 Eo=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},So=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ao=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function au(r,t={}){let e=iu(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=nt(t.maxDataLength));let n=t?.lengthDecoder??Ot,o=t?.lengthEncoder??qt;return{read:async i=>{let a=-1,c=new V;for(;;){c.append(await e.read({...i,bytes:1}));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Eo("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ao("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new So("message length too long");return e.read({...i,bytes:a})},write:async(i,a)=>{await e.write(new V(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new V(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function vo(r,t){let e=au(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 Mt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var De=class extends Error{constructor(t){super(`WebRTC transport error: ${t}`),this.name="WebRTCTransportError"}},Vt=class extends De{constructor(t="SDP handshake failed"){super(t),this.name="SDPHandshakeFailedError"}};var Io=class extends De{constructor(t,e){super(`Invalid fingerprint "${t}" within ${e}`),this.name="WebRTC/InvalidFingerprintError"}};var Co=class extends De{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},To=class extends De{constructor(t){super(`unsupported hash algorithm code: ${t} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var Ut;(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=()=>Ge(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=Jt((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.data!=null&&(s.uint32(18),s.string(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.data=o.string();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Yt(o,r.codec()),r.decode=(o,s)=>Zt(o,r.codec(),s)})(Ut||(Ut={}));var _o=async(r,t,e)=>{try{let n=Z();for(lm(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!==Ut.Type.ICE_CANDIDATE)throw new Sn("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){e.onProgress?.(new Mt("webrtc:end-of-ice-candidates")),e.log.trace("end-of-candidates received");continue}let i=new ou(s);e.log.trace("%s received new ICE candidate %o",e.direction,s);try{e.onProgress?.(new Mt("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&&Lo(r)!=="connected")throw n}};function Lo(r){return an?r.iceConnectionState:r.connectionState}function lm(r,t){r[an?"oniceconnectionstatechange":"onconnectionstatechange"]=e=>{switch(Lo(r)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new wn("RTCPeerConnection was closed"));break;default:break}}}async function cu({rtcConfiguration:r,dataChannel:t,signal:e,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=lu(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",u);let f=u.getPeerId();if(f==null)throw new Q("Relay peer was missing");let d=s.getConnections(mr(f)),g,x=!1;d.length===0?(l?.(new Mt("webrtc:dial-relay")),g=await i.dial(u,{signal:e,onProgress:l}),x=!0):(l?.(new Mt("webrtc:reuse-relay-connection")),g=d[0]);try{l?.(new Mt("webrtc:open-signaling-stream"));let m=await g.newStream(on,{signal:e,runOnLimitedConnection:!0}),h=vo(m).pb(Ut),w=new wo(r),b=new Re({logger:c},{peerConnection:w,dataChannelOptions:t});try{let p=w.createDataChannel("init");w.onicecandidate=({candidate:v})=>{let L=JSON.stringify(v?.toJSON()??null);a.trace("initiator sending ICE candidate %o",v),h.write({type:Ut.Type.ICE_CANDIDATE,data:L},{signal:e}).catch(T=>{a.error("error sending ICE candidate",T)})},w.onicecandidateerror=v=>{a.error("initiator ICE candidate error",v)};let I=await w.createOffer().catch(v=>{throw a.error("could not execute createOffer",v),new Vt("Failed to set createOffer")});a.trace("initiator send SDP offer %s",I.sdp),l?.(new Mt("webrtc:send-sdp-offer")),await h.write({type:Ut.Type.SDP_OFFER,data:I.sdp},{signal:e}),await w.setLocalDescription(I).catch(v=>{throw a.error("could not execute setLocalDescription",v),new Vt("Failed to set localDescription")}),l?.(new Mt("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let P=await h.read({signal:e});if(P.type!==Ut.Type.SDP_ANSWER)throw new Vt("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",P.data);let B=new xo({type:"answer",sdp:P.data});return await w.setRemoteDescription(B).catch(v=>{throw a.error("could not execute setRemoteDescription",v),new Vt("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),l?.(new Mt("webrtc:read-ice-candidates")),await _o(w,h,{direction:"initiator",signal:e,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),p.close(),l?.(new Mt("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await m.close({signal:e}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:w,muxerFactory:b}}catch(p){throw a.error("outgoing signaling error",p),w.close(),m.abort(p),p}finally{w.onicecandidate=null,w.onicecandidateerror=null}}finally{if(x)try{await g.close({signal:e})}catch(m){g.abort(m)}}}var uu=lt(Dl.matchers[0],z("p2p-circuit")),Bo=class r extends Qe{transportManager;shutdownController;events;constructor(t,e){super(),this.transportManager=t.transportManager,this.events=t.events,this.shutdownController=e.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}async listen(){this.events.addEventListener("transport:listening",this.onTransportListening)}onTransportListening(t){t.detail.getAddrs().filter(n=>uu.exactMatch(n)).map(n=>n.encapsulate("/webrtc")).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter(t=>!(t instanceof r)).map(t=>t.getAddrs().filter(e=>uu.exactMatch(e)).map(e=>e.encapsulate("/webrtc"))).flat()}updateAnnounceAddrs(){}async close(){this.events.removeEventListener("transport:listening",this.onTransportListening),this.shutdownController.abort(),queueMicrotask(()=>{this.safeDispatchEvent("close")})}};async function fu({peerConnection:r,stream:t,signal:e,connection:n,log:o}){o.trace("new inbound signaling stream");let s=vo(t).pb(Ut);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:Ut.Type.ICE_CANDIDATE,data:f},{signal:e}).catch(d=>{o.error("error sending ICE candidate",d)})},o.trace("recipient read SDP offer");let a=await s.read({signal:e});if(a.type!==Ut.Type.SDP_OFFER)throw new Vt(`expected message type SDP_OFFER, received: ${a.type??"undefined"} `);o.trace("recipient received SDP offer %s",a.data);let c=new xo({type:"offer",sdp:a.data});await r.setRemoteDescription(c).catch(u=>{throw o.error("could not execute setRemoteDescription",u),new Vt("Failed to set remoteDescription")});let l=await r.createAnswer().catch(u=>{throw o.error("could not execute createAnswer",u),new Vt("Failed to create answer")});o.trace("recipient send SDP answer %s",l.sdp),await s.write({type:Ut.Type.SDP_ANSWER,data:l.sdp},{signal:e}),await r.setLocalDescription(l).catch(u=>{throw o.error("could not execute setLocalDescription",u),new Vt("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await _o(r,s,{direction:"recipient",signal:e,log:o})}catch(a){if(Lo(r)!=="connected")throw o.error("error while handling signaling stream from peer %a",n.remoteAddr,a),r.close(),a;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",n.remoteAddr,a)}let i=re(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return o.trace("recipient connected to remote address %s",i),{remoteAddress:i}}var Po=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,e={}){this.components=t,this.init=e,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[mn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[tr]=["@libp2p/transport"];[Ma]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(on,t=>{let e=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);this._onProtocol(t,e).catch(n=>{this.log.error("failed to handle incoming connect from %p",t.connection.remotePeer,n)}).finally(()=>{e.clear()})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(on),this._started=!1}createListener(t){return new Bo(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(Nl.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 cu({rtcConfiguration:await Gi(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 je(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,signal:e.signal});return this._closeOnShutdown(o,i),a}async _onProtocol({connection:t,stream:e},n){let o=new wo(await Gi(this.init.rtcConfiguration)),s=new Re(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await fu({peerConnection:o,connection:t,stream:e,signal:n,log:this.log});await e.close({signal:n});let a=new je(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,signal:n}),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 lu(r){let t=r.toString().split("/webrtc/");if(t.length!==2)throw new Q("webrtc protocol was not present in multiaddr");if(!t[0].includes("/p2p-circuit"))throw new Q("p2p-circuit protocol was not present in multiaddr");let e=re(t[0]),o=re("/"+t[1]).getPeerId();if(o==null)throw new Q("destination peer id was missing");let s=e.protos().pop();if(s===void 0)throw new Q("invalid multiaddr");return s.name!=="p2p"&&(e=e.encapsulate(`/p2p/${o}`)),{baseAddr:e,peerId:mr(o)}}var Ro=class extends Qe{async listen(){throw new Co("WebRTCTransport.createListener")}getAddrs(){return[]}updateAnnounceAddrs(){}async close(){}};var ta=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=Z(),this.haveNext=Z()}[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=Z(),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 this.ended=!0,this.nextResult=t,this.haveNext.resolve(),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=Z(),await bt(this.readNext.promise,e?.signal,e)}};function hu(){return new ta}var Do=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var ea=class extends Error{code;constructor(t,e){super(t),this.code=e}},ra=class extends ea{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function du(r,t){let e=hu();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 V;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new ra("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:d}=await Promise.race([n.next(),l]);return f===!0?new V:d}for(;o.byteLength<i;){let{value:f,done:d}=await Promise.race([n.next(),l]);if(d===!0)throw new Do("unexpected end of input");o.append(f)}let u=o.sublist(0,i);return o.consume(i),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await 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 No=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ko=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Uo=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function na(r,t={}){let e=du(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=nt(t.maxDataLength));let n=t?.lengthDecoder??Ot,o=t?.lengthEncoder??qt;return{read:async i=>{let a=-1,c=new V;for(;;){c.append(await e.read(1,i));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new No("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Uo("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new ko("message length too long");return e.read(a,i)},write:async(i,a)=>{await e.write(new V(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new V(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function oa(){let r=Z(),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 pu(){let r=oa(),t=oa();return[{source:r.source,sink:t.sink},{source:t.source,sink:r.sink}]}var sa=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=Z(),this.haveNext=Z()}[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=Z(),t}async throw(t){return this.ended=!0,this.error=t,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 this.ended=!0,this.nextResult=t,this.haveNext.resolve(),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 this.error??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=Z(),await bt(this.readNext.promise,e?.signal,e)}};function mu(){return new sa}function um(r){return r[Symbol.asyncIterator]!=null}async function fm(r,t){try{await Promise.all(r.map(async e=>{for await(let n of e)await t.push(n)})),await t.end()}catch(e){await t.end(e).catch(()=>{})}}async function*hm(r){let t=mu();fm(r,t).catch(()=>{}),yield*t}function*dm(r){for(let t of r)yield*t}function pm(...r){let t=[];for(let e of r)um(e)||t.push(e);return t.length===r.length?dm(t):hm(r)}var gu=pm;function yu(r,...t){if(r==null)throw new Error("Empty pipeline");if(ia(r)){let n=r;r=()=>n.source}else if(xu(r)||wu(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&ia(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++)ia(e[n])&&(e[n]=gm(e[n]));return mm(...e)}var mm=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},wu=r=>r?.[Symbol.asyncIterator]!=null,xu=r=>r?.[Symbol.iterator]!=null,ia=r=>r==null?!1:r.sink!=null&&r.source!=null,gm=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Er({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(wu(s))o=async function*(){yield*s,n.end()};else if(xu(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return gu(n,o())}return r.source};var vr=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function Oo(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function aa(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Pt(r,...t){if(!aa(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error("Uint8Array expected of length "+t+", got length="+r.length)}function ca(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 bu(r,t){Pt(r);let e=t.outputLen;if(r.length<e)throw new Error("digestInto() expects output buffer of length at least "+e)}function la(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}var ge=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),Eu=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ym=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!ym)throw new Error("Non little-endian hardware is not supported");function wm(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Ko(r){if(typeof r=="string")r=wm(r);else if(aa(r))r=Mo(r);else throw new Error("Uint8Array expected, got "+typeof r);return r}function Su(r,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(r,t)}function Au(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 ua=(r,t)=>{function e(n,...o){if(Pt(n),r.nonceLength!==void 0){let u=o[0];if(!u)throw new Error("nonce / iv required");r.varSizeNonce?Pt(u):Pt(u,r.nonceLength)}let s=r.tagLength;s&&o[1]!==void 0&&Pt(o[1]);let i=t(n,...o),a=(u,f)=>{if(f!==void 0){if(u!==2)throw new Error("cipher output not supported");Pt(f)}},c=!1;return{encrypt(u,f){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Pt(u),a(i.encrypt.length,f),i.encrypt(u,f)},decrypt(u,f){if(Pt(u),s&&u.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(i.decrypt.length,f),i.decrypt(u,f)}}}return Object.assign(e,r),e};function fa(r,t,e=!0){if(t===void 0)return new Uint8Array(r);if(t.length!==r)throw new Error("invalid output length, expected "+r+", got: "+t.length);if(e&&!xm(t))throw new Error("invalid output, must be aligned");return t}function ha(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)}function xm(r){return r.byteOffset%4===0}function Mo(r){return Uint8Array.from(r)}function ye(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}var Iu=r=>Uint8Array.from(r.split("").map(t=>t.charCodeAt(0))),bm=Iu("expand 16-byte k"),Em=Iu("expand 32-byte k"),Sm=ge(bm),Am=ge(Em);function k(r,t){return r<<t|r>>>32-t}function da(r){return r.byteOffset%4===0}var Fo=64,vm=16,Cu=2**32-1,vu=new Uint32Array;function Im(r,t,e,n,o,s,i,a){let c=o.length,l=new Uint8Array(Fo),u=ge(l),f=da(o)&&da(s),d=f?ge(o):vu,g=f?ge(s):vu;for(let x=0;x<c;i++){if(r(t,e,n,u,i,a),i>=Cu)throw new Error("arx: counter overflow");let m=Math.min(Fo,c-x);if(f&&m===Fo){let h=x/4;if(x%4!==0)throw new Error("arx: invalid block position");for(let w=0,b;w<vm;w++)b=h+w,g[b]=d[b]^u[w];x+=Fo;continue}for(let h=0,w;h<m;h++)w=x+h,s[w]=o[w]^l[h];x+=m}}function pa(r,t){let{allowShortKeys:e,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Su({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof r!="function")throw new Error("core must be a function");return Oo(o),Oo(i),la(s),la(e),(a,c,l,u,f=0)=>{Pt(a),Pt(c),Pt(l);let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),Pt(u),Oo(f),f<0||f>=Cu)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let g=[],x=a.length,m,h;if(x===32)g.push(m=Mo(a)),h=Am;else if(x===16&&e)m=new Uint8Array(32),m.set(a),m.set(a,16),h=Sm,g.push(m);else throw new Error(`arx: invalid 32-byte key, got length=${x}`);da(c)||g.push(c=Mo(c));let w=ge(m);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,w,ge(c.subarray(0,16)),w),c=c.subarray(16)}let b=16-o;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let I=new Uint8Array(12);I.set(c,s?0:12-c.length),c=I,g.push(c)}let p=ge(c);return Im(r,h,w,p,l,u,f,i),ye(...g),u}}var At=(r,t)=>r[t++]&255|(r[t++]&255)<<8,ma=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=Ko(t),Pt(t,32);let e=At(t,0),n=At(t,2),o=At(t,4),s=At(t,6),i=At(t,8),a=At(t,10),c=At(t,12),l=At(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]=At(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],d=i[5],g=i[6],x=i[7],m=i[8],h=i[9],w=At(t,e+0),b=At(t,e+2),p=At(t,e+4),I=At(t,e+6),P=At(t,e+8),B=At(t,e+10),v=At(t,e+12),L=At(t,e+14),T=s[0]+(w&8191),K=s[1]+((w>>>13|b<<3)&8191),N=s[2]+((b>>>10|p<<6)&8191),O=s[3]+((p>>>7|I<<9)&8191),F=s[4]+((I>>>4|P<<12)&8191),C=s[5]+(P>>>1&8191),_=s[6]+((P>>>14|B<<2)&8191),E=s[7]+((B>>>11|v<<5)&8191),y=s[8]+((v>>>8|L<<8)&8191),A=s[9]+(L>>>5|o),S=0,R=S+T*a+K*(5*h)+N*(5*m)+O*(5*x)+F*(5*g);S=R>>>13,R&=8191,R+=C*(5*d)+_*(5*f)+E*(5*u)+y*(5*l)+A*(5*c),S+=R>>>13,R&=8191;let D=S+T*c+K*a+N*(5*h)+O*(5*m)+F*(5*x);S=D>>>13,D&=8191,D+=C*(5*g)+_*(5*d)+E*(5*f)+y*(5*u)+A*(5*l),S+=D>>>13,D&=8191;let U=S+T*l+K*c+N*a+O*(5*h)+F*(5*m);S=U>>>13,U&=8191,U+=C*(5*x)+_*(5*g)+E*(5*d)+y*(5*f)+A*(5*u),S+=U>>>13,U&=8191;let q=S+T*u+K*l+N*c+O*a+F*(5*h);S=q>>>13,q&=8191,q+=C*(5*m)+_*(5*x)+E*(5*g)+y*(5*d)+A*(5*f),S+=q>>>13,q&=8191;let M=S+T*f+K*u+N*l+O*c+F*a;S=M>>>13,M&=8191,M+=C*(5*h)+_*(5*m)+E*(5*x)+y*(5*g)+A*(5*d),S+=M>>>13,M&=8191;let G=S+T*d+K*f+N*u+O*l+F*c;S=G>>>13,G&=8191,G+=C*a+_*(5*h)+E*(5*m)+y*(5*x)+A*(5*g),S+=G>>>13,G&=8191;let j=S+T*g+K*d+N*f+O*u+F*l;S=j>>>13,j&=8191,j+=C*c+_*a+E*(5*h)+y*(5*m)+A*(5*x),S+=j>>>13,j&=8191;let it=S+T*x+K*g+N*d+O*f+F*u;S=it>>>13,it&=8191,it+=C*l+_*c+E*a+y*(5*h)+A*(5*m),S+=it>>>13,it&=8191;let at=S+T*m+K*x+N*g+O*d+F*f;S=at>>>13,at&=8191,at+=C*u+_*l+E*c+y*a+A*(5*h),S+=at>>>13,at&=8191;let ut=S+T*h+K*m+N*x+O*g+F*d;S=ut>>>13,ut&=8191,ut+=C*f+_*u+E*l+y*c+A*a,S+=ut>>>13,ut&=8191,S=(S<<2)+S|0,S=S+R|0,R=S&8191,S=S>>>13,D+=S,s[0]=R,s[1]=D,s[2]=U,s[3]=q,s[4]=M,s[5]=G,s[6]=j,s[7]=it,s[8]=at,s[9]=ut}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;ye(n)}update(t){ca(this);let{buffer:e,blockLen:n}=this;t=Ko(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(){ye(this.h,this.r,this.buffer,this.pad)}digestInto(t){ca(this),bu(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 Cm(r){let t=(n,o)=>r(o).update(Ko(n)).digest(),e=r(new Uint8Array(32));return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=n=>r(n),t}var Tu=Cm(r=>new ma(r));function Bu(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],d=t[2],g=t[3],x=t[4],m=t[5],h=t[6],w=t[7],b=o,p=e[0],I=e[1],P=e[2],B=i,v=a,L=c,T=l,K=u,N=f,O=d,F=g,C=x,_=m,E=h,y=w,A=b,S=p,R=I,D=P;for(let q=0;q<s;q+=2)B=B+K|0,A=k(A^B,16),C=C+A|0,K=k(K^C,12),B=B+K|0,A=k(A^B,8),C=C+A|0,K=k(K^C,7),v=v+N|0,S=k(S^v,16),_=_+S|0,N=k(N^_,12),v=v+N|0,S=k(S^v,8),_=_+S|0,N=k(N^_,7),L=L+O|0,R=k(R^L,16),E=E+R|0,O=k(O^E,12),L=L+O|0,R=k(R^L,8),E=E+R|0,O=k(O^E,7),T=T+F|0,D=k(D^T,16),y=y+D|0,F=k(F^y,12),T=T+F|0,D=k(D^T,8),y=y+D|0,F=k(F^y,7),B=B+N|0,D=k(D^B,16),E=E+D|0,N=k(N^E,12),B=B+N|0,D=k(D^B,8),E=E+D|0,N=k(N^E,7),v=v+O|0,A=k(A^v,16),y=y+A|0,O=k(O^y,12),v=v+O|0,A=k(A^v,8),y=y+A|0,O=k(O^y,7),L=L+F|0,S=k(S^L,16),C=C+S|0,F=k(F^C,12),L=L+F|0,S=k(S^L,8),C=C+S|0,F=k(F^C,7),T=T+K|0,R=k(R^T,16),_=_+R|0,K=k(K^_,12),T=T+K|0,R=k(R^T,8),_=_+R|0,K=k(K^_,7);let U=0;n[U++]=i+B|0,n[U++]=a+v|0,n[U++]=c+L|0,n[U++]=l+T|0,n[U++]=u+K|0,n[U++]=f+N|0,n[U++]=d+O|0,n[U++]=g+F|0,n[U++]=x+C|0,n[U++]=m+_|0,n[U++]=h+E|0,n[U++]=w+y|0,n[U++]=b+A|0,n[U++]=p+S|0,n[U++]=I+R|0,n[U++]=P+D|0}function Tm(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],d=t[4],g=t[5],x=t[6],m=t[7],h=e[0],w=e[1],b=e[2],p=e[3];for(let P=0;P<20;P+=2)o=o+c|0,h=k(h^o,16),d=d+h|0,c=k(c^d,12),o=o+c|0,h=k(h^o,8),d=d+h|0,c=k(c^d,7),s=s+l|0,w=k(w^s,16),g=g+w|0,l=k(l^g,12),s=s+l|0,w=k(w^s,8),g=g+w|0,l=k(l^g,7),i=i+u|0,b=k(b^i,16),x=x+b|0,u=k(u^x,12),i=i+u|0,b=k(b^i,8),x=x+b|0,u=k(u^x,7),a=a+f|0,p=k(p^a,16),m=m+p|0,f=k(f^m,12),a=a+f|0,p=k(p^a,8),m=m+p|0,f=k(f^m,7),o=o+l|0,p=k(p^o,16),x=x+p|0,l=k(l^x,12),o=o+l|0,p=k(p^o,8),x=x+p|0,l=k(l^x,7),s=s+u|0,h=k(h^s,16),m=m+h|0,u=k(u^m,12),s=s+u|0,h=k(h^s,8),m=m+h|0,u=k(u^m,7),i=i+f|0,w=k(w^i,16),d=d+w|0,f=k(f^d,12),i=i+f|0,w=k(w^i,8),d=d+w|0,f=k(f^d,7),a=a+c|0,b=k(b^a,16),g=g+b|0,c=k(c^g,12),a=a+c|0,b=k(b^a,8),g=g+b|0,c=k(c^g,7);let I=0;n[I++]=o,n[I++]=s,n[I++]=i,n[I++]=a,n[I++]=h,n[I++]=w,n[I++]=b,n[I++]=p}var _m=pa(Bu,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Lm=pa(Bu,{counterRight:!1,counterLength:8,extendNonceFn:Tm,allowShortKeys:!1});var Bm=new Uint8Array(16),_u=(r,t)=>{r.update(t);let e=t.length%16;e&&r.update(Bm.subarray(e))},Pm=new Uint8Array(32);function Lu(r,t,e,n,o){let s=r(t,e,Pm),i=Tu.create(s);o&&_u(i,o),_u(i,n);let a=new Uint8Array(16),c=Eu(a);ha(c,0,BigInt(o?o.length:0),!0),ha(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return ye(s,a),l}var Pu=r=>(t,e,n)=>({encrypt(s,i){let a=s.length;i=fa(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);r(t,e,c,c,1);let l=Lu(r,t,e,c,n);return i.set(l,a),ye(l),i},decrypt(s,i){i=fa(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=Lu(r,t,e,a,n);if(!Au(c,l))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),r(t,e,i,i,1),ye(l),i}}),ga=ua({blockSize:64,nonceLength:12,tagLength:16},Pu(_m)),mA=ua({blockSize:64,nonceLength:24,tagLength:16},Pu(Lm));function Du(r,t,e){return Ur(r),e===void 0&&(e=new Uint8Array(r.outputLen)),pr(r,Se(e),Se(t))}var ya=new Uint8Array([0]),Ru=new Uint8Array;function Nu(r,t,e,n=32){if(Ur(r),_n(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);e===void 0&&(e=Ru);let s=new Uint8Array(o*r.outputLen),i=pr.create(r,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)ya[0]=l+1,a.update(l===0?Ru:c).update(e).update(ya).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),ya.fill(0),s.slice(0,n)}var wa={hashSHA256(r){return ee(r.subarray())},getHKDF(r,t){let e=Du(ee,t,r),o=Nu(ee,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=qr.utils.randomPrivateKey();return{publicKey:qr.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:qr.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,t){return qr.getSharedSecret(r.subarray(),t.subarray())},chaCha20Poly1305Encrypt(r,t,e,n){return ga(n,t,e).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,t,e,n,o){return ga(n,t,e).decrypt(r.subarray(),o)}};var ku=wa;function Uu(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 Ir=r=>{let t=gt(2);return t[0]=r>>8,t[1]=r,t};Ir.bytes=2;var fn=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)};fn.bytes=2;function Ou(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 xa(r,t){!t.enabled||!vr||(r?(t(`LOCAL_STATIC_PUBLIC_KEY ${H(r.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${H(r.privateKey,"hex")}`)):t("Missing local static keys."))}function ba(r,t){!t.enabled||!vr||(r?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${H(r.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${H(r.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function Ku(r,t){!t.enabled||!vr||t(r?`REMOTE_STATIC_PUBLIC_KEY ${H(r.subarray(),"hex")}`:"Missing remote static public key.")}function Ea(r,t){!t.enabled||!vr||t(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${H(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Sa(r,t,e){!e.enabled||!vr||(e(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&H(r.k,"hex")}`),e(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&H(t.k,"hex")}`))}var Cr=class r extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var Rm=0,Dm=4294967295,Nm="Cipherstate has reached maximum n, a new handshake must be performed",Ho=class{n;bytes;view;constructor(t=Rm){this.n=t,this.bytes=mt(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>Dm)throw new Error(Nm)}};var Ye=mt(0),Tr=class{k;n;crypto;constructor(t,e=void 0,n=0){this.crypto=t,this.k=e,this.n=new Ho(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}},Aa=class{cs;ck;h;crypto;constructor(t,e){this.crypto=t;let n=X(e,"utf-8");this.h=km(t,n),this.ck=this.h,this.cs=new Tr(t)}mixKey(t){let[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new Tr(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new V(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,Ye);return[new Tr(this.crypto,t),new Tr(this.crypto,e)]}},va=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 Aa(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()}},hn=class extends va{writeMessageA(t){return new V(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let e=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new V(e,n,this.ss.encryptAndHash(t))}writeMessageC(t){let e=this.writeS();return this.writeSE(),new V(e,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(e){throw new Cr(`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 Cr(`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 Cr(`handshake stage 2 validation fail: ${e.message}`)}}};function km(r,t){if(t.length<=32){let e=mt(32);return e.set(t),e}else return r.hash(t)}var qo;(function(r){let t;r.codec=()=>(t==null&&(t=Jt((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.webtransportCerthashes!=null)for(let s of e.webtransportCerthashes)n.uint32(10),n.bytes(s);if(e.streamMuxers!=null)for(let s of e.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new Gr('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(e.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new Gr('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(e.string());break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Yt(e,r.codec()),r.decode=(e,n)=>Zt(e,r.codec(),n)})(qo||(qo={}));var dn;(function(r){let t;r.codec=()=>(t==null&&(t=Jt((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),qo.codec().encode(e.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={identityKey:mt(0),identitySig:mt(0)},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.identityKey=e.bytes();break}case 2:{s.identitySig=e.bytes();break}case 4:{s.extensions=qo.codec().decode(e,e.uint32(),{limits:o.limits?.extensions});break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>Yt(e,r.codec()),r.decode=(e,n)=>Zt(e,r.codec(),n)})(dn||(dn={}));async function Ia(r,t,e){let n=await r.sign(Mu(t));return dn.encode({identityKey:Ee(r.publicKey),identitySig:n,extensions:e})}async function Ca(r,t,e){try{let n=dn.decode(r),o=Xr(n.identityKey);if(e?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${e}`);if(!t)throw new Error("Remote static does not exist");let s=Mu(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new gn(n.message)}}function Mu(r){let t=X("noise-libp2p-static-key:");return r instanceof Uint8Array?yt([t,r],t.length+r.length):(r.prepend(t),r)}async function Fu(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Ia(s,a.publicKey,l),f=new hn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});xa(f.s,e),e.trace("Stage 0 - Initiator starting to send first message."),await n.write(f.writeMessageA(Ye),t),e.trace("Stage 0 - Initiator finished sending first message."),ba(f.e,e),e.trace("Stage 1 - Initiator waiting to receive first message from responder...");let d=f.readMessageB(await n.read(t));e.trace("Stage 1 - Initiator received the message."),Ea(f.re,e),Ku(f.rs,e),e.trace("Initiator going to check remote's signature...");let g=await Ca(d,f.rs,c);e.trace("All good with the signature!"),e.trace("Stage 2 - Initiator sending third handshake message."),await n.write(f.writeMessageC(u),t),e.trace("Stage 2 - Initiator sent message with signed payload.");let[x,m]=f.ss.split();return Sa(x,m,e),{payload:g,encrypt:h=>x.encryptWithAd(Ye,h),decrypt:(h,w)=>m.decryptWithAd(Ye,h,w)}}async function Hu(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Ia(s,a.publicKey,l),f=new hn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});xa(f.s,e),e.trace("Stage 0 - Responder waiting to receive first message."),f.readMessageA(await n.read(t)),e.trace("Stage 0 - Responder received first message."),Ea(f.re,e),e.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(f.writeMessageB(u),t),e.trace("Stage 1 - Responder sent the second handshake message with signed payload."),ba(f.e,e),e.trace("Stage 2 - Responder waiting for third handshake message...");let d=f.readMessageC(await n.read(t));e.trace("Stage 2 - Responder received the message, finished handshake.");let g=await Ca(d,f.rs,c),[x,m]=f.ss.split();return Sa(x,m,e),{payload:g,encrypt:h=>m.encryptWithAd(Ye,h),decrypt:(h,w)=>x.decryptWithAd(Ye,h,w)}}var Vu=16;function Wu(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 V(Ir(i.byteLength),i)}}}function Gu(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-Vu<o)throw new Error("Invalid chunk");let i=n.sublist(o,s),a=n.subarray(o,s-Vu);try{let c=r.decrypt(i,a);t?.decryptedPackets.increment(),yield c}catch(c){throw t?.decryptErrors.increment(),c}}}}var Vo=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??ku;this.crypto=Uu(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?Ou(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??mt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[tr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,e){let n=na(t,{lengthEncoder:Ir,lengthDecoder:fn,maxDataLength:65535}),o=await this.performHandshakeInitiator(n,this.components.privateKey,e?.remotePeer?.publicKey,e),s=await this.createSecureConnection(n,o);t.source=s.source,t.sink=s.sink;let i=Xr(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Ei(i),streamMuxer:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}getStreamMuxer(t){if(t==null)return;let e=this.components.upgrader.getStreamMuxers();if(e!=null)for(let n of t){let o=e.get(n);if(o!=null)return o}if(t.length)throw new yn("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(t,e){let n=na(t,{lengthEncoder:Ir,lengthDecoder:fn,maxDataLength:65535}),o=await this.performHandshakeResponder(n,this.components.privateKey,e?.remotePeer?.publicKey,e),s=await this.createSecureConnection(n,o);t.source=s.source,t.sink=s.sink;let i=Xr(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:Ei(i),streamMuxer:this.getStreamMuxer(o.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(t,e,n,o){let s;try{s=await Fu({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:[...this.components.upgrader.getStreamMuxers().keys()],webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async performHandshakeResponder(t,e,n,o){let s;try{s=await Hu({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:[...this.components.upgrader.getStreamMuxers().keys()],webtransportCerthashes:[],...this.extensions}},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async createSecureConnection(t,e){let[n,o]=pu(),s=t.unwrap();return await yu(n,Wu(e,this.metrics),s,i=>Ze(i,{lengthDecoder:fn}),Gu(e,this.metrics),n),o}};function zu(r={}){return t=>new Vo(t,r)}var Ta=Object.values(Oe).map(r=>r.decoder).reduce((r,t)=>r.or(t)),Um=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function $u(r){return r?.match(Um)?.groups?.fingerprint}function _a(r){let e=r.stringTuples().filter(n=>n[0]===Ol).map(n=>n[1])[0];if(e===void 0||e==="")throw new Q(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return e}function Om(r){return Ft.decode(Ta.decode(r))}function Km(r){let t=Om(_a(r)),e=Mm(t.code),n=t.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new Io(n,r.toString());return`${e} ${o.join(":").toUpperCase()}`}function ju(r){let t=r.split(":").map(o=>parseInt(o,16)),e=Uint8Array.from(t),n=Ct(ie.code,e);return re(`/certhash/${Dr.encode(n.bytes)}`)}function Mm(r){switch(r){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new To(r)}}function Xu(r,t){let{host:e,port:n,family:o}=r.toOptions(),s=Km(r);return{type:"answer",sdp:`v=0
3
3
  o=- 0 0 IN IP${o} ${e}
4
4
  s=-
5
5
  t=0 0
@@ -32,12 +32,12 @@ a=sctp-port:5000
32
32
  a=max-message-size:${xr}
33
33
  a=candidate:1467250027 1 UDP 1467250027 ${e} ${n} typ host
34
34
  a=end-of-candidates
35
- `}}function _a(r,t){if(r.sdp===void 0)throw new Q("Can't munge a missing SDP");let e=r.sdp.includes(`\r
35
+ `}}function La(r,t){if(r.sdp===void 0)throw new Q("Can't munge a missing SDP");let e=r.sdp.includes(`\r
36
36
  `)?`\r
37
37
  `:`
38
38
  `;return r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
39
39
  a=ice-ufrag:`+t+e).replace(/\na=ice-pwd:[^\n]*\n/,`
40
- a=ice-pwd:`+t+e),r}var La=X("libp2p-webrtc-noise:");function Ju(r,t,e){let n=r.trim().toLowerCase().replaceAll(":",""),o=X(n,"hex"),s=Ct(ie.code,o),i=Ca.decode(Ta(t)),a=La.byteLength+s.bytes.byteLength+i.byteLength;return e==="server"?yt([La,i,s.bytes],a):yt([La,s.bytes,i],a)}var Fm=an?"iceconnectionstatechange":"connectionstatechange";async function Qu(r,t,e){let n=r.createDataChannel("",{negotiated:!0,id:0});if(e.role==="client"){e.log.trace("client creating local offer");let d=await r.createOffer();e.log.trace("client created local offer %s",d.sdp);let g=_a(d,t);e.log.trace("client setting local offer %s",g.sdp),await r.setLocalDescription(g);let x=Xu(e.remoteAddr,t);e.log.trace("client setting server description %s",x.sdp),await r.setRemoteDescription(x)}else{let d=Zu(e.remoteAddr,t);e.log.trace("server setting client %s %s",d.type,d.sdp),await r.setRemoteDescription(d),e.log.trace("server creating local answer");let g=await r.createAnswer();e.log.trace("server created local answer");let x=_a(g,t);e.log.trace("server setting local description %s",g.sdp),await r.setLocalDescription(x)}if(e.log.trace("%s wait for handshake channel to open",e.role),await un(n,"open",e.signal),e.log.trace("%s handshake channel opened",e.role),e.role==="server"){let d=r.remoteFingerprint()?.value??"";e.remoteAddr=e.remoteAddr.encapsulate(ju(d))}let o=$u(r.localDescription?.sdp);if(o==null)throw new De("Could not get fingerprint from local description sdp");e.log.trace("%s performing noise handshake",e.role);let s=Ju(o,e.remoteAddr,e.role),i=zu({prologueBytes:s})(e),a=Ar({channel:n,direction:"inbound",logger:e.logger,...e.dataChannel??{}}),c={...a,sink:a.sink.bind(a),source:async function*(){for await(let d of a.source)for(let g of d)yield g}()},l=new je(e,{peerConnection:r,remoteAddr:e.remoteAddr,timeline:{open:Date.now()},metrics:e.events});r.addEventListener(Fm,()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(d=>{e.log.error("error closing connection",d),l.abort(d)});break;default:break}}),e.events?.increment({peer_connection:!0});let u=new Re(e,{peerConnection:r,metrics:e.events,dataChannelOptions:e.dataChannel});if(e.role==="client")return e.log.trace("%s secure inbound",e.role),await i.secureInbound(c,{remotePeer:e.remotePeerId,signal:e.signal}),e.log.trace("%s upgrade outbound",e.role),e.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,muxerFactory:u,signal:e.signal});e.log.trace("%s secure outbound",e.role);let f=await i.secureOutbound(c,{remotePeer:e.remotePeerId,signal:e.signal});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${f.remotePeer}`),e.log.trace("%s upgrade inbound",e.role),await e.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,muxerFactory:u,signal:e.signal})}async function tf(r,t,e,n){n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof e=="function"?await e():e;return new RTCPeerConnection({...o??{},certificates:[n]})}var Wo=class{log;metrics;components;init;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:webrtc-direct"),this.components=t,this.init=e,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[mn]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[tr]=["@libp2p/transport"];async dial(t,e){let n=await this._connect(t,e);return this.log("dialing address: %a",t),n}createListener(t){return new Ro(this.components,{...this.init,...t})}listenFilter(t){return t.filter(Pl.exactMatch)}dialFilter(t){return this.listenFilter(t)}async _connect(t,e){e.signal.throwIfAborted();let n,o=t.getPeerId();o!=null&&(n=mr(o));let s=Ql(),i=await tf("client",s,typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{});try{return await bt(Qu(i,s,{role:"client",log:this.log,logger:this.components.logger,metrics:this.components.metrics,events:this.metrics?.dialerEvents,signal:e.signal,remoteAddr:t,dataChannel:this.init.dataChannel,upgrader:e.upgrader,peerId:this.components.peerId,remotePeerId:n,privateKey:this.components.privateKey}),e.signal)}catch(a){throw i.close(),a}}};function Hm(r){return t=>new Wo(t,r)}function qm(r){return t=>new Po(t,r)}return pf(Vm);})();
40
+ a=ice-pwd:`+t+e),r}var Ba=X("libp2p-webrtc-noise:");function Ju(r,t,e){let n=r.trim().toLowerCase().replaceAll(":",""),o=X(n,"hex"),s=Ct(ie.code,o),i=Ta.decode(_a(t)),a=Ba.byteLength+s.bytes.byteLength+i.byteLength;return e==="server"?yt([Ba,i,s.bytes],a):yt([Ba,s.bytes,i],a)}var Fm=an?"iceconnectionstatechange":"connectionstatechange";async function Qu(r,t,e){let n=r.createDataChannel("",{negotiated:!0,id:0});if(e.role==="client"){e.log.trace("client creating local offer");let d=await r.createOffer();e.log.trace("client created local offer %s",d.sdp);let g=La(d,t);e.log.trace("client setting local offer %s",g.sdp),await r.setLocalDescription(g);let x=Xu(e.remoteAddr,t);e.log.trace("client setting server description %s",x.sdp),await r.setRemoteDescription(x)}else{let d=Zu(e.remoteAddr,t);e.log.trace("server setting client %s %s",d.type,d.sdp),await r.setRemoteDescription(d),e.log.trace("server creating local answer");let g=await r.createAnswer();e.log.trace("server created local answer");let x=La(g,t);e.log.trace("server setting local description %s",g.sdp),await r.setLocalDescription(x)}if(e.log.trace("%s wait for handshake channel to open",e.role),await un(n,"open",e.signal),e.log.trace("%s handshake channel opened",e.role),e.role==="server"){let d=r.remoteFingerprint()?.value??"";e.remoteAddr=e.remoteAddr.encapsulate(ju(d))}let o=$u(r.localDescription?.sdp);if(o==null)throw new De("Could not get fingerprint from local description sdp");e.log.trace("%s performing noise handshake",e.role);let s=Ju(o,e.remoteAddr,e.role),i=zu({prologueBytes:s})(e),a=Ar({channel:n,direction:"inbound",logger:e.logger,...e.dataChannel??{}}),c={...a,sink:a.sink.bind(a),source:async function*(){for await(let d of a.source)for(let g of d)yield g}()},l=new je(e,{peerConnection:r,remoteAddr:e.remoteAddr,timeline:{open:Date.now()},metrics:e.events});r.addEventListener(Fm,()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":l.close().catch(d=>{e.log.error("error closing connection",d),l.abort(d)});break;default:break}}),e.events?.increment({peer_connection:!0});let u=new Re(e,{peerConnection:r,metrics:e.events,dataChannelOptions:e.dataChannel});if(e.role==="client")return e.log.trace("%s secure inbound",e.role),await i.secureInbound(c,{remotePeer:e.remotePeerId,signal:e.signal}),e.log.trace("%s upgrade outbound",e.role),e.upgrader.upgradeOutbound(l,{skipProtection:!0,skipEncryption:!0,muxerFactory:u,signal:e.signal});e.log.trace("%s secure outbound",e.role);let f=await i.secureOutbound(c,{remotePeer:e.remotePeerId,signal:e.signal});l.remoteAddr=l.remoteAddr.encapsulate(`/p2p/${f.remotePeer}`),e.log.trace("%s upgrade inbound",e.role),await e.upgrader.upgradeInbound(l,{skipProtection:!0,skipEncryption:!0,muxerFactory:u,signal:e.signal})}async function tf(r,t,e,n){n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let o=typeof e=="function"?await e():e;return new RTCPeerConnection({...o??{},certificates:[n]})}var Wo=class{log;metrics;components;init;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:webrtc-direct"),this.components=t,this.init=e,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[mn]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[tr]=["@libp2p/transport"];async dial(t,e){let n=await this._connect(t,e);return this.log("dialing address: %a",t),n}createListener(t){return new Ro(this.components,{...this.init,...t})}listenFilter(t){return t.filter(Pl.exactMatch)}dialFilter(t){return this.listenFilter(t)}async _connect(t,e){e.signal.throwIfAborted();let n,o=t.getPeerId();o!=null&&(n=mr(o));let s=Ql(),i=await tf("client",s,typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{});try{return await bt(Qu(i,s,{role:"client",log:this.log,logger:this.components.logger,metrics:this.components.metrics,events:this.metrics?.dialerEvents,signal:e.signal,remoteAddr:t,dataChannel:this.init.dataChannel,upgrader:e.upgrader,peerId:this.components.peerId,remotePeerId:n,privateKey:this.components.privateKey}),e.signal)}catch(a){throw i.close(),a}}};function Hm(r){return t=>new Wo(t,r)}function qm(r){return t=>new Po(t,r)}return pf(Vm);})();
41
41
  /*! Bundled license information:
42
42
 
43
43
  @noble/hashes/esm/utils.js:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@libp2p/webrtc",
3
- "version": "5.2.9-78cd7d53e",
3
+ "version": "5.2.9-d53ef170c",
4
4
  "description": "A libp2p transport using WebRTC connections",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/transport-webrtc#readme",
@@ -54,10 +54,10 @@
54
54
  "@chainsafe/is-ip": "^2.0.2",
55
55
  "@chainsafe/libp2p-noise": "^16.0.0",
56
56
  "@ipshipyard/node-datachannel": "^0.26.4",
57
- "@libp2p/interface": "2.7.0-78cd7d53e",
58
- "@libp2p/interface-internal": "2.3.9-78cd7d53e",
59
- "@libp2p/peer-id": "5.1.0-78cd7d53e",
60
- "@libp2p/utils": "6.6.0-78cd7d53e",
57
+ "@libp2p/interface": "2.7.0-d53ef170c",
58
+ "@libp2p/interface-internal": "2.3.9-d53ef170c",
59
+ "@libp2p/peer-id": "5.1.0-d53ef170c",
60
+ "@libp2p/utils": "6.6.0-d53ef170c",
61
61
  "@multiformats/multiaddr": "^12.4.0",
62
62
  "@multiformats/multiaddr-matcher": "^1.6.0",
63
63
  "@peculiar/webcrypto": "^1.5.0",
@@ -83,9 +83,9 @@
83
83
  "uint8arrays": "^5.1.0"
84
84
  },
85
85
  "devDependencies": {
86
- "@libp2p/crypto": "5.0.15-78cd7d53e",
87
- "@libp2p/interface-compliance-tests": "6.4.2-78cd7d53e",
88
- "@libp2p/logger": "5.1.13-78cd7d53e",
86
+ "@libp2p/crypto": "5.0.15-d53ef170c",
87
+ "@libp2p/interface-compliance-tests": "6.4.2-d53ef170c",
88
+ "@libp2p/logger": "5.1.13-d53ef170c",
89
89
  "@types/sinon": "^17.0.3",
90
90
  "aegir": "^45.1.1",
91
91
  "delay": "^6.0.0",