@libp2p/mplex 9.0.12-c960eb659 → 9.0.12-d8f5bc211
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/README.md +6 -4
- package/dist/index.min.js +5 -5
- package/dist/src/index.d.ts +2 -1
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +5 -3
- package/dist/src/index.js.map +1 -1
- package/dist/src/mplex.d.ts +7 -2
- package/dist/src/mplex.d.ts.map +1 -1
- package/dist/src/mplex.js +27 -21
- package/dist/src/mplex.js.map +1 -1
- package/dist/src/stream.d.ts +3 -1
- package/dist/src/stream.d.ts.map +1 -1
- package/dist/src/stream.js +2 -3
- package/dist/src/stream.js.map +1 -1
- package/package.json +11 -10
- package/src/index.ts +7 -5
- package/src/mplex.ts +33 -24
- package/src/stream.ts +4 -3
package/README.md
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
[](http://libp2p.io/)
|
2
2
|
[](https://discuss.libp2p.io)
|
3
3
|
[](https://codecov.io/gh/libp2p/js-libp2p)
|
4
|
-
[](https://github.com/libp2p/js-libp2p/actions/workflows/main.yml?query=branch%3Amain)
|
5
5
|
|
6
6
|
> JavaScript implementation of <https://github.com/libp2p/mplex>
|
7
7
|
|
@@ -19,17 +19,19 @@ Loading this module through a script tag will make it's exports available as `Li
|
|
19
19
|
<script src="https://unpkg.com/@libp2p/mplex/dist/index.min.js"></script>
|
20
20
|
```
|
21
21
|
|
22
|
-
|
22
|
+
> JavaScript implementation of <https://github.com/libp2p/mplex>
|
23
|
+
|
24
|
+
# API Docs
|
23
25
|
|
24
26
|
- <https://libp2p.github.io/js-libp2p/modules/_libp2p_mplex.html>
|
25
27
|
|
26
|
-
|
28
|
+
# License
|
27
29
|
|
28
30
|
Licensed under either of
|
29
31
|
|
30
32
|
- Apache 2.0, ([LICENSE-APACHE](LICENSE-APACHE) / <http://www.apache.org/licenses/LICENSE-2.0>)
|
31
33
|
- MIT ([LICENSE-MIT](LICENSE-MIT) / <http://opensource.org/licenses/MIT>)
|
32
34
|
|
33
|
-
|
35
|
+
# Contribution
|
34
36
|
|
35
37
|
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
|
package/dist/index.min.js
CHANGED
@@ -1,15 +1,15 @@
|
|
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 wi=Object.create;var be=Object.defineProperty;var xi=Object.getOwnPropertyDescriptor;var Ei=Object.getOwnPropertyNames;var _i=Object.getPrototypeOf,Si=Object.prototype.hasOwnProperty;var g=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),L=(i,e)=>{for(var t in e)be(i,t,{get:e[t],enumerable:!0})},kt=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ei(e))!Si.call(i,s)&&s!==t&&be(i,s,{get:()=>e[s],enumerable:!(r=xi(e,s))||r.enumerable});return i};var Mt=(i,e,t)=>(t=i!=null?wi(_i(i)):{},kt(e||!i||!i.__esModule?be(t,"default",{value:i,enumerable:!0}):t,i)),Ci=i=>kt(be({},"__esModule",{value:!0}),i);var Dt=g((io,Pt)=>{var Y=1e3,Q=Y*60,X=Q*60,K=X*24,Ri=K*7,Ai=K*365.25;Pt.exports=function(i,e){e=e||{};var t=typeof i;if(t==="string"&&i.length>0)return Ii(i);if(t==="number"&&isFinite(i))return e.long?Ti(i):Li(i);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(i))};function Ii(i){if(i=String(i),!(i.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(i);if(e){var t=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return t*Ai;case"weeks":case"week":case"w":return t*Ri;case"days":case"day":case"d":return t*K;case"hours":case"hour":case"hrs":case"hr":case"h":return t*X;case"minutes":case"minute":case"mins":case"min":case"m":return t*Q;case"seconds":case"second":case"secs":case"sec":case"s":return t*Y;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Li(i){var e=Math.abs(i);return e>=K?Math.round(i/K)+"d":e>=X?Math.round(i/X)+"h":e>=Q?Math.round(i/Q)+"m":e>=Y?Math.round(i/Y)+"s":i+"ms"}function Ti(i){var e=Math.abs(i);return e>=K?ye(i,e,K,"day"):e>=X?ye(i,e,X,"hour"):e>=Q?ye(i,e,Q,"minute"):e>=Y?ye(i,e,Y,"second"):i+" ms"}function ye(i,e,t,r){var s=e>=t*1.5;return Math.round(i/t)+" "+r+(s?"s":"")}});var vt=g((so,Ot)=>{function Ni(i){t.debug=t,t.default=t,t.coerce=c,t.disable=n,t.enable=s,t.enabled=o,t.humanize=Dt(),t.destroy=h,Object.keys(i).forEach(u=>{t[u]=i[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let l=0;for(let d=0;d<u.length;d++)l=(l<<5)-l+u.charCodeAt(d),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(u){let l,d=null,w,m;function p(...f){if(!p.enabled)return;let y=p,E=Number(new Date),_=E-(l||E);y.diff=_,y.prev=l,y.curr=E,l=E,f[0]=t.coerce(f[0]),typeof f[0]!="string"&&f.unshift("%O");let S=0;f[0]=f[0].replace(/%([a-zA-Z%])/g,(P,I)=>{if(P==="%%")return"%";S++;let D=t.formatters[I];if(typeof D=="function"){let H=f[S];P=D.call(y,H),f.splice(S,1),S--}return P}),t.formatArgs.call(y,f),(y.log||t.log).apply(y,f)}return p.namespace=u,p.useColors=t.useColors(),p.color=t.selectColor(u),p.extend=r,p.destroy=t.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(w!==t.namespaces&&(w=t.namespaces,m=t.enabled(u)),m),set:f=>{d=f}}),typeof t.init=="function"&&t.init(p),p}function r(u,l){let d=t(this.namespace+(typeof l>"u"?":":l)+u);return d.log=this.log,d}function s(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let l,d=(typeof u=="string"?u:"").split(/[\s,]+/),w=d.length;for(l=0;l<w;l++)d[l]&&(u=d[l].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.slice(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function n(){let u=[...t.names.map(a),...t.skips.map(a).map(l=>"-"+l)].join(",");return t.enable(""),u}function o(u){if(u[u.length-1]==="*")return!0;let l,d;for(l=0,d=t.skips.length;l<d;l++)if(t.skips[l].test(u))return!1;for(l=0,d=t.names.length;l<d;l++)if(t.names[l].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack||u.message:u}function h(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}Ot.exports=Ni});var Bt=g((T,ge)=>{T.formatArgs=Mi;T.save=Pi;T.load=Di;T.useColors=ki;T.storage=Oi();T.destroy=(()=>{let i=!1;return()=>{i||(i=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();T.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function ki(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Mi(i){if(i[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+i[0]+(this.useColors?"%c ":" ")+"+"+ge.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;i.splice(1,0,e,"color: inherit");let t=0,r=0;i[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(r=t))}),i.splice(r,0,e)}T.log=console.debug||console.log||(()=>{});function Pi(i){try{i?T.storage.setItem("debug",i):T.storage.removeItem("debug")}catch{}}function Di(){let i;try{i=T.storage.getItem("debug")}catch{}return!i&&typeof process<"u"&&"env"in process&&(i=process.env.DEBUG),i}function Oi(){try{return localStorage}catch{}}ge.exports=vt()(T);var{formatters:vi}=ge.exports;vi.j=function(i){try{return JSON.stringify(i)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var ue=g((Bo,Xt)=>{Xt.exports=class{constructor(e={}){this.points=e.points,this.duration=e.duration,this.blockDuration=e.blockDuration,this.execEvenly=e.execEvenly,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs,this.keyPrefix=e.keyPrefix}get points(){return this._points}set points(e){this._points=e>=0?e:4}get duration(){return this._duration}set duration(e){this._duration=typeof e>"u"?1:e}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(e){this._blockDuration=typeof e>"u"?0:e}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(e){this._execEvenly=typeof e>"u"?!1:!!e}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(e){this._execEvenlyMinDelayMs=typeof e>"u"?Math.ceil(this.msDuration/this.points):e}get keyPrefix(){return this._keyPrefix}set keyPrefix(e){if(typeof e>"u"&&(e="rlflx"),typeof e!="string")throw new Error("keyPrefix must be string");this._keyPrefix=e}_getKeySecDuration(e={}){return e&&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)}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}}});var Zt=g((Uo,Jt)=>{Jt.exports=class{constructor(){this._keys={},this._addedKeysAmount=0}collectExpired(){let e=Date.now();Object.keys(this._keys).forEach(t=>{this._keys[t]<=e&&delete this._keys[t]}),this._addedKeysAmount=Object.keys(this._keys).length}add(e,t){this.addMs(e,t*1e3)}addMs(e,t){this._keys[e]=Date.now()+t,this._addedKeysAmount++,this._addedKeysAmount>999&&this.collectExpired()}msBeforeExpire(e){let t=this._keys[e];if(t&&t>=Date.now()){this.collectExpired();let r=Date.now();return t>=r?t-r:0}return 0}delete(e){e?delete this._keys[e]:Object.keys(this._keys).forEach(t=>{delete this._keys[t]})}}});var tr=g((qo,er)=>{var ns=Zt();er.exports=ns});var k=g((zo,rr)=>{rr.exports=class{constructor(e,t,r,s){this.remainingPoints=typeof e>"u"?0:e,this.msBeforeNext=typeof t>"u"?0:t,this.consumedPoints=typeof r>"u"?0:r,this.isFirstInDuration=typeof s>"u"?!1:s}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(e){return this._msBeforeNext=e,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(e){return this._remainingPoints=e,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(e){return this._consumedPoints=e,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(e){this._isFirstInDuration=!!e}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}}});var te=g((Wo,sr)=>{var We=ue(),os=tr(),ir=k();sr.exports=class extends We{constructor(e={}){super(e),this.inMemoryBlockOnConsumed=e.inMemoryBlockOnConsumed,this.inMemoryBlockDuration=e.inMemoryBlockDuration,this.insuranceLimiter=e.insuranceLimiter,this._inMemoryBlockedKeys=new os}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("storeClient is not set");this._client=e}_afterConsume(e,t,r,s,n,o={}){let a=this._getRateLimiterRes(r,s,n);if(this.inMemoryBlockOnConsumed>0&&!(this.inMemoryBlockDuration>0)&&a.consumedPoints>=this.inMemoryBlockOnConsumed)return this._inMemoryBlockedKeys.addMs(r,a.msBeforeNext),a.consumedPoints>this.points?t(a):e(a);if(a.consumedPoints>this.points){let c=Promise.resolve();this.blockDuration>0&&a.consumedPoints<=this.points+s&&(a.msBeforeNext=this.msBlockDuration,c=this._block(r,a.consumedPoints,this.msBlockDuration,o)),this.inMemoryBlockOnConsumed>0&&a.consumedPoints>=this.inMemoryBlockOnConsumed&&(this._inMemoryBlockedKeys.add(r,this.inMemoryBlockDuration),a.msBeforeNext=this.msInMemoryBlockDuration),c.then(()=>{t(a)}).catch(h=>{t(h)})}else if(this.execEvenly&&a.msBeforeNext>0&&!a.isFirstInDuration){let c=Math.ceil(a.msBeforeNext/(a.remainingPoints+2));c<this.execEvenlyMinDelayMs&&(c=a.consumedPoints*this.execEvenlyMinDelayMs),setTimeout(e,c,a)}else e(a)}_handleError(e,t,r,s,n,o=!1,a={}){this.insuranceLimiter instanceof We?this.insuranceLimiter[t](n,o,a).then(c=>{r(c)}).catch(c=>{s(c)}):s(e)}getInMemoryBlockMsBeforeExpire(e){return this.inMemoryBlockOnConsumed>0?this._inMemoryBlockedKeys.msBeforeExpire(e):0}get inMemoryBlockOnConsumed(){return this._inMemoryBlockOnConsumed}set inMemoryBlockOnConsumed(e){if(this._inMemoryBlockOnConsumed=e?parseInt(e):0,this.inMemoryBlockOnConsumed>0&&this.points>this.inMemoryBlockOnConsumed)throw new Error('inMemoryBlockOnConsumed option must be greater or equal "points" option')}get inMemoryBlockDuration(){return this._inMemoryBlockDuration}set inMemoryBlockDuration(e){if(this._inMemoryBlockDuration=e?parseInt(e):0,this.inMemoryBlockDuration>0&&this.inMemoryBlockOnConsumed===0)throw new Error("inMemoryBlockOnConsumed option must be set up")}get msInMemoryBlockDuration(){return this._inMemoryBlockDuration*1e3}get insuranceLimiter(){return this._insuranceLimiter}set insuranceLimiter(e){if(typeof e<"u"&&!(e instanceof We))throw new Error("insuranceLimiter must be instance of RateLimiterAbstract");this._insuranceLimiter=e,this._insuranceLimiter&&(this._insuranceLimiter.blockDuration=this.blockDuration,this._insuranceLimiter.execEvenly=this.execEvenly)}block(e,t,r={}){let s=t*1e3;return this._block(this.getKey(e),this.points+1,s,r)}set(e,t,r,s={}){let n=(r>=0?r:this.duration)*1e3;return this._block(this.getKey(e),t,n,s)}consume(e,t=1,r={}){return new Promise((s,n)=>{let o=this.getKey(e),a=this.getInMemoryBlockMsBeforeExpire(o);if(a>0)return n(new ir(0,a));this._upsert(o,t,this._getKeySecDuration(r)*1e3,!1,r).then(c=>{this._afterConsume(s,n,o,t,c)}).catch(c=>{this._handleError(c,"consume",s,n,e,t,r)})})}penalty(e,t=1,r={}){let s=this.getKey(e);return new Promise((n,o)=>{this._upsert(s,t,this._getKeySecDuration(r)*1e3,!1,r).then(a=>{n(this._getRateLimiterRes(s,t,a))}).catch(a=>{this._handleError(a,"penalty",n,o,e,t,r)})})}reward(e,t=1,r={}){let s=this.getKey(e);return new Promise((n,o)=>{this._upsert(s,-t,this._getKeySecDuration(r)*1e3,!1,r).then(a=>{n(this._getRateLimiterRes(s,-t,a))}).catch(a=>{this._handleError(a,"reward",n,o,e,t,r)})})}get(e,t={}){let r=this.getKey(e);return new Promise((s,n)=>{this._get(r,t).then(o=>{s(o===null||typeof o>"u"?null:this._getRateLimiterRes(r,0,o))}).catch(o=>{this._handleError(o,"get",s,n,e,t)})})}delete(e,t={}){let r=this.getKey(e);return new Promise((s,n)=>{this._delete(r,t).then(o=>{this._inMemoryBlockedKeys.delete(r),s(o)}).catch(o=>{this._handleError(o,"delete",s,n,e,t)})})}deleteInMemoryBlockedAll(){this._inMemoryBlockedKeys.delete()}_getRateLimiterRes(e,t,r){throw new Error("You have to implement the method '_getRateLimiterRes'!")}_block(e,t,r,s={}){return new Promise((n,o)=>{this._upsert(e,t,r,!0,s).then(()=>{n(new ir(0,r>0?r:-1,t))}).catch(a=>{this._handleError(a,"block",n,o,this.parseKey(e),r/1e3,s)})})}_get(e,t={}){throw new Error("You have to implement the method '_get'!")}_delete(e,t={}){throw new Error("You have to implement the method '_delete'!")}_upsert(e,t,r,s=!1,n={}){throw new Error("You have to implement the method '_upsert'!")}}});var or=g((Ko,nr)=>{var as=te(),cs=k(),Ke="redis.call('set', KEYS[1], 0, 'EX', ARGV[2], 'NX') local consumed = redis.call('incrby', KEYS[1], ARGV[1]) local ttl = redis.call('pttl', KEYS[1]) if ttl == -1 then redis.call('expire', KEYS[1], ARGV[2]) ttl = 1000 * ARGV[2] end return {consumed, ttl} ",Ge=class extends as{constructor(e){super(e),this.client=e.storeClient,this._rejectIfRedisNotReady=!!e.rejectIfRedisNotReady,this.useRedisPackage=e.useRedisPackage,this.useRedis3AndLowerPackage=e.useRedis3AndLowerPackage,typeof this.client.defineCommand=="function"&&this.client.defineCommand("rlflxIncr",{numberOfKeys:1,lua:Ke})}_isRedisReady(){return this._rejectIfRedisNotReady?!(this.client.status&&this.client.status!=="ready"||typeof this.client.isReady=="function"&&!this.client.isReady()):!0}_getRateLimiterRes(e,t,r){let[s,n]=r;Array.isArray(s)&&([,s]=s,[,n]=n);let o=new cs;return o.consumedPoints=parseInt(s),o.isFirstInDuration=o.consumedPoints===t,o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.msBeforeNext=n,o}async _upsert(e,t,r,s=!1){if(!this._isRedisReady())throw new Error("Redis connection is not ready");let n=Math.floor(r/1e3),o=this.client.multi();return s?(n>0?!this.useRedisPackage&&!this.useRedis3AndLowerPackage?o.set(e,t,"EX",n):o.set(e,t,{EX:n}):o.set(e,t),!this.useRedisPackage&&!this.useRedis3AndLowerPackage?o.pttl(e).exec(!0):o.pTTL(e).exec(!0)):n>0?!this.useRedisPackage&&!this.useRedis3AndLowerPackage?this.client.rlflxIncr([e].concat([String(t),String(n)])):this.useRedis3AndLowerPackage?new Promise((a,c)=>{let h=function(u,l){return u?c(u):a(l)};typeof this.client.rlflxIncr=="function"?this.client.rlflxIncr(e,t,n,h):this.client.eval(Ke,1,e,t,n,h)}):this.client.eval(Ke,{keys:[e],arguments:[String(t),String(n)]}):!this.useRedisPackage&&!this.useRedis3AndLowerPackage?o.incrby(e,t).pttl(e).exec(!0):o.incrBy(e,t).pTTL(e).exec(!0)}async _get(e){if(!this._isRedisReady())throw new Error("Redis connection is not ready");return!this.useRedisPackage&&!this.useRedis3AndLowerPackage?this.client.multi().get(e).pttl(e).exec().then(t=>{let[[,r]]=t;return r===null?null:t}):this.client.multi().get(e).pTTL(e).exec(!0).then(t=>{let[r]=t;return r===null?null:t})}_delete(e){return this.client.del(e).then(t=>t>0)}};nr.exports=Ge});var ur=g((Go,cr)=>{var us=te(),ls=k();function ar(i){try{let e=i.client?i.client:i,{version:t}=e.topology.s.options.metadata.driver,r=t.split(".").map(s=>parseInt(s));return{major:r[0],feature:r[1],patch:r[2]}}catch{return{major:0,feature:0,patch:0}}}var je=class i extends us{constructor(e){super(e),this.dbName=e.dbName,this.tableName=e.tableName,this.indexKeyPrefix=e.indexKeyPrefix,e.mongo?this.client=e.mongo:this.client=e.storeClient,typeof this.client.then=="function"?this.client.then(t=>{this.client=t,this._initCollection(),this._driverVersion=ar(this.client)}):(this._initCollection(),this._driverVersion=ar(this.client))}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?i.getDbName():e}static getDbName(){return"node-rate-limiter-flexible"}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("mongo is not set");this._client=e}get indexKeyPrefix(){return this._indexKeyPrefix}set indexKeyPrefix(e){this._indexKeyPrefix=e||{}}_initCollection(){let t=(typeof this.client.db=="function"?this.client.db(this.dbName):this.client).collection(this.tableName);t.createIndex({expire:-1},{expireAfterSeconds:0}),t.createIndex(Object.assign({},this.indexKeyPrefix,{key:1}),{unique:!0}),this._collection=t}_getRateLimiterRes(e,t,r){let s=new ls,n;return typeof r.value>"u"?n=r:n=r.value,s.isFirstInDuration=n.points===t,s.consumedPoints=n.points,s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.msBeforeNext=n.expire!==null?Math.max(new Date(n.expire).getTime()-Date.now(),0):-1,s}_upsert(e,t,r,s=!1,n={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let o=n.attrs||{},a,c;s?(a={key:e},a=Object.assign(a,o),c={$set:{key:e,points:t,expire:r>0?new Date(Date.now()+r):null}},c.$set=Object.assign(c.$set,o)):(a={$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}],key:e},a=Object.assign(a,o),c={$setOnInsert:{key:e,expire:r>0?new Date(Date.now()+r):null},$inc:{points:t}},c.$setOnInsert=Object.assign(c.$setOnInsert,o));let h={upsert:!0};return this._driverVersion.major>=4||this._driverVersion.major===3&&this._driverVersion.feature>=7||this._driverVersion.feature>=6&&this._driverVersion.patch>=7?h.returnDocument="after":h.returnOriginal=!1,new Promise((u,l)=>{this._collection.findOneAndUpdate(a,c,h).then(d=>{u(d)}).catch(d=>{if(d&&d.code===11e3){let w=Object.assign({$or:[{expire:{$lte:new Date}},{expire:{$eq:null}}],key:e},o),m={$set:Object.assign({key:e,points:t,expire:r>0?new Date(Date.now()+r):null},o)};this._collection.findOneAndUpdate(w,m,h).then(p=>{u(p)}).catch(p=>{p&&p.code===11e3?this._upsert(e,t,r,s).then(f=>u(f)).catch(f=>l(f)):l(p)})}else l(d)})})}_get(e,t={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let r=t.attrs||{},s=Object.assign({key:e,$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}]},r);return this._collection.findOne(s)}_delete(e,t={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let r=t.attrs||{},s=Object.assign({key:e},r);return this._collection.deleteOne(s).then(n=>n.deletedCount>0)}};cr.exports=je});var hr=g((jo,lr)=>{var hs=te(),ds=k(),He=class extends hs{constructor(e,t=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.dbName=e.dbName,this.tableName=e.tableName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?(this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()):this._createDbAndTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()}).catch(r=>{if(typeof t=="function")t(r);else throw r})}clearExpired(e){return new Promise(t=>{this._getConnection().then(r=>{r.query("DELETE FROM ??.?? WHERE expire < ?",[this.dbName,this.tableName,e],()=>{this._releaseConnection(r),t()})}).catch(()=>{t()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return new Promise((e,t)=>{this.client.getConnection((r,s)=>{if(r)return t(r);e(s)})});case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return e.release();case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);default:return!0}}_createDbAndTable(){return new Promise((e,t)=>{this._getConnection().then(r=>{r.query(`CREATE DATABASE IF NOT EXISTS \`${this.dbName}\`;`,s=>{if(s)return this._releaseConnection(r),t(s);r.query(this._getCreateTableStmt(),n=>{if(n)return this._releaseConnection(r),t(n);this._releaseConnection(r),e()})})}).catch(r=>{t(r)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS \`${this.dbName}\`.\`${this.tableName}\` (\`key\` VARCHAR(255) CHARACTER SET utf8 NOT NULL,\`points\` INT(9) NOT NULL default 0,\`expire\` BIGINT UNSIGNED,PRIMARY KEY (\`key\`)) ENGINE = INNODB;`}get clientType(){return this._clientType}set clientType(e){if(typeof e>"u")if(this.client.constructor.name==="Connection")e="connection";else if(this.client.constructor.name==="Pool")e="pool";else if(this.client.constructor.name==="Sequelize")e="sequelize";else throw new Error("storeType is not defined");this._clientType=e.toLowerCase()}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?"rtlmtrflx":e}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get tableCreated(){return this._tableCreated}set tableCreated(e){this._tableCreated=typeof e>"u"?!1:!!e}get clearExpiredByTimeout(){return this._clearExpiredByTimeout}set clearExpiredByTimeout(e){this._clearExpiredByTimeout=typeof e>"u"?!0:!!e}_getRateLimiterRes(e,t,r){let s=new ds,[n]=r;return s.isFirstInDuration=t===n.points,s.consumedPoints=s.isFirstInDuration?t:n.points,s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.msBeforeNext=n.expire?Math.max(n.expire-Date.now(),0):-1,s}_upsertTransaction(e,t,r,s,n){return new Promise((o,a)=>{e.query("BEGIN",c=>{if(c)return e.rollback(),a(c);let h=Date.now(),u=s>0?h+s:null,l,d;n?(l=`INSERT INTO ??.?? VALUES (?, ?, ?)
|
2
|
+
"use strict";var Libp2PMplex=(()=>{var ri=Object.create;var ce=Object.defineProperty;var ii=Object.getOwnPropertyDescriptor;var si=Object.getOwnPropertyNames;var ni=Object.getPrototypeOf,oi=Object.prototype.hasOwnProperty;var b=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),I=(i,e)=>{for(var t in e)ce(i,t,{get:e[t],enumerable:!0})},gt=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of si(e))!oi.call(i,s)&&s!==t&&ce(i,s,{get:()=>e[s],enumerable:!(r=ii(e,s))||r.enumerable});return i};var ai=(i,e,t)=>(t=i!=null?ri(ni(i)):{},gt(e||!i||!i.__esModule?ce(t,"default",{value:i,enumerable:!0}):t,i)),ci=i=>gt(ce({},"__esModule",{value:!0}),i);var ee=b((Kn,Lt)=>{Lt.exports=class{constructor(e={}){this.points=e.points,this.duration=e.duration,this.blockDuration=e.blockDuration,this.execEvenly=e.execEvenly,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs,this.keyPrefix=e.keyPrefix}get points(){return this._points}set points(e){this._points=e>=0?e:4}get duration(){return this._duration}set duration(e){this._duration=typeof e>"u"?1:e}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(e){this._blockDuration=typeof e>"u"?0:e}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(e){this._execEvenly=typeof e>"u"?!1:!!e}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(e){this._execEvenlyMinDelayMs=typeof e>"u"?Math.ceil(this.msDuration/this.points):e}get keyPrefix(){return this._keyPrefix}set keyPrefix(e){if(typeof e>"u"&&(e="rlflx"),typeof e!="string")throw new Error("keyPrefix must be string");this._keyPrefix=e}_getKeySecDuration(e={}){return e&&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)}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}}});var Ct=b((jn,Nt)=>{Nt.exports=class{constructor(){this._keys={},this._addedKeysAmount=0}collectExpired(){let e=Date.now();Object.keys(this._keys).forEach(t=>{this._keys[t]<=e&&delete this._keys[t]}),this._addedKeysAmount=Object.keys(this._keys).length}add(e,t){this.addMs(e,t*1e3)}addMs(e,t){this._keys[e]=Date.now()+t,this._addedKeysAmount++,this._addedKeysAmount>999&&this.collectExpired()}msBeforeExpire(e){let t=this._keys[e];if(t&&t>=Date.now()){this.collectExpired();let r=Date.now();return t>=r?t-r:0}return 0}delete(e){e?delete this._keys[e]:Object.keys(this._keys).forEach(t=>{delete this._keys[t]})}}});var Pt=b((Hn,Mt)=>{var fi=Ct();Mt.exports=fi});var T=b((Qn,kt)=>{kt.exports=class{constructor(e,t,r,s){this.remainingPoints=typeof e>"u"?0:e,this.msBeforeNext=typeof t>"u"?0:t,this.consumedPoints=typeof r>"u"?0:r,this.isFirstInDuration=typeof s>"u"?!1:s}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(e){return this._msBeforeNext=e,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(e){return this._remainingPoints=e,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(e){return this._consumedPoints=e,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(e){this._isFirstInDuration=!!e}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}}});var K=b((Jn,Bt)=>{var Ae=ee(),mi=Pt(),Dt=T();Bt.exports=class extends Ae{constructor(e={}){super(e),this.inMemoryBlockOnConsumed=e.inMemoryBlockOnConsumed,this.inMemoryBlockDuration=e.inMemoryBlockDuration,this.insuranceLimiter=e.insuranceLimiter,this._inMemoryBlockedKeys=new mi}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("storeClient is not set");this._client=e}_afterConsume(e,t,r,s,n,o={}){let a=this._getRateLimiterRes(r,s,n);if(this.inMemoryBlockOnConsumed>0&&!(this.inMemoryBlockDuration>0)&&a.consumedPoints>=this.inMemoryBlockOnConsumed)return this._inMemoryBlockedKeys.addMs(r,a.msBeforeNext),a.consumedPoints>this.points?t(a):e(a);if(a.consumedPoints>this.points){let c=Promise.resolve();this.blockDuration>0&&a.consumedPoints<=this.points+s&&(a.msBeforeNext=this.msBlockDuration,c=this._block(r,a.consumedPoints,this.msBlockDuration,o)),this.inMemoryBlockOnConsumed>0&&a.consumedPoints>=this.inMemoryBlockOnConsumed&&(this._inMemoryBlockedKeys.add(r,this.inMemoryBlockDuration),a.msBeforeNext=this.msInMemoryBlockDuration),c.then(()=>{t(a)}).catch(h=>{t(h)})}else if(this.execEvenly&&a.msBeforeNext>0&&!a.isFirstInDuration){let c=Math.ceil(a.msBeforeNext/(a.remainingPoints+2));c<this.execEvenlyMinDelayMs&&(c=a.consumedPoints*this.execEvenlyMinDelayMs),setTimeout(e,c,a)}else e(a)}_handleError(e,t,r,s,n,o=!1,a={}){this.insuranceLimiter instanceof Ae?this.insuranceLimiter[t](n,o,a).then(c=>{r(c)}).catch(c=>{s(c)}):s(e)}getInMemoryBlockMsBeforeExpire(e){return this.inMemoryBlockOnConsumed>0?this._inMemoryBlockedKeys.msBeforeExpire(e):0}get inMemoryBlockOnConsumed(){return this._inMemoryBlockOnConsumed}set inMemoryBlockOnConsumed(e){if(this._inMemoryBlockOnConsumed=e?parseInt(e):0,this.inMemoryBlockOnConsumed>0&&this.points>this.inMemoryBlockOnConsumed)throw new Error('inMemoryBlockOnConsumed option must be greater or equal "points" option')}get inMemoryBlockDuration(){return this._inMemoryBlockDuration}set inMemoryBlockDuration(e){if(this._inMemoryBlockDuration=e?parseInt(e):0,this.inMemoryBlockDuration>0&&this.inMemoryBlockOnConsumed===0)throw new Error("inMemoryBlockOnConsumed option must be set up")}get msInMemoryBlockDuration(){return this._inMemoryBlockDuration*1e3}get insuranceLimiter(){return this._insuranceLimiter}set insuranceLimiter(e){if(typeof e<"u"&&!(e instanceof Ae))throw new Error("insuranceLimiter must be instance of RateLimiterAbstract");this._insuranceLimiter=e,this._insuranceLimiter&&(this._insuranceLimiter.blockDuration=this.blockDuration,this._insuranceLimiter.execEvenly=this.execEvenly)}block(e,t,r={}){let s=t*1e3;return this._block(this.getKey(e),this.points+1,s,r)}set(e,t,r,s={}){let n=(r>=0?r:this.duration)*1e3;return this._block(this.getKey(e),t,n,s)}consume(e,t=1,r={}){return new Promise((s,n)=>{let o=this.getKey(e),a=this.getInMemoryBlockMsBeforeExpire(o);if(a>0)return n(new Dt(0,a));this._upsert(o,t,this._getKeySecDuration(r)*1e3,!1,r).then(c=>{this._afterConsume(s,n,o,t,c)}).catch(c=>{this._handleError(c,"consume",s,n,e,t,r)})})}penalty(e,t=1,r={}){let s=this.getKey(e);return new Promise((n,o)=>{this._upsert(s,t,this._getKeySecDuration(r)*1e3,!1,r).then(a=>{n(this._getRateLimiterRes(s,t,a))}).catch(a=>{this._handleError(a,"penalty",n,o,e,t,r)})})}reward(e,t=1,r={}){let s=this.getKey(e);return new Promise((n,o)=>{this._upsert(s,-t,this._getKeySecDuration(r)*1e3,!1,r).then(a=>{n(this._getRateLimiterRes(s,-t,a))}).catch(a=>{this._handleError(a,"reward",n,o,e,t,r)})})}get(e,t={}){let r=this.getKey(e);return new Promise((s,n)=>{this._get(r,t).then(o=>{s(o===null||typeof o>"u"?null:this._getRateLimiterRes(r,0,o))}).catch(o=>{this._handleError(o,"get",s,n,e,t)})})}delete(e,t={}){let r=this.getKey(e);return new Promise((s,n)=>{this._delete(r,t).then(o=>{this._inMemoryBlockedKeys.delete(r),s(o)}).catch(o=>{this._handleError(o,"delete",s,n,e,t)})})}deleteInMemoryBlockedAll(){this._inMemoryBlockedKeys.delete()}_getRateLimiterRes(e,t,r){throw new Error("You have to implement the method '_getRateLimiterRes'!")}_block(e,t,r,s={}){return new Promise((n,o)=>{this._upsert(e,t,r,!0,s).then(()=>{n(new Dt(0,r>0?r:-1,t))}).catch(a=>{this._handleError(a,"block",n,o,this.parseKey(e),r/1e3,s)})})}_get(e,t={}){throw new Error("You have to implement the method '_get'!")}_delete(e,t={}){throw new Error("You have to implement the method '_delete'!")}_upsert(e,t,r,s=!1,n={}){throw new Error("You have to implement the method '_upsert'!")}}});var vt=b((Zn,Ot)=>{var pi=K(),yi=T(),Ie="redis.call('set', KEYS[1], 0, 'EX', ARGV[2], 'NX') local consumed = redis.call('incrby', KEYS[1], ARGV[1]) local ttl = redis.call('pttl', KEYS[1]) if ttl == -1 then redis.call('expire', KEYS[1], ARGV[2]) ttl = 1000 * ARGV[2] end return {consumed, ttl} ",Te=class extends pi{constructor(e){super(e),this.client=e.storeClient,this._rejectIfRedisNotReady=!!e.rejectIfRedisNotReady,this.useRedisPackage=e.useRedisPackage||this.client.constructor.name==="Commander"||!1,this.useRedis3AndLowerPackage=e.useRedis3AndLowerPackage,typeof this.client.defineCommand=="function"&&this.client.defineCommand("rlflxIncr",{numberOfKeys:1,lua:Ie})}_isRedisReady(){return this._rejectIfRedisNotReady?!(this.client.status&&this.client.status!=="ready"||typeof this.client.isReady=="function"&&!this.client.isReady()):!0}_getRateLimiterRes(e,t,r){let[s,n]=r;Array.isArray(s)&&([,s]=s,[,n]=n);let o=new yi;return o.consumedPoints=parseInt(s),o.isFirstInDuration=o.consumedPoints===t,o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.msBeforeNext=n,o}async _upsert(e,t,r,s=!1){if(!this._isRedisReady())throw new Error("Redis connection is not ready");let n=Math.floor(r/1e3),o=this.client.multi();return s?(n>0?!this.useRedisPackage&&!this.useRedis3AndLowerPackage?o.set(e,t,"EX",n):o.set(e,t,{EX:n}):o.set(e,t),!this.useRedisPackage&&!this.useRedis3AndLowerPackage?o.pttl(e).exec(!0):o.pTTL(e).exec(!0)):n>0?!this.useRedisPackage&&!this.useRedis3AndLowerPackage?this.client.rlflxIncr([e].concat([String(t),String(n)])):this.useRedis3AndLowerPackage?new Promise((a,c)=>{let h=function(l,d){return l?c(l):a(d)};typeof this.client.rlflxIncr=="function"?this.client.rlflxIncr(e,t,n,h):this.client.eval(Ie,1,e,t,n,h)}):this.client.eval(Ie,{keys:[e],arguments:[String(t),String(n)]}):!this.useRedisPackage&&!this.useRedis3AndLowerPackage?o.incrby(e,t).pttl(e).exec(!0):o.incrBy(e,t).pTTL(e).exec(!0)}async _get(e){if(!this._isRedisReady())throw new Error("Redis connection is not ready");return!this.useRedisPackage&&!this.useRedis3AndLowerPackage?this.client.multi().get(e).pttl(e).exec().then(t=>{let[[,r]]=t;return r===null?null:t}):this.client.multi().get(e).pTTL(e).exec(!0).then(t=>{let[r]=t;return r===null?null:t})}_delete(e){return this.client.del(e).then(t=>t>0)}};Ot.exports=Te});var qt=b((eo,Ft)=>{var bi=K(),wi=T();function Ut(i){try{let e=i.client?i.client:i,{version:t}=e.topology.s.options.metadata.driver,r=t.split(".").map(s=>parseInt(s));return{major:r[0],feature:r[1],patch:r[2]}}catch{return{major:0,feature:0,patch:0}}}var Le=class i extends bi{constructor(e){super(e),this.dbName=e.dbName,this.tableName=e.tableName,this.indexKeyPrefix=e.indexKeyPrefix,e.mongo?this.client=e.mongo:this.client=e.storeClient,typeof this.client.then=="function"?this.client.then(t=>{this.client=t,this._initCollection(),this._driverVersion=Ut(this.client)}):(this._initCollection(),this._driverVersion=Ut(this.client))}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?i.getDbName():e}static getDbName(){return"node-rate-limiter-flexible"}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("mongo is not set");this._client=e}get indexKeyPrefix(){return this._indexKeyPrefix}set indexKeyPrefix(e){this._indexKeyPrefix=e||{}}_initCollection(){let t=(typeof this.client.db=="function"?this.client.db(this.dbName):this.client).collection(this.tableName);t.createIndex({expire:-1},{expireAfterSeconds:0}),t.createIndex(Object.assign({},this.indexKeyPrefix,{key:1}),{unique:!0}),this._collection=t}_getRateLimiterRes(e,t,r){let s=new wi,n;return typeof r.value>"u"?n=r:n=r.value,s.isFirstInDuration=n.points===t,s.consumedPoints=n.points,s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.msBeforeNext=n.expire!==null?Math.max(new Date(n.expire).getTime()-Date.now(),0):-1,s}_upsert(e,t,r,s=!1,n={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let o=n.attrs||{},a,c;s?(a={key:e},a=Object.assign(a,o),c={$set:{key:e,points:t,expire:r>0?new Date(Date.now()+r):null}},c.$set=Object.assign(c.$set,o)):(a={$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}],key:e},a=Object.assign(a,o),c={$setOnInsert:{key:e,expire:r>0?new Date(Date.now()+r):null},$inc:{points:t}},c.$setOnInsert=Object.assign(c.$setOnInsert,o));let h={upsert:!0};return this._driverVersion.major>=4||this._driverVersion.major===3&&this._driverVersion.feature>=7||this._driverVersion.feature>=6&&this._driverVersion.patch>=7?h.returnDocument="after":h.returnOriginal=!1,new Promise((l,d)=>{this._collection.findOneAndUpdate(a,c,h).then(y=>{l(y)}).catch(y=>{if(y&&y.code===11e3){let E=Object.assign({$or:[{expire:{$lte:new Date}},{expire:{$eq:null}}],key:e},o),u={$set:Object.assign({key:e,points:t,expire:r>0?new Date(Date.now()+r):null},o)};this._collection.findOneAndUpdate(E,u,h).then(m=>{l(m)}).catch(m=>{m&&m.code===11e3?this._upsert(e,t,r,s).then(f=>l(f)).catch(f=>d(f)):d(m)})}else d(y)})})}_get(e,t={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let r=t.attrs||{},s=Object.assign({key:e,$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}]},r);return this._collection.findOne(s)}_delete(e,t={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let r=t.attrs||{},s=Object.assign({key:e},r);return this._collection.deleteOne(s).then(n=>n.deletedCount>0)}};Ft.exports=Le});var Vt=b((to,zt)=>{var gi=K(),_i=T(),Ne=class extends gi{constructor(e,t=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.dbName=e.dbName,this.tableName=e.tableName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?(this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()):this._createDbAndTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()}).catch(r=>{if(typeof t=="function")t(r);else throw r})}clearExpired(e){return new Promise(t=>{this._getConnection().then(r=>{r.query("DELETE FROM ??.?? WHERE expire < ?",[this.dbName,this.tableName,e],()=>{this._releaseConnection(r),t()})}).catch(()=>{t()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return new Promise((e,t)=>{this.client.getConnection((r,s)=>{if(r)return t(r);e(s)})});case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return e.release();case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);default:return!0}}_createDbAndTable(){return new Promise((e,t)=>{this._getConnection().then(r=>{r.query(`CREATE DATABASE IF NOT EXISTS \`${this.dbName}\`;`,s=>{if(s)return this._releaseConnection(r),t(s);r.query(this._getCreateTableStmt(),n=>{if(n)return this._releaseConnection(r),t(n);this._releaseConnection(r),e()})})}).catch(r=>{t(r)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS \`${this.dbName}\`.\`${this.tableName}\` (\`key\` VARCHAR(255) CHARACTER SET utf8 NOT NULL,\`points\` INT(9) NOT NULL default 0,\`expire\` BIGINT UNSIGNED,PRIMARY KEY (\`key\`)) ENGINE = INNODB;`}get clientType(){return this._clientType}set clientType(e){if(typeof e>"u")if(this.client.constructor.name==="Connection")e="connection";else if(this.client.constructor.name==="Pool")e="pool";else if(this.client.constructor.name==="Sequelize")e="sequelize";else throw new Error("storeType is not defined");this._clientType=e.toLowerCase()}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?"rtlmtrflx":e}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get tableCreated(){return this._tableCreated}set tableCreated(e){this._tableCreated=typeof e>"u"?!1:!!e}get clearExpiredByTimeout(){return this._clearExpiredByTimeout}set clearExpiredByTimeout(e){this._clearExpiredByTimeout=typeof e>"u"?!0:!!e}_getRateLimiterRes(e,t,r){let s=new _i,[n]=r;return s.isFirstInDuration=t===n.points,s.consumedPoints=s.isFirstInDuration?t:n.points,s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.msBeforeNext=n.expire?Math.max(n.expire-Date.now(),0):-1,s}_upsertTransaction(e,t,r,s,n){return new Promise((o,a)=>{e.query("BEGIN",c=>{if(c)return e.rollback(),a(c);let h=Date.now(),l=s>0?h+s:null,d,y;n?(d=`INSERT INTO ??.?? VALUES (?, ?, ?)
|
3
3
|
ON DUPLICATE KEY UPDATE
|
4
4
|
points = ?,
|
5
|
-
expire = ?;`,
|
5
|
+
expire = ?;`,y=[this.dbName,this.tableName,t,r,l,r,l]):(d=`INSERT INTO ??.?? VALUES (?, ?, ?)
|
6
6
|
ON DUPLICATE KEY UPDATE
|
7
7
|
points = IF(expire <= ?, ?, points + (?)),
|
8
|
-
expire = IF(expire <= ?, ?, expire);`,
|
8
|
+
expire = IF(expire <= ?, ?, expire);`,y=[this.dbName,this.tableName,t,r,l,h,r,r,h,l]),e.query(d,y,E=>{if(E)return e.rollback(),a(E);e.query("SELECT points, expire FROM ??.?? WHERE `key` = ?;",[this.dbName,this.tableName,t],(u,m)=>{if(u)return e.rollback(),a(u);e.query("COMMIT",f=>{if(f)return e.rollback(),a(f);o(m)})})})})})}_upsert(e,t,r,s=!1){return this.tableCreated?new Promise((n,o)=>{this._getConnection().then(a=>{this._upsertTransaction(a,e,t,r,s).then(c=>{n(c),this._releaseConnection(a)}).catch(c=>{o(c),this._releaseConnection(a)})}).catch(a=>{o(a)})}):Promise.reject(Error("Table is not created yet"))}_get(e){return this.tableCreated?new Promise((t,r)=>{this._getConnection().then(s=>{s.query("SELECT points, expire FROM ??.?? WHERE `key` = ? AND (`expire` > ? OR `expire` IS NULL)",[this.dbName,this.tableName,e,Date.now()],(n,o)=>{n?r(n):o.length===0?t(null):t(o),this._releaseConnection(s)})}).catch(s=>{r(s)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?new Promise((t,r)=>{this._getConnection().then(s=>{s.query("DELETE FROM ??.?? WHERE `key` = ?",[this.dbName,this.tableName,e],(n,o)=>{n?r(n):t(o.affectedRows>0),this._releaseConnection(s)})}).catch(s=>{r(s)})}):Promise.reject(Error("Table is not created yet"))}};zt.exports=Ne});var Wt=b((ro,$t)=>{var Ei=K(),xi=T(),Ce=class extends Ei{constructor(e,t=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.tableName=e.tableName,this.schemaName=e.schemaName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?(this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()):this._createTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()}).catch(r=>{if(typeof t=="function")t(r);else throw r})}_getTableIdentifier(){return this.schemaName?`"${this.schemaName}"."${this.tableName}"`:`"${this.tableName}"`}clearExpired(e){return new Promise(t=>{let r={name:"rlflx-clear-expired",text:`DELETE FROM ${this._getTableIdentifier()} WHERE expire < $1`,values:[e]};this._query(r).then(()=>{t()}).catch(()=>{t()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return Promise.resolve(this.client);case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();case"typeorm":return Promise.resolve(this.client.driver.master);default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return!0;case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);case"typeorm":return!0;default:return!0}}_createTable(){return new Promise((e,t)=>{this._query({text:this._getCreateTableStmt()}).then(()=>{e()}).catch(r=>{r.code==="23505"?e():t(r)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS ${this._getTableIdentifier()} (
|
9
9
|
key varchar(255) PRIMARY KEY,
|
10
10
|
points integer NOT NULL DEFAULT 0,
|
11
11
|
expire bigint
|
12
|
-
);`}get clientType(){return this._clientType}set clientType(e){let t=this.client.constructor.name;if(typeof e>"u")if(t==="Client")e="client";else if(t==="Pool"||t==="BoundPool")e="pool";else if(t==="Sequelize")e="sequelize";else throw new Error("storeType is not defined");this._clientType=e.toLowerCase()}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get schemaName(){return this._schemaName}set schemaName(e){this._schemaName=e}get tableCreated(){return this._tableCreated}set tableCreated(e){this._tableCreated=typeof e>"u"?!1:!!e}get clearExpiredByTimeout(){return this._clearExpiredByTimeout}set clearExpiredByTimeout(e){this._clearExpiredByTimeout=typeof e>"u"?!0:!!e}_getRateLimiterRes(e,t,r){let s=new
|
12
|
+
);`}get clientType(){return this._clientType}set clientType(e){let t=this.client.constructor.name;if(typeof e>"u")if(t==="Client")e="client";else if(t==="Pool"||t==="BoundPool")e="pool";else if(t==="Sequelize")e="sequelize";else throw new Error("storeType is not defined");this._clientType=e.toLowerCase()}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get schemaName(){return this._schemaName}set schemaName(e){this._schemaName=e}get tableCreated(){return this._tableCreated}set tableCreated(e){this._tableCreated=typeof e>"u"?!1:!!e}get clearExpiredByTimeout(){return this._clearExpiredByTimeout}set clearExpiredByTimeout(e){this._clearExpiredByTimeout=typeof e>"u"?!0:!!e}_getRateLimiterRes(e,t,r){let s=new xi,n=r.rows[0];return s.isFirstInDuration=t===n.points,s.consumedPoints=s.isFirstInDuration?t:n.points,s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.msBeforeNext=n.expire?Math.max(n.expire-Date.now(),0):-1,s}_query(e){let r={name:`${this.tableName.toLowerCase()}:${e.name}`,text:e.text,values:e.values};return new Promise((s,n)=>{this._getConnection().then(o=>{o.query(r).then(a=>{s(a),this._releaseConnection(o)}).catch(a=>{n(a),this._releaseConnection(o)})}).catch(o=>{n(o)})})}_upsert(e,t,r,s=!1){if(!this.tableCreated)return Promise.reject(Error("Table is not created yet"));let n=r>0?Date.now()+r:null,o=s?" $3 ":` CASE
|
13
13
|
WHEN ${this._getTableIdentifier()}.expire <= $4 THEN $3
|
14
14
|
ELSE ${this._getTableIdentifier()}.expire
|
15
15
|
END `;return this._query({name:s?"rlflx-upsert-force":"rlflx-upsert",text:`
|
@@ -21,5 +21,5 @@
|
|
21
21
|
END,
|
22
22
|
expire = ${o}
|
23
23
|
RETURNING points, expire;`,values:[e,t,n,Date.now()]})}_get(e){return this.tableCreated?new Promise((t,r)=>{this._query({name:"rlflx-get",text:`
|
24
|
-
SELECT points, expire FROM ${this._getTableIdentifier()} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`,values:[e,Date.now()]}).then(s=>{s.rowCount===0&&(s=null),t(s)}).catch(s=>{r(s)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?this._query({name:"rlflx-delete",text:`DELETE FROM ${this._getTableIdentifier()} WHERE key = $1`,values:[e]}).then(t=>t.rowCount>0):Promise.reject(Error("Table is not created yet"))}};dr.exports=Ye});var mr=g(()=>{});var pr=g(()=>{});var yr=g((ea,br)=>{br.exports=class{constructor(e,t,r=null){this.value=e,this.expiresAt=t,this.timeoutId=r}get value(){return this._value}set value(e){this._value=parseInt(e)}get expiresAt(){return this._expiresAt}set expiresAt(e){!(e instanceof Date)&&Number.isInteger(e)&&(e=new Date(e)),this._expiresAt=e}get timeoutId(){return this._timeoutId}set timeoutId(e){this._timeoutId=e}}});var wr=g((ra,gr)=>{var ps=yr(),Qe=k();gr.exports=class{constructor(){this._storage={}}incrby(e,t,r){if(this._storage[e]){let s=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return s!==0?(this._storage[e].value=this._storage[e].value+t,new Qe(0,s,this._storage[e].value,!1)):this.set(e,t,r)}return this.set(e,t,r)}set(e,t,r){let s=r*1e3;return this._storage[e]&&this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),this._storage[e]=new ps(t,s>0?new Date(Date.now()+s):null),s>0&&(this._storage[e].timeoutId=setTimeout(()=>{delete this._storage[e]},s),this._storage[e].timeoutId.unref&&this._storage[e].timeoutId.unref()),new Qe(0,s===0?-1:s,this._storage[e].value,!0)}get(e){if(this._storage[e]){let t=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return new Qe(0,t,this._storage[e].value,!1)}return null}delete(e){return this._storage[e]?(this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),delete this._storage[e],!0):!1}}});var Je=g((ia,Er)=>{var bs=ue(),ys=wr(),xr=k(),Xe=class extends bs{constructor(e={}){super(e),this._memoryStorage=new ys}consume(e,t=1,r={}){return new Promise((s,n)=>{let o=this.getKey(e),a=this._getKeySecDuration(r),c=this._memoryStorage.incrby(o,t,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+t&&(c=this._memoryStorage.set(o,c.consumedPoints,this.blockDuration)),n(c);else if(this.execEvenly&&c.msBeforeNext>0&&!c.isFirstInDuration){let h=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));h<this.execEvenlyMinDelayMs&&(h=c.consumedPoints*this.execEvenlyMinDelayMs),setTimeout(s,h,c)}else s(c)})}penalty(e,t=1,r={}){let s=this.getKey(e);return new Promise(n=>{let o=this._getKeySecDuration(r),a=this._memoryStorage.incrby(s,t,o);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),n(a)})}reward(e,t=1,r={}){let s=this.getKey(e);return new Promise(n=>{let o=this._getKeySecDuration(r),a=this._memoryStorage.incrby(s,-t,o);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),n(a)})}block(e,t){let r=t*1e3,s=this.points+1;return this._memoryStorage.set(this.getKey(e),s,t),Promise.resolve(new xr(0,r===0?-1:r,s))}set(e,t,r){let s=(r>=0?r:this.duration)*1e3;return this._memoryStorage.set(this.getKey(e),t,r),Promise.resolve(new xr(0,s===0?-1:s,t))}get(e){let t=this._memoryStorage.get(this.getKey(e));return t!==null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),Promise.resolve(t)}delete(e){return Promise.resolve(this._memoryStorage.delete(this.getKey(e)))}};Er.exports=Xe});var Lr=g((sa,Ir)=>{var _r=mr(),gs=pr(),ws=ue(),Cr=Je(),xs=k(),v="rate_limiter_flexible",se=null,Sr=function(i,e,t,r){let s;r===null||r===!0||r===!1?s=r:s={remainingPoints:r.remainingPoints,msBeforeNext:r.msBeforeNext,consumedPoints:r.consumedPoints,isFirstInDuration:r.isFirstInDuration},i.send({channel:v,keyPrefix:e.keyPrefix,promiseId:e.promiseId,type:t,data:s})},Rr=function(i){setTimeout(()=>{this._initiated?process.send(i):typeof this._promises[i.promiseId]<"u"&&Rr.call(this,i)},30)},re=function(i,e,t,r,s){let n={channel:v,keyPrefix:this.keyPrefix,func:i,promiseId:e,data:{key:t,arg:r,opts:s}};this._initiated?process.send(n):Rr.call(this,n)},Ar=function(i,e){if(!e||e.channel!==v||typeof this._rateLimiters[e.keyPrefix]>"u")return!1;let t;switch(e.func){case"consume":t=this._rateLimiters[e.keyPrefix].consume(e.data.key,e.data.arg,e.data.opts);break;case"penalty":t=this._rateLimiters[e.keyPrefix].penalty(e.data.key,e.data.arg,e.data.opts);break;case"reward":t=this._rateLimiters[e.keyPrefix].reward(e.data.key,e.data.arg,e.data.opts);break;case"block":t=this._rateLimiters[e.keyPrefix].block(e.data.key,e.data.arg,e.data.opts);break;case"get":t=this._rateLimiters[e.keyPrefix].get(e.data.key,e.data.opts);break;case"delete":t=this._rateLimiters[e.keyPrefix].delete(e.data.key,e.data.opts);break;default:return!1}t&&t.then(r=>{Sr(i,e,"resolve",r)}).catch(r=>{Sr(i,e,"reject",r)})},Es=function(i){if(!i||i.channel!==v||i.keyPrefix!==this.keyPrefix)return!1;if(this._promises[i.promiseId]){clearTimeout(this._promises[i.promiseId].timeoutId);let e;switch(i.data===null||i.data===!0||i.data===!1?e=i.data:e=new xs(i.data.remainingPoints,i.data.msBeforeNext,i.data.consumedPoints,i.data.isFirstInDuration),i.type){case"resolve":this._promises[i.promiseId].resolve(e);break;case"reject":this._promises[i.promiseId].reject(e);break;default:throw new Error(`RateLimiterCluster: no such message type '${i.type}'`)}delete this._promises[i.promiseId]}},_s=function(){return{points:this.points,duration:this.duration,blockDuration:this.blockDuration,execEvenly:this.execEvenly,execEvenlyMinDelayMs:this.execEvenlyMinDelayMs,keyPrefix:this.keyPrefix}},ie=function(i,e){let t=process.hrtime(),r=t[0].toString()+t[1].toString();return typeof this._promises[r]<"u"&&(r+=gs.randomBytes(12).toString("base64")),this._promises[r]={resolve:i,reject:e,timeoutId:setTimeout(()=>{delete this._promises[r],e(new Error("RateLimiterCluster timeout: no answer from master in time"))},this.timeoutMs)},r},Ze=class{constructor(){if(se)return se;this._rateLimiters={},_r.setMaxListeners(0),_r.on("message",(e,t)=>{t&&t.channel===v&&t.type==="init"?(typeof this._rateLimiters[t.opts.keyPrefix]>"u"&&(this._rateLimiters[t.opts.keyPrefix]=new Cr(t.opts)),e.send({channel:v,type:"init",keyPrefix:t.opts.keyPrefix})):Ar.call(this,e,t)}),se=this}},et=class{constructor(e){if(se)return se;this._rateLimiters={},e.launchBus((t,r)=>{r.on("process:msg",s=>{let n=s.raw;if(n&&n.channel===v&&n.type==="init")typeof this._rateLimiters[n.opts.keyPrefix]>"u"&&(this._rateLimiters[n.opts.keyPrefix]=new Cr(n.opts)),e.sendDataToProcessId(s.process.pm_id,{data:{},topic:v,channel:v,type:"init",keyPrefix:n.opts.keyPrefix},(o,a)=>{o&&console.log(o,a)});else{let o={send:a=>{let c=a;c.topic=v,typeof c.data>"u"&&(c.data={}),e.sendDataToProcessId(s.process.pm_id,c,(h,u)=>{h&&console.log(h,u)})}};Ar.call(this,o,n)}})}),se=this}},tt=class extends ws{get timeoutMs(){return this._timeoutMs}set timeoutMs(e){this._timeoutMs=typeof e>"u"?5e3:Math.abs(parseInt(e))}constructor(e={}){super(e),process.setMaxListeners(0),this.timeoutMs=e.timeoutMs,this._initiated=!1,process.on("message",t=>{t&&t.channel===v&&t.type==="init"&&t.keyPrefix===this.keyPrefix?this._initiated=!0:Es.call(this,t)}),process.send({channel:v,type:"init",opts:_s.call(this)}),this._promises={}}consume(e,t=1,r={}){return new Promise((s,n)=>{let o=ie.call(this,s,n);re.call(this,"consume",o,e,t,r)})}penalty(e,t=1,r={}){return new Promise((s,n)=>{let o=ie.call(this,s,n);re.call(this,"penalty",o,e,t,r)})}reward(e,t=1,r={}){return new Promise((s,n)=>{let o=ie.call(this,s,n);re.call(this,"reward",o,e,t,r)})}block(e,t,r={}){return new Promise((s,n)=>{let o=ie.call(this,s,n);re.call(this,"block",o,e,t,r)})}get(e,t={}){return new Promise((r,s)=>{let n=ie.call(this,r,s);re.call(this,"get",n,e,t)})}delete(e,t={}){return new Promise((r,s)=>{let n=ie.call(this,r,s);re.call(this,"delete",n,e,t)})}};Ir.exports={RateLimiterClusterMaster:Ze,RateLimiterClusterMasterPM2:et,RateLimiterCluster:tt}});var Nr=g((na,Tr)=>{var Ss=te(),Cs=k(),rt=class extends Ss{constructor(e){super(e),this.client=e.storeClient}_getRateLimiterRes(e,t,r){let s=new Cs;return s.consumedPoints=parseInt(r.consumedPoints),s.isFirstInDuration=r.consumedPoints===t,s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.msBeforeNext=r.msBeforeNext,s}_upsert(e,t,r,s=!1,n={}){return new Promise((o,a)=>{let c=Date.now(),h=Math.floor(r/1e3);s?this.client.set(e,t,h,u=>{u?a(u):this.client.set(`${e}_expire`,h>0?c+h*1e3:-1,h,()=>{let l={consumedPoints:t,msBeforeNext:h>0?h*1e3:-1};o(l)})}):this.client.incr(e,t,(u,l)=>{u||l===!1?this.client.add(e,t,h,(d,w)=>{if(d||!w)if(typeof n.attemptNumber>"u"||n.attemptNumber<3){let m=Object.assign({},n);m.attemptNumber=m.attemptNumber?m.attemptNumber+1:1,this._upsert(e,t,r,s,m).then(p=>o(p)).catch(p=>a(p))}else a(new Error("Can not add key"));else this.client.add(`${e}_expire`,h>0?c+h*1e3:-1,h,()=>{let m={consumedPoints:t,msBeforeNext:h>0?h*1e3:-1};o(m)})}):this.client.get(`${e}_expire`,(d,w)=>{if(d)a(d);else{let m=w===!1?0:w,p={consumedPoints:l,msBeforeNext:m>=0?Math.max(m-c,0):-1};o(p)}})})})}_get(e){return new Promise((t,r)=>{let s=Date.now();this.client.get(e,(n,o)=>{o?this.client.get(`${e}_expire`,(a,c)=>{if(a)r(a);else{let h=c===!1?0:c,u={consumedPoints:o,msBeforeNext:h>=0?Math.max(h-s,0):-1};t(u)}}):t(null)})})}_delete(e){return new Promise((t,r)=>{this.client.del(e,(s,n)=>{s?r(s):n===!1?t(n):this.client.del(`${e}_expire`,o=>{o?r(o):t(n)})})})}};Tr.exports=rt});var Pr=g((aa,Mr)=>{var kr=k();Mr.exports=class{constructor(e={}){this.limiter=e.limiter,this.blackList=e.blackList,this.whiteList=e.whiteList,this.isBlackListed=e.isBlackListed,this.isWhiteListed=e.isWhiteListed,this.runActionAnyway=e.runActionAnyway}get limiter(){return this._limiter}set limiter(e){if(typeof e>"u")throw new Error("limiter is not set");this._limiter=e}get runActionAnyway(){return this._runActionAnyway}set runActionAnyway(e){this._runActionAnyway=typeof e>"u"?!1:e}get blackList(){return this._blackList}set blackList(e){this._blackList=Array.isArray(e)?e:[]}get isBlackListed(){return this._isBlackListed}set isBlackListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isBlackListed must be function");this._isBlackListed=e}get whiteList(){return this._whiteList}set whiteList(e){this._whiteList=Array.isArray(e)?e:[]}get isWhiteListed(){return this._isWhiteListed}set isWhiteListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isWhiteListed must be function");this._isWhiteListed=e}isBlackListedSomewhere(e){return this.blackList.indexOf(e)>=0||this.isBlackListed(e)}isWhiteListedSomewhere(e){return this.whiteList.indexOf(e)>=0||this.isWhiteListed(e)}getBlackRes(){return new kr(0,Number.MAX_SAFE_INTEGER,0,!1)}getWhiteRes(){return new kr(Number.MAX_SAFE_INTEGER,0,0,!1)}rejectBlack(){return Promise.reject(this.getBlackRes())}resolveBlack(){return Promise.resolve(this.getBlackRes())}resolveWhite(){return Promise.resolve(this.getWhiteRes())}consume(e,t=1){let r;return this.isWhiteListedSomewhere(e)?r=this.resolveWhite():this.isBlackListedSomewhere(e)&&(r=this.rejectBlack()),typeof r>"u"?this.limiter.consume(e,t):(this.runActionAnyway&&this.limiter.consume(e,t).catch(()=>{}),r)}block(e,t){let r;return this.isWhiteListedSomewhere(e)?r=this.resolveWhite():this.isBlackListedSomewhere(e)&&(r=this.resolveBlack()),typeof r>"u"?this.limiter.block(e,t):(this.runActionAnyway&&this.limiter.block(e,t).catch(()=>{}),r)}penalty(e,t){let r;return this.isWhiteListedSomewhere(e)?r=this.resolveWhite():this.isBlackListedSomewhere(e)&&(r=this.resolveBlack()),typeof r>"u"?this.limiter.penalty(e,t):(this.runActionAnyway&&this.limiter.penalty(e,t).catch(()=>{}),r)}reward(e,t){let r;return this.isWhiteListedSomewhere(e)?r=this.resolveWhite():this.isBlackListedSomewhere(e)&&(r=this.resolveBlack()),typeof r>"u"?this.limiter.reward(e,t):(this.runActionAnyway&&this.limiter.reward(e,t).catch(()=>{}),r)}get(e){let t;return this.isWhiteListedSomewhere(e)?t=this.resolveWhite():this.isBlackListedSomewhere(e)&&(t=this.resolveBlack()),typeof t>"u"||this.runActionAnyway?this.limiter.get(e):t}delete(e){return this.limiter.delete(e)}}});var Or=g((ua,Dr)=>{var Rs=ue();Dr.exports=class{constructor(...e){if(e.length<1)throw new Error("RateLimiterUnion: at least one limiter have to be passed");e.forEach(t=>{if(!(t instanceof Rs))throw new Error("RateLimiterUnion: all limiters have to be instance of RateLimiterAbstract")}),this._limiters=e}consume(e,t=1){return new Promise((r,s)=>{let n=[];this._limiters.forEach(o=>{n.push(o.consume(e,t).catch(a=>({rejected:!0,rej:a})))}),Promise.all(n).then(o=>{let a={},c=!1;o.forEach(h=>{h.rejected===!0&&(c=!0)});for(let h=0;h<o.length;h++)c&&o[h].rejected===!0?a[this._limiters[h].keyPrefix]=o[h].rej:c||(a[this._limiters[h].keyPrefix]=o[h]);c?s(a):r(a)})})}}});var Br=g((ha,vr)=>{vr.exports=class extends Error{constructor(e,t){super(),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="CustomError",this.message=e,t&&(this.extra=t)}}});var $r=g((fa,qr)=>{var Fr=Br(),Ur=4294967295,it="limiter";qr.exports=class{constructor(e,t={maxQueueSize:Ur}){this._queueLimiters={KEY_DEFAULT:new _e(e,t)},this._limiterFlexible=e,this._maxQueueSize=t.maxQueueSize}getTokensRemaining(e=it){return this._queueLimiters[e]?this._queueLimiters[e].getTokensRemaining():Promise.resolve(this._limiterFlexible.points)}removeTokens(e,t=it){return this._queueLimiters[t]||(this._queueLimiters[t]=new _e(this._limiterFlexible,{key:t,maxQueueSize:this._maxQueueSize})),this._queueLimiters[t].removeTokens(e)}};var _e=class{constructor(e,t={maxQueueSize:Ur,key:it}){this._key=t.key,this._waitTimeout=null,this._queue=[],this._limiterFlexible=e,this._maxQueueSize=t.maxQueueSize}getTokensRemaining(){return this._limiterFlexible.get(this._key).then(e=>e!==null?e.remainingPoints:this._limiterFlexible.points)}removeTokens(e){let t=this;return new Promise((r,s)=>{if(e>t._limiterFlexible.points){s(new Fr(`Requested tokens ${e} exceeds maximum ${t._limiterFlexible.points} tokens per interval`));return}t._queue.length>0?t._queueRequest.call(t,r,s,e):t._limiterFlexible.consume(t._key,e).then(n=>{r(n.remainingPoints)}).catch(n=>{n instanceof Error?s(n):(t._queueRequest.call(t,r,s,e),t._waitTimeout===null&&(t._waitTimeout=setTimeout(t._processFIFO.bind(t),n.msBeforeNext)))})})}_queueRequest(e,t,r){let s=this;s._queue.length<s._maxQueueSize?s._queue.push({resolve:e,reject:t,tokens:r}):t(new Fr(`Number of requests reached it's maximum ${s._maxQueueSize}`))}_processFIFO(){let e=this;if(e._waitTimeout!==null&&(clearTimeout(e._waitTimeout),e._waitTimeout=null),e._queue.length===0)return;let t=e._queue.shift();e._limiterFlexible.consume(e._key,t.tokens).then(r=>{t.resolve(r.remainingPoints),e._processFIFO.call(e)}).catch(r=>{r instanceof Error?(t.reject(r),e._processFIFO.call(e)):(e._queue.unshift(t),e._waitTimeout===null&&(e._waitTimeout=setTimeout(e._processFIFO.bind(e),r.msBeforeNext)))})}}});var Vr=g((pa,zr)=>{var st=k();zr.exports=class{constructor(e,t){this._rateLimiter=e,this._burstLimiter=t}_combineRes(e,t){return e?new st(e.remainingPoints,Math.min(e.msBeforeNext,t?t.msBeforeNext:0),e.consumedPoints,e.isFirstInDuration):null}consume(e,t=1,r={}){return this._rateLimiter.consume(e,t,r).catch(s=>s instanceof st?this._burstLimiter.consume(e,t,r).then(n=>Promise.resolve(this._combineRes(s,n))).catch(n=>n instanceof st?Promise.reject(this._combineRes(s,n)):Promise.reject(n)):Promise.reject(s))}get(e){return Promise.all([this._rateLimiter.get(e),this._burstLimiter.get(e)]).then(([t,r])=>this._combineRes(t,r))}get points(){return this._rateLimiter.points}}});var Kr=g((ba,Wr)=>{var As=or(),Is=ur(),Ls=hr(),Ts=fr(),{RateLimiterClusterMaster:Ns,RateLimiterClusterMasterPM2:ks,RateLimiterCluster:Ms}=Lr(),Ps=Je(),Ds=Nr(),Os=Pr(),vs=Or(),Bs=$r(),Fs=Vr(),Us=k();Wr.exports={RateLimiterRedis:As,RateLimiterMongo:Is,RateLimiterMySQL:Ls,RateLimiterPostgres:Ts,RateLimiterMemory:Ps,RateLimiterMemcache:Ds,RateLimiterClusterMaster:Ns,RateLimiterClusterMasterPM2:ks,RateLimiterCluster:Ms,RLWrapperBlackAndWhite:Os,RateLimiterUnion:vs,RateLimiterQueue:Bs,BurstyRateLimiter:Fs,RateLimiterRes:Us}});var eo={};L(eo,{mplex:()=>Zn});var $=class extends Error{code;props;constructor(e,t,r){super(e),this.code=t,this.name=r?.name??"CodeError",this.props=r??{}}};var N=Mt(Bt(),1);var Fe={};L(Fe,{base32:()=>V,base32hex:()=>Ki,base32hexpad:()=>ji,base32hexpadupper:()=>Hi,base32hexupper:()=>Gi,base32pad:()=>Vi,base32padupper:()=>Wi,base32upper:()=>zi,base32z:()=>Yi});function Bi(i,e){if(i.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var s=0;s<i.length;s++){var n=i.charAt(s),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=s}var a=i.length,c=i.charAt(0),h=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function l(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var p=0,f=0,y=0,E=m.length;y!==E&&m[y]===0;)y++,p++;for(var _=(E-y)*u+1>>>0,S=new Uint8Array(_);y!==E;){for(var A=m[y],P=0,I=_-1;(A!==0||P<f)&&I!==-1;I--,P++)A+=256*S[I]>>>0,S[I]=A%a>>>0,A=A/a>>>0;if(A!==0)throw new Error("Non-zero carry");f=P,y++}for(var D=_-f;D!==_&&S[D]===0;)D++;for(var H=c.repeat(p);D<_;++D)H+=i.charAt(S[D]);return H}function d(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var p=0;if(m[p]!==" "){for(var f=0,y=0;m[p]===c;)f++,p++;for(var E=(m.length-p)*h+1>>>0,_=new Uint8Array(E);m[p];){var S=t[m.charCodeAt(p)];if(S===255)return;for(var A=0,P=E-1;(S!==0||A<y)&&P!==-1;P--,A++)S+=a*_[P]>>>0,_[P]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");y=A,p++}if(m[p]!==" "){for(var I=E-y;I!==E&&_[I]===0;)I++;for(var D=new Uint8Array(f+(E-I)),H=f;I!==E;)D[H++]=_[I++];return D}}}function w(m){var p=d(m);if(p)return p;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:d,decode:w}}var Fi=Bi,Ui=Fi,Ft=Ui;var oo=new Uint8Array(0);var Ut=(i,e)=>{if(i===e)return!0;if(i.byteLength!==e.byteLength)return!1;for(let t=0;t<i.byteLength;t++)if(i[t]!==e[t])return!1;return!0},F=i=>{if(i instanceof Uint8Array&&i.constructor.name==="Uint8Array")return i;if(i instanceof ArrayBuffer)return new Uint8Array(i);if(ArrayBuffer.isView(i))return new Uint8Array(i.buffer,i.byteOffset,i.byteLength);throw new Error("Unknown type, must be binary type")};var qt=i=>new TextEncoder().encode(i),$t=i=>new TextDecoder().decode(i);var De=class{constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Oe=class{constructor(e,t,r){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=r}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 Vt(this,e)}},ve=class{constructor(e){this.decoders=e}or(e){return Vt(this,e)}decode(e){let t=e[0],r=this.decoders[t];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},Vt=(i,e)=>new ve({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}}),Be=class{constructor(e,t,r,s){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=s,this.encoder=new De(e,t,r),this.decoder=new Oe(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},J=({name:i,prefix:e,encode:t,decode:r})=>new Be(i,e,t,r),z=({prefix:i,name:e,alphabet:t})=>{let{encode:r,decode:s}=Ft(t,e);return J({prefix:i,name:e,encode:r,decode:n=>F(s(n))})},qi=(i,e,t,r)=>{let s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let n=i.length;for(;i[n-1]==="=";)--n;let o=new Uint8Array(n*t/8|0),a=0,c=0,h=0;for(let u=0;u<n;++u){let l=s[i[u]];if(l===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<t|l,a+=t,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},$i=(i,e,t)=>{let r=e[e.length-1]==="=",s=(1<<t)-1,n="",o=0,a=0;for(let c=0;c<i.length;++c)for(a=a<<8|i[c],o+=8;o>t;)o-=t,n+=e[s&a>>o];if(o&&(n+=e[s&a<<t-o]),r)for(;n.length*t&7;)n+="=";return n},x=({name:i,prefix:e,bitsPerChar:t,alphabet:r})=>J({prefix:e,name:i,encode(s){return $i(s,r,t)},decode(s){return qi(s,r,t,i)}});var V=x({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),zi=x({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Vi=x({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Wi=x({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ki=x({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Gi=x({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ji=x({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Hi=x({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Yi=x({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ue={};L(Ue,{base58btc:()=>O,base58flickr:()=>Qi});var O=z({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Qi=z({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var $e={};L($e,{base64:()=>qe,base64pad:()=>Xi,base64url:()=>Ji,base64urlpad:()=>Zi});var qe=x({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Xi=x({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ji=x({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Zi=x({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});N.default.formatters.b=i=>i==null?"undefined":O.baseEncode(i);N.default.formatters.t=i=>i==null?"undefined":V.baseEncode(i);N.default.formatters.m=i=>i==null?"undefined":qe.baseEncode(i);N.default.formatters.p=i=>i==null?"undefined":i.toString();N.default.formatters.c=i=>i==null?"undefined":i.toString();N.default.formatters.k=i=>i==null?"undefined":i.toString();N.default.formatters.a=i=>i==null?"undefined":i.toString();function es(i){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=i,e.destroy=()=>!0,e.extend=()=>e,e}function we(i){let e=es(`${i}:trace`);return N.default.enabled(`${i}:trace`)&&N.default.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=(0,N.default)(`${i}:trace`)),Object.assign((0,N.default)(i),{error:(0,N.default)(`${i}:error`),trace:e})}var ce=class extends Error{constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function Wt(i){if(i!=null){if(typeof i[Symbol.iterator]=="function")return i[Symbol.iterator]();if(typeof i[Symbol.asyncIterator]=="function")return i[Symbol.asyncIterator]();if(typeof i.next=="function")return i}throw new Error("argument is not an iterator or iterable")}function xe(i,e,t){let r=t??{},s=Wt(i);async function*n(){let o,a=()=>{o?.()};for(e.addEventListener("abort",a);;){let c;try{if(e.aborted){let{abortMessage:u,abortCode:l}=r;throw new ce(u,l)}let h=new Promise((u,l)=>{o=()=>{let{abortMessage:d,abortCode:w}=r;l(new ce(d,w))}});c=await Promise.race([h,s.next()]),o=null}catch(h){e.removeEventListener("abort",a);let u=h.type==="aborted"&&e.aborted;if(u&&r.onAbort!=null&&r.onAbort(i),typeof s.return=="function")try{let l=s.return();l instanceof Promise&&l.catch(d=>{r.onReturnError!=null&&r.onReturnError(d)})}catch(l){r.onReturnError!=null&&r.onReturnError(l)}if(u&&r.returnOnAbort===!0)return;throw h}if(c.done===!0)break;yield c.value}e.removeEventListener("abort",a)}return n()}function U(){let i={};return i.promise=new Promise((e,t)=>{i.resolve=e,i.reject=t}),i}var Ee=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Z=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new 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 ze=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function ee(i={}){return Gt(t=>{let r=t.shift();if(r==null)return{done:!0};if(r.error!=null)throw r.error;return{done:r.done===!0,value:r.value}},i)}function Kt(i={}){return Gt(t=>{let r,s=[];for(;!t.isEmpty()&&(r=t.shift(),r!=null);){if(r.error!=null)throw r.error;r.done===!1&&s.push(r.value)}return r==null?{done:!0}:{done:r.done===!0,value:s}},i)}function Gt(i,e){e=e??{};let t=e.onEnd,r=new Z,s,n,o,a=U(),c=async()=>{try{return r.isEmpty()?o?{done:!0}:await new Promise((f,y)=>{n=E=>{n=null,r.push(E);try{f(i(r))}catch(_){y(_)}return s}}):i(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=U()})}},h=f=>n!=null?n(f):(r.push(f),s),u=f=>(r=new Z,n!=null?n({error:f}):(r.push({error:f}),s)),l=f=>{if(o)return s;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})},d=f=>o?s:(o=!0,f!=null?u(f):h({done:!0})),w=()=>(r=new Z,d(),{done:!0}),m=f=>(d(f),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:w,throw:m,push:l,end:d,get readableLength(){return r.size},onEmpty:async f=>{let y=f?.signal;if(y?.throwIfAborted(),r.isEmpty())return;let E,_;y!=null&&(E=new Promise((S,A)=>{_=()=>{A(new ze)},y.addEventListener("abort",_)}));try{await Promise.race([a.promise,E])}finally{_!=null&&y!=null&&y?.removeEventListener("abort",_)}}},t==null)return s;let p=s;return s={[Symbol.asyncIterator](){return this},next(){return p.next()},throw(f){return p.throw(f),t!=null&&(t(f),t=void 0),{done:!0}},return(){return p.return(),t!=null&&(t(),t=void 0),{done:!0}},push:l,end(f){return p.end(f),t!=null&&(t(f),t=void 0),s},get readableLength(){return p.readableLength}},s}function ts(i){return i[Symbol.asyncIterator]!=null}function rs(...i){let e=[];for(let t of i)ts(t)||e.push(t);return e.length===i.length?function*(){for(let t of e)yield*t}():async function*(){let t=ee({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(i.map(async r=>{for await(let s of r)t.push(s)})),t.end()}catch(r){t.end(r)}}),yield*t}()}var jt=rs;function Ht(i,...e){if(i==null)throw new Error("Empty pipeline");if(Ve(i)){let r=i;i=()=>r.source}else if(Qt(i)||Yt(i)){let r=i;i=()=>r}let t=[i,...e];if(t.length>1&&Ve(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let r=1;r<t.length-1;r++)Ve(t[r])&&(t[r]=ss(t[r]));return is(...t)}var is=(...i)=>{let e;for(;i.length>0;)e=i.shift()(e);return e},Yt=i=>i?.[Symbol.asyncIterator]!=null,Qt=i=>i?.[Symbol.iterator]!=null,Ve=i=>i==null?!1:i.sink!=null&&i.source!=null,ss=i=>e=>{let t=i.sink(e);if(t?.then!=null){let r=ee({objectMode:!0});t.then(()=>{r.end()},o=>{r.end(o)});let s,n=i.source;if(Yt(n))s=async function*(){yield*n,r.end()};else if(Qt(n))s=function*(){yield*n,r.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return jt(r,s())}return i.source};var gi=Mt(Kr(),1);function W(i){return globalThis.Buffer!=null?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):i}function q(i=0){return globalThis.Buffer?.alloc!=null?W(globalThis.Buffer.alloc(i)):new Uint8Array(i)}function B(i=0){return globalThis.Buffer?.allocUnsafe!=null?W(globalThis.Buffer.allocUnsafe(i)):new Uint8Array(i)}function Se(i,e){e==null&&(e=i.reduce((s,n)=>s+n.length,0));let t=B(e),r=0;for(let s of i)t.set(s,r),r+=s.length;return W(t)}function nt(i,e){if(i===e)return!0;if(i.byteLength!==e.byteLength)return!1;for(let t=0;t<i.byteLength;t++)if(i[t]!==e[t])return!1;return!0}var ot={};L(ot,{base10:()=>qs});var qs=z({prefix:"9",name:"base10",alphabet:"0123456789"});var at={};L(at,{base16:()=>$s,base16upper:()=>zs});var $s=x({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),zs=x({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var ct={};L(ct,{base2:()=>Vs});var Vs=x({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ut={};L(ut,{base256emoji:()=>Hs});var Gr=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}"),Ws=Gr.reduce((i,e,t)=>(i[t]=e,i),[]),Ks=Gr.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function Gs(i){return i.reduce((e,t)=>(e+=Ws[t],e),"")}function js(i){let e=[];for(let t of i){let r=Ks[t.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(r)}return new Uint8Array(e)}var Hs=J({prefix:"\u{1F680}",name:"base256emoji",encode:Gs,decode:js});var lt={};L(lt,{base36:()=>Ys,base36upper:()=>Qs});var Ys=z({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Qs=z({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var ht={};L(ht,{base8:()=>Xs});var Xs=x({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var dt={};L(dt,{identity:()=>Js});var Js=J({prefix:"\0",name:"identity",encode:i=>$t(i),decode:i=>qt(i)});var Pa=new TextEncoder,Da=new TextDecoder;var mt={};L(mt,{identity:()=>_n});var tn=Yr,jr=128,rn=127,sn=~rn,nn=Math.pow(2,31);function Yr(i,e,t){e=e||[],t=t||0;for(var r=t;i>=nn;)e[t++]=i&255|jr,i/=128;for(;i&sn;)e[t++]=i&255|jr,i>>>=7;return e[t]=i|0,Yr.bytes=t-r+1,e}var on=ft,an=128,Hr=127;function ft(i,r){var t=0,r=r||0,s=0,n=r,o,a=i.length;do{if(n>=a)throw ft.bytes=0,new RangeError("Could not decode varint");o=i[n++],t+=s<28?(o&Hr)<<s:(o&Hr)*Math.pow(2,s),s+=7}while(o>=an);return ft.bytes=n-r,t}var cn=Math.pow(2,7),un=Math.pow(2,14),ln=Math.pow(2,21),hn=Math.pow(2,28),dn=Math.pow(2,35),fn=Math.pow(2,42),mn=Math.pow(2,49),pn=Math.pow(2,56),bn=Math.pow(2,63),yn=function(i){return i<cn?1:i<un?2:i<ln?3:i<hn?4:i<dn?5:i<fn?6:i<mn?7:i<pn?8:i<bn?9:10},gn={encode:tn,decode:on,encodingLength:yn},wn=gn,le=wn;var he=(i,e=0)=>[le.decode(i,e),le.decode.bytes],ne=(i,e,t=0)=>(le.encode(i,e,t),e),oe=i=>le.encodingLength(i);var G=(i,e)=>{let t=e.byteLength,r=oe(i),s=r+oe(t),n=new Uint8Array(s+t);return ne(i,n,0),ne(t,n,r),n.set(e,s),new ae(i,t,e,n)},Qr=i=>{let e=F(i),[t,r]=he(e),[s,n]=he(e.subarray(r)),o=e.subarray(r+n);if(o.byteLength!==s)throw new Error("Incorrect length");return new ae(t,s,o,e)},Xr=(i,e)=>{if(i===e)return!0;{let t=e;return i.code===t.code&&i.size===t.size&&t.bytes instanceof Uint8Array&&Ut(i.bytes,t.bytes)}},ae=class{constructor(e,t,r,s){this.code=e,this.size=t,this.digest=r,this.bytes=s}};var Jr=0,xn="identity",Zr=F,En=i=>G(Jr,Zr(i)),_n={code:Jr,name:xn,encode:Zr,digest:En};var yt={};L(yt,{sha256:()=>Sn,sha512:()=>Cn});var bt=({name:i,code:e,encode:t})=>new pt(i,e,t),pt=class{constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?G(this.code,t):t.then(r=>G(this.code,r))}else throw Error("Unknown type, must be binary type")}};var ti=i=>async e=>new Uint8Array(await crypto.subtle.digest(i,e)),Sn=bt({name:"sha2-256",code:18,encode:ti("SHA-256")}),Cn=bt({name:"sha2-512",code:19,encode:ti("SHA-512")});var ri=(i,e)=>{let{bytes:t,version:r}=i;switch(r){case 0:return An(t,gt(i),e||O.encoder);default:return In(t,gt(i),e||V.encoder)}};var ii=new WeakMap,gt=i=>{let e=ii.get(i);if(e==null){let t=new Map;return ii.set(i,t),t}return e},Re=class i{constructor(e,t,r,s){this.code=t,this.version=e,this.multihash=r,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==fe)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ln)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return i.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,r=G(e,t);return i.createV1(this.code,r)}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 i.equals(this,e)}static equals(e,t){let r=t;return r&&e.code===r.code&&e.version===r.version&&Xr(e.multihash,r.multihash)}toString(e){return ri(this,e)}toJSON(){return{"/":ri(this)}}link(){return this}get[Symbol.toStringTag](){return"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 i)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:r,code:s,multihash:n,bytes:o}=t;return new i(r,s,n,o||si(r,s,n.bytes))}else if(t[Tn]===!0){let{version:r,multihash:s,code:n}=t,o=Qr(s);return i.create(r,n,o)}else return null}static create(e,t,r){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==fe)throw new Error(`Version 0 CID must use dag-pb (code: ${fe}) block encoding`);return new i(e,t,r,r.bytes)}case 1:{let s=si(e,t,r.bytes);return new i(e,t,r,s)}default:throw new Error("Invalid version")}}static createV0(e){return i.create(0,fe,e)}static createV1(e,t){return i.create(1,e,t)}static decode(e){let[t,r]=i.decodeFirst(e);if(r.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=i.inspectBytes(e),r=t.size-t.multihashSize,s=F(e.subarray(r,r+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let n=s.subarray(t.multihashSize-t.digestSize),o=new ae(t.multihashCode,t.digestSize,n,s);return[t.version===0?i.createV0(o):i.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,r=()=>{let[l,d]=he(e.subarray(t));return t+=d,l},s=r(),n=fe;if(s===18?(s=0,t=0):n=r(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=t,a=r(),c=r(),h=t+c,u=h-o;return{version:s,codec:n,multihashCode:a,digestSize:c,multihashSize:u,size:h}}static parse(e,t){let[r,s]=Rn(e,t),n=i.decode(s);if(n.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return gt(n).set(r,e),n}},Rn=(i,e)=>{switch(i[0]){case"Q":{let t=e||O;return[O.prefix,t.decode(`${O.prefix}${i}`)]}case O.prefix:{let t=e||O;return[O.prefix,t.decode(i)]}case V.prefix:{let t=e||V;return[V.prefix,t.decode(i)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[i[0],e.decode(i)]}}},An=(i,e,t)=>{let{prefix:r}=t;if(r!==O.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(r);if(s==null){let n=t.encode(i).slice(1);return e.set(r,n),n}else return s},In=(i,e,t)=>{let{prefix:r}=t,s=e.get(r);if(s==null){let n=t.encode(i);return e.set(r,n),n}else return s},fe=112,Ln=18,si=(i,e,t)=>{let r=oe(i),s=r+oe(e),n=new Uint8Array(s+t.byteLength);return ne(i,n,0),ne(e,n,r),n.set(t,s),n},Tn=Symbol.for("@ipld/js-cid/CID");var wt={...dt,...ct,...ht,...ot,...at,...Fe,...lt,...Ue,...$e,...ut},Qa={...yt,...mt};function oi(i,e,t,r){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:r}}}var ni=oi("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),xt=oi("ascii","a",i=>{let e="a";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return e},i=>{i=i.substring(1);let e=B(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),Nn={utf8:ni,"utf-8":ni,hex:wt.base16,latin1:xt,ascii:xt,binary:xt,...wt},Ae=Nn;function Et(i,e="utf8"){let t=Ae[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?W(globalThis.Buffer.from(i,"utf-8")):t.decoder.decode(`${t.prefix}${i}`)}function me(i,e="utf8"){let t=Ae[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("utf8"):t.encoder.encode(i).substring(1)}var ci=Symbol.for("@achingbrain/uint8arraylist");function ai(i,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let r of i){let s=t+r.byteLength;if(e<s)return{buf:r,index:e-t};t=s}throw new RangeError("index is out of bounds")}function Ie(i){return!!i?.[ci]}var C=class i{constructor(...e){Object.defineProperty(this,ci,{value:!0}),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 r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else if(Ie(r))t+=r.byteLength,this.bufs.push(...r.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else if(Ie(r))t+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=ai(this.bufs,e);return t.buf[t.index]}set(e,t){let r=ai(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(t+r,e[r]);else if(Ie(e))for(let r=0;r<e.length;r++)this.set(t+r,e.get(r));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:r,length:s}=this._subList(e,t);return Se(r,s)}subarray(e,t){let{bufs:r,length:s}=this._subList(e,t);return r.length===1?r[0]:Se(r,s)}sublist(e,t){let{bufs:r,length:s}=this._subList(e,t),n=new i;return n.length=s,n.bufs=r,n}_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 r=[],s=0;for(let n=0;n<this.bufs.length;n++){let o=this.bufs[n],a=s,c=a+o.byteLength;if(s=c,e>=c)continue;let h=e>=a&&e<c,u=t>a&&t<=c;if(h&&u){if(e===a&&t===c){r.push(o);break}let l=e-a;r.push(o.subarray(l,l+(t-e)));break}if(h){if(e===0){r.push(o);continue}r.push(o.subarray(e-a));continue}if(u){if(t===c){r.push(o);break}r.push(o.subarray(0,t-a));break}r.push(o)}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!Ie(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let r=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=r.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let n=256,o=new Int32Array(n);for(let l=0;l<n;l++)o[l]=-1;for(let l=0;l<s;l++)o[r[l]]=l;let a=o,c=this.byteLength-r.byteLength,h=r.byteLength-1,u;for(let l=t;l<=c;l+=u){u=0;for(let d=h;d>=0;d--){let w=this.get(l+d);if(r[d]!==w){u=Math.max(1,d-a[w]);break}}if(u===0)return l}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let r=B(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){let s=q(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,r),this.write(s,e)}getInt32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){let s=q(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,r),this.write(s,e)}getBigInt64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){let s=q(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,r),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let r=B(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){let s=q(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,r),this.write(s,e)}getUint32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){let s=q(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,r),this.write(s,e)}getBigUint64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){let s=q(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,r),this.write(s,e)}getFloat32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){let s=q(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,r),this.write(s,e)}getFloat64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){let s=q(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,r),this.write(s,e)}equals(e){if(e==null||!(e instanceof i)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!nt(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let r=new i;return r.bufs=e,t==null&&(t=e.reduce((s,n)=>s+n.byteLength,0)),r.length=t,r}};var b;(function(i){i[i.NEW_STREAM=0]="NEW_STREAM",i[i.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",i[i.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",i[i.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",i[i.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",i[i.RESET_RECEIVER=5]="RESET_RECEIVER",i[i.RESET_INITIATOR=6]="RESET_INITIATOR"})(b||(b={}));var pe=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),_t=Object.freeze({NEW_STREAM:b.NEW_STREAM,MESSAGE:b.MESSAGE_INITIATOR,CLOSE:b.CLOSE_INITIATOR,RESET:b.RESET_INITIATOR}),ui=Object.freeze({MESSAGE:b.MESSAGE_RECEIVER,CLOSE:b.CLOSE_RECEIVER,RESET:b.RESET_RECEIVER});var St=1<<20,kn=4<<20,Le=class{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=St,t=kn){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 Object.assign(new Error("unprocessed message queue size too large!"),{code:"ERR_MSG_QUEUE_TOO_BIG"});let t=[];for(;this._buffer.length!==0;){if(this._headerInfo==null)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(h){if(h.code==="ERR_MSG_TOO_BIG")throw h;break}let{id:r,type:s,length:n,offset:o}=this._headerInfo;if(this._buffer.length-o<n)break;let c={id:r,type:s};(s===b.NEW_STREAM||s===b.MESSAGE_INITIATOR||s===b.MESSAGE_RECEIVER)&&(c.data=this._buffer.sublist(o,o+n)),t.push(c),this._buffer.consume(o+n),this._headerInfo=null}return t}_decodeHeader(e){let{value:t,offset:r}=hi(e),{value:s,offset:n}=hi(e,r),o=t&7;if(pe[o]==null)throw new Error(`Invalid type received: ${o}`);if(s>this._maxMessageSize)throw Object.assign(new Error("message size too large!"),{code:"ERR_MSG_TOO_BIG"});return{id:t>>3,type:o,offset:r+n,length:s}}},Mn=128,li=127;function hi(i,e=0){let t=0,r=0,s=e,n,o=i.length;do{if(s>=o||r>49)throw e=0,new RangeError("Could not decode varint");n=i.get(s++),t+=r<28?(n&li)<<r:(n&li)*Math.pow(2,r),r+=7}while(n>=Mn);return e=s-e,{value:t,offset:e}}function Pn(i){return i[Symbol.asyncIterator]!=null}var Te=1024*1024,di=(i,e)=>{e.append(i)};function Dn(i,e){return Pn(i)?async function*(){let t=new C,r=!1,s=U(),n=Number(e?.size??Te);if((isNaN(n)||n===0||n<0)&&(n=Te),n!==Math.round(n))throw new Error("Batch size must be an integer");let o=e?.yieldAfter??0,a=e?.serialize??di;for(Promise.resolve().then(async()=>{try{let c;for await(let h of i){if(a(h,t),t.byteLength>=n){clearTimeout(c),s.resolve();continue}c=setTimeout(()=>{s.resolve()},o)}clearTimeout(c),s.resolve()}catch(c){s.reject(c)}finally{r=!0}});!r;)if(await s.promise,s=U(),t.byteLength>0){let c=t;t=new C,yield c.subarray()}}():function*(){let t=new C,r=Number(e?.size??Te);if((isNaN(r)||r===0||r<0)&&(r=Te),r!==Math.round(r))throw new Error("Batch size must be an integer");let s=e?.serialize??di;for(let n of i)s(n,t),t.byteLength>=r&&(yield t.subarray(0,r),t.consume(r));t.byteLength>0&&(yield t.subarray())}()}var fi=Dn;var On=Math.pow(2,7),vn=Math.pow(2,14),Bn=Math.pow(2,21),Fn=Math.pow(2,28),Un=Math.pow(2,35),qn=Math.pow(2,42),$n=Math.pow(2,49),R=128;function j(i){if(i<On)return 1;if(i<vn)return 2;if(i<Bn)return 3;if(i<Fn)return 4;if(i<Un)return 5;if(i<qn)return 6;if(i<$n)return 7;if(Number.MAX_SAFE_INTEGER!=null&&i>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function zn(i,e,t=0){switch(j(i)){case 8:e[t++]=i&255|R,i/=128;case 7:e[t++]=i&255|R,i/=128;case 6:e[t++]=i&255|R,i/=128;case 5:e[t++]=i&255|R,i/=128;case 4:e[t++]=i&255|R,i>>>=7;case 3:e[t++]=i&255|R,i>>>=7;case 2:e[t++]=i&255|R,i>>>=7;case 1:{e[t++]=i&255,i>>>=7;break}default:throw new Error("unreachable")}return e}function Vn(i,e,t=0){switch(j(i)){case 8:e.set(t++,i&255|R),i/=128;case 7:e.set(t++,i&255|R),i/=128;case 6:e.set(t++,i&255|R),i/=128;case 5:e.set(t++,i&255|R),i/=128;case 4:e.set(t++,i&255|R),i>>>=7;case 3:e.set(t++,i&255|R),i>>>=7;case 2:e.set(t++,i&255|R),i>>>=7;case 1:{e.set(t++,i&255),i>>>=7;break}default:throw new Error("unreachable")}return e}function Ne(i,e,t=0){return e==null&&(e=B(j(i))),e instanceof Uint8Array?zn(i,e,t):Vn(i,e,t)}function Ct(i){return new Uint8Array(i)}var Rt=10*1024,At=class{_pool;_poolOffset;constructor(){this._pool=Ct(Rt),this._poolOffset=0}write(e,t){let r=this._pool,s=this._poolOffset;Ne(e.id<<3|e.type,r,s),s+=j(e.id<<3|e.type),(e.type===b.NEW_STREAM||e.type===b.MESSAGE_INITIATOR||e.type===b.MESSAGE_RECEIVER)&&e.data!=null?(Ne(e.data.length,r,s),s+=j(e.data.length)):(Ne(0,r,s),s+=j(0));let n=r.subarray(this._poolOffset,s);Rt-s<100?(this._pool=Ct(Rt),this._poolOffset=0):this._poolOffset=s,t.append(n),(e.type===b.NEW_STREAM||e.type===b.MESSAGE_INITIATOR||e.type===b.MESSAGE_RECEIVER)&&e.data!=null&&t.append(e.data)}},mi=new At;async function*pi(i,e=0){if(e==null||e===0){for await(let t of i){let r=new C;for(let s of t)mi.write(s,r);yield r.subarray()}return}yield*fi(i,{size:e,serialize:(t,r)=>{for(let s of t)mi.write(s,r)}})}var ke=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};async function It(i,e,t){if(e==null)return i;if(e.aborted)return Promise.reject(new ke(t?.errorMessage,t?.errorCode));let r,s=new ke(t?.errorMessage,t?.errorCode);try{return await Promise.race([i,new Promise((n,o)=>{r=()=>{o(s)},e.addEventListener("abort",r)})])}finally{r!=null&&e.removeEventListener("abort",r)}}var Kn="ERR_STREAM_RESET",Gn="ERR_SINK_INVALID_STATE",jn=5e3;function Lt(i){return i!=null&&typeof i.then=="function"}var Me=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;sinkController;sinkEnd;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;log;constructor(e){this.sinkController=new AbortController,this.sinkEnd=U(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??jn,this.onEnd=e.onEnd,this.onCloseRead=e?.onCloseRead,this.onCloseWrite=e?.onCloseWrite,this.onReset=e?.onReset,this.onAbort=e?.onAbort,this.source=this.streamSource=ee({onEnd:t=>{t!=null?this.log.trace("source ended with error",t):this.log.trace("source ended"),this.onSourceEnd(t)}}),this.sink=this.sink.bind(this)}async sink(e){if(this.writeStatus!=="ready")throw new $(`writable end state is "${this.writeStatus}" not "ready"`,Gn);try{this.writeStatus="writing";let t={signal:this.sinkController.signal};if(this.direction==="outbound"){let r=this.sendNewStream(t);Lt(r)&&await r}e=xe(e,this.sinkController.signal,{returnOnAbort:!0}),this.log.trace("sink reading from source");for await(let r of e){r=r instanceof Uint8Array?new C(r):r;let s=this.sendData(r,t);Lt(s)&&await s}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(t){throw this.log.trace("sink ended with error, calling abort with error",t),this.abort(t),t}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr)):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr)):this.log.trace("sink ended, waiting for source to end"))}async close(e){this.log.trace("closing gracefully"),this.status="closing",await Promise.all([this.closeRead(e),this.closeWrite(e)]),this.status="closed",this.log.trace("closed gracefully")}async closeRead(e={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let t=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),t==="ready"&&(this.log.trace("ending internal source queue"),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await It(this.sink([]),e.signal)),this.writeStatus==="writing"&&await new Promise((t,r)=>{queueMicrotask(()=>{this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),It(this.sinkEnd.promise,e.signal).then(t,r)})}),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",e),this.log("try to send reset to remote");let t=this.sendReset();Lt(t)&&t.catch(r=>{this.log.error("error sending reset message",r)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let e=new $("stream reset",Kn);this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}};var Tt=class extends Me{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types=e.direction==="outbound"?_t:ui,this.send=e.send,this.name=e.name,this.streamId=e.streamId,this.maxDataSize=e.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:_t.NEW_STREAM,data:new C(Et(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){let t=Math.min(e.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:e.sublist(0,t)}),e.consume(t)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}};function bi(i){let{id:e,name:t,send:r,onEnd:s,type:n="initiator",maxMsgSize:o=St}=i;return new Tt({id:n==="initiator"?`i${e}`:`r${e}`,streamId:e,name:`${t??e}`,direction:n==="initiator"?"outbound":"inbound",maxDataSize:o,onEnd:s,send:r,log:we(`libp2p:mplex:stream:${n}:${e}`)})}var M=we("libp2p:mplex"),Hn=1024,Yn=1024,Qn=1024*1024*4,Xn=5,Jn=500;function yi(i){let e={...i,type:`${pe[i.type]} (${i.type})`};return i.type===b.NEW_STREAM&&(e.data=me(i.data instanceof Uint8Array?i.data:i.data.subarray())),(i.type===b.MESSAGE_INITIATOR||i.type===b.MESSAGE_RECEIVER)&&(e.data=me(i.data instanceof Uint8Array?i.data:i.data.subarray(),"base16")),e}var Pe=class{protocol="/mplex/6.7.0";sink;source;_streamId;_streams;_init;_source;closeController;rateLimiter;closeTimeout;constructor(e){e=e??{},this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=e,this.closeTimeout=e.closeTimeout??Jn,this.sink=this._createSink(),this._source=Kt({objectMode:!0,onEnd:()=>{for(let t of this._streams.initiators.values())t.destroy();for(let t of this._streams.receivers.values())t.destroy()}}),this.source=Ht(this._source,t=>pi(t,this._init.minSendBytes)),this.closeController=new AbortController,this.rateLimiter=new gi.RateLimiterMemory({points:e.disconnectThreshold??Xn,duration:1})}get streams(){let e=[];for(let t of this._streams.initiators.values())e.push(t);for(let t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new Error("Muxer already closed");let t=this._streamId++;e=e==null?t.toString():e.toString();let r=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:r})}async close(e){if(this.closeController.signal.aborted)return;let t=e?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map(async r=>r.close({signal:t}))),this._source.end(),await this._source.onEmpty({signal:t}),this.closeController.abort()}catch(r){this.abort(r)}}abort(e){this.closeController.signal.aborted||(this.streams.forEach(t=>{t.abort(e)}),this.closeController.abort(e))}_newReceiverStream(e){let{id:t,name:r}=e,s=this._streams.receivers;return this._newStream({id:t,name:r,type:"receiver",registry:s})}_newStream(e){let{id:t,name:r,type:s,registry:n}=e;if(M("new %s stream %s",s,t),s==="initiator"&&this._streams.initiators.size===(this._init.maxOutboundStreams??Yn))throw new $("Too many outbound streams open","ERR_TOO_MANY_OUTBOUND_STREAMS");if(n.has(t))throw new Error(`${s} stream ${t} already exists!`);let c=bi({id:t,name:r,send:async h=>{M.enabled&&M.trace("%s stream %s send",s,t,yi(h)),this._source.push(h)},type:s,onEnd:()=>{M("%s stream with id %s and protocol %s ended",s,t,c.protocol),n.delete(t),this._init.onStreamEnd!=null&&this._init.onStreamEnd(c)},maxMsgSize:this._init.maxMsgSize});return n.set(t,c),c}_createSink(){return async t=>{try{t=xe(t,this.closeController.signal,{returnOnAbort:!0});let r=new Le(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(let s of t)for(let n of r.write(s))await this._handleIncoming(n);this._source.end()}catch(r){M("error in sink",r),this._source.end(r)}}}async _handleIncoming(e){let{id:t,type:r}=e;if(M.enabled&&M.trace("incoming message",yi(e)),e.type===b.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??Hn)){M("too many inbound streams open"),this._source.push({id:t,type:b.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{M("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),this.abort(new Error("Too many open streams"));return}return}let a=this._newReceiverStream({id:t,name:me(e.data instanceof Uint8Array?e.data:e.data.subarray())});this._init.onIncomingStream!=null&&this._init.onIncomingStream(a);return}let n=((r&1)===1?this._streams.initiators:this._streams.receivers).get(t);if(n==null){M("missing stream %s for message type %s",t,pe[r]);try{await this.rateLimiter.consume("missing-stream",1)}catch{M("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}let o=this._init.maxStreamBufferSize??Qn;try{switch(r){case b.MESSAGE_INITIATOR:case b.MESSAGE_RECEIVER:if(n.sourceReadableLength()>o)throw this._source.push({id:e.id,type:r===b.MESSAGE_INITIATOR?b.RESET_RECEIVER:b.RESET_INITIATOR}),new $("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers","ERR_STREAM_INPUT_BUFFER_FULL");n.sourcePush(e.data);break;case b.CLOSE_INITIATOR:case b.CLOSE_RECEIVER:n.remoteCloseWrite();break;case b.RESET_INITIATOR:case b.RESET_RECEIVER:n.reset();break;default:M("unknown message type %s",r)}}catch(a){M.error("error while processing message",a),n.abort(a)}}};var Nt=class{protocol="/mplex/6.7.0";_init;constructor(e={}){this._init=e}createStreamMuxer(e={}){return new Pe({...e,...this._init})}};function Zn(i={}){return()=>new Nt(i)}return Ci(eo);})();
|
24
|
+
SELECT points, expire FROM ${this._getTableIdentifier()} WHERE key = $1 AND (expire > $2 OR expire IS NULL);`,values:[e,Date.now()]}).then(s=>{s.rowCount===0&&(s=null),t(s)}).catch(s=>{r(s)})}):Promise.reject(Error("Table is not created yet"))}_delete(e){return this.tableCreated?this._query({name:"rlflx-delete",text:`DELETE FROM ${this._getTableIdentifier()} WHERE key = $1`,values:[e]}).then(t=>t.rowCount>0):Promise.reject(Error("Table is not created yet"))}};$t.exports=Ce});var Kt=b(()=>{});var Gt=b(()=>{});var Ht=b((co,jt)=>{jt.exports=class{constructor(e,t,r=null){this.value=e,this.expiresAt=t,this.timeoutId=r}get value(){return this._value}set value(e){this._value=parseInt(e)}get expiresAt(){return this._expiresAt}set expiresAt(e){!(e instanceof Date)&&Number.isInteger(e)&&(e=new Date(e)),this._expiresAt=e}get timeoutId(){return this._timeoutId}set timeoutId(e){this._timeoutId=e}}});var Qt=b((lo,Yt)=>{var Si=Ht(),Me=T();Yt.exports=class{constructor(){this._storage={}}incrby(e,t,r){if(this._storage[e]){let s=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return s!==0?(this._storage[e].value=this._storage[e].value+t,new Me(0,s,this._storage[e].value,!1)):this.set(e,t,r)}return this.set(e,t,r)}set(e,t,r){let s=r*1e3;return this._storage[e]&&this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),this._storage[e]=new Si(t,s>0?new Date(Date.now()+s):null),s>0&&(this._storage[e].timeoutId=setTimeout(()=>{delete this._storage[e]},s),this._storage[e].timeoutId.unref&&this._storage[e].timeoutId.unref()),new Me(0,s===0?-1:s,this._storage[e].value,!0)}get(e){if(this._storage[e]){let t=this._storage[e].expiresAt?this._storage[e].expiresAt.getTime()-new Date().getTime():-1;return new Me(0,t,this._storage[e].value,!1)}return null}delete(e){return this._storage[e]?(this._storage[e].timeoutId&&clearTimeout(this._storage[e].timeoutId),delete this._storage[e],!0):!1}}});var ke=b((uo,Jt)=>{var Ri=ee(),Ai=Qt(),Xt=T(),Pe=class extends Ri{constructor(e={}){super(e),this._memoryStorage=new Ai}consume(e,t=1,r={}){return new Promise((s,n)=>{let o=this.getKey(e),a=this._getKeySecDuration(r),c=this._memoryStorage.incrby(o,t,a);if(c.remainingPoints=Math.max(this.points-c.consumedPoints,0),c.consumedPoints>this.points)this.blockDuration>0&&c.consumedPoints<=this.points+t&&(c=this._memoryStorage.set(o,c.consumedPoints,this.blockDuration)),n(c);else if(this.execEvenly&&c.msBeforeNext>0&&!c.isFirstInDuration){let h=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));h<this.execEvenlyMinDelayMs&&(h=c.consumedPoints*this.execEvenlyMinDelayMs),setTimeout(s,h,c)}else s(c)})}penalty(e,t=1,r={}){let s=this.getKey(e);return new Promise(n=>{let o=this._getKeySecDuration(r),a=this._memoryStorage.incrby(s,t,o);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),n(a)})}reward(e,t=1,r={}){let s=this.getKey(e);return new Promise(n=>{let o=this._getKeySecDuration(r),a=this._memoryStorage.incrby(s,-t,o);a.remainingPoints=Math.max(this.points-a.consumedPoints,0),n(a)})}block(e,t){let r=t*1e3,s=this.points+1;return this._memoryStorage.set(this.getKey(e),s,t),Promise.resolve(new Xt(0,r===0?-1:r,s))}set(e,t,r){let s=(r>=0?r:this.duration)*1e3;return this._memoryStorage.set(this.getKey(e),t,r),Promise.resolve(new Xt(0,s===0?-1:s,t))}get(e){let t=this._memoryStorage.get(this.getKey(e));return t!==null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),Promise.resolve(t)}delete(e){return Promise.resolve(this._memoryStorage.delete(this.getKey(e)))}};Jt.exports=Pe});var nr=b((fo,sr)=>{var Zt=Kt(),Ii=Gt(),Ti=ee(),tr=ke(),Li=T(),N="rate_limiter_flexible",H=null,er=function(i,e,t,r){let s;r===null||r===!0||r===!1?s=r:s={remainingPoints:r.remainingPoints,msBeforeNext:r.msBeforeNext,consumedPoints:r.consumedPoints,isFirstInDuration:r.isFirstInDuration},i.send({channel:N,keyPrefix:e.keyPrefix,promiseId:e.promiseId,type:t,data:s})},rr=function(i){setTimeout(()=>{this._initiated?process.send(i):typeof this._promises[i.promiseId]<"u"&&rr.call(this,i)},30)},G=function(i,e,t,r,s){let n={channel:N,keyPrefix:this.keyPrefix,func:i,promiseId:e,data:{key:t,arg:r,opts:s}};this._initiated?process.send(n):rr.call(this,n)},ir=function(i,e){if(!e||e.channel!==N||typeof this._rateLimiters[e.keyPrefix]>"u")return!1;let t;switch(e.func){case"consume":t=this._rateLimiters[e.keyPrefix].consume(e.data.key,e.data.arg,e.data.opts);break;case"penalty":t=this._rateLimiters[e.keyPrefix].penalty(e.data.key,e.data.arg,e.data.opts);break;case"reward":t=this._rateLimiters[e.keyPrefix].reward(e.data.key,e.data.arg,e.data.opts);break;case"block":t=this._rateLimiters[e.keyPrefix].block(e.data.key,e.data.arg,e.data.opts);break;case"get":t=this._rateLimiters[e.keyPrefix].get(e.data.key,e.data.opts);break;case"delete":t=this._rateLimiters[e.keyPrefix].delete(e.data.key,e.data.opts);break;default:return!1}t&&t.then(r=>{er(i,e,"resolve",r)}).catch(r=>{er(i,e,"reject",r)})},Ni=function(i){if(!i||i.channel!==N||i.keyPrefix!==this.keyPrefix)return!1;if(this._promises[i.promiseId]){clearTimeout(this._promises[i.promiseId].timeoutId);let e;switch(i.data===null||i.data===!0||i.data===!1?e=i.data:e=new Li(i.data.remainingPoints,i.data.msBeforeNext,i.data.consumedPoints,i.data.isFirstInDuration),i.type){case"resolve":this._promises[i.promiseId].resolve(e);break;case"reject":this._promises[i.promiseId].reject(e);break;default:throw new Error(`RateLimiterCluster: no such message type '${i.type}'`)}delete this._promises[i.promiseId]}},Ci=function(){return{points:this.points,duration:this.duration,blockDuration:this.blockDuration,execEvenly:this.execEvenly,execEvenlyMinDelayMs:this.execEvenlyMinDelayMs,keyPrefix:this.keyPrefix}},j=function(i,e){let t=process.hrtime(),r=t[0].toString()+t[1].toString();return typeof this._promises[r]<"u"&&(r+=Ii.randomBytes(12).toString("base64")),this._promises[r]={resolve:i,reject:e,timeoutId:setTimeout(()=>{delete this._promises[r],e(new Error("RateLimiterCluster timeout: no answer from master in time"))},this.timeoutMs)},r},De=class{constructor(){if(H)return H;this._rateLimiters={},Zt.setMaxListeners(0),Zt.on("message",(e,t)=>{t&&t.channel===N&&t.type==="init"?(typeof this._rateLimiters[t.opts.keyPrefix]>"u"&&(this._rateLimiters[t.opts.keyPrefix]=new tr(t.opts)),e.send({channel:N,type:"init",keyPrefix:t.opts.keyPrefix})):ir.call(this,e,t)}),H=this}},Be=class{constructor(e){if(H)return H;this._rateLimiters={},e.launchBus((t,r)=>{r.on("process:msg",s=>{let n=s.raw;if(n&&n.channel===N&&n.type==="init")typeof this._rateLimiters[n.opts.keyPrefix]>"u"&&(this._rateLimiters[n.opts.keyPrefix]=new tr(n.opts)),e.sendDataToProcessId(s.process.pm_id,{data:{},topic:N,channel:N,type:"init",keyPrefix:n.opts.keyPrefix},(o,a)=>{o&&console.log(o,a)});else{let o={send:a=>{let c=a;c.topic=N,typeof c.data>"u"&&(c.data={}),e.sendDataToProcessId(s.process.pm_id,c,(h,l)=>{h&&console.log(h,l)})}};ir.call(this,o,n)}})}),H=this}},Oe=class extends Ti{get timeoutMs(){return this._timeoutMs}set timeoutMs(e){this._timeoutMs=typeof e>"u"?5e3:Math.abs(parseInt(e))}constructor(e={}){super(e),process.setMaxListeners(0),this.timeoutMs=e.timeoutMs,this._initiated=!1,process.on("message",t=>{t&&t.channel===N&&t.type==="init"&&t.keyPrefix===this.keyPrefix?this._initiated=!0:Ni.call(this,t)}),process.send({channel:N,type:"init",opts:Ci.call(this)}),this._promises={}}consume(e,t=1,r={}){return new Promise((s,n)=>{let o=j.call(this,s,n);G.call(this,"consume",o,e,t,r)})}penalty(e,t=1,r={}){return new Promise((s,n)=>{let o=j.call(this,s,n);G.call(this,"penalty",o,e,t,r)})}reward(e,t=1,r={}){return new Promise((s,n)=>{let o=j.call(this,s,n);G.call(this,"reward",o,e,t,r)})}block(e,t,r={}){return new Promise((s,n)=>{let o=j.call(this,s,n);G.call(this,"block",o,e,t,r)})}get(e,t={}){return new Promise((r,s)=>{let n=j.call(this,r,s);G.call(this,"get",n,e,t)})}delete(e,t={}){return new Promise((r,s)=>{let n=j.call(this,r,s);G.call(this,"delete",n,e,t)})}};sr.exports={RateLimiterClusterMaster:De,RateLimiterClusterMasterPM2:Be,RateLimiterCluster:Oe}});var ar=b((mo,or)=>{var Mi=K(),Pi=T(),ve=class extends Mi{constructor(e){super(e),this.client=e.storeClient}_getRateLimiterRes(e,t,r){let s=new Pi;return s.consumedPoints=parseInt(r.consumedPoints),s.isFirstInDuration=r.consumedPoints===t,s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.msBeforeNext=r.msBeforeNext,s}_upsert(e,t,r,s=!1,n={}){return new Promise((o,a)=>{let c=Date.now(),h=Math.floor(r/1e3);s?this.client.set(e,t,h,l=>{l?a(l):this.client.set(`${e}_expire`,h>0?c+h*1e3:-1,h,()=>{let d={consumedPoints:t,msBeforeNext:h>0?h*1e3:-1};o(d)})}):this.client.incr(e,t,(l,d)=>{l||d===!1?this.client.add(e,t,h,(y,E)=>{if(y||!E)if(typeof n.attemptNumber>"u"||n.attemptNumber<3){let u=Object.assign({},n);u.attemptNumber=u.attemptNumber?u.attemptNumber+1:1,this._upsert(e,t,r,s,u).then(m=>o(m)).catch(m=>a(m))}else a(new Error("Can not add key"));else this.client.add(`${e}_expire`,h>0?c+h*1e3:-1,h,()=>{let u={consumedPoints:t,msBeforeNext:h>0?h*1e3:-1};o(u)})}):this.client.get(`${e}_expire`,(y,E)=>{if(y)a(y);else{let u=E===!1?0:E,m={consumedPoints:d,msBeforeNext:u>=0?Math.max(u-c,0):-1};o(m)}})})})}_get(e){return new Promise((t,r)=>{let s=Date.now();this.client.get(e,(n,o)=>{o?this.client.get(`${e}_expire`,(a,c)=>{if(a)r(a);else{let h=c===!1?0:c,l={consumedPoints:o,msBeforeNext:h>=0?Math.max(h-s,0):-1};t(l)}}):t(null)})})}_delete(e){return new Promise((t,r)=>{this.client.del(e,(s,n)=>{s?r(s):n===!1?t(n):this.client.del(`${e}_expire`,o=>{o?r(o):t(n)})})})}};or.exports=ve});var lr=b((yo,hr)=>{var cr=T();hr.exports=class{constructor(e={}){this.limiter=e.limiter,this.blackList=e.blackList,this.whiteList=e.whiteList,this.isBlackListed=e.isBlackListed,this.isWhiteListed=e.isWhiteListed,this.runActionAnyway=e.runActionAnyway}get limiter(){return this._limiter}set limiter(e){if(typeof e>"u")throw new Error("limiter is not set");this._limiter=e}get runActionAnyway(){return this._runActionAnyway}set runActionAnyway(e){this._runActionAnyway=typeof e>"u"?!1:e}get blackList(){return this._blackList}set blackList(e){this._blackList=Array.isArray(e)?e:[]}get isBlackListed(){return this._isBlackListed}set isBlackListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isBlackListed must be function");this._isBlackListed=e}get whiteList(){return this._whiteList}set whiteList(e){this._whiteList=Array.isArray(e)?e:[]}get isWhiteListed(){return this._isWhiteListed}set isWhiteListed(e){if(typeof e>"u"&&(e=()=>!1),typeof e!="function")throw new Error("isWhiteListed must be function");this._isWhiteListed=e}isBlackListedSomewhere(e){return this.blackList.indexOf(e)>=0||this.isBlackListed(e)}isWhiteListedSomewhere(e){return this.whiteList.indexOf(e)>=0||this.isWhiteListed(e)}getBlackRes(){return new cr(0,Number.MAX_SAFE_INTEGER,0,!1)}getWhiteRes(){return new cr(Number.MAX_SAFE_INTEGER,0,0,!1)}rejectBlack(){return Promise.reject(this.getBlackRes())}resolveBlack(){return Promise.resolve(this.getBlackRes())}resolveWhite(){return Promise.resolve(this.getWhiteRes())}consume(e,t=1){let r;return this.isWhiteListedSomewhere(e)?r=this.resolveWhite():this.isBlackListedSomewhere(e)&&(r=this.rejectBlack()),typeof r>"u"?this.limiter.consume(e,t):(this.runActionAnyway&&this.limiter.consume(e,t).catch(()=>{}),r)}block(e,t){let r;return this.isWhiteListedSomewhere(e)?r=this.resolveWhite():this.isBlackListedSomewhere(e)&&(r=this.resolveBlack()),typeof r>"u"?this.limiter.block(e,t):(this.runActionAnyway&&this.limiter.block(e,t).catch(()=>{}),r)}penalty(e,t){let r;return this.isWhiteListedSomewhere(e)?r=this.resolveWhite():this.isBlackListedSomewhere(e)&&(r=this.resolveBlack()),typeof r>"u"?this.limiter.penalty(e,t):(this.runActionAnyway&&this.limiter.penalty(e,t).catch(()=>{}),r)}reward(e,t){let r;return this.isWhiteListedSomewhere(e)?r=this.resolveWhite():this.isBlackListedSomewhere(e)&&(r=this.resolveBlack()),typeof r>"u"?this.limiter.reward(e,t):(this.runActionAnyway&&this.limiter.reward(e,t).catch(()=>{}),r)}get(e){let t;return this.isWhiteListedSomewhere(e)?t=this.resolveWhite():this.isBlackListedSomewhere(e)&&(t=this.resolveBlack()),typeof t>"u"||this.runActionAnyway?this.limiter.get(e):t}delete(e){return this.limiter.delete(e)}}});var dr=b((wo,ur)=>{var ki=ee();ur.exports=class{constructor(...e){if(e.length<1)throw new Error("RateLimiterUnion: at least one limiter have to be passed");e.forEach(t=>{if(!(t instanceof ki))throw new Error("RateLimiterUnion: all limiters have to be instance of RateLimiterAbstract")}),this._limiters=e}consume(e,t=1){return new Promise((r,s)=>{let n=[];this._limiters.forEach(o=>{n.push(o.consume(e,t).catch(a=>({rejected:!0,rej:a})))}),Promise.all(n).then(o=>{let a={},c=!1;o.forEach(h=>{h.rejected===!0&&(c=!0)});for(let h=0;h<o.length;h++)c&&o[h].rejected===!0?a[this._limiters[h].keyPrefix]=o[h].rej:c||(a[this._limiters[h].keyPrefix]=o[h]);c?s(a):r(a)})})}}});var mr=b((_o,fr)=>{fr.exports=class extends Error{constructor(e,t){super(),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="CustomError",this.message=e,t&&(this.extra=t)}}});var wr=b((xo,br)=>{var pr=mr(),yr=4294967295,Ue="limiter";br.exports=class{constructor(e,t={maxQueueSize:yr}){this._queueLimiters={KEY_DEFAULT:new ue(e,t)},this._limiterFlexible=e,this._maxQueueSize=t.maxQueueSize}getTokensRemaining(e=Ue){return this._queueLimiters[e]?this._queueLimiters[e].getTokensRemaining():Promise.resolve(this._limiterFlexible.points)}removeTokens(e,t=Ue){return this._queueLimiters[t]||(this._queueLimiters[t]=new ue(this._limiterFlexible,{key:t,maxQueueSize:this._maxQueueSize})),this._queueLimiters[t].removeTokens(e)}};var ue=class{constructor(e,t={maxQueueSize:yr,key:Ue}){this._key=t.key,this._waitTimeout=null,this._queue=[],this._limiterFlexible=e,this._maxQueueSize=t.maxQueueSize}getTokensRemaining(){return this._limiterFlexible.get(this._key).then(e=>e!==null?e.remainingPoints:this._limiterFlexible.points)}removeTokens(e){let t=this;return new Promise((r,s)=>{if(e>t._limiterFlexible.points){s(new pr(`Requested tokens ${e} exceeds maximum ${t._limiterFlexible.points} tokens per interval`));return}t._queue.length>0?t._queueRequest.call(t,r,s,e):t._limiterFlexible.consume(t._key,e).then(n=>{r(n.remainingPoints)}).catch(n=>{n instanceof Error?s(n):(t._queueRequest.call(t,r,s,e),t._waitTimeout===null&&(t._waitTimeout=setTimeout(t._processFIFO.bind(t),n.msBeforeNext)))})})}_queueRequest(e,t,r){let s=this;s._queue.length<s._maxQueueSize?s._queue.push({resolve:e,reject:t,tokens:r}):t(new pr(`Number of requests reached it's maximum ${s._maxQueueSize}`))}_processFIFO(){let e=this;if(e._waitTimeout!==null&&(clearTimeout(e._waitTimeout),e._waitTimeout=null),e._queue.length===0)return;let t=e._queue.shift();e._limiterFlexible.consume(e._key,t.tokens).then(r=>{t.resolve(r.remainingPoints),e._processFIFO.call(e)}).catch(r=>{r instanceof Error?(t.reject(r),e._processFIFO.call(e)):(e._queue.unshift(t),e._waitTimeout===null&&(e._waitTimeout=setTimeout(e._processFIFO.bind(e),r.msBeforeNext)))})}}});var _r=b((Ro,gr)=>{var Fe=T();gr.exports=class{constructor(e,t){this._rateLimiter=e,this._burstLimiter=t}_combineRes(e,t){return e?new Fe(e.remainingPoints,Math.min(e.msBeforeNext,t?t.msBeforeNext:0),e.consumedPoints,e.isFirstInDuration):null}consume(e,t=1,r={}){return this._rateLimiter.consume(e,t,r).catch(s=>s instanceof Fe?this._burstLimiter.consume(e,t,r).then(n=>Promise.resolve(this._combineRes(s,n))).catch(n=>n instanceof Fe?Promise.reject(this._combineRes(s,n)):Promise.reject(n)):Promise.reject(s))}get(e){return Promise.all([this._rateLimiter.get(e),this._burstLimiter.get(e)]).then(([t,r])=>this._combineRes(t,r))}get points(){return this._rateLimiter.points}}});var xr=b((Ao,Er)=>{var Di=vt(),Bi=qt(),Oi=Vt(),vi=Wt(),{RateLimiterClusterMaster:Ui,RateLimiterClusterMasterPM2:Fi,RateLimiterCluster:qi}=nr(),zi=ke(),Vi=ar(),$i=lr(),Wi=dr(),Ki=wr(),Gi=_r(),ji=T();Er.exports={RateLimiterRedis:Di,RateLimiterMongo:Bi,RateLimiterMySQL:Oi,RateLimiterPostgres:vi,RateLimiterMemory:zi,RateLimiterMemcache:Vi,RateLimiterClusterMaster:Ui,RateLimiterClusterMasterPM2:Fi,RateLimiterCluster:qi,RLWrapperBlackAndWhite:$i,RateLimiterUnion:Wi,RateLimiterQueue:Ki,BurstyRateLimiter:Gi,RateLimiterRes:ji}});var In={};I(In,{mplex:()=>An});var U=class extends Error{code;props;constructor(e,t,r){super(e),this.code=t,this.name=r?.name??"CodeError",this.props=r??{}}};function _t(i){if(i!=null){if(typeof i[Symbol.iterator]=="function")return i[Symbol.iterator]();if(typeof i[Symbol.asyncIterator]=="function")return i[Symbol.asyncIterator]();if(typeof i.next=="function")return i}throw new Error("argument is not an iterator or iterable")}function Et(i){return i==null?!1:typeof i.then=="function"&&typeof i.catch=="function"&&typeof i.finally=="function"}function he(i,e){let t=_t(i).return?.();Et(t)&&t.catch(r=>{e.error("could not cause iterator to return",r)})}function D(){let i={};return i.promise=new Promise((e,t)=>{i.resolve=e,i.reject=t}),i}var le=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)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}},$=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new le(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 le(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Se=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function W(i={}){return St(t=>{let r=t.shift();if(r==null)return{done:!0};if(r.error!=null)throw r.error;return{done:r.done===!0,value:r.value}},i)}function xt(i={}){return St(t=>{let r,s=[];for(;!t.isEmpty()&&(r=t.shift(),r!=null);){if(r.error!=null)throw r.error;r.done===!1&&s.push(r.value)}return r==null?{done:!0}:{done:r.done===!0,value:s}},i)}function St(i,e){e=e??{};let t=e.onEnd,r=new $,s,n,o,a=D(),c=async()=>{try{return r.isEmpty()?o?{done:!0}:await new Promise((f,g)=>{n=x=>{n=null,r.push(x);try{f(i(r))}catch(_){g(_)}return s}}):i(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=D()})}},h=f=>n!=null?n(f):(r.push(f),s),l=f=>(r=new $,n!=null?n({error:f}):(r.push({error:f}),s)),d=f=>{if(o)return s;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})},y=f=>o?s:(o=!0,f!=null?l(f):h({done:!0})),E=()=>(r=new $,y(),{done:!0}),u=f=>(y(f),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:E,throw:u,push:d,end:y,get readableLength(){return r.size},onEmpty:async f=>{let g=f?.signal;if(g?.throwIfAborted(),r.isEmpty())return;let x,_;g!=null&&(x=new Promise((A,L)=>{_=()=>{L(new Se)},g.addEventListener("abort",_)}));try{await Promise.race([a.promise,x])}finally{_!=null&&g!=null&&g?.removeEventListener("abort",_)}}},t==null)return s;let m=s;return s={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(f){return m.throw(f),t!=null&&(t(f),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(f){return m.end(f),t!=null&&(t(f),t=void 0),s},get readableLength(){return m.readableLength},onEmpty:f=>m.onEmpty(f)},s}function hi(i){return i[Symbol.asyncIterator]!=null}function li(...i){let e=[];for(let t of i)hi(t)||e.push(t);return e.length===i.length?function*(){for(let t of e)yield*t}():async function*(){let t=W({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(i.map(async r=>{for await(let s of r)t.push(s)})),t.end()}catch(r){t.end(r)}}),yield*t}()}var Rt=li;function At(i,...e){if(i==null)throw new Error("Empty pipeline");if(Re(i)){let r=i;i=()=>r.source}else if(Tt(i)||It(i)){let r=i;i=()=>r}let t=[i,...e];if(t.length>1&&Re(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let r=1;r<t.length-1;r++)Re(t[r])&&(t[r]=di(t[r]));return ui(...t)}var ui=(...i)=>{let e;for(;i.length>0;)e=i.shift()(e);return e},It=i=>i?.[Symbol.asyncIterator]!=null,Tt=i=>i?.[Symbol.iterator]!=null,Re=i=>i==null?!1:i.sink!=null&&i.source!=null,di=i=>e=>{let t=i.sink(e);if(t?.then!=null){let r=W({objectMode:!0});t.then(()=>{r.end()},o=>{r.end(o)});let s,n=i.source;if(It(n))s=async function*(){yield*n,r.end()};else if(Tt(n))s=function*(){yield*n,r.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return Rt(r,s())}return i.source};var ti=ai(xr(),1);function F(i){return globalThis.Buffer!=null?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):i}function B(i=0){return globalThis.Buffer?.alloc!=null?F(globalThis.Buffer.alloc(i)):new Uint8Array(i)}function M(i=0){return globalThis.Buffer?.allocUnsafe!=null?F(globalThis.Buffer.allocUnsafe(i)):new Uint8Array(i)}function de(i,e){e==null&&(e=i.reduce((s,n)=>s+n.length,0));let t=M(e),r=0;for(let s of i)t.set(s,r),r+=s.length;return F(t)}function qe(i,e){if(i===e)return!0;if(i.byteLength!==e.byteLength)return!1;for(let t=0;t<i.byteLength;t++)if(i[t]!==e[t])return!1;return!0}var Ke={};I(Ke,{base10:()=>Zi});function Hi(i,e){if(i.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var s=0;s<i.length;s++){var n=i.charAt(s),o=n.charCodeAt(0);if(t[o]!==255)throw new TypeError(n+" is ambiguous");t[o]=s}var a=i.length,c=i.charAt(0),h=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function d(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 m=0,f=0,g=0,x=u.length;g!==x&&u[g]===0;)g++,m++;for(var _=(x-g)*l+1>>>0,A=new Uint8Array(_);g!==x;){for(var L=u[g],v=0,C=_-1;(L!==0||v<f)&&C!==-1;C--,v++)L+=256*A[C]>>>0,A[C]=L%a>>>0,L=L/a>>>0;if(L!==0)throw new Error("Non-zero carry");f=v,g++}for(var k=_-f;k!==_&&A[k]===0;)k++;for(var ae=c.repeat(m);k<_;++k)ae+=i.charAt(A[k]);return ae}function y(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;var m=0;if(u[m]!==" "){for(var f=0,g=0;u[m]===c;)f++,m++;for(var x=(u.length-m)*h+1>>>0,_=new Uint8Array(x);u[m];){var A=t[u.charCodeAt(m)];if(A===255)return;for(var L=0,v=x-1;(A!==0||L<g)&&v!==-1;v--,L++)A+=a*_[v]>>>0,_[v]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");g=L,m++}if(u[m]!==" "){for(var C=x-g;C!==x&&_[C]===0;)C++;for(var k=new Uint8Array(f+(x-C)),ae=f;C!==x;)k[ae++]=_[C++];return k}}}function E(u){var m=y(u);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:y,decode:E}}var Yi=Hi,Qi=Yi,Sr=Qi;var Bo=new Uint8Array(0);var Rr=(i,e)=>{if(i===e)return!0;if(i.byteLength!==e.byteLength)return!1;for(let t=0;t<i.byteLength;t++)if(i[t]!==e[t])return!1;return!0},O=i=>{if(i instanceof Uint8Array&&i.constructor.name==="Uint8Array")return i;if(i instanceof ArrayBuffer)return new Uint8Array(i);if(ArrayBuffer.isView(i))return new Uint8Array(i.buffer,i.byteOffset,i.byteLength);throw new Error("Unknown type, must be binary type")};var Ar=i=>new TextEncoder().encode(i),Ir=i=>new TextDecoder().decode(i);var ze=class{constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ve=class{constructor(e,t,r){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=r}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 Lr(this,e)}},$e=class{constructor(e){this.decoders=e}or(e){return Lr(this,e)}decode(e){let t=e[0],r=this.decoders[t];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},Lr=(i,e)=>new $e({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}}),We=class{constructor(e,t,r,s){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=s,this.encoder=new ze(e,t,r),this.decoder=new Ve(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},Y=({name:i,prefix:e,encode:t,decode:r})=>new We(i,e,t,r),q=({prefix:i,name:e,alphabet:t})=>{let{encode:r,decode:s}=Sr(t,e);return Y({prefix:i,name:e,encode:r,decode:n=>O(s(n))})},Xi=(i,e,t,r)=>{let s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=i.length;for(;i[n-1]==="=";)--n;let o=new Uint8Array(n*t/8|0),a=0,c=0,h=0;for(let l=0;l<n;++l){let d=s[i[l]];if(d===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<t|d,a+=t,a>=8&&(a-=8,o[h++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Ji=(i,e,t)=>{let r=e[e.length-1]==="=",s=(1<<t)-1,n="",o=0,a=0;for(let c=0;c<i.length;++c)for(a=a<<8|i[c],o+=8;o>t;)o-=t,n+=e[s&a>>o];if(o&&(n+=e[s&a<<t-o]),r)for(;n.length*t&7;)n+="=";return n},w=({name:i,prefix:e,bitsPerChar:t,alphabet:r})=>Y({prefix:e,name:i,encode(s){return Ji(s,r,t)},decode(s){return Xi(s,r,t,i)}});var Zi=q({prefix:"9",name:"base10",alphabet:"0123456789"});var Ge={};I(Ge,{base16:()=>es,base16upper:()=>ts});var es=w({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ts=w({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var je={};I(je,{base2:()=>rs});var rs=w({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var He={};I(He,{base256emoji:()=>as});var Nr=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}"),is=Nr.reduce((i,e,t)=>(i[t]=e,i),[]),ss=Nr.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function ns(i){return i.reduce((e,t)=>(e+=is[t],e),"")}function os(i){let e=[];for(let t of i){let r=ss[t.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(r)}return new Uint8Array(e)}var as=Y({prefix:"\u{1F680}",name:"base256emoji",encode:ns,decode:os});var Ye={};I(Ye,{base32:()=>Q,base32hex:()=>us,base32hexpad:()=>fs,base32hexpadupper:()=>ms,base32hexupper:()=>ds,base32pad:()=>hs,base32padupper:()=>ls,base32upper:()=>cs,base32z:()=>ps});var Q=w({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),cs=w({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),hs=w({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ls=w({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),us=w({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ds=w({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),fs=w({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ms=w({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ps=w({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Qe={};I(Qe,{base36:()=>ys,base36upper:()=>bs});var ys=q({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),bs=q({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Xe={};I(Xe,{base58btc:()=>P,base58flickr:()=>ws});var P=q({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ws=q({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Je={};I(Je,{base64:()=>gs,base64pad:()=>_s,base64url:()=>Es,base64urlpad:()=>xs});var gs=w({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),_s=w({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Es=w({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),xs=w({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ze={};I(Ze,{base8:()=>Ss});var Ss=w({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var et={};I(et,{identity:()=>Rs});var Rs=Y({prefix:"\0",name:"identity",encode:i=>Ir(i),decode:i=>Ar(i)});var Qo=new TextEncoder,Xo=new TextDecoder;var rt={};I(rt,{identity:()=>js});var Ts=Pr,Cr=128,Ls=127,Ns=~Ls,Cs=Math.pow(2,31);function Pr(i,e,t){e=e||[],t=t||0;for(var r=t;i>=Cs;)e[t++]=i&255|Cr,i/=128;for(;i&Ns;)e[t++]=i&255|Cr,i>>>=7;return e[t]=i|0,Pr.bytes=t-r+1,e}var Ms=tt,Ps=128,Mr=127;function tt(i,r){var t=0,r=r||0,s=0,n=r,o,a=i.length;do{if(n>=a)throw tt.bytes=0,new RangeError("Could not decode varint");o=i[n++],t+=s<28?(o&Mr)<<s:(o&Mr)*Math.pow(2,s),s+=7}while(o>=Ps);return tt.bytes=n-r,t}var ks=Math.pow(2,7),Ds=Math.pow(2,14),Bs=Math.pow(2,21),Os=Math.pow(2,28),vs=Math.pow(2,35),Us=Math.pow(2,42),Fs=Math.pow(2,49),qs=Math.pow(2,56),zs=Math.pow(2,63),Vs=function(i){return i<ks?1:i<Ds?2:i<Bs?3:i<Os?4:i<vs?5:i<Us?6:i<Fs?7:i<qs?8:i<zs?9:10},$s={encode:Ts,decode:Ms,encodingLength:Vs},Ws=$s,te=Ws;var re=(i,e=0)=>[te.decode(i,e),te.decode.bytes],X=(i,e,t=0)=>(te.encode(i,e,t),e),J=i=>te.encodingLength(i);var z=(i,e)=>{let t=e.byteLength,r=J(i),s=r+J(t),n=new Uint8Array(s+t);return X(i,n,0),X(t,n,r),n.set(e,s),new Z(i,t,e,n)},kr=i=>{let e=O(i),[t,r]=re(e),[s,n]=re(e.subarray(r)),o=e.subarray(r+n);if(o.byteLength!==s)throw new Error("Incorrect length");return new Z(t,s,o,e)},Dr=(i,e)=>{if(i===e)return!0;{let t=e;return i.code===t.code&&i.size===t.size&&t.bytes instanceof Uint8Array&&Rr(i.bytes,t.bytes)}},Z=class{constructor(e,t,r,s){this.code=e,this.size=t,this.digest=r,this.bytes=s}};var Br=0,Ks="identity",Or=O,Gs=i=>z(Br,Or(i)),js={code:Br,name:Ks,encode:Or,digest:Gs};var nt={};I(nt,{sha256:()=>Hs,sha512:()=>Ys});var st=({name:i,code:e,encode:t})=>new it(i,e,t),it=class{constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){let t=this.encode(e);return t instanceof Uint8Array?z(this.code,t):t.then(r=>z(this.code,r))}else throw Error("Unknown type, must be binary type")}};var Ur=i=>async e=>new Uint8Array(await crypto.subtle.digest(i,e)),Hs=st({name:"sha2-256",code:18,encode:Ur("SHA-256")}),Ys=st({name:"sha2-512",code:19,encode:Ur("SHA-512")});var Fr=(i,e)=>{let{bytes:t,version:r}=i;switch(r){case 0:return Xs(t,ot(i),e||P.encoder);default:return Js(t,ot(i),e||Q.encoder)}};var qr=new WeakMap,ot=i=>{let e=qr.get(i);if(e==null){let t=new Map;return qr.set(i,t),t}return e},me=class i{constructor(e,t,r,s){this.code=t,this.version=e,this.multihash=r,this.bytes=s,this["/"]=s}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==se)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Zs)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return i.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,r=z(e,t);return i.createV1(this.code,r)}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 i.equals(this,e)}static equals(e,t){let r=t;return r&&e.code===r.code&&e.version===r.version&&Dr(e.multihash,r.multihash)}toString(e){return Fr(this,e)}toJSON(){return{"/":Fr(this)}}link(){return this}get[Symbol.toStringTag](){return"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 i)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:r,code:s,multihash:n,bytes:o}=t;return new i(r,s,n,o||zr(r,s,n.bytes))}else if(t[en]===!0){let{version:r,multihash:s,code:n}=t,o=kr(s);return i.create(r,n,o)}else return null}static create(e,t,r){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==se)throw new Error(`Version 0 CID must use dag-pb (code: ${se}) block encoding`);return new i(e,t,r,r.bytes)}case 1:{let s=zr(e,t,r.bytes);return new i(e,t,r,s)}default:throw new Error("Invalid version")}}static createV0(e){return i.create(0,se,e)}static createV1(e,t){return i.create(1,e,t)}static decode(e){let[t,r]=i.decodeFirst(e);if(r.length)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=i.inspectBytes(e),r=t.size-t.multihashSize,s=O(e.subarray(r,r+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let n=s.subarray(t.multihashSize-t.digestSize),o=new Z(t.multihashCode,t.digestSize,n,s);return[t.version===0?i.createV0(o):i.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,r=()=>{let[d,y]=re(e.subarray(t));return t+=y,d},s=r(),n=se;if(s===18?(s=0,t=0):n=r(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=t,a=r(),c=r(),h=t+c,l=h-o;return{version:s,codec:n,multihashCode:a,digestSize:c,multihashSize:l,size:h}}static parse(e,t){let[r,s]=Qs(e,t),n=i.decode(s);if(n.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return ot(n).set(r,e),n}},Qs=(i,e)=>{switch(i[0]){case"Q":{let t=e||P;return[P.prefix,t.decode(`${P.prefix}${i}`)]}case P.prefix:{let t=e||P;return[P.prefix,t.decode(i)]}case Q.prefix:{let t=e||Q;return[Q.prefix,t.decode(i)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[i[0],e.decode(i)]}}},Xs=(i,e,t)=>{let{prefix:r}=t;if(r!==P.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(r);if(s==null){let n=t.encode(i).slice(1);return e.set(r,n),n}else return s},Js=(i,e,t)=>{let{prefix:r}=t,s=e.get(r);if(s==null){let n=t.encode(i);return e.set(r,n),n}else return s},se=112,Zs=18,zr=(i,e,t)=>{let r=J(i),s=r+J(e),n=new Uint8Array(s+t.byteLength);return X(i,n,0),X(e,n,r),n.set(t,s),n},en=Symbol.for("@ipld/js-cid/CID");var at={...et,...je,...Ze,...Ke,...Ge,...Ye,...Qe,...Xe,...Je,...He},fa={...nt,...rt};function $r(i,e,t,r){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:r}}}var Vr=$r("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),ct=$r("ascii","a",i=>{let e="a";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return e},i=>{i=i.substring(1);let e=M(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),tn={utf8:Vr,"utf-8":Vr,hex:at.base16,latin1:ct,ascii:ct,binary:ct,...at},pe=tn;function ht(i,e="utf8"){let t=pe[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?F(globalThis.Buffer.from(i,"utf-8")):t.decoder.decode(`${t.prefix}${i}`)}function ne(i,e="utf8"){let t=pe[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(i.buffer,i.byteOffset,i.byteLength).toString("utf8"):t.encoder.encode(i).substring(1)}var Kr=Symbol.for("@achingbrain/uint8arraylist");function Wr(i,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let r of i){let s=t+r.byteLength;if(e<s)return{buf:r,index:e-t};t=s}throw new RangeError("index is out of bounds")}function ye(i){return!!i?.[Kr]}var S=class i{constructor(...e){Object.defineProperty(this,Kr,{value:!0}),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 r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else if(ye(r))t+=r.byteLength,this.bufs.push(...r.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else if(ye(r))t+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=Wr(this.bufs,e);return t.buf[t.index]}set(e,t){let r=Wr(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(t+r,e[r]);else if(ye(e))for(let r=0;r<e.length;r++)this.set(t+r,e.get(r));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:r,length:s}=this._subList(e,t);return de(r,s)}subarray(e,t){let{bufs:r,length:s}=this._subList(e,t);return r.length===1?r[0]:de(r,s)}sublist(e,t){let{bufs:r,length:s}=this._subList(e,t),n=new i;return n.length=s,n.bufs=r,n}_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 r=[],s=0;for(let n=0;n<this.bufs.length;n++){let o=this.bufs[n],a=s,c=a+o.byteLength;if(s=c,e>=c)continue;let h=e>=a&&e<c,l=t>a&&t<=c;if(h&&l){if(e===a&&t===c){r.push(o);break}let d=e-a;r.push(o.subarray(d,d+(t-e)));break}if(h){if(e===0){r.push(o);continue}r.push(o.subarray(e-a));continue}if(l){if(t===c){r.push(o);break}r.push(o.subarray(0,t-a));break}r.push(o)}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!ye(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let r=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=r.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let n=256,o=new Int32Array(n);for(let d=0;d<n;d++)o[d]=-1;for(let d=0;d<s;d++)o[r[d]]=d;let a=o,c=this.byteLength-r.byteLength,h=r.byteLength-1,l;for(let d=t;d<=c;d+=l){l=0;for(let y=h;y>=0;y--){let E=this.get(d+y);if(r[y]!==E){l=Math.max(1,y-a[E]);break}}if(l===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 r=M(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){let s=B(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,r),this.write(s,e)}getInt32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){let s=B(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,r),this.write(s,e)}getBigInt64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){let s=B(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,r),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let r=M(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){let s=B(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,r),this.write(s,e)}getUint32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){let s=B(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,r),this.write(s,e)}getBigUint64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){let s=B(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,r),this.write(s,e)}getFloat32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){let s=B(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,r),this.write(s,e)}getFloat64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){let s=B(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,r),this.write(s,e)}equals(e){if(e==null||!(e instanceof i)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!qe(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let r=new i;return r.bufs=e,t==null&&(t=e.reduce((s,n)=>s+n.byteLength,0)),r.length=t,r}};var p;(function(i){i[i.NEW_STREAM=0]="NEW_STREAM",i[i.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",i[i.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",i[i.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",i[i.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",i[i.RESET_RECEIVER=5]="RESET_RECEIVER",i[i.RESET_INITIATOR=6]="RESET_INITIATOR"})(p||(p={}));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"}),lt=Object.freeze({NEW_STREAM:p.NEW_STREAM,MESSAGE:p.MESSAGE_INITIATOR,CLOSE:p.CLOSE_INITIATOR,RESET:p.RESET_INITIATOR}),Gr=Object.freeze({MESSAGE:p.MESSAGE_RECEIVER,CLOSE:p.CLOSE_RECEIVER,RESET:p.RESET_RECEIVER});var ut=1<<20,rn=4<<20,be=class{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=ut,t=rn){this._buffer=new S,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 Object.assign(new Error("unprocessed message queue size too large!"),{code:"ERR_MSG_QUEUE_TOO_BIG"});let t=[];for(;this._buffer.length!==0;){if(this._headerInfo==null)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(h){if(h.code==="ERR_MSG_TOO_BIG")throw h;break}let{id:r,type:s,length:n,offset:o}=this._headerInfo;if(this._buffer.length-o<n)break;let c={id:r,type:s};(s===p.NEW_STREAM||s===p.MESSAGE_INITIATOR||s===p.MESSAGE_RECEIVER)&&(c.data=this._buffer.sublist(o,o+n)),t.push(c),this._buffer.consume(o+n),this._headerInfo=null}return t}_decodeHeader(e){let{value:t,offset:r}=Hr(e),{value:s,offset:n}=Hr(e,r),o=t&7;if(oe[o]==null)throw new Error(`Invalid type received: ${o}`);if(s>this._maxMessageSize)throw Object.assign(new Error("message size too large!"),{code:"ERR_MSG_TOO_BIG"});return{id:t>>3,type:o,offset:r+n,length:s}}},sn=128,jr=127;function Hr(i,e=0){let t=0,r=0,s=e,n,o=i.length;do{if(s>=o||r>49)throw e=0,new RangeError("Could not decode varint");n=i.get(s++),t+=r<28?(n&jr)<<r:(n&jr)*Math.pow(2,r),r+=7}while(n>=sn);return e=s-e,{value:t,offset:e}}function nn(i){return i[Symbol.asyncIterator]!=null}var we=1024*1024,Yr=(i,e)=>{e.append(i)};function on(i,e){return nn(i)?async function*(){let t=new S,r=!1,s=D(),n=Number(e?.size??we);if((isNaN(n)||n===0||n<0)&&(n=we),n!==Math.round(n))throw new Error("Batch size must be an integer");let o=e?.yieldAfter??0,a=e?.serialize??Yr;for(Promise.resolve().then(async()=>{try{let c;for await(let h of i){if(a(h,t),t.byteLength>=n){clearTimeout(c),s.resolve();continue}c=setTimeout(()=>{s.resolve()},o)}clearTimeout(c),s.resolve()}catch(c){s.reject(c)}finally{r=!0}});!r;)if(await s.promise,s=D(),t.byteLength>0){let c=t;t=new S,yield c.subarray()}}():function*(){let t=new S,r=Number(e?.size??we);if((isNaN(r)||r===0||r<0)&&(r=we),r!==Math.round(r))throw new Error("Batch size must be an integer");let s=e?.serialize??Yr;for(let n of i)s(n,t),t.byteLength>=r&&(yield t.subarray(0,r),t.consume(r));t.byteLength>0&&(yield t.subarray())}()}var Qr=on;var an=Math.pow(2,7),cn=Math.pow(2,14),hn=Math.pow(2,21),ln=Math.pow(2,28),un=Math.pow(2,35),dn=Math.pow(2,42),fn=Math.pow(2,49),R=128;function V(i){if(i<an)return 1;if(i<cn)return 2;if(i<hn)return 3;if(i<ln)return 4;if(i<un)return 5;if(i<dn)return 6;if(i<fn)return 7;if(Number.MAX_SAFE_INTEGER!=null&&i>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function mn(i,e,t=0){switch(V(i)){case 8:e[t++]=i&255|R,i/=128;case 7:e[t++]=i&255|R,i/=128;case 6:e[t++]=i&255|R,i/=128;case 5:e[t++]=i&255|R,i/=128;case 4:e[t++]=i&255|R,i>>>=7;case 3:e[t++]=i&255|R,i>>>=7;case 2:e[t++]=i&255|R,i>>>=7;case 1:{e[t++]=i&255,i>>>=7;break}default:throw new Error("unreachable")}return e}function pn(i,e,t=0){switch(V(i)){case 8:e.set(t++,i&255|R),i/=128;case 7:e.set(t++,i&255|R),i/=128;case 6:e.set(t++,i&255|R),i/=128;case 5:e.set(t++,i&255|R),i/=128;case 4:e.set(t++,i&255|R),i>>>=7;case 3:e.set(t++,i&255|R),i>>>=7;case 2:e.set(t++,i&255|R),i>>>=7;case 1:{e.set(t++,i&255),i>>>=7;break}default:throw new Error("unreachable")}return e}function ge(i,e,t=0){return e==null&&(e=M(V(i))),e instanceof Uint8Array?mn(i,e,t):pn(i,e,t)}function dt(i){return new Uint8Array(i)}var ft=10*1024,mt=class{_pool;_poolOffset;constructor(){this._pool=dt(ft),this._poolOffset=0}write(e,t){let r=this._pool,s=this._poolOffset;ge(e.id<<3|e.type,r,s),s+=V(e.id<<3|e.type),(e.type===p.NEW_STREAM||e.type===p.MESSAGE_INITIATOR||e.type===p.MESSAGE_RECEIVER)&&e.data!=null?(ge(e.data.length,r,s),s+=V(e.data.length)):(ge(0,r,s),s+=V(0));let n=r.subarray(this._poolOffset,s);ft-s<100?(this._pool=dt(ft),this._poolOffset=0):this._poolOffset=s,t.append(n),(e.type===p.NEW_STREAM||e.type===p.MESSAGE_INITIATOR||e.type===p.MESSAGE_RECEIVER)&&e.data!=null&&t.append(e.data)}},Xr=new mt;async function*Jr(i,e=0){if(e==null||e===0){for await(let t of i){let r=new S;for(let s of t)Xr.write(s,r);yield r.subarray()}return}yield*Qr(i,{size:e,serialize:(t,r)=>{for(let s of t)Xr.write(s,r)}})}var _e=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}};async function pt(i,e,t){if(e==null)return i;if(e.aborted)return Promise.reject(new _e(t?.errorMessage,t?.errorCode));let r,s=new _e(t?.errorMessage,t?.errorCode);try{return await Promise.race([i,new Promise((n,o)=>{r=()=>{o(s)},e.addEventListener("abort",r)})])}finally{r!=null&&e.removeEventListener("abort",r)}}var bn="ERR_STREAM_RESET",wn="ERR_SINK_INVALID_STATE",gn=5e3;function yt(i){return i==null?!1:typeof i.then=="function"&&typeof i.catch=="function"&&typeof i.finally=="function"}var Ee=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;constructor(e){this.sinkController=new AbortController,this.sinkEnd=D(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??gn,this.onEnd=e.onEnd,this.onCloseRead=e?.onCloseRead,this.onCloseWrite=e?.onCloseWrite,this.onReset=e?.onReset,this.onAbort=e?.onAbort,this.source=this.streamSource=W({onEnd:t=>{t!=null?this.log.trace("source ended with error",t):this.log.trace("source ended"),this.onSourceEnd(t)}}),this.sink=this.sink.bind(this)}async sink(e){if(this.writeStatus!=="ready")throw new U(`writable end state is "${this.writeStatus}" not "ready"`,wn);try{this.writeStatus="writing";let t={signal:this.sinkController.signal};if(this.direction==="outbound"){let s=this.sendNewStream(t);yt(s)&&await s}let r=()=>{he(e,this.log)};try{this.sinkController.signal.addEventListener("abort",r),this.log.trace("sink reading from source");for await(let s of e){s=s instanceof Uint8Array?new S(s):s;let n=this.sendData(s,t);yt(n)&&await n}}finally{this.sinkController.signal.removeEventListener("abort",r)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(t){throw this.log.trace("sink ended with error, calling abort with error",t),this.abort(t),t}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr)):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr)):this.log.trace("sink ended, waiting for source to end"))}async close(e){this.log.trace("closing gracefully"),this.status="closing",await Promise.all([this.closeRead(e),this.closeWrite(e)]),this.status="closed",this.log.trace("closed gracefully")}async closeRead(e={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let t=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),t==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await pt(this.sink([]),e.signal)),this.writeStatus==="writing"&&await new Promise((t,r)=>{queueMicrotask(()=>{this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),pt(this.sinkEnd.promise,e.signal).then(t,r)})}),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",e),this.log("try to send reset to remote");let t=this.sendReset();yt(t)&&t.catch(r=>{this.log.error("error sending reset message",r)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let e=new U("stream reset",bn);this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}};var bt=class extends Ee{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types=e.direction==="outbound"?lt:Gr,this.send=e.send,this.name=e.name,this.streamId=e.streamId,this.maxDataSize=e.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:lt.NEW_STREAM,data:new S(ht(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){let t=Math.min(e.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:e.sublist(0,t)}),e.consume(t)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}};function Zr(i){let{id:e,name:t,send:r,onEnd:s,type:n="initiator",maxMsgSize:o=ut}=i;return new bt({id:n==="initiator"?`i${e}`:`r${e}`,streamId:e,name:`${t??e}`,direction:n==="initiator"?"outbound":"inbound",maxDataSize:o,onEnd:s,send:r,log:i.logger.forComponent(`libp2p:mplex:stream:${n}:${e}`)})}var _n=1024,En=1024,xn=1024*1024*4,Sn=5,Rn=500;function ei(i){let e={...i,type:`${oe[i.type]} (${i.type})`};return i.type===p.NEW_STREAM&&(e.data=ne(i.data instanceof Uint8Array?i.data:i.data.subarray())),(i.type===p.MESSAGE_INITIATOR||i.type===p.MESSAGE_RECEIVER)&&(e.data=ne(i.data instanceof Uint8Array?i.data:i.data.subarray(),"base16")),e}var xe=class{protocol="/mplex/6.7.0";sink;source;log;_streamId;_streams;_init;_source;closeController;rateLimiter;closeTimeout;logger;constructor(e,t){t=t??{},this.log=e.logger.forComponent("libp2p:mplex"),this.logger=e.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=t,this.closeTimeout=t.closeTimeout??Rn,this.sink=this._createSink(),this._source=xt({objectMode:!0,onEnd:()=>{for(let r of this._streams.initiators.values())r.destroy();for(let r of this._streams.receivers.values())r.destroy()}}),this.source=At(this._source,r=>Jr(r,this._init.minSendBytes)),this.closeController=new AbortController,this.rateLimiter=new ti.RateLimiterMemory({points:t.disconnectThreshold??Sn,duration:1})}get streams(){let e=[];for(let t of this._streams.initiators.values())e.push(t);for(let t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new Error("Muxer already closed");let t=this._streamId++;e=e==null?t.toString():e.toString();let r=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:r})}async close(e){if(this.closeController.signal.aborted)return;let t=e?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map(async r=>r.close({signal:t}))),this._source.end(),await this._source.onEmpty({signal:t}),this.closeController.abort()}catch(r){this.abort(r)}}abort(e){this.closeController.signal.aborted||(this.streams.forEach(t=>{t.abort(e)}),this.closeController.abort(e))}_newReceiverStream(e){let{id:t,name:r}=e,s=this._streams.receivers;return this._newStream({id:t,name:r,type:"receiver",registry:s})}_newStream(e){let{id:t,name:r,type:s,registry:n}=e;if(this.log("new %s stream %s",s,t),s==="initiator"&&this._streams.initiators.size===(this._init.maxOutboundStreams??En))throw new U("Too many outbound streams open","ERR_TOO_MANY_OUTBOUND_STREAMS");if(n.has(t))throw new Error(`${s} stream ${t} already exists!`);let c=Zr({id:t,name:r,send:async h=>{this.log.enabled&&this.log.trace("%s stream %s send",s,t,ei(h)),this._source.push(h)},type:s,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",s,t,c.protocol),n.delete(t),this._init.onStreamEnd!=null&&this._init.onStreamEnd(c)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return n.set(t,c),c}_createSink(){return async t=>{let r=()=>{he(t,this.log)};this.closeController.signal.addEventListener("abort",r);try{let s=new be(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(let n of t)for(let o of s.write(n))await this._handleIncoming(o);this._source.end()}catch(s){this.log("error in sink",s),this._source.end(s)}finally{this.closeController.signal.removeEventListener("abort",r)}}}async _handleIncoming(e){let{id:t,type:r}=e;if(this.log.enabled&&this.log.trace("incoming message",ei(e)),e.type===p.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??_n)){this.log("too many inbound streams open"),this._source.push({id:t,type:p.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),this.abort(new Error("Too many open streams"));return}return}let a=this._newReceiverStream({id:t,name:ne(e.data instanceof Uint8Array?e.data:e.data.subarray())});this._init.onIncomingStream!=null&&this._init.onIncomingStream(a);return}let n=((r&1)===1?this._streams.initiators:this._streams.receivers).get(t);if(n==null){this.log("missing stream %s for message type %s",t,oe[r]);try{await 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}let o=this._init.maxStreamBufferSize??xn;try{switch(r){case p.MESSAGE_INITIATOR:case p.MESSAGE_RECEIVER:if(n.sourceReadableLength()>o)throw this._source.push({id:e.id,type:r===p.MESSAGE_INITIATOR?p.RESET_RECEIVER:p.RESET_INITIATOR}),new U("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers","ERR_STREAM_INPUT_BUFFER_FULL");n.sourcePush(e.data);break;case p.CLOSE_INITIATOR:case p.CLOSE_RECEIVER:n.remoteCloseWrite();break;case p.RESET_INITIATOR:case p.RESET_RECEIVER:n.reset();break;default:this.log("unknown message type %s",r)}}catch(a){this.log.error("error while processing message",a),n.abort(a)}}};var wt=class{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}createStreamMuxer(e={}){return new xe(this.components,{...e,...this._init})}};function An(i={}){return e=>new wt(e,i)}return ci(In);})();
|
25
25
|
return Libp2PMplex}));
|
package/dist/src/index.d.ts
CHANGED
@@ -30,6 +30,7 @@
|
|
30
30
|
* pipe([1, 2, 3], stream)
|
31
31
|
* ```
|
32
32
|
*/
|
33
|
+
import { type MplexComponents } from './mplex.js';
|
33
34
|
import type { StreamMuxerFactory } from '@libp2p/interface/stream-muxer';
|
34
35
|
export interface MplexInit {
|
35
36
|
/**
|
@@ -83,5 +84,5 @@ export interface MplexInit {
|
|
83
84
|
*/
|
84
85
|
disconnectThreshold?: number;
|
85
86
|
}
|
86
|
-
export declare function mplex(init?: MplexInit): () => StreamMuxerFactory;
|
87
|
+
export declare function mplex(init?: MplexInit): (components: MplexComponents) => StreamMuxerFactory;
|
87
88
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/src/index.d.ts.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,EAAoB,KAAK,eAAe,EAAE,MAAM,YAAY,CAAA;AACnE,OAAO,KAAK,EAAe,kBAAkB,EAAmB,MAAM,gCAAgC,CAAA;AAEtG,MAAM,WAAW,SAAS;IACxB;;;;;OAKG;IACH,UAAU,CAAC,EAAE,MAAM,CAAA;IAEnB;;;;;;OAMG;IACH,8BAA8B,CAAC,EAAE,MAAM,CAAA;IAEvC;;;;;;;;;OASG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;IAErB;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAE1B;;;OAGG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAE3B;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAA;IAE5B;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAA;CAC7B;AAoBD,wBAAgB,KAAK,CAAE,IAAI,GAAE,SAAc,GAAG,CAAC,UAAU,EAAE,eAAe,KAAK,kBAAkB,CAEhG"}
|
package/dist/src/index.js
CHANGED
@@ -34,17 +34,19 @@ import { MplexStreamMuxer } from './mplex.js';
|
|
34
34
|
class Mplex {
|
35
35
|
protocol = '/mplex/6.7.0';
|
36
36
|
_init;
|
37
|
-
|
37
|
+
components;
|
38
|
+
constructor(components, init = {}) {
|
39
|
+
this.components = components;
|
38
40
|
this._init = init;
|
39
41
|
}
|
40
42
|
createStreamMuxer(init = {}) {
|
41
|
-
return new MplexStreamMuxer({
|
43
|
+
return new MplexStreamMuxer(this.components, {
|
42
44
|
...init,
|
43
45
|
...this._init
|
44
46
|
});
|
45
47
|
}
|
46
48
|
}
|
47
49
|
export function mplex(init = {}) {
|
48
|
-
return () => new Mplex(init);
|
50
|
+
return (components) => new Mplex(components, init);
|
49
51
|
}
|
50
52
|
//# sourceMappingURL=index.js.map
|
package/dist/src/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,EAAE,gBAAgB,
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,EAAE,gBAAgB,EAAwB,MAAM,YAAY,CAAA;AA8DnE,MAAM,KAAK;IACF,QAAQ,GAAG,cAAc,CAAA;IACf,KAAK,CAAW;IAChB,UAAU,CAAiB;IAE5C,YAAa,UAA2B,EAAE,OAAkB,EAAE;QAC5D,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAA;IACnB,CAAC;IAED,iBAAiB,CAAE,OAAwB,EAAE;QAC3C,OAAO,IAAI,gBAAgB,CAAC,IAAI,CAAC,UAAU,EAAE;YAC3C,GAAG,IAAI;YACP,GAAG,IAAI,CAAC,KAAK;SACd,CAAC,CAAA;IACJ,CAAC;CACF;AAED,MAAM,UAAU,KAAK,CAAE,OAAkB,EAAE;IACzC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,IAAI,KAAK,CAAC,UAAU,EAAE,IAAI,CAAC,CAAA;AACpD,CAAC"}
|
package/dist/src/mplex.d.ts
CHANGED
@@ -1,11 +1,14 @@
|
|
1
1
|
import { type Message } from './message-types.js';
|
2
2
|
import { type MplexStream } from './stream.js';
|
3
3
|
import type { MplexInit } from './index.js';
|
4
|
-
import type { AbortOptions } from '@libp2p/interface';
|
4
|
+
import type { AbortOptions, ComponentLogger } from '@libp2p/interface';
|
5
5
|
import type { Stream } from '@libp2p/interface/connection';
|
6
6
|
import type { StreamMuxer, StreamMuxerInit } from '@libp2p/interface/stream-muxer';
|
7
7
|
import type { Sink, Source } from 'it-stream-types';
|
8
8
|
import type { Uint8ArrayList } from 'uint8arraylist';
|
9
|
+
export interface MplexComponents {
|
10
|
+
logger: ComponentLogger;
|
11
|
+
}
|
9
12
|
interface MplexStreamMuxerInit extends MplexInit, StreamMuxerInit {
|
10
13
|
/**
|
11
14
|
* The default timeout to use in ms when shutting down the muxer.
|
@@ -16,6 +19,7 @@ export declare class MplexStreamMuxer implements StreamMuxer {
|
|
16
19
|
protocol: string;
|
17
20
|
sink: Sink<Source<Uint8ArrayList | Uint8Array>, Promise<void>>;
|
18
21
|
source: AsyncGenerator<Uint8Array>;
|
22
|
+
private readonly log;
|
19
23
|
private _streamId;
|
20
24
|
private readonly _streams;
|
21
25
|
private readonly _init;
|
@@ -23,7 +27,8 @@ export declare class MplexStreamMuxer implements StreamMuxer {
|
|
23
27
|
private readonly closeController;
|
24
28
|
private readonly rateLimiter;
|
25
29
|
private readonly closeTimeout;
|
26
|
-
|
30
|
+
private readonly logger;
|
31
|
+
constructor(components: MplexComponents, init?: MplexStreamMuxerInit);
|
27
32
|
/**
|
28
33
|
* Returns a Map of streams and their ids
|
29
34
|
*/
|
package/dist/src/mplex.d.ts.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"mplex.d.ts","sourceRoot":"","sources":["../../src/mplex.ts"],"names":[],"mappings":"
|
1
|
+
{"version":3,"file":"mplex.d.ts","sourceRoot":"","sources":["../../src/mplex.ts"],"names":[],"mappings":"AAQA,OAAO,EAAkC,KAAK,OAAO,EAAE,MAAM,oBAAoB,CAAA;AACjF,OAAO,EAAgB,KAAK,WAAW,EAAE,MAAM,aAAa,CAAA;AAC5D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AAC3C,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAU,MAAM,mBAAmB,CAAA;AAC9E,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,8BAA8B,CAAA;AAC1D,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAA;AAClF,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AACnD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AAyBpD,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,eAAe,CAAA;CACxB;AAED,UAAU,oBAAqB,SAAQ,SAAS,EAAE,eAAe;IAC/D;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB;AAED,qBAAa,gBAAiB,YAAW,WAAW;IAC3C,QAAQ,SAAiB;IAEzB,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,cAAc,GAAG,UAAU,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAA;IAC9D,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,CAAA;IAEzC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAQ;IAC5B,OAAO,CAAC,SAAS,CAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAA+E;IACxG,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAsB;IAC5C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAoB;IAC5C,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAiB;IACjD,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAmB;IAC/C,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAQ;IACrC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAiB;gBAE3B,UAAU,EAAE,eAAe,EAAE,IAAI,CAAC,EAAE,oBAAoB;IAyDrE;;OAEG;IACH,IAAI,OAAO,IAAK,MAAM,EAAE,CAWvB;IAED;;;OAGG;IACH,SAAS,CAAE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM;IAUjC;;OAEG;IACG,KAAK,CAAE,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC;IA4BnD,KAAK,CAAE,GAAG,EAAE,KAAK,GAAG,IAAI;IASxB;;OAEG;IACH,kBAAkB,CAAE,OAAO,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,WAAW;IAMvE,UAAU,CAAE,OAAO,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,WAAW,GAAG,UAAU,CAAC;QAAC,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,CAAA;KAAE,GAAG,WAAW;IAmCnI;;;OAGG;IACH,WAAW,IAAK,IAAI,CAAC,MAAM,CAAC,cAAc,GAAG,UAAU,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IA6BlE,eAAe,CAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;CAsGxD"}
|
package/dist/src/mplex.js
CHANGED
@@ -1,6 +1,5 @@
|
|
1
1
|
import { CodeError } from '@libp2p/interface/errors';
|
2
|
-
import {
|
3
|
-
import { abortableSource } from 'abortable-iterator';
|
2
|
+
import { closeSource } from '@libp2p/utils/close-source';
|
4
3
|
import { pipe } from 'it-pipe';
|
5
4
|
import { pushableV } from 'it-pushable';
|
6
5
|
import { RateLimiterMemory } from 'rate-limiter-flexible';
|
@@ -9,7 +8,6 @@ import { Decoder } from './decode.js';
|
|
9
8
|
import { encode } from './encode.js';
|
10
9
|
import { MessageTypes, MessageTypeNames } from './message-types.js';
|
11
10
|
import { createStream } from './stream.js';
|
12
|
-
const log = logger('libp2p:mplex');
|
13
11
|
const MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION = 1024;
|
14
12
|
const MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION = 1024;
|
15
13
|
const MAX_STREAM_BUFFER_SIZE = 1024 * 1024 * 4; // 4MB
|
@@ -32,6 +30,7 @@ export class MplexStreamMuxer {
|
|
32
30
|
protocol = '/mplex/6.7.0';
|
33
31
|
sink;
|
34
32
|
source;
|
33
|
+
log;
|
35
34
|
_streamId;
|
36
35
|
_streams;
|
37
36
|
_init;
|
@@ -39,8 +38,11 @@ export class MplexStreamMuxer {
|
|
39
38
|
closeController;
|
40
39
|
rateLimiter;
|
41
40
|
closeTimeout;
|
42
|
-
|
41
|
+
logger;
|
42
|
+
constructor(components, init) {
|
43
43
|
init = init ?? {};
|
44
|
+
this.log = components.logger.forComponent('libp2p:mplex');
|
45
|
+
this.logger = components.logger;
|
44
46
|
this._streamId = 0;
|
45
47
|
this._streams = {
|
46
48
|
/**
|
@@ -152,7 +154,7 @@ export class MplexStreamMuxer {
|
|
152
154
|
}
|
153
155
|
_newStream(options) {
|
154
156
|
const { id, name, type, registry } = options;
|
155
|
-
log('new %s stream %s', type, id);
|
157
|
+
this.log('new %s stream %s', type, id);
|
156
158
|
if (type === 'initiator' && this._streams.initiators.size === (this._init.maxOutboundStreams ?? MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION)) {
|
157
159
|
throw new CodeError('Too many outbound streams open', 'ERR_TOO_MANY_OUTBOUND_STREAMS');
|
158
160
|
}
|
@@ -160,19 +162,19 @@ export class MplexStreamMuxer {
|
|
160
162
|
throw new Error(`${type} stream ${id} already exists!`);
|
161
163
|
}
|
162
164
|
const send = async (msg) => {
|
163
|
-
if (log.enabled) {
|
164
|
-
log.trace('%s stream %s send', type, id, printMessage(msg));
|
165
|
+
if (this.log.enabled) {
|
166
|
+
this.log.trace('%s stream %s send', type, id, printMessage(msg));
|
165
167
|
}
|
166
168
|
this._source.push(msg);
|
167
169
|
};
|
168
170
|
const onEnd = () => {
|
169
|
-
log('%s stream with id %s and protocol %s ended', type, id, stream.protocol);
|
171
|
+
this.log('%s stream with id %s and protocol %s ended', type, id, stream.protocol);
|
170
172
|
registry.delete(id);
|
171
173
|
if (this._init.onStreamEnd != null) {
|
172
174
|
this._init.onStreamEnd(stream);
|
173
175
|
}
|
174
176
|
};
|
175
|
-
const stream = createStream({ id, name, send, type, onEnd, maxMsgSize: this._init.maxMsgSize });
|
177
|
+
const stream = createStream({ id, name, send, type, onEnd, maxMsgSize: this._init.maxMsgSize, logger: this.logger });
|
176
178
|
registry.set(id, stream);
|
177
179
|
return stream;
|
178
180
|
}
|
@@ -182,10 +184,11 @@ export class MplexStreamMuxer {
|
|
182
184
|
*/
|
183
185
|
_createSink() {
|
184
186
|
const sink = async (source) => {
|
187
|
+
const abortListener = () => {
|
188
|
+
closeSource(source, this.log);
|
189
|
+
};
|
190
|
+
this.closeController.signal.addEventListener('abort', abortListener);
|
185
191
|
try {
|
186
|
-
source = abortableSource(source, this.closeController.signal, {
|
187
|
-
returnOnAbort: true
|
188
|
-
});
|
189
192
|
const decoder = new Decoder(this._init.maxMsgSize, this._init.maxUnprocessedMessageQueueSize);
|
190
193
|
for await (const chunk of source) {
|
191
194
|
for (const msg of decoder.write(chunk)) {
|
@@ -195,21 +198,24 @@ export class MplexStreamMuxer {
|
|
195
198
|
this._source.end();
|
196
199
|
}
|
197
200
|
catch (err) {
|
198
|
-
log('error in sink', err);
|
201
|
+
this.log('error in sink', err);
|
199
202
|
this._source.end(err); // End the source with an error
|
200
203
|
}
|
204
|
+
finally {
|
205
|
+
this.closeController.signal.removeEventListener('abort', abortListener);
|
206
|
+
}
|
201
207
|
};
|
202
208
|
return sink;
|
203
209
|
}
|
204
210
|
async _handleIncoming(message) {
|
205
211
|
const { id, type } = message;
|
206
|
-
if (log.enabled) {
|
207
|
-
log.trace('incoming message', printMessage(message));
|
212
|
+
if (this.log.enabled) {
|
213
|
+
this.log.trace('incoming message', printMessage(message));
|
208
214
|
}
|
209
215
|
// Create a new stream?
|
210
216
|
if (message.type === MessageTypes.NEW_STREAM) {
|
211
217
|
if (this._streams.receivers.size === (this._init.maxInboundStreams ?? MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION)) {
|
212
|
-
log('too many inbound streams open');
|
218
|
+
this.log('too many inbound streams open');
|
213
219
|
// not going to allow this stream, send the reset message manually
|
214
220
|
// instead of setting it up just to tear it down
|
215
221
|
this._source.push({
|
@@ -223,7 +229,7 @@ export class MplexStreamMuxer {
|
|
223
229
|
await this.rateLimiter.consume('new-stream', 1);
|
224
230
|
}
|
225
231
|
catch {
|
226
|
-
log('rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection');
|
232
|
+
this.log('rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection');
|
227
233
|
// since there's no backpressure in mplex, the only thing we can really do to protect ourselves is close the connection
|
228
234
|
this.abort(new Error('Too many open streams'));
|
229
235
|
return;
|
@@ -239,7 +245,7 @@ export class MplexStreamMuxer {
|
|
239
245
|
const list = (type & 1) === 1 ? this._streams.initiators : this._streams.receivers;
|
240
246
|
const stream = list.get(id);
|
241
247
|
if (stream == null) {
|
242
|
-
log('missing stream %s for message type %s', id, MessageTypeNames[type]);
|
248
|
+
this.log('missing stream %s for message type %s', id, MessageTypeNames[type]);
|
243
249
|
// if the remote keeps sending us messages for streams that have been
|
244
250
|
// closed or were never opened they may be attacking us so if they do
|
245
251
|
// this very quickly all we can do is close the connection
|
@@ -247,7 +253,7 @@ export class MplexStreamMuxer {
|
|
247
253
|
await this.rateLimiter.consume('missing-stream', 1);
|
248
254
|
}
|
249
255
|
catch {
|
250
|
-
log('rate limit hit when receiving messages for streams that do not exist - closing remote connection');
|
256
|
+
this.log('rate limit hit when receiving messages for streams that do not exist - closing remote connection');
|
251
257
|
// since there's no backpressure in mplex, the only thing we can really do to protect ourselves is close the connection
|
252
258
|
this.abort(new Error('Too many messages for missing streams'));
|
253
259
|
return;
|
@@ -282,11 +288,11 @@ export class MplexStreamMuxer {
|
|
282
288
|
stream.reset();
|
283
289
|
break;
|
284
290
|
default:
|
285
|
-
log('unknown message type %s', type);
|
291
|
+
this.log('unknown message type %s', type);
|
286
292
|
}
|
287
293
|
}
|
288
294
|
catch (err) {
|
289
|
-
log.error('error while processing message', err);
|
295
|
+
this.log.error('error while processing message', err);
|
290
296
|
stream.abort(err);
|
291
297
|
}
|
292
298
|
}
|
package/dist/src/mplex.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"mplex.js","sourceRoot":"","sources":["../../src/mplex.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAA;AACpD,OAAO,EAAE,
|
1
|
+
{"version":3,"file":"mplex.js","sourceRoot":"","sources":["../../src/mplex.ts"],"names":[],"mappings":"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"}
|
package/dist/src/stream.d.ts
CHANGED
@@ -1,6 +1,7 @@
|
|
1
|
-
import { AbstractStream, type AbstractStreamInit } from '@libp2p/
|
1
|
+
import { AbstractStream, type AbstractStreamInit } from '@libp2p/utils/abstract-stream';
|
2
2
|
import { Uint8ArrayList } from 'uint8arraylist';
|
3
3
|
import type { Message } from './message-types.js';
|
4
|
+
import type { ComponentLogger } from '@libp2p/interface';
|
4
5
|
export interface Options {
|
5
6
|
id: number;
|
6
7
|
send(msg: Message): Promise<void>;
|
@@ -8,6 +9,7 @@ export interface Options {
|
|
8
9
|
onEnd?(err?: Error): void;
|
9
10
|
type?: 'initiator' | 'receiver';
|
10
11
|
maxMsgSize?: number;
|
12
|
+
logger: ComponentLogger;
|
11
13
|
}
|
12
14
|
interface MplexStreamInit extends AbstractStreamInit {
|
13
15
|
streamId: number;
|
package/dist/src/stream.d.ts.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../../src/stream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,KAAK,kBAAkB,EAAE,MAAM,
|
1
|
+
{"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../../src/stream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,KAAK,kBAAkB,EAAE,MAAM,+BAA+B,CAAA;AACvF,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AAI/C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAA;AACjD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAExD,MAAM,WAAW,OAAO;IACtB,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACjC,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,KAAK,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAA;IACzB,IAAI,CAAC,EAAE,WAAW,GAAG,UAAU,CAAA;IAC/B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,MAAM,EAAE,eAAe,CAAA;CACxB;AAED,UAAU,eAAgB,SAAQ,kBAAkB;IAClD,QAAQ,EAAE,MAAM,CAAA;IAChB,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAEjC;;;OAGG;IACH,WAAW,EAAE,MAAM,CAAA;CACpB;AAED,qBAAa,WAAY,SAAQ,cAAc;IAC7C,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAQ;IAC7B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAQ;IACjC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAiC;IACtD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAwB;IAC9C,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAQ;gBAEvB,IAAI,EAAE,eAAe;IAU5B,aAAa,IAAK,OAAO,CAAC,IAAI,CAAC;IAI/B,QAAQ,CAAE,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAe9C,SAAS,IAAK,OAAO,CAAC,IAAI,CAAC;IAI3B,cAAc,IAAK,OAAO,CAAC,IAAI,CAAC;IAIhC,aAAa,IAAK,OAAO,CAAC,IAAI,CAAC;CAGtC;AAED,wBAAgB,YAAY,CAAE,OAAO,EAAE,OAAO,GAAG,WAAW,CAa3D"}
|
package/dist/src/stream.js
CHANGED
@@ -1,5 +1,4 @@
|
|
1
|
-
import { AbstractStream } from '@libp2p/
|
2
|
-
import { logger } from '@libp2p/logger';
|
1
|
+
import { AbstractStream } from '@libp2p/utils/abstract-stream';
|
3
2
|
import { Uint8ArrayList } from 'uint8arraylist';
|
4
3
|
import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';
|
5
4
|
import { MAX_MSG_SIZE } from './decode.js';
|
@@ -53,7 +52,7 @@ export function createStream(options) {
|
|
53
52
|
maxDataSize: maxMsgSize,
|
54
53
|
onEnd,
|
55
54
|
send,
|
56
|
-
log: logger(`libp2p:mplex:stream:${type}:${id}`)
|
55
|
+
log: options.logger.forComponent(`libp2p:mplex:stream:${type}:${id}`)
|
57
56
|
});
|
58
57
|
}
|
59
58
|
//# sourceMappingURL=stream.js.map
|
package/dist/src/stream.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"stream.js","sourceRoot":"","sources":["../../src/stream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAA2B,MAAM,
|
1
|
+
{"version":3,"file":"stream.js","sourceRoot":"","sources":["../../src/stream.ts"],"names":[],"mappings":"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"}
|
package/package.json
CHANGED
@@ -1,9 +1,9 @@
|
|
1
1
|
{
|
2
2
|
"name": "@libp2p/mplex",
|
3
|
-
"version": "9.0.12-
|
3
|
+
"version": "9.0.12-d8f5bc211",
|
4
4
|
"description": "JavaScript implementation of https://github.com/libp2p/mplex",
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
6
|
-
"homepage": "https://github.com/libp2p/js-libp2p/tree/
|
6
|
+
"homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/stream-multiplexer-mplex#readme",
|
7
7
|
"repository": {
|
8
8
|
"type": "git",
|
9
9
|
"url": "git+https://github.com/libp2p/js-libp2p.git"
|
@@ -57,12 +57,11 @@
|
|
57
57
|
"test:electron-main": "aegir test -t electron-main"
|
58
58
|
},
|
59
59
|
"dependencies": {
|
60
|
-
"@libp2p/interface": "0.1.6-
|
61
|
-
"@libp2p/
|
62
|
-
"abortable-iterator": "^5.0.1",
|
60
|
+
"@libp2p/interface": "0.1.6-d8f5bc211",
|
61
|
+
"@libp2p/utils": "4.0.7-d8f5bc211",
|
63
62
|
"benchmark": "^2.1.4",
|
64
63
|
"it-batched-bytes": "^2.0.2",
|
65
|
-
"it-pushable": "^3.2.
|
64
|
+
"it-pushable": "^3.2.1",
|
66
65
|
"it-stream-types": "^2.0.1",
|
67
66
|
"rate-limiter-flexible": "^3.0.0",
|
68
67
|
"uint8-varint": "^2.0.0",
|
@@ -70,17 +69,19 @@
|
|
70
69
|
"uint8arrays": "^4.0.6"
|
71
70
|
},
|
72
71
|
"devDependencies": {
|
73
|
-
"@libp2p/interface-compliance-tests": "4.1.5-
|
72
|
+
"@libp2p/interface-compliance-tests": "4.1.5-d8f5bc211",
|
73
|
+
"@libp2p/logger": "3.1.0-d8f5bc211",
|
74
74
|
"aegir": "^41.0.2",
|
75
75
|
"cborg": "^4.0.3",
|
76
76
|
"delay": "^6.0.0",
|
77
77
|
"iso-random-stream": "^2.0.2",
|
78
|
-
"it-all": "^3.0.
|
79
|
-
"it-drain": "^3.0.
|
78
|
+
"it-all": "^3.0.3",
|
79
|
+
"it-drain": "^3.0.3",
|
80
80
|
"it-foreach": "^2.0.2",
|
81
81
|
"it-map": "^3.0.3",
|
82
|
+
"it-pair": "^2.0.6",
|
82
83
|
"it-pipe": "^3.0.1",
|
83
|
-
"it-to-buffer": "^4.0.
|
84
|
+
"it-to-buffer": "^4.0.3",
|
84
85
|
"p-defer": "^4.0.0",
|
85
86
|
"random-int": "^3.0.0"
|
86
87
|
},
|
package/src/index.ts
CHANGED
@@ -31,7 +31,7 @@
|
|
31
31
|
* ```
|
32
32
|
*/
|
33
33
|
|
34
|
-
import { MplexStreamMuxer } from './mplex.js'
|
34
|
+
import { MplexStreamMuxer, type MplexComponents } from './mplex.js'
|
35
35
|
import type { StreamMuxer, StreamMuxerFactory, StreamMuxerInit } from '@libp2p/interface/stream-muxer'
|
36
36
|
|
37
37
|
export interface MplexInit {
|
@@ -96,19 +96,21 @@ export interface MplexInit {
|
|
96
96
|
class Mplex implements StreamMuxerFactory {
|
97
97
|
public protocol = '/mplex/6.7.0'
|
98
98
|
private readonly _init: MplexInit
|
99
|
+
private readonly components: MplexComponents
|
99
100
|
|
100
|
-
constructor (init: MplexInit = {}) {
|
101
|
+
constructor (components: MplexComponents, init: MplexInit = {}) {
|
102
|
+
this.components = components
|
101
103
|
this._init = init
|
102
104
|
}
|
103
105
|
|
104
106
|
createStreamMuxer (init: StreamMuxerInit = {}): StreamMuxer {
|
105
|
-
return new MplexStreamMuxer({
|
107
|
+
return new MplexStreamMuxer(this.components, {
|
106
108
|
...init,
|
107
109
|
...this._init
|
108
110
|
})
|
109
111
|
}
|
110
112
|
}
|
111
113
|
|
112
|
-
export function mplex (init: MplexInit = {}): () => StreamMuxerFactory {
|
113
|
-
return () => new Mplex(init)
|
114
|
+
export function mplex (init: MplexInit = {}): (components: MplexComponents) => StreamMuxerFactory {
|
115
|
+
return (components) => new Mplex(components, init)
|
114
116
|
}
|
package/src/mplex.ts
CHANGED
@@ -1,6 +1,5 @@
|
|
1
1
|
import { CodeError } from '@libp2p/interface/errors'
|
2
|
-
import {
|
3
|
-
import { abortableSource } from 'abortable-iterator'
|
2
|
+
import { closeSource } from '@libp2p/utils/close-source'
|
4
3
|
import { pipe } from 'it-pipe'
|
5
4
|
import { type PushableV, pushableV } from 'it-pushable'
|
6
5
|
import { RateLimiterMemory } from 'rate-limiter-flexible'
|
@@ -10,14 +9,12 @@ import { encode } from './encode.js'
|
|
10
9
|
import { MessageTypes, MessageTypeNames, type Message } from './message-types.js'
|
11
10
|
import { createStream, type MplexStream } from './stream.js'
|
12
11
|
import type { MplexInit } from './index.js'
|
13
|
-
import type { AbortOptions } from '@libp2p/interface'
|
12
|
+
import type { AbortOptions, ComponentLogger, Logger } from '@libp2p/interface'
|
14
13
|
import type { Stream } from '@libp2p/interface/connection'
|
15
14
|
import type { StreamMuxer, StreamMuxerInit } from '@libp2p/interface/stream-muxer'
|
16
15
|
import type { Sink, Source } from 'it-stream-types'
|
17
16
|
import type { Uint8ArrayList } from 'uint8arraylist'
|
18
17
|
|
19
|
-
const log = logger('libp2p:mplex')
|
20
|
-
|
21
18
|
const MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION = 1024
|
22
19
|
const MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION = 1024
|
23
20
|
const MAX_STREAM_BUFFER_SIZE = 1024 * 1024 * 4 // 4MB
|
@@ -41,6 +38,10 @@ function printMessage (msg: Message): any {
|
|
41
38
|
return output
|
42
39
|
}
|
43
40
|
|
41
|
+
export interface MplexComponents {
|
42
|
+
logger: ComponentLogger
|
43
|
+
}
|
44
|
+
|
44
45
|
interface MplexStreamMuxerInit extends MplexInit, StreamMuxerInit {
|
45
46
|
/**
|
46
47
|
* The default timeout to use in ms when shutting down the muxer.
|
@@ -54,6 +55,7 @@ export class MplexStreamMuxer implements StreamMuxer {
|
|
54
55
|
public sink: Sink<Source<Uint8ArrayList | Uint8Array>, Promise<void>>
|
55
56
|
public source: AsyncGenerator<Uint8Array>
|
56
57
|
|
58
|
+
private readonly log: Logger
|
57
59
|
private _streamId: number
|
58
60
|
private readonly _streams: { initiators: Map<number, MplexStream>, receivers: Map<number, MplexStream> }
|
59
61
|
private readonly _init: MplexStreamMuxerInit
|
@@ -61,10 +63,13 @@ export class MplexStreamMuxer implements StreamMuxer {
|
|
61
63
|
private readonly closeController: AbortController
|
62
64
|
private readonly rateLimiter: RateLimiterMemory
|
63
65
|
private readonly closeTimeout: number
|
66
|
+
private readonly logger: ComponentLogger
|
64
67
|
|
65
|
-
constructor (init?: MplexStreamMuxerInit) {
|
68
|
+
constructor (components: MplexComponents, init?: MplexStreamMuxerInit) {
|
66
69
|
init = init ?? {}
|
67
70
|
|
71
|
+
this.log = components.logger.forComponent('libp2p:mplex')
|
72
|
+
this.logger = components.logger
|
68
73
|
this._streamId = 0
|
69
74
|
this._streams = {
|
70
75
|
/**
|
@@ -199,7 +204,7 @@ export class MplexStreamMuxer implements StreamMuxer {
|
|
199
204
|
_newStream (options: { id: number, name: string, type: 'initiator' | 'receiver', registry: Map<number, MplexStream> }): MplexStream {
|
200
205
|
const { id, name, type, registry } = options
|
201
206
|
|
202
|
-
log('new %s stream %s', type, id)
|
207
|
+
this.log('new %s stream %s', type, id)
|
203
208
|
|
204
209
|
if (type === 'initiator' && this._streams.initiators.size === (this._init.maxOutboundStreams ?? MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION)) {
|
205
210
|
throw new CodeError('Too many outbound streams open', 'ERR_TOO_MANY_OUTBOUND_STREAMS')
|
@@ -210,15 +215,15 @@ export class MplexStreamMuxer implements StreamMuxer {
|
|
210
215
|
}
|
211
216
|
|
212
217
|
const send = async (msg: Message): Promise<void> => {
|
213
|
-
if (log.enabled) {
|
214
|
-
log.trace('%s stream %s send', type, id, printMessage(msg))
|
218
|
+
if (this.log.enabled) {
|
219
|
+
this.log.trace('%s stream %s send', type, id, printMessage(msg))
|
215
220
|
}
|
216
221
|
|
217
222
|
this._source.push(msg)
|
218
223
|
}
|
219
224
|
|
220
225
|
const onEnd = (): void => {
|
221
|
-
log('%s stream with id %s and protocol %s ended', type, id, stream.protocol)
|
226
|
+
this.log('%s stream with id %s and protocol %s ended', type, id, stream.protocol)
|
222
227
|
registry.delete(id)
|
223
228
|
|
224
229
|
if (this._init.onStreamEnd != null) {
|
@@ -226,7 +231,7 @@ export class MplexStreamMuxer implements StreamMuxer {
|
|
226
231
|
}
|
227
232
|
}
|
228
233
|
|
229
|
-
const stream = createStream({ id, name, send, type, onEnd, maxMsgSize: this._init.maxMsgSize })
|
234
|
+
const stream = createStream({ id, name, send, type, onEnd, maxMsgSize: this._init.maxMsgSize, logger: this.logger })
|
230
235
|
registry.set(id, stream)
|
231
236
|
return stream
|
232
237
|
}
|
@@ -237,11 +242,13 @@ export class MplexStreamMuxer implements StreamMuxer {
|
|
237
242
|
*/
|
238
243
|
_createSink (): Sink<Source<Uint8ArrayList | Uint8Array>, Promise<void>> {
|
239
244
|
const sink: Sink<Source<Uint8ArrayList | Uint8Array>, Promise<void>> = async source => {
|
240
|
-
|
241
|
-
|
242
|
-
|
243
|
-
})
|
245
|
+
const abortListener = (): void => {
|
246
|
+
closeSource(source, this.log)
|
247
|
+
}
|
244
248
|
|
249
|
+
this.closeController.signal.addEventListener('abort', abortListener)
|
250
|
+
|
251
|
+
try {
|
245
252
|
const decoder = new Decoder(this._init.maxMsgSize, this._init.maxUnprocessedMessageQueueSize)
|
246
253
|
|
247
254
|
for await (const chunk of source) {
|
@@ -252,8 +259,10 @@ export class MplexStreamMuxer implements StreamMuxer {
|
|
252
259
|
|
253
260
|
this._source.end()
|
254
261
|
} catch (err: any) {
|
255
|
-
log('error in sink', err)
|
262
|
+
this.log('error in sink', err)
|
256
263
|
this._source.end(err) // End the source with an error
|
264
|
+
} finally {
|
265
|
+
this.closeController.signal.removeEventListener('abort', abortListener)
|
257
266
|
}
|
258
267
|
}
|
259
268
|
|
@@ -263,14 +272,14 @@ export class MplexStreamMuxer implements StreamMuxer {
|
|
263
272
|
async _handleIncoming (message: Message): Promise<void> {
|
264
273
|
const { id, type } = message
|
265
274
|
|
266
|
-
if (log.enabled) {
|
267
|
-
log.trace('incoming message', printMessage(message))
|
275
|
+
if (this.log.enabled) {
|
276
|
+
this.log.trace('incoming message', printMessage(message))
|
268
277
|
}
|
269
278
|
|
270
279
|
// Create a new stream?
|
271
280
|
if (message.type === MessageTypes.NEW_STREAM) {
|
272
281
|
if (this._streams.receivers.size === (this._init.maxInboundStreams ?? MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION)) {
|
273
|
-
log('too many inbound streams open')
|
282
|
+
this.log('too many inbound streams open')
|
274
283
|
|
275
284
|
// not going to allow this stream, send the reset message manually
|
276
285
|
// instead of setting it up just to tear it down
|
@@ -285,7 +294,7 @@ export class MplexStreamMuxer implements StreamMuxer {
|
|
285
294
|
try {
|
286
295
|
await this.rateLimiter.consume('new-stream', 1)
|
287
296
|
} catch {
|
288
|
-
log('rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection')
|
297
|
+
this.log('rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection')
|
289
298
|
// since there's no backpressure in mplex, the only thing we can really do to protect ourselves is close the connection
|
290
299
|
this.abort(new Error('Too many open streams'))
|
291
300
|
return
|
@@ -307,7 +316,7 @@ export class MplexStreamMuxer implements StreamMuxer {
|
|
307
316
|
const stream = list.get(id)
|
308
317
|
|
309
318
|
if (stream == null) {
|
310
|
-
log('missing stream %s for message type %s', id, MessageTypeNames[type])
|
319
|
+
this.log('missing stream %s for message type %s', id, MessageTypeNames[type])
|
311
320
|
|
312
321
|
// if the remote keeps sending us messages for streams that have been
|
313
322
|
// closed or were never opened they may be attacking us so if they do
|
@@ -315,7 +324,7 @@ export class MplexStreamMuxer implements StreamMuxer {
|
|
315
324
|
try {
|
316
325
|
await this.rateLimiter.consume('missing-stream', 1)
|
317
326
|
} catch {
|
318
|
-
log('rate limit hit when receiving messages for streams that do not exist - closing remote connection')
|
327
|
+
this.log('rate limit hit when receiving messages for streams that do not exist - closing remote connection')
|
319
328
|
// since there's no backpressure in mplex, the only thing we can really do to protect ourselves is close the connection
|
320
329
|
this.abort(new Error('Too many messages for missing streams'))
|
321
330
|
return
|
@@ -355,10 +364,10 @@ export class MplexStreamMuxer implements StreamMuxer {
|
|
355
364
|
stream.reset()
|
356
365
|
break
|
357
366
|
default:
|
358
|
-
log('unknown message type %s', type)
|
367
|
+
this.log('unknown message type %s', type)
|
359
368
|
}
|
360
369
|
} catch (err: any) {
|
361
|
-
log.error('error while processing message', err)
|
370
|
+
this.log.error('error while processing message', err)
|
362
371
|
stream.abort(err)
|
363
372
|
}
|
364
373
|
}
|
package/src/stream.ts
CHANGED
@@ -1,10 +1,10 @@
|
|
1
|
-
import { AbstractStream, type AbstractStreamInit } from '@libp2p/
|
2
|
-
import { logger } from '@libp2p/logger'
|
1
|
+
import { AbstractStream, type AbstractStreamInit } from '@libp2p/utils/abstract-stream'
|
3
2
|
import { Uint8ArrayList } from 'uint8arraylist'
|
4
3
|
import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
|
5
4
|
import { MAX_MSG_SIZE } from './decode.js'
|
6
5
|
import { InitiatorMessageTypes, ReceiverMessageTypes } from './message-types.js'
|
7
6
|
import type { Message } from './message-types.js'
|
7
|
+
import type { ComponentLogger } from '@libp2p/interface'
|
8
8
|
|
9
9
|
export interface Options {
|
10
10
|
id: number
|
@@ -13,6 +13,7 @@ export interface Options {
|
|
13
13
|
onEnd?(err?: Error): void
|
14
14
|
type?: 'initiator' | 'receiver'
|
15
15
|
maxMsgSize?: number
|
16
|
+
logger: ComponentLogger
|
16
17
|
}
|
17
18
|
|
18
19
|
interface MplexStreamInit extends AbstractStreamInit {
|
@@ -87,6 +88,6 @@ export function createStream (options: Options): MplexStream {
|
|
87
88
|
maxDataSize: maxMsgSize,
|
88
89
|
onEnd,
|
89
90
|
send,
|
90
|
-
log: logger(`libp2p:mplex:stream:${type}:${id}`)
|
91
|
+
log: options.logger.forComponent(`libp2p:mplex:stream:${type}:${id}`)
|
91
92
|
})
|
92
93
|
}
|