@metamask-previews/analytics-controller 2.0.0-preview-597a80865 → 2.0.0-preview-0d04fb622

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 (39) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +46 -5
  3. package/dist/AnalyticsController-method-action-types.cjs.map +1 -1
  4. package/dist/AnalyticsController-method-action-types.d.cts +102 -2
  5. package/dist/AnalyticsController-method-action-types.d.cts.map +1 -1
  6. package/dist/AnalyticsController-method-action-types.d.mts +102 -2
  7. package/dist/AnalyticsController-method-action-types.d.mts.map +1 -1
  8. package/dist/AnalyticsController-method-action-types.mjs.map +1 -1
  9. package/dist/AnalyticsController.cjs +341 -13
  10. package/dist/AnalyticsController.cjs.map +1 -1
  11. package/dist/AnalyticsController.d.cts +105 -2
  12. package/dist/AnalyticsController.d.cts.map +1 -1
  13. package/dist/AnalyticsController.d.mts +105 -2
  14. package/dist/AnalyticsController.d.mts.map +1 -1
  15. package/dist/AnalyticsController.mjs +341 -13
  16. package/dist/AnalyticsController.mjs.map +1 -1
  17. package/dist/EventFragment.types.cjs +3 -0
  18. package/dist/EventFragment.types.cjs.map +1 -0
  19. package/dist/EventFragment.types.d.cts +88 -0
  20. package/dist/EventFragment.types.d.cts.map +1 -0
  21. package/dist/EventFragment.types.d.mts +88 -0
  22. package/dist/EventFragment.types.d.mts.map +1 -0
  23. package/dist/EventFragment.types.mjs +2 -0
  24. package/dist/EventFragment.types.mjs.map +1 -0
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.d.cts +2 -1
  27. package/dist/index.d.cts.map +1 -1
  28. package/dist/index.d.mts +2 -1
  29. package/dist/index.d.mts.map +1 -1
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/selectors.cjs +19 -0
  32. package/dist/selectors.cjs.map +1 -1
  33. package/dist/selectors.d.cts +3 -0
  34. package/dist/selectors.d.cts.map +1 -1
  35. package/dist/selectors.d.mts +3 -0
  36. package/dist/selectors.d.mts.map +1 -1
  37. package/dist/selectors.mjs +19 -0
  38. package/dist/selectors.mjs.map +1 -1
  39. package/package.json +1 -1
@@ -10,7 +10,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
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
11
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
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;
13
+ var _AnalyticsController_instances, _AnalyticsController_platformAdapter, _AnalyticsController_isAnonymousEventsFeatureEnabled, _AnalyticsController_isEventQueuePersistenceEnabled, _AnalyticsController_isPreConsentQueueEnabled, _AnalyticsController_isGeolocationEnabled, _AnalyticsController_isEventFragmentsEnabled, _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, _AnalyticsController_reconcileEventFragments, _AnalyticsController_purgeNonPersistentEventFragments, _AnalyticsController_getEventFragment, _AnalyticsController_setEventFragment, _AnalyticsController_removeEventFragment, _AnalyticsController_clearEventFragments, _AnalyticsController_shouldIgnoreEventFragmentCall, _AnalyticsController_emitEventFragment, _AnalyticsController_isAnalyticsCaptureAllowed;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.AnalyticsController = exports.getDefaultAnalyticsControllerState = exports.controllerName = void 0;
16
16
  const base_controller_1 = require("@metamask/base-controller");
@@ -78,6 +78,12 @@ const analyticsControllerMetadata = {
78
78
  includeInDebugSnapshot: false,
79
79
  usedInUi: false,
80
80
  },
81
+ eventFragments: {
82
+ includeInStateLogs: false,
83
+ persist: true,
84
+ includeInDebugSnapshot: false,
85
+ usedInUi: false,
86
+ },
81
87
  };
82
88
  // === MESSENGER ===
