@twilio/conversations 3.0.0-rc.8 → 3.0.1-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.
Files changed (158) hide show
  1. package/README.md +38 -28
  2. package/builds/browser.js +4327 -7903
  3. package/builds/browser.js.map +1 -1
  4. package/builds/lib.d.ts +629 -102
  5. package/builds/lib.js +4319 -7904
  6. package/builds/lib.js.map +1 -1
  7. package/builds/twilio-conversations.js +27540 -41958
  8. package/builds/twilio-conversations.min.js +200 -1
  9. package/dist/aggregated-delivery-receipt.js +10 -1
  10. package/dist/aggregated-delivery-receipt.js.map +1 -1
  11. package/dist/channel-metadata-client.js +192 -0
  12. package/dist/channel-metadata-client.js.map +1 -0
  13. package/dist/client.js +75 -123
  14. package/dist/client.js.map +1 -1
  15. package/dist/command-executor.js +81 -20
  16. package/dist/command-executor.js.map +1 -1
  17. package/dist/configuration.js +14 -3
  18. package/dist/configuration.js.map +1 -1
  19. package/dist/content-client.js +184 -0
  20. package/dist/content-client.js.map +1 -0
  21. package/dist/content-template.js +310 -0
  22. package/dist/content-template.js.map +1 -0
  23. package/dist/conversation.js +105 -22
  24. package/dist/conversation.js.map +1 -1
  25. package/dist/data/conversations.js +43 -5
  26. package/dist/data/conversations.js.map +1 -1
  27. package/dist/data/messages.js +26 -19
  28. package/dist/data/messages.js.map +1 -1
  29. package/dist/data/participants.js +15 -4
  30. package/dist/data/participants.js.map +1 -1
  31. package/dist/data/users.js +11 -2
  32. package/dist/data/users.js.map +1 -1
  33. package/dist/detailed-delivery-receipt.js +9 -0
  34. package/dist/detailed-delivery-receipt.js.map +1 -1
  35. package/dist/index.js +20 -2
  36. package/dist/index.js.map +1 -1
  37. package/dist/interfaces/notification-types.js +9 -0
  38. package/dist/interfaces/notification-types.js.map +1 -1
  39. package/dist/interfaces/{attributes.js → rules.js} +26 -7
  40. package/dist/interfaces/rules.js.map +1 -0
  41. package/dist/logger.js +9 -0
  42. package/dist/logger.js.map +1 -1
  43. package/dist/media.js +9 -0
  44. package/dist/media.js.map +1 -1
  45. package/dist/message-builder.js +77 -6
  46. package/dist/message-builder.js.map +1 -1
  47. package/dist/message.js +115 -22
  48. package/dist/message.js.map +1 -1
  49. package/dist/node_modules/quick-lru/index.js +265 -0
  50. package/dist/node_modules/quick-lru/index.js.map +1 -0
  51. package/dist/node_modules/tslib/tslib.es6.js +9 -0
  52. package/dist/node_modules/tslib/tslib.es6.js.map +1 -1
  53. package/dist/packages/conversations/package.json.js +10 -1
  54. package/dist/packages/conversations/package.json.js.map +1 -1
  55. package/dist/participant.js +45 -36
  56. package/dist/participant.js.map +1 -1
  57. package/dist/push-notification.js +9 -0
  58. package/dist/push-notification.js.map +1 -1
  59. package/dist/rest-paginator.js +20 -11
  60. package/dist/rest-paginator.js.map +1 -1
  61. package/dist/services/network.js +110 -11
  62. package/dist/services/network.js.map +1 -1
  63. package/dist/services/typing-indicator.js +22 -5
  64. package/dist/services/typing-indicator.js.map +1 -1
  65. package/dist/unsent-message.js +9 -0
  66. package/dist/unsent-message.js.map +1 -1
  67. package/dist/user.js +20 -3
  68. package/dist/user.js.map +1 -1
  69. package/dist/util/deferred.js +9 -0
  70. package/dist/util/deferred.js.map +1 -1
  71. package/dist/util/index.js +9 -0
  72. package/dist/util/index.js.map +1 -1
  73. package/docs/.nojekyll +1 -0
  74. package/docs/assets/highlight.css +113 -0
  75. package/docs/assets/main.js +58 -0
  76. package/docs/assets/search.js +1 -0
  77. package/docs/assets/style.css +1279 -0
  78. package/docs/classes/AggregatedDeliveryReceipt.html +144 -3182
  79. package/docs/classes/CancellablePromise.html +224 -3209
  80. package/docs/classes/CancellationError.html +112 -0
  81. package/docs/classes/ChannelMetadata.html +67 -0
  82. package/docs/classes/Client.html +701 -4237
  83. package/docs/classes/ContentTemplate.html +97 -0
  84. package/docs/classes/ContentTemplateVariable.html +90 -0
  85. package/docs/classes/Conversation.html +768 -4352
  86. package/docs/classes/DetailedDeliveryReceipt.html +116 -3162
  87. package/docs/classes/Media.html +119 -3165
  88. package/docs/classes/Message.html +417 -3730
  89. package/docs/classes/MessageBuilder.html +208 -3274
  90. package/docs/classes/Participant.html +258 -3442
  91. package/docs/classes/PushNotification.html +101 -3129
  92. package/docs/classes/RestPaginator.html +120 -3158
  93. package/docs/classes/UnsentMessage.html +63 -3040
  94. package/docs/classes/User.html +209 -3347
  95. package/docs/index.html +146 -3502
  96. package/docs/interfaces/ClientOptions.html +66 -3033
  97. package/docs/interfaces/ConversationBindings.html +109 -3000
  98. package/docs/interfaces/ConversationEmailBinding.html +109 -3000
  99. package/docs/interfaces/ConversationLimits.html +87 -3097
  100. package/docs/interfaces/ConversationState.html +66 -3049
  101. package/docs/interfaces/ConversationUpdatedEventArgs.html +109 -3000
  102. package/docs/interfaces/CreateConversationOptions.html +73 -3065
  103. package/docs/interfaces/LastMessage.html +66 -3049
  104. package/docs/interfaces/Paginator.html +110 -3139
  105. package/docs/interfaces/ParticipantBindingOptions.html +110 -0
  106. package/docs/interfaces/ParticipantBindings.html +109 -3000
  107. package/docs/interfaces/ParticipantEmailBinding.html +109 -3000
  108. package/docs/interfaces/PushNotificationData.html +94 -3113
  109. package/docs/interfaces/SendEmailOptions.html +59 -3033
  110. package/docs/interfaces/SendMediaOptions.html +75 -3067
  111. package/docs/modules.html +180 -3509
  112. package/docs/types/ChannelType.html +106 -0
  113. package/docs/types/ConnectionState.html +115 -0
  114. package/docs/types/ContentData.html +106 -0
  115. package/docs/types/ContentDataAction.html +107 -0
  116. package/docs/types/ContentDataActionOther.html +121 -0
  117. package/docs/types/ContentDataActionPhone.html +128 -0
  118. package/docs/types/ContentDataActionReply.html +133 -0
  119. package/docs/types/ContentDataActionUrl.html +128 -0
  120. package/docs/types/ContentDataCallToAction.html +131 -0
  121. package/docs/types/ContentDataCard.html +137 -0
  122. package/docs/types/ContentDataListItem.html +121 -0
  123. package/docs/types/ContentDataListPicker.html +134 -0
  124. package/docs/types/ContentDataLocation.html +134 -0
  125. package/docs/types/ContentDataMedia.html +129 -0
  126. package/docs/types/ContentDataOther.html +121 -0
  127. package/docs/types/ContentDataQuickReply.html +131 -0
  128. package/docs/types/ContentDataReply.html +119 -0
  129. package/docs/types/ContentDataText.html +125 -0
  130. package/docs/types/ConversationStatus.html +107 -0
  131. package/docs/types/ConversationUpdateReason.html +106 -0
  132. package/docs/types/DeliveryAmount.html +106 -0
  133. package/docs/types/DeliveryStatus.html +106 -0
  134. package/docs/types/JSONArray.html +106 -0
  135. package/docs/types/JSONObject.html +111 -0
  136. package/docs/types/JSONValue.html +106 -0
  137. package/docs/types/LogLevel.html +106 -0
  138. package/docs/types/MediaCategory.html +106 -0
  139. package/docs/types/MessageType.html +106 -0
  140. package/docs/types/MessageUpdateReason.html +106 -0
  141. package/docs/types/NotificationLevel.html +109 -0
  142. package/docs/types/NotificationsChannelType.html +110 -0
  143. package/docs/types/ParticipantEmailLevel.html +108 -0
  144. package/docs/types/ParticipantType.html +107 -0
  145. package/docs/types/ParticipantUpdateReason.html +106 -0
  146. package/docs/types/PushNotificationType.html +106 -0
  147. package/docs/types/State.html +110 -0
  148. package/docs/types/UserUpdateReason.html +106 -0
  149. package/package.json +22 -17
  150. package/CHANGELOG.md +0 -501
  151. package/dist/interfaces/attributes.js.map +0 -1
  152. package/docs/assets/css/main.css +0 -2660
  153. package/docs/assets/images/icons.png +0 -0
  154. package/docs/assets/images/icons@2x.png +0 -0
  155. package/docs/assets/images/widgets.png +0 -0
  156. package/docs/assets/images/widgets@2x.png +0 -0
  157. package/docs/assets/js/main.js +0 -248
  158. package/docs/assets/js/search.js +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -128,6 +128,15 @@ This software includes platform.js under the following license.
128
128
  */
129
129
  'use strict';
130
130
 
