Sign In

@metamask/analytics-controller

Package Overview
Dependencies
Maintainers
3
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@metamask/analytics-controller - npm Package Compare versions

Comparing version
1.0.1
to
1.1.0
+16
-1
CHANGELOG.md

@@ -10,2 +10,16 @@ # Changelog

## [1.1.0]
### Added
- Optional persisted event queue support in `AnalyticsController`, disabled by default. ([#8797](https://github.com/MetaMask/core/pull/8797))
- Add optional analytics context on `trackEvent`, `identify`, and `trackView` to forward platform-specific context to `AnalyticsPlatformAdapter` implementations ([#8835](https://github.com/MetaMask/core/pull/8835))
- Optional `skipUUIDv4Check` on `AnalyticsPlatformAdapter` to allow non-UUIDv4 `analyticsId` strings when constructing `AnalyticsController` ([#8543](https://github.com/MetaMask/core/pull/8543))
### Changed
- Mark `analyticsId` as persisted (`persist: true`) in `AnalyticsController` state metadata so it is saved and restored with `optedIn` when using a persisted controller composition ([#8542](https://github.com/MetaMask/core/pull/8542))
- Bump `@metamask/messenger` from `^1.0.0` to `^1.2.0` ([#8364](https://github.com/MetaMask/core/pull/8364), [#8373](https://github.com/MetaMask/core/pull/8373), [#8632](https://github.com/MetaMask/core/pull/8632))
- Bump `@metamask/base-controller` from `^9.0.1` to `^9.1.0` ([#8457](https://github.com/MetaMask/core/pull/8457))
## [1.0.1]

@@ -25,4 +39,5 @@

[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/analytics-controller@1.0.1...HEAD
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/analytics-controller@1.1.0...HEAD
[1.1.0]: https://github.com/MetaMask/core/compare/@metamask/analytics-controller@1.0.1...@metamask/analytics-controller@1.1.0
[1.0.1]: https://github.com/MetaMask/core/compare/@metamask/analytics-controller@1.0.0...@metamask/analytics-controller@1.0.1
[1.0.0]: https://github.com/MetaMask/core/releases/tag/@metamask/analytics-controller@1.0.0
+1
-1

@@ -1,1 +0,1 @@

{"version":3,"file":"AnalyticsController-method-action-types.cjs","sourceRoot":"","sources":["../src/AnalyticsController-method-action-types.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { AnalyticsController } from './AnalyticsController';\n\n/**\n * Track an analytics event.\n *\n * Events are only tracked if analytics is enabled.\n *\n * @param event - Analytics event with properties and sensitive properties\n */\nexport type AnalyticsControllerTrackEventAction = {\n type: `AnalyticsController:trackEvent`;\n handler: AnalyticsController['trackEvent'];\n};\n\n/**\n * Identify a user for analytics.\n *\n * @param traits - User traits/properties\n */\nexport type AnalyticsControllerIdentifyAction = {\n type: `AnalyticsController:identify`;\n handler: AnalyticsController['identify'];\n};\n\n/**\n * Track a page or screen view.\n *\n * @param name - The identifier/name of the page or screen being viewed (e.g., \"home\", \"settings\", \"wallet\")\n * @param properties - Optional properties associated with the view\n */\nexport type AnalyticsControllerTrackViewAction = {\n type: `AnalyticsController:trackView`;\n handler: AnalyticsController['trackView'];\n};\n\n/**\n * Opt in to analytics.\n */\nexport type AnalyticsControllerOptInAction = {\n type: `AnalyticsController:optIn`;\n handler: AnalyticsController['optIn'];\n};\n\n/**\n * Opt out of analytics.\n */\nexport type AnalyticsControllerOptOutAction = {\n type: `AnalyticsController:optOut`;\n handler: AnalyticsController['optOut'];\n};\n\n/**\n * Union of all AnalyticsController action types.\n */\nexport type AnalyticsControllerMethodActions =\n | AnalyticsControllerTrackEventAction\n | AnalyticsControllerIdentifyAction\n | AnalyticsControllerTrackViewAction\n | AnalyticsControllerOptInAction\n | AnalyticsControllerOptOutAction;\n"]}
{"version":3,"file":"AnalyticsController-method-action-types.cjs","sourceRoot":"","sources":["../src/AnalyticsController-method-action-types.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { AnalyticsController } from './AnalyticsController';\n\n/**\n * Track an analytics event.\n *\n * Events are only tracked if analytics is enabled.\n *\n * @param event - Analytics event with properties and sensitive properties\n * @param context - Optional platform-specific context forwarded to the platform adapter.\n */\nexport type AnalyticsControllerTrackEventAction = {\n type: `AnalyticsController:trackEvent`;\n handler: AnalyticsController['trackEvent'];\n};\n\n/**\n * Identify a user for analytics.\n *\n * @param traits - User traits/properties\n * @param context - Optional platform-specific context forwarded to the platform adapter.\n */\nexport type AnalyticsControllerIdentifyAction = {\n type: `AnalyticsController:identify`;\n handler: AnalyticsController['identify'];\n};\n\n/**\n * Track a page or screen view.\n *\n * @param name - The identifier/name of the page or screen being viewed (e.g., \"home\", \"settings\", \"wallet\")\n * @param properties - Optional properties associated with the view\n * @param context - Optional platform-specific context forwarded to the platform adapter.\n */\nexport type AnalyticsControllerTrackViewAction = {\n type: `AnalyticsController:trackView`;\n handler: AnalyticsController['trackView'];\n};\n\n/**\n * Opt in to analytics.\n */\nexport type AnalyticsControllerOptInAction = {\n type: `AnalyticsController:optIn`;\n handler: AnalyticsController['optIn'];\n};\n\n/**\n * Opt out of analytics.\n */\nexport type AnalyticsControllerOptOutAction = {\n type: `AnalyticsController:optOut`;\n handler: AnalyticsController['optOut'];\n};\n\n/**\n * Union of all AnalyticsController action types.\n */\nexport type AnalyticsControllerMethodActions =\n | AnalyticsControllerTrackEventAction\n | AnalyticsControllerIdentifyAction\n | AnalyticsControllerTrackViewAction\n | AnalyticsControllerOptInAction\n | AnalyticsControllerOptOutAction;\n"]}

@@ -12,2 +12,3 @@ /**

* @param event - Analytics event with properties and sensitive properties
* @param context - Optional platform-specific context forwarded to the platform adapter.
*/

@@ -22,2 +23,3 @@ export type AnalyticsControllerTrackEventAction = {

* @param traits - User traits/properties
* @param context - Optional platform-specific context forwarded to the platform adapter.
*/

@@ -33,2 +35,3 @@ export type AnalyticsControllerIdentifyAction = {

* @param properties - Optional properties associated with the view
* @param context - Optional platform-specific context forwarded to the platform adapter.
*/

@@ -35,0 +38,0 @@ export type AnalyticsControllerTrackViewAction = {

@@ -1,1 +0,1 @@

{"version":3,"file":"AnalyticsController-method-action-types.d.cts","sourceRoot":"","sources":["../src/AnalyticsController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,kCAA8B;AAEjE;;;;;;GAMG;AACH,MAAM,MAAM,mCAAmC,GAAG;IAChD,IAAI,EAAE,gCAAgC,CAAC;IACvC,OAAO,EAAE,mBAAmB,CAAC,YAAY,CAAC,CAAC;CAC5C,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,iCAAiC,GAAG;IAC9C,IAAI,EAAE,8BAA8B,CAAC;IACrC,OAAO,EAAE,mBAAmB,CAAC,UAAU,CAAC,CAAC;CAC1C,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,kCAAkC,GAAG;IAC/C,IAAI,EAAE,+BAA+B,CAAC;IACtC,OAAO,EAAE,mBAAmB,CAAC,WAAW,CAAC,CAAC;CAC3C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,8BAA8B,GAAG;IAC3C,IAAI,EAAE,2BAA2B,CAAC;IAClC,OAAO,EAAE,mBAAmB,CAAC,OAAO,CAAC,CAAC;CACvC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,+BAA+B,GAAG;IAC5C,IAAI,EAAE,4BAA4B,CAAC;IACnC,OAAO,EAAE,mBAAmB,CAAC,QAAQ,CAAC,CAAC;CACxC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,gCAAgC,GACxC,mCAAmC,GACnC,iCAAiC,GACjC,kCAAkC,GAClC,8BAA8B,GAC9B,+BAA+B,CAAC"}
{"version":3,"file":"AnalyticsController-method-action-types.d.cts","sourceRoot":"","sources":["../src/AnalyticsController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,kCAA8B;AAEjE;;;;;;;GAOG;AACH,MAAM,MAAM,mCAAmC,GAAG;IAChD,IAAI,EAAE,gCAAgC,CAAC;IACvC,OAAO,EAAE,mBAAmB,CAAC,YAAY,CAAC,CAAC;CAC5C,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,iCAAiC,GAAG;IAC9C,IAAI,EAAE,8BAA8B,CAAC;IACrC,OAAO,EAAE,mBAAmB,CAAC,UAAU,CAAC,CAAC;CAC1C,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,kCAAkC,GAAG;IAC/C,IAAI,EAAE,+BAA+B,CAAC;IACtC,OAAO,EAAE,mBAAmB,CAAC,WAAW,CAAC,CAAC;CAC3C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,8BAA8B,GAAG;IAC3C,IAAI,EAAE,2BAA2B,CAAC;IAClC,OAAO,EAAE,mBAAmB,CAAC,OAAO,CAAC,CAAC;CACvC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,+BAA+B,GAAG;IAC5C,IAAI,EAAE,4BAA4B,CAAC;IACnC,OAAO,EAAE,mBAAmB,CAAC,QAAQ,CAAC,CAAC;CACxC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,gCAAgC,GACxC,mCAAmC,GACnC,iCAAiC,GACjC,kCAAkC,GAClC,8BAA8B,GAC9B,+BAA+B,CAAC"}

@@ -12,2 +12,3 @@ /**

* @param event - Analytics event with properties and sensitive properties
* @param context - Optional platform-specific context forwarded to the platform adapter.
*/

@@ -22,2 +23,3 @@ export type AnalyticsControllerTrackEventAction = {

* @param traits - User traits/properties
* @param context - Optional platform-specific context forwarded to the platform adapter.
*/

@@ -33,2 +35,3 @@ export type AnalyticsControllerIdentifyAction = {

* @param properties - Optional properties associated with the view
* @param context - Optional platform-specific context forwarded to the platform adapter.
*/

@@ -35,0 +38,0 @@ export type AnalyticsControllerTrackViewAction = {

@@ -1,1 +0,1 @@

{"version":3,"file":"AnalyticsController-method-action-types.d.mts","sourceRoot":"","sources":["../src/AnalyticsController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,kCAA8B;AAEjE;;;;;;GAMG;AACH,MAAM,MAAM,mCAAmC,GAAG;IAChD,IAAI,EAAE,gCAAgC,CAAC;IACvC,OAAO,EAAE,mBAAmB,CAAC,YAAY,CAAC,CAAC;CAC5C,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,iCAAiC,GAAG;IAC9C,IAAI,EAAE,8BAA8B,CAAC;IACrC,OAAO,EAAE,mBAAmB,CAAC,UAAU,CAAC,CAAC;CAC1C,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,kCAAkC,GAAG;IAC/C,IAAI,EAAE,+BAA+B,CAAC;IACtC,OAAO,EAAE,mBAAmB,CAAC,WAAW,CAAC,CAAC;CAC3C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,8BAA8B,GAAG;IAC3C,IAAI,EAAE,2BAA2B,CAAC;IAClC,OAAO,EAAE,mBAAmB,CAAC,OAAO,CAAC,CAAC;CACvC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,+BAA+B,GAAG;IAC5C,IAAI,EAAE,4BAA4B,CAAC;IACnC,OAAO,EAAE,mBAAmB,CAAC,QAAQ,CAAC,CAAC;CACxC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,gCAAgC,GACxC,mCAAmC,GACnC,iCAAiC,GACjC,kCAAkC,GAClC,8BAA8B,GAC9B,+BAA+B,CAAC"}
{"version":3,"file":"AnalyticsController-method-action-types.d.mts","sourceRoot":"","sources":["../src/AnalyticsController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,kCAA8B;AAEjE;;;;;;;GAOG;AACH,MAAM,MAAM,mCAAmC,GAAG;IAChD,IAAI,EAAE,gCAAgC,CAAC;IACvC,OAAO,EAAE,mBAAmB,CAAC,YAAY,CAAC,CAAC;CAC5C,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,iCAAiC,GAAG;IAC9C,IAAI,EAAE,8BAA8B,CAAC;IACrC,OAAO,EAAE,mBAAmB,CAAC,UAAU,CAAC,CAAC;CAC1C,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,MAAM,kCAAkC,GAAG;IAC/C,IAAI,EAAE,+BAA+B,CAAC;IACtC,OAAO,EAAE,mBAAmB,CAAC,WAAW,CAAC,CAAC;CAC3C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,8BAA8B,GAAG;IAC3C,IAAI,EAAE,2BAA2B,CAAC;IAClC,OAAO,EAAE,mBAAmB,CAAC,OAAO,CAAC,CAAC;CACvC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,+BAA+B,GAAG;IAC5C,IAAI,EAAE,4BAA4B,CAAC;IACnC,OAAO,EAAE,mBAAmB,CAAC,QAAQ,CAAC,CAAC;CACxC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,gCAAgC,GACxC,mCAAmC,GACnC,iCAAiC,GACjC,kCAAkC,GAClC,8BAA8B,GAC9B,+BAA+B,CAAC"}

@@ -1,1 +0,1 @@

{"version":3,"file":"AnalyticsController-method-action-types.mjs","sourceRoot":"","sources":["../src/AnalyticsController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { AnalyticsController } from './AnalyticsController';\n\n/**\n * Track an analytics event.\n *\n * Events are only tracked if analytics is enabled.\n *\n * @param event - Analytics event with properties and sensitive properties\n */\nexport type AnalyticsControllerTrackEventAction = {\n type: `AnalyticsController:trackEvent`;\n handler: AnalyticsController['trackEvent'];\n};\n\n/**\n * Identify a user for analytics.\n *\n * @param traits - User traits/properties\n */\nexport type AnalyticsControllerIdentifyAction = {\n type: `AnalyticsController:identify`;\n handler: AnalyticsController['identify'];\n};\n\n/**\n * Track a page or screen view.\n *\n * @param name - The identifier/name of the page or screen being viewed (e.g., \"home\", \"settings\", \"wallet\")\n * @param properties - Optional properties associated with the view\n */\nexport type AnalyticsControllerTrackViewAction = {\n type: `AnalyticsController:trackView`;\n handler: AnalyticsController['trackView'];\n};\n\n/**\n * Opt in to analytics.\n */\nexport type AnalyticsControllerOptInAction = {\n type: `AnalyticsController:optIn`;\n handler: AnalyticsController['optIn'];\n};\n\n/**\n * Opt out of analytics.\n */\nexport type AnalyticsControllerOptOutAction = {\n type: `AnalyticsController:optOut`;\n handler: AnalyticsController['optOut'];\n};\n\n/**\n * Union of all AnalyticsController action types.\n */\nexport type AnalyticsControllerMethodActions =\n | AnalyticsControllerTrackEventAction\n | AnalyticsControllerIdentifyAction\n | AnalyticsControllerTrackViewAction\n | AnalyticsControllerOptInAction\n | AnalyticsControllerOptOutAction;\n"]}
{"version":3,"file":"AnalyticsController-method-action-types.mjs","sourceRoot":"","sources":["../src/AnalyticsController-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { AnalyticsController } from './AnalyticsController';\n\n/**\n * Track an analytics event.\n *\n * Events are only tracked if analytics is enabled.\n *\n * @param event - Analytics event with properties and sensitive properties\n * @param context - Optional platform-specific context forwarded to the platform adapter.\n */\nexport type AnalyticsControllerTrackEventAction = {\n type: `AnalyticsController:trackEvent`;\n handler: AnalyticsController['trackEvent'];\n};\n\n/**\n * Identify a user for analytics.\n *\n * @param traits - User traits/properties\n * @param context - Optional platform-specific context forwarded to the platform adapter.\n */\nexport type AnalyticsControllerIdentifyAction = {\n type: `AnalyticsController:identify`;\n handler: AnalyticsController['identify'];\n};\n\n/**\n * Track a page or screen view.\n *\n * @param name - The identifier/name of the page or screen being viewed (e.g., \"home\", \"settings\", \"wallet\")\n * @param properties - Optional properties associated with the view\n * @param context - Optional platform-specific context forwarded to the platform adapter.\n */\nexport type AnalyticsControllerTrackViewAction = {\n type: `AnalyticsController:trackView`;\n handler: AnalyticsController['trackView'];\n};\n\n/**\n * Opt in to analytics.\n */\nexport type AnalyticsControllerOptInAction = {\n type: `AnalyticsController:optIn`;\n handler: AnalyticsController['optIn'];\n};\n\n/**\n * Opt out of analytics.\n */\nexport type AnalyticsControllerOptOutAction = {\n type: `AnalyticsController:optOut`;\n handler: AnalyticsController['optOut'];\n};\n\n/**\n * Union of all AnalyticsController action types.\n */\nexport type AnalyticsControllerMethodActions =\n | AnalyticsControllerTrackEventAction\n | AnalyticsControllerIdentifyAction\n | AnalyticsControllerTrackViewAction\n | AnalyticsControllerOptInAction\n | AnalyticsControllerOptOutAction;\n"]}

@@ -13,6 +13,8 @@ "use strict";

};
var _AnalyticsController_platformAdapter, _AnalyticsController_isAnonymousEventsFeatureEnabled, _AnalyticsController_initialized;
var _AnalyticsController_instances, _AnalyticsController_platformAdapter, _AnalyticsController_isAnonymousEventsFeatureEnabled, _AnalyticsController_isEventQueuePersistenceEnabled, _AnalyticsController_initialized, _AnalyticsController_sendOrQueueTrackEvent, _AnalyticsController_sendOrQueueIdentifyEvent, _AnalyticsController_sendOrQueueViewEvent, _AnalyticsController_enqueueEvent, _AnalyticsController_sendQueuedEvent, _AnalyticsController_replayQueuedEvents, _AnalyticsController_removeQueuedEvent, _AnalyticsController_clearQueuedEvents;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AnalyticsController = exports.getDefaultAnalyticsControllerState = exports.controllerName = void 0;
const base_controller_1 = require("@metamask/base-controller");
const lodash_1 = require("lodash");
const uuid_1 = require("uuid");
const analyticsControllerStateValidator_1 = require("./analyticsControllerStateValidator.cjs");

@@ -45,6 +47,4 @@ const AnalyticsLogger_1 = require("./AnalyticsLogger.cjs");

*
* Note: `optedIn` is persisted by the controller (`persist: true`).
* `analyticsId` is persisted by the platform (`persist: false`) and provided
* via initial state. The platform should subscribe to `stateChange` events
* to persist any state changes.
* Both `optedIn` and `analyticsId` are persisted (`persist: true`).
* The platform must supply a valid UUIDv4 `analyticsId` on first run.
*/

@@ -60,6 +60,12 @@ const analyticsControllerMetadata = {

includeInStateLogs: true,
persist: false,
persist: true,
includeInDebugSnapshot: true,
usedInUi: false,
},
eventQueue: {
includeInStateLogs: false,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
};

@@ -75,2 +81,42 @@ // === MESSENGER ===

/**
* Returns whether a value is a non-array object.
*
* @param value - The value to check.
* @returns True if the value is a record.
*/
function isRecord(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
/**
* Returns whether a value is a valid persisted analytics event.
*
* @param value - The value to check.
* @returns True if the value is a queued analytics event.
*/
function isAnalyticsQueuedEvent(value) {
if (!isRecord(value)) {
return false;
}
if (typeof value.messageId !== 'string' ||
typeof value.timestamp !== 'string') {
return false;
}
if (value.type === 'track') {
return (typeof value.eventName === 'string' &&
(value.properties === undefined || isRecord(value.properties)) &&
(value.context === undefined || isRecord(value.context)));
}
if (value.type === 'identify') {
return (typeof value.userId === 'string' &&
(value.traits === undefined || isRecord(value.traits)) &&
(value.context === undefined || isRecord(value.context)));
}
if (value.type === 'view') {
return (typeof value.name === 'string' &&
(value.properties === undefined || isRecord(value.properties)) &&
(value.context === undefined || isRecord(value.context)));
}
return false;
}
/**
* The AnalyticsController manages analytics tracking across platforms (Mobile/Extension).

@@ -85,5 +131,4 @@ * It provides a unified interface for tracking events, identifying users, and managing

*
* Note: The controller persists `optedIn` internally. The `analyticsId` is persisted
* by the platform and must be provided via initial state. The platform should subscribe
* to `AnalyticsController:stateChange` events to persist any state changes.
* The controller persists `optedIn` and `analyticsId` when composed with a persisted
* store. The platform must supply a valid `analyticsId` on first launch.
*/

@@ -100,6 +145,7 @@ class AnalyticsController extends base_controller_1.BaseController {

* @param options.isAnonymousEventsFeatureEnabled - Whether the anonymous events feature is enabled
* @param options.isEventQueuePersistenceEnabled - Whether analytics event queue persistence is enabled
* @throws Error if state.analyticsId is missing or not a valid UUIDv4
* @remarks After construction, call {@link AnalyticsController.init} to complete initialization.
*/
constructor({ state, messenger, platformAdapter, isAnonymousEventsFeatureEnabled = false, }) {
constructor({ state, messenger, platformAdapter, isAnonymousEventsFeatureEnabled = false, isEventQueuePersistenceEnabled = false, }) {
const initialState = {

@@ -109,3 +155,3 @@ ...getDefaultAnalyticsControllerState(),

};
(0, analyticsControllerStateValidator_1.validateAnalyticsControllerState)(initialState);
(0, analyticsControllerStateValidator_1.validateAnalyticsControllerState)(initialState, platformAdapter.skipUUIDv4Check === true);
super({

@@ -117,6 +163,9 @@ name: exports.controllerName,

});
_AnalyticsController_instances.add(this);
_AnalyticsController_platformAdapter.set(this, void 0);
_AnalyticsController_isAnonymousEventsFeatureEnabled.set(this, void 0);
_AnalyticsController_isEventQueuePersistenceEnabled.set(this, void 0);
_AnalyticsController_initialized.set(this, void 0);
__classPrivateFieldSet(this, _AnalyticsController_isAnonymousEventsFeatureEnabled, isAnonymousEventsFeatureEnabled, "f");
__classPrivateFieldSet(this, _AnalyticsController_isEventQueuePersistenceEnabled, isEventQueuePersistenceEnabled, "f");
__classPrivateFieldSet(this, _AnalyticsController_platformAdapter, platformAdapter, "f");

@@ -129,2 +178,3 @@ __classPrivateFieldSet(this, _AnalyticsController_initialized, false, "f");

analyticsId: this.state.analyticsId,
eventQueuePersistenceEnabled: __classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f"),
});

@@ -151,2 +201,3 @@ }

}
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_replayQueuedEvents).call(this);
}

@@ -159,4 +210,5 @@ /**

* @param event - Analytics event with properties and sensitive properties
* @param context - Optional platform-specific context forwarded to the platform adapter.
*/
trackEvent(event) {
trackEvent(event, context) {
// Don't track if analytics is disabled

@@ -169,3 +221,3 @@ if (!selectors_1.analyticsControllerSelectors.selectEnabled(this.state)) {

if (!event.hasProperties) {
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").track(event.name);
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueTrackEvent).call(this, event.name, undefined, context);
return;

@@ -177,13 +229,13 @@ }

// an event with user ID is tracked.
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").track(event.name, {
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueTrackEvent).call(this, event.name, {
...event.properties,
});
}, context);
}
const hasSensitiveProperties = Object.keys(event.sensitiveProperties).length > 0;
if (!__classPrivateFieldGet(this, _AnalyticsController_isAnonymousEventsFeatureEnabled, "f") || hasSensitiveProperties) {
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").track(event.name, {
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueTrackEvent).call(this, event.name, {
...event.properties,
...event.sensitiveProperties,
...(hasSensitiveProperties && { anonymous: true }),
});
}, context);
}

@@ -195,4 +247,5 @@ }

* @param traits - User traits/properties
* @param context - Optional platform-specific context forwarded to the platform adapter.
*/
identify(traits) {
identify(traits, context) {
if (!selectors_1.analyticsControllerSelectors.selectEnabled(this.state)) {

@@ -202,3 +255,3 @@ return;

// Delegate to platform adapter using the current analytics ID
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").identify(this.state.analyticsId, traits);
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueIdentifyEvent).call(this, this.state.analyticsId, traits, context);
}

@@ -210,4 +263,5 @@ /**

* @param properties - Optional properties associated with the view
* @param context - Optional platform-specific context forwarded to the platform adapter.
*/
trackView(name, properties) {
trackView(name, properties, context) {
if (!selectors_1.analyticsControllerSelectors.selectEnabled(this.state)) {

@@ -217,3 +271,3 @@ return;

// Delegate to platform adapter
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").view(name, properties);
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueViewEvent).call(this, name, properties, context);
}

@@ -235,6 +289,133 @@ /**

});
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearQueuedEvents).call(this);
}
}
exports.AnalyticsController = AnalyticsController;
_AnalyticsController_platformAdapter = new WeakMap(), _AnalyticsController_isAnonymousEventsFeatureEnabled = new WeakMap(), _AnalyticsController_initialized = new WeakMap();
_AnalyticsController_platformAdapter = new WeakMap(), _AnalyticsController_isAnonymousEventsFeatureEnabled = new WeakMap(), _AnalyticsController_isEventQueuePersistenceEnabled = new WeakMap(), _AnalyticsController_initialized = new WeakMap(), _AnalyticsController_instances = new WeakSet(), _AnalyticsController_sendOrQueueTrackEvent = function _AnalyticsController_sendOrQueueTrackEvent(eventName, properties, context) {
if (!__classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f")) {
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").track(eventName, properties, context);
return;
}
const queuedEvent = {
type: 'track',
eventName,
messageId: (0, uuid_1.v4)(),
timestamp: new Date().toISOString(),
...(properties === undefined ? {} : { properties }),
...(context === undefined ? {} : { context }),
};
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_enqueueEvent).call(this, queuedEvent);
}, _AnalyticsController_sendOrQueueIdentifyEvent = function _AnalyticsController_sendOrQueueIdentifyEvent(userId, traits, context) {
if (!__classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f")) {
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").identify(userId, traits, context);
return;
}
const queuedEvent = {
type: 'identify',
userId,
messageId: (0, uuid_1.v4)(),
timestamp: new Date().toISOString(),
...(traits === undefined ? {} : { traits }),
...(context === undefined ? {} : { context }),
};
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_enqueueEvent).call(this, queuedEvent);
}, _AnalyticsController_sendOrQueueViewEvent = function _AnalyticsController_sendOrQueueViewEvent(name, properties, context) {
if (!__classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f")) {
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").view(name, properties, context);
return;
}
const queuedEvent = {
type: 'view',
name,
messageId: (0, uuid_1.v4)(),
timestamp: new Date().toISOString(),
...(properties === undefined ? {} : { properties }),
...(context === undefined ? {} : { context }),
};
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_enqueueEvent).call(this, queuedEvent);
}, _AnalyticsController_enqueueEvent = function _AnalyticsController_enqueueEvent(queuedEvent) {
const eventQueue = {
...(this.state.eventQueue ?? {}),
[queuedEvent.messageId]: queuedEvent,
};
this.update((state) => {
state.eventQueue = eventQueue;
});
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendQueuedEvent).call(this, queuedEvent);
}, _AnalyticsController_sendQueuedEvent = function _AnalyticsController_sendQueuedEvent(queuedEvent) {
const timestamp = new Date(queuedEvent.timestamp);
if (Number.isNaN(timestamp.getTime())) {
(0, AnalyticsLogger_1.projectLogger)('Dropping queued analytics event with invalid timestamp', {
messageId: queuedEvent.messageId,
});
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_removeQueuedEvent).call(this, queuedEvent.messageId);
return;
}
const options = {
messageId: queuedEvent.messageId,
timestamp,
callback: (error) => {
if (error) {
(0, AnalyticsLogger_1.projectLogger)('Queued analytics event delivery failed', {
messageId: queuedEvent.messageId,
error,
});
return;
}
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_removeQueuedEvent).call(this, queuedEvent.messageId);
},
};
try {
if (queuedEvent.type === 'track') {
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").track(queuedEvent.eventName, (0, lodash_1.cloneDeep)(queuedEvent.properties), (0, lodash_1.cloneDeep)(queuedEvent.context), options);
}
else if (queuedEvent.type === 'identify') {
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").identify(queuedEvent.userId, (0, lodash_1.cloneDeep)(queuedEvent.traits), (0, lodash_1.cloneDeep)(queuedEvent.context), options);
}
else {
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").view(queuedEvent.name, (0, lodash_1.cloneDeep)(queuedEvent.properties), (0, lodash_1.cloneDeep)(queuedEvent.context), options);
}
}
catch (error) {
(0, AnalyticsLogger_1.projectLogger)('Error sending queued analytics event', {
messageId: queuedEvent.messageId,
error,
});
}
}, _AnalyticsController_replayQueuedEvents = function _AnalyticsController_replayQueuedEvents() {
if (!__classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f") || !this.state.eventQueue) {
return;
}
if (!selectors_1.analyticsControllerSelectors.selectEnabled(this.state)) {
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearQueuedEvents).call(this);
return;
}
for (const [messageId, queuedEvent] of Object.entries(this.state.eventQueue)) {
if (!isAnalyticsQueuedEvent(queuedEvent) ||
queuedEvent.messageId !== messageId) {
(0, AnalyticsLogger_1.projectLogger)('Dropping invalid queued analytics event', { messageId });
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_removeQueuedEvent).call(this, messageId);
continue;
}
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendQueuedEvent).call(this, queuedEvent);
}
}, _AnalyticsController_removeQueuedEvent = function _AnalyticsController_removeQueuedEvent(messageId) {
const currentEventQueue = this.state.eventQueue;
if (!currentEventQueue ||
!Object.prototype.hasOwnProperty.call(currentEventQueue, messageId)) {
return;
}
const { [messageId]: _deletedEvent, ...eventQueue } = currentEventQueue;
this.update((state) => {
state.eventQueue = eventQueue;
});
}, _AnalyticsController_clearQueuedEvents = function _AnalyticsController_clearQueuedEvents() {
if (!this.state.eventQueue ||
Object.keys(this.state.eventQueue).length === 0) {
return;
}
this.update((state) => {
state.eventQueue = {};
});
};
//# sourceMappingURL=AnalyticsController.cjs.map

@@ -1,1 +0,1 @@

{"version":3,"file":"AnalyticsController.cjs","sourceRoot":"","sources":["../src/AnalyticsController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAKA,+DAA2D;AAI3D,+FAAuF;AACvF,2DAAyD;AAOzD,+CAA2D;AAE3D,kBAAkB;AAElB;;;;GAIG;AACU,QAAA,cAAc,GAAG,qBAAqB,CAAC;AAqBpD;;;;;;;GAOG;AACH,SAAgB,kCAAkC;IAIhD,OAAO;QACL,OAAO,EAAE,KAAK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llerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\n\nimport type { AnalyticsControllerMethodActions } from './AnalyticsController-method-action-types';\nimport { validateAnalyticsControllerState } from './analyticsControllerStateValidator';\nimport { projectLogger as log } from './AnalyticsLogger';\nimport type {\n AnalyticsPlatformAdapter,\n AnalyticsEventProperties,\n AnalyticsUserTraits,\n AnalyticsTrackingEvent,\n} from './AnalyticsPlatformAdapter.types';\nimport { analyticsControllerSelectors } from './selectors';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link AnalyticsController}, used to namespace the\n * controller's actions and events and to namespace the controller's state data\n * when composed with other controllers.\n */\nexport const controllerName = 'AnalyticsController';\n\n// === STATE ===\n\n/**\n * Describes the shape of the state object for {@link AnalyticsController}.\n */\nexport type AnalyticsControllerState = {\n /**\n * Whether the user has opted in to analytics.\n */\n optedIn: boolean;\n\n /**\n * User's UUIDv4 analytics identifier.\n * This is an identity (unique per user), not a preference.\n * Must be provided by the platform - the controller does not generate it.\n */\n analyticsId: string;\n};\n\n/**\n * Returns default values for AnalyticsController state.\n *\n * Note: analyticsId is NOT included - it's an identity that must be\n * provided by the platform (generated once on first run, then persisted).\n *\n * @returns Default state without analyticsId\n */\nexport function getDefaultAnalyticsControllerState(): Omit<\n AnalyticsControllerState,\n 'analyticsId'\n> {\n return {\n optedIn: false,\n };\n}\n\n/**\n * The metadata for each property in {@link AnalyticsControllerState}.\n *\n * Note: `optedIn` is persisted by the controller (`persist: true`).\n * `analyticsId` is persisted by the platform (`persist: false`) and provided\n * via initial state. The platform should subscribe to `stateChange` events\n * to persist any state changes.\n */\nconst analyticsControllerMetadata = {\n optedIn: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n analyticsId: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: true,\n usedInUi: false,\n },\n} satisfies StateMetadata<AnalyticsControllerState>;\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'trackEvent',\n 'identify',\n 'trackView',\n 'optIn',\n 'optOut',\n] as const;\n\n/**\n * Returns the state of the {@link AnalyticsController}.\n */\nexport type AnalyticsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n AnalyticsControllerState\n>;\n\n/**\n * Actions that {@link AnalyticsControllerMessenger} exposes to other consumers.\n */\nexport type AnalyticsControllerActions =\n | AnalyticsControllerGetStateAction\n | AnalyticsControllerMethodActions;\n\n/**\n * Actions from other messengers that {@link AnalyticsControllerMessenger} calls.\n */\ntype AllowedActions = never;\n\n/**\n * Event emitted when the state of the {@link AnalyticsController} changes.\n */\nexport type AnalyticsControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n AnalyticsControllerState\n>;\n\n/**\n * Events that {@link AnalyticsControllerMessenger} exposes to other consumers.\n */\nexport type AnalyticsControllerEvents = AnalyticsControllerStateChangeEvent;\n\n/**\n * Events from other messengers that {@link AnalyticsControllerMessenger} subscribes to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link AnalyticsController}.\n */\nexport type AnalyticsControllerMessenger = Messenger<\n typeof controllerName,\n AnalyticsControllerActions | AllowedActions,\n AnalyticsControllerEvents | AllowedEvents\n>;\n\n// === CONTROLLER DEFINITION ===\n\n/**\n * The options that AnalyticsController takes.\n */\nexport type AnalyticsControllerOptions = {\n /**\n * Initial controller state. Must include a valid UUIDv4 `analyticsId`.\n * The platform is responsible for generating and persisting the analyticsId.\n */\n state: AnalyticsControllerState;\n /**\n * Messenger used to communicate with BaseController and other controllers.\n */\n messenger: AnalyticsControllerMessenger;\n /**\n * Platform adapter implementation for tracking events.\n */\n platformAdapter: AnalyticsPlatformAdapter;\n\n /**\n * Whether the anonymous events feature is enabled.\n *\n * @default false\n */\n isAnonymousEventsFeatureEnabled?: boolean;\n};\n\n/**\n * The AnalyticsController manages analytics tracking across platforms (Mobile/Extension).\n * It provides a unified interface for tracking events, identifying users, and managing\n * analytics preferences while delegating platform-specific implementation to an\n * {@link AnalyticsPlatformAdapter}.\n *\n * This controller follows the MetaMask controller pattern and integrates with the\n * messenger system to allow other controllers and components to track analytics events.\n * It delegates platform-specific implementation to an {@link AnalyticsPlatformAdapter}.\n *\n * Note: The controller persists `optedIn` internally. The `analyticsId` is persisted\n * by the platform and must be provided via initial state. The platform should subscribe\n * to `AnalyticsController:stateChange` events to persist any state changes.\n */\nexport class AnalyticsController extends BaseController<\n 'AnalyticsController',\n AnalyticsControllerState,\n AnalyticsControllerMessenger\n> {\n readonly #platformAdapter: AnalyticsPlatformAdapter;\n\n readonly #isAnonymousEventsFeatureEnabled: boolean;\n\n #initialized: boolean;\n\n /**\n * Constructs an AnalyticsController instance.\n *\n * @param options - Controller options\n * @param options.state - Initial controller state. Must include a valid UUIDv4 `analyticsId`.\n * Use `getDefaultAnalyticsControllerState()` for default opt-in preferences.\n * @param options.messenger - Messenger used to communicate with BaseController\n * @param options.platformAdapter - Platform adapter implementation for tracking\n * @param options.isAnonymousEventsFeatureEnabled - Whether the anonymous events feature is enabled\n * @throws Error if state.analyticsId is missing or not a valid UUIDv4\n * @remarks After construction, call {@link AnalyticsController.init} to complete initialization.\n */\n constructor({\n state,\n messenger,\n platformAdapter,\n isAnonymousEventsFeatureEnabled = false,\n }: AnalyticsControllerOptions) {\n const initialState: AnalyticsControllerState = {\n ...getDefaultAnalyticsControllerState(),\n ...state,\n };\n\n validateAnalyticsControllerState(initialState);\n\n super({\n name: controllerName,\n metadata: analyticsControllerMetadata,\n state: initialState,\n messenger,\n });\n\n this.#isAnonymousEventsFeatureEnabled = isAnonymousEventsFeatureEnabled;\n this.#platformAdapter = platformAdapter;\n this.#initialized = false;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n log('AnalyticsController initialized and ready', {\n enabled: analyticsControllerSelectors.selectEnabled(this.state),\n optedIn: this.state.optedIn,\n analyticsId: this.state.analyticsId,\n });\n }\n\n /**\n * Initialize the controller by calling the platform adapter's onSetupCompleted lifecycle hook.\n * This method must be called after construction to complete the setup process.\n */\n init(): void {\n if (this.#initialized) {\n log('AnalyticsController already initialized.');\n return;\n }\n\n this.#initialized = true;\n\n // Call onSetupCompleted lifecycle hook after initialization\n // State is already validated, so analyticsId is guaranteed to be a valid UUIDv4\n try {\n this.#platformAdapter.onSetupCompleted(this.state.analyticsId);\n } catch (error) {\n // Log error but don't throw - adapter setup failure shouldn't break controller\n log('Error calling platformAdapter.onSetupCompleted', error);\n }\n }\n\n /**\n * Track an analytics event.\n *\n * Events are only tracked if analytics is enabled.\n *\n * @param event - Analytics event with properties and sensitive properties\n */\n trackEvent(event: AnalyticsTrackingEvent): void {\n // Don't track if analytics is disabled\n if (!analyticsControllerSelectors.selectEnabled(this.state)) {\n return;\n }\n\n // if event does not have properties, send event without properties\n // and return to prevent any additional processing\n if (!event.hasProperties) {\n this.#platformAdapter.track(event.name);\n return;\n }\n\n // Track regular properties first if anonymous events feature is enabled\n if (this.#isAnonymousEventsFeatureEnabled) {\n // Note: Even if regular properties object is empty, we still send it to ensure\n // an event with user ID is tracked.\n this.#platformAdapter.track(event.name, {\n ...event.properties,\n });\n }\n\n const hasSensitiveProperties =\n Object.keys(event.sensitiveProperties).length > 0;\n\n if (!this.#isAnonymousEventsFeatureEnabled || hasSensitiveProperties) {\n this.#platformAdapter.track(event.name, {\n ...event.properties,\n ...event.sensitiveProperties,\n ...(hasSensitiveProperties && { anonymous: true }),\n });\n }\n }\n\n /**\n * Identify a user for analytics.\n *\n * @param traits - User traits/properties\n */\n identify(traits?: AnalyticsUserTraits): void {\n if (!analyticsControllerSelectors.selectEnabled(this.state)) {\n return;\n }\n\n // Delegate to platform adapter using the current analytics ID\n this.#platformAdapter.identify(this.state.analyticsId, traits);\n }\n\n /**\n * Track a page or screen view.\n *\n * @param name - The identifier/name of the page or screen being viewed (e.g., \"home\", \"settings\", \"wallet\")\n * @param properties - Optional properties associated with the view\n */\n trackView(name: string, properties?: AnalyticsEventProperties): void {\n if (!analyticsControllerSelectors.selectEnabled(this.state)) {\n return;\n }\n\n // Delegate to platform adapter\n this.#platformAdapter.view(name, properties);\n }\n\n /**\n * Opt in to analytics.\n */\n optIn(): void {\n this.update((state) => {\n state.optedIn = true;\n });\n }\n\n /**\n * Opt out of analytics.\n */\n optOut(): void {\n this.update((state) => {\n state.optedIn = false;\n });\n }\n}\n"]}
{"version":3,"file":"AnalyticsController.cjs","sourceRoot":"","sources":["../src/AnalyticsController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAKA,+DAA2D;AAG3D,mCAAmC;AACnC,+BAAkC;AAGlC,+FAAuF;AACvF,2DAAyD;AASzD,+CAA2D;AAE3D,kBAAkB;AAElB;;;;GAIG;AACU,QAAA,cAAc,GAAG,qBAAqB,CAAC;AA+FpD;;;;;;;GAOG;AACH,SAAgB,kCAAkC;IAIhD,OAAO;QACL,OAAO,EAAE,KAAK;KACf,CAAC;AACJ,CAAC;AAPD,gFAOC;AAED;;;;;GAKG;AACH,MAAM,2BAA2B,GAAG;IAClC,OAAO,EAAE;QACP,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,WAAW,EAAE;QACX,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,KAAK;KAChB;IACD,UAAU,EAAE;QACV,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,KAAK;KAChB;CACgD,CAAC;AAEpD,oBAAoB;AAEpB,MAAM,yBAAyB,GAAG;IAChC,YAAY;IACZ,UAAU;IACV,WAAW;IACX,OAAO;IACP,QAAQ;CACA,CAAC;AAyFX;;;;;GAKG;AACH,SAAS,QAAQ,CAAC,K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C,iBAAiB,EAAE,SAAS,CAAC,EACnE,CAAC;QACD,OAAO;IACT,CAAC;IAED,MAAM,EAAE,CAAC,SAAS,CAAC,EAAE,aAAa,EAAE,GAAG,UAAU,EAAE,GAAG,iBAAiB,CAAC;IAExE,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,UAAU,GAAG,UAAmB,CAAC;IACzC,CAAC,CAAC,CAAC;AACL,CAAC;IAMC,IACE,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU;QACtB,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,MAAM,KAAK,CAAC,EAC/C,CAAC;QACD,OAAO;IACT,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,UAAU,GAAG,EAAW,CAAC;IACjC,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { Json } from '@metamask/utils';\nimport { cloneDeep } from 'lodash';\nimport { v4 as uuid } from 'uuid';\n\nimport type { AnalyticsControllerMethodActions } from './AnalyticsController-method-action-types';\nimport { validateAnalyticsControllerState } from './analyticsControllerStateValidator';\nimport { projectLogger as log } from './AnalyticsLogger';\nimport type {\n AnalyticsPlatformAdapter,\n AnalyticsDeliveryOptions,\n AnalyticsContext,\n AnalyticsEventProperties,\n AnalyticsUserTraits,\n AnalyticsTrackingEvent,\n} from './AnalyticsPlatformAdapter.types';\nimport { analyticsControllerSelectors } from './selectors';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link AnalyticsController}, used to namespace the\n * controller's actions and events and to namespace the controller's state data\n * when composed with other controllers.\n */\nexport const controllerName = 'AnalyticsController';\n\n// === STATE ===\n\n/**\n * Describes the shape of the state object for {@link AnalyticsController}.\n */\nexport type AnalyticsControllerState = {\n /**\n * Whether the user has opted in to analytics.\n */\n optedIn: boolean;\n\n /**\n * User's UUIDv4 analytics identifier.\n * This is an identity (unique per user), not a preference.\n * Must be provided by the platform - the controller does not generate it.\n */\n analyticsId: string;\n\n /**\n * Persisted queue of analytics events waiting for delivery acknowledgement.\n * This is only used when event queue persistence is enabled.\n */\n eventQueue?: Record<string, Json>;\n};\n\n/**\n * Event types supported by the persisted analytics event queue.\n */\nexport type AnalyticsQueuedEventType = 'track' | 'identify' | 'view';\n\n/**\n * Base persisted event queue entry.\n */\nexport type AnalyticsQueuedEventBase = {\n /**\n * Event type used to replay the payload with the platform adapter.\n */\n type: AnalyticsQueuedEventType;\n\n /**\n * Stable identifier for the analytics payload.\n */\n messageId: string;\n\n /**\n * Original payload timestamp serialized for persistence.\n */\n timestamp: string;\n};\n\n/**\n * Persisted track event queue entry.\n */\nexport type AnalyticsQueuedTrackEvent = AnalyticsQueuedEventBase & {\n type: 'track';\n eventName: string;\n properties?: AnalyticsEventProperties;\n context?: AnalyticsContext;\n};\n\n/**\n * Persisted identify event queue entry.\n */\nexport type AnalyticsQueuedIdentifyEvent = AnalyticsQueuedEventBase & {\n type: 'identify';\n userId: string;\n traits?: AnalyticsUserTraits;\n context?: AnalyticsContext;\n};\n\n/**\n * Persisted view event queue entry.\n */\nexport type AnalyticsQueuedViewEvent = AnalyticsQueuedEventBase & {\n type: 'view';\n name: string;\n properties?: AnalyticsEventProperties;\n context?: AnalyticsContext;\n};\n\n/**\n * Persisted analytics event queue entry.\n */\nexport type AnalyticsQueuedEvent =\n | AnalyticsQueuedTrackEvent\n | AnalyticsQueuedIdentifyEvent\n | AnalyticsQueuedViewEvent;\n\n/**\n * Persisted analytics event queue keyed by message ID.\n */\nexport type AnalyticsEventQueue = Record<string, AnalyticsQueuedEvent>;\n\n/**\n * Returns default values for AnalyticsController state.\n *\n * Note: analyticsId is NOT included - it's an identity that must be\n * provided by the platform (generated once on first run, then persisted).\n *\n * @returns Default state without analyticsId\n */\nexport function getDefaultAnalyticsControllerState(): Omit<\n AnalyticsControllerState,\n 'analyticsId'\n> {\n return {\n optedIn: false,\n };\n}\n\n/**\n * The metadata for each property in {@link AnalyticsControllerState}.\n *\n * Both `optedIn` and `analyticsId` are persisted (`persist: true`).\n * The platform must supply a valid UUIDv4 `analyticsId` on first run.\n */\nconst analyticsControllerMetadata = {\n optedIn: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n analyticsId: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: false,\n },\n eventQueue: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: false,\n },\n} satisfies StateMetadata<AnalyticsControllerState>;\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'trackEvent',\n 'identify',\n 'trackView',\n 'optIn',\n 'optOut',\n] as const;\n\n/**\n * Returns the state of the {@link AnalyticsController}.\n */\nexport type AnalyticsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n AnalyticsControllerState\n>;\n\n/**\n * Actions that {@link AnalyticsControllerMessenger} exposes to other consumers.\n */\nexport type AnalyticsControllerActions =\n | AnalyticsControllerGetStateAction\n | AnalyticsControllerMethodActions;\n\n/**\n * Actions from other messengers that {@link AnalyticsControllerMessenger} calls.\n */\ntype AllowedActions = never;\n\n/**\n * Event emitted when the state of the {@link AnalyticsController} changes.\n */\nexport type AnalyticsControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n AnalyticsControllerState\n>;\n\n/**\n * Events that {@link AnalyticsControllerMessenger} exposes to other consumers.\n */\nexport type AnalyticsControllerEvents = AnalyticsControllerStateChangeEvent;\n\n/**\n * Events from other messengers that {@link AnalyticsControllerMessenger} subscribes to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link AnalyticsController}.\n */\nexport type AnalyticsControllerMessenger = Messenger<\n typeof controllerName,\n AnalyticsControllerActions | AllowedActions,\n AnalyticsControllerEvents | AllowedEvents\n>;\n\n// === CONTROLLER DEFINITION ===\n\n/**\n * The options that AnalyticsController takes.\n */\nexport type AnalyticsControllerOptions = {\n /**\n * Initial controller state. Must include a valid UUIDv4 `analyticsId`.\n * The platform is responsible for generating the ID on first run.\n * It is then persisted with controller state when using a persisted store.\n */\n state: AnalyticsControllerState;\n /**\n * Messenger used to communicate with BaseController and other controllers.\n */\n messenger: AnalyticsControllerMessenger;\n /**\n * Platform adapter implementation for tracking events.\n */\n platformAdapter: AnalyticsPlatformAdapter;\n\n /**\n * Whether the anonymous events feature is enabled.\n *\n * @default false\n */\n isAnonymousEventsFeatureEnabled?: boolean;\n\n /**\n * Whether analytics event queue persistence is enabled.\n *\n * When enabled, AnalyticsController persists each platform adapter payload\n * until the adapter reports successful delivery.\n *\n * @default false\n */\n isEventQueuePersistenceEnabled?: boolean;\n};\n\n/**\n * Returns whether a value is a non-array object.\n *\n * @param value - The value to check.\n * @returns True if the value is a record.\n */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Returns whether a value is a valid persisted analytics event.\n *\n * @param value - The value to check.\n * @returns True if the value is a queued analytics event.\n */\nfunction isAnalyticsQueuedEvent(value: unknown): value is AnalyticsQueuedEvent {\n if (!isRecord(value)) {\n return false;\n }\n\n if (\n typeof value.messageId !== 'string' ||\n typeof value.timestamp !== 'string'\n ) {\n return false;\n }\n\n if (value.type === 'track') {\n return (\n typeof value.eventName === 'string' &&\n (value.properties === undefined || isRecord(value.properties)) &&\n (value.context === undefined || isRecord(value.context))\n );\n }\n\n if (value.type === 'identify') {\n return (\n typeof value.userId === 'string' &&\n (value.traits === undefined || isRecord(value.traits)) &&\n (value.context === undefined || isRecord(value.context))\n );\n }\n\n if (value.type === 'view') {\n return (\n typeof value.name === 'string' &&\n (value.properties === undefined || isRecord(value.properties)) &&\n (value.context === undefined || isRecord(value.context))\n );\n }\n\n return false;\n}\n\n/**\n * The AnalyticsController manages analytics tracking across platforms (Mobile/Extension).\n * It provides a unified interface for tracking events, identifying users, and managing\n * analytics preferences while delegating platform-specific implementation to an\n * {@link AnalyticsPlatformAdapter}.\n *\n * This controller follows the MetaMask controller pattern and integrates with the\n * messenger system to allow other controllers and components to track analytics events.\n * It delegates platform-specific implementation to an {@link AnalyticsPlatformAdapter}.\n *\n * The controller persists `optedIn` and `analyticsId` when composed with a persisted\n * store. The platform must supply a valid `analyticsId` on first launch.\n */\nexport class AnalyticsController extends BaseController<\n 'AnalyticsController',\n AnalyticsControllerState,\n AnalyticsControllerMessenger\n> {\n readonly #platformAdapter: AnalyticsPlatformAdapter;\n\n readonly #isAnonymousEventsFeatureEnabled: boolean;\n\n readonly #isEventQueuePersistenceEnabled: boolean;\n\n #initialized: boolean;\n\n /**\n * Constructs an AnalyticsController instance.\n *\n * @param options - Controller options\n * @param options.state - Initial controller state. Must include a valid UUIDv4 `analyticsId`.\n * Use `getDefaultAnalyticsControllerState()` for default opt-in preferences.\n * @param options.messenger - Messenger used to communicate with BaseController\n * @param options.platformAdapter - Platform adapter implementation for tracking\n * @param options.isAnonymousEventsFeatureEnabled - Whether the anonymous events feature is enabled\n * @param options.isEventQueuePersistenceEnabled - Whether analytics event queue persistence is enabled\n * @throws Error if state.analyticsId is missing or not a valid UUIDv4\n * @remarks After construction, call {@link AnalyticsController.init} to complete initialization.\n */\n constructor({\n state,\n messenger,\n platformAdapter,\n isAnonymousEventsFeatureEnabled = false,\n isEventQueuePersistenceEnabled = false,\n }: AnalyticsControllerOptions) {\n const initialState: AnalyticsControllerState = {\n ...getDefaultAnalyticsControllerState(),\n ...state,\n };\n\n validateAnalyticsControllerState(\n initialState,\n platformAdapter.skipUUIDv4Check === true,\n );\n\n super({\n name: controllerName,\n metadata: analyticsControllerMetadata,\n state: initialState,\n messenger,\n });\n\n this.#isAnonymousEventsFeatureEnabled = isAnonymousEventsFeatureEnabled;\n this.#isEventQueuePersistenceEnabled = isEventQueuePersistenceEnabled;\n this.#platformAdapter = platformAdapter;\n this.#initialized = false;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n log('AnalyticsController initialized and ready', {\n enabled: analyticsControllerSelectors.selectEnabled(this.state),\n optedIn: this.state.optedIn,\n analyticsId: this.state.analyticsId,\n eventQueuePersistenceEnabled: this.#isEventQueuePersistenceEnabled,\n });\n }\n\n /**\n * Initialize the controller by calling the platform adapter's onSetupCompleted lifecycle hook.\n * This method must be called after construction to complete the setup process.\n */\n init(): void {\n if (this.#initialized) {\n log('AnalyticsController already initialized.');\n return;\n }\n\n this.#initialized = true;\n\n // Call onSetupCompleted lifecycle hook after initialization\n // State is already validated, so analyticsId is guaranteed to be a valid UUIDv4\n try {\n this.#platformAdapter.onSetupCompleted(this.state.analyticsId);\n } catch (error) {\n // Log error but don't throw - adapter setup failure shouldn't break controller\n log('Error calling platformAdapter.onSetupCompleted', error);\n }\n\n this.#replayQueuedEvents();\n }\n\n /**\n * Send final track payload through the platform adapter or queue it if persistence is enabled.\n *\n * @param eventName - The name of the event.\n * @param properties - Optional event properties.\n * @param context - Optional platform-specific context.\n */\n #sendOrQueueTrackEvent(\n eventName: string,\n properties?: AnalyticsEventProperties,\n context?: AnalyticsContext,\n ): void {\n if (!this.#isEventQueuePersistenceEnabled) {\n this.#platformAdapter.track(eventName, properties, context);\n return;\n }\n\n const queuedEvent: AnalyticsQueuedTrackEvent = {\n type: 'track',\n eventName,\n messageId: uuid(),\n timestamp: new Date().toISOString(),\n ...(properties === undefined ? {} : { properties }),\n ...(context === undefined ? {} : { context }),\n };\n\n this.#enqueueEvent(queuedEvent);\n }\n\n /**\n * Send final identify payload through the platform adapter or queue it if persistence is enabled.\n *\n * @param userId - The user ID.\n * @param traits - Optional user traits.\n * @param context - Optional platform-specific context.\n */\n #sendOrQueueIdentifyEvent(\n userId: string,\n traits?: AnalyticsUserTraits,\n context?: AnalyticsContext,\n ): void {\n if (!this.#isEventQueuePersistenceEnabled) {\n this.#platformAdapter.identify(userId, traits, context);\n return;\n }\n\n const queuedEvent: AnalyticsQueuedIdentifyEvent = {\n type: 'identify',\n userId,\n messageId: uuid(),\n timestamp: new Date().toISOString(),\n ...(traits === undefined ? {} : { traits }),\n ...(context === undefined ? {} : { context }),\n };\n\n this.#enqueueEvent(queuedEvent);\n }\n\n /**\n * Send final view payload through the platform adapter or queue it if persistence is enabled.\n *\n * @param name - The view name.\n * @param properties - Optional view properties.\n * @param context - Optional platform-specific context.\n */\n #sendOrQueueViewEvent(\n name: string,\n properties?: AnalyticsEventProperties,\n context?: AnalyticsContext,\n ): void {\n if (!this.#isEventQueuePersistenceEnabled) {\n this.#platformAdapter.view(name, properties, context);\n return;\n }\n\n const queuedEvent: AnalyticsQueuedViewEvent = {\n type: 'view',\n name,\n messageId: uuid(),\n timestamp: new Date().toISOString(),\n ...(properties === undefined ? {} : { properties }),\n ...(context === undefined ? {} : { context }),\n };\n\n this.#enqueueEvent(queuedEvent);\n }\n\n /**\n * Add an analytics event to the queue and send it.\n *\n * @param queuedEvent - The event to enqueue and deliver.\n */\n #enqueueEvent(queuedEvent: AnalyticsQueuedEvent): void {\n const eventQueue: Record<string, Json> = {\n ...(this.state.eventQueue ?? {}),\n [queuedEvent.messageId]: queuedEvent as unknown as Json,\n };\n\n this.update((state) => {\n state.eventQueue = eventQueue as never;\n });\n\n this.#sendQueuedEvent(queuedEvent);\n }\n\n /**\n * Send a queued event through the platform adapter.\n *\n * @param queuedEvent - The queued event to deliver.\n */\n #sendQueuedEvent(queuedEvent: AnalyticsQueuedEvent): void {\n const timestamp = new Date(queuedEvent.timestamp);\n\n if (Number.isNaN(timestamp.getTime())) {\n log('Dropping queued analytics event with invalid timestamp', {\n messageId: queuedEvent.messageId,\n });\n this.#removeQueuedEvent(queuedEvent.messageId);\n return;\n }\n\n const options: AnalyticsDeliveryOptions = {\n messageId: queuedEvent.messageId,\n timestamp,\n callback: (error?: unknown) => {\n if (error) {\n log('Queued analytics event delivery failed', {\n messageId: queuedEvent.messageId,\n error,\n });\n return;\n }\n\n this.#removeQueuedEvent(queuedEvent.messageId);\n },\n };\n\n try {\n if (queuedEvent.type === 'track') {\n this.#platformAdapter.track(\n queuedEvent.eventName,\n cloneDeep(queuedEvent.properties),\n cloneDeep(queuedEvent.context),\n options,\n );\n } else if (queuedEvent.type === 'identify') {\n this.#platformAdapter.identify(\n queuedEvent.userId,\n cloneDeep(queuedEvent.traits),\n cloneDeep(queuedEvent.context),\n options,\n );\n } else {\n this.#platformAdapter.view(\n queuedEvent.name,\n cloneDeep(queuedEvent.properties),\n cloneDeep(queuedEvent.context),\n options,\n );\n }\n } catch (error) {\n log('Error sending queued analytics event', {\n messageId: queuedEvent.messageId,\n error,\n });\n }\n }\n\n /**\n * Replay persisted analytics events.\n */\n #replayQueuedEvents(): void {\n if (!this.#isEventQueuePersistenceEnabled || !this.state.eventQueue) {\n return;\n }\n\n if (!analyticsControllerSelectors.selectEnabled(this.state)) {\n this.#clearQueuedEvents();\n return;\n }\n\n for (const [messageId, queuedEvent] of Object.entries(\n this.state.eventQueue,\n )) {\n if (\n !isAnalyticsQueuedEvent(queuedEvent) ||\n queuedEvent.messageId !== messageId\n ) {\n log('Dropping invalid queued analytics event', { messageId });\n this.#removeQueuedEvent(messageId);\n continue;\n }\n\n this.#sendQueuedEvent(queuedEvent);\n }\n }\n\n /**\n * Remove a queued analytics event.\n *\n * @param messageId - The queued event message ID.\n */\n #removeQueuedEvent(messageId: string): void {\n const currentEventQueue = this.state.eventQueue;\n\n if (\n !currentEventQueue ||\n !Object.prototype.hasOwnProperty.call(currentEventQueue, messageId)\n ) {\n return;\n }\n\n const { [messageId]: _deletedEvent, ...eventQueue } = currentEventQueue;\n\n this.update((state) => {\n state.eventQueue = eventQueue as never;\n });\n }\n\n /**\n * Clear all queued analytics events.\n */\n #clearQueuedEvents(): void {\n if (\n !this.state.eventQueue ||\n Object.keys(this.state.eventQueue).length === 0\n ) {\n return;\n }\n\n this.update((state) => {\n state.eventQueue = {} as never;\n });\n }\n\n /**\n * Track an analytics event.\n *\n * Events are only tracked if analytics is enabled.\n *\n * @param event - Analytics event with properties and sensitive properties\n * @param context - Optional platform-specific context forwarded to the platform adapter.\n */\n trackEvent(event: AnalyticsTrackingEvent, context?: AnalyticsContext): void {\n // Don't track if analytics is disabled\n if (!analyticsControllerSelectors.selectEnabled(this.state)) {\n return;\n }\n\n // if event does not have properties, send event without properties\n // and return to prevent any additional processing\n if (!event.hasProperties) {\n this.#sendOrQueueTrackEvent(event.name, undefined, context);\n return;\n }\n\n // Track regular properties first if anonymous events feature is enabled\n if (this.#isAnonymousEventsFeatureEnabled) {\n // Note: Even if regular properties object is empty, we still send it to ensure\n // an event with user ID is tracked.\n this.#sendOrQueueTrackEvent(\n event.name,\n {\n ...event.properties,\n },\n context,\n );\n }\n\n const hasSensitiveProperties =\n Object.keys(event.sensitiveProperties).length > 0;\n\n if (!this.#isAnonymousEventsFeatureEnabled || hasSensitiveProperties) {\n this.#sendOrQueueTrackEvent(\n event.name,\n {\n ...event.properties,\n ...event.sensitiveProperties,\n ...(hasSensitiveProperties && { anonymous: true }),\n },\n context,\n );\n }\n }\n\n /**\n * Identify a user for analytics.\n *\n * @param traits - User traits/properties\n * @param context - Optional platform-specific context forwarded to the platform adapter.\n */\n identify(traits?: AnalyticsUserTraits, context?: AnalyticsContext): void {\n if (!analyticsControllerSelectors.selectEnabled(this.state)) {\n return;\n }\n\n // Delegate to platform adapter using the current analytics ID\n this.#sendOrQueueIdentifyEvent(this.state.analyticsId, traits, context);\n }\n\n /**\n * Track a page or screen view.\n *\n * @param name - The identifier/name of the page or screen being viewed (e.g., \"home\", \"settings\", \"wallet\")\n * @param properties - Optional properties associated with the view\n * @param context - Optional platform-specific context forwarded to the platform adapter.\n */\n trackView(\n name: string,\n properties?: AnalyticsEventProperties,\n context?: AnalyticsContext,\n ): void {\n if (!analyticsControllerSelectors.selectEnabled(this.state)) {\n return;\n }\n\n // Delegate to platform adapter\n this.#sendOrQueueViewEvent(name, properties, context);\n }\n\n /**\n * Opt in to analytics.\n */\n optIn(): void {\n this.update((state) => {\n state.optedIn = true;\n });\n }\n\n /**\n * Opt out of analytics.\n */\n optOut(): void {\n this.update((state) => {\n state.optedIn = false;\n });\n\n this.#clearQueuedEvents();\n }\n}\n"]}
import type { ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
import { BaseController } from "@metamask/base-controller";
import type { Messenger } from "@metamask/messenger";
import type { Json } from "@metamask/utils";
import type { AnalyticsControllerMethodActions } from "./AnalyticsController-method-action-types.cjs";
import type { AnalyticsPlatformAdapter, AnalyticsEventProperties, AnalyticsUserTraits, AnalyticsTrackingEvent } from "./AnalyticsPlatformAdapter.types.cjs";
import type { AnalyticsPlatformAdapter, AnalyticsContext, AnalyticsEventProperties, AnalyticsUserTraits, AnalyticsTrackingEvent } from "./AnalyticsPlatformAdapter.types.cjs";
/**

@@ -26,4 +27,65 @@ * The name of the {@link AnalyticsController}, used to namespace the

analyticsId: string;
/**
* Persisted queue of analytics events waiting for delivery acknowledgement.
* This is only used when event queue persistence is enabled.
*/
eventQueue?: Record<string, Json>;
};
/**
* Event types supported by the persisted analytics event queue.
*/
export type AnalyticsQueuedEventType = 'track' | 'identify' | 'view';
/**
* Base persisted event queue entry.
*/
export type AnalyticsQueuedEventBase = {
/**
* Event type used to replay the payload with the platform adapter.
*/
type: AnalyticsQueuedEventType;
/**
* Stable identifier for the analytics payload.
*/
messageId: string;
/**
* Original payload timestamp serialized for persistence.
*/
timestamp: string;
};
/**
* Persisted track event queue entry.
*/
export type AnalyticsQueuedTrackEvent = AnalyticsQueuedEventBase & {
type: 'track';
eventName: string;
properties?: AnalyticsEventProperties;
context?: AnalyticsContext;
};
/**
* Persisted identify event queue entry.
*/
export type AnalyticsQueuedIdentifyEvent = AnalyticsQueuedEventBase & {
type: 'identify';
userId: string;
traits?: AnalyticsUserTraits;
context?: AnalyticsContext;
};
/**
* Persisted view event queue entry.
*/
export type AnalyticsQueuedViewEvent = AnalyticsQueuedEventBase & {
type: 'view';
name: string;
properties?: AnalyticsEventProperties;
context?: AnalyticsContext;
};
/**
* Persisted analytics event queue entry.
*/
export type AnalyticsQueuedEvent = AnalyticsQueuedTrackEvent | AnalyticsQueuedIdentifyEvent | AnalyticsQueuedViewEvent;
/**
* Persisted analytics event queue keyed by message ID.
*/
export type AnalyticsEventQueue = Record<string, AnalyticsQueuedEvent>;
/**
* Returns default values for AnalyticsController state.

@@ -72,3 +134,4 @@ *

* Initial controller state. Must include a valid UUIDv4 `analyticsId`.
* The platform is responsible for generating and persisting the analyticsId.
* The platform is responsible for generating the ID on first run.
* It is then persisted with controller state when using a persisted store.
*/

@@ -90,2 +153,11 @@ state: AnalyticsControllerState;

isAnonymousEventsFeatureEnabled?: boolean;
/**
* Whether analytics event queue persistence is enabled.
*
* When enabled, AnalyticsController persists each platform adapter payload
* until the adapter reports successful delivery.
*
* @default false
*/
isEventQueuePersistenceEnabled?: boolean;
};

@@ -102,5 +174,4 @@ /**

*
* Note: The controller persists `optedIn` internally. The `analyticsId` is persisted
* by the platform and must be provided via initial state. The platform should subscribe
* to `AnalyticsController:stateChange` events to persist any state changes.
* The controller persists `optedIn` and `analyticsId` when composed with a persisted
* store. The platform must supply a valid `analyticsId` on first launch.
*/

@@ -118,6 +189,7 @@ export declare class AnalyticsController extends BaseController<'AnalyticsController', AnalyticsControllerState, AnalyticsControllerMessenger> {

* @param options.isAnonymousEventsFeatureEnabled - Whether the anonymous events feature is enabled
* @param options.isEventQueuePersistenceEnabled - Whether analytics event queue persistence is enabled
* @throws Error if state.analyticsId is missing or not a valid UUIDv4
* @remarks After construction, call {@link AnalyticsController.init} to complete initialization.
*/
constructor({ state, messenger, platformAdapter, isAnonymousEventsFeatureEnabled, }: AnalyticsControllerOptions);
constructor({ state, messenger, platformAdapter, isAnonymousEventsFeatureEnabled, isEventQueuePersistenceEnabled, }: AnalyticsControllerOptions);
/**

@@ -134,4 +206,5 @@ * Initialize the controller by calling the platform adapter's onSetupCompleted lifecycle hook.

* @param event - Analytics event with properties and sensitive properties
* @param context - Optional platform-specific context forwarded to the platform adapter.
*/
trackEvent(event: AnalyticsTrackingEvent): void;
trackEvent(event: AnalyticsTrackingEvent, context?: AnalyticsContext): void;
/**

@@ -141,4 +214,5 @@ * Identify a user for analytics.

* @param traits - User traits/properties
* @param context - Optional platform-specific context forwarded to the platform adapter.
*/
identify(traits?: AnalyticsUserTraits): void;
identify(traits?: AnalyticsUserTraits, context?: AnalyticsContext): void;
/**

@@ -149,4 +223,5 @@ * Track a page or screen view.

* @param properties - Optional properties associated with the view
* @param context - Optional platform-specific context forwarded to the platform adapter.
*/
trackView(name: string, properties?: AnalyticsEventProperties): void;
trackView(name: string, properties?: AnalyticsEventProperties, context?: AnalyticsContext): void;
/**

@@ -153,0 +228,0 @@ * Opt in to analytics.

@@ -1,1 +0,1 @@

{"version":3,"file":"AnalyticsController.d.cts","sourceRoot":"","sources":["../src/AnalyticsController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAErD,OAAO,KAAK,EAAE,gCAAgC,EAAE,sDAAkD;AAGlG,OAAO,KAAK,EACV,wBAAwB,EACxB,wBAAwB,EACxB,mBAAmB,EACnB,sBAAsB,EACvB,6CAAyC;AAK1C;;;;GAIG;AACH,eAAO,MAAM,cAAc,wBAAwB,CAAC;AAIpD;;GAEG;AACH,MAAM,MAAM,wBAAwB,GAAG;IACrC;;OAEG;IACH,OAAO,EAAE,OAAO,CAAC;IAEjB;;;;OAIG;IACH,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAgB,kCAAkC,IAAI,IAAI,CACxD,wBA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AAC;AAE3B;;;GAGG;AACH,MAAM,MAAM,4BAA4B,GAAG,SAAS,CAClD,OAAO,cAAc,EACrB,0BAA0B,GAAG,cAAc,EAC3C,yBAAyB,GAAG,aAAa,CAC1C,CAAC;AAIF;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG;IACvC;;;;OAIG;IACH,KAAK,EAAE,wBAAwB,CAAC;IAChC;;OAEG;IACH,SAAS,EAAE,4BAA4B,CAAC;IACxC;;OAEG;IACH,eAAe,EAAE,wBAAwB,CAAC;IAE1C;;;;OAIG;IACH,+BAA+B,CAAC,EAAE,OAAO,CAAC;IAE1C;;;;;;;OAOG;IACH,8BAA8B,CAAC,EAAE,OAAO,CAAC;CAC1C,CAAC;AAyDF;;;;;;;;;;;;GAYG;AACH,qBAAa,mBAAoB,SAAQ,cAAc,CACrD,qBAAqB,EACrB,wBAAwB,EACxB,4BAA4B,CAC7B;;IASC;;;;;;;;;;;;OAYG;gBACS,EACV,KAAK,EACL,SAAS,EACT,eAAe,EACf,+BAAuC,EACvC,8BAAsC,GACvC,EAAE,0BAA0B;IAoC7B;;;OAGG;IACH,IAAI,IAAI,IAAI;IA+PZ;;;;;;;OAOG;IACH,UAAU,CAAC,KAAK,EAAE,sBAAsB,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,IAAI;IA0C3E;;;;;OAKG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,mBAAmB,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,IAAI;IASxE;;;;;;OAMG;IACH,SAAS,CACP,IAAI,EAAE,MAAM,EACZ,UAAU,CAAC,EAAE,wBAAwB,EACrC,OAAO,CAAC,EAAE,gBAAgB,GACzB,IAAI;IASP;;OAEG;IACH,KAAK,IAAI,IAAI;IAMb;;OAEG;IACH,MAAM,IAAI,IAAI;CAOf"}
import type { ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
import { BaseController } from "@metamask/base-controller";
import type { Messenger } from "@metamask/messenger";
import type { Json } from "@metamask/utils";
import type { AnalyticsControllerMethodActions } from "./AnalyticsController-method-action-types.mjs";
import type { AnalyticsPlatformAdapter, AnalyticsEventProperties, AnalyticsUserTraits, AnalyticsTrackingEvent } from "./AnalyticsPlatformAdapter.types.mjs";
import type { AnalyticsPlatformAdapter, AnalyticsContext, AnalyticsEventProperties, AnalyticsUserTraits, AnalyticsTrackingEvent } from "./AnalyticsPlatformAdapter.types.mjs";
/**

@@ -26,4 +27,65 @@ * The name of the {@link AnalyticsController}, used to namespace the

analyticsId: string;
/**
* Persisted queue of analytics events waiting for delivery acknowledgement.
* This is only used when event queue persistence is enabled.
*/
eventQueue?: Record<string, Json>;
};
/**
* Event types supported by the persisted analytics event queue.
*/
export type AnalyticsQueuedEventType = 'track' | 'identify' | 'view';
/**
* Base persisted event queue entry.
*/
export type AnalyticsQueuedEventBase = {
/**
* Event type used to replay the payload with the platform adapter.
*/
type: AnalyticsQueuedEventType;
/**
* Stable identifier for the analytics payload.
*/
messageId: string;
/**
* Original payload timestamp serialized for persistence.
*/
timestamp: string;
};
/**
* Persisted track event queue entry.
*/
export type AnalyticsQueuedTrackEvent = AnalyticsQueuedEventBase & {
type: 'track';
eventName: string;
properties?: AnalyticsEventProperties;
context?: AnalyticsContext;
};
/**
* Persisted identify event queue entry.
*/
export type AnalyticsQueuedIdentifyEvent = AnalyticsQueuedEventBase & {
type: 'identify';
userId: string;
traits?: AnalyticsUserTraits;
context?: AnalyticsContext;
};
/**
* Persisted view event queue entry.
*/
export type AnalyticsQueuedViewEvent = AnalyticsQueuedEventBase & {
type: 'view';
name: string;
properties?: AnalyticsEventProperties;
context?: AnalyticsContext;
};
/**
* Persisted analytics event queue entry.
*/
export type AnalyticsQueuedEvent = AnalyticsQueuedTrackEvent | AnalyticsQueuedIdentifyEvent | AnalyticsQueuedViewEvent;
/**
* Persisted analytics event queue keyed by message ID.
*/
export type AnalyticsEventQueue = Record<string, AnalyticsQueuedEvent>;
/**
* Returns default values for AnalyticsController state.

@@ -72,3 +134,4 @@ *

* Initial controller state. Must include a valid UUIDv4 `analyticsId`.
* The platform is responsible for generating and persisting the analyticsId.
* The platform is responsible for generating the ID on first run.
* It is then persisted with controller state when using a persisted store.
*/

@@ -90,2 +153,11 @@ state: AnalyticsControllerState;

isAnonymousEventsFeatureEnabled?: boolean;
/**
* Whether analytics event queue persistence is enabled.
*
* When enabled, AnalyticsController persists each platform adapter payload
* until the adapter reports successful delivery.
*
* @default false
*/
isEventQueuePersistenceEnabled?: boolean;
};

@@ -102,5 +174,4 @@ /**

*
* Note: The controller persists `optedIn` internally. The `analyticsId` is persisted
* by the platform and must be provided via initial state. The platform should subscribe
* to `AnalyticsController:stateChange` events to persist any state changes.
* The controller persists `optedIn` and `analyticsId` when composed with a persisted
* store. The platform must supply a valid `analyticsId` on first launch.
*/

@@ -118,6 +189,7 @@ export declare class AnalyticsController extends BaseController<'AnalyticsController', AnalyticsControllerState, AnalyticsControllerMessenger> {

* @param options.isAnonymousEventsFeatureEnabled - Whether the anonymous events feature is enabled
* @param options.isEventQueuePersistenceEnabled - Whether analytics event queue persistence is enabled
* @throws Error if state.analyticsId is missing or not a valid UUIDv4
* @remarks After construction, call {@link AnalyticsController.init} to complete initialization.
*/
constructor({ state, messenger, platformAdapter, isAnonymousEventsFeatureEnabled, }: AnalyticsControllerOptions);
constructor({ state, messenger, platformAdapter, isAnonymousEventsFeatureEnabled, isEventQueuePersistenceEnabled, }: AnalyticsControllerOptions);
/**

@@ -134,4 +206,5 @@ * Initialize the controller by calling the platform adapter's onSetupCompleted lifecycle hook.

* @param event - Analytics event with properties and sensitive properties
* @param context - Optional platform-specific context forwarded to the platform adapter.
*/
trackEvent(event: AnalyticsTrackingEvent): void;
trackEvent(event: AnalyticsTrackingEvent, context?: AnalyticsContext): void;
/**

@@ -141,4 +214,5 @@ * Identify a user for analytics.

* @param traits - User traits/properties
* @param context - Optional platform-specific context forwarded to the platform adapter.
*/
identify(traits?: AnalyticsUserTraits): void;
identify(traits?: AnalyticsUserTraits, context?: AnalyticsContext): void;
/**

@@ -149,4 +223,5 @@ * Track a page or screen view.

* @param properties - Optional properties associated with the view
* @param context - Optional platform-specific context forwarded to the platform adapter.
*/
trackView(name: string, properties?: AnalyticsEventProperties): void;
trackView(name: string, properties?: AnalyticsEventProperties, context?: AnalyticsContext): void;
/**

@@ -153,0 +228,0 @@ * Opt in to analytics.

@@ -1,1 +0,1 @@

{"version":3,"file":"AnalyticsController.d.mts","sourceRoot":"","sources":["../src/AnalyticsController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAErD,OAAO,KAAK,EAAE,gCAAgC,EAAE,sDAAkD;AAGlG,OAAO,KAAK,EACV,wBAAwB,EACxB,wBAAwB,EACxB,mBAAmB,EACnB,sBAAsB,EACvB,6CAAyC;AAK1C;;;;GAIG;AACH,eAAO,MAAM,cAAc,wBAAwB,CAAC;AAIpD;;GAEG;AACH,MAAM,MAAM,wBAAwB,GAAG;IACrC;;OAEG;IACH,OAAO,EAAE,OAAO,CAAC;IAEjB;;;;OAIG;IACH,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAgB,kCAAkC,IAAI,IAAI,CACxD,wBAAwB,EACxB,aAAa,CACd,CAIA;AAmCD;;GAEG;AACH,MAAM,MAAM,iCAAiC,GAAG,wBAAwB,CACtE,OAAO,cAAc,EACrB,wBAAwB,CACzB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAClC,iCAAiC,GACjC,gCAAgC,CAAC;AAErC;;GAEG;AACH,KAAK,cAAc,GAAG,KAAK,CAAC;AAE5B;;GAEG;AACH,MAAM,MAAM,mCAAmC,GAAG,0BAA0B,CAC1E,OAAO,cAAc,EACrB,wBAAwB,CACzB,CAAC;AAEF;;GA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C,EAAE,OAAO,CAAC;IAE1C;;;;;;;OAOG;IACH,8BAA8B,CAAC,EAAE,OAAO,CAAC;CAC1C,CAAC;AAyDF;;;;;;;;;;;;GAYG;AACH,qBAAa,mBAAoB,SAAQ,cAAc,CACrD,qBAAqB,EACrB,wBAAwB,EACxB,4BAA4B,CAC7B;;IASC;;;;;;;;;;;;OAYG;gBACS,EACV,KAAK,EACL,SAAS,EACT,eAAe,EACf,+BAAuC,EACvC,8BAAsC,GACvC,EAAE,0BAA0B;IAoC7B;;;OAGG;IACH,IAAI,IAAI,IAAI;IA+PZ;;;;;;;OAOG;IACH,UAAU,CAAC,KAAK,EAAE,sBAAsB,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,IAAI;IA0C3E;;;;;OAKG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,mBAAmB,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,IAAI;IASxE;;;;;;OAMG;IACH,SAAS,CACP,IAAI,EAAE,MAAM,EACZ,UAAU,CAAC,EAAE,wBAAwB,EACrC,OAAO,CAAC,EAAE,gBAAgB,GACzB,IAAI;IASP;;OAEG;IACH,KAAK,IAAI,IAAI;IAMb;;OAEG;IACH,MAAM,IAAI,IAAI;CAOf"}

@@ -12,4 +12,7 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {

};
var _AnalyticsController_platformAdapter, _AnalyticsController_isAnonymousEventsFeatureEnabled, _AnalyticsController_initialized;
var _AnalyticsController_instances, _AnalyticsController_platformAdapter, _AnalyticsController_isAnonymousEventsFeatureEnabled, _AnalyticsController_isEventQueuePersistenceEnabled, _AnalyticsController_initialized, _AnalyticsController_sendOrQueueTrackEvent, _AnalyticsController_sendOrQueueIdentifyEvent, _AnalyticsController_sendOrQueueViewEvent, _AnalyticsController_enqueueEvent, _AnalyticsController_sendQueuedEvent, _AnalyticsController_replayQueuedEvents, _AnalyticsController_removeQueuedEvent, _AnalyticsController_clearQueuedEvents;
import { BaseController } from "@metamask/base-controller";
import $lodash from "lodash";
const { cloneDeep } = $lodash;
import { v4 as uuid } from "uuid";
import { validateAnalyticsControllerState } from "./analyticsControllerStateValidator.mjs";

@@ -41,6 +44,4 @@ import { projectLogger as log } from "./AnalyticsLogger.mjs";

*
* Note: `optedIn` is persisted by the controller (`persist: true`).
* `analyticsId` is persisted by the platform (`persist: false`) and provided
* via initial state. The platform should subscribe to `stateChange` events
* to persist any state changes.
* Both `optedIn` and `analyticsId` are persisted (`persist: true`).
* The platform must supply a valid UUIDv4 `analyticsId` on first run.
*/

@@ -56,6 +57,12 @@ const analyticsControllerMetadata = {

includeInStateLogs: true,
persist: false,
persist: true,
includeInDebugSnapshot: true,
usedInUi: false,
},
eventQueue: {
includeInStateLogs: false,
persist: true,
includeInDebugSnapshot: false,
usedInUi: false,
},
};

@@ -71,2 +78,42 @@ // === MESSENGER ===

/**
* Returns whether a value is a non-array object.
*
* @param value - The value to check.
* @returns True if the value is a record.
*/
function isRecord(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
/**
* Returns whether a value is a valid persisted analytics event.
*
* @param value - The value to check.
* @returns True if the value is a queued analytics event.
*/
function isAnalyticsQueuedEvent(value) {
if (!isRecord(value)) {
return false;
}
if (typeof value.messageId !== 'string' ||
typeof value.timestamp !== 'string') {
return false;
}
if (value.type === 'track') {
return (typeof value.eventName === 'string' &&
(value.properties === undefined || isRecord(value.properties)) &&
(value.context === undefined || isRecord(value.context)));
}
if (value.type === 'identify') {
return (typeof value.userId === 'string' &&
(value.traits === undefined || isRecord(value.traits)) &&
(value.context === undefined || isRecord(value.context)));
}
if (value.type === 'view') {
return (typeof value.name === 'string' &&
(value.properties === undefined || isRecord(value.properties)) &&
(value.context === undefined || isRecord(value.context)));
}
return false;
}
/**
* The AnalyticsController manages analytics tracking across platforms (Mobile/Extension).

@@ -81,5 +128,4 @@ * It provides a unified interface for tracking events, identifying users, and managing

*
* Note: The controller persists `optedIn` internally. The `analyticsId` is persisted
* by the platform and must be provided via initial state. The platform should subscribe
* to `AnalyticsController:stateChange` events to persist any state changes.
* The controller persists `optedIn` and `analyticsId` when composed with a persisted
* store. The platform must supply a valid `analyticsId` on first launch.
*/

@@ -96,6 +142,7 @@ export class AnalyticsController extends BaseController {

* @param options.isAnonymousEventsFeatureEnabled - Whether the anonymous events feature is enabled
* @param options.isEventQueuePersistenceEnabled - Whether analytics event queue persistence is enabled
* @throws Error if state.analyticsId is missing or not a valid UUIDv4
* @remarks After construction, call {@link AnalyticsController.init} to complete initialization.
*/
constructor({ state, messenger, platformAdapter, isAnonymousEventsFeatureEnabled = false, }) {
constructor({ state, messenger, platformAdapter, isAnonymousEventsFeatureEnabled = false, isEventQueuePersistenceEnabled = false, }) {
const initialState = {

@@ -105,3 +152,3 @@ ...getDefaultAnalyticsControllerState(),

};
validateAnalyticsControllerState(initialState);
validateAnalyticsControllerState(initialState, platformAdapter.skipUUIDv4Check === true);
super({

@@ -113,6 +160,9 @@ name: controllerName,

});
_AnalyticsController_instances.add(this);
_AnalyticsController_platformAdapter.set(this, void 0);
_AnalyticsController_isAnonymousEventsFeatureEnabled.set(this, void 0);
_AnalyticsController_isEventQueuePersistenceEnabled.set(this, void 0);
_AnalyticsController_initialized.set(this, void 0);
__classPrivateFieldSet(this, _AnalyticsController_isAnonymousEventsFeatureEnabled, isAnonymousEventsFeatureEnabled, "f");
__classPrivateFieldSet(this, _AnalyticsController_isEventQueuePersistenceEnabled, isEventQueuePersistenceEnabled, "f");
__classPrivateFieldSet(this, _AnalyticsController_platformAdapter, platformAdapter, "f");

@@ -125,2 +175,3 @@ __classPrivateFieldSet(this, _AnalyticsController_initialized, false, "f");

analyticsId: this.state.analyticsId,
eventQueuePersistenceEnabled: __classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f"),
});

@@ -147,2 +198,3 @@ }

}
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_replayQueuedEvents).call(this);
}

@@ -155,4 +207,5 @@ /**

* @param event - Analytics event with properties and sensitive properties
* @param context - Optional platform-specific context forwarded to the platform adapter.
*/
trackEvent(event) {
trackEvent(event, context) {
// Don't track if analytics is disabled

@@ -165,3 +218,3 @@ if (!analyticsControllerSelectors.selectEnabled(this.state)) {

if (!event.hasProperties) {
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").track(event.name);
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueTrackEvent).call(this, event.name, undefined, context);
return;

@@ -173,13 +226,13 @@ }

// an event with user ID is tracked.
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").track(event.name, {
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueTrackEvent).call(this, event.name, {
...event.properties,
});
}, context);
}
const hasSensitiveProperties = Object.keys(event.sensitiveProperties).length > 0;
if (!__classPrivateFieldGet(this, _AnalyticsController_isAnonymousEventsFeatureEnabled, "f") || hasSensitiveProperties) {
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").track(event.name, {
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueTrackEvent).call(this, event.name, {
...event.properties,
...event.sensitiveProperties,
...(hasSensitiveProperties && { anonymous: true }),
});
}, context);
}

@@ -191,4 +244,5 @@ }

* @param traits - User traits/properties
* @param context - Optional platform-specific context forwarded to the platform adapter.
*/
identify(traits) {
identify(traits, context) {
if (!analyticsControllerSelectors.selectEnabled(this.state)) {

@@ -198,3 +252,3 @@ return;

// Delegate to platform adapter using the current analytics ID
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").identify(this.state.analyticsId, traits);
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueIdentifyEvent).call(this, this.state.analyticsId, traits, context);
}

@@ -206,4 +260,5 @@ /**

* @param properties - Optional properties associated with the view
* @param context - Optional platform-specific context forwarded to the platform adapter.
*/
trackView(name, properties) {
trackView(name, properties, context) {
if (!analyticsControllerSelectors.selectEnabled(this.state)) {

@@ -213,3 +268,3 @@ return;

// Delegate to platform adapter
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").view(name, properties);
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueViewEvent).call(this, name, properties, context);
}

@@ -231,5 +286,132 @@ /**

});
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearQueuedEvents).call(this);
}
}
_AnalyticsController_platformAdapter = new WeakMap(), _AnalyticsController_isAnonymousEventsFeatureEnabled = new WeakMap(), _AnalyticsController_initialized = new WeakMap();
_AnalyticsController_platformAdapter = new WeakMap(), _AnalyticsController_isAnonymousEventsFeatureEnabled = new WeakMap(), _AnalyticsController_isEventQueuePersistenceEnabled = new WeakMap(), _AnalyticsController_initialized = new WeakMap(), _AnalyticsController_instances = new WeakSet(), _AnalyticsController_sendOrQueueTrackEvent = function _AnalyticsController_sendOrQueueTrackEvent(eventName, properties, context) {
if (!__classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f")) {
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").track(eventName, properties, context);
return;
}
const queuedEvent = {
type: 'track',
eventName,
messageId: uuid(),
timestamp: new Date().toISOString(),
...(properties === undefined ? {} : { properties }),
...(context === undefined ? {} : { context }),
};
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_enqueueEvent).call(this, queuedEvent);
}, _AnalyticsController_sendOrQueueIdentifyEvent = function _AnalyticsController_sendOrQueueIdentifyEvent(userId, traits, context) {
if (!__classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f")) {
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").identify(userId, traits, context);
return;
}
const queuedEvent = {
type: 'identify',
userId,
messageId: uuid(),
timestamp: new Date().toISOString(),
...(traits === undefined ? {} : { traits }),
...(context === undefined ? {} : { context }),
};
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_enqueueEvent).call(this, queuedEvent);
}, _AnalyticsController_sendOrQueueViewEvent = function _AnalyticsController_sendOrQueueViewEvent(name, properties, context) {
if (!__classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f")) {
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").view(name, properties, context);
return;
}
const queuedEvent = {
type: 'view',
name,
messageId: uuid(),
timestamp: new Date().toISOString(),
...(properties === undefined ? {} : { properties }),
...(context === undefined ? {} : { context }),
};
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_enqueueEvent).call(this, queuedEvent);
}, _AnalyticsController_enqueueEvent = function _AnalyticsController_enqueueEvent(queuedEvent) {
const eventQueue = {
...(this.state.eventQueue ?? {}),
[queuedEvent.messageId]: queuedEvent,
};
this.update((state) => {
state.eventQueue = eventQueue;
});
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendQueuedEvent).call(this, queuedEvent);
}, _AnalyticsController_sendQueuedEvent = function _AnalyticsController_sendQueuedEvent(queuedEvent) {
const timestamp = new Date(queuedEvent.timestamp);
if (Number.isNaN(timestamp.getTime())) {
log('Dropping queued analytics event with invalid timestamp', {
messageId: queuedEvent.messageId,
});
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_removeQueuedEvent).call(this, queuedEvent.messageId);
return;
}
const options = {
messageId: queuedEvent.messageId,
timestamp,
callback: (error) => {
if (error) {
log('Queued analytics event delivery failed', {
messageId: queuedEvent.messageId,
error,
});
return;
}
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_removeQueuedEvent).call(this, queuedEvent.messageId);
},
};
try {
if (queuedEvent.type === 'track') {
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").track(queuedEvent.eventName, cloneDeep(queuedEvent.properties), cloneDeep(queuedEvent.context), options);
}
else if (queuedEvent.type === 'identify') {
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").identify(queuedEvent.userId, cloneDeep(queuedEvent.traits), cloneDeep(queuedEvent.context), options);
}
else {
__classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").view(queuedEvent.name, cloneDeep(queuedEvent.properties), cloneDeep(queuedEvent.context), options);
}
}
catch (error) {
log('Error sending queued analytics event', {
messageId: queuedEvent.messageId,
error,
});
}
}, _AnalyticsController_replayQueuedEvents = function _AnalyticsController_replayQueuedEvents() {
if (!__classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f") || !this.state.eventQueue) {
return;
}
if (!analyticsControllerSelectors.selectEnabled(this.state)) {
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearQueuedEvents).call(this);
return;
}
for (const [messageId, queuedEvent] of Object.entries(this.state.eventQueue)) {
if (!isAnalyticsQueuedEvent(queuedEvent) ||
queuedEvent.messageId !== messageId) {
log('Dropping invalid queued analytics event', { messageId });
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_removeQueuedEvent).call(this, messageId);
continue;
}
__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendQueuedEvent).call(this, queuedEvent);
}
}, _AnalyticsController_removeQueuedEvent = function _AnalyticsController_removeQueuedEvent(messageId) {
const currentEventQueue = this.state.eventQueue;
if (!currentEventQueue ||
!Object.prototype.hasOwnProperty.call(currentEventQueue, messageId)) {
return;
}
const { [messageId]: _deletedEvent, ...eventQueue } = currentEventQueue;
this.update((state) => {
state.eventQueue = eventQueue;
});
}, _AnalyticsController_clearQueuedEvents = function _AnalyticsController_clearQueuedEvents() {
if (!this.state.eventQueue ||
Object.keys(this.state.eventQueue).length === 0) {
return;
}
this.update((state) => {
state.eventQueue = {};
});
};
//# sourceMappingURL=AnalyticsController.mjs.map

@@ -1,1 +0,1 @@

{"version":3,"file":"AnalyticsController.mjs","sourceRoot":"","sources":["../src/AnalyticsController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAKA,OAAO,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;YACpB,KAAK,CAAC,OAAO,GAAG,IAAI,CAAC;QACvB,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACH,MAAM;QACJ,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,OAAO,GAAG,KAAK,CAAC;QACxB,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\n\nimport type { AnalyticsControllerMethodActions } from './AnalyticsController-method-action-types';\nimport { validateAnalyticsControllerState } from './analyticsControllerStateValidator';\nimport { projectLogger as log } from './AnalyticsLogger';\nimport type {\n AnalyticsPlatformAdapter,\n AnalyticsEventProperties,\n AnalyticsUserTraits,\n AnalyticsTrackingEvent,\n} from './AnalyticsPlatformAdapter.types';\nimport { analyticsControllerSelectors } from './selectors';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link AnalyticsController}, used to namespace the\n * controller's actions and events and to namespace the controller's state data\n * when composed with other controllers.\n */\nexport const controllerName = 'AnalyticsController';\n\n// === STATE ===\n\n/**\n * Describes the shape of the state object for {@link AnalyticsController}.\n */\nexport type AnalyticsControllerState = {\n /**\n * Whether the user has opted in to analytics.\n */\n optedIn: boolean;\n\n /**\n * User's UUIDv4 analytics identifier.\n * This is an identity (unique per user), not a preference.\n * Must be provided by the platform - the controller does not generate it.\n */\n analyticsId: string;\n};\n\n/**\n * Returns default values for AnalyticsController state.\n *\n * Note: analyticsId is NOT included - it's an identity that must be\n * provided by the platform (generated once on first run, then persisted).\n *\n * @returns Default state without analyticsId\n */\nexport function getDefaultAnalyticsControllerState(): Omit<\n AnalyticsControllerState,\n 'analyticsId'\n> {\n return {\n optedIn: false,\n };\n}\n\n/**\n * The metadata for each property in {@link AnalyticsControllerState}.\n *\n * Note: `optedIn` is persisted by the controller (`persist: true`).\n * `analyticsId` is persisted by the platform (`persist: false`) and provided\n * via initial state. The platform should subscribe to `stateChange` events\n * to persist any state changes.\n */\nconst analyticsControllerMetadata = {\n optedIn: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n analyticsId: {\n includeInStateLogs: true,\n persist: false,\n includeInDebugSnapshot: true,\n usedInUi: false,\n },\n} satisfies StateMetadata<AnalyticsControllerState>;\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'trackEvent',\n 'identify',\n 'trackView',\n 'optIn',\n 'optOut',\n] as const;\n\n/**\n * Returns the state of the {@link AnalyticsController}.\n */\nexport type AnalyticsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n AnalyticsControllerState\n>;\n\n/**\n * Actions that {@link AnalyticsControllerMessenger} exposes to other consumers.\n */\nexport type AnalyticsControllerActions =\n | AnalyticsControllerGetStateAction\n | AnalyticsControllerMethodActions;\n\n/**\n * Actions from other messengers that {@link AnalyticsControllerMessenger} calls.\n */\ntype AllowedActions = never;\n\n/**\n * Event emitted when the state of the {@link AnalyticsController} changes.\n */\nexport type AnalyticsControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n AnalyticsControllerState\n>;\n\n/**\n * Events that {@link AnalyticsControllerMessenger} exposes to other consumers.\n */\nexport type AnalyticsControllerEvents = AnalyticsControllerStateChangeEvent;\n\n/**\n * Events from other messengers that {@link AnalyticsControllerMessenger} subscribes to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link AnalyticsController}.\n */\nexport type AnalyticsControllerMessenger = Messenger<\n typeof controllerName,\n AnalyticsControllerActions | AllowedActions,\n AnalyticsControllerEvents | AllowedEvents\n>;\n\n// === CONTROLLER DEFINITION ===\n\n/**\n * The options that AnalyticsController takes.\n */\nexport type AnalyticsControllerOptions = {\n /**\n * Initial controller state. Must include a valid UUIDv4 `analyticsId`.\n * The platform is responsible for generating and persisting the analyticsId.\n */\n state: AnalyticsControllerState;\n /**\n * Messenger used to communicate with BaseController and other controllers.\n */\n messenger: AnalyticsControllerMessenger;\n /**\n * Platform adapter implementation for tracking events.\n */\n platformAdapter: AnalyticsPlatformAdapter;\n\n /**\n * Whether the anonymous events feature is enabled.\n *\n * @default false\n */\n isAnonymousEventsFeatureEnabled?: boolean;\n};\n\n/**\n * The AnalyticsController manages analytics tracking across platforms (Mobile/Extension).\n * It provides a unified interface for tracking events, identifying users, and managing\n * analytics preferences while delegating platform-specific implementation to an\n * {@link AnalyticsPlatformAdapter}.\n *\n * This controller follows the MetaMask controller pattern and integrates with the\n * messenger system to allow other controllers and components to track analytics events.\n * It delegates platform-specific implementation to an {@link AnalyticsPlatformAdapter}.\n *\n * Note: The controller persists `optedIn` internally. The `analyticsId` is persisted\n * by the platform and must be provided via initial state. The platform should subscribe\n * to `AnalyticsController:stateChange` events to persist any state changes.\n */\nexport class AnalyticsController extends BaseController<\n 'AnalyticsController',\n AnalyticsControllerState,\n AnalyticsControllerMessenger\n> {\n readonly #platformAdapter: AnalyticsPlatformAdapter;\n\n readonly #isAnonymousEventsFeatureEnabled: boolean;\n\n #initialized: boolean;\n\n /**\n * Constructs an AnalyticsController instance.\n *\n * @param options - Controller options\n * @param options.state - Initial controller state. Must include a valid UUIDv4 `analyticsId`.\n * Use `getDefaultAnalyticsControllerState()` for default opt-in preferences.\n * @param options.messenger - Messenger used to communicate with BaseController\n * @param options.platformAdapter - Platform adapter implementation for tracking\n * @param options.isAnonymousEventsFeatureEnabled - Whether the anonymous events feature is enabled\n * @throws Error if state.analyticsId is missing or not a valid UUIDv4\n * @remarks After construction, call {@link AnalyticsController.init} to complete initialization.\n */\n constructor({\n state,\n messenger,\n platformAdapter,\n isAnonymousEventsFeatureEnabled = false,\n }: AnalyticsControllerOptions) {\n const initialState: AnalyticsControllerState = {\n ...getDefaultAnalyticsControllerState(),\n ...state,\n };\n\n validateAnalyticsControllerState(initialState);\n\n super({\n name: controllerName,\n metadata: analyticsControllerMetadata,\n state: initialState,\n messenger,\n });\n\n this.#isAnonymousEventsFeatureEnabled = isAnonymousEventsFeatureEnabled;\n this.#platformAdapter = platformAdapter;\n this.#initialized = false;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n log('AnalyticsController initialized and ready', {\n enabled: analyticsControllerSelectors.selectEnabled(this.state),\n optedIn: this.state.optedIn,\n analyticsId: this.state.analyticsId,\n });\n }\n\n /**\n * Initialize the controller by calling the platform adapter's onSetupCompleted lifecycle hook.\n * This method must be called after construction to complete the setup process.\n */\n init(): void {\n if (this.#initialized) {\n log('AnalyticsController already initialized.');\n return;\n }\n\n this.#initialized = true;\n\n // Call onSetupCompleted lifecycle hook after initialization\n // State is already validated, so analyticsId is guaranteed to be a valid UUIDv4\n try {\n this.#platformAdapter.onSetupCompleted(this.state.analyticsId);\n } catch (error) {\n // Log error but don't throw - adapter setup failure shouldn't break controller\n log('Error calling platformAdapter.onSetupCompleted', error);\n }\n }\n\n /**\n * Track an analytics event.\n *\n * Events are only tracked if analytics is enabled.\n *\n * @param event - Analytics event with properties and sensitive properties\n */\n trackEvent(event: AnalyticsTrackingEvent): void {\n // Don't track if analytics is disabled\n if (!analyticsControllerSelectors.selectEnabled(this.state)) {\n return;\n }\n\n // if event does not have properties, send event without properties\n // and return to prevent any additional processing\n if (!event.hasProperties) {\n this.#platformAdapter.track(event.name);\n return;\n }\n\n // Track regular properties first if anonymous events feature is enabled\n if (this.#isAnonymousEventsFeatureEnabled) {\n // Note: Even if regular properties object is empty, we still send it to ensure\n // an event with user ID is tracked.\n this.#platformAdapter.track(event.name, {\n ...event.properties,\n });\n }\n\n const hasSensitiveProperties =\n Object.keys(event.sensitiveProperties).length > 0;\n\n if (!this.#isAnonymousEventsFeatureEnabled || hasSensitiveProperties) {\n this.#platformAdapter.track(event.name, {\n ...event.properties,\n ...event.sensitiveProperties,\n ...(hasSensitiveProperties && { anonymous: true }),\n });\n }\n }\n\n /**\n * Identify a user for analytics.\n *\n * @param traits - User traits/properties\n */\n identify(traits?: AnalyticsUserTraits): void {\n if (!analyticsControllerSelectors.selectEnabled(this.state)) {\n return;\n }\n\n // Delegate to platform adapter using the current analytics ID\n this.#platformAdapter.identify(this.state.analyticsId, traits);\n }\n\n /**\n * Track a page or screen view.\n *\n * @param name - The identifier/name of the page or screen being viewed (e.g., \"home\", \"settings\", \"wallet\")\n * @param properties - Optional properties associated with the view\n */\n trackView(name: string, properties?: AnalyticsEventProperties): void {\n if (!analyticsControllerSelectors.selectEnabled(this.state)) {\n return;\n }\n\n // Delegate to platform adapter\n this.#platformAdapter.view(name, properties);\n }\n\n /**\n * Opt in to analytics.\n */\n optIn(): void {\n this.update((state) => {\n state.optedIn = true;\n });\n }\n\n /**\n * Opt out of analytics.\n */\n optOut(): void {\n this.update((state) => {\n state.optedIn = false;\n });\n }\n}\n"]}
{"version":3,"file":"AnalyticsController.mjs","sourceRoot":"","sources":["../src/AnalyticsController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAKA,OAAO,EAAE,cAAc,EAAE,kCAAkC;;;AAI3D,OAAO,EAAE,EAAE,IAAI,IAAI,EAAE,aAAa;AAGlC,OAAO,EAAE,gCAAgC,EAAE,gDAA4C;AACvF,OAAO,EAAE,aAAa,IAAI,GAAG,EAAE,8BAA0B;AASzD,OAAO,EAAE,4BAA4B,EAAE,wBAAoB;AAE3D,kBAAkB;AAElB;;;;GAIG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,qBAAqB,CAAC;AA+FpD;;;;;;;GAOG;AACH,MAAM,UAAU,kCAAkC;IAIhD,OAAO;QACL,OAAO,EAAE,KAAK;KACf,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,2BAA2B,GAAG;IAClC,OAAO,EAAE;QACP,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,WAAW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AC;YACnC,SAAS;QACX,CAAC;QAED,uBAAA,IAAI,4EAAiB,MAArB,IAAI,EAAkB,WAAW,CAAC,CAAC;IACrC,CAAC;AACH,CAAC,2FAOkB,SAAiB;IAClC,MAAM,iBAAiB,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC;IAEhD,IACE,CAAC,iBAAiB;QAClB,CAAC,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,iBAAiB,EAAE,SAAS,CAAC,EACnE,CAAC;QACD,OAAO;IACT,CAAC;IAED,MAAM,EAAE,CAAC,SAAS,CAAC,EAAE,aAAa,EAAE,GAAG,UAAU,EAAE,GAAG,iBAAiB,CAAC;IAExE,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,UAAU,GAAG,UAAmB,CAAC;IACzC,CAAC,CAAC,CAAC;AACL,CAAC;IAMC,IACE,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU;QACtB,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,MAAM,KAAK,CAAC,EAC/C,CAAC;QACD,OAAO;IACT,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,UAAU,GAAG,EAAW,CAAC;IACjC,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { Json } from '@metamask/utils';\nimport { cloneDeep } from 'lodash';\nimport { v4 as uuid } from 'uuid';\n\nimport type { AnalyticsControllerMethodActions } from './AnalyticsController-method-action-types';\nimport { validateAnalyticsControllerState } from './analyticsControllerStateValidator';\nimport { projectLogger as log } from './AnalyticsLogger';\nimport type {\n AnalyticsPlatformAdapter,\n AnalyticsDeliveryOptions,\n AnalyticsContext,\n AnalyticsEventProperties,\n AnalyticsUserTraits,\n AnalyticsTrackingEvent,\n} from './AnalyticsPlatformAdapter.types';\nimport { analyticsControllerSelectors } from './selectors';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link AnalyticsController}, used to namespace the\n * controller's actions and events and to namespace the controller's state data\n * when composed with other controllers.\n */\nexport const controllerName = 'AnalyticsController';\n\n// === STATE ===\n\n/**\n * Describes the shape of the state object for {@link AnalyticsController}.\n */\nexport type AnalyticsControllerState = {\n /**\n * Whether the user has opted in to analytics.\n */\n optedIn: boolean;\n\n /**\n * User's UUIDv4 analytics identifier.\n * This is an identity (unique per user), not a preference.\n * Must be provided by the platform - the controller does not generate it.\n */\n analyticsId: string;\n\n /**\n * Persisted queue of analytics events waiting for delivery acknowledgement.\n * This is only used when event queue persistence is enabled.\n */\n eventQueue?: Record<string, Json>;\n};\n\n/**\n * Event types supported by the persisted analytics event queue.\n */\nexport type AnalyticsQueuedEventType = 'track' | 'identify' | 'view';\n\n/**\n * Base persisted event queue entry.\n */\nexport type AnalyticsQueuedEventBase = {\n /**\n * Event type used to replay the payload with the platform adapter.\n */\n type: AnalyticsQueuedEventType;\n\n /**\n * Stable identifier for the analytics payload.\n */\n messageId: string;\n\n /**\n * Original payload timestamp serialized for persistence.\n */\n timestamp: string;\n};\n\n/**\n * Persisted track event queue entry.\n */\nexport type AnalyticsQueuedTrackEvent = AnalyticsQueuedEventBase & {\n type: 'track';\n eventName: string;\n properties?: AnalyticsEventProperties;\n context?: AnalyticsContext;\n};\n\n/**\n * Persisted identify event queue entry.\n */\nexport type AnalyticsQueuedIdentifyEvent = AnalyticsQueuedEventBase & {\n type: 'identify';\n userId: string;\n traits?: AnalyticsUserTraits;\n context?: AnalyticsContext;\n};\n\n/**\n * Persisted view event queue entry.\n */\nexport type AnalyticsQueuedViewEvent = AnalyticsQueuedEventBase & {\n type: 'view';\n name: string;\n properties?: AnalyticsEventProperties;\n context?: AnalyticsContext;\n};\n\n/**\n * Persisted analytics event queue entry.\n */\nexport type AnalyticsQueuedEvent =\n | AnalyticsQueuedTrackEvent\n | AnalyticsQueuedIdentifyEvent\n | AnalyticsQueuedViewEvent;\n\n/**\n * Persisted analytics event queue keyed by message ID.\n */\nexport type AnalyticsEventQueue = Record<string, AnalyticsQueuedEvent>;\n\n/**\n * Returns default values for AnalyticsController state.\n *\n * Note: analyticsId is NOT included - it's an identity that must be\n * provided by the platform (generated once on first run, then persisted).\n *\n * @returns Default state without analyticsId\n */\nexport function getDefaultAnalyticsControllerState(): Omit<\n AnalyticsControllerState,\n 'analyticsId'\n> {\n return {\n optedIn: false,\n };\n}\n\n/**\n * The metadata for each property in {@link AnalyticsControllerState}.\n *\n * Both `optedIn` and `analyticsId` are persisted (`persist: true`).\n * The platform must supply a valid UUIDv4 `analyticsId` on first run.\n */\nconst analyticsControllerMetadata = {\n optedIn: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n analyticsId: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: false,\n },\n eventQueue: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: false,\n },\n} satisfies StateMetadata<AnalyticsControllerState>;\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = [\n 'trackEvent',\n 'identify',\n 'trackView',\n 'optIn',\n 'optOut',\n] as const;\n\n/**\n * Returns the state of the {@link AnalyticsController}.\n */\nexport type AnalyticsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n AnalyticsControllerState\n>;\n\n/**\n * Actions that {@link AnalyticsControllerMessenger} exposes to other consumers.\n */\nexport type AnalyticsControllerActions =\n | AnalyticsControllerGetStateAction\n | AnalyticsControllerMethodActions;\n\n/**\n * Actions from other messengers that {@link AnalyticsControllerMessenger} calls.\n */\ntype AllowedActions = never;\n\n/**\n * Event emitted when the state of the {@link AnalyticsController} changes.\n */\nexport type AnalyticsControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n AnalyticsControllerState\n>;\n\n/**\n * Events that {@link AnalyticsControllerMessenger} exposes to other consumers.\n */\nexport type AnalyticsControllerEvents = AnalyticsControllerStateChangeEvent;\n\n/**\n * Events from other messengers that {@link AnalyticsControllerMessenger} subscribes to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link AnalyticsController}.\n */\nexport type AnalyticsControllerMessenger = Messenger<\n typeof controllerName,\n AnalyticsControllerActions | AllowedActions,\n AnalyticsControllerEvents | AllowedEvents\n>;\n\n// === CONTROLLER DEFINITION ===\n\n/**\n * The options that AnalyticsController takes.\n */\nexport type AnalyticsControllerOptions = {\n /**\n * Initial controller state. Must include a valid UUIDv4 `analyticsId`.\n * The platform is responsible for generating the ID on first run.\n * It is then persisted with controller state when using a persisted store.\n */\n state: AnalyticsControllerState;\n /**\n * Messenger used to communicate with BaseController and other controllers.\n */\n messenger: AnalyticsControllerMessenger;\n /**\n * Platform adapter implementation for tracking events.\n */\n platformAdapter: AnalyticsPlatformAdapter;\n\n /**\n * Whether the anonymous events feature is enabled.\n *\n * @default false\n */\n isAnonymousEventsFeatureEnabled?: boolean;\n\n /**\n * Whether analytics event queue persistence is enabled.\n *\n * When enabled, AnalyticsController persists each platform adapter payload\n * until the adapter reports successful delivery.\n *\n * @default false\n */\n isEventQueuePersistenceEnabled?: boolean;\n};\n\n/**\n * Returns whether a value is a non-array object.\n *\n * @param value - The value to check.\n * @returns True if the value is a record.\n */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Returns whether a value is a valid persisted analytics event.\n *\n * @param value - The value to check.\n * @returns True if the value is a queued analytics event.\n */\nfunction isAnalyticsQueuedEvent(value: unknown): value is AnalyticsQueuedEvent {\n if (!isRecord(value)) {\n return false;\n }\n\n if (\n typeof value.messageId !== 'string' ||\n typeof value.timestamp !== 'string'\n ) {\n return false;\n }\n\n if (value.type === 'track') {\n return (\n typeof value.eventName === 'string' &&\n (value.properties === undefined || isRecord(value.properties)) &&\n (value.context === undefined || isRecord(value.context))\n );\n }\n\n if (value.type === 'identify') {\n return (\n typeof value.userId === 'string' &&\n (value.traits === undefined || isRecord(value.traits)) &&\n (value.context === undefined || isRecord(value.context))\n );\n }\n\n if (value.type === 'view') {\n return (\n typeof value.name === 'string' &&\n (value.properties === undefined || isRecord(value.properties)) &&\n (value.context === undefined || isRecord(value.context))\n );\n }\n\n return false;\n}\n\n/**\n * The AnalyticsController manages analytics tracking across platforms (Mobile/Extension).\n * It provides a unified interface for tracking events, identifying users, and managing\n * analytics preferences while delegating platform-specific implementation to an\n * {@link AnalyticsPlatformAdapter}.\n *\n * This controller follows the MetaMask controller pattern and integrates with the\n * messenger system to allow other controllers and components to track analytics events.\n * It delegates platform-specific implementation to an {@link AnalyticsPlatformAdapter}.\n *\n * The controller persists `optedIn` and `analyticsId` when composed with a persisted\n * store. The platform must supply a valid `analyticsId` on first launch.\n */\nexport class AnalyticsController extends BaseController<\n 'AnalyticsController',\n AnalyticsControllerState,\n AnalyticsControllerMessenger\n> {\n readonly #platformAdapter: AnalyticsPlatformAdapter;\n\n readonly #isAnonymousEventsFeatureEnabled: boolean;\n\n readonly #isEventQueuePersistenceEnabled: boolean;\n\n #initialized: boolean;\n\n /**\n * Constructs an AnalyticsController instance.\n *\n * @param options - Controller options\n * @param options.state - Initial controller state. Must include a valid UUIDv4 `analyticsId`.\n * Use `getDefaultAnalyticsControllerState()` for default opt-in preferences.\n * @param options.messenger - Messenger used to communicate with BaseController\n * @param options.platformAdapter - Platform adapter implementation for tracking\n * @param options.isAnonymousEventsFeatureEnabled - Whether the anonymous events feature is enabled\n * @param options.isEventQueuePersistenceEnabled - Whether analytics event queue persistence is enabled\n * @throws Error if state.analyticsId is missing or not a valid UUIDv4\n * @remarks After construction, call {@link AnalyticsController.init} to complete initialization.\n */\n constructor({\n state,\n messenger,\n platformAdapter,\n isAnonymousEventsFeatureEnabled = false,\n isEventQueuePersistenceEnabled = false,\n }: AnalyticsControllerOptions) {\n const initialState: AnalyticsControllerState = {\n ...getDefaultAnalyticsControllerState(),\n ...state,\n };\n\n validateAnalyticsControllerState(\n initialState,\n platformAdapter.skipUUIDv4Check === true,\n );\n\n super({\n name: controllerName,\n metadata: analyticsControllerMetadata,\n state: initialState,\n messenger,\n });\n\n this.#isAnonymousEventsFeatureEnabled = isAnonymousEventsFeatureEnabled;\n this.#isEventQueuePersistenceEnabled = isEventQueuePersistenceEnabled;\n this.#platformAdapter = platformAdapter;\n this.#initialized = false;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n\n log('AnalyticsController initialized and ready', {\n enabled: analyticsControllerSelectors.selectEnabled(this.state),\n optedIn: this.state.optedIn,\n analyticsId: this.state.analyticsId,\n eventQueuePersistenceEnabled: this.#isEventQueuePersistenceEnabled,\n });\n }\n\n /**\n * Initialize the controller by calling the platform adapter's onSetupCompleted lifecycle hook.\n * This method must be called after construction to complete the setup process.\n */\n init(): void {\n if (this.#initialized) {\n log('AnalyticsController already initialized.');\n return;\n }\n\n this.#initialized = true;\n\n // Call onSetupCompleted lifecycle hook after initialization\n // State is already validated, so analyticsId is guaranteed to be a valid UUIDv4\n try {\n this.#platformAdapter.onSetupCompleted(this.state.analyticsId);\n } catch (error) {\n // Log error but don't throw - adapter setup failure shouldn't break controller\n log('Error calling platformAdapter.onSetupCompleted', error);\n }\n\n this.#replayQueuedEvents();\n }\n\n /**\n * Send final track payload through the platform adapter or queue it if persistence is enabled.\n *\n * @param eventName - The name of the event.\n * @param properties - Optional event properties.\n * @param context - Optional platform-specific context.\n */\n #sendOrQueueTrackEvent(\n eventName: string,\n properties?: AnalyticsEventProperties,\n context?: AnalyticsContext,\n ): void {\n if (!this.#isEventQueuePersistenceEnabled) {\n this.#platformAdapter.track(eventName, properties, context);\n return;\n }\n\n const queuedEvent: AnalyticsQueuedTrackEvent = {\n type: 'track',\n eventName,\n messageId: uuid(),\n timestamp: new Date().toISOString(),\n ...(properties === undefined ? {} : { properties }),\n ...(context === undefined ? {} : { context }),\n };\n\n this.#enqueueEvent(queuedEvent);\n }\n\n /**\n * Send final identify payload through the platform adapter or queue it if persistence is enabled.\n *\n * @param userId - The user ID.\n * @param traits - Optional user traits.\n * @param context - Optional platform-specific context.\n */\n #sendOrQueueIdentifyEvent(\n userId: string,\n traits?: AnalyticsUserTraits,\n context?: AnalyticsContext,\n ): void {\n if (!this.#isEventQueuePersistenceEnabled) {\n this.#platformAdapter.identify(userId, traits, context);\n return;\n }\n\n const queuedEvent: AnalyticsQueuedIdentifyEvent = {\n type: 'identify',\n userId,\n messageId: uuid(),\n timestamp: new Date().toISOString(),\n ...(traits === undefined ? {} : { traits }),\n ...(context === undefined ? {} : { context }),\n };\n\n this.#enqueueEvent(queuedEvent);\n }\n\n /**\n * Send final view payload through the platform adapter or queue it if persistence is enabled.\n *\n * @param name - The view name.\n * @param properties - Optional view properties.\n * @param context - Optional platform-specific context.\n */\n #sendOrQueueViewEvent(\n name: string,\n properties?: AnalyticsEventProperties,\n context?: AnalyticsContext,\n ): void {\n if (!this.#isEventQueuePersistenceEnabled) {\n this.#platformAdapter.view(name, properties, context);\n return;\n }\n\n const queuedEvent: AnalyticsQueuedViewEvent = {\n type: 'view',\n name,\n messageId: uuid(),\n timestamp: new Date().toISOString(),\n ...(properties === undefined ? {} : { properties }),\n ...(context === undefined ? {} : { context }),\n };\n\n this.#enqueueEvent(queuedEvent);\n }\n\n /**\n * Add an analytics event to the queue and send it.\n *\n * @param queuedEvent - The event to enqueue and deliver.\n */\n #enqueueEvent(queuedEvent: AnalyticsQueuedEvent): void {\n const eventQueue: Record<string, Json> = {\n ...(this.state.eventQueue ?? {}),\n [queuedEvent.messageId]: queuedEvent as unknown as Json,\n };\n\n this.update((state) => {\n state.eventQueue = eventQueue as never;\n });\n\n this.#sendQueuedEvent(queuedEvent);\n }\n\n /**\n * Send a queued event through the platform adapter.\n *\n * @param queuedEvent - The queued event to deliver.\n */\n #sendQueuedEvent(queuedEvent: AnalyticsQueuedEvent): void {\n const timestamp = new Date(queuedEvent.timestamp);\n\n if (Number.isNaN(timestamp.getTime())) {\n log('Dropping queued analytics event with invalid timestamp', {\n messageId: queuedEvent.messageId,\n });\n this.#removeQueuedEvent(queuedEvent.messageId);\n return;\n }\n\n const options: AnalyticsDeliveryOptions = {\n messageId: queuedEvent.messageId,\n timestamp,\n callback: (error?: unknown) => {\n if (error) {\n log('Queued analytics event delivery failed', {\n messageId: queuedEvent.messageId,\n error,\n });\n return;\n }\n\n this.#removeQueuedEvent(queuedEvent.messageId);\n },\n };\n\n try {\n if (queuedEvent.type === 'track') {\n this.#platformAdapter.track(\n queuedEvent.eventName,\n cloneDeep(queuedEvent.properties),\n cloneDeep(queuedEvent.context),\n options,\n );\n } else if (queuedEvent.type === 'identify') {\n this.#platformAdapter.identify(\n queuedEvent.userId,\n cloneDeep(queuedEvent.traits),\n cloneDeep(queuedEvent.context),\n options,\n );\n } else {\n this.#platformAdapter.view(\n queuedEvent.name,\n cloneDeep(queuedEvent.properties),\n cloneDeep(queuedEvent.context),\n options,\n );\n }\n } catch (error) {\n log('Error sending queued analytics event', {\n messageId: queuedEvent.messageId,\n error,\n });\n }\n }\n\n /**\n * Replay persisted analytics events.\n */\n #replayQueuedEvents(): void {\n if (!this.#isEventQueuePersistenceEnabled || !this.state.eventQueue) {\n return;\n }\n\n if (!analyticsControllerSelectors.selectEnabled(this.state)) {\n this.#clearQueuedEvents();\n return;\n }\n\n for (const [messageId, queuedEvent] of Object.entries(\n this.state.eventQueue,\n )) {\n if (\n !isAnalyticsQueuedEvent(queuedEvent) ||\n queuedEvent.messageId !== messageId\n ) {\n log('Dropping invalid queued analytics event', { messageId });\n this.#removeQueuedEvent(messageId);\n continue;\n }\n\n this.#sendQueuedEvent(queuedEvent);\n }\n }\n\n /**\n * Remove a queued analytics event.\n *\n * @param messageId - The queued event message ID.\n */\n #removeQueuedEvent(messageId: string): void {\n const currentEventQueue = this.state.eventQueue;\n\n if (\n !currentEventQueue ||\n !Object.prototype.hasOwnProperty.call(currentEventQueue, messageId)\n ) {\n return;\n }\n\n const { [messageId]: _deletedEvent, ...eventQueue } = currentEventQueue;\n\n this.update((state) => {\n state.eventQueue = eventQueue as never;\n });\n }\n\n /**\n * Clear all queued analytics events.\n */\n #clearQueuedEvents(): void {\n if (\n !this.state.eventQueue ||\n Object.keys(this.state.eventQueue).length === 0\n ) {\n return;\n }\n\n this.update((state) => {\n state.eventQueue = {} as never;\n });\n }\n\n /**\n * Track an analytics event.\n *\n * Events are only tracked if analytics is enabled.\n *\n * @param event - Analytics event with properties and sensitive properties\n * @param context - Optional platform-specific context forwarded to the platform adapter.\n */\n trackEvent(event: AnalyticsTrackingEvent, context?: AnalyticsContext): void {\n // Don't track if analytics is disabled\n if (!analyticsControllerSelectors.selectEnabled(this.state)) {\n return;\n }\n\n // if event does not have properties, send event without properties\n // and return to prevent any additional processing\n if (!event.hasProperties) {\n this.#sendOrQueueTrackEvent(event.name, undefined, context);\n return;\n }\n\n // Track regular properties first if anonymous events feature is enabled\n if (this.#isAnonymousEventsFeatureEnabled) {\n // Note: Even if regular properties object is empty, we still send it to ensure\n // an event with user ID is tracked.\n this.#sendOrQueueTrackEvent(\n event.name,\n {\n ...event.properties,\n },\n context,\n );\n }\n\n const hasSensitiveProperties =\n Object.keys(event.sensitiveProperties).length > 0;\n\n if (!this.#isAnonymousEventsFeatureEnabled || hasSensitiveProperties) {\n this.#sendOrQueueTrackEvent(\n event.name,\n {\n ...event.properties,\n ...event.sensitiveProperties,\n ...(hasSensitiveProperties && { anonymous: true }),\n },\n context,\n );\n }\n }\n\n /**\n * Identify a user for analytics.\n *\n * @param traits - User traits/properties\n * @param context - Optional platform-specific context forwarded to the platform adapter.\n */\n identify(traits?: AnalyticsUserTraits, context?: AnalyticsContext): void {\n if (!analyticsControllerSelectors.selectEnabled(this.state)) {\n return;\n }\n\n // Delegate to platform adapter using the current analytics ID\n this.#sendOrQueueIdentifyEvent(this.state.analyticsId, traits, context);\n }\n\n /**\n * Track a page or screen view.\n *\n * @param name - The identifier/name of the page or screen being viewed (e.g., \"home\", \"settings\", \"wallet\")\n * @param properties - Optional properties associated with the view\n * @param context - Optional platform-specific context forwarded to the platform adapter.\n */\n trackView(\n name: string,\n properties?: AnalyticsEventProperties,\n context?: AnalyticsContext,\n ): void {\n if (!analyticsControllerSelectors.selectEnabled(this.state)) {\n return;\n }\n\n // Delegate to platform adapter\n this.#sendOrQueueViewEvent(name, properties, context);\n }\n\n /**\n * Opt in to analytics.\n */\n optIn(): void {\n this.update((state) => {\n state.optedIn = true;\n });\n }\n\n /**\n * Opt out of analytics.\n */\n optOut(): void {\n this.update((state) => {\n state.optedIn = false;\n });\n\n this.#clearQueuedEvents();\n }\n}\n"]}

@@ -26,6 +26,8 @@ "use strict";

* @param state - The analytics controller state to validate
* @param skipUUIDv4Check - When `true`, skips UUIDv4 format validation
* @throws Error if analyticsId is missing or not a valid UUIDv4
*/
function validateAnalyticsControllerState(state) {
if (!state.analyticsId || !isValidUUIDv4(state.analyticsId)) {
function validateAnalyticsControllerState(state, skipUUIDv4Check) {
if (!state.analyticsId ||
(skipUUIDv4Check !== true && !isValidUUIDv4(state.analyticsId))) {
throw new Error('Invalid analyticsId');

@@ -32,0 +34,0 @@ }

@@ -1,1 +0,1 @@

{"version":3,"file":"analyticsControllerStateValidator.cjs","sourceRoot":"","sources":["../src/analyticsControllerStateValidator.ts"],"names":[],"mappings":";;;AAEA;;;;;;GAMG;AACH,MAAM,aAAa,GACjB,yEAAyE,CAAC;AAE5E;;;;;GAKG;AACH,SAAgB,aAAa,CAAC,KAAa;IACzC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC;AAFD,sCAEC;AAED;;;;;GAKG;AACH,SAAgB,gCAAgC,CAC9C,KAA+B;IAE/B,IAAI,CAAC,KAAK,CAAC,WAAW,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE,CAAC;QAC5D,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;IACzC,CAAC;AACH,CAAC;AAND,4EAMC","sourcesContent":["import type { AnalyticsControllerState } from './AnalyticsController';\n\n/**\n * UUIDv4 format regex pattern.\n * Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\n * - x is any hexadecimal digit [0-9a-f]\n * - 4 indicates UUID version 4\n * - y is the variant indicator [89ab]\n */\nconst UUID_V4_REGEX =\n /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\n\n/**\n * Validates that a string is a valid UUIDv4 format.\n *\n * @param value - The string to validate\n * @returns True if the string matches UUIDv4 format\n */\nexport function isValidUUIDv4(value: string): boolean {\n return typeof value === 'string' && UUID_V4_REGEX.test(value);\n}\n\n/**\n * Validates that the analytics state has a valid UUIDv4 analyticsId.\n *\n * @param state - The analytics controller state to validate\n * @throws Error if analyticsId is missing or not a valid UUIDv4\n */\nexport function validateAnalyticsControllerState(\n state: AnalyticsControllerState,\n): void {\n if (!state.analyticsId || !isValidUUIDv4(state.analyticsId)) {\n throw new Error('Invalid analyticsId');\n }\n}\n"]}
{"version":3,"file":"analyticsControllerStateValidator.cjs","sourceRoot":"","sources":["../src/analyticsControllerStateValidator.ts"],"names":[],"mappings":";;;AAEA;;;;;;GAMG;AACH,MAAM,aAAa,GACjB,yEAAyE,CAAC;AAE5E;;;;;GAKG;AACH,SAAgB,aAAa,CAAC,KAAa;IACzC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC;AAFD,sCAEC;AAED;;;;;;GAMG;AACH,SAAgB,gCAAgC,CAC9C,KAA+B,EAC/B,eAAyB;IAEzB,IACE,CAAC,KAAK,CAAC,WAAW;QAClB,CAAC,eAAe,KAAK,IAAI,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,EAC/D,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;IACzC,CAAC;AACH,CAAC;AAVD,4EAUC","sourcesContent":["import type { AnalyticsControllerState } from './AnalyticsController';\n\n/**\n * UUIDv4 format regex pattern.\n * Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\n * - x is any hexadecimal digit [0-9a-f]\n * - 4 indicates UUID version 4\n * - y is the variant indicator [89ab]\n */\nconst UUID_V4_REGEX =\n /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\n\n/**\n * Validates that a string is a valid UUIDv4 format.\n *\n * @param value - The string to validate\n * @returns True if the string matches UUIDv4 format\n */\nexport function isValidUUIDv4(value: string): boolean {\n return typeof value === 'string' && UUID_V4_REGEX.test(value);\n}\n\n/**\n * Validates that the analytics state has a valid UUIDv4 analyticsId.\n *\n * @param state - The analytics controller state to validate\n * @param skipUUIDv4Check - When `true`, skips UUIDv4 format validation\n * @throws Error if analyticsId is missing or not a valid UUIDv4\n */\nexport function validateAnalyticsControllerState(\n state: AnalyticsControllerState,\n skipUUIDv4Check?: boolean,\n): void {\n if (\n !state.analyticsId ||\n (skipUUIDv4Check !== true && !isValidUUIDv4(state.analyticsId))\n ) {\n throw new Error('Invalid analyticsId');\n }\n}\n"]}

@@ -13,5 +13,6 @@ import type { AnalyticsControllerState } from "./AnalyticsController.cjs";

* @param state - The analytics controller state to validate
* @param skipUUIDv4Check - When `true`, skips UUIDv4 format validation
* @throws Error if analyticsId is missing or not a valid UUIDv4
*/
export declare function validateAnalyticsControllerState(state: AnalyticsControllerState): void;
export declare function validateAnalyticsControllerState(state: AnalyticsControllerState, skipUUIDv4Check?: boolean): void;
//# sourceMappingURL=analyticsControllerStateValidator.d.cts.map

@@ -1,1 +0,1 @@

{"version":3,"file":"analyticsControllerStateValidator.d.cts","sourceRoot":"","sources":["../src/analyticsControllerStateValidator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,wBAAwB,EAAE,kCAA8B;AAYtE;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEpD;AAED;;;;;GAKG;AACH,wBAAgB,gCAAgC,CAC9C,KAAK,EAAE,wBAAwB,GAC9B,IAAI,CAIN"}
{"version":3,"file":"analyticsControllerStateValidator.d.cts","sourceRoot":"","sources":["../src/analyticsControllerStateValidator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,wBAAwB,EAAE,kCAA8B;AAYtE;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEpD;AAED;;;;;;GAMG;AACH,wBAAgB,gCAAgC,CAC9C,KAAK,EAAE,wBAAwB,EAC/B,eAAe,CAAC,EAAE,OAAO,GACxB,IAAI,CAON"}

@@ -13,5 +13,6 @@ import type { AnalyticsControllerState } from "./AnalyticsController.mjs";

* @param state - The analytics controller state to validate
* @param skipUUIDv4Check - When `true`, skips UUIDv4 format validation
* @throws Error if analyticsId is missing or not a valid UUIDv4
*/
export declare function validateAnalyticsControllerState(state: AnalyticsControllerState): void;
export declare function validateAnalyticsControllerState(state: AnalyticsControllerState, skipUUIDv4Check?: boolean): void;
//# sourceMappingURL=analyticsControllerStateValidator.d.mts.map

@@ -1,1 +0,1 @@

{"version":3,"file":"analyticsControllerStateValidator.d.mts","sourceRoot":"","sources":["../src/analyticsControllerStateValidator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,wBAAwB,EAAE,kCAA8B;AAYtE;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEpD;AAED;;;;;GAKG;AACH,wBAAgB,gCAAgC,CAC9C,KAAK,EAAE,wBAAwB,GAC9B,IAAI,CAIN"}
{"version":3,"file":"analyticsControllerStateValidator.d.mts","sourceRoot":"","sources":["../src/analyticsControllerStateValidator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,wBAAwB,EAAE,kCAA8B;AAYtE;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEpD;AAED;;;;;;GAMG;AACH,wBAAgB,gCAAgC,CAC9C,KAAK,EAAE,wBAAwB,EAC/B,eAAe,CAAC,EAAE,OAAO,GACxB,IAAI,CAON"}

@@ -22,6 +22,8 @@ /**

* @param state - The analytics controller state to validate
* @param skipUUIDv4Check - When `true`, skips UUIDv4 format validation
* @throws Error if analyticsId is missing or not a valid UUIDv4
*/
export function validateAnalyticsControllerState(state) {
if (!state.analyticsId || !isValidUUIDv4(state.analyticsId)) {
export function validateAnalyticsControllerState(state, skipUUIDv4Check) {
if (!state.analyticsId ||
(skipUUIDv4Check !== true && !isValidUUIDv4(state.analyticsId))) {
throw new Error('Invalid analyticsId');

@@ -28,0 +30,0 @@ }

@@ -1,1 +0,1 @@

{"version":3,"file":"analyticsControllerStateValidator.mjs","sourceRoot":"","sources":["../src/analyticsControllerStateValidator.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,MAAM,aAAa,GACjB,yEAAyE,CAAC;AAE5E;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,KAAa;IACzC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,gCAAgC,CAC9C,KAA+B;IAE/B,IAAI,CAAC,KAAK,CAAC,WAAW,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE,CAAC;QAC5D,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;IACzC,CAAC;AACH,CAAC","sourcesContent":["import type { AnalyticsControllerState } from './AnalyticsController';\n\n/**\n * UUIDv4 format regex pattern.\n * Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\n * - x is any hexadecimal digit [0-9a-f]\n * - 4 indicates UUID version 4\n * - y is the variant indicator [89ab]\n */\nconst UUID_V4_REGEX =\n /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\n\n/**\n * Validates that a string is a valid UUIDv4 format.\n *\n * @param value - The string to validate\n * @returns True if the string matches UUIDv4 format\n */\nexport function isValidUUIDv4(value: string): boolean {\n return typeof value === 'string' && UUID_V4_REGEX.test(value);\n}\n\n/**\n * Validates that the analytics state has a valid UUIDv4 analyticsId.\n *\n * @param state - The analytics controller state to validate\n * @throws Error if analyticsId is missing or not a valid UUIDv4\n */\nexport function validateAnalyticsControllerState(\n state: AnalyticsControllerState,\n): void {\n if (!state.analyticsId || !isValidUUIDv4(state.analyticsId)) {\n throw new Error('Invalid analyticsId');\n }\n}\n"]}
{"version":3,"file":"analyticsControllerStateValidator.mjs","sourceRoot":"","sources":["../src/analyticsControllerStateValidator.ts"],"names":[],"mappings":"AAEA;;;;;;GAMG;AACH,MAAM,aAAa,GACjB,yEAAyE,CAAC;AAE5E;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,KAAa;IACzC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,gCAAgC,CAC9C,KAA+B,EAC/B,eAAyB;IAEzB,IACE,CAAC,KAAK,CAAC,WAAW;QAClB,CAAC,eAAe,KAAK,IAAI,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,EAC/D,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;IACzC,CAAC;AACH,CAAC","sourcesContent":["import type { AnalyticsControllerState } from './AnalyticsController';\n\n/**\n * UUIDv4 format regex pattern.\n * Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\n * - x is any hexadecimal digit [0-9a-f]\n * - 4 indicates UUID version 4\n * - y is the variant indicator [89ab]\n */\nconst UUID_V4_REGEX =\n /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\n\n/**\n * Validates that a string is a valid UUIDv4 format.\n *\n * @param value - The string to validate\n * @returns True if the string matches UUIDv4 format\n */\nexport function isValidUUIDv4(value: string): boolean {\n return typeof value === 'string' && UUID_V4_REGEX.test(value);\n}\n\n/**\n * Validates that the analytics state has a valid UUIDv4 analyticsId.\n *\n * @param state - The analytics controller state to validate\n * @param skipUUIDv4Check - When `true`, skips UUIDv4 format validation\n * @throws Error if analyticsId is missing or not a valid UUIDv4\n */\nexport function validateAnalyticsControllerState(\n state: AnalyticsControllerState,\n skipUUIDv4Check?: boolean,\n): void {\n if (\n !state.analyticsId ||\n (skipUUIDv4Check !== true && !isValidUUIDv4(state.analyticsId))\n ) {\n throw new Error('Invalid analyticsId');\n }\n}\n"]}

@@ -1,1 +0,1 @@

{"version":3,"file":"AnalyticsPlatformAdapter.types.cjs","sourceRoot":"","sources":["../src/AnalyticsPlatformAdapter.types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Json } from '@metamask/utils';\n\n/**\n * Analytics event properties\n */\nexport type AnalyticsEventProperties = Record<string, Json>;\n\n/**\n * User traits/properties for analytics identification\n */\nexport type AnalyticsUserTraits = Record<string, Json>;\n\n/**\n * Event properties structure with two distinct properties lists for regular and sensitive data.\n * Similar to ITrackingEvent from legacy analytics but decoupled for platform agnosticism.\n * Sensitivity is derived from the presence of sensitiveProperties (if sensitiveProperties has keys, the event is sensitive).\n */\nexport type AnalyticsTrackingEvent = {\n readonly name: string;\n properties: AnalyticsEventProperties;\n sensitiveProperties: AnalyticsEventProperties;\n /**\n * Legacy property handled by the mobile app.\n * This property is ignored by the analytics controller and will be removed from the type in the future.\n * The mobile app will use the future analytics privacy controller to handle this functionality.\n */\n saveDataRecording: boolean;\n readonly hasProperties: boolean;\n};\n\n/**\n * Platform adapter interface for analytics tracking\n * Implementations should handle platform-specific details (Segment SDK, etc.)\n */\nexport type AnalyticsPlatformAdapter = {\n /**\n * Track an analytics event.\n *\n * This is the same as trackEvent in the old analytics system\n *\n * @param eventName - The name of the event\n * @param properties - Event properties. If not provided, the event has no properties.\n * The privacy plugin should check for `isSensitive === true` to determine if an event contains sensitive data.\n */\n track(eventName: string, properties?: AnalyticsEventProperties): void;\n\n /**\n * Identify a user with traits.\n *\n * @param userId - The user identifier (e.g., metametrics ID)\n * @param traits - User traits/properties\n */\n identify(userId: string, traits?: AnalyticsUserTraits): void;\n\n /**\n * Track a UI unit (page or screen) view depending on the platform\n *\n * This method delegates to platform-specific Segment SDK methods:\n * - Web adapters should call `analytics.page(name, properties)`\n * - Mobile adapters should call `analytics.screen(name, properties)`\n *\n * @param name - The identifier/name of the page or screen being viewed (e.g., \"home\", \"settings\", \"wallet\")\n * @param properties - Optional properties associated with the view\n */\n view(name: string, properties?: AnalyticsEventProperties): void;\n\n /**\n * Lifecycle hook called after the AnalyticsController is fully initialized.\n *\n * This hook allows platform-specific adapters to perform setup that requires\n * access to the controller's state (e.g., analyticsId).\n *\n * The controller calls this method once after initialization, passing the\n * analyticsId from controller state. The analyticsId is guaranteed to be set\n * when this method is called - this is the definition of \"completed\" setup.\n *\n * @param analyticsId - The analytics ID from controller state. Always set (never empty).\n * @throws {AnalyticsPlatformAdapterSetupError} May throw errors during setup (e.g., configuration errors, network failures).\n * Errors thrown by this method are caught and logged by the controller, but do not prevent\n * controller initialization from completing successfully.\n *\n * @example\n * ```typescript\n * onSetupCompleted(analyticsId: string): void {\n * // Add platform-specific plugins that require analyticsId\n * client.add({\n * plugin: new PrivacyPlugin(analyticsId),\n * });\n * }\n * ```\n */\n onSetupCompleted(analyticsId: string): void;\n};\n"]}
{"version":3,"file":"AnalyticsPlatformAdapter.types.cjs","sourceRoot":"","sources":["../src/AnalyticsPlatformAdapter.types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Json } from '@metamask/utils';\n\n/**\n * Analytics event properties\n */\nexport type AnalyticsEventProperties = Record<string, Json>;\n\n/**\n * User traits/properties for analytics identification\n */\nexport type AnalyticsUserTraits = Record<string, Json>;\n\n/**\n * Callback invoked by the platform adapter after an analytics payload is\n * delivered or fails.\n */\nexport type AnalyticsInvocationCallback = (error?: unknown) => void;\n\n/**\n * Internal delivery metadata used by AnalyticsController when event queue\n * persistence is enabled.\n */\nexport type AnalyticsDeliveryOptions = {\n /**\n * Stable identifier for the analytics payload.\n */\n messageId?: string;\n\n /**\n * Original timestamp for the analytics payload.\n */\n timestamp?: Date;\n\n /**\n * Callback for delivery acknowledgement.\n */\n callback?: AnalyticsInvocationCallback;\n};\n\n/**\n * Event properties structure with two distinct properties lists for regular and sensitive data.\n * Similar to ITrackingEvent from legacy analytics but decoupled for platform agnosticism.\n * Sensitivity is derived from the presence of sensitiveProperties (if sensitiveProperties has keys, the event is sensitive).\n */\nexport type AnalyticsTrackingEvent = {\n readonly name: string;\n properties: AnalyticsEventProperties;\n sensitiveProperties: AnalyticsEventProperties;\n /**\n * Legacy property handled by the mobile app.\n * This property is ignored by the analytics controller and will be removed from the type in the future.\n * The mobile app will use the future analytics privacy controller to handle this functionality.\n */\n saveDataRecording: boolean;\n readonly hasProperties: boolean;\n};\n\n/**\n * Optional analytics context payload (for example Segment-style context).\n */\nexport type AnalyticsContext = Record<string, Json>;\n\n/**\n * Platform adapter interface for analytics tracking\n * Implementations should handle platform-specific details (Segment SDK, etc.)\n */\nexport type AnalyticsPlatformAdapter = {\n /**\n * When `true`, the controller accepts any non-empty `analyticsId` string\n * instead of requiring UUIDv4 format. Defaults to validation against UUIDv4 when omitted or `false`.\n */\n skipUUIDv4Check?: boolean;\n\n /**\n * Track an analytics event.\n *\n * This is the same as trackEvent in the old analytics system\n *\n * @param eventName - The name of the event\n * @param properties - Event properties. If not provided, the event has no properties.\n * The privacy plugin should check for `isSensitive === true` to determine if an event contains sensitive data.\n * @param context - Optional platform-specific context attached to the invocation.\n * @param options - Optional delivery metadata for platform adapters.\n */\n track(\n eventName: string,\n properties?: AnalyticsEventProperties,\n context?: AnalyticsContext,\n options?: AnalyticsDeliveryOptions,\n ): void;\n\n /**\n * Identify a user with traits.\n *\n * @param userId - The user identifier (e.g., metametrics ID)\n * @param traits - User traits/properties\n * @param context - Optional platform-specific context attached to the invocation.\n * @param options - Optional delivery metadata for platform adapters.\n */\n identify(\n userId: string,\n traits?: AnalyticsUserTraits,\n context?: AnalyticsContext,\n options?: AnalyticsDeliveryOptions,\n ): void;\n\n /**\n * Track a UI unit (page or screen) view depending on the platform\n *\n * This method delegates to platform-specific Segment SDK methods:\n * - Web adapters should call `analytics.page(name, properties)`\n * - Mobile adapters should call `analytics.screen(name, properties)`\n *\n * @param name - The identifier/name of the page or screen being viewed (e.g., \"home\", \"settings\", \"wallet\")\n * @param properties - Optional properties associated with the view\n * @param context - Optional platform-specific context attached to the invocation.\n * @param options - Optional delivery metadata for platform adapters.\n */\n view(\n name: string,\n properties?: AnalyticsEventProperties,\n context?: AnalyticsContext,\n options?: AnalyticsDeliveryOptions,\n ): void;\n\n /**\n * Lifecycle hook called after the AnalyticsController is fully initialized.\n *\n * This hook allows platform-specific adapters to perform setup that requires\n * access to the controller's state (e.g., analyticsId).\n *\n * The controller calls this method once after initialization, passing the\n * analyticsId from controller state. The analyticsId is guaranteed to be set\n * when this method is called - this is the definition of \"completed\" setup.\n *\n * @param analyticsId - The analytics ID from controller state. Always set (never empty).\n * @throws {AnalyticsPlatformAdapterSetupError} May throw errors during setup (e.g., configuration errors, network failures).\n * Errors thrown by this method are caught and logged by the controller, but do not prevent\n * controller initialization from completing successfully.\n *\n * @example\n * ```typescript\n * onSetupCompleted(analyticsId: string): void {\n * // Add platform-specific plugins that require analyticsId\n * client.add({\n * plugin: new PrivacyPlugin(analyticsId),\n * });\n * }\n * ```\n */\n onSetupCompleted(analyticsId: string): void;\n};\n"]}

@@ -11,2 +11,25 @@ import type { Json } from "@metamask/utils";

/**
* Callback invoked by the platform adapter after an analytics payload is
* delivered or fails.
*/
export type AnalyticsInvocationCallback = (error?: unknown) => void;
/**
* Internal delivery metadata used by AnalyticsController when event queue
* persistence is enabled.
*/
export type AnalyticsDeliveryOptions = {
/**
* Stable identifier for the analytics payload.
*/
messageId?: string;
/**
* Original timestamp for the analytics payload.
*/
timestamp?: Date;
/**
* Callback for delivery acknowledgement.
*/
callback?: AnalyticsInvocationCallback;
};
/**
* Event properties structure with two distinct properties lists for regular and sensitive data.

@@ -29,2 +52,6 @@ * Similar to ITrackingEvent from legacy analytics but decoupled for platform agnosticism.

/**
* Optional analytics context payload (for example Segment-style context).
*/
export type AnalyticsContext = Record<string, Json>;
/**
* Platform adapter interface for analytics tracking

@@ -35,2 +62,7 @@ * Implementations should handle platform-specific details (Segment SDK, etc.)

/**
* When `true`, the controller accepts any non-empty `analyticsId` string
* instead of requiring UUIDv4 format. Defaults to validation against UUIDv4 when omitted or `false`.
*/
skipUUIDv4Check?: boolean;
/**
* Track an analytics event.

@@ -43,4 +75,6 @@ *

* The privacy plugin should check for `isSensitive === true` to determine if an event contains sensitive data.
* @param context - Optional platform-specific context attached to the invocation.
* @param options - Optional delivery metadata for platform adapters.
*/
track(eventName: string, properties?: AnalyticsEventProperties): void;
track(eventName: string, properties?: AnalyticsEventProperties, context?: AnalyticsContext, options?: AnalyticsDeliveryOptions): void;
/**

@@ -51,4 +85,6 @@ * Identify a user with traits.

* @param traits - User traits/properties
* @param context - Optional platform-specific context attached to the invocation.
* @param options - Optional delivery metadata for platform adapters.
*/
identify(userId: string, traits?: AnalyticsUserTraits): void;
identify(userId: string, traits?: AnalyticsUserTraits, context?: AnalyticsContext, options?: AnalyticsDeliveryOptions): void;
/**

@@ -63,4 +99,6 @@ * Track a UI unit (page or screen) view depending on the platform

* @param properties - Optional properties associated with the view
* @param context - Optional platform-specific context attached to the invocation.
* @param options - Optional delivery metadata for platform adapters.
*/
view(name: string, properties?: AnalyticsEventProperties): void;
view(name: string, properties?: AnalyticsEventProperties, context?: AnalyticsContext, options?: AnalyticsDeliveryOptions): void;
/**

@@ -67,0 +105,0 @@ * Lifecycle hook called after the AnalyticsController is fully initialized.

@@ -1,1 +0,1 @@

{"version":3,"file":"AnalyticsPlatformAdapter.types.d.cts","sourceRoot":"","sources":["../src/AnalyticsPlatformAdapter.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAE5C;;GAEG;AACH,MAAM,MAAM,wBAAwB,GAAG,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AAE5D;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AAEvD;;;;GAIG;AACH,MAAM,MAAM,sBAAsB,GAAG;IACnC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,UAAU,EAAE,wBAAwB,CAAC;IACrC,mBAAmB,EAAE,wBAAwB,CAAC;IAC9C;;;;OAIG;IACH,iBAAiB,EAAE,OAAO,CAAC;IAC3B,QAAQ,CAAC,aAAa,EAAE,OAAO,CAAC;CACjC,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,wBAAwB,GAAG;IACrC;;;;;;;;OAQG;IACH,KAAK,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,wBAAwB,GAAG,IAAI,CAAC;IAEtE;;;;;OAKG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,mBAAmB,GAAG,IAAI,CAAC;IAE7D;;;;;;;;;OASG;IACH,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,wBAAwB,GAAG,IAAI,CAAC;IAEhE;;;;;;;;;;;;;;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EAAE,wBAAwB,EACrC,OAAO,CAAC,EAAE,gBAAgB,EAC1B,OAAO,CAAC,EAAE,wBAAwB,GACjC,IAAI,CAAC;IAER;;;;;;;OAOG;IACH,QAAQ,CACN,MAAM,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,mBAAmB,EAC5B,OAAO,CAAC,EAAE,gBAAgB,EAC1B,OAAO,CAAC,EAAE,wBAAwB,GACjC,IAAI,CAAC;IAER;;;;;;;;;;;OAWG;IACH,IAAI,CACF,IAAI,EAAE,MAAM,EACZ,UAAU,CAAC,EAAE,wBAAwB,EACrC,OAAO,CAAC,EAAE,gBAAgB,EAC1B,OAAO,CAAC,EAAE,wBAAwB,GACjC,IAAI,CAAC;IAER;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACH,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7C,CAAC"}

@@ -11,2 +11,25 @@ import type { Json } from "@metamask/utils";

/**
* Callback invoked by the platform adapter after an analytics payload is
* delivered or fails.
*/
export type AnalyticsInvocationCallback = (error?: unknown) => void;
/**
* Internal delivery metadata used by AnalyticsController when event queue
* persistence is enabled.
*/
export type AnalyticsDeliveryOptions = {
/**
* Stable identifier for the analytics payload.
*/
messageId?: string;
/**
* Original timestamp for the analytics payload.
*/
timestamp?: Date;
/**
* Callback for delivery acknowledgement.
*/
callback?: AnalyticsInvocationCallback;
};
/**
* Event properties structure with two distinct properties lists for regular and sensitive data.

@@ -29,2 +52,6 @@ * Similar to ITrackingEvent from legacy analytics but decoupled for platform agnosticism.

/**
* Optional analytics context payload (for example Segment-style context).
*/
export type AnalyticsContext = Record<string, Json>;
/**
* Platform adapter interface for analytics tracking

@@ -35,2 +62,7 @@ * Implementations should handle platform-specific details (Segment SDK, etc.)

/**
* When `true`, the controller accepts any non-empty `analyticsId` string
* instead of requiring UUIDv4 format. Defaults to validation against UUIDv4 when omitted or `false`.
*/
skipUUIDv4Check?: boolean;
/**
* Track an analytics event.

@@ -43,4 +75,6 @@ *

* The privacy plugin should check for `isSensitive === true` to determine if an event contains sensitive data.
* @param context - Optional platform-specific context attached to the invocation.
* @param options - Optional delivery metadata for platform adapters.
*/
track(eventName: string, properties?: AnalyticsEventProperties): void;
track(eventName: string, properties?: AnalyticsEventProperties, context?: AnalyticsContext, options?: AnalyticsDeliveryOptions): void;
/**

@@ -51,4 +85,6 @@ * Identify a user with traits.

* @param traits - User traits/properties
* @param context - Optional platform-specific context attached to the invocation.
* @param options - Optional delivery metadata for platform adapters.
*/
identify(userId: string, traits?: AnalyticsUserTraits): void;
identify(userId: string, traits?: AnalyticsUserTraits, context?: AnalyticsContext, options?: AnalyticsDeliveryOptions): void;
/**

@@ -63,4 +99,6 @@ * Track a UI unit (page or screen) view depending on the platform

* @param properties - Optional properties associated with the view
* @param context - Optional platform-specific context attached to the invocation.
* @param options - Optional delivery metadata for platform adapters.
*/
view(name: string, properties?: AnalyticsEventProperties): void;
view(name: string, properties?: AnalyticsEventProperties, context?: AnalyticsContext, options?: AnalyticsDeliveryOptions): void;
/**

@@ -67,0 +105,0 @@ * Lifecycle hook called after the AnalyticsController is fully initialized.

@@ -1,1 +0,1 @@

{"version":3,"file":"AnalyticsPlatformAdapter.types.d.mts","sourceRoot":"","sources":["../src/AnalyticsPlatformAdapter.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,wBAAwB;AAE5C;;GAEG;AACH,MAAM,MAAM,wBAAwB,GAAG,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AAE5D;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AAEvD;;;;GAIG;AACH,MAAM,MAAM,sBAAsB,GAAG;IACnC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,UAAU,EAAE,wBAAwB,CAAC;IACrC,mBAAmB,EAAE,wBAAwB,CAAC;IAC9C;;;;OAIG;IACH,iBAAiB,EAA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C,IAAI,EAAE,MAAM,CAAC;IACtB,UAAU,EAAE,wBAAwB,CAAC;IACrC,mBAAmB,EAAE,wBAAwB,CAAC;IAC9C;;;;OAIG;IACH,iBAAiB,EAAE,OAAO,CAAC;IAC3B,QAAQ,CAAC,aAAa,EAAE,OAAO,CAAC;CACjC,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AAEpD;;;GAGG;AACH,MAAM,MAAM,wBAAwB,GAAG;IACrC;;;OAGG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAE1B;;;;;;;;;;OAUG;IACH,KAAK,CACH,SAAS,EAAE,MAAM,EACjB,UAAU,CAAC,EAAE,wBAAwB,EACrC,OAAO,CAAC,EAAE,gBAAgB,EAC1B,OAAO,CAAC,EAAE,wBAAwB,GACjC,IAAI,CAAC;IAER;;;;;;;OAOG;IACH,QAAQ,CACN,MAAM,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,mBAAmB,EAC5B,OAAO,CAAC,EAAE,gBAAgB,EAC1B,OAAO,CAAC,EAAE,wBAAwB,GACjC,IAAI,CAAC;IAER;;;;;;;;;;;OAWG;IACH,IAAI,CACF,IAAI,EAAE,MAAM,EACZ,UAAU,CAAC,EAAE,wBAAwB,EACrC,OAAO,CAAC,EAAE,gBAAgB,EAC1B,OAAO,CAAC,EAAE,wBAAwB,GACjC,IAAI,CAAC;IAER;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACH,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7C,CAAC"}

@@ -1,1 +0,1 @@

{"version":3,"file":"AnalyticsPlatformAdapter.types.mjs","sourceRoot":"","sources":["../src/AnalyticsPlatformAdapter.types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Json } from '@metamask/utils';\n\n/**\n * Analytics event properties\n */\nexport type AnalyticsEventProperties = Record<string, Json>;\n\n/**\n * User traits/properties for analytics identification\n */\nexport type AnalyticsUserTraits = Record<string, Json>;\n\n/**\n * Event properties structure with two distinct properties lists for regular and sensitive data.\n * Similar to ITrackingEvent from legacy analytics but decoupled for platform agnosticism.\n * Sensitivity is derived from the presence of sensitiveProperties (if sensitiveProperties has keys, the event is sensitive).\n */\nexport type AnalyticsTrackingEvent = {\n readonly name: string;\n properties: AnalyticsEventProperties;\n sensitiveProperties: AnalyticsEventProperties;\n /**\n * Legacy property handled by the mobile app.\n * This property is ignored by the analytics controller and will be removed from the type in the future.\n * The mobile app will use the future analytics privacy controller to handle this functionality.\n */\n saveDataRecording: boolean;\n readonly hasProperties: boolean;\n};\n\n/**\n * Platform adapter interface for analytics tracking\n * Implementations should handle platform-specific details (Segment SDK, etc.)\n */\nexport type AnalyticsPlatformAdapter = {\n /**\n * Track an analytics event.\n *\n * This is the same as trackEvent in the old analytics system\n *\n * @param eventName - The name of the event\n * @param properties - Event properties. If not provided, the event has no properties.\n * The privacy plugin should check for `isSensitive === true` to determine if an event contains sensitive data.\n */\n track(eventName: string, properties?: AnalyticsEventProperties): void;\n\n /**\n * Identify a user with traits.\n *\n * @param userId - The user identifier (e.g., metametrics ID)\n * @param traits - User traits/properties\n */\n identify(userId: string, traits?: AnalyticsUserTraits): void;\n\n /**\n * Track a UI unit (page or screen) view depending on the platform\n *\n * This method delegates to platform-specific Segment SDK methods:\n * - Web adapters should call `analytics.page(name, properties)`\n * - Mobile adapters should call `analytics.screen(name, properties)`\n *\n * @param name - The identifier/name of the page or screen being viewed (e.g., \"home\", \"settings\", \"wallet\")\n * @param properties - Optional properties associated with the view\n */\n view(name: string, properties?: AnalyticsEventProperties): void;\n\n /**\n * Lifecycle hook called after the AnalyticsController is fully initialized.\n *\n * This hook allows platform-specific adapters to perform setup that requires\n * access to the controller's state (e.g., analyticsId).\n *\n * The controller calls this method once after initialization, passing the\n * analyticsId from controller state. The analyticsId is guaranteed to be set\n * when this method is called - this is the definition of \"completed\" setup.\n *\n * @param analyticsId - The analytics ID from controller state. Always set (never empty).\n * @throws {AnalyticsPlatformAdapterSetupError} May throw errors during setup (e.g., configuration errors, network failures).\n * Errors thrown by this method are caught and logged by the controller, but do not prevent\n * controller initialization from completing successfully.\n *\n * @example\n * ```typescript\n * onSetupCompleted(analyticsId: string): void {\n * // Add platform-specific plugins that require analyticsId\n * client.add({\n * plugin: new PrivacyPlugin(analyticsId),\n * });\n * }\n * ```\n */\n onSetupCompleted(analyticsId: string): void;\n};\n"]}
{"version":3,"file":"AnalyticsPlatformAdapter.types.mjs","sourceRoot":"","sources":["../src/AnalyticsPlatformAdapter.types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Json } from '@metamask/utils';\n\n/**\n * Analytics event properties\n */\nexport type AnalyticsEventProperties = Record<string, Json>;\n\n/**\n * User traits/properties for analytics identification\n */\nexport type AnalyticsUserTraits = Record<string, Json>;\n\n/**\n * Callback invoked by the platform adapter after an analytics payload is\n * delivered or fails.\n */\nexport type AnalyticsInvocationCallback = (error?: unknown) => void;\n\n/**\n * Internal delivery metadata used by AnalyticsController when event queue\n * persistence is enabled.\n */\nexport type AnalyticsDeliveryOptions = {\n /**\n * Stable identifier for the analytics payload.\n */\n messageId?: string;\n\n /**\n * Original timestamp for the analytics payload.\n */\n timestamp?: Date;\n\n /**\n * Callback for delivery acknowledgement.\n */\n callback?: AnalyticsInvocationCallback;\n};\n\n/**\n * Event properties structure with two distinct properties lists for regular and sensitive data.\n * Similar to ITrackingEvent from legacy analytics but decoupled for platform agnosticism.\n * Sensitivity is derived from the presence of sensitiveProperties (if sensitiveProperties has keys, the event is sensitive).\n */\nexport type AnalyticsTrackingEvent = {\n readonly name: string;\n properties: AnalyticsEventProperties;\n sensitiveProperties: AnalyticsEventProperties;\n /**\n * Legacy property handled by the mobile app.\n * This property is ignored by the analytics controller and will be removed from the type in the future.\n * The mobile app will use the future analytics privacy controller to handle this functionality.\n */\n saveDataRecording: boolean;\n readonly hasProperties: boolean;\n};\n\n/**\n * Optional analytics context payload (for example Segment-style context).\n */\nexport type AnalyticsContext = Record<string, Json>;\n\n/**\n * Platform adapter interface for analytics tracking\n * Implementations should handle platform-specific details (Segment SDK, etc.)\n */\nexport type AnalyticsPlatformAdapter = {\n /**\n * When `true`, the controller accepts any non-empty `analyticsId` string\n * instead of requiring UUIDv4 format. Defaults to validation against UUIDv4 when omitted or `false`.\n */\n skipUUIDv4Check?: boolean;\n\n /**\n * Track an analytics event.\n *\n * This is the same as trackEvent in the old analytics system\n *\n * @param eventName - The name of the event\n * @param properties - Event properties. If not provided, the event has no properties.\n * The privacy plugin should check for `isSensitive === true` to determine if an event contains sensitive data.\n * @param context - Optional platform-specific context attached to the invocation.\n * @param options - Optional delivery metadata for platform adapters.\n */\n track(\n eventName: string,\n properties?: AnalyticsEventProperties,\n context?: AnalyticsContext,\n options?: AnalyticsDeliveryOptions,\n ): void;\n\n /**\n * Identify a user with traits.\n *\n * @param userId - The user identifier (e.g., metametrics ID)\n * @param traits - User traits/properties\n * @param context - Optional platform-specific context attached to the invocation.\n * @param options - Optional delivery metadata for platform adapters.\n */\n identify(\n userId: string,\n traits?: AnalyticsUserTraits,\n context?: AnalyticsContext,\n options?: AnalyticsDeliveryOptions,\n ): void;\n\n /**\n * Track a UI unit (page or screen) view depending on the platform\n *\n * This method delegates to platform-specific Segment SDK methods:\n * - Web adapters should call `analytics.page(name, properties)`\n * - Mobile adapters should call `analytics.screen(name, properties)`\n *\n * @param name - The identifier/name of the page or screen being viewed (e.g., \"home\", \"settings\", \"wallet\")\n * @param properties - Optional properties associated with the view\n * @param context - Optional platform-specific context attached to the invocation.\n * @param options - Optional delivery metadata for platform adapters.\n */\n view(\n name: string,\n properties?: AnalyticsEventProperties,\n context?: AnalyticsContext,\n options?: AnalyticsDeliveryOptions,\n ): void;\n\n /**\n * Lifecycle hook called after the AnalyticsController is fully initialized.\n *\n * This hook allows platform-specific adapters to perform setup that requires\n * access to the controller's state (e.g., analyticsId).\n *\n * The controller calls this method once after initialization, passing the\n * analyticsId from controller state. The analyticsId is guaranteed to be set\n * when this method is called - this is the definition of \"completed\" setup.\n *\n * @param analyticsId - The analytics ID from controller state. Always set (never empty).\n * @throws {AnalyticsPlatformAdapterSetupError} May throw errors during setup (e.g., configuration errors, network failures).\n * Errors thrown by this method are caught and logged by the controller, but do not prevent\n * controller initialization from completing successfully.\n *\n * @example\n * ```typescript\n * onSetupCompleted(analyticsId: string): void {\n * // Add platform-specific plugins that require analyticsId\n * client.add({\n * plugin: new PrivacyPlugin(analyticsId),\n * });\n * }\n * ```\n */\n onSetupCompleted(analyticsId: string): void;\n};\n"]}

@@ -1,1 +0,1 @@

{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,8CAA8C;AAC9C,iEAG+B;AAF7B,0HAAA,mBAAmB,OAAA;AACnB,yIAAA,kCAAkC,OAAA;AAIpC,gBAAgB;AAChB,+FAA0F;AAAjF,wJAAA,kCAAkC,OAAA;AAa3C,mBAAmB;AACnB,6CAA2D;AAAlD,yHAAA,4BAA4B,OAAA","sourcesContent":["// Export controller class and state utilities\nexport {\n AnalyticsController,\n getDefaultAnalyticsControllerState,\n} from './AnalyticsController';\nexport type { AnalyticsControllerOptions } from './AnalyticsController';\n\n// Export errors\nexport { AnalyticsPlatformAdapterSetupError } from './AnalyticsPlatformAdapterSetupError';\n\n// Export types\nexport type {\n AnalyticsEventProperties,\n AnalyticsUserTraits,\n AnalyticsPlatformAdapter,\n AnalyticsTrackingEvent,\n} from './AnalyticsPlatformAdapter.types';\n\n// Export state types\nexport type { AnalyticsControllerState } from './AnalyticsController';\n\n// Export selectors\nexport { analyticsControllerSelectors } from './selectors';\n\n// Export messenger types\nexport type { AnalyticsControllerMessenger } from './AnalyticsController';\n\n// Export action and event types\nexport type {\n AnalyticsControllerActions,\n AnalyticsControllerEvents,\n AnalyticsControllerGetStateAction,\n AnalyticsControllerStateChangeEvent,\n} from './AnalyticsController';\nexport type {\n AnalyticsControllerTrackEventAction,\n AnalyticsControllerIdentifyAction,\n AnalyticsControllerTrackViewAction,\n AnalyticsControllerOptInAction,\n AnalyticsControllerOptOutAction,\n AnalyticsControllerMethodActions,\n} from './AnalyticsController-method-action-types';\n"]}
{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,8CAA8C;AAC9C,iEAG+B;AAF7B,0HAAA,mBAAmB,OAAA;AACnB,yIAAA,kCAAkC,OAAA;AAIpC,gBAAgB;AAChB,+FAA0F;AAAjF,wJAAA,kCAAkC,OAAA;AAwB3C,mBAAmB;AACnB,6CAA2D;AAAlD,yHAAA,4BAA4B,OAAA","sourcesContent":["// Export controller class and state utilities\nexport {\n AnalyticsController,\n getDefaultAnalyticsControllerState,\n} from './AnalyticsController';\nexport type { AnalyticsControllerOptions } from './AnalyticsController';\n\n// Export errors\nexport { AnalyticsPlatformAdapterSetupError } from './AnalyticsPlatformAdapterSetupError';\n\n// Export types\nexport type {\n AnalyticsContext,\n AnalyticsEventProperties,\n AnalyticsDeliveryOptions,\n AnalyticsInvocationCallback,\n AnalyticsUserTraits,\n AnalyticsPlatformAdapter,\n AnalyticsTrackingEvent,\n} from './AnalyticsPlatformAdapter.types';\n\n// Export state types\nexport type {\n AnalyticsControllerState,\n AnalyticsEventQueue,\n AnalyticsQueuedEvent,\n AnalyticsQueuedEventType,\n AnalyticsQueuedTrackEvent,\n AnalyticsQueuedIdentifyEvent,\n AnalyticsQueuedViewEvent,\n} from './AnalyticsController';\n\n// Export selectors\nexport { analyticsControllerSelectors } from './selectors';\n\n// Export messenger types\nexport type { AnalyticsControllerMessenger } from './AnalyticsController';\n\n// Export action and event types\nexport type {\n AnalyticsControllerActions,\n AnalyticsControllerEvents,\n AnalyticsControllerGetStateAction,\n AnalyticsControllerStateChangeEvent,\n} from './AnalyticsController';\nexport type {\n AnalyticsControllerTrackEventAction,\n AnalyticsControllerIdentifyAction,\n AnalyticsControllerTrackViewAction,\n AnalyticsControllerOptInAction,\n AnalyticsControllerOptOutAction,\n AnalyticsControllerMethodActions,\n} from './AnalyticsController-method-action-types';\n"]}
export { AnalyticsController, getDefaultAnalyticsControllerState, } from "./AnalyticsController.cjs";
export type { AnalyticsControllerOptions } from "./AnalyticsController.cjs";
export { AnalyticsPlatformAdapterSetupError } from "./AnalyticsPlatformAdapterSetupError.cjs";
export type { AnalyticsEventProperties, AnalyticsUserTraits, AnalyticsPlatformAdapter, AnalyticsTrackingEvent, } from "./AnalyticsPlatformAdapter.types.cjs";
export type { AnalyticsControllerState } from "./AnalyticsController.cjs";
export type { AnalyticsContext, AnalyticsEventProperties, AnalyticsDeliveryOptions, AnalyticsInvocationCallback, AnalyticsUserTraits, AnalyticsPlatformAdapter, AnalyticsTrackingEvent, } from "./AnalyticsPlatformAdapter.types.cjs";
export type { AnalyticsControllerState, AnalyticsEventQueue, AnalyticsQueuedEvent, AnalyticsQueuedEventType, AnalyticsQueuedTrackEvent, AnalyticsQueuedIdentifyEvent, AnalyticsQueuedViewEvent, } from "./AnalyticsController.cjs";
export { analyticsControllerSelectors } from "./selectors.cjs";

@@ -7,0 +7,0 @@ export type { AnalyticsControllerMessenger } from "./AnalyticsController.cjs";

@@ -1,1 +0,1 @@

{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,mBAAmB,EACnB,kCAAkC,GACnC,kCAA8B;AAC/B,YAAY,EAAE,0BAA0B,EAAE,kCAA8B;AAGxE,OAAO,EAAE,kCAAkC,EAAE,iDAA6C;AAG1F,YAAY,EACV,wBAAwB,EACxB,mBAAmB,EACnB,wBAAwB,EACxB,sBAAsB,GACvB,6CAAyC;AAG1C,YAAY,EAAE,wBAAwB,EAAE,kCAA8B;AAGtE,OAAO,EAAE,4BAA4B,EAAE,wBAAoB;AAG3D,YAAY,EAAE,4BAA4B,EAAE,kCAA8B;AAG1E,YAAY,EACV,0BAA0B,EAC1B,yBAAyB,EACzB,iCAAiC,EACjC,mCAAmC,GACpC,kCAA8B;AAC/B,YAAY,EACV,mCAAmC,EACnC,iCAAiC,EACjC,kCAAkC,EAClC,8BAA8B,EAC9B,+BAA+B,EAC/B,gCAAgC,GACjC,sDAAkD"}
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,mBAAmB,EACnB,kCAAkC,GACnC,kCAA8B;AAC/B,YAAY,EAAE,0BAA0B,EAAE,kCAA8B;AAGxE,OAAO,EAAE,kCAAkC,EAAE,iDAA6C;AAG1F,YAAY,EACV,gBAAgB,EAChB,wBAAwB,EACxB,wBAAwB,EACxB,2BAA2B,EAC3B,mBAAmB,EACnB,wBAAwB,EACxB,sBAAsB,GACvB,6CAAyC;AAG1C,YAAY,EACV,wBAAwB,EACxB,mBAAmB,EACnB,oBAAoB,EACpB,wBAAwB,EACxB,yBAAyB,EACzB,4BAA4B,EAC5B,wBAAwB,GACzB,kCAA8B;AAG/B,OAAO,EAAE,4BAA4B,EAAE,wBAAoB;AAG3D,YAAY,EAAE,4BAA4B,EAAE,kCAA8B;AAG1E,YAAY,EACV,0BAA0B,EAC1B,yBAAyB,EACzB,iCAAiC,EACjC,mCAAmC,GACpC,kCAA8B;AAC/B,YAAY,EACV,mCAAmC,EACnC,iCAAiC,EACjC,kCAAkC,EAClC,8BAA8B,EAC9B,+BAA+B,EAC/B,gCAAgC,GACjC,sDAAkD"}
export { AnalyticsController, getDefaultAnalyticsControllerState, } from "./AnalyticsController.mjs";
export type { AnalyticsControllerOptions } from "./AnalyticsController.mjs";
export { AnalyticsPlatformAdapterSetupError } from "./AnalyticsPlatformAdapterSetupError.mjs";
export type { AnalyticsEventProperties, AnalyticsUserTraits, AnalyticsPlatformAdapter, AnalyticsTrackingEvent, } from "./AnalyticsPlatformAdapter.types.mjs";
export type { AnalyticsControllerState } from "./AnalyticsController.mjs";
export type { AnalyticsContext, AnalyticsEventProperties, AnalyticsDeliveryOptions, AnalyticsInvocationCallback, AnalyticsUserTraits, AnalyticsPlatformAdapter, AnalyticsTrackingEvent, } from "./AnalyticsPlatformAdapter.types.mjs";
export type { AnalyticsControllerState, AnalyticsEventQueue, AnalyticsQueuedEvent, AnalyticsQueuedEventType, AnalyticsQueuedTrackEvent, AnalyticsQueuedIdentifyEvent, AnalyticsQueuedViewEvent, } from "./AnalyticsController.mjs";
export { analyticsControllerSelectors } from "./selectors.mjs";

@@ -7,0 +7,0 @@ export type { AnalyticsControllerMessenger } from "./AnalyticsController.mjs";

@@ -1,1 +0,1 @@

{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,mBAAmB,EACnB,kCAAkC,GACnC,kCAA8B;AAC/B,YAAY,EAAE,0BAA0B,EAAE,kCAA8B;AAGxE,OAAO,EAAE,kCAAkC,EAAE,iDAA6C;AAG1F,YAAY,EACV,wBAAwB,EACxB,mBAAmB,EACnB,wBAAwB,EACxB,sBAAsB,GACvB,6CAAyC;AAG1C,YAAY,EAAE,wBAAwB,EAAE,kCAA8B;AAGtE,OAAO,EAAE,4BAA4B,EAAE,wBAAoB;AAG3D,YAAY,EAAE,4BAA4B,EAAE,kCAA8B;AAG1E,YAAY,EACV,0BAA0B,EAC1B,yBAAyB,EACzB,iCAAiC,EACjC,mCAAmC,GACpC,kCAA8B;AAC/B,YAAY,EACV,mCAAmC,EACnC,iCAAiC,EACjC,kCAAkC,EAClC,8BAA8B,EAC9B,+BAA+B,EAC/B,gCAAgC,GACjC,sDAAkD"}
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,mBAAmB,EACnB,kCAAkC,GACnC,kCAA8B;AAC/B,YAAY,EAAE,0BAA0B,EAAE,kCAA8B;AAGxE,OAAO,EAAE,kCAAkC,EAAE,iDAA6C;AAG1F,YAAY,EACV,gBAAgB,EAChB,wBAAwB,EACxB,wBAAwB,EACxB,2BAA2B,EAC3B,mBAAmB,EACnB,wBAAwB,EACxB,sBAAsB,GACvB,6CAAyC;AAG1C,YAAY,EACV,wBAAwB,EACxB,mBAAmB,EACnB,oBAAoB,EACpB,wBAAwB,EACxB,yBAAyB,EACzB,4BAA4B,EAC5B,wBAAwB,GACzB,kCAA8B;AAG/B,OAAO,EAAE,4BAA4B,EAAE,wBAAoB;AAG3D,YAAY,EAAE,4BAA4B,EAAE,kCAA8B;AAG1E,YAAY,EACV,0BAA0B,EAC1B,yBAAyB,EACzB,iCAAiC,EACjC,mCAAmC,GACpC,kCAA8B;AAC/B,YAAY,EACV,mCAAmC,EACnC,iCAAiC,EACjC,kCAAkC,EAClC,8BAA8B,EAC9B,+BAA+B,EAC/B,gCAAgC,GACjC,sDAAkD"}

@@ -1,1 +0,1 @@

{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,8CAA8C;AAC9C,OAAO,EACL,mBAAmB,EACnB,kCAAkC,EACnC,kCAA8B;AAG/B,gBAAgB;AAChB,OAAO,EAAE,kCAAkC,EAAE,iDAA6C;AAa1F,mBAAmB;AACnB,OAAO,EAAE,4BAA4B,EAAE,wBAAoB","sourcesContent":["// Export controller class and state utilities\nexport {\n AnalyticsController,\n getDefaultAnalyticsControllerState,\n} from './AnalyticsController';\nexport type { AnalyticsControllerOptions } from './AnalyticsController';\n\n// Export errors\nexport { AnalyticsPlatformAdapterSetupError } from './AnalyticsPlatformAdapterSetupError';\n\n// Export types\nexport type {\n AnalyticsEventProperties,\n AnalyticsUserTraits,\n AnalyticsPlatformAdapter,\n AnalyticsTrackingEvent,\n} from './AnalyticsPlatformAdapter.types';\n\n// Export state types\nexport type { AnalyticsControllerState } from './AnalyticsController';\n\n// Export selectors\nexport { analyticsControllerSelectors } from './selectors';\n\n// Export messenger types\nexport type { AnalyticsControllerMessenger } from './AnalyticsController';\n\n// Export action and event types\nexport type {\n AnalyticsControllerActions,\n AnalyticsControllerEvents,\n AnalyticsControllerGetStateAction,\n AnalyticsControllerStateChangeEvent,\n} from './AnalyticsController';\nexport type {\n AnalyticsControllerTrackEventAction,\n AnalyticsControllerIdentifyAction,\n AnalyticsControllerTrackViewAction,\n AnalyticsControllerOptInAction,\n AnalyticsControllerOptOutAction,\n AnalyticsControllerMethodActions,\n} from './AnalyticsController-method-action-types';\n"]}
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,8CAA8C;AAC9C,OAAO,EACL,mBAAmB,EACnB,kCAAkC,EACnC,kCAA8B;AAG/B,gBAAgB;AAChB,OAAO,EAAE,kCAAkC,EAAE,iDAA6C;AAwB1F,mBAAmB;AACnB,OAAO,EAAE,4BAA4B,EAAE,wBAAoB","sourcesContent":["// Export controller class and state utilities\nexport {\n AnalyticsController,\n getDefaultAnalyticsControllerState,\n} from './AnalyticsController';\nexport type { AnalyticsControllerOptions } from './AnalyticsController';\n\n// Export errors\nexport { AnalyticsPlatformAdapterSetupError } from './AnalyticsPlatformAdapterSetupError';\n\n// Export types\nexport type {\n AnalyticsContext,\n AnalyticsEventProperties,\n AnalyticsDeliveryOptions,\n AnalyticsInvocationCallback,\n AnalyticsUserTraits,\n AnalyticsPlatformAdapter,\n AnalyticsTrackingEvent,\n} from './AnalyticsPlatformAdapter.types';\n\n// Export state types\nexport type {\n AnalyticsControllerState,\n AnalyticsEventQueue,\n AnalyticsQueuedEvent,\n AnalyticsQueuedEventType,\n AnalyticsQueuedTrackEvent,\n AnalyticsQueuedIdentifyEvent,\n AnalyticsQueuedViewEvent,\n} from './AnalyticsController';\n\n// Export selectors\nexport { analyticsControllerSelectors } from './selectors';\n\n// Export messenger types\nexport type { AnalyticsControllerMessenger } from './AnalyticsController';\n\n// Export action and event types\nexport type {\n AnalyticsControllerActions,\n AnalyticsControllerEvents,\n AnalyticsControllerGetStateAction,\n AnalyticsControllerStateChangeEvent,\n} from './AnalyticsController';\nexport type {\n AnalyticsControllerTrackEventAction,\n AnalyticsControllerIdentifyAction,\n AnalyticsControllerTrackViewAction,\n AnalyticsControllerOptInAction,\n AnalyticsControllerOptOutAction,\n AnalyticsControllerMethodActions,\n} from './AnalyticsController-method-action-types';\n"]}
{
"name": "@metamask/analytics-controller",
"version": "1.0.1",
"version": "1.1.0",
"description": "Common Analytics controller for event tracking",
"keywords": [
"MetaMask",
"Ethereum"
"Ethereum",
"MetaMask"
],

@@ -13,2 +13,3 @@ "homepage": "https://github.com/MetaMask/core/tree/main/packages/analytics-controller#readme",

},
"license": "(MIT OR Apache-2.0)",
"repository": {

@@ -18,4 +19,8 @@ "type": "git",

},
"license": "(MIT OR Apache-2.0)",
"files": [
"dist/"
],
"sideEffects": false,
"main": "./dist/index.cjs",
"types": "./dist/index.d.cts",
"exports": {

@@ -34,7 +39,6 @@ ".": {

},
"main": "./dist/index.cjs",
"types": "./dist/index.d.cts",
"files": [
"dist/"
],
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
},
"scripts": {

@@ -46,3 +50,4 @@ "build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references",

"changelog:validate": "../../scripts/validate-changelog.sh @metamask/analytics-controller",
"generate-method-action-types": "tsx ../../scripts/generate-method-action-types.ts",
"messenger-action-types:check": "tsx ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --check",
"messenger-action-types:generate": "tsx ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --generate",
"since-latest-release": "../../scripts/since-latest-release.sh",

@@ -55,10 +60,13 @@ "test": "NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter",

"dependencies": {
"@metamask/base-controller": "^9.0.1",
"@metamask/messenger": "^1.0.0",
"@metamask/utils": "^11.9.0"
"@metamask/base-controller": "^9.1.0",
"@metamask/messenger": "^1.2.0",
"@metamask/utils": "^11.9.0",
"lodash": "^4.17.21",
"uuid": "^8.3.2"
},
"devDependencies": {
"@metamask/auto-changelog": "^3.4.4",
"@metamask/auto-changelog": "^6.1.0",
"@ts-bridge/cli": "^0.6.4",
"@types/jest": "^29.5.14",
"@types/uuid": "^8.3.0",
"deepmerge": "^4.2.2",

@@ -74,7 +82,3 @@ "jest": "^29.7.0",

"node": "^18.18 || >=20"
},
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
}
}
+11
-18

@@ -17,14 +17,2 @@ # `@metamask/analytics-controller`

## Client Platform-Managed Storage
> [!NOTE]
> "Client platform" means mobile or extension
The controller does not persist state internally. The client platform is responsible for loading and persisting analytics settings. This design enables:
- **Early access**: The client platform can read the `analyticsId` before the controller is initialized, useful for other controllers or early startup code
- **Resilience**: Storing analytics settings separately from main state protects them from state corruption, allowing analytics to continue working even when main state is corrupted
Load settings from storage **before** initializing the controller, then subscribe to `AnalyticsController:stateChange` events to persist any state changes.
## State

@@ -34,12 +22,9 @@

| ------------- | --------- | --------------------------------------------- | --------- |
| `analyticsId` | `string` | UUIDv4 identifier (client platform-generated) | No |
| `analyticsId` | `string` | UUIDv4 identifier (client platform-generated) | Yes |
| `optedIn` | `boolean` | User opt-in status | Yes |
| `eventQueue` | `object` | Optional persisted delivery queue | Yes |
### Why `analyticsId` Has No Default
The `analyticsId` uniquely identifies the user. If the controller generated a new ID on each boot, the ID would be ineffective. The client platform must generate a UUID on first run, persist it, and provide it to the controller constructor.
### Client Platform Responsibilities
1. **Generate UUID on first run**: Use `uuid` package or client platform equivalent
1. **Generate or migrate an initial `analyticsId`**: Use the `uuid` package or client platform equivalent for new installs, or migrate an existing MetaMetrics identifier when available. The controller validates this value as a UUIDv4, but does not create a default ID.
2. **Load state before controller init**: Read from storage, provide to constructor

@@ -58,2 +43,10 @@ 3. **Subscribe to state changes**: Persist changes to isolated storage

## Persisted Event Queue
When `isEventQueuePersistenceEnabled` is enabled in the constructor, each final platform adapter payload is persisted until the adapter reports successful delivery through its callback.
This feature is disabled by default. Client platforms that already rely on SDK-level persistence, such as MetaMask Mobile through `@segment/analytics-react-native`'s `storePersistor` option, should leave it disabled.
Platforms without SDK-level persistence, such as MetaMask Extension, can enable it to replay queued payloads after restart. The queue stores the final adapter calls, so anonymous event splitting persists the identified and anonymous payloads separately.
## Lifecycle Hooks

@@ -60,0 +53,0 @@