@amplitude/analytics-react-native 1.6.5 → 1.6.6

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 (44) hide show
  1. package/lib/commonjs/config.js +1 -0
  2. package/lib/commonjs/config.js.map +1 -1
  3. package/lib/commonjs/constants.js +14 -0
  4. package/lib/commonjs/constants.js.map +1 -0
  5. package/lib/commonjs/index.js +6 -2
  6. package/lib/commonjs/index.js.map +1 -1
  7. package/lib/commonjs/migration/remnant-data-migration.js.map +1 -1
  8. package/lib/commonjs/react-native-client.js +102 -9
  9. package/lib/commonjs/react-native-client.js.map +1 -1
  10. package/lib/commonjs/types.js +6 -0
  11. package/lib/commonjs/types.js.map +1 -1
  12. package/lib/commonjs/version.js +1 -1
  13. package/lib/module/config.js +1 -0
  14. package/lib/module/config.js.map +1 -1
  15. package/lib/module/constants.js +8 -0
  16. package/lib/module/constants.js.map +1 -0
  17. package/lib/module/index.js +3 -1
  18. package/lib/module/index.js.map +1 -1
  19. package/lib/module/migration/remnant-data-migration.js.map +1 -1
  20. package/lib/module/react-native-client.js +103 -9
  21. package/lib/module/react-native-client.js.map +1 -1
  22. package/lib/module/types.js +1 -1
  23. package/lib/module/types.js.map +1 -1
  24. package/lib/module/version.js +1 -1
  25. package/lib/typescript/config.d.ts +2 -1
  26. package/lib/typescript/config.d.ts.map +1 -1
  27. package/lib/typescript/constants.d.ts +8 -0
  28. package/lib/typescript/constants.d.ts.map +1 -0
  29. package/lib/typescript/index.d.ts +1 -1
  30. package/lib/typescript/index.d.ts.map +1 -1
  31. package/lib/typescript/migration/remnant-data-migration.d.ts.map +1 -1
  32. package/lib/typescript/react-native-client.d.ts +16 -1
  33. package/lib/typescript/react-native-client.d.ts.map +1 -1
  34. package/lib/typescript/types.d.ts +1 -1
  35. package/lib/typescript/types.d.ts.map +1 -1
  36. package/lib/typescript/version.d.ts +1 -1
  37. package/package.json +2 -2
  38. package/src/config.ts +4 -0
  39. package/src/constants.ts +9 -0
  40. package/src/index.ts +2 -0
  41. package/src/migration/remnant-data-migration.ts +1 -2
  42. package/src/react-native-client.ts +130 -7
  43. package/src/types.ts +1 -0
  44. package/src/version.ts +1 -1
@@ -23,6 +23,9 @@ import {
23
23
  SpecialEventType,
24
24
  AnalyticsClient,
25
25
  OfflineDisabled,
26
+ ReactNativeAutocaptureOptions,
27
+ ReactNativeConfigAutocaptureBeta,
28
+ NavigationState,
26
29
  } from '@amplitude/analytics-core';
27
30
  import { CampaignTracker } from './campaign/campaign-tracker';
28
31
  import { Context } from './plugins/context';
@@ -30,18 +33,56 @@ import { networkConnectivityCheckerPlugin } from './plugins/network-connectivity
30
33
  import { useReactNativeConfig, createCookieStorage } from './config';
31
34
  import { parseOldCookies } from './cookie-migration';
32
35
  import { isNative } from './utils/platform';
36
+ import {
37
+ DEFAULT_APPLICATION_BACKGROUNDED_EVENT,
38
+ DEFAULT_APPLICATION_OPENED_EVENT,
39
+ DEFAULT_SCREEN_VIEWED_EVENT,
40
+ DEFAULT_SESSION_END_EVENT,
41
+ DEFAULT_SESSION_START_EVENT,
42
+ SCREEN_NAME,
43
+ } from './constants';
44
+
45
+ /**
46
+ * Walks React Navigation state to the focused leaf route.
47
+ * Nested navigators (tabs, stacks) store the visible screen in child `state`.
48
+ */
49
+ const getActiveRouteName = (navigationState: NavigationState): string | undefined => {
50
+ let state: NavigationState | undefined = navigationState;
51
+ let routeName: string | undefined;
52
+
53
+ while (state?.routes) {
54
+ const route = state.routes[state.index] as { name: string; state?: NavigationState } | undefined;
55
+ if (!route?.name) {
56
+ return undefined;
57
+ }
58
+ routeName = route.name;
59
+ state = route.state;
60
+ }
33
61
 
34
- const START_SESSION_EVENT = 'session_start';
35
- const END_SESSION_EVENT = 'session_end';
62
+ return routeName;
63
+ };
36
64
 
