@twilio/conversations 2.2.2 → 2.3.0-rc.0

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.
@@ -0,0 +1,301 @@
1
+ /*
2
+ @license
3
+ The following license applies to all parts of this software except as
4
+ documented below.
5
+
6
+ Copyright (c) 2019, Twilio, inc.
7
+ All rights reserved.
8
+
9
+ Redistribution and use in source and binary forms, with or without
10
+ modification, are permitted provided that the following conditions are
11
+ met:
12
+
13
+ 1. Redistributions of source code must retain the above copyright
14
+ notice, this list of conditions and the following disclaimer.
15
+
16
+ 2. Redistributions in binary form must reproduce the above copyright
17
+ notice, this list of conditions and the following disclaimer in
18
+ the documentation and/or other materials provided with the
19
+ distribution.
20
+
21
+ 3. Neither the name of Twilio nor the names of its contributors may
22
+ be used to endorse or promote products derived from this software
23
+ without specific prior written permission.
24
+
25
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36
+
37
+ This software includes javascript-state-machine under the following license.
38
+
39
+ Copyright (c) 2012, 2013, 2014, 2015, Jake Gordon and contributors
40
+
41
+ Permission is hereby granted, free of charge, to any person obtaining a copy
42
+ of this software and associated documentation files (the "Software"), to deal
43
+ in the Software without restriction, including without limitation the rights
44
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
45
+ copies of the Software, and to permit persons to whom the Software is
46
+ furnished to do so, subject to the following conditions:
47
+
48
+ The above copyright notice and this permission notice shall be included in all
49
+ copies or substantial portions of the Software.
50
+
51
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
52
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
53
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
54
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
55
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
56
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
57
+
58
+ This software includes loglevel under the following license.
59
+
60
+ Copyright (c) 2013 Tim Perry
61
+
62
+ Permission is hereby granted, free of charge, to any person
63
+ obtaining a copy of this software and associated documentation
64
+ files (the "Software"), to deal in the Software without
65
+ restriction, including without limitation the rights to use,
66
+ copy, modify, merge, publish, distribute, sublicense, and/or sell
67
+ copies of the Software, and to permit persons to whom the
68
+ Software is furnished to do so, subject to the following
69
+ conditions:
70
+
71
+ The above copyright notice and this permission notice shall be
72
+ included in all copies or substantial portions of the Software.
73
+
74
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
75
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
76
+ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
77
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
78
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
79
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
80
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
81
+ OTHER DEALINGS IN THE SOFTWARE.
82
+
83
+ This software includes q under the following license.
84
+
85
+ Copyright 2009–2014 Kristopher Michael Kowal. All rights reserved.
86
+ Permission is hereby granted, free of charge, to any person obtaining a copy
87
+ of this software and associated documentation files (the "Software"), to
88
+ deal in the Software without restriction, including without limitation the
89
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
90
+ sell copies of the Software, and to permit persons to whom the Software is
91
+ furnished to do so, subject to the following conditions:
92
+
93
+ The above copyright notice and this permission notice shall be included in
94
+ all copies or substantial portions of the Software.
95
+
96
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
97
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
98
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
99
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
100
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
101
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
102
+ IN THE SOFTWARE.
103
+
104
+ This software includes platform.js under the following license.
105
+
106
+ Copyright 2014 Benjamin Tan <https://d10.github.io/>
107
+ Copyright 2011-2015 John-David Dalton <http://allyoucanleet.com/>
108
+
109
+ Permission is hereby granted, free of charge, to any person obtaining
110
+ a copy of this software and associated documentation files (the
111
+ "Software"), to deal in the Software without restriction, including
112
+ without limitation the rights to use, copy, modify, merge, publish,
113
+ distribute, sublicense, and/or sell copies of the Software, and to
114
+ permit persons to whom the Software is furnished to do so, subject to
115
+ the following conditions:
116
+
117
+ The above copyright notice and this permission notice shall be
118
+ included in all copies or substantial portions of the Software.
119
+
120
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
121
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
122
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
123
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
124
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
125
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
126
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
127
+
128
+ */
129
+ 'use strict';
130
+
131
+ Object.defineProperty(exports, '__esModule', { value: true });
132
+
133
+ const collectActions = (actions) => {
134
+ return actions.map((action) => {
135
+ var _a, _b, _c, _d;
136
+ const rawData = JSON.stringify(action);
137
+ switch (action.type) {
138
+ case "QUICK_REPLY":
139
+ return {
140
+ type: "reply",
141
+ title: action.title,
142
+ id: (_a = action.id) !== null && _a !== void 0 ? _a : "",
143
+ index: (_b = action.index) !== null && _b !== void 0 ? _b : 0,
144
+ rawData,
145
+ };
146
+ case "PHONE_NUMBER":
147
+ return {
148
+ type: "phone",
149
+ title: action.title,
150
+ phone: (_c = action.phone) !== null && _c !== void 0 ? _c : "",
151
+ rawData,
152
+ };
153
+ case "URL":
154
+ return {
155
+ type: "url",
156
+ title: action.title,
157
+ url: (_d = action.url) !== null && _d !== void 0 ? _d : "",
158
+ rawData,
159
+ };
160
+ default:
161
+ return {
162
+ type: "other",
163
+ rawData,
164
+ };
165
+ }
166
+ });
167
+ };
168
+ const parseVariant = (type, data) => {
169
+ var _a, _b;
170
+ const rawData = JSON.stringify(data);
171
+ switch (type) {
172
+ case "twilio/text": {
173
+ const variant = data;
174
+ return {
175
+ type: "text",
176
+ body: variant.body,
177
+ rawData,
178
+ };
179
+ }
180
+ case "twilio/media": {
181
+ const variant = data;
182
+ return {
183
+ type: "media",
184
+ body: variant.body,
185
+ media: variant.media,
186
+ rawData,
187
+ };
188
+ }
189
+ case "twilio/location": {
190
+ const variant = data;
191
+ return {
192
+ type: "location",
193
+ longitude: variant.longitude,
194
+ latitude: variant.latitude,
195
+ label: variant.label,
196
+ rawData,
197
+ };
198
+ }
199
+ case "twilio/quick-reply": {
200
+ const variant = data;
201
+ return {
202
+ type: "quickReply",
203
+ body: variant.body,
204
+ replies: variant.actions,
205
+ rawData,
206
+ };
207
+ }
208
+ case "twilio/call-to-action": {
209
+ const variant = data;
210
+ return {
211
+ type: "callToAction",
212
+ body: variant.body,
213
+ actions: collectActions(variant.actions),
214
+ rawData,
215
+ };
216
+ }
217
+ case "twilio/list-picker": {
218
+ const variant = data;
219
+ return {
220
+ type: "listPicker",
221
+ body: variant.body,
222
+ button: variant.button,
223
+ items: variant.items,
224
+ rawData,
225
+ };
226
+ }
227
+ case "twilio/card": {
228
+ const variant = data;
229
+ return {
230
+ type: "card",
231
+ title: variant.title,
232
+ subtitle: variant.subtitle,
233
+ media: (_a = variant.media) !== null && _a !== void 0 ? _a : [],
234
+ actions: collectActions((_b = variant.actions) !== null && _b !== void 0 ? _b : []),
235
+ rawData,
236
+ };
237
+ }
238
+ default:
239
+ return {
240
+ type: "other",
241
+ rawData,
242
+ };
243
+ }
244
+ };
245
+ const collectVariants = (variants) => {
246
+ const variantsMap = new Map();
247
+ for (const [key, value] of Object.entries(variants)) {
248
+ variantsMap.set(key, parseVariant(key, value));
249
+ }
250
+ return variantsMap;
251
+ };
252
+ /**
253
+ * Represents a variable for a content template. See
254
+ * {@link ContentTemplate.variables}.
255
+ */
256
+ class ContentTemplateVariable {
257
+ constructor(
258
+ /**
259
+ * Name of the variable.
260
+ */
261
+ name,
262
+ /**
263
+ * Key of the variable
264
+ */
265
+ value) {
266
+ this.name = name;
267
+ this.value = value;
268
+ }
269
+ /**
270
+ * Copies the variable with a new value.
271
+ *
272
+ * @param value The new value for the variable.
273
+ */
274
+ copyWithValue(value) {
275
+ return new ContentTemplateVariable(this.name, value);
276
+ }
277
+ }
278
+ /**
279
+ * A rich content template.
280
+ *
281
+ * Use {@Link Client.getContentTemplates} to request all the templates available
282
+ * for the current account.
283
+ */
284
+ class ContentTemplate {
285
+ /**
286
+ * @internal
287
+ */
288
+ constructor(contentTemplateResponse) {
289
+ this.sid = contentTemplateResponse.sid;
290
+ this.friendlyName = contentTemplateResponse.friendly_name;
291
+ this.variables = Object.entries(JSON.parse(contentTemplateResponse.variables)).map(([key, value]) => new ContentTemplateVariable(key, value));
292
+ this.variants = collectVariants(contentTemplateResponse.variants);
293
+ this.dateCreated = new Date(contentTemplateResponse.date_created);
294
+ this.dateUpdated = new Date(contentTemplateResponse.date_updated);
295
+ }
296
+ }
297
+
298
+ exports.ContentTemplate = ContentTemplate;
299
+ exports.ContentTemplateVariable = ContentTemplateVariable;
300
+ exports.parseVariant = parseVariant;
301
+ //# sourceMappingURL=content-template.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"content-template.js","sources":["../src/content-template.ts"],"sourcesContent":["import {\n ContentDataCallToActionResponse,\n ContentDataCardResponse,\n ContentDataListPickerResponse,\n ContentDataLocationResponse,\n ContentDataMediaResponse,\n ContentDataQuickReplyResponse,\n ContentDataTextResponse,\n ContentTemplateResponse,\n} from \"./interfaces/commands/content-templates-response\";\n\n/**\n * Shows a button that sends back a predefined text. Used in\n * {@link ContentDataQuickReply}.\n */\ntype ContentDataReply = {\n /**\n * Display value of the action. This is the message that will be sent back\n * when the user taps on the button.\n */\n readonly title: string;\n\n /**\n * Postback payload. This field is not visible to the end user.\n */\n readonly id?: string;\n};\n\n/**\n * Shows a button that redirects recipient to a predefined URL.\n */\ntype ContentDataActionUrl = {\n /**\n * The type discriminant.\n */\n readonly type: \"url\";\n\n /**\n * Display value for the action.\n */\n readonly title: string;\n\n /**\n * URL to direct to when the recipient taps the button.\n */\n readonly url: string;\n\n /**\n * Full data as a stringified JSON. This could be used for future content\n * types and fields which are not yet supported by the newest version of\n * the Conversations SDK, or for using newer types in the older versions of\n * the SDK.\n */\n readonly rawData: string;\n};\n\n/**\n * Shows a button that calls a phone number.\n */\ntype ContentDataActionPhone = {\n /**\n * The type discriminant.\n */\n readonly type: \"phone\";\n\n /**\n * Display value for the action.\n */\n readonly title: string;\n\n /**\n * Phone number to call when the recipient taps the button.\n */\n readonly phone: string;\n\n /**\n * Full data as a stringified JSON. This could be used for future content\n * types and fields which are not yet supported by the newest version of\n * the Conversations SDK, or for using newer types in the older versions of\n * the SDK.\n */\n readonly rawData: string;\n};\n\n/**\n * Shows a button that sends back a predefined text.\n */\ntype ContentDataActionReply = {\n /**\n * The type discriminant.\n */\n readonly type: \"reply\";\n\n /**\n * Display value for the action. This is the message that will be sent back\n * when the user taps on the button.\n */\n readonly title: string;\n\n /**\n * Postback payload. This field is not visible to the end user.\n */\n readonly id?: string;\n\n /**\n * Index for the action.\n */\n readonly index: number;\n\n /**\n * Full data as a stringified JSON. This could be used for future content\n * types and fields which are not yet supported by the newest version of\n * the Conversations SDK, or for using newer types in the older versions of\n * the SDK.\n */\n readonly rawData: string;\n};\n\n/**\n * Used for unknown action types which aren't present in the current version of\n * the Conversations SDK.\n */\ntype ContentDataActionOther = {\n /**\n * The type discriminant.\n */\n readonly type: \"other\";\n\n /**\n * Full data as a stringified JSON. This could be used for future content\n * types and fields which are not yet supported by the newest version of\n * the Conversations SDK, or for using newer types in the older versions of\n * the SDK.\n */\n readonly rawData: string;\n};\n\n/**\n * A union of possible actions used in {@link ContentDataCallToAction} and\n * {@link ContentDataCard}.\n */\ntype ContentDataAction =\n | ContentDataActionUrl\n | ContentDataActionPhone\n | ContentDataActionReply\n | ContentDataActionOther;\n\n/**\n * Represents an item in the {@link ContentDataListPicker}.\n */\ntype ContentDataListItem = {\n /**\n * Unique item identifier. Not visible to the recipient.\n */\n readonly id: string;\n\n /**\n * Display value of the item.\n */\n readonly item: string;\n\n /**\n * Description of the item.\n */\n readonly description?: string;\n};\n\n/**\n * Contains only the plain text-based content. Represents the twilio/text\n * content type.\n */\ntype ContentDataText = {\n /**\n * The type discriminant.\n */\n readonly type: \"text\";\n\n /**\n * The text of the message you want to send.\n */\n readonly body: string;\n\n /**\n * Full data as a stringified JSON. This could be used for future content\n * types and fields which are not yet supported by the newest version of\n * the Conversations SDK, or for using newer types in the older versions of\n * the SDK.\n */\n readonly rawData: string;\n};\n\n/**\n * Used to send file attachments, or to send long texts via MMS in the US and\n * Canada. Represents the twilio/media content type.\n */\ntype ContentDataMedia = {\n /**\n * The type discriminant.\n */\n readonly type: \"media\";\n\n /**\n * The text of the message you want to send.\n */\n readonly body?: string;\n\n /**\n * URLs of the media you want to send.\n */\n readonly media: string[];\n\n /**\n * Full data as a stringified JSON. This could be used for future content\n * types and fields which are not yet supported by the newest version of\n * the Conversations SDK, or for using newer types in the older versions of\n * the SDK.\n */\n readonly rawData: string;\n};\n\n/**\n * Contains a location pin and an optional label, which can be used to enhance\n * delivery notifications or connect recipients to physical experiences you\n * offer. Represents the twilio/location content type.\n */\ntype ContentDataLocation = {\n /**\n * The type discriminant.\n */\n readonly type: \"location\";\n\n /**\n * The longitude value of the location pin you want to send.\n */\n readonly longitude: number;\n\n /**\n * The latitude value of the location pin you want to send.\n */\n readonly latitude: number;\n\n /**\n * The label to be displayed to the end user alongside the location pin.\n */\n readonly label?: string;\n\n /**\n * Full data as a stringified JSON. This could be used for future content\n * types and fields which are not yet supported by the newest version of\n * the Conversations SDK, or for using newer types in the older versions of\n * the SDK.\n */\n readonly rawData: string;\n};\n\n/**\n * Let recipients tap, rather than type, to respond to the message. Represents\n * the twilio/quick-reply content type.\n */\ntype ContentDataQuickReply = {\n /**\n * The type discriminant.\n */\n readonly type: \"quickReply\";\n\n /**\n * The text of the message you want to send. This is included as a regular\n * text message.\n */\n readonly body: string;\n\n /**\n * Up to 3 buttons can be created for quick reply. See\n * {@link ContentDataReply}.\n */\n readonly replies: ContentDataReply[];\n\n /**\n * Full data as a stringified JSON. This could be used for future content\n * types and fields which are not yet supported by the newest version of\n * the Conversations SDK, or for using newer types in the older versions of\n * the SDK.\n */\n readonly rawData: string;\n};\n\n/**\n * Buttons that let recipients tap to trigger actions such as launching a\n * website or making a phone call. Represents the twilio/call-to-action content\n * type.\n */\ntype ContentDataCallToAction = {\n /**\n * The type discriminant.\n */\n readonly type: \"callToAction\";\n\n /**\n * The text of the message you want to send. This is included as a regular\n * text message.\n */\n readonly body: string;\n\n /**\n * Buttons that recipients can tap on to act on the message.\n */\n readonly actions: ContentDataAction[];\n\n /**\n * Full data as a stringified JSON. This could be used for future content\n * types and fields which are not yet supported by the newest version of\n * the Conversations SDK, or for using newer types in the older versions of\n * the SDK.\n */\n readonly rawData: string;\n};\n\n/**\n * Shows a menu of up to 10 options, which offers a simple way for users to make\n * a selection. Represents the twilio/list-picker content type.\n */\ntype ContentDataListPicker = {\n /**\n * The type discriminant.\n */\n readonly type: \"listPicker\";\n\n /**\n * The text of the message you want to send. This is rendered as the body of\n * the message.\n */\n readonly body: string;\n\n /**\n * Display value of the primary button.\n */\n readonly button: string;\n\n /**\n * List item objects displayed in the list. See {@link ContentDataListItem}.\n */\n readonly items: ContentDataListItem[];\n\n /**\n * Full data as a stringified JSON. This could be used for future content\n * types and fields which are not yet supported by the newest version of\n * the Conversations SDK, or for using newer types in the older versions of\n * the SDK.\n */\n readonly rawData: string;\n};\n\n/**\n * Shows a menu of up to 10 options, which offers a simple way for users to make\n * a selection. Represents the twilio/card content type.\n */\ntype ContentDataCard = {\n /**\n * The type discriminant.\n */\n readonly type: \"card\";\n\n /**\n * Title of the card.\n */\n readonly title: string;\n\n /**\n * Subtitle of the card.\n */\n readonly subtitle?: string;\n\n /**\n * URLs of the media to send with the message.\n */\n readonly media: string[];\n\n /**\n * Buttons that the recipients can tap on to act on the message.\n */\n readonly actions: ContentDataAction[];\n\n /**\n * Full data as a stringified JSON. This could be used for future content\n * types and fields which are not yet supported by the newest version of\n * the Conversations SDK, or for using newer types in the older versions of\n * the SDK.\n */\n readonly rawData: string;\n};\n\n/**\n * Used for unknown content types which aren't present in the current version of\n * the Conversations SDK.\n */\ntype ContentDataOther = {\n /**\n * The type discriminant.\n */\n readonly type: \"other\";\n\n /**\n * Full data as a stringified JSON. This could be used for future content\n * types and fields which are not yet supported by the newest version of\n * the Conversations SDK, or for using newer types in the older versions of\n * the SDK.\n */\n readonly rawData: string;\n};\n\n/**\n * A union of possible data types in rich content templates.\n */\ntype ContentData =\n | ContentDataText\n | ContentDataMedia\n | ContentDataLocation\n | ContentDataQuickReply\n | ContentDataCallToAction\n | ContentDataListPicker\n | ContentDataCard\n | ContentDataOther;\n\nconst collectActions = (\n actions: ContentDataCallToActionResponse[\"actions\"]\n): ContentDataAction[] => {\n return actions.map((action) => {\n const rawData = JSON.stringify(action);\n\n switch (action.type) {\n case \"QUICK_REPLY\":\n return {\n type: \"reply\",\n title: action.title,\n id: action.id ?? \"\",\n index: action.index ?? 0,\n rawData,\n };\n case \"PHONE_NUMBER\":\n return {\n type: \"phone\",\n title: action.title,\n phone: action.phone ?? \"\",\n rawData,\n };\n case \"URL\":\n return {\n type: \"url\",\n title: action.title,\n url: action.url ?? \"\",\n rawData,\n };\n default:\n return {\n type: \"other\",\n rawData,\n };\n }\n });\n};\n\nconst parseVariant = (type: string, data: unknown): ContentData => {\n const rawData = JSON.stringify(data);\n\n switch (type) {\n case \"twilio/text\": {\n const variant = data as ContentDataTextResponse;\n return {\n type: \"text\",\n body: variant.body,\n rawData,\n };\n }\n case \"twilio/media\": {\n const variant = data as ContentDataMediaResponse;\n return {\n type: \"media\",\n body: variant.body,\n media: variant.media,\n rawData,\n };\n }\n case \"twilio/location\": {\n const variant = data as ContentDataLocationResponse;\n return {\n type: \"location\",\n longitude: variant.longitude,\n latitude: variant.latitude,\n label: variant.label,\n rawData,\n };\n }\n case \"twilio/quick-reply\": {\n const variant = data as ContentDataQuickReplyResponse;\n return {\n type: \"quickReply\",\n body: variant.body,\n replies: variant.actions,\n rawData,\n };\n }\n case \"twilio/call-to-action\": {\n const variant = data as ContentDataCallToActionResponse;\n return {\n type: \"callToAction\",\n body: variant.body,\n actions: collectActions(variant.actions),\n rawData,\n };\n }\n case \"twilio/list-picker\": {\n const variant = data as ContentDataListPickerResponse;\n return {\n type: \"listPicker\",\n body: variant.body,\n button: variant.button,\n items: variant.items,\n rawData,\n };\n }\n case \"twilio/card\": {\n const variant = data as ContentDataCardResponse;\n return {\n type: \"card\",\n title: variant.title,\n subtitle: variant.subtitle,\n media: variant.media ?? [],\n actions: collectActions(variant.actions ?? []),\n rawData,\n };\n }\n default:\n return {\n type: \"other\",\n rawData,\n };\n }\n};\n\nconst collectVariants = (\n variants: ContentTemplateResponse[\"variants\"]\n): Map<string, ContentData> => {\n const variantsMap = new Map<string, ContentData>();\n\n for (const [key, value] of Object.entries(variants)) {\n variantsMap.set(key, parseVariant(key, value));\n }\n\n return variantsMap;\n};\n\n/**\n * Represents a variable for a content template. See\n * {@link ContentTemplate.variables}.\n */\nclass ContentTemplateVariable {\n public constructor(\n /**\n * Name of the variable.\n */\n public readonly name: string,\n\n /**\n * Key of the variable\n */\n public readonly value: string\n ) {}\n\n /**\n * Copies the variable with a new value.\n *\n * @param value The new value for the variable.\n */\n public copyWithValue(value: string) {\n return new ContentTemplateVariable(this.name, value);\n }\n}\n\n/**\n * A rich content template.\n *\n * Use {@Link Client.getContentTemplates} to request all the templates available\n * for the current account.\n */\nclass ContentTemplate {\n /**\n * The server-assigned unique identifier for the template.\n */\n public readonly sid: string;\n\n /**\n * Friendly name used to describe the content. Not visible to the recipient.\n */\n public readonly friendlyName: string;\n\n /**\n * Variables used by this template.\n */\n public readonly variables: ContentTemplateVariable[];\n\n /**\n * Variants of the content. See @{link ContentData}.\n */\n public readonly variants: Map<string, ContentData>;\n\n /**\n * Date of creation.\n */\n public readonly dateCreated: Date;\n\n /**\n * Date of the last update.\n */\n public readonly dateUpdated: Date;\n\n /**\n * @internal\n */\n public constructor(contentTemplateResponse: ContentTemplateResponse) {\n this.sid = contentTemplateResponse.sid;\n this.friendlyName = contentTemplateResponse.friendly_name;\n this.variables = Object.entries(\n JSON.parse(contentTemplateResponse.variables) as Record<string, string>\n ).map(([key, value]) => new ContentTemplateVariable(key, value));\n this.variants = collectVariants(contentTemplateResponse.variants);\n this.dateCreated = new Date(contentTemplateResponse.date_created);\n this.dateUpdated = new Date(contentTemplateResponse.date_updated);\n }\n}\n\nexport {\n ContentDataActionUrl,\n ContentDataActionPhone,\n ContentDataActionReply,\n ContentDataActionOther,\n ContentDataAction,\n ContentDataText,\n ContentDataMedia,\n ContentDataLocation,\n ContentDataReply,\n ContentDataQuickReply,\n ContentDataCallToAction,\n ContentDataListPicker,\n ContentDataListItem,\n ContentDataCard,\n ContentDataOther,\n ContentData,\n ContentTemplate,\n ContentTemplateVariable,\n parseVariant,\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuaA,MAAM,cAAc,GAAG,CACrB,OAAmD,KAC5B;AACvB,IAAA,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,KAAI;;QAC5B,MAAM,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;QAEvC,QAAQ,MAAM,CAAC,IAAI;AACjB,YAAA,KAAK,aAAa;gBAChB,OAAO;AACL,oBAAA,IAAI,EAAE,OAAO;oBACb,KAAK,EAAE,MAAM,CAAC,KAAK;AACnB,oBAAA,EAAE,EAAE,CAAA,EAAA,GAAA,MAAM,CAAC,EAAE,mCAAI,EAAE;AACnB,oBAAA,KAAK,EAAE,CAA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AAC,CAAC,GAAG,EAAE,KAAK,CAAC,KAAK,IAAI,uBAAuB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC;QACjE,IAAI,CAAC,QAAQ,GAAG,eAAe,CAAC,uBAAuB,CAAC,QAAQ,CAAC,CAAC;QAClE,IAAI,CAAC,WAAW,GAAG,IAAI,IAAI,CAAC,uBAAuB,CAAC,YAAY,CAAC,CAAC;QAClE,IAAI,CAAC,WAAW,GAAG,IAAI,IAAI,CAAC,uBAAuB,CAAC,YAAY,CAAC,CAAC;KACnE;AACF;;;;;;"}
@@ -255,6 +255,10 @@ class Messages extends replayEventEmitter.ReplayEventEmitter {
255
255
  attributes: typeof message.attributes !== "undefined"
256
256
  ? JSON.stringify(message.attributes)
257
257
  : undefined,
258
+ content_sid: message.contentSid,
259
+ content_variables: typeof message.contentVariables !== "undefined"
260
+ ? JSON.stringify(message.contentVariables.reduce((accum, current) => (Object.assign(Object.assign({}, accum), { [current.name]: current.value })), {}))
261
+ : undefined,
258
262
  });
