UNPKG

12.8 kBJavaScriptView Raw
1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3import { __assign, __awaiter, __generator } from "tslib";
4import { Amplify, ConsoleLogger as Logger, Hub, parseAWSExports, } from '@aws-amplify/core';
5import { AWSPinpointProvider } from './Providers/AWSPinpointProvider';
6import { PageViewTracker, EventTracker, SessionTracker } from './trackers';
7var logger = new Logger('AnalyticsClass');
8var AMPLIFY_SYMBOL = (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function'
9 ? Symbol.for('amplify_default')
10 : '@@amplify_default');
11var dispatchAnalyticsEvent = function (event, data, message) {
12 Hub.dispatch('analytics', { event: event, data: data, message: message }, 'Analytics', AMPLIFY_SYMBOL);
13};
14var trackers = {
15 pageView: PageViewTracker,
16 event: EventTracker,
17 session: SessionTracker,
18};
19var _instance = null;
20/**
21 * Provide mobile analytics client functions
22 */
23var AnalyticsClass = /** @class */ (function () {
24 /**
25 * Initialize Analtyics
26 * @param config - Configuration of the Analytics
27 */
28 function AnalyticsClass() {
29 this._config = {};
30 this._pluggables = [];
31 this._disabled = false;
32 this._trackers = {};
33 _instance = this;
34 this.record = this.record.bind(this);
35 Hub.listen('auth', listener);
36 Hub.listen('storage', listener);
37 Hub.listen('analytics', listener);
38 Hub.listen('core', listener);
39 }
40 AnalyticsClass.prototype.getModuleName = function () {
41 return 'Analytics';
42 };
43 /**
44 * configure Analytics
45 * @param {Object} config - Configuration of the Analytics
46 */
47 AnalyticsClass.prototype.configure = function (config) {
48 var _this = this;
49 if (!config)
50 return this._config;
51 logger.debug('configure Analytics', config);
52 var amplifyConfig = parseAWSExports(config);
53 this._config = Object.assign({}, this._config, amplifyConfig.Analytics, config);
54 if (this._config['disabled']) {
55 this._disabled = true;
56 }
57 // turn on the autoSessionRecord if not specified
58 if (this._config['autoSessionRecord'] === undefined) {
59 this._config['autoSessionRecord'] = true;
60 }
61 this._pluggables.forEach(function (pluggable) {
62 // for backward compatibility
63 var providerConfig = pluggable.getProviderName() === 'AWSPinpoint' &&
64 !_this._config['AWSPinpoint']
65 ? _this._config
66 : _this._config[pluggable.getProviderName()];
67 pluggable.configure(__assign({ disabled: _this._config['disabled'], autoSessionRecord: _this._config['autoSessionRecord'] }, providerConfig));
68 });
69 if (this._pluggables.length === 0) {
70 this.addPluggable(new AWSPinpointProvider());
71 }
72 dispatchAnalyticsEvent('configured', null, "The Analytics category has been configured successfully");
73 logger.debug('current configuration', this._config);
74 return this._config;
75 };
76 /**
77 * add plugin into Analytics category
78 * @param pluggable - an instance of the plugin
79 */
80 AnalyticsClass.prototype.addPluggable = function (pluggable) {
81 if (pluggable && pluggable.getCategory() === 'Analytics') {
82 this._pluggables.push(pluggable);
83 // for backward compatibility
84 var providerConfig = pluggable.getProviderName() === 'AWSPinpoint' &&
85 !this._config['AWSPinpoint']
86 ? this._config
87 : this._config[pluggable.getProviderName()];
88 var config = __assign({ disabled: this._config['disabled'] }, providerConfig);
89 pluggable.configure(config);
90 return config;
91 }
92 };
93 /**
94 * Get the plugin object
95 * @param providerName - the name of the provider to be removed
96 */
97 AnalyticsClass.prototype.getPluggable = function (providerName) {
98 for (var i = 0; i < this._pluggables.length; i += 1) {
99 var pluggable = this._pluggables[i];
100 if (pluggable.getProviderName() === providerName) {
101 return pluggable;
102 }
103 }
104 logger.debug('No plugin found with providerName', providerName);
105 return null;
106 };
107 /**
108 * Remove the plugin object
109 * @param providerName - the name of the provider to be removed
110 */
111 AnalyticsClass.prototype.removePluggable = function (providerName) {
112 var idx = 0;
113 while (idx < this._pluggables.length) {
114 if (this._pluggables[idx].getProviderName() === providerName) {
115 break;
116 }
117 idx += 1;
118 }
119 if (idx === this._pluggables.length) {
120 logger.debug('No plugin found with providerName', providerName);
121 return;
122 }
123 else {
124 this._pluggables.splice(idx, idx + 1);
125 return;
126 }
127 };
128 /**
129 * stop sending events
130 */
131 AnalyticsClass.prototype.disable = function () {
132 this._disabled = true;
133 };
134 /**
135 * start sending events
136 */
137 AnalyticsClass.prototype.enable = function () {
138 this._disabled = false;
139 };
140 /**
141 * Record Session start
142 * @param [provider] - name of the provider.
143 * @return - A promise which resolves if buffer doesn't overflow
144 */
145 AnalyticsClass.prototype.startSession = function (provider) {
146 return __awaiter(this, void 0, void 0, function () {
147 var event, params;
148 return __generator(this, function (_a) {
149 event = { name: '_session.start' };
150 params = { event: event, provider: provider };
151 dispatchAnalyticsEvent('record', event, 'Recording Analytics session start event');
152 return [2 /*return*/, this._sendEvent(params)];
153 });
154 });
155 };
156 /**
157 * Record Session stop
158 * @param [provider] - name of the provider.
159 * @return - A promise which resolves if buffer doesn't overflow
160 */
161 AnalyticsClass.prototype.stopSession = function (provider) {
162 return __awaiter(this, void 0, void 0, function () {
163 var event, params;
164 return __generator(this, function (_a) {
165 event = { name: '_session.stop' };
166 params = { event: event, provider: provider };
167 dispatchAnalyticsEvent('record', event, 'Recording Analytics session stop event');
168 return [2 /*return*/, this._sendEvent(params)];
169 });
170 });
171 };
172 /**
173 * Record one analytic event and send it to Pinpoint
174 * @param event - An object with the name of the event, attributes of the event and event metrics.
175 * @param [provider] - name of the provider.
176 */
177 AnalyticsClass.prototype.record = function (event, provider) {
178 return __awaiter(this, void 0, void 0, function () {
179 var params;
180 return __generator(this, function (_a) {
181 params = { event: event, provider: provider };
182 dispatchAnalyticsEvent('record', params.event, 'Recording Analytics event');
183 return [2 /*return*/, this._sendEvent(params)];
184 });
185 });
186 };
187 AnalyticsClass.prototype.updateEndpoint = function (attrs, provider) {
188 return __awaiter(this, void 0, void 0, function () {
189 var event;
190 return __generator(this, function (_a) {
191 event = __assign(__assign({}, attrs), { name: '_update_endpoint' });
192 return [2 /*return*/, this.record(event, provider)];
193 });
194 });
195 };
196 AnalyticsClass.prototype._sendEvent = function (params) {
197 var _this = this;
198 if (this._disabled) {
199 logger.debug('Analytics has been disabled');
200 return Promise.resolve();
201 }
202 var provider = params.provider ? params.provider : 'AWSPinpoint';
203 return new Promise(function (resolve, reject) {
204 _this._pluggables.forEach(function (pluggable) {
205 if (pluggable.getProviderName() === provider) {
206 pluggable.record(params, { resolve: resolve, reject: reject });
207 }
208 });
209 });
210 };
211 AnalyticsClass.prototype.autoTrack = function (trackerType, opts) {
212 if (!trackers[trackerType]) {
213 logger.debug('invalid tracker type');
214 return;
215 }
216 // to sync up two different configuration ways of auto session tracking
217 if (trackerType === 'session') {
218 this._config['autoSessionRecord'] = opts['enable'];
219 }
220 var tracker = this._trackers[trackerType];
221 if (!tracker) {
222 this._trackers[trackerType] = new trackers[trackerType](this.record, opts);
223 }
224 else {
225 tracker.configure(opts);
226 }
227 };
228 return AnalyticsClass;
229}());
230export { AnalyticsClass };
231var endpointUpdated = false;
232var authConfigured = false;
233var analyticsConfigured = false;
234var credentialsConfigured = false;
235var listener = function (capsule) {
236 var channel = capsule.channel, payload = capsule.payload;
237 logger.debug('on hub capsule ' + channel, payload);
238 switch (channel) {
239 case 'auth':
240 authEvent(payload);
241 break;
242 case 'storage':
243 storageEvent(payload);
244 break;
245 case 'analytics':
246 analyticsEvent(payload);
247 break;
248 case 'core':
249 coreEvent(payload);
250 break;
251 default:
252 break;
253 }
254};
255var storageEvent = function (payload) {
256 var _a = payload.data, attrs = _a.attrs, metrics = _a.metrics;
257 if (!attrs)
258 return;
259 if (analyticsConfigured) {
260 _instance
261 .record({
262 name: 'Storage',
263 attributes: attrs,
264 metrics: metrics,
265 })
266 .catch(function (e) {
267 logger.debug('Failed to send the storage event automatically', e);
268 });
269 }
270};
271var authEvent = function (payload) {
272 var event = payload.event;
273 if (!event) {
274 return;
275 }
276 var recordAuthEvent = function (eventName) { return __awaiter(void 0, void 0, void 0, function () {
277 var err_1;
278 return __generator(this, function (_a) {
279 switch (_a.label) {
280 case 0:
281 if (!(authConfigured && analyticsConfigured)) return [3 /*break*/, 4];
282 _a.label = 1;
283 case 1:
284 _a.trys.push([1, 3, , 4]);
285 return [4 /*yield*/, _instance.record({ name: "_userauth." + eventName })];
286 case 2: return [2 /*return*/, _a.sent()];
287 case 3:
288 err_1 = _a.sent();
289 logger.debug("Failed to send the " + eventName + " event automatically", err_1);
290 return [3 /*break*/, 4];
291 case 4: return [2 /*return*/];
292 }
293 });
294 }); };
295 switch (event) {
296 case 'signIn':
297 return recordAuthEvent('sign_in');
298 case 'signUp':
299 return recordAuthEvent('sign_up');
300 case 'signOut':
301 return recordAuthEvent('sign_out');
302 case 'signIn_failure':
303 return recordAuthEvent('auth_fail');
304 case 'configured':
305 authConfigured = true;
306 if (analyticsConfigured) {
307 sendEvents();
308 }
309 break;
310 }
311};
312var analyticsEvent = function (payload) {
313 var event = payload.event;
314 if (!event)
315 return;
316 switch (event) {
317 case 'pinpointProvider_configured':
318 analyticsConfigured = true;
319 if (authConfigured || credentialsConfigured) {
320 sendEvents();
321 }
322 break;
323 }
324};
325var coreEvent = function (payload) {
326 var event = payload.event;
327 if (!event)
328 return;
329 switch (event) {
330 case 'credentials_configured':
331 credentialsConfigured = true;
332 if (analyticsConfigured) {
333 sendEvents();
334 }
335 break;
336 }
337};
338var sendEvents = function () {
339 var config = _instance.configure();
340 if (!endpointUpdated && config['autoSessionRecord']) {
341 _instance.updateEndpoint({ immediate: true }).catch(function (e) {
342 logger.debug('Failed to update the endpoint', e);
343 });
344 endpointUpdated = true;
345 }
346 _instance.autoTrack('session', {
347 enable: config['autoSessionRecord'],
348 });
349};
350export var Analytics = new AnalyticsClass();
351Amplify.register(Analytics);
352//# sourceMappingURL=Analytics.js.map
\No newline at end of file