@libp2p/simple-metrics 1.3.3 → 1.3.4

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
@@ -1,4 +1,4 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PSimpleMetrics = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
2
  "use strict";var Libp2PSimpleMetrics=(()=>{var Ve=Object.create;var I=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Oe=Object.getPrototypeOf,je=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),$e=(t,e)=>{for(var r in e)I(t,r,{get:e[r],enumerable:!0})},ie=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ue(e))!je.call(t,i)&&i!==r&&I(t,i,{get:()=>e[i],enumerable:!(n=ze(e,i))||n.enumerable});return t};var Ne=(t,e,r)=>(r=t!=null?Ve(Oe(t)):{},ie(e||!t||!t.__esModule?I(r,"default",{value:t,enumerable:!0}):r,t)),Te=t=>ie(I({},"__esModule",{value:!0}),t);var re=j((Fr,_e)=>{function M(){}M.prototype.clear=function(){this._root=null,this.size=0};M.prototype.find=function(t){for(var e=this._root;e!==null;){var r=this._comparator(t,e.data);if(r===0)return e.data;e=e.get_child(r>0)}return null};M.prototype.findIter=function(t){for(var e=this._root,r=this.iterator();e!==null;){var n=this._comparator(t,e.data);if(n===0)return r._cursor=e,r;r._ancestors.push(e),e=e.get_child(n>0)}return null};M.prototype.lowerBound=function(t){for(var e=this._root,r=this.iterator(),n=this._comparator;e!==null;){var i=n(t,e.data);if(i===0)return r._cursor=e,r;r._ancestors.push(e),e=e.get_child(i>0)}for(var o=r._ancestors.length-1;o>=0;--o)if(e=r._ancestors[o],n(t,e.data)<0)return r._cursor=e,r._ancestors.length=o,r;return r._ancestors.length=0,r};M.prototype.upperBound=function(t){for(var e=this.lowerBound(t),r=this._comparator;e.data()!==null&&r(e.data(),t)===0;)e.next();return e};M.prototype.min=function(){var t=this._root;if(t===null)return null;for(;t.left!==null;)t=t.left;return t.data};M.prototype.max=function(){var t=this._root;if(t===null)return null;for(;t.right!==null;)t=t.right;return t.data};M.prototype.iterator=function(){return new U(this)};M.prototype.each=function(t){for(var e=this.iterator(),r;(r=e.next())!==null;)if(t(r)===!1)return};M.prototype.reach=function(t){for(var e=this.iterator(),r;(r=e.prev())!==null;)if(t(r)===!1)return};function U(t){this._tree=t,this._ancestors=[],this._cursor=null}U.prototype.data=function(){return this._cursor!==null?this._cursor.data:null};U.prototype.next=function(){if(this._cursor===null){var t=this._tree._root;t!==null&&this._minNode(t)}else if(this._cursor.right===null){var e;do if(e=this._cursor,this._ancestors.length)this._cursor=this._ancestors.pop();else{this._cursor=null;break}while(this._cursor.right===e)}else this._ancestors.push(this._cursor),this._minNode(this._cursor.right);return this._cursor!==null?this._cursor.data:null};U.prototype.prev=function(){if(this._cursor===null){var t=this._tree._root;t!==null&&this._maxNode(t)}else if(this._cursor.left===null){var e;do if(e=this._cursor,this._ancestors.length)this._cursor=this._ancestors.pop();else{this._cursor=null;break}while(this._cursor.left===e)}else this._ancestors.push(this._cursor),this._maxNode(this._cursor.left);return this._cursor!==null?this._cursor.data:null};U.prototype._minNode=function(t){for(;t.left!==null;)this._ancestors.push(t),t=t.left;this._cursor=t};U.prototype._maxNode=function(t){for(;t.right!==null;)this._ancestors.push(t),t=t.right;this._cursor=t};_e.exports=M});var ve=j((kr,ye)=>{var ot=re();function O(t){this.data=t,this.left=null,this.right=null,this.red=!0}O.prototype.get_child=function(t){return t?this.right:this.left};O.prototype.set_child=function(t,e){t?this.right=e:this.left=e};function J(t){this._root=null,this._comparator=t,this.size=0}J.prototype=new ot;J.prototype.insert=function(t){var e=!1;if(this._root===null)this._root=new O(t),e=!0,this.size++;else{var r=new O(void 0),n=0,i=0,o=null,u=r,c=null,a=this._root;for(u.right=this._root;;){if(a===null?(a=new O(t),c.set_child(n,a),e=!0,this.size++):A(a.left)&&A(a.right)&&(a.red=!0,a.left.red=!1,a.right.red=!1),A(a)&&A(c)){var g=u.right===o;a===c.get_child(i)?u.set_child(g,$(o,!i)):u.set_child(g,we(o,!i))}var s=this._comparator(a.data,t);if(s===0)break;i=n,n=s<0,o!==null&&(u=o),o=c,c=a,a=a.get_child(n)}this._root=r.right}return this._root.red=!1,e};J.prototype.remove=function(t){if(this._root===null)return!1;var e=new O(void 0),r=e;r.right=this._root;for(var n=null,i=null,o=null,u=1;r.get_child(u)!==null;){var c=u;i=n,n=r,r=r.get_child(u);var a=this._comparator(t,r.data);if(u=a>0,a===0&&(o=r),!A(r)&&!A(r.get_child(u))){if(A(r.get_child(!u))){var g=$(r,u);n.set_child(c,g),n=g}else if(!A(r.get_child(!u))){var s=n.get_child(!c);if(s!==null)if(!A(s.get_child(!c))&&!A(s.get_child(c)))n.red=!1,s.red=!0,r.red=!0;else{var l=i.right===n;A(s.get_child(c))?i.set_child(l,we(n,c)):A(s.get_child(!c))&&i.set_child(l,$(n,c));var f=i.get_child(l);f.red=!0,r.red=!0,f.left.red=!1,f.right.red=!1}}}}return o!==null&&(o.data=r.data,n.set_child(n.right===r,r.get_child(r.left===null)),this.size--),this._root=e.right,this._root!==null&&(this._root.red=!1),o!==null};function A(t){return t!==null&&t.red}function $(t,e){var r=t.get_child(!e);return t.set_child(!e,r.get_child(e)),r.set_child(e,t),t.red=!0,r.red=!1,r}function we(t,e){return t.set_child(!e,$(t.get_child(!e),!e)),$(t,e)}ye.exports=J});var xe=j((Ar,Ce)=>{var at=re();function N(t){this.data=t,this.left=null,this.right=null}N.prototype.get_child=function(t){return t?this.right:this.left};N.prototype.set_child=function(t,e){t?this.right=e:this.left=e};function Q(t){this._root=null,this._comparator=t,this.size=0}Q.prototype=new at;Q.prototype.insert=function(t){if(this._root===null)return this._root=new N(t),this.size++,!0;for(var e=0,r=null,n=this._root;;){if(n===null)return n=new N(t),r.set_child(e,n),ret=!0,this.size++,!0;if(this._comparator(n.data,t)===0)return!1;e=this._comparator(n.data,t)<0,r=n,n=n.get_child(e)}};Q.prototype.remove=function(t){if(this._root===null)return!1;var e=new N(void 0),r=e;r.right=this._root;for(var n=null,i=null,o=1;r.get_child(o)!==null;){n=r,r=r.get_child(o);var u=this._comparator(t,r.data);o=u>0,u===0&&(i=r)}return i!==null?(i.data=r.data,n.set_child(n.right===r,r.get_child(r.left===null)),this._root=e.right,this.size--,!0):!1};Ce.exports=Q});var ke=j((Er,Fe)=>{Fe.exports={RBTree:ve(),BinTree:xe()}});var Me=j((Mr,Ee)=>{var ut=ke().RBTree;function p(t,e,r){this.discrete=t===!1,this.delta=t||.01,this.K=e===void 0?25:e,this.CX=r===void 0?1.1:r,this.centroids=new ut(Ae),this.nreset=0,this.reset()}p.prototype.reset=function(){this.centroids.clear(),this.n=0,this.nreset+=1,this.last_cumulate=0};p.prototype.size=function(){return this.centroids.size};p.prototype.toArray=function(t){var e=[];return t?(this._cumulate(!0),this.centroids.each(function(r){e.push(r)})):this.centroids.each(function(r){e.push({mean:r.mean,n:r.n})}),e};p.prototype.summary=function(){var t=this.discrete?"exact ":"approximating ",e=[t+this.n+" samples using "+this.size()+" centroids","min = "+this.percentile(0),"Q1 = "+this.percentile(.25),"Q2 = "+this.percentile(.5),"Q3 = "+this.percentile(.75),"max = "+this.percentile(1)];return e.join(`
3
- `)};function Ae(t,e){return t.mean>e.mean?1:t.mean<e.mean?-1:0}function ct(t,e){return t.mean_cumn-e.mean_cumn}p.prototype.push=function(t,e){e=e||1,t=Array.isArray(t)?t:[t];for(var r=0;r<t.length;r++)this._digest(t[r],e)};p.prototype.push_centroid=function(t){t=Array.isArray(t)?t:[t];for(var e=0;e<t.length;e++)this._digest(t[e].mean,t[e].n)};p.prototype._cumulate=function(t){if(!(this.n===this.last_cumulate||!t&&this.CX&&this.CX>this.n/this.last_cumulate)){var e=0;this.centroids.each(function(r){r.mean_cumn=e+r.n/2,e=r.cumn=e+r.n}),this.n=this.last_cumulate=e}};p.prototype.find_nearest=function(t){if(this.size()===0)return null;var e=this.centroids.lowerBound({mean:t}),r=e.data()===null?e.prev():e.data();if(r.mean===t||this.discrete)return r;var n=e.prev();return n&&Math.abs(n.mean-t)<Math.abs(r.mean-t)?n:r};p.prototype._new_centroid=function(t,e,r){var n={mean:t,n:e,cumn:r};return this.centroids.insert(n),this.n+=e,n};p.prototype._addweight=function(t,e,r){e!==t.mean&&(t.mean+=r*(e-t.mean)/(t.n+r)),t.cumn+=r,t.mean_cumn+=r/2,t.n+=r,this.n+=r};p.prototype._digest=function(t,e){var r=this.centroids.min(),n=this.centroids.max(),i=this.find_nearest(t);if(i&&i.mean===t)this._addweight(i,t,e);else if(i===r)this._new_centroid(t,e,0);else if(i===n)this._new_centroid(t,e,this.n);else if(this.discrete)this._new_centroid(t,e,i.cumn);else{var o=i.mean_cumn/this.n,u=Math.floor(4*this.n*this.delta*o*(1-o));u-i.n>=e?this._addweight(i,t,e):this._new_centroid(t,e,i.cumn)}this._cumulate(!1),!this.discrete&&this.K&&this.size()>this.K/this.delta&&this.compress()};p.prototype.bound_mean=function(t){var e=this.centroids.upperBound({mean:t}),r=e.prev(),n=r.mean===t?r:e.next();return[r,n]};p.prototype.p_rank=function(t){var e=Array.isArray(t)?t:[t],r=e.map(this._p_rank,this);return Array.isArray(t)?r:r[0]};p.prototype._p_rank=function(t){if(this.size()!==0){{if(t<this.centroids.min().mean)return 0;if(t>this.centroids.max().mean)return 1}this._cumulate(!0);var e=this.bound_mean(t),r=e[0],n=e[1];if(this.discrete)return r.cumn/this.n;var i=r.mean_cumn;return r!==n&&(i+=(t-r.mean)*(n.mean_cumn-r.mean_cumn)/(n.mean-r.mean)),i/this.n}};p.prototype.bound_mean_cumn=function(t){this.centroids._comparator=ct;var e=this.centroids.upperBound({mean_cumn:t});this.centroids._comparator=Ae;var r=e.prev(),n=r&&r.mean_cumn===t?r:e.next();return[r,n]};p.prototype.percentile=function(t){var e=Array.isArray(t)?t:[t],r=e.map(this._percentile,this);return Array.isArray(t)?r:r[0]};p.prototype._percentile=function(t){if(this.size()!==0){this._cumulate(!0);var e=this.n*t,r=this.bound_mean_cumn(e),n=r[0],i=r[1];return i===n||n===null||i===null?(n||i).mean:this.discrete?e<=n.cumn?n.mean:i.mean:n.mean+(e-n.mean_cumn)*(i.mean-n.mean)/(i.mean_cumn-n.mean_cumn)}};function lt(t){var e=Math.floor(Math.random()*t.length);return t.splice(e,1)[0]}p.prototype.compress=function(){if(!this.compressing){var t=this.toArray();for(this.reset(),this.compressing=!0;t.length>0;)this.push_centroid(lt(t));this._cumulate(!0),this.compressing=!1}};function S(t){this.config=t||{},this.mode=this.config.mode||"auto",p.call(this,this.mode==="cont"?t.delta:!1),this.digest_ratio=this.config.ratio||.9,this.digest_thresh=this.config.thresh||1e3,this.n_unique=0}S.prototype=Object.create(p.prototype);S.prototype.constructor=S;S.prototype.push=function(t){p.prototype.push.call(this,t),this.check_continuous()};S.prototype._new_centroid=function(t,e,r){this.n_unique+=1,p.prototype._new_centroid.call(this,t,e,r)};S.prototype._addweight=function(t,e,r){t.n===1&&(this.n_unique-=1),p.prototype._addweight.call(this,t,e,r)};S.prototype.check_continuous=function(){return this.mode!=="auto"||this.size()<this.digest_thresh?!1:this.n_unique/this.size()>this.digest_ratio?(this.mode="cont",this.discrete=!1,this.delta=this.config.delta||.01,this.compress(),!0):!1};Ee.exports={TDigest:p,Digest:S}});var dt={};$e(dt,{simpleMetrics:()=>ft});var se=Symbol.for("@libp2p/service-capabilities"),mt=Symbol.for("@libp2p/service-dependencies");var qt=new Uint8Array(0);function oe(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function qe(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),u=o.charCodeAt(0);if(r[u]!==255)throw new TypeError(o+" is ambiguous");r[u]=i}var c=t.length,a=t.charAt(0),g=Math.log(c)/Math.log(256),s=Math.log(256)/Math.log(c);function l(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var d=0,m=0,b=0,w=h.length;b!==w&&h[b]===0;)b++,d++;for(var x=(w-b)*s+1>>>0,_=new Uint8Array(x);b!==w;){for(var E=h[b],F=0,C=x-1;(E!==0||F<m)&&C!==-1;C--,F++)E+=256*_[C]>>>0,_[C]=E%c>>>0,E=E/c>>>0;if(E!==0)throw new Error("Non-zero carry");m=F,b++}for(var k=x-m;k!==x&&_[k]===0;)k++;for(var z=a.repeat(d);k<x;++k)z+=t.charAt(_[k]);return z}function f(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var d=0;if(h[d]!==" "){for(var m=0,b=0;h[d]===a;)m++,d++;for(var w=(h.length-d)*g+1>>>0,x=new Uint8Array(w);h[d];){var _=r[h.charCodeAt(d)];if(_===255)return;for(var E=0,F=w-1;(_!==0||E<b)&&F!==-1;F--,E++)_+=c*x[F]>>>0,x[F]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");b=E,d++}if(h[d]!==" "){for(var C=w-b;C!==w&&x[C]===0;)C++;for(var k=new Uint8Array(m+(w-C)),z=m;C!==w;)k[z++]=x[C++];return k}}}function V(h){var d=f(h);if(d)return d;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:f,decode:V}}var De=qe,Be=De,ae=Be;var K=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Z=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let i=r.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ue(this,e)}},W=class{decoders;constructor(e){this.decoders=e}or(e){return ue(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ue(t,e){return new W({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var Y=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new K(e,r,n),this.decoder=new Z(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ce({name:t,prefix:e,encode:r,decode:n}){return new Y(t,e,r,n)}function H({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=ae(r,t);return ce({prefix:e,name:t,encode:n,decode:o=>oe(i(o))})}function Ie(t,e,r,n){let i={};for(let s=0;s<e.length;++s)i[e[s]]=s;let o=t.length;for(;t[o-1]==="=";)--o;let u=new Uint8Array(o*r/8|0),c=0,a=0,g=0;for(let s=0;s<o;++s){let l=i[t[s]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|l,c+=r,c>=8&&(c-=8,u[g++]=255&a>>c)}if(c>=r||255&a<<8-c)throw new SyntaxError("Unexpected end of data");return u}function Pe(t,e,r){let n=e[e.length-1]==="=",i=(1<<r)-1,o="",u=0,c=0;for(let a=0;a<t.length;++a)for(c=c<<8|t[a],u+=8;u>r;)u-=r,o+=e[i&c>>u];if(u!==0&&(o+=e[i&c<<r-u]),n)for(;o.length*r&7;)o+="=";return o}function y({name:t,prefix:e,bitsPerChar:r,alphabet:n}){return ce({prefix:e,name:t,encode(i){return Pe(i,n,r)},decode(i){return Ie(i,n,r,t)}})}var le=y({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Jt=y({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Qt=y({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Xt=y({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Gt=y({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Kt=y({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Zt=y({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Wt=y({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Yt=y({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var he=H({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),tr=H({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var fe=y({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ir=y({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),sr=y({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),or=y({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function Le(t,e){try{if(typeof t=="string"&&t.length>0)return Re(t);if(typeof t=="number"&&isFinite(t))return e?.long?Qe(t):Je(t);throw new Error("Value is not a string or number.")}catch(r){let n=Xe(r)?`${r.message}. value=${JSON.stringify(t)}`:"An unknown error has occured.";throw new Error(n)}}function Re(t){if(t=String(t),t.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(!e)return NaN;let r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*315576e5;case"weeks":case"week":case"w":return r*6048e5;case"days":case"day":case"d":return r*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return r*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return r*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return r*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var L=Le;function Je(t){let e=Math.abs(t);return e>=864e5?`${Math.round(t/864e5)}d`:e>=36e5?`${Math.round(t/36e5)}h`:e>=6e4?`${Math.round(t/6e4)}m`:e>=1e3?`${Math.round(t/1e3)}s`:`${t}ms`}function Qe(t){let e=Math.abs(t);return e>=864e5?P(t,e,864e5,"day"):e>=36e5?P(t,e,36e5,"hour"):e>=6e4?P(t,e,6e4,"minute"):e>=1e3?P(t,e,1e3,"second"):`${t} ms`}function P(t,e,r,n){let i=e>=r*1.5;return`${Math.round(t/r)} ${n}${i?"s":""}`}function Xe(t){return typeof t=="object"&&t!==null&&"message"in t}function ee(t){r.debug=r,r.default=r,r.coerce=a,r.disable=o,r.enable=i,r.enabled=u,r.humanize=L,r.destroy=g,Object.keys(t).forEach(s=>{r[s]=t[s]}),r.names=[],r.skips=[],r.formatters={};function e(s){let l=0;for(let f=0;f<s.length;f++)l=(l<<5)-l+s.charCodeAt(f),l|=0;return r.colors[Math.abs(l)%r.colors.length]}r.selectColor=e;function r(s){let l,f=null,V,h;function d(...m){if(!d.enabled)return;let b=d,w=Number(new Date),x=w-(l||w);b.diff=x,b.prev=l,b.curr=w,l=w,m[0]=r.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let _=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(F,C)=>{if(F==="%%")return"%";_++;let k=r.formatters[C];if(typeof k=="function"){let z=m[_];F=k.call(b,z),m.splice(_,1),_--}return F}),r.formatArgs.call(b,m),(b.log||r.log).apply(b,m)}return d.namespace=s,d.useColors=r.useColors(),d.color=r.selectColor(s),d.extend=n,d.destroy=r.destroy,Object.defineProperty(d,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(V!==r.namespaces&&(V=r.namespaces,h=r.enabled(s)),h),set:m=>{f=m}}),typeof r.init=="function"&&r.init(d),d}function n(s,l){let f=r(this.namespace+(typeof l>"u"?":":l)+s);return f.log=this.log,f}function i(s){r.save(s),r.namespaces=s,r.names=[],r.skips=[];let l,f=(typeof s=="string"?s:"").split(/[\s,]+/),V=f.length;for(l=0;l<V;l++)f[l]&&(s=f[l].replace(/\*/g,".*?"),s[0]==="-"?r.skips.push(new RegExp("^"+s.substr(1)+"$")):r.names.push(new RegExp("^"+s+"$")))}function o(){let s=[...r.names.map(c),...r.skips.map(c).map(l=>"-"+l)].join(",");return r.enable(""),s}function u(s){if(s[s.length-1]==="*")return!0;let l,f;for(l=0,f=r.skips.length;l<f;l++)if(r.skips[l].test(s))return!1;for(l=0,f=r.names.length;l<f;l++)if(r.names[l].test(s))return!0;return!1}function c(s){return s.toString().substring(2,s.toString().length-2).replace(/\.\*\?$/,"*")}function a(s){return s instanceof Error?s.stack??s.message:s}function g(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.setupFormatters(r.formatters),r.enable(r.load()),r}var R=et(),Ge=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Ke(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function Ze(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+L(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(r++,i==="%c"&&(n=r))}),t.splice(n,0,e)}var We=console.debug??console.log??(()=>{});function Ye(t){try{t?R?.setItem("debug",t):R?.removeItem("debug")}catch{}}function He(){let t;try{t=R?.getItem("debug")}catch{}return!t&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(t=globalThis.process.env.DEBUG),t}function et(){try{return localStorage}catch{}}function tt(t){t.j=function(e){try{return JSON.stringify(e)}catch(r){return"[UnexpectedJSONParseError]: "+r.message}}}var de=ee({formatArgs:Ze,save:Ye,load:He,useColors:Ke,setupFormatters:tt,colors:Ge,storage:R,log:We});var v=de;v.formatters.b=t=>t==null?"undefined":he.baseEncode(t);v.formatters.t=t=>t==null?"undefined":le.baseEncode(t);v.formatters.m=t=>t==null?"undefined":fe.baseEncode(t);v.formatters.p=t=>t==null?"undefined":t.toString();v.formatters.c=t=>t==null?"undefined":t.toString();v.formatters.k=t=>t==null?"undefined":t.toString();v.formatters.a=t=>t==null?"undefined":t.toString();v.formatters.e=t=>t==null?"undefined":pe(t.stack)??pe(t.message)??t.toString();function rt(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 me(t){let e=rt(`${t}:trace`);return v.enabled(`${t}:trace`)&&v.names.map(r=>r.toString()).find(r=>r.includes(":trace"))!=null&&(e=v(`${t}:trace`)),Object.assign(v(t),{error:v(`${t}:error`),trace:e})}function pe(t){if(t!=null&&(t=t.trim(),t.length!==0))return t}function nt(t){let[e,r]=t[Symbol.asyncIterator]!=null?[t[Symbol.asyncIterator](),Symbol.asyncIterator]:[t[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[r](){return this}}}var be=nt;function it(t){return t[Symbol.asyncIterator]!=null}function ge(t){return t?.then!=null}function st(t,e){let r=0;if(it(t))return async function*(){for await(let a of t){let g=e(a,r++);ge(g)&&await g,yield a}}();let n=be(t),{value:i,done:o}=n.next();if(o===!0)return function*(){}();if(typeof e(i,r++)?.then=="function")return async function*(){yield i;for await(let a of n){let g=e(a,r++);ge(g)&&await g,yield a}}();let c=e;return function*(){yield i;for(let a of n)c(a,r++),yield a}()}var te=st;var Se=Ne(Me(),1),ht=me("libp2p:simple-metrics"),T=class{value=0;update(e){this.value=e}increment(e=1){this.value+=e}decrement(e=1){this.value-=e}reset(){this.value=0}timer(){let e=Date.now();return()=>{this.value=Date.now()-e}}},q=class{values={};update(e){Object.entries(e).forEach(([r,n])=>{this.values[r]=n})}increment(e){Object.entries(e).forEach(([r,n])=>{this.values[r]=this.values[r]??0;let i=typeof n=="number"?n:1;this.values[r]+=Number(i)})}decrement(e){Object.entries(e).forEach(([r,n])=>{this.values[r]=this.values[r]??0;let i=typeof n=="number"?n:1;this.values[r]-=Number(i)})}reset(){this.values={}}timer(e){let r=Date.now();return()=>{this.values[e]=Date.now()-r}}},D=class{bucketValues=new Map;countValue=0;sumValue=0;constructor(e){let r=[...e.buckets??[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10],1/0];for(let n of r)this.bucketValues.set(n,0)}observe(e){this.countValue++,this.sumValue+=e;for(let[r,n]of this.bucketValues.entries())e<=r&&this.bucketValues.set(r,n+1)}reset(){this.countValue=0,this.sumValue=0;for(let e of this.bucketValues.keys())this.bucketValues.set(e,0)}timer(){let e=Date.now();return()=>{this.observe(Date.now()-e)}}},X=class{histograms={};constructor(e){this.histograms={}}observe(e){for(let[r,n]of Object.entries(e))this.histograms[r]===void 0&&(this.histograms[r]=new D({})),this.histograms[r].observe(n)}reset(){for(let e of Object.values(this.histograms))e.reset()}timer(e){let r=Date.now();return()=>{this.observe({[e]:Date.now()-r})}}},B=class{sumValue=0;countValue=0;percentiles;tdigest=new Se.TDigest(.01);compressCount;constructor(e){this.percentiles=e.percentiles??[.01,.05,.5,.9,.95,.99,.999],this.compressCount=e.compressCount??1e3}observe(e){this.sumValue+=e,this.countValue++,this.tdigest.push(e),this.tdigest.size()>this.compressCount&&this.tdigest.compress()}reset(){this.sumValue=0,this.countValue=0,this.tdigest.reset()}timer(){let e=Date.now();return()=>{this.observe(Date.now()-e)}}},G=class{summaries={};opts;constructor(e){this.summaries={},this.opts=e}observe(e){for(let[r,n]of Object.entries(e))this.summaries[r]===void 0&&(this.summaries[r]=new B(this.opts)),this.summaries[r].observe(n)}reset(){for(let e of Object.values(this.summaries))e.reset()}timer(e){let r=Date.now();return()=>{this.observe({[e]:Date.now()-r})}}},ne=class{metrics=new Map;transferStats;started;interval;intervalMs;onMetrics;constructor(e,r){this.started=!1,this._emitMetrics=this._emitMetrics.bind(this),this.intervalMs=r.intervalMs??1e3,this.onMetrics=r.onMetrics,this.transferStats=new Map}[Symbol.toStringTag]="@libp2p/metrics-simple";[se]=["@libp2p/metrics"];isStarted(){return this.started}start(){this.started=!0,this.interval=setInterval(this._emitMetrics,this.intervalMs)}stop(){this.started=!1,clearInterval(this.interval)}_emitMetrics(){Promise.resolve().then(async()=>{let e={};for(let[r,n]of this.metrics.entries())n instanceof T?e[r]=n.value:n instanceof q?e[r]=n.values:n instanceof D?e[r]={count:n.countValue,sum:n.sumValue,buckets:{...n.bucketValues}}:n instanceof X?e[r]={...Object.fromEntries(Object.entries(n.histograms).map(([i,o])=>[i,{count:o.countValue,sum:o.sumValue,buckets:{...o.bucketValues}}]))}:n instanceof B?e[r]={count:n.countValue,sum:n.sumValue,percentiles:Object.fromEntries(n.percentiles.map(i=>[i,n.tdigest.percentile(i)]))}:n instanceof G?e[r]={...Object.fromEntries(Object.entries(n.summaries).map(([i,o])=>[i,{count:o.countValue,sum:o.sumValue,percentiles:Object.fromEntries(o.percentiles.map(u=>[u,o.tdigest.percentile(u)]))}]))}:e[r]=await n();this.onMetrics(structuredClone(e))}).catch(e=>{ht.error("could not invoke onMetrics callback",e)})}_incrementValue(e,r){let n=this.transferStats.get(e)??0;this.transferStats.set(e,n+r)}_track(e,r){let n=this,i=e.sink;e.sink=async function(c){await i(te(c,a=>{n._incrementValue(`${r} sent`,a.byteLength)}))};let o=e.source;e.source=te(o,u=>{n._incrementValue(`${r} received`,u.byteLength)})}trackMultiaddrConnection(e){this._track(e,"global")}trackProtocolStream(e,r){e.protocol!=null&&this._track(e,e.protocol)}registerMetric(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(r?.calculate!=null){this.metrics.set(e,r.calculate);return}let n=new T;return this.metrics.set(e,n),n}registerMetricGroup(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(r?.calculate!=null){this.metrics.set(e,r.calculate);return}let n=new q;return this.metrics.set(e,n),n}registerCounter(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(r?.calculate!=null){this.metrics.set(e,r.calculate);return}let n=new T;return this.metrics.set(e,n),n}registerCounterGroup(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(r?.calculate!=null){this.metrics.set(e,r.calculate);return}let n=new q;return this.metrics.set(e,n),n}registerHistogram(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(r?.calculate!=null){this.metrics.set(e,r.calculate);return}let n=new D(r);return this.metrics.set(e,n),n}registerHistogramGroup(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(r?.calculate!=null){this.metrics.set(e,r.calculate);return}let n=new X(r);return this.metrics.set(e,n),n}registerSummary(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(r?.calculate!=null){this.metrics.set(e,r.calculate);return}let n=new B(r);return this.metrics.set(e,n),n}registerSummaryGroup(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(r?.calculate!=null){this.metrics.set(e,r.calculate);return}let n=new G(r);return this.metrics.set(e,n),n}createTrace(){}traceFunction(e,r){return r}};function ft(t){return e=>new ne(e,t)}return Te(dt);})();
3
+ `)};function Ae(t,e){return t.mean>e.mean?1:t.mean<e.mean?-1:0}function ct(t,e){return t.mean_cumn-e.mean_cumn}p.prototype.push=function(t,e){e=e||1,t=Array.isArray(t)?t:[t];for(var r=0;r<t.length;r++)this._digest(t[r],e)};p.prototype.push_centroid=function(t){t=Array.isArray(t)?t:[t];for(var e=0;e<t.length;e++)this._digest(t[e].mean,t[e].n)};p.prototype._cumulate=function(t){if(!(this.n===this.last_cumulate||!t&&this.CX&&this.CX>this.n/this.last_cumulate)){var e=0;this.centroids.each(function(r){r.mean_cumn=e+r.n/2,e=r.cumn=e+r.n}),this.n=this.last_cumulate=e}};p.prototype.find_nearest=function(t){if(this.size()===0)return null;var e=this.centroids.lowerBound({mean:t}),r=e.data()===null?e.prev():e.data();if(r.mean===t||this.discrete)return r;var n=e.prev();return n&&Math.abs(n.mean-t)<Math.abs(r.mean-t)?n:r};p.prototype._new_centroid=function(t,e,r){var n={mean:t,n:e,cumn:r};return this.centroids.insert(n),this.n+=e,n};p.prototype._addweight=function(t,e,r){e!==t.mean&&(t.mean+=r*(e-t.mean)/(t.n+r)),t.cumn+=r,t.mean_cumn+=r/2,t.n+=r,this.n+=r};p.prototype._digest=function(t,e){var r=this.centroids.min(),n=this.centroids.max(),i=this.find_nearest(t);if(i&&i.mean===t)this._addweight(i,t,e);else if(i===r)this._new_centroid(t,e,0);else if(i===n)this._new_centroid(t,e,this.n);else if(this.discrete)this._new_centroid(t,e,i.cumn);else{var o=i.mean_cumn/this.n,u=Math.floor(4*this.n*this.delta*o*(1-o));u-i.n>=e?this._addweight(i,t,e):this._new_centroid(t,e,i.cumn)}this._cumulate(!1),!this.discrete&&this.K&&this.size()>this.K/this.delta&&this.compress()};p.prototype.bound_mean=function(t){var e=this.centroids.upperBound({mean:t}),r=e.prev(),n=r.mean===t?r:e.next();return[r,n]};p.prototype.p_rank=function(t){var e=Array.isArray(t)?t:[t],r=e.map(this._p_rank,this);return Array.isArray(t)?r:r[0]};p.prototype._p_rank=function(t){if(this.size()!==0){{if(t<this.centroids.min().mean)return 0;if(t>this.centroids.max().mean)return 1}this._cumulate(!0);var e=this.bound_mean(t),r=e[0],n=e[1];if(this.discrete)return r.cumn/this.n;var i=r.mean_cumn;return r!==n&&(i+=(t-r.mean)*(n.mean_cumn-r.mean_cumn)/(n.mean-r.mean)),i/this.n}};p.prototype.bound_mean_cumn=function(t){this.centroids._comparator=ct;var e=this.centroids.upperBound({mean_cumn:t});this.centroids._comparator=Ae;var r=e.prev(),n=r&&r.mean_cumn===t?r:e.next();return[r,n]};p.prototype.percentile=function(t){var e=Array.isArray(t)?t:[t],r=e.map(this._percentile,this);return Array.isArray(t)?r:r[0]};p.prototype._percentile=function(t){if(this.size()!==0){this._cumulate(!0);var e=this.n*t,r=this.bound_mean_cumn(e),n=r[0],i=r[1];return i===n||n===null||i===null?(n||i).mean:this.discrete?e<=n.cumn?n.mean:i.mean:n.mean+(e-n.mean_cumn)*(i.mean-n.mean)/(i.mean_cumn-n.mean_cumn)}};function lt(t){var e=Math.floor(Math.random()*t.length);return t.splice(e,1)[0]}p.prototype.compress=function(){if(!this.compressing){var t=this.toArray();for(this.reset(),this.compressing=!0;t.length>0;)this.push_centroid(lt(t));this._cumulate(!0),this.compressing=!1}};function S(t){this.config=t||{},this.mode=this.config.mode||"auto",p.call(this,this.mode==="cont"?t.delta:!1),this.digest_ratio=this.config.ratio||.9,this.digest_thresh=this.config.thresh||1e3,this.n_unique=0}S.prototype=Object.create(p.prototype);S.prototype.constructor=S;S.prototype.push=function(t){p.prototype.push.call(this,t),this.check_continuous()};S.prototype._new_centroid=function(t,e,r){this.n_unique+=1,p.prototype._new_centroid.call(this,t,e,r)};S.prototype._addweight=function(t,e,r){t.n===1&&(this.n_unique-=1),p.prototype._addweight.call(this,t,e,r)};S.prototype.check_continuous=function(){return this.mode!=="auto"||this.size()<this.digest_thresh?!1:this.n_unique/this.size()>this.digest_ratio?(this.mode="cont",this.discrete=!1,this.delta=this.config.delta||.01,this.compress(),!0):!1};Ee.exports={TDigest:p,Digest:S}});var dt={};$e(dt,{simpleMetrics:()=>ft});var se=Symbol.for("@libp2p/service-capabilities"),mt=Symbol.for("@libp2p/service-dependencies");var qt=new Uint8Array(0);function oe(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}function qe(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),u=o.charCodeAt(0);if(r[u]!==255)throw new TypeError(o+" is ambiguous");r[u]=i}var c=t.length,a=t.charAt(0),g=Math.log(c)/Math.log(256),s=Math.log(256)/Math.log(c);function l(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var d=0,m=0,b=0,w=h.length;b!==w&&h[b]===0;)b++,d++;for(var x=(w-b)*s+1>>>0,_=new Uint8Array(x);b!==w;){for(var E=h[b],F=0,C=x-1;(E!==0||F<m)&&C!==-1;C--,F++)E+=256*_[C]>>>0,_[C]=E%c>>>0,E=E/c>>>0;if(E!==0)throw new Error("Non-zero carry");m=F,b++}for(var k=x-m;k!==x&&_[k]===0;)k++;for(var z=a.repeat(d);k<x;++k)z+=t.charAt(_[k]);return z}function f(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var d=0;if(h[d]!==" "){for(var m=0,b=0;h[d]===a;)m++,d++;for(var w=(h.length-d)*g+1>>>0,x=new Uint8Array(w);h[d];){var _=r[h.charCodeAt(d)];if(_===255)return;for(var E=0,F=w-1;(_!==0||E<b)&&F!==-1;F--,E++)_+=c*x[F]>>>0,x[F]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");b=E,d++}if(h[d]!==" "){for(var C=w-b;C!==w&&x[C]===0;)C++;for(var k=new Uint8Array(m+(w-C)),z=m;C!==w;)k[z++]=x[C++];return k}}}function V(h){var d=f(h);if(d)return d;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:f,decode:V}}var De=qe,Be=De,ae=Be;var K=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Z=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let i=r.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ue(this,e)}},W=class{decoders;constructor(e){this.decoders=e}or(e){return ue(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ue(t,e){return new W({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var Y=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new K(e,r,n),this.decoder=new Z(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ce({name:t,prefix:e,encode:r,decode:n}){return new Y(t,e,r,n)}function H({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=ae(r,t);return ce({prefix:e,name:t,encode:n,decode:o=>oe(i(o))})}function Ie(t,e,r,n){let i={};for(let s=0;s<e.length;++s)i[e[s]]=s;let o=t.length;for(;t[o-1]==="=";)--o;let u=new Uint8Array(o*r/8|0),c=0,a=0,g=0;for(let s=0;s<o;++s){let l=i[t[s]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|l,c+=r,c>=8&&(c-=8,u[g++]=255&a>>c)}if(c>=r||(255&a<<8-c)!==0)throw new SyntaxError("Unexpected end of data");return u}function Pe(t,e,r){let n=e[e.length-1]==="=",i=(1<<r)-1,o="",u=0,c=0;for(let a=0;a<t.length;++a)for(c=c<<8|t[a],u+=8;u>r;)u-=r,o+=e[i&c>>u];if(u!==0&&(o+=e[i&c<<r-u]),n)for(;(o.length*r&7)!==0;)o+="=";return o}function y({name:t,prefix:e,bitsPerChar:r,alphabet:n}){return ce({prefix:e,name:t,encode(i){return Pe(i,n,r)},decode(i){return Ie(i,n,r,t)}})}var le=y({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Jt=y({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Qt=y({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Xt=y({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Gt=y({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Kt=y({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Zt=y({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Wt=y({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Yt=y({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var he=H({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),tr=H({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var fe=y({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),ir=y({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),sr=y({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),or=y({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function Le(t,e){try{if(typeof t=="string"&&t.length>0)return Re(t);if(typeof t=="number"&&isFinite(t))return e?.long?Qe(t):Je(t);throw new Error("Value is not a string or number.")}catch(r){let n=Xe(r)?`${r.message}. value=${JSON.stringify(t)}`:"An unknown error has occured.";throw new Error(n)}}function Re(t){if(t=String(t),t.length>100)throw new Error("Value exceeds the maximum length of 100 characters.");let e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(!e)return NaN;let r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*315576e5;case"weeks":case"week":case"w":return r*6048e5;case"days":case"day":case"d":return r*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return r*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return r*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return r*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var L=Le;function Je(t){let e=Math.abs(t);return e>=864e5?`${Math.round(t/864e5)}d`:e>=36e5?`${Math.round(t/36e5)}h`:e>=6e4?`${Math.round(t/6e4)}m`:e>=1e3?`${Math.round(t/1e3)}s`:`${t}ms`}function Qe(t){let e=Math.abs(t);return e>=864e5?P(t,e,864e5,"day"):e>=36e5?P(t,e,36e5,"hour"):e>=6e4?P(t,e,6e4,"minute"):e>=1e3?P(t,e,1e3,"second"):`${t} ms`}function P(t,e,r,n){let i=e>=r*1.5;return`${Math.round(t/r)} ${n}${i?"s":""}`}function Xe(t){return typeof t=="object"&&t!==null&&"message"in t}function ee(t){r.debug=r,r.default=r,r.coerce=a,r.disable=o,r.enable=i,r.enabled=u,r.humanize=L,r.destroy=g,Object.keys(t).forEach(s=>{r[s]=t[s]}),r.names=[],r.skips=[],r.formatters={};function e(s){let l=0;for(let f=0;f<s.length;f++)l=(l<<5)-l+s.charCodeAt(f),l|=0;return r.colors[Math.abs(l)%r.colors.length]}r.selectColor=e;function r(s){let l,f=null,V,h;function d(...m){if(!d.enabled)return;let b=d,w=Number(new Date),x=w-(l||w);b.diff=x,b.prev=l,b.curr=w,l=w,m[0]=r.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let _=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(F,C)=>{if(F==="%%")return"%";_++;let k=r.formatters[C];if(typeof k=="function"){let z=m[_];F=k.call(b,z),m.splice(_,1),_--}return F}),r.formatArgs.call(b,m),(b.log||r.log).apply(b,m)}return d.namespace=s,d.useColors=r.useColors(),d.color=r.selectColor(s),d.extend=n,d.destroy=r.destroy,Object.defineProperty(d,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(V!==r.namespaces&&(V=r.namespaces,h=r.enabled(s)),h),set:m=>{f=m}}),typeof r.init=="function"&&r.init(d),d}function n(s,l){let f=r(this.namespace+(typeof l>"u"?":":l)+s);return f.log=this.log,f}function i(s){r.save(s),r.namespaces=s,r.names=[],r.skips=[];let l,f=(typeof s=="string"?s:"").split(/[\s,]+/),V=f.length;for(l=0;l<V;l++)f[l]&&(s=f[l].replace(/\*/g,".*?"),s[0]==="-"?r.skips.push(new RegExp("^"+s.substr(1)+"$")):r.names.push(new RegExp("^"+s+"$")))}function o(){let s=[...r.names.map(c),...r.skips.map(c).map(l=>"-"+l)].join(",");return r.enable(""),s}function u(s){if(s[s.length-1]==="*")return!0;let l,f;for(l=0,f=r.skips.length;l<f;l++)if(r.skips[l].test(s))return!1;for(l=0,f=r.names.length;l<f;l++)if(r.names[l].test(s))return!0;return!1}function c(s){return s.toString().substring(2,s.toString().length-2).replace(/\.\*\?$/,"*")}function a(s){return s instanceof Error?s.stack??s.message:s}function g(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.setupFormatters(r.formatters),r.enable(r.load()),r}var R=et(),Ge=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Ke(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function Ze(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+L(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(r++,i==="%c"&&(n=r))}),t.splice(n,0,e)}var We=console.debug??console.log??(()=>{});function Ye(t){try{t?R?.setItem("debug",t):R?.removeItem("debug")}catch{}}function He(){let t;try{t=R?.getItem("debug")}catch{}return!t&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(t=globalThis.process.env.DEBUG),t}function et(){try{return localStorage}catch{}}function tt(t){t.j=function(e){try{return JSON.stringify(e)}catch(r){return"[UnexpectedJSONParseError]: "+r.message}}}var de=ee({formatArgs:Ze,save:Ye,load:He,useColors:Ke,setupFormatters:tt,colors:Ge,storage:R,log:We});var v=de;v.formatters.b=t=>t==null?"undefined":he.baseEncode(t);v.formatters.t=t=>t==null?"undefined":le.baseEncode(t);v.formatters.m=t=>t==null?"undefined":fe.baseEncode(t);v.formatters.p=t=>t==null?"undefined":t.toString();v.formatters.c=t=>t==null?"undefined":t.toString();v.formatters.k=t=>t==null?"undefined":t.toString();v.formatters.a=t=>t==null?"undefined":t.toString();v.formatters.e=t=>t==null?"undefined":pe(t.stack)??pe(t.message)??t.toString();function rt(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 me(t){let e=rt(`${t}:trace`);return v.enabled(`${t}:trace`)&&v.names.map(r=>r.toString()).find(r=>r.includes(":trace"))!=null&&(e=v(`${t}:trace`)),Object.assign(v(t),{error:v(`${t}:error`),trace:e})}function pe(t){if(t!=null&&(t=t.trim(),t.length!==0))return t}function nt(t){let[e,r]=t[Symbol.asyncIterator]!=null?[t[Symbol.asyncIterator](),Symbol.asyncIterator]:[t[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[r](){return this}}}var be=nt;function it(t){return t[Symbol.asyncIterator]!=null}function ge(t){return t?.then!=null}function st(t,e){let r=0;if(it(t))return async function*(){for await(let a of t){let g=e(a,r++);ge(g)&&await g,yield a}}();let n=be(t),{value:i,done:o}=n.next();if(o===!0)return function*(){}();if(typeof e(i,r++)?.then=="function")return async function*(){yield i;for await(let a of n){let g=e(a,r++);ge(g)&&await g,yield a}}();let c=e;return function*(){yield i;for(let a of n)c(a,r++),yield a}()}var te=st;var Se=Ne(Me(),1),ht=me("libp2p:simple-metrics"),T=class{value=0;update(e){this.value=e}increment(e=1){this.value+=e}decrement(e=1){this.value-=e}reset(){this.value=0}timer(){let e=Date.now();return()=>{this.value=Date.now()-e}}},q=class{values={};update(e){Object.entries(e).forEach(([r,n])=>{this.values[r]=n})}increment(e){Object.entries(e).forEach(([r,n])=>{this.values[r]=this.values[r]??0;let i=typeof n=="number"?n:1;this.values[r]+=Number(i)})}decrement(e){Object.entries(e).forEach(([r,n])=>{this.values[r]=this.values[r]??0;let i=typeof n=="number"?n:1;this.values[r]-=Number(i)})}reset(){this.values={}}timer(e){let r=Date.now();return()=>{this.values[e]=Date.now()-r}}},D=class{bucketValues=new Map;countValue=0;sumValue=0;constructor(e){let r=[...e.buckets??[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10],1/0];for(let n of r)this.bucketValues.set(n,0)}observe(e){this.countValue++,this.sumValue+=e;for(let[r,n]of this.bucketValues.entries())e<=r&&this.bucketValues.set(r,n+1)}reset(){this.countValue=0,this.sumValue=0;for(let e of this.bucketValues.keys())this.bucketValues.set(e,0)}timer(){let e=Date.now();return()=>{this.observe(Date.now()-e)}}},X=class{histograms={};constructor(e){this.histograms={}}observe(e){for(let[r,n]of Object.entries(e))this.histograms[r]===void 0&&(this.histograms[r]=new D({})),this.histograms[r].observe(n)}reset(){for(let e of Object.values(this.histograms))e.reset()}timer(e){let r=Date.now();return()=>{this.observe({[e]:Date.now()-r})}}},B=class{sumValue=0;countValue=0;percentiles;tdigest=new Se.TDigest(.01);compressCount;constructor(e){this.percentiles=e.percentiles??[.01,.05,.5,.9,.95,.99,.999],this.compressCount=e.compressCount??1e3}observe(e){this.sumValue+=e,this.countValue++,this.tdigest.push(e),this.tdigest.size()>this.compressCount&&this.tdigest.compress()}reset(){this.sumValue=0,this.countValue=0,this.tdigest.reset()}timer(){let e=Date.now();return()=>{this.observe(Date.now()-e)}}},G=class{summaries={};opts;constructor(e){this.summaries={},this.opts=e}observe(e){for(let[r,n]of Object.entries(e))this.summaries[r]===void 0&&(this.summaries[r]=new B(this.opts)),this.summaries[r].observe(n)}reset(){for(let e of Object.values(this.summaries))e.reset()}timer(e){let r=Date.now();return()=>{this.observe({[e]:Date.now()-r})}}},ne=class{metrics=new Map;transferStats;started;interval;intervalMs;onMetrics;constructor(e,r){this.started=!1,this._emitMetrics=this._emitMetrics.bind(this),this.intervalMs=r.intervalMs??1e3,this.onMetrics=r.onMetrics,this.transferStats=new Map}[Symbol.toStringTag]="@libp2p/metrics-simple";[se]=["@libp2p/metrics"];isStarted(){return this.started}start(){this.started=!0,this.interval=setInterval(this._emitMetrics,this.intervalMs)}stop(){this.started=!1,clearInterval(this.interval)}_emitMetrics(){Promise.resolve().then(async()=>{let e={};for(let[r,n]of this.metrics.entries())n instanceof T?e[r]=n.value:n instanceof q?e[r]=n.values:n instanceof D?e[r]={count:n.countValue,sum:n.sumValue,buckets:{...n.bucketValues}}:n instanceof X?e[r]={...Object.fromEntries(Object.entries(n.histograms).map(([i,o])=>[i,{count:o.countValue,sum:o.sumValue,buckets:{...o.bucketValues}}]))}:n instanceof B?e[r]={count:n.countValue,sum:n.sumValue,percentiles:Object.fromEntries(n.percentiles.map(i=>[i,n.tdigest.percentile(i)]))}:n instanceof G?e[r]={...Object.fromEntries(Object.entries(n.summaries).map(([i,o])=>[i,{count:o.countValue,sum:o.sumValue,percentiles:Object.fromEntries(o.percentiles.map(u=>[u,o.tdigest.percentile(u)]))}]))}:e[r]=await n();this.onMetrics(structuredClone(e))}).catch(e=>{ht.error("could not invoke onMetrics callback",e)})}_incrementValue(e,r){let n=this.transferStats.get(e)??0;this.transferStats.set(e,n+r)}_track(e,r){let n=this,i=e.sink;e.sink=async function(c){await i(te(c,a=>{n._incrementValue(`${r} sent`,a.byteLength)}))};let o=e.source;e.source=te(o,u=>{n._incrementValue(`${r} received`,u.byteLength)})}trackMultiaddrConnection(e){this._track(e,"global")}trackProtocolStream(e,r){e.protocol!=null&&this._track(e,e.protocol)}registerMetric(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(r?.calculate!=null){this.metrics.set(e,r.calculate);return}let n=new T;return this.metrics.set(e,n),n}registerMetricGroup(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(r?.calculate!=null){this.metrics.set(e,r.calculate);return}let n=new q;return this.metrics.set(e,n),n}registerCounter(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(r?.calculate!=null){this.metrics.set(e,r.calculate);return}let n=new T;return this.metrics.set(e,n),n}registerCounterGroup(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(r?.calculate!=null){this.metrics.set(e,r.calculate);return}let n=new q;return this.metrics.set(e,n),n}registerHistogram(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(r?.calculate!=null){this.metrics.set(e,r.calculate);return}let n=new D(r);return this.metrics.set(e,n),n}registerHistogramGroup(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(r?.calculate!=null){this.metrics.set(e,r.calculate);return}let n=new X(r);return this.metrics.set(e,n),n}registerSummary(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(r?.calculate!=null){this.metrics.set(e,r.calculate);return}let n=new B(r);return this.metrics.set(e,n),n}registerSummaryGroup(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(r?.calculate!=null){this.metrics.set(e,r.calculate);return}let n=new G(r);return this.metrics.set(e,n),n}createTrace(){}traceFunction(e,r){return r}};function ft(t){return e=>new ne(e,t)}return Te(dt);})();
4
4
  return Libp2PSimpleMetrics}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@libp2p/simple-metrics",
3
- "version": "1.3.3",
3
+ "version": "1.3.4",
4
4
  "description": "Simple in-memory metrics gathering for libp2p",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/libp2p/js-libp2p/tree/main/packages/metrics-simple#readme",
@@ -49,15 +49,15 @@
49
49
  "dep-check": "aegir dep-check -i events"
50
50
  },
51
51
  "dependencies": {
52
- "@libp2p/interface": "^2.6.0",
53
- "@libp2p/logger": "^5.1.9",
52
+ "@libp2p/interface": "^2.6.1",
53
+ "@libp2p/logger": "^5.1.10",
54
54
  "it-foreach": "^2.1.1",
55
55
  "it-stream-types": "^2.0.2",
56
56
  "tdigest": "^0.1.2"
57
57
  },
58
58
  "devDependencies": {
59
59
  "@types/tdigest": "^0.1.4",
60
- "aegir": "^45.0.5",
60
+ "aegir": "^45.1.1",
61
61
  "p-defer": "^4.0.1"
62
62
  },
63
63
  "sideEffects": false