@imtbl/sdk 0.45.4 → 0.45.6

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.
package/dist/config.js CHANGED
@@ -1,5 +1,274 @@
1
1
  import axios from 'axios';
2
2
 
3
+ const isNode = () => typeof window === 'undefined';
4
+ const isBrowser = () => !isNode();
5
+
6
+ var Detail;
7
+ (function (Detail) {
8
+ Detail["RUNTIME_ID"] = "rid";
9
+ Detail["PASSPORT_CLIENT_ID"] = "passportClientId";
10
+ Detail["ENVIRONMENT"] = "env";
11
+ Detail["PUBLISHABLE_API_KEY"] = "pak";
12
+ Detail["IDENTITY"] = "uid";
13
+ Detail["DOMAIN"] = "domain";
14
+ })(Detail || (Detail = {}));
15
+ var Store;
16
+ (function (Store) {
17
+ Store["EVENTS"] = "events";
18
+ Store["RUNTIME"] = "runtime";
19
+ })(Store || (Store = {}));
20
+ const POLLING_FREQUENCY = 5000;
21
+
22
+ const IMTBL_API = 'https://api.x.immutable.com';
23
+ async function post(path, data) {
24
+ const client = axios.create({
25
+ baseURL: IMTBL_API,
26
+ });
27
+ const payload = JSON.stringify(data);
28
+ const body = {
29
+ payload: btoa(payload),
30
+ };
31
+ const response = await client.post(path, body);
32
+ return response.data;
33
+ }
34
+
35
+ /**
36
+ * Abstraction on localstorage
37
+ */
38
+ const localStoragePrefix = '__IMX-';
39
+ const hasLocalstorage = () => isBrowser() && window.localStorage;
40
+ const parseItem = (payload) => {
41
+ // Try to parse, if can't be parsed assume string
42
+ // and return string
43
+ if (payload === null)
44
+ return undefined;
45
+ try {
46
+ return JSON.parse(payload);
47
+ }
48
+ catch (error) {
49
+ // Assumes it's a string.
50
+ return payload;
51
+ }
52
+ };
53
+ const serialiseItem = (payload) => {
54
+ if (typeof payload === 'string') {
55
+ return payload;
56
+ }
57
+ return JSON.stringify(payload);
58
+ };
59
+ /**
60
+ * GenKey will take into account the namespace
61
+ * as well as if being run in the Link, it will tap into the link
62
+ * @param {string} key
63
+ * @returns key
64
+ */
65
+ const genKey = (key) => `${localStoragePrefix}${key}`;
66
+ function getItem(key) {
67
+ if (hasLocalstorage()) {
68
+ return parseItem(window.localStorage.getItem(genKey(key)));
69
+ }
70
+ return undefined;
71
+ }
72
+ const setItem = (key, payload) => {
73
+ if (hasLocalstorage()) {
74
+ window.localStorage.setItem(genKey(key), serialiseItem(payload));
75
+ return true;
76
+ }
77
+ return false;
78
+ };
79
+
80
+ // In memory storage for events and other data
81
+ let EVENT_STORE;
82
+ let RUNTIME_DETAILS;
83
+ // Initialise store and runtime
84
+ const initialise$1 = () => {
85
+ EVENT_STORE = getItem(Store.EVENTS) || [];
86
+ RUNTIME_DETAILS = getItem(Store.RUNTIME) || {};
87
+ };
88
+ initialise$1();
89
+ // Runtime Details
90
+ const storeDetail = (key, value) => {
91
+ RUNTIME_DETAILS = {
92
+ ...RUNTIME_DETAILS,
93
+ [key]: value,
94
+ };
95
+ setItem(Store.RUNTIME, RUNTIME_DETAILS);
96
+ };
97
+ const getDetail = (key) => {
98
+ // Handle the scenario where detail is a falsy value
99
+ if (RUNTIME_DETAILS[key] === undefined) {
100
+ return undefined;
101
+ }
102
+ return RUNTIME_DETAILS[key];
103
+ };
104
+ const getAllDetails = () => RUNTIME_DETAILS;
105
+ // Events
106
+ const getEvents = () => EVENT_STORE;
107
+ const addEvent = (event) => {
108
+ EVENT_STORE.push(event);
109
+ setItem(Store.EVENTS, EVENT_STORE);
110
+ };
111
+ const removeSentEvents = (numberOfEvents) => {
112
+ EVENT_STORE = EVENT_STORE.slice(numberOfEvents);
113
+ setItem(Store.EVENTS, EVENT_STORE);
114
+ };
115
+ const flattenProperties = (properties) => {
116
+ const propertyMap = [];
117
+ Object.entries(properties).forEach(([key, value]) => {
118
+ if (typeof key === 'string'
119
+ || typeof value === 'string'
120
+ || typeof value === 'number'
121
+ || typeof value === 'boolean') {
122
+ propertyMap.push([key, value.toString()]);
123
+ }
124
+ });
125
+ return propertyMap;
126
+ };
127
+
128
+ let initialised = false;
129
+ const isInitialised = () => initialised;
130
+ const getReferrer = () => {
131
+ if (isNode()) {
132
+ return '';
133
+ }
134
+ if (window.location.ancestorOrigins
135
+ && window.location.ancestorOrigins.length > 0) {
136
+ return new URL(window.location.ancestorOrigins[0]).hostname;
137
+ }
138
+ return document.referrer ? new URL(window.document.referrer).hostname : '';
139
+ };
140
+ const runtimeHost = () => {
141
+ if (isNode()) {
142
+ return '';
143
+ }
144
+ if (window.opener || window.parent !== window) {
145
+ return getReferrer();
146
+ }
147
+ return new URL(window.location.href).hostname;
148
+ };
149
+ const getRuntimeDetails = () => {
150
+ if (isNode()) {
151
+ return { browser: 'nodejs' };
152
+ }
153
+ const domain = runtimeHost();
154
+ if (domain) {
155
+ storeDetail(Detail.DOMAIN, domain);
156
+ }
157
+ return {
158
+ browser: window.navigator.userAgent,
159
+ domain,
160
+ tz: Intl.DateTimeFormat().resolvedOptions().timeZone,
161
+ screen: `${window.screen.width}x${window.screen.height}`,
162
+ };
163
+ };
164
+ const initialise = async () => {
165
+ const runtimeDetails = flattenProperties(getRuntimeDetails());
166
+ // Get any existing runtimeId and send it along with the initialise
167
+ const existingRuntimeId = getDetail(Detail.RUNTIME_ID);
168
+ const body = {
169
+ version: 1,
170
+ data: {
171
+ runtimeDetails,
172
+ runtimeId: existingRuntimeId,
173
+ },
174
+ };
175
+ const response = await post('/v1/sdk/initialise', body);
176
+ // Get runtimeId and store it
177
+ const { runtimeId } = response;
178
+ storeDetail(Detail.RUNTIME_ID, runtimeId);
179
+ initialised = true;
180
+ };
181
+
182
+ function errorBoundary(fn) {
183
+ const wrappedFunction = ((...args) => {
184
+ try {
185
+ // Execute the original function
186
+ const result = fn(...args);
187
+ if (result instanceof Promise) {
188
+ // Silent fail for now, in future
189
+ // we can send errors to a logging service
190
+ return result.catch(() => undefined);
191
+ }
192
+ return result;
193
+ }
194
+ catch (error) {
195
+ // As above, fail silently for now
196
+ return undefined;
197
+ }
198
+ });
199
+ return wrappedFunction;
200
+ }
201
+
202
+ function isTestEnvironment() {
203
+ if (typeof process === 'undefined') {
204
+ return false;
205
+ }
206
+ return process.env.JEST_WORKER_ID !== undefined;
207
+ }
208
+
209
+ // Store the event in the event store
210
+ const trackFn = (moduleName, eventName, properties) => {
211
+ const event = {
212
+ event: `${moduleName}.${eventName}`,
213
+ time: new Date().toISOString(),
214
+ ...(properties && { properties: flattenProperties(properties) }),
215
+ };
216
+ addEvent(event);
217
+ };
218
+ const track = errorBoundary(trackFn);
219
+ // Sending events to the server
220
+ const flushFn = async () => {
221
+ // Don't flush if not initialised
222
+ if (isInitialised() === false) {
223
+ await initialise();
224
+ return;
225
+ }
226
+ const events = getEvents();
227
+ if (events.length === 0) {
228
+ return;
229
+ }
230
+ // Track events length here, incase
231
+ const numEvents = events.length;
232
+ // Get details and send it with the track request
233
+ const details = getAllDetails();
234
+ const metricsPayload = {
235
+ version: 1,
236
+ data: {
237
+ events,
238
+ details,
239
+ },
240
+ };
241
+ const response = await post('/v1/sdk/metrics', metricsPayload);
242
+ if (response instanceof Error) {
243
+ return;
244
+ }
245
+ // Clear events if successfully posted
246
+ removeSentEvents(numEvents);
247
+ };
248
+ const flush = errorBoundary(flushFn);
249
+ // Flush events every 5 seconds
250
+ const flushPoll = async () => {
251
+ await flush();
252
+ setTimeout(flushPoll, POLLING_FREQUENCY);
253
+ };
254
+ // This will get initialised when module is imported.
255
+ if (!isTestEnvironment()) {
256
+ errorBoundary(flushPoll)();
257
+ }
258
+
259
+ const setEnvironmentFn = (env) => {
260
+ storeDetail(Detail.ENVIRONMENT, env);
261
+ };
262
+ const setEnvironment = errorBoundary(setEnvironmentFn);
263
+ const setPublishableApiKeyFn = (publishableApiKey) => {
264
+ storeDetail(Detail.PUBLISHABLE_API_KEY, publishableApiKey);
265
+ };
266
+ const setPublishableApiKey = errorBoundary(setPublishableApiKeyFn);
267
+
268
+ track('metrics', 'sdk_version', {
269
+ version: '0.45.6',
270
+ });
271
+
3
272
  var Environment;
4
273
  (function (Environment) {
5
274
  Environment["PRODUCTION"] = "production";
@@ -12,6 +281,8 @@ class ImmutableConfiguration {
12
281
  publishableKey;
13
282
  constructor(options) {
14
283
  this.environment = options.environment;
284
+ setEnvironment(options.environment);
285
+ track('config', 'created_imtbl_config');
15
286
  }
16
287
  }
17
288
  const API_KEY_PREFIX = 'sk_imapik-';
@@ -27,6 +298,7 @@ const addPublishableKeyToAxiosHeader = (publishableKey) => {
27
298
  throw new Error('Invalid Publishable key. Create your Publishable key in Immutable developer hub.'
28
299
  + ' https://hub.immutable.com');
29
300
  }
301
+ setPublishableApiKey(publishableKey);
30
302
  axios.defaults.headers.common['x-immutable-publishable-key'] = publishableKey;
31
303
  };
32
304
  const addRateLimitingKeyToAxiosHeader = (rateLimitingKey) => {