@twilio/conversations 2.1.0-rc.8 → 3.0.0-rc.1

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/builds/lib.js CHANGED
@@ -147,8 +147,8 @@ var _defineProperty = require('@babel/runtime/helpers/defineProperty');
147
147
  var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
148
148
  require('core-js/modules/es.object.to-string.js');
149
149
  require('core-js/modules/es.promise.js');
150
+ require('core-js/modules/es.array.map.js');
150
151
  require('core-js/modules/web.dom-collections.for-each.js');
151
- require('core-js/modules/es.number.constructor.js');
152
152
  var _regeneratorRuntime = require('@babel/runtime/regenerator');
153
153
  var _typeof = require('@babel/runtime/helpers/typeof');
154
154
  require('core-js/modules/es.array.concat.js');
@@ -156,9 +156,9 @@ require('core-js/modules/es.array.from.js');
156
156
  require('core-js/modules/es.string.iterator.js');
157
157
  var loglevelLog = require('loglevel');
158
158
  var iso8601Duration = require('iso8601-duration');
159
- require('core-js/modules/es.array.map.js');
160
159
  require('core-js/modules/es.array.iterator.js');
161
160
  require('core-js/modules/web.dom-collections.iterator.js');
161
+ require('core-js/modules/es.number.constructor.js');
162
162
  require('core-js/modules/es.regexp.exec.js');
163
163
  require('core-js/modules/es.string.replace.js');
164
164
  require('core-js/modules/es.array.join.js');
@@ -266,7 +266,7 @@ function prepareLine(prefix, args) {
266
266
  return ["".concat(new Date().toISOString(), " Conversations ").concat(prefix, ":")].concat(Array.from(args));
267
267
  }
268
268
 
269
- var log$9 = loglevelLog__namespace.getLogger("twilio-conversations"); // twilio-conversations is used by Flex SDK. Please DO NOT change
269
+ var log$8 = loglevelLog__namespace.getLogger("twilio-conversations"); // twilio-conversations is used by Flex SDK. Please DO NOT change
270
270
 
271
271
  var Logger = /*#__PURE__*/function () {
272
272
  function Logger(prefix) {
@@ -280,7 +280,7 @@ var Logger = /*#__PURE__*/function () {
280
280
  _createClass__default['default'](Logger, [{
281
281
  key: "setLevel",
282
282
  value: function setLevel(level) {
283
- log$9.setLevel(level);
283
+ log$8.setLevel(level);
284
284
  }
285
285
  }, {
286
286
  key: "trace",
@@ -289,7 +289,7 @@ var Logger = /*#__PURE__*/function () {
289
289
  args[_key] = arguments[_key];
290
290
  }
291
291
 
292
- log$9.trace.apply(null, prepareLine(this.prefix + "T", args));
292
+ log$8.trace.apply(null, prepareLine(this.prefix + "T", args));
293
293
  }
294
294
  }, {
295
295
  key: "debug",
@@ -298,7 +298,7 @@ var Logger = /*#__PURE__*/function () {
298
298
  args[_key2] = arguments[_key2];
299
299
  }
300
300
 
301
- log$9.debug.apply(null, prepareLine(this.prefix + "D", args));
301
+ log$8.debug.apply(null, prepareLine(this.prefix + "D", args));
302
302
  }
303
303
  }, {
304
304
  key: "info",
@@ -307,7 +307,7 @@ var Logger = /*#__PURE__*/function () {
307
307
  args[_key3] = arguments[_key3];
308
308
  }
309
309
 
310
- log$9.info.apply(null, prepareLine(this.prefix + "I", args));
310
+ log$8.info.apply(null, prepareLine(this.prefix + "I", args));
311
311
  }
312
312
  }, {
313
313
  key: "warn",
@@ -316,7 +316,7 @@ var Logger = /*#__PURE__*/function () {
316
316
  args[_key4] = arguments[_key4];
317
317
  }
318
318
 
319
- log$9.warn.apply(null, prepareLine(this.prefix + "W", args));
319
+ log$8.warn.apply(null, prepareLine(this.prefix + "W", args));
320
320
  }
321
321
  }, {
322
322
  key: "error",
@@ -325,7 +325,7 @@ var Logger = /*#__PURE__*/function () {
325
325
  args[_key5] = arguments[_key5];
326
326
  }
327
327
 
328
- log$9.error.apply(null, prepareLine(this.prefix + "E", args));
328
+ log$8.error.apply(null, prepareLine(this.prefix + "E", args));
329
329
  }
330
330
  }], [{
331
331
  key: "scope",
@@ -335,7 +335,7 @@ var Logger = /*#__PURE__*/function () {
335
335
  }, {
336
336
  key: "setLevel",
337
337
  value: function setLevel(level) {
338
- log$9.setLevel(level);
338
+ log$8.setLevel(level);
339
339
  }
340
340
  }, {
341
341
  key: "trace",
@@ -344,7 +344,7 @@ var Logger = /*#__PURE__*/function () {
344
344
  args[_key6] = arguments[_key6];
345
345
  }
346
346
 
347
- log$9.trace.apply(null, prepareLine("T", args));
347
+ log$8.trace.apply(null, prepareLine("T", args));
348
348
  }
349
349
  }, {
350
350
  key: "debug",
@@ -353,7 +353,7 @@ var Logger = /*#__PURE__*/function () {
353
353
  args[_key7] = arguments[_key7];
354
354
  }
355
355
 
356
- log$9.debug.apply(null, prepareLine("D", args));
356
+ log$8.debug.apply(null, prepareLine("D", args));
357
357
  }
358
358
  }, {
359
359
  key: "info",
@@ -362,7 +362,7 @@ var Logger = /*#__PURE__*/function () {
362
362
  args[_key8] = arguments[_key8];
363
363
  }
364
364
 
365
- log$9.info.apply(null, prepareLine("I", args));
365
+ log$8.info.apply(null, prepareLine("I", args));
366
366
  }
367
367
  }, {
368
368
  key: "warn",
@@ -371,7 +371,7 @@ var Logger = /*#__PURE__*/function () {
371
371
  args[_key9] = arguments[_key9];
372
372
  }
373
373
 
374
- log$9.warn.apply(null, prepareLine("W", args));
374
+ log$8.warn.apply(null, prepareLine("W", args));
375
375
  }
376
376
  }, {
377
377
  key: "error",
@@ -380,7 +380,7 @@ var Logger = /*#__PURE__*/function () {
380
380
  args[_key10] = arguments[_key10];
381
381
  }
382
382
 
383
- log$9.error.apply(null, prepareLine("E", args));
383
+ log$8.error.apply(null, prepareLine("E", args));
384
384
  }
385
385
  }]);
386
386
 
@@ -426,8 +426,8 @@ var Configuration = function Configuration() {
426
426
  mediaAttachmentsCountLimit: configurationResponse.options.media_attachments_count_limit,
427
427
  mediaAttachmentSizeLimitInMb: configurationResponse.options.media_attachment_size_limit_in_mb,
428
428
  mediaAttachmentsTotalSizeLimitInMb: configurationResponse.options.media_attachments_total_size_limit_in_mb,
429
- emailHistoriesAllowedMimeTypes: configurationResponse.options.email_histories_allowed_mime_types,
430
- emailBodiesAllowedMimeTypes: configurationResponse.options.email_bodies_allowed_mime_types
429
+ emailHistoriesAllowedContentTypes: configurationResponse.options.email_histories_allowed_mime_types,
430
+ emailBodiesAllowedContentTypes: configurationResponse.options.email_bodies_allowed_mime_types
431
431
  };
432
432
  this.typingIndicatorTimeoutOverride = constructorOptions.typingIndicatorTimeoutOverride;
