@livechat/customer-sdk 3.1.2 → 3.1.3

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.
@@ -105,43 +105,125 @@
105
105
 
106
106
  var _ref = {},
107
107
  hasOwnProperty = _ref.hasOwnProperty;
108
+ /**
109
+ * returns true or false depending if the provided property is present inside the provided object
110
+ * @example
111
+ * hasOwn('a', { a: 1, b: 2 })
112
+ * // returns true
113
+ */
108
114
  function hasOwn(prop, obj) {
109
115
  return hasOwnProperty.call(obj, prop);
110
116
  }
111
117
 
118
+ /**
119
+ * returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level
120
+ * @example
121
+ * const arr = [{ a: [1, 2] }, { a: [3, 4] }, { a: [5, 6] }]
122
+ * flatMap(el => el.a, arr)
123
+ * // returns [1, 2, 3, 4, 5, 6]
124
+ */
112
125
  function flatMap(iteratee, arr) {
113
126
  var _ref;
114
127
  return (_ref = []).concat.apply(_ref, arr.map(iteratee));
115
128
  }
116
129
 
117
- var isArray = Array.isArray;
130
+ /**
131
+ * determines whether provided value is an array
132
+ * @example
133
+ * isArray([1, 2])
134
+ * // returns true
135
+ * isArray('hello')
136
+ * // returns false
137
+ */
138
+ function isArray(arr) {
139
+ return Array.isArray(arr);
140
+ }
118
141
 
142
+ /**
143
+ * returns true or false depending if the provided value is an object
144
+ * @example
145
+ * isObject({ a: 1 })
146
+ * // returns true
147
+ * isObject([1, 2])
148
+ * // returns false
149
+ */
119
150
  // eslint-disable-next-line @typescript-eslint/ban-types
120
151
  function isObject(obj) {
121
152
  return typeof obj === 'object' && obj !== null && !isArray(obj);
122
153
  }
123
154
 
