blob: f004cfddfa07588e502d27a71bf58f45bffa3601 [file]
// Copyright 2024 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Main analytics library. Defines extension-specific interfaces and provides the addEvent API.
// Exception: valid use of snake_case for property name to match the json field name
/* eslint-disable @typescript-eslint/naming-convention */
import { send, type UserProperties, type Measurement, type Event, createMeasurement } from './ga4';
import { AnalyticsInfo } from './info';
import { AnalyticsState } from './state';
interface FuchsiaUserProperties {
[key: string]: string | number | boolean | undefined;
os?: string;
arch?: string;
version?: string;
bot?: boolean;
internal: boolean;
metrics_level: number;
}
class FuchsiaUserPropertiesEncoded implements UserProperties {
[key: keyof (FuchsiaUserProperties)]: UserProperties[keyof (UserProperties)];
constructor(properties: FuchsiaUserProperties) {
for (const [index, value] of Object.entries(properties)) {
if (value !== undefined) {
this[index] = { value: value };
}
}
}
}
/**
* When analytics is allowed, wrap an Event in a Measurement and send it to the GA4 endpoint
* @param event the Event to send
*/
export async function addEvent(event: Event): Promise<void> {
if (AnalyticsState.optInLevel === 0 || !AnalyticsInfo.uuid) {
return;
}
const userProperties = new FuchsiaUserPropertiesEncoded(
{
os: AnalyticsInfo.os,
arch: AnalyticsInfo.arch,
version: AnalyticsInfo.extensionVersion,
internal: AnalyticsInfo.isInternalUser,
metrics_level: AnalyticsState.optInLevel,
});
const measurement: Measurement = createMeasurement(AnalyticsInfo.uuid, [event], userProperties);
await send(measurement, AnalyticsState.debugLevel);
}