433
433
  this.backoffConfiguration = _objectSpread$3({
@@ -560,7 +560,7 @@ var optionalAttributesValidator = declarativeTypeValidator.custom(function (valu
560
560
  function _createSuper$8(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$8(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
561
561
 
562
562
  function _isNativeReflectConstruct$8() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
563
- var log$8 = Logger.scope("User");
563
+ var log$7 = Logger.scope("User");
564
564
  /**
565
565
  * Extended user information.
566
566
  * Note that `isOnline` and `isNotifiable` properties are eligible
@@ -702,7 +702,7 @@ var User = /*#__PURE__*/function (_ReplayEventEmitter) {
702
702
 
703
703
  case 2:
704
704
  updateReasons = [];
705
- log$8.debug("User for", this.state.identity, "updated:", key, value);
705
+ log$7.debug("User for", this.state.identity, "updated:", key, value);
706
706
  _context.t0 = key;
707
707
  _context.next = _context.t0 === "friendlyName" ? 7 : _context.t0 === "attributes" ? 9 : _context.t0 === "reachability" ? 12 : 15;
708
708
  break;
@@ -716,7 +716,7 @@ var User = /*#__PURE__*/function (_ReplayEventEmitter) {
716
716
  return _context.abrupt("break", 16);
717
717
 
718
718
  case 9:
719
- updateAttributes = parseAttributes(value.value, "Retrieved malformed attributes from the server for user: ".concat(this.state.identity), log$8);
719
+ updateAttributes = parseAttributes(value.value, "Retrieved malformed attributes from the server for user: ".concat(this.state.identity), log$7);
720
720
 
721
721
  if (!isEqual__default['default'](this.state.attributes, updateAttributes)) {
722
722
  this.state.attributes = updateAttributes;
@@ -787,7 +787,7 @@ var User = /*#__PURE__*/function (_ReplayEventEmitter) {
787
787
 
788
788
  case 4:
789
789
  return _context2.abrupt("return", map.get("reachability").then(update).catch(function (err) {
790
- log$8.warn("Failed to get reachability info for ", _this2.state.identity, err);
790
+ log$7.warn("Failed to get reachability info for ", _this2.state.identity, err);
791
791
  }));
792
792
 
793
793
  case 5:
@@ -834,7 +834,7 @@ var User = /*#__PURE__*/function (_ReplayEventEmitter) {
834
834
  }).then(function (map) {
835
835
  _this3.entity = map;
836
836
  map.on("itemUpdated", function (args) {
837
- log$8.debug(_this3.state.entityName + " (" + _this3.state.identity + ") itemUpdated: " + args.item.key);
837
+ log$7.debug(_this3.state.entityName + " (" + _this3.state.identity + ") itemUpdated: " + args.item.key);
838
838
  return _this3._update(args.item.key, args.item.data);
839
839
  });
840
840
  return Promise.all([map.get("friendlyName").then(function (item) {
@@ -845,7 +845,7 @@ var User = /*#__PURE__*/function (_ReplayEventEmitter) {
845
845
  return _this3._update(item.key, item.data);
846
846
  })]);
847
847
  }).then(function () {
848
- log$8.debug("Fetched for", _this3.identity);
848
+ log$7.debug("Fetched for", _this3.identity);
849
849
  _this3.subscribed = "subscribed";
850
850
 
851
851
  _this3.emit("userSubscribed", _this3);
@@ -1238,7 +1238,7 @@ _defineProperty__default['default'](NotificationTypes, "CONSUMPTION_UPDATE", "tw
1238
1238
  function _createSuper$7(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$7(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
1239
1239
 
1240
1240
  function _isNativeReflectConstruct$7() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
1241
- var log$7 = Logger.scope("Participant");
1241
+ var log$6 = Logger.scope("Participant");
1242
1242
  /**
1243
1243
  * A participant represents a remote client in a conversation.
1244
1244
  */
@@ -1263,7 +1263,7 @@ var Participant = /*#__PURE__*/function (_ReplayEventEmitter) {
1263
1263
  _this.links = links;
1264
1264
  _this.services = services;
1265
1265
  _this.state = {
1266
- attributes: parseAttributes(data.attributes, "Retrieved malformed attributes from the server for participant: " + sid, log$7),
1266
+ attributes: parseAttributes(data.attributes, "Retrieved malformed attributes from the server for participant: " + sid, log$6),
1267
1267
  dateCreated: data.dateCreated ? parseTime$1(data.dateCreated) : null,
1268
1268
  dateUpdated: data.dateCreated ? parseTime$1(data.dateUpdated) : null,
1269
1269
  sid: sid,
@@ -1452,7 +1452,7 @@ var Participant = /*#__PURE__*/function (_ReplayEventEmitter) {
1452
1452
  key: "_update",
1453
1453
  value: function _update(data) {
1454
1454
  var updateReasons = [];
1455
- var updateAttributes = parseAttributes(data.attributes, "Retrieved malformed attributes from the server for participant: " + this.state.sid, log$7);
1455
+ var updateAttributes = parseAttributes(data.attributes, "Retrieved malformed attributes from the server for participant: " + this.state.sid, log$6);
1456
1456
 
1457
1457
  if (data.attributes && !isEqual__default['default'](this.state.attributes, updateAttributes)) {
1458
1458
  this.state.attributes = updateAttributes;
@@ -1621,7 +1621,7 @@ __decorate([declarativeTypeValidator.validateTypesAsync(attributesValidator), __
1621
1621
  function _createSuper$6(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$6(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
1622
1622
 
1623
1623
  function _isNativeReflectConstruct$6() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
1624
- var log$6 = Logger.scope("Participants");
1624
+ var log$5 = Logger.scope("Participants");
1625
1625
  /**
1626
1626
  * @classdesc Represents the collection of participants for the conversation
1627
1627
  * @fires Participants#participantJoined
@@ -1697,14 +1697,14 @@ var Participants = /*#__PURE__*/function (_ReplayEventEmitter) {
1697
1697
  mode: "open_existing"
1698
1698
  }).then(function (rosterMap) {
1699
1699
  rosterMap.on("itemAdded", function (args) {
1700
- log$6.debug(_this2.conversation.sid + " itemAdded: " + args.item.key);
1700
+ log$5.debug(_this2.conversation.sid + " itemAdded: " + args.item.key);
1701
1701
 
1702
1702
  _this2.upsertParticipant(args.item.key, args.item.data).then(function (participant) {
1703
1703
  _this2.emit("participantJoined", participant);
1704
1704
  });
1705
1705
  });
1706
1706
  rosterMap.on("itemRemoved", function (args) {
1707
- log$6.debug(_this2.conversation.sid + " itemRemoved: " + args.key);
1707
+ log$5.debug(_this2.conversation.sid + " itemRemoved: " + args.key);
1708
1708
  var participantSid = args.key;
1709
1709
 
1710
1710
  if (!_this2.participants.has(participantSid)) {
@@ -1722,7 +1722,7 @@ var Participants = /*#__PURE__*/function (_ReplayEventEmitter) {
1722
1722
  _this2.emit("participantLeft", leftParticipant);
1723
1723
  });
1724
1724
  rosterMap.on("itemUpdated", function (args) {
1725
- log$6.debug(_this2.conversation.sid + " itemUpdated: " + args.item.key);
1725
+ log$5.debug(_this2.conversation.sid + " itemUpdated: " + args.item.key);
1726
1726
 
1727
1727
  _this2.upsertParticipant(args.item.key, args.item.data);
1728
1728
  });
@@ -1744,10 +1744,10 @@ var Participants = /*#__PURE__*/function (_ReplayEventEmitter) {
1744
1744
  _this2.rosterEntityPromise = null;
1745
1745
 
1746
1746
  if (_this2.services.syncClient.connectionState != "disconnected") {
1747
- log$6.error("Failed to get roster object for conversation", _this2.conversation.sid, err);
1747
+ log$5.error("Failed to get roster object for conversation", _this2.conversation.sid, err);
1748
1748
  }
1749
1749
 
1750
- log$6.debug("ERROR: Failed to get roster object for conversation", _this2.conversation.sid, err);
1750
+ log$5.debug("ERROR: Failed to get roster object for conversation", _this2.conversation.sid, err);
1751
1751
  throw err;
1752
1752
  });
1753
1753
  }
@@ -2097,117 +2097,140 @@ var Media = /*#__PURE__*/function () {
2097
2097
 
2098
2098
  }, {
2099
2099
  key: "getContentTemporaryUrl",
2100
- value: function () {
2101
- var _getContentTemporaryUrl = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee() {
2102
- var _this$mcsMedia$getCon, _this$mcsMedia;
2100
+ value: function getContentTemporaryUrl() {
2101
+ var _this = this;
2103
2102
 
2104
- return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) {
2105
- while (1) {
2106
- switch (_context.prev = _context.next) {
2107
- case 0:
2108
- _context.next = 2;
2109
- return this._fetchMcsMedia();
2103
+ return new mcsClient.CancellablePromise( /*#__PURE__*/function () {
2104
+ var _ref = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee(resolve, reject, onCancel) {
2105
+ var _this$mcsMedia;
2110
2106
 
2111
- case 2:
2112
- return _context.abrupt("return", (_this$mcsMedia$getCon = (_this$mcsMedia = this.mcsMedia) === null || _this$mcsMedia === void 0 ? void 0 : _this$mcsMedia.getContentUrl()) !== null && _this$mcsMedia$getCon !== void 0 ? _this$mcsMedia$getCon : null);
2107
+ var fetchMediaRequest, contentUrlRequest, mcsMedia;
2108
+ return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) {
2109
+ while (1) {
2110
+ switch (_context.prev = _context.next) {
2111
+ case 0:
2112
+ fetchMediaRequest = _this._fetchMcsMedia();
2113
+ contentUrlRequest = (_this$mcsMedia = _this.mcsMedia) === null || _this$mcsMedia === void 0 ? void 0 : _this$mcsMedia.getContentUrl();
2114
+ onCancel(function () {
2115
+ fetchMediaRequest.cancel();
2113
2116
 
2114
- case 3:
2115
- case "end":
2116
- return _context.stop();
2117
- }
2118
- }
2119
- }, _callee, this);
2120
- }));
2117
+ if (contentUrlRequest) {
2118
+ contentUrlRequest.cancel();
2119
+ }
2120
+ });
2121
+ _context.prev = 3;
2121
2122
 
2122
- function getContentTemporaryUrl() {
2123
- return _getContentTemporaryUrl.apply(this, arguments);
2124
- }
2123
+ if (_this.mcsMedia) {
2124
+ _context.next = 9;
2125
+ break;
2126
+ }
2125
2127
 
2126
- return getContentTemporaryUrl;
2127
- }()
2128
- /**
2129
- * Returns cached direct content URL for the media.
2130
- *
2131
- * This URL will expire in several minutes. This function does not refresh the URL and can be used to query it several times
2132
- * without causing network traffic.
2133
- * If the URL becomes expired, you need to request a new one using getContentTemporaryUrl().
2134
- *
2135
- * @returns {Promise<String>}
2136
- */
2128
+ _context.next = 7;
2129
+ return fetchMediaRequest;
2137
2130
 
2138
- }, {
2139
- key: "getCachedTemporaryUrl",
2140
- value: function () {
2141
- var _getCachedTemporaryUrl = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee2() {
2142
- var _this$mcsMedia$getCac, _this$mcsMedia2;
2131
+ case 7:
2132
+ mcsMedia = _context.sent;
2133
+ contentUrlRequest = mcsMedia.getContentUrl();
2143
2134
 
2144
- return _regeneratorRuntime__default['default'].wrap(function _callee2$(_context2) {
2145
- while (1) {
2146
- switch (_context2.prev = _context2.next) {
2147
- case 0:
2148
- _context2.next = 2;
2149
- return this._fetchMcsMedia();
2135
+ case 9:
2136
+ _context.t0 = resolve;
2150
2137
 
2151
- case 2:
2152
- return _context2.abrupt("return", (_this$mcsMedia$getCac = (_this$mcsMedia2 = this.mcsMedia) === null || _this$mcsMedia2 === void 0 ? void 0 : _this$mcsMedia2.getCachedContentUrl()) !== null && _this$mcsMedia$getCac !== void 0 ? _this$mcsMedia$getCac : null);
2138
+ if (!contentUrlRequest) {
2139
+ _context.next = 16;
2140
+ break;
2141
+ }
2153
2142
 
2154
- case 3:
2155
- case "end":
2156
- return _context2.stop();
2157
- }
2158
- }
2159
- }, _callee2, this);
2160
- }));
2143
+ _context.next = 13;
2144
+ return contentUrlRequest;
2161
2145
 
2162
- function getCachedTemporaryUrl() {
2163
- return _getCachedTemporaryUrl.apply(this, arguments);
2164
- }
2146
+ case 13:
2147
+ _context.t1 = _context.sent;
2148
+ _context.next = 17;
2149
+ break;
2165
2150
 
2166
- return getCachedTemporaryUrl;
2167
- }()
2151
+ case 16:
2152
+ _context.t1 = null;
2153
+
2154
+ case 17:
2155
+ _context.t2 = _context.t1;
2156
+ (0, _context.t0)(_context.t2);
2157
+ _context.next = 24;
2158
+ break;
2159
+
2160
+ case 21:
2161
+ _context.prev = 21;
2162
+ _context.t3 = _context["catch"](3);
2163
+ reject(_context.t3);
2164
+
2165
+ case 24:
2166
+ case "end":
2167
+ return _context.stop();
2168
+ }
2169
+ }
2170
+ }, _callee, null, [[3, 21]]);
2171
+ }));
2172
+
2173
+ return function (_x, _x2, _x3) {
2174
+ return _ref.apply(this, arguments);
2175
+ };
2176
+ }());
2177
+ }
2168
2178
  }, {
2169
2179
  key: "_fetchMcsMedia",
2170
- value: function () {
2171
- var _fetchMcsMedia2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee3() {
2172
- return _regeneratorRuntime__default['default'].wrap(function _callee3$(_context3) {
2173
- while (1) {
2174
- switch (_context3.prev = _context3.next) {
2175
- case 0:
2176
- if (this.mcsMedia) {
2177
- _context3.next = 8;
2178
- break;
2179
- }
2180
+ value: function _fetchMcsMedia() {
2181
+ var _this2 = this;
2180
2182
 
2181
- if (!this.services.mcsClient) {
2182
- _context3.next = 7;
2183
+ return new mcsClient.CancellablePromise( /*#__PURE__*/function () {
2184
+ var _ref2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee2(resolve, reject, onCancel) {
2185
+ var request;
2186
+ return _regeneratorRuntime__default['default'].wrap(function _callee2$(_context2) {
2187
+ while (1) {
2188
+ switch (_context2.prev = _context2.next) {
2189
+ case 0:
2190
+ request = _this2.services.mcsClient.get(_this2.state.sid);
2191
+
2192
+ if (!_this2.services.mcsClient) {
2193
+ _context2.next = 14;
2194
+ break;
2195
+ }
2196
+
2197
+ onCancel(function () {
2198
+ return request.cancel();
2199
+ });
2200
+ _context2.prev = 3;
2201
+ _context2.next = 6;
2202
+ return request;
2203
+
2204
+ case 6:
2205
+ _this2.mcsMedia = _context2.sent;
2206
+ resolve(_this2.mcsMedia);
2207
+ _context2.next = 13;
2183
2208
  break;
2184
- }
2185
2209
 
2186
- _context3.next = 4;
2187
- return this.services.mcsClient.get(this.state.sid);
2210
+ case 10:
2211
+ _context2.prev = 10;
2212
+ _context2.t0 = _context2["catch"](3);
2213
+ reject(_context2.t0);
2188
2214
 
2189
- case 4:
2190
- this.mcsMedia = _context3.sent;
2191
- _context3.next = 8;
2192
- break;
2215
+ case 13:
2216
+ return _context2.abrupt("return");
2193
2217
 
2194
- case 7:
2195
- throw new Error("Media Content Service is unavailable");
2218
+ case 14:
2219
+ reject(new Error("Media Content Service is unavailable"));
2196
2220
 
2197
- case 8:
2198
- case "end":
2199
- return _context3.stop();
2221
+ case 15:
2222
+ case "end":
2223
+ return _context2.stop();
2224
+ }
2200
2225
  }
2201
- }
2202
- }, _callee3, this);
2203
- }));
2204
-
2205
- function _fetchMcsMedia() {
2206
- return _fetchMcsMedia2.apply(this, arguments);
2207
- }
2226
+ }, _callee2, null, [[3, 10]]);
2227
+ }));
2208
2228
 
2209
- return _fetchMcsMedia;
2210
- }()
2229
+ return function (_x4, _x5, _x6) {
2230
+ return _ref2.apply(this, arguments);
2231
+ };
2232
+ }());
2233
+ }
2211
2234
  }]);
2212
2235
 
2213
2236
  return Media;
@@ -2463,7 +2486,7 @@ function DetailedDeliveryReceipt(descriptor) {
2463
2486
  function _createSuper$5(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$5(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
2464
2487
 
2465
2488
  function _isNativeReflectConstruct$5() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
2466
- var log$5 = Logger.scope("Message");
2489
+ var log$4 = Logger.scope("Message");
2467
2490
  /**
2468
2491
  * A message in a conversation.
2469
2492
  */
@@ -2501,7 +2524,7 @@ var Message = /*#__PURE__*/function (_ReplayEventEmitter) {
2501
2524
  timestamp: data.timestamp ? new Date(data.timestamp) : null,
2502
2525
  dateUpdated: data.dateUpdated ? new Date(data.dateUpdated) : null,
2503
2526
  lastUpdatedBy: (_data$lastUpdatedBy = data.lastUpdatedBy) !== null && _data$lastUpdatedBy !== void 0 ? _data$lastUpdatedBy : null,
2504
- attributes: parseAttributes(data.attributes, "Got malformed attributes for the message ".concat(data.sid), log$5),
2527
+ attributes: parseAttributes(data.attributes, "Got malformed attributes for the message ".concat(data.sid), log$4),
2505
2528
  type: (_data$type = data.type) !== null && _data$type !== void 0 ? _data$type : "text",
2506
2529
  media: data.type && data.type === "media" && data.media ? new Media(data.media, _this.services) : null,
2507
2530
  medias: data.type && data.type === "media" && data.medias ? data.medias.map(function (m) {
@@ -2637,7 +2660,7 @@ var Message = /*#__PURE__*/function (_ReplayEventEmitter) {
2637
2660
  }, {
2638
2661
  key: "attachedMedia",
2639
2662
  get: function get() {
2640
- return this.getMediaByCategory(["media"]);
2663
+ return this.getMediaByCategories(["media"]);
2641
2664
  }
2642
2665
  /**
2643
2666
  * The server-assigned unique identifier of the authoring participant.
@@ -2665,8 +2688,8 @@ var Message = /*#__PURE__*/function (_ReplayEventEmitter) {
2665
2688
  */
2666
2689
 
2667
2690
  }, {
2668
- key: "getMediaByCategory",
2669
- value: function getMediaByCategory(categories) {
2691
+ key: "getMediaByCategories",
2692
+ value: function getMediaByCategories(categories) {
2670
2693
  var _this$state$medias;
2671
2694
 
2672
2695
  return ((_this$state$medias = this.state.medias) !== null && _this$state$medias !== void 0 ? _this$state$medias : []).filter(function (m) {
@@ -2675,7 +2698,7 @@ var Message = /*#__PURE__*/function (_ReplayEventEmitter) {
2675
2698
  }
2676
2699
  /**
2677
2700
  * Get a media descriptor for an email body attachment of a provided type.
2678
- * Allowed body types are returned in the Conversation.limits().emailBodiesAllowedMimeTypes array.
2701
+ * Allowed body types are returned in the Conversation.limits().emailBodiesAllowedContentTypes array.
2679
2702
  * @param type Type of email body to request, defaults to `text/plain`.
2680
2703
  */
2681
2704
 
@@ -2685,13 +2708,13 @@ var Message = /*#__PURE__*/function (_ReplayEventEmitter) {
2685
2708
  var _this$getMediaByCateg, _this$getMediaByCateg2;
2686
2709
 
2687
2710
  var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "text/plain";
2688
- return (_this$getMediaByCateg = (_this$getMediaByCateg2 = this.getMediaByCategory(["body"])) === null || _this$getMediaByCateg2 === void 0 ? void 0 : _this$getMediaByCateg2.filter(function (m) {
2711
+ return (_this$getMediaByCateg = (_this$getMediaByCateg2 = this.getMediaByCategories(["body"])) === null || _this$getMediaByCateg2 === void 0 ? void 0 : _this$getMediaByCateg2.filter(function (m) {
2689
2712
  return m.contentType == type;
2690
2713
  }).shift()) !== null && _this$getMediaByCateg !== void 0 ? _this$getMediaByCateg : null;
2691
2714
  }
2692
2715
  /**
2693
2716
  * Get a media descriptor for an email history attachment of a provided type.
2694
- * Allowed body types are returned in the Conversation.limits().emailHistoriesAllowedMimeTypes array.
2717
+ * Allowed body types are returned in the Conversation.limits().emailHistoriesAllowedContentTypes array.
2695
2718
  * @param type Type of email history to request, defaults to `text/plain`.
2696
2719
  */
2697
2720
 
@@ -2701,7 +2724,7 @@ var Message = /*#__PURE__*/function (_ReplayEventEmitter) {
2701
2724
  var _this$getMediaByCateg3, _this$getMediaByCateg4;
2702
2725
 
2703
2726
  var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "text/plain";
2704
- return (_this$getMediaByCateg3 = (_this$getMediaByCateg4 = this.getMediaByCategory(["history"])) === null || _this$getMediaByCateg4 === void 0 ? void 0 : _this$getMediaByCateg4.filter(function (m) {
2727
+ return (_this$getMediaByCateg3 = (_this$getMediaByCateg4 = this.getMediaByCategories(["history"])) === null || _this$getMediaByCateg4 === void 0 ? void 0 : _this$getMediaByCateg4.filter(function (m) {
2705
2728
  return m.contentType == type;
2706
2729
  }).shift()) !== null && _this$getMediaByCateg3 !== void 0 ? _this$getMediaByCateg3 : null;
2707
2730
  }
@@ -2740,7 +2763,7 @@ var Message = /*#__PURE__*/function (_ReplayEventEmitter) {
2740
2763
  updateReasons.push("dateCreated");
2741
2764
  }
2742
2765
 
2743
- var updatedAttributes = parseAttributes(data.attributes, "Got malformed attributes for the message ".concat(this.sid), log$5);
2766
+ var updatedAttributes = parseAttributes(data.attributes, "Got malformed attributes for the message ".concat(this.sid), log$4);
2744
2767
 
2745
2768
  if (!isEqual__default['default'](this.state.attributes, updatedAttributes)) {
2746
2769
  this.state.attributes = updatedAttributes;
@@ -2793,7 +2816,7 @@ var Message = /*#__PURE__*/function (_ReplayEventEmitter) {
2793
2816
 
2794
2817
  _context.next = 4;
2795
2818
  return this.conversation.getParticipantBySid(this.state.participantSid).catch(function () {
2796
- log$5.debug("Participant with sid \"".concat(_this2.participantSid, "\" not found for message ").concat(_this2.sid));
2819
+ log$4.debug("Participant with sid \"".concat(_this2.participantSid, "\" not found for message ").concat(_this2.sid));
2797
2820
  return null;
2798
2821
  });
2799
2822
 
@@ -2808,7 +2831,7 @@ var Message = /*#__PURE__*/function (_ReplayEventEmitter) {
2808
2831
 
2809
2832
  _context.next = 8;
2810
2833
  return this.conversation.getParticipantByIdentity(this.state.author).catch(function () {
2811
- log$5.debug("Participant with identity \"".concat(_this2.author, "\" not found for message ").concat(_this2.sid));
2834
+ log$4.debug("Participant with identity \"".concat(_this2.author, "\" not found for message ").concat(_this2.sid));
2812
2835
  return null;
2813
2836
  });
2814
2837
 
@@ -3019,57 +3042,96 @@ var Message = /*#__PURE__*/function (_ReplayEventEmitter) {
3019
3042
  return updateAttributes;
3020
3043
  }()
3021
3044
  /**
3022
- * Get content URLs for all media attachments in the given set using single operation.
3023
- * @param contentSet Set of media attachments to query for content URL.
3045
+ * Get content URLs for all media attachments in the given set using a single operation.
3046
+ * @param contentSet Set of media attachments to query content URLs.
3024
3047
  */
3025
3048
 
3026
3049
  }, {
3027
- key: "attachTemporaryUrlsFor",
3028
- value: function () {
3029
- var _attachTemporaryUrlsFor = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee6(contentSet) {
3030
- var _this3 = this;
3050
+ key: "getTemporaryContentUrlsForMedia",
3051
+ value: function getTemporaryContentUrlsForMedia(contentSet) {
3052
+ var _contentSet$map;
3031
3053
 
3032
- var sids;
3033
- return _regeneratorRuntime__default['default'].wrap(function _callee6$(_context6) {
3034
- while (1) {
3035
- switch (_context6.prev = _context6.next) {
3036
- case 0:
3037
- // We ignore existing mcsMedia members of each of the media entries.
3038
- // Instead we just collect their sids and pull new descriptors from a mediaSet GET endpoint.
3039
- sids = contentSet === null || contentSet === void 0 ? void 0 : contentSet.map(function (m) {
3040
- return m.sid;
3041
- });
3054
+ // We ignore existing mcsMedia members of each of the media entries.
3055
+ // Instead we just collect their sids and pull new descriptors from a mediaSet GET endpoint.
3056
+ var sids = (_contentSet$map = contentSet === null || contentSet === void 0 ? void 0 : contentSet.map(function (m) {
3057
+ return m.sid;
3058
+ })) !== null && _contentSet$map !== void 0 ? _contentSet$map : [];
3059
+ return this.getTemporaryContentUrlsForMediaSids(sids);
3060
+ }
3061
+ /**
3062
+ * Get content URLs for all media attachments in the given set of media sids using a single operation.
3063
+ * @param mediaSids Set of media sids to query for the content URL.
3064
+ */
3042
3065
 
3043
- if (!(this.services.mcsClient && sids)) {
3044
- _context6.next = 7;
3045
- break;
3046
- }
3066
+ }, {
3067
+ key: "getTemporaryContentUrlsForMediaSids",
3068
+ value: function getTemporaryContentUrlsForMediaSids(mediaSids) {
3069
+ var _this3 = this;
3047
3070
 
3048
- _context6.next = 4;
3049
- return this.services.mcsClient.mediaSetGet(sids);
3071
+ return new mcsClient.CancellablePromise( /*#__PURE__*/function () {
3072
+ var _ref = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee6(resolve, reject, onCancel) {
3073
+ var mediaGetRequest, urls;
3074
+ return _regeneratorRuntime__default['default'].wrap(function _callee6$(_context6) {
3075
+ while (1) {
3076
+ switch (_context6.prev = _context6.next) {
3077
+ case 0:
3078
+ mediaGetRequest = _this3.services.mcsClient.mediaSetGetContentUrls(mediaSids !== null && mediaSids !== void 0 ? mediaSids : []);
3050
3079
 
3051
- case 4:
3052
- return _context6.abrupt("return", _context6.sent.map(function (item) {
3053
- return new Media(item, _this3.services);
3054
- }));
3080
+ if (!(!_this3.services.mcsClient || !mediaSids)) {
3081
+ _context6.next = 4;
3082
+ break;
3083
+ }
3055
3084
 
3056
- case 7:
3057
- throw new Error("Media Content Service is unavailable");
3085
+ reject(new Error("Media Content Service is unavailable"));
3086
+ return _context6.abrupt("return");
3058
3087
 
3059
- case 8:
3060
- case "end":
3061
- return _context6.stop();
3088
+ case 4:
3089
+ onCancel(function () {
3090
+ mediaGetRequest.cancel();
3091
+ });
3092
+ _context6.prev = 5;
3093
+ _context6.next = 8;
3094
+ return mediaGetRequest;
3095
+
3096
+ case 8:
3097
+ urls = _context6.sent;
3098
+ resolve(urls);
3099
+ _context6.next = 15;
3100
+ break;
3101
+
3102
+ case 12:
3103
+ _context6.prev = 12;
3104
+ _context6.t0 = _context6["catch"](5);
3105
+ reject(_context6.t0);
3106
+
3107
+ case 15:
3108
+ case "end":
3109
+ return _context6.stop();
3110
+ }
3062
3111
  }
3063
- }
3064
- }, _callee6, this);
3065
- }));
3112
+ }, _callee6, null, [[5, 12]]);
3113
+ }));
3066
3114
 
3067
- function attachTemporaryUrlsFor(_x3) {
3068
- return _attachTemporaryUrlsFor.apply(this, arguments);
3069
- }
3115
+ return function (_x3, _x4, _x5) {
3116
+ return _ref.apply(this, arguments);
3117
+ };
3118
+ }());
3119
+ }
3120
+ /**
3121
+ * Get content URLs for all media attached to the message.
3122
+ */
3070
3123
 
3071
- return attachTemporaryUrlsFor;
3072
- }()
3124
+ }, {
3125
+ key: "getTemporaryContentUrlsForAttachedMedia",
3126
+ value: function getTemporaryContentUrlsForAttachedMedia() {
3127
+ var _media$map;
3128
+
3129
+ var media = this.attachedMedia;
3130
+ var sids = (_media$map = media === null || media === void 0 ? void 0 : media.map(function (m) {
3131
+ return m.sid;
3132
+ })) !== null && _media$map !== void 0 ? _media$map : [];
3133
+ return this.getTemporaryContentUrlsForMediaSids(sids);
3134
+ }
3073
3135
  }, {
3074
3136
  key: "_getDetailedDeliveryReceiptsPaginator",
3075
3137
  value: function () {
@@ -3105,7 +3167,7 @@ var Message = /*#__PURE__*/function (_ReplayEventEmitter) {
3105
3167
  }, _callee7, this);
3106
3168
  }));
3107
3169
 
3108
- function _getDetailedDeliveryReceiptsPaginator(_x4) {
3170
+ function _getDetailedDeliveryReceiptsPaginator(_x6) {
3109
3171
  return _getDetailedDeliveryReceiptsPaginator2.apply(this, arguments);
3110
3172
  }
3111
3173
 
@@ -3130,7 +3192,7 @@ __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator
3130
3192
  return [value instanceof Array && value.length > 0 && value.reduce(function (a, c) {
3131
3193
  return a && c instanceof Media;
3132
3194
  }, true), "a non-empty array of Media"];
3133
- })), __metadata("design:type", Function), __metadata("design:paramtypes", [Array]), __metadata("design:returntype", Promise)], Message.prototype, "attachTemporaryUrlsFor", null);
3195
+ })), __metadata("design:type", Function), __metadata("design:paramtypes", [Array]), __metadata("design:returntype", mcsClient.CancellablePromise)], Message.prototype, "getTemporaryContentUrlsForMedia", null);
3134
3196
 
3135
3197
  function _createForOfIteratorHelper$2(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$2(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
3136
3198
 
@@ -3141,7 +3203,7 @@ function _arrayLikeToArray$2(arr, len) { if (len == null || len > arr.length) le
3141
3203
  function _createSuper$4(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$4(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
3142
3204
 
3143
3205
  function _isNativeReflectConstruct$4() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
3144
- var log$4 = Logger.scope("Messages");
3206
+ var log$3 = Logger.scope("Messages");
3145
3207
  /**
3146
3208
  * Represents the collection of messages in a conversation
3147
3209
  */
@@ -3200,7 +3262,7 @@ var Messages = /*#__PURE__*/function (_ReplayEventEmitter) {
3200
3262
  case 6:
3201
3263
  list = _context.sent;
3202
3264
  list.on("itemAdded", function (args) {
3203
- log$4.debug("".concat(_this2.conversation.sid, " itemAdded: ").concat(args.item.index));
3265
+ log$3.debug("".concat(_this2.conversation.sid, " itemAdded: ").concat(args.item.index));
3204
3266
  var links = {
3205
3267
  self: "".concat(_this2.conversation.links.messages, "/").concat(args.item.data.sid),
3206
3268
  conversation: _this2.conversation.links.self,
@@ -3209,7 +3271,7 @@ var Messages = /*#__PURE__*/function (_ReplayEventEmitter) {
3209
3271
  var message = new Message(args.item.index, args.item.data, _this2.conversation, links, _this2.configuration, _this2.services);
3210
3272
 
3211
3273
  if (_this2.messagesByIndex.has(message.index)) {
3212
- log$4.debug("Message arrived, but is already known and ignored", _this2.conversation.sid, message.index);
3274
+ log$3.debug("Message arrived, but is already known and ignored", _this2.conversation.sid, message.index);
3213
3275
  return;
3214
3276
  }
3215
3277
 
@@ -3222,7 +3284,7 @@ var Messages = /*#__PURE__*/function (_ReplayEventEmitter) {
3222
3284
  _this2.emit("messageAdded", message);
3223
3285
  });
3224
3286
  list.on("itemRemoved", function (args) {
3225
- log$4.debug("#{this.conversation.sid} itemRemoved: ".concat(args.index));
3287
+ log$3.debug("#{this.conversation.sid} itemRemoved: ".concat(args.index));
3226
3288
  var index = args.index;
3227
3289
 
3228
3290
  if (_this2.messagesByIndex.has(index)) {
@@ -3240,7 +3302,7 @@ var Messages = /*#__PURE__*/function (_ReplayEventEmitter) {
3240
3302
  }
3241
3303
  });
3242
3304
  list.on("itemUpdated", function (args) {
3243
- log$4.debug("".concat(_this2.conversation.sid, " itemUpdated: ").concat(args.item.index));
3305
+ log$3.debug("".concat(_this2.conversation.sid, " itemUpdated: ").concat(args.item.index));
3244
3306
 
3245
3307
  var message = _this2.messagesByIndex.get(args.item.index);
3246
3308
 
@@ -3256,10 +3318,10 @@ var Messages = /*#__PURE__*/function (_ReplayEventEmitter) {
3256
3318
  this.messagesListPromise = null;
3257
3319
 
3258
3320
  if (this.services.syncClient.connectionState !== "disconnected") {
3259
- log$4.error("Failed to get messages object for conversation", this.conversation.sid, _context.t0);
3321
+ log$3.error("Failed to get messages object for conversation", this.conversation.sid, _context.t0);
3260
3322
  }
3261
3323
 
3262
- log$4.debug("ERROR: Failed to get messages object for conversation", this.conversation.sid, _context.t0);
3324
+ log$3.debug("ERROR: Failed to get messages object for conversation", this.conversation.sid, _context.t0);
3263
3325
  throw _context.t0;
3264
3326
 
3265
3327
  case 19:
@@ -3316,114 +3378,126 @@ var Messages = /*#__PURE__*/function (_ReplayEventEmitter) {
3316
3378
  return unsubscribe;
3317
3379
  }()
3318
3380
  /**
3319
- * Send Message to the conversation, message could include both text and multiple media attachments.
3381
+ * Send a message to the conversation. The message could include text and multiple media attachments.
3320
3382
  * @param message Message to post
3321
- * @returns Returns a promise which can fail
3322
3383
  */
3323
3384
 
3324
3385
  }, {
3325
3386
  key: "sendV2",
3326
- value: function () {
3327
- var _sendV = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee3(message) {
3328
- var _message$emailOptions;
3387
+ value: function sendV2(message) {
3388
+ var _this3 = this;
3329
3389
 
3330
- var media, _iterator, _step, _mediaContent$content, _mediaContent$media, _step$value, category, mediaContent;
3390
+ log$3.debug("Sending message V2", message.mediaContent, message.attributes, message.emailOptions);
3391
+ return new mcsClient.CancellablePromise( /*#__PURE__*/function () {
3392
+ var _ref = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee3(resolve, reject, onCancel) {
3393
+ var _message$emailOptions;
3331
3394
 
3332
- return _regeneratorRuntime__default['default'].wrap(function _callee3$(_context3) {
3333
- while (1) {
3334
- switch (_context3.prev = _context3.next) {
3335
- case 0:
3336
- log$4.debug("Sending message V2", message.mediaContent, message.attributes, message.emailOptions);
3337
- media = [];
3338
- _iterator = _createForOfIteratorHelper$2(message.mediaContent);
3339
- _context3.prev = 3;
3395
+ var media, requests, _iterator, _step, _step$value, category, mediaContent, _mediaContent$content, _mediaContent$media, request, messagesPostRequest;
3340
3396
 
3341
- _iterator.s();
3397
+ return _regeneratorRuntime__default['default'].wrap(function _callee3$(_context3) {
3398
+ while (1) {
3399
+ switch (_context3.prev = _context3.next) {
3400
+ case 0:
3401
+ media = [];
3402
+ requests = [];
3403
+ onCancel(function () {
3404
+ requests.forEach(function (request) {
3405
+ return request.cancel();
3406
+ });
3407
+ });
3408
+ _iterator = _createForOfIteratorHelper$2(message.mediaContent);
3409
+ _context3.prev = 4;
3342
3410
 
3343
- case 5:
3344
- if ((_step = _iterator.n()).done) {
3345
- _context3.next = 22;
3346
- break;
3347
- }
3411
+ _iterator.s();
3348
3412
 
3349
- _step$value = _slicedToArray__default['default'](_step.value, 2), category = _step$value[0], mediaContent = _step$value[1];
3350
- log$4.debug("Adding media to a message as ".concat(mediaContent instanceof FormData ? "FormData" : "SendMediaOptions"), mediaContent);
3351
- _context3.t0 = media;
3413
+ case 6:
3414
+ if ((_step = _iterator.n()).done) {
3415
+ _context3.next = 25;
3416
+ break;
3417
+ }
3352
3418
 
3353
- if (!(mediaContent instanceof FormData)) {
3419
+ _step$value = _slicedToArray__default['default'](_step.value, 2), category = _step$value[0], mediaContent = _step$value[1];
3420
+ _context3.prev = 8;
3421
+ log$3.debug("Adding media to a message as ".concat(mediaContent instanceof FormData ? "FormData" : "SendMediaOptions"), mediaContent);
3422
+ request = mediaContent instanceof FormData ? _this3.services.mcsClient.postFormData(mediaContent, category) : _this3.services.mcsClient.post((_mediaContent$content = mediaContent.contentType) !== null && _mediaContent$content !== void 0 ? _mediaContent$content : "", (_mediaContent$media = mediaContent.media) !== null && _mediaContent$media !== void 0 ? _mediaContent$media : "", category, mediaContent.filename);
3423
+ requests.push(request);
3424
+ _context3.t0 = media;
3354
3425
  _context3.next = 15;
3355
- break;
3356
- }
3357
-
3358
- _context3.next = 12;
3359
- return this.services.mcsClient.postFormData(mediaContent, category);
3360
-
3361
- case 12:
3362
- _context3.t1 = _context3.sent;
3363
- _context3.next = 18;
3364
- break;
3426
+ return request;
3365
3427
 
3366
- case 15:
3367
- _context3.next = 17;
3368
- return this.services.mcsClient.post((_mediaContent$content = mediaContent.contentType) !== null && _mediaContent$content !== void 0 ? _mediaContent$content : "", (_mediaContent$media = mediaContent.media) !== null && _mediaContent$media !== void 0 ? _mediaContent$media : "", category, mediaContent.filename);
3428
+ case 15:
3429
+ _context3.t1 = _context3.sent;
3369
3430
 
3370
- case 17:
3371
- _context3.t1 = _context3.sent;
3431
+ _context3.t0.push.call(_context3.t0, _context3.t1);
3372
3432
 
3373
- case 18:
3374
- _context3.t2 = _context3.t1;
3433
+ _context3.next = 23;
3434
+ break;
3375
3435
 
3376
- _context3.t0.push.call(_context3.t0, _context3.t2);
3436
+ case 19:
3437
+ _context3.prev = 19;
3438
+ _context3.t2 = _context3["catch"](8);
3439
+ reject(_context3.t2);
3440
+ return _context3.abrupt("return");
3377
3441
 
3378
- case 20:
3379
- _context3.next = 5;
3380
- break;
3442
+ case 23:
3443
+ _context3.next = 6;
3444
+ break;
3381
3445
 
3382
- case 22:
3383
- _context3.next = 27;
3384
- break;
3446
+ case 25:
3447
+ _context3.next = 30;
3448
+ break;
3385
3449
 
3386
- case 24:
3387
- _context3.prev = 24;
3388
- _context3.t3 = _context3["catch"](3);
3450
+ case 27:
3451
+ _context3.prev = 27;
3452
+ _context3.t3 = _context3["catch"](4);
3389
3453
 
3390
- _iterator.e(_context3.t3);
3454
+ _iterator.e(_context3.t3);
3391
3455
 
3392
- case 27:
3393
- _context3.prev = 27;
3456
+ case 30:
3457
+ _context3.prev = 30;
3394
3458
 
3395
- _iterator.f();
3459
+ _iterator.f();
3396
3460
 
3397
- return _context3.finish(27);
3461
+ return _context3.finish(30);
3398
3462
 
3399
- case 30:
3400
- _context3.next = 32;
3401
- return this.services.commandExecutor.mutateResource("post", this.conversation.links.messages, {
3402
- body: message.text,
3403
- subject: (_message$emailOptions = message.emailOptions) === null || _message$emailOptions === void 0 ? void 0 : _message$emailOptions.subject,
3404
- media_sids: media.map(function (m) {
3405
- return m.sid;
3406
- }),
3407
- attributes: typeof message.attributes !== "undefined" ? JSON.stringify(message.attributes) : undefined
3408
- });
3463
+ case 33:
3464
+ messagesPostRequest = _this3.services.commandExecutor.mutateResource("post", _this3.conversation.links.messages, {
3465
+ body: message.text,
3466
+ subject: (_message$emailOptions = message.emailOptions) === null || _message$emailOptions === void 0 ? void 0 : _message$emailOptions.subject,
3467
+ media_sids: media.map(function (m) {
3468
+ return m.sid;
3469
+ }),
3470
+ attributes: typeof message.attributes !== "undefined" ? JSON.stringify(message.attributes) : undefined
3471
+ });
3472
+ _context3.prev = 34;
3473
+ _context3.t4 = resolve;
3474
+ _context3.next = 38;
3475
+ return messagesPostRequest;
3476
+
3477
+ case 38:
3478
+ _context3.t5 = _context3.sent;
3479
+ (0, _context3.t4)(_context3.t5);
3480
+ _context3.next = 45;
3481
+ break;
3409
3482
 
3410
- case 32:
3411
- return _context3.abrupt("return", _context3.sent);
3483
+ case 42:
3484
+ _context3.prev = 42;
3485
+ _context3.t6 = _context3["catch"](34);
3486
+ reject(_context3.t6);
3412
3487
 
3413
- case 33:
3414
- case "end":
3415
- return _context3.stop();
3488
+ case 45:
3489
+ case "end":
3490
+ return _context3.stop();
3491
+ }
3416
3492
  }
3417
- }
3418
- }, _callee3, this, [[3, 24, 27, 30]]);
3419
- }));
3420
-
3421
- function sendV2(_x2) {
3422
- return _sendV.apply(this, arguments);
3423
- }
3493
+ }, _callee3, null, [[4, 27, 30, 33], [8, 19], [34, 42]]);
3494
+ }));
3424
3495
 
3425
- return sendV2;
3426
- }()
3496
+ return function (_x2, _x3, _x4) {
3497
+ return _ref.apply(this, arguments);
3498
+ };
3499
+ }());
3500
+ }
3427
3501
  /**
3428
3502
  * Send Message to the conversation
3429
3503
  * @param message Message to post
@@ -3445,18 +3519,14 @@ var Messages = /*#__PURE__*/function (_ReplayEventEmitter) {
3445
3519
  case 0:
3446
3520
  attributes = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : {};
3447
3521
  emailOptions = _args4.length > 2 ? _args4[2] : undefined;
3448
- log$4.debug("Sending text message", message, attributes, emailOptions);
3449
- _context4.next = 5;
3450
- return this.services.commandExecutor.mutateResource("post", this.conversation.links.messages, {
3522
+ log$3.debug("Sending text message", message, attributes, emailOptions);
3523
+ return _context4.abrupt("return", this.services.commandExecutor.mutateResource("post", this.conversation.links.messages, {
3451
3524
  body: message !== null && message !== void 0 ? message : "",
3452
3525
  attributes: typeof attributes !== "undefined" ? JSON.stringify(attributes) : undefined,
3453
3526
  subject: emailOptions === null || emailOptions === void 0 ? void 0 : emailOptions.subject
3454
- });
3455
-
3456
- case 5:
3457
- return _context4.abrupt("return", _context4.sent);
3527
+ }));
3458
3528
 
3459
- case 6:
3529
+ case 4:
3460
3530
  case "end":
3461
3531
  return _context4.stop();
3462
3532
  }
@@ -3464,7 +3534,7 @@ var Messages = /*#__PURE__*/function (_ReplayEventEmitter) {
3464
3534
  }, _callee4, this);
3465
3535
  }));
3466
3536
 
3467
- function send(_x3) {
3537
+ function send(_x5) {
3468
3538
  return _send.apply(this, arguments);
3469
3539
  }
3470
3540
 
@@ -3494,8 +3564,8 @@ var Messages = /*#__PURE__*/function (_ReplayEventEmitter) {
3494
3564
  case 0:
3495
3565
  attributes = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : {};
3496
3566
  emailOptions = _args5.length > 2 ? _args5[2] : undefined;
3497
- log$4.debug("Sending media message", mediaContent, attributes, emailOptions);
3498
- log$4.debug("Sending media message as ".concat(mediaContent instanceof FormData ? "FormData" : "SendMediaOptions"), mediaContent, attributes);
3567
+ log$3.debug("Sending media message", mediaContent, attributes, emailOptions);
3568
+ log$3.debug("Sending media message as ".concat(mediaContent instanceof FormData ? "FormData" : "SendMediaOptions"), mediaContent, attributes);
3499
3569
 
3500
3570
  if (!(mediaContent instanceof FormData)) {
3501
3571
  _context5.next = 10;
@@ -3536,7 +3606,7 @@ var Messages = /*#__PURE__*/function (_ReplayEventEmitter) {
3536
3606
  }, _callee5, this);
3537
3607
  }));
3538
3608
 
3539
- function sendMedia(_x4) {
3609
+ function sendMedia(_x6) {
3540
3610
  return _sendMedia.apply(this, arguments);
3541
3611
  }
3542
3612
 
@@ -3571,7 +3641,7 @@ var Messages = /*#__PURE__*/function (_ReplayEventEmitter) {
3571
3641
  }, _callee6, this);
3572
3642
  }));
3573
3643
 
3574
- function getMessages(_x5, _x6) {
3644
+ function getMessages(_x7, _x8) {
3575
3645
  return _getMessages2.apply(this, arguments);
3576
3646
  }
3577
3647
 
@@ -3580,7 +3650,7 @@ var Messages = /*#__PURE__*/function (_ReplayEventEmitter) {
3580
3650
  }, {
3581
3651
  key: "_wrapPaginator",
3582
3652
  value: function _wrapPaginator(order, page, op) {
3583
- var _this3 = this;
3653
+ var _this4 = this;
3584
3654
 
3585
3655
  // Due to an inconsistency between Sync and Chat conventions, next and
3586
3656
  // previous pages should be swapped.
@@ -3588,13 +3658,13 @@ var Messages = /*#__PURE__*/function (_ReplayEventEmitter) {
3588
3658
 
3589
3659
  var nextPage = function nextPage() {
3590
3660
  return page.nextPage().then(function (page) {
3591
- return _this3._wrapPaginator(order, page, op);
3661
+ return _this4._wrapPaginator(order, page, op);
3592
3662
  });
3593
3663
  };
3594
3664
 
3595
3665
  var previousPage = function previousPage() {
3596
3666
  return page.prevPage().then(function (page) {
3597
- return _this3._wrapPaginator(order, page, op);
3667
+ return _this4._wrapPaginator(order, page, op);
3598
3668
  });
3599
3669
  };
3600
3670
 
@@ -3613,7 +3683,7 @@ var Messages = /*#__PURE__*/function (_ReplayEventEmitter) {
3613
3683
  }, {
3614
3684
  key: "_upsertMessage",
3615
3685
  value: function _upsertMessage(index, value) {
3616
- var _this4 = this;
3686
+ var _this5 = this;
3617
3687
 
3618
3688
  var cachedMessage = this.messagesByIndex.get(index);
3619
3689
 
@@ -3629,7 +3699,7 @@ var Messages = /*#__PURE__*/function (_ReplayEventEmitter) {
3629
3699
  var message = new Message(index, value, this.conversation, links, this.configuration, this.services);
3630
3700
  this.messagesByIndex.set(message.index, message);
3631
3701
  message.on("updated", function (args) {
3632
- return _this4.emit("messageUpdated", args);
3702
+ return _this5.emit("messageUpdated", args);
3633
3703
  });
3634
3704
  return message;
3635
3705
  }
@@ -3646,7 +3716,7 @@ var Messages = /*#__PURE__*/function (_ReplayEventEmitter) {
3646
3716
  key: "_getMessages",
3647
3717
  value: function () {
3648
3718
  var _getMessages3 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee7() {
3649
- var _this5 = this;
3719
+ var _this6 = this;
3650
3720
 
3651
3721
  var pageSize,
3652
3722
  anchor,
@@ -3682,7 +3752,7 @@ var Messages = /*#__PURE__*/function (_ReplayEventEmitter) {
3682
3752
  _context7.next = 12;
3683
3753
  return this._wrapPaginator(order, page, function (items) {
3684
3754
  return Promise.all(items.map(function (item) {
3685
- return _this5._upsertMessage(item.index, item.data);
3755
+ return _this6._upsertMessage(item.index, item.data);
3686
3756
  }));
3687
3757
  });
3688
3758
 
@@ -3735,34 +3805,48 @@ var UnsentMessage = /*#__PURE__*/function () {
3735
3805
 
3736
3806
  _createClass__default['default'](UnsentMessage, [{
3737
3807
  key: "send",
3738
- value: function () {
3739
- var _send = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee() {
3740
- var response;
3741
- return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) {
3742
- while (1) {
3743
- switch (_context.prev = _context.next) {
3744
- case 0:
3745
- _context.next = 2;
3746
- return this.messagesEntity.sendV2(this);
3808
+ value: function send() {
3809
+ var _this = this;
3747
3810
 
3748
- case 2:
3749
- response = _context.sent;
3750
- return _context.abrupt("return", parseToNumber(response.index));
3811
+ return new mcsClient.CancellablePromise( /*#__PURE__*/function () {
3812
+ var _ref = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee(resolve, reject, onCancel) {
3813
+ var request, response;
3814
+ return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) {
3815
+ while (1) {
3816
+ switch (_context.prev = _context.next) {
3817
+ case 0:
3818
+ request = _this.messagesEntity.sendV2(_this);
3819
+ onCancel(function () {
3820
+ return request.cancel();
3821
+ });
3822
+ _context.prev = 2;
3823
+ _context.next = 5;
3824
+ return request;
3751
3825
 
3752
- case 4:
3753
- case "end":
3754
- return _context.stop();
3755
- }
3756
- }
3757
- }, _callee, this);
3758
- }));
3826
+ case 5:
3827
+ response = _context.sent;
3828
+ resolve(parseToNumber(response.index));
3829
+ _context.next = 12;
3830
+ break;
3759
3831
 
3760
- function send() {
3761
- return _send.apply(this, arguments);
3762
- }
3832
+ case 9:
3833
+ _context.prev = 9;
3834
+ _context.t0 = _context["catch"](2);
3835
+ reject(_context.t0);
3763
3836
 
3764
- return send;
3765
- }()
3837
+ case 12:
3838
+ case "end":
3839
+ return _context.stop();
3840
+ }
3841
+ }
3842
+ }, _callee, null, [[2, 9]]);
3843
+ }));
3844
+
3845
+ return function (_x, _x2, _x3) {
3846
+ return _ref.apply(this, arguments);
3847
+ };
3848
+ }());
3849
+ }
3766
3850
  }]);
3767
3851
 
3768
3852
  return UnsentMessage;
@@ -3831,27 +3915,27 @@ var MessageBuilder = /*#__PURE__*/function () {
3831
3915
  return this;
3832
3916
  }
3833
3917
  /**
3834
- * Set email body with given MIME-type.
3835
- * @param mimeType Format of the body to set (text/plain or text/html).
3836
- * @param body Body payload in selected format.
3918
+ * Set the email body with a given content type.
3919
+ * @param contentType Format of the body to set (text/plain or text/html).
3920
+ * @param body Body payload in the selected format.
3837
3921
  */
3838
3922
 
3839
3923
  }, {
3840
3924
  key: "setEmailBody",
3841
- value: function setEmailBody(mimeType, body) {
3842
- this.emailBodies.set(mimeType, body);
3925
+ value: function setEmailBody(contentType, body) {
3926
+ this.emailBodies.set(contentType, body);
3843
3927
  return this;
3844
3928
  }
3845
3929
  /**
3846
- * Set email history with given MIME-type.
3847
- * @param mimeType Format of the history to set (text/plain or text/html).
3848
- * @param history History payload in selected format.
3930
+ * Set the email history with a given content type.
3931
+ * @param contentType Format of the history to set (text/plain or text/html).
3932
+ * @param history History payload in the selected format.
3849
3933
  */
3850
3934
 
3851
3935
  }, {
3852
3936
  key: "setEmailHistory",
3853
- value: function setEmailHistory(mimeType, history) {
3854
- this.emailHistories.set(mimeType, history);
3937
+ value: function setEmailHistory(contentType, history) {
3938
+ this.emailHistories.set(contentType, history);
3855
3939
  return this;
3856
3940
  }
3857
3941
  /**
@@ -3887,22 +3971,22 @@ var MessageBuilder = /*#__PURE__*/function () {
3887
3971
  var _this = this;
3888
3972
 
3889
3973
  this.emailBodies.forEach(function (_, key) {
3890
- if (!_this.limits.emailBodiesAllowedMimeTypes.includes(key)) {
3891
- throw new Error("Unsupported email body MIME type ".concat(key));
3974
+ if (!_this.limits.emailBodiesAllowedContentTypes.includes(key)) {
3975
+ throw new Error("Unsupported email body content type ".concat(key));
3892
3976
  }
3893
3977
  });
3894
3978
  this.emailHistories.forEach(function (_, key) {
3895
- if (!_this.limits.emailHistoriesAllowedMimeTypes.includes(key)) {
3896
- throw new Error("Unsupported email history MIME type ".concat(key));
3979
+ if (!_this.limits.emailHistoriesAllowedContentTypes.includes(key)) {
3980
+ throw new Error("Unsupported email history content type ".concat(key));
3897
3981
  }
3898
3982
  });
3899
3983
 
3900
- if (this.emailBodies.size > this.limits.emailBodiesAllowedMimeTypes.length) {
3901
- throw new Error("Too many email bodies attached to the message (".concat(this.emailBodies.size, " > ").concat(this.limits.emailBodiesAllowedMimeTypes.length, ")"));
3984
+ if (this.emailBodies.size > this.limits.emailBodiesAllowedContentTypes.length) {
3985
+ throw new Error("Too many email bodies attached to the message (".concat(this.emailBodies.size, " > ").concat(this.limits.emailBodiesAllowedContentTypes.length, ")"));
3902
3986
  }
3903
3987
 
3904
- if (this.emailHistories.size > this.limits.emailHistoriesAllowedMimeTypes.length) {
3905
- throw new Error("Too many email histories attached to the message (".concat(this.emailHistories.size, " > ").concat(this.limits.emailHistoriesAllowedMimeTypes.length, ")"));
3988
+ if (this.emailHistories.size > this.limits.emailHistoriesAllowedContentTypes.length) {
3989
+ throw new Error("Too many email histories attached to the message (".concat(this.emailHistories.size, " > ").concat(this.limits.emailHistoriesAllowedContentTypes.length, ")"));
3906
3990
  }
3907
3991
 
3908
3992
  if (this.message.mediaContent.length > this.limits.mediaAttachmentsCountLimit) {
@@ -3919,8 +4003,17 @@ var MessageBuilder = /*#__PURE__*/function () {
3919
4003
  });
3920
4004
  return this.message;
3921
4005
  }
3922
- }, {
3923
- key: "getPayloadContentType",
4006
+ /**
4007
+ * Prepares a message and sends it to the conversation.
4008
+ */
4009
+
4010
+ }, {
4011
+ key: "buildAndSend",
4012
+ value: function buildAndSend() {
4013
+ return this.build().send();
4014
+ }
4015
+ }, {
4016
+ key: "getPayloadContentType",
3924
4017
  value: function getPayloadContentType(payload) {
3925
4018
  if (typeof FormData !== "undefined" && payload instanceof FormData) {
3926
4019
  return payload.get("Content-Type");
@@ -3942,7 +4035,7 @@ function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) le
3942
4035
  function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
3943
4036
 
3944
4037
  function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
3945
- var log$3 = Logger.scope("Conversation");
4038
+ var log$2 = Logger.scope("Conversation");
3946
4039
  var fieldMappings = {
3947
4040
  lastMessage: "lastMessage",
3948
4041
  attributes: "attributes",
@@ -4170,6 +4263,10 @@ var Conversation = /*#__PURE__*/function (_ReplayEventEmitter) {
4170
4263
  get: function get() {
4171
4264
  return this.channelState.bindings;
4172
4265
  }
4266
+ /**
4267
+ * Current conversation limits.
4268
+ */
4269
+
4173
4270
  }, {
4174
4271
  key: "limits",
4175
4272
  get: function get() {
@@ -4218,10 +4315,10 @@ var Conversation = /*#__PURE__*/function (_ReplayEventEmitter) {
4218
4315
  _this2.entityPromise = null;
4219
4316
 
4220
4317
  if (_this2.services.syncClient.connectionState != "disconnected") {
4221
- log$3.error("Failed to get conversation object", err);
4318
+ log$2.error("Failed to get conversation object", err);
4222
4319
  }
4223
4320
 
4224
- log$3.debug("ERROR: Failed to get conversation object", err);
4321
+ log$2.debug("ERROR: Failed to get conversation object", err);
4225
4322
  throw err;
4226
4323
  });
4227
4324
  }
@@ -4247,7 +4344,7 @@ var Conversation = /*#__PURE__*/function (_ReplayEventEmitter) {
4247
4344
  return this._subscribe();
4248
4345
 
4249
4346
  case 3:
4250
- log$3.trace("_subscribeStreams, this.entity.data=", (_this$entity = this.entity) === null || _this$entity === void 0 ? void 0 : _this$entity.data);
4347
+ log$2.trace("_subscribeStreams, this.entity.data=", (_this$entity = this.entity) === null || _this$entity === void 0 ? void 0 : _this$entity.data);
4251
4348
  messagesObjectName = (_this$entity2 = this.entity) === null || _this$entity2 === void 0 ? void 0 : _this$entity2.data.messages;
4252
4349
  rosterObjectName = (_this$entity3 = this.entity) === null || _this$entity3 === void 0 ? void 0 : _this$entity3.data.roster;
4253
4350
  _context.next = 8;
@@ -4262,10 +4359,10 @@ var Conversation = /*#__PURE__*/function (_ReplayEventEmitter) {
4262
4359
  _context.t0 = _context["catch"](0);
4263
4360
 
4264
4361
  if (this.services.syncClient.connectionState !== "disconnected") {
4265
- log$3.error("Failed to subscribe on conversation objects", this.sid, _context.t0);
4362
+ log$2.error("Failed to subscribe on conversation objects", this.sid, _context.t0);
4266
4363
  }
4267
4364
 
4268
- log$3.debug("ERROR: Failed to subscribe on conversation objects", this.sid, _context.t0);
4365
+ log$2.debug("ERROR: Failed to subscribe on conversation objects", this.sid, _context.t0);
4269
4366
  throw _context.t0;
4270
4367
 
4271
4368
  case 15:
@@ -4344,7 +4441,7 @@ var Conversation = /*#__PURE__*/function (_ReplayEventEmitter) {
4344
4441
 
4345
4442
  if (status === "joined") {
4346
4443
  this._subscribeStreams().catch(function (err) {
4347
- log$3.debug("ERROR while setting conversation status " + status, err);
4444
+ log$2.debug("ERROR while setting conversation status " + status, err);
4348
4445
 
4349
4446
  if (_this3.services.syncClient.connectionState !== "disconnected") {
4350
4447
  throw err;
@@ -4352,7 +4449,7 @@ var Conversation = /*#__PURE__*/function (_ReplayEventEmitter) {
4352
4449
  });
4353
4450
  } else if (this.entityPromise) {
4354
4451
  this._unsubscribe().catch(function (err) {
4355
- log$3.debug("ERROR while setting conversation status " + status, err);
4452
+ log$2.debug("ERROR while setting conversation status " + status, err);
4356
4453
 
4357
4454
  if (_this3.services.syncClient.connectionState !== "disconnected") {
4358
4455
  throw err;
@@ -4380,7 +4477,7 @@ var Conversation = /*#__PURE__*/function (_ReplayEventEmitter) {
4380
4477
  function _update(update) {
4381
4478
  var _update$lastMessage, _update$lastMessage2, _this$channelState$la2, _this$channelState$la3, _this$channelState$lo;
4382
4479
 
4383
- log$3.trace("_update", update);
4480
+ log$2.trace("_update", update);
4384
4481
  Conversation.preprocessUpdate(update, this.sid);
4385
4482
  var updateReasons = new Set();
4386
4483
 
@@ -5479,7 +5576,7 @@ var Conversation = /*#__PURE__*/function (_ReplayEventEmitter) {
5479
5576
  JSON.stringify(update.attributes);
5480
5577
  }
5481
5578
  } catch (e) {
5482
- log$3.warn("Retrieved malformed attributes from the server for conversation: " + conversationSid);
5579
+ log$2.warn("Retrieved malformed attributes from the server for conversation: " + conversationSid);
5483
5580
  update.attributes = {};
5484
5581
  }
5485
5582
 
@@ -5488,7 +5585,7 @@ var Conversation = /*#__PURE__*/function (_ReplayEventEmitter) {
5488
5585
  update.dateCreated = new Date(update.dateCreated);
5489
5586
  }
5490
5587
  } catch (e) {
5491
- log$3.warn("Retrieved malformed dateCreated from the server for conversation: " + conversationSid);
5588
+ log$2.warn("Retrieved malformed dateCreated from the server for conversation: " + conversationSid);
5492
5589
  delete update.dateCreated;
5493
5590
  }
5494
5591
 
@@ -5497,7 +5594,7 @@ var Conversation = /*#__PURE__*/function (_ReplayEventEmitter) {
5497
5594
  update.dateUpdated = new Date(update.dateUpdated);
5498
5595
  }
5499
5596
  } catch (e) {
5500
- log$3.warn("Retrieved malformed dateUpdated from the server for conversation: " + conversationSid);
5597
+ log$2.warn("Retrieved malformed dateUpdated from the server for conversation: " + conversationSid);
5501
5598
  delete update.dateUpdated;
5502
5599
  }
5503
5600
 
@@ -5506,7 +5603,7 @@ var Conversation = /*#__PURE__*/function (_ReplayEventEmitter) {
5506
5603
  update.lastMessage.timestamp = new Date(update.lastMessage.timestamp);
5507
5604
  }
5508
5605
  } catch (e) {
5509
- log$3.warn("Retrieved malformed lastMessage.timestamp from the server for conversation: " + conversationSid);
5606
+ log$2.warn("Retrieved malformed lastMessage.timestamp from the server for conversation: " + conversationSid);
5510
5607
  delete update.lastMessage.timestamp;
5511
5608
  }
5512
5609
  }
@@ -5629,7 +5726,7 @@ function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) {
5629
5726
  function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
5630
5727
 
5631
5728
  function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
5632
- var log$2 = Logger.scope("Conversations");
5729
+ var log$1 = Logger.scope("Conversations");
5633
5730
  /**
5634
5731
  * Represents conversations collection
5635
5732
  * {@see Conversation}
@@ -5759,12 +5856,12 @@ var Conversations = /*#__PURE__*/function (_ReplayEventEmitter) {
5759
5856
  case 3:
5760
5857
  map = _context2.sent;
5761
5858
  map.on("itemAdded", function (args) {
5762
- log$2.debug("itemAdded: ".concat(args.item.key));
5859
+ log$1.debug("itemAdded: ".concat(args.item.key));
5763
5860
 
5764
5861
  _this2._upsertConversation("sync", args.item.key, args.item.data);
5765
5862
  });
5766
5863
  map.on("itemRemoved", function (args) {
5767
- log$2.debug("itemRemoved: ".concat(args.key));
5864
+ log$1.debug("itemRemoved: ".concat(args.key));
5768
5865
  var sid = args.key;
5769
5866
 
5770
5867
  if (!_this2.myConversationsFetched) {
@@ -5790,7 +5887,7 @@ var Conversations = /*#__PURE__*/function (_ReplayEventEmitter) {
5790
5887
  conversation.emit("removed", conversation);
5791
5888
  });
5792
5889
  map.on("itemUpdated", function (args) {
5793
- log$2.debug("itemUpdated: ".concat(args.item.key));
5890
+ log$1.debug("itemUpdated: ".concat(args.item.key));
5794
5891
 
5795
5892
  _this2._upsertConversation("sync", args.item.key, args.item.data);
5796
5893
  });
@@ -5820,7 +5917,7 @@ var Conversations = /*#__PURE__*/function (_ReplayEventEmitter) {
5820
5917
  case 16:
5821
5918
  this.myConversationsFetched = true;
5822
5919
  this.tombstones.clear();
5823
- log$2.debug("The conversations list has been successfully fetched");
5920
+ log$1.debug("The conversations list has been successfully fetched");
5824
5921
  return _context2.abrupt("return", this);
5825
5922
 
5826
5923
  case 22:
@@ -5829,10 +5926,10 @@ var Conversations = /*#__PURE__*/function (_ReplayEventEmitter) {
5829
5926
  errorMessage = "Failed to fetch the conversations list";
5830
5927
 
5831
5928
  if (this.services.syncClient.connectionState !== "disconnected") {
5832
- log$2.error(errorMessage, _context2.t0);
5929
+ log$1.error(errorMessage, _context2.t0);
5833
5930
  }
5834
5931
 
5835
- log$2.debug("ERROR: ".concat(errorMessage), _context2.t0);
5932
+ log$1.debug("ERROR: ".concat(errorMessage), _context2.t0);
5836
5933
  throw _context2.t0;
5837
5934
 
5838
5935
  case 28:
@@ -6121,7 +6218,7 @@ var Conversations = /*#__PURE__*/function (_ReplayEventEmitter) {
6121
6218
  break;
6122
6219
  }
6123
6220
 
6124
- log$2.trace("upsertConversation: conversation is known from sync and came from chat, ignoring", {
6221
+ log$1.trace("upsertConversation: conversation is known from sync and came from chat, ignoring", {
6125
6222
  sid: conversation.sid,
6126
6223
  data: data.status,
6127
6224
  conversation: conversation.status
@@ -6211,7 +6308,7 @@ var Conversations = /*#__PURE__*/function (_ReplayEventEmitter) {
6211
6308
  while (1) {
6212
6309
  switch (_context10.prev = _context10.next) {
6213
6310
  case 0:
6214
- log$2.trace("upsertConversation called for ".concat(sid), data);
6311
+ log$1.trace("upsertConversation called for ".concat(sid), data);
6215
6312
  conversation = this.conversations.get(sid); // If the channel is known, update it
6216
6313
 
6217
6314
  if (!conversation) {
@@ -6219,7 +6316,7 @@ var Conversations = /*#__PURE__*/function (_ReplayEventEmitter) {
6219
6316
  break;
6220
6317
  }
6221
6318
 
6222
- log$2.trace("upsertConversation: the conversation ".concat(conversation.sid, " is known;") + "its status is known from the source ".concat(conversation._statusSource(), " ") + "and the update came from the source ".concat(source), conversation);
6319
+ log$1.trace("upsertConversation: the conversation ".concat(conversation.sid, " is known;") + "its status is known from the source ".concat(conversation._statusSource(), " ") + "and the update came from the source ".concat(source), conversation);
6223
6320
  _context10.next = 6;
6224
6321
  return this._updateConversation(source, conversation, data);
6225
6322
 
@@ -6236,12 +6333,12 @@ var Conversations = /*#__PURE__*/function (_ReplayEventEmitter) {
6236
6333
  break;
6237
6334
  }
6238
6335
 
6239
- log$2.trace("upsertChannel: the channel is deleted but reappeared again from chat, ignoring", sid);
6336
+ log$1.trace("upsertChannel: the channel is deleted but reappeared again from chat, ignoring", sid);
6240
6337
  return _context10.abrupt("return", null);
6241
6338
 
6242
6339
  case 12:
6243
6340
  // If the conversation is unknown, fetch it
6244
- log$2.trace("upsertConversation: creating a local conversation object with sid " + sid, data);
6341
+ log$1.trace("upsertConversation: creating a local conversation object with sid " + sid, data);
6245
6342
  baseLink = "".concat(this.configuration.links.conversations, "/").concat(sid);
6246
6343
  links = {
6247
6344
  self: baseLink,
@@ -6645,7 +6742,7 @@ var Users = /*#__PURE__*/function (_ReplayEventEmitter) {
6645
6742
  return Users;
6646
6743
  }(replayEventEmitter.ReplayEventEmitter);
6647
6744
 
6648
- var log$1 = Logger.scope("TypingIndicator");
6745
+ var log = Logger.scope("TypingIndicator");
6649
6746
  /**
6650
6747
  * An important note in regards to typing timeout timers. There are two places that the SDK can get the "typing_timeout" attribute from. The first
6651
6748
  * place that the attribute appears in is the response received from POST -> /v1/typing REST call. In the body of that response, the value of the
@@ -6733,7 +6830,7 @@ var TypingIndicator = /*#__PURE__*/function () {
6733
6830
  while (1) {
6734
6831
  switch (_context2.prev = _context2.next) {
6735
6832
  case 0:
6736
- log$1.trace("Got new typing indicator ", message);
6833
+ log.trace("Got new typing indicator ", message);
6737
6834
  this.getConversation(message.channel_sid).then(function (conversation) {
6738
6835
  if (!conversation) {
6739
6836
  return;
@@ -6749,7 +6846,7 @@ var TypingIndicator = /*#__PURE__*/function () {
6749
6846
  participant._startTyping(timeout);
6750
6847
  });
6751
6848
  }).catch(function (err) {
6752
- log$1.error(err);
6849
+ log.error(err);
6753
6850
  throw err;
6754
6851
  });
6755
6852
 
@@ -6789,7 +6886,7 @@ var TypingIndicator = /*#__PURE__*/function () {
6789
6886
  value: function _send(conversationSid) {
6790
6887
  var _this3 = this;
6791
6888
 
6792
- log$1.trace("Sending typing indicator");
6889
+ log.trace("Sending typing indicator");
6793
6890
  var url = this.configuration.links.typing;
6794
6891
  var headers = {
6795
6892
  "Content-Type": "application/x-www-form-urlencoded"
@@ -6800,7 +6897,7 @@ var TypingIndicator = /*#__PURE__*/function () {
6800
6897
  _this3.serviceTypingTimeout = response.body.typing_timeout * 1000;
6801
6898
  }
6802
6899
  }).catch(function (err) {
6803
- log$1.error("Failed to send typing indicator:", err);
6900
+ log.error("Failed to send typing indicator:", err);
6804
6901
  throw err;
6805
6902
  });
6806
6903
  }
@@ -6856,7 +6953,7 @@ function PushNotification(data) {
6856
6953
  this.data = data.data || {};
6857
6954
  };
6858
6955
 
6859
- var version = "2.1.0-rc.8";
6956
+ var version = "3.0.0-rc.1";
6860
6957
 
6861
6958
  function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
6862
6959
 
@@ -7070,8 +7167,9 @@ function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflec
7070
7167
  function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
7071
7168
 
7072
7169
  var Client_1;
7073
- var log = Logger.scope("Client");
7074
- var SDK_VERSION = version;
7170
+ /**
7171
+ * Client services.
7172
+ */
7075
7173
 
7076
7174
  var ClientServices = function ClientServices() {
7077
7175
  _classCallCheck__default['default'](this, ClientServices);
@@ -7087,28 +7185,246 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7087
7185
  var _super = _createSuper(Client);
7088
7186
 
7089
7187
  /**
7090
- * Client connection state.
7188
+ * Fired when a conversation becomes visible to the client. The event is also
7189
+ * triggered when the client creates a new conversation.
7190
+ * Fired for all conversations that the client has joined.
7191
+ *
7192
+ * Parameters:
7193
+ * 1. {@link Conversation} `conversation` - the conversation in question
7194
+ * @event
7195
+ */
7196
+
7197
+ /**
7198
+ * Fired when the client joins a conversation.
7199
+ *
7200
+ * Parameters:
7201
+ * 1. {@link Conversation} `conversation` - the conversation in question
7202
+ * @event
7203
+ */
7204
+
7205
+ /**
7206
+ * Fired when the client leaves a conversation.
7207
+ *
7208
+ * Parameters:
7209
+ * 1. {@link Conversation} `conversation` - the conversation in question
7210
+ * @event
7211
+ */
7212
+
7213
+ /**
7214
+ * Fired when a conversation is no longer visible to the client.
7215
+ *
7216
+ * Parameters:
7217
+ * 1. {@link Conversation} `conversation` - the conversation in question
7218
+ * @event
7219
+ */
7220
+
7221
+ /**
7222
+ * Fired when the attributes or the metadata of a conversation have been
7223
+ * updated. During conversation's creation and initialization, this event
7224
+ * might be fired multiple times for same joined or created conversation as
7225
+ * new data is arriving from different sources.
7226
+ *
7227
+ * Parameters:
7228
+ * 1. object `data` - info object provided with the event. It has the
7229
+ * following properties:
7230
+ * * {@link Conversation} `conversation` - the conversation in question
7231
+ * * {@link ConversationUpdateReason}[] `updateReasons` - array of reasons
7232
+ * for the update
7233
+ * @event
7234
+ */
7235
+
7236
+ /**
7237
+ * Fired when a participant has joined a conversation.
7238
+ *
7239
+ * Parameters:
7240
+ * 1. {@link Participant} `participant` - the participant in question
7241
+ * @event
7242
+ */
7243
+
7244
+ /**
7245
+ * Fired when a participant has left a conversation.
7246
+ *
7247
+ * Parameters:
7248
+ * 1. {@link Participant} `participant` - the participant in question
7249
+ * @event
7250
+ */
7251
+
7252
+ /**
7253
+ * Fired when a participant's fields have been updated.
7254
+ *
7255
+ * Parameters:
7256
+ * 1. object `data` - info object provided with the event. It has the
7257
+ * following properties:
7258
+ * * {@link Participant} `participant` - the participant in question
7259
+ * * {@link ParticipantUpdateReason}[] `updateReasons` - array of reasons
7260
+ * for the update
7261
+ * @event
7262
+ */
7263
+
7264
+ /**
7265
+ * Fired when a new message has been added to the conversation on the server.
7266
+ *
7267
+ * Parameters:
7268
+ * 1. {@link Message} `message` - the message in question
7269
+ * @event
7270
+ */
7271
+
7272
+ /**
7273
+ * Fired when a message is removed from the message list of a conversation.
7274
+ *
7275
+ * Parameters:
7276
+ * 1. {@link Message} `message` - the message in question
7277
+ * @event
7278
+ */
7279
+
7280
+ /**
7281
+ * Fired when the fields of an existing message are updated with new values.
7282
+ *
7283
+ * Parameters:
7284
+ * 1. object `data` - info object provided with the event. It has the
7285
+ * following properties:
7286
+ * * {@link Message} `message` - the message in question
7287
+ * * {@link MessageUpdateReason}[] `updateReasons` - array of reasons for
7288
+ * the update
7289
+ * @event
7290
+ */
7291
+
7292
+ /**
7293
+ * Fired when the token is about to expire and needs to be updated.
7294
+ * * Parameters:
7295
+ * 1. number `message` - token's time to live
7296
+ * @event
7297
+ */
7298
+
7299
+ /**
7300
+ * Fired when the token has expired.
7301
+ * @event
7302
+ */
7303
+
7304
+ /**
7305
+ * Fired when a participant has stopped typing.
7306
+ *
7307
+ * Parameters:
7308
+ * 1. {@link Participant} `participant` - the participant in question
7309
+ * @event
7310
+ */
7311
+
7312
+ /**
7313
+ * Fired when a participant has started typing.
7314
+ *
7315
+ * Parameters:
7316
+ * 1. {@link Participant} `participant` - the participant in question
7317
+ * @event
7318
+ */
7319
+
7320
+ /**
7321
+ * Fired when the client has received (and parsed) a push notification via one
7322
+ * of the push channels (apn or fcm).
7323
+ *
7324
+ * Parameters:
7325
+ * 1. {@link PushNotification} `pushNotification` - the push notification in
7326
+ * question
7327
+ * @event
7328
+ */
7329
+
7330
+ /**
7331
+ * Fired when the client has subscribed to a user.
7332
+ *
7333
+ * Parameters:
7334
+ * 1. {@link User} `user` - the user in question
7335
+ * @event
7336
+ */
7337
+
7338
+ /**
7339
+ * Fired when the client has unsubscribed from a user.
7340
+ *
7341
+ * Parameters:
7342
+ * 1. {@link User} `user` - the user in question
7343
+ * @event
7344
+ */
7345
+
7346
+ /**
7347
+ * Fired when the properties or the reachability status of a user have been
7348
+ * updated.
7349
+ *
7350
+ * Parameters:
7351
+ * 1. object `data` - info object provided with the event. It has the
7352
+ * following properties:
7353
+ * * {@link User} `user` - the user in question
7354
+ * * {@link UserUpdateReason}[] `updateReasons` - array of reasons for the
7355
+ * update
7356
+ * @event
7357
+ */
7358
+
7359
+ /**
7360
+ * Fired when the state of the client has been changed.
7361
+ *
7362
+ * Parameters:
7363
+ * 1. object `data` - info object provided with the event. It has the
7364
+ * following properties:
7365
+ * * {@link State} `state` - the new client state
7366
+ * * Error? `error` - the initialization error if present
7367
+ * @event
7368
+ */
7369
+
7370
+ /**
7371
+ * Fired when the connection state of the client has been changed.
7372
+ *
7373
+ * Parameters:
7374
+ * 1. {@link ConnectionState} `state` - the new connection state
7375
+ * @event
7376
+ */
7377
+
7378
+ /**
7379
+ * Fired when the connection is interrupted for an unexpected reason.
7380
+ *
7381
+ * Parameters:
7382
+ * 1. object `data` - info object provided with the event. It has the
7383
+ * following properties:
7384
+ * * boolean `terminal` - Twilsock will stop connection attempts if true
7385
+ * * string `message` - the error message of the root cause
7386
+ * * number? `httpStatusCode` - http status code if available
7387
+ * * number? `errorCode` - Twilio public error code if available
7388
+ * @event
7091
7389
  */
7092
7390
 
7093
7391
  /**
7094
7392
  * Current version of the Conversations client.
7095
7393
  */
7096
7394
 
7395
+ /**
7396
+ * Logger instance.
7397
+ */
7398
+
7399
+ /**
7400
+ * Supported push notification channels.
7401
+ */
7402
+
7403
+ /**
7404
+ * Supported push data fields.
7405
+ */
7406
+
7097
7407
  /**
7098
7408
  * Current version of the Conversations client.
7099
7409
  */
7100
7410
 
7101
7411
  /**
7102
- * Returned Conversations instance is not yet fully initialized. Calling any operations will block until it is.
7103
- * Use connection events to monitor when client becomes fully available (connectionStateChanged with state
7104
- * 'connected') or not available (connectionStateChange with state 'denied', event tokenExpired, event connectionError).
7412
+ * Client connection state.
7413
+ */
7414
+
7415
+ /**
7416
+ * Returned Conversations instance is not yet fully initialized. Calling any
7417
+ * operations will block until it is. Use connection events to monitor when
7418
+ * client becomes fully available (connectionStateChanged with state
7419
+ * 'connected') or not available (connectionStateChange with state 'denied',
7420
+ * event tokenExpired, event connectionError).
7105
7421
  *
7106
7422
  * @param fpaToken Access token
7107
7423
  * @param options Options to customize the Client
7108
7424
  * @returns A not yet fully-initialized client.
7109
7425
  */
7110
7426
  function Client(fpaToken) {
7111
- var _this$options$logLeve, _this$options$twilsoc, _this$options$transpo, _this$options$notific, _this$options$syncCli;
7427
+ var _this$_options$logLev, _this$_options$twilso, _this$_options$transp, _this$_options$notifi, _this$_options$syncCl;
7112
7428
 
7113
7429
  var _this;
7114
7430
 
@@ -7118,87 +7434,89 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7118
7434
 
7119
7435
  _this = _super.call(this);
7120
7436
 
7121
- _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "connectionState", "unknown");
7437
+ _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "version", version);
7122
7438
 
7123
- _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "version", SDK_VERSION);
7439
+ _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "connectionState", "unknown");
7124
7440
 
7125
7441
  _defineProperty__default['default'](_assertThisInitialized__default['default'](_this), "parsePushNotification", Client_1.parsePushNotification);
7126
7442
 
7127
- _this.fpaToken = fpaToken !== null && fpaToken !== void 0 ? fpaToken : "";
7128
- _this.options = options !== null && options !== void 0 ? options : {};
7443
+ _this._fpaToken = fpaToken !== null && fpaToken !== void 0 ? fpaToken : "";
7444
+ _this._options = options !== null && options !== void 0 ? options : {};
7129
7445
 
7130
- if (!_this.options.disableDeepClone) {
7131
- var _options = _objectSpread(_objectSpread({}, _this.options), {}, {
7446
+ if (!_this._options.disableDeepClone) {
7447
+ var _options = _objectSpread(_objectSpread({}, _this._options), {}, {
7132
7448
  transport: undefined,
7133
7449
  twilsockClient: undefined
7134
7450
  });
7135
7451
 
7136
7452
  _options = deepClone(_options);
7137
- _options.transport = _this.options.transport;
7138
- _options.twilsockClient = _this.options.twilsockClient;
7139
- _this.options = _options;
7453
+ _options.transport = _this._options.transport;
7454
+ _options.twilsockClient = _this._options.twilsockClient;
7455
+ _this._options = _options;
7140
7456
  }
7141
7457
 
7142
- _this.options.logLevel = (_this$options$logLeve = _this.options.logLevel) !== null && _this$options$logLeve !== void 0 ? _this$options$logLeve : "silent";
7143
- log.setLevel(_this.options.logLevel);
7144
- var productId = _this.options.productId = "ip_messaging"; // Filling ClientMetadata
7458
+ _this._options.logLevel = (_this$_options$logLev = _this._options.logLevel) !== null && _this$_options$logLev !== void 0 ? _this$_options$logLev : "silent";
7459
+
7460
+ Client_1._logger.setLevel(_this._options.logLevel);
7461
+
7462
+ var productId = _this._options.productId = "ip_messaging"; // Filling ClientMetadata
7145
7463
 
7146
- _this.options.clientMetadata = _this.options.clientMetadata || {};
7464
+ _this._options.clientMetadata = _this._options.clientMetadata || {};
7147
7465
 
7148
- if (!_this.options.clientMetadata.hasOwnProperty("type")) {
7149
- _this.options.clientMetadata.type = "conversations";
7466
+ if (!_this._options.clientMetadata.hasOwnProperty("type")) {
7467
+ _this._options.clientMetadata.type = "conversations";
7150
7468
  }
7151
7469
 
7152
- if (!_this.options.clientMetadata.hasOwnProperty("sdk")) {
7153
- _this.options.clientMetadata.sdk = "JS";
7154
- _this.options.clientMetadata.sdkv = SDK_VERSION;
7470
+ if (!_this._options.clientMetadata.hasOwnProperty("sdk")) {
7471
+ _this._options.clientMetadata.sdk = "JS";
7472
+ _this._options.clientMetadata.sdkv = version;
7155
7473
  } // Enable session local storage for Sync
7156
7474
 
7157
7475
 
7158
- _this.options.Sync = _this.options.Sync || {};
7476
+ _this._options.Sync = _this._options.Sync || {};
7159
7477
 
7160
- if (typeof _this.options.Sync.enableSessionStorage === "undefined") {
7161
- _this.options.Sync.enableSessionStorage = true;
7478
+ if (typeof _this._options.Sync.enableSessionStorage === "undefined") {
7479
+ _this._options.Sync.enableSessionStorage = true;
7162
7480
  }
7163
7481
 
7164
- if (_this.options.region) {
7165
- _this.options.Sync.region = _this.options.region;
7482
+ if (_this._options.region) {
7483
+ _this._options.Sync.region = _this._options.region;
7166
7484
  }
7167
7485
 
7168
7486
  if (!fpaToken) {
7169
7487
  throw new Error("A valid Twilio token should be provided");
7170
7488
  }
7171
7489
 
7172
- _this.services = new ClientServices();
7173
- _this._myself = new User("", "", null, _this.services);
7174
- var startTwilsock = !_this.options.twilsockClient; // Create default init registrations if none were provided.
7490
+ _this._services = new ClientServices();
7491
+ _this._myself = new User("", "", null, _this._services);
7492
+ var startTwilsock = !_this._options.twilsockClient; // Create default init registrations if none were provided.
7175
7493
  // Otherwise, the outside party have to list all the init registrations they
7176
7494
  // need.
7177
7495
  // Init registrations passed to the Conversations client will be passed down
7178
7496
  // to the Sync client as well.
7179
7497
 
7180
- if (!_this.options.initRegistrations) {
7498
+ if (!_this._options.initRegistrations) {
7181
7499
  var initRegistration = new twilsock.InitRegistration(productId);
7182
7500
  Client_1.populateInitRegistrations(initRegistration);
7183
- _this.options.initRegistrations = [initRegistration];
7501
+ _this._options.initRegistrations = [initRegistration];
7184
7502
  }
7185
7503
 
7186
- _this.services.twilsockClient = _this.options.twilsockClient = (_this$options$twilsoc = _this.options.twilsockClient) !== null && _this$options$twilsoc !== void 0 ? _this$options$twilsoc : new twilsock.TwilsockClient(fpaToken, productId, _this.options);
7504
+ _this._services.twilsockClient = _this._options.twilsockClient = (_this$_options$twilso = _this._options.twilsockClient) !== null && _this$_options$twilso !== void 0 ? _this$_options$twilso : new twilsock.TwilsockClient(fpaToken, productId, _this._options);
7187
7505
 
7188
- _this.services.twilsockClient.on("tokenAboutToExpire", function (ttl) {
7506
+ _this._services.twilsockClient.on("tokenAboutToExpire", function (ttl) {
7189
7507
  return _this.emit("tokenAboutToExpire", ttl);
7190
7508
  });
7191
7509
 
7192
- _this.services.twilsockClient.on("tokenExpired", function () {
7510
+ _this._services.twilsockClient.on("tokenExpired", function () {
7193
7511
  return _this.emit("tokenExpired");
7194
7512
  });
7195
7513
 
7196
- _this.services.twilsockClient.on("connectionError", function (error) {
7514
+ _this._services.twilsockClient.on("connectionError", function (error) {
7197
7515
  return _this.emit("connectionError", error);
7198
7516
  });
7199
7517
 
7200
- _this.services.twilsockClient.on("stateChanged", function (state) {
7201
- log.debug("Handling stateChanged for ConversationsClient: new state ".concat(state));
7518
+ _this._services.twilsockClient.on("stateChanged", function (state) {
7519
+ Client_1._logger.debug("Handling stateChanged for ConversationsClient: new state ".concat(state));
7202
7520
 
7203
7521
  if (state !== _this.connectionState) {
7204
7522
  _this.connectionState = state;
@@ -7207,49 +7525,52 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7207
7525
  }
7208
7526
  });
7209
7527
 
7210
- _this.services.transport = _this.options.transport = (_this$options$transpo = _this.options.transport) !== null && _this$options$transpo !== void 0 ? _this$options$transpo : _this.options.twilsockClient;
7211
- _this.services.notificationClient = _this.options.notificationsClient = (_this$options$notific = _this.options.notificationsClient) !== null && _this$options$notific !== void 0 ? _this$options$notific : new notifications.Notifications(fpaToken, _this.options);
7212
- _this.services.syncClient = _this.options.syncClient = (_this$options$syncCli = _this.options.syncClient) !== null && _this$options$syncCli !== void 0 ? _this$options$syncCli : new twilioSync.SyncClient(fpaToken, _this.options);
7528
+ _this._services.transport = _this._options.transport = (_this$_options$transp = _this._options.transport) !== null && _this$_options$transp !== void 0 ? _this$_options$transp : _this._options.twilsockClient;
7529
+ _this._services.notificationClient = _this._options.notificationsClient = (_this$_options$notifi = _this._options.notificationsClient) !== null && _this$_options$notifi !== void 0 ? _this$_options$notifi : new notifications.Notifications(fpaToken, _this._options);
7530
+ _this._services.syncClient = _this._options.syncClient = (_this$_options$syncCl = _this._options.syncClient) !== null && _this$_options$syncCl !== void 0 ? _this$_options$syncCl : new twilioSync.SyncClient(fpaToken, _this._options);
7213
7531
  var configurationOptions = (options === null || options === void 0 ? void 0 : options.Chat) || (options === null || options === void 0 ? void 0 : options.IPMessaging) || options || {};
7214
7532
  var region = configurationOptions.region || (options === null || options === void 0 ? void 0 : options.region);
7215
7533
  var baseUrl = configurationOptions.apiUri || configurationOptions.typingUri || "https://aim.".concat(region || "us1", ".twilio.com");
7216
- _this.services.commandExecutor = new CommandExecutor(baseUrl, {
7217
- transport: _this.options.transport
7534
+ _this._services.commandExecutor = new CommandExecutor(baseUrl, {
7535
+ transport: _this._options.transport
7218
7536
  }, productId);
7219
7537
 
7220
- var emitFailed = function emitFailed(err) {
7221
- _this._rejectEnsureReady(err);
7538
+ var emitFailed = function emitFailed(error) {
7539
+ _this._rejectEnsureReady(error);
7222
7540
 
7223
- _this.emit("stateChanged", "failed");
7541
+ _this.emit("stateChanged", {
7542
+ state: "failed",
7543
+ error: error
7544
+ });
7224
7545
  };
7225
7546
 
7226
- _this.services.twilsockClient.once("connectionError", emitFailed);
7547
+ _this._services.twilsockClient.once("connectionError", emitFailed);
7227
7548
 
7228
- _this.services.twilsockClient.once("disconnected", emitFailed); // ConversationsClient will be able to initialize only after twilsock is connected
7549
+ _this._services.twilsockClient.once("disconnected", emitFailed); // The client will be able to initialize only after Twilsock is connected
7229
7550
 
7230
7551
 
7231
- _this.services.twilsockClient.once("connected", /*#__PURE__*/_asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee() {
7552
+ _this._services.twilsockClient.once("connected", /*#__PURE__*/_asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee() {
7232
7553
  var startupEvent;
7233
7554
  return _regeneratorRuntime__default['default'].wrap(function _callee$(_context) {
7234
7555
  while (1) {
7235
7556
  switch (_context.prev = _context.next) {
7236
7557
  case 0:
7237
- log.debug("ConversationsClient started INITIALIZING");
7558
+ Client_1._logger.debug("ConversationsClient started INITIALIZING");
7238
7559
 
7239
- _this.services.twilsockClient.off("connectionError", emitFailed);
7560
+ _this._services.twilsockClient.off("connectionError", emitFailed);
7240
7561
 
7241
- _this.services.twilsockClient.off("disconnected", emitFailed);
7562
+ _this._services.twilsockClient.off("disconnected", emitFailed);
7242
7563
 
7243
7564
  _context.prev = 3;
7244
7565
  startupEvent = "conversations.client.startup";
7245
7566
 
7246
- _this.services.twilsockClient.addPartialTelemetryEvent(new twilsock.TelemetryEventDescription(startupEvent, "Conversations client startup", new Date()), startupEvent, twilsock.TelemetryPoint.Start);
7567
+ _this._services.twilsockClient.addPartialTelemetryEvent(new twilsock.TelemetryEventDescription(startupEvent, "Conversations client startup", new Date()), startupEvent, twilsock.TelemetryPoint.Start);
7247
7568
 
7248
7569
  _context.next = 8;
7249
7570
  return _this._initialize();
7250
7571
 
7251
7572
  case 8:
7252
- _this.services.twilsockClient.addPartialTelemetryEvent(new twilsock.TelemetryEventDescription("", "", new Date()), startupEvent, twilsock.TelemetryPoint.End);
7573
+ _this._services.twilsockClient.addPartialTelemetryEvent(new twilsock.TelemetryEventDescription("", "", new Date()), startupEvent, twilsock.TelemetryPoint.End);
7253
7574
 
7254
7575
  _context.next = 15;
7255
7576
  break;
@@ -7261,7 +7582,10 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7261
7582
  // Fail ChatClient if initialization is incomplete
7262
7583
  _this._rejectEnsureReady(_context.t0);
7263
7584
 
7264
- _this.emit("stateChanged", "failed");
7585
+ _this.emit("stateChanged", {
7586
+ state: "failed",
7587
+ error: _context.t0
7588
+ });
7265
7589
 
7266
7590
  case 15:
7267
7591
  case "end":
@@ -7279,154 +7603,77 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7279
7603
  }); // @todo How to process unhandled rejection here?
7280
7604
 
7281
7605
  if (startTwilsock) {
7282
- _this.services.twilsockClient.connect();
7606
+ _this._services.twilsockClient.connect();
7283
7607
  }
7284
7608
 
7285
7609
  return _this;
7286
7610
  }
7611
+ /**
7612
+ * Information of the logged-in user. Before client initialization, returns an
7613
+ * uninitialized user. Will trigger a {@link Client.userUpdated} event after
7614
+ * initialization.
7615
+ */
7616
+
7287
7617
 
7288
7618
  _createClass__default['default'](Client, [{
7289
7619
  key: "user",
7290
- get:
7291
- /**
7292
- * Information of the logged-in user. Before client initialization, returns an
7293
- * uninitialized user. Will trigger a {@link Client.userUpdated} event after
7294
- * initialization.
7295
- */
7296
- function get() {
7620
+ get: function get() {
7297
7621
  return this._myself;
7298
7622
  }
7299
7623
  /**
7300
- * Client reachability state. Throws if accessed before the client
7624
+ * Client reachability state. Throws an error if accessed before the client
7301
7625
  * initialization was completed.
7302
7626
  */
7303
7627
 
7304
7628
  }, {
7305
7629
  key: "reachabilityEnabled",
7306
7630
  get: function get() {
7307
- if (!this.configuration) {
7631
+ if (!this._configuration) {
7308
7632
  throw new Error("Reachability information could not yet be accessed as the client " + "has not yet been initialized. Subscribe to the 'stateChanged' event " + "to properly react to the client initialization.");
7309
7633
  }
7310
7634
 
7311
- return this.configuration.reachabilityEnabled;
7312
- }
7313
- }, {
7314
- key: "token",
7315
- get: function get() {
7316
- return this.fpaToken;
7317
- }
7318
- }, {
7319
- key: "_subscribeToPushNotifications",
7320
- value: function _subscribeToPushNotifications(channelType) {
7321
- var _this2 = this;
7322
-
7323
- [NotificationTypes.NEW_MESSAGE, NotificationTypes.ADDED_TO_CONVERSATION, NotificationTypes.REMOVED_FROM_CONVERSATION, NotificationTypes.TYPING_INDICATOR, NotificationTypes.CONSUMPTION_UPDATE].forEach(function (messageType) {
7324
- _this2.services.notificationClient.subscribe(channelType, messageType);
7325
- });
7635
+ return this._configuration.reachabilityEnabled;
7326
7636
  }
7327
- }, {
7328
- key: "_unsubscribeFromPushNotifications",
7329
- value: function _unsubscribeFromPushNotifications(channelType) {
7330
- var _this3 = this;
7637
+ /**
7638
+ * @deprecated Call constructor directly.
7639
+ *
7640
+ * Factory method to create a Conversations client instance.
7641
+ *
7642
+ * The factory method will automatically trigger connection.
7643
+ * Do not use it if you need finer-grained control.
7644
+ *
7645
+ * Since this method returns an already-initialized client, some of the events
7646
+ * will be lost because they happen *before* the initialization. It is
7647
+ * recommended that `client.onWithReplay` is used as opposed to `client.on`
7648
+ * for subscribing to client events. The `client.onWithReplay` will re-emit
7649
+ * the most recent value for a given event if it emitted before the
7650
+ * subscription.
7651
+ *
7652
+ * @param token Access token.
7653
+ * @param options Options to customize the client.
7654
+ * @returns Returns a fully initialized client.
7655
+ */
7331
7656
 
7332
- [NotificationTypes.NEW_MESSAGE, NotificationTypes.ADDED_TO_CONVERSATION, NotificationTypes.REMOVED_FROM_CONVERSATION, NotificationTypes.TYPING_INDICATOR, NotificationTypes.CONSUMPTION_UPDATE].forEach(function (messageType) {
7333
- _this3.services.notificationClient.unsubscribe(channelType, messageType);
7334
- });
7335
- }
7336
7657
  }, {
7337
- key: "_initialize",
7338
- value: function () {
7339
- var _initialize2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee2() {
7340
- var _this4 = this;
7341
-
7342
- var configurationResponse;
7658
+ key: "shutdown",
7659
+ value:
7660
+ /**
7661
+ * Gracefully shut down the client.
7662
+ */
7663
+ function () {
7664
+ var _shutdown = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee2() {
7343
7665
  return _regeneratorRuntime__default['default'].wrap(function _callee2$(_context2) {
7344
7666
  while (1) {
7345
7667
  switch (_context2.prev = _context2.next) {
7346
7668
  case 0:
7347
7669
  _context2.next = 2;
7348
- return this.services.commandExecutor.fetchResource("Client/v2/Configuration");
7670
+ return this._ensureReady;
7349
7671
 
7350
7672
  case 2:
7351
- configurationResponse = _context2.sent;
7352
- this.configuration = new Configuration(this.options, configurationResponse, log);
7353
-
7354
- this._myself._resolveInitialization(this.configuration, this.configuration.userIdentity, this.configuration.userInfo, true);
7355
-
7356
- this.services.typingIndicator = new TypingIndicator(this.getConversationBySid.bind(this), this.configuration, this.services);
7357
- this.services.network = new Network(this.configuration, this.services);
7358
- this.services.users = new Users(this._myself, this.configuration, this.services);
7359
- this.services.users.on("userSubscribed", function (user) {
7360
- _this4.emit("userSubscribed", user);
7361
- });
7362
- this.services.users.on("userUpdated", function (args) {
7363
- return _this4.emit("userUpdated", args);
7364
- });
7365
- this.services.users.on("userUnsubscribed", function (user) {
7366
- _this4.emit("userUnsubscribed", user);
7367
- });
7368
- this.conversations = new Conversations(this.configuration, this.services);
7369
- this.conversations.on("conversationAdded", function (conversation) {
7370
- _this4.emit("conversationAdded", conversation);
7371
- });
7372
- this.conversations.on("conversationRemoved", function (conversation) {
7373
- _this4.emit("conversationRemoved", conversation);
7374
- });
7375
- this.conversations.on("conversationJoined", function (conversation) {
7376
- _this4.emit("conversationJoined", conversation);
7377
- });
7378
- this.conversations.on("conversationLeft", function (conversation) {
7379
- _this4.emit("conversationLeft", conversation);
7380
- });
7381
- this.conversations.on("conversationUpdated", function (args) {
7382
- return _this4.emit("conversationUpdated", args);
7383
- });
7384
- this.conversations.on("participantJoined", function (participant) {
7385
- _this4.emit("participantJoined", participant);
7386
- });
7387
- this.conversations.on("participantLeft", function (participant) {
7388
- _this4.emit("participantLeft", participant);
7389
- });
7390
- this.conversations.on("participantUpdated", function (args) {
7391
- return _this4.emit("participantUpdated", args);
7392
- });
7393
- this.conversations.on("messageAdded", function (message) {
7394
- return _this4.emit("messageAdded", message);
7395
- });
7396
- this.conversations.on("messageUpdated", function (args) {
7397
- return _this4.emit("messageUpdated", args);
7398
- });
7399
- this.conversations.on("messageRemoved", function (message) {
7400
- return _this4.emit("messageRemoved", message);
7401
- });
7402
- this.conversations.on("typingStarted", function (participant) {
7403
- return _this4.emit("typingStarted", participant);
7404
- });
7405
- this.conversations.on("typingEnded", function (participant) {
7406
- return _this4.emit("typingEnded", participant);
7407
- });
7408
- this.conversationsPromise = this.conversations.fetchConversations().then(function () {
7409
- return _this4.conversations;
7410
- }).catch(function (error) {
7411
- throw error;
7412
- });
7413
- _context2.next = 28;
7414
- return this.services.users.myself._ensureFetched();
7415
-
7416
- case 28:
7417
- Client_1.supportedPushChannels.forEach(function (channelType) {
7418
- return _this4._subscribeToPushNotifications(channelType);
7419
- });
7420
- this.services.typingIndicator.initialize();
7421
- this.services.mcsClient = new mcsClient.McsClient(this.fpaToken, this.configuration.links.mediaService, this.configuration.links.mediaSetService, _objectSpread(_objectSpread({}, this.options), {}, {
7422
- transport: undefined
7423
- }));
7424
-
7425
- this._resolveEnsureReady();
7426
-
7427
- this.emit("stateChanged", "initialized");
7673
+ _context2.next = 4;
7674
+ return this._services.twilsockClient.disconnect();
7428
7675
 
7429
- case 33:
7676
+ case 4:
7430
7677
  case "end":
7431
7678
  return _context2.stop();
7432
7679
  }
@@ -7434,20 +7681,21 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7434
7681
  }, _callee2, this);
7435
7682
  }));
7436
7683
 
7437
- function _initialize() {
7438
- return _initialize2.apply(this, arguments);
7684
+ function shutdown() {
7685
+ return _shutdown.apply(this, arguments);
7439
7686
  }
7440
7687
 
7441
- return _initialize;
7688
+ return shutdown;
7442
7689
  }()
7443
7690
  /**
7444
- * Gracefully shut down the client.
7691
+ * Update the token used by the client and re-register with the Conversations services.
7692
+ * @param token New access token.
7445
7693
  */
7446
7694
 
7447
7695
  }, {
7448
- key: "shutdown",
7696
+ key: "updateToken",
7449
7697
  value: function () {
7450
- var _shutdown = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee3() {
7698
+ var _updateToken = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee3(token) {
7451
7699
  return _regeneratorRuntime__default['default'].wrap(function _callee3$(_context3) {
7452
7700
  while (1) {
7453
7701
  switch (_context3.prev = _context3.next) {
@@ -7456,10 +7704,32 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7456
7704
  return this._ensureReady;
7457
7705
 
7458
7706
  case 2:
7459
- _context3.next = 4;
7460
- return this.services.twilsockClient.disconnect();
7707
+ Client_1._logger.info("updateToken");
7461
7708
 
7462
- case 4:
7709
+ if (!(this._fpaToken === token)) {
7710
+ _context3.next = 5;
7711
+ break;
7712
+ }
7713
+
7714
+ return _context3.abrupt("return", this);
7715
+
7716
+ case 5:
7717
+ _context3.next = 7;
7718
+ return this._services.twilsockClient.updateToken(token);
7719
+
7720
+ case 7:
7721
+ _context3.next = 9;
7722
+ return this._services.notificationClient.updateToken(token);
7723
+
7724
+ case 9:
7725
+ _context3.next = 11;
7726
+ return this._services.mcsClient.updateToken(token);
7727
+
7728
+ case 11:
7729
+ this._fpaToken = token;
7730
+ return _context3.abrupt("return", this);
7731
+
7732
+ case 13:
7463
7733
  case "end":
7464
7734
  return _context3.stop();
7465
7735
  }
@@ -7467,21 +7737,22 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7467
7737
  }, _callee3, this);
7468
7738
  }));
7469
7739
 
7470
- function shutdown() {
7471
- return _shutdown.apply(this, arguments);
7740
+ function updateToken(_x) {
7741
+ return _updateToken.apply(this, arguments);
7472
7742
  }
7473
7743
 
7474
- return shutdown;
7744
+ return updateToken;
7475
7745
  }()
7476
7746
  /**
7477
- * Update the token used by the client and re-register with the Conversations services.
7478
- * @param token New access token.
7747
+ * Get a known conversation by its SID.
7748
+ * @param conversationSid Conversation sid
7479
7749
  */
7480
7750
 
7481
7751
  }, {
7482
- key: "updateToken",
7752
+ key: "getConversationBySid",
7483
7753
  value: function () {
7484
- var _updateToken = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee4(token) {
7754
+ var _getConversationBySid = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee4(conversationSid) {
7755
+ var conversation;
7485
7756
  return _regeneratorRuntime__default['default'].wrap(function _callee4$(_context4) {
7486
7757
  while (1) {
7487
7758
  switch (_context4.prev = _context4.next) {
@@ -7490,32 +7761,27 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7490
7761
  return this._ensureReady;
7491
7762
 
7492
7763
  case 2:
7493
- log.info("updateToken");
7764
+ _context4.next = 4;
7765
+ return this._conversations.myConversationsRead.promise;
7494
7766
 
7495
- if (!(this.fpaToken === token)) {
7496
- _context4.next = 5;
7497
- break;
7498
- }
7767
+ case 4:
7768
+ _context4.next = 6;
7769
+ return this._conversations.getConversation(conversationSid);
7499
7770
 
7500
- return _context4.abrupt("return", this);
7771
+ case 6:
7772
+ conversation = _context4.sent;
7501
7773
 
7502
- case 5:
7503
- _context4.next = 7;
7504
- return this.services.twilsockClient.updateToken(token);
7774
+ if (conversation) {
7775
+ _context4.next = 9;
7776
+ break;
7777
+ }
7505
7778
 
7506
- case 7:
7507
- _context4.next = 9;
7508
- return this.services.notificationClient.updateToken(token);
7779
+ throw new Error("Conversation with SID ".concat(conversationSid, " is not found."));
7509
7780
 
7510
7781
  case 9:
7511
- _context4.next = 11;
7512
- return this.services.mcsClient.updateToken(token);
7513
-
7514
- case 11:
7515
- this.fpaToken = token;
7516
- return _context4.abrupt("return", this);
7782
+ return _context4.abrupt("return", conversation);
7517
7783
 
7518
- case 13:
7784
+ case 10:
7519
7785
  case "end":
7520
7786
  return _context4.stop();
7521
7787
  }
@@ -7523,21 +7789,22 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7523
7789
  }, _callee4, this);
7524
7790
  }));
7525
7791
 
7526
- function updateToken(_x) {
7527
- return _updateToken.apply(this, arguments);
7792
+ function getConversationBySid(_x2) {
7793
+ return _getConversationBySid.apply(this, arguments);
7528
7794
  }
7529
7795
 
7530
- return updateToken;
7796
+ return getConversationBySid;
7531
7797
  }()
7532
7798
  /**
7533
- * Get a known conversation by its SID.
7799
+ * Peek a conversation by its SID.
7534
7800
  * @param conversationSid Conversation sid
7801
+ * @internal
7535
7802
  */
7536
7803
 
7537
7804
  }, {
7538
- key: "getConversationBySid",
7805
+ key: "peekConversationBySid",
7539
7806
  value: function () {
7540
- var _getConversationBySid = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee5(conversationSid) {
7807
+ var _peekConversationBySid = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee5(conversationSid) {
7541
7808
  var conversation;
7542
7809
  return _regeneratorRuntime__default['default'].wrap(function _callee5$(_context5) {
7543
7810
  while (1) {
@@ -7548,38 +7815,22 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7548
7815
 
7549
7816
  case 2:
7550
7817
  _context5.next = 4;
7551
- return this.conversations.myConversationsRead.promise;
7818
+ return this._conversations.peekConversation(conversationSid);
7552
7819
 
7553
7820
  case 4:
7554
- _context5.next = 6;
7555
- return this.conversations.getConversation(conversationSid);
7556
-
7557
- case 6:
7558
- conversation = _context5.sent;
7559
-
7560
- if (conversation) {
7561
- _context5.next = 11;
7562
- break;
7563
- }
7564
-
7565
- _context5.next = 10;
7566
- return this.conversations.peekConversation(conversationSid);
7567
-
7568
- case 10:
7569
7821
  conversation = _context5.sent;
7570
7822
 
7571
- case 11:
7572
7823
  if (conversation) {
7573
- _context5.next = 13;
7824
+ _context5.next = 7;
7574
7825
  break;
7575
7826
  }
7576
7827
 
7577
7828
  throw new Error("Conversation with SID ".concat(conversationSid, " is not found."));
7578
7829
 
7579
- case 13:
7830
+ case 7:
7580
7831
  return _context5.abrupt("return", conversation);
7581
7832
 
7582
- case 14:
7833
+ case 8:
7583
7834
  case "end":
7584
7835
  return _context5.stop();
7585
7836
  }
@@ -7587,11 +7838,11 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7587
7838
  }, _callee5, this);
7588
7839
  }));
7589
7840
 
7590
- function getConversationBySid(_x2) {
7591
- return _getConversationBySid.apply(this, arguments);
7841
+ function peekConversationBySid(_x3) {
7842
+ return _peekConversationBySid.apply(this, arguments);
7592
7843
  }
7593
7844
 
7594
- return getConversationBySid;
7845
+ return peekConversationBySid;
7595
7846
  }()
7596
7847
  /**
7597
7848
  * Get a known conversation by its unique identifier name.
@@ -7612,11 +7863,11 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7612
7863
 
7613
7864
  case 2:
7614
7865
  _context6.next = 4;
7615
- return this.conversations.myConversationsRead.promise;
7866
+ return this._conversations.myConversationsRead.promise;
7616
7867
 
7617
7868
  case 4:
7618
7869
  _context6.next = 6;
7619
- return this.conversations.getConversationByUniqueName(uniqueName);
7870
+ return this._conversations.getConversationByUniqueName(uniqueName);
7620
7871
 
7621
7872
  case 6:
7622
7873
  conversation = _context6.sent;
@@ -7639,7 +7890,7 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7639
7890
  }, _callee6, this);
7640
7891
  }));
7641
7892
 
7642
- function getConversationByUniqueName(_x3) {
7893
+ function getConversationByUniqueName(_x4) {
7643
7894
  return _getConversationByUniqueName.apply(this, arguments);
7644
7895
  }
7645
7896
 
@@ -7661,7 +7912,7 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7661
7912
  return this._ensureReady;
7662
7913
 
7663
7914
  case 2:
7664
- return _context7.abrupt("return", this.conversationsPromise.then(function (conversations) {
7915
+ return _context7.abrupt("return", this._conversationsPromise.then(function (conversations) {
7665
7916
  return conversations.getConversations();
7666
7917
  }));
7667
7918
 
@@ -7698,7 +7949,7 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7698
7949
 
7699
7950
  case 2:
7700
7951
  options = options || {};
7701
- return _context8.abrupt("return", this.conversationsPromise.then(function (conversationsEntity) {
7952
+ return _context8.abrupt("return", this._conversationsPromise.then(function (conversationsEntity) {
7702
7953
  return conversationsEntity.addConversation(options);
7703
7954
  }));
7704
7955
 
@@ -7710,7 +7961,7 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7710
7961
  }, _callee8, this);
7711
7962
  }));
7712
7963
 
7713
- function createConversation(_x4) {
7964
+ function createConversation(_x5) {
7714
7965
  return _createConversation.apply(this, arguments);
7715
7966
  }
7716
7967
 
@@ -7719,7 +7970,8 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7719
7970
  /**
7720
7971
  * Register for push notifications.
7721
7972
  * @param channelType Channel type.
7722
- * @param registrationId Push notification ID provided by the FCM/APNS service on the platform.
7973
+ * @param registrationId Push notification ID provided by the FCM/APNS service
7974
+ * on the platform.
7723
7975
  */
7724
7976
 
7725
7977
  }, {
@@ -7736,9 +7988,10 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7736
7988
  case 2:
7737
7989
  this._subscribeToPushNotifications(channelType);
7738
7990
 
7739
- this.services.notificationClient.setPushRegistrationId(channelType, registrationId);
7991
+ this._services.notificationClient.setPushRegistrationId(channelType, registrationId);
7992
+
7740
7993
  _context9.next = 6;
7741
- return this.services.notificationClient.commitChanges();
7994
+ return this._services.notificationClient.commitChanges();
7742
7995
 
7743
7996
  case 6:
7744
7997
  case "end":
@@ -7748,7 +8001,7 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7748
8001
  }, _callee9, this);
7749
8002
  }));
7750
8003
 
7751
- function setPushRegistrationId(_x5, _x6) {
8004
+ function setPushRegistrationId(_x6, _x7) {
7752
8005
  return _setPushRegistrationId.apply(this, arguments);
7753
8006
  }
7754
8007
 
@@ -7775,7 +8028,7 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7775
8028
  this._unsubscribeFromPushNotifications(channelType);
7776
8029
 
7777
8030
  _context10.next = 5;
7778
- return this.services.notificationClient.commitChanges();
8031
+ return this._services.notificationClient.commitChanges();
7779
8032
 
7780
8033
  case 5:
7781
8034
  case "end":
@@ -7785,7 +8038,7 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7785
8038
  }, _callee10, this);
7786
8039
  }));
7787
8040
 
7788
- function unsetPushRegistrationId(_x7) {
8041
+ function unsetPushRegistrationId(_x8) {
7789
8042
  return _unsetPushRegistrationId.apply(this, arguments);
7790
8043
  }
7791
8044
 
@@ -7795,11 +8048,14 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7795
8048
  * Clear existing registrations directly using provided device token.
7796
8049
  * This is useful to ensure stopped subscriptions without resubscribing.
7797
8050
  *
7798
- * This function goes completely beside the state machine and removes all registrations.
7799
- * Use with caution: if it races with current state machine operations, madness will ensue.
8051
+ * This function goes completely beside the state machine and removes all
8052
+ * registrations.
8053
+ * Use with caution: if it races with current state machine operations,
8054
+ * madness will ensue.
7800
8055
  *
7801
8056
  * @param channelType Channel type.
7802
- * @param registrationId Push notification ID provided by the FCM/APNS service on the platform.
8057
+ * @param registrationId Push notification ID provided by the FCM/APNS service
8058
+ * on the platform.
7803
8059
  */
7804
8060
 
7805
8061
  }, {
@@ -7811,7 +8067,7 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7811
8067
  switch (_context11.prev = _context11.next) {
7812
8068
  case 0:
7813
8069
  _context11.next = 2;
7814
- return this.services.notificationClient.removeRegistrations(channelType, registrationId);
8070
+ return this._services.notificationClient.removeRegistrations(channelType, registrationId);
7815
8071
 
7816
8072
  case 2:
7817
8073
  case "end":
@@ -7821,17 +8077,22 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7821
8077
  }, _callee11, this);
7822
8078
  }));
7823
8079
 
7824
- function removePushRegistrations(_x8, _x9) {
8080
+ function removePushRegistrations(_x9, _x10) {
7825
8081
  return _removePushRegistrations.apply(this, arguments);
7826
8082
  }
7827
8083
 
7828
8084
  return removePushRegistrations;
7829
8085
  }()
8086
+ /**
8087
+ * Current version of the Conversations client.
8088
+ */
8089
+
7830
8090
  }, {
7831
8091
  key: "handlePushNotification",
7832
8092
  value:
7833
8093
  /**
7834
- * Handle push notification payload parsing and emit the {@link Client.pushNotification} event on this {@link Client} instance.
8094
+ * Handle push notification payload parsing and emit the
8095
+ * {@link Client.pushNotification} event on this {@link Client} instance.
7835
8096
  * @param notificationPayload Push notification payload
7836
8097
  */
7837
8098
  function () {
@@ -7844,7 +8105,8 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7844
8105
  return this._ensureReady;
7845
8106
 
7846
8107
  case 2:
7847
- log.debug("handlePushNotification, notificationPayload=", notificationPayload);
8108
+ Client_1._logger.debug("handlePushNotification, notificationPayload=", notificationPayload);
8109
+
7848
8110
  this.emit("pushNotification", Client_1.parsePushNotification(notificationPayload));
7849
8111
 
7850
8112
  case 4:
@@ -7855,14 +8117,15 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7855
8117
  }, _callee12, this);
7856
8118
  }));
7857
8119
 
7858
- function handlePushNotification(_x10) {
8120
+ function handlePushNotification(_x11) {
7859
8121
  return _handlePushNotification.apply(this, arguments);
7860
8122
  }
7861
8123
 
7862
8124
  return handlePushNotification;
7863
8125
  }()
7864
8126
  /**
7865
- * Gets a user with the given identity. If it's in the subscribed list, then return the user object from it;
8127
+ * Gets a user with the given identity. If it's in the subscribed list, then
8128
+ * return the user object from it;
7866
8129
  * if not, then subscribe and add user to the subscribed list.
7867
8130
  * @param identity Identity of the user.
7868
8131
  * @returns A fully initialized user.
@@ -7880,7 +8143,7 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7880
8143
  return this._ensureReady;
7881
8144
 
7882
8145
  case 2:
7883
- return _context13.abrupt("return", this.services.users.getUser(identity));
8146
+ return _context13.abrupt("return", this._services.users.getUser(identity));
7884
8147
 
7885
8148
  case 3:
7886
8149
  case "end":
@@ -7890,7 +8153,7 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7890
8153
  }, _callee13, this);
7891
8154
  }));
7892
8155
 
7893
- function getUser(_x11) {
8156
+ function getUser(_x12) {
7894
8157
  return _getUser.apply(this, arguments);
7895
8158
  }
7896
8159
 
@@ -7912,7 +8175,7 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7912
8175
  return this._ensureReady;
7913
8176
 
7914
8177
  case 2:
7915
- return _context14.abrupt("return", this.services.users.getSubscribedUsers());
8178
+ return _context14.abrupt("return", this._services.users.getSubscribedUsers());
7916
8179
 
7917
8180
  case 3:
7918
8181
  case "end":
@@ -7928,52 +8191,254 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7928
8191
 
7929
8192
  return getSubscribedUsers;
7930
8193
  }()
7931
- }], [{
7932
- key: "populateInitRegistrations",
7933
- value: function populateInitRegistrations(reg) {
7934
- reg.populateInitRegistrations([NotificationTypes.TYPING_INDICATOR]);
7935
- twilioSync.SyncClient.populateInitRegistrations(reg);
8194
+ /**
8195
+ * Get content URLs for all media attachments in the given set of media sids
8196
+ * using a single operation.
8197
+ * @param mediaSids Set of media sids to query for the content URL.
8198
+ */
8199
+
8200
+ }, {
8201
+ key: "getTemporaryContentUrlsForMediaSids",
8202
+ value: function getTemporaryContentUrlsForMediaSids(mediaSids) {
8203
+ var _this2 = this;
8204
+
8205
+ return new mcsClient.CancellablePromise( /*#__PURE__*/function () {
8206
+ var _ref2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee15(resolve, reject, onCancel) {
8207
+ var request, urls;
8208
+ return _regeneratorRuntime__default['default'].wrap(function _callee15$(_context15) {
8209
+ while (1) {
8210
+ switch (_context15.prev = _context15.next) {
8211
+ case 0:
8212
+ if (!(!_this2._services.mcsClient || !mediaSids)) {
8213
+ _context15.next = 3;
8214
+ break;
8215
+ }
8216
+
8217
+ reject(new Error("Media Content Service is unavailable"));
8218
+ return _context15.abrupt("return");
8219
+
8220
+ case 3:
8221
+ request = _this2._services.mcsClient.mediaSetGetContentUrls(mediaSids);
8222
+ onCancel(function () {
8223
+ request.cancel();
8224
+ });
8225
+ _context15.prev = 5;
8226
+ _context15.next = 8;
8227
+ return request;
8228
+
8229
+ case 8:
8230
+ urls = _context15.sent;
8231
+ resolve(urls);
8232
+ _context15.next = 15;
8233
+ break;
8234
+
8235
+ case 12:
8236
+ _context15.prev = 12;
8237
+ _context15.t0 = _context15["catch"](5);
8238
+ reject(_context15.t0);
8239
+
8240
+ case 15:
8241
+ case "end":
8242
+ return _context15.stop();
8243
+ }
8244
+ }
8245
+ }, _callee15, null, [[5, 12]]);
8246
+ }));
8247
+
8248
+ return function (_x13, _x14, _x15) {
8249
+ return _ref2.apply(this, arguments);
8250
+ };
8251
+ }());
7936
8252
  }
7937
8253
  /**
7938
- * Fired when a conversation becomes visible to the client. The event is also triggered when the client creates a new conversation.
7939
- * Fired for all conversations client has joined.
7940
- *
7941
- * Parameters:
7942
- * 1. {@link Conversation} `conversation` - the conversation in question
7943
- * @event
8254
+ * Get content URLs for all media attachments in the given set using a single
8255
+ * operation.
8256
+ * @param contentSet Set of media attachments to query content URLs.
7944
8257
  */
7945
8258
 
7946
8259
  }, {
7947
- key: "create",
7948
- value:
8260
+ key: "getTemporaryContentUrlsForMedia",
8261
+ value: function getTemporaryContentUrlsForMedia(contentSet) {
8262
+ // We ignore existing mcsMedia members of each of the media entries.
8263
+ // Instead, we just collect their sids and pull new descriptors from a
8264
+ // mediaSet GET endpoint.
8265
+ var sids = contentSet.map(function (m) {
8266
+ return m.sid;
8267
+ });
8268
+ return this.getTemporaryContentUrlsForMediaSids(sids);
8269
+ }
7949
8270
  /**
7950
- * @deprecated Call constructor directly.
7951
- *
7952
- * Factory method to create a Conversations client instance.
7953
- *
7954
- * The factory method will automatically trigger connection.
7955
- * Do not use it if you need finer-grained control.
7956
- *
7957
- * Since this method returns an already-initialized client, some of the events
7958
- * will be lost because they happen *before* the initialization. It is
7959
- * recommended that `client.onWithReplay` is used as opposed to `client.on`
7960
- * for subscribing to client events. The `client.onWithReplay` will re-emit
7961
- * the most recent value for a given event if it emitted before the
7962
- * subscription.
7963
- *
7964
- * @param token Access token.
7965
- * @param options Options to customize the client.
7966
- * @returns Returns a fully initialized client.
8271
+ * Initialize the client.
7967
8272
  */
7968
- function () {
7969
- var _create = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee15(token, options) {
8273
+
8274
+ }, {
8275
+ key: "_initialize",
8276
+ value: function () {
8277
+ var _initialize2 = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee16() {
8278
+ var _this3 = this;
8279
+
8280
+ var configurationResponse;
8281
+ return _regeneratorRuntime__default['default'].wrap(function _callee16$(_context16) {
8282
+ while (1) {
8283
+ switch (_context16.prev = _context16.next) {
8284
+ case 0:
8285
+ _context16.next = 2;
8286
+ return this._services.commandExecutor.fetchResource("Client/v2/Configuration");
8287
+
8288
+ case 2:
8289
+ configurationResponse = _context16.sent;
8290
+ this._configuration = new Configuration(this._options, configurationResponse, Client_1._logger);
8291
+
8292
+ this._myself._resolveInitialization(this._configuration, this._configuration.userIdentity, this._configuration.userInfo, true);
8293
+
8294
+ this._services.typingIndicator = new TypingIndicator(this.getConversationBySid.bind(this), this._configuration, this._services);
8295
+ this._services.network = new Network(this._configuration, this._services);
8296
+ this._services.users = new Users(this._myself, this._configuration, this._services);
8297
+
8298
+ this._services.users.on("userSubscribed", function (user) {
8299
+ _this3.emit("userSubscribed", user);
8300
+ });
8301
+
8302
+ this._services.users.on("userUpdated", function (args) {
8303
+ return _this3.emit("userUpdated", args);
8304
+ });
8305
+
8306
+ this._services.users.on("userUnsubscribed", function (user) {
8307
+ _this3.emit("userUnsubscribed", user);
8308
+ });
8309
+
8310
+ this._conversations = new Conversations(this._configuration, this._services);
8311
+
8312
+ this._conversations.on("conversationAdded", function (conversation) {
8313
+ _this3.emit("conversationAdded", conversation);
8314
+ });
8315
+
8316
+ this._conversations.on("conversationRemoved", function (conversation) {
8317
+ _this3.emit("conversationRemoved", conversation);
8318
+ });
8319
+
8320
+ this._conversations.on("conversationJoined", function (conversation) {
8321
+ _this3.emit("conversationJoined", conversation);
8322
+ });
8323
+
8324
+ this._conversations.on("conversationLeft", function (conversation) {
8325
+ _this3.emit("conversationLeft", conversation);
8326
+ });
8327
+
8328
+ this._conversations.on("conversationUpdated", function (args) {
8329
+ return _this3.emit("conversationUpdated", args);
8330
+ });
8331
+
8332
+ this._conversations.on("participantJoined", function (participant) {
8333
+ _this3.emit("participantJoined", participant);
8334
+ });
8335
+
8336
+ this._conversations.on("participantLeft", function (participant) {
8337
+ _this3.emit("participantLeft", participant);
8338
+ });
8339
+
8340
+ this._conversations.on("participantUpdated", function (args) {
8341
+ return _this3.emit("participantUpdated", args);
8342
+ });
8343
+
8344
+ this._conversations.on("messageAdded", function (message) {
8345
+ return _this3.emit("messageAdded", message);
8346
+ });
8347
+
8348
+ this._conversations.on("messageUpdated", function (args) {
8349
+ return _this3.emit("messageUpdated", args);
8350
+ });
8351
+
8352
+ this._conversations.on("messageRemoved", function (message) {
8353
+ return _this3.emit("messageRemoved", message);
8354
+ });
8355
+
8356
+ this._conversations.on("typingStarted", function (participant) {
8357
+ return _this3.emit("typingStarted", participant);
8358
+ });
8359
+
8360
+ this._conversations.on("typingEnded", function (participant) {
8361
+ return _this3.emit("typingEnded", participant);
8362
+ });
8363
+
8364
+ this._conversationsPromise = this._conversations.fetchConversations().then(function () {
8365
+ return _this3._conversations;
8366
+ }).catch(function (error) {
8367
+ throw error;
8368
+ });
8369
+ _context16.next = 28;
8370
+ return this._services.users.myself._ensureFetched();
8371
+
8372
+ case 28:
8373
+ Client_1._supportedPushChannels.forEach(function (channelType) {
8374
+ return _this3._subscribeToPushNotifications(channelType);
8375
+ });
8376
+
8377
+ this._services.typingIndicator.initialize();
8378
+
8379
+ this._services.mcsClient = new mcsClient.McsClient(this._fpaToken, this._configuration.links.mediaService, this._configuration.links.mediaSetService, _objectSpread(_objectSpread({}, this._options), {}, {
8380
+ transport: undefined
8381
+ }));
8382
+
8383
+ this._resolveEnsureReady();
8384
+
8385
+ this.emit("stateChanged", {
8386
+ state: "initialized"
8387
+ });
8388
+
8389
+ case 33:
8390
+ case "end":
8391
+ return _context16.stop();
8392
+ }
8393
+ }
8394
+ }, _callee16, this);
8395
+ }));
8396
+
8397
+ function _initialize() {
8398
+ return _initialize2.apply(this, arguments);
8399
+ }
8400
+
8401
+ return _initialize;
8402
+ }()
8403
+ /**
8404
+ * Subscribe to push notifications.
8405
+ * @param channelType The channel type to subscribe to.
8406
+ */
8407
+
8408
+ }, {
8409
+ key: "_subscribeToPushNotifications",
8410
+ value: function _subscribeToPushNotifications(channelType) {
8411
+ var _this4 = this;
8412
+
8413
+ [NotificationTypes.NEW_MESSAGE, NotificationTypes.ADDED_TO_CONVERSATION, NotificationTypes.REMOVED_FROM_CONVERSATION, NotificationTypes.TYPING_INDICATOR, NotificationTypes.CONSUMPTION_UPDATE].forEach(function (messageType) {
8414
+ _this4._services.notificationClient.subscribe(channelType, messageType);
8415
+ });
8416
+ }
8417
+ /**
8418
+ * Unsubscribe from push notifications.
8419
+ * @param channelType The channel type to unsubscribe from.
8420
+ */
8421
+
8422
+ }, {
8423
+ key: "_unsubscribeFromPushNotifications",
8424
+ value: function _unsubscribeFromPushNotifications(channelType) {
8425
+ var _this5 = this;
8426
+
8427
+ [NotificationTypes.NEW_MESSAGE, NotificationTypes.ADDED_TO_CONVERSATION, NotificationTypes.REMOVED_FROM_CONVERSATION, NotificationTypes.TYPING_INDICATOR, NotificationTypes.CONSUMPTION_UPDATE].forEach(function (messageType) {
8428
+ _this5._services.notificationClient.unsubscribe(channelType, messageType);
8429
+ });
8430
+ }
8431
+ }], [{
8432
+ key: "create",
8433
+ value: function () {
8434
+ var _create = _asyncToGenerator__default['default']( /*#__PURE__*/_regeneratorRuntime__default['default'].mark(function _callee17(token, options) {
7970
8435
  var client;
7971
- return _regeneratorRuntime__default['default'].wrap(function _callee15$(_context15) {
8436
+ return _regeneratorRuntime__default['default'].wrap(function _callee17$(_context17) {
7972
8437
  while (1) {
7973
- switch (_context15.prev = _context15.next) {
8438
+ switch (_context17.prev = _context17.next) {
7974
8439
  case 0:
7975
8440
  if (!(options !== null && options !== void 0 && options.twilsockClient)) {
7976
- _context15.next = 2;
8441
+ _context17.next = 2;
7977
8442
  break;
7978
8443
  }
7979
8444
 
@@ -7981,64 +8446,45 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
7981
8446
 
7982
8447
  case 2:
7983
8448
  client = new Client_1(token, options);
7984
- _context15.next = 5;
8449
+ _context17.next = 5;
7985
8450
  return client._ensureReady;
7986
8451
 
7987
8452
  case 5:
7988
- return _context15.abrupt("return", client);
8453
+ return _context17.abrupt("return", client);
7989
8454
 
7990
8455
  case 6:
7991
8456
  case "end":
7992
- return _context15.stop();
8457
+ return _context17.stop();
7993
8458
  }
7994
8459
  }
7995
- }, _callee15);
8460
+ }, _callee17);
7996
8461
  }));
7997
8462
 
7998
- function create(_x12, _x13) {
8463
+ function create(_x16, _x17) {
7999
8464
  return _create.apply(this, arguments);
8000
8465
  }
8001
8466
 
8002
8467
  return create;
8003
8468
  }()
8004
- }, {
8005
- key: "parsePushNotificationChatData",
8006
- value: function parsePushNotificationChatData(data) {
8007
- var result = {};
8008
-
8009
- for (var key in Client_1.supportedPushDataFields) {
8010
- if (typeof data[key] === "undefined" || data[key] === null) {
8011
- continue;
8012
- }
8013
-
8014
- if (key !== "message_index") {
8015
- result[Client_1.supportedPushDataFields[key]] = data[key];
8016
- continue;
8017
- }
8018
-
8019
- if (parseToNumber(data[key]) !== null) {
8020
- result[Client_1.supportedPushDataFields[key]] = Number(data[key]);
8021
- }
8022
- }
8023
-
8024
- return result;
8025
- }
8026
8469
  /**
8027
- * Static method for push notification payload parsing. Returns parsed push as a {@link PushNotification} object.
8470
+ * Static method for push notification payload parsing. Returns parsed push as
8471
+ * a {@link PushNotification} object.
8028
8472
  * @param notificationPayload Push notification payload.
8029
8473
  */
8030
8474
 
8031
8475
  }, {
8032
8476
  key: "parsePushNotification",
8033
8477
  value: function parsePushNotification(notificationPayload) {
8034
- log.debug("parsePushNotification, notificationPayload=", notificationPayload); // APNS specifics
8478
+ Client_1._logger.debug("parsePushNotification, notificationPayload=", notificationPayload); // APNS specifics
8479
+
8035
8480
 
8036
8481
  if (typeof notificationPayload.aps !== "undefined") {
8037
8482
  if (!notificationPayload.twi_message_type) {
8038
8483
  throw new Error("Provided push notification payload does not contain Programmable Chat push notification type");
8039
8484
  }
8040
8485
 
8041
- var data = Client_1.parsePushNotificationChatData(notificationPayload);
8486
+ var data = Client_1._parsePushNotificationChatData(notificationPayload);
8487
+
8042
8488
  var apsPayload = notificationPayload.aps;
8043
8489
  var body;
8044
8490
  var title = null;
@@ -8069,7 +8515,7 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
8069
8515
  throw new Error("Provided push notification payload does not contain Programmable Chat push notification type");
8070
8516
  }
8071
8517
 
8072
- var _data = Client_1.parsePushNotificationChatData(notificationPayload.data);
8518
+ var _data = Client_1._parsePushNotificationChatData(notificationPayload.data);
8073
8519
 
8074
8520
  return new PushNotification({
8075
8521
  title: dataPayload.twi_title || null,
@@ -8084,19 +8530,80 @@ exports.Client = Client_1 = (_temp = _class = /*#__PURE__*/function (_ReplayEven
8084
8530
 
8085
8531
  throw new Error("Provided push notification payload is not Programmable Chat notification");
8086
8532
  }
8533
+ /**
8534
+ * Static method for parsing push notification chat data.
8535
+ * @param data Data to parse
8536
+ */
8537
+
8538
+ }, {
8539
+ key: "_parsePushNotificationChatData",
8540
+ value: function _parsePushNotificationChatData(data) {
8541
+ var result = {};
8542
+
8543
+ for (var key in Client_1._supportedPushDataFields) {
8544
+ var value = data[key];
8545
+
8546
+ if (typeof value === "undefined" || value === null) {
8547
+ continue;
8548
+ }
8549
+
8550
+ if (key === "message_index" || key === "media_count") {
8551
+ var number = parseToNumber(value);
8552
+
8553
+ if (number !== null) {
8554
+ result[Client_1._supportedPushDataFields[key]] = number;
8555
+ }
8556
+
8557
+ continue;
8558
+ }
8559
+
8560
+ if (key === "media") {
8561
+ if (typeof value === "string") {
8562
+ try {
8563
+ result[Client_1._supportedPushDataFields[key]] = JSON.parse(value);
8564
+ } catch (_unused) {
8565
+ Client_1._logger.debug("Media message notification parsing error");
8566
+ }
8567
+ }
8568
+
8569
+ continue;
8570
+ }
8571
+
8572
+ result[Client_1._supportedPushDataFields[key]] = value;
8573
+ }
8574
+
8575
+ return result;
8576
+ }
8577
+ /**
8578
+ * Populate the client with init registrations.
8579
+ * @param reg The init registration to populate.
8580
+ */
8581
+
8582
+ }, {
8583
+ key: "populateInitRegistrations",
8584
+ value: function populateInitRegistrations(reg) {
8585
+ reg.populateInitRegistrations([NotificationTypes.TYPING_INDICATOR]);
8586
+ twilioSync.SyncClient.populateInitRegistrations(reg);
8587
+ }
8087
8588
  }]);
8088
8589
 
8089
8590
  return Client;
8090
- }(replayEventEmitter.ReplayEventEmitter), _defineProperty__default['default'](_class, "version", SDK_VERSION), _defineProperty__default['default'](_class, "supportedPushChannels", ["fcm", "apn"]), _defineProperty__default['default'](_class, "supportedPushDataFields", {
8591
+ }(replayEventEmitter.ReplayEventEmitter), _defineProperty__default['default'](_class, "conversationAdded", "conversationAdded"), _defineProperty__default['default'](_class, "conversationJoined", "conversationJoined"), _defineProperty__default['default'](_class, "conversationLeft", "conversationLeft"), _defineProperty__default['default'](_class, "conversationRemoved", "conversationRemoved"), _defineProperty__default['default'](_class, "conversationUpdated", "conversationUpdated"), _defineProperty__default['default'](_class, "participantJoined", "participantJoined"), _defineProperty__default['default'](_class, "participantLeft", "participantLeft"), _defineProperty__default['default'](_class, "participantUpdated", "participantUpdated"), _defineProperty__default['default'](_class, "messageAdded", "messageAdded"), _defineProperty__default['default'](_class, "messageRemoved", "messageRemoved"), _defineProperty__default['default'](_class, "messageUpdated", "messageUpdated"), _defineProperty__default['default'](_class, "tokenAboutToExpire", "tokenAboutToExpire"), _defineProperty__default['default'](_class, "tokenExpired", "tokenExpired"), _defineProperty__default['default'](_class, "typingEnded", "typingEnded"), _defineProperty__default['default'](_class, "typingStarted", "typingStarted"), _defineProperty__default['default'](_class, "pushNotification", "pushNotification"), _defineProperty__default['default'](_class, "userSubscribed", "userSubscribed"), _defineProperty__default['default'](_class, "userUnsubscribed", "userUnsubscribed"), _defineProperty__default['default'](_class, "userUpdated", "userUpdated"), _defineProperty__default['default'](_class, "stateChanged", "stateChanged"), _defineProperty__default['default'](_class, "connectionStateChanged", "connectionStateChanged"), _defineProperty__default['default'](_class, "connectionError", "connectionError"), _defineProperty__default['default'](_class, "version", version), _defineProperty__default['default'](_class, "_logger", Logger.scope("Client")), _defineProperty__default['default'](_class, "_supportedPushChannels", ["fcm", "apn"]), _defineProperty__default['default'](_class, "_supportedPushDataFields", {
8091
8592
  conversation_sid: "conversationSid",
8593
+ conversation_title: "conversationTitle",
8092
8594
  message_sid: "messageSid",
8093
- message_index: "messageIndex"
8094
- }), _defineProperty__default['default'](_class, "conversationAdded", "conversationAdded"), _defineProperty__default['default'](_class, "conversationJoined", "conversationJoined"), _defineProperty__default['default'](_class, "conversationLeft", "conversationLeft"), _defineProperty__default['default'](_class, "conversationRemoved", "conversationRemoved"), _defineProperty__default['default'](_class, "conversationUpdated", "conversationUpdated"), _defineProperty__default['default'](_class, "participantJoined", "participantJoined"), _defineProperty__default['default'](_class, "participantLeft", "participantLeft"), _defineProperty__default['default'](_class, "participantUpdated", "participantUpdated"), _defineProperty__default['default'](_class, "messageAdded", "messageAdded"), _defineProperty__default['default'](_class, "messageRemoved", "messageRemoved"), _defineProperty__default['default'](_class, "messageUpdated", "messageUpdated"), _defineProperty__default['default'](_class, "tokenAboutToExpire", "tokenAboutToExpire"), _defineProperty__default['default'](_class, "tokenExpired", "tokenExpired"), _defineProperty__default['default'](_class, "typingEnded", "typingEnded"), _defineProperty__default['default'](_class, "typingStarted", "typingStarted"), _defineProperty__default['default'](_class, "pushNotification", "pushNotification"), _defineProperty__default['default'](_class, "userSubscribed", "userSubscribed"), _defineProperty__default['default'](_class, "userUnsubscribed", "userUnsubscribed"), _defineProperty__default['default'](_class, "userUpdated", "userUpdated"), _defineProperty__default['default'](_class, "stateChanged", "stateChanged"), _defineProperty__default['default'](_class, "connectionStateChanged", "connectionStateChanged"), _defineProperty__default['default'](_class, "connectionError", "connectionError"), _temp);
8595
+ message_index: "messageIndex",
8596
+ media_count: "mediaCount",
8597
+ media: "media" // object
8598
+
8599
+ }), _temp);
8095
8600
 
8096
8601
  __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", Promise)], exports.Client.prototype, "updateToken", null);
8097
8602
 
8098
8603
  __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", Promise)], exports.Client.prototype, "getConversationBySid", null);
8099
8604
 
8605
+ __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", Promise)], exports.Client.prototype, "peekConversationBySid", null);
8606
+
8100
8607
  __decorate([declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.nonEmptyString), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", Promise)], exports.Client.prototype, "getConversationByUniqueName", null);
8101
8608
 
8102
8609
  __decorate([declarativeTypeValidator.validateTypesAsync(["undefined", declarativeTypeValidator.objectSchema("conversation options", {