@libp2p/mplex 12.0.37-fcbb136ad → 12.0.38
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 +1 -1
- package/dist/index.min.js.map +2 -2
- package/dist/typedoc-urls.json +6 -0
- package/package.json +5 -5
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 Me=Object.defineProperty;var Xt=Object.getOwnPropertyDescriptor;var Jt=Object.getOwnPropertyNames;var Zt=Object.prototype.hasOwnProperty;var D=(r,e)=>{for(var t in e)Me(r,t,{get:e[t],enumerable:!0})},Yt=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Jt(e))!Zt.call(r,n)&&n!==t&&Me(r,n,{get:()=>e[n],enumerable:!(s=Xt(e,n))||s.enumerable});return r};var er=r=>Yt(Me({},"__esModule",{value:!0}),r);var qs={};D(qs,{mplex:()=>Ws});var V=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},ce=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var N=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Z=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var Y=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var ue=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},$=class extends Event{error;local;constructor(e,t,s){super("close",s),this.error=t,this.local=e}},he=class extends ${constructor(e,t){super(!0,e,t)}},fe=class extends ${constructor(e,t){super(!1,e,t)}};function tr(r){return typeof r?.handleEvent=="function"}function rr(r){return r===!0||r===!1}function sr(r){return rr(r)?r:r?.capture??!1}function Be(r){let e={capture:sr(r),once:!!r?.once};return r?.passive!=null&&(e.passive=r?.passive),r?.signal!=null&&(e.signal=r?.signal),e}function pt(r,e){return Be(r).capture===Be(e).capture}var W=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=Be(s);if(n?.signal?.aborted===!0)return;let i=h=>{n.once&&this.removeEventListener(e,t,n),tr(t)?t.handleEvent(h):t(h)},o=this.#e.get(e);if(o==null&&(o=[],this.#e.set(e,o)),o.some(h=>h.callback!==t?!1:pt(h.options,n)))return;super.addEventListener(e,i,n);let c=()=>{this.removeEventListener(e,t,n)};n.signal?.addEventListener("abort",c),o.push({callback:t,wrapper:i,options:n,onAbort:c})}removeEventListener(e,t,s){let n=this.#e.get(e);if(n==null){super.removeEventListener(e,t??null,s);return}this.#e.set(e,n.filter(i=>i.callback===t&&pt(i.options,s)?(super.removeEventListener(e,i.wrapper,s),i.options?.signal?.removeEventListener("abort",i.onAbort),!1):!0))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var gt=Symbol.for("@libp2p/service-capabilities");function M(r=0){return new Uint8Array(r)}function L(r=0){return new Uint8Array(r)}function nr(r){return r?.buffer instanceof ArrayBuffer}function Ue(r){if(nr(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function le(r,e){e==null&&(e=r.reduce((n,i)=>n+i.length,0));let t=L(e),s=0;for(let n of r)t.set(n,s),s+=n.length;return Ue(t)}function _e(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 yt=Symbol.for("@achingbrain/uint8arraylist");function bt(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 de(r){return!!r?.[yt]}var C=class r{bufs;length;[yt]=!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(de(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(de(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=bt(this.bufs,e);return t.buf[t.index]}set(e,t){let s=bt(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(de(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 le(s,n)}subarray(e,t){let{bufs:s,length:n}=this._subList(e,t);return s.length===1?s[0]:le(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 h=e>=a&&e<c,m=t>a&&t<=c;if(h&&m){if(e===a&&t===c){s.push(o);break}let d=e-a;s.push(o.subarray(d,d+(t-e)));break}if(h){if(e===0){s.push(o);continue}s.push(o.subarray(e-a));continue}if(m){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(!de(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 d=0;d<i;d++)o[d]=-1;for(let d=0;d<n;d++)o[s[d]]=d;let a=o,c=this.byteLength-s.byteLength,h=s.byteLength-1,m;for(let d=t;d<=c;d+=m){m=0;for(let p=h;p>=0;p--){let x=this.get(d+p);if(s[p]!==x){m=Math.max(1,p-a[x]);break}}if(m===0)return d}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=L(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=L(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(!_e(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={};D(ze,{base10:()=>lr});var Mn=new Uint8Array(0);function xt(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 R(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return z(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return z(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Et(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var wt=4096;function St(r){let e=r.length;if(e<=wt)return String.fromCharCode.apply(String,r);let t="",s=0;for(;s<e;)t+=String.fromCharCode.apply(String,r.subarray(s,s+=wt));return t}function ir(r){return r?.buffer instanceof ArrayBuffer}function z(r){return ir(r)?r:r.slice()}function or(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),n=0;n<s.length;n++)s[n]=255;for(var i=0;i<r.length;i++){var o=r.charAt(i),a=o.charCodeAt(0);if(s[a]!==255)throw new TypeError(o+" is ambiguous");if(s[a]=i,t){var c=o.toLowerCase().charCodeAt(0),h=o.toUpperCase().charCodeAt(0);c!==a&&(s[c]=i),h!==a&&(s[h]=i)}}var m=r.length,d=r.charAt(0),p=Math.log(m)/Math.log(256),x=Math.log(256)/Math.log(m);function _(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";for(var y=0,w=0,g=0,S=u.length;g!==S&&u[g]===0;)g++,y++;for(var T=(S-g)*x+1>>>0,P=new Uint8Array(T);g!==S;){for(var v=u[g],F=0,U=T-1;(v!==0||F<w)&&U!==-1;U--,F++)v+=256*P[U]>>>0,P[U]=v%m>>>0,v=v/m>>>0;if(v!==0)throw new Error("Non-zero carry");w=F,g++}for(var A=T-w;A!==T&&P[A]===0;)A++;for(var J=d.repeat(y);A<T;++A)J+=r.charAt(P[A]);return J}function E(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;var y=0;if(u[y]!==" "){for(var w=0,g=0;u[y]===d;)w++,y++;for(var S=(u.length-y)*p+1>>>0,T=new Uint8Array(S);u[y];){var P=u.charCodeAt(y);if(P>255)return;var v=s[P];if(v===255)return;for(var F=0,U=S-1;(v!==0||F<g)&&U!==-1;U--,F++)v+=m*T[U]>>>0,T[U]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");g=F,y++}if(u[y]!==" "){for(var A=S-g;A!==S&&T[A]===0;)A++;for(var J=new Uint8Array(w+(S-A)),Ht=w;A!==S;)J[Ht++]=T[A++];return J}}}function f(u){var y=E(u);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:_,decodeUnsafe:E,decode:f}}var ar=or,cr=ar,Lt=cr;var Ne=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")}},Oe=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 It(this,e)}},Pe=class{decoders;constructor(e){this.decoders=e}or(e){return It(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 It(r,e){return new Pe({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Fe=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 Ne(e,t,s),this.decoder=new Oe(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function q({name:r,prefix:e,encode:t,decode:s}){return new Fe(r,e,t,s)}function O({name:r,prefix:e,alphabet:t,caseInsensitive:s=!1}){let{encode:n,decode:i}=Lt(t,r,s);return q({prefix:e,name:r,encode:n,decode:o=>R(i(o))})}function ur(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 h=0;h<n;++h){let m=e[r[h]];if(m===void 0)throw new SyntaxError(`Non-${s} character`);a=a<<t|m,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 hr(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 fr(r,e){let t={};for(let s=0;s<r.length;++s)if(r[s]!=="="&&(t[r[s]]=s,e)){let n=r[s].toLowerCase(),i=r[s].toUpperCase();n!==r[s]&&(t[n]=s),i!==r[s]&&(t[i]=s)}return t}function b({name:r,prefix:e,bitsPerChar:t,alphabet:s,caseInsensitive:n=!1}){let i=fr(s,n);return q({prefix:e,name:r,encode(o){return hr(o,s,t)},decode(o){return ur(o,i,t,r)}})}var lr=O({prefix:"9",name:"base10",alphabet:"0123456789"});var ke={};D(ke,{base16:()=>dr,base16upper:()=>mr});var dr=b({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),mr=b({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var Ve={};D(Ve,{base2:()=>pr});var pr=b({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var $e={};D($e,{base256emoji:()=>xr});var At=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}"),gr=At.reduce((r,e,t)=>(r[t]=e,r),[]),br=At.reduce((r,e,t)=>{let s=e.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${e}`);return r[s]=t,r},[]);function yr(r){return r.reduce((e,t)=>(e+=gr[t],e),"")}function wr(r){let e=[];for(let t of r){let s=t.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${t}`);let n=br[s];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var xr=q({prefix:"\u{1F680}",name:"base256emoji",encode:yr,decode:wr});var We={};D(We,{base32:()=>G,base32hex:()=>Lr,base32hexpad:()=>Ar,base32hexpadupper:()=>Dr,base32hexupper:()=>Ir,base32pad:()=>Sr,base32padupper:()=>vr,base32upper:()=>Er,base32z:()=>Cr});var G=b({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),Er=b({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),Sr=b({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),vr=b({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),Lr=b({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),Ir=b({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),Ar=b({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),Dr=b({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),Cr=b({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var qe={};D(qe,{base36:()=>ee,base36upper:()=>Tr});var ee=O({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),Tr=O({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var Ge={};D(Ge,{base58btc:()=>B,base58flickr:()=>Rr});var B=O({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Rr=O({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var je={};D(je,{base64:()=>Mr,base64pad:()=>Br,base64url:()=>Ur,base64urlpad:()=>_r});var Mr=b({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Br=b({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ur=b({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),_r=b({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Qe={};D(Qe,{base8:()=>Nr});var Nr=b({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ke={};D(Ke,{identity:()=>Or});var Or=q({prefix:"\0",name:"identity",encode:r=>St(R(r)),decode:r=>R(Et(r))});var Qn=new TextEncoder,Kn=new TextDecoder;var Xe={};D(Xe,{identity:()=>is});var zr=Tt,Dt=128,kr=127,Vr=~kr,$r=Math.pow(2,31);function Tt(r,e,t){e=e||[],t=t||0;for(var s=t;r>=$r;)e[t++]=r&255|Dt,r/=128;for(;r&Vr;)e[t++]=r&255|Dt,r>>>=7;return e[t]=r|0,Tt.bytes=t-s+1,e}var Wr=He,qr=128,Ct=127;function He(r,s){var t=0,s=s||0,n=0,i=s,o,a=r.length;do{if(i>=a)throw He.bytes=0,new RangeError("Could not decode varint");o=r[i++],t+=n<28?(o&Ct)<<n:(o&Ct)*Math.pow(2,n),n+=7}while(o>=qr);return He.bytes=i-s,t}var Gr=Math.pow(2,7),jr=Math.pow(2,14),Qr=Math.pow(2,21),Kr=Math.pow(2,28),Hr=Math.pow(2,35),Xr=Math.pow(2,42),Jr=Math.pow(2,49),Zr=Math.pow(2,56),Yr=Math.pow(2,63),es=function(r){return r<Gr?1:r<jr?2:r<Qr?3:r<Kr?4:r<Hr?5:r<Xr?6:r<Jr?7:r<Zr?8:r<Yr?9:10},ts={encode:zr,decode:Wr,encodingLength:es},rs=ts,te=rs;function re(r,e=0){let t=te.decode(r,e),s=te.decode.bytes;if(s>9)throw new RangeError("Invalid varint: too long");if(s>1&&r[e+s-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[t,s]}function j(r,e,t=0){return te.encode(r,e,t),e}function Q(r){return te.encodingLength(r)}function H(r,e){let t=e.byteLength,s=Q(r),n=s+Q(t),i=new Uint8Array(n+t);return j(r,i,0),j(t,i,s),i.set(e,n),new K(r,t,e,i)}function Rt(r){let e=R(r),[t,s]=re(e),[n,i]=re(e.subarray(s)),o=e.subarray(s+i);if(o.byteLength!==n)throw new Error("Incorrect length");return new K(t,n,o,e)}function Mt(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&xt(r.bytes,t.bytes)}}var K=class{code;size;digest;bytes;constructor(e,t,s,n){this.code=e,this.size=t,this.digest=z(s),this.bytes=z(n)}};var Bt=0,ss="identity",Ut=R;function ns(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 H(Bt,Ut(r))}var is={code:Bt,name:ss,encode:Ut,digest:ns};var Ye={};D(Ye,{sha256:()=>as,sha512:()=>cs});var os=20;function Ze({name:r,code:e,encode:t,minDigestLength:s,maxDigestLength:n}){return new Je(r,e,t,s,n)}var Je=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,s,n,i){this.name=e,this.code=t,this.encode=s,this.minDigestLength=n??os,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?_t(s,this.code,t?.truncate):s.then(n=>_t(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function _t(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 H(e,r)}function Ot(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var as=Ze({name:"sha2-256",code:18,encode:Ot("SHA-256")}),cs=Ze({name:"sha2-512",code:19,encode:Ot("SHA-512")});function Pt(r,e){let{bytes:t,version:s}=r;return s===0?hs(t,et(r),e??B.encoder):fs(t,et(r),e??G.encoder)}var Ft=new WeakMap;function et(r){let e=Ft.get(r);if(e==null){let t=new Map;return Ft.set(r,t),t}return e}var pe=class r{code;version;multihash;bytes;"/";constructor(e,t,s,n){this.code=t,this.version=e,this.multihash=s,this.bytes=z(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!==ne)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==ls)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=H(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&&Mt(e.multihash,s.multihash)}toString(e){return Pt(this,e)}toJSON(){return{"/":Pt(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??zt(s,n,i.bytes))}else if(t[ds]===!0){let{version:s,multihash:n,code:i}=t,o=Rt(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!==ne)throw new Error(`Version 0 CID must use dag-pb (code: ${ne}) block encoding`);return new r(e,t,s,s.bytes)}case 1:{let n=zt(e,t,s.bytes);return new r(e,t,s,n)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,ne,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=R(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 K(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[d,p]=re(e.subarray(t));return t+=p,d},n=s(),i=ne;if(n===18)n=0,t=0;else if(n===1)i=s();else throw n===0?new RangeError("Invalid CID version, v0 is always implicit"):new RangeError(`Invalid CID version ${n}`);let o=t,a=s(),c=s(),h=t+c,m=h-o;return{version:n,codec:i,multihashCode:a,digestSize:c,multihashSize:m,size:h}}static parse(e,t){let[s,n]=us(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 et(i).set(s,e),i}};function us(r,e){switch(r[0]){case"Q":{let t=e??B;return[B.prefix,t.decode(`${B.prefix}${r}`)]}case B.prefix:{let t=e??B;return[B.prefix,t.decode(r)]}case G.prefix:{let t=e??G;return[G.prefix,t.decode(r)]}case ee.prefix:{let t=e??ee;return[ee.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 hs(r,e,t){let{prefix:s}=t;if(s!==B.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 fs(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 ne=112,ls=18;function zt(r,e,t){let s=Q(r),n=s+Q(e),i=new Uint8Array(n+t.byteLength);return j(r,i,0),j(e,i,s),i.set(t,n),i}var ds=Symbol.for("@ipld/js-cid/CID");var tt={...Ke,...Ve,...Qe,...ze,...ke,...We,...qe,...Ge,...je,...$e},gi={...Ye,...Xe};function Vt(r,e,t,s){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:s}}}var kt=Vt("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),rt=Vt("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=L(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ms={utf8:kt,"utf-8":kt,hex:tt.base16,latin1:rt,ascii:rt,binary:rt,...tt},ge=ms;function st(r,e="utf8"){let t=ge[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var ps=Math.pow(2,7),gs=Math.pow(2,14),bs=Math.pow(2,21),ys=Math.pow(2,28),ws=Math.pow(2,35),xs=Math.pow(2,42),Es=Math.pow(2,49),I=128;function k(r){if(r<ps)return 1;if(r<gs)return 2;if(r<bs)return 3;if(r<ys)return 4;if(r<ws)return 5;if(r<xs)return 6;if(r<Es)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ss(r,e,t=0){switch(k(r)){case 8:e[t++]=r&255|I,r/=128;case 7:e[t++]=r&255|I,r/=128;case 6:e[t++]=r&255|I,r/=128;case 5:e[t++]=r&255|I,r/=128;case 4:e[t++]=r&255|I,r>>>=7;case 3:e[t++]=r&255|I,r>>>=7;case 2:e[t++]=r&255|I,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function vs(r,e,t=0){switch(k(r)){case 8:e.set(t++,r&255|I),r/=128;case 7:e.set(t++,r&255|I),r/=128;case 6:e.set(t++,r&255|I),r/=128;case 5:e.set(t++,r&255|I),r/=128;case 4:e.set(t++,r&255|I),r>>>=7;case 3:e.set(t++,r&255|I),r>>>=7;case 2:e.set(t++,r&255|I),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=L(k(r))),e instanceof Uint8Array?Ss(r,e,t):vs(r,e,t)}function ye(r,e="utf8"){let t=ge[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function we(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var xe=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}},X=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new xe(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 xe(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 nt=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 Is(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 Is(r,e){e=e??{};let t=e.onEnd,s=new X,n,i,o,a=we(),c=async()=>{try{return s.isEmpty()?o?{done:!0}:await new Promise((f,u)=>{i=y=>{i=null,s.push(y);try{f(r(s))}catch(w){u(w)}return n}}):r(s)}finally{s.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=we()})}},h=f=>i!=null?i(f):(s.push(f),n),m=f=>(s=new X,i!=null?i({error:f}):(s.push({error:f}),n)),d=f=>{if(o)return n;if(e?.objectMode!==!0&&f?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return h({done:!1,value:f})},p=f=>o?n:(o=!0,f!=null?m(f):h({done:!0})),x=()=>(s=new X,p(),{done:!0}),_=f=>(p(f),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:c,return:x,throw:_,push:d,end:p,get readableLength(){return s.size},onEmpty:async f=>{let u=f?.signal;if(u?.throwIfAborted(),s.isEmpty())return;let y,w;u!=null&&(y=new Promise((g,S)=>{w=()=>{S(new nt)},u.addEventListener("abort",w)}));try{await Promise.race([a.promise,y])}finally{w!=null&&u!=null&&u?.removeEventListener("abort",w)}}},t==null)return n;let E=n;return n={[Symbol.asyncIterator](){return this},next(){return E.next()},throw(f){return E.throw(f),t!=null&&(t(f),t=void 0),{done:!0}},return(){return E.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(f){return E.end(f),t!=null&&(t(f),t=void 0),n},get readableLength(){return E.readableLength},onEmpty:f=>E.onEmpty(f)},n}var it=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},As=r=>"reason"in r?r.reason:new DOMException("This operation was aborted.","AbortError"),Ds=2**31-1,Cs=(r,e)=>{if(typeof r!="number"||Math.sign(r)!==1)return new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(typeof e?.setTimeout!="function"||typeof e?.clearTimeout!="function")return new TypeError("Expected `customTimers` to have a `setTimeout` and a `clearTimeout` function")};function ot(r,e){let{milliseconds:t,fallback:s,message:n,customTimers:i={setTimeout,clearTimeout},signal:o}=e,a,c,h=()=>{try{r.cancel?.()}catch{}},d=new Promise((p,x)=>{let _=()=>{x(As(o)),h()},E=Cs(t,i);try{E?x(E):o?.aborted?_():o&&(c=_,o.addEventListener("abort",c,{once:!0}))}finally{r.then(p,x)}if(E||o?.aborted||t>Ds)return;let f=s||n===!1||n instanceof Error?void 0:new it(n??`Promise timed out after ${t} milliseconds`);a=i.setTimeout.call(void 0,()=>{if(s)try{p(s())}catch(u){x(u)}else n===!1?p():x(n instanceof Error?n:f);h()},t)}).finally(()=>{try{d.clear()}catch{}try{c&&o.removeEventListener("abort",c)}catch{}});return d.clear=()=>{a!==void 0&&(i.clearTimeout.call(void 0,a),a=void 0)},d}var Wt=r=>typeof r=="function"?{filter:r}:{...r},Ts=r=>r===1/0||Number.isSafeInteger(r)&&r>=0,Rs=[["addEventListener","removeEventListener"],["on","off"],["addListener","removeListener"]],Ms=r=>{for(let[e,t]of Rs){let s=r?.[e],n=r?.[t];if(typeof s=="function"&&typeof n=="function")return{addListener:s.bind(r),removeListener:n.bind(r)}}throw new TypeError("Emitter is not compatible")},Bs=r=>{let e=new Map;for(let[t,s]of r)for(let n of Array.isArray(t)?t:[t])e.has(n)||e.set(n,s);return e},Us=({addListener:r,removeListener:e,handlers:t,signal:s,abortHandler:n,isDone:i})=>{s?.addEventListener("abort",n,{once:!0});for(let[o,a]of t)if(r(o,a),i()){e(o,a);return}},_s=({removeListener:r,handlers:e,signal:t,abortHandler:s})=>{for(let[n,i]of e)r(n,i);t?.removeEventListener("abort",s)},Ns=(r,e,t)=>{let s=Promise.resolve();return(n,i)=>{s=s.then(async()=>{if(e())return;let o;try{o=r?await r(n):!0}catch(a){e()||t(a);return}e()||i(o)})}};function Os(r,e,t){let s=()=>{},n=!1,i,o=new Promise((a,c)=>{t=Wt(t);let{filter:h}=t;if(!Ts(t.count))throw new TypeError("The `count` option should be at least 0 or more");if(typeof t.timeout=="number"&&!(t.timeout>0))throw new TypeError(`Expected the \`timeout\` option to be a positive number, got \`${t.timeout}\``);t.signal?.throwIfAborted();let{addListener:m,removeListener:d}=Ms(r);if(t.count===0){a([]);return}let p=[],x=g=>{s(),c(g)},_=Ns(h,()=>n,x),E=g=>{p.push(g),t.count===p.length&&(s(),a(p))},f=(...g)=>{if(n)return;let S=t.multiArgs?g:g[0];if(!h){E(S);return}_(S,T=>{T&&E(S)})},u=(...g)=>{x(t.rejectionMultiArgs?g:g[0])},y=()=>{x(t.signal.reason)},w={addListener:m,removeListener:d,handlers:Bs([[e,f],[t.rejectionEvents??["error"],u]]),signal:t.signal,abortHandler:y,isDone:()=>n};s=()=>{n=!0,clearTimeout(i),_s(w)},Us(w),!(n||!t.resolveImmediately)&&(Number.isFinite(t.timeout)&&t.timeout<=2**31-1&&(i=setTimeout(s,t.timeout)),a(p))});if(o.cancel=s,typeof t.timeout=="number"&&t.timeout>0&&!t.resolveImmediately){let a=ot(o,{milliseconds:t.timeout});return a.cancel=()=>{s(),a.clear()},a}return o}function at(r,e,t){let s=Os(r,e,{...Wt(t),count:1,resolveImmediately:!1}),n=s.then(i=>i[0]);return n.cancel=s.cancel,n}var Ee=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 Se=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},ve=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Ps(r){return r.reason}function Le(r,e,t){if(e==null||r==null)return r;let s=t?.translateError??Ps;if(e.aborted)return r.catch(()=>{}),Promise.reject(s(e));let n;return Promise.race([r,new Promise((i,o)=>{n=()=>{o(s(e))},e.addEventListener("abort",n)})]).finally(()=>{n!=null&&e.removeEventListener("abort",n)})}var Fs=Math.pow(2,20)*4,Ie=class extends W{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;#e=!1;#t;#r=new Set;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??Fs,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new C,this.writeBuffer=new C,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 ve)};this.addEventListener("close",s)}get readBufferLength(){return this.readBuffer.byteLength}get readableEnded(){return this.#e}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Le(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){let e=$t(),t,s=i=>{e.push(i.data)};this.addEventListener("message",s);let n=()=>{this.#r.delete(n),this.removeEventListener("message",s),t=this.#t,e.end()};this.#r.add(n),this.readableDone()&&n();try{if(yield*e,t!=null)throw t}finally{this.removeEventListener("message",s),this.#r.delete(n)}}readableDone(){return this.readBuffer.byteLength===0&&(this.remoteWriteStatus==="closed"||this.readStatus==="closing"||this.readStatus==="closed")}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new N(`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.readBuffer.byteLength>0&&(this.#t??=e,this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closed",this.maybeDispatchEnd());return}this.log.error("abort with error - %e",e),this.status="aborted",this.#t=e,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(),this.maybeDispatchEnd();try{this.sendReset(e)}catch(t){this.log.error("failed to send reset to remote - %e",t)}this.dispatchEvent(new he(e))}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new N("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 N("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 N(`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 N(`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(){if(this.status==="aborted"||this.status==="reset"||this.status==="closed")return;this.log("remote reset");let e=new ce;this.#t=e,this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed",this.maybeDispatchEnd()),this.dispatchEvent(new fe(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.maybeDispatchEnd(),this.dispatchEvent(new $))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.maybeDispatchEnd(),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 C(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}}maybeDispatchEnd(){this.readableDone()&&(this.#r.forEach(e=>{e()}),!this.#e&&(this.#e=!0,this.safeDispatchEvent("end")))}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 ue(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.maybeDispatchEnd()),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Z(`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 Z(`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 qt(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ae=class extends W{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){try{this.abort(a)}catch(c){this.log.error("error aborting muxer - %e",c)}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 Le(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 V;let t=this.onCreateStream({...this.streamOptions,...e});return qt(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 Se(`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 De=class extends Ie{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 at(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 at(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){if(!(this.readStatus==="closing"||this.readStatus==="closed")){this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",this.maybeDispatchEnd();try{await this.sendCloseRead(e)}catch(t){throw this.log.error("failed to close readable end - %e",t),t}finally{this.readStatus="closed"}this.log("closed readable end gracefully")}}};var Ce=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 ct}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 Ee("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)}},ct=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 l;(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"})(l||(l={}));var ie=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),ut=Object.freeze({NEW_STREAM:l.NEW_STREAM,MESSAGE:l.MESSAGE_INITIATOR,CLOSE:l.CLOSE_INITIATOR,RESET:l.RESET_INITIATOR}),Gt=Object.freeze({MESSAGE:l.MESSAGE_RECEIVER,CLOSE:l.CLOSE_RECEIVER,RESET:l.RESET_RECEIVER});var oe=1<<20,ht=4<<20,Te=class{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=oe,t=ht){this._buffer=new C,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 Y("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(h){if(h.name==="InvalidMessageError")throw h;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===l.NEW_STREAM||n===l.MESSAGE_INITIATOR||n===l.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}=Qt(e),{value:n,offset:i}=Qt(e,s),o=t&7;if(ie[o]==null)throw new Error(`Invalid type received: ${o}`);if(n>this._maxMessageSize)throw new Y("Message size too large");return{id:t>>3,type:o,offset:s+i,length:n}}},zs=128,jt=127;function Qt(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&jt)<<s:(i&jt)*Math.pow(2,s),s+=7}while(i>=zs);return e=n-e,{value:t,offset:e}}var ft=10*1024,lt=class{_pool;_poolOffset;constructor(){this._pool=L(ft),this._poolOffset=0}write(e,t){let s=this._pool,n=this._poolOffset;be(e.id<<3|e.type,s,n),n+=k(e.id<<3|e.type),(e.type===l.NEW_STREAM||e.type===l.MESSAGE_INITIATOR||e.type===l.MESSAGE_RECEIVER)&&e.data!=null?(be(e.data.length,s,n),n+=k(e.data.length)):(be(0,s,n),n+=k(0));let i=s.subarray(this._poolOffset,n);ft-n<100?(this._pool=L(ft),this._poolOffset=0):this._poolOffset=n,t.append(i),(e.type===l.NEW_STREAM||e.type===l.MESSAGE_INITIATOR||e.type===l.MESSAGE_RECEIVER)&&e.data!=null&&t.append(e.data)}},ks=new lt;function ae(r){let e=new C;return ks.write(r,e),e}var dt=class extends De{streamId;types;maxDataSize;muxer;constructor(e){super(e),this.types=e.direction==="outbound"?ut:Gt,this.maxDataSize=e.maxDataSize,this.muxer=e.muxer,this.streamId=parseInt(this.id.substring(1)),e.direction==="outbound"&&queueMicrotask(()=>{this.muxer.send(ae({id:this.streamId,type:ut.NEW_STREAM,data:new C(st(this.id))}))})}sendData(e){let t=new C,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(ae({id:this.streamId,type:this.types.MESSAGE,data:i}))}return{sentBytes:s,canSendMore:this.muxer.send(t)}}sendReset(){return this.muxer.send(ae({id:this.streamId,type:this.types.RESET}))}async sendCloseWrite(e){this.muxer.send(ae({id:this.streamId,type:this.types.CLOSE})),e?.signal?.throwIfAborted()}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}};function Kt(r){let{id:e,muxer:t,direction:s,maxMsgSize:n=oe}=r;return new dt({...r,id:s==="outbound"?`i${e}`:`r${e}`,direction:s,maxDataSize:n,muxer:t,log:r.log.newScope(`${s}:${e}`),protocol:""})}var Vs=5;function $s(r){let e={...r,type:`${ie[r.type]} (${r.type})`};return r.type===l.NEW_STREAM&&(e.data=ye(r.data.subarray())),(r.type===l.MESSAGE_INITIATOR||r.type===l.MESSAGE_RECEIVER)&&(e.data=ye(r.data.subarray(),"base16")),e}var Re=class extends Ae{_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??oe,this.maxUnprocessedMessageQueueSize=t.maxUnprocessedMessageQueueSize??ht,this.decoder=new Te(this.maxMessageSize,this.maxUnprocessedMessageQueueSize),this.rateLimiter=new Ce({points:t.disconnectThreshold??Vs,duration:1})}onData(e){for(let t of this.decoder.write(e))this.handleMessage(t)}onCreateStream(e){if(this.status!=="open")throw new V("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),Kt({...s,id:e,direction:t,maxMsgSize:this.maxMessageSize,log:this.log,muxer:this})}handleMessage(e){if(this.log.enabled&&this.log.trace("incoming message",$s(e)),e.type===l.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,ie[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 l.MESSAGE_INITIATOR:case l.MESSAGE_RECEIVER:s.onData(e.data);break;case l.CLOSE_INITIATOR:case l.CLOSE_RECEIVER:s.onRemoteCloseWrite();break;case l.RESET_INITIATOR:case l.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 mt=class{protocol="/mplex/6.7.0";_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@libp2p/mplex";[gt]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new Re(e,{...this._init})}};function Ws(r={}){return()=>new mt(r)}return er(qs);})();
|
|
2
|
+
"use strict";var Libp2PMplex=(()=>{var Me=Object.defineProperty;var Xt=Object.getOwnPropertyDescriptor;var Jt=Object.getOwnPropertyNames;var Zt=Object.prototype.hasOwnProperty;var D=(r,e)=>{for(var t in e)Me(r,t,{get:e[t],enumerable:!0})},Yt=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Jt(e))!Zt.call(r,n)&&n!==t&&Me(r,n,{get:()=>e[n],enumerable:!(s=Xt(e,n))||s.enumerable});return r};var er=r=>Yt(Me({},"__esModule",{value:!0}),r);var qs={};D(qs,{mplex:()=>Ws});var V=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},ue=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var N=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Z=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var Y=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var he=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},$=class extends Event{error;local;constructor(e,t,s){super("close",s),this.error=t,this.local=e}},fe=class extends ${constructor(e,t){super(!0,e,t)}},le=class extends ${constructor(e,t){super(!1,e,t)}};function tr(r){return typeof r?.handleEvent=="function"}function rr(r){return r===!0||r===!1}function sr(r){return rr(r)?r:r?.capture??!1}function Be(r){let e={capture:sr(r),once:!!r?.once};return r?.passive!=null&&(e.passive=r?.passive),r?.signal!=null&&(e.signal=r?.signal),e}function pt(r,e){return Be(r).capture===Be(e).capture}var W=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=Be(s);if(n?.signal?.aborted===!0)return;let i=h=>{n.once&&this.removeEventListener(e,t,n),tr(t)?t.handleEvent(h):t(h)},o=this.#e.get(e);if(o==null&&(o=[],this.#e.set(e,o)),o.some(h=>h.callback!==t?!1:pt(h.options,n)))return;super.addEventListener(e,i,n);let c=()=>{this.removeEventListener(e,t,n)};n.signal?.addEventListener("abort",c),o.push({callback:t,wrapper:i,options:n,onAbort:c})}removeEventListener(e,t,s){let n=this.#e.get(e);if(n==null){super.removeEventListener(e,t??null,s);return}this.#e.set(e,n.filter(i=>i.callback===t&&pt(i.options,s)?(super.removeEventListener(e,i.wrapper,s),i.options?.signal?.removeEventListener("abort",i.onAbort),!1):!0))}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var gt=Symbol.for("@libp2p/service-capabilities");function M(r=0){return new Uint8Array(r)}function L(r=0){return new Uint8Array(r)}function nr(r){return r?.buffer instanceof ArrayBuffer}function Ue(r){if(nr(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}function de(r,e){e==null&&(e=r.reduce((n,i)=>n+i.length,0));let t=L(e),s=0;for(let n of r)t.set(n,s),s+=n.length;return Ue(t)}function _e(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 wt=Symbol.for("@achingbrain/uint8arraylist");function bt(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 me(r){return!!r?.[wt]}var C=class r{bufs;length;[wt]=!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(me(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(me(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=bt(this.bufs,e);return t.buf[t.index]}set(e,t){let s=bt(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(me(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 de(s,n)}subarray(e,t){let{bufs:s,length:n}=this._subList(e,t);return s.length===1?s[0]:de(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 h=e>=a&&e<c,m=t>a&&t<=c;if(h&&m){if(e===a&&t===c){s.push(o);break}let d=e-a;s.push(o.subarray(d,d+(t-e)));break}if(h){if(e===0){s.push(o);continue}s.push(o.subarray(e-a));continue}if(m){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(!me(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 d=0;d<i;d++)o[d]=-1;for(let d=0;d<n;d++)o[s[d]]=d;let a=o,c=this.byteLength-s.byteLength,h=s.byteLength-1,m;for(let d=t;d<=c;d+=m){m=0;for(let p=h;p>=0;p--){let x=this.get(d+p);if(s[p]!==x){m=Math.max(1,p-a[x]);break}}if(m===0)return d}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=L(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=L(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(!_e(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={};D(ze,{base10:()=>lr});var Mn=new Uint8Array(0);function xt(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 R(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return z(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return z(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Et(r){let e=new Uint8Array(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}var yt=4096;function St(r){let e=r.length;if(e<=yt)return String.fromCharCode.apply(String,r);let t="",s=0;for(;s<e;)t+=String.fromCharCode.apply(String,r.subarray(s,s+=yt));return t}function ir(r){return r?.buffer instanceof ArrayBuffer}function z(r){return ir(r)?r:r.slice()}function or(r,e,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var s=new Uint8Array(256),n=0;n<s.length;n++)s[n]=255;for(var i=0;i<r.length;i++){var o=r.charAt(i),a=o.charCodeAt(0);if(s[a]!==255)throw new TypeError(o+" is ambiguous");if(s[a]=i,t){var c=o.toLowerCase().charCodeAt(0),h=o.toUpperCase().charCodeAt(0);c!==a&&(s[c]=i),h!==a&&(s[h]=i)}}var m=r.length,d=r.charAt(0),p=Math.log(m)/Math.log(256),x=Math.log(256)/Math.log(m);function _(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";for(var w=0,y=0,g=0,S=u.length;g!==S&&u[g]===0;)g++,w++;for(var T=(S-g)*x+1>>>0,P=new Uint8Array(T);g!==S;){for(var v=u[g],F=0,U=T-1;(v!==0||F<y)&&U!==-1;U--,F++)v+=256*P[U]>>>0,P[U]=v%m>>>0,v=v/m>>>0;if(v!==0)throw new Error("Non-zero carry");y=F,g++}for(var A=T-y;A!==T&&P[A]===0;)A++;for(var J=d.repeat(w);A<T;++A)J+=r.charAt(P[A]);return J}function E(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;var w=0;if(u[w]!==" "){for(var y=0,g=0;u[w]===d;)y++,w++;for(var S=(u.length-w)*p+1>>>0,T=new Uint8Array(S);u[w];){var P=u.charCodeAt(w);if(P>255)return;var v=s[P];if(v===255)return;for(var F=0,U=S-1;(v!==0||F<g)&&U!==-1;U--,F++)v+=m*T[U]>>>0,T[U]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");g=F,w++}if(u[w]!==" "){for(var A=S-g;A!==S&&T[A]===0;)A++;for(var J=new Uint8Array(y+(S-A)),Ht=y;A!==S;)J[Ht++]=T[A++];return J}}}function f(u){var w=E(u);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:_,decodeUnsafe:E,decode:f}}var ar=or,cr=ar,Lt=cr;var Ne=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")}},Oe=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 It(this,e)}},Pe=class{decoders;constructor(e){this.decoders=e}or(e){return It(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 It(r,e){return new Pe({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Fe=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 Ne(e,t,s),this.decoder=new Oe(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function q({name:r,prefix:e,encode:t,decode:s}){return new Fe(r,e,t,s)}function O({name:r,prefix:e,alphabet:t,caseInsensitive:s=!1}){let{encode:n,decode:i}=Lt(t,r,s);return q({prefix:e,name:r,encode:n,decode:o=>R(i(o))})}function ur(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 h=0;h<n;++h){let m=e[r[h]];if(m===void 0)throw new SyntaxError(`Non-${s} character`);a=a<<t|m,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 hr(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 fr(r,e){let t={};for(let s=0;s<r.length;++s)if(r[s]!=="="&&(t[r[s]]=s,e)){let n=r[s].toLowerCase(),i=r[s].toUpperCase();n!==r[s]&&(t[n]=s),i!==r[s]&&(t[i]=s)}return t}function b({name:r,prefix:e,bitsPerChar:t,alphabet:s,caseInsensitive:n=!1}){let i=fr(s,n);return q({prefix:e,name:r,encode(o){return hr(o,s,t)},decode(o){return ur(o,i,t,r)}})}var lr=O({prefix:"9",name:"base10",alphabet:"0123456789"});var ke={};D(ke,{base16:()=>dr,base16upper:()=>mr});var dr=b({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4,caseInsensitive:!0}),mr=b({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4,caseInsensitive:!0});var Ve={};D(Ve,{base2:()=>pr});var pr=b({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var $e={};D($e,{base256emoji:()=>xr});var At=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}"),gr=At.reduce((r,e,t)=>(r[t]=e,r),[]),br=At.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+=gr[t],e),"")}function yr(r){let e=[];for(let t of r){let s=t.codePointAt(0);if(s==null)throw new Error(`Invalid character: ${t}`);let n=br[s];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var xr=q({prefix:"\u{1F680}",name:"base256emoji",encode:wr,decode:yr});var We={};D(We,{base32:()=>G,base32hex:()=>Lr,base32hexpad:()=>Ar,base32hexpadupper:()=>Dr,base32hexupper:()=>Ir,base32pad:()=>Sr,base32padupper:()=>vr,base32upper:()=>Er,base32z:()=>Cr});var G=b({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),Er=b({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),Sr=b({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),vr=b({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),Lr=b({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),Ir=b({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),Ar=b({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),Dr=b({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),Cr=b({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var qe={};D(qe,{base36:()=>ee,base36upper:()=>Tr});var ee=O({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),Tr=O({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var Ge={};D(Ge,{base58btc:()=>B,base58flickr:()=>Rr});var B=O({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Rr=O({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var je={};D(je,{base64:()=>Mr,base64pad:()=>Br,base64url:()=>Ur,base64urlpad:()=>_r});var Mr=b({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Br=b({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ur=b({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),_r=b({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Qe={};D(Qe,{base8:()=>Nr});var Nr=b({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ke={};D(Ke,{identity:()=>Or});var Or=q({prefix:"\0",name:"identity",encode:r=>St(R(r)),decode:r=>R(Et(r))});var Qn=new TextEncoder,Kn=new TextDecoder;var Xe={};D(Xe,{identity:()=>is});var zr=Tt,Dt=128,kr=127,Vr=~kr,$r=Math.pow(2,31);function Tt(r,e,t){e=e||[],t=t||0;for(var s=t;r>=$r;)e[t++]=r&255|Dt,r/=128;for(;r&Vr;)e[t++]=r&255|Dt,r>>>=7;return e[t]=r|0,Tt.bytes=t-s+1,e}var Wr=He,qr=128,Ct=127;function He(r,s){var t=0,s=s||0,n=0,i=s,o,a=r.length;do{if(i>=a)throw He.bytes=0,new RangeError("Could not decode varint");o=r[i++],t+=n<28?(o&Ct)<<n:(o&Ct)*Math.pow(2,n),n+=7}while(o>=qr);return He.bytes=i-s,t}var Gr=Math.pow(2,7),jr=Math.pow(2,14),Qr=Math.pow(2,21),Kr=Math.pow(2,28),Hr=Math.pow(2,35),Xr=Math.pow(2,42),Jr=Math.pow(2,49),Zr=Math.pow(2,56),Yr=Math.pow(2,63),es=function(r){return r<Gr?1:r<jr?2:r<Qr?3:r<Kr?4:r<Hr?5:r<Xr?6:r<Jr?7:r<Zr?8:r<Yr?9:10},ts={encode:zr,decode:Wr,encodingLength:es},rs=ts,te=rs;function re(r,e=0){let t=te.decode(r,e),s=te.decode.bytes;if(s>9)throw new RangeError("Invalid varint: too long");if(s>1&&r[e+s-1]===0)throw new RangeError("Invalid varint: not minimally encoded");return[t,s]}function j(r,e,t=0){return te.encode(r,e,t),e}function Q(r){return te.encodingLength(r)}function H(r,e){let t=e.byteLength,s=Q(r),n=s+Q(t),i=new Uint8Array(n+t);return j(r,i,0),j(t,i,s),i.set(e,n),new K(r,t,e,i)}function Rt(r){let e=R(r),[t,s]=re(e),[n,i]=re(e.subarray(s)),o=e.subarray(s+i);if(o.byteLength!==n)throw new Error("Incorrect length");return new K(t,n,o,e)}function Mt(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&xt(r.bytes,t.bytes)}}var K=class{code;size;digest;bytes;constructor(e,t,s,n){this.code=e,this.size=t,this.digest=z(s),this.bytes=z(n)}};var Bt=0,ss="identity",Ut=R;function ns(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 H(Bt,Ut(r))}var is={code:Bt,name:ss,encode:Ut,digest:ns};var Ye={};D(Ye,{sha256:()=>as,sha512:()=>cs});var os=20;function Ze({name:r,code:e,encode:t,minDigestLength:s,maxDigestLength:n}){return new Je(r,e,t,s,n)}var Je=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,s,n,i){this.name=e,this.code=t,this.encode=s,this.minDigestLength=n??os,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?_t(s,this.code,t?.truncate):s.then(n=>_t(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function _t(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 H(e,r)}function Ot(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var as=Ze({name:"sha2-256",code:18,encode:Ot("SHA-256")}),cs=Ze({name:"sha2-512",code:19,encode:Ot("SHA-512")});function Pt(r,e){let{bytes:t,version:s}=r;return s===0?hs(t,et(r),e??B.encoder):fs(t,et(r),e??G.encoder)}var Ft=new WeakMap;function et(r){let e=Ft.get(r);if(e==null){let t=new Map;return Ft.set(r,t),t}return e}var ge=class r{code;version;multihash;bytes;"/";constructor(e,t,s,n){this.code=t,this.version=e,this.multihash=s,this.bytes=z(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!==ne)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==ls)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=H(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&&Mt(e.multihash,s.multihash)}toString(e){return Pt(this,e)}toJSON(){return{"/":Pt(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??zt(s,n,i.bytes))}else if(t[ds]===!0){let{version:s,multihash:n,code:i}=t,o=Rt(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!==ne)throw new Error(`Version 0 CID must use dag-pb (code: ${ne}) block encoding`);return new r(e,t,s,s.bytes)}case 1:{let n=zt(e,t,s.bytes);return new r(e,t,s,n)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,ne,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=R(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 K(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[d,p]=re(e.subarray(t));return t+=p,d},n=s(),i=ne;if(n===18)n=0,t=0;else if(n===1)i=s();else throw n===0?new RangeError("Invalid CID version, v0 is always implicit"):new RangeError(`Invalid CID version ${n}`);let o=t,a=s(),c=s(),h=t+c,m=h-o;return{version:n,codec:i,multihashCode:a,digestSize:c,multihashSize:m,size:h}}static parse(e,t){let[s,n]=us(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 et(i).set(s,e),i}};function us(r,e){switch(r[0]){case"Q":{let t=e??B;return[B.prefix,t.decode(`${B.prefix}${r}`)]}case B.prefix:{let t=e??B;return[B.prefix,t.decode(r)]}case G.prefix:{let t=e??G;return[G.prefix,t.decode(r)]}case ee.prefix:{let t=e??ee;return[ee.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 hs(r,e,t){let{prefix:s}=t;if(s!==B.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 fs(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 ne=112,ls=18;function zt(r,e,t){let s=Q(r),n=s+Q(e),i=new Uint8Array(n+t.byteLength);return j(r,i,0),j(e,i,s),i.set(t,n),i}var ds=Symbol.for("@ipld/js-cid/CID");var tt={...Ke,...Ve,...Qe,...ze,...ke,...We,...qe,...Ge,...je,...$e},gi={...Ye,...Xe};function Vt(r,e,t,s){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:s}}}var kt=Vt("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),rt=Vt("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=L(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ms={utf8:kt,"utf-8":kt,hex:tt.base16,latin1:rt,ascii:rt,binary:rt,...tt},be=ms;function st(r,e="utf8"){let t=be[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var ps=Math.pow(2,7),gs=Math.pow(2,14),bs=Math.pow(2,21),ws=Math.pow(2,28),ys=Math.pow(2,35),xs=Math.pow(2,42),Es=Math.pow(2,49),I=128;function k(r){if(r<ps)return 1;if(r<gs)return 2;if(r<bs)return 3;if(r<ws)return 4;if(r<ys)return 5;if(r<xs)return 6;if(r<Es)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ss(r,e,t=0){switch(k(r)){case 8:e[t++]=r&255|I,r/=128;case 7:e[t++]=r&255|I,r/=128;case 6:e[t++]=r&255|I,r/=128;case 5:e[t++]=r&255|I,r/=128;case 4:e[t++]=r&255|I,r>>>=7;case 3:e[t++]=r&255|I,r>>>=7;case 2:e[t++]=r&255|I,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function vs(r,e,t=0){switch(k(r)){case 8:e.set(t++,r&255|I),r/=128;case 7:e.set(t++,r&255|I),r/=128;case 6:e.set(t++,r&255|I),r/=128;case 5:e.set(t++,r&255|I),r/=128;case 4:e.set(t++,r&255|I),r>>>=7;case 3:e.set(t++,r&255|I),r>>>=7;case 2:e.set(t++,r&255|I),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function we(r,e,t=0){return e==null&&(e=L(k(r))),e instanceof Uint8Array?Ss(r,e,t):vs(r,e,t)}function ye(r,e="utf8"){let t=be[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function xe(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Ee=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}},X=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new Ee(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 Ee(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 nt=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 Is(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 Is(r,e){e=e??{};let t=e.onEnd,s=new X,n,i,o,a=xe(),c=async()=>{try{return s.isEmpty()?o?{done:!0}:await new Promise((f,u)=>{i=w=>{i=null,s.push(w);try{f(r(s))}catch(y){u(y)}return n}}):r(s)}finally{s.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=xe()})}},h=f=>i!=null?i(f):(s.push(f),n),m=f=>(s=new X,i!=null?i({error:f}):(s.push({error:f}),n)),d=f=>{if(o)return n;if(e?.objectMode!==!0&&f?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return h({done:!1,value:f})},p=f=>o?n:(o=!0,f!=null?m(f):h({done:!0})),x=()=>(s=new X,p(),{done:!0}),_=f=>(p(f),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:c,return:x,throw:_,push:d,end:p,get readableLength(){return s.size},onEmpty:async f=>{let u=f?.signal;if(u?.throwIfAborted(),s.isEmpty())return;let w,y;u!=null&&(w=new Promise((g,S)=>{y=()=>{S(new nt)},u.addEventListener("abort",y)}));try{await Promise.race([a.promise,w])}finally{y!=null&&u!=null&&u?.removeEventListener("abort",y)}}},t==null)return n;let E=n;return n={[Symbol.asyncIterator](){return this},next(){return E.next()},throw(f){return E.throw(f),t!=null&&(t(f),t=void 0),{done:!0}},return(){return E.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(f){return E.end(f),t!=null&&(t(f),t=void 0),n},get readableLength(){return E.readableLength},onEmpty:f=>E.onEmpty(f)},n}var it=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},As=r=>"reason"in r?r.reason:new DOMException("This operation was aborted.","AbortError"),Ds=2**31-1,Cs=(r,e)=>{if(typeof r!="number"||Math.sign(r)!==1)return new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(typeof e?.setTimeout!="function"||typeof e?.clearTimeout!="function")return new TypeError("Expected `customTimers` to have a `setTimeout` and a `clearTimeout` function")};function ot(r,e){let{milliseconds:t,fallback:s,message:n,customTimers:i={setTimeout,clearTimeout},signal:o}=e,a,c,h=()=>{try{r.cancel?.()}catch{}},d=new Promise((p,x)=>{let _=()=>{x(As(o)),h()},E=Cs(t,i);try{E?x(E):o?.aborted?_():o&&(c=_,o.addEventListener("abort",c,{once:!0}))}finally{r.then(p,x)}if(E||o?.aborted||t>Ds)return;let f=s||n===!1||n instanceof Error?void 0:new it(n??`Promise timed out after ${t} milliseconds`);a=i.setTimeout.call(void 0,()=>{if(s)try{p(s())}catch(u){x(u)}else n===!1?p():x(n instanceof Error?n:f);h()},t)}).finally(()=>{try{d.clear()}catch{}try{c&&o.removeEventListener("abort",c)}catch{}});return d.clear=()=>{a!==void 0&&(i.clearTimeout.call(void 0,a),a=void 0)},d}var Wt=r=>typeof r=="function"?{filter:r}:{...r},Ts=r=>r===1/0||Number.isSafeInteger(r)&&r>=0,Rs=[["addEventListener","removeEventListener"],["on","off"],["addListener","removeListener"]],Ms=r=>{for(let[e,t]of Rs){let s=r?.[e],n=r?.[t];if(typeof s=="function"&&typeof n=="function")return{addListener:s.bind(r),removeListener:n.bind(r)}}throw new TypeError("Emitter is not compatible")},Bs=r=>{let e=new Map;for(let[t,s]of r)for(let n of Array.isArray(t)?t:[t])e.has(n)||e.set(n,s);return e},Us=({addListener:r,removeListener:e,handlers:t,signal:s,abortHandler:n,isDone:i})=>{s?.addEventListener("abort",n,{once:!0});for(let[o,a]of t)if(r(o,a),i()){e(o,a);return}},_s=({removeListener:r,handlers:e,signal:t,abortHandler:s})=>{for(let[n,i]of e)r(n,i);t?.removeEventListener("abort",s)},Ns=(r,e,t)=>{let s=Promise.resolve();return(n,i)=>{s=s.then(async()=>{if(e())return;let o;try{o=r?await r(n):!0}catch(a){e()||t(a);return}e()||i(o)})}};function Os(r,e,t){let s=()=>{},n=!1,i,o=new Promise((a,c)=>{t=Wt(t);let{filter:h}=t;if(!Ts(t.count))throw new TypeError("The `count` option should be at least 0 or more");if(typeof t.timeout=="number"&&!(t.timeout>0))throw new TypeError(`Expected the \`timeout\` option to be a positive number, got \`${t.timeout}\``);t.signal?.throwIfAborted();let{addListener:m,removeListener:d}=Ms(r);if(t.count===0){a([]);return}let p=[],x=g=>{s(),c(g)},_=Ns(h,()=>n,x),E=g=>{p.push(g),t.count===p.length&&(s(),a(p))},f=(...g)=>{if(n)return;let S=t.multiArgs?g:g[0];if(!h){E(S);return}_(S,T=>{T&&E(S)})},u=(...g)=>{x(t.rejectionMultiArgs?g:g[0])},w=()=>{x(t.signal.reason)},y={addListener:m,removeListener:d,handlers:Bs([[e,f],[t.rejectionEvents??["error"],u]]),signal:t.signal,abortHandler:w,isDone:()=>n};s=()=>{n=!0,clearTimeout(i),_s(y)},Us(y),!(n||!t.resolveImmediately)&&(Number.isFinite(t.timeout)&&t.timeout<=2**31-1&&(i=setTimeout(s,t.timeout)),a(p))});if(o.cancel=s,typeof t.timeout=="number"&&t.timeout>0&&!t.resolveImmediately){let a=ot(o,{milliseconds:t.timeout});return a.cancel=()=>{s(),a.clear()},a}return o}function at(r,e,t){let s=Os(r,e,{...Wt(t),count:1,resolveImmediately:!1}),n=s.then(i=>i[0]);return n.cancel=s.cancel,n}var Se=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 ve=class extends Error{static name="MaxEarlyStreamsError";name="MaxEarlyStreamsError"},ie=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function Ps(r){return r.reason}function Le(r,e,t){if(e==null||r==null)return r;let s=t?.translateError??Ps;if(e.aborted)return r.catch(()=>{}),Promise.reject(s(e));let n;return Promise.race([r,new Promise((i,o)=>{n=()=>{o(s(e))},e.addEventListener("abort",n)})]).finally(()=>{n!=null&&e.removeEventListener("abort",n)})}var Fs=Math.pow(2,20)*4,Ie=class extends W{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;#e=!1;#t;#r=new Set;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??Fs,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new C,this.writeBuffer=new C,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.onDrainPromise=void 0};this.addEventListener("drain",t);let s=n=>{this.onDrainPromise?.reject(n.error??new ie),this.onDrainPromise=void 0};this.addEventListener("close",s)}get readBufferLength(){return this.readBuffer.byteLength}get readableEnded(){return this.#e}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){if(this.writeStatus==="closed")throw this.#t??new ie;return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Le(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){let e=$t(),t,s=i=>{e.push(i.data)};this.addEventListener("message",s);let n=()=>{this.#r.delete(n),this.removeEventListener("message",s),t=this.#t,e.end()};this.#r.add(n),this.readableDone()&&n();try{if(yield*e,t!=null)throw t}finally{this.removeEventListener("message",s),this.#r.delete(n)}}readableDone(){return this.readBuffer.byteLength===0&&(this.remoteWriteStatus==="closed"||this.readStatus==="closing"||this.readStatus==="closed")}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new N(`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.readBuffer.byteLength>0&&(this.#t??=e,this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closed",this.maybeDispatchEnd());return}this.log.error("abort with error - %e",e),this.status="aborted",this.#t=e,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(),this.maybeDispatchEnd();try{this.sendReset(e)}catch(t){this.log.error("failed to send reset to remote - %e",t)}this.dispatchEvent(new fe(e))}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new N("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 N("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 N(`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 N(`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(){if(this.status==="aborted"||this.status==="reset"||this.status==="closed")return;this.log("remote reset");let e=new ue;this.#t=e,this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed",this.maybeDispatchEnd()),this.dispatchEvent(new le(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.maybeDispatchEnd(),this.dispatchEvent(new $))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.maybeDispatchEnd(),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 C(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}}maybeDispatchEnd(){this.readableDone()&&(this.#r.forEach(e=>{e()}),!this.#e&&(this.#e=!0,this.safeDispatchEvent("end")))}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 he(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.maybeDispatchEnd()),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new Z(`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 Z(`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 qt(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ae=class extends W{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){try{this.abort(a)}catch(c){this.log.error("error aborting muxer - %e",c)}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 Le(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 V;let t=this.onCreateStream({...this.streamOptions,...e});return qt(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 ve(`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 De=class extends Ie{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 at(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 at(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){if(!(this.readStatus==="closing"||this.readStatus==="closed")){this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.readStatus="closing",this.maybeDispatchEnd();try{await this.sendCloseRead(e)}catch(t){throw this.log.error("failed to close readable end - %e",t),t}finally{this.readStatus="closed"}this.log("closed readable end gracefully")}}};var Ce=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 ct}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 Se("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)}},ct=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 l;(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"})(l||(l={}));var oe=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),ut=Object.freeze({NEW_STREAM:l.NEW_STREAM,MESSAGE:l.MESSAGE_INITIATOR,CLOSE:l.CLOSE_INITIATOR,RESET:l.RESET_INITIATOR}),Gt=Object.freeze({MESSAGE:l.MESSAGE_RECEIVER,CLOSE:l.CLOSE_RECEIVER,RESET:l.RESET_RECEIVER});var ae=1<<20,ht=4<<20,Te=class{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=ae,t=ht){this._buffer=new C,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 Y("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(h){if(h.name==="InvalidMessageError")throw h;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===l.NEW_STREAM||n===l.MESSAGE_INITIATOR||n===l.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}=Qt(e),{value:n,offset:i}=Qt(e,s),o=t&7;if(oe[o]==null)throw new Error(`Invalid type received: ${o}`);if(n>this._maxMessageSize)throw new Y("Message size too large");return{id:t>>3,type:o,offset:s+i,length:n}}},zs=128,jt=127;function Qt(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&jt)<<s:(i&jt)*Math.pow(2,s),s+=7}while(i>=zs);return e=n-e,{value:t,offset:e}}var ft=10*1024,lt=class{_pool;_poolOffset;constructor(){this._pool=L(ft),this._poolOffset=0}write(e,t){let s=this._pool,n=this._poolOffset;we(e.id<<3|e.type,s,n),n+=k(e.id<<3|e.type),(e.type===l.NEW_STREAM||e.type===l.MESSAGE_INITIATOR||e.type===l.MESSAGE_RECEIVER)&&e.data!=null?(we(e.data.length,s,n),n+=k(e.data.length)):(we(0,s,n),n+=k(0));let i=s.subarray(this._poolOffset,n);ft-n<100?(this._pool=L(ft),this._poolOffset=0):this._poolOffset=n,t.append(i),(e.type===l.NEW_STREAM||e.type===l.MESSAGE_INITIATOR||e.type===l.MESSAGE_RECEIVER)&&e.data!=null&&t.append(e.data)}},ks=new lt;function ce(r){let e=new C;return ks.write(r,e),e}var dt=class extends De{streamId;types;maxDataSize;muxer;constructor(e){super(e),this.types=e.direction==="outbound"?ut:Gt,this.maxDataSize=e.maxDataSize,this.muxer=e.muxer,this.streamId=parseInt(this.id.substring(1)),e.direction==="outbound"&&queueMicrotask(()=>{this.muxer.send(ce({id:this.streamId,type:ut.NEW_STREAM,data:new C(st(this.id))}))})}sendData(e){let t=new C,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(ce({id:this.streamId,type:this.types.MESSAGE,data:i}))}return{sentBytes:s,canSendMore:this.muxer.send(t)}}sendReset(){return this.muxer.send(ce({id:this.streamId,type:this.types.RESET}))}async sendCloseWrite(e){this.muxer.send(ce({id:this.streamId,type:this.types.CLOSE})),e?.signal?.throwIfAborted()}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}};function Kt(r){let{id:e,muxer:t,direction:s,maxMsgSize:n=ae}=r;return new dt({...r,id:s==="outbound"?`i${e}`:`r${e}`,direction:s,maxDataSize:n,muxer:t,log:r.log.newScope(`${s}:${e}`),protocol:""})}var Vs=5;function $s(r){let e={...r,type:`${oe[r.type]} (${r.type})`};return r.type===l.NEW_STREAM&&(e.data=ye(r.data.subarray())),(r.type===l.MESSAGE_INITIATOR||r.type===l.MESSAGE_RECEIVER)&&(e.data=ye(r.data.subarray(),"base16")),e}var Re=class extends Ae{_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??ae,this.maxUnprocessedMessageQueueSize=t.maxUnprocessedMessageQueueSize??ht,this.decoder=new Te(this.maxMessageSize,this.maxUnprocessedMessageQueueSize),this.rateLimiter=new Ce({points:t.disconnectThreshold??Vs,duration:1})}onData(e){for(let t of this.decoder.write(e))this.handleMessage(t)}onCreateStream(e){if(this.status!=="open")throw new V("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),Kt({...s,id:e,direction:t,maxMsgSize:this.maxMessageSize,log:this.log,muxer:this})}handleMessage(e){if(this.log.enabled&&this.log.trace("incoming message",$s(e)),e.type===l.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,oe[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 l.MESSAGE_INITIATOR:case l.MESSAGE_RECEIVER:s.onData(e.data);break;case l.CLOSE_INITIATOR:case l.CLOSE_RECEIVER:s.onRemoteCloseWrite();break;case l.RESET_INITIATOR:case l.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 mt=class{protocol="/mplex/6.7.0";_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@libp2p/mplex";[gt]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new Re(e,{...this._init})}};function Ws(r={}){return()=>new mt(r)}return er(qs);})();
|
|
3
3
|
return Libp2PMplex}));
|
|
4
4
|
//# sourceMappingURL=index.min.js.map
|