@libp2p/mplex 12.0.23 → 12.0.24

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,4 +1,4 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PMplex = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var Libp2PMplex=(()=>{var De=Object.defineProperty;var kt=Object.getOwnPropertyDescriptor;var $t=Object.getOwnPropertyNames;var Wt=Object.prototype.hasOwnProperty;var L=(r,e)=>{for(var t in e)De(r,t,{get:e[t],enumerable:!0})},jt=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of $t(e))!Wt.call(r,n)&&n!==t&&De(r,n,{get:()=>e[n],enumerable:!(s=kt(e,n))||s.enumerable});return r};var qt=r=>jt(De({},"__esModule",{value:!0}),r);var Ls={};L(Ls,{mplex:()=>vs});var P=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},ne=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var _=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},K=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var Q=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var ie=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},F=class extends Event{error;local;constructor(e,t,s){super("close",s),this.error=t,this.local=e}},oe=class extends F{constructor(e,t){super(!0,e,t)}},ae=class extends F{constructor(e,t){super(!1,e,t)}};function Gt(r){return typeof r?.handleEvent=="function"}function Kt(r){return(r!==!0&&r!==!1&&r?.once)??!1}var z=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,s){let n=Kt(s);super.addEventListener(e,o=>{if(n){let a=this.#e.get(o.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(o.type,a))}Gt(t)?t.handleEvent(o):t(o)},s);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:t,once:n})}removeEventListener(e,t,s){super.removeEventListener(e.toString(),t??null,s);let n=this.#e.get(e);n!=null&&(n=n.filter(({callback:i})=>i!==t),this.#e.set(e,n))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var ut=Symbol.for("@libp2p/service-capabilities");var Be={};L(Be,{base58btc:()=>R,base58flickr:()=>er});var en=new Uint8Array(0);function ht(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function M(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 ft(r){return new TextEncoder().encode(r)}function lt(r){return new TextDecoder().decode(r)}function Qt(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),s=0;s<t.length;s++)t[s]=255;for(var n=0;n<r.length;n++){var i=r.charAt(n),o=i.charCodeAt(0);if(t[o]!==255)throw new TypeError(i+" is ambiguous");t[o]=n}var a=r.length,c=r.charAt(0),p=Math.log(a)/Math.log(256),g=Math.log(256)/Math.log(a);function l(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var b=0,u=0,x=0,E=h.length;x!==E&&h[x]===0;)x++,b++;for(var y=(E-x)*g+1>>>0,v=new Uint8Array(y);x!==E;){for(var D=h[x],N=0,T=y-1;(D!==0||N<u)&&T!==-1;T--,N++)D+=256*v[T]>>>0,v[T]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");u=N,x++}for(var C=y-u;C!==y&&v[C]===0;)C++;for(var se=c.repeat(b);C<y;++C)se+=r.charAt(v[C]);return se}function d(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var b=0;if(h[b]!==" "){for(var u=0,x=0;h[b]===c;)u++,b++;for(var E=(h.length-b)*p+1>>>0,y=new Uint8Array(E);h[b];){var v=t[h.charCodeAt(b)];if(v===255)return;for(var D=0,N=E-1;(v!==0||D<x)&&N!==-1;N--,D++)v+=a*y[N]>>>0,y[N]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");x=D,b++}if(h[b]!==" "){for(var T=E-x;T!==E&&y[T]===0;)T++;for(var C=new Uint8Array(u+(E-T)),se=u;T!==E;)C[se++]=y[T++];return C}}}function m(h){var b=d(h);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:d,decode:m}}var Xt=Qt,Ht=Xt,mt=Ht;var Te=class{name;prefix;baseEncode;constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Re=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,s){this.name=e,this.prefix=t;let n=t.codePointAt(0);if(n===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=s}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return pt(this,e)}},Ce=class{decoders;constructor(e){this.decoders=e}or(e){return pt(this,e)}decode(e){let t=e[0],s=this.decoders[t];if(s!=null)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function pt(r,e){return new Ce({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Me=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,s,n){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=n,this.encoder=new Te(e,t,s),this.decoder=new Re(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function V({name:r,prefix:e,encode:t,decode:s}){return new Me(r,e,t,s)}function U({name:r,prefix:e,alphabet:t}){let{encode:s,decode:n}=mt(t,r);return V({prefix:e,name:r,encode:s,decode:i=>M(n(i))})}function Jt(r,e,t,s){let n=r.length;for(;r[n-1]==="=";)--n;let i=new Uint8Array(n*t/8|0),o=0,a=0,c=0;for(let p=0;p<n;++p){let g=e[r[p]];if(g===void 0)throw new SyntaxError(`Non-${s} character`);a=a<<t|g,o+=t,o>=8&&(o-=8,i[c++]=255&a>>o)}if(o>=t||(255&a<<8-o)!==0)throw new SyntaxError("Unexpected end of data");return i}function Zt(r,e,t){let s=e[e.length-1]==="=",n=(1<<t)-1,i="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,i+=e[n&a>>o];if(o!==0&&(i+=e[n&a<<t-o]),s)for(;(i.length*t&7)!==0;)i+="=";return i}function Yt(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function w({name:r,prefix:e,bitsPerChar:t,alphabet:s}){let n=Yt(s);return V({prefix:e,name:r,encode(i){return Zt(i,s,t)},decode(i){return Jt(i,n,t,r)}})}var R=U({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),er=U({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ne={};L(Ne,{base32:()=>k,base32hex:()=>nr,base32hexpad:()=>or,base32hexpadupper:()=>ar,base32hexupper:()=>ir,base32pad:()=>rr,base32padupper:()=>sr,base32upper:()=>tr,base32z:()=>cr});var k=w({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),tr=w({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),rr=w({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),sr=w({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),nr=w({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ir=w({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),or=w({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ar=w({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),cr=w({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var _e={};L(_e,{base36:()=>X,base36upper:()=>ur});var X=U({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ur=U({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var hr=wt,gt=128,fr=127,lr=~fr,dr=Math.pow(2,31);function wt(r,e,t){e=e||[],t=t||0;for(var s=t;r>=dr;)e[t++]=r&255|gt,r/=128;for(;r&lr;)e[t++]=r&255|gt,r>>>=7;return e[t]=r|0,wt.bytes=t-s+1,e}var mr=Ue,pr=128,bt=127;function Ue(r,s){var t=0,s=s||0,n=0,i=s,o,a=r.length;do{if(i>=a)throw Ue.bytes=0,new RangeError("Could not decode varint");o=r[i++],t+=n<28?(o&bt)<<n:(o&bt)*Math.pow(2,n),n+=7}while(o>=pr);return Ue.bytes=i-s,t}var gr=Math.pow(2,7),br=Math.pow(2,14),wr=Math.pow(2,21),xr=Math.pow(2,28),yr=Math.pow(2,35),Er=Math.pow(2,42),Sr=Math.pow(2,49),vr=Math.pow(2,56),Lr=Math.pow(2,63),Ir=function(r){return r<gr?1:r<br?2:r<wr?3:r<xr?4:r<yr?5:r<Er?6:r<Sr?7:r<vr?8:r<Lr?9:10},Ar={encode:hr,decode:mr,encodingLength:Ir},Dr=Ar,H=Dr;function J(r,e=0){return[H.decode(r,e),H.decode.bytes]}function $(r,e,t=0){return H.encode(r,e,t),e}function W(r){return H.encodingLength(r)}function q(r,e){let t=e.byteLength,s=W(r),n=s+W(t),i=new Uint8Array(n+t);return $(r,i,0),$(t,i,s),i.set(e,n),new j(r,t,e,i)}function xt(r){let e=M(r),[t,s]=J(e),[n,i]=J(e.subarray(s)),o=e.subarray(s+i);if(o.byteLength!==n)throw new Error("Incorrect length");return new j(t,n,o,e)}function yt(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ht(r.bytes,t.bytes)}}var j=class{code;size;digest;bytes;constructor(e,t,s,n){this.code=e,this.size=t,this.digest=s,this.bytes=n}};function Et(r,e){let{bytes:t,version:s}=r;return s===0?Rr(t,Oe(r),e??R.encoder):Cr(t,Oe(r),e??k.encoder)}var St=new WeakMap;function Oe(r){let e=St.get(r);if(e==null){let t=new Map;return St.set(r,t),t}return e}var ue=class r{code;version;multihash;bytes;"/";constructor(e,t,s,n){this.code=t,this.version=e,this.multihash=s,this.bytes=n,this["/"]=n}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Y)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Mr)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,s=q(e,t);return r.createV1(this.code,s)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let s=t;return s!=null&&e.code===s.code&&e.version===s.version&&yt(e.multihash,s.multihash)}toString(e){return Et(this,e)}toJSON(){return{"/":Et(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:s,code:n,multihash:i,bytes:o}=t;return new r(s,n,i,o??vt(s,n,i.bytes))}else if(t[Br]===!0){let{version:s,multihash:n,code:i}=t,o=xt(n);return r.create(s,i,o)}else return null}static create(e,t,s){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(s.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Y)throw new Error(`Version 0 CID must use dag-pb (code: ${Y}) block encoding`);return new r(e,t,s,s.bytes)}case 1:{let n=vt(e,t,s.bytes);return new r(e,t,s,n)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Y,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,s]=r.decodeFirst(e);if(s.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),s=t.size-t.multihashSize,n=M(e.subarray(s,s+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=n.subarray(t.multihashSize-t.digestSize),o=new j(t.multihashCode,t.digestSize,i,n);return[t.version===0?r.createV0(o):r.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,s=()=>{let[l,d]=J(e.subarray(t));return t+=d,l},n=s(),i=Y;if(n===18?(n=0,t=0):i=s(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let o=t,a=s(),c=s(),p=t+c,g=p-o;return{version:n,codec:i,multihashCode:a,digestSize:c,multihashSize:g,size:p}}static parse(e,t){let[s,n]=Tr(e,t),i=r.decode(n);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Oe(i).set(s,e),i}};function Tr(r,e){switch(r[0]){case"Q":{let t=e??R;return[R.prefix,t.decode(`${R.prefix}${r}`)]}case R.prefix:{let t=e??R;return[R.prefix,t.decode(r)]}case k.prefix:{let t=e??k;return[k.prefix,t.decode(r)]}case X.prefix:{let t=e??X;return[X.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Rr(r,e,t){let{prefix:s}=t;if(s!==R.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let n=e.get(s);if(n==null){let i=t.encode(r).slice(1);return e.set(s,i),i}else return n}function Cr(r,e,t){let{prefix:s}=t,n=e.get(s);if(n==null){let i=t.encode(r);return e.set(s,i),i}else return n}var Y=112,Mr=18;function vt(r,e,t){let s=W(r),n=s+W(e),i=new Uint8Array(n+t.byteLength);return $(r,i,0),$(e,i,s),i.set(t,n),i}var Br=Symbol.for("@ipld/js-cid/CID");var Pe={};L(Pe,{identity:()=>Ur});var Lt=0,Nr="identity",It=M;function _r(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return q(Lt,It(r))}var Ur={code:Lt,name:Nr,encode:It,digest:_r};function Fe(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function B(r=0){return new Uint8Array(r)}function I(r=0){return new Uint8Array(r)}function he(r,e){e==null&&(e=r.reduce((n,i)=>n+i.length,0));let t=I(e),s=0;for(let n of r)t.set(n,s),s+=n.length;return t}var Dt=Symbol.for("@achingbrain/uint8arraylist");function At(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let s of r){let n=t+s.byteLength;if(e<n)return{buf:s,index:e-t};t=n}throw new RangeError("index is out of bounds")}function fe(r){return!!r?.[Dt]}var A=class r{bufs;length;[Dt]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let s of e)if(s instanceof Uint8Array)t+=s.byteLength,this.bufs.push(s);else if(fe(s)){t+=s.byteLength;for(let n of s.bufs)this.bufs.push(n)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let s of e.reverse())if(s instanceof Uint8Array)t+=s.byteLength,this.bufs.unshift(s);else if(fe(s))t+=s.byteLength,this.bufs.unshift(...s.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=At(this.bufs,e);return t.buf[t.index]}set(e,t){let s=At(this.bufs,e);s.buf[s.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let s=0;s<e.length;s++)this.set(t+s,e[s]);else if(fe(e))for(let s=0;s<e.length;s++)this.set(t+s,e.get(s));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:s,length:n}=this._subList(e,t);return he(s,n)}subarray(e,t){let{bufs:s,length:n}=this._subList(e,t);return s.length===1?s[0]:he(s,n)}sublist(e,t){let{bufs:s,length:n}=this._subList(e,t),i=new r;return i.length=n,i.bufs=s,i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let s=[],n=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],a=n,c=a+o.byteLength;if(n=c,e>=c)continue;let p=e>=a&&e<c,g=t>a&&t<=c;if(p&&g){if(e===a&&t===c){s.push(o);break}let l=e-a;s.push(o.subarray(l,l+(t-e)));break}if(p){if(e===0){s.push(o);continue}s.push(o.subarray(e-a));continue}if(g){if(t===c){s.push(o);break}s.push(o.subarray(0,t-a));break}s.push(o)}return{bufs:s,length:t-e}}indexOf(e,t=0){if(!fe(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let s=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let n=s.byteLength;if(n===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let l=0;l<i;l++)o[l]=-1;for(let l=0;l<n;l++)o[s[l]]=l;let a=o,c=this.byteLength-s.byteLength,p=s.byteLength-1,g;for(let l=t;l<=c;l+=g){g=0;for(let d=p;d>=0;d--){let m=this.get(l+d);if(s[d]!==m){g=Math.max(1,d-a[m]);break}}if(g===0)return l}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let s=I(1);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt8(0,t),this.write(s,e)}getInt16(e,t){let s=this.subarray(e,e+2);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt16(0,t)}setInt16(e,t,s){let n=B(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,s),this.write(n,e)}getInt32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt32(0,t)}setInt32(e,t,s){let n=B(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,s),this.write(n,e)}getBigInt64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigInt64(0,t)}setBigInt64(e,t,s){let n=B(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,s),this.write(n,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let s=I(1);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint8(0,t),this.write(s,e)}getUint16(e,t){let s=this.subarray(e,e+2);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint16(0,t)}setUint16(e,t,s){let n=B(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,s),this.write(n,e)}getUint32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint32(0,t)}setUint32(e,t,s){let n=B(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,s),this.write(n,e)}getBigUint64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigUint64(0,t)}setBigUint64(e,t,s){let n=B(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,s),this.write(n,e)}getFloat32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getFloat32(0,t)}setFloat32(e,t,s){let n=B(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,s),this.write(n,e)}getFloat64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getFloat64(0,t)}setFloat64(e,t,s){let n=B(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,s),this.write(n,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Fe(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let s=new r;return s.bufs=e,t==null&&(t=e.reduce((n,i)=>n+i.byteLength,0)),s.length=t,s}};var ze={};L(ze,{base10:()=>Pr});var Pr=U({prefix:"9",name:"base10",alphabet:"0123456789"});var Ve={};L(Ve,{base16:()=>Fr,base16upper:()=>zr});var Fr=w({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),zr=w({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ke={};L(ke,{base2:()=>Vr});var Vr=w({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var $e={};L($e,{base256emoji:()=>qr});var Tt=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}"),kr=Tt.reduce((r,e,t)=>(r[t]=e,r),[]),$r=Tt.reduce((r,e,t)=>{let s=e.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${e}`);return r[s]=t,r},[]);function Wr(r){return r.reduce((e,t)=>(e+=kr[t],e),"")}function jr(r){let e=[];for(let t of r){let s=t.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${t}`);let n=$r[s];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var qr=V({prefix:"\u{1F680}",name:"base256emoji",encode:Wr,decode:jr});var We={};L(We,{base64:()=>Gr,base64pad:()=>Kr,base64url:()=>Qr,base64urlpad:()=>Xr});var Gr=w({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Kr=w({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Qr=w({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Xr=w({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var je={};L(je,{base8:()=>Hr});var Hr=w({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var qe={};L(qe,{identity:()=>Jr});var Jr=V({prefix:"\0",name:"identity",encode:r=>lt(r),decode:r=>ft(r)});var Pn=new TextEncoder,Fn=new TextDecoder;var Qe={};L(Qe,{sha256:()=>ts,sha512:()=>rs});var es=20;function Ke({name:r,code:e,encode:t,minDigestLength:s,maxDigestLength:n}){return new Ge(r,e,t,s,n)}var Ge=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,s,n,i){this.name=e,this.code=t,this.encode=s,this.minDigestLength=n??es,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let s=this.encode(e);return s instanceof Uint8Array?Rt(s,this.code,t?.truncate):s.then(n=>Rt(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Rt(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return q(e,r)}function Mt(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ts=Ke({name:"sha2-256",code:18,encode:Mt("SHA-256")}),rs=Ke({name:"sha2-512",code:19,encode:Mt("SHA-512")});var Xe={...qe,...ke,...je,...ze,...Ve,...Ne,..._e,...Be,...We,...$e},Hn={...Qe,...Pe};function Nt(r,e,t,s){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:s}}}var Bt=Nt("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),He=Nt("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=I(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ss={utf8:Bt,"utf-8":Bt,hex:Xe.base16,latin1:He,ascii:He,binary:He,...Xe},le=ss;function Je(r,e="utf8"){let t=le[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function de(r,e="utf8"){let t=le[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var ns=Math.pow(2,7),is=Math.pow(2,14),os=Math.pow(2,21),as=Math.pow(2,28),cs=Math.pow(2,35),us=Math.pow(2,42),hs=Math.pow(2,49),S=128;function O(r){if(r<ns)return 1;if(r<is)return 2;if(r<os)return 3;if(r<as)return 4;if(r<cs)return 5;if(r<us)return 6;if(r<hs)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function fs(r,e,t=0){switch(O(r)){case 8:e[t++]=r&255|S,r/=128;case 7:e[t++]=r&255|S,r/=128;case 6:e[t++]=r&255|S,r/=128;case 5:e[t++]=r&255|S,r/=128;case 4:e[t++]=r&255|S,r>>>=7;case 3:e[t++]=r&255|S,r>>>=7;case 2:e[t++]=r&255|S,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function ls(r,e,t=0){switch(O(r)){case 8:e.set(t++,r&255|S),r/=128;case 7:e.set(t++,r&255|S),r/=128;case 6:e.set(t++,r&255|S),r/=128;case 5:e.set(t++,r&255|S),r/=128;case 4:e.set(t++,r&255|S),r>>>=7;case 3:e.set(t++,r&255|S),r>>>=7;case 2:e.set(t++,r&255|S),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function me(r,e,t=0){return e==null&&(e=I(O(r))),e instanceof Uint8Array?fs(r,e,t):ls(r,e,t)}function pe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ge=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},G=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ge(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new ge(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Ze=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function _t(r={}){return ms(t=>{let s=t.shift();if(s==null)return{done:!0};if(s.error!=null)throw s.error;return{done:s.done===!0,value:s.value}},r)}function ms(r,e){e=e??{};let t=e.onEnd,s=new G,n,i,o,a=pe(),c=async()=>{try{return s.isEmpty()?o?{done:!0}:await new Promise((u,x)=>{i=E=>{i=null,s.push(E);try{u(r(s))}catch(y){x(y)}return n}}):r(s)}finally{s.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=pe()})}},p=u=>i!=null?i(u):(s.push(u),n),g=u=>(s=new G,i!=null?i({error:u}):(s.push({error:u}),n)),l=u=>{if(o)return n;if(e?.objectMode!==!0&&u?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return p({done:!1,value:u})},d=u=>o?n:(o=!0,u!=null?g(u):p({done:!0})),m=()=>(s=new G,d(),{done:!0}),h=u=>(d(u),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:c,return:m,throw:h,push:l,end:d,get readableLength(){return s.size},onEmpty:async u=>{let x=u?.signal;if(x?.throwIfAborted(),s.isEmpty())return;let E,y;x!=null&&(E=new Promise((v,D)=>{y=()=>{D(new Ze)},x.addEventListener("abort",y)}));try{await Promise.race([a.promise,E])}finally{y!=null&&x!=null&&x?.removeEventListener("abort",y)}}},t==null)return n;let b=n;return n={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(u){return b.throw(u),t!=null&&(t(u),t=void 0),{done:!0}},return(){return b.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(u){return b.end(u),t!=null&&(t(u),t=void 0),n},get readableLength(){return b.readableLength},onEmpty:u=>b.onEmpty(u)},n}var Ye=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Ut=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function et(r,e){let{milliseconds:t,fallback:s,message:n,customTimers:i={setTimeout,clearTimeout},signal:o}=e,a,c,g=new Promise((l,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(o?.aborted){d(Ut(o));return}if(o&&(c=()=>{d(Ut(o))},o.addEventListener("abort",c,{once:!0})),r.then(l,d),t===Number.POSITIVE_INFINITY)return;let m=new Ye;a=i.setTimeout.call(void 0,()=>{if(s){try{l(s())}catch(h){d(h)}return}typeof r.cancel=="function"&&r.cancel(),n===!1?l():n instanceof Error?d(n):(m.message=n??`Promise timed out after ${t} milliseconds`,d(m))},t)}).finally(()=>{g.clear(),c&&o&&o.removeEventListener("abort",c)});return g.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},g}var ps=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function gs(r,e,t){let s,n=new Promise((i,o)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:p,removeListener:g}=ps(r),l=async(...m)=>{let h=t.multiArgs?m:m[0];if(t.filter)try{if(!await t.filter(h))return}catch(b){s(),o(b);return}c.push(h),t.count===c.length&&(s(),i(c))},d=(...m)=>{s(),o(t.rejectionMultiArgs?m:m[0])};s=()=>{for(let m of a)g(m,l);for(let m of t.rejectionEvents)a.includes(m)||g(m,d)};for(let m of a)p(m,l);for(let m of t.rejectionEvents)a.includes(m)||p(m,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(n.cancel=s,typeof t.timeout=="number"){let i=et(n,{milliseconds:t.timeout});return i.cancel=()=>{s(),i.clear()},i}return n}function tt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let s=gs(r,e,t),n=s.then(i=>i[0]);return n.cancel=s.cancel,n}var be=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}};var we=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},xe=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function bs(r){return r.reason}async function ye(r,e,t){if(e==null)return r;let s=t?.translateError??bs;if(e.aborted)return r.catch(()=>{}),Promise.reject(s(e));let n;try{return await Promise.race([r,new Promise((i,o)=>{n=()=>{o(s(e))},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var ws=Math.pow(2,20)*4,Ee=class extends z{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??ws,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new A,this.writeBuffer=new A,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(n){this.log.error("processSendQueue threw - %e",n)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let s=n=>{this.onDrainPromise?.reject(n.error??new xe)};this.addEventListener("close",s)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),ye(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=_t(),t=i=>{e.push(i.data)};this.addEventListener("message",t);let s=i=>{e.end(i.error)};this.addEventListener("close",s);let n=()=>{e.end()};this.addEventListener("remoteCloseWrite",n);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",s),this.removeEventListener("remoteCloseWrite",n)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new _(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new oe(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new _("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new _("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new _(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new _(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new ne;this.dispatchEvent(new ae(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new F))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,s=0;for(;this.writeBuffer.byteLength>0;){let n=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(n===0){e=!1;break}let i=this.writeBuffer.sublist(0,n),o=new A(i);this.writeBuffer.consume(i.byteLength);let a=this.sendData(i);if(e=a.canSendMore,s+=a.sentBytes,a.sentBytes!==o.byteLength&&(o.consume(a.sentBytes),this.writeBuffer.prepend(o)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",s,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new ie(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new K(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new K(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};function Ot(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Se=class extends z{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let s=o=>{try{this.onData(o.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",s);let n=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(o=>{o.onMuxerDrain()})};this.maConn.addEventListener("drain",n);let i=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",i)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(s=>{s.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await ye(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new P;let t=this.onCreateStream({...this.streamOptions,...e});return Ot(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new we(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=s=>{let n=this.streams.findIndex(i=>i===e);n!==-1&&this.streams.splice(n,1),s.error!=null?s.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var ve=class extends Ee{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await tt(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await tt(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};var Le=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new rt}consume(e,t=1,s={}){let n=this.getKey(e),i=this._getKeySecDuration(s),o=this.memoryStorage.incrby(n,t,i);if(o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.consumedPoints>this.points)throw this.blockDuration>0&&o.consumedPoints<=this.points+t&&(o=this.memoryStorage.set(n,o.consumedPoints,this.blockDuration)),new be("Rate limit exceeded",o);return o}penalty(e,t=1,s={}){let n=this.getKey(e),i=this._getKeySecDuration(s),o=this.memoryStorage.incrby(n,t,i);return o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o}reward(e,t=1,s={}){let n=this.getKey(e),i=this._getKeySecDuration(s),o=this.memoryStorage.incrby(n,-t,i);return o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o}block(e,t){let s=t*1e3,n=this.points+1;return this.memoryStorage.set(this.getKey(e),n,t),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:n,isFirstInDuration:!1}}set(e,t,s=0){let n=(s>=0?s:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,s),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},rt=class{storage;constructor(){this.storage=new Map}incrby(e,t,s){let n=this.storage.get(e);if(n!=null){let i=n.expiresAt!=null?n.expiresAt.getTime()-new Date().getTime():-1;return n.expiresAt==null||i>0?(n.value+=t,{remainingPoints:0,msBeforeNext:i,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,s)}return this.set(e,t,s)}set(e,t,s){let n=s*1e3,i=this.storage.get(e);i!=null&&clearTimeout(i.timeoutId);let o={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,o),n>0&&(o.timeoutId=setTimeout(()=>{this.storage.delete(e)},n),o.timeoutId.unref!=null&&o.timeoutId.unref()),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};var f;(function(r){r[r.NEW_STREAM=0]="NEW_STREAM",r[r.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",r[r.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",r[r.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",r[r.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",r[r.RESET_RECEIVER=5]="RESET_RECEIVER",r[r.RESET_INITIATOR=6]="RESET_INITIATOR"})(f||(f={}));var ee=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),st=Object.freeze({NEW_STREAM:f.NEW_STREAM,MESSAGE:f.MESSAGE_INITIATOR,CLOSE:f.CLOSE_INITIATOR,RESET:f.RESET_INITIATOR}),Pt=Object.freeze({MESSAGE:f.MESSAGE_RECEIVER,CLOSE:f.CLOSE_RECEIVER,RESET:f.RESET_RECEIVER});var te=1<<20,nt=4<<20,Ie=class{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=te,t=nt){this._buffer=new A,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(e==null||e.length===0)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw new Q("Unprocessed message queue size too large!");let t=[];for(;this._buffer.length!==0;){if(this._headerInfo==null)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(p){if(p.name==="InvalidMessageError")throw p;break}let{id:s,type:n,length:i,offset:o}=this._headerInfo;if(this._buffer.length-o<i)break;let c={id:s,type:n};(n===f.NEW_STREAM||n===f.MESSAGE_INITIATOR||n===f.MESSAGE_RECEIVER)&&(c.data=this._buffer.sublist(o,o+i)),t.push(c),this._buffer.consume(o+i),this._headerInfo=null}return t}_decodeHeader(e){let{value:t,offset:s}=zt(e),{value:n,offset:i}=zt(e,s),o=t&7;if(ee[o]==null)throw new Error(`Invalid type received: ${o}`);if(n>this._maxMessageSize)throw new Q("Message size too large");return{id:t>>3,type:o,offset:s+i,length:n}}},xs=128,Ft=127;function zt(r,e=0){let t=0,s=0,n=e,i,o=r.length;do{if(n>=o||s>49)throw e=0,new RangeError("Could not decode varint");i=r.get(n++),t+=s<28?(i&Ft)<<s:(i&Ft)*Math.pow(2,s),s+=7}while(i>=xs);return e=n-e,{value:t,offset:e}}var it=10*1024,ot=class{_pool;_poolOffset;constructor(){this._pool=I(it),this._poolOffset=0}write(e,t){let s=this._pool,n=this._poolOffset;me(e.id<<3|e.type,s,n),n+=O(e.id<<3|e.type),(e.type===f.NEW_STREAM||e.type===f.MESSAGE_INITIATOR||e.type===f.MESSAGE_RECEIVER)&&e.data!=null?(me(e.data.length,s,n),n+=O(e.data.length)):(me(0,s,n),n+=O(0));let i=s.subarray(this._poolOffset,n);it-n<100?(this._pool=I(it),this._poolOffset=0):this._poolOffset=n,t.append(i),(e.type===f.NEW_STREAM||e.type===f.MESSAGE_INITIATOR||e.type===f.MESSAGE_RECEIVER)&&e.data!=null&&t.append(e.data)}},ys=new ot;function re(r){let e=new A;return ys.write(r,e),e}var at=class extends ve{streamId;types;maxDataSize;muxer;constructor(e){super(e),this.types=e.direction==="outbound"?st:Pt,this.maxDataSize=e.maxDataSize,this.muxer=e.muxer,this.streamId=parseInt(this.id.substring(1)),e.direction==="outbound"&&queueMicrotask(()=>{this.muxer.send(re({id:this.streamId,type:st.NEW_STREAM,data:new A(Je(this.id))}))})}sendData(e){let t=new A,s=e.byteLength;for(;e.byteLength>0;){let n=Math.min(e.byteLength,this.maxDataSize),i=e.sublist(0,n);e=e.sublist(n),t.append(re({id:this.streamId,type:this.types.MESSAGE,data:i}))}return{sentBytes:s,canSendMore:this.muxer.send(t)}}sendReset(){return this.muxer.send(re({id:this.streamId,type:this.types.RESET}))}async sendCloseWrite(e){this.muxer.send(re({id:this.streamId,type:this.types.CLOSE})),e?.signal?.throwIfAborted()}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}};function Vt(r){let{id:e,muxer:t,direction:s,maxMsgSize:n=te}=r;return new at({...r,id:s==="outbound"?`i${e}`:`r${e}`,direction:s,maxDataSize:n,muxer:t,log:r.log.newScope(`${s}:${e}`),protocol:""})}var Es=5;function Ss(r){let e={...r,type:`${ee[r.type]} (${r.type})`};return r.type===f.NEW_STREAM&&(e.data=de(r.data.subarray())),(r.type===f.MESSAGE_INITIATOR||r.type===f.MESSAGE_RECEIVER)&&(e.data=de(r.data.subarray(),"base16")),e}var Ae=class extends Se{_streamId;rateLimiter;maxMessageSize;maxUnprocessedMessageQueueSize;decoder;constructor(e,t){super(e,{...t,protocol:"/mplex/6.7.0",name:"mplex"}),this._streamId=0,this.maxMessageSize=t.maxMessageSize??te,this.maxUnprocessedMessageQueueSize=t.maxUnprocessedMessageQueueSize??nt,this.decoder=new Ie(this.maxMessageSize,this.maxUnprocessedMessageQueueSize),this.rateLimiter=new Le({points:t.disconnectThreshold??Es,duration:1})}onData(e){for(let t of this.decoder.write(e))this.handleMessage(t)}onCreateStream(e){if(this.status!=="open")throw new P("Muxer already closed");let t=this._streamId++;return this._newStream(t,"outbound",e)}_newStream(e,t,s){return this.log("new %s stream %s",t,e),Vt({...s,id:e,direction:t,maxMsgSize:this.maxMessageSize,log:this.log,muxer:this})}handleMessage(e){if(this.log.enabled&&this.log.trace("incoming message",Ss(e)),e.type===f.NEW_STREAM){try{this.rateLimiter.consume("new-stream",1)}catch{this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),this.abort(new Error("Too many open streams"));return}let n=this._newStream(e.id,"inbound",this.streamOptions);this.onRemoteStream(n);return}let t=`${(e.type&1)===1?"i":"r"}${e.id}`,s=this.streams.find(n=>n.id===t);if(s==null){this.log("missing stream %s for message type %s",t,ee[e.type]);try{this.rateLimiter.consume("missing-stream",1)}catch{this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),this.abort(new Error("Too many messages for missing streams"));return}return}try{switch(e.type){case f.MESSAGE_INITIATOR:case f.MESSAGE_RECEIVER:s.onData(e.data);break;case f.CLOSE_INITIATOR:case f.CLOSE_RECEIVER:s.onRemoteCloseWrite();break;case f.RESET_INITIATOR:case f.RESET_RECEIVER:s.onRemoteReset();break;default:this.log("unknown message type")}}catch(n){this.log.error("error while processing message - %e",n),s.abort(n)}}};var ct=class{protocol="/mplex/6.7.0";_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@libp2p/mplex";[ut]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new Ae(e,{...this._init})}};function vs(r={}){return()=>new ct(r)}return qt(Ls);})();
2
+ "use strict";var Libp2PMplex=(()=>{var Te=Object.defineProperty;var qt=Object.getOwnPropertyDescriptor;var jt=Object.getOwnPropertyNames;var Gt=Object.prototype.hasOwnProperty;var L=(r,e)=>{for(var t in e)Te(r,t,{get:e[t],enumerable:!0})},Kt=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of jt(e))!Gt.call(r,n)&&n!==t&&Te(r,n,{get:()=>e[n],enumerable:!(s=qt(e,n))||s.enumerable});return r};var Qt=r=>Kt(Te({},"__esModule",{value:!0}),r);var Ts={};L(Ts,{mplex:()=>Ds});var F=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},oe=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var U=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Q=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var X=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var ae=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},z=class extends Event{error;local;constructor(e,t,s){super("close",s),this.error=t,this.local=e}},ce=class extends z{constructor(e,t){super(!0,e,t)}},ue=class extends z{constructor(e,t){super(!1,e,t)}};function Xt(r){return typeof r?.handleEvent=="function"}function Ht(r){return(r!==!0&&r!==!1&&r?.once)??!1}var V=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,s){let n=Ht(s);super.addEventListener(e,o=>{if(n){let a=this.#e.get(o.type);a!=null&&(a=a.filter(({callback:c})=>c!==t),this.#e.set(o.type,a))}Xt(t)?t.handleEvent(o):t(o)},s);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:t,once:n})}removeEventListener(e,t,s){super.removeEventListener(e.toString(),t??null,s);let n=this.#e.get(e);n!=null&&(n=n.filter(({callback:i})=>i!==t),this.#e.set(e,n))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var ht=Symbol.for("@libp2p/service-capabilities");var Ue={};L(Ue,{base58btc:()=>T,base58flickr:()=>nr});var on=new Uint8Array(0);function ft(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function C(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return O(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return O(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function lt(r){return new TextEncoder().encode(r)}function dt(r){return new TextDecoder().decode(r)}function Jt(r){return r?.buffer instanceof ArrayBuffer}function O(r){return Jt(r)?r:r.slice()}function Zt(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),s=0;s<t.length;s++)t[s]=255;for(var n=0;n<r.length;n++){var i=r.charAt(n),o=i.charCodeAt(0);if(t[o]!==255)throw new TypeError(i+" is ambiguous");t[o]=n}var a=r.length,c=r.charAt(0),p=Math.log(a)/Math.log(256),g=Math.log(256)/Math.log(a);function l(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var b=0,u=0,w=0,E=h.length;w!==E&&h[w]===0;)w++,b++;for(var x=(E-w)*g+1>>>0,v=new Uint8Array(x);w!==E;){for(var A=h[w],B=0,D=x-1;(A!==0||B<u)&&D!==-1;D--,B++)A+=256*v[D]>>>0,v[D]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");u=B,w++}for(var R=x-u;R!==x&&v[R]===0;)R++;for(var ie=c.repeat(b);R<x;++R)ie+=r.charAt(v[R]);return ie}function d(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var b=0;if(h[b]!==" "){for(var u=0,w=0;h[b]===c;)u++,b++;for(var E=(h.length-b)*p+1>>>0,x=new Uint8Array(E);h[b];){var v=t[h.charCodeAt(b)];if(v===255)return;for(var A=0,B=E-1;(v!==0||A<w)&&B!==-1;B--,A++)v+=a*x[B]>>>0,x[B]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");w=A,b++}if(h[b]!==" "){for(var D=E-w;D!==E&&x[D]===0;)D++;for(var R=new Uint8Array(u+(E-D)),ie=u;D!==E;)R[ie++]=x[D++];return R}}}function m(h){var b=d(h);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:d,decode:m}}var Yt=Zt,er=Yt,pt=er;var Re=class{name;prefix;baseEncode;constructor(e,t,s){this.name=e,this.prefix=t,this.baseEncode=s}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ce=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,s){this.name=e,this.prefix=t;let n=t.codePointAt(0);if(n===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=s}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return gt(this,e)}},Me=class{decoders;constructor(e){this.decoders=e}or(e){return gt(this,e)}decode(e){let t=e[0],s=this.decoders[t];if(s!=null)return s.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function gt(r,e){return new Me({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Be=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,s,n){this.name=e,this.prefix=t,this.baseEncode=s,this.baseDecode=n,this.encoder=new Re(e,t,s),this.decoder=new Ce(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function k({name:r,prefix:e,encode:t,decode:s}){return new Be(r,e,t,s)}function N({name:r,prefix:e,alphabet:t}){let{encode:s,decode:n}=pt(t,r);return k({prefix:e,name:r,encode:s,decode:i=>C(n(i))})}function tr(r,e,t,s){let n=r.length;for(;r[n-1]==="=";)--n;let i=new Uint8Array(n*t/8|0),o=0,a=0,c=0;for(let p=0;p<n;++p){let g=e[r[p]];if(g===void 0)throw new SyntaxError(`Non-${s} character`);a=a<<t|g,o+=t,o>=8&&(o-=8,i[c++]=255&a>>o)}if(o>=t||(255&a<<8-o)!==0)throw new SyntaxError("Unexpected end of data");return i}function rr(r,e,t){let s=e[e.length-1]==="=",n=(1<<t)-1,i="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,i+=e[n&a>>o];if(o!==0&&(i+=e[n&a<<t-o]),s)for(;(i.length*t&7)!==0;)i+="=";return i}function sr(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function y({name:r,prefix:e,bitsPerChar:t,alphabet:s}){let n=sr(s);return k({prefix:e,name:r,encode(i){return rr(i,s,t)},decode(i){return tr(i,n,t,r)}})}var T=N({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),nr=N({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ne={};L(Ne,{base32:()=>$,base32hex:()=>cr,base32hexpad:()=>hr,base32hexpadupper:()=>fr,base32hexupper:()=>ur,base32pad:()=>or,base32padupper:()=>ar,base32upper:()=>ir,base32z:()=>lr});var $=y({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ir=y({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),or=y({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ar=y({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),cr=y({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ur=y({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),hr=y({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),fr=y({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),lr=y({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var _e={};L(_e,{base36:()=>H,base36upper:()=>dr});var H=N({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),dr=N({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var mr=wt,bt=128,pr=127,gr=~pr,br=Math.pow(2,31);function wt(r,e,t){e=e||[],t=t||0;for(var s=t;r>=br;)e[t++]=r&255|bt,r/=128;for(;r&gr;)e[t++]=r&255|bt,r>>>=7;return e[t]=r|0,wt.bytes=t-s+1,e}var yr=Oe,wr=128,yt=127;function Oe(r,s){var t=0,s=s||0,n=0,i=s,o,a=r.length;do{if(i>=a)throw Oe.bytes=0,new RangeError("Could not decode varint");o=r[i++],t+=n<28?(o&yt)<<n:(o&yt)*Math.pow(2,n),n+=7}while(o>=wr);return Oe.bytes=i-s,t}var xr=Math.pow(2,7),Er=Math.pow(2,14),Sr=Math.pow(2,21),vr=Math.pow(2,28),Lr=Math.pow(2,35),Ir=Math.pow(2,42),Ar=Math.pow(2,49),Dr=Math.pow(2,56),Tr=Math.pow(2,63),Rr=function(r){return r<xr?1:r<Er?2:r<Sr?3:r<vr?4:r<Lr?5:r<Ir?6:r<Ar?7:r<Dr?8:r<Tr?9:10},Cr={encode:mr,decode:yr,encodingLength:Rr},Mr=Cr,J=Mr;function Z(r,e=0){return[J.decode(r,e),J.decode.bytes]}function W(r,e,t=0){return J.encode(r,e,t),e}function q(r){return J.encodingLength(r)}function G(r,e){let t=e.byteLength,s=q(r),n=s+q(t),i=new Uint8Array(n+t);return W(r,i,0),W(t,i,s),i.set(e,n),new j(r,t,e,i)}function xt(r){let e=C(r),[t,s]=Z(e),[n,i]=Z(e.subarray(s)),o=e.subarray(s+i);if(o.byteLength!==n)throw new Error("Incorrect length");return new j(t,n,o,e)}function Et(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ft(r.bytes,t.bytes)}}var j=class{code;size;digest;bytes;constructor(e,t,s,n){this.code=e,this.size=t,this.digest=O(s),this.bytes=O(n)}};function St(r,e){let{bytes:t,version:s}=r;return s===0?Ur(t,Pe(r),e??T.encoder):Nr(t,Pe(r),e??$.encoder)}var vt=new WeakMap;function Pe(r){let e=vt.get(r);if(e==null){let t=new Map;return vt.set(r,t),t}return e}var fe=class r{code;version;multihash;bytes;"/";constructor(e,t,s,n){this.code=t,this.version=e,this.multihash=s,this.bytes=O(n),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==ee)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==_r)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,s=G(e,t);return r.createV1(this.code,s)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let s=t;return s!=null&&e.code===s.code&&e.version===s.version&&Et(e.multihash,s.multihash)}toString(e){return St(this,e)}toJSON(){return{"/":St(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:s,code:n,multihash:i,bytes:o}=t;return new r(s,n,i,o??Lt(s,n,i.bytes))}else if(t[Or]===!0){let{version:s,multihash:n,code:i}=t,o=xt(n);return r.create(s,i,o)}else return null}static create(e,t,s){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(s.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==ee)throw new Error(`Version 0 CID must use dag-pb (code: ${ee}) block encoding`);return new r(e,t,s,s.bytes)}case 1:{let n=Lt(e,t,s.bytes);return new r(e,t,s,n)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,ee,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,s]=r.decodeFirst(e);if(s.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),s=t.size-t.multihashSize,n=C(e.subarray(s,s+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=n.subarray(t.multihashSize-t.digestSize),o=new j(t.multihashCode,t.digestSize,i,n);return[t.version===0?r.createV0(o):r.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,s=()=>{let[l,d]=Z(e.subarray(t));return t+=d,l},n=s(),i=ee;if(n===18?(n=0,t=0):i=s(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let o=t,a=s(),c=s(),p=t+c,g=p-o;return{version:n,codec:i,multihashCode:a,digestSize:c,multihashSize:g,size:p}}static parse(e,t){let[s,n]=Br(e,t),i=r.decode(n);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Pe(i).set(s,e),i}};function Br(r,e){switch(r[0]){case"Q":{let t=e??T;return[T.prefix,t.decode(`${T.prefix}${r}`)]}case T.prefix:{let t=e??T;return[T.prefix,t.decode(r)]}case $.prefix:{let t=e??$;return[$.prefix,t.decode(r)]}case H.prefix:{let t=e??H;return[H.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Ur(r,e,t){let{prefix:s}=t;if(s!==T.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let n=e.get(s);if(n==null){let i=t.encode(r).slice(1);return e.set(s,i),i}else return n}function Nr(r,e,t){let{prefix:s}=t,n=e.get(s);if(n==null){let i=t.encode(r);return e.set(s,i),i}else return n}var ee=112,_r=18;function Lt(r,e,t){let s=q(r),n=s+q(e),i=new Uint8Array(n+t.byteLength);return W(r,i,0),W(e,i,s),i.set(t,n),i}var Or=Symbol.for("@ipld/js-cid/CID");var Fe={};L(Fe,{identity:()=>zr});var It=0,Pr="identity",At=C;function Fr(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return G(It,At(r))}var zr={code:It,name:Pr,encode:At,digest:Fr};function M(r=0){return new Uint8Array(r)}function te(r=0){return new Uint8Array(r)}function ze(r,e){e==null&&(e=r.reduce((n,i)=>n+i.length,0));let t=te(e),s=0;for(let n of r)t.set(n,s),s+=n.length;return t}function Dt(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var Rt=Symbol.for("@achingbrain/uint8arraylist");function Tt(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let s of r){let n=t+s.byteLength;if(e<n)return{buf:s,index:e-t};t=n}throw new RangeError("index is out of bounds")}function le(r){return!!r?.[Rt]}var I=class r{bufs;length;[Rt]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let s of e)if(s instanceof Uint8Array)t+=s.byteLength,this.bufs.push(s);else if(le(s)){t+=s.byteLength;for(let n of s.bufs)this.bufs.push(n)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let s of e.reverse())if(s instanceof Uint8Array)t+=s.byteLength,this.bufs.unshift(s);else if(le(s))t+=s.byteLength,this.bufs.unshift(...s.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Tt(this.bufs,e);return t.buf[t.index]}set(e,t){let s=Tt(this.bufs,e);s.buf[s.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let s=0;s<e.length;s++)this.set(t+s,e[s]);else if(le(e))for(let s=0;s<e.length;s++)this.set(t+s,e.get(s));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:s,length:n}=this._subList(e,t);return ze(s,n)}subarray(e,t){let{bufs:s,length:n}=this._subList(e,t);return s.length===1?s[0]:ze(s,n)}sublist(e,t){let{bufs:s,length:n}=this._subList(e,t),i=new r;return i.length=n,i.bufs=s,i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let s=[],n=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],a=n,c=a+o.byteLength;if(n=c,e>=c)continue;let p=e>=a&&e<c,g=t>a&&t<=c;if(p&&g){if(e===a&&t===c){s.push(o);break}let l=e-a;s.push(o.subarray(l,l+(t-e)));break}if(p){if(e===0){s.push(o);continue}s.push(o.subarray(e-a));continue}if(g){if(t===c){s.push(o);break}s.push(o.subarray(0,t-a));break}s.push(o)}return{bufs:s,length:t-e}}indexOf(e,t=0){if(!le(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let s=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let n=s.byteLength;if(n===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let l=0;l<i;l++)o[l]=-1;for(let l=0;l<n;l++)o[s[l]]=l;let a=o,c=this.byteLength-s.byteLength,p=s.byteLength-1,g;for(let l=t;l<=c;l+=g){g=0;for(let d=p;d>=0;d--){let m=this.get(l+d);if(s[d]!==m){g=Math.max(1,d-a[m]);break}}if(g===0)return l}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let s=te(1);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt8(0,t),this.write(s,e)}getInt16(e,t){let s=this.subarray(e,e+2);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt16(0,t)}setInt16(e,t,s){let n=M(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,s),this.write(n,e)}getInt32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getInt32(0,t)}setInt32(e,t,s){let n=M(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,s),this.write(n,e)}getBigInt64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigInt64(0,t)}setBigInt64(e,t,s){let n=M(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,s),this.write(n,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let s=te(1);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint8(0,t),this.write(s,e)}getUint16(e,t){let s=this.subarray(e,e+2);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint16(0,t)}setUint16(e,t,s){let n=M(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,s),this.write(n,e)}getUint32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getUint32(0,t)}setUint32(e,t,s){let n=M(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,s),this.write(n,e)}getBigUint64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigUint64(0,t)}setBigUint64(e,t,s){let n=M(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,s),this.write(n,e)}getFloat32(e,t){let s=this.subarray(e,e+4);return new DataView(s.buffer,s.byteOffset,s.byteLength).getFloat32(0,t)}setFloat32(e,t,s){let n=M(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,s),this.write(n,e)}getFloat64(e,t){let s=this.subarray(e,e+8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getFloat64(0,t)}setFloat64(e,t,s){let n=M(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,s),this.write(n,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!Dt(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let s=new r;return s.bufs=e,t==null&&(t=e.reduce((n,i)=>n+i.byteLength,0)),s.length=t,s}};var Ve={};L(Ve,{base10:()=>Vr});var Vr=N({prefix:"9",name:"base10",alphabet:"0123456789"});var ke={};L(ke,{base16:()=>kr,base16upper:()=>$r});var kr=y({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),$r=y({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var $e={};L($e,{base2:()=>Wr});var Wr=y({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var We={};L(We,{base256emoji:()=>Qr});var Ct=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}"),qr=Ct.reduce((r,e,t)=>(r[t]=e,r),[]),jr=Ct.reduce((r,e,t)=>{let s=e.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${e}`);return r[s]=t,r},[]);function Gr(r){return r.reduce((e,t)=>(e+=qr[t],e),"")}function Kr(r){let e=[];for(let t of r){let s=t.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${t}`);let n=jr[s];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Qr=k({prefix:"\u{1F680}",name:"base256emoji",encode:Gr,decode:Kr});var qe={};L(qe,{base64:()=>Xr,base64pad:()=>Hr,base64url:()=>Jr,base64urlpad:()=>Zr});var Xr=y({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Hr=y({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Jr=y({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Zr=y({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var je={};L(je,{base8:()=>Yr});var Yr=y({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ge={};L(Ge,{identity:()=>es});var es=k({prefix:"\0",name:"identity",encode:r=>dt(r),decode:r=>lt(r)});var qn=new TextEncoder,jn=new TextDecoder;var Xe={};L(Xe,{sha256:()=>ns,sha512:()=>is});var ss=20;function Qe({name:r,code:e,encode:t,minDigestLength:s,maxDigestLength:n}){return new Ke(r,e,t,s,n)}var Ke=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,s,n,i){this.name=e,this.code=t,this.encode=s,this.minDigestLength=n??ss,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let s=this.encode(e);return s instanceof Uint8Array?Mt(s,this.code,t?.truncate):s.then(n=>Mt(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Mt(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return G(e,r)}function Ut(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ns=Qe({name:"sha2-256",code:18,encode:Ut("SHA-256")}),is=Qe({name:"sha2-512",code:19,encode:Ut("SHA-512")});var He={...Ge,...$e,...je,...Ve,...ke,...Ne,..._e,...Ue,...qe,...We},si={...Xe,...Fe};function _(r=0){return new Uint8Array(r)}function _t(r,e,t,s){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:s}}}var Nt=_t("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Je=_t("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=_(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),os={utf8:Nt,"utf-8":Nt,hex:He.base16,latin1:Je,ascii:Je,binary:Je,...He},de=os;function Ze(r,e="utf8"){let t=de[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function me(r,e="utf8"){let t=de[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function pe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ge=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},K=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ge(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new ge(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Ye=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Ot(r={}){return cs(t=>{let s=t.shift();if(s==null)return{done:!0};if(s.error!=null)throw s.error;return{done:s.done===!0,value:s.value}},r)}function cs(r,e){e=e??{};let t=e.onEnd,s=new K,n,i,o,a=pe(),c=async()=>{try{return s.isEmpty()?o?{done:!0}:await new Promise((u,w)=>{i=E=>{i=null,s.push(E);try{u(r(s))}catch(x){w(x)}return n}}):r(s)}finally{s.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=pe()})}},p=u=>i!=null?i(u):(s.push(u),n),g=u=>(s=new K,i!=null?i({error:u}):(s.push({error:u}),n)),l=u=>{if(o)return n;if(e?.objectMode!==!0&&u?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return p({done:!1,value:u})},d=u=>o?n:(o=!0,u!=null?g(u):p({done:!0})),m=()=>(s=new K,d(),{done:!0}),h=u=>(d(u),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:c,return:m,throw:h,push:l,end:d,get readableLength(){return s.size},onEmpty:async u=>{let w=u?.signal;if(w?.throwIfAborted(),s.isEmpty())return;let E,x;w!=null&&(E=new Promise((v,A)=>{x=()=>{A(new Ye)},w.addEventListener("abort",x)}));try{await Promise.race([a.promise,E])}finally{x!=null&&w!=null&&w?.removeEventListener("abort",x)}}},t==null)return n;let b=n;return n={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(u){return b.throw(u),t!=null&&(t(u),t=void 0),{done:!0}},return(){return b.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(u){return b.end(u),t!=null&&(t(u),t=void 0),n},get readableLength(){return b.readableLength},onEmpty:u=>b.onEmpty(u)},n}var et=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},Pt=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function tt(r,e){let{milliseconds:t,fallback:s,message:n,customTimers:i={setTimeout,clearTimeout},signal:o}=e,a,c,g=new Promise((l,d)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(o?.aborted){d(Pt(o));return}if(o&&(c=()=>{d(Pt(o))},o.addEventListener("abort",c,{once:!0})),r.then(l,d),t===Number.POSITIVE_INFINITY)return;let m=new et;a=i.setTimeout.call(void 0,()=>{if(s){try{l(s())}catch(h){d(h)}return}typeof r.cancel=="function"&&r.cancel(),n===!1?l():n instanceof Error?d(n):(m.message=n??`Promise timed out after ${t} milliseconds`,d(m))},t)}).finally(()=>{g.clear(),c&&o&&o.removeEventListener("abort",c)});return g.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},g}var us=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function hs(r,e,t){let s,n=new Promise((i,o)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:p,removeListener:g}=us(r),l=async(...m)=>{let h=t.multiArgs?m:m[0];if(t.filter)try{if(!await t.filter(h))return}catch(b){s(),o(b);return}c.push(h),t.count===c.length&&(s(),i(c))},d=(...m)=>{s(),o(t.rejectionMultiArgs?m:m[0])};s=()=>{for(let m of a)g(m,l);for(let m of t.rejectionEvents)a.includes(m)||g(m,d)};for(let m of a)p(m,l);for(let m of t.rejectionEvents)a.includes(m)||p(m,d);t.signal&&t.signal.addEventListener("abort",()=>{d(t.signal.reason)},{once:!0}),t.resolveImmediately&&i(c)});if(n.cancel=s,typeof t.timeout=="number"){let i=tt(n,{milliseconds:t.timeout});return i.cancel=()=>{s(),i.clear()},i}return n}function rt(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let s=hs(r,e,t),n=s.then(i=>i[0]);return n.cancel=s.cancel,n}var be=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}};var ye=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},we=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function fs(r){return r.reason}async function xe(r,e,t){if(e==null)return r;let s=t?.translateError??fs;if(e.aborted)return r.catch(()=>{}),Promise.reject(s(e));let n;try{return await Promise.race([r,new Promise((i,o)=>{n=()=>{o(s(e))},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var ls=Math.pow(2,20)*4,Ee=class extends V{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??ls,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new I,this.writeBuffer=new I,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,queueMicrotask(()=>{try{this.processSendQueue()}catch(n){this.log.error("processSendQueue threw - %e",n)}})),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let s=n=>{this.onDrainPromise?.reject(n.error??new we)};this.addEventListener("close",s)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),xe(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=Ot(),t=i=>{e.push(i.data)};this.addEventListener("message",t);let s=i=>{e.end(i.error)};this.addEventListener("close",s);let n=()=>{e.end()};this.addEventListener("remoteCloseWrite",n);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",s),this.removeEventListener("remoteCloseWrite",n)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new U(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new ce(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new U("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new U("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new U(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new U(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new oe;this.dispatchEvent(new ue(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new z))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;if(this.writeStatus!=="writable"&&this.writeStatus!=="closing")return this.log.trace("not processing send queue as stream is %s",this.writeStatus),!1;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,s=0;for(;this.writeBuffer.byteLength>0;){let n=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(n===0){e=!1;break}let i=this.writeBuffer.sublist(0,n),o=new I(i);this.writeBuffer.consume(i.byteLength);let a;try{a=this.sendData(i)}catch(c){throw this.writeBuffer.prepend(o),this.abort(c),c}if(e=a.canSendMore,s+=a.sentBytes,a.sentBytes!==o.byteLength&&(o.consume(a.sentBytes),this.writeBuffer.prepend(o)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",s,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new ae(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Q(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new Q(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};function Ft(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Se=class extends V{streams;protocol;status;log;maConn;streamOptions;earlyStreams;maxEarlyStreams;metrics;constructor(e,t){super(),this.maConn=e,this.protocol=t.protocol,this.streams=[],this.earlyStreams=[],this.status="open",this.log=e.log.newScope(t.name),this.streamOptions=t.streamOptions,this.maxEarlyStreams=t.maxEarlyStreams??10,this.metrics=t.metrics;let s=o=>{try{this.onData(o.data)}catch(a){this.abort(a),this.maConn.abort(a)}};this.maConn.addEventListener("message",s);let n=()=>{this.log("underlying stream drained, signal %d streams to continue writing",this.streams.length),this.streams.forEach(o=>{o.onMuxerDrain()})};this.maConn.addEventListener("drain",n);let i=()=>{this.log("underlying stream closed with status %s and %d streams",this.status,this.streams.length),this.onTransportClosed()};this.maConn.addEventListener("close",i)}send(e){let t=this.maConn.send(e);return t===!1&&(this.log("underlying stream saturated, signal %d streams to pause writing",this.streams.length),this.streams.forEach(s=>{s.onMuxerNeedsDrain()})),t}async close(e){this.status==="closed"||this.status==="closing"||(this.status="closing",await xe(Promise.all([...this.streams].map(async t=>{await t.close(e)})),e?.signal),this.status="closed")}abort(e){this.status!=="closed"&&(this.status="closing",[...this.streams].forEach(t=>{t.abort(e)}),this.status="closed")}onTransportClosed(e){this.status="closing";try{[...this.streams].forEach(t=>{t.onTransportClosed(e)})}catch(t){this.abort(t)}this.status="closed"}async createStream(e){if(this.status!=="open")throw new F;let t=this.onCreateStream({...this.streamOptions,...e});return Ft(t)&&(t=await t),this.streams.push(t),this.cleanUpStream(t),t}onRemoteStream(e){if(this.streams.push(e),this.cleanUpStream(e),this.listenerCount("stream")===0){this.earlyStreams.push(e),this.earlyStreams.length>this.maxEarlyStreams&&this.abort(new ye(`Too many early streams were opened - ${this.earlyStreams.length}/${this.maxEarlyStreams}`));return}this.safeDispatchEvent("stream",{detail:e})}cleanUpStream(e){let t=s=>{let n=this.streams.findIndex(i=>i===e);n!==-1&&this.streams.splice(n,1),s.error!=null?s.local?this.metrics?.increment({[`${e.direction}_stream_reset`]:!0}):this.metrics?.increment({[`${e.direction}_stream_abort`]:!0}):this.metrics?.increment({[`${e.direction}_stream_end`]:!0})};e.addEventListener("close",t),this.metrics?.increment({[`${e.direction}_stream`]:!0})}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="stream"&&this.earlyStreams.length>0&&queueMicrotask(()=>{this.earlyStreams.forEach(t=>{this.safeDispatchEvent("stream",{detail:t})}),this.earlyStreams=[]})}};var ve=class extends Ee{id;protocol;constructor(e){super(e),this.id=e.id,this.protocol=e.protocol??""}async close(e){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.writeStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await rt(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData),await rt(this,"drain",{...e,rejectionEvents:["close"]}),this.log("write queue drained, closing writable end of stream, %d unsent bytes, sending %s",this.writeBuffer.byteLength,this.sendingData)),await this.sendCloseWrite(e),this.writeStatus="closed",this.log("closed writable end gracefully"),this.remoteWriteStatus==="closed"&&this.onTransportClosed())}async closeRead(e){this.readStatus==="closing"||this.readStatus==="closed"||(this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",await this.sendCloseRead(e),this.readStatus="closed",this.log("closed readable end gracefully"))}};var Le=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new st}consume(e,t=1,s={}){let n=this.getKey(e),i=this._getKeySecDuration(s),o=this.memoryStorage.incrby(n,t,i);if(o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.consumedPoints>this.points)throw this.blockDuration>0&&o.consumedPoints<=this.points+t&&(o=this.memoryStorage.set(n,o.consumedPoints,this.blockDuration)),new be("Rate limit exceeded",o);return o}penalty(e,t=1,s={}){let n=this.getKey(e),i=this._getKeySecDuration(s),o=this.memoryStorage.incrby(n,t,i);return o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o}reward(e,t=1,s={}){let n=this.getKey(e),i=this._getKeySecDuration(s),o=this.memoryStorage.incrby(n,-t,i);return o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o}block(e,t){let s=t*1e3,n=this.points+1;return this.memoryStorage.set(this.getKey(e),n,t),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:n,isFirstInDuration:!1}}set(e,t,s=0){let n=(s>=0?s:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,s),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},st=class{storage;constructor(){this.storage=new Map}incrby(e,t,s){let n=this.storage.get(e);if(n!=null){let i=n.expiresAt!=null?n.expiresAt.getTime()-new Date().getTime():-1;return n.expiresAt==null||i>0?(n.value+=t,{remainingPoints:0,msBeforeNext:i,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,s)}return this.set(e,t,s)}set(e,t,s){let n=s*1e3,i=this.storage.get(e);i!=null&&clearTimeout(i.timeoutId);let o={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,o),n>0&&(o.timeoutId=setTimeout(()=>{this.storage.delete(e)},n),o.timeoutId.unref!=null&&o.timeoutId.unref()),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};var f;(function(r){r[r.NEW_STREAM=0]="NEW_STREAM",r[r.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",r[r.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",r[r.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",r[r.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",r[r.RESET_RECEIVER=5]="RESET_RECEIVER",r[r.RESET_INITIATOR=6]="RESET_INITIATOR"})(f||(f={}));var re=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),nt=Object.freeze({NEW_STREAM:f.NEW_STREAM,MESSAGE:f.MESSAGE_INITIATOR,CLOSE:f.CLOSE_INITIATOR,RESET:f.RESET_INITIATOR}),zt=Object.freeze({MESSAGE:f.MESSAGE_RECEIVER,CLOSE:f.CLOSE_RECEIVER,RESET:f.RESET_RECEIVER});var se=1<<20,it=4<<20,Ie=class{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=se,t=it){this._buffer=new I,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(e==null||e.length===0)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw new X("Unprocessed message queue size too large!");let t=[];for(;this._buffer.length!==0;){if(this._headerInfo==null)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(p){if(p.name==="InvalidMessageError")throw p;break}let{id:s,type:n,length:i,offset:o}=this._headerInfo;if(this._buffer.length-o<i)break;let c={id:s,type:n};(n===f.NEW_STREAM||n===f.MESSAGE_INITIATOR||n===f.MESSAGE_RECEIVER)&&(c.data=this._buffer.sublist(o,o+i)),t.push(c),this._buffer.consume(o+i),this._headerInfo=null}return t}_decodeHeader(e){let{value:t,offset:s}=kt(e),{value:n,offset:i}=kt(e,s),o=t&7;if(re[o]==null)throw new Error(`Invalid type received: ${o}`);if(n>this._maxMessageSize)throw new X("Message size too large");return{id:t>>3,type:o,offset:s+i,length:n}}},ds=128,Vt=127;function kt(r,e=0){let t=0,s=0,n=e,i,o=r.length;do{if(n>=o||s>49)throw e=0,new RangeError("Could not decode varint");i=r.get(n++),t+=s<28?(i&Vt)<<s:(i&Vt)*Math.pow(2,s),s+=7}while(i>=ds);return e=n-e,{value:t,offset:e}}function $t(r=0){return new Uint8Array(r)}var ms=Math.pow(2,7),ps=Math.pow(2,14),gs=Math.pow(2,21),bs=Math.pow(2,28),ys=Math.pow(2,35),ws=Math.pow(2,42),xs=Math.pow(2,49),S=128;function P(r){if(r<ms)return 1;if(r<ps)return 2;if(r<gs)return 3;if(r<bs)return 4;if(r<ys)return 5;if(r<ws)return 6;if(r<xs)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Es(r,e,t=0){switch(P(r)){case 8:e[t++]=r&255|S,r/=128;case 7:e[t++]=r&255|S,r/=128;case 6:e[t++]=r&255|S,r/=128;case 5:e[t++]=r&255|S,r/=128;case 4:e[t++]=r&255|S,r>>>=7;case 3:e[t++]=r&255|S,r>>>=7;case 2:e[t++]=r&255|S,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Ss(r,e,t=0){switch(P(r)){case 8:e.set(t++,r&255|S),r/=128;case 7:e.set(t++,r&255|S),r/=128;case 6:e.set(t++,r&255|S),r/=128;case 5:e.set(t++,r&255|S),r/=128;case 4:e.set(t++,r&255|S),r>>>=7;case 3:e.set(t++,r&255|S),r>>>=7;case 2:e.set(t++,r&255|S),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Ae(r,e,t=0){return e==null&&(e=$t(P(r))),e instanceof Uint8Array?Es(r,e,t):Ss(r,e,t)}var ot=10*1024,at=class{_pool;_poolOffset;constructor(){this._pool=_(ot),this._poolOffset=0}write(e,t){let s=this._pool,n=this._poolOffset;Ae(e.id<<3|e.type,s,n),n+=P(e.id<<3|e.type),(e.type===f.NEW_STREAM||e.type===f.MESSAGE_INITIATOR||e.type===f.MESSAGE_RECEIVER)&&e.data!=null?(Ae(e.data.length,s,n),n+=P(e.data.length)):(Ae(0,s,n),n+=P(0));let i=s.subarray(this._poolOffset,n);ot-n<100?(this._pool=_(ot),this._poolOffset=0):this._poolOffset=n,t.append(i),(e.type===f.NEW_STREAM||e.type===f.MESSAGE_INITIATOR||e.type===f.MESSAGE_RECEIVER)&&e.data!=null&&t.append(e.data)}},Ls=new at;function ne(r){let e=new I;return Ls.write(r,e),e}var ct=class extends ve{streamId;types;maxDataSize;muxer;constructor(e){super(e),this.types=e.direction==="outbound"?nt:zt,this.maxDataSize=e.maxDataSize,this.muxer=e.muxer,this.streamId=parseInt(this.id.substring(1)),e.direction==="outbound"&&queueMicrotask(()=>{this.muxer.send(ne({id:this.streamId,type:nt.NEW_STREAM,data:new I(Ze(this.id))}))})}sendData(e){let t=new I,s=e.byteLength;for(;e.byteLength>0;){let n=Math.min(e.byteLength,this.maxDataSize),i=e.sublist(0,n);e=e.sublist(n),t.append(ne({id:this.streamId,type:this.types.MESSAGE,data:i}))}return{sentBytes:s,canSendMore:this.muxer.send(t)}}sendReset(){return this.muxer.send(ne({id:this.streamId,type:this.types.RESET}))}async sendCloseWrite(e){this.muxer.send(ne({id:this.streamId,type:this.types.CLOSE})),e?.signal?.throwIfAborted()}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}};function Wt(r){let{id:e,muxer:t,direction:s,maxMsgSize:n=se}=r;return new ct({...r,id:s==="outbound"?`i${e}`:`r${e}`,direction:s,maxDataSize:n,muxer:t,log:r.log.newScope(`${s}:${e}`),protocol:""})}var Is=5;function As(r){let e={...r,type:`${re[r.type]} (${r.type})`};return r.type===f.NEW_STREAM&&(e.data=me(r.data.subarray())),(r.type===f.MESSAGE_INITIATOR||r.type===f.MESSAGE_RECEIVER)&&(e.data=me(r.data.subarray(),"base16")),e}var De=class extends Se{_streamId;rateLimiter;maxMessageSize;maxUnprocessedMessageQueueSize;decoder;constructor(e,t){super(e,{...t,protocol:"/mplex/6.7.0",name:"mplex"}),this._streamId=0,this.maxMessageSize=t.maxMessageSize??se,this.maxUnprocessedMessageQueueSize=t.maxUnprocessedMessageQueueSize??it,this.decoder=new Ie(this.maxMessageSize,this.maxUnprocessedMessageQueueSize),this.rateLimiter=new Le({points:t.disconnectThreshold??Is,duration:1})}onData(e){for(let t of this.decoder.write(e))this.handleMessage(t)}onCreateStream(e){if(this.status!=="open")throw new F("Muxer already closed");let t=this._streamId++;return this._newStream(t,"outbound",e)}_newStream(e,t,s){return this.log("new %s stream %s",t,e),Wt({...s,id:e,direction:t,maxMsgSize:this.maxMessageSize,log:this.log,muxer:this})}handleMessage(e){if(this.log.enabled&&this.log.trace("incoming message",As(e)),e.type===f.NEW_STREAM){try{this.rateLimiter.consume("new-stream",1)}catch{this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),this.abort(new Error("Too many open streams"));return}let n=this._newStream(e.id,"inbound",this.streamOptions);this.onRemoteStream(n);return}let t=`${(e.type&1)===1?"i":"r"}${e.id}`,s=this.streams.find(n=>n.id===t);if(s==null){this.log("missing stream %s for message type %s",t,re[e.type]);try{this.rateLimiter.consume("missing-stream",1)}catch{this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),this.abort(new Error("Too many messages for missing streams"));return}return}try{switch(e.type){case f.MESSAGE_INITIATOR:case f.MESSAGE_RECEIVER:s.onData(e.data);break;case f.CLOSE_INITIATOR:case f.CLOSE_RECEIVER:s.onRemoteCloseWrite();break;case f.RESET_INITIATOR:case f.RESET_RECEIVER:s.onRemoteReset();break;default:this.log("unknown message type")}}catch(n){this.log.error("error while processing message - %e",n),s.abort(n)}}};var ut=class{protocol="/mplex/6.7.0";_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@libp2p/mplex";[ht]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new De(e,{...this._init})}};function Ds(r={}){return()=>new ut(r)}return Qt(Ts);})();
3
3
  return Libp2PMplex}));
4
4
  //# sourceMappingURL=index.min.js.map