@libp2p/mplex
Version:
JavaScript implementation of https://github.com/libp2p/mplex
2 lines • 51 kB
JavaScript
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PMplex = factory()}(typeof self !== 'undefined' ? self : this, function () {
"use strict";var Libp2PMplex=(()=>{var xe=Object.defineProperty;var Bt=Object.getOwnPropertyDescriptor;var Wt=Object.getOwnPropertyNames;var Gt=Object.prototype.hasOwnProperty;var v=(r,e)=>{for(var t in e)xe(r,t,{get:e[t],enumerable:!0})},$t=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Wt(e))!Gt.call(r,s)&&s!==t&&xe(r,s,{get:()=>e[s],enumerable:!(n=Bt(e,s))||n.enumerable});return r};var qt=r=>$t(xe({},"__esModule",{value:!0}),r);var Dn={};v(Dn,{mplex:()=>Ln});var te=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},re=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}},ne=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}};var K=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var se=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}};var rt=Symbol.for("@libp2p/service-capabilities"),On=Symbol.for("@libp2p/service-dependencies");function nt(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function st(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function oe(r,e){let t=nt(r).return?.();st(t)&&t.catch(n=>{e.error("could not cause iterator to return",n)})}var ot=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},Kt=new WeakMap;function jt({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(ot());let o,i,a,c=r??clearTimeout,m=()=>{c(o),a(ot())},f=()=>{s&&s.removeEventListener("abort",m)},l=new Promise((y,N)=>{i=()=>{f(),y(n)},a=N,o=(e??setTimeout)(i,t)});return s&&s.addEventListener("abort",m,{once:!0}),Kt.set(l,()=>{c(o),o=null,i()}),l}}var Xt=jt(),it=Xt;var ie=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 ae=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new Ee}async consume(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);if(i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i.consumedPoints>this.points)throw this.blockDuration>0&&i.consumedPoints<=this.points+t&&(i=this.memoryStorage.set(s,i.consumedPoints,this.blockDuration)),new ie("Rate limit exceeded",i);if(this.execEvenly&&i.msBeforeNext>0&&!i.isFirstInDuration){let a=Math.ceil(i.msBeforeNext/(i.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=i.consumedPoints*this.execEvenlyMinDelayMs),await it(a)}return i}penalty(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}reward(e,t=1,n={}){let s=this.getKey(e),o=this._getKeySecDuration(n),i=this.memoryStorage.incrby(s,-t,o);return i.remainingPoints=Math.max(this.points-i.consumedPoints,0),i}block(e,t){let n=t*1e3,s=this.points+1;return this.memoryStorage.set(this.getKey(e),s,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:s,isFirstInDuration:!1}}set(e,t,n=0){let s=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:s===0?-1:s,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)}},Ee=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let s=this.storage.get(e);if(s!=null){let o=s.expiresAt!=null?s.expiresAt.getTime()-new Date().getTime():-1;return s.expiresAt==null||o>0?(s.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:s.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let s=n*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let i={value:t,expiresAt:s>0?new Date(Date.now()+s):void 0};return this.storage.set(e,i),s>0&&(i.timeoutId=setTimeout(()=>{this.storage.delete(e)},s),i.timeoutId.unref!=null&&i.timeoutId.unref()),{remainingPoints:0,msBeforeNext:s===0?-1:s,consumedPoints:i.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}};function E(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var ce=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}},z=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new ce(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 ce(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 Se=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function V(r={}){return Jt(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Jt(r,e){e=e??{};let t=e.onEnd,n=new z,s,o,i,a=E(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,g)=>{o=x=>{o=null,n.push(x);try{h(r(n))}catch(w){g(w)}return s}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=E()})}},m=h=>o!=null?o(h):(n.push(h),s),f=h=>(n=new z,o!=null?o({error:h}):(n.push({error:h}),s)),l=h=>{if(i)return s;if(e?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return m({done:!1,value:h})},y=h=>i?s:(i=!0,h!=null?f(h):m({done:!0})),N=()=>(n=new z,y(),{done:!0}),d=h=>(y(h),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:N,throw:d,push:l,end:y,get readableLength(){return n.size},onEmpty:async h=>{let g=h?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let x,w;g!=null&&(x=new Promise((I,_)=>{w=()=>{_(new Se)},g.addEventListener("abort",w)}));try{await Promise.race([a.promise,x])}finally{w!=null&&g!=null&&g?.removeEventListener("abort",w)}}},t==null)return s;let b=s;return s={[Symbol.asyncIterator](){return this},next(){return b.next()},throw(h){return b.throw(h),t!=null&&(t(h),t=void 0),{done:!0}},return(){return b.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(h){return b.end(h),t!=null&&(t(h),t=void 0),s},get readableLength(){return b.readableLength},onEmpty:h=>b.onEmpty(h)},s}var ue=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function P(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new ue(t?.errorMessage,t?.errorCode,t?.errorName));let n,s=new ue(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((o,i)=>{n=()=>{i(s)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var Ie=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=E(),this.haveNext=E()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=E(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=E(),await P(this.readNext.promise,t?.signal,t)}};function at(){return new Ie}function Qt(r){return r[Symbol.asyncIterator]!=null}async function Ht(r,e){try{await Promise.all(r.map(async t=>{for await(let n of t)await e.push(n)})),await e.end()}catch(t){await e.end(t).catch(()=>{})}}async function*Zt(r){let e=at();Ht(r,e).catch(()=>{}),yield*e}function*Yt(r){for(let e of r)yield*e}function er(...r){let e=[];for(let t of r)Qt(t)||e.push(t);return e.length===r.length?Yt(e):Zt(r)}var ct=er;function ut(r,...e){if(r==null)throw new Error("Empty pipeline");if(ve(r)){let n=r;r=()=>n.source}else if(lt(r)||ht(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&ve(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)ve(t[n])&&(t[n]=rr(t[n]));return tr(...t)}var tr=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},ht=r=>r?.[Symbol.asyncIterator]!=null,lt=r=>r?.[Symbol.iterator]!=null,ve=r=>r==null?!1:r.sink!=null&&r.source!=null,rr=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=V({objectMode:!0});t.then(()=>{n.end()},i=>{n.end(i)});let s,o=r.source;if(ht(o))s=async function*(){yield*o,n.end()};else if(lt(o))s=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return ct(n,s())}return r.source};function Ae(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 L(r=0){return new Uint8Array(r)}function A(r=0){return new Uint8Array(r)}function he(r,e){e==null&&(e=r.reduce((s,o)=>s+o.length,0));let t=A(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}var Me={};v(Me,{base10:()=>ur});var Fs=new Uint8Array(0);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}function D(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 mt(r){return new TextDecoder().decode(r)}function sr(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var o=r.charAt(s),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=s}var a=r.length,c=r.charAt(0),m=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var b=0,h=0,g=0,x=d.length;g!==x&&d[g]===0;)g++,b++;for(var w=(x-g)*f+1>>>0,I=new Uint8Array(w);g!==x;){for(var _=d[g],U=0,R=w-1;(_!==0||U<h)&&R!==-1;R--,U++)_+=256*I[R]>>>0,I[R]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");h=U,g++}for(var M=w-h;M!==w&&I[M]===0;)M++;for(var ee=c.repeat(b);M<w;++M)ee+=r.charAt(I[M]);return ee}function y(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var b=0;if(d[b]!==" "){for(var h=0,g=0;d[b]===c;)h++,b++;for(var x=(d.length-b)*m+1>>>0,w=new Uint8Array(x);d[b];){var I=t[d.charCodeAt(b)];if(I===255)return;for(var _=0,U=x-1;(I!==0||_<g)&&U!==-1;U--,_++)I+=a*w[U]>>>0,w[U]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");g=_,b++}if(d[b]!==" "){for(var R=x-g;R!==x&&w[R]===0;)R++;for(var M=new Uint8Array(h+(x-R)),ee=h;R!==x;)M[ee++]=w[R++];return M}}}function N(d){var b=y(d);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:y,decode:N}}var or=sr,ir=or,bt=ir;var _e=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Re=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return gt(this,e)}},Ce=class{decoders;constructor(e){this.decoders=e}or(e){return gt(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function gt(r,e){return new Ce({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Te=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new _e(e,t,n),this.decoder=new Re(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function B({name:r,prefix:e,encode:t,decode:n}){return new Te(r,e,t,n)}function O({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=bt(t,r);return B({prefix:e,name:r,encode:n,decode:o=>D(s(o))})}function ar(r,e,t,n){let s={};for(let f=0;f<e.length;++f)s[e[f]]=f;let o=r.length;for(;r[o-1]==="=";)--o;let i=new Uint8Array(o*t/8|0),a=0,c=0,m=0;for(let f=0;f<o;++f){let l=s[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,i[m++]=255&c>>a)}if(a>=t||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return i}function cr(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,o+=e[s&a>>i];if(i!==0&&(o+=e[s&a<<t-i]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function p({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return B({prefix:e,name:r,encode(s){return cr(s,n,t)},decode(s){return ar(s,n,t,r)}})}var ur=O({prefix:"9",name:"base10",alphabet:"0123456789"});var Le={};v(Le,{base16:()=>hr,base16upper:()=>lr});var hr=p({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),lr=p({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var De={};v(De,{base2:()=>dr});var dr=p({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ne={};v(Ne,{base256emoji:()=>gr});var wt=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}"),fr=wt.reduce((r,e,t)=>(r[t]=e,r),[]),mr=wt.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function pr(r){return r.reduce((e,t)=>(e+=fr[t],e),"")}function br(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=mr[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var gr=B({prefix:"\u{1F680}",name:"base256emoji",encode:pr,decode:br});var Ue={};v(Ue,{base32:()=>W,base32hex:()=>Er,base32hexpad:()=>Ir,base32hexpadupper:()=>vr,base32hexupper:()=>Sr,base32pad:()=>yr,base32padupper:()=>xr,base32upper:()=>wr,base32z:()=>Ar});var W=p({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),wr=p({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),yr=p({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),xr=p({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Er=p({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Sr=p({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ir=p({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),vr=p({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ar=p({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Oe={};v(Oe,{base36:()=>j,base36upper:()=>_r});var j=O({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_r=O({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Pe={};v(Pe,{base58btc:()=>C,base58flickr:()=>Rr});var C=O({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Rr=O({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ke={};v(ke,{base64:()=>Cr,base64pad:()=>Tr,base64url:()=>Mr,base64urlpad:()=>Lr});var Cr=p({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Tr=p({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Mr=p({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Lr=p({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Fe={};v(Fe,{base8:()=>Dr});var Dr=p({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ze={};v(ze,{identity:()=>Nr});var Nr=B({prefix:"\0",name:"identity",encode:r=>mt(r),decode:r=>ft(r)});var eo=new TextEncoder,to=new TextDecoder;var Be={};v(Be,{identity:()=>rn});var Pr=Et,yt=128,kr=127,Fr=~kr,zr=Math.pow(2,31);function Et(r,e,t){e=e||[],t=t||0;for(var n=t;r>=zr;)e[t++]=r&255|yt,r/=128;for(;r&Fr;)e[t++]=r&255|yt,r>>>=7;return e[t]=r|0,Et.bytes=t-n+1,e}var Vr=Ve,Br=128,xt=127;function Ve(r,n){var t=0,n=n||0,s=0,o=n,i,a=r.length;do{if(o>=a)throw Ve.bytes=0,new RangeError("Could not decode varint");i=r[o++],t+=s<28?(i&xt)<<s:(i&xt)*Math.pow(2,s),s+=7}while(i>=Br);return Ve.bytes=o-n,t}var Wr=Math.pow(2,7),Gr=Math.pow(2,14),$r=Math.pow(2,21),qr=Math.pow(2,28),Kr=Math.pow(2,35),jr=Math.pow(2,42),Xr=Math.pow(2,49),Jr=Math.pow(2,56),Qr=Math.pow(2,63),Hr=function(r){return r<Wr?1:r<Gr?2:r<$r?3:r<qr?4:r<Kr?5:r<jr?6:r<Xr?7:r<Jr?8:r<Qr?9:10},Zr={encode:Pr,decode:Vr,encodingLength:Hr},Yr=Zr,X=Yr;function J(r,e=0){return[X.decode(r,e),X.decode.bytes]}function G(r,e,t=0){return X.encode(r,e,t),e}function $(r){return X.encodingLength(r)}function k(r,e){let t=e.byteLength,n=$(r),s=n+$(t),o=new Uint8Array(s+t);return G(r,o,0),G(t,o,n),o.set(e,s),new q(r,t,e,o)}function St(r){let e=D(r),[t,n]=J(e),[s,o]=J(e.subarray(n)),i=e.subarray(n+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new q(t,s,i,e)}function It(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&dt(r.bytes,t.bytes)}}var q=class{code;size;digest;bytes;constructor(e,t,n,s){this.code=e,this.size=t,this.digest=n,this.bytes=s}};var vt=0,en="identity",At=D;function tn(r){return k(vt,At(r))}var rn={code:vt,name:en,encode:At,digest:tn};var $e={};v($e,{sha256:()=>nn,sha512:()=>sn});function Ge({name:r,code:e,encode:t}){return new We(r,e,t)}var We=class{name;code;encode;constructor(e,t,n){this.name=e,this.code=t,this.encode=n}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?k(this.code,t):t.then(n=>k(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Rt(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var nn=Ge({name:"sha2-256",code:18,encode:Rt("SHA-256")}),sn=Ge({name:"sha2-512",code:19,encode:Rt("SHA-512")});function Ct(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return an(t,qe(r),e??C.encoder);default:return cn(t,qe(r),e??W.encoder)}}var Tt=new WeakMap;function qe(r){let e=Tt.get(r);if(e==null){let t=new Map;return Tt.set(r,t),t}return e}var de=class r{code;version;multihash;bytes;"/";constructor(e,t,n,s){this.code=t,this.version=e,this.multihash=n,this.bytes=s,this["/"]=s}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!==H)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==un)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=k(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&It(e.multihash,n.multihash)}toString(e){return Ct(this,e)}toJSON(){return{"/":Ct(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:o,bytes:i}=t;return new r(n,s,o,i??Mt(n,s,o.bytes))}else if(t[hn]===!0){let{version:n,multihash:s,code:o}=t,i=St(s);return r.create(n,o,i)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==H)throw new Error(`Version 0 CID must use dag-pb (code: ${H}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Mt(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,H,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=D(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=s.subarray(t.multihashSize-t.digestSize),i=new q(t.multihashCode,t.digestSize,o,s);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[l,y]=J(e.subarray(t));return t+=y,l},s=n(),o=H;if(s===18?(s=0,t=0):o=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=t,a=n(),c=n(),m=t+c,f=m-i;return{version:s,codec:o,multihashCode:a,digestSize:c,multihashSize:f,size:m}}static parse(e,t){let[n,s]=on(e,t),o=r.decode(s);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return qe(o).set(n,e),o}};function on(r,e){switch(r[0]){case"Q":{let t=e??C;return[C.prefix,t.decode(`${C.prefix}${r}`)]}case C.prefix:{let t=e??C;return[C.prefix,t.decode(r)]}case W.prefix:{let t=e??W;return[W.prefix,t.decode(r)]}case j.prefix:{let t=e??j;return[j.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 an(r,e,t){let{prefix:n}=t;if(n!==C.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return s}function cn(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let o=t.encode(r);return e.set(n,o),o}else return s}var H=112,un=18;function Mt(r,e,t){let n=$(r),s=n+$(e),o=new Uint8Array(s+t.byteLength);return G(r,o,0),G(e,o,n),o.set(t,s),o}var hn=Symbol.for("@ipld/js-cid/CID");var Ke={...ze,...De,...Fe,...Me,...Le,...Ue,...Oe,...Pe,...ke,...Ne},vo={...$e,...Be};function Dt(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Lt=Dt("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),je=Dt("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=A(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ln={utf8:Lt,"utf-8":Lt,hex:Ke.base16,latin1:je,ascii:je,binary:je,...Ke},fe=ln;function Xe(r,e="utf8"){let t=fe[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function Z(r,e="utf8"){let t=fe[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Ut=Symbol.for("@achingbrain/uint8arraylist");function Nt(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function me(r){return!!r?.[Ut]}var T=class r{bufs;length;[Ut]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(me(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(me(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Nt(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Nt(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(me(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return he(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:he(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),o=new r;return o.length=s,o.bufs=[...n],o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],a=s,c=a+i.byteLength;if(s=c,e>=c)continue;let m=e>=a&&e<c,f=t>a&&t<=c;if(m&&f){if(e===a&&t===c){n.push(i);break}let l=e-a;n.push(i.subarray(l,l+(t-e)));break}if(m){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(f){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!me(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let l=0;l<o;l++)i[l]=-1;for(let l=0;l<s;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,m=n.byteLength-1,f;for(let l=t;l<=c;l+=f){f=0;for(let y=m;y>=0;y--){let N=this.get(l+y);if(n[y]!==N){f=Math.max(1,y-a[N]);break}}if(f===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 n=A(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=L(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=L(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=L(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=A(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=L(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=L(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=L(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=L(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=L(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,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(!Ae(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,o)=>s+o.byteLength,0)),n.length=t,n}};var u;(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"})(u||(u={}));var Y=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),Je=Object.freeze({NEW_STREAM:u.NEW_STREAM,MESSAGE:u.MESSAGE_INITIATOR,CLOSE:u.CLOSE_INITIATOR,RESET:u.RESET_INITIATOR}),Ot=Object.freeze({MESSAGE:u.MESSAGE_RECEIVER,CLOSE:u.CLOSE_RECEIVER,RESET:u.RESET_RECEIVER});var Qe=1<<20,dn=4<<20,pe=class{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=Qe,t=dn){this._buffer=new T,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 K("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(m){if(m.name==="InvalidMessageError")throw m;break}let{id:n,type:s,length:o,offset:i}=this._headerInfo;if(this._buffer.length-i<o)break;let c={id:n,type:s};(s===u.NEW_STREAM||s===u.MESSAGE_INITIATOR||s===u.MESSAGE_RECEIVER)&&(c.data=this._buffer.sublist(i,i+o)),t.push(c),this._buffer.consume(i+o),this._headerInfo=null}return t}_decodeHeader(e){let{value:t,offset:n}=kt(e),{value:s,offset:o}=kt(e,n),i=t&7;if(Y[i]==null)throw new Error(`Invalid type received: ${i}`);if(s>this._maxMessageSize)throw new K("Message size too large");return{id:t>>3,type:i,offset:n+o,length:s}}},fn=128,Pt=127;function kt(r,e=0){let t=0,n=0,s=e,o,i=r.length;do{if(s>=i||n>49)throw e=0,new RangeError("Could not decode varint");o=r.get(s++),t+=n<28?(o&Pt)<<n:(o&Pt)*Math.pow(2,n),n+=7}while(o>=fn);return e=s-e,{value:t,offset:e}}var mn=Math.pow(2,7),pn=Math.pow(2,14),bn=Math.pow(2,21),gn=Math.pow(2,28),wn=Math.pow(2,35),yn=Math.pow(2,42),xn=Math.pow(2,49),S=128;function F(r){if(r<mn)return 1;if(r<pn)return 2;if(r<bn)return 3;if(r<gn)return 4;if(r<wn)return 5;if(r<yn)return 6;if(r<xn)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function En(r,e,t=0){switch(F(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 Sn(r,e,t=0){switch(F(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 be(r,e,t=0){return e==null&&(e=A(F(r))),e instanceof Uint8Array?En(r,e,t):Sn(r,e,t)}var He=10*1024,Ze=class{_pool;_poolOffset;constructor(){this._pool=A(He),this._poolOffset=0}write(e,t){let n=this._pool,s=this._poolOffset;be(e.id<<3|e.type,n,s),s+=F(e.id<<3|e.type),(e.type===u.NEW_STREAM||e.type===u.MESSAGE_INITIATOR||e.type===u.MESSAGE_RECEIVER)&&e.data!=null?(be(e.data.length,n,s),s+=F(e.data.length)):(be(0,n,s),s+=F(0));let o=n.subarray(this._poolOffset,s);He-s<100?(this._pool=A(He),this._poolOffset=0):this._poolOffset=s,t.append(o),(e.type===u.NEW_STREAM||e.type===u.MESSAGE_INITIATOR||e.type===u.MESSAGE_RECEIVER)&&e.data!=null&&t.append(e.data)}},vn=new Ze;async function*Ft(r){for await(let e of r){let t=new T;vn.write(e,t),yield t}}var ge=class extends Error{constructor(e="Stream input buffer error"){super(e),this.name="StreamInputBufferError"}};var An=5e3;function Ye(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var we=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=E(),this.closed=E(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??An,this.onEnd=e.onEnd,this.onCloseRead=e?.onCloseRead,this.onCloseWrite=e?.onCloseWrite,this.onReset=e?.onReset,this.onAbort=e?.onAbort,this.source=this.streamSource=V({onEnd:t=>{t!=null?this.log.trace("source ended with error",t):this.log.trace("source ended"),this.onSourceEnd(t)}}),this.sink=this.sink.bind(this)}async sink(e){if(this.writeStatus!=="ready")throw new ne(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";let t={signal:this.sinkController.signal};if(this.direction==="outbound"){let s=this.sendNewStream(t);Ye(s)&&await s}let n=()=>{oe(e,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let s of e){s=s instanceof Uint8Array?new T(s):s;let o=this.sendData(s,t);Ye(o)&&(this.sendingData=E(),await o,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",n)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(t){throw this.log.trace("sink ended with error, calling abort with error",t),this.abort(t),t}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){this.status==="open"&&(this.log.trace("closing gracefully"),this.status="closing",await P(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully"))}async closeRead(e={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let t=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),t==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await P(this.sink([]),e.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await P(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await P(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",e),this.log("try to send reset to remote");let t=this.sendReset();Ye(t)&&t.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let e=new re("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}};var et=class extends we{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types=e.direction==="outbound"?Je:Ot,this.send=e.send,this.name=e.name,this.streamId=e.streamId,this.maxDataSize=e.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:Je.NEW_STREAM,data:new T(Xe(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){let t=Math.min(e.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:e.sublist(0,t)}),e.consume(t)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}};function zt(r){let{id:e,name:t,send:n,onEnd:s,type:o="initiator",maxMsgSize:i=Qe}=r;return new et({id:o==="initiator"?`i${e}`:`r${e}`,streamId:e,name:`${t??e}`,direction:o==="initiator"?"outbound":"inbound",maxDataSize:i,onEnd:s,send:n,log:r.logger.forComponent(`libp2p:mplex:stream:${o}:${e}`)})}var _n=1024,Rn=1024,Cn=1024*1024*4,Tn=5,Mn=500;function Vt(r){let e={...r,type:`${Y[r.type]} (${r.type})`};return r.type===u.NEW_STREAM&&(e.data=Z(r.data instanceof Uint8Array?r.data:r.data.subarray())),(r.type===u.MESSAGE_INITIATOR||r.type===u.MESSAGE_RECEIVER)&&(e.data=Z(r.data instanceof Uint8Array?r.data:r.data.subarray(),"base16")),e}var ye=class{protocol="/mplex/6.7.0";sink;source;log;_streamId;_streams;_init;_source;closeController;rateLimiter;closeTimeout;logger;constructor(e,t){t=t??{},this.log=e.logger.forComponent("libp2p:mplex"),this.logger=e.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=t,this.closeTimeout=t.closeTimeout??Mn,this.sink=this._createSink(),this._source=V({objectMode:!0,onEnd:()=>{for(let n of this._streams.initiators.values())n.destroy();for(let n of this._streams.receivers.values())n.destroy()}}),this.source=ut(this._source,n=>Ft(n)),this.closeController=new AbortController,this.rateLimiter=new ae({points:t.disconnectThreshold??Tn,duration:1})}get streams(){let e=[];for(let t of this._streams.initiators.values())e.push(t);for(let t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new te("Muxer already closed");let t=this._streamId++;e=e==null?t.toString():e.toString();let n=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:n})}async close(e){if(this.closeController.signal.aborted)return;let t=e?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map(async n=>n.close({signal:t}))),this._source.end(),await this._source.onEmpty({signal:t}),this.closeController.abort()}catch(n){this.abort(n)}}abort(e){this.closeController.signal.aborted||(this.streams.forEach(t=>{t.abort(e)}),this.closeController.abort(e))}_newReceiverStream(e){let{id:t,name:n}=e,s=this._streams.receivers;return this._newStream({id:t,name:n,type:"receiver",registry:s})}_newStream(e){let{id:t,name:n,type:s,registry:o}=e;if(this.log("new %s stream %s",s,t),s==="initiator"&&this._streams.initiators.size===(this._init.maxOutboundStreams??Rn))throw new se("Too many outbound streams open");if(o.has(t))throw new Error(`${s} stream ${t} already exists!`);let c=zt({id:t,name:n,send:async m=>{this.log.enabled&&this.log.trace("%s stream %s send",s,t,Vt(m)),this._source.push(m)},type:s,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",s,t,c.protocol),o.delete(t),this._init.onStreamEnd!=null&&this._init.onStreamEnd(c)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return o.set(t,c),c}_createSink(){return async t=>{let n=()=>{oe(t,this.log)};this.closeController.signal.addEventListener("abort",n);try{let s=new pe(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(let o of t)for(let i of s.write(o))await this._handleIncoming(i);this._source.end()}catch(s){this.log("error in sink",s),this._source.end(s)}finally{this.closeController.signal.removeEventListener("abort",n)}}}async _handleIncoming(e){let{id:t,type:n}=e;if(this.log.enabled&&this.log.trace("incoming message",Vt(e)),e.type===u.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??_n)){this.log("too many inbound streams open"),this._source.push({id:t,type:u.RESET_RECEIVER});try{await 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}return}let a=this._newReceiverStream({id:t,name:Z(e.data instanceof Uint8Array?e.data:e.data.subarray())});this._init.onIncomingStream!=null&&this._init.onIncomingStream(a);return}let o=((n&1)===1?this._streams.initiators:this._streams.receivers).get(t);if(o==null){this.log("missing stream %s for message type %s",t,Y[n]);try{await this.rateLimiter.consume("missing-stream",1)}catch{this.log("rate limit hit when receiving messages for streams that do not exist