259
263
  try {
260
264
  resolve(await messagesPostRequest);
@@ -1 +1 @@
1
- {"version":3,"file":"messages.js","sources":["../../src/data/messages.ts"],"sourcesContent":["import { Logger } from \"../logger\";\n\nimport {\n Message,\n MessageData,\n MessageUpdatedEventArgs,\n MessageUpdateReason,\n} from \"../message\";\nimport {\n Conversation,\n SendEmailOptions,\n SendMediaOptions,\n} from \"../conversation\";\nimport { UnsentMessage } from \"../unsent-message\";\n\nimport { SyncList, SyncClient } from \"twilio-sync\";\nimport { SyncPaginator } from \"../sync-paginator\";\n\nimport { McsClient, McsMedia, CancellablePromise } from \"@twilio/mcs-client\";\nimport { Network } from \"../services/network\";\nimport { Configuration } from \"../configuration\";\nimport { CommandExecutor } from \"../command-executor\";\nimport { SendMessageRequest } from \"../interfaces/commands/send-message\";\nimport { MessageResponse } from \"../interfaces/commands/message-response\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport { JSONValue } from \"../types\";\n\ntype MessagesEvents = {\n messageAdded: (message: Message) => void;\n messageRemoved: (message: Message) => void;\n messageUpdated: (data: {\n message: Message;\n updateReasons: MessageUpdateReason[];\n }) => void;\n};\n\nconst log = Logger.scope(\"Messages\");\n\nexport interface MessagesServices {\n mcsClient: McsClient;\n network: Network;\n syncClient: SyncClient;\n commandExecutor: CommandExecutor;\n}\n\n/**\n * Represents the collection of messages in a conversation\n */\nclass Messages extends ReplayEventEmitter<MessagesEvents> {\n public readonly conversation: Conversation;\n private readonly configuration: Configuration;\n private readonly services: MessagesServices;\n private readonly messagesByIndex: Map<number, Message>;\n private messagesListPromise: Promise<SyncList> | null;\n\n public constructor(\n conversation: Conversation,\n configuration: Configuration,\n services: MessagesServices\n ) {\n super();\n\n this.conversation = conversation;\n this.configuration = configuration;\n this.services = services;\n\n this.messagesByIndex = new Map();\n this.messagesListPromise = null;\n }\n\n /**\n * Subscribe to the Messages Event Stream\n * @param arg - Name of the Sync object, or the SyncList itself, that\n * represents the Messages resource.\n */\n public async subscribe(arg: string | SyncList) {\n if (this.messagesListPromise) {\n return this.messagesListPromise;\n }\n\n this.messagesListPromise =\n typeof arg === \"string\"\n ? this.services.syncClient.list({\n id: arg,\n mode: \"open_existing\",\n })\n : Promise.resolve(arg);\n\n try {\n const list = await this.messagesListPromise;\n\n list.on(\"itemAdded\", (args) => {\n log.debug(`${this.conversation.sid} itemAdded: ${args.item.index}`);\n\n const links = {\n self: `${this.conversation._links.messages}/${args.item.data.sid}`,\n conversation: this.conversation._links.self,\n messages_receipts: `${this.conversation._links.messages}/${args.item.data.sid}/Receipts`,\n };\n const message = new Message(\n args.item.index,\n args.item.data,\n this.conversation,\n links,\n this.configuration,\n this.services\n );\n\n if (this.messagesByIndex.has(message.index)) {\n log.debug(\n \"Message arrived, but is already known and ignored\",\n this.conversation.sid,\n message.index\n );\n return;\n }\n\n this.messagesByIndex.set(message.index, message);\n\n message.on(\"updated\", (args: MessageUpdatedEventArgs) =>\n this.emit(\"messageUpdated\", args)\n );\n\n this.emit(\"messageAdded\", message);\n });\n\n list.on(\"itemRemoved\", (args) => {\n log.debug(`#{this.conversation.sid} itemRemoved: ${args.index}`);\n\n const index = args.index;\n\n if (this.messagesByIndex.has(index)) {\n const message = this.messagesByIndex.get(index);\n if (!message) {\n return;\n }\n\n this.messagesByIndex.delete(message.index);\n message.removeAllListeners(\"updated\");\n this.emit(\"messageRemoved\", message);\n }\n });\n\n list.on(\"itemUpdated\", (args) => {\n log.debug(`${this.conversation.sid} itemUpdated: ${args.item.index}`);\n\n const message = this.messagesByIndex.get(args.item.index);\n\n if (message) {\n message._update(args.item.data);\n }\n });\n\n return list;\n } catch (err) {\n this.messagesListPromise = null;\n\n if (this.services.syncClient.connectionState !== \"disconnected\") {\n log.error(\n \"Failed to get messages object for conversation\",\n this.conversation.sid,\n err\n );\n }\n\n log.debug(\n \"ERROR: Failed to get messages object for conversation\",\n this.conversation.sid,\n err\n );\n\n throw err;\n }\n }\n\n public async unsubscribe() {\n if (!this.messagesListPromise) {\n return;\n }\n\n const entity = await this.messagesListPromise;\n entity.close();\n this.messagesListPromise = null;\n }\n\n /**\n * Send a message to the conversation. The message could include text and multiple media attachments.\n * @param message Message to post\n */\n public sendV2(message: UnsentMessage): CancellablePromise<MessageResponse> {\n log.debug(\n \"Sending message V2\",\n message.mediaContent,\n message.attributes,\n message.emailOptions\n );\n\n return new CancellablePromise(async (resolve, reject, onCancel) => {\n const media: McsMedia[] = [];\n const requests: CancellablePromise<McsMedia>[] = [];\n\n onCancel(() => {\n requests.forEach((request) => request.cancel());\n });\n\n for (const [category, mediaContent] of message.mediaContent) {\n try {\n log.debug(\n `Adding media to a message as ${\n mediaContent instanceof FormData ? \"FormData\" : \"SendMediaOptions\"\n }`,\n mediaContent\n );\n\n const request =\n mediaContent instanceof FormData\n ? this.services.mcsClient.postFormData(mediaContent, category)\n : this.services.mcsClient.post(\n mediaContent.contentType ?? \"\",\n mediaContent.media ?? \"\",\n category,\n mediaContent.filename\n );\n\n requests.push(request);\n\n media.push(await request);\n } catch (e) {\n reject(e);\n return;\n }\n }\n\n const messagesPostRequest = this.services.commandExecutor.mutateResource<\n SendMessageRequest,\n MessageResponse\n >(\"post\", this.conversation._links.messages, {\n body: message.text,\n subject: message.emailOptions?.subject,\n media_sids: media.map((m) => m.sid),\n attributes:\n typeof message.attributes !== \"undefined\"\n ? JSON.stringify(message.attributes)\n : undefined,\n });\n\n try {\n resolve(await messagesPostRequest);\n } catch (e) {\n reject(e);\n }\n });\n }\n\n /**\n * Send Message to the conversation\n * @param message Message to post\n * @param attributes Message attributes\n * @param emailOptions Options that modify E-mail integration behaviors.\n * @returns Returns promise which can fail\n */\n public async send(\n message: null | string | FormData | SendMediaOptions,\n attributes: JSONValue = {},\n emailOptions?: SendEmailOptions\n ): Promise<MessageResponse> {\n log.debug(\"Sending text message\", message, attributes, emailOptions);\n\n return this.services.commandExecutor.mutateResource<\n SendMessageRequest,\n MessageResponse\n >(\"post\", this.conversation._links.messages, {\n body: message ?? \"\",\n attributes:\n typeof attributes !== \"undefined\"\n ? JSON.stringify(attributes)\n : undefined,\n subject: emailOptions?.subject,\n });\n }\n\n /**\n * Send Media Message to the conversation\n * @param mediaContent Media content to post\n * @param attributes Message attributes\n * @param emailOptions Email options\n * @returns Returns promise which can fail\n */\n public async sendMedia(\n mediaContent: FormData | SendMediaOptions,\n attributes: JSONValue = {},\n emailOptions?: SendEmailOptions\n ) {\n log.debug(\"Sending media message\", mediaContent, attributes, emailOptions);\n log.debug(\n `Sending media message as ${\n mediaContent instanceof FormData ? \"FormData\" : \"SendMediaOptions\"\n }`,\n mediaContent,\n attributes\n );\n\n const media: McsMedia =\n mediaContent instanceof FormData\n ? await this.services.mcsClient.postFormData(mediaContent)\n : await this.services.mcsClient.post(\n mediaContent.contentType ?? \"\",\n mediaContent.media ?? \"\",\n \"media\",\n mediaContent.filename\n );\n\n // emailOptions are currently ignored for media messages.\n return await this.services.commandExecutor.mutateResource<\n SendMessageRequest,\n MessageResponse\n >(\"post\", this.conversation._links.messages, {\n media_sids: [media.sid],\n attributes:\n typeof attributes !== \"undefined\"\n ? JSON.stringify(attributes)\n : undefined,\n });\n }\n\n /**\n * Returns messages from conversation using paginator interface\n * @param pageSize Number of messages to return in single chunk. By default it's 30.\n * @param anchor Most early message id which is already known, or 'end' by default\n * @param direction Pagination order 'backwards' or 'forward', 'forward' by default\n * @returns Last page of messages by default\n */\n public async getMessages(\n pageSize: number | undefined,\n anchor: number | \"end\" | undefined,\n direction: \"forward\" | \"backwards\" = \"backwards\"\n ): Promise<SyncPaginator<Message>> {\n return this._getMessages(pageSize, anchor, direction);\n }\n\n private _wrapPaginator(order, page, op) {\n // Due to an inconsistency between Sync and Chat conventions, next and\n // previous pages should be swapped.\n const shouldReverse = order === \"desc\";\n\n const nextPage = () =>\n page.nextPage().then((page) => this._wrapPaginator(order, page, op));\n const previousPage = () =>\n page.prevPage().then((page) => this._wrapPaginator(order, page, op));\n\n return op(page.items).then((items) => ({\n items: items.sort((x, y) => {\n return x.index - y.index;\n }),\n hasPrevPage: shouldReverse ? page.hasNextPage : page.hasPrevPage,\n hasNextPage: shouldReverse ? page.hasPrevPage : page.hasNextPage,\n prevPage: shouldReverse ? nextPage : previousPage,\n nextPage: shouldReverse ? previousPage : nextPage,\n }));\n }\n\n private _upsertMessage(index: number, value: MessageData) {\n const cachedMessage = this.messagesByIndex.get(index);\n\n if (cachedMessage) {\n return cachedMessage;\n }\n\n const links = {\n self: `${this.conversation._links.messages}/${value.sid}`,\n conversation: this.conversation._links.self,\n messages_receipts: `${this.conversation._links.messages}/${value.sid}/Receipts`,\n };\n const message = new Message(\n index,\n value,\n this.conversation,\n links,\n this.configuration,\n this.services\n );\n\n this.messagesByIndex.set(message.index, message);\n\n message.on(\"updated\", (args: MessageUpdatedEventArgs) =>\n this.emit(\"messageUpdated\", args)\n );\n\n return message;\n }\n\n /**\n * Returns last messages from conversation\n * @param {Number} [pageSize] Number of messages to return in single chunk. By default it's 30.\n * @param {String} [anchor] Most early message id which is already known, or 'end' by default\n * @param {String} [direction] Pagination order 'backwards' or 'forward', or 'forward' by default\n * @returns {Promise<SyncPaginator<Message>>} last page of messages by default\n * @private\n */\n private async _getMessages(\n pageSize = 30,\n anchor: number | \"end\" = \"end\",\n direction: \"forward\" | \"backwards\" = \"forward\"\n ): Promise<SyncPaginator<Message>> {\n const order = direction === \"backwards\" ? \"desc\" : \"asc\";\n const list = await this.messagesListPromise;\n const page = await list?.getItems({\n from: anchor !== \"end\" ? anchor : void 0,\n pageSize,\n order,\n limit: pageSize, // @todo Limit equals pageSize by default in Sync. This is probably not ideal.\n });\n\n return await this._wrapPaginator(order, page, (items) =>\n Promise.all(\n items.map((item) => this._upsertMessage(item.index, item.data))\n )\n );\n }\n}\n\nexport { Messages };\n"],"names":["Logger","ReplayEventEmitter","message","Message","CancellablePromise"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,GAAG,GAAGA,aAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;AASrC;;AAEG;AACH,MAAM,QAAS,SAAQC,qCAAkC,CAAA;AAOvD,IAAA,WAAA,CACE,YAA0B,EAC1B,aAA4B,EAC5B,QAA0B,EAAA;AAE1B,QAAA,KAAK,EAAE,CAAC;AAER,QAAA,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;AACjC,QAAA,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;AACnC,QAAA,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;AAEzB,QAAA,IAAI,CAAC,eAAe,GAAG,IAAI,GAAG,EAAE,CAAC;AACjC,QAAA,IAAI,CAAC,mBAAmB,GAAG,IAAI,CAAC;KACjC;AAED;;;;AAIG;IACI,MAAM,SAAS,CAAC,GAAsB,EAAA;QAC3C,I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MAAM,IAAI,CAAC,mBAAmB,CAAC;QAC5C,MAAM,IAAI,GAAG,OAAM,IAAI,KAAJ,IAAA,IAAA,IAAI,KAAJ,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,IAAI,CAAE,QAAQ,CAAC;AAChC,YAAA,IAAI,EAAE,MAAM,KAAK,KAAK,GAAG,MAAM,GAAG,KAAK,CAAC;YACxC,QAAQ;YACR,KAAK;YACL,KAAK,EAAE,QAAQ;AAChB,SAAA,CAAC,CAAA,CAAC;AAEH,QAAA,OAAO,MAAM,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,KAAK,KAClD,OAAO,CAAC,GAAG,CACT,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAChE,CACF,CAAC;KACH;AACF;;;;"}
1
+ {"version":3,"file":"messages.js","sources":["../../src/data/messages.ts"],"sourcesContent":["import { Logger } from \"../logger\";\n\nimport {\n Message,\n MessageData,\n MessageUpdatedEventArgs,\n MessageUpdateReason,\n} from \"../message\";\nimport {\n Conversation,\n SendEmailOptions,\n SendMediaOptions,\n} from \"../conversation\";\nimport { UnsentMessage } from \"../unsent-message\";\n\nimport { SyncList, SyncClient } from \"twilio-sync\";\nimport { SyncPaginator } from \"../sync-paginator\";\n\nimport { McsClient, McsMedia, CancellablePromise } from \"@twilio/mcs-client\";\nimport { Network } from \"../services/network\";\nimport { Configuration } from \"../configuration\";\nimport { CommandExecutor } from \"../command-executor\";\nimport { SendMessageRequest } from \"../interfaces/commands/send-message\";\nimport { MessageResponse } from \"../interfaces/commands/message-response\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport { JSONValue } from \"../types\";\n\ntype MessagesEvents = {\n messageAdded: (message: Message) => void;\n messageRemoved: (message: Message) => void;\n messageUpdated: (data: {\n message: Message;\n updateReasons: MessageUpdateReason[];\n }) => void;\n};\n\nconst log = Logger.scope(\"Messages\");\n\nexport interface MessagesServices {\n mcsClient: McsClient;\n network: Network;\n syncClient: SyncClient;\n commandExecutor: CommandExecutor;\n}\n\n/**\n * Represents the collection of messages in a conversation\n */\nclass Messages extends ReplayEventEmitter<MessagesEvents> {\n public readonly conversation: Conversation;\n private readonly configuration: Configuration;\n private readonly services: MessagesServices;\n private readonly messagesByIndex: Map<number, Message>;\n private messagesListPromise: Promise<SyncList> | null;\n\n public constructor(\n conversation: Conversation,\n configuration: Configuration,\n services: MessagesServices\n ) {\n super();\n\n this.conversation = conversation;\n this.configuration = configuration;\n this.services = services;\n\n this.messagesByIndex = new Map();\n this.messagesListPromise = null;\n }\n\n /**\n * Subscribe to the Messages Event Stream\n * @param arg - Name of the Sync object, or the SyncList itself, that\n * represents the Messages resource.\n */\n public async subscribe(arg: string | SyncList) {\n if (this.messagesListPromise) {\n return this.messagesListPromise;\n }\n\n this.messagesListPromise =\n typeof arg === \"string\"\n ? this.services.syncClient.list({\n id: arg,\n mode: \"open_existing\",\n })\n : Promise.resolve(arg);\n\n try {\n const list = await this.messagesListPromise;\n\n list.on(\"itemAdded\", (args) => {\n log.debug(`${this.conversation.sid} itemAdded: ${args.item.index}`);\n\n const links = {\n self: `${this.conversation._links.messages}/${args.item.data.sid}`,\n conversation: this.conversation._links.self,\n messages_receipts: `${this.conversation._links.messages}/${args.item.data.sid}/Receipts`,\n };\n const message = new Message(\n args.item.index,\n args.item.data,\n this.conversation,\n links,\n this.configuration,\n this.services\n );\n\n if (this.messagesByIndex.has(message.index)) {\n log.debug(\n \"Message arrived, but is already known and ignored\",\n this.conversation.sid,\n message.index\n );\n return;\n }\n\n this.messagesByIndex.set(message.index, message);\n\n message.on(\"updated\", (args: MessageUpdatedEventArgs) =>\n this.emit(\"messageUpdated\", args)\n );\n\n this.emit(\"messageAdded\", message);\n });\n\n list.on(\"itemRemoved\", (args) => {\n log.debug(`#{this.conversation.sid} itemRemoved: ${args.index}`);\n\n const index = args.index;\n\n if (this.messagesByIndex.has(index)) {\n const message = this.messagesByIndex.get(index);\n if (!message) {\n return;\n }\n\n this.messagesByIndex.delete(message.index);\n message.removeAllListeners(\"updated\");\n this.emit(\"messageRemoved\", message);\n }\n });\n\n list.on(\"itemUpdated\", (args) => {\n log.debug(`${this.conversation.sid} itemUpdated: ${args.item.index}`);\n\n const message = this.messagesByIndex.get(args.item.index);\n\n if (message) {\n message._update(args.item.data);\n }\n });\n\n return list;\n } catch (err) {\n this.messagesListPromise = null;\n\n if (this.services.syncClient.connectionState !== \"disconnected\") {\n log.error(\n \"Failed to get messages object for conversation\",\n this.conversation.sid,\n err\n );\n }\n\n log.debug(\n \"ERROR: Failed to get messages object for conversation\",\n this.conversation.sid,\n err\n );\n\n throw err;\n }\n }\n\n public async unsubscribe() {\n if (!this.messagesListPromise) {\n return;\n }\n\n const entity = await this.messagesListPromise;\n entity.close();\n this.messagesListPromise = null;\n }\n\n /**\n * Send a message to the conversation. The message could include text and multiple media attachments.\n * @param message Message to post\n */\n public sendV2(message: UnsentMessage): CancellablePromise<MessageResponse> {\n log.debug(\n \"Sending message V2\",\n message.mediaContent,\n message.attributes,\n message.emailOptions\n );\n\n return new CancellablePromise(async (resolve, reject, onCancel) => {\n const media: McsMedia[] = [];\n const requests: CancellablePromise<McsMedia>[] = [];\n\n onCancel(() => {\n requests.forEach((request) => request.cancel());\n });\n\n for (const [category, mediaContent] of message.mediaContent) {\n try {\n log.debug(\n `Adding media to a message as ${\n mediaContent instanceof FormData ? \"FormData\" : \"SendMediaOptions\"\n }`,\n mediaContent\n );\n\n const request =\n mediaContent instanceof FormData\n ? this.services.mcsClient.postFormData(mediaContent, category)\n : this.services.mcsClient.post(\n mediaContent.contentType ?? \"\",\n mediaContent.media ?? \"\",\n category,\n mediaContent.filename\n );\n\n requests.push(request);\n\n media.push(await request);\n } catch (e) {\n reject(e);\n return;\n }\n }\n\n const messagesPostRequest = this.services.commandExecutor.mutateResource<\n SendMessageRequest,\n MessageResponse\n >(\"post\", this.conversation._links.messages, {\n body: message.text,\n subject: message.emailOptions?.subject,\n media_sids: media.map((m) => m.sid),\n attributes:\n typeof message.attributes !== \"undefined\"\n ? JSON.stringify(message.attributes)\n : undefined,\n content_sid: message.contentSid,\n content_variables:\n typeof message.contentVariables !== \"undefined\"\n ? JSON.stringify(\n message.contentVariables.reduce<Record<string, string>>(\n (accum, current) => ({\n ...accum,\n [current.name]: current.value,\n }),\n {}\n )\n )\n : undefined,\n });\n\n try {\n resolve(await messagesPostRequest);\n } catch (e) {\n reject(e);\n }\n });\n }\n\n /**\n * Send Message to the conversation\n * @param message Message to post\n * @param attributes Message attributes\n * @param emailOptions Options that modify E-mail integration behaviors.\n * @returns Returns promise which can fail\n */\n public async send(\n message: null | string | FormData | SendMediaOptions,\n attributes: JSONValue = {},\n emailOptions?: SendEmailOptions\n ): Promise<MessageResponse> {\n log.debug(\"Sending text message\", message, attributes, emailOptions);\n\n return this.services.commandExecutor.mutateResource<\n SendMessageRequest,\n MessageResponse\n >(\"post\", this.conversation._links.messages, {\n body: message ?? \"\",\n attributes:\n typeof attributes !== \"undefined\"\n ? JSON.stringify(attributes)\n : undefined,\n subject: emailOptions?.subject,\n });\n }\n\n /**\n * Send Media Message to the conversation\n * @param mediaContent Media content to post\n * @param attributes Message attributes\n * @param emailOptions Email options\n * @returns Returns promise which can fail\n */\n public async sendMedia(\n mediaContent: FormData | SendMediaOptions,\n attributes: JSONValue = {},\n emailOptions?: SendEmailOptions\n ) {\n log.debug(\"Sending media message\", mediaContent, attributes, emailOptions);\n log.debug(\n `Sending media message as ${\n mediaContent instanceof FormData ? \"FormData\" : \"SendMediaOptions\"\n }`,\n mediaContent,\n attributes\n );\n\n const media: McsMedia =\n mediaContent instanceof FormData\n ? await this.services.mcsClient.postFormData(mediaContent)\n : await this.services.mcsClient.post(\n mediaContent.contentType ?? \"\",\n mediaContent.media ?? \"\",\n \"media\",\n mediaContent.filename\n );\n\n // emailOptions are currently ignored for media messages.\n return await this.services.commandExecutor.mutateResource<\n SendMessageRequest,\n MessageResponse\n >(\"post\", this.conversation._links.messages, {\n media_sids: [media.sid],\n attributes:\n typeof attributes !== \"undefined\"\n ? JSON.stringify(attributes)\n : undefined,\n });\n }\n\n /**\n * Returns messages from conversation using paginator interface\n * @param pageSize Number of messages to return in single chunk. By default it's 30.\n * @param anchor Most early message id which is already known, or 'end' by default\n * @param direction Pagination order 'backwards' or 'forward', 'forward' by default\n * @returns Last page of messages by default\n */\n public async getMessages(\n pageSize: number | undefined,\n anchor: number | \"end\" | undefined,\n direction: \"forward\" | \"backwards\" = \"backwards\"\n ): Promise<SyncPaginator<Message>> {\n return this._getMessages(pageSize, anchor, direction);\n }\n\n private _wrapPaginator(order, page, op) {\n // Due to an inconsistency between Sync and Chat conventions, next and\n // previous pages should be swapped.\n const shouldReverse = order === \"desc\";\n\n const nextPage = () =>\n page.nextPage().then((page) => this._wrapPaginator(order, page, op));\n const previousPage = () =>\n page.prevPage().then((page) => this._wrapPaginator(order, page, op));\n\n return op(page.items).then((items) => ({\n items: items.sort((x, y) => {\n return x.index - y.index;\n }),\n hasPrevPage: shouldReverse ? page.hasNextPage : page.hasPrevPage,\n hasNextPage: shouldReverse ? page.hasPrevPage : page.hasNextPage,\n prevPage: shouldReverse ? nextPage : previousPage,\n nextPage: shouldReverse ? previousPage : nextPage,\n }));\n }\n\n private _upsertMessage(index: number, value: MessageData) {\n const cachedMessage = this.messagesByIndex.get(index);\n\n if (cachedMessage) {\n return cachedMessage;\n }\n\n const links = {\n self: `${this.conversation._links.messages}/${value.sid}`,\n conversation: this.conversation._links.self,\n messages_receipts: `${this.conversation._links.messages}/${value.sid}/Receipts`,\n };\n const message = new Message(\n index,\n value,\n this.conversation,\n links,\n this.configuration,\n this.services\n );\n\n this.messagesByIndex.set(message.index, message);\n\n message.on(\"updated\", (args: MessageUpdatedEventArgs) =>\n this.emit(\"messageUpdated\", args)\n );\n\n return message;\n }\n\n /**\n * Returns last messages from conversation\n * @param {Number} [pageSize] Number of messages to return in single chunk. By default it's 30.\n * @param {String} [anchor] Most early message id which is already known, or 'end' by default\n * @param {String} [direction] Pagination order 'backwards' or 'forward', or 'forward' by default\n * @returns {Promise<SyncPaginator<Message>>} last page of messages by default\n * @private\n */\n private async _getMessages(\n pageSize = 30,\n anchor: number | \"end\" = \"end\",\n direction: \"forward\" | \"backwards\" = \"forward\"\n ): Promise<SyncPaginator<Message>> {\n const order = direction === \"backwards\" ? \"desc\" : \"asc\";\n const list = await this.messagesListPromise;\n const page = await list?.getItems({\n from: anchor !== \"end\" ? anchor : void 0,\n pageSize,\n order,\n limit: pageSize, // @todo Limit equals pageSize by default in Sync. This is probably not ideal.\n });\n\n return await this._wrapPaginator(order, page, (items) =>\n Promise.all(\n items.map((item) => this._upsertMessage(item.index, item.data))\n )\n );\n }\n}\n\nexport { Messages };\n"],"names":["Logger","ReplayEventEmitter","message","Message","CancellablePromise"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,GAAG,GAAGA,aAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;AASrC;;AAEG;AACH,MAAM,QAAS,SAAQC,qCAAkC,CAAA;AAOvD,IAAA,WAAA,CACE,YAA0B,EAC1B,aAA4B,EAC5B,QAA0B,EAAA;AAE1B,QAAA,KAAK,EAAE,CAAC;AAER,QAAA,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;AACjC,QAAA,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;AACnC,QAAA,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;AAEzB,QAAA,IAAI,CAAC,eAAe,GAAG,IAAI,GAAG,EAAE,CAAC;AACjC,QAAA,IAAI,CAAC,mBAAmB,GAAG,IAAI,CAAC;KACjC;A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AAC,GAAG,CAACD,SAAO,CAAC,KAAK,EAAEA,SAAO,CAAC,CAAC;AAEjD,QAAAA,SAAO,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,IAA6B,KAClD,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,IAAI,CAAC,CAClC,CAAC;AAEF,QAAA,OAAOA,SAAO,CAAC;KAChB;AAED;;;;;;;AAOG;IACK,MAAM,YAAY,CACxB,QAAQ,GAAG,EAAE,EACb,MAAyB,GAAA,KAAK,EAC9B,SAAA,GAAqC,SAAS,EAAA;AAE9C,QAAA,MAAM,KAAK,GAAG,SAAS,KAAK,WAAW,GAAG,MAAM,GAAG,KAAK,CAAC;AACzD,QAAA,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,mBAAmB,CAAC;QAC5C,MAAM,IAAI,GAAG,OAAM,IAAI,KAAJ,IAAA,IAAA,IAAI,KAAJ,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,IAAI,CAAE,QAAQ,CAAC;AAChC,YAAA,IAAI,EAAE,MAAM,KAAK,KAAK,GAAG,MAAM,GAAG,KAAK,CAAC;YACxC,QAAQ;YACR,KAAK;YACL,KAAK,EAAE,QAAQ;AAChB,SAAA,CAAC,CAAA,CAAC;AAEH,QAAA,OAAO,MAAM,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,KAAK,KAClD,OAAO,CAAC,GAAG,CACT,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAChE,CACF,CAAC;KACH;AACF;;;;"}
package/dist/index.js CHANGED
@@ -144,6 +144,7 @@ var unsentMessage = require('./unsent-message.js');
144
144
  var user = require('./user.js');
145
145
  var pushNotification = require('./push-notification.js');
146
146
  var notificationTypes = require('./interfaces/notification-types.js');
147
+ var contentTemplate = require('./content-template.js');
147
148
 
148
149
 
149
150
 
@@ -167,4 +168,6 @@ exports.UnsentMessage = unsentMessage.UnsentMessage;
167
168
  exports.User = user.User;
168
169
  exports.PushNotification = pushNotification.PushNotification;
169
170
  exports.NotificationTypes = notificationTypes.NotificationTypes;
171
+ exports.ContentTemplate = contentTemplate.ContentTemplate;
172
+ exports.ContentTemplateVariable = contentTemplate.ContentTemplateVariable;
170
173
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -199,6 +199,25 @@ class MessageBuilder {
199
199
  this.emailHistories.set(contentType, history);
200
200
  return this;
201
201
  }
202
+ /**
203
+ * Adds {@link ContentTemplate} SID for the message alongside optional
204
+ * variables. When no variables provided, the default values will be used.
205
+ *
206
+ * Adding the content SID converts the message to a rich message. In this
207
+ * case, other fields are ignored and the message is sent using the content
208
+ * from the the {@link ContentTemplate}.
209
+ *
210
+ * Use {@link Client.getContentTemplates} to request all available
211
+ * {@link ContentTemplate}s.
212
+ *
213
+ * @param contentSid SID of the {@link ContentTemplate}
214
+ * @param variables Custom variables to resolve the template.
215
+ */
216
+ setContentTemplate(contentSid, contentVariables = []) {
217
+ this.message.contentSid = contentSid;
218
+ this.message.contentVariables = contentVariables;
219
+ return this;
220
+ }
202
221
  /**
203
222
  * Adds media to the message.
204
223
  * @param payload Media to add.
@@ -1 +1 @@
1
- {"version":3,"file":"message-builder.js","sources":["../src/message-builder.ts"],"sourcesContent":["import { CancellablePromise } from \"@twilio/mcs-client\";\nimport { ConversationLimits } from \"./interfaces/conversation-limits\";\nimport { SendMediaOptions } from \"./conversation\";\nimport { UnsentMessage } from \"./unsent-message\";\nimport { JSONValue } from \"./types\";\nimport { Messages } from \"./data/messages\";\n\n/**\n * Message builder. Allows the message to be built and sent via method chaining.\n *\n * Example:\n *\n * ```ts\n * await testConversation.prepareMessage()\n * .setBody('Hello!')\n * .setAttributes({foo: 'bar'})\n * .addMedia(media1)\n * .addMedia(media2)\n * .build()\n * .send();\n * ```\n */\nclass MessageBuilder {\n private readonly message: UnsentMessage;\n private emailBodies: Map<string, FormData | SendMediaOptions>;\n private emailHistories: Map<string, FormData | SendMediaOptions>;\n\n /**\n * @internal\n */\n constructor(\n private readonly limits: ConversationLimits,\n messagesEntity: Messages\n ) {\n this.message = new UnsentMessage(messagesEntity);\n this.emailBodies = new Map<string, FormData | SendMediaOptions>();\n this.emailHistories = new Map<string, FormData | SendMediaOptions>();\n }\n\n /**\n * Sets the message body.\n * @param text Contents of the body.\n */\n setBody(text: string): MessageBuilder {\n this.message.text = text;\n return this;\n }\n\n /**\n * Sets the message subject.\n * @param subject Contents of the subject.\n */\n setSubject(subject: string): MessageBuilder {\n this.message.emailOptions.subject = subject;\n return this;\n }\n\n /**\n * Sets the message attributes.\n * @param attributes Message attributes.\n */\n setAttributes(attributes: JSONValue): MessageBuilder {\n this.message.attributes = attributes;\n return this;\n }\n\n /**\n * Set the email body with a given content type.\n * @param contentType Format of the body to set (text/plain or text/html).\n * @param body Body payload in the selected format.\n */\n setEmailBody(\n contentType: string,\n body: FormData | SendMediaOptions\n ): MessageBuilder {\n this.emailBodies.set(contentType, body);\n return this;\n }\n\n /**\n * Set the email history with a given content type.\n * @param contentType Format of the history to set (text/plain or text/html).\n * @param history History payload in the selected format.\n */\n setEmailHistory(\n contentType: string,\n history: FormData | SendMediaOptions\n ): MessageBuilder {\n this.emailHistories.set(contentType, history);\n return this;\n }\n\n /**\n * Adds media to the message.\n * @param payload Media to add.\n */\n addMedia(payload: FormData | SendMediaOptions): MessageBuilder {\n if (typeof FormData === \"undefined\" && payload instanceof FormData) {\n throw new Error(\"Could not add FormData content whilst not in a browser\");\n }\n if (!(payload instanceof FormData)) {\n const mediaOptions = payload as SendMediaOptions;\n if (!mediaOptions.contentType || !mediaOptions.media) {\n throw new Error(\n \"Media content in SendMediaOptions must contain non-empty contentType and media\"\n );\n }\n }\n this.message.mediaContent.push([\"media\", payload]);\n return this;\n }\n\n /**\n * Builds the message, making it ready to be sent.\n */\n build(): UnsentMessage {\n this.emailBodies.forEach((_, key) => {\n if (!this.limits.emailBodiesAllowedContentTypes.includes(key)) {\n throw new Error(`Unsupported email body content type ${key}`);\n }\n });\n this.emailHistories.forEach((_, key) => {\n if (!this.limits.emailHistoriesAllowedContentTypes.includes(key)) {\n throw new Error(`Unsupported email history content type ${key}`);\n }\n });\n if (\n this.emailBodies.size > this.limits.emailBodiesAllowedContentTypes.length\n ) {\n throw new Error(\n `Too many email bodies attached to the message (${this.emailBodies.size} > ${this.limits.emailBodiesAllowedContentTypes.length})`\n );\n }\n if (\n this.emailHistories.size >\n this.limits.emailHistoriesAllowedContentTypes.length\n ) {\n throw new Error(\n `Too many email histories attached to the message (${this.emailHistories.size} > ${this.limits.emailHistoriesAllowedContentTypes.length})`\n );\n }\n\n if (\n this.message.mediaContent.length > this.limits.mediaAttachmentsCountLimit\n ) {\n throw new Error(\n `Too many media attachments in the message (${this.message.mediaContent.length} > ${this.limits.mediaAttachmentsCountLimit})`\n );\n }\n\n // @todo we don't know the sizes of the attachments in FormData\n // @todo insertion below makes build() method non-repeatable - probably move to UnsentMessage.send() or even sendV2()?\n\n this.emailBodies.forEach((body) => {\n this.message.mediaContent.push([\"body\", body]);\n });\n\n this.emailHistories.forEach((history) => {\n this.message.mediaContent.push([\"history\", history]);\n });\n\n return this.message;\n }\n\n /**\n * Prepares a message and sends it to the conversation.\n */\n buildAndSend(): CancellablePromise<number | null> {\n return this.build().send();\n }\n\n private getPayloadContentType(\n payload: FormData | SendMediaOptions\n ): string | null {\n if (typeof FormData !== \"undefined\" && payload instanceof FormData) {\n return payload.get(\"Content-Type\") as string;\n }\n return (payload as SendMediaOptions).contentType;\n }\n}\n\nexport { MessageBuilder };\n"],"names":["UnsentMessage"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;AAcG;AACH,MAAM,cAAc,CAAA;AAKlB;;AAEG;IACH,WACmB,CAAA,MAA0B,EAC3C,cAAwB,EAAA;QADP,IAAM,CAAA,MAAA,GAAN,MAAM,CAAoB;QAG3C,IAAI,CAAC,OAAO,GAAG,IAAIA,2BAAa,CAAC,cAAc,CAAC,CAAC;AACjD,QAAA,IAAI,CAAC,WAAW,GAAG,IAAI,GAAG,EAAuC,CAAC;AAClE,QAAA,IAAI,CAAC,cAAc,GAAG,IAAI,GAAG,EAAuC,CAAC;KACtE;AAED;;;AAGG;AACH,IAAA,OAAO,CAAC,IAAY,EAAA;AAClB,QAAA,IAAI,CAAC,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;AACzB,QAAA,OAAO,IAAI,CAAC;KACb;AAED;;;AAGG;AACH,IAAA,UAAU,CAAC,OAAe,EAAA;QACxB,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,OAAO,GAAG,OAAO,CAAC;AAC5C,QAAA,OAAO,IAAI,CAAC;KACb;AAED;;;AAGG;AACH,IAAA,aAAa,CAAC,UAAqB,EAAA;AACjC,QAAA,IAAI,CAAC,OAAO,CAAC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CAAC,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;AACjD,SAAC,CAAC,CAAC;QAEH,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,OAAO,KAAI;AACtC,YAAA,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC;AACvD,SAAC,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC,OAAO,CAAC;KACrB;AAED;;AAEG;IACH,YAAY,GAAA;AACV,QAAA,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,CAAC;KAC5B;AAEO,IAAA,qBAAqB,CAC3B,OAAoC,EAAA;QAEpC,IAAI,OAAO,QAAQ,KAAK,WAAW,IAAI,OAAO,YAAY,QAAQ,EAAE;AAClE,YAAA,OAAO,OAAO,CAAC,GAAG,CAAC,cAAc,CAAW,CAAC;AAC9C,SAAA;QACD,OAAQ,OAA4B,CAAC,WAAW,CAAC;KAClD;AACF;;;;"}
1
+ {"version":3,"file":"message-builder.js","sources":["../src/message-builder.ts"],"sourcesContent":["import { CancellablePromise } from \"@twilio/mcs-client\";\nimport { ConversationLimits } from \"./interfaces/conversation-limits\";\nimport { SendMediaOptions } from \"./conversation\";\nimport { UnsentMessage } from \"./unsent-message\";\nimport { JSONValue } from \"./types\";\nimport { Messages } from \"./data/messages\";\nimport { ContentTemplateVariable } from \"./content-template\";\n\n/**\n * Message builder. Allows the message to be built and sent via method chaining.\n *\n * Example:\n *\n * ```ts\n * await testConversation.prepareMessage()\n * .setBody('Hello!')\n * .setAttributes({foo: 'bar'})\n * .addMedia(media1)\n * .addMedia(media2)\n * .build()\n * .send();\n * ```\n */\nclass MessageBuilder {\n private readonly message: UnsentMessage;\n private emailBodies: Map<string, FormData | SendMediaOptions>;\n private emailHistories: Map<string, FormData | SendMediaOptions>;\n\n /**\n * @internal\n */\n constructor(\n private readonly limits: ConversationLimits,\n messagesEntity: Messages\n ) {\n this.message = new UnsentMessage(messagesEntity);\n this.emailBodies = new Map<string, FormData | SendMediaOptions>();\n this.emailHistories = new Map<string, FormData | SendMediaOptions>();\n }\n\n /**\n * Sets the message body.\n * @param text Contents of the body.\n */\n setBody(text: string): MessageBuilder {\n this.message.text = text;\n return this;\n }\n\n /**\n * Sets the message subject.\n * @param subject Contents of the subject.\n */\n setSubject(subject: string): MessageBuilder {\n this.message.emailOptions.subject = subject;\n return this;\n }\n\n /**\n * Sets the message attributes.\n * @param attributes Message attributes.\n */\n setAttributes(attributes: JSONValue): MessageBuilder {\n this.message.attributes = attributes;\n return this;\n }\n\n /**\n * Set the email body with a given content type.\n * @param contentType Format of the body to set (text/plain or text/html).\n * @param body Body payload in the selected format.\n */\n setEmailBody(\n contentType: string,\n body: FormData | SendMediaOptions\n ): MessageBuilder {\n this.emailBodies.set(contentType, body);\n return this;\n }\n\n /**\n * Set the email history with a given content type.\n * @param contentType Format of the history to set (text/plain or text/html).\n * @param history History payload in the selected format.\n */\n setEmailHistory(\n contentType: string,\n history: FormData | SendMediaOptions\n ): MessageBuilder {\n this.emailHistories.set(contentType, history);\n return this;\n }\n\n /**\n * Adds {@link ContentTemplate} SID for the message alongside optional\n * variables. When no variables provided, the default values will be used.\n *\n * Adding the content SID converts the message to a rich message. In this\n * case, other fields are ignored and the message is sent using the content\n * from the the {@link ContentTemplate}.\n *\n * Use {@link Client.getContentTemplates} to request all available\n * {@link ContentTemplate}s.\n *\n * @param contentSid SID of the {@link ContentTemplate}\n * @param variables Custom variables to resolve the template.\n */\n setContentTemplate(\n contentSid: string,\n contentVariables: ContentTemplateVariable[] = []\n ): MessageBuilder {\n this.message.contentSid = contentSid;\n this.message.contentVariables = contentVariables;\n return this;\n }\n\n /**\n * Adds media to the message.\n * @param payload Media to add.\n */\n addMedia(payload: FormData | SendMediaOptions): MessageBuilder {\n if (typeof FormData === \"undefined\" && payload instanceof FormData) {\n throw new Error(\"Could not add FormData content whilst not in a browser\");\n }\n if (!(payload instanceof FormData)) {\n const mediaOptions = payload as SendMediaOptions;\n if (!mediaOptions.contentType || !mediaOptions.media) {\n throw new Error(\n \"Media content in SendMediaOptions must contain non-empty contentType and media\"\n );\n }\n }\n this.message.mediaContent.push([\"media\", payload]);\n return this;\n }\n\n /**\n * Builds the message, making it ready to be sent.\n */\n build(): UnsentMessage {\n this.emailBodies.forEach((_, key) => {\n if (!this.limits.emailBodiesAllowedContentTypes.includes(key)) {\n throw new Error(`Unsupported email body content type ${key}`);\n }\n });\n this.emailHistories.forEach((_, key) => {\n if (!this.limits.emailHistoriesAllowedContentTypes.includes(key)) {\n throw new Error(`Unsupported email history content type ${key}`);\n }\n });\n if (\n this.emailBodies.size > this.limits.emailBodiesAllowedContentTypes.length\n ) {\n throw new Error(\n `Too many email bodies attached to the message (${this.emailBodies.size} > ${this.limits.emailBodiesAllowedContentTypes.length})`\n );\n }\n if (\n this.emailHistories.size >\n this.limits.emailHistoriesAllowedContentTypes.length\n ) {\n throw new Error(\n `Too many email histories attached to the message (${this.emailHistories.size} > ${this.limits.emailHistoriesAllowedContentTypes.length})`\n );\n }\n\n if (\n this.message.mediaContent.length > this.limits.mediaAttachmentsCountLimit\n ) {\n throw new Error(\n `Too many media attachments in the message (${this.message.mediaContent.length} > ${this.limits.mediaAttachmentsCountLimit})`\n );\n }\n\n // @todo we don't know the sizes of the attachments in FormData\n // @todo insertion below makes build() method non-repeatable - probably move to UnsentMessage.send() or even sendV2()?\n\n this.emailBodies.forEach((body) => {\n this.message.mediaContent.push([\"body\", body]);\n });\n\n this.emailHistories.forEach((history) => {\n this.message.mediaContent.push([\"history\", history]);\n });\n\n return this.message;\n }\n\n /**\n * Prepares a message and sends it to the conversation.\n */\n buildAndSend(): CancellablePromise<number | null> {\n return this.build().send();\n }\n\n private getPayloadContentType(\n payload: FormData | SendMediaOptions\n ): string | null {\n if (typeof FormData !== \"undefined\" && payload instanceof FormData) {\n return payload.get(\"Content-Type\") as string;\n }\n return (payload as SendMediaOptions).contentType;\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