Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(engine): BaileysAdapter — text send, recipient resolution, presence, inbound fan-out
rmyndharise1fff3c507fc
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 1ea9db05c..7a3c0bf68 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -141,3 +141,119 @@ describe('BaileysAdapter capability gating', () => {});});+describe('BaileysAdapter messaging', () => {+ beforeEach(() => {+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };+ jest.clearAllMocks();+ });++ const readyAdapter = async (over: Partial<EngineEventCallbacks> = {}): Promise<BaileysAdapter> => {+ const adapter = newAdapter();+ await adapter.initialize(over);+ fakeSock.fire('connection.update', { connection: 'open' });+ return adapter;+ };++ it('sendTextMessage calls sock.sendMessage(jid, { text }) and returns the message id', async () => {+ fakeSock.sendMessage.mockResolvedValue({ key: { id: 'OUT1' }, messageTimestamp: 1700000001 });+ const adapter = await readyAdapter();+ const res = await adapter.sendTextMessage('[email protected]', 'hello');+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', { text: 'hello' });+ expect(res).toEqual({ id: 'OUT1', timestamp: 1700000001 });+ });++ it('getNumberId resolves via onWhatsApp and returns the jid when it exists', async () => {+ fakeSock.onWhatsApp.mockResolvedValue([{ jid: '[email protected]', exists: true }]);+ const adapter = await readyAdapter();+ await expect(adapter.getNumberId('628111')).resolves.toBe('[email protected]');+ await expect(adapter.checkNumberExists('628111')).resolves.toBe(true);+ });++ it('getNumberId returns null when the number is not on WhatsApp', async () => {+ fakeSock.onWhatsApp.mockResolvedValue([{ jid: '[email protected]', exists: false }]);+ const adapter = await readyAdapter();+ await expect(adapter.getNumberId('628111')).resolves.toBeNull();+ await expect(adapter.checkNumberExists('628111')).resolves.toBe(false);+ });++ it('sendChatState maps typing -> composing presence', async () => {+ const adapter = await readyAdapter();+ await adapter.sendChatState('[email protected]', 'typing');+ expect(fakeSock.sendPresenceUpdate).toHaveBeenCalledWith('composing', '[email protected]');+ });++ it('messaging methods throw EngineNotReadyError before the connection is open', async () => {+ const adapter = newAdapter();+ await adapter.initialize({});+ await expect(adapter.sendTextMessage('x', 'y')).rejects.toBeInstanceOf(EngineNotReadyError);+ });+});++describe('BaileysAdapter inbound fan-out', () => {+ const baileys = jest.requireMock('@whiskeysockets/baileys') as { getContentType: jest.Mock };++ beforeEach(() => {+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };+ jest.clearAllMocks();+ baileys.getContentType.mockReturnValue('conversation');+ });++ it('routes an inbound (not fromMe) message to onMessage with a neutral shape', async () => {+ const onMessage = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessage });+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [+ {+ key: { remoteJid: '[email protected]', fromMe: false, id: 'IN1' },+ message: { conversation: 'hi there' },+ messageTimestamp: 1700000002,+ pushName: 'Alice',+ },+ ],+ });+ expect(onMessage).toHaveBeenCalledTimes(1);+ const msg = onMessage.mock.calls[0][0] as { id: string; body: string; type: string; fromMe: boolean };+ expect(msg).toMatchObject({ id: 'IN1', body: 'hi there', type: 'text', fromMe: false });+ });++ it('routes a fromMe message to onMessageCreate (outgoing), not onMessage', async () => {+ const onMessage = jest.fn();+ const onMessageCreate = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessage, onMessageCreate });+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [+ {+ key: { remoteJid: '[email protected]', fromMe: true, id: 'OUT2' },+ message: { conversation: 'sent from phone' },+ messageTimestamp: 1700000003,+ },+ ],+ });+ expect(onMessageCreate).toHaveBeenCalledTimes(1);+ expect(onMessage).not.toHaveBeenCalled();+ });++ it('ignores append (history) upserts', async () => {+ const onMessage = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessage });+ fakeSock.fire('messages.upsert', {+ type: 'append',+ messages: [{ key: { remoteJid: '[email protected]', fromMe: false, id: 'OLD' }, message: { conversation: 'old' } }],+ });+ expect(onMessage).not.toHaveBeenCalled();+ });++ it('emits onMessageAck from messages.update with a neutral status', async () => {+ const onMessageAck = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessageAck });+ fakeSock.fire('messages.update', [{ key: { id: 'OUT1' }, update: { status: 3 } }]);+ expect(onMessageAck).toHaveBeenCalledWith('OUT1', 'delivered');+ });+});+diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex b69df4903..9e5d9aca5 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -2,9 +2,11 @@ import * as path from 'path';import makeWASocket, {DisconnectReason,fetchLatestBaileysVersion,+ getContentType,useMultiFileAuthState,} from '@whiskeysockets/baileys';-import type { WASocket } from '@whiskeysockets/baileys';+import type { WAMessage, WASocket } from '@whiskeysockets/baileys';+import { buildIncomingMessageFromBaileys, mapBaileysStatus } from './baileys-message-mapper';import type { ILogger } from '@whiskeysockets/baileys/lib/Utils/logger.js';import {ChatState,@@ -104,7 +106,8 @@ export class BaileysAdapter implements IWhatsAppEngine {sock.ev.on('creds.update', saveCreds);sock.ev.on('connection.update', update => this.handleConnectionUpdate(update));- // Message listeners are wired in the messaging slice (Task 5).+ sock.ev.on('messages.upsert', event => this.handleMessagesUpsert(event));+ sock.ev.on('messages.update', updates => this.handleMessagesUpdate(updates));}private handleConnectionUpdate(update: {@@ -214,22 +217,32 @@ export class BaileysAdapter implements IWhatsAppEngine {return this.pushName;}- // ----- Messaging (implemented in the messaging slice; gated until then) -----+ // ----- Messaging ------ sendTextMessage(_chatId: string, _text: string): Promise<MessageResult> {- return this.unsupported('sendTextMessage');+ async sendTextMessage(chatId: string, text: string): Promise<MessageResult> {+ this.ensureReady();+ const sent = await this.sock!.sendMessage(chatId, { text });+ return {+ id: sent?.key?.id ?? '',+ timestamp: this.toUnixSeconds(sent?.messageTimestamp),+ };}- checkNumberExists(_number: string): Promise<boolean> {- return this.unsupported('checkNumberExists');+ async checkNumberExists(number: string): Promise<boolean> {+ return (await this.getNumberId(number)) !== null;}- getNumberId(_number: string): Promise<string | null> {- return this.unsupported('getNumberId');+ async getNumberId(number: string): Promise<string | null> {+ this.ensureReady();+ const results = await this.sock!.onWhatsApp(number);+ const hit = results?.[0];+ return hit?.exists ? hit.jid : null;}- sendChatState(_chatId: string, _state: ChatState): Promise<void> {- return this.unsupported('sendChatState');+ async sendChatState(chatId: string, state: ChatState): Promise<void> {+ this.ensureReady();+ const presence = state === 'typing' ? 'composing' : state === 'recording' ? 'recording' : 'paused';+ await this.sock!.sendPresenceUpdate(presence, chatId);}// ----- Gated: not supported by this minimal slice (no store) -----@@ -402,6 +415,64 @@ export class BaileysAdapter implements IWhatsAppEngine {// ----- Helpers -----+ private handleMessagesUpsert(event: { messages: WAMessage[]; type: string }): void {+ // Only live messages ('notify'); 'append' is history sync, which this storeless slice skips.+ if (event.type !== 'notify') {+ return;+ }+ for (const msg of event.messages) {+ if (!msg.message || !msg.key?.remoteJid) {+ continue; // protocol/empty messages carry no neutral content+ }+ const incoming = this.mapMessage(msg);+ if (msg.key.fromMe) {+ this.callbacks.onMessageCreate?.(incoming);+ } else {+ this.callbacks.onMessage?.(incoming);+ }+ }+ }++ private handleMessagesUpdate(updates: Array<{ key?: { id?: string | null }; update?: { status?: number | null } }>): void {+ for (const u of updates) {+ const status = mapBaileysStatus(u.update?.status);+ if (status && u.key?.id) {+ this.callbacks.onMessageAck?.(u.key.id, status);+ }+ }+ }++ private mapMessage(msg: WAMessage): IncomingMessage {+ const content = msg.message ?? {};+ const contentType = getContentType(msg.message ?? undefined);+ const body = content.conversation ?? content.extendedTextMessage?.text ?? '';+ return buildIncomingMessageFromBaileys({+ id: msg.key.id ?? '',+ remoteJid: msg.key.remoteJid!,+ fromMe: msg.key.fromMe === true,+ participant: msg.key.participant ?? undefined,+ body,+ contentType,+ isPtt: content.audioMessage?.ptt === true,+ timestamp: this.toUnixSeconds(msg.messageTimestamp),+ pushName: msg.pushName ?? undefined,+ selfJid: this.normalizedSelfJid(),+ });+ }++ private normalizedSelfJid(): string {+ const phone = this.extractPhone(this.sock?.user?.id);+ return phone ? `${phone}@s.whatsapp.net` : '';+ }++ /** Baileys timestamps are `number | Long`; normalize to unix seconds. */+ private toUnixSeconds(ts: number | { toNumber(): number } | null | undefined): number {+ if (ts == null) {+ return Math.floor(Date.now() / 1000);+ }+ return typeof ts === 'number' ? ts : ts.toNumber();+ }+// eslint-disable-next-line @typescript-eslint/no-explicit-anyprivate unsupported(method: string): Promise<any> {return Promise.reject(new EngineNotSupportedError(method));