131
+ var global =
132
+ typeof global !== "undefined"
133
+ ? global
134
+ : typeof self !== "undefined"
135
+ ? self
136
+ : typeof window !== "undefined"
137
+ ? window
138
+ : {};
139
+
131
140
  Object.defineProperty(exports, '__esModule', { value: true });
132
141
 
133
142
  /******************************************************************************
@@ -1 +1 @@
1
- {"version":3,"file":"tslib.es6.js","sources":["../../../../../node_modules/tslib/tslib.es6.js"],"sourcesContent":["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAwCA;AACO,SAAS,UAAU,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE;AAC1D,IAAI,IAAI,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,MAAM,GAAG,IAAI,KAAK,IAAI,GAAG,IAAI,GAAG,MAAM,CAAC,wBAAwB,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC;AACjI,IAAI,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,OAAO,CAAC,QAAQ,KAAK,UAAU,EAAE,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;AACnI,SAAS,KAAK,IAAI,CAAC,GAAG,UAAU,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,IAAI,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC;AACtJ,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;AAClE,CAAC;AAKD;AACO,SAAS,UAAU,CAAC,WAAW,EAAE,aAAa,EAAE;AACvD,IAAI,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,OAAO,CAAC,QAAQ,KAAK,UAAU,EAAE,OAAO,OAAO,CAAC,QAAQ,CAAC,WAAW,EAAE,aAAa,CAAC,CAAC;AACnI;;;;;"}
1
+ {"version":3,"file":"tslib.es6.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -128,9 +128,18 @@ This software includes platform.js under the following license.
128
128
  */
129
129
  'use strict';
130
130
 
131
+ var global =
132
+ typeof global !== "undefined"
133
+ ? global
134
+ : typeof self !== "undefined"
135
+ ? self
136
+ : typeof window !== "undefined"
137
+ ? window
138
+ : {};
139
+
131
140
  Object.defineProperty(exports, '__esModule', { value: true });
132
141
 
133
- var version = "3.0.0-rc.8";
142
+ var version = "3.0.1-rc.1";
134
143
 
135
144
  exports.version = version;
136
145
  //# sourceMappingURL=package.json.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"package.json.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"package.json.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -128,12 +128,21 @@ This software includes platform.js under the following license.
128
128
  */
129
129
  'use strict';
130
130
 
131
+ var global =
132
+ typeof global !== "undefined"
133
+ ? global
134
+ : typeof self !== "undefined"
135
+ ? self
136
+ : typeof window !== "undefined"
137
+ ? window
138
+ : {};
139
+
131
140
  Object.defineProperty(exports, '__esModule', { value: true });
132
141
 
133
142
  var tslib_es6 = require('./node_modules/tslib/tslib.es6.js');
134
143
  var index = require('./util/index.js');
135
144
  var logger = require('./logger.js');
136
- var attributes = require('./interfaces/attributes.js');
145
+ var rules = require('./interfaces/rules.js');
137
146
  var declarativeTypeValidator = require('@twilio/declarative-type-validator');
138
147
  var replayEventEmitter = require('@twilio/replay-event-emitter');
139
148
  var isEqual = require('lodash.isequal');
@@ -147,39 +156,6 @@ const log = logger.Logger.scope("Participant");
147
156
  * A participant represents a remote client in a conversation.
148
157
  */
