@libp2p/mplex 10.0.5-d10506189 → 10.0.6-6d11e8268
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +5 -5
- package/package.json +6 -6
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 Zr=Object.create;var ce=Object.defineProperty;var ei=Object.getOwnPropertyDescriptor;var ti=Object.getOwnPropertyNames;var ri=Object.getPrototypeOf,ii=Object.prototype.hasOwnProperty;var b=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),A=(i,e)=>{for(var t in e)ce(i,t,{get:e[t],enumerable:!0})},wt=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ti(e))!ii.call(i,s)&&s!==t&&ce(i,s,{get:()=>e[s],enumerable:!(r=ei(e,s))||r.enumerable});return i};var si=(i,e,t)=>(t=i!=null?Zr(ri(i)):{},wt(e||!i||!i.__esModule?ce(t,"default",{value:i,enumerable:!0}):t,i)),ni=i=>wt(ce({},"__esModule",{value:!0}),i);var ee=b((Po,It)=>{It.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 Mt=b((Do,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((Bo,Ct)=>{var ui=Mt();Ct.exports=ui});var L=b((vo,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((Fo,Bt)=>{var Le=ee(),fi=Pt(),Dt=L();Bt.exports=class extends Le{constructor(e={}){super(e),this.inMemoryBlockOnConsumed=e.inMemoryBlockOnConsumed,this.inMemoryBlockDuration=e.inMemoryBlockDuration,this.insuranceLimiter=e.insuranceLimiter,this._inMemoryBlockedKeys=new fi}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 Le?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 Le))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((qo,Ot)=>{var di=K(),mi=L(),Te="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} ",Ie=class extends di{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:Te})}_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 mi;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,f){return l?c(l):a(f)};typeof this.client.rlflxIncr=="function"?this.client.rlflxIncr(e,t,n,h):this.client.eval(Te,1,e,t,n,h)}):this.client.eval(Te,{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=Ie});var qt=b((Vo,Ft)=>{var pi=K(),yi=L();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 Ne=class i extends pi{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 yi,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,f)=>{this._collection.findOneAndUpdate(a,c,h).then(y=>{l(y)}).catch(y=>{if(y&&y.code===11e3){let _=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(_,u,h).then(m=>{l(m)}).catch(m=>{m&&m.code===11e3?this._upsert(e,t,r,s).then(d=>l(d)).catch(d=>f(d)):f(m)})}else f(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=Ne});var $t=b(($o,Vt)=>{var bi=K(),gi=L(),Me=class extends bi{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 gi,[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,f,y;n?(f=`INSERT INTO ??.?? VALUES (?, ?, ?)
|
2
|
+
"use strict";var Libp2PMplex=(()=>{var ii=Object.create;var le=Object.defineProperty;var si=Object.getOwnPropertyDescriptor;var ni=Object.getOwnPropertyNames;var oi=Object.getPrototypeOf,ai=Object.prototype.hasOwnProperty;var b=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),A=(i,e)=>{for(var t in e)le(i,t,{get:e[t],enumerable:!0})},xt=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ni(e))!ai.call(i,s)&&s!==t&&le(i,s,{get:()=>e[s],enumerable:!(r=si(e,s))||r.enumerable});return i};var ci=(i,e,t)=>(t=i!=null?ii(oi(i)):{},xt(e||!i||!i.__esModule?le(t,"default",{value:i,enumerable:!0}):t,i)),li=i=>xt(le({},"__esModule",{value:!0}),i);var Z=b((Oo,Nt)=>{Nt.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((Uo,Mt)=>{Mt.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 kt=b((Fo,Pt)=>{var pi=Ct();Pt.exports=pi});var T=b((Vo,Dt)=>{Dt.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 z=b((zo,Ot)=>{var Le=Z(),yi=kt(),Bt=T();Ot.exports=class extends Le{constructor(e={}){super(e),this.inMemoryBlockOnConsumed=e.inMemoryBlockOnConsumed,this.inMemoryBlockDuration=e.inMemoryBlockDuration,this.insuranceLimiter=e.insuranceLimiter,this._inMemoryBlockedKeys=new yi}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(l=>{t(l)})}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 Le?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 Le))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 Bt(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 Bt(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 Ut=b((Wo,vt)=>{var bi=z(),gi=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} ",Ne=class extends bi{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 gi;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 l=function(h,f){return h?c(h):a(f)};typeof this.client.rlflxIncr=="function"?this.client.rlflxIncr(e,t,n,l):this.client.eval(Ie,1,e,t,n,l)}):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)}};vt.exports=Ne});var Vt=b((Ko,qt)=>{var wi=z(),xi=T();function Ft(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 Me=class i extends wi{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=Ft(this.client)}):(this._initCollection(),this._driverVersion=Ft(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 xi,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 l={upsert:!0};return this._driverVersion.major>=4||this._driverVersion.major===3&&this._driverVersion.feature>=7||this._driverVersion.feature>=6&&this._driverVersion.patch>=7?l.returnDocument="after":l.returnOriginal=!1,new Promise((h,f)=>{this._collection.findOneAndUpdate(a,c,l).then(y=>{h(y)}).catch(y=>{if(y&&y.code===11e3){let _=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(_,u,l).then(m=>{h(m)}).catch(m=>{m&&m.code===11e3?this._upsert(e,t,r,s).then(d=>h(d)).catch(d=>f(d)):f(m)})}else f(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)}};qt.exports=Me});var zt=b((Go,$t)=>{var _i=z(),Ei=T(),Ce=class extends _i{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 Ei,[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 l=Date.now(),h=s>0?l+s:null,f,y;n?(f=`INSERT INTO ??.?? VALUES (?, ?, ?)
|
3
3
|
ON DUPLICATE KEY UPDATE
|
4
4
|
points = ?,
|
5
|
-
expire = ?;`,y=[this.dbName,this.tableName,t,r,
|
5
|
+
expire = ?;`,y=[this.dbName,this.tableName,t,r,h,r,h]):(f=`INSERT INTO ??.?? VALUES (?, ?, ?)
|
6
6
|
ON DUPLICATE KEY UPDATE
|
7
7
|
points = IF(expire <= ?, ?, points + (?)),
|
8
|
-
expire = IF(expire <= ?, ?, expire);`,y=[this.dbName,this.tableName,t,r,l,
|
8
|
+
expire = IF(expire <= ?, ?, expire);`,y=[this.dbName,this.tableName,t,r,h,l,r,r,l,h]),e.query(f,y,_=>{if(_)return e.rollback(),a(_);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",d=>{if(d)return e.rollback(),a(d);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"))}};$t.exports=Ce});var Kt=b((jo,Wt)=>{var Si=z(),Ri=T(),Pe=class extends Si{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 Ri,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"))}};zt.exports=Ce});var Kt=b(()=>{});var Gt=b(()=>{});var Ht=b((Yo,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((Xo,Yt)=>{var _i=Ht(),Pe=L();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 Pe(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 _i(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 Pe(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 Pe(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 De=b((Jo,Jt)=>{var Ei=ee(),Si=Qt(),Xt=L(),ke=class extends Ei{constructor(e={}){super(e),this._memoryStorage=new Si}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=ke});var nr=b((Zo,sr)=>{var Zt=Kt(),Ri=Gt(),Ai=ee(),tr=De(),Li=L(),I="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:I,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:I,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!==I||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)})},Ti=function(i){if(!i||i.channel!==I||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]}},Ii=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+=Ri.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},Be=class{constructor(){if(H)return H;this._rateLimiters={},Zt.setMaxListeners(0),Zt.on("message",(e,t)=>{t&&t.channel===I&&t.type==="init"?(typeof this._rateLimiters[t.opts.keyPrefix]>"u"&&(this._rateLimiters[t.opts.keyPrefix]=new tr(t.opts)),e.send({channel:I,type:"init",keyPrefix:t.opts.keyPrefix})):ir.call(this,e,t)}),H=this}},Oe=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===I&&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:I,channel:I,type:"init",keyPrefix:n.opts.keyPrefix},(o,a)=>{o&&console.log(o,a)});else{let o={send:a=>{let c=a;c.topic=I,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}},ve=class extends Ai{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===I&&t.type==="init"&&t.keyPrefix===this.keyPrefix?this._initiated=!0:Ti.call(this,t)}),process.send({channel:I,type:"init",opts:Ii.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:Be,RateLimiterClusterMasterPM2:Oe,RateLimiterCluster:ve}});var ar=b((ea,or)=>{var Ni=K(),Mi=L(),Ue=class extends Ni{constructor(e){super(e),this.client=e.storeClient}_getRateLimiterRes(e,t,r){let s=new Mi;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 f={consumedPoints:t,msBeforeNext:h>0?h*1e3:-1};o(f)})}):this.client.incr(e,t,(l,f)=>{l||f===!1?this.client.add(e,t,h,(y,_)=>{if(y||!_)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,_)=>{if(y)a(y);else{let u=_===!1?0:_,m={consumedPoints:f,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=Ue});var lr=b((ra,hr)=>{var cr=L();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 fr=b((sa,ur)=>{var Ci=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 Ci))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((oa,dr)=>{dr.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 gr=b((ca,br)=>{var pr=mr(),yr=4294967295,Fe="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=Fe){return this._queueLimiters[e]?this._queueLimiters[e].getTokensRemaining():Promise.resolve(this._limiterFlexible.points)}removeTokens(e,t=Fe){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:Fe}){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 xr=b((la,wr)=>{var qe=L();wr.exports=class{constructor(e,t){this._rateLimiter=e,this._burstLimiter=t}_combineRes(e,t){return e?new qe(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 qe?this._burstLimiter.consume(e,t,r).then(n=>Promise.resolve(this._combineRes(s,n))).catch(n=>n instanceof qe?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 Er=b((ua,_r)=>{var Pi=vt(),ki=qt(),Di=$t(),Bi=Wt(),{RateLimiterClusterMaster:Oi,RateLimiterClusterMasterPM2:vi,RateLimiterCluster:Ui}=nr(),Fi=De(),qi=ar(),Vi=lr(),$i=fr(),zi=gr(),Wi=xr(),Ki=L();_r.exports={RateLimiterRedis:Pi,RateLimiterMongo:ki,RateLimiterMySQL:Di,RateLimiterPostgres:Bi,RateLimiterMemory:Fi,RateLimiterMemcache:qi,RateLimiterClusterMaster:Oi,RateLimiterClusterMasterPM2:vi,RateLimiterCluster:Ui,RLWrapperBlackAndWhite:Vi,RateLimiterUnion:$i,RateLimiterQueue:zi,BurstyRateLimiter:Wi,RateLimiterRes:Ki}});var Sn={};A(Sn,{mplex:()=>En});var An=Symbol.for("@libp2p/connection");var Tn=Symbol.for("@libp2p/content-routing");var Mn=Symbol.for("@libp2p/peer-discovery");var Pn=Symbol.for("@libp2p/peer-id");var Dn=Symbol.for("@libp2p/peer-routing");var xt;(function(i){i.Accept="accept",i.Ignore="ignore",i.Reject="reject"})(xt||(xt={}));var Un=Symbol.for("@libp2p/transport");var _t;(function(i){i[i.FATAL_ALL=0]="FATAL_ALL",i[i.NO_FATAL=1]="NO_FATAL"})(_t||(_t={}));var U=class extends Error{code;props;constructor(e,t,r){super(e),this.code=t,this.name=r?.name??"CodeError",this.props=r??{}}};var Se=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},Wn=globalThis.CustomEvent??Se;function Et(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 St(i){return i==null?!1:typeof i.then=="function"&&typeof i.catch=="function"&&typeof i.finally=="function"}function he(i,e){let t=Et(i).return?.();St(t)&&t.catch(r=>{e.error("could not cause iterator to return",r)})}function V(){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}},W=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 Re=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function F(i={}){return oi(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 oi(i,e){e=e??{};let t=e.onEnd,r=new W,s,n,o,a=V(),c=async()=>{try{return r.isEmpty()?o?{done:!0}:await new Promise((d,w)=>{n=E=>{n=null,r.push(E);try{d(i(r))}catch(x){w(x)}return s}}):i(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=V()})}},h=d=>n!=null?n(d):(r.push(d),s),l=d=>(r=new W,n!=null?n({error:d}):(r.push({error:d}),s)),f=d=>{if(o)return s;if(e?.objectMode!==!0&&d?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return h({done:!1,value:d})},y=d=>o?s:(o=!0,d!=null?l(d):h({done:!0})),_=()=>(r=new W,y(),{done:!0}),u=d=>(y(d),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:_,throw:u,push:f,end:y,get readableLength(){return r.size},onEmpty:async d=>{let w=d?.signal;if(w?.throwIfAborted(),r.isEmpty())return;let E,x;w!=null&&(E=new Promise((R,T)=>{x=()=>{T(new Re)},w.addEventListener("abort",x)}));try{await Promise.race([a.promise,E])}finally{x!=null&&w!=null&&w?.removeEventListener("abort",x)}}},t==null)return s;let m=s;return s={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(d){return m.throw(d),t!=null&&(t(d),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(d){return m.end(d),t!=null&&(t(d),t=void 0),s},get readableLength(){return m.readableLength},onEmpty:d=>m.onEmpty(d)},s}function ai(i){return i[Symbol.asyncIterator]!=null}function ci(...i){let e=[];for(let t of i)ai(t)||e.push(t);return e.length===i.length?function*(){for(let t of e)yield*t}():async function*(){let t=F({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=ci;function At(i,...e){if(i==null)throw new Error("Empty pipeline");if(Ae(i)){let r=i;i=()=>r.source}else if(Tt(i)||Lt(i)){let r=i;i=()=>r}let t=[i,...e];if(t.length>1&&Ae(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++)Ae(t[r])&&(t[r]=li(t[r]));return hi(...t)}var hi=(...i)=>{let e;for(;i.length>0;)e=i.shift()(e);return e},Lt=i=>i?.[Symbol.asyncIterator]!=null,Tt=i=>i?.[Symbol.iterator]!=null,Ae=i=>i==null?!1:i.sink!=null&&i.source!=null,li=i=>e=>{let t=i.sink(e);if(t?.then!=null){let r=F({objectMode:!0});t.then(()=>{r.end()},o=>{r.end(o)});let s,n=i.source;if(Lt(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 Jr=si(Er(),1);function D(i){return globalThis.Buffer!=null?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):i}function B(i=0){return globalThis.Buffer?.alloc!=null?D(globalThis.Buffer.alloc(i)):new Uint8Array(i)}function M(i=0){return globalThis.Buffer?.allocUnsafe!=null?D(globalThis.Buffer.allocUnsafe(i)):new Uint8Array(i)}function fe(i,e){if(globalThis.Buffer!=null)return D(globalThis.Buffer.concat(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 D(t)}function Ve(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 Ge={};A(Ge,{base10:()=>Xi});function Gi(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 f(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,d=0,w=0,E=u.length;w!==E&&u[w]===0;)w++,m++;for(var x=(E-w)*l+1>>>0,R=new Uint8Array(x);w!==E;){for(var T=u[w],v=0,N=x-1;(T!==0||v<d)&&N!==-1;N--,v++)T+=256*R[N]>>>0,R[N]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");d=v,w++}for(var k=x-d;k!==x&&R[k]===0;)k++;for(var ae=c.repeat(m);k<x;++k)ae+=i.charAt(R[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 d=0,w=0;u[m]===c;)d++,m++;for(var E=(u.length-m)*h+1>>>0,x=new Uint8Array(E);u[m];){var R=t[u.charCodeAt(m)];if(R===255)return;for(var T=0,v=E-1;(R!==0||T<w)&&v!==-1;v--,T++)R+=a*x[v]>>>0,x[v]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");w=T,m++}if(u[m]!==" "){for(var N=E-w;N!==E&&x[N]===0;)N++;for(var k=new Uint8Array(d+(E-N)),ae=d;N!==E;)k[ae++]=x[N++];return k}}}function _(u){var m=y(u);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:y,decode:_}}var ji=Gi,Hi=ji,Sr=Hi;var _a=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),Lr=i=>new TextDecoder().decode(i);var $e=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")}},ze=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 Ir(this,e)}},We=class{constructor(e){this.decoders=e}or(e){return Ir(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`)}},Ir=(i,e)=>new We({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}}),Ke=class{constructor(e,t,r,s){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=s,this.encoder=new $e(e,t,r),this.decoder=new ze(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 Ke(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))})},Yi=(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 f=s[i[l]];if(f===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<t|f,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},Qi=(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},g=({name:i,prefix:e,bitsPerChar:t,alphabet:r})=>Y({prefix:e,name:i,encode(s){return Qi(s,r,t)},decode(s){return Yi(s,r,t,i)}});var Xi=q({prefix:"9",name:"base10",alphabet:"0123456789"});var je={};A(je,{base16:()=>Ji,base16upper:()=>Zi});var Ji=g({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Zi=g({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var He={};A(He,{base2:()=>es});var es=g({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ye={};A(Ye,{base256emoji:()=>ns});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}"),ts=Nr.reduce((i,e,t)=>(i[t]=e,i),[]),rs=Nr.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function is(i){return i.reduce((e,t)=>(e+=ts[t],e),"")}function ss(i){let e=[];for(let t of i){let r=rs[t.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(r)}return new Uint8Array(e)}var ns=Y({prefix:"\u{1F680}",name:"base256emoji",encode:is,decode:ss});var Qe={};A(Qe,{base32:()=>Q,base32hex:()=>hs,base32hexpad:()=>us,base32hexpadupper:()=>fs,base32hexupper:()=>ls,base32pad:()=>as,base32padupper:()=>cs,base32upper:()=>os,base32z:()=>ds});var Q=g({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),os=g({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),as=g({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),cs=g({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),hs=g({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ls=g({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),us=g({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),fs=g({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ds=g({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Xe={};A(Xe,{base36:()=>ms,base36upper:()=>ps});var ms=q({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ps=q({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Je={};A(Je,{base58btc:()=>C,base58flickr:()=>ys});var C=q({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ys=q({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ze={};A(Ze,{base64:()=>bs,base64pad:()=>gs,base64url:()=>ws,base64urlpad:()=>xs});var bs=g({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),gs=g({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ws=g({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),xs=g({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var et={};A(et,{base8:()=>_s});var _s=g({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var tt={};A(tt,{identity:()=>Es});var Es=Y({prefix:"\0",name:"identity",encode:i=>Lr(i),decode:i=>Ar(i)});var Oa=new TextEncoder,va=new TextDecoder;var it={};A(it,{identity:()=>Ks});var As=Pr,Mr=128,Ls=127,Ts=~Ls,Is=Math.pow(2,31);function Pr(i,e,t){e=e||[],t=t||0;for(var r=t;i>=Is;)e[t++]=i&255|Mr,i/=128;for(;i&Ts;)e[t++]=i&255|Mr,i>>>=7;return e[t]=i|0,Pr.bytes=t-r+1,e}var Ns=rt,Ms=128,Cr=127;function rt(i,r){var t=0,r=r||0,s=0,n=r,o,a=i.length;do{if(n>=a)throw rt.bytes=0,new RangeError("Could not decode varint");o=i[n++],t+=s<28?(o&Cr)<<s:(o&Cr)*Math.pow(2,s),s+=7}while(o>=Ms);return rt.bytes=n-r,t}var Cs=Math.pow(2,7),Ps=Math.pow(2,14),ks=Math.pow(2,21),Ds=Math.pow(2,28),Bs=Math.pow(2,35),Os=Math.pow(2,42),vs=Math.pow(2,49),Us=Math.pow(2,56),Fs=Math.pow(2,63),qs=function(i){return i<Cs?1:i<Ps?2:i<ks?3:i<Ds?4:i<Bs?5:i<Os?6:i<vs?7:i<Us?8:i<Fs?9:10},Vs={encode:As,decode:Ns,encodingLength:qs},$s=Vs,te=$s;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 $=(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,zs="identity",Or=O,Ws=i=>$(Br,Or(i)),Ks={code:Br,name:zs,encode:Or,digest:Ws};var ot={};A(ot,{sha256:()=>Gs,sha512:()=>js});var nt=({name:i,code:e,encode:t})=>new st(i,e,t),st=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?$(this.code,t):t.then(r=>$(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)),Gs=nt({name:"sha2-256",code:18,encode:Ur("SHA-256")}),js=nt({name:"sha2-512",code:19,encode:Ur("SHA-512")});var Fr=(i,e)=>{let{bytes:t,version:r}=i;switch(r){case 0:return Ys(t,at(i),e||C.encoder);default:return Qs(t,at(i),e||Q.encoder)}};var qr=new WeakMap,at=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!==Xs)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=$(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||Vr(r,s,n.bytes))}else if(t[Js]===!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=Vr(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[f,y]=re(e.subarray(t));return t+=y,f},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]=Hs(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 at(n).set(r,e),n}},Hs=(i,e)=>{switch(i[0]){case"Q":{let t=e||C;return[C.prefix,t.decode(`${C.prefix}${i}`)]}case C.prefix:{let t=e||C;return[C.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)]}}},Ys=(i,e,t)=>{let{prefix:r}=t;if(r!==C.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},Qs=(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,Xs=18,Vr=(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},Js=Symbol.for("@ipld/js-cid/CID");var ct={...tt,...He,...et,...Ge,...je,...Qe,...Xe,...Je,...Ze,...Ye},Za={...ot,...it};function zr(i,e,t,r){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:r}}}var $r=zr("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),ht=zr("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}),Zs={utf8:$r,"utf-8":$r,hex:ct.base16,latin1:ht,ascii:ht,binary:ht,...ct},pe=Zs;function lt(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?D(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 P=class i{bufs;length;[Kr]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let 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 fe(r,s)}subarray(e,t){let{bufs:r,length:s}=this._subList(e,t);return r.length===1?r[0]:fe(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 f=e-a;r.push(o.subarray(f,f+(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 f=0;f<n;f++)o[f]=-1;for(let f=0;f<s;f++)o[r[f]]=f;let a=o,c=this.byteLength-r.byteLength,h=r.byteLength-1,l;for(let f=t;f<=c;f+=l){l=0;for(let y=h;y>=0;y--){let _=this.get(f+y);if(r[y]!==_){l=Math.max(1,y-a[_]);break}}if(l===0)return f}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(!Ve(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"}),ut=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 ft=1<<20,en=4<<20,be=class{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=ft,t=en){this._buffer=new P,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}}},tn=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>=tn);return e=s-e,{value:t,offset:e}}var rn=Math.pow(2,7),sn=Math.pow(2,14),nn=Math.pow(2,21),on=Math.pow(2,28),an=Math.pow(2,35),cn=Math.pow(2,42),hn=Math.pow(2,49),S=128;function z(i){if(i<rn)return 1;if(i<sn)return 2;if(i<nn)return 3;if(i<on)return 4;if(i<an)return 5;if(i<cn)return 6;if(i<hn)return 7;if(Number.MAX_SAFE_INTEGER!=null&&i>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ln(i,e,t=0){switch(z(i)){case 8:e[t++]=i&255|S,i/=128;case 7:e[t++]=i&255|S,i/=128;case 6:e[t++]=i&255|S,i/=128;case 5:e[t++]=i&255|S,i/=128;case 4:e[t++]=i&255|S,i>>>=7;case 3:e[t++]=i&255|S,i>>>=7;case 2:e[t++]=i&255|S,i>>>=7;case 1:{e[t++]=i&255,i>>>=7;break}default:throw new Error("unreachable")}return e}function un(i,e,t=0){switch(z(i)){case 8:e.set(t++,i&255|S),i/=128;case 7:e.set(t++,i&255|S),i/=128;case 6:e.set(t++,i&255|S),i/=128;case 5:e.set(t++,i&255|S),i/=128;case 4:e.set(t++,i&255|S),i>>>=7;case 3:e.set(t++,i&255|S),i>>>=7;case 2:e.set(t++,i&255|S),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(z(i))),e instanceof Uint8Array?ln(i,e,t):un(i,e,t)}function dt(i){return new Uint8Array(i)}var mt=10*1024,pt=class{_pool;_poolOffset;constructor(){this._pool=dt(mt),this._poolOffset=0}write(e,t){let r=this._pool,s=this._poolOffset;ge(e.id<<3|e.type,r,s),s+=z(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+=z(e.data.length)):(ge(0,r,s),s+=z(0));let n=r.subarray(this._poolOffset,s);mt-s<100?(this._pool=dt(mt),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)}},dn=new pt;async function*Yr(i){for await(let e of i){let t=new P;dn.write(e,t),yield t}}var we=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 xe(i,e,t){if(e==null)return i;if(e.aborted)return Promise.reject(new we(t?.errorMessage,t?.errorCode));let r,s=new we(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 mn="ERR_STREAM_RESET",pn="ERR_SINK_INVALID_STATE",yn=5e3;function yt(i){return i==null?!1:typeof i.then=="function"&&typeof i.catch=="function"&&typeof i.finally=="function"}var _e=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;constructor(e){this.sinkController=new AbortController,this.sinkEnd=V(),this.closed=V(),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??yn,this.onEnd=e.onEnd,this.onCloseRead=e?.onCloseRead,this.onCloseWrite=e?.onCloseWrite,this.onReset=e?.onReset,this.onAbort=e?.onAbort,this.source=this.streamSource=F({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"`,pn);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 P(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.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){this.log.trace("closing gracefully"),this.status="closing",await Promise.all([this.closeRead(e),this.closeWrite(e)]),await xe(this.closed.promise,e?.signal),this.status="closed",this.log.trace("closed gracefully")}async closeRead(e={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let t=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),t==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await xe(this.sink([]),e.signal)),this.writeStatus==="writing"&&await new Promise((t,r)=>{queueMicrotask(()=>{this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),xe(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",mn);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 _e{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types=e.direction==="outbound"?ut: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:ut.NEW_STREAM,data:new P(lt(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 Qr(i){let{id:e,name:t,send:r,onEnd:s,type:n="initiator",maxMsgSize:o=ft}=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 bn=1024,gn=1024,wn=1024*1024*4,xn=5,_n=500;function Xr(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 Ee=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??_n,this.sink=this._createSink(),this._source=F({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=>Yr(r)),this.closeController=new AbortController,this.rateLimiter=new Jr.RateLimiterMemory({points:t.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(this.log("new %s stream %s",s,t),s==="initiator"&&this._streams.initiators.size===(this._init.maxOutboundStreams??gn))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=Qr({id:t,name:r,send:async h=>{this.log.enabled&&this.log.trace("%s stream %s send",s,t,Xr(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",Xr(e)),e.type===p.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??bn)){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??wn;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 gt=class{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}createStreamMuxer(e={}){return new Ee(this.components,{...e,...this._init})}};function En(i={}){return e=>new gt(e,i)}return ni(Sn);})();
|
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"))}};Wt.exports=Pe});var Gt=b(()=>{});var jt=b(()=>{});var Yt=b((Zo,Ht)=>{Ht.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 Xt=b((ta,Qt)=>{var Ai=Yt(),ke=T();Qt.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!this._storage[e].expiresAt||s>0?(this._storage[e].value=this._storage[e].value+t,new ke(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 Ai(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 ke(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 ke(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 Be=b((ra,Zt)=>{var Ti=Z(),Li=Xt(),Jt=T(),De=class extends Ti{constructor(e={}){super(e),this._memoryStorage=new Li}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 l=Math.ceil(c.msBeforeNext/(c.remainingPoints+2));l<this.execEvenlyMinDelayMs&&(l=c.consumedPoints*this.execEvenlyMinDelayMs),setTimeout(s,l,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 Jt(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 Jt(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)))}};Zt.exports=De});var or=b((ia,nr)=>{var er=Gt(),Ii=jt(),Ni=Z(),rr=Be(),Mi=T(),I="rate_limiter_flexible",G=null,tr=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:I,keyPrefix:e.keyPrefix,promiseId:e.promiseId,type:t,data:s})},ir=function(i){setTimeout(()=>{this._initiated?process.send(i):typeof this._promises[i.promiseId]<"u"&&ir.call(this,i)},30)},W=function(i,e,t,r,s){let n={channel:I,keyPrefix:this.keyPrefix,func:i,promiseId:e,data:{key:t,arg:r,opts:s}};this._initiated?process.send(n):ir.call(this,n)},sr=function(i,e){if(!e||e.channel!==I||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=>{tr(i,e,"resolve",r)}).catch(r=>{tr(i,e,"reject",r)})},Ci=function(i){if(!i||i.channel!==I||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 Mi(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]}},Pi=function(){return{points:this.points,duration:this.duration,blockDuration:this.blockDuration,execEvenly:this.execEvenly,execEvenlyMinDelayMs:this.execEvenlyMinDelayMs,keyPrefix:this.keyPrefix}},K=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},Oe=class{constructor(){if(G)return G;this._rateLimiters={},er.setMaxListeners(0),er.on("message",(e,t)=>{t&&t.channel===I&&t.type==="init"?(typeof this._rateLimiters[t.opts.keyPrefix]>"u"&&(this._rateLimiters[t.opts.keyPrefix]=new rr(t.opts)),e.send({channel:I,type:"init",keyPrefix:t.opts.keyPrefix})):sr.call(this,e,t)}),G=this}},ve=class{constructor(e){if(G)return G;this._rateLimiters={},e.launchBus((t,r)=>{r.on("process:msg",s=>{let n=s.raw;if(n&&n.channel===I&&n.type==="init")typeof this._rateLimiters[n.opts.keyPrefix]>"u"&&(this._rateLimiters[n.opts.keyPrefix]=new rr(n.opts)),e.sendDataToProcessId(s.process.pm_id,{data:{},topic:I,channel:I,type:"init",keyPrefix:n.opts.keyPrefix},(o,a)=>{o&&console.log(o,a)});else{let o={send:a=>{let c=a;c.topic=I,typeof c.data>"u"&&(c.data={}),e.sendDataToProcessId(s.process.pm_id,c,(l,h)=>{l&&console.log(l,h)})}};sr.call(this,o,n)}})}),G=this}},Ue=class extends Ni{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===I&&t.type==="init"&&t.keyPrefix===this.keyPrefix?this._initiated=!0:Ci.call(this,t)}),process.send({channel:I,type:"init",opts:Pi.call(this)}),this._promises={}}consume(e,t=1,r={}){return new Promise((s,n)=>{let o=K.call(this,s,n);W.call(this,"consume",o,e,t,r)})}penalty(e,t=1,r={}){return new Promise((s,n)=>{let o=K.call(this,s,n);W.call(this,"penalty",o,e,t,r)})}reward(e,t=1,r={}){return new Promise((s,n)=>{let o=K.call(this,s,n);W.call(this,"reward",o,e,t,r)})}block(e,t,r={}){return new Promise((s,n)=>{let o=K.call(this,s,n);W.call(this,"block",o,e,t,r)})}get(e,t={}){return new Promise((r,s)=>{let n=K.call(this,r,s);W.call(this,"get",n,e,t)})}delete(e,t={}){return new Promise((r,s)=>{let n=K.call(this,r,s);W.call(this,"delete",n,e,t)})}};nr.exports={RateLimiterClusterMaster:Oe,RateLimiterClusterMasterPM2:ve,RateLimiterCluster:Ue}});var cr=b((sa,ar)=>{var ki=z(),Di=T(),Fe=class extends ki{constructor(e){super(e),this.client=e.storeClient}_getRateLimiterRes(e,t,r){let s=new Di;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(),l=Math.floor(r/1e3);s?this.client.set(e,t,l,h=>{h?a(h):this.client.set(`${e}_expire`,l>0?c+l*1e3:-1,l,()=>{let f={consumedPoints:t,msBeforeNext:l>0?l*1e3:-1};o(f)})}):this.client.incr(e,t,(h,f)=>{h||f===!1?this.client.add(e,t,l,(y,_)=>{if(y||!_)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`,l>0?c+l*1e3:-1,l,()=>{let u={consumedPoints:t,msBeforeNext:l>0?l*1e3:-1};o(u)})}):this.client.get(`${e}_expire`,(y,_)=>{if(y)a(y);else{let u=_===!1?0:_,m={consumedPoints:f,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 l=c===!1?0:c,h={consumedPoints:o,msBeforeNext:l>=0?Math.max(l-s,0):-1};t(h)}}):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)})})})}};ar.exports=Fe});var ur=b((oa,hr)=>{var lr=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 lr(0,Number.MAX_SAFE_INTEGER,0,!1)}getWhiteRes(){return new lr(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((ca,fr)=>{var Bi=Z();fr.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 Bi))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(l=>{l.rejected===!0&&(c=!0)});for(let l=0;l<o.length;l++)c&&o[l].rejected===!0?a[this._limiters[l].keyPrefix]=o[l].rej:c||(a[this._limiters[l].keyPrefix]=o[l]);c?s(a):r(a)})})}}});var pr=b((ha,mr)=>{mr.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((fa,gr)=>{var yr=pr(),br=4294967295,qe="limiter";gr.exports=class{constructor(e,t={maxQueueSize:br}){this._queueLimiters={KEY_DEFAULT:new fe(e,t)},this._limiterFlexible=e,this._maxQueueSize=t.maxQueueSize}getTokensRemaining(e=qe){return this._queueLimiters[e]?this._queueLimiters[e].getTokensRemaining():Promise.resolve(this._limiterFlexible.points)}removeTokens(e,t=qe){return this._queueLimiters[t]||(this._queueLimiters[t]=new fe(this._limiterFlexible,{key:t,maxQueueSize:this._maxQueueSize})),this._queueLimiters[t].removeTokens(e)}};var fe=class{constructor(e,t={maxQueueSize:br,key:qe}){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 yr(`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 yr(`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((ma,xr)=>{var Ve=T();xr.exports=class{constructor(e,t){this._rateLimiter=e,this._burstLimiter=t}_combineRes(e,t){return e?new Ve(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 Ve?this._burstLimiter.consume(e,t,r).then(n=>Promise.resolve(this._combineRes(s,n))).catch(n=>n instanceof Ve?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 Sr=b((pa,Er)=>{var Oi=Ut(),vi=Vt(),Ui=zt(),Fi=Kt(),{RateLimiterClusterMaster:qi,RateLimiterClusterMasterPM2:Vi,RateLimiterCluster:$i}=or(),zi=Be(),Wi=cr(),Ki=ur(),Gi=dr(),ji=wr(),Hi=_r(),Yi=T();Er.exports={RateLimiterRedis:Oi,RateLimiterMongo:vi,RateLimiterMySQL:Ui,RateLimiterPostgres:Fi,RateLimiterMemory:zi,RateLimiterMemcache:Wi,RateLimiterClusterMaster:qi,RateLimiterClusterMasterPM2:Vi,RateLimiterCluster:$i,RLWrapperBlackAndWhite:Ki,RateLimiterUnion:Gi,RateLimiterQueue:ji,BurstyRateLimiter:Hi,RateLimiterRes:Yi}});var Ln={};A(Ln,{mplex:()=>Tn});var Nn=Symbol.for("@libp2p/connection");var Cn=Symbol.for("@libp2p/content-routing");var Dn=Symbol.for("@libp2p/peer-discovery");var On=Symbol.for("@libp2p/peer-id");var Un=Symbol.for("@libp2p/peer-routing");var _t;(function(i){i.Accept="accept",i.Ignore="ignore",i.Reject="reject"})(_t||(_t={}));var $n=Symbol.for("@libp2p/transport");var Et;(function(i){i[i.FATAL_ALL=0]="FATAL_ALL",i[i.NO_FATAL=1]="NO_FATAL"})(Et||(Et={}));var O=class extends Error{code;props;constructor(e,t,r){super(e),this.code=t,this.name=r?.name??"CodeError",this.props=r??{}}};var Re=class extends Event{detail;constructor(e,t){super(e,t),this.detail=t?.detail}},Hn=globalThis.CustomEvent??Re;function St(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 Rt(i){return i==null?!1:typeof i.then=="function"&&typeof i.catch=="function"&&typeof i.finally=="function"}function he(i,e){let t=St(i).return?.();Rt(t)&&t.catch(r=>{e.error("could not cause iterator to return",r)})}function F(){let i={};return i.promise=new Promise((e,t)=>{i.resolve=e,i.reject=t}),i}var ue=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 ue(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 ue(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 Ae=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function v(i={}){return hi(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 hi(i,e){e=e??{};let t=e.onEnd,r=new $,s,n,o,a=F(),c=async()=>{try{return r.isEmpty()?o?{done:!0}:await new Promise((d,w)=>{n=E=>{n=null,r.push(E);try{d(i(r))}catch(x){w(x)}return s}}):i(r)}finally{r.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=F()})}},l=d=>n!=null?n(d):(r.push(d),s),h=d=>(r=new $,n!=null?n({error:d}):(r.push({error:d}),s)),f=d=>{if(o)return s;if(e?.objectMode!==!0&&d?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:d})},y=d=>o?s:(o=!0,d!=null?h(d):l({done:!0})),_=()=>(r=new $,y(),{done:!0}),u=d=>(y(d),{done:!0});if(s={[Symbol.asyncIterator](){return this},next:c,return:_,throw:u,push:f,end:y,get readableLength(){return r.size},onEmpty:async d=>{let w=d?.signal;if(w?.throwIfAborted(),r.isEmpty())return;let E,x;w!=null&&(E=new Promise((R,L)=>{x=()=>{L(new Ae)},w.addEventListener("abort",x)}));try{await Promise.race([a.promise,E])}finally{x!=null&&w!=null&&w?.removeEventListener("abort",x)}}},t==null)return s;let m=s;return s={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(d){return m.throw(d),t!=null&&(t(d),t=void 0),{done:!0}},return(){return m.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(d){return m.end(d),t!=null&&(t(d),t=void 0),s},get readableLength(){return m.readableLength},onEmpty:d=>m.onEmpty(d)},s}function ui(i){return i[Symbol.asyncIterator]!=null}function fi(...i){let e=[];for(let t of i)ui(t)||e.push(t);return e.length===i.length?function*(){for(let t of e)yield*t}():async function*(){let t=v({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 At=fi;function Tt(i,...e){if(i==null)throw new Error("Empty pipeline");if(Te(i)){let r=i;i=()=>r.source}else if(It(i)||Lt(i)){let r=i;i=()=>r}let t=[i,...e];if(t.length>1&&Te(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++)Te(t[r])&&(t[r]=mi(t[r]));return di(...t)}var di=(...i)=>{let e;for(;i.length>0;)e=i.shift()(e);return e},Lt=i=>i?.[Symbol.asyncIterator]!=null,It=i=>i?.[Symbol.iterator]!=null,Te=i=>i==null?!1:i.sink!=null&&i.source!=null,mi=i=>e=>{let t=i.sink(e);if(t?.then!=null){let r=v({objectMode:!0});t.then(()=>{r.end()},o=>{r.end(o)});let s,n=i.source;if(Lt(n))s=async function*(){yield*n,r.end()};else if(It(n))s=function*(){yield*n,r.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return At(r,s())}return i.source};var ri=ci(Sr(),1);function j(i){return globalThis.Buffer!=null?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):i}function de(i=0){return globalThis.Buffer?.allocUnsafe!=null?j(globalThis.Buffer.allocUnsafe(i)):new Uint8Array(i)}var Ge={};A(Ge,{base10:()=>ts});function Qi(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),l=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function f(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,d=0,w=0,E=u.length;w!==E&&u[w]===0;)w++,m++;for(var x=(E-w)*h+1>>>0,R=new Uint8Array(x);w!==E;){for(var L=u[w],B=0,N=x-1;(L!==0||B<d)&&N!==-1;N--,B++)L+=256*R[N]>>>0,R[N]=L%a>>>0,L=L/a>>>0;if(L!==0)throw new Error("Non-zero carry");d=B,w++}for(var P=x-d;P!==x&&R[P]===0;)P++;for(var ce=c.repeat(m);P<x;++P)ce+=i.charAt(R[P]);return ce}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 d=0,w=0;u[m]===c;)d++,m++;for(var E=(u.length-m)*l+1>>>0,x=new Uint8Array(E);u[m];){var R=t[u.charCodeAt(m)];if(R===255)return;for(var L=0,B=E-1;(R!==0||L<w)&&B!==-1;B--,L++)R+=a*x[B]>>>0,x[B]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");w=L,m++}if(u[m]!==" "){for(var N=E-w;N!==E&&x[N]===0;)N++;for(var P=new Uint8Array(d+(E-N)),ce=d;N!==E;)P[ce++]=x[N++];return P}}}function _(u){var m=y(u);if(m)return m;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:y,decode:_}}var Xi=Qi,Ji=Xi,Rr=Ji;var Aa=new Uint8Array(0);var Ar=(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},k=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 Tr=i=>new TextEncoder().encode(i),Lr=i=>new TextDecoder().decode(i);var $e=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")}},ze=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 Nr(this,e)}},We=class{constructor(e){this.decoders=e}or(e){return Nr(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`)}},Nr=(i,e)=>new We({...i.decoders||{[i.prefix]:i},...e.decoders||{[e.prefix]:e}}),Ke=class{constructor(e,t,r,s){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=s,this.encoder=new $e(e,t,r),this.decoder=new ze(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},H=({name:i,prefix:e,encode:t,decode:r})=>new Ke(i,e,t,r),U=({prefix:i,name:e,alphabet:t})=>{let{encode:r,decode:s}=Rr(t,e);return H({prefix:i,name:e,encode:r,decode:n=>k(s(n))})},Zi=(i,e,t,r)=>{let s={};for(let h=0;h<e.length;++h)s[e[h]]=h;let n=i.length;for(;i[n-1]==="=";)--n;let o=new Uint8Array(n*t/8|0),a=0,c=0,l=0;for(let h=0;h<n;++h){let f=s[i[h]];if(f===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<t|f,a+=t,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=t||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},es=(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},g=({name:i,prefix:e,bitsPerChar:t,alphabet:r})=>H({prefix:e,name:i,encode(s){return es(s,r,t)},decode(s){return Zi(s,r,t,i)}});var ts=U({prefix:"9",name:"base10",alphabet:"0123456789"});var je={};A(je,{base16:()=>rs,base16upper:()=>is});var rs=g({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),is=g({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var He={};A(He,{base2:()=>ss});var ss=g({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ye={};A(Ye,{base256emoji:()=>ls});var Mr=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}"),ns=Mr.reduce((i,e,t)=>(i[t]=e,i),[]),os=Mr.reduce((i,e,t)=>(i[e.codePointAt(0)]=t,i),[]);function as(i){return i.reduce((e,t)=>(e+=ns[t],e),"")}function cs(i){let e=[];for(let t of i){let r=os[t.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${t}`);e.push(r)}return new Uint8Array(e)}var ls=H({prefix:"\u{1F680}",name:"base256emoji",encode:as,decode:cs});var Qe={};A(Qe,{base32:()=>Y,base32hex:()=>ds,base32hexpad:()=>ps,base32hexpadupper:()=>ys,base32hexupper:()=>ms,base32pad:()=>us,base32padupper:()=>fs,base32upper:()=>hs,base32z:()=>bs});var Y=g({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),hs=g({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),us=g({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),fs=g({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ds=g({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ms=g({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ps=g({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ys=g({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),bs=g({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Xe={};A(Xe,{base36:()=>gs,base36upper:()=>ws});var gs=U({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ws=U({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Je={};A(Je,{base58btc:()=>M,base58flickr:()=>xs});var M=U({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xs=U({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ze={};A(Ze,{base64:()=>_s,base64pad:()=>Es,base64url:()=>Ss,base64urlpad:()=>Rs});var _s=g({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Es=g({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ss=g({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Rs=g({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var et={};A(et,{base8:()=>As});var As=g({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var tt={};A(tt,{identity:()=>Ts});var Ts=H({prefix:"\0",name:"identity",encode:i=>Lr(i),decode:i=>Tr(i)});var qa=new TextEncoder,Va=new TextDecoder;var it={};A(it,{identity:()=>Ys});var Ns=kr,Cr=128,Ms=127,Cs=~Ms,Ps=Math.pow(2,31);function kr(i,e,t){e=e||[],t=t||0;for(var r=t;i>=Ps;)e[t++]=i&255|Cr,i/=128;for(;i&Cs;)e[t++]=i&255|Cr,i>>>=7;return e[t]=i|0,kr.bytes=t-r+1,e}var ks=rt,Ds=128,Pr=127;function rt(i,r){var t=0,r=r||0,s=0,n=r,o,a=i.length;do{if(n>=a)throw rt.bytes=0,new RangeError("Could not decode varint");o=i[n++],t+=s<28?(o&Pr)<<s:(o&Pr)*Math.pow(2,s),s+=7}while(o>=Ds);return rt.bytes=n-r,t}var Bs=Math.pow(2,7),Os=Math.pow(2,14),vs=Math.pow(2,21),Us=Math.pow(2,28),Fs=Math.pow(2,35),qs=Math.pow(2,42),Vs=Math.pow(2,49),$s=Math.pow(2,56),zs=Math.pow(2,63),Ws=function(i){return i<Bs?1:i<Os?2:i<vs?3:i<Us?4:i<Fs?5:i<qs?6:i<Vs?7:i<$s?8:i<zs?9:10},Ks={encode:Ns,decode:ks,encodingLength:Ws},Gs=Ks,ee=Gs;var te=(i,e=0)=>[ee.decode(i,e),ee.decode.bytes],Q=(i,e,t=0)=>(ee.encode(i,e,t),e),X=i=>ee.encodingLength(i);var q=(i,e)=>{let t=e.byteLength,r=X(i),s=r+X(t),n=new Uint8Array(s+t);return Q(i,n,0),Q(t,n,r),n.set(e,s),new J(i,t,e,n)},Dr=i=>{let e=k(i),[t,r]=te(e),[s,n]=te(e.subarray(r)),o=e.subarray(r+n);if(o.byteLength!==s)throw new Error("Incorrect length");return new J(t,s,o,e)},Br=(i,e)=>{if(i===e)return!0;{let t=e;return i.code===t.code&&i.size===t.size&&t.bytes instanceof Uint8Array&&Ar(i.bytes,t.bytes)}},J=class{constructor(e,t,r,s){this.code=e,this.size=t,this.digest=r,this.bytes=s}};var Or=0,js="identity",vr=k,Hs=i=>q(Or,vr(i)),Ys={code:Or,name:js,encode:vr,digest:Hs};var ot={};A(ot,{sha256:()=>Qs,sha512:()=>Xs});var nt=({name:i,code:e,encode:t})=>new st(i,e,t),st=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?q(this.code,t):t.then(r=>q(this.code,r))}else throw Error("Unknown type, must be binary type")}};var Fr=i=>async e=>new Uint8Array(await crypto.subtle.digest(i,e)),Qs=nt({name:"sha2-256",code:18,encode:Fr("SHA-256")}),Xs=nt({name:"sha2-512",code:19,encode:Fr("SHA-512")});var qr=(i,e)=>{let{bytes:t,version:r}=i;switch(r){case 0:return Zs(t,at(i),e||M.encoder);default:return en(t,at(i),e||Y.encoder)}};var Vr=new WeakMap,at=i=>{let e=Vr.get(i);if(e==null){let t=new Map;return Vr.set(i,t),t}return e},pe=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!==ie)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==tn)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=q(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&&Br(e.multihash,r.multihash)}toString(e){return qr(this,e)}toJSON(){return{"/":qr(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||$r(r,s,n.bytes))}else if(t[rn]===!0){let{version:r,multihash:s,code:n}=t,o=Dr(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!==ie)throw new Error(`Version 0 CID must use dag-pb (code: ${ie}) block encoding`);return new i(e,t,r,r.bytes)}case 1:{let s=$r(e,t,r.bytes);return new i(e,t,r,s)}default:throw new Error("Invalid version")}}static createV0(e){return i.create(0,ie,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=k(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 J(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[f,y]=te(e.subarray(t));return t+=y,f},s=r(),n=ie;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(),l=t+c,h=l-o;return{version:s,codec:n,multihashCode:a,digestSize:c,multihashSize:h,size:l}}static parse(e,t){let[r,s]=Js(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 at(n).set(r,e),n}},Js=(i,e)=>{switch(i[0]){case"Q":{let t=e||M;return[M.prefix,t.decode(`${M.prefix}${i}`)]}case M.prefix:{let t=e||M;return[M.prefix,t.decode(i)]}case Y.prefix:{let t=e||Y;return[Y.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)]}}},Zs=(i,e,t)=>{let{prefix:r}=t;if(r!==M.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},en=(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},ie=112,tn=18,$r=(i,e,t)=>{let r=X(i),s=r+X(e),n=new Uint8Array(s+t.byteLength);return Q(i,n,0),Q(e,n,r),n.set(t,s),n},rn=Symbol.for("@ipld/js-cid/CID");var ct={...tt,...He,...et,...Ge,...je,...Qe,...Xe,...Je,...Ze,...Ye},ic={...ot,...it};function Wr(i,e,t,r){return{name:i,prefix:e,encoder:{name:i,prefix:e,encode:t},decoder:{decode:r}}}var zr=Wr("utf8","u",i=>"u"+new TextDecoder("utf8").decode(i),i=>new TextEncoder().encode(i.substring(1))),lt=Wr("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=de(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}),sn={utf8:zr,"utf-8":zr,hex:ct.base16,latin1:lt,ascii:lt,binary:lt,...ct},ye=sn;function ht(i,e="utf8"){let t=ye[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?j(globalThis.Buffer.from(i,"utf-8")):t.decoder.decode(`${t.prefix}${i}`)}function se(i,e="utf8"){let t=ye[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)}function ne(i){return globalThis.Buffer!=null?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):i}function D(i=0){return globalThis.Buffer?.alloc!=null?ne(globalThis.Buffer.alloc(i)):new Uint8Array(i)}function oe(i=0){return globalThis.Buffer?.allocUnsafe!=null?ne(globalThis.Buffer.allocUnsafe(i)):new Uint8Array(i)}function ut(i,e){e==null&&(e=i.reduce((s,n)=>s+n.length,0));let t=oe(e),r=0;for(let s of i)t.set(s,r),r+=s.length;return ne(t)}function Kr(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 jr=Symbol.for("@achingbrain/uint8arraylist");function Gr(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 be(i){return!!i?.[jr]}var C=class i{bufs;length;[jr]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else if(be(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(be(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=Gr(this.bufs,e);return t.buf[t.index]}set(e,t){let r=Gr(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(be(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 ut(r,s)}subarray(e,t){let{bufs:r,length:s}=this._subList(e,t);return r.length===1?r[0]:ut(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 l=e>=a&&e<c,h=t>a&&t<=c;if(l&&h){if(e===a&&t===c){r.push(o);break}let f=e-a;r.push(o.subarray(f,f+(t-e)));break}if(l){if(e===0){r.push(o);continue}r.push(o.subarray(e-a));continue}if(h){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(!be(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 f=0;f<n;f++)o[f]=-1;for(let f=0;f<s;f++)o[r[f]]=f;let a=o,c=this.byteLength-r.byteLength,l=r.byteLength-1,h;for(let f=t;f<=c;f+=h){h=0;for(let y=l;y>=0;y--){let _=this.get(f+y);if(r[y]!==_){h=Math.max(1,y-a[_]);break}}if(h===0)return f}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=oe(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=D(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=D(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=D(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=oe(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=D(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=D(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=D(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=D(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=D(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(!Kr(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 ae=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),ft=Object.freeze({NEW_STREAM:p.NEW_STREAM,MESSAGE:p.MESSAGE_INITIATOR,CLOSE:p.CLOSE_INITIATOR,RESET:p.RESET_INITIATOR}),Hr=Object.freeze({MESSAGE:p.MESSAGE_RECEIVER,CLOSE:p.CLOSE_RECEIVER,RESET:p.RESET_RECEIVER});var dt=1<<20,nn=4<<20,ge=class{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=dt,t=nn){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(l){if(l.code==="ERR_MSG_TOO_BIG")throw l;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}=Qr(e),{value:s,offset:n}=Qr(e,r),o=t&7;if(ae[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}}},on=128,Yr=127;function Qr(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&Yr)<<r:(n&Yr)*Math.pow(2,r),r+=7}while(n>=on);return e=s-e,{value:t,offset:e}}function Xr(i){return globalThis.Buffer!=null?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):i}function Jr(i=0){return globalThis.Buffer?.allocUnsafe!=null?Xr(globalThis.Buffer.allocUnsafe(i)):new Uint8Array(i)}var an=Math.pow(2,7),cn=Math.pow(2,14),ln=Math.pow(2,21),hn=Math.pow(2,28),un=Math.pow(2,35),fn=Math.pow(2,42),dn=Math.pow(2,49),S=128;function V(i){if(i<an)return 1;if(i<cn)return 2;if(i<ln)return 3;if(i<hn)return 4;if(i<un)return 5;if(i<fn)return 6;if(i<dn)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|S,i/=128;case 7:e[t++]=i&255|S,i/=128;case 6:e[t++]=i&255|S,i/=128;case 5:e[t++]=i&255|S,i/=128;case 4:e[t++]=i&255|S,i>>>=7;case 3:e[t++]=i&255|S,i>>>=7;case 2:e[t++]=i&255|S,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|S),i/=128;case 7:e.set(t++,i&255|S),i/=128;case 6:e.set(t++,i&255|S),i/=128;case 5:e.set(t++,i&255|S),i/=128;case 4:e.set(t++,i&255|S),i>>>=7;case 3:e.set(t++,i&255|S),i>>>=7;case 2:e.set(t++,i&255|S),i>>>=7;case 1:{e.set(t++,i&255),i>>>=7;break}default:throw new Error("unreachable")}return e}function we(i,e,t=0){return e==null&&(e=Jr(V(i))),e instanceof Uint8Array?mn(i,e,t):pn(i,e,t)}function mt(i){return new Uint8Array(i)}var pt=10*1024,yt=class{_pool;_poolOffset;constructor(){this._pool=mt(pt),this._poolOffset=0}write(e,t){let r=this._pool,s=this._poolOffset;we(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?(we(e.data.length,r,s),s+=V(e.data.length)):(we(0,r,s),s+=V(0));let n=r.subarray(this._poolOffset,s);pt-s<100?(this._pool=mt(pt),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)}},bn=new yt;async function*Zr(i){for await(let e of i){let t=new C;bn.write(e,t),yield t}}var xe=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 _e(i,e,t){if(e==null)return i;if(e.aborted)return Promise.reject(new xe(t?.errorMessage,t?.errorCode));let r,s=new xe(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 gn="ERR_STREAM_RESET",wn="ERR_SINK_INVALID_STATE",xn=5e3;function bt(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;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;constructor(e){this.sinkController=new AbortController,this.sinkEnd=F(),this.closed=F(),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??xn,this.onEnd=e.onEnd,this.onCloseRead=e?.onCloseRead,this.onCloseWrite=e?.onCloseWrite,this.onReset=e?.onReset,this.onAbort=e?.onAbort,this.source=this.streamSource=v({onEnd:t=>{t!=null?this.log.trace("source ended with error",t):this.log.trace("source ended"),this.onSourceEnd(t)}}),this.sink=this.sink.bind(this)}async sink(e){if(this.writeStatus!=="ready")throw new O(`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);bt(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 C(s):s;let n=this.sendData(s,t);bt(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.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",e!=null&&this.endErr==null&&(this.endErr=e),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){this.log.trace("closing gracefully"),this.status="closing",await Promise.all([this.closeRead(e),this.closeWrite(e)]),await _e(this.closed.promise,e?.signal),this.status="closed",this.log.trace("closed gracefully")}async closeRead(e={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let t=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),t==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await _e(this.sink([]),e.signal)),this.writeStatus==="writing"&&await new Promise((t,r)=>{queueMicrotask(()=>{this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),_e(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();bt(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 O("stream reset",gn);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 gt=class extends Ee{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types=e.direction==="outbound"?ft:Hr,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:ft.NEW_STREAM,data:new C(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 ei(i){let{id:e,name:t,send:r,onEnd:s,type:n="initiator",maxMsgSize:o=dt}=i;return new gt({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,Sn=1024*1024*4,Rn=5,An=500;function ti(i){let e={...i,type:`${ae[i.type]} (${i.type})`};return i.type===p.NEW_STREAM&&(e.data=se(i.data instanceof Uint8Array?i.data:i.data.subarray())),(i.type===p.MESSAGE_INITIATOR||i.type===p.MESSAGE_RECEIVER)&&(e.data=se(i.data instanceof Uint8Array?i.data:i.data.subarray(),"base16")),e}var Se=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??An,this.sink=this._createSink(),this._source=v({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=Tt(this._source,r=>Zr(r)),this.closeController=new AbortController,this.rateLimiter=new ri.RateLimiterMemory({points:t.disconnectThreshold??Rn,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 O("Too many outbound streams open","ERR_TOO_MANY_OUTBOUND_STREAMS");if(n.has(t))throw new Error(`${s} stream ${t} already exists!`);let c=ei({id:t,name:r,send:async l=>{this.log.enabled&&this.log.trace("%s stream %s send",s,t,ti(l)),this._source.push(l)},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 ge(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",ti(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:se(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,ae[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??Sn;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 O("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 Se(this.components,{...e,...this._init})}};function Tn(i={}){return e=>new wt(e,i)}return li(Ln);})();
|
25
25
|
return Libp2PMplex}));
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@libp2p/mplex",
|
3
|
-
"version": "10.0.
|
3
|
+
"version": "10.0.6-6d11e8268",
|
4
4
|
"description": "JavaScript implementation of https://github.com/libp2p/mplex",
|
5
5
|
"license": "Apache-2.0 OR MIT",
|
6
6
|
"homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/stream-multiplexer-mplex#readme",
|
@@ -61,19 +61,19 @@
|
|
61
61
|
"test:electron-main": "aegir test -t electron-main"
|
62
62
|
},
|
63
63
|
"dependencies": {
|
64
|
-
"@libp2p/interface": "1.0.1-
|
65
|
-
"@libp2p/utils": "5.0.2-
|
64
|
+
"@libp2p/interface": "1.0.1-6d11e8268",
|
65
|
+
"@libp2p/utils": "5.0.2-6d11e8268",
|
66
66
|
"benchmark": "^2.1.4",
|
67
67
|
"it-pushable": "^3.2.1",
|
68
68
|
"it-stream-types": "^2.0.1",
|
69
69
|
"rate-limiter-flexible": "^3.0.0",
|
70
70
|
"uint8-varint": "^2.0.0",
|
71
71
|
"uint8arraylist": "^2.4.3",
|
72
|
-
"uint8arrays": "^
|
72
|
+
"uint8arrays": "^5.0.0"
|
73
73
|
},
|
74
74
|
"devDependencies": {
|
75
|
-
"@libp2p/interface-compliance-tests": "5.0.
|
76
|
-
"@libp2p/logger": "4.0.1-
|
75
|
+
"@libp2p/interface-compliance-tests": "5.0.6-6d11e8268",
|
76
|
+
"@libp2p/logger": "4.0.1-6d11e8268",
|
77
77
|
"aegir": "^41.0.2",
|
78
78
|
"cborg": "^4.0.3",
|
79
79
|
"delay": "^6.0.0",
|