83
89
  const MESSENGER_EXPOSED_METHODS = [
@@ -87,6 +93,12 @@ const MESSENGER_EXPOSED_METHODS = [
87
93
  'optIn',
88
94
  'optOut',
89
95
  'resetConsentDecision',
96
+ 'createEventFragment',
97
+ 'upsertEventFragment',
98
+ 'updateEventFragment',
99
+ 'getEventFragmentById',
100
+ 'deleteEventFragment',
101
+ 'finalizeEventFragment',
90
102
  ];
91
103
  /**
92
104
  * Returns whether a value is a non-array object.
@@ -158,6 +170,69 @@ function isAnalyticsQueuedEvent(value) {
158
170
  }
159
171
  return false;
160
172
  }
173
+ /**
174
+ * Returns whether a value is a valid persisted event fragment.
175
+ *
176
+ * @param value - The value to check.
177
+ * @returns True if the value is an event fragment.
178
+ */
179
+ function isAnalyticsEventFragment(value) {
180
+ if (!isRecord(value)) {
181
+ return false;
182
+ }
183
+ return (typeof value.id === 'string' &&
184
+ typeof value.createdAt === 'number' &&
185
+ typeof value.lastUpdated === 'number' &&
186
+ isRecord(value.properties) &&
187
+ isRecord(value.sensitiveProperties) &&
188
+ (value.initialEvent === undefined ||
189
+ typeof value.initialEvent === 'string') &&
190
+ (value.successEvent === undefined ||
191
+ typeof value.successEvent === 'string') &&
192
+ (value.failureEvent === undefined ||
193
+ typeof value.failureEvent === 'string') &&
194
+ (value.context === undefined || isRecord(value.context)) &&
195
+ (value.persist === undefined || typeof value.persist === 'boolean'));
196
+ }
197
+ /**
198
+ * Merges a payload into an event fragment.
199
+ *
200
+ * `properties`, `sensitiveProperties` and `context` are merged one level deep,
201
+ * so a key written twice is replaced rather than combined. This keeps array
202
+ * values predictable: writing a shorter array replaces the longer one instead
203
+ * of leaving stale trailing entries behind.
204
+ *
205
+ * @param fragment - The fragment to merge into.
206
+ * @param payload - The payload to merge.
207
+ * @returns A new fragment with the payload applied.
208
+ */
209
+ function mergeEventFragment(fragment, payload) {
210
+ const context = mergeEventFragmentContext(fragment.context, payload.context);
211
+ return {
212
+ ...fragment,
213
+ properties: { ...fragment.properties, ...(payload.properties ?? {}) },
214
+ sensitiveProperties: {
215
+ ...fragment.sensitiveProperties,
216
+ ...(payload.sensitiveProperties ?? {}),
217
+ },
218
+ ...(context === undefined ? {} : { context }),
219
+ lastUpdated: Date.now(),
220
+ };
221
+ }
222
+ /**
223
+ * Merges two optional analytics contexts, preserving `undefined` when neither
224
+ * side has one so an empty context is never sent.
225
+ *
226
+ * @param base - The context to merge into.
227
+ * @param override - The context whose fields win.
228
+ * @returns The merged context, or `undefined` when both sides are unset.
229
+ */
230
+ function mergeEventFragmentContext(base, override) {
231
+ if (base === undefined && override === undefined) {
232
+ return undefined;
233
+ }
234
+ return { ...(base ?? {}), ...(override ?? {}) };
235
+ }
161
236
  /**
162
237
  * The AnalyticsController manages analytics tracking across platforms (Mobile/Extension).
163
238
  * It provides a unified interface for tracking events, identifying users, and managing
@@ -184,10 +259,11 @@ class AnalyticsController extends base_controller_1.BaseController {
184
259
  * @param options.isEventQueuePersistenceEnabled - Whether analytics event queue persistence is enabled
185
260
  * @param options.isPreConsentQueueEnabled - Whether the pre-consent event queue is enabled
186
261
  * @param options.isGeolocationEnabled - Whether geolocation enrichment is enabled
262
+ * @param options.isEventFragmentsEnabled - Whether the event fragments feature is enabled
187
263
  * @throws Error if state.analyticsId is missing or not a valid UUIDv4
188
264
  * @remarks After construction, call {@link AnalyticsController.init} to complete initialization.
189
265
  */
190
- constructor({ state, messenger, platformAdapter, isAnonymousEventsFeatureEnabled = false, isEventQueuePersistenceEnabled = false, isPreConsentQueueEnabled = false, isGeolocationEnabled = false, }) {
266
+ constructor({ state, messenger, platformAdapter, isAnonymousEventsFeatureEnabled = false, isEventQueuePersistenceEnabled = false, isPreConsentQueueEnabled = false, isGeolocationEnabled = false, isEventFragmentsEnabled = false, }) {
191
267
  const initialState = {
192
268
  ...getDefaultAnalyticsControllerState(),
193
269
  ...state,
@@ -205,6 +281,7 @@ class AnalyticsController extends base_controller_1.BaseController {
205
281
  _AnalyticsController_isEventQueuePersistenceEnabled.set(this, void 0);
206
282
  _AnalyticsController_isPreConsentQueueEnabled.set(this, void 0);
207
283
  _AnalyticsController_isGeolocationEnabled.set(this, void 0);
284
+ _AnalyticsController_isEventFragmentsEnabled.set(this, void 0);
208
285
  /**
209
286
  * The in-flight (or settled) initialization promise. Set on the first
210
287
  * {@link init} call and returned by subsequent calls so overlapping callers
@@ -221,6 +298,7 @@ class AnalyticsController extends base_controller_1.BaseController {
221
298
  __classPrivateFieldSet(this, _AnalyticsController_isEventQueuePersistenceEnabled, isEventQueuePersistenceEnabled, "f");
222
299
  __classPrivateFieldSet(this, _AnalyticsController_isPreConsentQueueEnabled, isPreConsentQueueEnabled, "f");
223
300
  __classPrivateFieldSet(this, _AnalyticsController_isGeolocationEnabled, isGeolocationEnabled, "f");
301
+ __classPrivateFieldSet(this, _AnalyticsController_isEventFragmentsEnabled, isEventFragmentsEnabled, "f");
224
302
  __classPrivateFieldSet(this, _AnalyticsController_platformAdapter, platformAdapter, "f");
225
303
  __classPrivateFieldSet(this, _AnalyticsController_initPromise, undefined, "f");
226
304
  __classPrivateFieldSet(this, _AnalyticsController_locationResolvePromise, undefined, "f");
@@ -233,6 +311,7 @@ class AnalyticsController extends base_controller_1.BaseController {
233
311
  eventQueuePersistenceEnabled: __classPrivateFieldGet(this, _AnalyticsController_isEventQueuePersistenceEnabled, "f"),
234
312
  preConsentQueueEnabled: __classPrivateFieldGet(this, _AnalyticsController_isPreConsentQueueEnabled, "f"),
235
313
  geolocationEnabled: __classPrivateFieldGet(this, _AnalyticsController_isGeolocationEnabled, "f"),
314
+ eventFragmentsEnabled: __classPrivateFieldGet(this, _AnalyticsController_isEventFragmentsEnabled, "f"),
236
315
  });
237
316
  }
238
317
  /**
@@ -270,15 +349,11 @@ class AnalyticsController extends base_controller_1.BaseController {
270
349
  * @param context - Optional platform-specific context forwarded to the platform adapter.
271
350
  */
272
351
  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
- }
352
+ // An event captured while the user is still undecided is held in the
353
+ // pre-consent queue (see #sendOrQueueTrackEvent) instead of being
354
+ // delivered, and replayed if they later opt in.
355
+ if (!__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_isAnalyticsCaptureAllowed).call(this)) {
356
+ return;
282
357
  }
283
358
  // if event does not have properties, send event without properties
284
359
  // and return to prevent any additional processing
@@ -336,6 +411,153 @@ class AnalyticsController extends base_controller_1.BaseController {
336
411
  // Delegate to platform adapter
337
412
  __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_sendOrQueueViewEvent).call(this, name, properties, __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_withLocationContext).call(this, context));
338
413
  }
414
+ /**
415
+ * Create an event fragment.
416
+ *
417
+ * A fragment accumulates properties across a user journey so that several
418
+ * parts of a client can contribute to the same set of events without
419
+ * re-deriving them. Declaring `successEvent` and `failureEvent` turns the
420
+ * fragment into a funnel that {@link finalizeEventFragment} closes. Declaring
421
+ * none of the event names makes it a pure property bag that the client reads
422
+ * back with {@link getEventFragmentById} when it emits its own events.
423
+ *
424
+ * Any existing fragment with the same ID is replaced, so a new journey never
425
+ * inherits properties from a stale one.
426
+ *
427
+ * Nothing is created unless the user is opted in, or undecided with the
428
+ * pre-consent queue enabled, so an opted-out user accumulates no fragment
429
+ * data.
430
+ *
431
+ * @param options - The fragment definition. An ID is generated when one is
432
+ * not supplied.
433
+ * @returns The created fragment, or `undefined` when the event fragments
434
+ * feature is disabled or the consent state does not allow capture.
435
+ */
436
+ createEventFragment(options = {}) {
437
+ if (__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_shouldIgnoreEventFragmentCall).call(this, 'createEventFragment')) {
438
+ return undefined;
439
+ }
440
+ const now = Date.now();
441
+ const fragment = {
442
+ id: options.id ?? (0, uuid_1.v4)(),
443
+ properties: { ...(options.properties ?? {}) },
444
+ sensitiveProperties: { ...(options.sensitiveProperties ?? {}) },
445
+ createdAt: now,
446
+ lastUpdated: now,
447
+ ...(options.initialEvent === undefined
448
+ ? {}
449
+ : { initialEvent: options.initialEvent }),
450
+ ...(options.successEvent === undefined
451
+ ? {}
452
+ : { successEvent: options.successEvent }),
453
+ ...(options.failureEvent === undefined
454
+ ? {}
455
+ : { failureEvent: options.failureEvent }),
456
+ ...(options.context === undefined ? {} : { context: options.context }),
457
+ ...(options.persist === undefined ? {} : { persist: options.persist }),
458
+ };
459
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_setEventFragment).call(this, fragment);
460
+ if (fragment.initialEvent) {
461
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_emitEventFragment).call(this, fragment, fragment.initialEvent, fragment.context);
462
+ }
463
+ return fragment;
464
+ }
465
+ /**
466
+ * Write to an event fragment, creating a property bag if none exists.
467
+ *
468
+ * This is the ergonomic entry point for contributors that do not know
469
+ * whether the journey has been started yet, and it avoids the read then
470
+ * write race a caller would otherwise have to implement itself.
471
+ *
472
+ * @param id - The fragment ID.
473
+ * @param payload - The properties and context to merge in.
474
+ */
475
+ upsertEventFragment(id, payload = {}) {
476
+ if (__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_shouldIgnoreEventFragmentCall).call(this, 'upsertEventFragment')) {
477
+ return;
478
+ }
479
+ const fragment = __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_getEventFragment).call(this, id);
480
+ if (!fragment) {
481
+ this.createEventFragment({ id, ...payload });
482
+ return;
483
+ }
484
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_setEventFragment).call(this, mergeEventFragment(fragment, payload));
485
+ }
486
+ /**
487
+ * Write to an existing event fragment.
488
+ *
489
+ * @param id - The fragment ID.
490
+ * @param payload - The properties and context to merge in.
491
+ * @throws Error if no fragment has that ID when the call is not ignored.
492
+ * Use {@link upsertEventFragment} when the fragment may not exist yet.
493
+ * When the event fragments feature is disabled or the consent state does not
494
+ * allow capture, the call is a logged no-op and does not throw.
495
+ */
496
+ updateEventFragment(id, payload = {}) {
497
+ if (__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_shouldIgnoreEventFragmentCall).call(this, 'updateEventFragment')) {
498
+ return;
499
+ }
500
+ const fragment = __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_getEventFragment).call(this, id);
501
+ if (!fragment) {
502
+ throw new Error(`Event fragment with id ${id} does not exist.`);
503
+ }
504
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_setEventFragment).call(this, mergeEventFragment(fragment, payload));
505
+ }
506
+ /**
507
+ * Read an event fragment.
508
+ *
509
+ * @param id - The fragment ID.
510
+ * @returns The fragment, or `undefined` when no fragment has that ID, the
511
+ * event fragments feature is disabled, or the consent state does not allow
512
+ * capture.
513
+ */
514
+ getEventFragmentById(id) {
515
+ if (__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_shouldIgnoreEventFragmentCall).call(this, 'getEventFragmentById')) {
516
+ return undefined;
517
+ }
518
+ return __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_getEventFragment).call(this, id);
519
+ }
520
+ /**
521
+ * Discard an event fragment without emitting anything.
522
+ *
523
+ * @param id - The fragment ID.
524
+ */
525
+ deleteEventFragment(id) {
526
+ if (__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_shouldIgnoreEventFragmentCall).call(this, 'deleteEventFragment')) {
527
+ return;
528
+ }
529
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_removeEventFragment).call(this, id);
530
+ }
531
+ /**
532
+ * Close an event fragment, emitting its closing event and discarding it.
533
+ *
534
+ * The event emitted is `failureEvent` when the journey was abandoned and
535
+ * `successEvent` otherwise. A fragment that does not declare the relevant
536
+ * event name is discarded silently, which is what makes a pure property bag
537
+ * possible.
538
+ *
539
+ * @param id - The fragment ID.
540
+ * @param options - Finalization options.
541
+ * @param options.abandoned - Whether the journey was abandoned.
542
+ * @param options.context - Context merged over the fragment's own context.
543
+ * @throws Error if no fragment has that ID when the call is not ignored.
544
+ * When the event fragments feature is disabled or the consent state does not
545
+ * allow capture, the call is a logged no-op and does not throw.
546
+ */
547
+ finalizeEventFragment(id, { abandoned = false, context } = {}) {
548
+ if (__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_shouldIgnoreEventFragmentCall).call(this, 'finalizeEventFragment')) {
549
+ return;
550
+ }
551
+ const fragment = __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_getEventFragment).call(this, id);
552
+ if (!fragment) {
553
+ throw new Error(`Event fragment with id ${id} does not exist.`);
554
+ }
555
+ const eventName = abandoned ? fragment.failureEvent : fragment.successEvent;
556
+ if (eventName) {
557
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_emitEventFragment).call(this, fragment, eventName, mergeEventFragmentContext(fragment.context, context));
558
+ }
559
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_removeEventFragment).call(this, id);
560
+ }
339
561
  /**
340
562
  * Opt in to analytics.
341
563
  *
@@ -366,7 +588,8 @@ class AnalyticsController extends base_controller_1.BaseController {
366
588
  * Opt out of analytics.
367
589
  *
368
590
  * Records that a consent decision has been made and discards any persisted
369
- * events so nothing captured before the decision is ever delivered.
591
+ * events and in-progress event fragments so nothing captured before the
592
+ * decision is ever delivered.
370
593
  */
