import { ChatMessage as ChatMessageModel, DataPacket, protoInt64 } from '@livekit/protocol'; import type { CoreRoom } from '../CoreRoom'; import { DataChannelKind } from '../data-channel/types'; import { ParticipantEvent, RoomEvent } from '../events'; import type { DataPacketOwner, ExtensionContext, LocalParticipantApiProvider, RoomExtension, } from '../extensions'; import type { ChatMessage, SendTextOptions } from '../types'; import { extractChatMessage } from '../utils'; /** * Methods the legacy `chat` extension adds to the local participant. * @experimental */ export interface ChatLocalParticipantApi { /** @deprecated Consider migrating to {@link sendText} */ sendChatMessage(text: string, options?: SendTextOptions): Promise; /** @deprecated Consider migrating to {@link sendText} */ editChatMessage(editText: string, originalMessage: ChatMessage): Promise; } /** * The legacy chat message packets (`sendChatMessage`, `RoomEvent.ChatMessage`). Superseded by * text streams; the full `Room` keeps it, the core entry does not offer it. */ export const chat = { key: /* @__PURE__ */ Symbol('lk.extension.chat'), install( room: CoreRoom, _ctx: ExtensionContext, ): LocalParticipantApiProvider & DataPacketOwner { const participant = room.localParticipant; participant.on(ParticipantEvent.ChatMessage, (msg) => { room.emit(RoomEvent.ChatMessage, msg, participant); }); const send = async (msg: ChatMessage) => { const packet = new DataPacket({ value: { case: 'chatMessage', value: new ChatMessageModel({ ...msg, timestamp: protoInt64.parse(msg.timestamp), editTimestamp: msg.editTimestamp !== undefined ? protoInt64.parse(msg.editTimestamp) : undefined, }), }, }); await room.engine.sendDataPacket(packet, DataChannelKind.RELIABLE); participant.emit(ParticipantEvent.ChatMessage, msg); return msg; }; return { dataPackets: { chatMessage: (chatMessage, _packet, _encryptionType, sender) => { room.emit(RoomEvent.ChatMessage, extractChatMessage(chatMessage), sender); }, }, localParticipant: { sendChatMessage: (text, options) => send({ id: crypto.randomUUID(), message: text, timestamp: Date.now(), attachedFiles: options?.attachments, }), editChatMessage: (editText, originalMessage) => send({ ...originalMessage, message: editText, editTimestamp: Date.now() }), }, }; }, } satisfies RoomExtension<{}, ChatLocalParticipantApi>;