@twilio/conversations 3.0.1-rc.1 → 3.0.1-rc.103
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/browser.js +9543 -4302
- package/builds/browser.js.map +1 -1
- package/builds/lib.d.ts +256 -61
- package/builds/lib.js +9543 -4302
- package/builds/lib.js.map +1 -1
- package/builds/twilio-conversations.js +44686 -27540
- package/builds/twilio-conversations.min.js +1 -200
- package/dist/channel-metadata-client.js +1 -1
- package/dist/channel-metadata-client.js.map +1 -1
- package/dist/client.js +153 -43
- package/dist/client.js.map +1 -1
- package/dist/command-executor.js +31 -50
- package/dist/command-executor.js.map +1 -1
- package/dist/configuration.js +8 -4
- package/dist/configuration.js.map +1 -1
- package/dist/content-template.js +1 -1
- package/dist/content-template.js.map +1 -1
- package/dist/conversation.js +12 -46
- package/dist/conversation.js.map +1 -1
- package/dist/data/conversations.js +2 -18
- package/dist/data/conversations.js.map +1 -1
- package/dist/data/messages.js +13 -3
- package/dist/data/messages.js.map +1 -1
- package/dist/data/participants.js +2 -4
- package/dist/data/participants.js.map +1 -1
- package/dist/data/users.js +2 -2
- package/dist/data/users.js.map +1 -1
- package/dist/index.js +5 -6
- package/dist/index.js.map +1 -1
- package/dist/media.js.map +1 -1
- package/dist/message-builder.js.map +1 -1
- package/dist/message-recipients-client.js +237 -0
- package/dist/message-recipients-client.js.map +1 -0
- package/dist/message.js +57 -0
- package/dist/message.js.map +1 -1
- package/dist/node_modules/quick-lru/index.js.map +1 -1
- package/dist/node_modules/tslib/tslib.es6.js.map +1 -1
- package/dist/packages/conversations/package.json.js +1 -1
- package/dist/participant.js +34 -34
- package/dist/participant.js.map +1 -1
- package/dist/push-notification.js.map +1 -1
- package/dist/rest-paginator.js +11 -11
- package/dist/rest-paginator.js.map +1 -1
- package/dist/services/network.js +11 -101
- package/dist/services/network.js.map +1 -1
- package/dist/services/typing-indicator.js +5 -13
- package/dist/services/typing-indicator.js.map +1 -1
- package/dist/unsent-message.js.map +1 -1
- package/dist/user.js.map +1 -1
- package/dist/util/index.js.map +1 -1
- package/docs/assets/css/main.css +2660 -0
- package/docs/assets/images/icons.png +0 -0
- package/docs/assets/images/icons@2x.png +0 -0
- package/docs/assets/images/widgets.png +0 -0
- package/docs/assets/images/widgets@2x.png +0 -0
- package/docs/assets/js/main.js +248 -0
- package/docs/assets/js/search.js +1 -0
- package/docs/classes/AggregatedDeliveryReceipt.html +3182 -144
- package/docs/classes/CancellablePromise.html +3209 -224
- package/docs/classes/ChannelMetadata.html +3049 -66
- package/docs/classes/Client.html +4276 -701
- package/docs/classes/ContentTemplate.html +3115 -96
- package/docs/classes/ContentTemplateVariable.html +3114 -88
- package/docs/classes/Conversation.html +4380 -768
- package/docs/classes/DetailedDeliveryReceipt.html +3162 -116
- package/docs/classes/EmailRecipientDescriptor.html +3098 -0
- package/docs/classes/Media.html +3165 -119
- package/docs/classes/Message.html +3824 -417
- package/docs/classes/MessageBuilder.html +3315 -208
- package/docs/classes/Participant.html +3442 -258
- package/docs/classes/PushNotification.html +3129 -101
- package/docs/classes/RestPaginator.html +3158 -120
- package/docs/classes/UnknownRecipientDescriptor.html +3067 -0
- package/docs/classes/UnsentMessage.html +3040 -63
- package/docs/classes/User.html +3347 -209
- package/docs/index.html +4366 -146
- package/docs/interfaces/ClientOptions.html +3065 -66
- package/docs/interfaces/ConversationBindings.html +3000 -109
- package/docs/interfaces/ConversationEmailBinding.html +3000 -109
- package/docs/interfaces/ConversationLimits.html +3097 -87
- package/docs/interfaces/ConversationState.html +3049 -66
- package/docs/interfaces/ConversationUpdatedEventArgs.html +3000 -109
- package/docs/interfaces/CreateConversationOptions.html +3065 -73
- package/docs/interfaces/LastMessage.html +3049 -66
- package/docs/interfaces/Paginator.html +3139 -110
- package/docs/interfaces/ParticipantBindings.html +3000 -109
- package/docs/interfaces/ParticipantEmailBinding.html +3000 -109
- package/docs/interfaces/PushNotificationData.html +3113 -94
- package/docs/interfaces/SendEmailOptions.html +3033 -59
- package/docs/interfaces/SendMediaOptions.html +3067 -75
- package/docs/modules.html +4373 -180
- package/package.json +13 -14
- package/docs/.nojekyll +0 -1
- package/docs/assets/highlight.css +0 -113
- package/docs/assets/main.js +0 -58
- package/docs/assets/search.js +0 -1
- package/docs/assets/style.css +0 -1279
- package/docs/classes/CancellationError.html +0 -112
- package/docs/interfaces/ParticipantBindingOptions.html +0 -110
- package/docs/types/ChannelType.html +0 -106
- package/docs/types/ConnectionState.html +0 -115
- package/docs/types/ContentData.html +0 -106
- package/docs/types/ContentDataAction.html +0 -107
- package/docs/types/ContentDataActionOther.html +0 -121
- package/docs/types/ContentDataActionPhone.html +0 -128
- package/docs/types/ContentDataActionReply.html +0 -133
- package/docs/types/ContentDataActionUrl.html +0 -128
- package/docs/types/ContentDataCallToAction.html +0 -131
- package/docs/types/ContentDataCard.html +0 -137
- package/docs/types/ContentDataListItem.html +0 -121
- package/docs/types/ContentDataListPicker.html +0 -134
- package/docs/types/ContentDataLocation.html +0 -134
- package/docs/types/ContentDataMedia.html +0 -129
- package/docs/types/ContentDataOther.html +0 -121
- package/docs/types/ContentDataQuickReply.html +0 -131
- package/docs/types/ContentDataReply.html +0 -119
- package/docs/types/ContentDataText.html +0 -125
- package/docs/types/ConversationStatus.html +0 -107
- package/docs/types/ConversationUpdateReason.html +0 -106
- package/docs/types/DeliveryAmount.html +0 -106
- package/docs/types/DeliveryStatus.html +0 -106
- package/docs/types/JSONArray.html +0 -106
- package/docs/types/JSONObject.html +0 -111
- package/docs/types/JSONValue.html +0 -106
- package/docs/types/LogLevel.html +0 -106
- package/docs/types/MediaCategory.html +0 -106
- package/docs/types/MessageType.html +0 -106
- package/docs/types/MessageUpdateReason.html +0 -106
- package/docs/types/NotificationLevel.html +0 -109
- package/docs/types/NotificationsChannelType.html +0 -110
- package/docs/types/ParticipantEmailLevel.html +0 -108
- package/docs/types/ParticipantType.html +0 -107
- package/docs/types/ParticipantUpdateReason.html +0 -106
- package/docs/types/PushNotificationType.html +0 -106
- package/docs/types/State.html +0 -110
- package/docs/types/UserUpdateReason.html +0 -106
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../../node_modules/quick-lru/index.js"],"sourcesContent":["'use strict';\n\nclass QuickLRU {\n\tconstructor(options = {}) {\n\t\tif (!(options.maxSize && options.maxSize > 0)) {\n\t\t\tthrow new TypeError('`maxSize` must be a number greater than 0');\n\t\t}\n\n\t\tthis.maxSize = options.maxSize;\n\t\tthis.onEviction = options.onEviction;\n\t\tthis.cache = new Map();\n\t\tthis.oldCache = new Map();\n\t\tthis._size = 0;\n\t}\n\n\t_set(key, value) {\n\t\tthis.cache.set(key, value);\n\t\tthis._size++;\n\n\t\tif (this._size >= this.maxSize) {\n\t\t\tthis._size = 0;\n\n\t\t\tif (typeof this.onEviction === 'function') {\n\t\t\t\tfor (const [key, value] of this.oldCache.entries()) {\n\t\t\t\t\tthis.onEviction(key, value);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.oldCache = this.cache;\n\t\t\tthis.cache = new Map();\n\t\t}\n\t}\n\n\tget(key) {\n\t\tif (this.cache.has(key)) {\n\t\t\treturn this.cache.get(key);\n\t\t}\n\n\t\tif (this.oldCache.has(key)) {\n\t\t\tconst value = this.oldCache.get(key);\n\t\t\tthis.oldCache.delete(key);\n\t\t\tthis._set(key, value);\n\t\t\treturn value;\n\t\t}\n\t}\n\n\tset(key, value) {\n\t\tif (this.cache.has(key)) {\n\t\t\tthis.cache.set(key, value);\n\t\t} else {\n\t\t\tthis._set(key, value);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\thas(key) {\n\t\treturn this.cache.has(key) || this.oldCache.has(key);\n\t}\n\n\tpeek(key) {\n\t\tif (this.cache.has(key)) {\n\t\t\treturn this.cache.get(key);\n\t\t}\n\n\t\tif (this.oldCache.has(key)) {\n\t\t\treturn this.oldCache.get(key);\n\t\t}\n\t}\n\n\tdelete(key) {\n\t\tconst deleted = this.cache.delete(key);\n\t\tif (deleted) {\n\t\t\tthis._size--;\n\t\t}\n\n\t\treturn this.oldCache.delete(key) || deleted;\n\t}\n\n\tclear() {\n\t\tthis.cache.clear();\n\t\tthis.oldCache.clear();\n\t\tthis._size = 0;\n\t}\n\n\t* keys() {\n\t\tfor (const [key] of this) {\n\t\t\tyield key;\n\t\t}\n\t}\n\n\t* values() {\n\t\tfor (const [, value] of this) {\n\t\t\tyield value;\n\t\t}\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tfor (const item of this.cache) {\n\t\t\tyield item;\n\t\t}\n\n\t\tfor (const item of this.oldCache) {\n\t\t\tconst [key] = item;\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\tyield item;\n\t\t\t}\n\t\t}\n\t}\n\n\tget size() {\n\t\tlet oldCacheSize = 0;\n\t\tfor (const key of this.oldCache.keys()) {\n\t\t\tif (!this.cache.has(key)) {\n\t\t\t\toldCacheSize++;\n\t\t\t}\n\t\t}\n\n\t\treturn Math.min(this._size + oldCacheSize, this.maxSize);\n\t}\n}\n\nmodule.exports = QuickLRU;\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,MAAM,QAAQ,CAAC;AACf,CAAC,WAAW,CAAC,OAAO,GAAG,EAAE,EAAE;AAC3B,EAAE,IAAI,EAAE,OAAO,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO,GAAG,CAAC,CAAC,EAAE;AACjD,GAAG,MAAM,IAAI,SAAS,CAAC,2CAA2C,CAAC,CAAC;AACpE,GAAG;AACH;AACA,EAAE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;AACjC,EAAE,IAAI,CAAC,UAAU,GAAG,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AC,IAAI,EAAE,EAAE;AAC1C,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;AAC7B,IAAI,YAAY,EAAE,CAAC;AACnB,IAAI;AACJ,GAAG;AACH;AACA,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,GAAG,YAAY,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;AAC3D,EAAE;AACF,CAAC;AACD;AACA,IAAA,QAAc,GAAG;;;;"}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"tslib.es6.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
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;;;;;"}
|
package/dist/participant.js
CHANGED
@@ -156,6 +156,39 @@ const log = logger.Logger.scope("Participant");
|
|
156
156
|
* A participant represents a remote client in a conversation.
|
157
157
|
*/
|
158
158
|
class Participant extends replayEventEmitter.ReplayEventEmitter {
|
159
|
+
/**
|
160
|
+
* @internal
|
161
|
+
*/
|
162
|
+
constructor(data, sid, conversation, links, services) {
|
163
|
+
var _a, _b;
|
164
|
+
super();
|
165
|
+
this.conversation = conversation;
|
166
|
+
this.links = links;
|
167
|
+
this.services = services;
|
168
|
+
this.state = {
|
169
|
+
attributes: index.parseAttributes(data.attributes, "Retrieved malformed attributes from the server for participant: " +
|
170
|
+
sid, log),
|
171
|
+
dateCreated: data.dateCreated ? index.parseTime(data.dateCreated) : null,
|
172
|
+
dateUpdated: data.dateCreated ? index.parseTime(data.dateUpdated) : null,
|
173
|
+
sid: sid,
|
174
|
+
typingTimeout: null,
|
175
|
+
isTyping: false,
|
176
|
+
identity: data.identity,
|
177
|
+
roleSid: (_a = data.roleSid) !== null && _a !== void 0 ? _a : "",
|
178
|
+
lastReadMessageIndex: Number.isInteger(data.lastConsumedMessageIndex)
|
179
|
+
? data.lastConsumedMessageIndex
|
180
|
+
: null,
|
181
|
+
lastReadTimestamp: data.lastConsumptionTimestamp
|
182
|
+
? index.parseTime(data.lastConsumptionTimestamp)
|
183
|
+
: null,
|
184
|
+
type: data.type || "chat",
|
185
|
+
userInfo: data.userInfo,
|
186
|
+
bindings: (_b = data.bindings) !== null && _b !== void 0 ? _b : {},
|
187
|
+
};
|
188
|
+
if (!data.identity && !data.type) {
|
189
|
+
throw new Error("Received invalid Participant object from server: Missing identity or type of Participant.");
|
190
|
+
}
|
191
|
+
}
|
159
192
|
/**
|
160
193
|
* The server-assigned unique identifier for the participant.
|
161
194
|
*/
|
@@ -223,45 +256,12 @@ class Participant extends replayEventEmitter.ReplayEventEmitter {
|
|
223
256
|
* using the type dynamically `participant.bindings[participant.type]`
|
224
257
|
* just be aware that the binding information has different structure for
|
225
258
|
* each participant type.
|
226
|
-
* See also {
|
259
|
+
* See also {ParticipantEmailBinding}, the only available currently binding descriptor.
|
227
260
|
*/
|
228
261
|
get bindings() {
|
229
262
|
var _a;
|
230
263
|
return (_a = this.state.bindings) !== null && _a !== void 0 ? _a : {};
|
231
264
|
}
|
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
|
-
}
|
265
265
|
/**
|
266
266
|
* Internal method used to start or reset the typing indicator timeout (with event emitting).
|
267
267
|
* @internal
|
package/dist/participant.js.map
CHANGED
@@ -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 { 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,CAAC,WAAW,CAAC;KAC/B;AAED;;AAEG;AACH,IAAA,IAAW,WAAW,GAAA;AACpB,QAAA,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,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;;;;"}
|
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 \"./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 * 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 {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;AA6F7D;;AAEG;IACH,WACE,CAAA,IAA2B,EAC3B,GAAW,EACX,YAA0B,EAC1B,KAAuB,EACvB,QAA6B,EAAA;;AAE7B,Q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E,aAAa,EAAE,aAAa,EAAE,CAAC,CAAC;AAC3E,SAAA;AAED,QAAA,OAAO,IAAI,CAAC;KACb;AAED;;AAEG;AACH,IAAA,MAAM,OAAO,GAAA;AACX,QAAA,IAAI,IAAI,CAAC,IAAI,IAAI,MAAM,EAAE;YACvB,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;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,UAAI,CAAC;;;;AAUxB,CAAA,EAAA,WAAA,CAAA,SAAA,EAAA,kBAAA,EAAA,IAAA,CAAA;;;;"}
|
@@ -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\
|
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;;;;"}
|
package/dist/rest-paginator.js
CHANGED
@@ -143,6 +143,17 @@ Object.defineProperty(exports, '__esModule', { value: true });
|
|
143
143
|
* Pagination helper class.
|
144
144
|
*/
|
145
145
|
class RestPaginator {
|
146
|
+
/**
|
147
|
+
* @internal
|
148
|
+
*/
|
149
|
+
constructor(items, source, prevToken, nextToken) {
|
150
|
+
this.state = {
|
151
|
+
prevToken,
|
152
|
+
nextToken,
|
153
|
+
source,
|
154
|
+
items,
|
155
|
+
};
|
156
|
+
}
|
146
157
|
/**
|
147
158
|
* Indicates the existence of the next page.
|
148
159
|
*/
|
@@ -161,17 +172,6 @@ class RestPaginator {
|
|
161
172
|
get items() {
|
162
173
|
return this.state.items;
|
163
174
|
}
|
164
|
-
/**
|
165
|
-
* @internal
|
166
|
-
*/
|
167
|
-
constructor(items, source, prevToken, nextToken) {
|
168
|
-
this.state = {
|
169
|
-
prevToken,
|
170
|
-
nextToken,
|
171
|
-
source,
|
172
|
-
items,
|
173
|
-
};
|
174
|
-
}
|
175
175
|
/**
|
176
176
|
* Request the next page. Does not modify the existing object.
|
177
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;
|
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;;;;"}
|
package/dist/services/network.js
CHANGED
@@ -140,50 +140,13 @@ var global =
|
|
140
140
|
Object.defineProperty(exports, '__esModule', { value: true });
|
141
141
|
|
142
142
|
var operationRetrier = require('@twilio/operation-retrier');
|
143
|
-
var twilsock = require('twilsock');
|
144
|
-
var shared = require('@twilio/shared');
|
145
143
|
|
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
|
-
}
|
179
144
|
class Network {
|
180
145
|
constructor(configuration, services) {
|
181
|
-
this.isShutdownInitiated = false;
|
182
146
|
this.configuration = configuration;
|
183
147
|
this.services = services;
|
184
148
|
this.cache = new Map();
|
185
149
|
this.cacheLifetime = this.configuration.httpCacheInterval * 100;
|
186
|
-
this.pendingRequests = new Set();
|
187
150
|
this.cleanupCache();
|
188
151
|
}
|
189
152
|
isExpired(timestamp) {
|
@@ -204,23 +167,6 @@ class Network {
|
|
204
167
|
this.timer ||
|
205
168
|
setInterval(() => this.cleanupCache(), this.cacheLifetime * 2);
|
206
169
|
}
|
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
|
-
}
|
224
170
|
executeWithRetry(request, retryWhenThrottled = false) {
|
225
171
|
return new Promise((resolve, reject) => {
|
226
172
|
const codesToRetryOn = [502, 503, 504];
|
@@ -230,37 +176,21 @@ class Network {
|
|
230
176
|
const retrier = new operationRetrier.Retrier(this.configuration.backoffConfiguration);
|
231
177
|
retrier.on("attempt", () => {
|
232
178
|
request()
|
233
|
-
.then((result) =>
|
234
|
-
|
235
|
-
if (
|
236
|
-
retrier.
|
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);
|
179
|
+
.then((result) => retrier.succeeded(result))
|
180
|
+
.catch((err) => {
|
181
|
+
if (codesToRetryOn.indexOf(err.status) > -1) {
|
182
|
+
retrier.failed(err);
|
247
183
|
}
|
248
|
-
else if (
|
184
|
+
else if (err.message === "Twilsock disconnected") {
|
249
185
|
// Ugly hack. We must make a proper exceptions for twilsock
|
250
|
-
retrier.failed(
|
186
|
+
retrier.failed(err);
|
251
187
|
}
|
252
188
|
else {
|
253
189
|
// Fatal error
|
254
190
|
retrier.removeAllListeners();
|
255
191
|
retrier.cancel();
|
256
|
-
reject(
|
192
|
+
reject(err);
|
257
193
|
}
|
258
|
-
})
|
259
|
-
.catch((err) => {
|
260
|
-
// Fatal error
|
261
|
-
retrier.removeAllListeners();
|
262
|
-
retrier.cancel();
|
263
|
-
reject(err);
|
264
194
|
});
|
265
195
|
});
|
266
196
|
retrier.on("succeeded", (result) => {
|
@@ -272,35 +202,15 @@ class Network {
|
|
272
202
|
});
|
273
203
|
}
|
274
204
|
async get(url) {
|
275
|
-
if (this.isShutdownInitiated) {
|
276
|
-
throw new Error("Client has been shut down.");
|
277
|
-
}
|
278
205
|
const cacheEntry = this.cache.get(url);
|
279
206
|
if (cacheEntry && !this.isExpired(cacheEntry.timestamp)) {
|
280
207
|
return cacheEntry.response;
|
281
208
|
}
|
282
|
-
const
|
283
|
-
|
284
|
-
|
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
|
-
});
|
209
|
+
const headers = {};
|
210
|
+
const response = await this.executeWithRetry(() => this.services.transport.get(url, headers, this.configuration.productId), this.configuration.retryWhenThrottled);
|
211
|
+
this.cache.set(url, { response, timestamp: Date.now() });
|
294
212
|
this.pokeTimer();
|
295
|
-
return
|
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();
|
213
|
+
return response;
|
304
214
|
}
|
305
215
|
}
|
306
216
|
|
@@ -1 +1 @@
|
|
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,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ation-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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,MAAM,OAAO,CAAA;IAQX,WAAY,CAAA,aAAa,EAAE,QAAQ,EAAA;AACjC,QAAA,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;AACnC,QAAA,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;AACzB,QAAA,IAAI,CAAC,KAAK,GAAG,IAAI,GAAG,EAAsB,CAAC;QAC3C,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,aAAa,CAAC,iBAAiB,GAAG,GAAG,CAAC;QAChE,IAAI,CAAC,YAAY,EAAE,CAAC;KACrB;AAEO,IAAA,SAAS,CAAC,SAAiB,EAAA;AACjC,QAAA,OAAO,CAAC,IAAI,CAAC,aAAa,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,SAAS,GAAG,IAAI,CAAC,aAAa,CAAC;KAC3E;IAEO,YAAY,GAAA;QAClB,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,EAAE;YAC/B,IAAI,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE;AAC/B,gBAAA,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC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AAS,EAAE,CAAC;AACjB,QAAA,OAAO,QAAQ,CAAC;KACjB;AACF;;;;"}
|
@@ -141,7 +141,6 @@ Object.defineProperty(exports, '__esModule', { value: true });
|
|
141
141
|
|
142
142
|
var logger = require('../logger.js');
|
143
143
|
var notificationTypes = require('../interfaces/notification-types.js');
|
144
|
-
var twilsock = require('twilsock');
|
145
144
|
|
146
145
|
const log = logger.Logger.scope("TypingIndicator");
|
147
146
|
/**
|
@@ -182,7 +181,7 @@ class TypingIndicator {
|
|
182
181
|
// this.services.notificationClient.subscribe(NotificationTypes.TYPING_INDICATOR, 'twilsock');
|
183
182
|
this.services.notificationClient.on("message", async (type, message) => {
|
184
183
|
if (type === notificationTypes.NotificationTypes.TYPING_INDICATOR) {
|
185
|
-
await this._handleRemoteTyping(
|
184
|
+
await this._handleRemoteTyping(message);
|
186
185
|
}
|
187
186
|
});
|
188
187
|
}
|
@@ -229,19 +228,12 @@ class TypingIndicator {
|
|
229
228
|
const headers = {
|
230
229
|
"Content-Type": "application/x-www-form-urlencoded",
|
231
230
|
};
|
232
|
-
const
|
231
|
+
const body = `ChannelSid=${conversationSid}`;
|
233
232
|
return this.services.twilsockClient
|
234
|
-
.
|
235
|
-
method: "POST",
|
236
|
-
url,
|
237
|
-
headers,
|
238
|
-
payload,
|
239
|
-
grant: this.configuration.productId,
|
240
|
-
}))
|
233
|
+
.post(url, headers, body, this.configuration.productId)
|
241
234
|
.then((response) => {
|
242
|
-
|
243
|
-
|
244
|
-
this.serviceTypingTimeout = body.typing_timeout * 1000;
|
235
|
+
if (response.body.hasOwnProperty("typing_timeout")) {
|
236
|
+
this.serviceTypingTimeout = response.body.typing_timeout * 1000;
|
245
237
|
}
|
246
238
|
})
|
247
239
|
.catch((err) => {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"typing-indicator.js","sources":["../../src/services/typing-indicator.ts"],"sourcesContent":["import { Logger } from \"../logger\";\n\nimport { Notifications } from \"@twilio/notifications\";\n\nimport { NotificationTypes } from \"../interfaces/notification-types\";\nimport {
|
1
|
+
{"version":3,"file":"typing-indicator.js","sources":["../../src/services/typing-indicator.ts"],"sourcesContent":["import { Logger } from \"../logger\";\n\nimport { Notifications } from \"@twilio/notifications\";\n\nimport { NotificationTypes } from \"../interfaces/notification-types\";\nimport { TwilsockClient } from \"twilsock\";\nimport { Configuration } from \"../configuration\";\nimport { Conversation } from \"../conversation\";\n\nconst log = Logger.scope(\"TypingIndicator\");\n\nexport interface TypingIndicatorServices {\n twilsockClient: TwilsockClient;\n notificationClient: Notifications;\n}\n\n/**\n * 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\n * 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\n * \"typing_timeout\" attribute will be exactly the same as defined in the console. The second place that the attribute appears in is from a\n * notification of type \"twilio.ipmsg.typing_indicator\". In this case, the \"typing_timeout\" value will be +1 of that in the console. This\n * intentional. The timeout returned from the POST -> /v1/typing call should be used to disable further calls for that period of time. On contrary,\n * the timeout returned from the notification should be used as the timeout for the \"typingEnded\" event, +1 is to account for latency.\n *\n * @private\n */\n\n/**\n * @class TypingIndicator\n *\n * @constructor\n * @private\n */\nclass TypingIndicator {\n private readonly services: TypingIndicatorServices;\n private readonly configuration: Configuration;\n\n private sentUpdates: Map<string, number>;\n private getConversation: (conversationSid: string) => Promise<Conversation>;\n private serviceTypingTimeout;\n\n constructor(\n getConversation: (conversationSid: string) => Promise<Conversation>,\n config: Configuration,\n services: TypingIndicatorServices\n ) {\n this.configuration = config;\n this.services = services;\n this.getConversation = getConversation;\n\n this.serviceTypingTimeout = null;\n this.sentUpdates = new Map();\n }\n\n public get typingTimeout(): number {\n return (\n this.configuration.typingIndicatorTimeoutOverride ||\n this.serviceTypingTimeout ||\n this.configuration.typingIndicatorTimeoutDefault\n );\n }\n\n /**\n * Initialize TypingIndicator controller\n * Registers for needed message types and sets listeners\n * @private\n */\n initialize(): void {\n // this.services.notificationClient.subscribe(NotificationTypes.TYPING_INDICATOR, 'twilsock');\n this.services.notificationClient.on(\"message\", async (type, message) => {\n if (type === NotificationTypes.TYPING_INDICATOR) {\n await this._handleRemoteTyping(message);\n }\n });\n }\n\n /**\n * Remote participants typing events handler\n */\n private async _handleRemoteTyping(message) {\n log.trace(\"Got new typing indicator \", message);\n\n this.getConversation(message.channel_sid)\n .then((conversation) => {\n if (!conversation) {\n return;\n }\n\n conversation._participants.forEach((participant) => {\n if (participant.identity !== message.identity) {\n return;\n }\n\n const timeout = this.configuration.typingIndicatorTimeoutOverride\n ? this.configuration.typingIndicatorTimeoutOverride + 1000\n : message.typing_timeout * 1000;\n participant._startTyping(timeout);\n });\n })\n .catch((err) => {\n log.error(err);\n throw err;\n });\n }\n\n /**\n * Send typing event for the given conversation sid\n * @param {String} conversationSid\n */\n send(conversationSid: string) {\n const lastUpdate = this.sentUpdates.get(conversationSid);\n if (lastUpdate && lastUpdate > Date.now() - this.typingTimeout) {\n return Promise.resolve();\n }\n\n this.sentUpdates.set(conversationSid, Date.now());\n return this._send(conversationSid);\n }\n\n private _send(conversationSid: string) {\n log.trace(\"Sending typing indicator\");\n\n const url = this.configuration.links.typing;\n const headers = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n };\n const body = `ChannelSid=${conversationSid}`;\n\n return this.services.twilsockClient\n .post<{ typing_timeout: number }>(\n url,\n headers,\n body,\n this.configuration.productId\n )\n .then((response) => {\n if (response.body.hasOwnProperty(\"typing_timeout\")) {\n this.serviceTypingTimeout = response.body.typing_timeout * 1000;\n }\n })\n .catch((err) => {\n log.error(\"Failed to send typing indicator:\", err);\n throw err;\n });\n }\n}\n\nexport { TypingIndicator };\n"],"names":["Logger","NotificationTypes"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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