@metamask-previews/analytics-controller 2.0.0-preview-3866c0ff1 → 2.0.0-preview-e3275932a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/CHANGELOG.md +0 -4
  2. package/dist/AnalyticsController-method-action-types.cjs +7 -0
  3. package/dist/AnalyticsController-method-action-types.cjs.map +1 -0
  4. package/dist/{AnalyticsController-method-action-types.d.ts → AnalyticsController-method-action-types.d.cts} +2 -2
  5. package/dist/AnalyticsController-method-action-types.d.cts.map +1 -0
  6. package/dist/AnalyticsController-method-action-types.d.mts +81 -0
  7. package/dist/AnalyticsController-method-action-types.d.mts.map +1 -0
  8. package/dist/{AnalyticsController-method-action-types.js → AnalyticsController-method-action-types.mjs} +1 -1
  9. package/dist/AnalyticsController-method-action-types.mjs.map +1 -0
  10. package/dist/AnalyticsController.cjs +641 -0
  11. package/dist/AnalyticsController.cjs.map +1 -0
  12. package/dist/{AnalyticsController.d.ts → AnalyticsController.d.cts} +8 -8
  13. package/dist/AnalyticsController.d.cts.map +1 -0
  14. package/dist/AnalyticsController.d.mts +312 -0
  15. package/dist/AnalyticsController.d.mts.map +1 -0
  16. package/dist/AnalyticsController.mjs +637 -0
  17. package/dist/AnalyticsController.mjs.map +1 -0
  18. package/dist/AnalyticsLogger.cjs +8 -0
  19. package/dist/AnalyticsLogger.cjs.map +1 -0
  20. package/dist/AnalyticsLogger.d.cts +5 -0
  21. package/dist/AnalyticsLogger.d.cts.map +1 -0
  22. package/dist/AnalyticsLogger.d.mts +5 -0
  23. package/dist/AnalyticsLogger.d.mts.map +1 -0
  24. package/dist/{AnalyticsLogger.js → AnalyticsLogger.mjs} +2 -2
  25. package/dist/AnalyticsLogger.mjs.map +1 -0
  26. package/dist/AnalyticsPlatformAdapter.types.cjs +3 -0
  27. package/dist/AnalyticsPlatformAdapter.types.cjs.map +1 -0
  28. package/dist/{AnalyticsPlatformAdapter.types.d.ts → AnalyticsPlatformAdapter.types.d.cts} +2 -2
  29. package/dist/AnalyticsPlatformAdapter.types.d.cts.map +1 -0
  30. package/dist/AnalyticsPlatformAdapter.types.d.mts +144 -0
  31. package/dist/AnalyticsPlatformAdapter.types.d.mts.map +1 -0
  32. package/dist/AnalyticsPlatformAdapter.types.mjs +2 -0
  33. package/dist/AnalyticsPlatformAdapter.types.mjs.map +1 -0
  34. package/dist/AnalyticsPlatformAdapterSetupError.cjs +17 -0
  35. package/dist/AnalyticsPlatformAdapterSetupError.cjs.map +1 -0
  36. package/dist/{AnalyticsPlatformAdapterSetupError.d.ts → AnalyticsPlatformAdapterSetupError.d.cts} +1 -1
  37. package/dist/AnalyticsPlatformAdapterSetupError.d.cts.map +1 -0
  38. package/dist/AnalyticsPlatformAdapterSetupError.d.mts +8 -0
  39. package/dist/AnalyticsPlatformAdapterSetupError.d.mts.map +1 -0
  40. package/dist/{AnalyticsPlatformAdapterSetupError.js → AnalyticsPlatformAdapterSetupError.mjs} +1 -2
  41. package/dist/AnalyticsPlatformAdapterSetupError.mjs.map +1 -0
  42. package/dist/analyticsControllerStateValidator.cjs +36 -0
  43. package/dist/analyticsControllerStateValidator.cjs.map +1 -0
  44. package/dist/{analyticsControllerStateValidator.d.ts → analyticsControllerStateValidator.d.cts} +2 -2
  45. package/dist/analyticsControllerStateValidator.d.cts.map +1 -0
  46. package/dist/analyticsControllerStateValidator.d.mts +17 -0
  47. package/dist/analyticsControllerStateValidator.d.mts.map +1 -0
  48. package/dist/{analyticsControllerStateValidator.js → analyticsControllerStateValidator.mjs} +1 -1
  49. package/dist/analyticsControllerStateValidator.mjs.map +1 -0
  50. package/dist/index.cjs +14 -0
  51. package/dist/index.cjs.map +1 -0
  52. package/dist/{index.d.ts → index.d.cts} +10 -10
  53. package/dist/index.d.cts.map +1 -0
  54. package/dist/index.d.mts +10 -0
  55. package/dist/index.d.mts.map +1 -0
  56. package/dist/index.mjs +7 -0
  57. package/dist/index.mjs.map +1 -0
  58. package/dist/{selectors.d.ts → selectors.cjs} +13 -12
  59. package/dist/selectors.cjs.map +1 -0
  60. package/dist/selectors.d.cts +12 -0
  61. package/dist/selectors.d.cts.map +1 -0
  62. package/dist/selectors.d.mts +12 -0
  63. package/dist/selectors.d.mts.map +1 -0
  64. package/dist/{selectors.js → selectors.mjs} +1 -1
  65. package/dist/selectors.mjs.map +1 -0
  66. package/package.json +17 -13
  67. package/dist/AnalyticsController-method-action-types.d.ts.map +0 -1
  68. package/dist/AnalyticsController-method-action-types.js.map +0 -1
  69. package/dist/AnalyticsController.d.ts.map +0 -1
  70. package/dist/AnalyticsController.js +0 -746
  71. package/dist/AnalyticsController.js.map +0 -1
  72. package/dist/AnalyticsLogger.d.ts +0 -4
  73. package/dist/AnalyticsLogger.d.ts.map +0 -1
  74. package/dist/AnalyticsLogger.js.map +0 -1
  75. package/dist/AnalyticsPlatformAdapter.types.d.ts.map +0 -1
  76. package/dist/AnalyticsPlatformAdapter.types.js +0 -2
  77. package/dist/AnalyticsPlatformAdapter.types.js.map +0 -1
  78. package/dist/AnalyticsPlatformAdapterSetupError.d.ts.map +0 -1
  79. package/dist/AnalyticsPlatformAdapterSetupError.js.map +0 -1
  80. package/dist/analyticsControllerStateValidator.d.ts.map +0 -1
  81. package/dist/analyticsControllerStateValidator.js.map +0 -1
  82. package/dist/index.d.ts.map +0 -1
  83. package/dist/index.js +0 -7
  84. package/dist/index.js.map +0 -1
  85. package/dist/selectors.d.ts.map +0 -1
  86. package/dist/selectors.js.map +0 -1
