@libp2p/simple-metrics 1.1.6 → 1.1.7-6ccbb06f0

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,3 +1,3 @@
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 z=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var re=Object.prototype.hasOwnProperty;var ne=(r,e)=>{for(var t in e)z(r,t,{get:e[t],enumerable:!0})},oe=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of te(e))!re.call(r,s)&&s!==t&&z(r,s,{get:()=>e[s],enumerable:!(n=ee(e,s))||n.enumerable});return r};var se=r=>oe(z({},"__esModule",{value:!0}),r);var $e={};ne($e,{simpleMetrics:()=>Ue});var R=Symbol.for("@libp2p/service-capabilities"),Ne=Symbol.for("@libp2p/service-dependencies");var rt=new Uint8Array(0);function T(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function ie(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var d=r.charAt(s),m=d.charCodeAt(0);if(t[m]!==255)throw new TypeError(d+" is ambiguous");t[m]=s}var u=r.length,f=r.charAt(0),E=Math.log(u)/Math.log(256),o=Math.log(256)/Math.log(u);function i(a){if(a instanceof Uint8Array||(ArrayBuffer.isView(a)?a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength):Array.isArray(a)&&(a=Uint8Array.from(a))),!(a instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(a.length===0)return"";for(var c=0,p=0,h=0,C=a.length;h!==C&&a[h]===0;)h++,c++;for(var y=(C-h)*o+1>>>0,b=new Uint8Array(y);h!==C;){for(var A=a[h],F=0,x=y-1;(A!==0||F<p)&&x!==-1;x--,F++)A+=256*b[x]>>>0,b[x]=A%u>>>0,A=A/u>>>0;if(A!==0)throw new Error("Non-zero carry");p=F,h++}for(var v=y-p;v!==y&&b[v]===0;)v++;for(var M=f.repeat(c);v<y;++v)M+=r.charAt(b[v]);return M}function l(a){if(typeof a!="string")throw new TypeError("Expected String");if(a.length===0)return new Uint8Array;var c=0;if(a[c]!==" "){for(var p=0,h=0;a[c]===f;)p++,c++;for(var C=(a.length-c)*E+1>>>0,y=new Uint8Array(C);a[c];){var b=t[a.charCodeAt(c)];if(b===255)return;for(var A=0,F=C-1;(b!==0||A<h)&&F!==-1;F--,A++)b+=u*y[F]>>>0,y[F]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");h=A,c++}if(a[c]!==" "){for(var x=C-h;x!==C&&y[x]===0;)x++;for(var v=new Uint8Array(p+(C-x)),M=p;x!==C;)v[M++]=y[x++];return v}}}function S(a){var c=l(a);if(c)return c;throw new Error(`Non-${e} character`)}return{encode:i,decodeUnsafe:l,decode:S}}var ae=ie,ce=ae,B=ce;var I=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},P=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){if(this.name=e,this.prefix=t,t.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=t.codePointAt(0),this.baseDecode=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 J(this,e)}},j=class{decoders;constructor(e){this.decoders=e}or(e){return J(this,e)}decode(e){let t=e[0],n=this.decoders[t];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 J(r,e){return new j({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var D=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,s){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new I(e,t,n),this.decoder=new P(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function G({name:r,prefix:e,encode:t,decode:n}){return new D(r,e,t,n)}function L({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=B(t,r);return G({prefix:e,name:r,encode:n,decode:d=>T(s(d))})}function ue(r,e,t,n){let s={};for(let o=0;o<e.length;++o)s[e[o]]=o;let d=r.length;for(;r[d-1]==="=";)--d;let m=new Uint8Array(d*t/8|0),u=0,f=0,E=0;for(let o=0;o<d;++o){let i=s[r[o]];if(i===void 0)throw new SyntaxError(`Non-${n} character`);f=f<<t|i,u+=t,u>=8&&(u-=8,m[E++]=255&f>>u)}if(u>=t||255&f<<8-u)throw new SyntaxError("Unexpected end of data");return m}function fe(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,d="",m=0,u=0;for(let f=0;f<r.length;++f)for(u=u<<8|r[f],m+=8;m>t;)m-=t,d+=e[s&u>>m];if(m!==0&&(d+=e[s&u<<t-m]),n)for(;d.length*t&7;)d+="=";return d}function w({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return G({prefix:e,name:r,encode(s){return fe(s,n,t)},decode(s){return ue(s,n,t,r)}})}var X=w({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ut=w({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ft=w({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),lt=w({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),dt=w({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),pt=w({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ht=w({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),mt=w({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),bt=w({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Z=L({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xt=L({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var K=w({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ft=w({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),vt=w({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Et=w({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function le(r,e){try{if(typeof r=="string"&&r.length>0)return de(r);if(typeof r=="number"&&isFinite(r))return e?.long?he(r):pe(r);throw new Error("Value is not a string or number.")}catch(t){let n=me(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function de(r){if(r=String(r),r.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(r);if(!e)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var O=le;function pe(r){let e=Math.abs(r);return e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function he(r){let e=Math.abs(r);return e>=864e5?$(r,e,864e5,"day"):e>=36e5?$(r,e,36e5,"hour"):e>=6e4?$(r,e,6e4,"minute"):e>=1e3?$(r,e,1e3,"second"):`${r} ms`}function $(r,e,t,n){let s=e>=t*1.5;return`${Math.round(r/t)} ${n}${s?"s":""}`}function me(r){return typeof r=="object"&&r!==null&&"message"in r}function _(r){t.debug=t,t.default=t,t.coerce=f,t.disable=d,t.enable=s,t.enabled=m,t.humanize=O,t.destroy=E,Object.keys(r).forEach(o=>{t[o]=r[o]}),t.names=[],t.skips=[],t.formatters={};function e(o){let i=0;for(let l=0;l<o.length;l++)i=(i<<5)-i+o.charCodeAt(l),i|=0;return t.colors[Math.abs(i)%t.colors.length]}t.selectColor=e;function t(o){let i,l=null,S,a;function c(...p){if(!c.enabled)return;let h=c,C=Number(new Date),y=C-(i||C);h.diff=y,h.prev=i,h.curr=C,i=C,p[0]=t.coerce(p[0]),typeof p[0]!="string"&&p.unshift("%O");let b=0;p[0]=p[0].replace(/%([a-zA-Z%])/g,(F,x)=>{if(F==="%%")return"%";b++;let v=t.formatters[x];if(typeof v=="function"){let M=p[b];F=v.call(h,M),p.splice(b,1),b--}return F}),t.formatArgs.call(h,p),(h.log||t.log).apply(h,p)}return c.namespace=o,c.useColors=t.useColors(),c.color=t.selectColor(o),c.extend=n,c.destroy=t.destroy,Object.defineProperty(c,"enabled",{enumerable:!0,configurable:!1,get:()=>l!==null?l:(S!==t.namespaces&&(S=t.namespaces,a=t.enabled(o)),a),set:p=>{l=p}}),typeof t.init=="function"&&t.init(c),c}function n(o,i){let l=t(this.namespace+(typeof i>"u"?":":i)+o);return l.log=this.log,l}function s(o){t.save(o),t.namespaces=o,t.names=[],t.skips=[];let i,l=(typeof o=="string"?o:"").split(/[\s,]+/),S=l.length;for(i=0;i<S;i++)l[i]&&(o=l[i].replace(/\*/g,".*?"),o[0]==="-"?t.skips.push(new RegExp("^"+o.substr(1)+"$")):t.names.push(new RegExp("^"+o+"$")))}function d(){let o=[...t.names.map(u),...t.skips.map(u).map(i=>"-"+i)].join(",");return t.enable(""),o}function m(o){if(o[o.length-1]==="*")return!0;let i,l;for(i=0,l=t.skips.length;i<l;i++)if(t.skips[i].test(o))return!1;for(i=0,l=t.names.length;i<l;i++)if(t.names[i].test(o))return!0;return!1}function u(o){return o.toString().substring(2,o.toString().length-2).replace(/\.\*\?$/,"*")}function f(o){return o instanceof Error?o.stack??o.message:o}function E(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var N=Fe(),be=["#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 Ce(){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(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+O(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}var xe=console.debug??console.log??(()=>{});function ge(r){try{r?N?.setItem("debug",r):N?.removeItem("debug")}catch{}}function ye(){let r;try{r=N?.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Fe(){try{return localStorage}catch{}}function ve(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Q=_({formatArgs:we,save:ge,load:ye,useColors:Ce,setupFormatters:ve,colors:be,storage:N,log:xe});var g=Q;g.formatters.b=r=>r==null?"undefined":Z.baseEncode(r);g.formatters.t=r=>r==null?"undefined":X.baseEncode(r);g.formatters.m=r=>r==null?"undefined":K.baseEncode(r);g.formatters.p=r=>r==null?"undefined":r.toString();g.formatters.c=r=>r==null?"undefined":r.toString();g.formatters.k=r=>r==null?"undefined":r.toString();g.formatters.a=r=>r==null?"undefined":r.toString();function Ee(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function W(r){let e=Ee(`${r}:trace`);return g.enabled(`${r}:trace`)&&g.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=g(`${r}:trace`)),Object.assign(g(r),{error:g(`${r}:error`),trace:e})}function Ae(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Y=Ae;function Se(r){return r[Symbol.asyncIterator]!=null}function H(r){return r?.then!=null}function Me(r,e){let t=0;if(Se(r))return async function*(){for await(let f of r){let E=e(f,t++);H(E)&&await E,yield f}}();let n=Y(r),{value:s,done:d}=n.next();if(d===!0)return function*(){}();if(typeof e(s,t++)?.then=="function")return async function*(){yield s;for await(let f of n){let E=e(f,t++);H(E)&&await E,yield f}}();let u=e;return function*(){yield s;for(let f of n)u(f,t++),yield f}()}var V=Me;var ke=W("libp2p:simple-metrics"),k=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}}},U=class{values={};update(e){Object.entries(e).forEach(([t,n])=>{this.values[t]=n})}increment(e){Object.entries(e).forEach(([t,n])=>{this.values[t]=this.values[t]??0;let s=typeof n=="number"?n:1;this.values[t]+=Number(s)})}decrement(e){Object.entries(e).forEach(([t,n])=>{this.values[t]=this.values[t]??0;let s=typeof n=="number"?n:1;this.values[t]-=Number(s)})}reset(){this.values={}}timer(e){let t=Date.now();return()=>{this.values[e]=Date.now()-t}}},q=class{metrics=new Map;transferStats;started;interval;intervalMs;onMetrics;constructor(e,t){this.started=!1,this._emitMetrics=this._emitMetrics.bind(this),this.intervalMs=t.intervalMs??1e3,this.onMetrics=t.onMetrics,this.transferStats=new Map}[Symbol.toStringTag]="@libp2p/metrics-simple";[R]=["@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[t,n]of this.metrics.entries())n instanceof k?e[t]=n.value:n instanceof U?e[t]=n.values:e[t]=await n();this.onMetrics(structuredClone(e))}).catch(e=>{ke.error("could not invoke onMetrics callback",e)})}_incrementValue(e,t){let n=this.transferStats.get(e)??0;this.transferStats.set(e,n+t)}_track(e,t){let n=this,s=e.sink;e.sink=async function(u){await s(V(u,f=>{n._incrementValue(`${t} sent`,f.byteLength)}))};let d=e.source;e.source=V(d,m=>{n._incrementValue(`${t} received`,m.byteLength)})}trackMultiaddrConnection(e){this._track(e,"global")}trackProtocolStream(e,t){e.protocol!=null&&this._track(e,e.protocol)}registerMetric(e,t={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(t?.calculate!=null){this.metrics.set(e,t.calculate);return}let n=new k;return this.metrics.set(e,n),n}registerMetricGroup(e,t={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(t?.calculate!=null){this.metrics.set(e,t.calculate);return}let n=new U;return this.metrics.set(e,n),n}registerCounter(e,t={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(t?.calculate!=null){this.metrics.set(e,t.calculate);return}let n=new k;return this.metrics.set(e,n),n}registerCounterGroup(e,t={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(t?.calculate!=null){this.metrics.set(e,t.calculate);return}let n=new U;return this.metrics.set(e,n),n}};function Ue(r){return e=>new q(e,r)}return se($e);})();
2
+ "use strict";var Libp2PSimpleMetrics=(()=>{var z=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var re=Object.prototype.hasOwnProperty;var ne=(r,e)=>{for(var t in e)z(r,t,{get:e[t],enumerable:!0})},oe=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of te(e))!re.call(r,o)&&o!==t&&z(r,o,{get:()=>e[o],enumerable:!(n=ee(e,o))||n.enumerable});return r};var se=r=>oe(z({},"__esModule",{value:!0}),r);var $e={};ne($e,{simpleMetrics:()=>Ue});var R=Symbol.for("@libp2p/service-capabilities"),Ne=Symbol.for("@libp2p/service-dependencies");var rt=new Uint8Array(0);function T(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function ie(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var o=0;o<r.length;o++){var d=r.charAt(o),m=d.charCodeAt(0);if(t[m]!==255)throw new TypeError(d+" is ambiguous");t[m]=o}var f=r.length,u=r.charAt(0),E=Math.log(f)/Math.log(256),s=Math.log(256)/Math.log(f);function i(a){if(a instanceof Uint8Array||(ArrayBuffer.isView(a)?a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength):Array.isArray(a)&&(a=Uint8Array.from(a))),!(a instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(a.length===0)return"";for(var c=0,p=0,h=0,C=a.length;h!==C&&a[h]===0;)h++,c++;for(var y=(C-h)*s+1>>>0,b=new Uint8Array(y);h!==C;){for(var A=a[h],F=0,w=y-1;(A!==0||F<p)&&w!==-1;w--,F++)A+=256*b[w]>>>0,b[w]=A%f>>>0,A=A/f>>>0;if(A!==0)throw new Error("Non-zero carry");p=F,h++}for(var v=y-p;v!==y&&b[v]===0;)v++;for(var M=u.repeat(c);v<y;++v)M+=r.charAt(b[v]);return M}function l(a){if(typeof a!="string")throw new TypeError("Expected String");if(a.length===0)return new Uint8Array;var c=0;if(a[c]!==" "){for(var p=0,h=0;a[c]===u;)p++,c++;for(var C=(a.length-c)*E+1>>>0,y=new Uint8Array(C);a[c];){var b=t[a.charCodeAt(c)];if(b===255)return;for(var A=0,F=C-1;(b!==0||A<h)&&F!==-1;F--,A++)b+=f*y[F]>>>0,y[F]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");h=A,c++}if(a[c]!==" "){for(var w=C-h;w!==C&&y[w]===0;)w++;for(var v=new Uint8Array(p+(C-w)),M=p;w!==C;)v[M++]=y[w++];return v}}}function S(a){var c=l(a);if(c)return c;throw new Error(`Non-${e} character`)}return{encode:i,decodeUnsafe:l,decode:S}}var ae=ie,ce=ae,B=ce;var I=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},P=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 J(this,e)}},j=class{decoders;constructor(e){this.decoders=e}or(e){return J(this,e)}decode(e){let t=e[0],n=this.decoders[t];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 J(r,e){return new j({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var D=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new I(e,t,n),this.decoder=new P(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function G({name:r,prefix:e,encode:t,decode:n}){return new D(r,e,t,n)}function L({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=B(t,r);return G({prefix:e,name:r,encode:n,decode:d=>T(o(d))})}function fe(r,e,t,n){let o={};for(let s=0;s<e.length;++s)o[e[s]]=s;let d=r.length;for(;r[d-1]==="=";)--d;let m=new Uint8Array(d*t/8|0),f=0,u=0,E=0;for(let s=0;s<d;++s){let i=o[r[s]];if(i===void 0)throw new SyntaxError(`Non-${n} character`);u=u<<t|i,f+=t,f>=8&&(f-=8,m[E++]=255&u>>f)}if(f>=t||255&u<<8-f)throw new SyntaxError("Unexpected end of data");return m}function ue(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,d="",m=0,f=0;for(let u=0;u<r.length;++u)for(f=f<<8|r[u],m+=8;m>t;)m-=t,d+=e[o&f>>m];if(m!==0&&(d+=e[o&f<<t-m]),n)for(;d.length*t&7;)d+="=";return d}function x({name:r,prefix:e,bitsPerChar:t,alphabet:n}){return G({prefix:e,name:r,encode(o){return ue(o,n,t)},decode(o){return fe(o,n,t,r)}})}var X=x({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ft=x({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ut=x({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),lt=x({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),dt=x({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),pt=x({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ht=x({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),mt=x({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),bt=x({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Z=L({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),wt=L({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var K=x({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ft=x({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),vt=x({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Et=x({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});function le(r,e){try{if(typeof r=="string"&&r.length>0)return de(r);if(typeof r=="number"&&isFinite(r))return e?.long?he(r):pe(r);throw new Error("Value is not a string or number.")}catch(t){let n=me(t)?`${t.message}. value=${JSON.stringify(r)}`:"An unknown error has occured.";throw new Error(n)}}function de(r){if(r=String(r),r.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(r);if(!e)return NaN;let t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*315576e5;case"weeks":case"week":case"w":return t*6048e5;case"days":case"day":case"d":return t*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return t*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return t*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return t*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}var O=le;function pe(r){let e=Math.abs(r);return e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function he(r){let e=Math.abs(r);return e>=864e5?$(r,e,864e5,"day"):e>=36e5?$(r,e,36e5,"hour"):e>=6e4?$(r,e,6e4,"minute"):e>=1e3?$(r,e,1e3,"second"):`${r} ms`}function $(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}function me(r){return typeof r=="object"&&r!==null&&"message"in r}function _(r){t.debug=t,t.default=t,t.coerce=u,t.disable=d,t.enable=o,t.enabled=m,t.humanize=O,t.destroy=E,Object.keys(r).forEach(s=>{t[s]=r[s]}),t.names=[],t.skips=[],t.formatters={};function e(s){let i=0;for(let l=0;l<s.length;l++)i=(i<<5)-i+s.charCodeAt(l),i|=0;return t.colors[Math.abs(i)%t.colors.length]}t.selectColor=e;function t(s){let i,l=null,S,a;function c(...p){if(!c.enabled)return;let h=c,C=Number(new Date),y=C-(i||C);h.diff=y,h.prev=i,h.curr=C,i=C,p[0]=t.coerce(p[0]),typeof p[0]!="string"&&p.unshift("%O");let b=0;p[0]=p[0].replace(/%([a-zA-Z%])/g,(F,w)=>{if(F==="%%")return"%";b++;let v=t.formatters[w];if(typeof v=="function"){let M=p[b];F=v.call(h,M),p.splice(b,1),b--}return F}),t.formatArgs.call(h,p),(h.log||t.log).apply(h,p)}return c.namespace=s,c.useColors=t.useColors(),c.color=t.selectColor(s),c.extend=n,c.destroy=t.destroy,Object.defineProperty(c,"enabled",{enumerable:!0,configurable:!1,get:()=>l!==null?l:(S!==t.namespaces&&(S=t.namespaces,a=t.enabled(s)),a),set:p=>{l=p}}),typeof t.init=="function"&&t.init(c),c}function n(s,i){let l=t(this.namespace+(typeof i>"u"?":":i)+s);return l.log=this.log,l}function o(s){t.save(s),t.namespaces=s,t.names=[],t.skips=[];let i,l=(typeof s=="string"?s:"").split(/[\s,]+/),S=l.length;for(i=0;i<S;i++)l[i]&&(s=l[i].replace(/\*/g,".*?"),s[0]==="-"?t.skips.push(new RegExp("^"+s.substr(1)+"$")):t.names.push(new RegExp("^"+s+"$")))}function d(){let s=[...t.names.map(f),...t.skips.map(f).map(i=>"-"+i)].join(",");return t.enable(""),s}function m(s){if(s[s.length-1]==="*")return!0;let i,l;for(i=0,l=t.skips.length;i<l;i++)if(t.skips[i].test(s))return!1;for(i=0,l=t.names.length;i<l;i++)if(t.names[i].test(s))return!0;return!1}function f(s){return s.toString().substring(2,s.toString().length-2).replace(/\.\*\?$/,"*")}function u(s){return s instanceof Error?s.stack??s.message:s}function E(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var N=Fe(),be=["#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 Ce(){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 xe(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+O(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}var we=console.debug??console.log??(()=>{});function ge(r){try{r?N?.setItem("debug",r):N?.removeItem("debug")}catch{}}function ye(){let r;try{r=N?.getItem("debug")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function Fe(){try{return localStorage}catch{}}function ve(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Q=_({formatArgs:xe,save:ge,load:ye,useColors:Ce,setupFormatters:ve,colors:be,storage:N,log:we});var g=Q;g.formatters.b=r=>r==null?"undefined":Z.baseEncode(r);g.formatters.t=r=>r==null?"undefined":X.baseEncode(r);g.formatters.m=r=>r==null?"undefined":K.baseEncode(r);g.formatters.p=r=>r==null?"undefined":r.toString();g.formatters.c=r=>r==null?"undefined":r.toString();g.formatters.k=r=>r==null?"undefined":r.toString();g.formatters.a=r=>r==null?"undefined":r.toString();function Ee(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function W(r){let e=Ee(`${r}:trace`);return g.enabled(`${r}:trace`)&&g.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=g(`${r}:trace`)),Object.assign(g(r),{error:g(`${r}:error`),trace:e})}function Ae(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:o=>{n.push(o)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var Y=Ae;function Se(r){return r[Symbol.asyncIterator]!=null}function H(r){return r?.then!=null}function Me(r,e){let t=0;if(Se(r))return async function*(){for await(let u of r){let E=e(u,t++);H(E)&&await E,yield u}}();let n=Y(r),{value:o,done:d}=n.next();if(d===!0)return function*(){}();if(typeof e(o,t++)?.then=="function")return async function*(){yield o;for await(let u of n){let E=e(u,t++);H(E)&&await E,yield u}}();let f=e;return function*(){yield o;for(let u of n)f(u,t++),yield u}()}var V=Me;var ke=W("libp2p:simple-metrics"),k=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}}},U=class{values={};update(e){Object.entries(e).forEach(([t,n])=>{this.values[t]=n})}increment(e){Object.entries(e).forEach(([t,n])=>{this.values[t]=this.values[t]??0;let o=typeof n=="number"?n:1;this.values[t]+=Number(o)})}decrement(e){Object.entries(e).forEach(([t,n])=>{this.values[t]=this.values[t]??0;let o=typeof n=="number"?n:1;this.values[t]-=Number(o)})}reset(){this.values={}}timer(e){let t=Date.now();return()=>{this.values[e]=Date.now()-t}}},q=class{metrics=new Map;transferStats;started;interval;intervalMs;onMetrics;constructor(e,t){this.started=!1,this._emitMetrics=this._emitMetrics.bind(this),this.intervalMs=t.intervalMs??1e3,this.onMetrics=t.onMetrics,this.transferStats=new Map}[Symbol.toStringTag]="@libp2p/metrics-simple";[R]=["@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[t,n]of this.metrics.entries())n instanceof k?e[t]=n.value:n instanceof U?e[t]=n.values:e[t]=await n();this.onMetrics(structuredClone(e))}).catch(e=>{ke.error("could not invoke onMetrics callback",e)})}_incrementValue(e,t){let n=this.transferStats.get(e)??0;this.transferStats.set(e,n+t)}_track(e,t){let n=this,o=e.sink;e.sink=async function(f){await o(V(f,u=>{n._incrementValue(`${t} sent`,u.byteLength)}))};let d=e.source;e.source=V(d,m=>{n._incrementValue(`${t} received`,m.byteLength)})}trackMultiaddrConnection(e){this._track(e,"global")}trackProtocolStream(e,t){e.protocol!=null&&this._track(e,e.protocol)}registerMetric(e,t={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(t?.calculate!=null){this.metrics.set(e,t.calculate);return}let n=new k;return this.metrics.set(e,n),n}registerMetricGroup(e,t={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(t?.calculate!=null){this.metrics.set(e,t.calculate);return}let n=new U;return this.metrics.set(e,n),n}registerCounter(e,t={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(t?.calculate!=null){this.metrics.set(e,t.calculate);return}let n=new k;return this.metrics.set(e,n),n}registerCounterGroup(e,t={}){if(e==null||e.trim()==="")throw new Error("Metric name is required");if(t?.calculate!=null){this.metrics.set(e,t.calculate);return}let n=new U;return this.metrics.set(e,n),n}};function Ue(r){return e=>new q(e,r)}return se($e);})();
3
3
  return Libp2PSimpleMetrics}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@libp2p/simple-metrics",
3
- "version": "1.1.6",
3
+ "version": "1.1.7-6ccbb06f0",
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",
@@ -50,8 +50,8 @@
50
50
  "dep-check": "aegir dep-check -i events"
51
51
  },
52
52
  "dependencies": {
53
- "@libp2p/interface": "^2.0.0",
54
- "@libp2p/logger": "^5.0.0",
53
+ "@libp2p/interface": "2.0.1-6ccbb06f0",
54
+ "@libp2p/logger": "5.0.1-6ccbb06f0",
55
55
  "it-foreach": "^2.1.0",
56
56
  "it-stream-types": "^2.0.1"
57
57
  },
@@ -1,8 +0,0 @@
1
- {
2
- "OnMetrics": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_simple_metrics.OnMetrics.html",
3
- ".:OnMetrics": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_simple_metrics.OnMetrics.html",
4
- "SimpleMetricsInit": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_simple_metrics.SimpleMetricsInit.html",
5
- ".:SimpleMetricsInit": "https://libp2p.github.io/js-libp2p/interfaces/_libp2p_simple_metrics.SimpleMetricsInit.html",
6
- "simpleMetrics": "https://libp2p.github.io/js-libp2p/functions/_libp2p_simple_metrics.simpleMetrics.html",
7
- ".:simpleMetrics": "https://libp2p.github.io/js-libp2p/functions/_libp2p_simple_metrics.simpleMetrics.html"
8
- }