blob: 90b65d400c8672645685d31620d06f0a4e4dfc20 [file] [log] [blame] [edit]
// 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, UserProperties, Measurement, 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) {
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 as string, [event], userProperties);
await send(measurement, AnalyticsState.debugLevel);
}