@@ -0,0 +1,641 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _AnalyticsController_instances, _AnalyticsController_platformAdapter, _AnalyticsController_isAnonymousEventsFeatureEnabled, _AnalyticsController_isEventQueuePersistenceEnabled, _AnalyticsController_isPreConsentQueueEnabled, _AnalyticsController_isGeolocationEnabled, _AnalyticsController_initPromise, _AnalyticsController_locationResolvePromise, _AnalyticsController_locationContext, _AnalyticsController_performInit, _AnalyticsController_maybeResolveLocation, _AnalyticsController_resolveLocationContext, _AnalyticsController_withLocationContext, _AnalyticsController_sendOrQueueTrackEvent, _AnalyticsController_sendOrQueueIdentifyEvent, _AnalyticsController_sendOrQueueViewEvent, _AnalyticsController_enqueueEvent, _AnalyticsController_sendQueuedEvent, _AnalyticsController_replayQueuedEvents, _AnalyticsController_removeQueuedEvent, _AnalyticsController_clearQueuedEvents, _AnalyticsController_enqueuePreConsentEvent, _AnalyticsController_replayPreConsentEvents, _AnalyticsController_enrichPreConsentEvent, _AnalyticsController_clearPreConsentEvents, _AnalyticsController_reconcilePreConsentEvents;
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.AnalyticsController = exports.getDefaultAnalyticsControllerState = exports.controllerName = void 0;
16
+ const base_controller_1 = require("@metamask/base-controller");
17
+ const lodash_1 = require("lodash");
18
+ const uuid_1 = require("uuid");
19
+ const analyticsControllerStateValidator_js_1 = require("./analyticsControllerStateValidator.cjs");
20
+ const AnalyticsLogger_js_1 = require("./AnalyticsLogger.cjs");
21
+ const selectors_js_1 = require("./selectors.cjs");
22
+ // === GENERAL ===
23
+ /**
24
+ * The name of the {@link AnalyticsController}, used to namespace the
25
+ * controller's actions and events and to namespace the controller's state data
26
+ * when composed with other controllers.
27
+ */
28
+ exports.controllerName = 'AnalyticsController';
29
+ /**
30
+ * Returns default values for AnalyticsController state.
31
+ *
32
+ * Note: analyticsId is NOT included - it's an identity that must be
33
+ * provided by the platform (generated once on first run, then persisted).
34
+ *
35
+ * @returns Default state without analyticsId
36
+ */
37
+ function getDefaultAnalyticsControllerState() {
38
+ return {
39
+ optedIn: false,
40
+ consentDecisionMade: false,
41
+ };
42
+ }
43
+ exports.getDefaultAnalyticsControllerState = getDefaultAnalyticsControllerState;
44
+ /**
45
+ * The metadata for each property in {@link AnalyticsControllerState}.
46
+ *
47
+ * Both `optedIn` and `analyticsId` are persisted (`persist: true`).
48
+ * The platform must supply a valid UUIDv4 `analyticsId` on first run.
49
+ */
50
+ const analyticsControllerMetadata = {
51
+ optedIn: {
52
+ includeInStateLogs: true,
53
+ persist: true,
54
+ includeInDebugSnapshot: true,
55
+ usedInUi: true,
56
+ },
57
+ analyticsId: {
58
+ includeInStateLogs: true,
59
+ persist: true,
60
+ includeInDebugSnapshot: true,
61
+ usedInUi: false,
62
+ },
63
+ eventQueue: {
64
+ includeInStateLogs: false,
65
+ persist: true,
66
+ includeInDebugSnapshot: false,
67
+ usedInUi: false,
68
+ },
69
+ consentDecisionMade: {
70
+ includeInStateLogs: true,
71
+ persist: true,
72
+ includeInDebugSnapshot: true,
73
+ usedInUi: true,
74
+ },
75
+ preConsentEventQueue: {
76
+ includeInStateLogs: false,
77
+ persist: true,
78
+ includeInDebugSnapshot: false,
79
+ usedInUi: false,
80
+ },
81
+ };
82
+ // === MESSENGER ===
83
+ const MESSENGER_EXPOSED_METHODS = [
84
+ 'trackEvent',
85
+ 'identify',
86
+ 'trackView',
87
+ 'optIn',
88
+ 'optOut',
89
+ 'resetConsentDecision',
90
+ ];
91
+ /**
92
+ * Returns whether a value is a non-array object.
93
+ *
94
+ * @param value - The value to check.
95
+ * @returns True if the value is a record.
96
+ */
97
+ function isRecord(value) {
98
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
99
+ }
100
+ /**
101
+ * Returns whether a JSON value is a non-array object.
102
+ *
103
+ * @param value - The value to check.
104
+ * @returns True if the value is a JSON record.
105
+ */
106
+ function isJsonRecord(value) {
107
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
108
+ }
109
+ /**
110
+ * Builds the analytics location context from geolocation data, keeping only
111
+ * the fields the geolocation API was able to determine.
112
+ *
113
+ * @param geolocation - The geolocation data to convert.
114
+ * @returns The location context, or `undefined` when no field is known.
115
+ */
116
+ function buildLocationContext(geolocation) {
117
+ const locationContext = {
118
+ ...(geolocation.country === null
119
+ ? {}
120
+ : { country_code: geolocation.country }),
121
+ ...(geolocation.region === null ? {} : { region: geolocation.region }),
122
+ ...(geolocation.timezone === null
123
+ ? {}
124
+ : { timezone: geolocation.timezone }),
125
+ };
126
+ return Object.keys(locationContext).length === 0
127
+ ? undefined
128
+ : locationContext;
129
+ }
130
+ /**
131
+ * Returns whether a value is a valid persisted analytics event.
132
+ *
133
+ * @param value - The value to check.
134
+ * @returns True if the value is a queued analytics event.
135
+ */
136
+ function isAnalyticsQueuedEvent(value) {
137
+ if (!isRecord(value)) {
138
+ return false;
139
+ }
140
+ if (typeof value.messageId !== 'string' ||
141
+ typeof value.timestamp !== 'string') {
142
+ return false;
143
+ }
144
+ if (value.type === 'track') {
145
+ return (typeof value.eventName === 'string' &&
146
+ (value.properties === undefined || isRecord(value.properties)) &&
147
+ (value.context === undefined || isRecord(value.context)));
148
+ }
149
+ if (value.type === 'identify') {
150
+ return (typeof value.userId === 'string' &&
151
+ (value.traits === undefined || isRecord(value.traits)) &&
152
+ (value.context === undefined || isRecord(value.context)));
153
+ }
154
+ if (value.type === 'view') {
155
+ return (typeof value.name === 'string' &&
156
+ (value.properties === undefined || isRecord(value.properties)) &&
157
+ (value.context === undefined || isRecord(value.context)));
158
+ }
159
+ return false;
160
+ }
161
+ /**
162
+ * The AnalyticsController manages analytics tracking across platforms (Mobile/Extension).
163
+ * It provides a unified interface for tracking events, identifying users, and managing
164
+ * analytics preferences while delegating platform-specific implementation to an
165
+ * {@link AnalyticsPlatformAdapter}.
166
+ *
167
+ * This controller follows the MetaMask controller pattern and integrates with the
168
+ * messenger system to allow other controllers and components to track analytics events.
169
+ * It delegates platform-specific implementation to an {@link AnalyticsPlatformAdapter}.
170
+ *
171
+ * The controller persists `optedIn` and `analyticsId` when composed with a persisted
172
+ * store. The platform must supply a valid `analyticsId` on first launch.
173
+ */
174
+ class AnalyticsController extends base_controller_1.BaseController {
175
+ /**
176
+ * Constructs an AnalyticsController instance.
177
+ *
178
+ * @param options - Controller options
179
+ * @param options.state - Initial controller state. Must include a valid UUIDv4 `analyticsId`.
180
+ * Use `getDefaultAnalyticsControllerState()` for default opt-in preferences.
181
+ * @param options.messenger - Messenger used to communicate with BaseController
182
+ * @param options.platformAdapter - Platform adapter implementation for tracking
183
+ * @param options.isAnonymousEventsFeatureEnabled - Whether the anonymous events feature is enabled
184
+ * @param options.isEventQueuePersistenceEnabled - Whether analytics event queue persistence is enabled
185
+ * @param options.isPreConsentQueueEnabled - Whether the pre-consent event queue is enabled
186
+ * @param options.isGeolocationEnabled - Whether geolocation enrichment is enabled
187
+ * @throws Error if state.analyticsId is missing or not a valid UUIDv4
188
+ * @remarks After construction, call {@link AnalyticsController.init} to complete initialization.
189
+ */
190
+ constructor({ state, messenger, platformAdapter, isAnonymousEventsFeatureEnabled = false, isEventQueuePersistenceEnabled = false, isPreConsentQueueEnabled = false, isGeolocationEnabled = false, }) {
191
+ const initialState = {
192
+ ...getDefaultAnalyticsControllerState(),
193
+ ...state,
194
+ };
195
+ (0, analyticsControllerStateValidator_js_1.validateAnalyticsControllerState)(initialState, platformAdapter.skipUUIDv4Check === true);
196
+ super({
197
+ name: exports.controllerName,
198
+ metadata: analyticsControllerMetadata,
199
+ state: initialState,
200
+ messenger,
201
+ });
202
+ _AnalyticsController_instances.add(this);
203
+ _AnalyticsController_platformAdapter.set(this, void 0);
204
+ _AnalyticsController_isAnonymousEventsFeatureEnabled.set(this, void 0);
205
+ _AnalyticsController_isEventQueuePersistenceEnabled.set(this, void 0);
206
+ _AnalyticsController_isPreConsentQueueEnabled.set(this, void 0);
207
+ _AnalyticsController_isGeolocationEnabled.set(this, void 0);
208
+ /**
209
+ * The in-flight (or settled) initialization promise. Set on the first
210
+ * {@link init} call and returned by subsequent calls so overlapping callers
211
+ * await the same work rather than observing a premature completion.
212
+ */
213
+ _AnalyticsController_initPromise.set(this, void 0);
214
+ /**
215
+ * The in-flight (or settled) geolocation resolution, if any. Its presence
216
+ * marks that resolution has been started, so it runs at most once.
217
+ */
218
+ _AnalyticsController_locationResolvePromise.set(this, void 0);
219
+ _AnalyticsController_locationContext.set(this, void 0);
220
+ __classPrivateFieldSet(this, _AnalyticsController_isAnonymousEventsFeatureEnabled, isAnonymousEventsFeatureEnabled, "f");
221
+ __classPrivateFieldSet(this, _AnalyticsController_isEventQueuePersistenceEnabled, isEventQueuePersistenceEnabled, "f");
222
+ __classPrivateFieldSet(this, _AnalyticsController_isPreConsentQueueEnabled, isPreConsentQueueEnabled, "f");
223
+ __classPrivateFieldSet(this, _AnalyticsController_isGeolocationEnabled, isGeolocationEnabled, "f");
224
+ __classPrivateFieldSet(this, _AnalyticsController_platformAdapter, platformAdapter, "f");
225
+ __classPrivateFieldSet(this, _AnalyticsController_initPromise, undefined, "f");
226
+ __classPrivateFieldSet(this, _AnalyticsController_locationResolvePromise, undefined, "f");
227
+ this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
228
+ (0, AnalyticsLogger_js_1.projectLogger)('AnalyticsController initialized and ready', {
229
+ enabled: selectors_js_1.analyticsControllerSelectors.selectEnabled(this.state),
230
+ optedIn: this.state.optedIn,
231
+ consentDecisionMade: this.state.consentDecisionMade,
232
+ analyticsId: this.state.analyticsId,
233
+ eventQueuePersistenceEnabled: __classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f"),
234
+ preConsentQueueEnabled: __classPrivateFieldGet(this, _AnalyticsController_isPreConsentQueueEnabled, "f"),
235
+ geolocationEnabled: __classPrivateFieldGet(this, _AnalyticsController_isGeolocationEnabled, "f"),
236
+ });
237
+ }
238
+ /**
239
+ * Initialize the controller by calling the platform adapter's
240
+ * onSetupCompleted lifecycle hook and replaying any queued events. This
241
+ * method must be called after construction to complete the setup process.
242
+ *
243
+ * When geolocation enrichment is enabled (`isGeolocationEnabled`), geolocation
244
+ * is resolved only for a user who is already opted in; for undecided or
245
+ * opted-out users it is deferred until they opt in (see {@link optIn}), so a
246
+ * user's location is never requested before they consent to analytics. In
247
+ * either case the `GeolocationController` and its
248
+ * `GeolocationController:getGeolocationData` action must be registered before
249
+ * resolution occurs, or enrichment is skipped for the session (a message is
250
+ * logged, see {@link #resolveLocationContext}).
251
+ *
252
+ * Safe to call more than once: the first call performs initialization and
253
+ * subsequent calls return the same in-flight (or settled) promise.
254
+ *
255
+ * @returns A promise that resolves once initialization has completed.
256
+ */
257
+ init() {
258
+ // Cache the in-flight promise so repeated or overlapping calls share a
259
+ // single initialization and all await the same completion (rather than an
260
+ // early call observing a finished init while work is still pending).
261
+ __classPrivateFieldSet(this, _AnalyticsController_initPromise, __classPrivateFieldGet(this, _AnalyticsController_initPromise, "f") ?? __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_performInit).call(this), "f");
262
+ return __classPrivateFieldGet(this, _AnalyticsController_initPromise, "f");
263
+ }
264
+ /**
265
+ * Track an analytics event.
266
+ *
267
+ * Events are only tracked if analytics is enabled.
268
+ *
269
+ * @param event - Analytics event with properties and sensitive properties
270
+ * @param context - Optional platform-specific context forwarded to the platform adapter.
271
+ */
272
+ trackEvent(event, context) {
273
+ if (!selectors_js_1.analyticsControllerSelectors.selectEnabled(this.state)) {
274
+ // While the user is undecided, fall through so the event is processed and
275
+ // captured in the pre-consent queue (see #sendOrQueueTrackEvent) to be
276
+ // replayed if they later opt in. Otherwise (opted out, or pre-consent
277
+ // queue disabled) drop it.
278
+ const shouldQueuePreConsent = __classPrivateFieldGet(this, _AnalyticsController_isPreConsentQueueEnabled, "f") && !this.state.consentDecisionMade;
279
+ if (!shouldQueuePreConsent) {
280
+ return;
281
+ }
282
+ }
283
+ // if event does not have properties, send event without properties
284
+ // and return to prevent any additional processing
285
+ if (!event.hasProperties) {
286
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueTrackEvent).call(this, event.name, undefined, __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_withLocationContext).call(this, context));
287
+ return;
288
+ }
289
+ // Track regular properties first if anonymous events feature is enabled
290
+ if (__classPrivateFieldGet(this, _AnalyticsController_isAnonymousEventsFeatureEnabled, "f")) {
291
+ // Note: Even if regular properties object is empty, we still send it to ensure
292
+ // an event with user ID is tracked.
293
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueTrackEvent).call(this, event.name, {
294
+ ...event.properties,
295
+ }, __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_withLocationContext).call(this, context));
296
+ }
297
+ const hasSensitiveProperties = Object.keys(event.sensitiveProperties).length > 0;
298
+ if (!__classPrivateFieldGet(this, _AnalyticsController_isAnonymousEventsFeatureEnabled, "f") || hasSensitiveProperties) {
299
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueTrackEvent).call(this, event.name, {
300
+ ...event.properties,
301
+ ...event.sensitiveProperties,
302
+ ...(hasSensitiveProperties && { anonymous: true }),
303
+ },
304
+ // When the anonymous events feature is enabled, this payload is the
305
+ // anonymous one and must carry no geolocation. When the feature is
306
+ // disabled, this is the single identified payload, so it is enriched.
307
+ __classPrivateFieldGet(this, _AnalyticsController_isAnonymousEventsFeatureEnabled, "f")
308
+ ? context
309
+ : __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_withLocationContext).call(this, context));
310
+ }
311
+ }
312
+ /**
313
+ * Identify a user for analytics.
314
+ *
315
+ * @param traits - User traits/properties
316
+ * @param context - Optional platform-specific context forwarded to the platform adapter.
317
+ */
318
+ identify(traits, context) {
319
+ if (!selectors_js_1.analyticsControllerSelectors.selectEnabled(this.state)) {
320
+ return;
321
+ }
322
+ // Delegate to platform adapter using the current analytics ID
323
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueIdentifyEvent).call(this, this.state.analyticsId, traits, __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_withLocationContext).call(this, context));
324
+ }
325
+ /**
326
+ * Track a page or screen view.
327
+ *
328
+ * @param name - The identifier/name of the page or screen being viewed (e.g., "home", "settings", "wallet")
329
+ * @param properties - Optional properties associated with the view
330
+ * @param context - Optional platform-specific context forwarded to the platform adapter.
331
+ */
332
+ trackView(name, properties, context) {
333
+ if (!selectors_js_1.analyticsControllerSelectors.selectEnabled(this.state)) {
334
+ return;
335
+ }
336
+ // Delegate to platform adapter
337
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueViewEvent).call(this, name, properties, __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_withLocationContext).call(this, context));
338
+ }
339
+ /**
340
+ * Opt in to analytics.
341
+ *
342
+ * Records that a consent decision has been made and replays any events that
343
+ * were queued while the user was undecided.
344
+ *
345
+ * When geolocation enrichment is enabled, geolocation is resolved here (once
346
+ * the user has consented) and awaited before the queued events are replayed,
347
+ * so those events are enriched with the resolved location as they are sent.
348
+ *
349
+ * @returns A promise that resolves once opt-in processing has completed.
350
+ */
351
+ async optIn() {
352
+ this.update((state) => {
353
+ state.optedIn = true;
354
+ state.consentDecisionMade = true;
355
+ });
356
+ // Now that the user has consented, resolve geolocation (once) and wait for
357
+ // it so the queued pre-consent events can be enriched as they replay.
358
+ await __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_maybeResolveLocation).call(this);
359
+ // Reconcile against the current state rather than replaying blindly: the
360
+ // consent decision may have changed while geolocation was resolving (e.g.
361
+ // resetConsentDecision ran during the await), and preserved pre-consent
362
+ // events must not be delivered once the user is no longer opted in.
363
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_reconcilePreConsentEvents).call(this);
364
+ }
365
+ /**
366
+ * Opt out of analytics.
367
+ *
368
+ * Records that a consent decision has been made and discards any persisted
369
+ * events so nothing captured before the decision is ever delivered.
370
+ */
371
+ optOut() {
372
+ this.update((state) => {
373
+ state.optedIn = false;
374
+ state.consentDecisionMade = true;
375
+ });
376
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearQueuedEvents).call(this);
377
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearPreConsentEvents).call(this);
378
+ }
379
+ /**
380
+ * Reset the consent decision back to undecided.
381
+ *
382
+ * Intended for client flows that restart onboarding. Clears the opt-in
383
+ * preference and discards the delivery queue, but preserves any pre-consent
384
+ * events so they can still be replayed if the user opts in again. The user is
385
+ * treated as undecided again.
386
+ */
387
+ resetConsentDecision() {
388
+ this.update((state) => {
389
+ state.optedIn = false;
390
+ state.consentDecisionMade = false;
391
+ });
392
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearQueuedEvents).call(this);
393
+ }
394
+ }
395
+ exports.AnalyticsController = AnalyticsController;
396
+ _AnalyticsController_platformAdapter = new WeakMap(), _AnalyticsController_isAnonymousEventsFeatureEnabled = new WeakMap(), _AnalyticsController_isEventQueuePersistenceEnabled = new WeakMap(), _AnalyticsController_isPreConsentQueueEnabled = new WeakMap(), _AnalyticsController_isGeolocationEnabled = new WeakMap(), _AnalyticsController_initPromise = new WeakMap(), _AnalyticsController_locationResolvePromise = new WeakMap(), _AnalyticsController_locationContext = new WeakMap(), _AnalyticsController_instances = new WeakSet(), _AnalyticsController_performInit =
397
+ /**
398
+ * Performs the one-time initialization work: resolve geolocation, run the
399
+ * platform adapter's onSetupCompleted lifecycle hook, then replay any queued
400
+ * and pre-consent events.
401
+ */
402
+ async function _AnalyticsController_performInit() {
403
+ // Resolve geolocation only when the user is already opted in; for undecided
404
+ // or opted-out users it is deferred to {@link optIn}. Awaited so that an
405
+ // already-opted-in session has location available before events replay.
406
+ await __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_maybeResolveLocation).call(this);
407
+ // Call onSetupCompleted lifecycle hook after initialization
408
+ // State is already validated, so analyticsId is guaranteed to be a valid UUIDv4
409
+ try {
410
+ __classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").onSetupCompleted(this.state.analyticsId);
411
+ }
412
+ catch (error) {
413
+ // Log error but don't throw - adapter setup failure shouldn't break controller
414
+ (0, AnalyticsLogger_js_1.projectLogger)('Error calling platformAdapter.onSetupCompleted', error);
415
+ }
416
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_replayQueuedEvents).call(this);
417
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_reconcilePreConsentEvents).call(this);
418
+ }, _AnalyticsController_maybeResolveLocation = function _AnalyticsController_maybeResolveLocation() {
419
+ if (__classPrivateFieldGet(this, _AnalyticsController_isGeolocationEnabled, "f") &&
420
+ __classPrivateFieldGet(this, _AnalyticsController_locationResolvePromise, "f") === undefined &&
421
+ selectors_js_1.analyticsControllerSelectors.selectEnabled(this.state)) {
422
+ __classPrivateFieldSet(this, _AnalyticsController_locationResolvePromise, __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_resolveLocationContext).call(this), "f");
423
+ }
424
+ return __classPrivateFieldGet(this, _AnalyticsController_locationResolvePromise, "f");
425
+ }, _AnalyticsController_resolveLocationContext = async function _AnalyticsController_resolveLocationContext() {
426
+ try {
427
+ const geolocation = await this.messenger.call('GeolocationController:getGeolocationData');
428
+ __classPrivateFieldSet(this, _AnalyticsController_locationContext, buildLocationContext(geolocation), "f");
429
+ }
430
+ catch (error) {
431
+ // A common cause is the GeolocationController not being registered before
432
+ // resolution runs (at init for an opted-in user, otherwise at opt-in).
433
+ // Name it here so the failure is diagnosable, since enrichment is
434
+ // otherwise skipped silently for the session.
435
+ (0, AnalyticsLogger_js_1.projectLogger)('Failed to resolve geolocation for analytics enrichment; events will be sent without location. Ensure the GeolocationController is registered and initialized before the user opts in when geolocation is enabled.', error);
436
+ }
437
+ }, _AnalyticsController_withLocationContext = function _AnalyticsController_withLocationContext(context) {
438
+ if (!__classPrivateFieldGet(this, _AnalyticsController_locationContext, "f")) {
439
+ return context;
440
+ }
441
+ const callerLocation = context?.location;
442
+ return {
443
+ ...context,
444
+ location: {
445
+ ...(isJsonRecord(callerLocation) ? callerLocation : {}),
446
+ ...__classPrivateFieldGet(this, _AnalyticsController_locationContext, "f"),
447
+ },
448
+ };
449
+ }, _AnalyticsController_sendOrQueueTrackEvent = function _AnalyticsController_sendOrQueueTrackEvent(eventName, properties, context) {
450
+ // Direct delivery: enabled and not persisting.
451
+ if (selectors_js_1.analyticsControllerSelectors.selectEnabled(this.state) &&
452
+ !__classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f")) {
453
+ __classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").track(eventName, properties, context);
454
+ return;
455
+ }
456
+ const queuedEvent = {
457
+ type: 'track',
458
+ eventName,
459
+ messageId: (0, uuid_1.v4)(),
460
+ timestamp: new Date().toISOString(),
461
+ ...(properties === undefined ? {} : { properties }),
462
+ ...(context === undefined ? {} : { context }),
463
+ };
464
+ // Not yet enabled (reached only while undecided with the pre-consent queue
465
+ // enabled): hold the event until the user opts in.
466
+ if (!selectors_js_1.analyticsControllerSelectors.selectEnabled(this.state)) {
467
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_enqueuePreConsentEvent).call(this, queuedEvent);
468
+ return;
469
+ }
470
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_enqueueEvent).call(this, queuedEvent);
471
+ }, _AnalyticsController_sendOrQueueIdentifyEvent = function _AnalyticsController_sendOrQueueIdentifyEvent(userId, traits, context) {
472
+ if (!__classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f")) {
473
+ __classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").identify(userId, traits, context);
474
+ return;
475
+ }
476
+ const queuedEvent = {
477
+ type: 'identify',
478
+ userId,
479
+ messageId: (0, uuid_1.v4)(),
480
+ timestamp: new Date().toISOString(),
481
+ ...(traits === undefined ? {} : { traits }),
482
+ ...(context === undefined ? {} : { context }),
483
+ };
484
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_enqueueEvent).call(this, queuedEvent);
485
+ }, _AnalyticsController_sendOrQueueViewEvent = function _AnalyticsController_sendOrQueueViewEvent(name, properties, context) {
486
+ if (!__classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f")) {
487
+ __classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").view(name, properties, context);
488
+ return;
489
+ }
490
+ const queuedEvent = {
491
+ type: 'view',
492
+ name,
493
+ messageId: (0, uuid_1.v4)(),
494
+ timestamp: new Date().toISOString(),
495
+ ...(properties === undefined ? {} : { properties }),
496
+ ...(context === undefined ? {} : { context }),
497
+ };
498
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_enqueueEvent).call(this, queuedEvent);
499
+ }, _AnalyticsController_enqueueEvent = function _AnalyticsController_enqueueEvent(queuedEvent) {
500
+ const eventQueue = {
501
+ ...(this.state.eventQueue ?? {}),
502
+ [queuedEvent.messageId]: queuedEvent,
503
+ };
504
+ this.update((state) => {
505
+ state.eventQueue = eventQueue;
506
+ });
507
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendQueuedEvent).call(this, queuedEvent);
508
+ }, _AnalyticsController_sendQueuedEvent = function _AnalyticsController_sendQueuedEvent(queuedEvent) {
509
+ const timestamp = new Date(queuedEvent.timestamp);
510
+ if (Number.isNaN(timestamp.getTime())) {
511
+ (0, AnalyticsLogger_js_1.projectLogger)('Dropping queued analytics event with invalid timestamp', {
512
+ messageId: queuedEvent.messageId,
513
+ });
514
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_removeQueuedEvent).call(this, queuedEvent.messageId);
515
+ return;
516
+ }
517
+ const options = {
518
+ messageId: queuedEvent.messageId,
519
+ timestamp,
520
+ callback: (error) => {
521
+ if (error) {
522
+ (0, AnalyticsLogger_js_1.projectLogger)('Queued analytics event delivery failed', {
523
+ messageId: queuedEvent.messageId,
524
+ error,
525
+ });
526
+ }
527
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_removeQueuedEvent).call(this, queuedEvent.messageId);
528
+ },
529
+ };
530
+ try {
531
+ if (queuedEvent.type === 'track') {
532
+ __classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").track(queuedEvent.eventName, (0, lodash_1.cloneDeep)(queuedEvent.properties), (0, lodash_1.cloneDeep)(queuedEvent.context), options);
533
+ }
534
+ else if (queuedEvent.type === 'identify') {
535
+ __classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").identify(queuedEvent.userId, (0, lodash_1.cloneDeep)(queuedEvent.traits), (0, lodash_1.cloneDeep)(queuedEvent.context), options);
536
+ }
537
+ else {
538
+ __classPrivateFieldGet(this, _AnalyticsController_platformAdapter, "f").view(queuedEvent.name, (0, lodash_1.cloneDeep)(queuedEvent.properties), (0, lodash_1.cloneDeep)(queuedEvent.context), options);
539
+ }
540
+ }
541
+ catch (error) {
542
+ (0, AnalyticsLogger_js_1.projectLogger)('Error sending queued analytics event', {
543
+ messageId: queuedEvent.messageId,
544
+ error,
545
+ });
546
+ }
547
+ }, _AnalyticsController_replayQueuedEvents = function _AnalyticsController_replayQueuedEvents() {
548
+ if (!__classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f") || !this.state.eventQueue) {
549
+ return;
550
+ }
551
+ if (!selectors_js_1.analyticsControllerSelectors.selectEnabled(this.state)) {
552
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearQueuedEvents).call(this);
553
+ return;
554
+ }
555
+ for (const [messageId, queuedEvent] of Object.entries(this.state.eventQueue)) {
556
+ if (!isAnalyticsQueuedEvent(queuedEvent) ||
557
+ queuedEvent.messageId !== messageId) {
558
+ (0, AnalyticsLogger_js_1.projectLogger)('Dropping invalid queued analytics event', { messageId });
559
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_removeQueuedEvent).call(this, messageId);
560
+ continue;
561
+ }
562
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendQueuedEvent).call(this, queuedEvent);
563
+ }
564
+ }, _AnalyticsController_removeQueuedEvent = function _AnalyticsController_removeQueuedEvent(messageId) {
565
+ const currentEventQueue = this.state.eventQueue;
566
+ if (!currentEventQueue ||
567
+ !Object.prototype.hasOwnProperty.call(currentEventQueue, messageId)) {
568
+ return;
569
+ }
570
+ const { [messageId]: _deletedEvent, ...eventQueue } = currentEventQueue;
571
+ this.update((state) => {
572
+ state.eventQueue = eventQueue;
573
+ });
574
+ }, _AnalyticsController_clearQueuedEvents = function _AnalyticsController_clearQueuedEvents() {
575
+ if (!this.state.eventQueue ||
576
+ Object.keys(this.state.eventQueue).length === 0) {
577
+ return;
578
+ }
579
+ this.update((state) => {
580
+ state.eventQueue = {};
581
+ });
582
+ }, _AnalyticsController_enqueuePreConsentEvent = function _AnalyticsController_enqueuePreConsentEvent(queuedEvent) {
583
+ const preConsentEventQueue = {
584
+ ...(this.state.preConsentEventQueue ?? {}),
585
+ [queuedEvent.messageId]: queuedEvent,
586
+ };
587
+ this.update((state) => {
588
+ state.preConsentEventQueue = preConsentEventQueue;
589
+ });
590
+ }, _AnalyticsController_replayPreConsentEvents = function _AnalyticsController_replayPreConsentEvents(queue) {
591
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearPreConsentEvents).call(this);
592
+ for (const [messageId, queuedEvent] of Object.entries(queue)) {
593
+ if (!isAnalyticsQueuedEvent(queuedEvent) ||
594
+ queuedEvent.messageId !== messageId) {
595
+ (0, AnalyticsLogger_js_1.projectLogger)('Dropping invalid queued pre-consent analytics event', {
596
+ messageId,
597
+ });
598
+ continue;
599
+ }
600
+ const eventToReplay = __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_enrichPreConsentEvent).call(this, queuedEvent);
601
+ if (__classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f")) {
602
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_enqueueEvent).call(this, eventToReplay);
603
+ }
604
+ else {
605
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendQueuedEvent).call(this, eventToReplay);
606
+ }
607
+ }
608
+ }, _AnalyticsController_enrichPreConsentEvent = function _AnalyticsController_enrichPreConsentEvent(queuedEvent) {
609
+ if (queuedEvent.type === 'track' &&
610
+ queuedEvent.properties?.anonymous === true) {
611
+ return queuedEvent;
612
+ }
613
+ const context = __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_withLocationContext).call(this, queuedEvent.context);
614
+ return {
615
+ ...queuedEvent,
616
+ ...(context === undefined ? {} : { context }),
617
+ };
618
+ }, _AnalyticsController_clearPreConsentEvents = function _AnalyticsController_clearPreConsentEvents() {
619
+ if (!this.state.preConsentEventQueue) {
620
+ return;
621
+ }
622
+ this.update((state) => {
623
+ state.preConsentEventQueue = {};
624
+ });
625
+ }, _AnalyticsController_reconcilePreConsentEvents = function _AnalyticsController_reconcilePreConsentEvents() {
626
+ const queue = this.state.preConsentEventQueue;
627
+ if (!queue) {
628
+ return;
629
+ }
630
+ if (!__classPrivateFieldGet(this, _AnalyticsController_isPreConsentQueueEnabled, "f")) {
631
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearPreConsentEvents).call(this);
632
+ return;
633
+ }
634
+ if (this.state.optedIn) {
635
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_replayPreConsentEvents).call(this, queue);
636
+ }
637
+ else if (this.state.consentDecisionMade) {
638
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearPreConsentEvents).call(this);
639
+ }
640
+ };
641
+ //# sourceMappingURL=AnalyticsController.cjs.map