371
594
  optOut() {
372
595
  this.update((state) => {
@@ -375,6 +598,7 @@ class AnalyticsController extends base_controller_1.BaseController {
375
598
  });
376
599
  __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearQueuedEvents).call(this);
377
600
  __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearPreConsentEvents).call(this);
601
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearEventFragments).call(this);
378
602
  }
379
603
  /**
380
604
  * Reset the consent decision back to undecided.
@@ -383,6 +607,10 @@ class AnalyticsController extends base_controller_1.BaseController {
383
607
  * preference and discards the delivery queue, but preserves any pre-consent
384
608
  * events so they can still be replayed if the user opts in again. The user is
385
609
  * treated as undecided again.
610
+ *
611
+ * In-progress event fragments are kept only while the undecided user can
612
+ * still accumulate them, and discarded otherwise, so no fragment outlives the
613
+ * consent state that allowed it.
386
614
  */
387
615
  resetConsentDecision() {
388
616
  this.update((state) => {
@@ -390,16 +618,30 @@ class AnalyticsController extends base_controller_1.BaseController {
390
618
  state.consentDecisionMade = false;
391
619
  });
392
620
  __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearQueuedEvents).call(this);
621
+ if (!__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_isAnalyticsCaptureAllowed).call(this)) {
622
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearEventFragments).call(this);
623
+ }
393
624
  }
