@aws-amplify/analytics 7.0.1-api-v6-models.9351bcf.0 → 7.0.1-api-v6-models.891fe0d.0

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 (87) hide show
  1. package/lib/apis/disable.js +1 -1
  2. package/lib/apis/enable.js +1 -1
  3. package/lib/errors/AnalyticsError.js +7 -11
  4. package/lib/errors/assertValidationError.js +6 -6
  5. package/lib/errors/validation.js +10 -11
  6. package/lib/providers/kinesis/apis/flushEvents.js +20 -23
  7. package/lib/providers/kinesis/apis/record.js +24 -26
  8. package/lib/providers/kinesis/utils/getEventBuffer.js +39 -70
  9. package/lib/providers/kinesis/utils/resolveConfig.js +14 -13
  10. package/lib/providers/kinesis-firehose/apis/flushEvents.js +19 -22
  11. package/lib/providers/kinesis-firehose/apis/record.js +22 -24
  12. package/lib/providers/kinesis-firehose/utils/getEventBuffer.js +39 -68
  13. package/lib/providers/kinesis-firehose/utils/resolveConfig.js +14 -13
  14. package/lib/providers/personalize/apis/flushEvents.js +18 -21
  15. package/lib/providers/personalize/apis/record.js +55 -71
  16. package/lib/providers/personalize/utils/autoTrackMedia.js +96 -98
  17. package/lib/providers/personalize/utils/cachedSession.js +30 -42
  18. package/lib/providers/personalize/utils/getEventBuffer.js +35 -62
  19. package/lib/providers/personalize/utils/resolveConfig.js +14 -13
  20. package/lib/providers/pinpoint/apis/configureAutoTrack.js +6 -6
  21. package/lib/providers/pinpoint/apis/flushEvents.js +10 -13
  22. package/lib/providers/pinpoint/apis/identifyUser.js +18 -30
  23. package/lib/providers/pinpoint/apis/record.js +15 -16
  24. package/lib/providers/pinpoint/utils/resolveConfig.js +5 -6
  25. package/lib/providers/pinpoint/utils/resolveCredentials.js +7 -15
  26. package/lib/setupTests.js +1 -1
  27. package/lib/trackers/EventTracker.js +39 -45
  28. package/lib/trackers/PageViewTracker.js +41 -45
  29. package/lib/trackers/SessionTracker.js +25 -31
  30. package/lib/trackers/SessionTracker.native.js +25 -31
  31. package/lib/tsconfig.tsbuildinfo +1 -1
  32. package/lib/utils/eventBuffer/EventBuffer.js +34 -62
  33. package/lib/utils/groupBy.js +4 -7
  34. package/lib/utils/resolveCredentials.js +7 -15
  35. package/lib/utils/statusHelpers.js +4 -4
  36. package/lib/utils/trackerConfigHelpers.js +2 -2
  37. package/lib/utils/trackerConfigHelpers.native.js +2 -2
  38. package/lib/utils/trackerHelpers.js +5 -5
  39. package/lib/utils/userAgent.js +3 -3
  40. package/lib-esm/apis/disable.js +1 -1
  41. package/lib-esm/apis/enable.js +1 -1
  42. package/lib-esm/errors/AnalyticsError.js +6 -11
  43. package/lib-esm/errors/assertValidationError.js +4 -4
  44. package/lib-esm/errors/validation.js +10 -11
  45. package/lib-esm/providers/kinesis/apis/flushEvents.js +15 -18
  46. package/lib-esm/providers/kinesis/apis/record.js +18 -20
  47. package/lib-esm/providers/kinesis/utils/constants.js +1 -1
  48. package/lib-esm/providers/kinesis/utils/getEventBuffer.js +37 -68
  49. package/lib-esm/providers/kinesis/utils/resolveConfig.js +11 -10
  50. package/lib-esm/providers/kinesis-firehose/apis/flushEvents.js +15 -18
  51. package/lib-esm/providers/kinesis-firehose/apis/record.js +17 -19
  52. package/lib-esm/providers/kinesis-firehose/utils/constants.js +1 -1
  53. package/lib-esm/providers/kinesis-firehose/utils/getEventBuffer.js +37 -66
  54. package/lib-esm/providers/kinesis-firehose/utils/resolveConfig.js +11 -10
  55. package/lib-esm/providers/personalize/apis/flushEvents.js +14 -17
  56. package/lib-esm/providers/personalize/apis/record.js +50 -66
  57. package/lib-esm/providers/personalize/utils/autoTrackMedia.js +94 -96
  58. package/lib-esm/providers/personalize/utils/cachedSession.js +28 -40
  59. package/lib-esm/providers/personalize/utils/constants.js +4 -4
  60. package/lib-esm/providers/personalize/utils/getEventBuffer.js +33 -60
  61. package/lib-esm/providers/personalize/utils/resolveConfig.js +11 -10
  62. package/lib-esm/providers/pinpoint/apis/configureAutoTrack.js +4 -4
  63. package/lib-esm/providers/pinpoint/apis/flushEvents.js +5 -8
  64. package/lib-esm/providers/pinpoint/apis/identifyUser.js +14 -26
  65. package/lib-esm/providers/pinpoint/apis/record.js +9 -10
  66. package/lib-esm/providers/pinpoint/utils/resolveConfig.js +3 -4
  67. package/lib-esm/providers/pinpoint/utils/resolveCredentials.js +5 -13
  68. package/lib-esm/setupTests.js +1 -1
  69. package/lib-esm/trackers/EventTracker.js +37 -44
  70. package/lib-esm/trackers/PageViewTracker.js +39 -44
  71. package/lib-esm/trackers/SessionTracker.js +22 -29
  72. package/lib-esm/trackers/SessionTracker.native.js +22 -29
  73. package/lib-esm/tsconfig.tsbuildinfo +1 -1
  74. package/lib-esm/utils/eventBuffer/EventBuffer.js +33 -62
  75. package/lib-esm/utils/groupBy.js +4 -7
  76. package/lib-esm/utils/resolveCredentials.js +5 -13
  77. package/lib-esm/utils/statusHelpers.js +4 -4
  78. package/lib-esm/utils/trackerConfigHelpers.js +1 -1
  79. package/lib-esm/utils/trackerConfigHelpers.native.js +1 -1
  80. package/lib-esm/utils/trackerHelpers.js +4 -4
  81. package/lib-esm/utils/userAgent.js +2 -2
  82. package/package.json +6 -9
  83. package/src/providers/kinesis/utils/getEventBuffer.ts +6 -7
  84. package/src/providers/kinesis-firehose/utils/getEventBuffer.ts +6 -7
  85. package/src/providers/personalize/utils/getEventBuffer.ts +6 -7
  86. package/src/trackers/SessionTracker.native.ts +2 -3
  87. package/src/trackers/SessionTracker.ts +2 -3
