summaryrefslogtreecommitdiff
path: root/shared/metrics-8/src/utils/metrics-dev-console/setup-metrics-dev.ts
blob: fb7def6385383c0eae7457d1d4bf18dcac83e5d2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { isFlushEvent, makeFlushEvent } from './events/flush-event';
import { makeRecordEvent } from './events/record-event';
import type { MetricsOptions, FlushEvent, MetricsObject } from './type';

/**
 * Updates the metrics console by dispatching appropriate events
 */
const updateMetricsConsole = (
    topic: string,
    metricsData: MetricsOptions | FlushEvent,
): void => {
    let event = null;
    const { metricsDevType, ...data } = metricsData ?? ({} as MetricsObject);

    if (isFlushEvent(metricsData)) {
        event = makeFlushEvent(metricsData, topic);
    } else if (metricsData) {
        event = makeRecordEvent(data, topic);
    }

    if (event) {
        try {
            window.dispatchEvent(event);
        } catch (e) {
            console.error('metric console failed', e);
        }
    }
};

const isMetricsDevConsoleEnabled = () => {
    return (
        typeof window !== 'undefined' &&
        window.localStorage?.getItem('metrics-dev') === 'true'
    );
};

/**
 * Sends metrics data to the development console if enabled
 * @param metricsData - The metrics data to send
 * @param topic - The topic/category for the metrics
 */
export const sendToMetricsDevConsole = (
    metricsData: MetricsOptions,
    topic: string,
): void => {
    if (import.meta.env.APP_SCOPE === 'internal') {
        if (isMetricsDevConsoleEnabled()) {
            try {
                updateMetricsConsole(topic, metricsData);
            } catch (error) {
                console.warn('Failed to send metrics to dev console:', error);
            }
        }
    }
};