155
+ /**
156
+ * returns an array of the provided object keys
157
+ * @example
158
+ * keys({ a: 1, b: 2, c: 3 })
159
+ * // returns ['a', 'b', 'c']
160
+ */
161
+ function keys(obj) {
162
+ if ('keys' in Object && typeof Object.keys === 'function') {
163
+ return Object.keys(obj);
164
+ }
165
+ var keysArray = [];
166
+ for (var property in obj) {
167
+ if (Object.prototype.hasOwnProperty.call(obj, property)) {
168
+ keysArray.push(property);
169
+ }
170
+ }
171
+ return keysArray;
172
+ }
173
+
174
+ /**
175
+ * maps values of the provided object
176
+ * @example
177
+ * mapValues(val => val.toUpperCase(), { a: 'foo', b: 'bar' })
178
+ * // returns { a: 'FOO', b: 'BAR' }
179
+ */
124
180
  function mapValues(mapper, obj) {
125
- return Object.keys(obj).reduce(function (acc, key) {
181
+ return keys(obj).reduce(function (acc, key) {
126
182
  acc[key] = mapper(obj[key]);
127
183
  return acc;
128
184
  }, {});
129
185
  }
130
186
 
187
+ /**
188
+ * returns the provided value
189
+ * @example
190
+ * identity('hello')
191
+ * // returns 'hello'
192
+ */
131
193
  function identity(value) {
132
194
  return value;
133
195
  }
134
196
 
197
+ /**
198
+ * generates a random id
199
+ * @example
200
+ * generateRandomId()
201
+ * // returns 'd1rjknhhch8'
202
+ */
135
203
  function generateRandomId() {
136
204
  return Math.random().toString(36).substring(2);
137
205
  }
138
206
 
207
+ /**
208
+ * generates an unique id based on the provided object keys
209
+ * @example
210
+ * generateUniqueId({ xuvarw8cao: 1, b837g2nba1d: 2 })
211
+ * // returns 'd1rjknhhch8'
212
+ */
139
213
  function generateUniqueId(map) {
140
214
  var id = generateRandomId();
141
215
  return hasOwn(id, map) ? generateUniqueId(map) : id;
142
216
  }
143
217
 
144
- // based on https://github.com/developit/dlv/blob/d7ec976d12665f1c25dec2acf955dfc2e8757a9c/index.js
218
+ /**
219
+ * returns the value from the specififed path from the provided object
220
+ * @example
221
+ * const obj = { a: { b: [1, 2, 3] } }
222
+ * get('a.b.1', obj)
223
+ * // returns 2
224
+ * get(['a', 'b', '1'], obj)
225
+ * // returns 2
226
+ */
145
227
  function get(propPath, obj) {
146
228
  var arrPath = typeof propPath === 'string' ? propPath.split('.') : propPath;
147
229
  var pathPartIndex = 0;
@@ -152,14 +234,40 @@
152
234
  return result;
153
235
  }
154
236
 
237
+ /**
238
+ * returns true or false depending if the provided value is present inside the provided array or string
239
+ * @example
240
+ * includes('a', ['a', 'b', 'c'])
241
+ * // returns true
242
+ * includes('d', 'abc')
243
+ * // returns false
244
+ */
245
+
155
246
  function includes(value, arrOrStr) {
156
247
  return arrOrStr.indexOf(value) !== -1;
157
248
  }
158
249
 
250
+ /**
251
+ * returns true or false depending if the provided value is an empty object or an empty array
252
+ * @example
253
+ * isEmpty({})
254
+ * // returns true
255
+ */
159
256
  function isEmpty(collection) {
160
257
  return (isArray(collection) ? collection : Object.keys(collection)).length === 0;
161
258
  }
162
259
 
260
+ /**
261
+ * constructs an object from the provided array of objects, grouped by the value of the specified key
262
+ * @example
263
+ * const arr = [
264
+ * { a: 'foo', b: 'bar' },
265
+ * { a: 'foo', b: 'baz' },
266
+ * { a: 'test', b: 'bab' },
267
+ * ]
268
+ * keyBy('a', arr)
269
+ * // returns { foo: { a: 'foo', b: 'baz' }, test: { a: 'test', b: 'bab' } }
270
+ */
163
271
  function keyBy(prop, arr) {
164
272
  return arr.reduce(function (acc, el) {
165
273
  acc[el[prop]] = el;
@@ -167,20 +275,47 @@
167
275
  }, {});
168
276
  }
169
277
 
170
- // TODO: this should return `T | undefined` to match native behavior
278
+ /**
279
+ * returns the last element of the provided array or undefined when array is empty
280
+ * @example
281
+ * last([1, 2, 3])
282
+ * // returns 3
283
+ */
171
284
  function last(arr) {
172
- return arr.length > 0 ? arr[arr.length - 1] : null;
285
+ return arr.length > 0 ? arr[arr.length - 1] : undefined;
173
286
  }
174
287
 
288
+ /**
289
+ * does literally nothing
290
+ * @example
291
+ * somethingAsyncAndDangerous().catch(noop)
292
+ */
175
293
  // eslint-disable-next-line @typescript-eslint/no-empty-function
176
294
  function noop() {}
177
295
 
296
+ /**
297
+ * returns an array of values of the provided object
298
+ * @example
299
+ * values({ a: 1, b: 2, c: 3 })
300
+ * // returns [1, 2, 3]
301
+ */
178
302
  function values(obj) {
179
- return Object.keys(obj).map(function (key) {
303
+ return keys(obj).map(function (key) {
180
304
  return obj[key];
181
305
  });
182
306
  }
183
307
 
308
+ /**
309
+ * sorts values of the provided object or array based on the provided mapping function or the provided prop string
310
+ * @example
311
+ * const obj = {
312
+ * a: { chats: 1 },
313
+ * b: { chats: 3 },
314
+ * c: { chats: 2 },
315
+ * }
316
+ * numericSortBy(el => el.chats * -1, obj)
317
+ * // returns [{ chats: 3 }, { chats: 2 }, { chats: 1 }]
318
+ */
184
319
  function numericSortBy(propOrMapper, collection) {
185
320
  var mapper = typeof propOrMapper === 'function' ? propOrMapper : function (element) {
186
321
  return get(propOrMapper, element);
@@ -190,13 +325,25 @@
190
325
  });
191
326
  }
192
327
 
193
- function pick(props, obj) {
194
- return props.reduce(function (acc, prop) {
328
+ /**
329
+ * picks specified properties from the object
330
+ * @example
331
+ * pick(['b'], { a: 1, b: 2 })
332
+ * // returns { b: 2 }
333
+ */
334
+ function pick(keys, obj) {
335
+ return keys.reduce(function (acc, prop) {
195
336
  acc[prop] = obj[prop];
196
337
  return acc;
197
338
  }, {});
198
339
  }
199
340
 
341
+ /**
342
+ * picks specified props only if they exist on the provided object
343
+ * @example
344
+ * pickOwn(['b'], { a: 1, b: 2 })
345
+ * // returns { b: 2 }
346
+ */
200
347
  function pickOwn(props, obj) {
201
348
  return props.reduce(function (acc, prop) {
202
349
  if (hasOwn(prop, obj)) {
@@ -206,19 +353,41 @@
206
353
  }, {});
207
354
  }
208
355
 
209
- var toPairs = function toPairs(obj) {
210
- return Object.keys(obj).map(function (key) {
356
+ /**
357
+ * returns an array of derived from the provided object key-value tuples
358
+ * @example
359
+ * toPairs({ a: 1, b: 2 })
360
+ * // returns [['a', 1], ['b', 2]]
361
+ */
362
+ function toPairs(obj) {
363
+ return keys(obj).map(function (key) {
211
364
  return [key, obj[key]];
212
365
  });
213
- };
366
+ }
214
367
 
215
- var stringCompare = function stringCompare(strA, strB) {
368
+ /**
369
+ * returns 0 for matching strings
370
+ * return -1 for string with lower char code at some position
371
+ * return 1 for string with greater char code at some position
372
+ * @example
373
+ * stringCompare('abc', 'abc')
374
+ * // returns 0
375
+ * stringCompare('abc', 'abd')
376
+ * // returns -1
377
+ */
378
+ function stringCompare(strA, strB) {
216
379
  if (strA === strB) {
217
380
  return 0;
218
381
  }
219
382
  return strA < strB ? -1 : 1;
220
- };
383
+ }
221
384
 
385
+ /**
386
+ * returns an array with all the duplicates from the provided array removed based on the iteratee function
387
+ * @example
388
+ * uniqBy(el => el.toString(), [1, '1', 2, '3', 3])
389
+ * // returns [1, 2, '3']
390
+ */
222
391
  function uniqBy(iteratee, arr) {
223
392
  // with polyfills this could be just: return Array.from(new Set(arr.map(iteratee)))
224
393
  var seen = [];
@@ -309,25 +478,18 @@
309
478
  });
310
479
  }
311
480
 
312
- function getRoot() {
313
- return new Promise(function (resolve) {
314
- var next = function next() {
315
- if (!document.body) {
316
- setTimeout(next, 100);
317
- return;
318
- }
319
- resolve(document.body);
320
- };
321
- next();
322
- });
323
- }
324
-
325
- function removeNode(node) {
326
- var parentNode = node.parentNode;
327
- if (parentNode) {
328
- parentNode.removeChild(node);
329
- }
330
- }
481
+ var ACCOUNTS_URL = "https://accounts.livechatinc.com";
482
+ var buildPath = function buildPath(_ref) {
483
+ var uniqueGroups = _ref.uniqueGroups,
484
+ organizationId = _ref.organizationId,
485
+ groupId = _ref.groupId;
486
+ return "" + (uniqueGroups ? "/v2/customer/" + organizationId + "/" + groupId + "/token" : '/v2/customer/token');
487
+ };
488
+ var buildRequestUrl = function buildRequestUrl(config, env) {
489
+ var url = env === 'production' ? ACCOUNTS_URL : ACCOUNTS_URL.replace('accounts.', "accounts." + env + ".");
490
+ var path = buildPath(config);
491
+ return "" + url + path;
492
+ };
331
493
 
332
494
  var createError = function createError(_ref) {
333
495
  var code = _ref.code,
@@ -337,7 +499,7 @@
337
499
  return err;
338
500
  };
339
501
 
340
- var parseTokenResponse = function parseTokenResponse(token, licenseId) {
502
+ var parseTokenResponse = function parseTokenResponse(token, organizationId) {
341
503
  if ('identity_exception' in token) {
342
504
  throw createError({
343
505
  code: 'SSO_IDENTITY_EXCEPTION',
@@ -356,119 +518,33 @@
356
518
  expiresIn: token.expires_in * 1000,
357
519
  tokenType: token.token_type,
358
520
  creationDate: Date.now(),
359
- licenseId: licenseId
360
- };
361
- };
362
-
363
- var ACCOUNTS_URL = "https://accounts.livechatinc.com";
364
- var buildPath = function buildPath(_ref) {
365
- var uniqueGroups = _ref.uniqueGroups,
366
- licenseId = _ref.licenseId,
367
- groupId = _ref.groupId;
368
- return (uniqueGroups ? "/licence/g" + licenseId + "_" + groupId : '') + "/customer";
369
- };
370
- var buildRequestUrl = function buildRequestUrl(config, env) {
371
- var url = env === 'production' ? ACCOUNTS_URL : ACCOUNTS_URL.replace('accounts.', "accounts." + env + ".");
372
- var path = buildPath(config);
373
- return "" + url + path;
374
- };
375
-
376
- var POST_MESSAGE_ORIGIN = 'https://accounts.livechatinc.com';
377
- var CUSTOMER_AUTH_FOOTPRINT = '@livechat/customer-auth';
378
- var getPostMessageOrigin = function getPostMessageOrigin(env) {
379
- return env === 'production' ? POST_MESSAGE_ORIGIN : POST_MESSAGE_ORIGIN.replace('accounts.', "accounts." + env + ".");
380
- };
381
- var buildParams = function buildParams(_ref, redirectUri) {
382
- var clientId = _ref.clientId,
383
- licenseId = _ref.licenseId;
384
- return {
385
- license_id: String(licenseId),
386
- flow: 'button',
387
- response_type: 'token',
388
- client_id: clientId,
389
- redirect_uri: redirectUri,
390
- post_message_uri: redirectUri,
391
- state: CUSTOMER_AUTH_FOOTPRINT
521
+ organizationId: organizationId
392
522
  };
393
523
  };
394
- var buildIframe = function buildIframe(config, env) {
395
- var redirectUri = getOrigin(String(window.location)) + window.location.pathname;
396
- var params = buildParams(config, redirectUri);
397
- var iframe = document.createElement('iframe');
398
- iframe.style.display = 'none';
399
- iframe.setAttribute('src', buildRequestUrl(config, env) + "?" + buildQueryString(params));
400
- return iframe;
401
- };
402
- var isTokenResponse = function isTokenResponse(data) {
403
- return data && data.state === CUSTOMER_AUTH_FOOTPRINT;
404
- };
405
- function fetchUsingIframe(config, env) {
406
- var licenseId = config.licenseId;
407
- var postMessageOrigin = getPostMessageOrigin(env);
408
- return new Promise(function (resolve, reject) {
409
- var iframe = buildIframe(config, env);
410
- var cleanup = function cleanup() {
411
- removeNode(iframe);
412
- // eslint-disable-next-line no-use-before-define
413
- window.removeEventListener('message', listener, false);
414
- };
415
- var timeoutId = setTimeout(function () {
416
- cleanup();
417
- reject(createError({
418
- message: 'Request timed out.',
419
- code: 'REQUEST_TIMEOUT'
420
- }));
421
- }, 15 * 1000);
422
- var listener = function listener(_ref2) {
423
- var origin = _ref2.origin,
424
- data = _ref2.data;
425
- if (origin !== postMessageOrigin) {
426
- return;
427
- }
428
- if (!isTokenResponse(data)) {
429
- return;
430
- }
431
- clearTimeout(timeoutId);
432
- cleanup();
433
- try {
434
- resolve(parseTokenResponse(data, licenseId));
435
- } catch (err) {
436
- reject(err);
437
- }
438
- };
439
- window.addEventListener('message', listener, false);
440
- getRoot().then(function (body) {
441
- body.appendChild(iframe);
442
- });
443
- });
444
- }
445
524
 
446
525
  var fetchToken = function fetchToken(config, env) {
447
- if (config.uniqueGroups) {
448
- return fetchUsingIframe(config, env);
449
- }
450
- return unfetch(buildRequestUrl(config, env) + "/token", {
526
+ return unfetch("" + buildRequestUrl(config, env), {
451
527
  method: 'POST',
452
528
  credentials: 'include',
453
529
  body: JSON.stringify({
454
530
  response_type: 'token',
455
531
  grant_type: 'cookie',
456
532
  client_id: config.clientId,
457
- license_id: config.licenseId,
533
+ organization_id: config.organizationId,
458
534
  redirect_uri: getOrigin(String(window.location)) + window.location.pathname
459
535
  })
460
536
  }).then(function (res) {
461
537
  return res.json();
462
538
  }).then(function (token) {
463
- return parseTokenResponse(token, config.licenseId);
539
+ return parseTokenResponse(token, config.organizationId);
464
540
  });
465
541
  };
466
542
 
467
543
  var validateConfig = function validateConfig(_ref) {
468
- var licenseId = _ref.licenseId,
544
+ var organizationId = _ref.organizationId,
469
545
  clientId = _ref.clientId;
470
- if (typeof licenseId !== 'number' || typeof clientId !== 'string') {
471
- throw new Error('You need to pass valid configuration object: { licenseId, clientId }.');
546
+ if (typeof organizationId !== 'string' || typeof clientId !== 'string') {
547
+ throw new Error('You need to pass valid configuration object: { organizationId, clientId }.');
472
548
  }
473
549
  };
474
550
 
@@ -477,25 +553,39 @@
477
553
  expiresIn = _ref.expiresIn;
478
554
  return Date.now() >= creationDate + expiresIn;
479
555
  };
480
- var createAuth = function createAuth(config, env) {
556
+ var createAuth = function createAuth(config, licenseId, env) {
481
557
  validateConfig(config);
482
- var cacheKey = "" + "@@lc_auth_token:" + config.licenseId + (config.uniqueGroups ? ":" + config.groupId : '');
558
+ var tokenStoragePrefix = config.tokenStoragePrefix || "@@lc_auth_token:";
559
+ var oldCacheKey = "" + tokenStoragePrefix + licenseId + (config.uniqueGroups ? ":" + config.groupId : '');
560
+ var newCacheKey = "" + tokenStoragePrefix + config.organizationId + (config.uniqueGroups ? ":" + config.groupId : '');
483
561
  var pendingTokenRequest = null;
484
562
  var cachedToken = null;
485
- var retrievingToken = storage.getItem(cacheKey).then(function (token) {
563
+ var retrievingToken = storage.getItem(oldCacheKey).then(function (token) {
486
564
  if (retrievingToken === null) {
487
565
  return;
488
566
  }
489
567
  retrievingToken = null;
490
568
  if (!token) {
569
+ storage.removeItem(oldCacheKey).then(function () {
570
+ return storage.getItem(newCacheKey).then(function (newKeyToken) {
571
+ if (!newKeyToken) {
572
+ return;
573
+ }
574
+ cachedToken = JSON.parse(newKeyToken);
575
+ });
576
+ });
491
577
  return;
492
578
  }
493
- cachedToken = JSON.parse(token);
579
+ storage.setItem(newCacheKey, token).then(function () {
580
+ storage.removeItem(oldCacheKey).then(function () {
581
+ cachedToken = JSON.parse(token);
582
+ });
583
+ });
494
584
  });
495
585
  var getFreshToken = function getFreshToken() {
496
586
  pendingTokenRequest = fetchToken(config, env).then(function (token) {
497
587
  pendingTokenRequest = null;
498
- storage.setItem(cacheKey, JSON.stringify(token));
588
+ storage.setItem(newCacheKey, JSON.stringify(token));
499
589
  cachedToken = token;
500
590
  return token;
501
591
  }, function (err) {
@@ -525,7 +615,7 @@
525
615
  var invalidate = function invalidate() {
526
616
  cachedToken = null;
527
617
  retrievingToken = null;
528
- return storage.removeItem(cacheKey);
618
+ return storage.removeItem(newCacheKey);
529
619
  };
530
620
  return {
531
621
  getFreshToken: getFreshToken,
@@ -1094,13 +1184,62 @@
1094
1184
  return sideEffectsMiddleware;
1095
1185
  };
1096
1186
 
1097
- function deferred() {
1098
- var def = {};
1099
- def.promise = new Promise(function (resolve, reject) {
1100
- def.resolve = resolve;
1101
- def.reject = reject;
1187
+ var createBackoff = function createBackoff(_ref) {
1188
+ var _ref$min = _ref.min,
1189
+ min = _ref$min === void 0 ? 1000 : _ref$min,
1190
+ _ref$max = _ref.max,
1191
+ max = _ref$max === void 0 ? 5000 : _ref$max,
1192
+ _ref$jitter = _ref.jitter,
1193
+ jitter = _ref$jitter === void 0 ? 0.5 : _ref$jitter;
1194
+ var attempts = 0;
1195
+ return {
1196
+ duration: function duration() {
1197
+ var ms = min * Math.pow(2, attempts++);
1198
+ if (jitter) {
1199
+ var rand = Math.random();
1200
+ var deviation = Math.floor(rand * jitter * ms);
1201
+ ms = (Math.floor(rand * 10) & 1) === 0 ? ms - deviation : ms + deviation;
1202
+ }
1203
+ return Math.min(ms, max) | 0;
1204
+ },
1205
+ reset: function reset() {
1206
+ attempts = 0;
1207
+ }
1208
+ };
1209
+ };
1210
+
1211
+ /**
1212
+ * promiseTry allows us to move success / error handling to be promise based so we will handle both synchronous and asynchronous execution failures and success properly.
1213
+ * @param anyFunction - function to be called
1214
+ * @returns promise that resolves to the return value of the function
1215
+ * @example
1216
+ * const promise = promiseTry(() => 1)
1217
+ * promise.then(value => console.log(value)) // 1
1218
+ */
1219
+
1220
+ function promiseTry(anyFunction) {
1221
+ return new Promise(function (resolve) {
1222
+ resolve(anyFunction());
1223
+ });
1224
+ }
1225
+
1226
+ /**
1227
+ * Creates a deferred object that can be resolved or rejected later.
1228
+ * @returns A deferred object with a promise and resolve and reject functions.
1229
+ * @example
1230
+ * const def = promiseDeferred()
1231
+ * const promise = def.promise
1232
+ * def.resolve(1)
1233
+ * return promise.then(res => console.log(res)) // 1
1234
+ */
1235
+
1236
+ function promiseDeferred() {
1237
+ var deferred = {};
1238
+ deferred.promise = new Promise(function (resolve, reject) {
1239
+ deferred.resolve = resolve;
1240
+ deferred.reject = reject;
1102
1241
  });
1103
- return def;
1242
+ return deferred;
1104
1243
  }
1105
1244
 
1106
1245
  var createReducer = function createReducer(initialState, reducersMap) {
@@ -1124,6 +1263,8 @@
1124
1263
  var AGENT = 'agent';
1125
1264
  var CUSTOMER = 'customer';
1126
1265
 
1266
+ var LIVECHAT_ORGANIZATION_ID = 'feaf6c0e-9f43-48ff-9ad0-8e24e0350932';
1267
+
1127
1268
  var getAllRequests = function getAllRequests(state) {
1128
1269
  return state.requests;
1129
1270
  };
@@ -1147,9 +1288,9 @@
1147
1288
  return getConnectionStatus(state) === DESTROYED;
1148
1289
  };
1149
1290
  var getEnvPart = function getEnvPart(_ref) {
1150
- var licenseId = _ref.licenseId,
1291
+ var organizationId = _ref.organizationId,
1151
1292
  env = _ref.env;
1152
- if (licenseId === 1520) {
1293
+ if (organizationId === LIVECHAT_ORGANIZATION_ID) {
1153
1294
  return '.staging';
1154
1295
  }
1155
1296
  if (env === 'production') {
@@ -1163,12 +1304,12 @@
1163
1304
  return "https://api" + regionPart + getEnvPart(state) + ".livechatinc.com";
1164
1305
  };
1165
1306
  var getServerUrl = function getServerUrl(state) {
1166
- return getApiOrigin(state) + "/v3.3/customer";
1307
+ return getApiOrigin(state) + "/v3.4/customer";
1167
1308
  };
1168
1309
  var createInitialState = function createInitialState(initialStateData) {
1169
1310
  var _initialStateData$app = initialStateData.application,
1170
1311
  application = _initialStateData$app === void 0 ? {} : _initialStateData$app,
1171
- licenseId = initialStateData.licenseId,
1312
+ organizationId = initialStateData.organizationId,
1172
1313
  _initialStateData$gro = initialStateData.groupId,
1173
1314
  groupId = _initialStateData$gro === void 0 ? null : _initialStateData$gro,
1174
1315
  env = initialStateData.env,
@@ -1185,9 +1326,9 @@
1185
1326
  return {
1186
1327
  application: _extends({}, application, {
1187
1328
  name: "customer_sdk",
1188
- version: "3.1.2"
1329
+ version: "3.1.3"
1189
1330
  }),
1190
- licenseId: licenseId,
1331
+ organizationId: organizationId,
1191
1332
  env: env,
1192
1333
  groupId: groupId,
1193
1334
  chats: {},
@@ -1641,10 +1782,10 @@
1641
1782
  // TODO: this thing is not really well typed and should be improved
1642
1783
  var sendRequestAction = function sendRequestAction(store, action) {
1643
1784
  action.payload.id = generateUniqueId(store.getState().requests);
1644
- var _deferred = deferred(),
1645
- resolve = _deferred.resolve,
1646
- reject = _deferred.reject,
1647
- promise = _deferred.promise;
1785
+ var _promiseDeferred = promiseDeferred(),
1786
+ resolve = _promiseDeferred.resolve,
1787
+ reject = _promiseDeferred.reject,
1788
+ promise = _promiseDeferred.promise;
1648
1789
  action.payload.promise = promise;
1649
1790
  action.payload.resolve = resolve;
1650
1791
  action.payload.reject = reject;
@@ -1652,59 +1793,44 @@
1652
1793
  return promise;
1653
1794
  };
1654
1795
 
1655
- var promiseTry = (function (fn) {
1656
- return new Promise(function (resolve) {
1657
- resolve(fn());
1658
- });
1659
- });
1660
-
1661
- var createBackoff = function createBackoff(_ref) {
1662
- var _ref$min = _ref.min,
1663
- min = _ref$min === void 0 ? 1000 : _ref$min,
1664
- _ref$max = _ref.max,
1665
- max = _ref$max === void 0 ? 5000 : _ref$max,
1666
- _ref$jitter = _ref.jitter,
1667
- jitter = _ref$jitter === void 0 ? 0.5 : _ref$jitter;
1668
- var attempts = 0;
1669
- return {
1670
- duration: function duration() {
1671
- var ms = min * Math.pow(2, attempts++);
1672
- if (jitter) {
1673
- var rand = Math.random();
1674
- var deviation = Math.floor(rand * jitter * ms);
1675
- ms = (Math.floor(rand * 10) & 1) === 0 ? ms - deviation : ms + deviation;
1676
- }
1677
- return Math.min(ms, max) | 0;
1678
- },
1679
- reset: function reset() {
1680
- attempts = 0;
1681
- }
1682
- };
1683
- };
1684
-
1685
1796
  var AUTHENTICATION = 'AUTHENTICATION';
1686
1797
  var CUSTOMER_BANNED$1 = 'CUSTOMER_BANNED';
1687
1798
  var USERS_LIMIT_REACHED = 'USERS_LIMIT_REACHED';
1688
1799
  var WRONG_PRODUCT_VERSION = 'WRONG_PRODUCT_VERSION';
1689
1800
 
1690
- var getSideStorageKey = function getSideStorageKey(store) {
1801
+ var getSideStorageKeyByLicense = function getSideStorageKeyByLicense(store, licenseId) {
1691
1802
  var _store$getState = store.getState(),
1692
- licenseId = _store$getState.licenseId,
1693
1803
  groupId = _store$getState.groupId,
1694
1804
  uniqueGroups = _store$getState.uniqueGroups;
1695
1805
  return "side_storage_" + licenseId + (uniqueGroups ? ":" + groupId : '');
1696
1806
  };
1697
- var getSideStorage = function getSideStorage(store) {
1698
- return storage.getItem(getSideStorageKey(store))["catch"](noop).then(function (sideStorage) {
1699
- return JSON.parse(sideStorage || '{}');
1807
+ var getSideStorageKeyByOrganization = function getSideStorageKeyByOrganization(store) {
1808
+ var _store$getState2 = store.getState(),
1809
+ organizationId = _store$getState2.organizationId,
1810
+ groupId = _store$getState2.groupId,
1811
+ uniqueGroups = _store$getState2.uniqueGroups;
1812
+ return "side_storage_" + organizationId + (uniqueGroups ? ":" + groupId : '');
1813
+ };
1814
+ var getSideStorage = function getSideStorage(store, licenseId) {
1815
+ var sideStorageLicenseKey = getSideStorageKeyByLicense(store, licenseId);
1816
+ var sideStorageOrganizationKey = getSideStorageKeyByOrganization(store);
1817
+ return storage.getItem(sideStorageLicenseKey)["catch"](noop).then(function (sideStorage) {
1818
+ if (!sideStorage) {
1819
+ return storage.getItem(sideStorageOrganizationKey)["catch"](noop).then(function (organizationSideStorage) {
1820
+ return JSON.parse(organizationSideStorage || '{}');
1821
+ })["catch"](noop);
1822
+ }
1823
+ return storage.setItem(sideStorageOrganizationKey, sideStorage)["catch"](noop).then(function () {
1824
+ return storage.removeItem(sideStorageLicenseKey)["catch"](noop).then(function () {
1825
+ return JSON.parse(sideStorage);
1826
+ })["catch"](noop);
1827
+ });
1700
1828
  })
1701
1829
  // shouldnt get triggered, just a defensive measure against malformed storage entries
1702
- ["catch"](function () {
1703
- return {};
1704
- });
1830
+ ["catch"](noop);
1705
1831
  };
1706
1832
  var saveSideStorage = function saveSideStorage(store, sideStorage) {
1707
- return storage.setItem(getSideStorageKey(store), JSON.stringify(sideStorage))["catch"](noop);
1833
+ storage.setItem(getSideStorageKeyByOrganization(store), JSON.stringify(sideStorage))["catch"](noop);
1708
1834
  };
1709
1835
 
1710
1836
  var taskChain = function taskChain(_ref, onSuccess, onError) {
@@ -1745,7 +1871,7 @@
1745
1871
  setTimeout(resolve, ms);
1746
1872
  });
1747
1873
  };
1748
- function createLoginTask(auth, customerDataProvider) {
1874
+ function createLoginTask(auth, customerDataProvider, licenseId) {
1749
1875
  var store;
1750
1876
  var sentPage = null;
1751
1877
  var task;
@@ -1766,7 +1892,7 @@
1766
1892
  return store.dispatch(reconnect(currentBackoffStrategy.duration()));
1767
1893
  };
1768
1894
  var getTokenAndSideStorage = function getTokenAndSideStorage() {
1769
- return Promise.all([auth.getToken(), getSideStorage(store)]);
1895
+ return Promise.all([auth.getToken(), getSideStorage(store, licenseId)]);
1770
1896
  };
1771
1897
  var dispatchSelfId = function dispatchSelfId(_ref2) {
1772
1898
  var token = _ref2[0],
@@ -1906,7 +2032,7 @@
1906
2032
  return;
1907
2033
  }
1908
2034
  var query = buildQueryString({
1909
- license_id: state.licenseId
2035
+ organization_id: state.organizationId
1910
2036
  });
1911
2037
  var payload = {
1912
2038
  session_fields: parseCustomerSessionFields(sessionFields || {}),
@@ -2405,11 +2531,11 @@
2405
2531
  {
2406
2532
  var upgradedPushes = [];
2407
2533
  socket.emit(_extends({}, frame, {
2408
- version: '3.3',
2534
+ version: '3.4',
2409
2535
  payload: _extends({}, frame.payload, {
2410
2536
  pushes: {
2411
- // '3.4': upgradedPushes,
2412
- '3.3': values(serverPushActions).filter(function (pushAction) {
2537
+ // '3.5': upgradedPushes,
2538
+ '3.4': values(serverPushActions).filter(function (pushAction) {
2413
2539
  return (
2414
2540
  // `customer_disconnected` can be sent immediately after opening the connection, before it even received login request
2415
2541
  // therefore it's not possible to subscribe for a particular version of this push - the "connection version" is always used
@@ -2579,9 +2705,10 @@
2579
2705
  var auth = _ref9.auth,
2580
2706
  customerDataProvider = _ref9.customerDataProvider,
2581
2707
  emitter = _ref9.emitter,
2582
- socket = _ref9.socket;
2708
+ socket = _ref9.socket,
2709
+ licenseId = _ref9.licenseId;
2583
2710
  var emit = emitter.emit;
2584
- var loginTask = createLoginTask(auth, customerDataProvider);
2711
+ var loginTask = createLoginTask(auth, customerDataProvider, licenseId);
2585
2712
 
2586
2713
  // TODO: using Store type here is a lie, middleware only provides MiddlewareAPI here
2587
2714
  return function (action, store) {
@@ -2993,14 +3120,14 @@
2993
3120
  resolve = noop;
2994
3121
  },
2995
3122
  check: function check() {
2996
- var deferred$1 = deferred();
2997
- resolve = deferred$1.resolve;
3123
+ var deferred = promiseDeferred();
3124
+ resolve = deferred.resolve;
2998
3125
  timer = setTimeout(function () {
2999
3126
  var err = new Error('Timeout.');
3000
3127
  err.code = 'TIMEOUT';
3001
- deferred$1.reject(err);
3128
+ deferred.reject(err);
3002
3129
  }, 2000);
3003
- return deferred$1.promise;
3130
+ return deferred.promise;
3004
3131
  },
3005
3132
  resolve: function (_resolve) {
3006
3133
  function resolve() {
@@ -3102,7 +3229,7 @@
3102
3229
  var url = (getServerUrl(state) + "/rtm/ws").replace(/^https/, 'wss');
3103
3230
  return createPlatformClient(url, {
3104
3231
  query: {
3105
- license_id: state.licenseId
3232
+ organization_id: state.organizationId
3106
3233
  },
3107
3234
  emitter: emitter
3108
3235
  });
@@ -3394,16 +3521,17 @@
3394
3521
  var lastEventSummary = last(lastEventSummariesArray.sort(function (eventSummaryA, eventSummaryB) {
3395
3522
  return eventSummaryA.thread_id === eventSummaryB.thread_id ? stringCompare(eventSummaryA.event.created_at, eventSummaryB.event.created_at) : stringCompare(eventSummaryA.thread_created_at, eventSummaryB.thread_created_at);
3396
3523
  }));
3397
- if (lastEventSummary) {
3524
+ if (lastEventSummary && chatSummary.lastEventsPerType) {
3398
3525
  chatSummary.lastEvent = chatSummary.lastEventsPerType[lastEventSummary.event.type];
3399
3526
  }
3400
3527
  return chatSummary;
3401
3528
  });
3402
3529
  return {
3403
3530
  chatsSummary: numericSortBy(function (_ref4) {
3531
+ var _ref5;
3404
3532
  var lastEvent = _ref4.lastEvent,
3405
3533
  order = _ref4.order;
3406
- return -1 * (lastEvent !== undefined ? lastEvent.timestamp : order);
3534
+ return -1 * ((_ref5 = lastEvent !== undefined ? lastEvent.timestamp : order) != null ? _ref5 : 0);
3407
3535
  }, chatsSummary),
3408
3536
  totalChats: payload.total_chats,
3409
3537
  users: uniqBy(function (user) {
@@ -3580,9 +3708,9 @@
3580
3708
  };
3581
3709
  }
3582
3710
  };
3583
- var parseResponse = function parseResponse(_ref5) {
3584
- var request = _ref5.request,
3585
- response = _ref5.response;
3711
+ var parseResponse = function parseResponse(_ref6) {
3712
+ var request = _ref6.request,
3713
+ response = _ref6.response;
3586
3714
  switch (response.action) {
3587
3715
  case ACCEPT_GREETING:
3588
3716
  return {
@@ -3836,9 +3964,10 @@
3836
3964
  customerId = _ref.customerId,
3837
3965
  _ref$groupId = _ref.groupId,
3838
3966
  groupId = _ref$groupId === void 0 ? state.groupId : _ref$groupId,
3967
+ licenseId = _ref.licenseId,
3839
3968
  timeZone = _ref.timeZone;
3840
3969
  var ticketBody = _extends({
3841
- licence_id: state.licenseId,
3970
+ licence_id: licenseId,
3842
3971
  ticket_message: '',
3843
3972
  offline_message: '',
3844
3973
  visitor_id: customerId,
@@ -3918,6 +4047,7 @@
3918
4047
  var sendTicketForm = function sendTicketForm(store, auth, _ref2) {
3919
4048
  var filledForm = _ref2.filledForm,
3920
4049
  groupId = _ref2.groupId,
4050
+ licenseId = _ref2.licenseId,
3921
4051
  timeZone = _ref2.timeZone;
3922
4052
  return auth.getToken().then(function (token) {
3923
4053
  var state = store.getState();
@@ -3929,6 +4059,7 @@
3929
4059
  fields: filledForm.fields,
3930
4060
  customerId: token.entityId,
3931
4061
  groupId: groupId,
4062
+ licenseId: licenseId,
3932
4063
  timeZone: timeZone
3933
4064
  });
3934
4065
  return unfetch(url, {
@@ -4080,7 +4211,7 @@
4080
4211
  validateFile(file);
4081
4212
  var state = store.getState();
4082
4213
  var query = buildQueryString({
4083
- license_id: state.licenseId
4214
+ organization_id: state.organizationId
4084
4215
  });
4085
4216
  var url = getServerUrl(state) + "/action/" + UPLOAD_FILE + "?" + query;
4086
4217
  var payload = {
@@ -4146,7 +4277,7 @@
4146
4277
  */
4147
4278
  var log = function log(_ref) {
4148
4279
  var env = _ref.env,
4149
- licenseId = _ref.licenseId,
4280
+ organizationId = _ref.organizationId,
4150
4281
  eventName = _ref.eventName;
4151
4282
  if (env !== 'production' || "customer_sdk" !== 'customer_sdk') {
4152
4283
  return Promise.resolve();
@@ -4154,10 +4285,10 @@
4154
4285
  var message = {
4155
4286
  event_name: eventName,
4156
4287
  severity: 'Informational',
4157
- sdkVersion: "3.1.2"
4288
+ sdkVersion: "3.1.3"
4158
4289
  };
4159
4290
  var body = {
4160
- licence_id: licenseId,
4291
+ organizationId: organizationId,
4161
4292
  event_id: 'chat_widget_customer_sdk',
4162
4293
  message: JSON.stringify(message)
4163
4294
  };
@@ -4272,7 +4403,7 @@
4272
4403
  });
4273
4404
 
4274
4405
  var CHATS_PAGINATION_MAX_LIMIT = 25;
4275
- var init = function init(config, env) {
4406
+ var init = function init(config, env, licenseId) {
4276
4407
  if (env === void 0) {
4277
4408
  env = 'production';
4278
4409
  }
@@ -4287,12 +4418,13 @@
4287
4418
  }));
4288
4419
  var emitter = createMitt();
4289
4420
  var socket = createSocketClient(store);
4290
- var auth = typeof identityProvider === 'function' ? identityProvider() : createAuth(instanceConfig, env);
4421
+ var auth = typeof identityProvider === 'function' ? identityProvider() : createAuth(instanceConfig, licenseId, env);
4291
4422
  store.addSideEffectsHandler(createSideEffectsHandler({
4292
4423
  emitter: emitter,
4293
4424
  socket: socket,
4294
4425
  auth: auth,
4295
- customerDataProvider: customerDataProvider
4426
+ customerDataProvider: customerDataProvider,
4427
+ licenseId: licenseId
4296
4428
  }));
4297
4429
  socketListener(store, socket);
4298
4430
  var sendRequestAction$1 = sendRequestAction.bind(null, store);
@@ -4491,7 +4623,7 @@
4491
4623
  resumeChat: function resumeChat(data) {
4492
4624
  log({
4493
4625
  env: env,
4494
- licenseId: config.licenseId,
4626
+ organizationId: config.organizationId,
4495
4627
  eventName: 'chat_started'
4496
4628
  });
4497
4629
  return sendRequestAction$1(sendRequest(RESUME_CHAT, parseResumeChatData(data)));
@@ -4546,7 +4678,7 @@
4546
4678
  }
4547
4679
  log({
4548
4680
  env: env,
4549
- licenseId: config.licenseId,
4681
+ organizationId: config.organizationId,
4550
4682
  eventName: 'chat_started'
4551
4683
  });
4552
4684
  return sendRequestAction$1(sendRequest(START_CHAT, parseStartChatData(data)));