Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): map the raw newsletter node in channel lookups

Yudhi Armyndharisd4551a0d8f94
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index 3279f30eb..d685ef038 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -970,8 +970,8 @@ adapter boundary — none silently stubs.
(`newsletterMetadata('jid', …)`), including one the account does not follow. whatsapp-web.js 1.34.x
exposes no per-id lookup, so the adapter scans the subscribed-channel list and returns `null` (a
`404`) for every channel the account is not subscribed to. The `Channel` payload differs too:
- whatsapp-web.js never fills `picture` or `createdAt`, both of which Baileys reads off the newsletter
- metadata.
+ Baileys reads `createdAt` off the newsletter metadata and whatsapp-web.js never fills it. Neither
+ engine fills `picture`: WhatsApp reports the channel picture as a media path, not a URL.
- **`starMessage` (baileys).** Needs the stored key's `fromMe` — the same id means different
messages depending on direction.
- **`addParticipants` result shape.** wwjs returns a per-participant `{code,message}` object or a
diff --git a/src/engine/adapters/baileys-channels.spec.ts b/src/engine/adapters/baileys-channels.spec.ts
index d8a11dd11..4f4300724 100644
--- a/src/engine/adapters/baileys-channels.spec.ts
+++ b/src/engine/adapters/baileys-channels.spec.ts
@@ -28,7 +28,8 @@ function channels(sock: Record<string, jest.Mock>, budgetMs: number): BaileysCha
return new BaileysChannels(host, budgetMs);
}
-const META = { id: '120363000000000000@newsletter', name: 'Release notes' };
+/** The raw node newsletterMetadata resolves to: nested under thread_metadata, not the flattened create shape. */
+const META = { id: '120363000000000000@newsletter', thread_metadata: { name: { text: 'Release notes' } } };
describe('channel operations report an unanswered query instead of a bare 500', () => {
it.each([
@@ -74,6 +75,7 @@ describe('channel operations that must not change', () => {
const newsletterMetadata = jest.fn().mockResolvedValue(META);
await expect(channels({ newsletterMetadata }, 500).getChannelById('120363@newsletter')).resolves.toMatchObject({
id: '120363000000000000@newsletter',
+ name: 'Release notes',
});
});
});
diff --git a/src/engine/adapters/baileys-channels.ts b/src/engine/adapters/baileys-channels.ts
index e35a696c8..78f34df0c 100644
--- a/src/engine/adapters/baileys-channels.ts
+++ b/src/engine/adapters/baileys-channels.ts
@@ -1,4 +1,4 @@
-import type { WASocket } from '@whiskeysockets/baileys';
+import type { NewsletterMetadata, WASocket } from '@whiskeysockets/baileys';
import { Channel } from '../interfaces/whatsapp-engine.interface';
import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';
import { mapServerRefusal } from './baileys-groups';
@@ -47,6 +47,25 @@ export function wmexRefusalCode(error: unknown): number | undefined {
return undefined;
}
+/**
+ * `thread_metadata` as newsletterMetadata actually returns it (recorded live in
+ * scripts/patch-baileys-newsletter-create.spec.js). The .d.ts types it as the flattened create shape.
+ */
+interface RawNewsletterThread {
+ name?: { text?: string } | null;
+ description?: { text?: string } | null;
+ invite?: string;
+ subscribers_count?: string;
+ verification?: 'VERIFIED' | 'UNVERIFIED';
+ creation_time?: string;
+}
+
+/** A wire number that may come as a string, or as NaN from the create parser; undefined unless finite. */
+function finiteNumber(value: number | string | undefined): number | undefined {
+ const n = typeof value === 'string' ? Number.parseInt(value, 10) : value;
+ return n !== undefined && Number.isFinite(n) ? n : undefined;
+}
+
export class BaileysChannels {
constructor(
private readonly host: BaileysChannelsHost,
@@ -192,27 +211,31 @@ export class BaileysChannels {
);
}
- /** Map a Baileys NewsletterMetadata to the neutral Channel shape (optionals only when present). */
- private toChannel(meta: {
- id: string;
- name: string;
- description?: string;
- invite?: string;
- creation_time?: number;
- subscribers?: number;
- picture?: { url?: string };
- verification?: string;
- thread_metadata?: { creation_time?: number };
- }): Channel {
- const createdAt = meta.creation_time ?? meta.thread_metadata?.creation_time;
+ /**
+ * Map a channel to the neutral Channel shape (optionals only when present).
+ *
+ * Two shapes arrive here. newsletterCreate flattens its response (parseNewsletterCreateResponse),
+ * but newsletterMetadata returns the raw GraphQL node untouched: fields nested under
+ * `thread_metadata`, name and description as `{ text }`, counts and timestamps as strings. The
+ * flat fields are read first and the nested ones fill the gaps. The flat parse uses parseInt, so
+ * a missing number arrives as NaN and is dropped rather than serialized as null.
+ *
+ * No `picture`: neither shape carries a URL, only a CDN direct path.
+ */
+ private toChannel(meta: NewsletterMetadata): Channel {
+ const thread = meta.thread_metadata as RawNewsletterThread | undefined;
+ const description = meta.description ?? thread?.description?.text;
+ const invite = meta.invite ?? thread?.invite;
+ const subscriberCount = finiteNumber(meta.subscribers) ?? finiteNumber(thread?.subscribers_count);
+ const verification = meta.verification ?? thread?.verification;
+ const createdAt = finiteNumber(meta.creation_time) ?? finiteNumber(thread?.creation_time);
return {
id: meta.id,
- name: meta.name,
- ...(meta.description ? { description: meta.description } : {}),
- ...(meta.invite ? { inviteCode: meta.invite } : {}),
- ...(meta.subscribers !== undefined ? { subscriberCount: meta.subscribers } : {}),
- ...(meta.picture?.url ? { picture: meta.picture.url } : {}),
- ...(meta.verification ? { verified: meta.verification === 'VERIFIED' } : {}),
+ name: meta.name ?? thread?.name?.text ?? '',
+ ...(description ? { description } : {}),
+ ...(invite ? { inviteCode: invite } : {}),
+ ...(subscriberCount !== undefined ? { subscriberCount } : {}),
+ ...(verification ? { verified: verification === 'VERIFIED' } : {}),
...(createdAt !== undefined ? { createdAt } : {}),
};
}
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 9973227f0..83045c83e 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -4384,27 +4384,33 @@ describe('BaileysAdapter store-backed ops', () => {
expect(fakeSock.sendMessage).toHaveBeenCalledWith('484848@lid', expect.objectContaining({ pin: stored.key }));
});
- it('getChannelById maps newsletterMetadata(jid) → Channel (optionals only when present)', async () => {
+ // newsletterMetadata hands back the raw GraphQL node (parseNewsletterMetadata returns it as-is), nested
+ // under thread_metadata with string counts; only newsletterCreate flattens. Recorded live in
+ // scripts/patch-baileys-newsletter-create.spec.js.
+ it('getChannelById maps the raw newsletterMetadata(jid) node → Channel (optionals only when present)', async () => {
fakeSock.newsletterMetadata.mockResolvedValue({
id: '120363N@newsletter',
- name: 'Announcements',
- description: 'News',
- invite: 'ABC123',
- subscribers: 421,
- picture: { url: 'https://x/p.png' },
- verification: 'VERIFIED',
- creation_time: 1700000000,
+ thread_metadata: {
+ name: { text: 'Announcements' },
+ creation_time: '1700000000',
+ description: { text: 'News' },
+ invite: 'ABC123',
+ subscribers_count: '421',
+ verification: 'VERIFIED',
+ picture: { direct_path: '/v/t61/p', id: '1', type: 'IMAGE' },
+ },
+ viewer_metadata: { mute: 'OFF' },
});
const adapter = await ready();
const channel = await adapter.getChannelById('120363N@newsletter');
expect(fakeSock.newsletterMetadata).toHaveBeenCalledWith('jid', '120363N@newsletter');
+ // No picture: neither shape carries a URL, only a direct path.
expect(channel).toEqual({
id: '120363N@newsletter',
name: 'Announcements',
description: 'News',
inviteCode: 'ABC123',
subscriberCount: 421,
- picture: 'https://x/p.png',
verified: true,
createdAt: 1700000000,
});
@@ -4417,12 +4423,31 @@ describe('BaileysAdapter store-backed ops', () => {
});
it('subscribeToChannel resolves invite→jid via newsletterMetadata then follows', async () => {
- fakeSock.newsletterMetadata.mockResolvedValue({ id: '120363S@newsletter', name: 'Solo', invite: 'CODE1' });
+ fakeSock.newsletterMetadata.mockResolvedValue({
+ id: '120363S@newsletter',
+ thread_metadata: {
+ name: { text: 'Solo' },
+ creation_time: '1786405315',
+ description: null,
+ invite: 'CODE1',
+ subscribers_count: '1',
+ verification: 'UNVERIFIED',
+ picture: null,
+ },
+ viewer_metadata: { mute: 'off' },
+ });
const adapter = await ready();
const channel = await adapter.subscribeToChannel('CODE1');
expect(fakeSock.newsletterMetadata).toHaveBeenCalledWith('invite', 'CODE1');
expect(fakeSock.newsletterFollow).toHaveBeenCalledWith('120363S@newsletter');
- expect(channel).toEqual({ id: '120363S@newsletter', name: 'Solo', inviteCode: 'CODE1' });
+ expect(channel).toEqual({
+ id: '120363S@newsletter',
+ name: 'Solo',
+ inviteCode: 'CODE1',
+ subscriberCount: 1,
+ verified: false,
+ createdAt: 1786405315,
+ });
});
it('subscribeToChannel throws ChannelNotFoundError when the invite resolves null', async () => {
@@ -7070,6 +7095,26 @@ describe('BaileysAdapter channel administration', () => {
expect(channel).toMatchObject({ id: CHANNEL, name: 'Product updates', inviteCode: 'ABC123' });
});
+ // parseNewsletterCreateResponse flattens with parseInt, so a field WhatsApp left out arrives as NaN,
+ // which would serialize as null in a field the contract types as a number.
+ it('drops a count or timestamp the flattened create response could not parse', async () => {
+ fakeSock.newsletterCreate.mockResolvedValue({
+ id: CHANNEL,
+ name: 'Product updates',
+ creation_time: Number.NaN,
+ subscribers: Number.NaN,
+ picture: { id: '1', directPath: '/v/t61/p' },
+ verification: 'UNVERIFIED',
+ });
+ const adapter = await readyAdapter();
+
+ await expect(adapter.createChannel('Product updates')).resolves.toEqual({
+ id: CHANNEL,
+ name: 'Product updates',
+ verified: false,
+ });
+ });
+
it('deletes a channel by id', async () => {
const adapter = await readyAdapter();