394
625
  }
395
626
  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 =
627
+ _AnalyticsController_platformAdapter = new WeakMap(), _AnalyticsController_isAnonymousEventsFeatureEnabled = new WeakMap(), _AnalyticsController_isEventQueuePersistenceEnabled = new WeakMap(), _AnalyticsController_isPreConsentQueueEnabled = new WeakMap(), _AnalyticsController_isGeolocationEnabled = new WeakMap(), _AnalyticsController_isEventFragmentsEnabled = new WeakMap(), _AnalyticsController_initPromise = new WeakMap(), _AnalyticsController_locationResolvePromise = new WeakMap(), _AnalyticsController_locationContext = new WeakMap(), _AnalyticsController_instances = new WeakSet(), _AnalyticsController_performInit =
397
628
  /**
398
629
  * Performs the one-time initialization work: resolve geolocation, run the
399
630
  * platform adapter's onSetupCompleted lifecycle hook, then replay any queued
400
631
  * and pre-consent events.
401
632
  */
402
633
  async function _AnalyticsController_performInit() {
634
+ // Snapshot fragment IDs and createdAt before any awaited init work so
635
+ // reconciliation can tell previous-session leftovers from fragments
636
+ // created or replaced while init runs.
637
+ const initEventFragmentSnapshot = new Map();
638
+ for (const [id, fragment] of Object.entries(this.state.eventFragments ?? {})) {
639
+ if (isAnalyticsEventFragment(fragment) &&
640
+ fragment.id === id &&
641
+ typeof fragment.createdAt === 'number') {
642
+ initEventFragmentSnapshot.set(id, fragment.createdAt);
643
+ }
644
+ }
403
645
  // Resolve geolocation only when the user is already opted in; for undecided
404
646
  // or opted-out users it is deferred to {@link optIn}. Awaited so that an
405
647
  // already-opted-in session has location available before events replay.
@@ -415,6 +657,7 @@ async function _AnalyticsController_performInit() {
415
657
  }
416
658
  __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_replayQueuedEvents).call(this);
