@libp2p/utils 7.0.8 → 7.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -6,8 +6,8 @@ ${e}${n.split(`
6
6
  `).join(`
7
7
  ${e}`)}`:n!=null?`${n.split(`
8
8
  `).join(`
9
- ${e}`)}`:r!=null?`${r}`:`${t.toString()}`}function jf(t){return t instanceof AggregateError||t?.name==="AggregateError"&&Array.isArray(t.errors)}function Bs(t,e=""){if(jf(t)){let r=Fs(t,e);return t.errors.length>0?(e=`${e} `,r+=`${t.errors.map(n=>`
10
- ${e}${Bs(n,`${e}`)}`).join(`
9
+ ${e}`)}`:r!=null?`${r}`:`${t.toString()}`}function jf(t){return t instanceof AggregateError||t?.name==="AggregateError"&&Array.isArray(t.errors)}function Bs(t,e=""){if(jf(t)){let r=Fs(t,e);return t.errors.length>0?(e=`${e} `,r+=`
10
+ ${e}${t.errors.map(n=>`${Bs(n,`${e}`)}`).join(`
11
11
  ${e}`)}`):r+=`
12
12
  ${e}[Error list was empty]`,r.trim()}return Fs(t,e)}z.formatters.e=t=>t==null?"undefined":Bs(t);function Wf(t){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=t,e.destroy=()=>!0,e.extend=()=>e,e}function Mt(t){return{forComponent(e){return Us(e,t)}}}function Us(t,e){let r=Wf(`${t}:trace`);return z.enabled(`${t}:trace`)&&z.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(r=z(`${t}:trace`,e)),Object.assign(z(t,e),{error:z(`${t}:error`,e),trace:r,newScope:n=>Us(`${t}:${n}`,e)})}function ks(t){if(t!=null&&(t=t.trim(),t.length!==0))return t}var Gf=0,Kn=class extends Ne{local;remote;constructor(e){let r=`${Gf++}`;super({...e,id:r,log:Mt().forComponent(`libp2p:stream-pair:${e.direction}:${r}`)}),this.local=e.local,this.remote=e.remote,this.local.addEventListener("drain",()=>{this.safeDispatchEvent("drain")}),this.remote.addEventListener("message",n=>{this.onData(n.data)}),this.remote.addEventListener("reset",n=>{this.onRemoteReset()}),this.remote.addEventListener("closeWrite",n=>{this.onRemoteCloseWrite()})}sendData(e){let r=this.local.send(new ie(e));return{sentBytes:e.byteLength,canSendMore:r}}sendReset(){this.local.send(new Event("reset"))}async sendCloseWrite(e){return M(new Promise((r,n)=>{this.local.send(new Event("closeWrite")),this.local.onIdle().then(r,n)}),e?.signal)}async sendCloseRead(e){return M(new Promise((r,n)=>{this.local.send(new Event("closeRead")),this.local.onIdle().then(r,n)}),e?.signal)}sendPause(){this.local.send(new Event("pause"))}sendResume(){this.local.send(new Event("resume"))}onRemotePaused(){this.local.pause()}onRemoteResumed(){this.local.resume()}onMuxerDrain(){this.local.resume()}};var Ns=Symbol.for("sindresorhus/unlimited-timeout#brand");function Ps(t,e,...r){if(typeof t!="function")throw new TypeError("Expected callback to be a function");e??=0,e=Number(e);let n=!1,o={[Ns]:!0,id:void 0,cleared:!1,ref(){return n=!1,o.id?.ref?.(),o},unref(){return n=!0,o.id?.unref?.(),o}};if(e===Number.POSITIVE_INFINITY||e>Number.MAX_SAFE_INTEGER)return o;(!Number.isFinite(e)||e<0)&&(e=0);let i=performance.now()+e,s=a=>{o.cleared||(a<=2147483647?(o.id=globalThis.setTimeout(()=>{o.cleared||t(...r)},a),n&&o.id?.unref?.()):(o.id=globalThis.setTimeout(()=>{let u=performance.now(),c=Math.max(0,i-u);s(c)},2147483647),n&&o.id?.unref?.()))};return s(e),o}function Ms(t){!t||typeof t!="object"||!t[Ns]||(t.cleared=!0,t.id!==void 0&&(globalThis.clearTimeout(t.id),t.id=void 0))}var Hf=new WeakMap;function Xf({clearTimeout:t,setTimeout:e}={}){return(r,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(o.reason);let i,s,a,u=t??clearTimeout,c=()=>{u(i),a(o.reason)},f=()=>{o&&o.removeEventListener("abort",c)},d=new Promise((h,g)=>{s=()=>{f(),h(n)},a=g,i=(e??setTimeout)(s,r)});return o&&o.addEventListener("abort",c,{once:!0}),Hf.set(d,()=>{u(i),i=null,s()}),d}}var Qf=Xf({setTimeout:Ps,clearTimeout:Ms}),Jn=Qf;var Kf=1024*64,Ot=class extends se{needsDrain;queue;capacity;delay;log;chunkSize;constructor(e){super(),this.needsDrain=!1,this.queue=new re({concurrency:1}),this.capacity=e.capacity??5,this.delay=e.delay??0,this.log=e.log,this.chunkSize=e.chunkSize??Kf,this.queue.addEventListener("idle",()=>{this.needsDrain?(this.log("network send queue drained"),this.needsDrain=!1,this.safeDispatchEvent("drain")):this.log("network send queue idle")})}send(e){if(Jf(e)){let r=new I(e.data);for(;r.byteLength>0;){let n=Math.min(this.chunkSize,r.byteLength),o=r.sublist(0,n);r.consume(o.byteLength);let i=new ie(o);this.queue.add(async s=>{this.delay>0&&await M(Jn(this.delay),s.signal),this.dispatchEvent(s.evt)},{evt:i})}}else this.queue.add(async r=>{this.delay>0&&await M(Jn(this.delay),r.signal),this.dispatchEvent(r.evt)},{evt:e});return this.queue.size>=this.capacity?(this.log("network send queue full"),this.needsDrain=!0,!1):!0}pause(){this.queue.pause()}resume(){this.queue.resume()}onIdle(){return this.queue.onIdle()}size(){return this.queue.size}};function Jf(t){return t?.data instanceof Uint8Array||Qe(t?.data)}var Os=0,Fr=class extends Lt{local;remote;constructor(e){super(e),this.local=e.local,this.remote=e.remote,this.local.addEventListener("drain",()=>{this.safeDispatchEvent("drain")}),this.remote.addEventListener("message",r=>{this.status==="open"&&this.onData(r.data)}),this.remote.addEventListener("reset",r=>{this.status==="open"&&this.onRemoteReset()}),this.remote.addEventListener("close",r=>{this.onTransportClosed()}),this.remote.addEventListener("pause",r=>{this.local.pause()}),this.remote.addEventListener("resume",r=>{this.local.resume()})}sendData(e){let r=this.local.send(new ie(e));return{sentBytes:e.byteLength,canSendMore:r}}sendReset(){this.local.send(new Event("reset"))}async sendClose(e){return this.local.needsDrain&&await T(this.local,"drain",{signal:e?.signal}),M(new Promise((r,n)=>{this.local.send(new Event("close")),this.local.onIdle().then(r,n)}),e?.signal)}sendPause(){this.local.send(new Event("pause"))}sendResume(){this.local.send(new Event("resume"))}};function Yn(t={}){let e=`${Os++}`,r=`${Os++}`,n=Mt().forComponent(`libp2p:mock-maconn:outbound:${e}`),o=Mt().forComponent(`libp2p:mock-maconn:inbound:${r}`),i=new Ot({...t,log:n}),s=new Ot({...t,log:o});return[new Fr({...t.outbound,id:r,direction:"outbound",local:i,remote:s,remoteAddr:t?.outbound?.remoteAddr??Ce(`/ip4/127.0.0.1/tcp/${r}`),log:n}),new Fr({...t.inbound,id:e,direction:"inbound",local:s,remote:i,remoteAddr:t?.inbound?.remoteAddr??Ce(`/ip4/127.0.0.1/tcp/${e}`),log:o})]}var Zn=class extends re{has(e){return this.find(e)!=null}find(e){return this.queue.find(r=>e.equals(r.options.peerId))}};var eo=class extends re{constructor(e={}){super({...e,sort:(r,n)=>r.options.priority>n.options.priority?-1:r.options.priority<n.options.priority?1:0})}};var to=class{memoryStorage;points;duration;blockDuration;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new kr}consume(e,r=1,n={}){let o=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(o,r,i);if(s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.consumedPoints>this.points)throw this.blockDuration>0&&s.consumedPoints<=this.points+r&&(s=this.memoryStorage.set(o,s.consumedPoints,this.blockDuration)),new vt("Rate limit exceeded",s);return s}penalty(e,r=1,n={}){let o=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(o,r,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}reward(e,r=1,n={}){let o=this.getKey(e),i=this._getKeySecDuration(n),s=this.memoryStorage.incrby(o,-r,i);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}block(e,r){let n=r*1e3,o=this.points+1;return this.memoryStorage.set(this.getKey(e),o,r),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:o,isFirstInDuration:!1}}set(e,r,n=0){let o=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),r,n),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:r,isFirstInDuration:!1}}get(e){let r=this.memoryStorage.get(this.getKey(e));return r!=null&&(r.remainingPoints=Math.max(this.points-r.consumedPoints,0)),r}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},kr=class{storage;constructor(){this.storage=new Map}incrby(e,r,n){let o=this.storage.get(e);if(o!=null){let i=o.expiresAt!=null?o.expiresAt.getTime()-new Date().getTime():-1;return o.expiresAt==null||i>0?(o.value+=r,{remainingPoints:0,msBeforeNext:i,consumedPoints:o.value,isFirstInDuration:!1}):this.set(e,r,n)}return this.set(e,r,n)}set(e,r,n){let o=n*1e3,i=this.storage.get(e);i!=null&&clearTimeout(i.timeoutId);let s={value:r,expiresAt:o>0?new Date(Date.now()+o):void 0};return this.storage.set(e,s),o>0&&(s.timeoutId=setTimeout(()=>{this.storage.delete(e)},o),s.timeoutId.unref!=null&&s.timeoutId.unref()),{remainingPoints:0,msBeforeNext:o===0?-1:o,consumedPoints:s.value,isFirstInDuration:!0}}get(e){let r=this.storage.get(e);if(r!=null)return{remainingPoints:0,msBeforeNext:r.expiresAt!=null?r.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:r.value,isFirstInDuration:!1}}delete(e){let r=this.storage.get(e);return r!=null?(r.timeoutId!=null&&clearTimeout(r.timeoutId),this.storage.delete(e),!0):!1}};function Yf(t,e,r){let n,o,i=!1;function s(){let c={signal:o.signal};if(r?.timeout!=null){let f=rr([o.signal,AbortSignal.timeout(r.timeout)]);c.signal=f}i=!0,Promise.resolve().then(async()=>{await t(c)}).catch(()=>{}).finally(()=>{i=!1,!o.signal.aborted&&(n=setTimeout(s,e))})}let a=Ze(s,r?.debounce??100),u=!1;return{setInterval:c=>{e!==c&&(e=c,n!=null&&(clearTimeout(n),n=setTimeout(s,e)))},setTimeout:c=>{r??={},r.timeout=c},run:()=>{i||(clearTimeout(n),a())},start:()=>{u||(u=!0,o=new AbortController,o.signal,r?.runImmediately===!0?queueMicrotask(()=>{s()}):n=setTimeout(s,e))},stop:()=>{clearTimeout(n),o?.abort(),u=!1}}}async function $s(t={}){let[e,r]=Yn({...t,outbound:t.outboundConnection,inbound:t.inboundConnection}),n=Ar({streamOptions:t.outbound}).createStreamMuxer(e),o=Ar({streamOptions:t.inbound}).createStreamMuxer(r),[i,s]=await Promise.all([T(o,"stream").then(a=>a.detail),n.createStream({...t.outbound,protocol:t.protocol})]);return[s,i]}async function Zf(t={}){let[e,r]=await $s(t);return kn(r),e}function el(t){let{name:e,metrics:r}=t,n=[];return r?.registerMetric(e,{calculate:()=>n.length}),n}var ro=class extends Map{metric;constructor(e){super();let{name:r,metrics:n}=e;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,r){return super.set(e,r),this.updateComponentMetric(),this}delete(e){let r=super.delete(e);return this.updateComponentMetric(),r}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function tl(t){let{name:e,metrics:r}=t,n;return r!=null?n=new ro({name:e,metrics:r}):n=new Map,n}return Xs(rl);})();
13
13
  /*! Bundled license information: