@twilio/conversations 2.0.1-rc.7 → 2.1.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -0
- package/builds/browser.js +249 -65
- package/builds/browser.js.map +1 -1
- package/builds/lib.d.ts +86 -9
- package/builds/lib.js +249 -65
- package/builds/lib.js.map +1 -1
- package/builds/twilio-conversations.js +254 -251
- package/builds/twilio-conversations.min.js +3 -3
- package/dist/conversation.js +24 -10
- package/dist/conversation.js.map +1 -1
- package/dist/data/conversations.js +1 -1
- package/dist/data/conversations.js.map +1 -1
- package/dist/data/messages.js +1 -1
- package/dist/data/messages.js.map +1 -1
- package/dist/data/participants.js +7 -3
- package/dist/data/participants.js.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/interfaces/attributes.js +147 -0
- package/dist/interfaces/attributes.js.map +1 -0
- package/dist/message-builder.js +52 -0
- package/dist/message-builder.js.map +1 -1
- package/dist/message.js +35 -4
- package/dist/message.js.map +1 -1
- package/dist/packages/conversations/package.json.js +1 -1
- package/dist/participant.js +20 -3
- package/dist/participant.js.map +1 -1
- package/dist/user.js +2 -1
- package/dist/user.js.map +1 -1
- package/docs/assets/js/search.js +1 -1
- package/docs/classes/AggregatedDeliveryReceipt.html +15 -0
- package/docs/classes/Client.html +15 -0
- package/docs/classes/Conversation.html +24 -2
- package/docs/classes/DetailedDeliveryReceipt.html +15 -0
- package/docs/classes/Media.html +15 -0
- package/docs/classes/Message.html +83 -2
- package/docs/classes/MessageBuilder.html +91 -0
- package/docs/classes/Participant.html +45 -1
- package/docs/classes/PushNotification.html +15 -0
- package/docs/classes/RestPaginator.html +15 -0
- package/docs/classes/UnsentMessage.html +15 -0
- package/docs/classes/User.html +15 -0
- package/docs/index.html +37 -3
- package/docs/interfaces/ClientOptions.html +15 -0
- package/docs/interfaces/ConversationBindings.html +3118 -0
- package/docs/interfaces/ConversationEmailBinding.html +3118 -0
- package/docs/interfaces/ConversationState.html +15 -0
- package/docs/interfaces/CreateConversationOptions.html +15 -0
- package/docs/interfaces/LastMessage.html +15 -0
- package/docs/interfaces/Paginator.html +15 -0
- package/docs/interfaces/ParticipantBindings.html +3118 -0
- package/docs/interfaces/ParticipantEmailBinding.html +3118 -0
- package/docs/interfaces/PushNotificationData.html +15 -0
- package/docs/interfaces/SendEmailOptions.html +15 -0
- package/docs/interfaces/SendMediaOptions.html +15 -0
- package/docs/modules.html +37 -3
- package/package.json +9 -9
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"messages.js","sources":["../../src/data/messages.ts"],"sourcesContent":["import { EventEmitter } from 'events';\nimport { Logger } from '../logger';\n\nimport {\n Message,\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 } 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';\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>;\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 name - The name of Sync object for the Messages resource.\n */\n public async subscribe(name: string) {\n if (this.messagesListPromise) {\n return this.messagesListPromise;\n }\n\n this.messagesListPromise = this.services.syncClient.list({\n id: name,\n mode: 'open_existing',\n });\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 let message = this.messagesByIndex.get(index);\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 Message to the conversation, message could include both text and multiple media attachments.\n * @param message Message to post\n * @returns Returns promise which can fail\n */\n public async sendV2(message: UnsentMessage) {\n log.debug(\n 'Sending message V2',\n message.mediaContent,\n message.attributes,\n message.emailOptions\n );\n\n const media: McsMedia[] = [];\n\n for (const [category, mediaContent] of message.mediaContent) {\n log.debug(\n `Adding media to a message as ${\n mediaContent instanceof FormData ? 'FormData' : 'SendMediaOptions'\n }`,\n mediaContent\n );\n\n media.push(\n mediaContent instanceof FormData\n ? await this.services.mcsClient.postFormData(mediaContent, category)\n : await this.services.mcsClient.post(\n mediaContent.contentType,\n mediaContent.media,\n category,\n mediaContent.filename\n )\n );\n }\n\n return await 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\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: string | null,\n attributes: any = {},\n emailOptions?: SendEmailOptions\n ): Promise<MessageResponse> {\n log.debug('Sending text message', message, attributes, emailOptions);\n\n return await 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: any = {},\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,\n anchor: number | 'end',\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: any) {\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAM,GAAG,GAAGA,aAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;AASrC;;;AAGA,MAAM,QAAS,SAAQC,qCAAkC;IAOvD,YACE,YAA0B,EAC1B,aAA4B,EAC5B,QAA0B;QAE1B,KAA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AAC,YAAY,CAAC,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,GAAG,WAAW;SAC/E,CAAC;QACF,MAAMA,SAAO,GAAG,IAAIC,eAAO,CACzB,KAAK,EACL,KAAK,EACL,IAAI,CAAC,YAAY,EACjB,KAAK,EACL,IAAI,CAAC,aAAa,EAClB,IAAI,CAAC,QAAQ,CACd,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,GAAG,CAACD,SAAO,CAAC,KAAK,EAAEA,SAAO,CAAC,CAAC;QAEjDA,SAAO,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,IAA6B,KAClD,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,IAAI,CAAC,CAClC,CAAC;QAEF,OAAOA,SAAO,CAAC;KAChB;;;;;;;;;IAUO,MAAM,YAAY,CACxB,QAAQ,GAAG,EAAE,EACb,SAAyB,KAAK,EAC9B,YAAqC,SAAS;QAE9C,MAAM,KAAK,GAAG,SAAS,KAAK,WAAW,GAAG,MAAM,GAAG,KAAK,CAAC;QACzD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,mBAAmB,CAAC;QAC5C,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC;YAC/B,IAAI,EAAE,MAAM,KAAK,KAAK,GAAG,MAAM,GAAG,KAAK,CAAC;YACxC,QAAQ;YACR,KAAK;YACL,KAAK,EAAE,QAAQ;SAChB,CAAC,CAAC;QAEH,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;;;;;"}
|
1
|
+
{"version":3,"file":"messages.js","sources":["../../src/data/messages.ts"],"sourcesContent":["import { Logger } from '../logger';\n\nimport {\n Message,\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 } 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';\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>;\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 name - The name of Sync object for the Messages resource.\n */\n public async subscribe(name: string) {\n if (this.messagesListPromise) {\n return this.messagesListPromise;\n }\n\n this.messagesListPromise = this.services.syncClient.list({\n id: name,\n mode: 'open_existing',\n });\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 let message = this.messagesByIndex.get(index);\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 Message to the conversation, message could include both text and multiple media attachments.\n * @param message Message to post\n * @returns Returns a promise which can fail\n */\n public async sendV2(message: UnsentMessage): Promise<MessageResponse> {\n log.debug(\n 'Sending message V2',\n message.mediaContent,\n message.attributes,\n message.emailOptions\n );\n\n const media: McsMedia[] = [];\n\n for (const [category, mediaContent] of message.mediaContent) {\n log.debug(\n `Adding media to a message as ${\n mediaContent instanceof FormData ? 'FormData' : 'SendMediaOptions'\n }`,\n mediaContent\n );\n\n media.push(\n mediaContent instanceof FormData\n ? await this.services.mcsClient.postFormData(mediaContent, category)\n : await this.services.mcsClient.post(\n mediaContent.contentType,\n mediaContent.media,\n category,\n mediaContent.filename\n )\n );\n }\n\n return await 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\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: string | null,\n attributes: any = {},\n emailOptions?: SendEmailOptions\n ): Promise<MessageResponse> {\n log.debug('Sending text message', message, attributes, emailOptions);\n\n return await 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: any = {},\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,\n anchor: number | 'end',\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: any) {\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAM,GAAG,GAAGA,aAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;AASrC;;;AAGA,MAAM,QAAS,SAAQC,qCAAkC;IAOvD,YACE,YAA0B,EAC1B,aAA4B,EAC5B,QAA0B;QAE1B,KAAK,EAAE,CAAC;QAER,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAEzB,IAAI,CAAC,eAAe,GAAG,IAAI,GAAG,EAAE,CAAC;QACjC,IAAI,CAAC,mBAAmB,GAAG,IAAI,CAAC;KACjC;;;;;IAMM,MAAM,SAAS,CAAC,IAAY;QACjC,IAAI,IAAI,CAAC,mBAAmB,EAAE;YAC5B,OAAO,IAAI,CAAC,mBAAmB,CAAC;SACjC;QAED,IAAI,CAAC,mBAAmB,GAAG,IAAI,CAAC,QAAQ,CAAC,UAAU,CAA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CAClC,CAAC;QAEF,OAAOA,SAAO,CAAC;KAChB;;;;;;;;;IAUO,MAAM,YAAY,CACxB,QAAQ,GAAG,EAAE,EACb,SAAyB,KAAK,EAC9B,YAAqC,SAAS;QAE9C,MAAM,KAAK,GAAG,SAAS,KAAK,WAAW,GAAG,MAAM,GAAG,KAAK,CAAC;QACzD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,mBAAmB,CAAC;QAC5C,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC;YAC/B,IAAI,EAAE,MAAM,KAAK,KAAK,GAAG,MAAM,GAAG,KAAK,CAAC;YACxC,QAAQ;YACR,KAAK;YACL,KAAK,EAAE,QAAQ;SAChB,CAAC,CAAC;QAEH,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;;;;;"}
|
@@ -219,7 +219,7 @@ class Participants extends replayEventEmitter.ReplayEventEmitter {
|
|
219
219
|
/**
|
220
220
|
* @returns {Promise<Array<Participant>>} returns list of participants {@see Participant}
|
221
221
|
*/
|
222
|
-
getParticipants() {
|
222
|
+
async getParticipants() {
|
223
223
|
return this.rosterEntityPromise.then(() => {
|
224
224
|
let participants = [];
|
225
225
|
this.participants.forEach(participant => participants.push(participant));
|
@@ -273,14 +273,18 @@ class Participants extends replayEventEmitter.ReplayEventEmitter {
|
|
273
273
|
* @param proxyAddress
|
274
274
|
* @param address
|
275
275
|
* @param attributes
|
276
|
+
* @param bindingOptions
|
276
277
|
* @returns {Promise<any>}
|
277
278
|
*/
|
278
|
-
addNonChatParticipant(proxyAddress, address, attributes) {
|
279
|
+
addNonChatParticipant(proxyAddress, address, attributes = {}, bindingOptions = {}) {
|
280
|
+
var _a, _b;
|
279
281
|
return this.services.commandExecutor.mutateResource('post', this.links.participants, {
|
280
282
|
attributes: typeof attributes !== 'undefined' ? JSON.stringify(attributes) : undefined,
|
281
283
|
messaging_binding: {
|
282
284
|
address,
|
283
|
-
proxy_address: proxyAddress
|
285
|
+
proxy_address: proxyAddress,
|
286
|
+
name: (_a = bindingOptions === null || bindingOptions === void 0 ? void 0 : bindingOptions.email) === null || _a === void 0 ? void 0 : _a.name,
|
287
|
+
level: (_b = bindingOptions === null || bindingOptions === void 0 ? void 0 : bindingOptions.email) === null || _b === void 0 ? void 0 : _b.level,
|
284
288
|
}
|
285
289
|
});
|
286
290
|
}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"participants.js","sources":["../../src/data/participants.ts"],"sourcesContent":["import { EventEmitter } from 'events';\nimport {\n ParticipantDescriptor,\n Participant,\n ParticipantUpdatedEventArgs,\n ParticipantUpdateReason\n} from '../participant';\nimport { Logger } from '../logger';\n\nimport { Conversation } from '../conversation';\n\nimport { SyncMap, SyncClient } from 'twilio-sync';\nimport { Users } from './users';\nimport { CommandExecutor } from '../command-executor';\nimport {\n AddParticipantRequest\n} from '../interfaces/commands/add-participant';\nimport { Configuration } from '../configuration';\nimport { ParticipantResponse } from '../interfaces/commands/participant-response';\nimport { ReplayEventEmitter } from '@twilio/replay-event-emitter';\n\ntype ParticipantsEvents = {\n participantJoined: (participant: Participant) => void;\n participantLeft: (participant: Participant) => void;\n participantUpdated: (data: {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n }) => void;\n};\n\nconst log = Logger.scope('Participants');\n\nexport interface ParticipantsServices {\n syncClient: SyncClient;\n users: Users;\n commandExecutor: CommandExecutor;\n}\n\ninterface ParticipantsLinks {\n participants: string;\n}\n\n/**\n * @classdesc Represents the collection of participants for the conversation\n * @fires Participants#participantJoined\n * @fires Participants#participantLeft\n * @fires Participants#participantUpdated\n */\nclass Participants extends ReplayEventEmitter<ParticipantsEvents> {\n\n private readonly configuration: Configuration;\n private readonly services: ParticipantsServices;\n private readonly links: ParticipantsLinks;\n\n rosterEntityPromise: Promise<SyncMap>;\n\n public readonly conversation: Conversation;\n public readonly participants: Map<string, Participant>;\n\n constructor(\n conversation: Conversation,\n participants: Map<string, Participant>,\n links: ParticipantsLinks,\n configuration: Configuration,\n services: ParticipantsServices,\n ) {\n super();\n this.conversation = conversation;\n this.participants = participants;\n this.links = links;\n this.configuration = configuration;\n this.services = services;\n }\n\n async unsubscribe(): Promise<void> {\n if (this.rosterEntityPromise) {\n let entity = await this.rosterEntityPromise;\n entity.close();\n this.rosterEntityPromise = null;\n }\n }\n\n subscribe(rosterObjectName: string) {\n return this.rosterEntityPromise = this.rosterEntityPromise\n || this.services.syncClient.map({ id: rosterObjectName, mode: 'open_existing' })\n .then(rosterMap => {\n rosterMap.on('itemAdded', args => {\n log.debug(this.conversation.sid + ' itemAdded: ' + args.item.key);\n this.upsertParticipant(args.item.key, args.item.data)\n .then(participant => {\n this.emit('participantJoined', participant);\n });\n });\n\n rosterMap.on('itemRemoved', args => {\n log.debug(this.conversation.sid + ' itemRemoved: ' + args.key);\n let participantSid = args.key;\n if (!this.participants.has(participantSid)) {\n return;\n }\n let leftParticipant = this.participants.get(participantSid);\n this.participants.delete(participantSid);\n this.emit('participantLeft', leftParticipant);\n });\n\n rosterMap.on('itemUpdated', args => {\n log.debug(this.conversation.sid + ' itemUpdated: ' + args.item.key);\n this.upsertParticipant(args.item.key, args.item.data);\n });\n\n let participantsPromises = [];\n let that = this;\n const rosterMapHandler = function(paginator) {\n paginator.items.forEach(item => { participantsPromises.push(that.upsertParticipant(item.key, item.data)); });\n return paginator.hasNextPage ? paginator.nextPage().then(rosterMapHandler) : null;\n };\n\n return rosterMap\n .getItems()\n .then(rosterMapHandler)\n .then(() => Promise.all(participantsPromises))\n .then(() => rosterMap);\n })\n .catch(err => {\n this.rosterEntityPromise = null;\n if (this.services.syncClient.connectionState != 'disconnected') {\n log.error('Failed to get roster object for conversation', this.conversation.sid, err);\n }\n log.debug('ERROR: Failed to get roster object for conversation', this.conversation.sid, err);\n throw err;\n });\n }\n\n async upsertParticipant(participantSid: string, data: ParticipantDescriptor): Promise<Participant> {\n let participant = this.participants.get(participantSid);\n if (participant) {\n return participant._update(data);\n }\n\n const links = {\n self: `${this.links.participants}/${participantSid}`\n };\n\n participant = new Participant(data, participantSid, this.conversation, links, this.services);\n this.participants.set(participantSid, participant);\n participant.on('updated', (args: ParticipantUpdatedEventArgs) => this.emit('participantUpdated', args));\n return participant;\n }\n\n /**\n * @returns {Promise<Array<Participant>>} returns list of participants {@see Participant}\n */\n getParticipants(): Promise<Array<Participant>> {\n return this.rosterEntityPromise.then(() => {\n let participants = [];\n this.participants.forEach(participant => participants.push(participant));\n return participants;\n });\n }\n\n /**\n * Get participant by SID from conversation\n * @returns {Promise<Participant>}\n */\n async getParticipantBySid(participantSid: string): Promise<Participant> {\n return this.rosterEntityPromise.then(() => {\n let participant = this.participants.get(participantSid);\n if (!participant) {\n throw new Error('Participant with SID ' + participantSid + ' was not found');\n }\n return participant;\n });\n }\n\n /**\n * Get participant by identity from conversation\n * @returns {Promise<Participant>}\n */\n async getParticipantByIdentity(identity: string): Promise<Participant> {\n let foundParticipant = null;\n return this.rosterEntityPromise.then(() => {\n this.participants.forEach(participant => {\n if (participant.identity === identity) {\n foundParticipant = participant;\n }\n });\n if (!foundParticipant) {\n throw new Error('Participant with identity ' + identity + ' was not found');\n }\n return foundParticipant;\n });\n }\n\n /**\n * Add a chat participant to the conversation\n * @returns {Promise<any>}\n */\n async add(identity: string, attributes: any): Promise<any> {\n return await this.services.commandExecutor.mutateResource<AddParticipantRequest, ParticipantResponse>(\n 'post',\n this.links.participants,\n {\n identity,\n attributes: typeof attributes !== 'undefined' ? JSON.stringify(attributes) : undefined\n }\n );\n }\n\n /**\n * Add a non-chat participant to the conversation.\n *\n * @param proxyAddress\n * @param address\n * @param attributes\n * @returns {Promise<any>}\n */\n addNonChatParticipant(proxyAddress: string, address: string, attributes: any): Promise<any> {\n return this.services.commandExecutor.mutateResource<AddParticipantRequest, ParticipantResponse>(\n 'post',\n this.links.participants,\n {\n attributes: typeof attributes !== 'undefined' ? JSON.stringify(attributes) : undefined,\n messaging_binding: {\n address,\n proxy_address: proxyAddress\n }\n }\n );\n }\n\n /**\n * Remove the participant with a given identity from a conversation.\n */\n remove(identity: string): Promise<any> {\n return this.services.commandExecutor.mutateResource(\n 'delete',\n `${this.links.participants}/${identity}`,\n );\n }\n}\n\nexport { Participants };\n\n/**\n * Fired when participant joined conversation\n * @event Participants#participantJoined\n * @type {Participant}\n */\n\n/**\n * Fired when participant left conversation\n * @event Participants#participantLeft\n * @type {Participant}\n */\n\n/**\n * Fired when participant updated\n * @event Participants#participantUpdated\n * @type {Object}\n * @property {Participant} participant - Updated Participant\n * @property {Participant#UpdateReason[]} updateReasons - Array of Participant's updated event reasons\n */\n"],"names":["Logger","ReplayEventEmitter","participant","Participant"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAM,GAAG,GAAGA,aAAM,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;AAYzC;;;;;;AAMA,MAAM,YAAa,SAAQC,qCAAsC;IAW/D,YACE,YAA0B,EAC1B,YAAsC,EACtC,KAAwB,EACxB,aAA4B,EAC5B,QAA8B;QAE9B,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;KAC1B;IAED,MAAM,WAAW;QACf,IAAI,IAAI,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GAAG,SAAS;YACtF,iBAAiB,EAAE;gBACjB,OAAO;gBACP,aAAa,EAAE,YAAY;aAC5B;SACF,CACF,CAAC;KACH;;;;IAKD,MAAM,CAAC,QAAgB;QACrB,OAAO,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,cAAc,CACjD,QAAQ,EACR,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,IAAI,QAAQ,EAAE,CACzC,CAAC;KACH;CACF;AAID;;;;;AAMA;;;;;AAMA;;;;;;;;;;"}
|
1
|
+
{"version":3,"file":"participants.js","sources":["../../src/data/participants.ts"],"sourcesContent":["import { EventEmitter } from 'events';\nimport {\n ParticipantDescriptor,\n Participant,\n ParticipantUpdatedEventArgs,\n ParticipantUpdateReason,\n ParticipantEmailBinding\n} from '../participant';\nimport { Logger } from '../logger';\n\nimport { Conversation } from '../conversation';\n\nimport { SyncMap, SyncClient } from 'twilio-sync';\nimport { Users } from './users';\nimport { CommandExecutor } from '../command-executor';\nimport {\n AddParticipantRequest\n} from '../interfaces/commands/add-participant';\nimport { Configuration } from '../configuration';\nimport { ParticipantResponse } from '../interfaces/commands/participant-response';\nimport { ReplayEventEmitter } from '@twilio/replay-event-emitter';\n\ntype ParticipantsEvents = {\n participantJoined: (participant: Participant) => void;\n participantLeft: (participant: Participant) => void;\n participantUpdated: (data: {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n }) => void;\n};\n\nconst log = Logger.scope('Participants');\n\nexport interface ParticipantsServices {\n syncClient: SyncClient;\n users: Users;\n commandExecutor: CommandExecutor;\n}\n\ninterface ParticipantsLinks {\n participants: string;\n}\n\nexport interface ParticipantBindingOptions {\n email?: ParticipantEmailBinding;\n}\n\n/**\n * @classdesc Represents the collection of participants for the conversation\n * @fires Participants#participantJoined\n * @fires Participants#participantLeft\n * @fires Participants#participantUpdated\n */\nclass Participants extends ReplayEventEmitter<ParticipantsEvents> {\n\n private readonly configuration: Configuration;\n private readonly services: ParticipantsServices;\n private readonly links: ParticipantsLinks;\n\n rosterEntityPromise: Promise<SyncMap>;\n\n public readonly conversation: Conversation;\n public readonly participants: Map<string, Participant>;\n\n constructor(\n conversation: Conversation,\n participants: Map<string, Participant>,\n links: ParticipantsLinks,\n configuration: Configuration,\n services: ParticipantsServices,\n ) {\n super();\n this.conversation = conversation;\n this.participants = participants;\n this.links = links;\n this.configuration = configuration;\n this.services = services;\n }\n\n async unsubscribe(): Promise<void> {\n if (this.rosterEntityPromise) {\n let entity = await this.rosterEntityPromise;\n entity.close();\n this.rosterEntityPromise = null;\n }\n }\n\n subscribe(rosterObjectName: string) {\n return this.rosterEntityPromise = this.rosterEntityPromise\n || this.services.syncClient.map({ id: rosterObjectName, mode: 'open_existing' })\n .then(rosterMap => {\n rosterMap.on('itemAdded', args => {\n log.debug(this.conversation.sid + ' itemAdded: ' + args.item.key);\n this.upsertParticipant(args.item.key, args.item.data)\n .then(participant => {\n this.emit('participantJoined', participant);\n });\n });\n\n rosterMap.on('itemRemoved', args => {\n log.debug(this.conversation.sid + ' itemRemoved: ' + args.key);\n let participantSid = args.key;\n if (!this.participants.has(participantSid)) {\n return;\n }\n let leftParticipant = this.participants.get(participantSid);\n this.participants.delete(participantSid);\n this.emit('participantLeft', leftParticipant);\n });\n\n rosterMap.on('itemUpdated', args => {\n log.debug(this.conversation.sid + ' itemUpdated: ' + args.item.key);\n this.upsertParticipant(args.item.key, args.item.data);\n });\n\n let participantsPromises = [];\n let that = this;\n const rosterMapHandler = function(paginator) {\n paginator.items.forEach(item => { participantsPromises.push(that.upsertParticipant(item.key, item.data)); });\n return paginator.hasNextPage ? paginator.nextPage().then(rosterMapHandler) : null;\n };\n\n return rosterMap\n .getItems()\n .then(rosterMapHandler)\n .then(() => Promise.all(participantsPromises))\n .then(() => rosterMap);\n })\n .catch(err => {\n this.rosterEntityPromise = null;\n if (this.services.syncClient.connectionState != 'disconnected') {\n log.error('Failed to get roster object for conversation', this.conversation.sid, err);\n }\n log.debug('ERROR: Failed to get roster object for conversation', this.conversation.sid, err);\n throw err;\n });\n }\n\n async upsertParticipant(participantSid: string, data: ParticipantDescriptor): Promise<Participant> {\n let participant = this.participants.get(participantSid);\n if (participant) {\n return participant._update(data);\n }\n\n const links = {\n self: `${this.links.participants}/${participantSid}`\n };\n\n participant = new Participant(data, participantSid, this.conversation, links, this.services);\n this.participants.set(participantSid, participant);\n participant.on('updated', (args: ParticipantUpdatedEventArgs) => this.emit('participantUpdated', args));\n return participant;\n }\n\n /**\n * @returns {Promise<Array<Participant>>} returns list of participants {@see Participant}\n */\n async getParticipants(): Promise<Array<Participant>> {\n return this.rosterEntityPromise.then(() => {\n let participants = [];\n this.participants.forEach(participant => participants.push(participant));\n return participants;\n });\n }\n\n /**\n * Get participant by SID from conversation\n * @returns {Promise<Participant>}\n */\n async getParticipantBySid(participantSid: string): Promise<Participant> {\n return this.rosterEntityPromise.then(() => {\n let participant = this.participants.get(participantSid);\n if (!participant) {\n throw new Error('Participant with SID ' + participantSid + ' was not found');\n }\n return participant;\n });\n }\n\n /**\n * Get participant by identity from conversation\n * @returns {Promise<Participant>}\n */\n async getParticipantByIdentity(identity: string): Promise<Participant> {\n let foundParticipant = null;\n return this.rosterEntityPromise.then(() => {\n this.participants.forEach(participant => {\n if (participant.identity === identity) {\n foundParticipant = participant;\n }\n });\n if (!foundParticipant) {\n throw new Error('Participant with identity ' + identity + ' was not found');\n }\n return foundParticipant;\n });\n }\n\n /**\n * Add a chat participant to the conversation\n * @returns {Promise<any>}\n */\n async add(identity: string, attributes: any): Promise<any> {\n return await this.services.commandExecutor.mutateResource<AddParticipantRequest, ParticipantResponse>(\n 'post',\n this.links.participants,\n {\n identity,\n attributes: typeof attributes !== 'undefined' ? JSON.stringify(attributes) : undefined\n }\n );\n }\n\n /**\n * Add a non-chat participant to the conversation.\n *\n * @param proxyAddress\n * @param address\n * @param attributes\n * @param bindingOptions\n * @returns {Promise<any>}\n */\n addNonChatParticipant(proxyAddress: string, address: string, attributes: Record<string, any> = {},\n bindingOptions: ParticipantBindingOptions = {}): Promise<any> {\n return this.services.commandExecutor.mutateResource<AddParticipantRequest, ParticipantResponse>(\n 'post',\n this.links.participants,\n {\n attributes: typeof attributes !== 'undefined' ? JSON.stringify(attributes) : undefined,\n messaging_binding: {\n address,\n proxy_address: proxyAddress,\n name: bindingOptions?.email?.name,\n level: bindingOptions?.email?.level,\n }\n }\n );\n }\n\n /**\n * Remove the participant with a given identity from a conversation.\n */\n remove(identity: string): Promise<any> {\n return this.services.commandExecutor.mutateResource(\n 'delete',\n `${this.links.participants}/${identity}`,\n );\n }\n}\n\nexport { Participants };\n\n/**\n * Fired when participant joined conversation\n * @event Participants#participantJoined\n * @type {Participant}\n */\n\n/**\n * Fired when participant left conversation\n * @event Participants#participantLeft\n * @type {Participant}\n */\n\n/**\n * Fired when participant updated\n * @event Participants#participantUpdated\n * @type {Object}\n * @property {Participant} participant - Updated Participant\n * @property {Participant#UpdateReason[]} updateReasons - Array of Participant's updated event reasons\n */\n"],"names":["Logger","ReplayEventEmitter","participant","Participant"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAM,GAAG,GAAGA,aAAM,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;AAgBzC;;;;;;AAMA,MAAM,YAAa,SAAQC,qCAAsC;IAW/D,YACE,YAA0B,EAC1B,YAAsC,EACtC,KAAwB,EACxB,aAA4B,EAC5B,QAA8B;QAE9B,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;K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AAU,EAAE,OAAO,UAAU,KAAK,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,GAAG,SAAS;YACtF,iBAAiB,EAAE;gBACjB,OAAO;gBACP,aAAa,EAAE,YAAY;gBAC3B,IAAI,EAAE,MAAA,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,KAAK,0CAAE,IAAI;gBACjC,KAAK,EAAE,MAAA,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,KAAK,0CAAE,KAAK;aACpC;SACF,CACF,CAAC;KACH;;;;IAKD,MAAM,CAAC,QAAgB;QACrB,OAAO,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,cAAc,CACjD,QAAQ,EACR,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,IAAI,QAAQ,EAAE,CACzC,CAAC;KACH;CACF;AAID;;;;;AAMA;;;;;AAMA;;;;;;;;;;"}
|
package/dist/index.js
CHANGED
@@ -130,6 +130,7 @@ This software includes platform.js under the following license.
|
|
130
130
|
|
131
131
|
Object.defineProperty(exports, '__esModule', { value: true });
|
132
132
|
|
133
|
+
require('isomorphic-form-data');
|
133
134
|
var client = require('./client.js');
|
134
135
|
var conversation = require('./conversation.js');
|
135
136
|
var participant = require('./participant.js');
|
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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
@@ -0,0 +1,147 @@
|
|
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
|
+
var declarativeTypeValidator = require('@twilio/declarative-type-validator');
|
134
|
+
|
135
|
+
// Any JSON value
|
136
|
+
const attributesValidator = declarativeTypeValidator.custom((value) => [
|
137
|
+
['string', 'number', 'boolean', 'object'].includes(typeof value),
|
138
|
+
'a JSON type'
|
139
|
+
]);
|
140
|
+
const optionalAttributesValidator = declarativeTypeValidator.custom((value) => [
|
141
|
+
['undefined', 'string', 'number', 'boolean', 'object'].includes(typeof value),
|
142
|
+
'an optional JSON type'
|
143
|
+
]);
|
144
|
+
|
145
|
+
exports.attributesValidator = attributesValidator;
|
146
|
+
exports.optionalAttributesValidator = optionalAttributesValidator;
|
147
|
+
//# sourceMappingURL=attributes.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"attributes.js","sources":["../../src/interfaces/attributes.ts"],"sourcesContent":["import { custom } from '@twilio/declarative-type-validator';\n\n// Any JSON value\nexport const attributesValidator = custom((value) => [\n ['string', 'number', 'boolean', 'object'].includes(typeof value),\n 'a JSON type'\n]);\n\nexport const optionalAttributesValidator = custom((value) => [\n ['undefined', 'string', 'number', 'boolean', 'object'].includes(typeof value),\n 'an optional JSON type'\n]);\n"],"names":["custom"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA;MACa,mBAAmB,GAAGA,+BAAM,CAAC,CAAC,KAAK,KAAK;IACjD,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC,QAAQ,CAAC,OAAO,KAAK,CAAC;IAChE,aAAa;CAChB,EAAE;MAEU,2BAA2B,GAAGA,+BAAM,CAAC,CAAC,KAAK,KAAK;IACzD,CAAC,WAAW,EAAE,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC,QAAQ,CAAC,OAAO,KAAK,CAAC;IAC7E,uBAAuB;CAC1B;;;;;"}
|
package/dist/message-builder.js
CHANGED
@@ -154,6 +154,8 @@ class MessageBuilder {
|
|
154
154
|
constructor(limits, messagesEntity) {
|
155
155
|
this.limits = limits;
|
156
156
|
this.message = new unsentMessage.UnsentMessage(messagesEntity);
|
157
|
+
this.emailBodies = new Map();
|
158
|
+
this.emailHistories = new Map();
|
157
159
|
}
|
158
160
|
/**
|
159
161
|
* Sets the message body.
|
@@ -179,11 +181,38 @@ class MessageBuilder {
|
|
179
181
|
this.message.attributes = attributes;
|
180
182
|
return this;
|
181
183
|
}
|
184
|
+
/**
|
185
|
+
* Set email body with given MIME-type.
|
186
|
+
* @param mimeType Format of the body to set (text/plain or text/html).
|
187
|
+
* @param body Body payload in selected format.
|
188
|
+
*/
|
189
|
+
setEmailBody(mimeType, body) {
|
190
|
+
this.emailBodies.set(mimeType, body);
|
191
|
+
return this;
|
192
|
+
}
|
193
|
+
/**
|
194
|
+
* Set email history with given MIME-type.
|
195
|
+
* @param mimeType Format of the history to set (text/plain or text/html).
|
196
|
+
* @param history History payload in selected format.
|
197
|
+
*/
|
198
|
+
setEmailHistory(mimeType, history) {
|
199
|
+
this.emailHistories.set(mimeType, history);
|
200
|
+
return this;
|
201
|
+
}
|
182
202
|
/**
|
183
203
|
* Adds media to the message.
|
184
204
|
* @param payload Media to add.
|
185
205
|
*/
|
186
206
|
addMedia(payload) {
|
207
|
+
if (typeof FormData === 'undefined' && (payload instanceof FormData)) {
|
208
|
+
throw new Error('Could not add FormData content whilst not in a browser');
|
209
|
+
}
|
210
|
+
if (!(payload instanceof FormData)) {
|
211
|
+
const mediaOptions = payload;
|
212
|
+
if (!mediaOptions.contentType || !mediaOptions.media) {
|
213
|
+
throw new Error('Media content in SendMediaOptions must contain non-empty contentType and media');
|
214
|
+
}
|
215
|
+
}
|
187
216
|
this.message.mediaContent.push(['media', payload]);
|
188
217
|
return this;
|
189
218
|
}
|
@@ -191,10 +220,33 @@ class MessageBuilder {
|
|
191
220
|
* Builds the message, making it ready to be sent.
|
192
221
|
*/
|
193
222
|
build() {
|
223
|
+
this.emailBodies.forEach((_, key) => {
|
224
|
+
if (!this.limits.emailBodiesAllowedMimeTypes.includes(key)) {
|
225
|
+
throw new Error(`Unsupported email body MIME type ${key}`);
|
226
|
+
}
|
227
|
+
});
|
228
|
+
this.emailHistories.forEach((_, key) => {
|
229
|
+
if (!this.limits.emailHistoriesAllowedMimeTypes.includes(key)) {
|
230
|
+
throw new Error(`Unsupported email history MIME type ${key}`);
|
231
|
+
}
|
232
|
+
});
|
233
|
+
if (this.emailBodies.size > this.limits.emailBodiesAllowedMimeTypes.length) {
|
234
|
+
throw new Error(`Too many email bodies attached to the message (${this.emailBodies.size} > ${this.limits.emailBodiesAllowedMimeTypes.length})`);
|
235
|
+
}
|
236
|
+
if (this.emailHistories.size > this.limits.emailHistoriesAllowedMimeTypes.length) {
|
237
|
+
throw new Error(`Too many email histories attached to the message (${this.emailHistories.size} > ${this.limits.emailHistoriesAllowedMimeTypes.length})`);
|
238
|
+
}
|
194
239
|
if (this.message.mediaContent.length > this.limits.mediaAttachmentsCountLimit) {
|
195
240
|
throw new Error(`Too many media attachments in the message (${this.message.mediaContent.length} > ${this.limits.mediaAttachmentsCountLimit})`);
|
196
241
|
}
|
197
242
|
// @todo we don't know the sizes of the attachments in FormData
|
243
|
+
// @todo insertion below makes build() method non-repeatable - probably move to UnsentMessage.send() or even sendV2()?
|
244
|
+
this.emailBodies.forEach((body) => {
|
245
|
+
this.message.mediaContent.push(['body', body]);
|
246
|
+
});
|
247
|
+
this.emailHistories.forEach((history) => {
|
248
|
+
this.message.mediaContent.push(['history', history]);
|
249
|
+
});
|
198
250
|
return this.message;
|
199
251
|
}
|
200
252
|
getPayloadContentType(payload) {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"message-builder.js","sources":["../src/message-builder.ts"],"sourcesContent":["import { Limits } from './interfaces/limits';\nimport { SendMediaOptions } from './conversation';\nimport { UnsentMessage } from './unsent-message';\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\n /**\n * @internal\n */\n constructor(private readonly limits: Limits, messagesEntity: any) {\n this.message = new UnsentMessage(messagesEntity);\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: any): MessageBuilder {\n this.message.attributes = attributes;\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 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 if (this.message.mediaContent.length > this.limits.mediaAttachmentsCountLimit) {\n throw new Error(`Too many media attachments in the message (${this.message.mediaContent.length} > ${this.limits.mediaAttachmentsCountLimit})`);\n }\n\n // @todo we don't know the sizes of the attachments in FormData\n\n return this.message;\n }\n\n private getPayloadContentType(payload: FormData | SendMediaOptions): string {\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;AAeA,MAAM,cAAc;;;;
|
1
|
+
{"version":3,"file":"message-builder.js","sources":["../src/message-builder.ts"],"sourcesContent":["import { Limits } from './interfaces/limits';\nimport { Conversation, SendMediaOptions } from './conversation';\nimport { UnsentMessage } from './unsent-message';\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(private readonly limits: Limits, messagesEntity: any) {\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: any): MessageBuilder {\n this.message.attributes = attributes;\n return this;\n }\n\n /**\n * Set email body with given MIME-type.\n * @param mimeType Format of the body to set (text/plain or text/html).\n * @param body Body payload in selected format.\n */\n setEmailBody(mimeType: string, body: FormData | SendMediaOptions): MessageBuilder {\n this.emailBodies.set(mimeType, body);\n return this;\n }\n\n /**\n * Set email history with given MIME-type.\n * @param mimeType Format of the history to set (text/plain or text/html).\n * @param history History payload in selected format.\n */\n setEmailHistory(mimeType: string, history: FormData | SendMediaOptions): MessageBuilder {\n this.emailHistories.set(mimeType, 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('Media content in SendMediaOptions must contain non-empty contentType and media');\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.emailBodiesAllowedMimeTypes.includes(key)) {\n throw new Error(`Unsupported email body MIME type ${key}`);\n }\n });\n this.emailHistories.forEach((_, key) => {\n if (!this.limits.emailHistoriesAllowedMimeTypes.includes(key)) {\n throw new Error(`Unsupported email history MIME type ${key}`);\n }\n });\n if (this.emailBodies.size > this.limits.emailBodiesAllowedMimeTypes.length) {\n throw new Error(`Too many email bodies attached to the message (${this.emailBodies.size} > ${this.limits.emailBodiesAllowedMimeTypes.length})`);\n }\n if (this.emailHistories.size > this.limits.emailHistoriesAllowedMimeTypes.length) {\n throw new Error(`Too many email histories attached to the message (${this.emailHistories.size} > ${this.limits.emailHistoriesAllowedMimeTypes.length})`);\n }\n\n if (this.message.mediaContent.length > this.limits.mediaAttachmentsCountLimit) {\n throw new Error(`Too many media attachments in the message (${this.message.mediaContent.length} > ${this.limits.mediaAttachmentsCountLimit})`);\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 private getPayloadContentType(payload: FormData | SendMediaOptions): string {\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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C;SAC1J;QAED,IAAI,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,0BAA0B,EAAE;YAC7E,MAAM,IAAI,KAAK,CAAC,8CAA8C,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,MAAM,MAAM,IAAI,CAAC,MAAM,CAAC,0BAA0B,GAAG,CAAC,CAAC;SAChJ;;;QAKD,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,IAAI;YAC5B,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;SAChD,CAAC,CAAC;QAEH,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,OAAO;YAClC,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC;SACtD,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC,OAAO,CAAC;KACrB;IAEO,qBAAqB,CAAC,OAAoC;QAChE,IAAI,OAAO,QAAQ,KAAK,WAAW,KAAK,OAAO,YAAY,QAAQ,CAAC,EAAE;YACpE,OAAO,OAAO,CAAC,GAAG,CAAC,cAAc,CAAW,CAAC;SAC9C;QACD,OAAQ,OAA4B,CAAC,WAAW,CAAC;KAClD;;;;;"}
|
package/dist/message.js
CHANGED
@@ -136,6 +136,7 @@ var logger = require('./logger.js');
|
|
136
136
|
var media = require('./media.js');
|
137
137
|
var aggregatedDeliveryReceipt = require('./aggregated-delivery-receipt.js');
|
138
138
|
var declarativeTypeValidator = require('@twilio/declarative-type-validator');
|
139
|
+
var attributes = require('./interfaces/attributes.js');
|
139
140
|
var restPaginator = require('./rest-paginator.js');
|
140
141
|
var detailedDeliveryReceipt = require('./detailed-delivery-receipt.js');
|
141
142
|
var replayEventEmitter = require('@twilio/replay-event-emitter');
|
@@ -224,11 +225,11 @@ class Message extends replayEventEmitter.ReplayEventEmitter {
|
|
224
225
|
*/
|
225
226
|
get attributes() { return this.state.attributes; }
|
226
227
|
/**
|
227
|
-
*
|
228
|
+
* Type of the message.
|
228
229
|
*/
|
229
230
|
get type() { return this.state.type; }
|
230
231
|
/**
|
231
|
-
* One of the attached media.
|
232
|
+
* One of the attached media (if present).
|
232
233
|
* @deprecated Use attachedMedia instead. Note that the latter is now an array.
|
233
234
|
*/
|
234
235
|
get media() { return this.state.media; }
|
@@ -256,6 +257,24 @@ class Message extends replayEventEmitter.ReplayEventEmitter {
|
|
256
257
|
var _a;
|
257
258
|
return (_a = this.state.medias) === null || _a === void 0 ? void 0 : _a.filter((m) => categories.includes(m.category));
|
258
259
|
}
|
260
|
+
/**
|
261
|
+
* Get a media descriptor for an email body attachment of a provided type.
|
262
|
+
* Allowed body types are returned in the Conversation.limits().emailBodiesAllowedMimeTypes array.
|
263
|
+
* @param type Type of email body to request, defaults to `text/plain`.
|
264
|
+
*/
|
265
|
+
getEmailBody(type = 'text/plain') {
|
266
|
+
var _a, _b;
|
267
|
+
return (_b = (_a = this.getMediaByCategory(['body'])) === null || _a === void 0 ? void 0 : _a.filter((m) => m.contentType == type).shift()) !== null && _b !== void 0 ? _b : null;
|
268
|
+
}
|
269
|
+
/**
|
270
|
+
* Get a media descriptor for an email history attachment of a provided type.
|
271
|
+
* Allowed body types are returned in the Conversation.limits().emailHistoriesAllowedMimeTypes array.
|
272
|
+
* @param type Type of email history to request, defaults to `text/plain`.
|
273
|
+
*/
|
274
|
+
getEmailHistory(type = 'text/plain') {
|
275
|
+
var _a, _b;
|
276
|
+
return (_b = (_a = this.getMediaByCategory(['history'])) === null || _a === void 0 ? void 0 : _a.filter((m) => m.contentType == type).shift()) !== null && _b !== void 0 ? _b : null;
|
277
|
+
}
|
259
278
|
_update(data) {
|
260
279
|
let updateReasons = [];
|
261
280
|
if ((data.text || ((typeof data.text) === 'string')) && data.text !== this.state.body) {
|
@@ -424,6 +443,18 @@ class Message extends replayEventEmitter.ReplayEventEmitter {
|
|
424
443
|
* * {@link MessageUpdateReason}[] updateReasons - array of reasons for the update
|
425
444
|
*/
|
426
445
|
Message.updated = 'updated';
|
446
|
+
tslib_es6.__decorate([
|
447
|
+
declarativeTypeValidator.validateTypes(declarativeTypeValidator.nonEmptyString),
|
448
|
+
tslib_es6.__metadata("design:type", Function),
|
449
|
+
tslib_es6.__metadata("design:paramtypes", [String]),
|
450
|
+
tslib_es6.__metadata("design:returntype", media.Media)
|
451
|
+
], Message.prototype, "getEmailBody", null);
|
452
|
+
tslib_es6.__decorate([
|
453
|
+
declarativeTypeValidator.validateTypes(declarativeTypeValidator.nonEmptyString),
|
454
|
+
tslib_es6.__metadata("design:type", Function),
|
455
|
+
tslib_es6.__metadata("design:paramtypes", [String]),
|
456
|
+
tslib_es6.__metadata("design:returntype", media.Media)
|
457
|
+
], Message.prototype, "getEmailHistory", null);
|
427
458
|
tslib_es6.__decorate([
|
428
459
|
declarativeTypeValidator.validateTypesAsync('string'),
|
429
460
|
tslib_es6.__metadata("design:type", Function),
|
@@ -431,14 +462,14 @@ tslib_es6.__decorate([
|
|
431
462
|
tslib_es6.__metadata("design:returntype", Promise)
|
432
463
|
], Message.prototype, "updateBody", null);
|
433
464
|
tslib_es6.__decorate([
|
434
|
-
declarativeTypeValidator.validateTypesAsync(
|
465
|
+
declarativeTypeValidator.validateTypesAsync(attributes.attributesValidator),
|
435
466
|
tslib_es6.__metadata("design:type", Function),
|
436
467
|
tslib_es6.__metadata("design:paramtypes", [Object]),
|
437
468
|
tslib_es6.__metadata("design:returntype", Promise)
|
438
469
|
], Message.prototype, "updateAttributes", null);
|
439
470
|
tslib_es6.__decorate([
|
440
471
|
declarativeTypeValidator.validateTypesAsync(declarativeTypeValidator.custom(value => [
|
441
|
-
value instanceof Array && value.length > 0 && value.reduce((a, c) => a && c instanceof media.Media),
|
472
|
+
value instanceof Array && value.length > 0 && value.reduce((a, c) => a && c instanceof media.Media, true),
|
442
473
|
'a non-empty array of Media'
|
443
474
|
])),
|
444
475
|
tslib_es6.__metadata("design:type", Function),
|