417
659
  __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_reconcilePreConsentEvents).call(this);
660
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_reconcileEventFragments).call(this, initEventFragmentSnapshot);
418
661
  }, _AnalyticsController_maybeResolveLocation = function _AnalyticsController_maybeResolveLocation() {
419
662
  if (__classPrivateFieldGet(this, _AnalyticsController_isGeolocationEnabled, "f") &&
420
663
  __classPrivateFieldGet(this, _AnalyticsController_locationResolvePromise, "f") === undefined &&
@@ -637,5 +880,90 @@ async function _AnalyticsController_performInit() {
637
880
  else if (this.state.consentDecisionMade) {
638
881
  __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearPreConsentEvents).call(this);
639
882
  }
883
+ }, _AnalyticsController_reconcileEventFragments = function _AnalyticsController_reconcileEventFragments(initEventFragmentSnapshot) {
884
+ const fragments = this.state.eventFragments;
885
+ if (!fragments) {
886
+ return;
887
+ }
888
+ if (!__classPrivateFieldGet(this, _AnalyticsController_isEventFragmentsEnabled, "f") || !__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_isAnalyticsCaptureAllowed).call(this)) {
889
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_clearEventFragments).call(this);
890
+ return;
891
+ }
892
+ __classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_purgeNonPersistentEventFragments).call(this, fragments, initEventFragmentSnapshot);
893
+ }, _AnalyticsController_purgeNonPersistentEventFragments = function _AnalyticsController_purgeNonPersistentEventFragments(currentEventFragments, initEventFragmentSnapshot) {
894
+ const eventFragments = {};
895
+ for (const [id, fragment] of Object.entries(currentEventFragments)) {
896
+ if (!isAnalyticsEventFragment(fragment) || fragment.id !== id) {
897
+ (0, AnalyticsLogger_js_1.projectLogger)('Dropping invalid persisted event fragment', { id });
898
+ continue;
899
+ }
900
+ const snapshotCreatedAt = initEventFragmentSnapshot.get(id);
901
+ if (fragment.persist === true ||
902
+ snapshotCreatedAt === undefined ||
903
+ fragment.createdAt !== snapshotCreatedAt) {
904
+ eventFragments[id] = fragment;
905
+ }
906
+ }
907
+ if (Object.keys(eventFragments).length ===
908
+ Object.keys(currentEventFragments).length) {
909
+ return;
910
+ }
911
+ this.update((state) => {
912
+ state.eventFragments = eventFragments;
913
+ });
914
+ }, _AnalyticsController_getEventFragment = function _AnalyticsController_getEventFragment(id) {
915
+ return this.state.eventFragments?.[id];
916
+ }, _AnalyticsController_setEventFragment = function _AnalyticsController_setEventFragment(fragment) {
917
+ const eventFragments = {
918
+ ...this.state.eventFragments,
919
+ [fragment.id]: fragment,
920
+ };
921
+ this.update((state) => {
922
+ state.eventFragments = eventFragments;
923
+ });
924
+ }, _AnalyticsController_removeEventFragment = function _AnalyticsController_removeEventFragment(id) {
925
+ const currentEventFragments = this.state.eventFragments;
926
+ if (!currentEventFragments ||
927
+ !Object.prototype.hasOwnProperty.call(currentEventFragments, id)) {
928
+ return;
929
+ }
930
+ const { [id]: _deletedFragment, ...eventFragments } = currentEventFragments;
931
+ this.update((state) => {
932
+ state.eventFragments = eventFragments;
933
+ });
934
+ }, _AnalyticsController_clearEventFragments = function _AnalyticsController_clearEventFragments() {
935
+ if (!this.state.eventFragments ||
936
+ Object.keys(this.state.eventFragments).length === 0) {
937
+ return;
938
+ }
939
+ this.update((state) => {
940
+ state.eventFragments = {};
941
+ });
942
+ }, _AnalyticsController_shouldIgnoreEventFragmentCall = function _AnalyticsController_shouldIgnoreEventFragmentCall(method) {
943
+ if (!__classPrivateFieldGet(this, _AnalyticsController_isEventFragmentsEnabled, "f")) {
944
+ (0, AnalyticsLogger_js_1.projectLogger)('Ignoring event fragment call because the event fragments feature is disabled', { method });
945
+ return true;
946
+ }
947
+ if (!__classPrivateFieldGet(this, _AnalyticsController_instances, "m", _AnalyticsController_isAnalyticsCaptureAllowed).call(this)) {
948
+ (0, AnalyticsLogger_js_1.projectLogger)('Ignoring event fragment call because the consent state does not allow capturing analytics', { method });
949
+ return true;
950
+ }
951
+ return false;
952
+ }, _AnalyticsController_emitEventFragment = function _AnalyticsController_emitEventFragment(fragment, name, context) {
953
+ const properties = { ...fragment.properties };
954
+ const sensitiveProperties = { ...fragment.sensitiveProperties };
955
+ this.trackEvent({
956
+ name,
957
+ properties,
958
+ sensitiveProperties,
959
+ saveDataRecording: false,
960
+ hasProperties: Object.keys(properties).length > 0 ||
961
+ Object.keys(sensitiveProperties).length > 0,
962
+ }, context);
963
+ }, _AnalyticsController_isAnalyticsCaptureAllowed = function _AnalyticsController_isAnalyticsCaptureAllowed() {
964
+ if (selectors_js_1.analyticsControllerSelectors.selectEnabled(this.state)) {
965
+ return true;
966
+ }
967
+ return __classPrivateFieldGet(this, _AnalyticsController_isPreConsentQueueEnabled, "f") && !this.state.consentDecisionMade;
640
968
  };
641
969
  //# sourceMappingURL=AnalyticsController.cjs.map