UNPKG

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