41 lines
1.5 KiB
JavaScript
41 lines
1.5 KiB
JavaScript
let telemetryPromise = null;
|
||
const pendingUxEvents = [];
|
||
|
||
export function initializeTelemetry() {
|
||
if (['localhost', '127.0.0.1', '::1'].includes(window.location.hostname)) {
|
||
return Promise.resolve();
|
||
}
|
||
if (!telemetryPromise) {
|
||
telemetryPromise = import('/vendor/otel.js').then(() => flushPendingUxEvents()).catch(error => {
|
||
console.warn('Не удалось инициализировать браузерную телеметрию');
|
||
});
|
||
}
|
||
return telemetryPromise;
|
||
}
|
||
|
||
export function trackUxEvent(name, attributes = {}) {
|
||
const event = {
|
||
name: String(name || 'неизвестное_событие'),
|
||
attributes: sanitizeAttributes(attributes),
|
||
timestamp: new Date().toISOString()
|
||
};
|
||
document.dispatchEvent(new CustomEvent('magistr:ux-event', { detail: event }));
|
||
if (typeof window.__magistrTrackUx === 'function') {
|
||
window.__magistrTrackUx(event.name, event.attributes);
|
||
} else {
|
||
pendingUxEvents.push(event);
|
||
if (pendingUxEvents.length > 100) pendingUxEvents.shift();
|
||
}
|
||
}
|
||
|
||
export function flushPendingUxEvents() {
|
||
if (typeof window.__magistrTrackUx !== 'function') return;
|
||
pendingUxEvents.splice(0).forEach(event => window.__magistrTrackUx(event.name, event.attributes));
|
||
}
|
||
|
||
function sanitizeAttributes(attributes) {
|
||
return Object.fromEntries(Object.entries(attributes || {})
|
||
.filter(([, value]) => ['string', 'number', 'boolean'].includes(typeof value))
|
||
.map(([key, value]) => [String(key), value]));
|
||
}
|