@mts-pjsc/bretrics
Version:
115 lines • 3.89 kB
JavaScript
import { onLCP, onCLS, onFCP, onINP, onTTFB } from "web-vitals";
export class Bretrics {
constructor() {
this.apiPath = "/bretrics";
this.labels = {};
}
sendWebVitalsMetrics() {
onLCP((metric) => this.sendWebVitals(metric));
onCLS((metric) => this.sendWebVitals(metric));
onFCP((metric) => this.sendWebVitals(metric));
onINP((metric) => this.sendWebVitals(metric));
onTTFB((metric) => this.sendWebVitals(metric));
return this;
}
setup(config) {
this.apiPath = config.apiPath ?? this.apiPath;
return this;
}
sendMetrics(metric) {
this.sendToMicroservice(metric);
return this;
}
useDefaultMonitoring() {
this.useDefaultLabels();
this.sendWebVitalsMetrics();
Promise.resolve().then(() => {
this.sendMetrics({
// eslint-disable-next-line camelcase
elements_count: document.getElementsByTagName("*").length
});
});
return this;
}
useDefaultLabels() {
const defaultLabels = {
// eslint-disable-next-line camelcase
device_type: this.getDeviceType(),
path: decodeURIComponent(location.pathname) // Decode for human readable non latin chars
};
this.labels = {
...this.labels,
...defaultLabels
};
return this;
}
setLabels(labels) {
this.labels = {
...this.labels,
...labels
};
return this;
}
sendWebVitals(webVitalsMetric) {
const webmonMetrics = {};
Reflect.set(webmonMetrics, webVitalsMetric.name.toLowerCase(), webVitalsMetric.value);
this.sendToMicroservice(webmonMetrics);
}
sendToMicroservice(metrics) {
const path = `${this.apiPath}/send-metrics/metrics`;
const body = JSON.stringify(this.prepareData(metrics));
if (typeof navigator.sendBeacon === "function") {
navigator.sendBeacon(path, body);
}
else {
fetch(path, {
body,
method: "POST",
keepalive: true
});
}
}
prepareData(metrics) {
const sendMetrics = {};
const metricsNames = Reflect.ownKeys(metrics);
const labelsCount = Reflect.ownKeys(this.labels).length;
for (const metricsName of metricsNames) {
const metricValue = Reflect.get(metrics, metricsName);
if (typeof metricValue === "number" && labelsCount === 0) {
Reflect.set(sendMetrics, metricsName, metricValue);
}
else if (typeof metricValue === "number") {
Reflect.set(sendMetrics, metricsName, {
value: metricValue,
labels: this.labels
});
}
else {
Reflect.set(sendMetrics, metricsName, {
value: metricValue.value,
labels: {
...this.labels,
...metricValue.labels
}
});
}
}
return sendMetrics;
}
// eslint-disable-next-line class-methods-use-this
getDeviceType() {
const ua = navigator.userAgent;
// eslint-disable-next-line prefer-named-capture-group
if ((/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/iu).test(ua)) {
return "tablet";
}
if (
// eslint-disable-next-line prefer-named-capture-group
(/Mobile|iP(hone|od)|Android|BlackBerry|IEMobile|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/u).test(ua)) {
return "mobile";
}
return "desktop";
}
}
export const bretrics = new Bretrics();
//# sourceMappingURL=index.js.map