149
158
  class Participant extends replayEventEmitter.ReplayEventEmitter {
150
- /**
151
- * @internal
152
- */
153
- constructor(data, sid, conversation, links, services) {
154
- var _a, _b;
155
- super();
156
- this.conversation = conversation;
157
- this.links = links;
158
- this.services = services;
159
- this.state = {
160
- attributes: index.parseAttributes(data.attributes, "Retrieved malformed attributes from the server for participant: " +
161
- sid, log),
162
- dateCreated: data.dateCreated ? index.parseTime(data.dateCreated) : null,
163
- dateUpdated: data.dateCreated ? index.parseTime(data.dateUpdated) : null,
164
- sid: sid,
165
- typingTimeout: null,
166
- isTyping: false,
167
- identity: data.identity,
168
- roleSid: (_a = data.roleSid) !== null && _a !== void 0 ? _a : "",
169
- lastReadMessageIndex: Number.isInteger(data.lastConsumedMessageIndex)
170
- ? data.lastConsumedMessageIndex
171
- : null,
172
- lastReadTimestamp: data.lastConsumptionTimestamp
173
- ? index.parseTime(data.lastConsumptionTimestamp)
174
- : null,
175
- type: data.type || "chat",
176
- userInfo: data.userInfo,
177
- bindings: (_b = data.bindings) !== null && _b !== void 0 ? _b : {},
178
- };
179
- if (!data.identity && !data.type) {
180
- throw new Error("Received invalid Participant object from server: Missing identity or type of Participant.");
181
- }
182
- }
183
159
  /**
184
160
  * The server-assigned unique identifier for the participant.
185
161
  */
@@ -247,12 +223,45 @@ class Participant extends replayEventEmitter.ReplayEventEmitter {
247
223
  * using the type dynamically `participant.bindings[participant.type]`
248
224
  * just be aware that the binding information has different structure for
249
225
  * each participant type.
250
- * See also {ParticipantEmailBinding}, the only available currently binding descriptor.
226
+ * See also {@link ParticipantEmailBinding}, the only available currently binding descriptor.
251
227
  */
252
228
  get bindings() {
253
229
  var _a;
254
230
  return (_a = this.state.bindings) !== null && _a !== void 0 ? _a : {};
255
231
  }
232
+ /**
233
+ * @internal
234
+ */
235
+ constructor(data, sid, conversation, links, services) {
236
+ var _a, _b;
237
+ super();
238
+ this.conversation = conversation;
239
+ this.links = links;
240
+ this.services = services;
241
+ this.state = {
242
+ attributes: index.parseAttributes(data.attributes, "Retrieved malformed attributes from the server for participant: " +
243
+ sid, log),
244
+ dateCreated: data.dateCreated ? index.parseTime(data.dateCreated) : null,
245
+ dateUpdated: data.dateCreated ? index.parseTime(data.dateUpdated) : null,
246
+ sid: sid,
247
+ typingTimeout: null,
248
+ isTyping: false,
249
+ identity: data.identity,
250
+ roleSid: (_a = data.roleSid) !== null && _a !== void 0 ? _a : "",
251
+ lastReadMessageIndex: Number.isInteger(data.lastConsumedMessageIndex)
252
+ ? data.lastConsumedMessageIndex
253
+ : null,
254
+ lastReadTimestamp: data.lastConsumptionTimestamp
255
+ ? index.parseTime(data.lastConsumptionTimestamp)
256
+ : null,
257
+ type: data.type || "chat",
258
+ userInfo: data.userInfo,
259
+ bindings: (_b = data.bindings) !== null && _b !== void 0 ? _b : {},
260
+ };
261
+ if (!data.identity && !data.type) {
262
+ throw new Error("Received invalid Participant object from server: Missing identity or type of Participant.");
263
+ }
264
+ }
256
265
  /**
257
266
  * Internal method used to start or reset the typing indicator timeout (with event emitting).
258
267
  * @internal
@@ -387,7 +396,7 @@ Participant.typingEnded = "typingEnded";
387
396
  */
388
397
  Participant.updated = "updated";
389
398
  tslib_es6.__decorate([
390
- declarativeTypeValidator.validateTypesAsync(attributes.attributesValidator),
399
+ declarativeTypeValidator.validateTypesAsync(rules.json),
391
400
  tslib_es6.__metadata("design:type", Function),
392
401
  tslib_es6.__metadata("design:paramtypes", [Object]),
393
402
  tslib_es6.__metadata("design:returntype", Promise)
@@ -1 +1 @@
1
- {"version":3,"file":"participant.js","sources":["../src/participant.ts"],"sourcesContent":["import { Users } from \"./data/users\";\nimport { User } from \"./user\";\nimport { parseTime, parseAttributes } from \"./util\";\nimport { Logger } from \"./logger\";\nimport { Conversation } from \"./conversation\";\nimport { attributesValidator } from \"./interfaces/attributes\";\nimport { validateTypesAsync } from \"@twilio/declarative-type-validator\";\nimport { CommandExecutor } from \"./command-executor\";\nimport { EditParticipantRequest } from \"./interfaces/commands/edit-participant\";\nimport { ParticipantResponse } from \"./interfaces/commands/participant-response\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport isEqual from \"lodash.isequal\";\nimport { JSONValue } from \"./types\";\n\ntype ParticipantEvents = {\n typingEnded: (participant: Participant) => void;\n typingStarted: (participant: Participant) => void;\n updated: (data: {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n }) => void;\n};\n\nconst log = Logger.scope(\"Participant\");\n\ninterface ParticipantDescriptor {\n attributes?: JSONValue;\n dateCreated: Date | null;\n dateUpdated: Date | null;\n identity: string;\n roleSid?: string;\n lastConsumedMessageIndex: number | null;\n lastConsumptionTimestamp: number | null;\n type: ParticipantType;\n userInfo?: string;\n bindings?: ParticipantBindings;\n}\n\ninterface ParticipantState {\n attributes: JSONValue;\n dateCreated: Date | null;\n dateUpdated: Date | null;\n identity: string;\n isTyping: boolean;\n lastReadMessageIndex: number | null;\n lastReadTimestamp: Date | null;\n roleSid: string;\n sid: string;\n type: ParticipantType;\n typingTimeout: number | null;\n userInfo?: string;\n bindings?: ParticipantBindings;\n}\n\ninterface ParticipantServices {\n users: Users;\n commandExecutor: CommandExecutor;\n}\n\ninterface ParticipantLinks {\n self: string;\n}\n\n/**\n * The reason for the `updated` event being emitted by a participant.\n */\ntype ParticipantUpdateReason =\n | \"attributes\"\n | \"dateCreated\"\n | \"dateUpdated\"\n | \"roleSid\"\n | \"lastReadMessageIndex\"\n | \"lastReadTimestamp\"\n | \"bindings\";\n\n/**\n * Type of a participant.\n */\ntype ParticipantType = \"chat\" | \"sms\" | \"whatsapp\" | \"email\";\n\ninterface ParticipantUpdatedEventArgs {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n}\n\n/**\n * Bindings for conversation participant.\n */\ninterface ParticipantBindings {\n email?: ParticipantEmailBinding;\n}\n\n/**\n * Email participation level.\n * to = to/from\n * cc = cc\n */\ntype ParticipantEmailLevel = \"to\" | \"cc\";\n\n/**\n * Bindings for email participant.\n */\ninterface ParticipantEmailBinding {\n name: string;\n address: string;\n level: ParticipantEmailLevel;\n}\n\n/**\n * A participant represents a remote client in a conversation.\n */\nclass Participant extends ReplayEventEmitter<ParticipantEvents> {\n private state: ParticipantState;\n private readonly links: ParticipantLinks;\n private readonly services: ParticipantServices;\n\n /**\n * Conversation that the remote client is a participant of.\n */\n public readonly conversation: Conversation;\n\n /**\n * The server-assigned unique identifier for the participant.\n */\n public get sid(): string {\n return this.state.sid;\n }\n\n /**\n * Custom attributes of the participant.\n */\n public get attributes(): JSONValue {\n return this.state.attributes;\n }\n\n /**\n * Date this participant was created on.\n */\n public get dateCreated(): Date | null {\n return this.state.dateCreated;\n }\n\n /**\n * Date this participant was last updated on.\n */\n public get dateUpdated(): Date | null {\n return this.state.dateUpdated;\n }\n\n /**\n * Identity of the participant.\n */\n public get identity(): string | null {\n return this.state.identity;\n }\n\n /**\n * Indicates whether the participant is currently typing.\n */\n public get isTyping(): boolean {\n return this.state.isTyping;\n }\n\n /**\n * The index of the last read message by the participant.\n * Note that retrieving messages on a client endpoint does not mean that messages are read,\n * please consider reading about the [Read Horizon feature](https://www.twilio.com/docs/api/chat/guides/consumption-horizon)\n * to find out about the proper way to mark messages as read.\n */\n public get lastReadMessageIndex(): number | null {\n return this.state.lastReadMessageIndex;\n }\n\n /**\n * Date of the most recent read horizon update.\n */\n public get lastReadTimestamp(): Date | null {\n return this.state.lastReadTimestamp;\n }\n\n public get roleSid(): string {\n return this.state.roleSid;\n }\n\n /**\n * Type of the participant.\n */\n public get type(): ParticipantType {\n return this.state.type;\n }\n\n /**\n * Get the bindings mapping for the current participant.\n * Available binding depends on the participant type.\n * You could access it as `participant.bindings.sms?.address` or\n * using the type dynamically `participant.bindings[participant.type]`\n * just be aware that the binding information has different structure for\n * each participant type.\n * See also {ParticipantEmailBinding}, the only available currently binding descriptor.\n */\n public get bindings(): ParticipantBindings {\n return this.state.bindings ?? {};\n }\n\n /**\n * @internal\n */\n constructor(\n data: ParticipantDescriptor,\n sid: string,\n conversation: Conversation,\n links: ParticipantLinks,\n services: ParticipantServices\n ) {\n super();\n\n this.conversation = conversation;\n this.links = links;\n this.services = services;\n this.state = {\n attributes: parseAttributes(\n data.attributes,\n \"Retrieved malformed attributes from the server for participant: \" +\n sid,\n log\n ),\n dateCreated: data.dateCreated ? parseTime(data.dateCreated) : null,\n dateUpdated: data.dateCreated ? parseTime(data.dateUpdated) : null,\n sid: sid,\n typingTimeout: null,\n isTyping: false,\n identity: data.identity,\n roleSid: data.roleSid ?? \"\",\n lastReadMessageIndex: Number.isInteger(data.lastConsumedMessageIndex)\n ? data.lastConsumedMessageIndex\n : null,\n lastReadTimestamp: data.lastConsumptionTimestamp\n ? parseTime(data.lastConsumptionTimestamp)\n : null,\n type: data.type || \"chat\",\n userInfo: data.userInfo,\n bindings: data.bindings ?? {},\n };\n\n if (!data.identity && !data.type) {\n throw new Error(\n \"Received invalid Participant object from server: Missing identity or type of Participant.\"\n );\n }\n }\n\n /**\n * Fired when the participant has started typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant in question\n * @event\n */\n static readonly typingStarted = \"typingStarted\";\n\n /**\n * Fired when the participant has stopped typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant in question\n * @event\n */\n static readonly typingEnded = \"typingEnded\";\n\n /**\n * Fired when the fields of the participant have been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * {@link Participant} participant - the participant in question\n * * {@link ParticipantUpdateReason}[] updateReasons - array of reasons for the update\n * @event\n */\n static readonly updated = \"updated\";\n\n /**\n * Internal method used to start or reset the typing indicator timeout (with event emitting).\n * @internal\n */\n _startTyping(timeout) {\n if (this.state.typingTimeout) {\n clearTimeout(this.state.typingTimeout);\n }\n\n this.state.isTyping = true;\n this.emit(\"typingStarted\", this);\n\n this.conversation.emit(\"typingStarted\", this);\n\n this.state.typingTimeout = Number(\n setTimeout(() => this._endTyping(), timeout)\n );\n return this;\n }\n\n /**\n * Internal method function used to stop the typing indicator timeout (with event emitting).\n * @internal\n */\n _endTyping() {\n if (!this.state.typingTimeout) {\n return;\n }\n\n this.state.isTyping = false;\n this.emit(\"typingEnded\", this);\n\n this.conversation.emit(\"typingEnded\", this);\n\n clearInterval(this.state.typingTimeout);\n this.state.typingTimeout = null;\n }\n\n /**\n * Internal method function used update local object's property roleSid with a new value.\n * @internal\n */\n _update(data) {\n const updateReasons: ParticipantUpdateReason[] = [];\n\n const updateAttributes = parseAttributes(\n data.attributes,\n \"Retrieved malformed attributes from the server for participant: \" +\n this.state.sid,\n log\n );\n\n if (data.attributes && !isEqual(this.state.attributes, updateAttributes)) {\n this.state.attributes = updateAttributes;\n updateReasons.push(\"attributes\");\n }\n\n const updatedDateUpdated = parseTime(data.dateUpdated);\n if (\n data.dateUpdated &&\n updatedDateUpdated?.getTime() !==\n (this.state.dateUpdated && this.state.dateUpdated.getTime())\n ) {\n this.state.dateUpdated = updatedDateUpdated;\n updateReasons.push(\"dateUpdated\");\n }\n\n const updatedDateCreated = parseTime(data.dateCreated);\n if (\n data.dateCreated &&\n updatedDateCreated?.getTime() !==\n (this.state.dateCreated && this.state.dateCreated.getTime())\n ) {\n this.state.dateCreated = updatedDateCreated;\n updateReasons.push(\"dateCreated\");\n }\n\n if (data.roleSid && this.state.roleSid !== data.roleSid) {\n this.state.roleSid = data.roleSid;\n updateReasons.push(\"roleSid\");\n }\n\n if (\n (Number.isInteger(data.lastConsumedMessageIndex) ||\n data.lastConsumedMessageIndex === null) &&\n this.state.lastReadMessageIndex !== data.lastConsumedMessageIndex\n ) {\n this.state.lastReadMessageIndex = data.lastConsumedMessageIndex;\n updateReasons.push(\"lastReadMessageIndex\");\n }\n\n if (data.lastConsumptionTimestamp) {\n const lastReadTimestamp = new Date(data.lastConsumptionTimestamp);\n if (\n !this.state.lastReadTimestamp ||\n this.state.lastReadTimestamp.getTime() !== lastReadTimestamp.getTime()\n ) {\n this.state.lastReadTimestamp = lastReadTimestamp;\n updateReasons.push(\"lastReadTimestamp\");\n }\n }\n\n if (data.bindings && !isEqual(this.state.bindings, data.bindings)) {\n this.state.bindings = data.bindings;\n updateReasons.push(\"bindings\");\n }\n\n if (updateReasons.length > 0) {\n this.emit(\"updated\", { participant: this, updateReasons: updateReasons });\n }\n\n return this;\n }\n\n /**\n * Get the user for this participant and subscribes to it. Supported only for participants of type `chat`.\n */\n async getUser(): Promise<User> {\n if (this.type != \"chat\") {\n throw new Error(\n \"Getting User is not supported for this Participant type: \" + this.type\n );\n }\n\n return this.services.users.getUser(\n this.state.identity,\n this.state.userInfo\n );\n }\n\n /**\n * Remove the participant from the conversation.\n */\n async remove() {\n return this.conversation.removeParticipant(this);\n }\n\n /**\n * Update the attributes of the participant.\n * @param attributes New attributes.\n */\n @validateTypesAsync(attributesValidator)\n async updateAttributes(attributes: JSONValue): Promise<Participant> {\n await this.services.commandExecutor.mutateResource<\n EditParticipantRequest,\n ParticipantResponse\n >(\"post\", this.links.self, {\n attributes: JSON.stringify(attributes),\n });\n\n return this;\n }\n}\n\nexport {\n ParticipantDescriptor,\n ParticipantServices,\n Participant,\n ParticipantUpdateReason,\n ParticipantType,\n ParticipantUpdatedEventArgs,\n ParticipantBindings,\n ParticipantEmailBinding,\n ParticipantEmailLevel,\n};\n"],"names":["Logger","ReplayEventEmitter","parseAttributes","parseTime","isEqual","__decorate","validateTypesAsync","attributesValidator"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAM,GAAG,GAAGA,aAAM,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;AAqFxC;;AAEG;AACH,MAAM,WAAY,SAAQC,qCAAqC,CAAA;AA6F7D;;AAEG;IACH,WACE,CAAA,IAA2B,EAC3B,GAAW,EACX,YAA0B,EAC1B,KAAuB,EACvB,QAA6B,EAAA;;AAE7B,QAAA,KAAK,EAAE,CAAC;AAER,QAAA,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;AACjC,QAAA,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;AACnB,QAAA,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG;AACX,YAAA,UAAU,EAAEC,qBAAe,CACzB,IAAI,CAAC,UAAU,EACf,kEAAkE;gBAChE,GAAG,EACL,GAAG,CACJ;AACD,YAAA,WAAW,EAAE,IAAI,CAAC,WAAW,GAAGC,eAAS,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,IAAI;AAClE,YAAA,WAAW,EAAE,IAAI,CAAC,WAA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AAM,MAAM,GAAA;QACV,OAAO,IAAI,CAAC,YAAY,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;KAClD;AAED;;;AAGG;IAEH,MAAM,gBAAgB,CAAC,UAAqB,EAAA;AAC1C,QAAA,MAAM,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,cAAc,CAGhD,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE;AACzB,YAAA,UAAU,EAAE,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC;AACvC,SAAA,CAAC,CAAC;AAEH,QAAA,OAAO,IAAI,CAAC;KACb;;AApLD;;;;;;AAMG;AACa,WAAa,CAAA,aAAA,GAAG,eAAe,CAAC;AAEhD;;;;;;AAMG;AACa,WAAW,CAAA,WAAA,GAAG,aAAa,CAAC;AAE5C;;;;;;;;AAQG;AACa,WAAO,CAAA,OAAA,GAAG,SAAS,CAAC;AAgJpCC,oBAAA,CAAA;IADCC,2CAAkB,CAACC,8BAAmB,CAAC;;;;AAUvC,CAAA,EAAA,WAAA,CAAA,SAAA,EAAA,kBAAA,EAAA,IAAA,CAAA;;;;"}
1
+ {"version":3,"file":"participant.js","sources":["../src/participant.ts"],"sourcesContent":["import { Users } from \"./data/users\";\nimport { User } from \"./user\";\nimport { parseTime, parseAttributes } from \"./util\";\nimport { Logger } from \"./logger\";\nimport { Conversation } from \"./conversation\";\nimport { json } from \"./interfaces/rules\";\nimport { validateTypesAsync } from \"@twilio/declarative-type-validator\";\nimport { CommandExecutor } from \"./command-executor\";\nimport { EditParticipantRequest } from \"./interfaces/commands/edit-participant\";\nimport { ParticipantResponse } from \"./interfaces/commands/participant-response\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport isEqual from \"lodash.isequal\";\nimport { JSONValue } from \"@twilio/shared\";\n\ntype ParticipantEvents = {\n typingEnded: (participant: Participant) => void;\n typingStarted: (participant: Participant) => void;\n updated: (data: {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n }) => void;\n};\n\nconst log = Logger.scope(\"Participant\");\n\ninterface ParticipantDescriptor {\n attributes?: JSONValue;\n dateCreated: Date | null;\n dateUpdated: Date | null;\n identity: string;\n roleSid?: string;\n lastConsumedMessageIndex: number | null;\n lastConsumptionTimestamp: number | null;\n type: ParticipantType;\n userInfo?: string;\n bindings?: ParticipantBindings;\n}\n\ninterface ParticipantState {\n attributes: JSONValue;\n dateCreated: Date | null;\n dateUpdated: Date | null;\n identity: string;\n isTyping: boolean;\n lastReadMessageIndex: number | null;\n lastReadTimestamp: Date | null;\n roleSid: string;\n sid: string;\n type: ParticipantType;\n typingTimeout: number | null;\n userInfo?: string;\n bindings?: ParticipantBindings;\n}\n\ninterface ParticipantServices {\n users: Users;\n commandExecutor: CommandExecutor;\n}\n\ninterface ParticipantLinks {\n self: string;\n}\n\n/**\n * The reason for the `updated` event being emitted by a participant.\n */\ntype ParticipantUpdateReason =\n | \"attributes\"\n | \"dateCreated\"\n | \"dateUpdated\"\n | \"roleSid\"\n | \"lastReadMessageIndex\"\n | \"lastReadTimestamp\"\n | \"bindings\";\n\n/**\n * Participant type. The string variant can be used to denote new types of\n * participant that aren't supported by this version of the SDK.\n */\ntype ParticipantType = \"chat\" | \"sms\" | \"whatsapp\" | \"email\" | string;\n\ninterface ParticipantUpdatedEventArgs {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n}\n\n/**\n * Bindings for conversation participant.\n */\ninterface ParticipantBindings {\n email?: ParticipantEmailBinding;\n}\n\n/**\n * Email participation level.\n * to = to/from\n * cc = cc\n */\ntype ParticipantEmailLevel = \"to\" | \"cc\";\n\n/**\n * Bindings for email participant.\n */\ninterface ParticipantEmailBinding {\n name: string;\n address: string;\n level: ParticipantEmailLevel;\n}\n\n/**\n * A participant represents a remote client in a conversation.\n */\nclass Participant extends ReplayEventEmitter<ParticipantEvents> {\n private state: ParticipantState;\n private readonly links: ParticipantLinks;\n private readonly services: ParticipantServices;\n\n /**\n * Conversation that the remote client is a participant of.\n */\n public readonly conversation: Conversation;\n\n /**\n * The server-assigned unique identifier for the participant.\n */\n public get sid(): string {\n return this.state.sid;\n }\n\n /**\n * Custom attributes of the participant.\n */\n public get attributes(): JSONValue {\n return this.state.attributes;\n }\n\n /**\n * Date this participant was created on.\n */\n public get dateCreated(): Date | null {\n return this.state.dateCreated;\n }\n\n /**\n * Date this participant was last updated on.\n */\n public get dateUpdated(): Date | null {\n return this.state.dateUpdated;\n }\n\n /**\n * Identity of the participant.\n */\n public get identity(): string | null {\n return this.state.identity;\n }\n\n /**\n * Indicates whether the participant is currently typing.\n */\n public get isTyping(): boolean {\n return this.state.isTyping;\n }\n\n /**\n * The index of the last read message by the participant.\n * Note that retrieving messages on a client endpoint does not mean that messages are read,\n * please consider reading about the [Read Horizon feature](https://www.twilio.com/docs/api/chat/guides/consumption-horizon)\n * to find out about the proper way to mark messages as read.\n */\n public get lastReadMessageIndex(): number | null {\n return this.state.lastReadMessageIndex;\n }\n\n /**\n * Date of the most recent read horizon update.\n */\n public get lastReadTimestamp(): Date | null {\n return this.state.lastReadTimestamp;\n }\n\n public get roleSid(): string {\n return this.state.roleSid;\n }\n\n /**\n * Type of the participant.\n */\n public get type(): ParticipantType {\n return this.state.type;\n }\n\n /**\n * Get the bindings mapping for the current participant.\n * Available binding depends on the participant type.\n * You could access it as `participant.bindings.sms?.address` or\n * using the type dynamically `participant.bindings[participant.type]`\n * just be aware that the binding information has different structure for\n * each participant type.\n * See also {@link ParticipantEmailBinding}, the only available currently binding descriptor.\n */\n public get bindings(): ParticipantBindings {\n return this.state.bindings ?? {};\n }\n\n /**\n * @internal\n */\n constructor(\n data: ParticipantDescriptor,\n sid: string,\n conversation: Conversation,\n links: ParticipantLinks,\n services: ParticipantServices\n ) {\n super();\n\n this.conversation = conversation;\n this.links = links;\n this.services = services;\n this.state = {\n attributes: parseAttributes(\n data.attributes,\n \"Retrieved malformed attributes from the server for participant: \" +\n sid,\n log\n ),\n dateCreated: data.dateCreated ? parseTime(data.dateCreated) : null,\n dateUpdated: data.dateCreated ? parseTime(data.dateUpdated) : null,\n sid: sid,\n typingTimeout: null,\n isTyping: false,\n identity: data.identity,\n roleSid: data.roleSid ?? \"\",\n lastReadMessageIndex: Number.isInteger(data.lastConsumedMessageIndex)\n ? data.lastConsumedMessageIndex\n : null,\n lastReadTimestamp: data.lastConsumptionTimestamp\n ? parseTime(data.lastConsumptionTimestamp)\n : null,\n type: data.type || \"chat\",\n userInfo: data.userInfo,\n bindings: data.bindings ?? {},\n };\n\n if (!data.identity && !data.type) {\n throw new Error(\n \"Received invalid Participant object from server: Missing identity or type of Participant.\"\n );\n }\n }\n\n /**\n * Fired when the participant has started typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant in question\n * @event\n */\n static readonly typingStarted = \"typingStarted\";\n\n /**\n * Fired when the participant has stopped typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant in question\n * @event\n */\n static readonly typingEnded = \"typingEnded\";\n\n /**\n * Fired when the fields of the participant have been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the following properties:\n * * {@link Participant} participant - the participant in question\n * * {@link ParticipantUpdateReason}[] updateReasons - array of reasons for the update\n * @event\n */\n static readonly updated = \"updated\";\n\n /**\n * Internal method used to start or reset the typing indicator timeout (with event emitting).\n * @internal\n */\n _startTyping(timeout) {\n if (this.state.typingTimeout) {\n clearTimeout(this.state.typingTimeout);\n }\n\n this.state.isTyping = true;\n this.emit(\"typingStarted\", this);\n\n this.conversation.emit(\"typingStarted\", this);\n\n this.state.typingTimeout = Number(\n setTimeout(() => this._endTyping(), timeout)\n );\n return this;\n }\n\n /**\n * Internal method function used to stop the typing indicator timeout (with event emitting).\n * @internal\n */\n _endTyping() {\n if (!this.state.typingTimeout) {\n return;\n }\n\n this.state.isTyping = false;\n this.emit(\"typingEnded\", this);\n\n this.conversation.emit(\"typingEnded\", this);\n\n clearInterval(this.state.typingTimeout);\n this.state.typingTimeout = null;\n }\n\n /**\n * Internal method function used update local object's property roleSid with a new value.\n * @internal\n */\n _update(data) {\n const updateReasons: ParticipantUpdateReason[] = [];\n\n const updateAttributes = parseAttributes(\n data.attributes,\n \"Retrieved malformed attributes from the server for participant: \" +\n this.state.sid,\n log\n );\n\n if (data.attributes && !isEqual(this.state.attributes, updateAttributes)) {\n this.state.attributes = updateAttributes;\n updateReasons.push(\"attributes\");\n }\n\n const updatedDateUpdated = parseTime(data.dateUpdated);\n if (\n data.dateUpdated &&\n updatedDateUpdated?.getTime() !==\n (this.state.dateUpdated && this.state.dateUpdated.getTime())\n ) {\n this.state.dateUpdated = updatedDateUpdated;\n updateReasons.push(\"dateUpdated\");\n }\n\n const updatedDateCreated = parseTime(data.dateCreated);\n if (\n data.dateCreated &&\n updatedDateCreated?.getTime() !==\n (this.state.dateCreated && this.state.dateCreated.getTime())\n ) {\n this.state.dateCreated = updatedDateCreated;\n updateReasons.push(\"dateCreated\");\n }\n\n if (data.roleSid && this.state.roleSid !== data.roleSid) {\n this.state.roleSid = data.roleSid;\n updateReasons.push(\"roleSid\");\n }\n\n if (\n (Number.isInteger(data.lastConsumedMessageIndex) ||\n data.lastConsumedMessageIndex === null) &&\n this.state.lastReadMessageIndex !== data.lastConsumedMessageIndex\n ) {\n this.state.lastReadMessageIndex = data.lastConsumedMessageIndex;\n updateReasons.push(\"lastReadMessageIndex\");\n }\n\n if (data.lastConsumptionTimestamp) {\n const lastReadTimestamp = new Date(data.lastConsumptionTimestamp);\n if (\n !this.state.lastReadTimestamp ||\n this.state.lastReadTimestamp.getTime() !== lastReadTimestamp.getTime()\n ) {\n this.state.lastReadTimestamp = lastReadTimestamp;\n updateReasons.push(\"lastReadTimestamp\");\n }\n }\n\n if (data.bindings && !isEqual(this.state.bindings, data.bindings)) {\n this.state.bindings = data.bindings;\n updateReasons.push(\"bindings\");\n }\n\n if (updateReasons.length > 0) {\n this.emit(\"updated\", { participant: this, updateReasons: updateReasons });\n }\n\n return this;\n }\n\n /**\n * Get the user for this participant and subscribes to it. Supported only for participants of type `chat`.\n */\n async getUser(): Promise<User> {\n if (this.type != \"chat\") {\n throw new Error(\n \"Getting User is not supported for this Participant type: \" + this.type\n );\n }\n\n return this.services.users.getUser(\n this.state.identity,\n this.state.userInfo\n );\n }\n\n /**\n * Remove the participant from the conversation.\n */\n async remove() {\n return this.conversation.removeParticipant(this);\n }\n\n /**\n * Update the attributes of the participant.\n * @param attributes New attributes.\n */\n @validateTypesAsync(json)\n async updateAttributes(attributes: JSONValue): Promise<Participant> {\n await this.services.commandExecutor.mutateResource<\n EditParticipantRequest,\n ParticipantResponse\n >(\"post\", this.links.self, {\n attributes: JSON.stringify(attributes),\n });\n\n return this;\n }\n}\n\nexport {\n ParticipantDescriptor,\n ParticipantServices,\n Participant,\n ParticipantUpdateReason,\n ParticipantType,\n ParticipantUpdatedEventArgs,\n ParticipantBindings,\n ParticipantEmailBinding,\n ParticipantEmailLevel,\n};\n"],"names":["Logger","ReplayEventEmitter","parseAttributes","parseTime","isEqual","__decorate","validateTypesAsync","json"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAM,GAAG,GAAGA,aAAM,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;AAsFxC;;AAEG;AACH,MAAM,WAAY,SAAQC,qCAAqC,CAAA;AAU7D;;AAEG;AACH,IAAA,IAAW,GAAG,GAAA;AACZ,QAAA,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC;KACvB;AAED;;AAEG;AACH,IAAA,IAAW,UAAU,GAAA;AACnB,QAAA,OAAO,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC;KAC9B;AAED;;AAEG;AACH,IAAA,IAAW,WAAW,GAAA;AACpB,QAAA,OAAO,IAAI,CAAC,KAAK,CA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ACvB,MAAM,IAAI,KAAK,CACb,2DAA2D,GAAG,IAAI,CAAC,IAAI,CACxE,CAAC;AACH,SAAA;QAED,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,OAAO,CAChC,IAAI,CAAC,KAAK,CAAC,QAAQ,EACnB,IAAI,CAAC,KAAK,CAAC,QAAQ,CACpB,CAAC;KACH;AAED;;AAEG;AACH,IAAA,MAAM,MAAM,GAAA;QACV,OAAO,IAAI,CAAC,YAAY,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;KAClD;AAED;;;AAGG;AAEG,IAAN,MAAM,gBAAgB,CAAC,UAAqB,EAAA;AAC1C,QAAA,MAAM,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,cAAc,CAGhD,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE;AACzB,YAAA,UAAU,EAAE,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC;AACvC,SAAA,CAAC,CAAC;AAEH,QAAA,OAAO,IAAI,CAAC;KACb;;AApLD;;;;;;AAMG;AACa,WAAa,CAAA,aAAA,GAAG,eAAe,CAAC;AAEhD;;;;;;AAMG;AACa,WAAW,CAAA,WAAA,GAAG,aAAa,CAAC;AAE5C;;;;;;;;AAQG;AACa,WAAO,CAAA,OAAA,GAAG,SAAS,CAAC;AAgJ9BC,oBAAA,CAAA;IADLC,2CAAkB,CAACC,UAAI,CAAC;;;;AAUxB,CAAA,EAAA,WAAA,CAAA,SAAA,EAAA,kBAAA,EAAA,IAAA,CAAA;;;;"}
@@ -128,6 +128,15 @@ This software includes platform.js under the following license.
128
128
  */
129
129
  'use strict';
130
130
 
131
+ var global =
132
+ typeof global !== "undefined"
133
+ ? global
134
+ : typeof self !== "undefined"
135
+ ? self
136
+ : typeof window !== "undefined"
137
+ ? window
138
+ : {};
139
+
131
140
  Object.defineProperty(exports, '__esModule', { value: true });
132
141
 
133
142
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"push-notification.js","sources":["../src/push-notification.ts"],"sourcesContent":["/**\n * Push notification type.\n */\nimport { Media } from \"./media\";\n\ntype PushNotificationType =\n | \"twilio.conversations.new_message\"\n | \"twilio.conversations.added_to_conversation\"\n | \"twilio.conversations.removed_from_conversation\";\n\ninterface PushNotificationDescriptor {\n title: string | null;\n body: string | null;\n sound: string | null;\n badge: number | null;\n action: string | null;\n type: PushNotificationType;\n data: Record<string, unknown>;\n}\n\n/**\n * Additional data for a given push notification.\n */\ninterface PushNotificationData {\n /**\n * SID of the conversation.\n */\n conversationSid?: string;\n\n /**\n * Title of the conversation.\n */\n conversationTitle?: string;\n\n /**\n * Index of the message in the conversation.\n */\n messageIndex?: number;\n\n /**\n * SID of the message in the conversation.\n */\n messageSid?: string;\n\n /**\n * Media of the notification\n */\n media?: Media;\n\n /**\n * Count of the attached media of the message.\n */\n mediaCount?: number;\n}\n\n/**\n * Push notification for a Conversations client.\n */\nclass PushNotification {\n /**\n * Title of the notification.\n */\n public readonly title: string | null;\n\n /**\n * Text of the notification.\n */\n public readonly body: string | null;\n\n /**\n * Sound of the notification.\n */\n public readonly sound: string | null;\n\n /**\n * Number of the badge.\n */\n public readonly badge: number | null;\n\n /**\n * Notification action (`click_action` in FCM terms and `category` in APN terms).\n */\n public readonly action: string | null;\n\n /**\n * Type of the notification.\n */\n public readonly type: PushNotificationType;\n\n /**\n * Additional data of the conversation.\n */\n public readonly data: PushNotificationData;\n\n /**\n * @internal\n */\n constructor(data: PushNotificationDescriptor) {\n this.title = data.title || null;\n this.body = data.body || null;\n this.sound = data.sound || null;\n this.badge = data.badge || null;\n this.action = data.action || null;\n this.type = data.type || null;\n this.data = data.data || {};\n }\n}\n\nexport {\n PushNotification,\n PushNotificationType,\n PushNotificationDescriptor,\n PushNotificationData,\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA;;AAEG;AACH,MAAM,gBAAgB,CAAA;AAoCpB;;AAEG;AACH,IAAA,WAAA,CAAY,IAAgC,EAAA;QAC1C,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC;QAChC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC;QAC9B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC;QAChC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC;QAChC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC;QAClC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC;QAC9B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC;KAC7B;AACF;;;;"}
1
+ {"version":3,"file":"push-notification.js","sources":["../src/push-notification.ts"],"sourcesContent":["/**\n * Push notification type.\n */\nimport { Media } from \"./media\";\n\n/**\n * Type of a push notification.\n */\ntype PushNotificationType =\n | \"twilio.conversations.new_message\"\n | \"twilio.conversations.added_to_conversation\"\n | \"twilio.conversations.removed_from_conversation\";\n\ninterface PushNotificationDescriptor {\n title: string | null;\n body: string | null;\n sound: string | null;\n badge: number | null;\n action: string | null;\n type: PushNotificationType;\n data: Record<string, unknown>;\n}\n\n/**\n * Additional data for a given push notification.\n */\ninterface PushNotificationData {\n /**\n * SID of the conversation.\n */\n conversationSid?: string;\n\n /**\n * Title of the conversation.\n */\n conversationTitle?: string;\n\n /**\n * Index of the message in the conversation.\n */\n messageIndex?: number;\n\n /**\n * SID of the message in the conversation.\n */\n messageSid?: string;\n\n /**\n * Media of the notification\n */\n media?: Media;\n\n /**\n * Count of the attached media of the message.\n */\n mediaCount?: number;\n}\n\n/**\n * Push notification for a Conversations client.\n */\nclass PushNotification {\n /**\n * Title of the notification.\n */\n public readonly title: string | null;\n\n /**\n * Text of the notification.\n */\n public readonly body: string | null;\n\n /**\n * Sound of the notification.\n */\n public readonly sound: string | null;\n\n /**\n * Number of the badge.\n */\n public readonly badge: number | null;\n\n /**\n * Notification action (`click_action` in FCM terms and `category` in APN terms).\n */\n public readonly action: string | null;\n\n /**\n * Type of the notification.\n */\n public readonly type: PushNotificationType;\n\n /**\n * Additional data of the conversation.\n */\n public readonly data: PushNotificationData;\n\n /**\n * @internal\n */\n constructor(data: PushNotificationDescriptor) {\n this.title = data.title || null;\n this.body = data.body || null;\n this.sound = data.sound || null;\n this.badge = data.badge || null;\n this.action = data.action || null;\n this.type = data.type || null;\n this.data = data.data || {};\n }\n}\n\nexport {\n PushNotification,\n PushNotificationType,\n PushNotificationDescriptor,\n PushNotificationData,\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA;;AAEG;AACH,MAAM,gBAAgB,CAAA;AAoCpB;;AAEG;AACH,IAAA,WAAA,CAAY,IAAgC,EAAA;QAC1C,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC;QAChC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC;QAC9B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC;QAChC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC;QAChC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC;QAClC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC;QAC9B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC;KAC7B;AACF;;;;"}
@@ -128,23 +128,21 @@ This software includes platform.js under the following license.
128
128
  */
129
129
  'use strict';
130
130
 
131
+ var global =
132
+ typeof global !== "undefined"
133
+ ? global
134
+ : typeof self !== "undefined"
135
+ ? self
136
+ : typeof window !== "undefined"
137
+ ? window
138
+ : {};
139
+
131
140
  Object.defineProperty(exports, '__esModule', { value: true });
132
141
 
133
142
  /**
134
143
  * Pagination helper class.
135
144
  */
136
145
  class RestPaginator {
137
- /**
138
- * @internal
139
- */
140
- constructor(items, source, prevToken, nextToken) {
141
- this.state = {
142
- prevToken,
143
- nextToken,
144
- source,
145
- items,
146
- };
147
- }
148
146
  /**
149
147
  * Indicates the existence of the next page.
150
148
  */
@@ -163,6 +161,17 @@ class RestPaginator {
163
161
  get items() {
164
162
  return this.state.items;
165
163
  }
164
+ /**
165
+ * @internal
166
+ */
167
+ constructor(items, source, prevToken, nextToken) {
168
+ this.state = {
169
+ prevToken,
170
+ nextToken,
171
+ source,
172
+ items,
173
+ };
174
+ }
166
175
  /**
167
176
  * Request the next page. Does not modify the existing object.
168
177
  */
@@ -1 +1 @@
1
- {"version":3,"file":"rest-paginator.js","sources":["../src/rest-paginator.ts"],"sourcesContent":["import { Paginator } from \"./interfaces/paginator\";\n\ninterface PaginatorState<T> {\n source: (token: string) => Promise<RestPaginator<T>>;\n nextToken: string;\n prevToken: string;\n items: T[];\n}\n\n/**\n * Pagination helper class.\n */\nclass RestPaginator<T> implements Paginator<T> {\n private state: PaginatorState<T>;\n\n /**\n * Indicates the existence of the next page.\n */\n public get hasNextPage(): boolean {\n return !!this.state.nextToken;\n }\n\n /**\n * Indicates the existence of the previous page\n */\n public get hasPrevPage(): boolean {\n return !!this.state.prevToken;\n }\n\n /**\n * Array of elements on the current page.\n */\n public get items(): T[] {\n return this.state.items;\n }\n\n /**\n * @internal\n */\n constructor(items, source, prevToken, nextToken) {\n this.state = {\n prevToken,\n nextToken,\n source,\n items,\n };\n }\n\n /**\n * Request the next page. Does not modify the existing object.\n */\n nextPage(): Promise<RestPaginator<T>> {\n return this.hasNextPage\n ? this.state.source(this.state.nextToken)\n : Promise.reject(new Error(\"No next page\"));\n }\n\n /**\n * Request the previous page. Does not modify the existing object.\n */\n prevPage(): Promise<RestPaginator<T>> {\n return this.hasPrevPage\n ? this.state.source(this.state.prevToken)\n : Promise.reject(new Error(\"No previous page\"));\n }\n}\n\nexport { RestPaginator };\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA;;AAEG;AACH,MAAM,aAAa,CAAA;AAwBjB;;AAEG;AACH,IAAA,WAAA,CAAY,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAA;QAC7C,IAAI,CAAC,KAAK,GAAG;YACX,SAAS;YACT,SAAS;YACT,MAAM;YACN,KAAK;SACN,CAAC;KACH;AA/BD;;AAEG;AACH,IAAA,IAAW,WAAW,GAAA;AACpB,QAAA,OAAO,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC;KAC/B;AAED;;AAEG;AACH,IAAA,IAAW,WAAW,GAAA;AACpB,QAAA,OAAO,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC;KAC/B;AAED;;AAEG;AACH,IAAA,IAAW,KAAK,GAAA;AACd,QAAA,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC;KACzB;AAcD;;AAEG;IACH,QAAQ,GAAA;QACN,OAAO,IAAI,CAAC,WAAW;AACrB,cAAE,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC;cACvC,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,cAAc,CAAC,CAAC,CAAC;KAC/C;AAED;;AAEG;IACH,QAAQ,GAAA;QACN,OAAO,IAAI,CAAC,WAAW;AACrB,cAAE,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC;cACvC,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC,CAAC;KACnD;AACF;;;;"}
1
+ {"version":3,"file":"rest-paginator.js","sources":["../src/rest-paginator.ts"],"sourcesContent":["import { Paginator } from \"./interfaces/paginator\";\n\ninterface PaginatorState<T> {\n source: (token: string) => Promise<RestPaginator<T>>;\n nextToken: string;\n prevToken: string;\n items: T[];\n}\n\n/**\n * Pagination helper class.\n */\nclass RestPaginator<T> implements Paginator<T> {\n private state: PaginatorState<T>;\n\n /**\n * Indicates the existence of the next page.\n */\n public get hasNextPage(): boolean {\n return !!this.state.nextToken;\n }\n\n /**\n * Indicates the existence of the previous page\n */\n public get hasPrevPage(): boolean {\n return !!this.state.prevToken;\n }\n\n /**\n * Array of elements on the current page.\n */\n public get items(): T[] {\n return this.state.items;\n }\n\n /**\n * @internal\n */\n constructor(items, source, prevToken, nextToken) {\n this.state = {\n prevToken,\n nextToken,\n source,\n items,\n };\n }\n\n /**\n * Request the next page. Does not modify the existing object.\n */\n nextPage(): Promise<RestPaginator<T>> {\n return this.hasNextPage\n ? this.state.source(this.state.nextToken)\n : Promise.reject(new Error(\"No next page\"));\n }\n\n /**\n * Request the previous page. Does not modify the existing object.\n */\n prevPage(): Promise<RestPaginator<T>> {\n return this.hasPrevPage\n ? this.state.source(this.state.prevToken)\n : Promise.reject(new Error(\"No previous page\"));\n }\n}\n\nexport { RestPaginator };\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA;;AAEG;AACH,MAAM,aAAa,CAAA;AAGjB;;AAEG;AACH,IAAA,IAAW,WAAW,GAAA;AACpB,QAAA,OAAO,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC;KAC/B;AAED;;AAEG;AACH,IAAA,IAAW,WAAW,GAAA;AACpB,QAAA,OAAO,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC;KAC/B;AAED;;AAEG;AACH,IAAA,IAAW,KAAK,GAAA;AACd,QAAA,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC;KACzB;AAED;;AAEG;AACH,IAAA,WAAA,CAAY,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAA;QAC7C,IAAI,CAAC,KAAK,GAAG;YACX,SAAS;YACT,SAAS;YACT,MAAM;YACN,KAAK;SACN,CAAC;KACH;AAED;;AAEG;IACH,QAAQ,GAAA;QACN,OAAO,IAAI,CAAC,WAAW;AACrB,cAAE,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC;cACvC,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,cAAc,CAAC,CAAC,CAAC;KAC/C;AAED;;AAEG;IACH,QAAQ,GAAA;QACN,OAAO,IAAI,CAAC,WAAW;AACrB,cAAE,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC;cACvC,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC,CAAC;KACnD;AACF;;;;"}
@@ -128,16 +128,62 @@ This software includes platform.js under the following license.
128
128
  */
129
129
  'use strict';
130
130
 
131
+ var global =
132
+ typeof global !== "undefined"
133
+ ? global
134
+ : typeof self !== "undefined"
135
+ ? self
136
+ : typeof window !== "undefined"
137
+ ? window
138
+ : {};
139
+
131
140
  Object.defineProperty(exports, '__esModule', { value: true });
132
141
 
133
142
  var operationRetrier = require('@twilio/operation-retrier');
143
+ var twilsock = require('twilsock');
144
+ var shared = require('@twilio/shared');
134
145
 
146
+ function messageFromErrorBody(transportError, payload) {
147
+ if ((payload === null || payload === void 0 ? void 0 : payload.message) && typeof payload.message === "string") {
148
+ return payload.message;
149
+ }
150
+ switch (transportError.statusCode) {
151
+ case 429:
152
+ return "Throttled by server";
153
+ case 404:
154
+ return "Not found from server";
155
+ default:
156
+ return "Error from server";
157
+ }
158
+ }
159
+ function codeFromErrorBody(payload) {
160
+ var _a;
161
+ return (_a = payload === null || payload === void 0 ? void 0 : payload.code) !== null && _a !== void 0 ? _a : 0;
162
+ }
163
+ function mapTransportError(transportError, payload) {
164
+ var _a, _b;
165
+ if (transportError.statusCode === 409) {
166
+ return new Error(`${messageFromErrorBody(transportError, payload)} ${transportError.statusCode}:${codeFromErrorBody(payload)} ${payload}`);
167
+ }
168
+ else if (transportError.statusCode) {
169
+ return new Error(`${messageFromErrorBody(transportError, payload)} ${transportError.statusCode}:${codeFromErrorBody(payload)}`);
170
+ }
171
+ else if (transportError instanceof shared.TwilioError &&
172
+ transportError.errorInfo.reason === "transportDisconnected") {
173
+ return transportError;
174
+ }
175
+ else {
176
+ return new Error((_b = (_a = payload === null || payload === void 0 ? void 0 : payload.message) !== null && _a !== void 0 ? _a : transportError.message) !== null && _b !== void 0 ? _b : "Unexpected error");
177
+ }
178
+ }
135
179
  class Network {
136
180
  constructor(configuration, services) {
181
+ this.isShutdownInitiated = false;
137
182
  this.configuration = configuration;
138
183
  this.services = services;
139
184
  this.cache = new Map();
140
185
  this.cacheLifetime = this.configuration.httpCacheInterval * 100;
186
+ this.pendingRequests = new Set();
141
187
  this.cleanupCache();
142
188
  }
143
189
  isExpired(timestamp) {
@@ -158,6 +204,23 @@ class Network {
158
204
  this.timer ||
159
205
  setInterval(() => this.cleanupCache(), this.cacheLifetime * 2);
160
206
  }
207
+ static responsePostProcess(response) {
208
+ let body;
209
+ try {
210
+ body = JSON.parse(response.payload);
211
+ }
212
+ catch (_a) {
213
+ body = response.payload;
214
+ }
215
+ return {
216
+ status: {
217
+ code: response.statusCode,
218
+ status: response.status,
219
+ },
220
+ headers: response.headers,
221
+ body,
222
+ };
223
+ }
161
224
  executeWithRetry(request, retryWhenThrottled = false) {
162
225
  return new Promise((resolve, reject) => {
163
226
  const codesToRetryOn = [502, 503, 504];
@@ -167,21 +230,37 @@ class Network {
167
230
  const retrier = new operationRetrier.Retrier(this.configuration.backoffConfiguration);
168
231
  retrier.on("attempt", () => {
169
232
  request()
170
- .then((result) => retrier.succeeded(result))
171
- .catch((err) => {
172
- if (codesToRetryOn.indexOf(err.status) > -1) {
173
- retrier.failed(err);
233
+ .then((result) => {
234
+ const isError = result.statusCode >= 400;
235
+ if (!isError) {
236
+ retrier.succeeded(result);
237
+ return;
238
+ }
239
+ let parsedPayload = {};
240
+ try {
241
+ parsedPayload = JSON.parse(result.payload);
242
+ }
243
+ catch (_a) { }
244
+ if (codesToRetryOn.includes(result.statusCode)) {
245
+ const delayOverride = parseInt(result.headers ? result.headers["Retry-After"] : null);
246
+ retrier.failed(mapTransportError(result, parsedPayload), isNaN(delayOverride) ? undefined : delayOverride * 1000);
174
247
  }
175
- else if (err.message === "Twilsock disconnected") {
248
+ else if (parsedPayload.message === "Twilsock disconnected") {
176
249
  // Ugly hack. We must make a proper exceptions for twilsock
177
- retrier.failed(err);
250
+ retrier.failed(mapTransportError(result, parsedPayload));
178
251
  }
179
252
  else {
180
253
  // Fatal error
181
254
  retrier.removeAllListeners();
182
255
  retrier.cancel();
183
- reject(err);
256
+ reject(mapTransportError(result, parsedPayload));
184
257
  }
258
+ })
259
+ .catch((err) => {
260
+ // Fatal error
261
+ retrier.removeAllListeners();
262
+ retrier.cancel();
263
+ reject(err);
185
264
  });
186
265
  });
187
266
  retrier.on("succeeded", (result) => {
@@ -193,15 +272,35 @@ class Network {
193
272
  });
194
273
  }
195
274
  async get(url) {
275
+ if (this.isShutdownInitiated) {
276
+ throw new Error("Client has been shut down.");
277
+ }
196
278
  const cacheEntry = this.cache.get(url);
197
279
  if (cacheEntry && !this.isExpired(cacheEntry.timestamp)) {
198
280
  return cacheEntry.response;
199
281
  }
200
- const headers = {};
201
- const response = await this.executeWithRetry(() => this.services.transport.get(url, headers, this.configuration.productId), this.configuration.retryWhenThrottled);
202
- this.cache.set(url, { response, timestamp: Date.now() });
282
+ const responsePromise = this.executeWithRetry(() => this.services.transport.sendRequest(new twilsock.HttpRequest({
283
+ url,
284
+ grant: this.configuration.productId,
285
+ })), this.configuration.retryWhenThrottled);
286
+ this.pendingRequests.add(responsePromise);
287
+ const response = await responsePromise;
288
+ this.pendingRequests.delete(responsePromise);
289
+ const postProcessedResponse = Network.responsePostProcess(response);
290
+ this.cache.set(url, {
291
+ response: postProcessedResponse,
292
+ timestamp: Date.now(),
293
+ });
203
294
  this.pokeTimer();
204
- return response;
295
+ return postProcessedResponse;
296
+ }
297
+ async disconnect() {
298
+ this.isShutdownInitiated = true;
299
+ try {
300
+ await Promise.all([...this.pendingRequests]);
301
+ }
302
+ catch (_a) { }
303
+ await this.services.syncClient.shutdown();
205
304
  }
206
305
  }
207
306
 
@@ -1 +1 @@
1
- {"version":3,"file":"network.js","sources":["../../src/services/network.ts"],"sourcesContent":["import { Retrier } from \"@twilio/operation-retrier\";\nimport { Transport, TransportResult } from \"twilsock\";\nimport { Configuration } from \"../configuration\";\n\nimport Timeout = NodeJS.Timeout;\n\ninterface CacheEntry {\n response: TransportResult<unknown>;\n timestamp: number;\n}\n\nexport interface NetworkServices {\n transport: Transport;\n}\n\nclass Network {\n private readonly configuration: Configuration;\n private readonly services: NetworkServices;\n private cacheLifetime: number;\n\n private readonly cache: Map<string, CacheEntry>;\n private timer!: number | NodeJS.Timeout;\n\n constructor(configuration, services) {\n this.configuration = configuration;\n this.services = services;\n this.cache = new Map<string, CacheEntry>();\n this.cacheLifetime = this.configuration.httpCacheInterval * 100;\n this.cleanupCache();\n }\n\n private isExpired(timestamp: number): boolean {\n return !this.cacheLifetime || Date.now() - timestamp > this.cacheLifetime;\n }\n\n private cleanupCache() {\n for (const [k, v] of this.cache) {\n if (this.isExpired(v.timestamp)) {\n this.cache.delete(k);\n }\n }\n\n if (this.cache.size === 0) {\n clearInterval(this.timer as Timeout);\n }\n }\n\n pokeTimer() {\n this.timer =\n this.timer ||\n setInterval(() => this.cleanupCache(), this.cacheLifetime * 2);\n }\n\n private executeWithRetry<T>(\n request,\n retryWhenThrottled = false\n ): Promise<TransportResult<T>> {\n return new Promise((resolve, reject) => {\n const codesToRetryOn = [502, 503, 504];\n if (retryWhenThrottled) {\n codesToRetryOn.push(429);\n }\n\n const retrier = new Retrier(this.configuration.backoffConfiguration);\n retrier.on(\"attempt\", () => {\n request()\n .then((result) => retrier.succeeded(result))\n .catch((err) => {\n if (codesToRetryOn.indexOf(err.status) > -1) {\n retrier.failed(err);\n } else if (err.message === \"Twilsock disconnected\") {\n // Ugly hack. We must make a proper exceptions for twilsock\n retrier.failed(err);\n } else {\n // Fatal error\n retrier.removeAllListeners();\n retrier.cancel();\n reject(err);\n }\n });\n });\n\n retrier.on(\"succeeded\", (result) => {\n resolve(result);\n });\n retrier.on(\"cancelled\", (err) => reject(err));\n retrier.on(\"failed\", (err) => reject(err));\n\n retrier.start();\n });\n }\n\n async get<T>(url: string): Promise<TransportResult<T>> {\n const cacheEntry = this.cache.get(url);\n if (cacheEntry && !this.isExpired(cacheEntry.timestamp)) {\n return cacheEntry.response as TransportResult<T>;\n }\n\n const headers = {};\n const response = await this.executeWithRetry<T>(\n () =>\n this.services.transport.get<T>(\n url,\n headers,\n this.configuration.productId\n ),\n this.configuration.retryWhenThrottled\n );\n this.cache.set(url, { response, timestamp: Date.now() });\n this.pokeTimer();\n return response;\n }\n}\n\nexport { Network };\n"],"names":["Retrier"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAK,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;YAE3C,OAAO,CAAC,KAAK,EAAE,CAAC;AAClB,SAAC,CAAC,CAAC;KACJ;IAED,MAAM,GAAG,CAAI,GAAW,EAAA;QACtB,MAAM,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACvC,IAAI,UAAU,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE;YACvD,OAAO,UAAU,CAAC,QAA8B,CAAC;AAClD,SAAA;QAED,MAAM,OAAO,GAAG,EAAE,CAAC;AACnB,QAAA,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,gBAAgB,CAC1C,MACE,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,GAAG,CACzB,GAAG,EACH,OAAO,EACP,IAAI,CAAC,aAAa,CAAC,SAAS,CAC7B,EACH,IAAI,CAAC,aAAa,CAAC,kBAAkB,CACtC,CAAC;AACF,QAAA,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;QACzD,IAAI,CAAC,SAAS,EAAE,CAAC;AACjB,QAAA,OAAO,QAAQ,CAAC;KACjB;AACF;;;;"}
1
+ {"version":3,"file":"network.js","sources":["../../src/services/network.ts"],"sourcesContent":["import { Retrier } from \"@twilio/operation-retrier\";\nimport { TwilsockClient, HttpResponse, HttpRequest } from \"twilsock\";\nimport { Configuration } from \"../configuration\";\n\nimport Timeout = NodeJS.Timeout;\nimport { SyncClient } from \"twilio-sync\";\nimport { TwilioError } from \"@twilio/shared\";\n\ninterface PostProcessedResponse {\n status: {\n code: number;\n status: string;\n };\n headers: Record<string, string>;\n body: unknown;\n}\n\ninterface CacheEntry {\n response: PostProcessedResponse;\n timestamp: number;\n}\n\nexport interface NetworkServices {\n transport: TwilsockClient;\n syncClient: SyncClient;\n}\n\nfunction messageFromErrorBody(transportError, payload): string {\n if (payload?.message && typeof payload.message === \"string\") {\n return payload.message;\n }\n switch (transportError.statusCode) {\n case 429:\n return \"Throttled by server\";\n case 404:\n return \"Not found from server\";\n default:\n return \"Error from server\";\n }\n}\n\nfunction codeFromErrorBody(payload): number {\n return payload?.code ?? 0;\n}\n\nfunction mapTransportError(transportError, payload): Error {\n if (transportError.statusCode === 409) {\n return new Error(\n `${messageFromErrorBody(transportError, payload)} ${\n transportError.statusCode\n }:${codeFromErrorBody(payload)} ${payload}`\n );\n } else if (transportError.statusCode) {\n return new Error(\n `${messageFromErrorBody(transportError, payload)} ${\n transportError.statusCode\n }:${codeFromErrorBody(payload)}`\n );\n } else if (\n transportError instanceof TwilioError &&\n transportError.errorInfo.reason === \"transportDisconnected\"\n ) {\n return transportError;\n } else {\n return new Error(\n payload?.message ?? transportError.message ?? \"Unexpected error\"\n );\n }\n}\n\nclass Network {\n private readonly configuration: Configuration;\n private readonly services: NetworkServices;\n private cacheLifetime: number;\n\n private readonly cache: Map<string, CacheEntry>;\n private timer!: number | NodeJS.Timeout;\n private pendingRequests: Set<Promise<HttpResponse<unknown>>>;\n private isShutdownInitiated = false;\n\n constructor(configuration, services) {\n this.configuration = configuration;\n this.services = services;\n this.cache = new Map<string, CacheEntry>();\n this.cacheLifetime = this.configuration.httpCacheInterval * 100;\n this.pendingRequests = new Set();\n this.cleanupCache();\n }\n\n private isExpired(timestamp: number): boolean {\n return !this.cacheLifetime || Date.now() - timestamp > this.cacheLifetime;\n }\n\n private cleanupCache() {\n for (const [k, v] of this.cache) {\n if (this.isExpired(v.timestamp)) {\n this.cache.delete(k);\n }\n }\n\n if (this.cache.size === 0) {\n clearInterval(this.timer as Timeout);\n }\n }\n\n pokeTimer() {\n this.timer =\n this.timer ||\n setInterval(() => this.cleanupCache(), this.cacheLifetime * 2);\n }\n\n private static responsePostProcess(response): PostProcessedResponse {\n let body;\n\n try {\n body = JSON.parse(response.payload);\n } catch {\n body = response.payload;\n }\n\n return {\n status: {\n code: response.statusCode,\n status: response.status,\n },\n headers: response.headers,\n body,\n };\n }\n\n private executeWithRetry<T>(\n request,\n retryWhenThrottled = false\n ): Promise<HttpResponse> {\n return new Promise((resolve, reject) => {\n const codesToRetryOn = [502, 503, 504];\n if (retryWhenThrottled) {\n codesToRetryOn.push(429);\n }\n\n const retrier = new Retrier(this.configuration.backoffConfiguration);\n retrier.on(\"attempt\", () => {\n request()\n .then((result) => {\n const isError = result.statusCode >= 400;\n if (!isError) {\n retrier.succeeded(result);\n return;\n }\n\n let parsedPayload: Record<string, unknown> = {};\n try {\n parsedPayload = JSON.parse(result.payload);\n } catch {}\n if (codesToRetryOn.includes(result.statusCode)) {\n const delayOverride = parseInt(\n result.headers ? result.headers[\"Retry-After\"] : null\n );\n retrier.failed(\n mapTransportError(result, parsedPayload),\n isNaN(delayOverride) ? undefined : delayOverride * 1000\n );\n } else if (parsedPayload.message === \"Twilsock disconnected\") {\n // Ugly hack. We must make a proper exceptions for twilsock\n retrier.failed(mapTransportError(result, parsedPayload));\n } else {\n // Fatal error\n retrier.removeAllListeners();\n retrier.cancel();\n reject(mapTransportError(result, parsedPayload));\n }\n })\n .catch((err) => {\n // Fatal error\n retrier.removeAllListeners();\n retrier.cancel();\n reject(err);\n });\n });\n\n retrier.on(\"succeeded\", (result) => {\n resolve(result);\n });\n retrier.on(\"cancelled\", (err) => reject(err));\n retrier.on(\"failed\", (err) => reject(err));\n\n retrier.start();\n });\n }\n\n async get(url: string): Promise<any> {\n if (this.isShutdownInitiated) {\n throw new Error(\"Client has been shut down.\");\n }\n\n const cacheEntry = this.cache.get(url);\n if (cacheEntry && !this.isExpired(cacheEntry.timestamp)) {\n return cacheEntry.response;\n }\n\n const responsePromise = this.executeWithRetry(\n () =>\n this.services.transport.sendRequest(\n new HttpRequest({\n url,\n grant: this.configuration.productId,\n })\n ),\n this.configuration.retryWhenThrottled\n );\n\n this.pendingRequests.add(responsePromise);\n const response = await responsePromise;\n this.pendingRequests.delete(responsePromise);\n\n const postProcessedResponse = Network.responsePostProcess(response);\n this.cache.set(url, {\n response: postProcessedResponse,\n timestamp: Date.now(),\n });\n this.pokeTimer();\n return postProcessedResponse;\n }\n\n async disconnect() {\n this.isShutdownInitiated = true;\n try {\n await Promise.all([...this.pendingRequests]);\n } catch {}\n await this.services.syncClient.shutdown();\n }\n}\n\nexport { Network };\n"],"names":["TwilioError","Retrier","HttpRequest"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAS,oBAAoB,CAAC,cAAc,EAAE,OAAO,EAAA;AACnD,IAAA,IAAI,CAAA,OAAO,KAAP,IAAA,IAAA,OAAO,uBAAP,OAAO,CAAE,OAAO,KAAI,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ,EAAE;QAC3D,OAAO,OAAO,CAAC,OAAO,CAAC;AACxB,KAAA;IACD,QAAQ,cAAc,CAAC,UAAU;AAC/B,QAAA,KAAK,GAAG;AACN,YAAA,OAAO,qBAAqB,CAAC;AAC/B,QAAA,KAAK,GAAG;AACN,YAAA,OAAO,uBAAuB,CAAC;AACjC,QAAA;AACE,YAAA,OAAO,mBAAmB,CAAC;AAC9B,KAAA;AACH,CAAC;AAED,SAAS,iBAAiB,CAAC,OAAO,EAAA;;IAChC,OAAO,CAAA,EAAA,GAAA,OAAO,KAAA,IAAA,IAAP,OAAO,KAAA,KAAA,CAAA,GAAA,KAAA,CAAA,GAAP,OAAO,CAAE,IAAI,MAAI,IAAA,IAAA,EAAA,KAAA,KAAA,CAAA,GAAA,EAAA,GAAA,CAAC,CAAC;AAC5B,CAAC;AAED,SAAS,iBAAiB,CAAC,cAAc,EAAE,OAAO,EAAA;;AAChD,IAAA,IAAI,cAAc,CAAC,UAAU,KAA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