37
65
  export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeClient, AnalyticsClient {
38
66
  appState: AppStateStatus = 'background';
67
+ /**
68
+ * True after a transition into `background` until the next `active`.
69
+ * Used so Application Opened only pairs with Application Backgrounded
70
+ * (e.g. skip iOS inactive→active from Control Center overlays).
71
+ */
72
+ private wasBackgrounded = false;
73
+ /**
74
+ * Last focused leaf route name emitted by `trackScreenViewOnNavigationStateChange`.
75
+ * Dedupes React Navigation callbacks that only change params, history shape, or
76
+ * fire twice for the same visible screen (e.g. `onReady` + `onStateChange`, tabs).
77
+ */
78
+ private lastNavigationScreenName: string | undefined;
39
79
  private appStateChangeHandler: NativeEventSubscription | undefined;
40
80
  explicitSessionId: number | undefined;
41
81
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
42
82
  // @ts-ignore
43
83
  config: ReactNativeConfig;
44
84
  userProperties: { [key: string]: any } | undefined;
85
+ autocapture: ReactNativeAutocaptureOptions | null = null;
45
86
 
46
87
  init(apiKey = '', userId?: string, options?: ReactNativeOptions) {
47
88
  return returnWrapper(this._init({ ...options, userId, apiKey }));
@@ -68,6 +109,23 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
68
109
  });
69
110
  await super._init(reactNativeOptions);
70
111
 
112
+ // Step 2.1: parse autocapture config (always reset so re-init clears prior flags)
113
+ const autocaptureConfig = (this.config as ReactNativeConfigAutocaptureBeta).autocapture;
114
+ if (autocaptureConfig === true) {
115
+ this.autocapture = {
116
+ appLifecycles: true,
117
+ sessions: true,
118
+ };
119
+ } else if (autocaptureConfig && typeof autocaptureConfig === 'object') {
120
+ this.autocapture = autocaptureConfig;
121
+ } else {
122
+ this.autocapture = null;
123
+ }
124
+ // Drop any background seen before this init so Opened cannot fire unpaired.
125
+ this.wasBackgrounded = false;
126
+ // Allow the first navigation screen view after re-init.
127
+ this.lastNavigationScreenName = undefined;
128
+
71
129
  // Set up the analytics connector to integrate with the experiment SDK.
72
130
  // Send events from the experiment SDK and forward identifies to the
73
131
  // identity store.
@@ -100,7 +158,15 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
100
158
 
101
159
  this.initializing = false;
102
160
 
103
- // Step 5: Track attributions
161
+ // Step 5: autocapture
162
+
163
+ // Step 5.1: track Application Opened when already foregrounded at init (cold start).
164
+ // Do not await — track().promise waits on flush/network and would block init.
165
+ if (this.autocapture?.appLifecycles === true && this.appState === 'active') {
166
+ this.track('[Amplitude] Application Opened');
167
+ }
168
+
169
+ // Step 5.2: run attribution strategy
104
170
  await this.runAttributionStrategy(options.attribution, isNewSession);
105
171
 
106
172
  // Step 6: Run queued functions
@@ -173,6 +239,8 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
173
239
  reset() {
174
240
  this.setUserId(undefined);
175
241
  this.setDeviceId(UUID());
242
+ // Allow the current focused route to emit again for the new identity.
243
+ this.lastNavigationScreenName = undefined;
176
244
  }
177
245
 
178
246
  getSessionId() {
@@ -209,6 +277,37 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
209
277
  this.config.lastEventTime = this.currentTimeMillis();
210
278
  }
211
279
 
