1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | var __assign = (this && this.__assign) || function () {
|
14 | __assign = Object.assign || function(t) {
|
15 | for (var s, i = 1, n = arguments.length; i < n; i++) {
|
16 | s = arguments[i];
|
17 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
|
18 | t[p] = s[p];
|
19 | }
|
20 | return t;
|
21 | };
|
22 | return __assign.apply(this, arguments);
|
23 | };
|
24 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
25 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
26 | return new (P || (P = Promise))(function (resolve, reject) {
|
27 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
28 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
29 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
30 | step((generator = generator.apply(thisArg, _arguments || [])).next());
|
31 | });
|
32 | };
|
33 | var __generator = (this && this.__generator) || function (thisArg, body) {
|
34 | var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
|
35 | return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
36 | function verb(n) { return function (v) { return step([n, v]); }; }
|
37 | function step(op) {
|
38 | if (f) throw new TypeError("Generator is already executing.");
|
39 | while (_) try {
|
40 | if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
41 | if (y = 0, t) op = [op[0] & 2, t.value];
|
42 | switch (op[0]) {
|
43 | case 0: case 1: t = op; break;
|
44 | case 4: _.label++; return { value: op[1], done: false };
|
45 | case 5: _.label++; y = op[1]; op = [0]; continue;
|
46 | case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
47 | default:
|
48 | if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
49 | if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
50 | if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
51 | if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
52 | if (t[2]) _.ops.pop();
|
53 | _.trys.pop(); continue;
|
54 | }
|
55 | op = body.call(thisArg, _);
|
56 | } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
57 | if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
58 | }
|
59 | };
|
60 | var __rest = (this && this.__rest) || function (s, e) {
|
61 | var t = {};
|
62 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
63 | t[p] = s[p];
|
64 | if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
65 | for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
66 | if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
67 | t[p[i]] = s[p[i]];
|
68 | }
|
69 | return t;
|
70 | };
|
71 | import { ConsoleLogger as Logger, ClientDevice, Credentials, Signer, JS, Hub, getAmplifyUserAgent, } from '@aws-amplify/core';
|
72 | import { PinpointClient, PutEventsCommand, UpdateEndpointCommand, } from '@aws-sdk/client-pinpoint';
|
73 | import Cache from '@aws-amplify/cache';
|
74 | import { v1 as uuid } from 'uuid';
|
75 | import EventsBuffer from './EventBuffer';
|
76 | var AMPLIFY_SYMBOL = (typeof Symbol !== 'undefined' &&
|
77 | typeof Symbol.for === 'function'
|
78 | ? Symbol.for('amplify_default')
|
79 | : '@@amplify_default');
|
80 | var dispatchAnalyticsEvent = function (event, data) {
|
81 | Hub.dispatch('analytics', { event: event, data: data }, 'Analytics', AMPLIFY_SYMBOL);
|
82 | };
|
83 | var logger = new Logger('AWSPinpointProvider');
|
84 | var RETRYABLE_CODES = [429, 500];
|
85 | var ACCEPTED_CODES = [202];
|
86 | var FORBIDDEN_CODE = 403;
|
87 | var MOBILE_SERVICE_NAME = 'mobiletargeting';
|
88 | var EXPIRED_TOKEN_CODE = 'ExpiredTokenException';
|
89 | var UPDATE_ENDPOINT = '_update_endpoint';
|
90 | var SESSION_START = '_session.start';
|
91 | var SESSION_STOP = '_session.stop';
|
92 | var BEACON_SUPPORTED = typeof navigator !== 'undefined' &&
|
93 | navigator &&
|
94 | typeof navigator.sendBeacon === 'function';
|
95 |
|
96 | var BUFFER_SIZE = 1000;
|
97 | var FLUSH_SIZE = 100;
|
98 | var FLUSH_INTERVAL = 5 * 1000;
|
99 | var RESEND_LIMIT = 5;
|
100 |
|
101 | var AWSPinpointProvider = (function () {
|
102 | function AWSPinpointProvider(config) {
|
103 | this._endpointGenerating = true;
|
104 | this._endpointUpdateInProgress = false;
|
105 | this._buffer = null;
|
106 | this._endpointBuffer = [];
|
107 | this._config = config ? config : {};
|
108 | this._config.bufferSize = this._config.bufferSize || BUFFER_SIZE;
|
109 | this._config.flushSize = this._config.flushSize || FLUSH_SIZE;
|
110 | this._config.flushInterval = this._config.flushInterval || FLUSH_INTERVAL;
|
111 | this._config.resendLimit = this._config.resendLimit || RESEND_LIMIT;
|
112 | this._clientInfo = ClientDevice.clientInfo();
|
113 | }
|
114 | |
115 |
|
116 |
|
117 | AWSPinpointProvider.prototype.getCategory = function () {
|
118 | return AWSPinpointProvider.category;
|
119 | };
|
120 | |
121 |
|
122 |
|
123 | AWSPinpointProvider.prototype.getProviderName = function () {
|
124 | return AWSPinpointProvider.providerName;
|
125 | };
|
126 | |
127 |
|
128 |
|
129 |
|
130 | AWSPinpointProvider.prototype.configure = function (config) {
|
131 | var _this = this;
|
132 | logger.debug('configure Analytics', config);
|
133 | var conf = config || {};
|
134 | this._config = Object.assign({}, this._config, conf);
|
135 |
|
136 |
|
137 | this._endpointGenerating = !!config['autoSessionRecord'];
|
138 | if (this._config.appId && !this._config.disabled) {
|
139 | if (!this._config.endpointId) {
|
140 | var cacheKey = this.getProviderName() + '_' + this._config.appId;
|
141 | this._getEndpointId(cacheKey)
|
142 | .then(function (endpointId) {
|
143 | logger.debug('setting endpoint id from the cache', endpointId);
|
144 | _this._config.endpointId = endpointId;
|
145 | dispatchAnalyticsEvent('pinpointProvider_configured', null);
|
146 | })
|
147 | .catch(function (err) {
|
148 | logger.debug('Failed to generate endpointId', err);
|
149 | });
|
150 | }
|
151 | else {
|
152 | dispatchAnalyticsEvent('pinpointProvider_configured', null);
|
153 | }
|
154 | }
|
155 | else {
|
156 | this._flushBuffer();
|
157 | }
|
158 | return this._config;
|
159 | };
|
160 | |
161 |
|
162 |
|
163 |
|
164 | AWSPinpointProvider.prototype.record = function (params, handlers) {
|
165 | return __awaiter(this, void 0, void 0, function () {
|
166 | var credentials, timestamp;
|
167 | return __generator(this, function (_a) {
|
168 | switch (_a.label) {
|
169 | case 0:
|
170 | logger.debug('_public record', params);
|
171 | return [4 , this._getCredentials()];
|
172 | case 1:
|
173 | credentials = _a.sent();
|
174 | if (!credentials || !this._config.appId || !this._config.region) {
|
175 | logger.debug('cannot send events without credentials, applicationId or region');
|
176 | return [2 , handlers.reject(new Error('No credentials, applicationId or region'))];
|
177 | }
|
178 | this._initClients(credentials);
|
179 | timestamp = new Date().getTime();
|
180 |
|
181 | this._generateSession(params);
|
182 | params.event.eventId = uuid();
|
183 | Object.assign(params, { timestamp: timestamp, config: this._config });
|
184 | if (params.event.immediate) {
|
185 | return [2 , this._send(params, handlers)];
|
186 | }
|
187 | else {
|
188 | this._putToBuffer(params, handlers);
|
189 | }
|
190 | return [2 ];
|
191 | }
|
192 | });
|
193 | });
|
194 | };
|
195 | AWSPinpointProvider.prototype._sendEndpointUpdate = function (endpointObject) {
|
196 | return __awaiter(this, void 0, void 0, function () {
|
197 | var next;
|
198 | return __generator(this, function (_a) {
|
199 | switch (_a.label) {
|
200 | case 0:
|
201 | if (this._endpointUpdateInProgress) {
|
202 | this._endpointBuffer.push(endpointObject);
|
203 | return [2 ];
|
204 | }
|
205 | this._endpointUpdateInProgress = true;
|
206 | return [4 , this._updateEndpoint(endpointObject)];
|
207 | case 1:
|
208 | _a.sent();
|
209 | next = this._endpointBuffer.shift();
|
210 | this._endpointUpdateInProgress = false;
|
211 | next && this._sendEndpointUpdate(next);
|
212 | return [2 ];
|
213 | }
|
214 | });
|
215 | });
|
216 | };
|
217 | |
218 |
|
219 |
|
220 |
|
221 |
|
222 | AWSPinpointProvider.prototype._putToBuffer = function (params, handlers) {
|
223 | if (params.event.name === UPDATE_ENDPOINT) {
|
224 | this._sendEndpointUpdate({ params: params, handlers: handlers });
|
225 | return;
|
226 | }
|
227 | this._buffer && this._buffer.push({ params: params, handlers: handlers });
|
228 | };
|
229 | AWSPinpointProvider.prototype._generateSession = function (params) {
|
230 | this._sessionId = this._sessionId || uuid();
|
231 | var event = params.event;
|
232 | switch (event.name) {
|
233 | case SESSION_START:
|
234 |
|
235 | this._sessionStartTimestamp = new Date().getTime();
|
236 | this._sessionId = uuid();
|
237 | event.session = {
|
238 | Id: this._sessionId,
|
239 | StartTimestamp: new Date(this._sessionStartTimestamp).toISOString(),
|
240 | };
|
241 | break;
|
242 | case SESSION_STOP:
|
243 | var stopTimestamp = new Date().getTime();
|
244 | this._sessionStartTimestamp =
|
245 | this._sessionStartTimestamp || new Date().getTime();
|
246 | this._sessionId = this._sessionId || uuid();
|
247 | event.session = {
|
248 | Id: this._sessionId,
|
249 | Duration: stopTimestamp - this._sessionStartTimestamp,
|
250 | StartTimestamp: new Date(this._sessionStartTimestamp).toISOString(),
|
251 | StopTimestamp: new Date(stopTimestamp).toISOString(),
|
252 | };
|
253 | this._sessionId = undefined;
|
254 | this._sessionStartTimestamp = undefined;
|
255 | break;
|
256 | default:
|
257 | this._sessionStartTimestamp =
|
258 | this._sessionStartTimestamp || new Date().getTime();
|
259 | this._sessionId = this._sessionId || uuid();
|
260 | event.session = {
|
261 | Id: this._sessionId,
|
262 | StartTimestamp: new Date(this._sessionStartTimestamp).toISOString(),
|
263 | };
|
264 | }
|
265 | };
|
266 | AWSPinpointProvider.prototype._send = function (params, handlers) {
|
267 | return __awaiter(this, void 0, void 0, function () {
|
268 | var event;
|
269 | return __generator(this, function (_a) {
|
270 | event = params.event;
|
271 | switch (event.name) {
|
272 | case UPDATE_ENDPOINT:
|
273 | return [2 , this._updateEndpoint({ params: params, handlers: handlers })];
|
274 | case SESSION_STOP:
|
275 | return [2 , this._pinpointSendStopSession(params, handlers)];
|
276 | default:
|
277 | return [2 , this._pinpointPutEvents(params, handlers)];
|
278 | }
|
279 | return [2 ];
|
280 | });
|
281 | });
|
282 | };
|
283 | AWSPinpointProvider.prototype._generateBatchItemContext = function (params) {
|
284 | var _a;
|
285 | var event = params.event, timestamp = params.timestamp, config = params.config;
|
286 | var name = event.name, attributes = event.attributes, metrics = event.metrics, eventId = event.eventId, session = event.session;
|
287 | var appId = config.appId, endpointId = config.endpointId;
|
288 | var endpointContext = {};
|
289 | var eventParams = {
|
290 | ApplicationId: appId,
|
291 | EventsRequest: {
|
292 | BatchItem: {},
|
293 | },
|
294 | };
|
295 | var endpointObj = {};
|
296 | endpointObj.Endpoint = endpointContext;
|
297 | endpointObj.Events = (_a = {},
|
298 | _a[eventId] = {
|
299 | EventType: name,
|
300 | Timestamp: new Date(timestamp).toISOString(),
|
301 | Attributes: attributes,
|
302 | Metrics: metrics,
|
303 | Session: session,
|
304 | },
|
305 | _a);
|
306 | eventParams.EventsRequest.BatchItem[endpointId] = endpointObj;
|
307 | return eventParams;
|
308 | };
|
309 | AWSPinpointProvider.prototype._pinpointPutEvents = function (params, handlers) {
|
310 | return __awaiter(this, void 0, void 0, function () {
|
311 | var eventId, endpointId, eventParams, command, data, _a, _b, _c, _d, StatusCode, Message, err_1;
|
312 | return __generator(this, function (_e) {
|
313 | switch (_e.label) {
|
314 | case 0:
|
315 | eventId = params.event.eventId, endpointId = params.config.endpointId;
|
316 | eventParams = this._generateBatchItemContext(params);
|
317 | command = new PutEventsCommand(eventParams);
|
318 | _e.label = 1;
|
319 | case 1:
|
320 | _e.trys.push([1, 3, , 4]);
|
321 | return [4 , this.pinpointClient.send(command)];
|
322 | case 2:
|
323 | data = _e.sent();
|
324 | _a = data, _b = endpointId, _c = eventId, _d = _a.EventsResponse.Results[_b].EventsItemResponse[_c], StatusCode = _d.StatusCode, Message = _d.Message;
|
325 | if (ACCEPTED_CODES.includes(StatusCode)) {
|
326 | logger.debug('record event success. ', data);
|
327 | return [2 , handlers.resolve(data)];
|
328 | }
|
329 | else {
|
330 | if (RETRYABLE_CODES.includes(StatusCode)) {
|
331 | this._retry(params, handlers);
|
332 | }
|
333 | else {
|
334 | logger.error("Event " + eventId + " is not accepted, the error is " + Message);
|
335 | return [2 , handlers.reject(data)];
|
336 | }
|
337 | }
|
338 | return [3 , 4];
|
339 | case 3:
|
340 | err_1 = _e.sent();
|
341 | this._eventError(err_1);
|
342 | return [2 , handlers.reject(err_1)];
|
343 | case 4: return [2 ];
|
344 | }
|
345 | });
|
346 | });
|
347 | };
|
348 | AWSPinpointProvider.prototype._pinpointSendStopSession = function (params, handlers) {
|
349 | if (!BEACON_SUPPORTED) {
|
350 | this._pinpointPutEvents(params, handlers);
|
351 | return;
|
352 | }
|
353 | var eventParams = this._generateBatchItemContext(params);
|
354 | var region = this._config.region;
|
355 | var ApplicationId = eventParams.ApplicationId, EventsRequest = eventParams.EventsRequest;
|
356 | var accessInfo = {
|
357 | secret_key: this._config.credentials.secretAccessKey,
|
358 | access_key: this._config.credentials.accessKeyId,
|
359 | session_token: this._config.credentials.sessionToken,
|
360 | };
|
361 | var url = "https://pinpoint." + region + ".amazonaws.com/v1/apps/" + ApplicationId + "/events/legacy";
|
362 | var body = JSON.stringify(EventsRequest);
|
363 | var method = 'POST';
|
364 | var request = {
|
365 | url: url,
|
366 | body: body,
|
367 | method: method,
|
368 | };
|
369 | var serviceInfo = { region: region, service: MOBILE_SERVICE_NAME };
|
370 | var requestUrl = Signer.signUrl(request, accessInfo, serviceInfo, null);
|
371 | var success = navigator.sendBeacon(requestUrl, body);
|
372 | if (success) {
|
373 | return handlers.resolve('sendBeacon success');
|
374 | }
|
375 | return handlers.reject('sendBeacon failure');
|
376 | };
|
377 | AWSPinpointProvider.prototype._retry = function (params, handlers) {
|
378 | var resendLimit = params.config.resendLimit;
|
379 |
|
380 | params.resendLimit =
|
381 | typeof params.resendLimit === 'number' ? params.resendLimit : resendLimit;
|
382 | if (params.resendLimit-- > 0) {
|
383 | logger.debug("resending event " + params.eventName + " with " + params.resendLimit + " retry times left");
|
384 | this._pinpointPutEvents(params, handlers);
|
385 | }
|
386 | else {
|
387 | logger.debug("retry times used up for event " + params.eventName);
|
388 | }
|
389 | };
|
390 | AWSPinpointProvider.prototype._updateEndpoint = function (endpointObject) {
|
391 | return __awaiter(this, void 0, void 0, function () {
|
392 | var params, handlers, config, event, appId, endpointId, request, update_params, command, data, err_2, failureData;
|
393 | return __generator(this, function (_a) {
|
394 | switch (_a.label) {
|
395 | case 0:
|
396 | params = endpointObject.params, handlers = endpointObject.handlers;
|
397 | config = params.config, event = params.event;
|
398 | appId = config.appId, endpointId = config.endpointId;
|
399 | request = this._endpointRequest(config, JS.transferKeyToLowerCase(event, [], ['attributes', 'userAttributes', 'Attributes', 'UserAttributes']));
|
400 | update_params = {
|
401 | ApplicationId: appId,
|
402 | EndpointId: endpointId,
|
403 | EndpointRequest: request,
|
404 | };
|
405 | _a.label = 1;
|
406 | case 1:
|
407 | _a.trys.push([1, 3, , 4]);
|
408 | command = new UpdateEndpointCommand(update_params);
|
409 | return [4 , this.pinpointClient.send(command)];
|
410 | case 2:
|
411 | data = _a.sent();
|
412 | logger.debug('updateEndpoint success', data);
|
413 | this._endpointGenerating = false;
|
414 | this._resumeBuffer();
|
415 | handlers.resolve(data);
|
416 | return [2 ];
|
417 | case 3:
|
418 | err_2 = _a.sent();
|
419 | failureData = {
|
420 | err: err_2,
|
421 | update_params: update_params,
|
422 | endpointObject: endpointObject,
|
423 | };
|
424 | return [2 , this._handleEndpointUpdateFailure(failureData)];
|
425 | case 4: return [2 ];
|
426 | }
|
427 | });
|
428 | });
|
429 | };
|
430 | AWSPinpointProvider.prototype._handleEndpointUpdateFailure = function (failureData) {
|
431 | return __awaiter(this, void 0, void 0, function () {
|
432 | var err, endpointObject, statusCode, exponential;
|
433 | return __generator(this, function (_a) {
|
434 | err = failureData.err, endpointObject = failureData.endpointObject;
|
435 | statusCode = err.$metadata && err.$metadata.httpStatusCode;
|
436 | logger.debug('updateEndpoint error', err);
|
437 | switch (statusCode) {
|
438 | case FORBIDDEN_CODE:
|
439 | return [2 , this._handleEndpointUpdateForbidden(failureData)];
|
440 | default:
|
441 | if (RETRYABLE_CODES.includes(statusCode)) {
|
442 | exponential = true;
|
443 | return [2 , this._retryEndpointUpdate(endpointObject, exponential)];
|
444 | }
|
445 | logger.error('updateEndpoint failed', err);
|
446 | endpointObject.handlers.reject(err);
|
447 | }
|
448 | return [2 ];
|
449 | });
|
450 | });
|
451 | };
|
452 | AWSPinpointProvider.prototype._handleEndpointUpdateForbidden = function (failureData) {
|
453 | var err = failureData.err, endpointObject = failureData.endpointObject;
|
454 | var code = err.code, retryable = err.retryable;
|
455 | if (code !== EXPIRED_TOKEN_CODE && !retryable) {
|
456 | return endpointObject.handlers.reject(err);
|
457 | }
|
458 | this._retryEndpointUpdate(endpointObject);
|
459 | };
|
460 | AWSPinpointProvider.prototype._retryEndpointUpdate = function (endpointObject, exponential) {
|
461 | if (exponential === void 0) { exponential = false; }
|
462 | logger.debug('_retryEndpointUpdate', endpointObject);
|
463 | var params = endpointObject.params;
|
464 |
|
465 | var resendLimit = params.config.resendLimit;
|
466 | params.resendLimit =
|
467 | typeof params.resendLimit === 'number' ? params.resendLimit : resendLimit;
|
468 | if (params.resendLimit-- > 0) {
|
469 | logger.debug("resending endpoint update " + params.event.eventId + " with " + params.resendLimit + " retry attempts remaining");
|
470 |
|
471 | this._endpointBuffer.length
|
472 | ? this._endpointBuffer.unshift(endpointObject)
|
473 | : this._updateEndpoint(endpointObject);
|
474 | return;
|
475 | }
|
476 | logger.warn("resending endpoint update " + params.event.eventId + " failed after " + params.config.resendLimit + " attempts");
|
477 | if (this._endpointGenerating) {
|
478 | logger.error('Initial endpoint update failed. ');
|
479 | }
|
480 | };
|
481 | |
482 |
|
483 |
|
484 |
|
485 |
|
486 | AWSPinpointProvider.prototype._initClients = function (credentials) {
|
487 | return __awaiter(this, void 0, void 0, function () {
|
488 | var identityId, region;
|
489 | return __generator(this, function (_a) {
|
490 | logger.debug('init clients');
|
491 | if (this.pinpointClient &&
|
492 | this._config.credentials &&
|
493 | this._config.credentials.sessionToken === credentials.sessionToken &&
|
494 | this._config.credentials.identityId === credentials.identityId) {
|
495 | logger.debug('no change for aws credentials, directly return from init');
|
496 | return [2 ];
|
497 | }
|
498 | identityId = this._config.credentials
|
499 | ? this._config.credentials.identityId
|
500 | : null;
|
501 | this._config.credentials = credentials;
|
502 | region = this._config.region;
|
503 | logger.debug('init clients with credentials', credentials);
|
504 | this.pinpointClient = new PinpointClient({
|
505 | region: region,
|
506 | credentials: credentials,
|
507 | customUserAgent: getAmplifyUserAgent(),
|
508 | });
|
509 |
|
510 | this.pinpointClient.middlewareStack.addRelativeTo(function (next) { return function (args) {
|
511 | delete args.request.headers['amz-sdk-invocation-id'];
|
512 | delete args.request.headers['amz-sdk-request'];
|
513 | return next(args);
|
514 | }; }, {
|
515 | step: 'finalizeRequest',
|
516 | relation: 'after',
|
517 | toMiddleware: 'retryMiddleware',
|
518 | });
|
519 | if (this._bufferExists() && identityId === credentials.identityId) {
|
520 |
|
521 | this._updateBufferClient();
|
522 | }
|
523 | else {
|
524 |
|
525 |
|
526 |
|
527 | this._initBuffer();
|
528 | }
|
529 | this._customizePinpointClientReq();
|
530 | return [2 ];
|
531 | });
|
532 | });
|
533 | };
|
534 | AWSPinpointProvider.prototype._bufferExists = function () {
|
535 | return this._buffer && this._buffer instanceof EventsBuffer;
|
536 | };
|
537 | AWSPinpointProvider.prototype._initBuffer = function () {
|
538 | if (this._bufferExists()) {
|
539 | this._flushBuffer();
|
540 | }
|
541 | this._buffer = new EventsBuffer(this.pinpointClient, this._config);
|
542 |
|
543 |
|
544 | if (this._endpointGenerating) {
|
545 | this._buffer.pause();
|
546 | }
|
547 | };
|
548 | AWSPinpointProvider.prototype._updateBufferClient = function () {
|
549 | if (this._bufferExists()) {
|
550 | this._buffer.updateClient(this.pinpointClient);
|
551 | }
|
552 | };
|
553 | AWSPinpointProvider.prototype._flushBuffer = function () {
|
554 | if (this._bufferExists()) {
|
555 | this._buffer.flush();
|
556 | this._buffer = null;
|
557 | }
|
558 | };
|
559 | AWSPinpointProvider.prototype._resumeBuffer = function () {
|
560 | if (this._bufferExists()) {
|
561 | this._buffer.resume();
|
562 | }
|
563 | };
|
564 | AWSPinpointProvider.prototype._customizePinpointClientReq = function () {
|
565 |
|
566 |
|
567 |
|
568 |
|
569 |
|
570 |
|
571 |
|
572 |
|
573 | };
|
574 | AWSPinpointProvider.prototype._getEndpointId = function (cacheKey) {
|
575 | return __awaiter(this, void 0, void 0, function () {
|
576 | var endpointId, ttl, expiration;
|
577 | return __generator(this, function (_a) {
|
578 | switch (_a.label) {
|
579 | case 0: return [4 , Cache.getItem(cacheKey)];
|
580 | case 1:
|
581 | endpointId = _a.sent();
|
582 | logger.debug('endpointId from cache', endpointId, 'type', typeof endpointId);
|
583 | if (!endpointId) {
|
584 | endpointId = uuid();
|
585 | ttl = 1000 * 60 * 60 * 24 * 365 * 100;
|
586 | expiration = new Date().getTime() + ttl;
|
587 | Cache.setItem(cacheKey, endpointId, {
|
588 | expires: expiration,
|
589 | priority: 1,
|
590 | });
|
591 | }
|
592 | return [2 , endpointId];
|
593 | }
|
594 | });
|
595 | });
|
596 | };
|
597 | |
598 |
|
599 |
|
600 |
|
601 | AWSPinpointProvider.prototype._endpointRequest = function (config, event) {
|
602 | var credentials = config.credentials;
|
603 | var clientInfo = this._clientInfo || {};
|
604 | var clientContext = config.clientContext || {};
|
605 |
|
606 |
|
607 |
|
608 |
|
609 | var defaultEndpointConfig = config.endpoint || {};
|
610 | var demographicByClientInfo = {
|
611 | appVersion: clientInfo.appVersion,
|
612 | make: clientInfo.make,
|
613 | model: clientInfo.model,
|
614 | modelVersion: clientInfo.version,
|
615 | platform: clientInfo.platform,
|
616 | };
|
617 |
|
618 | var clientId = clientContext.clientId, appTitle = clientContext.appTitle, appVersionName = clientContext.appVersionName, appVersionCode = clientContext.appVersionCode, appPackageName = clientContext.appPackageName, demographicByClientContext = __rest(clientContext, ["clientId", "appTitle", "appVersionName", "appVersionCode", "appPackageName"]);
|
619 | var channelType = event.address
|
620 | ? clientInfo.platform === 'android'
|
621 | ? 'GCM'
|
622 | : 'APNS'
|
623 | : undefined;
|
624 | var tmp = __assign(__assign(__assign({ channelType: channelType, requestId: uuid(), effectiveDate: new Date().toISOString() }, defaultEndpointConfig), event), { attributes: __assign(__assign({}, defaultEndpointConfig.attributes), event.attributes), demographic: __assign(__assign(__assign(__assign({}, demographicByClientInfo), demographicByClientContext), defaultEndpointConfig.demographic), event.demographic), location: __assign(__assign({}, defaultEndpointConfig.location), event.location), metrics: __assign(__assign({}, defaultEndpointConfig.metrics), event.metrics), user: {
|
625 | userId: event.userId ||
|
626 | defaultEndpointConfig.userId ||
|
627 | credentials.identityId,
|
628 | userAttributes: __assign(__assign({}, defaultEndpointConfig.userAttributes), event.userAttributes),
|
629 | } });
|
630 |
|
631 | var userId = tmp.userId, userAttributes = tmp.userAttributes, name = tmp.name, session = tmp.session, eventId = tmp.eventId, immediate = tmp.immediate, ret = __rest(tmp, ["userId", "userAttributes", "name", "session", "eventId", "immediate"]);
|
632 | return JS.transferKeyToUpperCase(ret, [], ['metrics', 'userAttributes', 'attributes']);
|
633 | };
|
634 | AWSPinpointProvider.prototype._eventError = function (err) {
|
635 | logger.error('record event failed.', err);
|
636 | logger.warn("Please ensure you have updated your Pinpoint IAM Policy " +
|
637 | "with the Action: \"mobiletargeting:PutEvents\" " +
|
638 | "in order to record events");
|
639 | };
|
640 | AWSPinpointProvider.prototype._getCredentials = function () {
|
641 | return __awaiter(this, void 0, void 0, function () {
|
642 | var credentials, err_3;
|
643 | return __generator(this, function (_a) {
|
644 | switch (_a.label) {
|
645 | case 0:
|
646 | _a.trys.push([0, 2, , 3]);
|
647 | return [4 , Credentials.get()];
|
648 | case 1:
|
649 | credentials = _a.sent();
|
650 | if (!credentials)
|
651 | return [2 , null];
|
652 | logger.debug('set credentials for analytics', credentials);
|
653 | return [2 , Credentials.shear(credentials)];
|
654 | case 2:
|
655 | err_3 = _a.sent();
|
656 | logger.debug('ensure credentials error', err_3);
|
657 | return [2 , null];
|
658 | case 3: return [2 ];
|
659 | }
|
660 | });
|
661 | });
|
662 | };
|
663 | AWSPinpointProvider.category = 'Analytics';
|
664 | AWSPinpointProvider.providerName = 'AWSPinpoint';
|
665 | return AWSPinpointProvider;
|
666 | }());
|
667 | export { AWSPinpointProvider };
|
668 |
|
669 |
|
670 |
|
671 | export default AWSPinpointProvider;
|
672 |
|
\ | No newline at end of file |