@twilio/conversations 2.2.2-rc.4 → 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.
@@ -1 +1 @@
1
- {"version":3,"file":"conversation.js","sources":["../src/conversation.ts"],"sourcesContent":["import \"isomorphic-form-data\";\nimport { Logger } from \"./logger\";\nimport { ParticipantBindingOptions, Participants } from \"./data/participants\";\nimport {\n Participant,\n ParticipantUpdatedEventArgs,\n ParticipantUpdateReason,\n} from \"./participant\";\nimport { Messages } from \"./data/messages\";\nimport {\n Message,\n MessageUpdatedEventArgs,\n MessageUpdateReason,\n} from \"./message\";\nimport { UriBuilder, parseToNumber, parseTime } from \"./util\";\nimport { Users } from \"./data/users\";\nimport { Paginator } from \"./interfaces/paginator\";\nimport { ConversationsDataSource } from \"./data/conversations\";\nimport { McsClient } from \"@twilio/mcs-client\";\nimport { SyncClient, SyncDocument, SyncList, SyncMap } from \"twilio-sync\";\nimport { TypingIndicator } from \"./services/typing-indicator\";\nimport { Network } from \"./services/network\";\nimport {\n validateTypesAsync,\n custom,\n literal,\n nonEmptyString,\n nonNegativeInteger,\n objectSchema,\n} from \"@twilio/declarative-type-validator\";\nimport {\n attributesValidator,\n optionalAttributesValidator,\n} from \"./interfaces/attributes\";\nimport { Configuration } from \"./configuration\";\nimport { CommandExecutor } from \"./command-executor\";\nimport { AddParticipantRequest } from \"./interfaces/commands/add-participant\";\nimport { EditConversationRequest } from \"./interfaces/commands/edit-conversation\";\nimport { ConversationResponse } from \"./interfaces/commands/conversation-response\";\nimport { ParticipantResponse } from \"./interfaces/commands/participant-response\";\nimport { EditNotificationLevelRequest } from \"./interfaces/commands/edit-notification-level\";\nimport {\n EditLastReadMessageIndexRequest,\n EditLastReadMessageIndexResponse,\n} from \"./interfaces/commands/edit-last-read-message-index\";\nimport { ConversationLimits } from \"./interfaces/conversation-limits\";\nimport { MessageBuilder } from \"./message-builder\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport isEqual from \"lodash.isequal\";\nimport { JSONValue } from \"./types\";\n\n/**\n * Conversation events.\n */\ntype ConversationEvents = {\n participantJoined: (participant: Participant) => void;\n participantLeft: (participant: Participant) => void;\n participantUpdated: (data: {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n }) => void;\n messageAdded: (message: Message) => void;\n messageRemoved: (message: Message) => void;\n messageUpdated: (data: {\n message: Message;\n updateReasons: MessageUpdateReason[];\n }) => void;\n typingEnded: (participant: Participant) => void;\n typingStarted: (participant: Participant) => void;\n updated: (data: {\n conversation: Conversation;\n updateReasons: ConversationUpdateReason[];\n }) => void;\n removed: (conversation: Conversation) => void;\n};\n\n/**\n * Reason for the `updated` event emission by a conversation.\n */\ntype ConversationUpdateReason =\n | \"attributes\"\n | \"createdBy\"\n | \"dateCreated\"\n | \"dateUpdated\"\n | \"friendlyName\"\n | \"lastReadMessageIndex\"\n | \"state\"\n | \"status\"\n | \"uniqueName\"\n | \"lastMessage\"\n | \"notificationLevel\"\n | \"bindings\";\n\n/**\n * Status of the conversation, relative to the client: whether the conversation\n * has been `joined` or the client is `notParticipating` in the conversation.\n */\ntype ConversationStatus = \"notParticipating\" | \"joined\";\n\n/**\n * User's notification level for the conversation. Determines\n * whether the currently logged-in user will receive pushes for events\n * in this conversation. Can be either `muted` or `default`, where\n * `default` defers to the global service push configuration.\n */\ntype NotificationLevel = \"default\" | \"muted\";\n\n/**\n * State of the conversation.\n */\ninterface ConversationState {\n /**\n * Current state.\n */\n current: \"active\" | \"inactive\" | \"closed\";\n\n /**\n * Date at which the latest conversation state update happened.\n */\n dateUpdated: Date;\n}\n\n/**\n * Event arguments for the `updated` event.\n */\ninterface ConversationUpdatedEventArgs {\n conversation: Conversation;\n updateReasons: ConversationUpdateReason[];\n}\n\n/**\n * Binding for email conversation.\n */\ninterface ConversationBindings {\n email?: ConversationEmailBinding;\n sms?: ConversationSmsBinding;\n}\n\n/**\n * Binding for email conversation.\n */\ninterface ConversationEmailBinding {\n name?: string;\n projected_address: string;\n}\n\n/**\n * Binding for SMS conversation.\n */\ninterface ConversationSmsBinding {\n address?: string;\n}\n\n/**\n * Configuration for attaching a media file to a message.\n * These options can be passed to {@link Conversation.sendMessage} and\n * {@link MessageBuilder.addMedia}.\n */\ninterface SendMediaOptions {\n /**\n * Content type of media.\n */\n contentType: null | string;\n\n /**\n * Optional filename.\n */\n filename?: string;\n\n /**\n * Content to post.\n */\n media: null | string | Buffer | Blob;\n}\n\n/**\n * These options can be passed to {@link Conversation.sendMessage}.\n */\ninterface SendEmailOptions {\n /**\n * Message subject. Ignored for media messages.\n */\n subject?: string;\n}\n\n/**\n * Information about the last message of a conversation.\n */\ninterface LastMessage {\n /**\n * Message's index.\n */\n index?: number;\n\n /**\n * Message's creation date.\n */\n dateCreated?: Date;\n}\n\n/**\n * Conversation services.\n */\ninterface ConversationServices {\n users: Users;\n typingIndicator: TypingIndicator;\n network: Network;\n mcsClient: McsClient;\n syncClient: SyncClient;\n commandExecutor: CommandExecutor;\n}\n\n/**\n * Internal (private) state of the conversation.\n */\ninterface ConversationInternalState {\n uniqueName: string | null;\n status: ConversationStatus;\n attributes: JSONValue;\n createdBy?: string;\n dateCreated: Date | null;\n dateUpdated: Date | null;\n friendlyName: string | null;\n lastReadMessageIndex: number | null;\n lastMessage?: LastMessage;\n notificationLevel?: NotificationLevel;\n state?: ConversationState;\n bindings: ConversationBindings;\n}\n\n/**\n * Conversation descriptor.\n */\ninterface ConversationDescriptor {\n channel: string;\n entityName: string;\n uniqueName: string;\n attributes: JSONValue;\n createdBy?: string;\n friendlyName?: string;\n lastConsumedMessageIndex: number;\n dateCreated: Date | null;\n dateUpdated: Date | null;\n notificationLevel?: NotificationLevel;\n bindings?: ConversationBindings;\n}\n\n/**\n * Conversation links.\n */\ninterface ConversationLinks {\n self: string;\n messages: string;\n participants: string;\n}\n\n/**\n * Map of the fields that will be processed with update messages.\n */\nconst fieldMappings = {\n lastMessage: \"lastMessage\",\n attributes: \"attributes\",\n createdBy: \"createdBy\",\n dateCreated: \"dateCreated\",\n dateUpdated: \"dateUpdated\",\n friendlyName: \"friendlyName\",\n lastConsumedMessageIndex: \"lastConsumedMessageIndex\",\n notificationLevel: \"notificationLevel\",\n sid: \"sid\",\n status: \"status\",\n uniqueName: \"uniqueName\",\n state: \"state\",\n bindings: \"bindings\",\n};\n\n/**\n * A conversation represents communication between multiple Conversations\n * clients.\n */\nclass Conversation extends ReplayEventEmitter<ConversationEvents> {\n /**\n * Fired when a participant has joined the conversation.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - participant that joined the\n * conversation\n * @event\n */\n public static readonly participantJoined = \"participantJoined\";\n\n /**\n * Fired when a participant has left the conversation.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - participant that left the\n * conversation\n * @event\n */\n public static readonly participantLeft = \"participantLeft\";\n\n /**\n * Fired when data of a participant has been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the\n * following properties:\n * * {@link Participant} `participant` - participant that has received the\n * update\n * * {@link ParticipantUpdateReason}[] `updateReasons` - array of reasons\n * for the update\n * @event\n */\n public static readonly participantUpdated = \"participantUpdated\";\n\n /**\n * Fired when a new message has been added to the conversation.\n *\n * Parameters:\n * 1. {@link Message} `message` - message that has been added\n * @event\n */\n public static readonly messageAdded = \"messageAdded\";\n\n /**\n * Fired when message is removed from the conversation's message list.\n *\n * Parameters:\n * 1. {@link Message} `message` - message that has been removed\n * @event\n */\n public static readonly messageRemoved = \"messageRemoved\";\n\n /**\n * Fired when data of a message has been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the\n * following properties:\n * * {@link Message} `message` - message that has received the update\n * * {@link MessageUpdateReason}[] `updateReasons` - array of reasons for\n * the update\n * @event\n */\n public static readonly messageUpdated = \"messageUpdated\";\n\n /**\n * Fired when a participant has stopped typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant that has stopped\n * typing\n * @event\n */\n public static readonly typingEnded = \"typingEnded\";\n\n /**\n * Fired when a participant has started typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant that has started\n * typing\n * @event\n */\n public static readonly typingStarted = \"typingStarted\";\n\n /**\n * Fired when the data of the conversation has been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the\n * following properties:\n * * {@link Conversation} `conversation` - conversation that has received\n * the update\n * * {@link ConversationUpdateReason}[] `updateReasons` - array of reasons\n * for the update\n * @event\n */\n public static readonly updated = \"updated\";\n\n /**\n * Fired when the conversation was destroyed or the currently-logged-in user\n * has left private conversation.\n *\n * Parameters:\n * 1. {@link Conversation} `conversation` - conversation that has been removed\n * @event\n */\n public static readonly removed = \"removed\";\n\n /**\n * Logger instance.\n */\n private static readonly _logger = Logger.scope(\"Conversation\");\n\n /**\n * Unique system identifier of the conversation.\n */\n public readonly sid: string;\n\n /**\n * Conversation links for REST requests.\n * @internal\n */\n public readonly _links: ConversationLinks;\n\n /**\n * Map of participants.\n * @internal\n */\n public readonly _participants: Map<string, Participant>;\n\n /**\n * Configuration of the client that the conversation belongs to.\n */\n private readonly _configuration: Configuration;\n\n /**\n * Conversation service objects.\n */\n private readonly _services: ConversationServices;\n\n /**\n * Internal state of the conversation.\n */\n private readonly _internalState: ConversationInternalState;\n\n /**\n * Name of the conversation entity document.\n */\n private readonly _entityName: string;\n\n /**\n * Messages entity.\n */\n private readonly _messagesEntity: Messages;\n\n /**\n * Sync list containing messages.\n */\n private _messagesList?: SyncList;\n\n /**\n * Participants entity.\n */\n private readonly _participantsEntity: Participants;\n\n /**\n * Sync map containing participants.\n */\n private _participantsMap?: SyncMap;\n\n /**\n * Source of the most recent update.\n */\n private _dataSource!: ConversationsDataSource;\n\n /**\n * Promise for the conversation entity document.\n */\n private _entityPromise!: Promise<SyncDocument> | null;\n\n /**\n * Conversation entity document.\n */\n private _entity!: SyncDocument | null;\n\n /**\n * @param descriptor Conversation descriptor.\n * @param sid Conversation SID.\n * @param links Conversation links for REST requests.\n * @param configuration Client configuration.\n * @param services Conversation services.\n * @internal\n */\n public constructor(\n descriptor: ConversationDescriptor,\n sid: string,\n links: ConversationLinks,\n configuration: Configuration,\n services: ConversationServices\n ) {\n super();\n\n this.sid = sid;\n this._links = links;\n this._configuration = configuration;\n this._services = services;\n this._entityName = descriptor.channel;\n this._internalState = {\n uniqueName: descriptor.uniqueName || null,\n status: \"notParticipating\",\n attributes: descriptor.attributes ?? {},\n createdBy: descriptor.createdBy,\n dateCreated: parseTime(descriptor.dateCreated),\n dateUpdated: parseTime(descriptor.dateUpdated),\n friendlyName: descriptor.friendlyName || null,\n lastReadMessageIndex: Number.isInteger(\n descriptor.lastConsumedMessageIndex\n )\n ? descriptor.lastConsumedMessageIndex\n : null,\n bindings: descriptor.bindings ?? {},\n };\n\n if (descriptor.notificationLevel) {\n this._internalState.notificationLevel = descriptor.notificationLevel;\n }\n\n const participantsLinks = {\n participants: this._links.participants,\n };\n\n this._participants = new Map();\n this._participantsEntity = new Participants(\n this,\n this._participants,\n participantsLinks,\n this._configuration,\n this._services\n );\n this._participantsEntity.on(\"participantJoined\", (participant) =>\n this.emit(\"participantJoined\", participant)\n );\n this._participantsEntity.on(\"participantLeft\", (participant) =>\n this.emit(\"participantLeft\", participant)\n );\n this._participantsEntity.on(\n \"participantUpdated\",\n (args: ParticipantUpdatedEventArgs) =>\n this.emit(\"participantUpdated\", args)\n );\n\n this._messagesEntity = new Messages(this, configuration, services);\n this._messagesEntity.on(\"messageAdded\", (message) =>\n this._onMessageAdded(message)\n );\n this._messagesEntity.on(\"messageUpdated\", (args: MessageUpdatedEventArgs) =>\n this.emit(\"messageUpdated\", args)\n );\n this._messagesEntity.on(\"messageRemoved\", (message) =>\n this.emit(\"messageRemoved\", message)\n );\n }\n\n /**\n * Unique name of the conversation.\n */\n public get uniqueName(): string | null {\n return this._internalState.uniqueName;\n }\n\n /**\n * Status of the conversation.\n */\n public get status(): ConversationStatus {\n return this._internalState.status;\n }\n\n /**\n * Name of the conversation.\n */\n public get friendlyName(): string | null {\n return this._internalState.friendlyName;\n }\n\n /**\n * Date this conversation was last updated on.\n */\n public get dateUpdated(): Date | null {\n return this._internalState.dateUpdated;\n }\n\n /**\n * Date this conversation was created on.\n */\n public get dateCreated(): Date | null {\n return this._internalState.dateCreated;\n }\n\n /**\n * Identity of the user that created this conversation.\n */\n public get createdBy(): string {\n return this._internalState.createdBy ?? \"\";\n }\n\n /**\n * Custom attributes of the conversation.\n */\n public get attributes(): JSONValue {\n return this._internalState.attributes;\n }\n\n /**\n * Index of the last message the user has read in this conversation.\n */\n public get lastReadMessageIndex(): number | null {\n return this._internalState.lastReadMessageIndex;\n }\n\n /**\n * Last message sent to this conversation.\n */\n public get lastMessage(): LastMessage | undefined {\n return this._internalState.lastMessage ?? undefined;\n }\n\n /**\n * User notification level for this conversation.\n */\n public get notificationLevel(): NotificationLevel {\n return this._internalState.notificationLevel ?? \"default\";\n }\n\n /**\n * Conversation bindings. Undocumented feature (for now).\n * @internal\n */\n public get bindings(): ConversationBindings {\n return this._internalState.bindings;\n }\n\n /**\n * Current conversation limits.\n */\n public get limits(): ConversationLimits {\n return this._configuration.limits;\n }\n\n /**\n * State of the conversation.\n */\n public get state(): ConversationState | undefined {\n return this._internalState.state;\n }\n\n /**\n * Source of the conversation update.\n * @internal\n */\n public get _statusSource(): ConversationsDataSource {\n return this._dataSource;\n }\n\n /**\n * Preprocess the update object.\n * @param update The update object received from Sync.\n * @param conversationSid The SID of the conversation in question.\n */\n private static preprocessUpdate(update, conversationSid: string) {\n try {\n if (typeof update.attributes === \"string\") {\n update.attributes = JSON.parse(update.attributes);\n } else if (update.attributes) {\n JSON.stringify(update.attributes);\n }\n } catch (e) {\n Conversation._logger.warn(\n \"Retrieved malformed attributes from the server for conversation: \" +\n conversationSid\n );\n update.attributes = {};\n }\n\n try {\n if (update.dateCreated) {\n update.dateCreated = new Date(update.dateCreated);\n }\n } catch (e) {\n Conversation._logger.warn(\n \"Retrieved malformed dateCreated from the server for conversation: \" +\n conversationSid\n );\n delete update.dateCreated;\n }\n\n try {\n if (update.dateUpdated) {\n update.dateUpdated = new Date(update.dateUpdated);\n }\n } catch (e) {\n Conversation._logger.warn(\n \"Retrieved malformed dateUpdated from the server for conversation: \" +\n conversationSid\n );\n delete update.dateUpdated;\n }\n\n try {\n if (update.lastMessage && update.lastMessage.timestamp) {\n update.lastMessage.timestamp = new Date(update.lastMessage.timestamp);\n }\n } catch (e) {\n Conversation._logger.warn(\n \"Retrieved malformed lastMessage.timestamp from the server for conversation: \" +\n conversationSid\n );\n delete update.lastMessage.timestamp;\n }\n }\n\n /**\n * Add a participant to the conversation by its identity.\n * @param identity Identity of the Client to add.\n * @param attributes Attributes to be attached to the participant.\n * @returns The added participant.\n */\n @validateTypesAsync(nonEmptyString, optionalAttributesValidator)\n public async add(\n identity: string,\n attributes?: JSONValue\n ): Promise<ParticipantResponse> {\n return this._participantsEntity.add(identity, attributes ?? {});\n }\n\n /**\n * Add a non-chat participant to the conversation.\n * @param proxyAddress Proxy (Twilio) address of the participant.\n * @param address User address of the participant.\n * @param attributes Attributes to be attached to the participant.\n * @param bindingOptions Options for adding email participants - name and\n * CC/To level.\n * @returns The added participant.\n */\n @validateTypesAsync(\n nonEmptyString,\n nonEmptyString,\n optionalAttributesValidator\n )\n public async addNonChatParticipant(\n proxyAddress: string,\n address: string,\n attributes: JSONValue = {},\n bindingOptions: ParticipantBindingOptions = {}\n ): Promise<ParticipantResponse> {\n return this._participantsEntity.addNonChatParticipant(\n proxyAddress,\n address,\n attributes ?? {},\n bindingOptions ?? {}\n );\n }\n\n /**\n * Advance the conversation's last read message index to the current read\n * horizon. Rejects if the user is not a participant of the conversation. Last\n * read message index is updated only if the new index value is higher than\n * the previous.\n * @param index Message index to advance to.\n * @return Resulting unread messages count in the conversation.\n */\n @validateTypesAsync(nonNegativeInteger)\n public async advanceLastReadMessageIndex(index: number): Promise<number> {\n await this._subscribeStreams();\n\n if (index < (this.lastReadMessageIndex ?? 0)) {\n return await this._setLastReadMessageIndex(this.lastReadMessageIndex);\n }\n\n return await this._setLastReadMessageIndex(index);\n }\n\n /**\n * Delete the conversation and unsubscribe from its events.\n */\n public async delete(): Promise<Conversation> {\n await this._services.commandExecutor.mutateResource(\n \"delete\",\n this._links.self\n );\n\n return this;\n }\n\n /**\n * Get the custom attributes of this Conversation.\n */\n public async getAttributes(): Promise<JSONValue> {\n await this._subscribe();\n return this.attributes;\n }\n\n /**\n * Returns messages from the conversation using the paginator interface.\n * @param pageSize Number of messages to return in a single chunk. Default is\n * 30.\n * @param anchor Index of the newest message to fetch. Default is from the\n * end.\n * @param direction Query direction. By default, it queries backwards\n * from newer to older. The `\"forward\"` value will query in the opposite\n * direction.\n * @return A page of messages.\n */\n @validateTypesAsync(\n [\"undefined\", nonNegativeInteger],\n [\"undefined\", nonNegativeInteger],\n [\"undefined\", literal(\"backwards\", \"forward\")]\n )\n public async getMessages(\n pageSize?: number,\n anchor?: number,\n direction?: \"backwards\" | \"forward\"\n ): Promise<Paginator<Message>> {\n await this._subscribeStreams();\n return this._messagesEntity.getMessages(pageSize, anchor, direction);\n }\n\n /**\n * Get a list of all the participants who are joined to this conversation.\n */\n public async getParticipants(): Promise<Participant[]> {\n await this._subscribeStreams();\n return this._participantsEntity.getParticipants();\n }\n\n /**\n * Get conversation participants count.\n *\n * This method is semi-realtime. This means that this data will be eventually\n * correct, but will also be possibly incorrect for a few seconds. The\n * Conversations system does not provide real time events for counter values\n * changes.\n *\n * This is useful for any UI badges, but it is not recommended to build any\n * core application logic based on these counters being accurate in real time.\n */\n public async getParticipantsCount(): Promise<number> {\n const url = new UriBuilder(this._configuration.links.conversations)\n .path(this.sid)\n .build();\n const response = await this._services.network.get<ConversationResponse>(\n url\n );\n\n return response.body.participants_count ?? 0;\n }\n\n /**\n * Get a participant by its SID.\n * @param participantSid Participant SID.\n */\n @validateTypesAsync(nonEmptyString)\n public async getParticipantBySid(\n participantSid: string\n ): Promise<Participant | null> {\n return this._participantsEntity.getParticipantBySid(participantSid);\n }\n\n /**\n * Get a participant by its identity.\n * @param identity Participant identity.\n */\n @validateTypesAsync(nonEmptyString)\n public async getParticipantByIdentity(\n identity: string | null = \"\"\n ): Promise<Participant | null> {\n return this._participantsEntity.getParticipantByIdentity(identity ?? \"\");\n }\n\n /**\n * Get the total message count in the conversation.\n *\n * This method is semi-realtime. This means that this data will be eventually\n * correct, but will also be possibly incorrect for a few seconds. The\n * Conversations system does not provide real time events for counter values\n * changes.\n *\n * This is useful for any UI badges, but it is not recommended to build any\n * core application logic based on these counters being accurate in real time.\n */\n public async getMessagesCount(): Promise<number> {\n const url = new UriBuilder(this._configuration.links.conversations)\n .path(this.sid)\n .build();\n const response = await this._services.network.get<ConversationResponse>(\n url\n );\n\n return response.body.messages_count ?? 0;\n }\n\n /**\n * Get count of unread messages for the user if they are a participant of this\n * conversation. Rejects if the user is not a participant of the conversation.\n *\n * Use this method to obtain the number of unread messages together with\n * {@link Conversation.updateLastReadMessageIndex} instead of relying on the\n * message indices which may have gaps. See {@link Message.index} for details.\n *\n * This method is semi-realtime. This means that this data will be eventually\n * correct, but it will also be possibly incorrect for a few seconds. The\n * Conversations system does not provide real time events for counter values\n * changes.\n *\n * This is useful for any UI badges, but it is not recommended to build any\n * core application logic based on these counters being accurate in real time.\n *\n * If the read horizon is not set, this function will return null. This could mean\n * that all messages in the conversation are unread, or that the read horizon system\n * is not being used. How to interpret this `null` value is up to the customer application.\n *\n * @return Number of unread messages based on the current read horizon set for\n * the user or `null` if the read horizon is not set.\n */\n public async getUnreadMessagesCount(): Promise<number | null> {\n const url = new UriBuilder(this._configuration.links.myConversations)\n .path(this.sid)\n .build();\n const response = await this._services.network.get<ConversationResponse>(\n url\n );\n\n if (response.body.conversation_sid !== this.sid) {\n throw new Error(\n \"Conversation was not found in the user conversations list\"\n );\n }\n\n const unreadMessageCount = response.body.unread_messages_count;\n\n if (typeof unreadMessageCount === \"number\") {\n return unreadMessageCount;\n }\n\n return null;\n }\n\n /**\n * Join the conversation and subscribe to its events.\n */\n public async join(): Promise<Conversation> {\n await this._services.commandExecutor.mutateResource<\n AddParticipantRequest,\n ParticipantResponse\n >(\"post\", this._links.participants, {\n identity: this._configuration.userIdentity,\n });\n\n return this;\n }\n\n /**\n * Leave the conversation.\n */\n public async leave(): Promise<Conversation> {\n if (this._internalState.status === \"joined\") {\n await this._services.commandExecutor.mutateResource(\n \"delete\",\n `${this._links.participants}/${encodeURIComponent(\n this._configuration.userIdentity\n )}`\n );\n }\n\n return this;\n }\n\n /**\n * Remove a participant from the conversation. When a string is passed as the\n * argument, it will assume that the string is an identity or SID.\n * @param participant Identity, SID or the participant object to remove.\n */\n @validateTypesAsync([nonEmptyString, Participant])\n public async removeParticipant(\n participant: string | Participant\n ): Promise<void> {\n await this._participantsEntity.remove(\n typeof participant === \"string\" ? participant : participant.sid\n );\n }\n\n /**\n * Send a message to the conversation.\n * @param message Message body for the text message,\n * `FormData` or {@link SendMediaOptions} for media content. Sending FormData\n * is supported only with the browser engine.\n * @param messageAttributes Attributes for the message.\n * @param emailOptions Email options for the message.\n * @return Index of the new message.\n */\n @validateTypesAsync(\n [\n \"string\",\n FormData,\n literal(null),\n objectSchema(\"media options\", {\n contentType: nonEmptyString,\n media: custom((value) => {\n let isValid =\n (typeof value === \"string\" && value.length > 0) ||\n value instanceof Uint8Array ||\n value instanceof ArrayBuffer;\n\n if (typeof Blob === \"function\") {\n isValid = isValid || value instanceof Blob;\n }\n\n return [\n isValid,\n \"a non-empty string, an instance of Buffer or an instance of Blob\",\n ];\n }),\n }),\n ],\n optionalAttributesValidator,\n [\n \"undefined\",\n literal(null),\n objectSchema(\"email attributes\", {\n subject: [nonEmptyString, \"undefined\"],\n }),\n ]\n )\n public async sendMessage(\n message: null | string | FormData | SendMediaOptions,\n messageAttributes?: JSONValue,\n emailOptions?: SendEmailOptions\n ): Promise<number> {\n if (typeof message === \"string\" || message === null) {\n const response = await this._messagesEntity.send(\n message,\n messageAttributes,\n emailOptions\n );\n return parseToNumber(response.index) ?? 0;\n }\n\n const response = await this._messagesEntity.sendMedia(\n message,\n messageAttributes,\n emailOptions\n );\n return parseToNumber(response.index) ?? 0;\n }\n\n /**\n * New interface to prepare for sending a message.\n * Use this instead of {@link Message.sendMessage}.\n * @return A MessageBuilder to help set all message sending options.\n */\n public prepareMessage(): MessageBuilder {\n return new MessageBuilder(this.limits, this._messagesEntity);\n }\n\n /**\n * Set last read message index of the conversation to the index of the last\n * known message.\n * @return Resulting unread messages count in the conversation.\n */\n public async setAllMessagesRead(): Promise<number> {\n await this._subscribeStreams();\n\n const messagesPage = await this.getMessages(1);\n\n if (messagesPage.items.length > 0) {\n return this.advanceLastReadMessageIndex(messagesPage.items[0].index);\n }\n\n return 0;\n }\n\n /**\n * Set all messages in the conversation unread.\n * @returns New count of unread messages after this update.\n */\n public async setAllMessagesUnread(): Promise<number> {\n await this._subscribeStreams();\n return await this._setLastReadMessageIndex(null);\n }\n\n /**\n * Set user notification level for this conversation.\n * @param notificationLevel New user notification level.\n */\n @validateTypesAsync(literal(\"default\", \"muted\"))\n public async setUserNotificationLevel(\n notificationLevel: NotificationLevel\n ): Promise<void> {\n await this._services.commandExecutor.mutateResource<EditNotificationLevelRequest>(\n \"post\",\n `${this._configuration.links.myConversations}/${this.sid}`,\n {\n notification_level: notificationLevel,\n }\n );\n }\n\n /**\n * Send a notification to the server indicating that this client is currently\n * typing in this conversation. Typing ended notification is sent after a\n * while automatically, but by calling this method again you ensure that\n * typing ended is not received.\n */\n public typing(): Promise<void> {\n return this._services.typingIndicator.send(this.sid);\n }\n\n /**\n * Update the attributes of the conversation.\n * @param attributes New attributes.\n */\n @validateTypesAsync(attributesValidator)\n public async updateAttributes(attributes: JSONValue): Promise<Conversation> {\n await this._services.commandExecutor.mutateResource<\n EditConversationRequest,\n ConversationResponse\n >(\"post\", this._links.self, {\n attributes:\n attributes !== undefined ? JSON.stringify(attributes) : undefined,\n });\n\n return this;\n }\n\n /**\n * Update the friendly name of the conversation.\n * @param friendlyName New friendly name.\n */\n @validateTypesAsync(\"string\")\n public async updateFriendlyName(friendlyName: string): Promise<Conversation> {\n if (this._internalState.friendlyName !== friendlyName) {\n await this._services.commandExecutor.mutateResource<\n EditConversationRequest,\n ConversationResponse\n >(\"post\", this._links.self, { friendly_name: friendlyName });\n }\n\n return this;\n }\n\n /**\n * Set the last read message index to the current read horizon.\n * @param index Message index to set as last read. If null is provided, then\n * the behavior is identical to {@link Conversation.setAllMessagesUnread}.\n * @returns New count of unread messages after this update.\n */\n @validateTypesAsync([literal(null), nonNegativeInteger])\n public async updateLastReadMessageIndex(\n index: number | null\n ): Promise<number> {\n await this._subscribeStreams();\n return this._setLastReadMessageIndex(index);\n }\n\n /**\n * Update the unique name of the conversation.\n * @param uniqueName New unique name for the conversation. Setting unique name\n * to null removes it.\n */\n @validateTypesAsync([\"string\", literal(null)])\n public async updateUniqueName(\n uniqueName: string | null\n ): Promise<Conversation> {\n if (this._internalState.uniqueName !== uniqueName) {\n uniqueName ||= \"\";\n\n await this._services.commandExecutor.mutateResource<\n EditConversationRequest,\n ConversationResponse\n >(\"post\", this._links.self, {\n unique_name: uniqueName,\n });\n }\n\n return this;\n }\n\n /**\n * Load and subscribe to this conversation and do not subscribe to its\n * participants and messages. This or _subscribeStreams will need to be called\n * before any events on conversation will fire.\n * @internal\n */\n public async _subscribe(): Promise<SyncDocument> {\n if (this._entityPromise) {\n return this._entityPromise;\n }\n\n this._entityPromise = this._services.syncClient.document({\n id: this._entityName,\n mode: \"open_existing\",\n });\n\n try {\n this._entity = await this._entityPromise;\n this._entity.on(\"updated\", (args) => this._update(args.data));\n this._entity.on(\"removed\", () => this.emit(\"removed\", this));\n this._update(this._entity.data);\n\n return this._entity;\n } catch (err) {\n this._entity = null;\n this._entityPromise = null;\n\n if (this._services.syncClient.connectionState != \"disconnected\") {\n Conversation._logger.error(\"Failed to get conversation object\", err);\n }\n Conversation._logger.debug(\n \"ERROR: Failed to get conversation object\",\n err\n );\n\n throw err;\n }\n }\n\n /**\n * Fetch participants and messages of the conversation. This method needs to\n * be called during conversation initialization to catch broken conversations\n * (broken conversations are conversations that have essential Sync entities\n * missing, i.e. the conversation document, the messages list or the\n * participant map). In case of this conversation being broken, the method\n * will throw an exception that will be caught and handled gracefully.\n * @internal\n */\n public async _fetchStreams() {\n await this._subscribe();\n Conversation._logger.trace(\n \"_streamsAvailable, this.entity.data=\",\n this._entity?.data\n );\n\n const data = this._entity?.data as Record<string, string>;\n this._messagesList = await this._services.syncClient.list({\n id: data.messages,\n mode: \"open_existing\",\n });\n this._participantsMap = await this._services.syncClient.map({\n id: data.roster,\n mode: \"open_existing\",\n });\n }\n\n /**\n * Load the attributes of this conversation and instantiate its participants\n * and messages. This or _subscribe will need to be called before any events\n * on the conversation will fire. This will need to be called before any\n * events on participants or messages will fire\n * @internal\n */\n public async _subscribeStreams() {\n try {\n await this._subscribe();\n Conversation._logger.trace(\n \"_subscribeStreams, this.entity.data=\",\n this._entity?.data\n );\n\n const data = this._entity?.data as Record<string, string>;\n const messagesObjectName = data.messages;\n const rosterObjectName = data.roster;\n\n await Promise.all([\n this._messagesEntity.subscribe(\n this._messagesList ?? messagesObjectName\n ),\n this._participantsEntity.subscribe(\n this._participantsMap ?? rosterObjectName\n ),\n ]);\n } catch (err) {\n if (this._services.syncClient.connectionState !== \"disconnected\") {\n Conversation._logger.error(\n \"Failed to subscribe on conversation objects\",\n this.sid,\n err\n );\n }\n Conversation._logger.debug(\n \"ERROR: Failed to subscribe on conversation objects\",\n this.sid,\n err\n );\n\n throw err;\n }\n }\n\n /**\n * Stop listening for and firing events on this conversation.\n * @internal\n */\n public async _unsubscribe() {\n if (this._entity) {\n await this._entity.close();\n this._entity = null;\n this._entityPromise = null;\n }\n\n return Promise.all([\n this._participantsEntity.unsubscribe(),\n this._messagesEntity.unsubscribe(),\n ]);\n }\n\n /**\n * Set conversation status.\n * @internal\n */\n public _setStatus(\n status: ConversationStatus,\n source: ConversationsDataSource\n ) {\n this._dataSource = source;\n\n if (this._internalState.status === status) {\n return;\n }\n\n this._internalState.status = status;\n\n if (status === \"joined\") {\n this._subscribeStreams().catch((err) => {\n Conversation._logger.debug(\n \"ERROR while setting conversation status \" + status,\n err\n );\n if (this._services.syncClient.connectionState !== \"disconnected\") {\n throw err;\n }\n });\n return;\n }\n\n if (this._entityPromise) {\n this._unsubscribe().catch((err) => {\n Conversation._logger.debug(\n \"ERROR while setting conversation status \" + status,\n err\n );\n if (this._services.syncClient.connectionState !== \"disconnected\") {\n throw err;\n }\n });\n }\n }\n\n /**\n * Update the local conversation object with new values.\n * @internal\n */\n public _update(update) {\n Conversation._logger.trace(\"_update\", update);\n\n Conversation.preprocessUpdate(update, this.sid);\n const updateReasons = new Set<ConversationUpdateReason>();\n\n for (const key of Object.keys(update)) {\n const localKey = fieldMappings[key];\n\n if (!localKey) {\n continue;\n }\n\n switch (localKey) {\n case fieldMappings.status:\n if (\n !update.status ||\n update.status === \"unknown\" ||\n this._internalState.status === update.status\n ) {\n break;\n }\n\n this._internalState.status = update.status;\n updateReasons.add(localKey);\n\n break;\n case fieldMappings.attributes:\n if (isEqual(this._internalState.attributes, update.attributes)) {\n break;\n }\n\n this._internalState.attributes = update.attributes;\n updateReasons.add(localKey);\n\n break;\n case fieldMappings.lastConsumedMessageIndex:\n if (\n update.lastConsumedMessageIndex === undefined ||\n update.lastConsumedMessageIndex ===\n this._internalState.lastReadMessageIndex\n ) {\n break;\n }\n\n this._internalState.lastReadMessageIndex =\n update.lastConsumedMessageIndex;\n updateReasons.add(\"lastReadMessageIndex\");\n\n break;\n case fieldMappings.lastMessage:\n if (this._internalState.lastMessage && !update.lastMessage) {\n delete this._internalState.lastMessage;\n updateReasons.add(localKey);\n\n break;\n }\n\n this._internalState.lastMessage =\n this._internalState.lastMessage || {};\n\n if (\n update.lastMessage?.index !== undefined &&\n update.lastMessage.index !== this._internalState.lastMessage.index\n ) {\n this._internalState.lastMessage.index = update.lastMessage.index;\n updateReasons.add(localKey);\n }\n\n if (\n update.lastMessage?.timestamp !== undefined &&\n this._internalState.lastMessage?.dateCreated?.getTime() !==\n update.lastMessage.timestamp.getTime()\n ) {\n this._internalState.lastMessage.dateCreated =\n update.lastMessage.timestamp;\n updateReasons.add(localKey);\n }\n\n if (isEqual(this._internalState.lastMessage, {})) {\n delete this._internalState.lastMessage;\n }\n\n break;\n case fieldMappings.state:\n const state = update.state || undefined;\n\n if (state !== undefined) {\n state.dateUpdated = new Date(state.dateUpdated);\n }\n\n if (isEqual(this._internalState.state, state)) {\n break;\n }\n\n this._internalState.state = state;\n updateReasons.add(localKey);\n\n break;\n case fieldMappings.bindings:\n if (isEqual(this._internalState.bindings, update.bindings)) {\n break;\n }\n\n this._internalState.bindings = update.bindings;\n updateReasons.add(localKey);\n\n break;\n default:\n const isDate = update[key] instanceof Date;\n const keysMatchAsDates =\n isDate &&\n this._internalState[localKey]?.getTime() === update[key].getTime();\n const keysMatchAsNonDates = !isDate && this[localKey] === update[key];\n\n if (keysMatchAsDates || keysMatchAsNonDates) {\n break;\n }\n\n this._internalState[localKey] = update[key];\n updateReasons.add(localKey);\n }\n }\n\n if (updateReasons.size > 0) {\n this.emit(\"updated\", {\n conversation: this,\n updateReasons: [...updateReasons],\n });\n }\n }\n\n /**\n * Handle onMessageAdded event.\n */\n private _onMessageAdded(message) {\n for (const participant of this._participants.values()) {\n if (participant.identity === message.author) {\n participant._endTyping();\n break;\n }\n }\n this.emit(\"messageAdded\", message);\n }\n\n /**\n * Set last read message index.\n * @param index New index to set.\n */\n private async _setLastReadMessageIndex(\n index: number | null\n ): Promise<number> {\n const result = await this._services.commandExecutor.mutateResource<\n EditLastReadMessageIndexRequest,\n EditLastReadMessageIndexResponse\n >(\"post\", `${this._configuration.links.myConversations}/${this.sid}`, {\n last_read_message_index: index,\n });\n\n return result.unread_messages_count;\n }\n}\n\nexport {\n ConversationDescriptor,\n Conversation,\n ConversationServices,\n ConversationUpdateReason,\n ConversationStatus,\n NotificationLevel,\n ConversationState,\n ConversationUpdatedEventArgs,\n SendMediaOptions,\n SendEmailOptions,\n LastMessage,\n ConversationBindings,\n ConversationEmailBinding,\n};\n"],"names":["ReplayEventEmitter","parseTime","Participants","Messages","UriBuilder","parseToNumber","MessageBuilder","isEqual","Logger","__decorate","validateTypesAsync","nonEmptyString","optionalAttributesValidator","nonNegativeInteger","literal","Participant","objectSchema","custom","attributesValidator"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgQA;;AAEG;AACH,MAAM,aAAa,GAAG;AACpB,IAAA,WAAW,EAAE,aAAa;AAC1B,IAAA,UAAU,EAAE,YAAY;AACxB,IAAA,SAAS,EAAE,WAAW;AACtB,IAAA,WAAW,EAAE,aAAa;AAC1B,IAAA,WAAW,EAAE,aAAa;AAC1B,IAAA,YAAY,EAAE,cAAc;AAC5B,IAAA,wBAAwB,EAAE,0BAA0B;AACpD,IAAA,iBAAiB,EAAE,mBAAmB;AACtC,IAAA,GAAG,EAAE,KAAK;AACV,IAAA,MAAM,EAAE,QAAQ;AAChB,IAAA,UAAU,EAAE,YAAY;AACxB,IAAA,KAAK,EAAE,OAAO;AACd,IAAA,QAAQ,EAAE,UAAU;CACrB,CAAC;AAEF;;;AAGG;AACH,MAAM,YAAa,SAAQA,qCAAsC,CAAA;AA2L/D;;;;;;;AAOG;IACH,WACE,CAAA,UAAkC,EAClC,GAAW,EACX,KAAwB,EACxB,aAA4B,EAC5B,QAA8B,EAAA;;AAE9B,QAAA,KAAK,EAAE,CAAC;AAER,QAAA,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;AACf,QAAA,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;AACpB,QAAA,IAAI,CAAC,cAAc,GAAG,aAAa,CAAC;AACpC,QAAA,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;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AA;AAODT,oBAAA,CAAA;IADCC,2CAAkB,CAAC,QAAQ,CAAC;;;;AAU5B,CAAA,EAAA,YAAA,CAAA,SAAA,EAAA,oBAAA,EAAA,IAAA,CAAA,CAAA;AASDD,oBAAA,CAAA;IADCC,2CAAkB,CAAC,CAACI,gCAAO,CAAC,IAAI,CAAC,EAAED,2CAAkB,CAAC,CAAC;;;;AAMvD,CAAA,EAAA,YAAA,CAAA,SAAA,EAAA,4BAAA,EAAA,IAAA,CAAA,CAAA;AAQDJ,oBAAA,CAAA;IADCC,2CAAkB,CAAC,CAAC,QAAQ,EAAEI,gCAAO,CAAC,IAAI,CAAC,CAAC,CAAC;;;;AAgB7C,CAAA,EAAA,YAAA,CAAA,SAAA,EAAA,kBAAA,EAAA,IAAA,CAAA;;;;"}
1
+ {"version":3,"file":"conversation.js","sources":["../src/conversation.ts"],"sourcesContent":["import \"isomorphic-form-data\";\nimport { Logger } from \"./logger\";\nimport { ParticipantBindingOptions, Participants } from \"./data/participants\";\nimport {\n Participant,\n ParticipantUpdatedEventArgs,\n ParticipantUpdateReason,\n} from \"./participant\";\nimport { Messages } from \"./data/messages\";\nimport {\n Message,\n MessageUpdatedEventArgs,\n MessageUpdateReason,\n} from \"./message\";\nimport { UriBuilder, parseToNumber, parseTime } from \"./util\";\nimport { Users } from \"./data/users\";\nimport { Paginator } from \"./interfaces/paginator\";\nimport { ConversationsDataSource } from \"./data/conversations\";\nimport { McsClient } from \"@twilio/mcs-client\";\nimport { SyncClient, SyncDocument, SyncList, SyncMap } from \"twilio-sync\";\nimport { TypingIndicator } from \"./services/typing-indicator\";\nimport { Network } from \"./services/network\";\nimport {\n validateTypesAsync,\n custom,\n literal,\n nonEmptyString,\n nonNegativeInteger,\n objectSchema,\n} from \"@twilio/declarative-type-validator\";\nimport {\n attributesValidator,\n optionalAttributesValidator,\n} from \"./interfaces/attributes\";\nimport { Configuration } from \"./configuration\";\nimport { CommandExecutor } from \"./command-executor\";\nimport { AddParticipantRequest } from \"./interfaces/commands/add-participant\";\nimport { EditConversationRequest } from \"./interfaces/commands/edit-conversation\";\nimport { ConversationResponse } from \"./interfaces/commands/conversation-response\";\nimport { ParticipantResponse } from \"./interfaces/commands/participant-response\";\nimport { EditNotificationLevelRequest } from \"./interfaces/commands/edit-notification-level\";\nimport {\n EditLastReadMessageIndexRequest,\n EditLastReadMessageIndexResponse,\n} from \"./interfaces/commands/edit-last-read-message-index\";\nimport { ConversationLimits } from \"./interfaces/conversation-limits\";\nimport { MessageBuilder } from \"./message-builder\";\nimport { ReplayEventEmitter } from \"@twilio/replay-event-emitter\";\nimport isEqual from \"lodash.isequal\";\nimport { JSONValue } from \"./types\";\n\n/**\n * Conversation events.\n */\ntype ConversationEvents = {\n participantJoined: (participant: Participant) => void;\n participantLeft: (participant: Participant) => void;\n participantUpdated: (data: {\n participant: Participant;\n updateReasons: ParticipantUpdateReason[];\n }) => void;\n messageAdded: (message: Message) => void;\n messageRemoved: (message: Message) => void;\n messageUpdated: (data: {\n message: Message;\n updateReasons: MessageUpdateReason[];\n }) => void;\n typingEnded: (participant: Participant) => void;\n typingStarted: (participant: Participant) => void;\n updated: (data: {\n conversation: Conversation;\n updateReasons: ConversationUpdateReason[];\n }) => void;\n removed: (conversation: Conversation) => void;\n};\n\n/**\n * Reason for the `updated` event emission by a conversation.\n */\ntype ConversationUpdateReason =\n | \"attributes\"\n | \"createdBy\"\n | \"dateCreated\"\n | \"dateUpdated\"\n | \"friendlyName\"\n | \"lastReadMessageIndex\"\n | \"state\"\n | \"status\"\n | \"uniqueName\"\n | \"lastMessage\"\n | \"notificationLevel\"\n | \"bindings\";\n\n/**\n * Status of the conversation, relative to the client: whether the conversation\n * has been `joined` or the client is `notParticipating` in the conversation.\n */\ntype ConversationStatus = \"notParticipating\" | \"joined\";\n\n/**\n * User's notification level for the conversation. Determines\n * whether the currently logged-in user will receive pushes for events\n * in this conversation. Can be either `muted` or `default`, where\n * `default` defers to the global service push configuration.\n */\ntype NotificationLevel = \"default\" | \"muted\";\n\n/**\n * State of the conversation.\n */\ninterface ConversationState {\n /**\n * Current state.\n */\n current: \"active\" | \"inactive\" | \"closed\";\n\n /**\n * Date at which the latest conversation state update happened.\n */\n dateUpdated: Date;\n}\n\n/**\n * Event arguments for the `updated` event.\n */\ninterface ConversationUpdatedEventArgs {\n conversation: Conversation;\n updateReasons: ConversationUpdateReason[];\n}\n\n/**\n * Binding for email conversation.\n */\ninterface ConversationBindings {\n email?: ConversationEmailBinding;\n sms?: ConversationSmsBinding;\n}\n\n/**\n * Binding for email conversation.\n */\ninterface ConversationEmailBinding {\n name?: string;\n projected_address: string;\n}\n\n/**\n * Binding for SMS conversation.\n */\ninterface ConversationSmsBinding {\n address?: string;\n}\n\n/**\n * Configuration for attaching a media file to a message.\n * These options can be passed to {@link Conversation.sendMessage} and\n * {@link MessageBuilder.addMedia}.\n */\ninterface SendMediaOptions {\n /**\n * Content type of media.\n */\n contentType: null | string;\n\n /**\n * Optional filename.\n */\n filename?: string;\n\n /**\n * Content to post.\n */\n media: null | string | Buffer | Blob;\n}\n\n/**\n * These options can be passed to {@link Conversation.sendMessage}.\n */\ninterface SendEmailOptions {\n /**\n * Message subject. Ignored for media messages.\n */\n subject?: string;\n}\n\n/**\n * Information about the last message of a conversation.\n */\ninterface LastMessage {\n /**\n * Message's index.\n */\n index?: number;\n\n /**\n * Message's creation date.\n */\n dateCreated?: Date;\n}\n\n/**\n * Conversation services.\n */\ninterface ConversationServices {\n users: Users;\n typingIndicator: TypingIndicator;\n network: Network;\n mcsClient: McsClient;\n syncClient: SyncClient;\n commandExecutor: CommandExecutor;\n}\n\n/**\n * Internal (private) state of the conversation.\n */\ninterface ConversationInternalState {\n uniqueName: string | null;\n status: ConversationStatus;\n attributes: JSONValue;\n createdBy?: string;\n dateCreated: Date | null;\n dateUpdated: Date | null;\n friendlyName: string | null;\n lastReadMessageIndex: number | null;\n lastMessage?: LastMessage;\n notificationLevel?: NotificationLevel;\n state?: ConversationState;\n bindings: ConversationBindings;\n}\n\n/**\n * Conversation descriptor.\n */\ninterface ConversationDescriptor {\n channel: string;\n entityName: string;\n uniqueName: string;\n attributes: JSONValue;\n createdBy?: string;\n friendlyName?: string;\n lastConsumedMessageIndex: number;\n dateCreated: Date | null;\n dateUpdated: Date | null;\n notificationLevel?: NotificationLevel;\n bindings?: ConversationBindings;\n}\n\n/**\n * Conversation links.\n */\ninterface ConversationLinks {\n self: string;\n messages: string;\n participants: string;\n}\n\n/**\n * Map of the fields that will be processed with update messages.\n */\nconst fieldMappings = {\n lastMessage: \"lastMessage\",\n attributes: \"attributes\",\n createdBy: \"createdBy\",\n dateCreated: \"dateCreated\",\n dateUpdated: \"dateUpdated\",\n friendlyName: \"friendlyName\",\n lastConsumedMessageIndex: \"lastConsumedMessageIndex\",\n notificationLevel: \"notificationLevel\",\n sid: \"sid\",\n status: \"status\",\n uniqueName: \"uniqueName\",\n state: \"state\",\n bindings: \"bindings\",\n};\n\n/**\n * A conversation represents communication between multiple Conversations\n * clients.\n */\nclass Conversation extends ReplayEventEmitter<ConversationEvents> {\n /**\n * Fired when a participant has joined the conversation.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - participant that joined the\n * conversation\n * @event\n */\n public static readonly participantJoined = \"participantJoined\";\n\n /**\n * Fired when a participant has left the conversation.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - participant that left the\n * conversation\n * @event\n */\n public static readonly participantLeft = \"participantLeft\";\n\n /**\n * Fired when data of a participant has been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the\n * following properties:\n * * {@link Participant} `participant` - participant that has received the\n * update\n * * {@link ParticipantUpdateReason}[] `updateReasons` - array of reasons\n * for the update\n * @event\n */\n public static readonly participantUpdated = \"participantUpdated\";\n\n /**\n * Fired when a new message has been added to the conversation.\n *\n * Parameters:\n * 1. {@link Message} `message` - message that has been added\n * @event\n */\n public static readonly messageAdded = \"messageAdded\";\n\n /**\n * Fired when message is removed from the conversation's message list.\n *\n * Parameters:\n * 1. {@link Message} `message` - message that has been removed\n * @event\n */\n public static readonly messageRemoved = \"messageRemoved\";\n\n /**\n * Fired when data of a message has been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the\n * following properties:\n * * {@link Message} `message` - message that has received the update\n * * {@link MessageUpdateReason}[] `updateReasons` - array of reasons for\n * the update\n * @event\n */\n public static readonly messageUpdated = \"messageUpdated\";\n\n /**\n * Fired when a participant has stopped typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant that has stopped\n * typing\n * @event\n */\n public static readonly typingEnded = \"typingEnded\";\n\n /**\n * Fired when a participant has started typing.\n *\n * Parameters:\n * 1. {@link Participant} `participant` - the participant that has started\n * typing\n * @event\n */\n public static readonly typingStarted = \"typingStarted\";\n\n /**\n * Fired when the data of the conversation has been updated.\n *\n * Parameters:\n * 1. object `data` - info object provided with the event. It has the\n * following properties:\n * * {@link Conversation} `conversation` - conversation that has received\n * the update\n * * {@link ConversationUpdateReason}[] `updateReasons` - array of reasons\n * for the update\n * @event\n */\n public static readonly updated = \"updated\";\n\n /**\n * Fired when the conversation was destroyed or the currently-logged-in user\n * has left private conversation.\n *\n * Parameters:\n * 1. {@link Conversation} `conversation` - conversation that has been removed\n * @event\n */\n public static readonly removed = \"removed\";\n\n /**\n * Logger instance.\n */\n private static readonly _logger = Logger.scope(\"Conversation\");\n\n /**\n * Unique system identifier of the conversation.\n */\n public readonly sid: string;\n\n /**\n * Conversation links for REST requests.\n * @internal\n */\n public readonly _links: ConversationLinks;\n\n /**\n * Map of participants.\n * @internal\n */\n public readonly _participants: Map<string, Participant>;\n\n /**\n * Configuration of the client that the conversation belongs to.\n */\n private readonly _configuration: Configuration;\n\n /**\n * Conversation service objects.\n */\n private readonly _services: ConversationServices;\n\n /**\n * Internal state of the conversation.\n */\n private readonly _internalState: ConversationInternalState;\n\n /**\n * Name of the conversation entity document.\n */\n private readonly _entityName: string;\n\n /**\n * Messages entity.\n */\n private readonly _messagesEntity: Messages;\n\n /**\n * Sync list containing messages.\n */\n private _messagesList?: SyncList;\n\n /**\n * Participants entity.\n */\n private readonly _participantsEntity: Participants;\n\n /**\n * Sync map containing participants.\n */\n private _participantsMap?: SyncMap;\n\n /**\n * Source of the most recent update.\n */\n private _dataSource!: ConversationsDataSource;\n\n /**\n * Promise for the conversation entity document.\n */\n private _entityPromise!: Promise<SyncDocument> | null;\n\n /**\n * Conversation entity document.\n */\n private _entity!: SyncDocument | null;\n\n /**\n * @param descriptor Conversation descriptor.\n * @param sid Conversation SID.\n * @param links Conversation links for REST requests.\n * @param configuration Client configuration.\n * @param services Conversation services.\n * @internal\n */\n public constructor(\n descriptor: ConversationDescriptor,\n sid: string,\n links: ConversationLinks,\n configuration: Configuration,\n services: ConversationServices\n ) {\n super();\n\n this.sid = sid;\n this._links = links;\n this._configuration = configuration;\n this._services = services;\n this._entityName = descriptor.channel;\n this._internalState = {\n uniqueName: descriptor.uniqueName || null,\n status: \"notParticipating\",\n attributes: descriptor.attributes ?? {},\n createdBy: descriptor.createdBy,\n dateCreated: parseTime(descriptor.dateCreated),\n dateUpdated: parseTime(descriptor.dateUpdated),\n friendlyName: descriptor.friendlyName || null,\n lastReadMessageIndex: Number.isInteger(\n descriptor.lastConsumedMessageIndex\n )\n ? descriptor.lastConsumedMessageIndex\n : null,\n bindings: descriptor.bindings ?? {},\n };\n\n if (descriptor.notificationLevel) {\n this._internalState.notificationLevel = descriptor.notificationLevel;\n }\n\n const participantsLinks = {\n participants: this._links.participants,\n };\n\n this._participants = new Map();\n this._participantsEntity = new Participants(\n this,\n this._participants,\n participantsLinks,\n this._configuration,\n this._services\n );\n this._participantsEntity.on(\"participantJoined\", (participant) =>\n this.emit(\"participantJoined\", participant)\n );\n this._participantsEntity.on(\"participantLeft\", (participant) =>\n this.emit(\"participantLeft\", participant)\n );\n this._participantsEntity.on(\n \"participantUpdated\",\n (args: ParticipantUpdatedEventArgs) =>\n this.emit(\"participantUpdated\", args)\n );\n\n this._messagesEntity = new Messages(this, configuration, services);\n this._messagesEntity.on(\"messageAdded\", (message) =>\n this._onMessageAdded(message)\n );\n this._messagesEntity.on(\"messageUpdated\", (args: MessageUpdatedEventArgs) =>\n this.emit(\"messageUpdated\", args)\n );\n this._messagesEntity.on(\"messageRemoved\", (message) =>\n this.emit(\"messageRemoved\", message)\n );\n }\n\n /**\n * Unique name of the conversation.\n */\n public get uniqueName(): string | null {\n return this._internalState.uniqueName;\n }\n\n /**\n * Status of the conversation.\n */\n public get status(): ConversationStatus {\n return this._internalState.status;\n }\n\n /**\n * Name of the conversation.\n */\n public get friendlyName(): string | null {\n return this._internalState.friendlyName;\n }\n\n /**\n * Date this conversation was last updated on.\n */\n public get dateUpdated(): Date | null {\n return this._internalState.dateUpdated;\n }\n\n /**\n * Date this conversation was created on.\n */\n public get dateCreated(): Date | null {\n return this._internalState.dateCreated;\n }\n\n /**\n * Identity of the user that created this conversation.\n */\n public get createdBy(): string {\n return this._internalState.createdBy ?? \"\";\n }\n\n /**\n * Custom attributes of the conversation.\n */\n public get attributes(): JSONValue {\n return this._internalState.attributes;\n }\n\n /**\n * Index of the last message the user has read in this conversation.\n */\n public get lastReadMessageIndex(): number | null {\n return this._internalState.lastReadMessageIndex;\n }\n\n /**\n * Last message sent to this conversation.\n */\n public get lastMessage(): LastMessage | undefined {\n return this._internalState.lastMessage ?? undefined;\n }\n\n /**\n * User notification level for this conversation.\n */\n public get notificationLevel(): NotificationLevel {\n return this._internalState.notificationLevel ?? \"default\";\n }\n\n /**\n * Conversation bindings. Undocumented feature (for now).\n * @internal\n */\n public get bindings(): ConversationBindings {\n return this._internalState.bindings;\n }\n\n /**\n * Current conversation limits.\n */\n public get limits(): ConversationLimits {\n return this._configuration.limits;\n }\n\n /**\n * State of the conversation.\n */\n public get state(): ConversationState | undefined {\n return this._internalState.state;\n }\n\n /**\n * Source of the conversation update.\n * @internal\n */\n public get _statusSource(): ConversationsDataSource {\n return this._dataSource;\n }\n\n /**\n * Preprocess the update object.\n * @param update The update object received from Sync.\n * @param conversationSid The SID of the conversation in question.\n */\n private static preprocessUpdate(update, conversationSid: string) {\n try {\n if (typeof update.attributes === \"string\") {\n update.attributes = JSON.parse(update.attributes);\n } else if (update.attributes) {\n JSON.stringify(update.attributes);\n }\n } catch (e) {\n Conversation._logger.warn(\n \"Retrieved malformed attributes from the server for conversation: \" +\n conversationSid\n );\n update.attributes = {};\n }\n\n try {\n if (update.dateCreated) {\n update.dateCreated = new Date(update.dateCreated);\n }\n } catch (e) {\n Conversation._logger.warn(\n \"Retrieved malformed dateCreated from the server for conversation: \" +\n conversationSid\n );\n delete update.dateCreated;\n }\n\n try {\n if (update.dateUpdated) {\n update.dateUpdated = new Date(update.dateUpdated);\n }\n } catch (e) {\n Conversation._logger.warn(\n \"Retrieved malformed dateUpdated from the server for conversation: \" +\n conversationSid\n );\n delete update.dateUpdated;\n }\n\n try {\n if (update.lastMessage && update.lastMessage.timestamp) {\n update.lastMessage.timestamp = new Date(update.lastMessage.timestamp);\n }\n } catch (e) {\n Conversation._logger.warn(\n \"Retrieved malformed lastMessage.timestamp from the server for conversation: \" +\n conversationSid\n );\n delete update.lastMessage.timestamp;\n }\n }\n\n /**\n * Add a participant to the conversation by its identity.\n * @param identity Identity of the Client to add.\n * @param attributes Attributes to be attached to the participant.\n * @returns The added participant.\n */\n @validateTypesAsync(nonEmptyString, optionalAttributesValidator)\n public async add(\n identity: string,\n attributes?: JSONValue\n ): Promise<ParticipantResponse> {\n return this._participantsEntity.add(identity, attributes ?? {});\n }\n\n /**\n * Add a non-chat participant to the conversation.\n * @param proxyAddress Proxy (Twilio) address of the participant.\n * @param address User address of the participant.\n * @param attributes Attributes to be attached to the participant.\n * @param bindingOptions Options for adding email participants - name and\n * CC/To level.\n * @returns The added participant.\n */\n @validateTypesAsync(\n nonEmptyString,\n nonEmptyString,\n optionalAttributesValidator\n )\n public async addNonChatParticipant(\n proxyAddress: string,\n address: string,\n attributes: JSONValue = {},\n bindingOptions: ParticipantBindingOptions = {}\n ): Promise<ParticipantResponse> {\n return this._participantsEntity.addNonChatParticipant(\n proxyAddress,\n address,\n attributes ?? {},\n bindingOptions ?? {}\n );\n }\n\n /**\n * Advance the conversation's last read message index to the current read\n * horizon. Rejects if the user is not a participant of the conversation. Last\n * read message index is updated only if the new index value is higher than\n * the previous.\n * @param index Message index to advance to.\n * @return Resulting unread messages count in the conversation.\n */\n @validateTypesAsync(nonNegativeInteger)\n public async advanceLastReadMessageIndex(index: number): Promise<number> {\n await this._subscribeStreams();\n\n if (index < (this.lastReadMessageIndex ?? 0)) {\n return await this._setLastReadMessageIndex(this.lastReadMessageIndex);\n }\n\n return await this._setLastReadMessageIndex(index);\n }\n\n /**\n * Delete the conversation and unsubscribe from its events.\n */\n public async delete(): Promise<Conversation> {\n await this._services.commandExecutor.mutateResource(\n \"delete\",\n this._links.self\n );\n\n return this;\n }\n\n /**\n * Get the custom attributes of this Conversation.\n */\n public async getAttributes(): Promise<JSONValue> {\n await this._subscribe();\n return this.attributes;\n }\n\n /**\n * Returns messages from the conversation using the paginator interface.\n * @param pageSize Number of messages to return in a single chunk. Default is\n * 30.\n * @param anchor Index of the newest message to fetch. Default is from the\n * end.\n * @param direction Query direction. By default, it queries backwards\n * from newer to older. The `\"forward\"` value will query in the opposite\n * direction.\n * @return A page of messages.\n */\n @validateTypesAsync(\n [\"undefined\", nonNegativeInteger],\n [\"undefined\", nonNegativeInteger],\n [\"undefined\", literal(\"backwards\", \"forward\")]\n )\n public async getMessages(\n pageSize?: number,\n anchor?: number,\n direction?: \"backwards\" | \"forward\"\n ): Promise<Paginator<Message>> {\n await this._subscribeStreams();\n return this._messagesEntity.getMessages(pageSize, anchor, direction);\n }\n\n /**\n * Get a list of all the participants who are joined to this conversation.\n */\n public async getParticipants(): Promise<Participant[]> {\n await this._subscribeStreams();\n return this._participantsEntity.getParticipants();\n }\n\n /**\n * Get conversation participants count.\n *\n * This method is semi-realtime. This means that this data will be eventually\n * correct, but will also be possibly incorrect for a few seconds. The\n * Conversations system does not provide real time events for counter values\n * changes.\n *\n * This is useful for any UI badges, but it is not recommended to build any\n * core application logic based on these counters being accurate in real time.\n */\n public async getParticipantsCount(): Promise<number> {\n const url = new UriBuilder(this._configuration.links.conversations)\n .path(this.sid)\n .build();\n const response = await this._services.network.get<ConversationResponse>(\n url\n );\n\n return response.body.participants_count ?? 0;\n }\n\n /**\n * Get a participant by its SID.\n * @param participantSid Participant SID.\n */\n @validateTypesAsync(nonEmptyString)\n public async getParticipantBySid(\n participantSid: string\n ): Promise<Participant | null> {\n return this._participantsEntity.getParticipantBySid(participantSid);\n }\n\n /**\n * Get a participant by its identity.\n * @param identity Participant identity.\n */\n @validateTypesAsync(nonEmptyString)\n public async getParticipantByIdentity(\n identity: string | null = \"\"\n ): Promise<Participant | null> {\n return this._participantsEntity.getParticipantByIdentity(identity ?? \"\");\n }\n\n /**\n * Get the total message count in the conversation.\n *\n * This method is semi-realtime. This means that this data will be eventually\n * correct, but will also be possibly incorrect for a few seconds. The\n * Conversations system does not provide real time events for counter values\n * changes.\n *\n * This is useful for any UI badges, but it is not recommended to build any\n * core application logic based on these counters being accurate in real time.\n */\n public async getMessagesCount(): Promise<number> {\n const url = new UriBuilder(this._configuration.links.conversations)\n .path(this.sid)\n .build();\n const response = await this._services.network.get<ConversationResponse>(\n url\n );\n\n return response.body.messages_count ?? 0;\n }\n\n /**\n * Get count of unread messages for the user if they are a participant of this\n * conversation. Rejects if the user is not a participant of the conversation.\n *\n * Use this method to obtain the number of unread messages together with\n * {@link Conversation.updateLastReadMessageIndex} instead of relying on the\n * message indices which may have gaps. See {@link Message.index} for details.\n *\n * This method is semi-realtime. This means that this data will be eventually\n * correct, but it will also be possibly incorrect for a few seconds. The\n * Conversations system does not provide real time events for counter values\n * changes.\n *\n * This is useful for any UI badges, but it is not recommended to build any\n * core application logic based on these counters being accurate in real time.\n *\n * If the read horizon is not set, this function will return null. This could mean\n * that all messages in the conversation are unread, or that the read horizon system\n * is not being used. How to interpret this `null` value is up to the customer application.\n *\n * @return Number of unread messages based on the current read horizon set for\n * the user or `null` if the read horizon is not set.\n */\n public async getUnreadMessagesCount(): Promise<number | null> {\n const url = new UriBuilder(this._configuration.links.myConversations)\n .path(this.sid)\n .build();\n const response = await this._services.network.get<ConversationResponse>(\n url\n );\n\n if (response.body.conversation_sid !== this.sid) {\n throw new Error(\n \"Conversation was not found in the user conversations list\"\n );\n }\n\n const unreadMessageCount = response.body.unread_messages_count;\n\n if (typeof unreadMessageCount === \"number\") {\n return unreadMessageCount;\n }\n\n return null;\n }\n\n /**\n * Join the conversation and subscribe to its events.\n */\n public async join(): Promise<Conversation> {\n await this._services.commandExecutor.mutateResource<\n AddParticipantRequest,\n ParticipantResponse\n >(\"post\", this._links.participants, {\n identity: this._configuration.userIdentity,\n });\n\n return this;\n }\n\n /**\n * Leave the conversation.\n */\n public async leave(): Promise<Conversation> {\n if (this._internalState.status === \"joined\") {\n await this._services.commandExecutor.mutateResource(\n \"delete\",\n `${this._links.participants}/${encodeURIComponent(\n this._configuration.userIdentity\n )}`\n );\n }\n\n return this;\n }\n\n /**\n * Remove a participant from the conversation. When a string is passed as the\n * argument, it will assume that the string is an identity or SID.\n * @param participant Identity, SID or the participant object to remove.\n */\n @validateTypesAsync([nonEmptyString, Participant])\n public async removeParticipant(\n participant: string | Participant\n ): Promise<void> {\n await this._participantsEntity.remove(\n typeof participant === \"string\" ? participant : participant.sid\n );\n }\n\n /**\n * Send a message to the conversation.\n * @param message Message body for the text message,\n * `FormData` or {@link SendMediaOptions} for media content. Sending FormData\n * is supported only with the browser engine.\n * @param messageAttributes Attributes for the message.\n * @param emailOptions Email options for the message.\n * @return Index of the new message.\n */\n @validateTypesAsync(\n [\n \"string\",\n FormData,\n literal(null),\n objectSchema(\"media options\", {\n contentType: nonEmptyString,\n media: custom((value) => {\n let isValid =\n (typeof value === \"string\" && value.length > 0) ||\n value instanceof Uint8Array ||\n value instanceof ArrayBuffer;\n\n if (typeof Blob === \"function\") {\n isValid = isValid || value instanceof Blob;\n }\n\n return [\n isValid,\n \"a non-empty string, an instance of Buffer or an instance of Blob\",\n ];\n }),\n }),\n ],\n optionalAttributesValidator,\n [\n \"undefined\",\n literal(null),\n objectSchema(\"email attributes\", {\n subject: [nonEmptyString, \"undefined\"],\n }),\n ]\n )\n public async sendMessage(\n message: null | string | FormData | SendMediaOptions,\n messageAttributes?: JSONValue,\n emailOptions?: SendEmailOptions\n ): Promise<number> {\n if (typeof message === \"string\" || message === null) {\n const response = await this._messagesEntity.send(\n message,\n messageAttributes,\n emailOptions\n );\n return parseToNumber(response.index) ?? 0;\n }\n\n const response = await this._messagesEntity.sendMedia(\n message,\n messageAttributes,\n emailOptions\n );\n return parseToNumber(response.index) ?? 0;\n }\n\n /**\n * New interface to prepare for sending a message.\n * Use this instead of {@link Conversation.sendMessage}.\n * @return A MessageBuilder to help set all message sending options.\n */\n public prepareMessage(): MessageBuilder {\n return new MessageBuilder(this.limits, this._messagesEntity);\n }\n\n /**\n * Set last read message index of the conversation to the index of the last\n * known message.\n * @return Resulting unread messages count in the conversation.\n */\n public async setAllMessagesRead(): Promise<number> {\n await this._subscribeStreams();\n\n const messagesPage = await this.getMessages(1);\n\n if (messagesPage.items.length > 0) {\n return this.advanceLastReadMessageIndex(messagesPage.items[0].index);\n }\n\n return 0;\n }\n\n /**\n * Set all messages in the conversation unread.\n * @returns New count of unread messages after this update.\n */\n public async setAllMessagesUnread(): Promise<number> {\n await this._subscribeStreams();\n return await this._setLastReadMessageIndex(null);\n }\n\n /**\n * Set user notification level for this conversation.\n * @param notificationLevel New user notification level.\n */\n @validateTypesAsync(literal(\"default\", \"muted\"))\n public async setUserNotificationLevel(\n notificationLevel: NotificationLevel\n ): Promise<void> {\n await this._services.commandExecutor.mutateResource<EditNotificationLevelRequest>(\n \"post\",\n `${this._configuration.links.myConversations}/${this.sid}`,\n {\n notification_level: notificationLevel,\n }\n );\n }\n\n /**\n * Send a notification to the server indicating that this client is currently\n * typing in this conversation. Typing ended notification is sent after a\n * while automatically, but by calling this method again you ensure that\n * typing ended is not received.\n */\n public typing(): Promise<void> {\n return this._services.typingIndicator.send(this.sid);\n }\n\n /**\n * Update the attributes of the conversation.\n * @param attributes New attributes.\n */\n @validateTypesAsync(attributesValidator)\n public async updateAttributes(attributes: JSONValue): Promise<Conversation> {\n await this._services.commandExecutor.mutateResource<\n EditConversationRequest,\n ConversationResponse\n >(\"post\", this._links.self, {\n attributes:\n attributes !== undefined ? JSON.stringify(attributes) : undefined,\n });\n\n return this;\n }\n\n /**\n * Update the friendly name of the conversation.\n * @param friendlyName New friendly name.\n */\n @validateTypesAsync(\"string\")\n public async updateFriendlyName(friendlyName: string): Promise<Conversation> {\n if (this._internalState.friendlyName !== friendlyName) {\n await this._services.commandExecutor.mutateResource<\n EditConversationRequest,\n ConversationResponse\n >(\"post\", this._links.self, { friendly_name: friendlyName });\n }\n\n return this;\n }\n\n /**\n * Set the last read message index to the current read horizon.\n * @param index Message index to set as last read. If null is provided, then\n * the behavior is identical to {@link Conversation.setAllMessagesUnread}.\n * @returns New count of unread messages after this update.\n */\n @validateTypesAsync([literal(null), nonNegativeInteger])\n public async updateLastReadMessageIndex(\n index: number | null\n ): Promise<number> {\n await this._subscribeStreams();\n return this._setLastReadMessageIndex(index);\n }\n\n /**\n * Update the unique name of the conversation.\n * @param uniqueName New unique name for the conversation. Setting unique name\n * to null removes it.\n */\n @validateTypesAsync([\"string\", literal(null)])\n public async updateUniqueName(\n uniqueName: string | null\n ): Promise<Conversation> {\n if (this._internalState.uniqueName !== uniqueName) {\n uniqueName ||= \"\";\n\n await this._services.commandExecutor.mutateResource<\n EditConversationRequest,\n ConversationResponse\n >(\"post\", this._links.self, {\n unique_name: uniqueName,\n });\n }\n\n return this;\n }\n\n /**\n * Load and subscribe to this conversation and do not subscribe to its\n * participants and messages. This or _subscribeStreams will need to be called\n * before any events on conversation will fire.\n * @internal\n */\n public async _subscribe(): Promise<SyncDocument> {\n if (this._entityPromise) {\n return this._entityPromise;\n }\n\n this._entityPromise = this._services.syncClient.document({\n id: this._entityName,\n mode: \"open_existing\",\n });\n\n try {\n this._entity = await this._entityPromise;\n this._entity.on(\"updated\", (args) => this._update(args.data));\n this._entity.on(\"removed\", () => this.emit(\"removed\", this));\n this._update(this._entity.data);\n\n return this._entity;\n } catch (err) {\n this._entity = null;\n this._entityPromise = null;\n\n if (this._services.syncClient.connectionState != \"disconnected\") {\n Conversation._logger.error(\"Failed to get conversation object\", err);\n }\n Conversation._logger.debug(\n \"ERROR: Failed to get conversation object\",\n err\n );\n\n throw err;\n }\n }\n\n /**\n * Fetch participants and messages of the conversation. This method needs to\n * be called during conversation initialization to catch broken conversations\n * (broken conversations are conversations that have essential Sync entities\n * missing, i.e. the conversation document, the messages list or the\n * participant map). In case of this conversation being broken, the method\n * will throw an exception that will be caught and handled gracefully.\n * @internal\n */\n public async _fetchStreams() {\n await this._subscribe();\n Conversation._logger.trace(\n \"_streamsAvailable, this.entity.data=\",\n this._entity?.data\n );\n\n const data = this._entity?.data as Record<string, string>;\n this._messagesList = await this._services.syncClient.list({\n id: data.messages,\n mode: \"open_existing\",\n });\n this._participantsMap = await this._services.syncClient.map({\n id: data.roster,\n mode: \"open_existing\",\n });\n }\n\n /**\n * Load the attributes of this conversation and instantiate its participants\n * and messages. This or _subscribe will need to be called before any events\n * on the conversation will fire. This will need to be called before any\n * events on participants or messages will fire\n * @internal\n */\n public async _subscribeStreams() {\n try {\n await this._subscribe();\n Conversation._logger.trace(\n \"_subscribeStreams, this.entity.data=\",\n this._entity?.data\n );\n\n const data = this._entity?.data as Record<string, string>;\n const messagesObjectName = data.messages;\n const rosterObjectName = data.roster;\n\n await Promise.all([\n this._messagesEntity.subscribe(\n this._messagesList ?? messagesObjectName\n ),\n this._participantsEntity.subscribe(\n this._participantsMap ?? rosterObjectName\n ),\n ]);\n } catch (err) {\n if (this._services.syncClient.connectionState !== \"disconnected\") {\n Conversation._logger.error(\n \"Failed to subscribe on conversation objects\",\n this.sid,\n err\n );\n }\n Conversation._logger.debug(\n \"ERROR: Failed to subscribe on conversation objects\",\n this.sid,\n err\n );\n\n throw err;\n }\n }\n\n /**\n * Stop listening for and firing events on this conversation.\n * @internal\n */\n public async _unsubscribe() {\n if (this._entity) {\n await this._entity.close();\n this._entity = null;\n this._entityPromise = null;\n }\n\n return Promise.all([\n this._participantsEntity.unsubscribe(),\n this._messagesEntity.unsubscribe(),\n ]);\n }\n\n /**\n * Set conversation status.\n * @internal\n */\n public _setStatus(\n status: ConversationStatus,\n source: ConversationsDataSource\n ) {\n this._dataSource = source;\n\n if (this._internalState.status === status) {\n return;\n }\n\n this._internalState.status = status;\n\n if (status === \"joined\") {\n this._subscribeStreams().catch((err) => {\n Conversation._logger.debug(\n \"ERROR while setting conversation status \" + status,\n err\n );\n if (this._services.syncClient.connectionState !== \"disconnected\") {\n throw err;\n }\n });\n return;\n }\n\n if (this._entityPromise) {\n this._unsubscribe().catch((err) => {\n Conversation._logger.debug(\n \"ERROR while setting conversation status \" + status,\n err\n );\n if (this._services.syncClient.connectionState !== \"disconnected\") {\n throw err;\n }\n });\n }\n }\n\n /**\n * Update the local conversation object with new values.\n * @internal\n */\n public _update(update) {\n Conversation._logger.trace(\"_update\", update);\n\n Conversation.preprocessUpdate(update, this.sid);\n const updateReasons = new Set<ConversationUpdateReason>();\n\n for (const key of Object.keys(update)) {\n const localKey = fieldMappings[key];\n\n if (!localKey) {\n continue;\n }\n\n switch (localKey) {\n case fieldMappings.status:\n if (\n !update.status ||\n update.status === \"unknown\" ||\n this._internalState.status === update.status\n ) {\n break;\n }\n\n this._internalState.status = update.status;\n updateReasons.add(localKey);\n\n break;\n case fieldMappings.attributes:\n if (isEqual(this._internalState.attributes, update.attributes)) {\n break;\n }\n\n this._internalState.attributes = update.attributes;\n updateReasons.add(localKey);\n\n break;\n case fieldMappings.lastConsumedMessageIndex:\n if (\n update.lastConsumedMessageIndex === undefined ||\n update.lastConsumedMessageIndex ===\n this._internalState.lastReadMessageIndex\n ) {\n break;\n }\n\n this._internalState.lastReadMessageIndex =\n update.lastConsumedMessageIndex;\n updateReasons.add(\"lastReadMessageIndex\");\n\n break;\n case fieldMappings.lastMessage:\n if (this._internalState.lastMessage && !update.lastMessage) {\n delete this._internalState.lastMessage;\n updateReasons.add(localKey);\n\n break;\n }\n\n this._internalState.lastMessage =\n this._internalState.lastMessage || {};\n\n if (\n update.lastMessage?.index !== undefined &&\n update.lastMessage.index !== this._internalState.lastMessage.index\n ) {\n this._internalState.lastMessage.index = update.lastMessage.index;\n updateReasons.add(localKey);\n }\n\n if (\n update.lastMessage?.timestamp !== undefined &&\n this._internalState.lastMessage?.dateCreated?.getTime() !==\n update.lastMessage.timestamp.getTime()\n ) {\n this._internalState.lastMessage.dateCreated =\n update.lastMessage.timestamp;\n updateReasons.add(localKey);\n }\n\n if (isEqual(this._internalState.lastMessage, {})) {\n delete this._internalState.lastMessage;\n }\n\n break;\n case fieldMappings.state:\n const state = update.state || undefined;\n\n if (state !== undefined) {\n state.dateUpdated = new Date(state.dateUpdated);\n }\n\n if (isEqual(this._internalState.state, state)) {\n break;\n }\n\n this._internalState.state = state;\n updateReasons.add(localKey);\n\n break;\n case fieldMappings.bindings:\n if (isEqual(this._internalState.bindings, update.bindings)) {\n break;\n }\n\n this._internalState.bindings = update.bindings;\n updateReasons.add(localKey);\n\n break;\n default:\n const isDate = update[key] instanceof Date;\n const keysMatchAsDates =\n isDate &&\n this._internalState[localKey]?.getTime() === update[key].getTime();\n const keysMatchAsNonDates = !isDate && this[localKey] === update[key];\n\n if (keysMatchAsDates || keysMatchAsNonDates) {\n break;\n }\n\n this._internalState[localKey] = update[key];\n updateReasons.add(localKey);\n }\n }\n\n if (updateReasons.size > 0) {\n this.emit(\"updated\", {\n conversation: this,\n updateReasons: [...updateReasons],\n });\n }\n }\n\n /**\n * Handle onMessageAdded event.\n */\n private _onMessageAdded(message) {\n for (const participant of this._participants.values()) {\n if (participant.identity === message.author) {\n participant._endTyping();\n break;\n }\n }\n this.emit(\"messageAdded\", message);\n }\n\n /**\n * Set last read message index.\n * @param index New index to set.\n */\n private async _setLastReadMessageIndex(\n index: number | null\n ): Promise<number> {\n const result = await this._services.commandExecutor.mutateResource<\n EditLastReadMessageIndexRequest,\n EditLastReadMessageIndexResponse\n >(\"post\", `${this._configuration.links.myConversations}/${this.sid}`, {\n last_read_message_index: index,\n });\n\n return result.unread_messages_count;\n }\n}\n\nexport {\n ConversationDescriptor,\n Conversation,\n ConversationServices,\n ConversationUpdateReason,\n ConversationStatus,\n NotificationLevel,\n ConversationState,\n ConversationUpdatedEventArgs,\n SendMediaOptions,\n SendEmailOptions,\n LastMessage,\n ConversationBindings,\n ConversationEmailBinding,\n};\n"],"names":["ReplayEventEmitter","parseTime","Participants","Messages","UriBuilder","parseToNumber","MessageBuilder","isEqual","Logger","__decorate","validateTypesAsync","nonEmptyString","optionalAttributesValidator","nonNegativeInteger","literal","Participant","objectSchema","custom","attributesValidator"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgQA;;AAEG;AACH,MAAM,aAAa,GAAG;AACpB,IAAA,WAAW,EAAE,aAAa;AAC1B,IAAA,UAAU,EAAE,YAAY;AACxB,IAAA,SAAS,EAAE,WAAW;AACtB,IAAA,WAAW,EAAE,aAAa;AAC1B,IAAA,WAAW,EAAE,aAAa;AAC1B,IAAA,YAAY,EAAE,cAAc;AAC5B,IAAA,wBAAwB,EAAE,0BAA0B;AACpD,IAAA,iBAAiB,EAAE,mBAAmB;AACtC,IAAA,GAAG,EAAE,KAAK;AACV,IAAA,MAAM,EAAE,QAAQ;AAChB,IAAA,UAAU,EAAE,YAAY;AACxB,IAAA,KAAK,EAAE,OAAO;AACd,IAAA,QAAQ,EAAE,UAAU;CACrB,CAAC;AAEF;;;AAGG;AACH,MA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,YAAA,CAAA,SAAA,EAAA,aAAA,EAAA,IAAA,CAAA,CAAA;AA0CDF,oBAAA,CAAA;AADC,IAAAC,2CAAkB,CAACI,gCAAO,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;;;;AAW/C,CAAA,EAAA,YAAA,CAAA,SAAA,EAAA,0BAAA,EAAA,IAAA,CAAA,CAAA;AAiBDL,oBAAA,CAAA;IADCC,2CAAkB,CAACQ,8BAAmB,CAAC;;;;AAWvC,CAAA,EAAA,YAAA,CAAA,SAAA,EAAA,kBAAA,EAAA,IAAA,CAAA,CAAA;AAODT,oBAAA,CAAA;IADCC,2CAAkB,CAAC,QAAQ,CAAC;;;;AAU5B,CAAA,EAAA,YAAA,CAAA,SAAA,EAAA,oBAAA,EAAA,IAAA,CAAA,CAAA;AASDD,oBAAA,CAAA;IADCC,2CAAkB,CAAC,CAACI,gCAAO,CAAC,IAAI,CAAC,EAAED,2CAAkB,CAAC,CAAC;;;;AAMvD,CAAA,EAAA,YAAA,CAAA,SAAA,EAAA,4BAAA,EAAA,IAAA,CAAA,CAAA;AAQDJ,oBAAA,CAAA;IADCC,2CAAkB,CAAC,CAAC,QAAQ,EAAEI,gCAAO,CAAC,IAAI,CAAC,CAAC,CAAC;;;;AAgB7C,CAAA,EAAA,YAAA,CAAA,SAAA,EAAA,kBAAA,EAAA,IAAA,CAAA;;;;"}
@@ -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,CAA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CACd,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,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;;;;"}
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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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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,IA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AI,MAAM,IAAI,CAAC,MAAM,CAAC,iCAAiC,CAAC,MAAM,CAAA,CAAA,CAAG,CAC3I,CAAC;AACH,SAAA;AAED,QAAA,IACE,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,0BAA0B,EACzE;AACA,YAAA,MAAM,IAAI,KAAK,CACb,8CAA8C,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,MAAM,CAAA,GAAA,EAAM,IAAI,CAAC,MAAM,CAAC,0BAA0B,CAAA,CAAA,CAAG,CAC9H,CAAC;AACH,SAAA;;;QAKD,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,IAAI,KAAI;AAChC,YAAA,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,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;\n }\n}\n\nexport { MessageBuilder };\n"],"names":["UnsentMessage"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQA;;;;;;;;;;;;;;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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