-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Analytics.ts
446 lines (392 loc) · 10.2 KB
/
Analytics.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import {
Amplify,
ConsoleLogger as Logger,
Hub,
parseAWSExports,
} from '@aws-amplify/core';
import { AWSPinpointProvider } from './Providers/AWSPinpointProvider';
import {
AnalyticsProvider,
EventAttributes,
EventMetrics,
AnalyticsEvent,
AutoTrackSessionOpts,
AutoTrackPageViewOpts,
AutoTrackEventOpts,
PersonalizeAnalyticsEvent,
KinesisAnalyticsEvent,
} from './types';
import { PageViewTracker, EventTracker, SessionTracker } from './trackers';
const logger = new Logger('AnalyticsClass');
const AMPLIFY_SYMBOL = (
typeof Symbol !== 'undefined' && typeof Symbol.for === 'function'
? Symbol.for('amplify_default')
: '@@amplify_default'
) as Symbol;
const dispatchAnalyticsEvent = (event: string, data: any, message: string) => {
Hub.dispatch(
'analytics',
{ event, data, message },
'Analytics',
AMPLIFY_SYMBOL
);
};
const trackers = {
pageView: PageViewTracker,
event: EventTracker,
session: SessionTracker,
};
type TrackerTypes = keyof typeof trackers;
type Trackers = (typeof trackers)[TrackerTypes];
let _instance = null;
/**
* Provide mobile analytics client functions
*/
export class AnalyticsClass {
private _config;
private _pluggables: AnalyticsProvider[];
private _disabled: boolean;
private _trackers: Trackers | {};
/**
* Initialize Analtyics
* @param config - Configuration of the Analytics
*/
constructor() {
this._config = {};
this._pluggables = [];
this._disabled = false;
this._trackers = {};
_instance = this;
this.record = this.record.bind(this);
Hub.listen('auth', listener);
Hub.listen('storage', listener);
Hub.listen('analytics', listener);
Hub.listen('core', listener);
}
public getModuleName() {
return 'Analytics';
}
/**
* configure Analytics
* @param {Object} config - Configuration of the Analytics
*/
public configure(config?) {
if (!config) return this._config;
logger.debug('configure Analytics', config);
const amplifyConfig = parseAWSExports(config);
this._config = Object.assign(
{},
this._config,
amplifyConfig.Analytics,
config
);
if (this._config['disabled']) {
this._disabled = true;
}
// turn on the autoSessionRecord if not specified
if (this._config['autoSessionRecord'] === undefined) {
this._config['autoSessionRecord'] = true;
}
this._pluggables.forEach(pluggable => {
// for backward compatibility
const providerConfig =
pluggable.getProviderName() === 'AWSPinpoint' &&
!this._config['AWSPinpoint']
? this._config
: this._config[pluggable.getProviderName()];
pluggable.configure({
disabled: this._config['disabled'],
autoSessionRecord: this._config['autoSessionRecord'],
...providerConfig,
});
});
if (this._pluggables.length === 0) {
this.addPluggable(new AWSPinpointProvider());
}
dispatchAnalyticsEvent(
'configured',
null,
`The Analytics category has been configured successfully`
);
logger.debug('current configuration', this._config);
return this._config;
}
/**
* add plugin into Analytics category
* @param pluggable - an instance of the plugin
*/
public addPluggable(pluggable: AnalyticsProvider) {
if (pluggable && pluggable.getCategory() === 'Analytics') {
this._pluggables.push(pluggable);
// for backward compatibility
const providerConfig =
pluggable.getProviderName() === 'AWSPinpoint' &&
!this._config['AWSPinpoint']
? this._config
: this._config[pluggable.getProviderName()];
const config = { disabled: this._config['disabled'], ...providerConfig };
pluggable.configure(config);
return config;
}
}
/**
* Get the plugin object
* @param providerName - the name of the provider to be removed
*/
public getPluggable(providerName: string): AnalyticsProvider {
for (let i = 0; i < this._pluggables.length; i += 1) {
const pluggable = this._pluggables[i];
if (pluggable.getProviderName() === providerName) {
return pluggable;
}
}
logger.debug('No plugin found with providerName', providerName);
return null;
}
/**
* Remove the plugin object
* @param providerName - the name of the provider to be removed
*/
public removePluggable(providerName: string): void {
let idx = 0;
while (idx < this._pluggables.length) {
if (this._pluggables[idx].getProviderName() === providerName) {
break;
}
idx += 1;
}
if (idx === this._pluggables.length) {
logger.debug('No plugin found with providerName', providerName);
return;
} else {
this._pluggables.splice(idx, idx + 1);
return;
}
}
/**
* stop sending events
*/
public disable() {
this._disabled = true;
}
/**
* start sending events
*/
public enable() {
this._disabled = false;
}
/**
* Record Session start
* @param [provider] - name of the provider.
* @return - A promise which resolves if buffer doesn't overflow
*/
public async startSession(provider?: string) {
const event = { name: '_session.start' };
const params = { event, provider };
dispatchAnalyticsEvent(
'record',
event,
'Recording Analytics session start event'
);
return this._sendEvent(params);
}
/**
* Record Session stop
* @param [provider] - name of the provider.
* @return - A promise which resolves if buffer doesn't overflow
*/
public async stopSession(provider?: string) {
const event = { name: '_session.stop' };
const params = { event, provider };
dispatchAnalyticsEvent(
'record',
event,
'Recording Analytics session stop event'
);
return this._sendEvent(params);
}
/**
* Record one analytic event and send it to Pinpoint
* @param event - An object with the name of the event, attributes of the event and event metrics.
* @param [provider] - name of the provider.
*/
public async record(
event: AnalyticsEvent | PersonalizeAnalyticsEvent | KinesisAnalyticsEvent,
provider?: string
) {
const params = { event, provider };
dispatchAnalyticsEvent('record', params.event, 'Recording Analytics event');
return this._sendEvent(params);
}
public async updateEndpoint(
attrs: { [key: string]: any },
provider?: string
) {
const event = { ...attrs, name: '_update_endpoint' };
return this.record(event, provider);
}
private _sendEvent(params: {
event: AnalyticsEvent | PersonalizeAnalyticsEvent | KinesisAnalyticsEvent;
provider?: string;
}) {
if (this._disabled) {
logger.debug('Analytics has been disabled');
return Promise.resolve();
}
const provider = params.provider ? params.provider : 'AWSPinpoint';
return new Promise((resolve, reject) => {
this._pluggables.forEach(pluggable => {
if (pluggable.getProviderName() === provider) {
pluggable.record(params, { resolve, reject });
}
});
});
}
/**
* Enable or disable auto tracking
* @param trackerType - The type of tracker to activate.
* @param [opts] - Auto tracking options.
*/
public autoTrack(trackerType: 'session', opts: AutoTrackSessionOpts);
public autoTrack(trackerType: 'pageView', opts: AutoTrackPageViewOpts);
public autoTrack(trackerType: 'event', opts: AutoTrackEventOpts);
// ensures backwards compatibility for non-pinpoint provider users
public autoTrack(
trackerType: TrackerTypes,
opts: { provider: string; [key: string]: any }
);
public autoTrack(trackerType: TrackerTypes, opts: { [key: string]: any }) {
if (!trackers[trackerType]) {
logger.debug('invalid tracker type');
return;
}
// to sync up two different configuration ways of auto session tracking
if (trackerType === 'session') {
this._config['autoSessionRecord'] = opts['enable'];
}
const tracker = this._trackers[trackerType];
if (!tracker) {
this._trackers[trackerType] = new trackers[trackerType](
this.record,
opts
);
} else {
tracker.configure(opts);
}
}
}
let endpointUpdated = false;
let authConfigured = false;
let analyticsConfigured = false;
let credentialsConfigured = false;
const listener = capsule => {
const { channel, payload } = capsule;
logger.debug('on hub capsule ' + channel, payload);
switch (channel) {
case 'auth':
authEvent(payload);
break;
case 'storage':
storageEvent(payload);
break;
case 'analytics':
analyticsEvent(payload);
break;
case 'core':
coreEvent(payload);
break;
default:
break;
}
};
const storageEvent = payload => {
const {
data: { attrs, metrics },
} = payload;
if (!attrs) return;
if (analyticsConfigured) {
_instance
.record({
name: 'Storage',
attributes: attrs,
metrics,
})
.catch(e => {
logger.debug('Failed to send the storage event automatically', e);
});
}
};
const authEvent = payload => {
const { event } = payload;
if (!event) {
return;
}
const recordAuthEvent = async eventName => {
if (authConfigured && analyticsConfigured) {
try {
return await _instance.record({ name: `_userauth.${eventName}` });
} catch (err) {
logger.debug(
`Failed to send the ${eventName} event automatically`,
err
);
}
}
};
switch (event) {
case 'signIn':
return recordAuthEvent('sign_in');
case 'signUp':
return recordAuthEvent('sign_up');
case 'signOut':
return recordAuthEvent('sign_out');
case 'signIn_failure':
return recordAuthEvent('auth_fail');
case 'configured':
authConfigured = true;
if (analyticsConfigured) {
sendEvents();
}
break;
}
};
const analyticsEvent = payload => {
const { event } = payload;
if (!event) return;
switch (event) {
case 'pinpointProvider_configured':
analyticsConfigured = true;
if (authConfigured || credentialsConfigured) {
sendEvents();
}
break;
}
};
const coreEvent = payload => {
const { event } = payload;
if (!event) return;
switch (event) {
case 'credentials_configured':
credentialsConfigured = true;
if (analyticsConfigured) {
sendEvents();
}
break;
}
};
const sendEvents = () => {
const config = _instance.configure();
if (!endpointUpdated && config['autoSessionRecord']) {
_instance.updateEndpoint({ immediate: true }).catch(e => {
logger.debug('Failed to update the endpoint', e);
});
endpointUpdated = true;
}
_instance.autoTrack('session', {
enable: config['autoSessionRecord'],
});
};
export const Analytics = new AnalyticsClass();
Amplify.register(Analytics);