@libp2p/simple-metrics 1.3.12 → 1.3.13
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 +2 -2
- package/dist/index.min.js.map +3 -3
- package/dist/src/index.d.ts +5 -2
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +119 -96
- package/dist/src/index.js.map +1 -1
- package/dist/typedoc-urls.json +2 -0
- package/package.json +4 -4
- package/src/index.ts +162 -107
package/dist/index.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PSimpleMetrics = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var Libp2PSimpleMetrics=(()=>{var Ve=Object.create;var
|
|
3
|
-
`)};function Ae(t,e){return t.mean>e.mean?1:t.mean<e.mean?-1:0}function lt(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 s=i.mean_cumn/this.n,a=Math.floor(4*this.n*this.delta*s*(1-s));a-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=lt;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 ht(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(ht(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 pt={};$e(pt,{simpleMetrics:()=>dt});var se=Symbol.for("@libp2p/service-capabilities"),bt=Symbol.for("@libp2p/service-dependencies");var Dt=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 s=t.charAt(i),a=s.charCodeAt(0);if(r[a]!==255)throw new TypeError(s+" is ambiguous");r[a]=i}var c=t.length,u=t.charAt(0),b=Math.log(c)/Math.log(256),o=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,g=0,w=h.length;g!==w&&h[g]===0;)g++,d++;for(var x=(w-g)*o+1>>>0,_=new Uint8Array(x);g!==w;){for(var E=h[g],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,g++}for(var k=x-m;k!==x&&_[k]===0;)k++;for(var z=u.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,g=0;h[d]===u;)m++,d++;for(var w=(h.length-d)*b+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<g)&&F!==-1;F--,E++)_+=c*x[F]>>>0,x[F]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");g=E,d++}if(h[d]!==" "){for(var C=w-g;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:s=>oe(i(s))})}function Ie(t,e,r,n){let i=t.length;for(;t[i-1]==="=";)--i;let s=new Uint8Array(i*r/8|0),a=0,c=0,u=0;for(let b=0;b<i;++b){let o=e[t[b]];if(o===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|o,a+=r,a>=8&&(a-=8,s[u++]=255&c>>a)}if(a>=r||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return s}function Pe(t,e,r){let n=e[e.length-1]==="=",i=(1<<r)-1,s="",a=0,c=0;for(let u=0;u<t.length;++u)for(c=c<<8|t[u],a+=8;a>r;)a-=r,s+=e[i&c>>a];if(a!==0&&(s+=e[i&c<<r-a]),n)for(;(s.length*r&7)!==0;)s+="=";return s}function Le(t){let e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function y({name:t,prefix:e,bitsPerChar:r,alphabet:n}){let i=Le(n);return ce({prefix:e,name:t,encode(s){return Pe(s,n,r)},decode(s){return Ie(s,i,r,t)}})}var le=y({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Qt=y({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Xt=y({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Gt=y({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Kt=y({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Zt=y({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Wt=y({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Yt=y({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ht=y({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var he=H({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),rr=H({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var fe=y({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),sr=y({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),or=y({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ar=y({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function Re(t,e){try{if(typeof t=="string"&&t.length>0)return Je(t);if(typeof t=="number"&&isFinite(t))return e?.long?Xe(t):Qe(t);throw new Error("Value is not a string or number.")}catch(r){let n=Ge(r)?`${r.message}. value=${JSON.stringify(t)}`:"An unknown error has occured.";throw new Error(n)}}function Je(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=Re;function Qe(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 Xe(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 Ge(t){return typeof t=="object"&&t!==null&&"message"in t}function ee(t){r.debug=r,r.default=r,r.coerce=u,r.disable=s,r.enable=i,r.enabled=a,r.humanize=L,r.destroy=b,Object.keys(t).forEach(o=>{r[o]=t[o]}),r.names=[],r.skips=[],r.formatters={};function e(o){let l=0;for(let f=0;f<o.length;f++)l=(l<<5)-l+o.charCodeAt(f),l|=0;return r.colors[Math.abs(l)%r.colors.length]}r.selectColor=e;function r(o){let l,f=null,V,h;function d(...m){if(!d.enabled)return;let g=d,w=Number(new Date),x=w-(l||w);g.diff=x,g.prev=l,g.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(g,z),m.splice(_,1),_--}return F}),r.formatArgs.call(g,m),(g.log||r.log).apply(g,m)}return d.namespace=o,d.useColors=r.useColors(),d.color=r.selectColor(o),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(o)),h),set:m=>{f=m}}),typeof r.init=="function"&&r.init(d),d}function n(o,l){let f=r(this.namespace+(typeof l>"u"?":":l)+o);return f.log=this.log,f}function i(o){r.save(o),r.namespaces=o,r.names=[],r.skips=[];let l,f=(typeof o=="string"?o:"").split(/[\s,]+/),V=f.length;for(l=0;l<V;l++)f[l]&&(o=f[l].replace(/\*/g,".*?"),o[0]==="-"?r.skips.push(new RegExp("^"+o.substr(1)+"$")):r.names.push(new RegExp("^"+o+"$")))}function s(){let o=[...r.names.map(c),...r.skips.map(c).map(l=>"-"+l)].join(",");return r.enable(""),o}function a(o){if(o[o.length-1]==="*")return!0;let l,f;for(l=0,f=r.skips.length;l<f;l++)if(r.skips[l].test(o))return!1;for(l=0,f=r.names.length;l<f;l++)if(r.names[l].test(o))return!0;return!1}function c(o){return o.toString().substring(2,o.toString().length-2).replace(/\.\*\?$/,"*")}function u(o){return o instanceof Error?o.stack??o.message:o}function b(){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=tt(),Ke=["#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 Ze(){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 We(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 Ye=console.debug??console.log??(()=>{});function He(t){try{t?R?.setItem("debug",t):R?.removeItem("debug")}catch{}}function et(){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 tt(){try{return localStorage}catch{}}function rt(t){t.j=function(e){try{return JSON.stringify(e)}catch(r){return"[UnexpectedJSONParseError]: "+r.message}}}var de=ee({formatArgs:We,save:He,load:et,useColors:Ze,setupFormatters:rt,colors:Ke,storage:R,log:Ye});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 nt(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=nt(`${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 it(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=it;function st(t){return t[Symbol.asyncIterator]!=null}function ge(t){return t?.then!=null}function ot(t,e){let r=0;if(st(t))return async function*(){for await(let u of t){let b=e(u,r++);ge(b)&&await b,yield u}}();let n=be(t),{value:i,done:s}=n.next();if(s===!0)return function*(){}();if(typeof e(i,r++)?.then=="function")return async function*(){yield i;for await(let u of n){let b=e(u,r++);ge(b)&&await b,yield u}}();let c=e;return function*(){yield i;for(let u of n)c(u,r++),yield u}()}var te=ot;var Se=Ne(Me(),1),ft=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,s])=>[i,{count:s.countValue,sum:s.sumValue,buckets:{...s.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,s])=>[i,{count:s.countValue,sum:s.sumValue,percentiles:Object.fromEntries(s.percentiles.map(a=>[a,s.tdigest.percentile(a)]))}]))}:e[r]=await n();this.onMetrics(structuredClone(e))}).catch(e=>{ft.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,u=>{n._incrementValue(`${r} sent`,u.byteLength)}))};let s=e.source;e.source=te(s,a=>{n._incrementValue(`${r} received`,a.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 dt(t){return e=>new ne(e,t)}return Te(pt);})();
|
|
2
|
+
"use strict";var Libp2PSimpleMetrics=(()=>{var Ve=Object.create;var N=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var De=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty;var O=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),$e=(t,e)=>{for(var r in e)N(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))!Oe.call(t,i)&&i!==r&&N(t,i,{get:()=>e[i],enumerable:!(n=ze(e,i))||n.enumerable});return t};var je=(t,e,r)=>(r=t!=null?Ve(De(t)):{},ie(e||!t||!t.__esModule?N(r,"default",{value:t,enumerable:!0}):r,t)),Ne=t=>ie(N({},"__esModule",{value:!0}),t);var ee=O((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=O((kr,ye)=>{var at=ee();function D(t){this.data=t,this.left=null,this.right=null,this.red=!0}D.prototype.get_child=function(t){return t?this.right:this.left};D.prototype.set_child=function(t,e){t?this.right=e:this.left=e};function I(t){this._root=null,this._comparator=t,this.size=0}I.prototype=new at;I.prototype.insert=function(t){var e=!1;if(this._root===null)this._root=new D(t),e=!0,this.size++;else{var r=new D(void 0),n=0,i=0,o=null,a=r,c=null,u=this._root;for(a.right=this._root;;){if(u===null?(u=new D(t),c.set_child(n,u),e=!0,this.size++):A(u.left)&&A(u.right)&&(u.red=!0,u.left.red=!1,u.right.red=!1),A(u)&&A(c)){var g=a.right===o;u===c.get_child(i)?a.set_child(g,$(o,!i)):a.set_child(g,we(o,!i))}var s=this._comparator(u.data,t);if(s===0)break;i=n,n=s<0,o!==null&&(a=o),o=c,c=u,u=u.get_child(n)}this._root=r.right}return this._root.red=!1,e};I.prototype.remove=function(t){if(this._root===null)return!1;var e=new D(void 0),r=e;r.right=this._root;for(var n=null,i=null,o=null,a=1;r.get_child(a)!==null;){var c=a;i=n,n=r,r=r.get_child(a);var u=this._comparator(t,r.data);if(a=u>0,u===0&&(o=r),!A(r)&&!A(r.get_child(a))){if(A(r.get_child(!a))){var g=$(r,a);n.set_child(c,g),n=g}else if(!A(r.get_child(!a))){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=I});var xe=O((Ar,Ce)=>{var ut=ee();function j(t){this.data=t,this.left=null,this.right=null}j.prototype.get_child=function(t){return t?this.right:this.left};j.prototype.set_child=function(t,e){t?this.right=e:this.left=e};function P(t){this._root=null,this._comparator=t,this.size=0}P.prototype=new ut;P.prototype.insert=function(t){if(this._root===null)return this._root=new j(t),this.size++,!0;for(var e=0,r=null,n=this._root;;){if(n===null)return n=new j(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)}};P.prototype.remove=function(t){if(this._root===null)return!1;var e=new j(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 a=this._comparator(t,r.data);o=a>0,a===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=P});var ke=O((Er,Fe)=>{Fe.exports={RBTree:ve(),BinTree:xe()}});var Me=O((Mr,Ee)=>{var ct=ke().RBTree;function d(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 ct(Ae),this.nreset=0,this.reset()}d.prototype.reset=function(){this.centroids.clear(),this.n=0,this.nreset+=1,this.last_cumulate=0};d.prototype.size=function(){return this.centroids.size};d.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};d.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 lt(t,e){return t.mean_cumn-e.mean_cumn}d.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)};d.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)};d.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}};d.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};d.prototype._new_centroid=function(t,e,r){var n={mean:t,n:e,cumn:r};return this.centroids.insert(n),this.n+=e,n};d.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};d.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,a=Math.floor(4*this.n*this.delta*o*(1-o));a-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()};d.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]};d.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]};d.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}};d.prototype.bound_mean_cumn=function(t){this.centroids._comparator=lt;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]};d.prototype.percentile=function(t){var e=Array.isArray(t)?t:[t],r=e.map(this._percentile,this);return Array.isArray(t)?r:r[0]};d.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 ht(t){var e=Math.floor(Math.random()*t.length);return t.splice(e,1)[0]}d.prototype.compress=function(){if(!this.compressing){var t=this.toArray();for(this.reset(),this.compressing=!0;t.length>0;)this.push_centroid(ht(t));this._cumulate(!0),this.compressing=!1}};function S(t){this.config=t||{},this.mode=this.config.mode||"auto",d.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(d.prototype);S.prototype.constructor=S;S.prototype.push=function(t){d.prototype.push.call(this,t),this.check_continuous()};S.prototype._new_centroid=function(t,e,r){this.n_unique+=1,d.prototype._new_centroid.call(this,t,e,r)};S.prototype._addweight=function(t,e,r){t.n===1&&(this.n_unique-=1),d.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:d,Digest:S}});var dt={};$e(dt,{simpleMetrics:()=>pt});var se=Symbol.for("@libp2p/service-capabilities"),gt=Symbol.for("@libp2p/service-dependencies");var Tt=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 Te(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),a=o.charCodeAt(0);if(r[a]!==255)throw new TypeError(o+" is ambiguous");r[a]=i}var c=t.length,u=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 p=0,m=0,b=0,w=h.length;b!==w&&h[b]===0;)b++,p++;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=u.repeat(p);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 p=0;if(h[p]!==" "){for(var m=0,b=0;h[p]===u;)m++,p++;for(var w=(h.length-p)*g+1>>>0,x=new Uint8Array(w);h[p];){var _=r[h.charCodeAt(p)];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,p++}if(h[p]!==" "){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 p=f(h);if(p)return p;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:f,decode:V}}var qe=Te,Be=qe,ae=Be;var X=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")}},G=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)}},K=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 K({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var Z=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 X(e,r,n),this.decoder=new G(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 Z(t,e,r,n)}function W({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=t.length;for(;t[i-1]==="=";)--i;let o=new Uint8Array(i*r/8|0),a=0,c=0,u=0;for(let g=0;g<i;++g){let s=e[t[g]];if(s===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|s,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||(255&c<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return o}function Pe(t,e,r){let n=e[e.length-1]==="=",i=(1<<r)-1,o="",a=0,c=0;for(let u=0;u<t.length;++u)for(c=c<<8|t[u],a+=8;a>r;)a-=r,o+=e[i&c>>a];if(a!==0&&(o+=e[i&c<<r-a]),n)for(;(o.length*r&7)!==0;)o+="=";return o}function Le(t){let e={};for(let r=0;r<t.length;++r)e[t[r]]=r;return e}function y({name:t,prefix:e,bitsPerChar:r,alphabet:n}){let i=Le(n);return ce({prefix:e,name:t,encode(o){return Pe(o,n,r)},decode(o){return Ie(o,i,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=W({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),tr=W({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 Re(t,e){try{if(typeof t=="string"&&t.length>0)return Je(t);if(typeof t=="number"&&isFinite(t))return e?.long?Xe(t):Qe(t);throw new Error("Value is not a string or number.")}catch(r){let n=Ge(r)?`${r.message}. value=${JSON.stringify(t)}`:"An unknown error has occured.";throw new Error(n)}}function Je(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 q=Re;function Qe(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 Xe(t){let e=Math.abs(t);return e>=864e5?T(t,e,864e5,"day"):e>=36e5?T(t,e,36e5,"hour"):e>=6e4?T(t,e,6e4,"minute"):e>=1e3?T(t,e,1e3,"second"):`${t} ms`}function T(t,e,r,n){let i=e>=r*1.5;return`${Math.round(t/r)} ${n}${i?"s":""}`}function Ge(t){return typeof t=="object"&&t!==null&&"message"in t}function Y(t){r.debug=r,r.default=r,r.coerce=u,r.disable=o,r.enable=i,r.enabled=a,r.humanize=q,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 p(...m){if(!p.enabled)return;let b=p,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 p.namespace=s,p.useColors=r.useColors(),p.color=r.selectColor(s),p.extend=n,p.destroy=r.destroy,Object.defineProperty(p,"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(p),p}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 a(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 u(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 B=tt(),Ke=["#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 Ze(){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 We(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+q(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 Ye=console.debug??console.log??(()=>{});function He(t){try{t?B?.setItem("debug",t):B?.removeItem("debug")}catch{}}function et(){let t;try{t=B?.getItem("debug")}catch{}return!t&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(t=globalThis.process.env.DEBUG),t}function tt(){try{return localStorage}catch{}}function rt(t){t.j=function(e){try{return JSON.stringify(e)}catch(r){return"[UnexpectedJSONParseError]: "+r.message}}}var pe=Y({formatArgs:We,save:He,load:et,useColors:Ze,setupFormatters:rt,colors:Ke,storage:B,log:Ye});var v=pe;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":de(t.stack)??de(t.message)??t.toString();function nt(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=nt(`${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 de(t){if(t!=null&&(t=t.trim(),t.length!==0))return t}function it(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 ge=it;function st(t){return t[Symbol.asyncIterator]!=null}function be(t){return t?.then!=null}function ot(t,e){let r=0;if(st(t))return async function*(){for await(let u of t){let g=e(u,r++);be(g)&&await g,yield u}}();let n=ge(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(let u of n){let g=e(u,r++);be(g)&&await g,yield u}}();let c=e;return function*(){yield i;for(let u of n)c(u,r++),yield u}()}var H=ot;var Se=je(Me(),1),ft=me("libp2p:simple-metrics"),L=class{value=0;calculate;constructor(e){this.calculate=e?.calculate}async collect(){return this.calculate!=null?this.calculate():this.value}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}}},R=class{values={};calculate;constructor(e){this.calculate=e?.calculate}async collect(){return this.calculate!=null?this.calculate():this.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}}},J=class{bucketValues=new Map;countValue=0;sumValue=0;calculate;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);this.calculate=e?.calculate}async collect(){return this.calculate!=null&&this.observe(await this.calculate()),{count:this.countValue,sum:this.sumValue,buckets:{...this.bucketValues}}}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)}}},te=class{histograms={};calculate;constructor(e){this.histograms={},this.calculate=e?.calculate}async collect(){let e={};for(let[r,n]of Object.entries(this.histograms))e[r]=await n.collect();return e}observe(e){for(let[r,n]of Object.entries(e))this.histograms[r]===void 0&&(this.histograms[r]=new J),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})}}},Q=class{sumValue=0;countValue=0;percentiles;tdigest=new Se.TDigest(.01);compressCount;calculate;constructor(e){this.percentiles=e?.percentiles??[.01,.05,.5,.9,.95,.99,.999],this.compressCount=e?.compressCount??1e3,this.calculate=e?.calculate}async collect(){return this.calculate!=null&&this.observe(await this.calculate()),{count:this.countValue,sum:this.sumValue,percentiles:Object.fromEntries(this.percentiles.map(e=>[e,this.tdigest.percentile(e)]))}}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)}}},re=class{summaries={};opts;constructor(e){this.summaries={},this.opts=e}async collect(){return{...Object.fromEntries(Object.entries(this.summaries).map(([e,r])=>[e,{count:r.countValue,sum:r.sumValue,percentiles:Object.fromEntries(r.percentiles.map(n=>[n,r.tdigest.percentile(n)]))}]))}}observe(e){for(let[r,n]of Object.entries(e))this.summaries[r]===void 0&&(this.summaries[r]=new Q(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;log;constructor(e,r){this.log=e.logger.forComponent("libp2p:simple-metrics"),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),this.transferStats.clear()}_emitMetrics(){Promise.resolve().then(async()=>{let e={};for(let[r,n]of this.metrics.entries())e[r]=await n.collect();this.onMetrics(structuredClone(e))}).catch(e=>{ft.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(H(c,u=>{n._incrementValue(`${r} sent`,u.byteLength)}))};let o=e.source;e.source=H(o,a=>{n._incrementValue(`${r} received`,a.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");let n=this.metrics.get(e);return n!=null?(this.log("reuse existing metric",e),n):(n=new L(r),this.metrics.set(e,n),n)}registerMetricGroup(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");let n=this.metrics.get(e);return n!=null?(this.log("reuse existing metric",e),n):(n=new R(r),this.metrics.set(e,n),n)}registerCounter(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");let n=this.metrics.get(e);return n!=null?(this.log("reuse existing metric",e),n):(n=new L(r),this.metrics.set(e,n),n)}registerCounterGroup(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");let n=this.metrics.get(e);return n!=null?(this.log("reuse existing metric",e),n):(n=new R(r),this.metrics.set(e,n),n)}registerHistogram(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");let n=this.metrics.get(e);return n!=null?(this.log("reuse existing metric",e),n):(n=new J(r),this.metrics.set(e,n),n)}registerHistogramGroup(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");let n=this.metrics.get(e);return n!=null?(this.log("reuse existing metric",e),n):(n=new te(r),this.metrics.set(e,n),n)}registerSummary(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");let n=this.metrics.get(e);return n!=null?(this.log("reuse existing metric",e),n):(n=new Q(r),this.metrics.set(e,n),n)}registerSummaryGroup(e,r={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");let n=this.metrics.get(e);return n!=null?(this.log("reuse existing metric",e),n):(n=new re(r),this.metrics.set(e,n),n)}createTrace(){}traceFunction(e,r){return r}};function pt(t){return e=>new ne(e,t)}return Ne(dt);})();
|
|
4
4
|
return Libp2PSimpleMetrics}));
|
|
5
5
|
//# sourceMappingURL=index.min.js.map
|