280
+ trackScreenView(screenName: string, eventProperties?: Record<string, any>, eventOptions?: EventOptions) {
281
+ const isScreenViewTrackingDisabled = this.autocapture?.screenViews === false;
282
+ if (isScreenViewTrackingDisabled) {
283
+ return returnWrapper(Promise.resolve(undefined));
284
+ }
285
+ return this.track(
286
+ DEFAULT_SCREEN_VIEWED_EVENT,
287
+ {
288
+ [SCREEN_NAME]: screenName,
289
+ ...eventProperties,
290
+ },
291
+ eventOptions,
292
+ );
293
+ }
294
+
295
+ trackScreenViewOnNavigationStateChange(
296
+ navigationState: NavigationState | undefined,
297
+ eventProperties?: Record<string, any>,
298
+ eventOptions?: EventOptions,
299
+ ) {
300
+ if (!navigationState) {
301
+ return returnWrapper(Promise.resolve(undefined));
302
+ }
303
+ const screenName = getActiveRouteName(navigationState);
304
+ if (!screenName || screenName === this.lastNavigationScreenName) {
305
+ return returnWrapper(Promise.resolve(undefined));
306
+ }
307
+ this.lastNavigationScreenName = screenName;
308
+ return this.trackScreenView(screenName, eventProperties, eventOptions);
309
+ }
310
+
212
311
  private setSessionIdInternal(sessionId: number, eventTime: number) {
213
312
  const previousSessionId = this.config.sessionId;
214
313
  if (previousSessionId === sessionId) {
@@ -217,12 +316,12 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
217
316
 
218
317
  this.config.sessionId = sessionId;
219
318
 
220
- if (this.config.trackingSessionEvents) {
319
+ if (this.config.trackingSessionEvents || this.autocapture?.sessions) {
221
320
  this.config.loggerProvider?.log(`SESSION_END event: previousSessionId = ${previousSessionId ?? 'undefined'}`);
222
321
 
223
322
  if (previousSessionId !== undefined) {
224
323
  const sessionEndEvent: Event = {
225
- event_type: END_SESSION_EVENT,
324
+ event_type: DEFAULT_SESSION_END_EVENT,
226
325
  time: this.config.lastEventTime !== undefined ? this.config.lastEventTime + 1 : sessionId, // increment lastEventTime to sort events properly in UI - session_end should be the last event in a session
227
326
  session_id: previousSessionId,
228
327
  };
@@ -231,7 +330,7 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
231
330
 
232
331
  this.config.loggerProvider?.log(`SESSION_START event: sessionId = ${sessionId}`);
233
332
  const sessionStartEvent: Event = {
234
- event_type: START_SESSION_EVENT,
333
+ event_type: DEFAULT_SESSION_START_EVENT,
235
334
  time: eventTime,
236
335
  session_id: sessionId,
237
336
  };
@@ -248,7 +347,8 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
248
347
  event = { ...event, time: eventTime };
249
348
  }
250
349
 
251
- const isSessionEvent = event.event_type === START_SESSION_EVENT || event.event_type === END_SESSION_EVENT;
350
+ const isSessionEvent =
351
+ event.event_type === DEFAULT_SESSION_START_EVENT || event.event_type === DEFAULT_SESSION_END_EVENT;
252
352
  const isCustomEventSessionId =
253
353
  !isSessionEvent && event.session_id != undefined && event.session_id !== this.getSessionId();
254
354
  if (!isCustomEventSessionId) {
@@ -324,11 +424,21 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
324
424
  } else {
325
425
  this.exitForeground(timestamp);
326
426
  }
427
+ if (nextAppState == 'background' && this.autocapture?.appLifecycles === true) {
428
+ // Only remember background when we also emit Backgrounded, so Opened stays paired.
429
+ this.wasBackgrounded = true;
430
+ this.track(DEFAULT_APPLICATION_BACKGROUNDED_EVENT);
431
+ }
327
432
  }
328
433
  };
329
434
 
330
435
  private enterForeground(timestamp: number) {
331
436
  this.config.loggerProvider?.log('App Activated');
437
+ // Only emit Application Opened after a real background (not inactive→active).
438
+ if (this.autocapture?.appLifecycles === true && this.wasBackgrounded) {
439
+ this.track(DEFAULT_APPLICATION_OPENED_EVENT);
440
+ }
441
+ this.wasBackgrounded = false;
332
442
  return this.startNewSessionIfNeeded(timestamp);
333
443
  }
334
444
 
@@ -340,6 +450,19 @@ export class AmplitudeReactNative extends AmplitudeCore implements ReactNativeCl
340
450
  export const createInstance = (): ReactNativeClient => {
341
451
  const client = new AmplitudeReactNative();
342
452
  return {
453
+ ...client,
454
+ trackScreenView: debugWrapper(
455
+ client.trackScreenView.bind(client),
456
+ 'trackScreenView',
457
+ getClientLogConfig(client),
458
+ getClientStates(client, ['config.apiKey', 'timeline.queue.length']),
459
+ ),
460
+ trackScreenViewOnNavigationStateChange: debugWrapper(
461
+ client.trackScreenViewOnNavigationStateChange.bind(client),
462
+ 'trackScreenViewOnNavigationStateChange',
463
+ getClientLogConfig(client),
464
+ getClientStates(client, ['config.apiKey', 'timeline.queue.length']),
465
+ ),
343
466
  init: debugWrapper(
344
467
  client.init.bind(client),
345
468
  'init',
package/src/types.ts CHANGED
@@ -4,6 +4,7 @@ export {
4
4
  BaseEvent,
5
5
  EventOptions,
6
6
  ReactNativeClient,
7
+ NavigationState,
7
8
  ReactNativeAttributionOptions,
8
9
  ReactNativeOptions,
9
10
  ReactNativeConfig,
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const VERSION = '1.6.5';
1
+ export const VERSION = '1.6.6';