@@ -1,6 +1,5 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- import { __assign, __awaiter, __generator, __rest } from "tslib";
4
3
  import { isBrowser } from '@aws-amplify/core/internals/utils';
5
4
  import { ConsoleLogger } from '@aws-amplify/core';
6
5
  var HTML5_MEDIA_EVENT;
@@ -22,43 +21,43 @@ var EVENT_TYPE;
22
21
  EVENT_TYPE["PAUSE"] = "Pause";
23
22
  EVENT_TYPE["TIME_WATCHED"] = "TimeWatched";
24
23
  })(EVENT_TYPE || (EVENT_TYPE = {}));
25
- var logger = new ConsoleLogger('MediaAutoTrack');
26
- var startIframeAutoTracking = function (element, recordEvent) {
27
- var isPlaying = false;
28
- var player;
29
- var mediaProperties = function () {
30
- var duration = Number(parseFloat(player.getDuration()).toFixed(4));
31
- var currentTime = Number(parseFloat(player.getCurrentTime()).toFixed(4));
24
+ const logger = new ConsoleLogger('MediaAutoTrack');
25
+ const startIframeAutoTracking = (element, recordEvent) => {
26
+ let isPlaying = false;
27
+ let player;
28
+ const mediaProperties = () => {
29
+ const duration = Number(parseFloat(player.getDuration()).toFixed(4));
30
+ const currentTime = Number(parseFloat(player.getCurrentTime()).toFixed(4));
32
31
  return {
33
- duration: duration,
32
+ duration,
34
33
  eventValue: Number((currentTime / duration).toFixed(4)),
35
34
  };
36
35
  };
37
- var scriptElement = document.createElement('script');
36
+ const scriptElement = document.createElement('script');
38
37
  scriptElement.type = 'text/javascript';
39
38
  scriptElement.src = 'https://www.youtube.com/iframe_api';
40
39
  document.body.append(scriptElement);
41
- var timer = setInterval(function () {
40
+ const timer = setInterval(() => {
42
41
  if (isPlaying && player) {
43
42
  recordEvent(EVENT_TYPE.TIME_WATCHED, mediaProperties());
44
43
  }
45
44
  }, 3000);
46
- element.addEventListener('unload', function () { return clearInterval(timer); });
45
+ element.addEventListener('unload', () => clearInterval(timer));
47
46
  // @ts-ignore
48
- window.onYouTubeIframeAPIReady = function () {
47
+ window.onYouTubeIframeAPIReady = () => {
49
48
  // @ts-ignore
50
49
  delete window.onYouTubeIframeAPIReady;
51
50
  // @ts-ignore
52
51
  player = new window.YT.Player(element.id, {
53
52
  events: {
54
- onStateChange: function (event) {
55
- var iframeEventMapping = {
53
+ onStateChange: (event) => {
54
+ const iframeEventMapping = {
56
55
  0: EVENT_TYPE.ENDED,
57
56
  1: EVENT_TYPE.PLAY,
58
57
  2: EVENT_TYPE.PAUSE,
59
58
  };
60
59
  // @ts-ignore
61
- var eventType = iframeEventMapping[event.data];
60
+ const eventType = iframeEventMapping[event.data];
62
61
  switch (eventType) {
63
62
  case EVENT_TYPE.ENDED:
64
63
  case EVENT_TYPE.PAUSE:
@@ -76,104 +75,103 @@ var startIframeAutoTracking = function (element, recordEvent) {
76
75
  });
77
76
  };
78
77
  };
79
- var startHTMLMediaAutoTracking = function (element, recordEvent) {
80
- var isPlaying = false;
81
- var mediaProperties = function () { return ({
78
+ const startHTMLMediaAutoTracking = (element, recordEvent) => {
79
+ let isPlaying = false;
80
+ const mediaProperties = () => ({
82
81
  duration: element.duration,
83
82
  eventValue: Number((element.currentTime / element.duration).toFixed(4)),
84
- }); };
85
- var timer = setInterval(function () {
83
+ });
84
+ const timer = setInterval(() => {
86
85
  if (isPlaying) {
87
86
  recordEvent(EVENT_TYPE.TIME_WATCHED, mediaProperties());
88
87
  }
89
88
  }, 3000);
90
- element.addEventListener('unload', function () { return clearInterval(timer); });
91
- element.addEventListener(HTML5_MEDIA_EVENT.PLAY, function () {
89
+ element.addEventListener('unload', () => clearInterval(timer));
90
+ element.addEventListener(HTML5_MEDIA_EVENT.PLAY, () => {
92
91
  isPlaying = true;
93
92
  recordEvent(EVENT_TYPE.PLAY, mediaProperties());
94
93
  });
95
- element.addEventListener(HTML5_MEDIA_EVENT.PAUSE, function () {
94
+ element.addEventListener(HTML5_MEDIA_EVENT.PAUSE, () => {
96
95
  isPlaying = false;
97
96
  recordEvent(EVENT_TYPE.PAUSE, mediaProperties());
98
97
  });
99
- element.addEventListener(HTML5_MEDIA_EVENT.ENDED, function () {
98
+ element.addEventListener(HTML5_MEDIA_EVENT.ENDED, () => {
100
99
  isPlaying = false;
101
100
  recordEvent(EVENT_TYPE.ENDED, mediaProperties());
102
101
  });
103
102
  };
104
- var checkElementLoaded = function (interval, maxTries) {
105
- var retryCount = 0;
106
- var wait = function () { return new Promise(function (r) { return setTimeout(r, interval); }); };
107
- var check = function (elementId) { return __awaiter(void 0, void 0, void 0, function () {
108
- var domElement;
109
- return __generator(this, function (_a) {
110
- switch (_a.label) {
111
- case 0:
112
- if (retryCount >= maxTries) {
113
- return [2 /*return*/, false];
114
- }
115
- domElement = document.getElementById(elementId);
116
- if (!(domElement && domElement.clientHeight)) return [3 /*break*/, 1];
117
- return [2 /*return*/, true];
118
- case 1:
119
- retryCount += 1;
120
- return [4 /*yield*/, wait()];
121
- case 2:
122
- _a.sent();
123
- return [4 /*yield*/, check(elementId)];
124
- case 3: return [2 /*return*/, _a.sent()];
125
- }
126
- });
127
- }); };
103
+ const checkElementLoaded = (interval, maxTries) => {
104
+ let retryCount = 0;
105
+ const wait = () => new Promise(r => setTimeout(r, interval));
106
+ const check = async (elementId) => {
107
+ if (retryCount >= maxTries) {
108
+ return false;
109
+ }
110
+ const domElement = document.getElementById(elementId);
111
+ if (domElement && domElement.clientHeight) {
112
+ return true;
113
+ }
114
+ else {
115
+ retryCount += 1;
116
+ await wait();
117
+ return await check(elementId);
118
+ }
119
+ };
128
120
  return check;
129
121
  };
130
- var recordEvent = function (config, eventBuffer) {
131
- return function (eventType, properties) {
132
- // override eventType and merge properties
133
- eventBuffer.append(__assign(__assign({}, config), { event: __assign(__assign({}, config.event), { eventType: eventType, properties: __assign(__assign({}, config.event.properties), properties) }), timestamp: Date.now() }));
134
- };
122
+ const recordEvent = (config, eventBuffer) => (eventType, properties) => {
123
+ // override eventType and merge properties
124
+ eventBuffer.append({
125
+ ...config,
126
+ event: {
127
+ ...config.event,
128
+ eventType,
129
+ properties: {
130
+ ...config.event.properties,
131
+ ...properties,
132
+ },
133
+ },
134
+ timestamp: Date.now(),
135
+ });
135
136
  };
136
- export var autoTrackMedia = function (config, eventBuffer) { return __awaiter(void 0, void 0, void 0, function () {
137
- var _a, eventType, properties, domElementId, otherProperties, elementId, isElementLoaded, autoTrackConfigWithoutDomElementId, element;
138
- return __generator(this, function (_b) {
139
- switch (_b.label) {
140
- case 0:
141
- _a = config.event, eventType = _a.eventType, properties = _a.properties;
142
- domElementId = properties.domElementId, otherProperties = __rest(properties, ["domElementId"]);
143
- if (!isBrowser()) {
144
- logger.debug("".concat(eventType, " only for browser"));
145
- return [2 /*return*/];
146
- }
147
- if (typeof domElementId === 'string' && !domElementId) {
148
- logger.debug("Missing domElementId field in 'properties' for MediaAutoTrack event type.");
149
- return [2 /*return*/];
150
- }
151
- elementId = domElementId;
152
- return [4 /*yield*/, checkElementLoaded(500, 5)(elementId)];
153
- case 1:
154
- isElementLoaded = _b.sent();
155
- if (isElementLoaded) {
156
- autoTrackConfigWithoutDomElementId = __assign(__assign({}, config), { event: __assign(__assign({}, config.event), { properties: otherProperties }) });
157
- element = document.getElementById(elementId);
158
- switch (element === null || element === void 0 ? void 0 : element.tagName) {
159
- case MEDIA_TYPE.IFRAME:
160
- startIframeAutoTracking(element, recordEvent(autoTrackConfigWithoutDomElementId, eventBuffer));
161
- break;
162
- case MEDIA_TYPE.VIDEO:
163
- case MEDIA_TYPE.AUDIO:
164
- if (element instanceof HTMLMediaElement) {
165
- startHTMLMediaAutoTracking(element, recordEvent(autoTrackConfigWithoutDomElementId, eventBuffer));
166
- }
167
- break;
168
- default:
169
- logger.debug("Unsupported DOM element tag: ".concat(element === null || element === void 0 ? void 0 : element.tagName));
170
- break;
171
- }
172
- }
173
- else {
174
- logger.debug('Cannot find the media element.');
137
+ export const autoTrackMedia = async (config, eventBuffer) => {
138
+ const { eventType, properties } = config.event;
139
+ const { domElementId, ...otherProperties } = properties;
140
+ if (!isBrowser()) {
141
+ logger.debug(`${eventType} only for browser`);
142
+ return;
143
+ }
144
+ if (typeof domElementId === 'string' && !domElementId) {
145
+ logger.debug("Missing domElementId field in 'properties' for MediaAutoTrack event type.");
146
+ return;
147
+ }
148
+ const elementId = domElementId;
149
+ const isElementLoaded = await checkElementLoaded(500, 5)(elementId);
150
+ if (isElementLoaded) {
151
+ const autoTrackConfigWithoutDomElementId = {
152
+ ...config,
153
+ event: {
154
+ ...config.event,
155
+ properties: otherProperties,
156
+ },
157
+ };
158
+ const element = document.getElementById(elementId);
159
+ switch (element?.tagName) {
160
+ case MEDIA_TYPE.IFRAME:
161
+ startIframeAutoTracking(element, recordEvent(autoTrackConfigWithoutDomElementId, eventBuffer));
162
+ break;
163
+ case MEDIA_TYPE.VIDEO:
164
+ case MEDIA_TYPE.AUDIO:
165
+ if (element instanceof HTMLMediaElement) {
166
+ startHTMLMediaAutoTracking(element, recordEvent(autoTrackConfigWithoutDomElementId, eventBuffer));
175
167
  }
176
- return [2 /*return*/];
168
+ break;
169
+ default:
170
+ logger.debug(`Unsupported DOM element tag: ${element?.tagName}`);
171
+ break;
177
172
  }
178
- });
179
- }); };
173
+ }
174
+ else {
175
+ logger.debug('Cannot find the media element.');
176
+ }
177
+ };
@@ -1,52 +1,40 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- import { __awaiter, __generator } from "tslib";
4
3
  import { Cache } from '@aws-amplify/core';
5
4
  import { isBrowser, amplifyUuid } from '@aws-amplify/core/internals/utils';
6
- var PERSONALIZE_CACHE_USERID = '_awsct_uid';
7
- var PERSONALIZE_CACHE_SESSIONID = '_awsct_sid';
8
- var DEFAULT_CACHE_PREFIX = 'personalize';
9
- var DELIMITER = '.';
10
- var CACHE_EXPIRY_IN_DAYS = 7;
11
- var normalize = function (key) {
12
- return [key, isBrowser() ? window.location.host : DEFAULT_CACHE_PREFIX].join(DELIMITER);
13
- };
14
- var getCache = function (key) { return Cache.getItem(normalize(key)); };
15
- var setCache = function (key, value) {
16
- var expiredAt = new Date(Date.now() + 3600000 * 24 * CACHE_EXPIRY_IN_DAYS);
5
+ const PERSONALIZE_CACHE_USERID = '_awsct_uid';
6
+ const PERSONALIZE_CACHE_SESSIONID = '_awsct_sid';
7
+ const DEFAULT_CACHE_PREFIX = 'personalize';
8
+ const DELIMITER = '.';
9
+ const CACHE_EXPIRY_IN_DAYS = 7;
10
+ const normalize = (key) => [key, isBrowser() ? window.location.host : DEFAULT_CACHE_PREFIX].join(DELIMITER);
11
+ const getCache = (key) => Cache.getItem(normalize(key));
12
+ const setCache = (key, value) => {
13
+ const expiredAt = new Date(Date.now() + 3600000 * 24 * CACHE_EXPIRY_IN_DAYS);
17
14
  Cache.setItem(normalize(key), value, {
18
15
  expires: expiredAt.getTime(),
19
16
  });
20
17
  };
21
- export var resolveCachedSession = function () { return __awaiter(void 0, void 0, void 0, function () {
22
- var sessionId, userId;
23
- return __generator(this, function (_a) {
24
- switch (_a.label) {
25
- case 0: return [4 /*yield*/, getCache(PERSONALIZE_CACHE_SESSIONID)];
26
- case 1:
27
- sessionId = _a.sent();
28
- if (!sessionId) {
29
- sessionId = amplifyUuid();
30
- setCache(PERSONALIZE_CACHE_SESSIONID, sessionId);
31
- }
32
- return [4 /*yield*/, getCache(PERSONALIZE_CACHE_USERID)];
33
- case 2:
34
- userId = _a.sent();
35
- return [2 /*return*/, {
36
- sessionId: sessionId,
37
- userId: userId,
38
- }];
39
- }
40
- });
41
- }); };
42
- export var updateCachedSession = function (newUserId, currentSessionId, currentUserId) {
43
- var isNoCachedSession = !currentSessionId;
44
- var isSignOutCase = !newUserId && !currentUserId;
45
- var isSwitchUserCase = !!newUserId && !!currentUserId && newUserId !== currentUserId;
46
- var isRequireNewSession = isNoCachedSession || isSignOutCase || isSwitchUserCase;
47
- var isRequireUpdateSession = !!currentSessionId && !currentUserId && !!newUserId;
18
+ export const resolveCachedSession = async () => {
19
+ let sessionId = await getCache(PERSONALIZE_CACHE_SESSIONID);
20
+ if (!sessionId) {
21
+ sessionId = amplifyUuid();
22
+ setCache(PERSONALIZE_CACHE_SESSIONID, sessionId);
23
+ }
24
+ const userId = await getCache(PERSONALIZE_CACHE_USERID);
25
+ return {
26
+ sessionId,
27
+ userId,
28
+ };
29
+ };
30
+ export const updateCachedSession = (newUserId, currentSessionId, currentUserId) => {
31
+ const isNoCachedSession = !currentSessionId;
32
+ const isSignOutCase = !newUserId && !currentUserId;
33
+ const isSwitchUserCase = !!newUserId && !!currentUserId && newUserId !== currentUserId;
34
+ const isRequireNewSession = isNoCachedSession || isSignOutCase || isSwitchUserCase;
35
+ const isRequireUpdateSession = !!currentSessionId && !currentUserId && !!newUserId;
48
36
  if (isRequireNewSession) {
49
- var newSessionId = amplifyUuid();
37
+ const newSessionId = amplifyUuid();
50
38
  setCache(PERSONALIZE_CACHE_SESSIONID, newSessionId);
51
39
  setCache(PERSONALIZE_CACHE_USERID, newUserId);
52
40
  }
@@ -1,9 +1,9 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- export var DEFAULT_PERSONALIZE_CONFIG = {
3
+ export const DEFAULT_PERSONALIZE_CONFIG = {
4
4
  flushSize: 5,
5
5
  flushInterval: 5000,
6
6
  };
7
- export var PERSONALIZE_FLUSH_SIZE_MAX = 10;
8
- export var IDENTIFY_EVENT_TYPE = 'Identify';
9
- export var MEDIA_AUTO_TRACK_EVENT_TYPE = 'MediaAutoTrack';
7
+ export const PERSONALIZE_FLUSH_SIZE_MAX = 10;
8
+ export const IDENTIFY_EVENT_TYPE = 'Identify';
9
+ export const MEDIA_AUTO_TRACK_EVENT_TYPE = 'MediaAutoTrack';
@@ -1,6 +1,5 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- import { __awaiter, __generator, __read, __values } from "tslib";
4
3
  import { EventBuffer, groupBy } from '../../../utils';
5
4
  import { PersonalizeEventsClient, PutEventsCommand, } from '@aws-sdk/client-personalize-events';
6
5
  /**
@@ -11,85 +10,59 @@ import { PersonalizeEventsClient, PutEventsCommand, } from '@aws-sdk/client-pers
11
10
  * Only one active session should exist at any given moment.
12
11
  * When a new session is initiated, the previous ones should be released.
13
12
  * */
14
- var eventBufferMap = {};
15
- var cachedClients = {};
16
- var DELIMITER = '#';
17
- var createPutEventsCommand = function (ids, events) {
18
- var _a = __read(ids.split(DELIMITER), 3), trackingId = _a[0], sessionId = _a[1], userId = _a[2];
13
+ const eventBufferMap = {};
14
+ const cachedClients = {};
15
+ const DELIMITER = '#';
16
+ const createPutEventsCommand = (ids, events) => {
17
+ const [trackingId, sessionId, userId] = ids.split(DELIMITER);
19
18
  return new PutEventsCommand({
20
- trackingId: trackingId,
21
- sessionId: sessionId,
22
- userId: userId,
23
- eventList: events.map(function (event) { return ({
19
+ trackingId,
20
+ sessionId,
21
+ userId,
22
+ eventList: events.map(event => ({
24
23
  eventId: event.event.eventId,
25
24
  eventType: event.event.eventType,
26
25
  properties: JSON.stringify(event.event.properties),
27
26
  sentAt: new Date(event.timestamp),
28
- }); }),
27
+ })),
29
28
  });
30
29
  };
31
- var submitEvents = function (events, client) { return __awaiter(void 0, void 0, void 0, function () {
32
- var groupedByIds, requests;
33
- return __generator(this, function (_a) {
34
- switch (_a.label) {
35
- case 0:
36
- groupedByIds = Object.entries(groupBy(function (event) {
37
- return [event.trackingId, event.sessionId, event.userId]
38
- .filter(function (id) { return !!id; })
39
- .join(DELIMITER);
40
- }, events));
41
- requests = groupedByIds
42
- .map(function (_a) {
43
- var _b = __read(_a, 2), ids = _b[0], events = _b[1];
44
- return createPutEventsCommand(ids, events);
45
- })
46
- .map(function (command) { return client.send(command); });
47
- return [4 /*yield*/, Promise.allSettled(requests)];
48
- case 1:
49
- _a.sent();
50
- return [2 /*return*/, Promise.resolve([])];
51
- }
52
- });
53
- }); };
54
- export var getEventBuffer = function (_a) {
55
- var e_1, _b;
56
- var region = _a.region, flushSize = _a.flushSize, flushInterval = _a.flushInterval, bufferSize = _a.bufferSize, credentials = _a.credentials, identityId = _a.identityId, userAgentValue = _a.userAgentValue;
57
- var sessionToken = credentials.sessionToken;
58
- var sessionIdentityKey = [region, sessionToken, identityId]
59
- .filter(function (x) { return !!x; })
60
- .join('-');
30
+ const submitEvents = async (events, client) => {
31
+ const groupedByIds = Object.entries(groupBy(event => [event.trackingId, event.sessionId, event.userId]
32
+ .filter(id => !!id)
33
+ .join(DELIMITER), events));
34
+ const requests = groupedByIds
35
+ .map(([ids, events]) => createPutEventsCommand(ids, events))
36
+ .map(command => client.send(command));
37
+ await Promise.allSettled(requests);
38
+ return Promise.resolve([]);
39
+ };
40
+ export const getEventBuffer = ({ region, flushSize, flushInterval, bufferSize, credentials, identityId, userAgentValue, }) => {
41
+ const sessionIdentityKey = [region, identityId].filter(x => !!x).join('-');
61
42
  if (!eventBufferMap[sessionIdentityKey]) {
62
- var getClient = function () {
43
+ const getClient = () => {
63
44
  if (!cachedClients[sessionIdentityKey]) {
64
45
  cachedClients[sessionIdentityKey] = new PersonalizeEventsClient({
65
- region: region,
66
- credentials: credentials,
46
+ region,
47
+ credentials,
67
48
  customUserAgent: userAgentValue,
68
49
  });
69
50
  }
70
- return function (events) { return submitEvents(events, cachedClients[sessionIdentityKey]); };
51
+ return events => submitEvents(events, cachedClients[sessionIdentityKey]);
71
52
  };
72
53
  eventBufferMap[sessionIdentityKey] =
73
54
  new EventBuffer({
74
- bufferSize: bufferSize,
75
- flushSize: flushSize,
76
- flushInterval: flushInterval,
55
+ bufferSize,
56
+ flushSize,
57
+ flushInterval,
77
58
  }, getClient);
78
- var releaseSessionKeys = Object.keys(eventBufferMap).filter(function (key) { return key !== sessionIdentityKey; });
79
- try {
80
- for (var releaseSessionKeys_1 = __values(releaseSessionKeys), releaseSessionKeys_1_1 = releaseSessionKeys_1.next(); !releaseSessionKeys_1_1.done; releaseSessionKeys_1_1 = releaseSessionKeys_1.next()) {
81
- var releaseSessionKey = releaseSessionKeys_1_1.value;
59
+ const releaseSessionKeys = Object.keys(eventBufferMap).filter(key => key !== sessionIdentityKey);
60
+ for (const releaseSessionKey of releaseSessionKeys) {
61
+ eventBufferMap[releaseSessionKey].flushAll().finally(() => {
82
62
  eventBufferMap[releaseSessionKey].release();
83
63
  delete eventBufferMap[releaseSessionKey];
84
64
  delete cachedClients[releaseSessionKey];
85
- }
86
- }
87
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
88
- finally {
89
- try {
90
- if (releaseSessionKeys_1_1 && !releaseSessionKeys_1_1.done && (_b = releaseSessionKeys_1.return)) _b.call(releaseSessionKeys_1);
91
- }
92
- finally { if (e_1) throw e_1.error; }
65
+ });
93
66
  }
94
67
  }
95
68
  return eventBufferMap[sessionIdentityKey];
@@ -1,21 +1,22 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- import { __assign } from "tslib";
4
3
  import { Amplify } from '@aws-amplify/core';
5
4
  import { AnalyticsValidationErrorCode, assertValidationError, } from '../../../errors';
6
5
  import { DEFAULT_PERSONALIZE_CONFIG, PERSONALIZE_FLUSH_SIZE_MAX } from './';
7
- export var resolveConfig = function () {
8
- var _a;
9
- var config = (_a = Amplify.getConfig().Analytics) === null || _a === void 0 ? void 0 : _a.Personalize;
10
- var _b = __assign(__assign({}, DEFAULT_PERSONALIZE_CONFIG), config), region = _b.region, trackingId = _b.trackingId, _c = _b.flushSize, flushSize = _c === void 0 ? DEFAULT_PERSONALIZE_CONFIG.flushSize : _c, _d = _b.flushInterval, flushInterval = _d === void 0 ? DEFAULT_PERSONALIZE_CONFIG.flushInterval : _d;
6
+ export const resolveConfig = () => {
7
+ const config = Amplify.getConfig().Analytics?.Personalize;
8
+ const { region, trackingId, flushSize = DEFAULT_PERSONALIZE_CONFIG.flushSize, flushInterval = DEFAULT_PERSONALIZE_CONFIG.flushInterval, } = {
9
+ ...DEFAULT_PERSONALIZE_CONFIG,
10
+ ...config,
11
+ };
11
12
  assertValidationError(!!region, AnalyticsValidationErrorCode.NoRegion);
12
13
  assertValidationError(!!trackingId, AnalyticsValidationErrorCode.NoTrackingId);
13
- assertValidationError(flushSize <= PERSONALIZE_FLUSH_SIZE_MAX, AnalyticsValidationErrorCode.InvalidFlushSize, "FlushSize for Personalize should be less or equal than ".concat(PERSONALIZE_FLUSH_SIZE_MAX));
14
+ assertValidationError(flushSize <= PERSONALIZE_FLUSH_SIZE_MAX, AnalyticsValidationErrorCode.InvalidFlushSize, `FlushSize for Personalize should be less or equal than ${PERSONALIZE_FLUSH_SIZE_MAX}`);
14
15
  return {
15
- region: region,
16
- trackingId: trackingId,
16
+ region,
17
+ trackingId,
17
18
  bufferSize: flushSize + 1,
18
- flushSize: flushSize,
19
- flushInterval: flushInterval,
19
+ flushSize,
20
+ flushInterval,
20
21
  };
21
22
  };
@@ -3,12 +3,12 @@
3
3
  import { updateProviderTrackers, validateTrackerConfiguration, } from '../../../utils';
4
4
  import { record } from './record';
5
5
  // Configured Tracker instances for Pinpoint
6
- var configuredTrackers = {};
6
+ const configuredTrackers = {};
7
7
  // Callback that will emit an appropriate event to Pinpoint when required by the Tracker
8
- var emitTrackingEvent = function (eventName, attributes) {
8
+ const emitTrackingEvent = (eventName, attributes) => {
9
9
  record({
10
10
  name: eventName,
11
- attributes: attributes,
11
+ attributes,
12
12
  });
13
13
  };
14
14
  /**
@@ -24,7 +24,7 @@ var emitTrackingEvent = function (eventName, attributes) {
24
24
  * @throws validation: {@link AnalyticsValidationErrorCode} - Thrown when the provided parameters or library
25
25
  * configuration is incorrect.
26
26
  */
27
- export var configureAutoTrack = function (input) {
27
+ export const configureAutoTrack = (input) => {
28
28
  validateTrackerConfiguration(input);
29
29
  // Initialize or update this provider's trackers
30
30
  updateProviderTrackers(input, emitTrackingEvent, configuredTrackers);
@@ -5,7 +5,7 @@ import { flushEvents as flushEventsCore } from '@aws-amplify/core/internals/prov
5
5
  import { AnalyticsAction } from '@aws-amplify/core/internals/utils';
6
6
  import { ConsoleLogger } from '@aws-amplify/core';
7
7
  import { getAnalyticsUserAgentString } from '../../../utils';
8
- var logger = new ConsoleLogger('Analytics');
8
+ const logger = new ConsoleLogger('Analytics');
9
9
  /**
10
10
  * Flushes all buffered Pinpoint events to the service.
11
11
  *
@@ -13,12 +13,9 @@ var logger = new ConsoleLogger('Analytics');
13
13
  * This API will make a best-effort attempt to flush events from the buffer. Events recorded immediately after invoking
14
14
  * this API may not be included in the flush.
15
15
  */
16
- export var flushEvents = function () {
17
- var _a = resolveConfig(), appId = _a.appId, region = _a.region;
16
+ export const flushEvents = () => {
17
+ const { appId, region } = resolveConfig();
18
18
  resolveCredentials()
19
- .then(function (_a) {
20
- var credentials = _a.credentials, identityId = _a.identityId;
21
- return flushEventsCore(appId, region, credentials, identityId, getAnalyticsUserAgentString(AnalyticsAction.Record));
22
- })
23
- .catch(function (e) { return logger.warn('Failed to flush events', e); });
19
+ .then(({ credentials, identityId }) => flushEventsCore(appId, region, credentials, identityId, getAnalyticsUserAgentString(AnalyticsAction.Record)))
20
+ .catch(e => logger.warn('Failed to flush events', e));
24
21
  };
@@ -1,6 +1,5 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- import { __awaiter, __generator } from "tslib";
4
3
  import { AnalyticsAction } from '@aws-amplify/core/internals/utils';
5
4
  import { updateEndpoint, } from '@aws-amplify/core/internals/providers/pinpoint';
6
5
  import { getAnalyticsUserAgentString } from '../../../utils';
@@ -50,30 +49,19 @@ import { resolveConfig, resolveCredentials } from '../utils';
50
49
  * }
51
50
  * });
52
51
  */
53
- export var identifyUser = function (_a) {
54
- var userId = _a.userId, userProfile = _a.userProfile, options = _a.options;
55
- return __awaiter(void 0, void 0, void 0, function () {
56
- var _b, credentials, identityId, _c, appId, region, userAttributes;
57
- return __generator(this, function (_d) {
58
- switch (_d.label) {
59
- case 0: return [4 /*yield*/, resolveCredentials()];
60
- case 1:
61
- _b = _d.sent(), credentials = _b.credentials, identityId = _b.identityId;
62
- _c = resolveConfig(), appId = _c.appId, region = _c.region;
63
- userAttributes = (options !== null && options !== void 0 ? options : {}).userAttributes;
64
- updateEndpoint({
65
- appId: appId,
66
- category: 'Analytics',
67
- credentials: credentials,
68
- identityId: identityId,
69
- region: region,
70
- userAttributes: userAttributes,
71
- userId: userId,
72
- userProfile: userProfile,
73
- userAgentValue: getAnalyticsUserAgentString(AnalyticsAction.IdentifyUser),
74
- });
75
- return [2 /*return*/];
76
- }
77
- });
52
+ export const identifyUser = async ({ userId, userProfile, options, }) => {
53
+ const { credentials, identityId } = await resolveCredentials();
54
+ const { appId, region } = resolveConfig();
55
+ const { userAttributes } = options ?? {};
56
+ updateEndpoint({
57
+ appId,
58
+ category: 'Analytics',
59
+ credentials,
60
+ identityId,
61
+ region,
62
+ userAttributes,
63
+ userId,
64
+ userProfile,
65
+ userAgentValue: getAnalyticsUserAgentString(AnalyticsAction.IdentifyUser),
78
66
  });
79
67
  };