Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(engine): split the whatsapp-web.js adapter into per-domain delegates
Yudhi Armyndharisf075dae70610
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 12d265be8..f2926e356 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -1,5 +1,4 @@import { EventEmitter } from 'events';-import { InternalServerErrorException } from '@nestjs/common';import {Client,LocalAuth,@@ -23,7 +22,6 @@ import {Contact,Group,GroupInfo,- GroupParticipant,ParticipantOperationResult,LocationInput,PollInput,@@ -41,7 +39,6 @@ import {PaginatedProducts,ChatSummary,ChatState,- DeliveryStatus,RevokedMessage,EditedMessage,ReactionEvent,@@ -51,199 +48,43 @@ import {import { resolveWebVersionPin } from '../wa-web-version';import { resolveAuthTimeoutMs } from '../engine-init-timeout';import { killOrphanedChromiumProcesses, removeStaleSingletonFiles } from './chromium-profile-hygiene';-import { chatKind, isChannelJid, userPart } from '../identity/wa-id';+import { isChannelJid } from '../identity/wa-id';import { LidMappingStore } from '../identity/lid-mapping-store.service';-import { ChatLabelsUnsupportedError } from '../../common/errors/chat-labels-unsupported.error';import { createLogger } from '../../common/services/logger.service';import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';-import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';-import { MessageNotFoundError } from '../../common/errors/message-not-found.error';import { CallNotFoundError } from '../../common/errors/call-not-found.error';-import { EngineRefusedError } from '../../common/errors/engine-refused.error';-import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';-import { GroupNotFoundError } from '../../common/errors/group-not-found.error';-import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';import { ChannelMediaNotSupportedError } from '../../common/errors/channel-media-not-supported.error';-import { EngineTransportError } from '../../common/errors/engine-transport.error';-import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';-import {- GroupChat,- GroupMetadataRaw,- MessageWithReactions,- BusinessClient,- WwjsChannelData,- GroupCreateResult,- SerializedWid,-} from '../types/whatsapp-web-js.types';+import { SerializedWid } from '../types/whatsapp-web-js.types';import { buildEditedMessage, buildIncomingMessageBase, mapContactFields } from './message-mapper';-import { buildVCard } from './vcard';+import { WwebjsGroups } from './wwebjs-groups';+import { type WwebjsEngineHost } from './wwebjs-host';+import { WwebjsMessaging, declaredOnlyMedia, extractWwebjsCall, wwebjsAckToDeliveryStatus } from './wwebjs-messaging';+import { WwebjsContacts } from './wwebjs-contacts';+import { WwebjsProfile } from './wwebjs-profile';+import { WwebjsLabels } from './wwebjs-labels';+import { WwebjsChannels } from './wwebjs-channels';+import { WwebjsStatus } from './wwebjs-status';+import { WwebjsChats } from './wwebjs-chats';+import { WwebjsCatalog } from './wwebjs-catalog';+import { isSupportedProxyUrl, buildProxyLaunchConfig } from './wwebjs-proxy';+import {+ probeOnboardingModal,+ resolveOnboardingContinueLabels,+ ONBOARDING_DEFAULT_CONTINUE_LABEL,+} from './wwebjs-onboarding';+import { wwebjsGroupUpdateChanges, wwebjsGroupRecipientIds } from './wwebjs-group-events';import { BACKPORT_MISSING_MESSAGE, isBackportMissing } from './wwebjs-backport-check';import {capInboundMedia,- chatHistoryMediaBudgetBytes,coerceDeclaredSize,inboundMediaConcurrency,inboundMediaMaxBytes,- ingestMediaBudgetBytes,inboundMediaTimeoutMs,isMediaDownloadEnabled,withInboundDownloadTimeout,} from './inbound-media-cap';import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';-/**- * Map a whatsapp-web.js MessageAck integer to the neutral DeliveryStatus.- * wwebjs: -1 ERROR, 0 PENDING, 1 SERVER (sent), 2 DEVICE (delivered), 3 READ, 4 PLAYED.- * PLAYED collapses to `read` (preserving prior behaviour, which treated ack>=3 as read).- */-export function wwebjsAckToDeliveryStatus(ack: number): DeliveryStatus {- if (ack < 0) return 'failed';- if (ack >= 3) return 'read';- if (ack === 2) return 'delivered';- if (ack === 1) return 'sent';- return 'pending';-}--/**- * Interpret the on/off value a group settings notification carries in `body` ('on'/'true' → true,- * 'off'/'false' → false). Undefined when the body holds anything else (e.g. a rendered template- * string), in which case the caller emits the update without that change rather than guess.- */-function parseWwebjsOnOff(body: string): boolean | undefined {- const v = body.trim().toLowerCase();- if (v === 'on' || v === 'true') return true;- if (v === 'off' || v === 'false') return false;- return undefined;-}--/**- * Reduce a `group_update` GroupNotification to the neutral `changes` delta. `subject`/`description`- * carry the new value in `body`; `announce`/`restrict` encode the new setting as on/off text (the- * latter maps to the neutral `locked`). Anything uninterpretable — a `picture` change, or a WA Web- * build that stops putting the value in `body` — yields an empty delta: the occurrence is still- * emitted, just without fields we would be guessing at. Compared as strings because the runtime- * gp2 subtypes can exceed the GroupNotificationTypes enum (e.g. a 'locked' rename of 'restrict').- */-export function wwebjsGroupUpdateChanges(notification: GroupNotification): NonNullable<GroupEvent['changes']> {- const body = typeof notification.body === 'string' ? notification.body : '';- switch (String(notification.type)) {- case 'subject':- return { subject: body };- case 'description':- return { description: body };- case 'announce': {- const on = parseWwebjsOnOff(body);- return on === undefined ? {} : { announce: on };- }- case 'restrict':- case 'locked': {- const on = parseWwebjsOnOff(body);- return on === undefined ? {} : { locked: on };- }- default:- return {};- }-}--/**- * A GroupNotification's `recipientIds` are assigned straight through from the wire- * (`this.recipientIds = data.recipients`), outside upstream's id normalization — so on a WA Web- * build that renamed `_serialized` to `$1` (#747) an entry can arrive as a raw id object instead- * of a string. Coerce both shapes to the neutral (already @c.us/@g.us) string form; entries that- * resolve to nothing are dropped rather than forwarded as "undefined".- */-export function wwebjsGroupRecipientIds(notification: GroupNotification): string[] {- const raw = notification.recipientIds as unknown;- if (!Array.isArray(raw)) return [];- return raw- .map(entry => {- if (typeof entry === 'string') return entry;- const wid = entry as SerializedWid | undefined;- return wid?._serialized ?? wid?.$1 ?? '';- })- .filter(id => id.length > 0);-}--/**- * Extract call detail from a whatsapp-web.js `call_log` message, or `undefined` for any other type.- * The public Message wrapper doesn't expose call fields, so we read them off the raw `_data`. An- * incoming call (`!fromMe`) with no recorded `callDuration` was never answered → missed; an outgoing- * call is never "missed". Used by getChatHistory, where `call_log` entries actually appear.- */-export function extractWwebjsCall(msg: Message): { video: boolean; missed: boolean } | undefined {- if ((msg.type as string) !== 'call_log') return undefined;- const d = (msg as unknown as { _data?: { isVideoCall?: boolean; callDuration?: number } })._data ?? {};- return { video: Boolean(d.isVideoCall), missed: !msg.fromMe && !d.callDuration };-}--/**- * The `media` envelope for a message whose blob is not downloaded: keeps the sender-declared metadata- * so the `media` field stays present (n8n/dashboard contract) while carrying the `omitted` marker- * instead of base64. Used when downloads are disabled, the size pre-gate trips, the aggregate history- * budget is spent, or the download fails/times out.- */-function declaredOnlyMedia(msg: Message): IncomingMessage['media'] {- const data = (msg as unknown as { _data?: { size?: number; mimetype?: string; filename?: string } })._data;- return {- mimetype: data?.mimetype ?? '',- filename: data?.filename || undefined,- omitted: true,- sizeBytes: coerceDeclaredSize(data?.size),- };-}--/**- * Whether a per-session proxy URL parses to a supported scheme — defense-in-depth for a stored proxy- * that bypassed DTO validation (e.g. loaded from the DB on restart). The host is NOT SSRF-blocked: a- * per-session proxy is operator-chosen egress, and a loopback proxy sidecar is a legitimate setup.- */-export function isSupportedProxyUrl(url: string): boolean {- try {- return ['http:', 'https:', 'socks4:', 'socks5:'].includes(new URL(url).protocol);- } catch {- return false;- }-}--export interface ProxyLaunchConfig {- /** Credential-less `--proxy-server` value — Chromium ignores credentials embedded in this flag. */- serverArg: string;- /** Username/password for whatsapp-web.js's `proxyAuthentication` (→ `page.authenticate`, HTTP/HTTPS only). */- proxyAuthentication?: { username: string; password: string };- /** The URL carries credentials for a SOCKS proxy, which Chromium cannot authenticate at all. */- socksAuthUnsupported: boolean;-}--/**- * Split a proxy URL into a credential-less `--proxy-server` value plus, for an HTTP/HTTPS proxy, the- * username/password to hand to whatsapp-web.js's `proxyAuthentication` (which calls `page.authenticate`- * — the only way Chromium authenticates a proxy). Credentials embedded in `--proxy-server` are ignored- * by Chromium, and SOCKS proxies cannot be authenticated at all, so SOCKS credentials are surfaced via- * `socksAuthUnsupported` for the caller to warn about instead of failing with an opaque nav timeout (#628).- * Call only with a URL that already passed {@link isSupportedProxyUrl}.- */-export function buildProxyLaunchConfig(url: string): ProxyLaunchConfig {- const parsed = new URL(url);- const serverArg = `${parsed.protocol}//${parsed.host}`;- const username = decodeURIComponent(parsed.username);- const password = decodeURIComponent(parsed.password);- const hasCredentials = username !== '' || password !== '';- const isSocks = parsed.protocol === 'socks4:' || parsed.protocol === 'socks5:';- if (hasCredentials && !isSocks) {- return { serverArg, proxyAuthentication: { username, password }, socksAuthUnsupported: false };- }- return { serverArg, socksAuthUnsupported: hasCredentials && isSocks };-}--/**- * Whether a MediaInput's string `data` is an http(s) URL (to be fetched through the SSRF-guarded- * loadRemoteMedia) rather than base64. Case-insensitive, matching the Baileys adapter — a mixed-case- * scheme like `HTTPS://` must still route through the guarded fetch, not be treated as base64.- */-export function isHttpUrl(value: string): boolean {- return /^https?:\/\//i.test(value);-}-/*** Detect Puppeteer's "Execution context was destroyed" error. During `Client.inject()` this is most* often a persistent browser profile left stale by an OpenWA upgrade that changed the Chromium/Chrome@@ -256,23 +97,6 @@ export function isExecutionContextDestroyedError(reason: string): boolean {return /execution context was destroyed/i.test(reason);}-/**- * Fetch remote media for sending, with an SSRF host guard, a byte cap, and a timeout.- * The guard runs BEFORE any network call, so an internal/reserved URL throws `SsrfBlockedError`- * and no outbound socket is opened. The byte cap (node-fetch `size`) and `AbortSignal` timeout- * bound memory use and hang time. `unsafeMime` is left at its default (false) to preserve the- * existing MIME-detection behavior.- */-export async function loadRemoteMedia(url: string): Promise<MessageMedia> {- // Fetch through the SSRF-pinned path: it validates the host, pins the connection to the vetted IP- // (so a DNS rebind can't redirect it to an internal target between check and connect), caps bytes,- // and refuses redirects. We then build the MessageMedia from the returned bytes — NOT via- // MessageMedia.fromUrl, whose bundled node-fetch performs its own unpinned DNS re-resolution.- const { data, mimetype } = await loadRemoteMediaBuffer(url);- const filename = new URL(url).pathname.split('/').pop() || undefined;- return new MessageMedia(mimetype || 'application/octet-stream', data.toString('base64'), filename);-}-export interface WhatsAppWebJsConfig {sessionId: string;sessionDataPath: string;@@ -309,84 +133,6 @@ const ONBOARDING_MODAL_PROBE_TIMEOUT_MS = 5_000;// Five failed clicks still trips in ~25s — far inside the lifetime cap and the ~5m unlink deadline.const ONBOARDING_MODAL_MAX_DISMISS_CLICKS = 5;-/** The modal's confirm-button label on an English WhatsApp Web. */-const ONBOARDING_DEFAULT_CONTINUE_LABEL = 'Continue';--/**- * Extra confirm-button labels for a deployment whose WhatsApp Web does not render this modal in- * English, comma-separated (`WWEBJS_ONBOARDING_CONTINUE_LABELS=Continuar,Weiter`).- *- * Needed because the match is on visible text and WhatsApp controls those strings — we are not going- * to carry its translation table. Read per probe, not cached, so an operator can correct a running- * deployment through the infra config without a restart.- *- * Supplying labels also drops the heading requirement for THOSE labels: the English heading regex- * would reject a localised modal anyway, so requiring both would make the setting useless. That is a- * deliberate, operator-opted-in loosening — see {@link probeOnboardingModal}.- */-function resolveOnboardingContinueLabels(): string[] {- const extra = (process.env.WWEBJS_ONBOARDING_CONTINUE_LABELS ?? '')- .split(',')- .map(label => label.trim())- .filter(Boolean);- return [ONBOARDING_DEFAULT_CONTINUE_LABEL, ...extra];-}--/**- * In-page probe for the onboarding modal: click its confirm button if it is on screen.- *- * Exported and self-contained on purpose. `page.evaluate` stringifies this into the browser, so it- * may not close over anything in this module — every input arrives as an argument — and being a plain- * function means the DOM matching can be unit-tested directly, rather than only through a mocked- * `evaluate` that proves nothing about the matching itself.- *- * The BUTTON is the presence signal, never the heading text on its own. `textContent` on a `div`- * concatenates every descendant, so a chat-list row previewing the words "what's new" — an ordinary- * English message — satisfies a heading-only test. Treating that as a stuck modal would take a- * perfectly healthy session out of READY and block every send. A visible control whose exact label is- * the confirm label, sitting within a few levels of an element that also carries the heading, is a- * shape the chat list does not produce. The ancestor walk is bounded for the same reason: matching- * against `<body>` would just be the loose text test again.- *- * LANGUAGE. The default label and the heading are English, and the modal is rendered in whatever- * language WhatsApp Web decides. Two things address that, both defaulting to today's behaviour:- * the launch args pin `--lang` so the page has a deterministic locale, and an operator can add- * their own labels (see {@link resolveOnboardingContinueLabels}). An operator-supplied label matches- * WITHOUT the heading check — the English heading would reject a localised modal regardless, so- * requiring both would make the setting inert. The default `Continue` keeps the heading requirement,- * so the out-of-the-box false-positive surface is unchanged.- */-export function probeOnboardingModal(options?: { labels?: string[]; headingOptionalFor?: string[] }): {- modalPresent: boolean;- dismissed: boolean;-} {- const isVisible = (el: Element): boolean => {- const rect = (el as HTMLElement).getBoundingClientRect();- return rect.width > 0 && rect.height > 0 && (el as HTMLElement).offsetParent !== null;- };- const labels = options?.labels?.length ? options.labels : ['Continue'];- const headingOptional = new Set(options?.headingOptionalFor ?? []);- // Both apostrophes: WhatsApp Web renders the typographic U+2019, and an ASCII quote appears in- // older builds. Matching only the ASCII form means never recognising the real modal.- const heading = /what[’']?s new/i;- const candidates = Array.from(document.querySelectorAll('button, [role="button"]'))- .map(el => ({ el, label: (el.textContent || '').trim() }))- .filter(c => isVisible(c.el) && labels.includes(c.label));- for (const { el, label } of candidates.reverse()) {- if (headingOptional.has(label)) {- (el as HTMLElement).click();- return { modalPresent: true, dismissed: true };- }- let scope: Element | null = el;- for (let depth = 0; depth < 8 && scope; depth++, scope = scope.parentElement) {- if (!heading.test(scope.textContent || '')) continue;- (el as HTMLElement).click();- return { modalPresent: true, dismissed: true };- }- }- return { modalPresent: false, dismissed: false };-}-// WhatsApp Web version resolution (the #488 auto-resolve) lives in a dependency-free module so infra// status can import it without loading whatsapp-web.js (engine lazy-loading). The adapter imports// resolveWebVersionPin above for use in initialize().@@ -397,34 +143,27 @@ export function probeOnboardingModal(options?: { labels?: string[]; headingOptio// they are configuring.export { resolveAuthTimeoutMs };-/**- * Extracts the JID of the parent community a group is linked to, if any.- * The field name has varied across whatsapp-web.js/WA Web versions, so- * known candidates are checked in order.- */-export function extractLinkedParentJID(groupMetadata?: GroupMetadataRaw): string | null {- const candidate =- groupMetadata?.parentGroup ?? groupMetadata?.linkedParentGroup ?? groupMetadata?.linkedParent ?? null;-- if (!candidate) {- return null;- }+// extractLinkedParentJID moved to ./wwebjs-groups with the group operations; re-exported because+// existing callers (the adapter spec) still import it from here.+export { extractLinkedParentJID } from './wwebjs-groups';- if (typeof candidate === 'string') {- return candidate;- }+// Messaging helpers moved to ./wwebjs-messaging with the messaging operations; re-exported because+// existing callers (the adapter spec) still import them from here.+export {+ isHttpUrl,+ loadRemoteMedia,+ extractWwebjsCall,+ isNoLidForUserError,+ wwebjsAckToDeliveryStatus,+} from './wwebjs-messaging';- return candidate._serialized ?? null;-}+// Proxy launch helpers moved to ./wwebjs-proxy; re-exported because existing callers (the adapter+// spec) still import them from here.+export { isSupportedProxyUrl, buildProxyLaunchConfig } from './wwebjs-proxy';-/**- * True when a send error is whatsapp-web.js's "recipient needs a LID we don't have" failure, raised- * when sending to a `@c.us` for a contact WhatsApp has migrated to `@lid`.- * ponytail: matched on the wwjs error text — there is no structured code; revisit if wwjs changes it.- */-export function isNoLidForUserError(err: unknown): boolean {- return err instanceof Error && err.message.includes('No LID for user');-}+// The onboarding-modal probe moved to ./wwebjs-onboarding with its label resolution; re-exported+// because existing callers (the adapter spec) still import it from here.+export { probeOnboardingModal } from './wwebjs-onboarding';export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngine {private client: Client | null = null;@@ -471,6 +210,30 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginconstructor(private readonly config: WhatsAppWebJsConfig) {super();+ // API-surface clusters live in ./wwebjs-* delegates; the public methods below forward to them.+ // The host is one object literal shared by every delegate, and closures (not a `this` reference)+ // keep the delegates' surface exactly this narrow. Built in the constructor, not as a field+ // initializer: `config` is a parameter property, which field initializers read before assignment.+ this.host = {+ ensureReady: () => this.ensureReady(),+ getClient: () => this.client!,+ logger: this.logger,+ isPageTransportError: error => this.isPageTransportError(error),+ reportIfPageTransportError: (error, context) => this.reportIfPageTransportError(error, context),+ ensureNotChannelRecipient: chatId => this.ensureNotChannelRecipient(chatId),+ getNumberId: number => this.getNumberId(number),+ capInboundMediaFor: (msg, maxBytesOverride) => this.capInboundMediaFor(msg, maxBytesOverride),+ config: this.config,+ };+ this.groups = new WwebjsGroups(this.host);+ this.messaging = new WwebjsMessaging(this.host);+ this.contacts = new WwebjsContacts(this.host);+ this.profile = new WwebjsProfile(this.host);+ this.labels = new WwebjsLabels(this.host);+ this.channels = new WwebjsChannels(this.host);+ this.statuses = new WwebjsStatus(this.host);+ this.chats = new WwebjsChats(this.host, this.messaging);+ this.catalog = new WwebjsCatalog(this.host);}private readonly logger = createLogger('WhatsAppWebJsAdapter');@@ -483,6 +246,17 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngininboundMediaConcurrency(),);+ private readonly host: WwebjsEngineHost;+ private readonly groups: WwebjsGroups;+ private readonly messaging: WwebjsMessaging;+ private readonly contacts: WwebjsContacts;+ private readonly profile: WwebjsProfile;+ private readonly labels: WwebjsLabels;+ private readonly channels: WwebjsChannels;+ private readonly statuses: WwebjsStatus;+ private readonly chats: WwebjsChats;+ private readonly catalog: WwebjsCatalog;+/*** Download inbound media safely. downloadMedia() can't be size-bounded at the source, so (1) pre-gate* on the sender-declared size and skip the download entirely when it exceeds the cap, and (2) run the@@ -1696,1351 +1470,270 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginreturn this.pushName;}- // Cache of resolved individual recipients: `<phone>@c.us` -> the id `sendMessage` accepts (a- // `<lid>@lid` for a migrated contact, or the confirmed `@c.us` for a non-migrated one). `getNumberId`- // is a rate-limited WhatsApp Web existence probe that also throws intermittently, so caching every- // confirmed resolution keeps ordinary sends from re-probing on each message (#580). A `@lid` is- // stable; a stale entry (a contact that migrates mid-session) self-heals via the retry in- // `sendResolved`.- // ponytail: unbounded Map, bounded in practice by distinct recipients per session; add an LRU only- // if a session ever addresses a truly unbounded set of fresh numbers.- private readonly resolvedSendIds = new Map<string, string>();-- /**- * Resolve an individual (`@c.us`) recipient to the id whatsapp-web.js will accept. WhatsApp has- * migrated some contacts to privacy-id addressing, for which `sendMessage` throws `No LID for user`- * on the phone WID but accepts the `@lid` that `getNumberId` returns (#573). Any server-confirmed- * resolution (a distinct `@lid` OR a confirmed non-migrated `@c.us`) is cached, since it is stable- * and re-probing costs a rate-limited round-trip (#580); a `null`/thrown lookup is NOT cached so an- * unregistered or transiently-flaky contact keeps being retried. Groups/channels and already-`@lid`- * targets are returned unchanged, and any resolution failure falls back to the original id so a send- * is never blocked on it.- */- private async resolveSendId(chatId: string): Promise<string> {- if (!chatId.endsWith('@c.us')) {- return chatId;- }- const cached = this.resolvedSendIds.get(chatId);- if (cached) {- return cached;- }- try {- const wid = await this.getNumberId(chatId);- if (wid) {- this.resolvedSendIds.set(chatId, wid);- if (wid.endsWith('@lid')) {- // Persist the learned phone -> lid so the message read-path (resolveJidCandidates) can- // bridge this contact's `@c.us` and `@lid` rows on a pure whatsapp-web.js deployment- // (#583 R3). Fire-and-forget: resolution (and the send) must never block/fail on the write.- void this.config.lidMappingStore- ?.remember(userPart(wid), userPart(chatId), this.config.sessionId)- ?.catch(() => {});- }- return wid;- }- return chatId;- } catch {- return chatId;- }+ sendTextMessage(chatId: string, text: string, mentions?: string[]): Promise<MessageResult> {+ return this.messaging.sendTextMessage(chatId, text, mentions);}- /**- * Resolve `chatId` and run `send` against the resolved id. If the send fails with `No LID for user`- * — the signature of a contact whose cached/resolved id is stale (typically a `@c.us` for a contact- * that has since migrated to `@lid`) — drop the mapping, re-resolve once, and retry only if the- * fresh id differs, so a genuinely unreachable recipient surfaces its error instead of looping.- */- private async sendResolved<T>(chatId: string, send: (to: string) => Promise<T>): Promise<T> {- const to = await this.resolveSendId(chatId);- try {- return await send(to);- } catch (err) {- // A transport-level failure means the page/browser is gone — report it as a death signal.- // No-op for ordinary send errors; the retry/throw behavior below is unchanged.- this.reportIfPageTransportError(err, 'sendMessage');- if (!chatId.endsWith('@c.us') || !isNoLidForUserError(err)) {- throw err;- }- this.resolvedSendIds.delete(chatId);- const fresh = await this.resolveSendId(chatId);- if (fresh === to) {- throw err;- }- // The first send threw, but wwjs can throw after the message is already on the wire — so this- // retry may produce a duplicate. Log it: without this the second copy is invisible.- this.logger.warn('Send retried against a re-resolved id after "No LID for user"; may duplicate', {- chatId,- staleId: to,- freshId: fresh,- });- return send(fresh);- }+ sendImageMessage(chatId: string, media: MediaInput): Promise<MessageResult> {+ return this.messaging.sendImageMessage(chatId, media);}- async sendTextMessage(chatId: string, text: string, mentions?: string[]): Promise<MessageResult> {- this.ensureReady();- // wwebjs accepts neutral `<phone>@c.us` WIDs directly as mentionedJidList, so no de-normalization- // is needed. Omit the options object entirely when none are given to keep today's send behavior.- const msg = await this.sendResolved(chatId, to =>- mentions?.length ? this.client!.sendMessage(to, text, { mentions }) : this.client!.sendMessage(to, text),- );- return this.toMessageResult(msg);+ sendVideoMessage(chatId: string, media: MediaInput): Promise<MessageResult> {+ return this.messaging.sendVideoMessage(chatId, media);}- async sendImageMessage(chatId: string, media: MediaInput): Promise<MessageResult> {- return this.sendMediaMessage(chatId, media);+ sendAudioMessage(chatId: string, media: MediaInput): Promise<MessageResult> {+ return this.messaging.sendAudioMessage(chatId, media);}- async sendVideoMessage(chatId: string, media: MediaInput): Promise<MessageResult> {- return this.sendMediaMessage(chatId, media);+ sendDocumentMessage(chatId: string, media: MediaInput): Promise<MessageResult> {+ return this.messaging.sendDocumentMessage(chatId, media);}- async sendAudioMessage(chatId: string, media: MediaInput): Promise<MessageResult> {- return this.sendMediaMessage(chatId, media, media.ptt ? { sendAudioAsVoice: true } : undefined);+ getContacts(): Promise<Contact[]> {+ return this.contacts.getContacts();}- /**- * Without `sendMediaAsDocument` whatsapp-web.js lets WA Web classify the attachment from its declared- * mimetype (`Injected/Utils.js` `processMediaData` -> `prepRawMedia`), so an `image/*`, `video/*` or- * `audio/*` payload posted here reached the recipient as a photo/video/audio bubble — re-encoded and- * stripped of its filename — instead of a document (#989). Baileys has always forced it via the- * explicit `document:` content key, so the two engines disagreed on the same request.- *- * The flag is withheld for `status@broadcast` and broadcast lists: whatsapp-web.js refuses every- * `@broadcast` recipient outright once it is set (`Client.js` returns `null`, which `toMessageResult`- * surfaces as a failed send), so setting it there would turn a working send into an error rather than- * improve it. Those recipients keep the classification they have today.- */- async sendDocumentMessage(chatId: string, media: MediaInput): Promise<MessageResult> {- const kind = chatKind(chatId);- const asDocument = kind !== 'status' && kind !== 'broadcast';- return this.sendMediaMessage(chatId, media, asDocument ? { sendMediaAsDocument: true } : undefined);+ getContactById(contactId: string): Promise<Contact | null> {+ return this.contacts.getContactById(contactId);}- private async sendMediaMessage(- chatId: string,- media: MediaInput,- extraOptions?: { sendAudioAsVoice?: boolean; sendMediaAsDocument?: boolean },- ): Promise<MessageResult> {- this.ensureReady();- this.ensureNotChannelRecipient(chatId);-- // Build the media once (a remote URL is fetched here); sendResolved may retry the send itself.- const messageMedia = await this.toMessageMedia(media);- // A nameless document reaches WA Web as `new File([blob], undefined)` and is labelled literally- // "undefined". Only documents render a filename, so default just this path — as Baileys does.- if (extraOptions?.sendMediaAsDocument && !messageMedia.filename) {- messageMedia.filename = 'file';- }- const msg = await this.sendResolved(chatId, to =>- this.client!.sendMessage(to, messageMedia, {- caption: media.caption,- ...(media.mentions?.length ? { mentions: media.mentions } : {}),- // sendAudioAsVoice only for audio, sendMediaAsDocument only for documents;- // {...undefined} contributes no keys.- ...extraOptions,- }),- );-- return this.toMessageResult(msg);+ getNumberId(number: string): Promise<string | null> {+ return this.contacts.getNumberId(number);}- async getContacts(): Promise<Contact[]> {- this.ensureReady();- try {- const contacts = await this.client!.getContacts();-- return contacts.map(c => ({- id: c.id._serialized,- name: c.name || undefined,- pushName: c.pushname || undefined,- number: c.number,- isMyContact: c.isMyContact,- isBlocked: c.isBlocked,- }));- } catch (error) {- this.reportIfPageTransportError(error, 'getContacts');- throw error;- }+ checkNumberExists(number: string): Promise<boolean> {+ return this.contacts.checkNumberExists(number);}- async getContactById(contactId: string): Promise<Contact | null> {- this.ensureReady();- try {- const contact = await this.client!.getContactById(contactId);- return {- id: contact.id._serialized,- name: contact.name || undefined,- pushName: contact.pushname || undefined,- number: contact.number,- isMyContact: contact.isMyContact,- isBlocked: contact.isBlocked,- };- } catch (error) {- this.logger.warn(`Failed to get contact: ${contactId}`, { error: String(error) });- return null;- }+ resolveContactPhone(contactId: string): Promise<string | null> {+ return this.contacts.resolveContactPhone(contactId);}- async getNumberId(number: string): Promise<string | null> {- this.ensureReady();- try {- const numberId = await this.client!.getNumberId(number);- return numberId?._serialized ?? null;- } catch (error) {- this.reportIfPageTransportError(error, 'getNumberId');- throw error;- }+ getGroups(): Promise<Group[]> {+ return this.groups.getGroups();}- async checkNumberExists(number: string): Promise<boolean> {- return (await this.getNumberId(number)) !== null;- }+ // ============= Phase 3: Extended Messaging =============- async resolveContactPhone(contactId: string): Promise<string | null> {- this.ensureReady();- try {- // Queried one id at a time: the batch form is prone to "Evaluation failed" and rate-limiting- // (whatsapp-web.js #3857/#3969). `pn` is the phone JID (`<digits>@c.us`) when the account knows- // the mapping; best-effort, so a missing mapping or any failure resolves to null.- const [result] = await this.client!.getContactLidAndPhone([contactId]);- const pn = result?.pn;- return pn ? pn.replace(/@c\.us$/i, '').replace(/\D/g, '') || null : null;- } catch (error) {- this.logger.debug(`resolveContactPhone failed for ${contactId}`, {- error: error instanceof Error ? error.message : String(error),- });- return null;- }+ sendLocationMessage(chatId: string, location: LocationInput): Promise<MessageResult> {+ return this.messaging.sendLocationMessage(chatId, location);}- async getGroups(): Promise<Group[]> {- this.ensureReady();- try {- const chats = await this.client!.getChats();-- // Filter only group chats- const groups = chats.filter(chat => chat.isGroup);-- // List path: read linkedParentJID synchronously from whatever metadata getChats()- // already loaded. We deliberately do NOT fall back to getChatById per group here —- // that would be an N+1 round-trip across every group on every list call. Groups- // whose metadata isn't loaded report null; the single-group endpoint (getGroupInfo,- // which loads full metadata via getChatById) is the authoritative source.- return groups.map(g => {- const groupChat = g as unknown as GroupChat;- return {- id: g.id._serialized,- name: g.name,- participantsCount: groupChat.participants?.length,- isAdmin: groupChat.participants?.some(- p => p.isAdmin && p.id._serialized === this.client?.info?.wid?._serialized,- ),- linkedParentJID: extractLinkedParentJID(groupChat.groupMetadata),- };- });- } catch (error) {- this.reportIfPageTransportError(error, 'getGroups');- throw error;- }+ sendContactMessage(chatId: string, contact: ContactCard): Promise<MessageResult> {+ return this.messaging.sendContactMessage(chatId, contact);}- // ============= Phase 3: Extended Messaging =============-- async sendLocationMessage(chatId: string, location: LocationInput): Promise<MessageResult> {- this.ensureReady();- // Import Location class dynamically from whatsapp-web.js- const module = await import('whatsapp-web.js');- const Location = module.Location || module.default?.Location;-- const loc = new Location(location.latitude, location.longitude, {- name: location.description || '',- address: location.address || '',- });- const msg = await this.sendResolved(chatId, to => this.client!.sendMessage(to, loc));- return this.toMessageResult(msg);+ sendStickerMessage(chatId: string, media: MediaInput): Promise<MessageResult> {+ return this.messaging.sendStickerMessage(chatId, media);}- async sendContactMessage(chatId: string, contact: ContactCard): Promise<MessageResult> {- this.ensureReady();- // Shared builder sanitizes name/number (strips CR/LF, digits-only waid) so a crafted contact- // can't inject extra vCard fields — the previous inline build interpolated raw values.- const vcard = buildVCard(contact);-- const msg = await this.sendResolved(chatId, to =>- this.client!.sendMessage(to, vcard, {- parseVCards: true,- }),- );- return this.toMessageResult(msg);- }-- async sendStickerMessage(chatId: string, media: MediaInput): Promise<MessageResult> {- this.ensureReady();- // Sticker has its own send path (sendMediaAsSticker), not the sendMediaMessage funnel, but it- // hits the same channel crash: for a channel wwjs drops the sticker form and runs processMediaData- // with sendToChannel, which still ends at msg.avParams() (Utils.js:518). Guard it too (#673).- this.ensureNotChannelRecipient(chatId);- // Keep the fetched content-type for a remote URL: here the mimetype selects the conversion, and- // whatsapp-web.js returns the media unconverted once it reads as webp (Util.formatImageToWebpSticker).- const messageMedia = await this.toMessageMedia(media, { trustDeclaredType: false });-- const msg = await this.sendResolved(chatId, to =>- this.client!.sendMessage(to, messageMedia, {- sendMediaAsSticker: true,- }),- );- return this.toMessageResult(msg);- }-- async sendPollMessage(chatId: string, poll: PollInput): Promise<MessageResult> {- this.ensureReady();- // Import Poll dynamically like Location; the .default fallback covers builds where the- // classes land on module.default (a plain `module.Poll` would be undefined there and- // `new Poll` fails with "not a constructor").- const module = await import('whatsapp-web.js');- const Poll = module.Poll || module.default?.Poll;-- // wwebjs's typings mark `messageSecret` as required, but at runtime it is optional (it is- // only used as a custom poll id), so cast to the constructor's options type to pass just- // allowMultipleAnswers.- type PollSendOptions = ConstructorParameters<typeof Poll>[2];- const pollOptions = { allowMultipleAnswers: poll.allowMultipleAnswers === true } as PollSendOptions;- const msg = await this.sendResolved(chatId, to =>- this.client!.sendMessage(to, new Poll(poll.name, poll.options, pollOptions)),- );- return this.toMessageResult(msg);+ sendPollMessage(chatId: string, poll: PollInput): Promise<MessageResult> {+ return this.messaging.sendPollMessage(chatId, poll);}- async replyToMessage(chatId: string, quotedMsgId: string, text: string): Promise<MessageResult> {- this.ensureReady();- try {- // Find the message to quote- const chat = await this.client!.getChatById(chatId);- const messages = await chat.fetchMessages({ limit: 100 });- const quotedMsg = messages.find(m => m.id._serialized === quotedMsgId);-- if (!quotedMsg) {- throw new MessageNotFoundError(quotedMsgId);- }-- // Reply's send leg hits the same `No LID for user` path as a normal send for a migrated contact,- // so route it through sendResolved (resolve @c.us->@lid, cache, self-heal). reply(content, chatId)- // accepts an explicit target (#583 R1).- const msg = await this.sendResolved(chatId, to => quotedMsg.reply(text, to));- return this.toMessageResult(msg);- } catch (error) {- this.reportIfPageTransportError(error, 'replyToMessage');- throw error;- }+ replyToMessage(chatId: string, quotedMsgId: string, text: string): Promise<MessageResult> {+ return this.messaging.replyToMessage(chatId, quotedMsgId, text);}- async forwardMessage(fromChatId: string, toChatId: string, messageId: string): Promise<MessageResult> {- this.ensureReady();- try {- const chat = await this.client!.getChatById(fromChatId);- const messages = await chat.fetchMessages({ limit: 100 });- const msgToForward = messages.find(m => m.id._serialized === messageId);-- if (!msgToForward) {- throw new MessageNotFoundError(messageId);- }-- // The forward's send leg fails with `No LID for user` for a LID-migrated destination, so resolve- // it (and self-heal a stale mapping) via sendResolved. Capture the id actually sent to so the- // id-recovery below reads back from the SAME (resolved) chat, not the raw @c.us (#583 R1).- let resolvedTo = toChatId;- await this.sendResolved(toChatId, to => {- resolvedTo = to;- return msgToForward.forward(to);- });-- // whatsapp-web.js's forward() returns void, so BEST-EFFORT recover the REAL id of the sent copy by- // reading it back from the destination chat (the most recent outgoing message). The delivery-ack- // matcher keys on this id, so a synthetic one would leave the forward stuck at SENT; Baileys already- // returns the real id. The forward already succeeded here, so recovery must NEVER fail the operation.- // When the copy can't be identified we return an explicit-unknown id (empty): message.service then- // leaves the row's waMessageId unset so no ack can mis-match it — unlike a synthetic or source id,- // which could cross-drive another row's delivery status. Concurrent forwards to the same chat may- // mis-identify the copy — acceptable for delivery-status accuracy.- try {- const destChat = await this.client!.getChatById(resolvedTo);- const sentByMe = (await destChat?.fetchMessages({ limit: 5, fromMe: true })) ?? [];- let sent: (typeof sentByMe)[number] | undefined;- for (const m of sentByMe) {- if (!sent || m.timestamp > sent.timestamp) {- sent = m;- }- }- if (sent) {- return this.toMessageResult(sent);- }- } catch (error) {- // Still surface a dead page even though the send itself succeeded (detection only; the- // forward's best-effort recovery contract is unchanged).- this.reportIfPageTransportError(error, 'forwardMessage');- this.logger.warn(`Forward succeeded but recovering the sent message id failed: ${String(error)}`);- }- return { id: '', timestamp: Math.floor(Date.now() / 1000) };- } catch (error) {- this.reportIfPageTransportError(error, 'forwardMessage');- throw error;- }+ forwardMessage(fromChatId: string, toChatId: string, messageId: string): Promise<MessageResult> {+ return this.messaging.forwardMessage(fromChatId, toChatId, messageId);}// ============= Phase 3: Group Management =============- async getGroupInfo(groupId: string): Promise<GroupInfo | null> {- this.ensureReady();- try {- const chat = await this.client!.getChatById(groupId);- if (!chat.isGroup) {- return null;- }- const groupChat = chat as unknown as GroupChat;- const participants: GroupParticipant[] = (groupChat.participants || []).map(p => ({- id: String(p.id._serialized),- number: String(p.id.user),- name: p.name ? String(p.name) : undefined,- isAdmin: Boolean(p.isAdmin),- isSuperAdmin: Boolean(p.isSuperAdmin),- }));-- return {- id: chat.id._serialized,- name: chat.name,- description: groupChat.description ? String(groupChat.description) : undefined,- owner: groupChat.owner?._serialized ? String(groupChat.owner._serialized) : undefined,- createdAt: groupChat.createdAt,- participants,- isReadOnly: Boolean(groupChat.isReadOnly),- isAnnounce: Boolean(groupChat.isAnnounce),- announce: groupChat.groupMetadata?.announce,- locked: groupChat.groupMetadata?.restrict,- ephemeralSeconds: groupChat.groupMetadata?.ephemeralDuration,- linkedParentJID: extractLinkedParentJID(groupChat.groupMetadata),- };- } catch (error) {- // A dead page and a genuinely-missing group both land in this catch; only the second may- // become null (→ service 404). A transport death surfaced as "group not found" sends- // operators debugging the wrong layer — report it and answer 503 instead.- if (this.isPageTransportError(error)) {- this.reportIfPageTransportError(error, 'getGroupInfo');- throw new EngineTransportError(`Transport died while reading group ${groupId}`);- }- this.logger.warn(`Failed to get group: ${groupId}`, { error: String(error) });- return null;- }+ getGroupInfo(groupId: string): Promise<GroupInfo | null> {+ return this.groups.getGroupInfo(groupId);}- async createGroup(name: string, participants: string[]): Promise<Group> {- this.ensureReady();- // Ensure participant IDs are in correct format- const participantIds = participants.map(p => (p.includes('@') ? p : `${p}@c.us`));- const result = await this.client!.createGroup(name, participantIds);-- // whatsapp-web.js reports a failed creation by RESOLVING with a plain string- // ('CreateGroupError: …', Client.js:2376) rather than throwing, and its own typings say so- // (`Promise<CreateGroupResult | string>`). Reading `.gid` straight off that string threw an opaque- // TypeError and discarded the reason upstream actually gave us; surface it instead.- if (typeof result === 'string') {- throw new Error(result);- }- const gid = (result as unknown as GroupCreateResult).gid as SerializedWid | undefined;- const groupId = gid?._serialized ?? gid?.$1;- // A group id is not ack-safe the way a message id is: there is no empty-sentinel equivalent, and any- // placeholder would be handed back as a real, addressable group. Fail instead of inventing one.- if (!groupId) {- throw new Error('the group was created but its id could not be read');- }- return {- id: groupId,- name: name,- participantsCount: participants.length,- };+ createGroup(name: string, participants: string[]): Promise<Group> {+ return this.groups.createGroup(name, participants);}- async addParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {- this.ensureReady();- const chat = await this.client!.getChatById(groupId);- if (!chat.isGroup) {- throw new Error('Chat is not a group');- }- const participantIds = participants.map(p => (p.includes('@') ? p : `${p}@c.us`));- const raw = await (chat as unknown as GroupChat).addParticipants(participantIds);- // whatsapp-web.js reports a batch-level refusal (no admin rights, empty group) by RESOLVING a- // plain reason string (GroupChat.js:106-107,128-130) instead of throwing — surface it as a- // refusal, not a success.- if (typeof raw === 'string') {- throw new EngineRefusedError(raw);- }- // Per-participant outcome: code 200 = added; 403 invite-only / 404 not registered / 408- // recently left / 409 already a member / 419 group full (GroupChat.js:102-116).- const results: ParticipantOperationResult[] = Object.entries(raw ?? {}).map(([id, r]) => {- // A 403 with isInviteV4Sent is not a failure: wwebjs already delivered the private group- // invite (GroupChat.js:203-240). Report it as success-with-invite — otherwise an all-invite- // batch throws "failed for all" (HTTP 403) even though every participant was reached.- const inviteSent = r.code === 403 && r.isInviteV4Sent === true;- return {- id,- success: r.code === 200 || inviteSent,- status: r.code,- message: inviteSent- ? 'the participant can only be added by private invitation — invite sent'- : r.message || undefined,- };- });- return this.assertParticipantResults('addParticipants', groupId, results);+ addParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {+ return this.groups.addParticipants(groupId, participants);}- async removeParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {- return this.runStatusOnlyParticipantOp('removeParticipants', groupId, participants);+ removeParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {+ return this.groups.removeParticipants(groupId, participants);}- async promoteParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {- return this.runStatusOnlyParticipantOp('promoteParticipants', groupId, participants);+ promoteParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {+ return this.groups.promoteParticipants(groupId, participants);}- async demoteParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {- return this.runStatusOnlyParticipantOp('demoteParticipants', groupId, participants);+ demoteParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {+ return this.groups.demoteParticipants(groupId, participants);}- /**- * whatsapp-web.js remove/promote/demote resolve `{status: 200}` for the whole batch and reject on- * a page-side failure (GroupChat.js:267-298,305-340,343-374) — there is no per-participant- * breakdown to map: the page-side code even drops requested ids it can't find in the group and- * still resolves 200, so a 200 confirms the batch, not any individual. A non-200 status is a- * batch refusal. Within the per-participant shape the truthful report is one entry per requested- * participant carrying the batch status, annotated so a consumer can tell it apart from an- * individually-confirmed outcome (addParticipants); nothing per-participant exists to map.- */- private async runStatusOnlyParticipantOp(- op: 'removeParticipants' | 'promoteParticipants' | 'demoteParticipants',- groupId: string,- participants: string[],- ): Promise<ParticipantOperationResult[]> {- this.ensureReady();- const chat = await this.client!.getChatById(groupId);- if (!chat.isGroup) {- throw new Error('Chat is not a group');- }- const participantIds = participants.map(p => (p.includes('@') ? p : `${p}@c.us`));- const res = await (chat as unknown as GroupChat)[op](participantIds);- if (res?.status !== 200) {- throw new EngineRefusedError(`${op} refused for group ${groupId} (status ${res?.status ?? 'unknown'})`);- }- return participantIds.map(id => ({- id,- success: true,- status: 200,- message: 'confirmed with the batch — wwebjs reports no per-participant outcome',- }));+ leaveGroup(groupId: string): Promise<void> {+ return this.groups.leaveGroup(groupId);}- /**- * Shared gate for the membership writes: a result list with at least one success resolves as-is- * (partial refusals stay visible per participant); a batch that failed for EVERY requested- * participant is a refusal of the operation itself (HTTP 403), not a per-participant detail; and- * an empty result is no evidence of success at all.- */- private assertParticipantResults(- op: string,- groupId: string,- results: ParticipantOperationResult[],- ): ParticipantOperationResult[] {- if (results.length === 0) {- throw new EngineRefusedError(`${op} returned no per-participant outcome for group ${groupId}`);- }- if (results.every(r => !r.success)) {- const detail = results.map(r => `${r.id} (${r.status ?? '?'})`).join(', ');- throw new EngineRefusedError(- `${op} failed for all ${results.length} participant(s) in group ${groupId}: ${detail}`,- );- }- return results;+ setGroupSubject(groupId: string, subject: string): Promise<void> {+ return this.groups.setGroupSubject(groupId, subject);}- async leaveGroup(groupId: string): Promise<void> {- this.ensureReady();- const chat = await this.client!.getChatById(groupId);- if (!chat.isGroup) {- throw new Error('Chat is not a group');- }- await (chat as unknown as GroupChat).leave();+ setGroupDescription(groupId: string, description: string): Promise<void> {+ return this.groups.setGroupDescription(groupId, description);}- async setGroupSubject(groupId: string, subject: string): Promise<void> {- this.ensureReady();- const chat = await this.client!.getChatById(groupId);- if (!chat.isGroup) {- throw new Error('Chat is not a group');- }- // GroupChat.setSubject resolves false when WA Web rejects the change (e.g. the account lacks- // admin rights; index.d.ts:1982) instead of throwing — surface the refusal, not a false success.- const ok = await (chat as unknown as GroupChat).setSubject(subject);- if (!ok) {- throw new EngineRefusedError(`Failed to set the subject for group ${groupId} — admin rights required`);- }+ // Reactions (Phase 3)+ reactToMessage(chatId: string, messageId: string, emoji: string): Promise<void> {+ return this.messaging.reactToMessage(chatId, messageId, emoji);}- async setGroupDescription(groupId: string, description: string): Promise<void> {- this.ensureReady();- const chat = await this.client!.getChatById(groupId);- if (!chat.isGroup) {- throw new Error('Chat is not a group');- }- // Same discarded-boolean contract as setSubject (index.d.ts:1984).- const ok = await (chat as unknown as GroupChat).setDescription(description);- if (!ok) {- throw new EngineRefusedError(`Failed to set the description for group ${groupId} — admin rights required`);- }+ getMessageReactions(chatId: string, messageId: string): Promise<MessageReaction[]> {+ return this.messaging.getMessageReactions(chatId, messageId);}- // Reactions (Phase 3)- async reactToMessage(chatId: string, messageId: string, emoji: string): Promise<void> {- this.ensureReady();- try {- // NOTE: do NOT resolve chatId to @lid here — whatsapp-web.js reacts using the found message's own- // id, not this chatId, so LID-resolving the lookup gives no send benefit and would miss a message- // stored under the pre-migration @c.us chat (#583 R1 review).- const chat = await this.client!.getChatById(chatId);- const messages = await chat.fetchMessages({ limit: 100 });- const message = messages.find(m => m.id._serialized === messageId);- if (!message) {- throw new MessageNotFoundError(messageId, chatId);- }- await (message as MessageWithReactions).react(emoji);- this.logger.log(`Reacted to message ${messageId} with ${emoji || '(removed)'}`);- } catch (error) {- this.reportIfPageTransportError(error, 'reactToMessage');- throw error;- }+ // Labels (Phase 3) - WhatsApp Business only+ getLabels(): Promise<Label[]> {+ return this.labels.getLabels();}- async getMessageReactions(chatId: string, messageId: string): Promise<MessageReaction[]> {- this.ensureReady();- const chat = await this.client!.getChatById(chatId);- const messages = await chat.fetchMessages({ limit: 100 });- const message = messages.find(m => m.id._serialized === messageId);- if (!message) {- throw new MessageNotFoundError(messageId, chatId);- }- const msgWithReactions = message as MessageWithReactions;- if (!msgWithReactions.hasReaction) {- return [];- }- const reactions = await msgWithReactions.getReactions();- if (!reactions) {- return [];- }- // Map reactions to our interface format- const result: MessageReaction[] = [];-- for (const r of reactions) {- result.push({- emoji: String(r.id),- senders: (r.senders || []).map(s => ({- senderId: String(s.senderId),- emoji: String(s.reaction),- timestamp: Number(s.timestamp),- })),- });- }- return result;+ getLabelById(labelId: string): Promise<Label | null> {+ return this.labels.getLabelById(labelId);}- // Labels (Phase 3) - WhatsApp Business only- async getLabels(): Promise<Label[]> {- this.ensureReady();- const labels = await (this.client as unknown as BusinessClient).getLabels();- if (!labels) {- return [];- }-- return labels.map(label => ({- id: String(label.id),- name: String(label.name),- hexColor: String(label.hexColor),- }));+ getChatLabels(chatId: string): Promise<Label[]> {+ return this.labels.getChatLabels(chatId);}- async getLabelById(labelId: string): Promise<Label | null> {- this.ensureReady();- const label = await (this.client as unknown as BusinessClient).getLabelById(labelId);- if (!label) {- return null;- }- return {- id: String(label.id),- name: String(label.name),- hexColor: String(label.hexColor),- };+ addLabelToChat(chatId: string, labelId: string): Promise<void> {+ return this.labels.addLabelToChat(chatId, labelId);}- async getChatLabels(chatId: string): Promise<Label[]> {- this.ensureReady();- if (isChannelJid(chatId)) {- // A channel resolves to a wwebjs `Channel`, which has no getLabels() and carries no chat labels.- // Return empty instead of letting the unguarded call throw a TypeError (HTTP 500).- return [];- }- const chat = await this.client!.getChatById(chatId);- const labels = await (chat as unknown as GroupChat).getLabels();- if (!labels) {- return [];- }+ removeLabelFromChat(chatId: string, labelId: string): Promise<void> {+ return this.labels.removeLabelFromChat(chatId, labelId);+ }- return labels.map(label => ({- id: String(label.id),- name: String(label.name),- hexColor: String(label.hexColor),- }));+ // Channels/Newsletter (Phase 3)+ getSubscribedChannels(): Promise<Channel[]> {+ return this.channels.getSubscribedChannels();}- async addLabelToChat(chatId: string, labelId: string): Promise<void> {- this.ensureReady();- await this.changeChatLabel(chatId, labelId, true);+ getChannelById(channelId: string): Promise<Channel | null> {+ return this.channels.getChannelById(channelId);}- async removeLabelFromChat(chatId: string, labelId: string): Promise<void> {- this.ensureReady();- await this.changeChatLabel(chatId, labelId, false);+ subscribeToChannel(_inviteCode: string): Promise<Channel> {+ return this.channels.subscribeToChannel(_inviteCode);}- /**- * whatsapp-web.js has no add-/remove-one-label primitive: `client.addOrRemoveLabels(ids, chats)` REPLACES- * a chat's label set with `ids` (adding the listed labels, removing any existing label not listed). So- * toggle a single label by reading the current set, mutating it, and writing the whole set back.- * Labels are a WhatsApp Business feature — the write throws `[LT01]` on a personal account; channels- * carry no labels at all. Both are surfaced as a 422 rather than an opaque 500.- *- * The read and write are separate calls, so two concurrent single-label writes to the SAME chat can- * lose an update (last write wins, as a full-set replace). Acceptable for low-frequency label admin;- * serialize per (sessionId, chatId) if that ever becomes a real workload.- */- private async changeChatLabel(chatId: string, labelId: string, add: boolean): Promise<void> {- if (isChannelJid(chatId)) {- throw new ChatLabelsUnsupportedError('Channels do not support chat labels.');- }- const ids = new Set((await this.getChatLabels(chatId)).map(label => label.id));- if (add) {- ids.add(labelId);- } else {- ids.delete(labelId);- }- try {- await this.client!.addOrRemoveLabels([...ids], [chatId]);- } catch (error) {- // whatsapp-web.js throws `[LT01] Only Whatsapp business` from the page context on a personal account.- if (String(error instanceof Error ? error.message : error).includes('LT01')) {- throw new ChatLabelsUnsupportedError();- }- throw error;- }- this.logger.log(`${add ? 'Added' : 'Removed'} label ${labelId} ${add ? 'to' : 'from'} chat ${chatId}`);+ unsubscribeFromChannel(channelId: string): Promise<void> {+ return this.channels.unsubscribeFromChannel(channelId);}- // Channels/Newsletter (Phase 3)- async getSubscribedChannels(): Promise<Channel[]> {- this.ensureReady();- const channels = await (this.client as unknown as BusinessClient).getChannels();- if (!channels) {- return [];- }- return channels.map((ch: WwjsChannelData) => ({- id: String(typeof ch.id === 'object' ? ch.id._serialized : ch.id),- name: String(ch.name || ''),- description: ch.description ? String(ch.description) : undefined,- inviteCode: ch.inviteCode ? String(ch.inviteCode) : undefined,- subscriberCount: ch.subscriberCount ? Number(ch.subscriberCount) : undefined,- verified: ch.verified ? Boolean(ch.verified) : undefined,- }));- }-- async getChannelById(channelId: string): Promise<Channel | null> {- this.ensureReady();- // wwebjs 1.34.x exposes no client.getChannelById; resolve from the subscribed-channel list (#625).- const channels = await this.getSubscribedChannels();- return channels.find(c => c.id === channelId) ?? null;- }-- // whatsapp-web.js `Client.subscribeToChannel(channelId)` takes a channel ID and resolves a- // boolean (index.d.ts:71; Client.js:2533) — the interface contract here is subscribe-by-INVITE-CODE- // returning the subscribed Channel. The old wiring passed the invite code straight in and mapped- // the returned boolean as if it were a Channel, fabricating `{ id: "undefined" }`: a reported- // success that never subscribed anything. A real wiring is the two-step- // `getChannelByInviteCode(inviteCode)` (Client.js:1707) → `subscribeToChannel(channel.id)` flow;- // until that is verified against a live session, an honest 501 beats a phantom success.- // eslint-disable-next-line @typescript-eslint/require-await, @typescript-eslint/no-unused-vars- async subscribeToChannel(_inviteCode: string): Promise<Channel> {- this.ensureReady();- throw new EngineNotSupportedError('subscribeToChannel');- }-- async unsubscribeFromChannel(channelId: string): Promise<void> {- this.ensureReady();- // Resolves false instead of throwing when the unsubscription did not complete (Client.js:2556)- // — surface the refusal rather than reporting a false success.- const ok = await (this.client as unknown as BusinessClient).unsubscribeFromChannel(channelId);- if (!ok) {- throw new EngineRefusedError(`Failed to unsubscribe from channel ${channelId}`);- }- this.logger.log(`Unsubscribed from channel: ${channelId}`);- }-- async getChannelMessages(channelId: string, limit: number = 50): Promise<ChannelMessage[]> {- this.ensureReady();- // wwebjs 1.34.x has no client.getChannelById (calling it threw and the error was swallowed into an- // empty list, #625). The subscribed Channel instances returned by getChannels() carry fetchMessages(),- // so resolve the channel from that list and read its messages. A missing channel surfaces as a- // ChannelNotFoundError (→ 404, like getChannelById) so callers can tell "no messages" apart from- // "wrong/unsubscribed channel" instead of getting a silent [].- const channels = await (this.client as unknown as BusinessClient).getChannels();- const channel = channels?.find(c => (typeof c.id === 'object' ? c.id._serialized : c.id) === channelId);- if (!channel) {- throw new ChannelNotFoundError(channelId);- }- // wwebjs Channel.fetchMessages only honors a limit > 0: its load-earlier loop AND the final- // splice are both gated on `searchOptions.limit > 0` (Channel.js:352), so a 0/negative/NaN- // limit fails OPEN and returns every loaded message. Substitute the default instead.- const safeLimit = Number.isFinite(limit) && limit >= 1 ? Math.trunc(limit) : 50;- const messages = await channel.fetchMessages({ limit: safeLimit });- return (messages ?? []).map(msg => ({- // Read `$1` before the sentinel (#747), and don't `String()` the object branch: that turned an- // unreadable id into the literal "undefined" rather than the empty sentinel every other path- // uses. Read-only endpoint — never persisted, never ack-matched — so `''` carries no collision- // risk here; it just means "id unreadable".- id: (typeof msg.id === 'object' ? (msg.id?._serialized ?? msg.id?.$1) : msg.id) || '',- body: String(msg.body || ''),- timestamp: Number(msg.timestamp),- hasMedia: Boolean(msg.hasMedia),- mediaUrl: msg.mediaUrl ? String(msg.mediaUrl) : undefined,- }));+ getChannelMessages(channelId: string, limit: number = 50): Promise<ChannelMessage[]> {+ return this.channels.getChannelMessages(channelId, limit);}// ========== Gap Quick Wins Implementation ==========- async getChatHistory(+ getChatHistory(chatId: string,limit: number = 50,includeMedia: boolean = false,mediaMaxBytes?: number,signal?: AbortSignal,): Promise<IncomingMessage[]> {- this.ensureReady();- const chat = await this.client!.getChatById(chatId);- const messages = await chat.fetchMessages({ limit });- const results: IncomingMessage[] = [];- // Aggregate base64 budget across the whole pass: the per-message cap bounds ONE blob, but without- // an aggregate bound a 100-message history could stack ~100 × 50 MiB into one response. Once the- // running total crosses the budget, later media messages get the declared-only `omitted` marker —- // no download — while everything already inlined stays inline (a small history is byte-identical- // to before). `signal` (client disconnect) stops the loop between messages; partials are returned.- // The 25 MiB default is sized for ONE HTTP response and is too tight for a caller that ingests- // into a store instead (mediaMaxBytes — the status seed): two ~10 MiB videos are ~28 MiB of- // base64 and would strip every later status. Such a caller gets a budget derived from its own- // per-item cap rather than an exemption — unbounded here would mean a 50-item seed could stack- // ~650 MiB of base64 on the heap at connect time.- let mediaBudget = !includeMedia- ? Number.POSITIVE_INFINITY- : mediaMaxBytes === undefined- ? chatHistoryMediaBudgetBytes()- : ingestMediaBudgetBytes(mediaMaxBytes);- for (const msg of messages) {- if (signal?.aborted) {- break;- }- // Reuse the shared mapper so history messages carry the same author/contact- // enrichment as live incoming messages (#223). The mapper defaults chatId to- // msg.from, which is wrong here (history includes fromMe messages whose `from`- // is our own number), so override it to the requested chat and recompute the- // chatId-derived flags (isGroup, isStatusBroadcast, kind) from the real chat.- const out = buildIncomingMessageBase(msg);- out.chatId = chatId;- out.isGroup = chatId.endsWith('@g.us');- out.isStatusBroadcast = chatId === 'status@broadcast';- out.kind = chatKind(chatId);- const call = extractWwebjsCall(msg);- if (call) out.call = call;- // Mirror the live handler's location + quoted-message enrichment so history renders identically —- // buildIncomingMessageBase sets type='location' but no coordinates, and never resolves quotes.- if (msg.type === MessageTypes.LOCATION && msg.location) {- out.location = {- latitude: Number(msg.location.latitude),- longitude: Number(msg.location.longitude),- description: msg.location.description || undefined,- address: msg.location.address || undefined,- url: msg.location.url || undefined,- };- }- if (msg.hasQuotedMsg) {- try {- const quoted = await msg.getQuotedMessage();- out.quotedMessage = { id: quoted.id._serialized, body: quoted.body };- } catch (error) {- this.logger.warn(`Failed to resolve quoted message for ${msg.id._serialized}: ${String(error)}`);- }- }- if (includeMedia && msg.hasMedia) {- if (mediaBudget <= 0) {- out.media = declaredOnlyMedia(msg);- } else {- try {- // Same pre-gate + limiter as live media: a large historical blob shouldn't bloat the- // response/heap. Callers (the status seed) can tighten the cap below the global default.- const capped = await this.capInboundMediaFor(msg, mediaMaxBytes);- if (capped) {- out.media = capped;- // Only an inlined payload spends budget; an omitted marker carries no base64.- if (capped.data) {- mediaBudget -= capped.data.length;- }- }- } catch (error) {- this.logger.warn(`Failed to download media for ${msg.id._serialized}: ${String(error)}`);- }- }- }- results.push(out);- }- return results;+ return this.messaging.getChatHistory(chatId, limit, includeMedia, mediaMaxBytes, signal);}// Delete Message- async deleteMessage(chatId: string, messageId: string, forEveryone: boolean = true): Promise<void> {- this.ensureReady();- // NOTE: do NOT resolve chatId to @lid here — delete operates on the found message's own key, not- // this chatId, so LID-resolving the lookup gives no benefit and would miss a message stored under- // the pre-migration @c.us chat (#583 R1 review).- const chat = await this.client!.getChatById(chatId);- const messages = await chat.fetchMessages({ limit: 100 });- const message = messages.find(m => m.id._serialized === messageId || m.id.id === messageId);- if (!message) {- throw new MessageNotFoundError(messageId, chatId);- }- await message.delete(forEveryone);- this.logger.log(`Deleted message ${messageId} from chat ${chatId} (forEveryone: ${forEveryone})`);+ deleteMessage(chatId: string, messageId: string, forEveryone: boolean = true): Promise<void> {+ return this.messaging.deleteMessage(chatId, messageId, forEveryone);}// Edit Message- async editMessage(chatId: string, messageId: string, body: string): Promise<MessageResult> {- this.ensureReady();- // Same lookup window as react/delete: fetchMessages sees only the 100 most recent messages.- // NOTE: do NOT resolve chatId to @lid here — edit operates on the found message's own key, not- // this chatId, so LID-resolving the lookup would miss a message stored under the pre-migration- // @c.us chat (#583 R1 review).- const chat = await this.client!.getChatById(chatId);- // getChatById RESOLVES undefined for an unknown chat (wwebjs does not throw) — that is the same- // client-facing outcome as a message outside the fetch window, not a TypeError (-> 500).- if (!chat) {- throw new MessageNotFoundError(messageId, chatId);- }- const messages = await chat.fetchMessages({ limit: 100 });- const message = messages.find(m => m.id._serialized === messageId || m.id.id === messageId);- if (!message) {- throw new MessageNotFoundError(messageId, chatId);- }- const edited = await message.edit(body);- if (!edited) {- // wwebjs RESOLVES null (instead of throwing) when the page-side edit is refused — only the- // account's own text messages are editable; surface the refusal, not a phantom success.- throw new EngineRefusedError(- `the edit of message ${messageId} was rejected — only the account's own text messages can be edited`,- );- }- this.logger.log(`Edited message ${messageId} in chat ${chatId}`);- return this.toMessageResult(edited);+ editMessage(chatId: string, messageId: string, body: string): Promise<MessageResult> {+ return this.messaging.editMessage(chatId, messageId, body);}// Get Profile Picture- async getProfilePicture(contactId: string): Promise<string | null> {- this.ensureReady();- try {- const url = await this.client!.getProfilePicUrl(contactId);- return url || null;- } catch (error) {- // Mirrors getGroupInfo: a dead page and a contact with no picture both land here, and only the- // second may become null (→ service: the contact simply has no avatar). A transport death- // surfaced as "no picture" sends operators debugging the wrong layer — report it and answer 503.- if (this.isPageTransportError(error)) {- this.reportIfPageTransportError(error, 'getProfilePicture');- throw new EngineTransportError(`Transport died while reading profile picture for ${contactId}`);- }- this.logger.warn(`Failed to get profile picture for ${contactId}: ${String(error)}`);- return null;- }+ getProfilePicture(contactId: string): Promise<string | null> {+ return this.contacts.getProfilePicture(contactId);}// Block Contact- async blockContact(contactId: string): Promise<void> {- this.ensureReady();- const contact = await this.client!.getContactById(contactId);- await contact.block();- this.logger.log(`Blocked contact ${contactId}`);+ blockContact(contactId: string): Promise<void> {+ return this.contacts.blockContact(contactId);}// Unblock Contact- async unblockContact(contactId: string): Promise<void> {- this.ensureReady();- const contact = await this.client!.getContactById(contactId);- await contact.unblock();- this.logger.log(`Unblocked contact ${contactId}`);+ unblockContact(contactId: string): Promise<void> {+ return this.contacts.unblockContact(contactId);}// ========== Profile (own account) ==========- async setProfileName(name: string): Promise<void> {- this.ensureReady();- // setDisplayName resolves false (rather than throwing) when WhatsApp refuses the rename.- const ok = await this.client!.setDisplayName(name);- if (!ok) {- throw new EngineRefusedError('the engine rejected the profile name change');- }- this.logger.log('Updated profile name');+ setProfileName(name: string): Promise<void> {+ return this.profile.setProfileName(name);}- async setProfileStatus(status: string): Promise<void> {- this.ensureReady();- await this.client!.setStatus(status);- this.logger.log('Updated profile status');+ setProfileStatus(status: string): Promise<void> {+ return this.profile.setProfileStatus(status);}- async setProfilePicture(media: MediaInput): Promise<void> {- this.ensureReady();- const messageMedia = await this.toMessageMedia(media);- // setProfilePicture resolves false (rather than throwing) when the upload is refused.- const ok = await this.client!.setProfilePicture(messageMedia);- if (!ok) {- throw new EngineRefusedError('the engine rejected the profile picture change');- }- this.logger.log('Updated profile picture');+ setProfilePicture(media: MediaInput): Promise<void> {+ return this.profile.setProfilePicture(media);}// Get Group Invite Code- async getGroupInviteCode(groupId: string): Promise<string> {- this.ensureReady();- const chat = await this.client!.getChatById(groupId);- if (!chat.isGroup) {- throw new Error(`${groupId} is not a group`);- }- const inviteCode = await (chat as unknown as GroupChat).getInviteCode();- this.logger.log(`Got invite code for group ${groupId}`);- return String(inviteCode);+ getGroupInviteCode(groupId: string): Promise<string> {+ return this.groups.getGroupInviteCode(groupId);}// Revoke Group Invite Code- async revokeGroupInviteCode(groupId: string): Promise<string> {- this.ensureReady();- const chat = await this.client!.getChatById(groupId);- if (!chat.isGroup) {- throw new Error(`${groupId} is not a group`);- }- const newCode = await (chat as unknown as GroupChat).revokeInvite();- this.logger.log(`Revoked invite code for group ${groupId}, new code generated`);- return String(newCode);+ revokeGroupInviteCode(groupId: string): Promise<string> {+ return this.groups.revokeGroupInviteCode(groupId);}// Join Group via Invite Code- async joinGroupViaInviteCode(inviteCode: string): Promise<string> {- this.ensureReady();- // acceptInvite throws a page-side evaluation error when the invite is refused (invalid/expired/- // revoked); otherwise it resolves the joined group's id (`res.gid._serialized || res.gid.$1`,- // Client.js:1836-1845) — already the neutral `<id>@g.us` dialect. A gid-less result is the same- // client-facing outcome as a thrown refusal: no such invite (400, not a 500).- let groupId: string | undefined;- try {- groupId = await this.client!.acceptInvite(inviteCode);- } catch (error) {- // A refused invite and a broken page both land here, and only the first is the caller's- // fault. A transport death must not be reported as "invalid invite" (400): report the death- // to the liveness path and answer 503 so the caller can tell the layers apart.- if (this.isPageTransportError(error)) {- this.reportIfPageTransportError(error, 'joinGroupViaInviteCode');- throw new EngineTransportError('Transport died while accepting the group invite');- }- this.logger.warn(`Failed to accept group invite: ${String(error)}`);- groupId = undefined;- }- if (!groupId) {- throw new InvalidInviteCodeError();- }- this.logger.log(`Joined group ${groupId} via invite code`);- return groupId;- }-- /** Resolve a group chat or throw — the shared preamble of the group settings writes. */- private async requireGroupChat(groupId: string): Promise<GroupChat> {- this.ensureReady();- const chat = await this.client!.getChatById(groupId);- // getChatById RESOLVES undefined for an unknown id (wwebjs does not throw): unknown id and a- // non-group id are the same client-facing outcome — there is no such group (404, not a 500).- if (!chat?.isGroup) {- throw new GroupNotFoundError(groupId);- }- return chat as unknown as GroupChat;+ joinGroupViaInviteCode(inviteCode: string): Promise<string> {+ return this.groups.joinGroupViaInviteCode(inviteCode);}// Set "only admins can send messages" (announce)- async setGroupMessagesAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void> {- const groupChat = await this.requireGroupChat(groupId);- // Resolves false instead of throwing when the account lacks admin rights (GroupChat.js:503) —- // surface that as an error rather than a silent no-op.- const ok = await groupChat.setMessagesAdminsOnly(adminsOnly);- if (!ok) {- throw new EngineRefusedError(- `Failed to update the messages-admins-only setting for group ${groupId} — admin rights required`,- );- }+ setGroupMessagesAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void> {+ return this.groups.setGroupMessagesAdminsOnly(groupId, adminsOnly);}// Set "only admins can edit group info" (locked/restrict)- async setGroupInfoAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void> {- const groupChat = await this.requireGroupChat(groupId);- const ok = await groupChat.setInfoAdminsOnly(adminsOnly);- if (!ok) {- throw new EngineRefusedError(- `Failed to update the info-admins-only setting for group ${groupId} — admin rights required`,- );- }+ setGroupInfoAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void> {+ return this.groups.setGroupInfoAdminsOnly(groupId, adminsOnly);}- // whatsapp-web.js 1.34.7 exposes no disappearing-messages setter (no Client/GroupChat symbol in- // index.d.ts; only a create-time messageTimer option, Client.js:2371) — an honest 501, not a no-op.- // eslint-disable-next-line @typescript-eslint/require-await, @typescript-eslint/no-unused-vars- async setGroupEphemeral(_groupId: string, _durationSec: number): Promise<void> {- this.ensureReady();- throw new EngineNotSupportedError('setGroupEphemeral');+ setGroupEphemeral(groupId: string, durationSec: number): Promise<void> {+ return this.groups.setGroupEphemeral(groupId, durationSec);}// ========== Status/Stories (Phase 3) ==========// Note: These are stub implementations - whatsapp-web.js has limited Status API support- /* eslint-disable @typescript-eslint/require-await, @typescript-eslint/no-unused-vars */-- async getContactStatuses(): Promise<Status[]> {- this.ensureReady();- return this.collectStatuses(await this.client!.getBroadcasts());- }-- async getContactStatus(contactId: string): Promise<Status[]> {- this.ensureReady();- // A contact with no active 24h story resolves to an "empty" Broadcast (id/msgs/getContact- // undefined — Broadcast._patch only runs when data is truthy). That is the common case, so guard- // it: return [] rather than dereferencing undefined inside collectStatuses (→ 500).- const broadcast = await this.client!.getBroadcastById(contactId);- return broadcast?.msgs?.length ? this.collectStatuses([broadcast]) : [];- }-- /**- * Map whatsapp-web.js story Broadcasts (+ their Messages) into the neutral Status shape. Each- * Broadcast is one contact's story (its `msgs`); we flatten across broadcasts. type collapses to- * the Status union (image/video, else text — audio/other stories are rare and become 'text').- * expiresAt is timestamp + 24h (WhatsApp status TTL). Broadcasts without msgs are skipped (a story- * that expired between getBroadcasts and here, or a phantom entry).- */- private async collectStatuses(- broadcasts: ReadonlyArray<{- msgs?: Message[];- getContact: () => Promise<{ id: { _serialized: string }; name?: string; pushname?: string }>;- }>,- ): Promise<Status[]> {- const statuses: Status[] = [];- for (const broadcast of broadcasts) {- if (!broadcast?.msgs?.length) {- continue;- }- const contact = await broadcast.getContact();- const contactSummary = {- id: contact.id._serialized,- ...(contact.name ? { name: contact.name } : {}),- ...(contact.pushname ? { pushName: contact.pushname } : {}),- };- for (const msg of broadcast.msgs) {- const ts = new Date(msg.timestamp * 1000);- // Reuse the same capped/limited/timeout-bounded inbound media download the live message path- // uses (capInboundMediaFor), so a seeded status renders identically to one that arrived live.- let media: IncomingMessage['media'];- if (msg.hasMedia) {- try {- media = await this.capInboundMediaFor(msg);- } catch (error) {- this.logger.warn(`Failed to download media for status ${msg.id._serialized}: ${String(error)}`);- }- }- statuses.push({- // `deleteStatus` takes this id as its revoke handle, so losing it to the rename makes a- // listed status unactionable (#747). The contact id above is a Wid and is unaffected.- id: ((msg.id as unknown as SerializedWid)?._serialized ?? (msg.id as unknown as SerializedWid)?.$1) || '',- contact: contactSummary,- type: msg.type === MessageTypes.IMAGE ? 'image' : msg.type === MessageTypes.VIDEO ? 'video' : 'text',- ...(msg.body ? { caption: msg.body } : {}),- ...(media ? { media } : {}),- timestamp: ts,- expiresAt: new Date(ts.getTime() + 24 * 3_600_000),- });- }- }- return statuses;- }-- private warnedStatusRecipients = false;-- async postTextStatus(text: string, options: StatusPostOptions): Promise<StatusResult> {- this.ensureReady();- this.warnStatusRecipientsOnce(options);- // whatsapp-web.js posts a text status by messaging status@broadcast with styling in `extra`- // (Client.js maps options.extra → page extraOptions → sendStatusTextMsgAction in Utils.js).- // backgroundColor is a #RRGGBB hex; font is the fontStyle index 0-7.- const msg = await this.client!.sendMessage('status@broadcast', text, {- extra: {- ...(options.backgroundColor !== undefined ? { backgroundColor: options.backgroundColor } : {}),- ...(options.font !== undefined ? { fontStyle: options.font } : {}),- },- });- return this.toStatusResult(msg);- }- async postImageStatus(media: MediaInput, options: StatusPostOptions): Promise<StatusResult> {- return this.postMediaStatus(media, options);+ getContactStatuses(): Promise<Status[]> {+ return this.statuses.getContactStatuses();}- async postVideoStatus(media: MediaInput, options: StatusPostOptions): Promise<StatusResult> {- return this.postMediaStatus(media, options);- }-- private async postMediaStatus(media: MediaInput, options: StatusPostOptions): Promise<StatusResult> {- this.ensureReady();- this.warnStatusRecipientsOnce(options);- const messageMedia = await this.toMessageMedia(media);- const msg = await this.client!.sendMessage('status@broadcast', messageMedia, {- ...(options.caption !== undefined ? { caption: options.caption } : {}),- });- return this.toStatusResult(msg);+ getContactStatus(contactId: string): Promise<Status[]> {+ return this.statuses.getContactStatus(contactId);}- /**- * Build a MessageMedia from a MediaInput (URL → fetched, base64/Buffer → wrapped).- *- * `trustDeclaredType: false` keeps the fetched response's content-type for a remote URL. Use it- * wherever the mimetype is an INSTRUCTION rather than a label: whatsapp-web.js decides how to- * convert a sticker from it, and `Util.formatImageToWebpSticker` returns the media untouched when it- * already says webp. A caller that declares `image/webp` over bytes that are not webp would then- * have raw bytes shipped as a sticker. The response describes bytes the caller never saw, so for- * that one decision it is the better source. The declared filename still wins either way — that is- * a label, and nothing branches on it.- */- private async toMessageMedia(media: MediaInput, opts?: { trustDeclaredType?: boolean }): Promise<MessageMedia> {- if (typeof media.data === 'string' && isHttpUrl(media.data)) {- const fetched = await loadRemoteMedia(media.data);- // `loadRemoteMedia` derives both fields from the response (content-type, URL basename) because- // that is all it has. The caller usually knows better, so let an explicit `mimetype`/`filename`- // win — matching `resolveMediaBuffer` on the Baileys adapter, which already prefers the caller's.- // `application/octet-stream` is the DTO's own placeholder, not a statement about the bytes.- if (opts?.trustDeclaredType !== false && media.mimetype && media.mimetype !== 'application/octet-stream') {- fetched.mimetype = media.mimetype;- }- // Sticker path (trustDeclaredType:false): a specific fetched image/video MIME stays authoritative,- // but a generic/empty fetched MIME carries no information, and the caller's declared- // image/* or video/* would otherwise be discarded — whatsapp-web.js then rejects the format- // before running the sticker conversion. Fall back ONLY in that one shape: remote URL +- // trustDeclaredType:false + generic fetched type + convertible declared type. Canonicalize the- // value handed downstream (lowercased, params stripped) so a mixed-case declared type is- // normalized exactly once. A declared image/webp IS accepted here when the fetched response- // carries no usable MIME — the caller is asserting what the bytes actually are, so trusting it- // only in the generic-fetched shape can't bypass the sticker conversion the way globally- // trusting a declared WebP over a specific fetched type would. Arbitrary application/* is- // rejected (e.g. the DTO's own octet-stream placeholder, or application/pdf).- const normalizeMediaType = (value?: string): string => (value ?? '').split(';', 1)[0].trim().toLowerCase();- const fetchedType = normalizeMediaType(fetched.mimetype);- const declaredType = normalizeMediaType(media.mimetype);- const fetchedTypeIsGeneric = !fetchedType || fetchedType === 'application/octet-stream';- const declaredTypeIsConvertible = declaredType.startsWith('image/') || declaredType.startsWith('video/');- if (opts?.trustDeclaredType === false && fetchedTypeIsGeneric && declaredTypeIsConvertible) {- fetched.mimetype = declaredType;- }- if (media.filename) {- fetched.filename = media.filename;- }- return fetched;- }- const data = typeof media.data === 'string' ? media.data : media.data.toString('base64');- return new MessageMedia(media.mimetype, data, media.filename);- }-- /**- * Build the `MessageResult` for a send from whatever whatsapp-web.js hands back.- *- * `client.sendMessage()` can RESOLVE with `undefined` instead of throwing, and it collapses two- * opposite outcomes into that one value (`Client.js:1558`): the chat could not be resolved so nothing- * was sent (`if (!chat) return null`, `Client.js:1539`), or the message went out and only its id could- * not be read back (`Msg.get` miss, `Injected/Utils.js:585`). Nothing here can tell those apart, so an- * absent message is reported as a failed send: a false negative is visible and retryable, while- * claiming delivery for a message that never left is not recoverable. wwebjs's own typings hide the- * case entirely — `index.d.ts` declares `Promise<Message>`, so `strict` never flagged these reads.- *- * A `Message` instance is different: wwebjs only builds one from a real message model, so its presence- * proves the send happened. An id it cannot read there means "sent, id unknown" and carries the empty- * sentinel `forwardMessage` already returns — which `saveOutgoingMessage` stores as NULL rather than a- * fabricated id that a later ack could mis-match.- */- private toMessageResult(msg: Message | undefined): MessageResult {- if (!msg) {- throw new Error(- 'the engine returned no message for this send, so it may not have been delivered — check the chat before retrying',- );- }- const id = msg.id as unknown as SerializedWid | undefined;- return { id: id?._serialized ?? id?.$1 ?? '', timestamp: msg.timestamp };+ postTextStatus(text: string, options: StatusPostOptions): Promise<StatusResult> {+ return this.statuses.postTextStatus(text, options);}- /**- * The status-post counterpart of `toMessageResult`, but its absent-message case is *narrower* than a- * send's. `Injected/Utils.js` builds the status model and returns it from the `isStatus` branch before- * ever reaching the `Msg.get` miss that makes an ordinary send ambiguous — so the only way back with no- * message is `Client.js`'s `if (!chat) return null`, i.e. nothing was posted at all. Not an ambiguity:- * a plain failure, which was previously dressed up as a `201` carrying a `new Date()` invented for a- * status that never existed.- *- * Thrown as an `InternalServerErrorException` rather than a bare `Error` because there is no global- * exception filter (see `message-not-found.error.spec.ts`), so a bare `Error` reaches the caller as- * `{"statusCode":500,"message":"Internal server error"}` — and unlike a send, which routes its message- * into the `message:failed` hook, HTTP is the only consumer a status post has. The same 500, with the- * reason surviving.- *- * A present `Message` proves the post happened, so an id it cannot read there carries the same empty- * sentinel `toMessageResult` uses. Read `$1` before falling back to it (#747): the sentinel means- * "posted, id unknown", and `deleteStatus` takes this id as the revoke handle — spending it on an id- * that was readable all along leaves a status nothing can revoke.- */- private toStatusResult(msg: Message | undefined): StatusResult {- if (!msg) {- throw new InternalServerErrorException(- 'the engine returned no message for this status post, so it may not have been published — check your status before retrying',- );- }- const id = msg.id as unknown as SerializedWid | undefined;- const ts = msg.timestamp ? new Date(msg.timestamp * 1000) : new Date();- return {- statusId: id?._serialized ?? id?.$1 ?? '',- timestamp: ts,- expiresAt: new Date(ts.getTime() + 24 * 3_600_000),- };+ postImageStatus(media: MediaInput, options: StatusPostOptions): Promise<StatusResult> {+ return this.statuses.postImageStatus(media, options);}- private warnStatusRecipientsOnce(options: StatusPostOptions): void {- if (this.warnedStatusRecipients || !options.recipients?.length) return;- this.warnedStatusRecipients = true;- this.logger.warn(- "postStatus on the whatsapp-web.js engine broadcasts to the account's status-privacy audience; " +- 'the recipients allow-list is not honored by whatsapp-web.js (it is on the Baileys engine).',- );+ postVideoStatus(media: MediaInput, options: StatusPostOptions): Promise<StatusResult> {+ return this.statuses.postVideoStatus(media, options);}- async deleteStatus(statusId: string): Promise<void> {- this.ensureReady();- // Revokes the caller's own status post. revokeStatusMessage resolves the message by id and- // throws if it isn't fromMe/isn't a status — the statusId returned by postText/Image/VideoStatus- // (msg.id._serialized) is the id it expects.- await this.client!.revokeStatusMessage(statusId);+ deleteStatus(statusId: string): Promise<void> {+ return this.statuses.deleteStatus(statusId);}// ========== Catalog (Phase 3) ==========@@ -3049,137 +1742,44 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin// reported "no catalog" / "no products" for a capability that never ran. Honest 501s instead,// matching sendProduct/sendCatalog below.- async getCatalog(): Promise<Catalog | null> {- this.ensureReady();- throw new EngineNotSupportedError('getCatalog');+ getCatalog(): Promise<Catalog | null> {+ return this.catalog.getCatalog();}- async getProducts(_options?: ProductQueryOptions): Promise<PaginatedProducts> {- this.ensureReady();- throw new EngineNotSupportedError('getProducts');+ getProducts(_options?: ProductQueryOptions): Promise<PaginatedProducts> {+ return this.catalog.getProducts(_options);}- async getProduct(_productId: string): Promise<Product | null> {- this.ensureReady();- throw new EngineNotSupportedError('getProduct');+ getProduct(_productId: string): Promise<Product | null> {+ return this.catalog.getProduct(_productId);}- async sendProduct(_chatId: string, _productId: string, _body?: string): Promise<MessageResult> {- this.ensureReady();- throw new EngineNotSupportedError('sendProduct');+ sendProduct(_chatId: string, _productId: string, _body?: string): Promise<MessageResult> {+ return this.catalog.sendProduct(_chatId, _productId, _body);}- async sendCatalog(_chatId: string, _body?: string): Promise<MessageResult> {- this.ensureReady();- throw new EngineNotSupportedError('sendCatalog');+ sendCatalog(_chatId: string, _body?: string): Promise<MessageResult> {+ return this.catalog.sendCatalog(_chatId, _body);}- /* eslint-enable @typescript-eslint/require-await, @typescript-eslint/no-unused-vars */-- async getChats(): Promise<ChatSummary[]> {- this.ensureReady();- const chats = await this.client!.getChats();- const summaries: ChatSummary[] = [];- let skipped = 0;-- // Map the raw whatsapp-web.js chat objects to the library-agnostic ChatSummary- // shape so that no library types leak past the engine boundary. Some WA system- // or channel-like entries can lack the normal serialized id; skip those instead- // of failing the whole dashboard chats request.- for (const chat of chats) {- const id = chat.id?._serialized;- if (!id) {- skipped++;- continue;- }-- summaries.push({- id,- name: chat.name || id,- isGroup: Boolean(chat.isGroup),- kind: chatKind(id),- unreadCount: chat.unreadCount || 0,- timestamp: chat.timestamp || 0,- // A location message's body is the base64 map thumbnail; don't surface it as the chat preview.- lastMessage: chat.lastMessage?.type === MessageTypes.LOCATION ? '📍' : chat.lastMessage?.body || undefined,- });- }-- if (skipped > 0) {- this.logger.warn(`Skipped ${skipped} chat(s) without a serialized id`);- }-- return summaries;+ getChats(): Promise<ChatSummary[]> {+ return this.chats.getChats();}- async sendSeen(chatId: string): Promise<boolean> {- this.ensureReady();- try {- const chat = await this.client!.getChatById(chatId);- return await chat.sendSeen();- } catch (error) {- this.logger.error(`Error marking chat ${chatId} as read`, String(error));- return false;- }+ sendSeen(chatId: string): Promise<boolean> {+ return this.chats.sendSeen(chatId);}- async markUnread(chatId: string): Promise<boolean> {- this.ensureReady();- if (isChannelJid(chatId)) {- // A channel resolves to a wwebjs `Channel`, which has no markUnread() — there is no unread- // state to toggle on a channel. Report the no-op rather than throwing a TypeError.- return false;- }- try {- const chat = await this.client!.getChatById(chatId);- // Chat.markUnread() resolves void, so synthesize the boolean from a clean call.- await chat.markUnread();- return true;- } catch (error) {- this.logger.error(`Error marking chat ${chatId} as unread`, String(error));- return false;- }+ markUnread(chatId: string): Promise<boolean> {+ return this.chats.markUnread(chatId);}- async deleteChat(chatId: string): Promise<boolean> {- this.ensureReady();- if (isChannelJid(chatId)) {- // A channel resolves to a wwebjs `Channel`, which has no delete() (only the destructive- // deleteChannel()); a generic chat-delete must not silently unsubscribe a channel.- return false;- }- try {- const chat = await this.client!.getChatById(chatId);- return await chat.delete();- } catch (error) {- this.logger.error(`Error deleting chat ${chatId}`, String(error));- return false;- }+ deleteChat(chatId: string): Promise<boolean> {+ return this.chats.deleteChat(chatId);}- async sendChatState(chatId: string, state: ChatState): Promise<void> {- this.ensureReady();- if (isChannelJid(chatId)) {- // A channel resolves to a wwebjs `Channel`, which has no presence methods- // (sendStateTyping/sendStateRecording/clearState). Presence is best-effort, so no-op.- return;- }- try {- const to = await this.resolveSendId(chatId);- const chat = await this.client!.getChatById(to);- if (state === 'typing') {- await chat.sendStateTyping();- } else if (state === 'recording') {- await chat.sendStateRecording();- } else {- await chat.clearState();- }- } catch (error) {- // Presence is best-effort and already swallowed here — it never breaks the surrounding send —- // so log at WARN, not ERROR: a migrated contact routinely yields `No LID for user` on the- // presence path and an ERROR line reads as a fault when nothing actually failed (#582).- this.logger.warn(`Could not set chat state '${state}' for ${chatId} (best-effort)`, { error: String(error) });- }+ sendChatState(chatId: string, state: ChatState): Promise<void> {+ return this.chats.sendChatState(chatId, state);}private ensureReady(): void {diff --git a/src/engine/adapters/wwebjs-catalog.ts b/src/engine/adapters/wwebjs-catalog.tsnew file mode 100644index 000000000..b2aa07c16--- /dev/null+++ b/src/engine/adapters/wwebjs-catalog.ts@@ -0,0 +1,46 @@+import {+ Catalog,+ MessageResult,+ Product,+ ProductQueryOptions,+ PaginatedProducts,+} from '../interfaces/whatsapp-engine.interface';+import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';+import { type WwebjsEngineHost } from './wwebjs-host';++/**+ * Catalog operations extracted from WhatsAppWebJsAdapter: whatsapp-web.js has no Catalog API at all+ * (no Client.getCatalog/getProducts/getProduct symbol in index.d.ts), so these are honest 501s.+ * The adapter keeps the public methods as thin forwarders and injects the shared host surface+ * (./wwebjs-host) via closures, so the delegate never touches lifecycle state directly.+ */+export class WwebjsCatalog {+ constructor(private readonly host: WwebjsEngineHost) {}++ /* eslint-disable @typescript-eslint/require-await, @typescript-eslint/no-unused-vars */+ async getCatalog(): Promise<Catalog | null> {+ this.host.ensureReady();+ throw new EngineNotSupportedError('getCatalog');+ }++ async getProducts(_options?: ProductQueryOptions): Promise<PaginatedProducts> {+ this.host.ensureReady();+ throw new EngineNotSupportedError('getProducts');+ }++ async getProduct(_productId: string): Promise<Product | null> {+ this.host.ensureReady();+ throw new EngineNotSupportedError('getProduct');+ }++ async sendProduct(_chatId: string, _productId: string, _body?: string): Promise<MessageResult> {+ this.host.ensureReady();+ throw new EngineNotSupportedError('sendProduct');+ }++ async sendCatalog(_chatId: string, _body?: string): Promise<MessageResult> {+ this.host.ensureReady();+ throw new EngineNotSupportedError('sendCatalog');+ }+ /* eslint-enable @typescript-eslint/require-await, @typescript-eslint/no-unused-vars */+}diff --git a/src/engine/adapters/wwebjs-channels.ts b/src/engine/adapters/wwebjs-channels.tsnew file mode 100644index 000000000..ea4d77308--- /dev/null+++ b/src/engine/adapters/wwebjs-channels.ts@@ -0,0 +1,98 @@+import { type Client } from 'whatsapp-web.js';+import { Channel, ChannelMessage } from '../interfaces/whatsapp-engine.interface';+import { BusinessClient, WwjsChannelData } from '../types/whatsapp-web-js.types';+import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';+import { type WwebjsEngineHost } from './wwebjs-host';++/**+ * Channel/Newsletter operations extracted from WhatsAppWebJsAdapter. The adapter keeps the public+ * methods as thin forwarders and injects the shared host surface (./wwebjs-host) via closures, so+ * the delegate never touches lifecycle state directly.+ */+export class WwebjsChannels {+ constructor(private readonly host: WwebjsEngineHost) {}++ /** Post-ensureReady client handle. */+ private client(): Client {+ return this.host.getClient();+ }++ async getSubscribedChannels(): Promise<Channel[]> {+ this.host.ensureReady();+ const channels = await (this.client() as unknown as BusinessClient).getChannels();+ if (!channels) {+ return [];+ }+ return channels.map((ch: WwjsChannelData) => ({+ id: String(typeof ch.id === 'object' ? ch.id._serialized : ch.id),+ name: String(ch.name || ''),+ description: ch.description ? String(ch.description) : undefined,+ inviteCode: ch.inviteCode ? String(ch.inviteCode) : undefined,+ subscriberCount: ch.subscriberCount ? Number(ch.subscriberCount) : undefined,+ verified: ch.verified ? Boolean(ch.verified) : undefined,+ }));+ }++ async getChannelById(channelId: string): Promise<Channel | null> {+ this.host.ensureReady();+ // wwebjs 1.34.x exposes no client.getChannelById; resolve from the subscribed-channel list (#625).+ const channels = await this.getSubscribedChannels();+ return channels.find(c => c.id === channelId) ?? null;+ }++ // whatsapp-web.js `Client.subscribeToChannel(channelId)` takes a channel ID and resolves a+ // boolean (index.d.ts:71; Client.js:2533) — the interface contract here is subscribe-by-INVITE-CODE+ // returning the subscribed Channel. The old wiring passed the invite code straight in and mapped+ // the returned boolean as if it were a Channel, fabricating `{ id: "undefined" }`: a reported+ // success that never subscribed anything. A real wiring is the two-step+ // `getChannelByInviteCode(inviteCode)` (Client.js:1707) → `subscribeToChannel(channel.id)` flow;+ // until that is verified against a live session, an honest 501 beats a phantom success.+ // eslint-disable-next-line @typescript-eslint/require-await, @typescript-eslint/no-unused-vars+ async subscribeToChannel(_inviteCode: string): Promise<Channel> {+ this.host.ensureReady();+ throw new EngineNotSupportedError('subscribeToChannel');+ }++ async unsubscribeFromChannel(channelId: string): Promise<void> {+ this.host.ensureReady();+ // Resolves false instead of throwing when the unsubscription did not complete (Client.js:2556)+ // — surface the refusal rather than reporting a false success.+ const ok = await (this.client() as unknown as BusinessClient).unsubscribeFromChannel(channelId);+ if (!ok) {+ throw new EngineRefusedError(`Failed to unsubscribe from channel ${channelId}`);+ }+ this.host.logger.log(`Unsubscribed from channel: ${channelId}`);+ }++ async getChannelMessages(channelId: string, limit: number = 50): Promise<ChannelMessage[]> {+ this.host.ensureReady();+ // wwebjs 1.34.x has no client.getChannelById (calling it threw and the error was swallowed into an+ // empty list, #625). The subscribed Channel instances returned by getChannels() carry fetchMessages(),+ // so resolve the channel from that list and read its messages. A missing channel surfaces as a+ // ChannelNotFoundError (→ 404, like getChannelById) so callers can tell "no messages" apart from+ // "wrong/unsubscribed channel" instead of getting a silent [].+ const channels = await (this.client() as unknown as BusinessClient).getChannels();+ const channel = channels?.find(c => (typeof c.id === 'object' ? c.id._serialized : c.id) === channelId);+ if (!channel) {+ throw new ChannelNotFoundError(channelId);+ }+ // wwebjs Channel.fetchMessages only honors a limit > 0: its load-earlier loop AND the final+ // splice are both gated on `searchOptions.limit > 0` (Channel.js:352), so a 0/negative/NaN+ // limit fails OPEN and returns every loaded message. Substitute the default instead.+ const safeLimit = Number.isFinite(limit) && limit >= 1 ? Math.trunc(limit) : 50;+ const messages = await channel.fetchMessages({ limit: safeLimit });+ return (messages ?? []).map(msg => ({+ // Read `$1` before the sentinel (#747), and don't `String()` the object branch: that turned an+ // unreadable id into the literal "undefined" rather than the empty sentinel every other path+ // uses. Read-only endpoint — never persisted, never ack-matched — so `''` carries no collision+ // risk here; it just means "id unreadable".+ id: (typeof msg.id === 'object' ? (msg.id?._serialized ?? msg.id?.$1) : msg.id) || '',+ body: String(msg.body || ''),+ timestamp: Number(msg.timestamp),+ hasMedia: Boolean(msg.hasMedia),+ mediaUrl: msg.mediaUrl ? String(msg.mediaUrl) : undefined,+ }));+ }+}diff --git a/src/engine/adapters/wwebjs-chats.ts b/src/engine/adapters/wwebjs-chats.tsnew file mode 100644index 000000000..2fc3d4172--- /dev/null+++ b/src/engine/adapters/wwebjs-chats.ts@@ -0,0 +1,131 @@+import { MessageTypes, type Client } from 'whatsapp-web.js';+import { ChatSummary, ChatState } from '../interfaces/whatsapp-engine.interface';+import { chatKind, isChannelJid } from '../identity/wa-id';+import { WwebjsMessaging } from './wwebjs-messaging';+import { type WwebjsEngineHost } from './wwebjs-host';++/**+ * Chat-list operations extracted from WhatsAppWebJsAdapter. The adapter keeps the public methods as+ * thin forwarders and injects the shared host surface (./wwebjs-host) via closures, so the delegate+ * never touches lifecycle state directly. Presence (sendChatState) resolves the recipient through+ * the messaging delegate's send-id cache, exactly like a send.+ */+export class WwebjsChats {+ constructor(+ private readonly host: WwebjsEngineHost,+ private readonly messaging: WwebjsMessaging,+ ) {}++ /** Post-ensureReady client handle. */+ private client(): Client {+ return this.host.getClient();+ }++ async getChats(): Promise<ChatSummary[]> {+ this.host.ensureReady();+ const chats = await this.client().getChats();+ const summaries: ChatSummary[] = [];+ let skipped = 0;++ // Map the raw whatsapp-web.js chat objects to the library-agnostic ChatSummary+ // shape so that no library types leak past the engine boundary. Some WA system+ // or channel-like entries can lack the normal serialized id; skip those instead+ // of failing the whole dashboard chats request.+ for (const chat of chats) {+ const id = chat.id?._serialized;+ if (!id) {+ skipped++;+ continue;+ }++ summaries.push({+ id,+ name: chat.name || id,+ isGroup: Boolean(chat.isGroup),+ kind: chatKind(id),+ unreadCount: chat.unreadCount || 0,+ timestamp: chat.timestamp || 0,+ // A location message's body is the base64 map thumbnail; don't surface it as the chat preview.+ lastMessage: chat.lastMessage?.type === MessageTypes.LOCATION ? '📍' : chat.lastMessage?.body || undefined,+ });+ }++ if (skipped > 0) {+ this.host.logger.warn(`Skipped ${skipped} chat(s) without a serialized id`);+ }++ return summaries;+ }++ async sendSeen(chatId: string): Promise<boolean> {+ this.host.ensureReady();+ try {+ const chat = await this.client().getChatById(chatId);+ return await chat.sendSeen();+ } catch (error) {+ this.host.logger.error(`Error marking chat ${chatId} as read`, String(error));+ return false;+ }+ }++ async markUnread(chatId: string): Promise<boolean> {+ this.host.ensureReady();+ if (isChannelJid(chatId)) {+ // A channel resolves to a wwebjs `Channel`, which has no markUnread() — there is no unread+ // state to toggle on a channel. Report the no-op rather than throwing a TypeError.+ return false;+ }+ try {+ const chat = await this.client().getChatById(chatId);+ // Chat.markUnread() resolves void, so synthesize the boolean from a clean call.+ await chat.markUnread();+ return true;+ } catch (error) {+ this.host.logger.error(`Error marking chat ${chatId} as unread`, String(error));+ return false;+ }+ }++ async deleteChat(chatId: string): Promise<boolean> {+ this.host.ensureReady();+ if (isChannelJid(chatId)) {+ // A channel resolves to a wwebjs `Channel`, which has no delete() (only the destructive+ // deleteChannel()); a generic chat-delete must not silently unsubscribe a channel.+ return false;+ }+ try {+ const chat = await this.client().getChatById(chatId);+ return await chat.delete();+ } catch (error) {+ this.host.logger.error(`Error deleting chat ${chatId}`, String(error));+ return false;+ }+ }++ async sendChatState(chatId: string, state: ChatState): Promise<void> {+ this.host.ensureReady();+ if (isChannelJid(chatId)) {+ // A channel resolves to a wwebjs `Channel`, which has no presence methods+ // (sendStateTyping/sendStateRecording/clearState). Presence is best-effort, so no-op.+ return;+ }+ try {+ const to = await this.messaging.resolveSendId(chatId);+ const chat = await this.client().getChatById(to);+ if (state === 'typing') {+ await chat.sendStateTyping();+ } else if (state === 'recording') {+ await chat.sendStateRecording();+ } else {+ await chat.clearState();+ }+ } catch (error) {+ // Presence is best-effort and already swallowed here — it never breaks the surrounding send —+ // so log at WARN, not ERROR: a migrated contact routinely yields `No LID for user` on the+ // presence path and an ERROR line reads as a fault when nothing actually failed (#582).+ this.host.logger.warn(`Could not set chat state '${state}' for ${chatId} (best-effort)`, {+ error: String(error),+ });+ }+ }+}diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.tsnew file mode 100644index 000000000..1cd559a38--- /dev/null+++ b/src/engine/adapters/wwebjs-contacts.ts@@ -0,0 +1,119 @@+import { type Client } from 'whatsapp-web.js';+import { Contact } from '../interfaces/whatsapp-engine.interface';+import { EngineTransportError } from '../../common/errors/engine-transport.error';+import { type WwebjsEngineHost } from './wwebjs-host';++/**+ * Contact operations extracted from WhatsAppWebJsAdapter. The adapter keeps the public methods as+ * thin forwarders and injects the shared host surface (./wwebjs-host) via closures, so the delegate+ * never touches lifecycle state directly.+ */+export class WwebjsContacts {+ constructor(private readonly host: WwebjsEngineHost) {}++ /** Post-ensureReady client handle. */+ private client(): Client {+ return this.host.getClient();+ }++ async getContacts(): Promise<Contact[]> {+ this.host.ensureReady();+ try {+ const contacts = await this.client().getContacts();++ return contacts.map(c => ({+ id: c.id._serialized,+ name: c.name || undefined,+ pushName: c.pushname || undefined,+ number: c.number,+ isMyContact: c.isMyContact,+ isBlocked: c.isBlocked,+ }));+ } catch (error) {+ this.host.reportIfPageTransportError(error, 'getContacts');+ throw error;+ }+ }++ async getContactById(contactId: string): Promise<Contact | null> {+ this.host.ensureReady();+ try {+ const contact = await this.client().getContactById(contactId);+ return {+ id: contact.id._serialized,+ name: contact.name || undefined,+ pushName: contact.pushname || undefined,+ number: contact.number,+ isMyContact: contact.isMyContact,+ isBlocked: contact.isBlocked,+ };+ } catch (error) {+ this.host.logger.warn(`Failed to get contact: ${contactId}`, { error: String(error) });+ return null;+ }+ }++ async getNumberId(number: string): Promise<string | null> {+ this.host.ensureReady();+ try {+ const numberId = await this.client().getNumberId(number);+ return numberId?._serialized ?? null;+ } catch (error) {+ this.host.reportIfPageTransportError(error, 'getNumberId');+ throw error;+ }+ }++ async checkNumberExists(number: string): Promise<boolean> {+ return (await this.getNumberId(number)) !== null;+ }++ async resolveContactPhone(contactId: string): Promise<string | null> {+ this.host.ensureReady();+ try {+ // Queried one id at a time: the batch form is prone to "Evaluation failed" and rate-limiting+ // (whatsapp-web.js #3857/#3969). `pn` is the phone JID (`<digits>@c.us`) when the account knows+ // the mapping; best-effort, so a missing mapping or any failure resolves to null.+ const [result] = await this.client().getContactLidAndPhone([contactId]);+ const pn = result?.pn;+ return pn ? pn.replace(/@c\.us$/i, '').replace(/\D/g, '') || null : null;+ } catch (error) {+ this.host.logger.debug(`resolveContactPhone failed for ${contactId}`, {+ error: error instanceof Error ? error.message : String(error),+ });+ return null;+ }+ }++ async blockContact(contactId: string): Promise<void> {+ this.host.ensureReady();+ const contact = await this.client().getContactById(contactId);+ await contact.block();+ this.host.logger.log(`Blocked contact ${contactId}`);+ }++ async unblockContact(contactId: string): Promise<void> {+ this.host.ensureReady();+ const contact = await this.client().getContactById(contactId);+ await contact.unblock();+ this.host.logger.log(`Unblocked contact ${contactId}`);+ }++ async getProfilePicture(contactId: string): Promise<string | null> {+ this.host.ensureReady();+ try {+ const url = await this.client().getProfilePicUrl(contactId);+ return url || null;+ } catch (error) {+ // Mirrors getGroupInfo: a dead page and a contact with no picture both land here, and only the+ // second may become null (→ service: the contact simply has no avatar). A transport death+ // surfaced as "no picture" sends operators debugging the wrong layer — report it and answer 503.+ if (this.host.isPageTransportError(error)) {+ this.host.reportIfPageTransportError(error, 'getProfilePicture');+ throw new EngineTransportError(`Transport died while reading profile picture for ${contactId}`);+ }+ this.host.logger.warn(`Failed to get profile picture for ${contactId}: ${String(error)}`);+ return null;+ }+ }+}diff --git a/src/engine/adapters/wwebjs-group-events.ts b/src/engine/adapters/wwebjs-group-events.tsnew file mode 100644index 000000000..db13b5518--- /dev/null+++ b/src/engine/adapters/wwebjs-group-events.ts@@ -0,0 +1,63 @@+import { type GroupNotification } from 'whatsapp-web.js';+import { GroupEvent } from '../interfaces/whatsapp-engine.interface';+import { SerializedWid } from '../types/whatsapp-web-js.types';++/**+ * Interpret the on/off value a group settings notification carries in `body` ('on'/'true' → true,+ * 'off'/'false' → false). Undefined when the body holds anything else (e.g. a rendered template+ * string), in which case the caller emits the update without that change rather than guess.+ */+function parseWwebjsOnOff(body: string): boolean | undefined {+ const v = body.trim().toLowerCase();+ if (v === 'on' || v === 'true') return true;+ if (v === 'off' || v === 'false') return false;+ return undefined;+}++/**+ * Reduce a `group_update` GroupNotification to the neutral `changes` delta. `subject`/`description`+ * carry the new value in `body`; `announce`/`restrict` encode the new setting as on/off text (the+ * latter maps to the neutral `locked`). Anything uninterpretable — a `picture` change, or a WA Web+ * build that stops putting the value in `body` — yields an empty delta: the occurrence is still+ * emitted, just without fields we would be guessing at. Compared as strings because the runtime+ * gp2 subtypes can exceed the GroupNotificationTypes enum (e.g. a 'locked' rename of 'restrict').+ */+export function wwebjsGroupUpdateChanges(notification: GroupNotification): NonNullable<GroupEvent['changes']> {+ const body = typeof notification.body === 'string' ? notification.body : '';+ switch (String(notification.type)) {+ case 'subject':+ return { subject: body };+ case 'description':+ return { description: body };+ case 'announce': {+ const on = parseWwebjsOnOff(body);+ return on === undefined ? {} : { announce: on };+ }+ case 'restrict':+ case 'locked': {+ const on = parseWwebjsOnOff(body);+ return on === undefined ? {} : { locked: on };+ }+ default:+ return {};+ }+}++/**+ * A GroupNotification's `recipientIds` are assigned straight through from the wire+ * (`this.recipientIds = data.recipients`), outside upstream's id normalization — so on a WA Web+ * build that renamed `_serialized` to `$1` (#747) an entry can arrive as a raw id object instead+ * of a string. Coerce both shapes to the neutral (already @c.us/@g.us) string form; entries that+ * resolve to nothing are dropped rather than forwarded as "undefined".+ */+export function wwebjsGroupRecipientIds(notification: GroupNotification): string[] {+ const raw = notification.recipientIds as unknown;+ if (!Array.isArray(raw)) return [];+ return raw+ .map(entry => {+ if (typeof entry === 'string') return entry;+ const wid = entry as SerializedWid | undefined;+ return wid?._serialized ?? wid?.$1 ?? '';+ })+ .filter(id => id.length > 0);+}diff --git a/src/engine/adapters/wwebjs-groups.ts b/src/engine/adapters/wwebjs-groups.tsnew file mode 100644index 000000000..c4bb7b767--- /dev/null+++ b/src/engine/adapters/wwebjs-groups.ts@@ -0,0 +1,377 @@+import { type Client } from 'whatsapp-web.js';+import {+ Group,+ GroupInfo,+ GroupParticipant,+ ParticipantOperationResult,+} from '../interfaces/whatsapp-engine.interface';+import { GroupChat, GroupMetadataRaw, GroupCreateResult, SerializedWid } from '../types/whatsapp-web-js.types';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { EngineTransportError } from '../../common/errors/engine-transport.error';+import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';+import { GroupNotFoundError } from '../../common/errors/group-not-found.error';+import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';+import { type WwebjsEngineHost } from './wwebjs-host';++/**+ * Extracts the JID of the parent community a group is linked to, if any.+ * The field name has varied across whatsapp-web.js/WA Web versions, so+ * known candidates are checked in order.+ */+export function extractLinkedParentJID(groupMetadata?: GroupMetadataRaw): string | null {+ const candidate =+ groupMetadata?.parentGroup ?? groupMetadata?.linkedParentGroup ?? groupMetadata?.linkedParent ?? null;++ if (!candidate) {+ return null;+ }++ if (typeof candidate === 'string') {+ return candidate;+ }++ return candidate._serialized ?? null;+}++/**+ * Group-domain operations extracted from WhatsAppWebJsAdapter. The adapter keeps the public+ * methods as thin forwarders and injects the shared host surface (./wwebjs-host) via closures,+ * so the delegate never touches lifecycle state directly.+ */+export class WwebjsGroups {+ constructor(private readonly host: WwebjsEngineHost) {}++ /** Post-ensureReady client handle. */+ private client(): Client {+ return this.host.getClient();+ }++ async getGroups(): Promise<Group[]> {+ this.host.ensureReady();+ try {+ const client = this.client();+ const chats = await client.getChats();++ // Filter only group chats+ const groups = chats.filter(chat => chat.isGroup);++ // List path: read linkedParentJID synchronously from whatever metadata getChats()+ // already loaded. We deliberately do NOT fall back to getChatById per group here —+ // that would be an N+1 round-trip across every group on every list call. Groups+ // whose metadata isn't loaded report null; the single-group endpoint (getGroupInfo,+ // which loads full metadata via getChatById) is the authoritative source.+ return groups.map(g => {+ const groupChat = g as unknown as GroupChat;+ return {+ id: g.id._serialized,+ name: g.name,+ participantsCount: groupChat.participants?.length,+ isAdmin: groupChat.participants?.some(p => p.isAdmin && p.id._serialized === client.info?.wid?._serialized),+ linkedParentJID: extractLinkedParentJID(groupChat.groupMetadata),+ };+ });+ } catch (error) {+ this.host.reportIfPageTransportError(error, 'getGroups');+ throw error;+ }+ }++ async getGroupInfo(groupId: string): Promise<GroupInfo | null> {+ this.host.ensureReady();+ try {+ const chat = await this.client().getChatById(groupId);+ if (!chat.isGroup) {+ return null;+ }+ const groupChat = chat as unknown as GroupChat;+ const participants: GroupParticipant[] = (groupChat.participants || []).map(p => ({+ id: String(p.id._serialized),+ number: String(p.id.user),+ name: p.name ? String(p.name) : undefined,+ isAdmin: Boolean(p.isAdmin),+ isSuperAdmin: Boolean(p.isSuperAdmin),+ }));++ return {+ id: chat.id._serialized,+ name: chat.name,+ description: groupChat.description ? String(groupChat.description) : undefined,+ owner: groupChat.owner?._serialized ? String(groupChat.owner._serialized) : undefined,+ createdAt: groupChat.createdAt,+ participants,+ isReadOnly: Boolean(groupChat.isReadOnly),+ isAnnounce: Boolean(groupChat.isAnnounce),+ announce: groupChat.groupMetadata?.announce,+ locked: groupChat.groupMetadata?.restrict,+ ephemeralSeconds: groupChat.groupMetadata?.ephemeralDuration,+ linkedParentJID: extractLinkedParentJID(groupChat.groupMetadata),+ };+ } catch (error) {+ // A dead page and a genuinely-missing group both land in this catch; only the second may+ // become null (→ service 404). A transport death surfaced as "group not found" sends+ // operators debugging the wrong layer — report it and answer 503 instead.+ if (this.host.isPageTransportError(error)) {+ this.host.reportIfPageTransportError(error, 'getGroupInfo');+ throw new EngineTransportError(`Transport died while reading group ${groupId}`);+ }+ this.host.logger.warn(`Failed to get group: ${groupId}`, { error: String(error) });+ return null;+ }+ }++ async createGroup(name: string, participants: string[]): Promise<Group> {+ this.host.ensureReady();+ // Ensure participant IDs are in correct format+ const participantIds = participants.map(p => (p.includes('@') ? p : `${p}@c.us`));+ const result = await this.client().createGroup(name, participantIds);++ // whatsapp-web.js reports a failed creation by RESOLVING with a plain string+ // ('CreateGroupError: …', Client.js:2376) rather than throwing, and its own typings say so+ // (`Promise<CreateGroupResult | string>`). Reading `.gid` straight off that string threw an opaque+ // TypeError and discarded the reason upstream actually gave us; surface it instead.+ if (typeof result === 'string') {+ throw new Error(result);+ }+ const gid = (result as unknown as GroupCreateResult).gid as SerializedWid | undefined;+ const groupId = gid?._serialized ?? gid?.$1;+ // A group id is not ack-safe the way a message id is: there is no empty-sentinel equivalent, and any+ // placeholder would be handed back as a real, addressable group. Fail instead of inventing one.+ if (!groupId) {+ throw new Error('the group was created but its id could not be read');+ }+ return {+ id: groupId,+ name: name,+ participantsCount: participants.length,+ };+ }++ async addParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {+ this.host.ensureReady();+ const chat = await this.client().getChatById(groupId);+ if (!chat.isGroup) {+ throw new Error('Chat is not a group');+ }+ const participantIds = participants.map(p => (p.includes('@') ? p : `${p}@c.us`));+ const raw = await (chat as unknown as GroupChat).addParticipants(participantIds);+ // whatsapp-web.js reports a batch-level refusal (no admin rights, empty group) by RESOLVING a+ // plain reason string (GroupChat.js:106-107,128-130) instead of throwing — surface it as a+ // refusal, not a success.+ if (typeof raw === 'string') {+ throw new EngineRefusedError(raw);+ }+ // Per-participant outcome: code 200 = added; 403 invite-only / 404 not registered / 408+ // recently left / 409 already a member / 419 group full (GroupChat.js:102-116).+ const results: ParticipantOperationResult[] = Object.entries(raw ?? {}).map(([id, r]) => {+ // A 403 with isInviteV4Sent is not a failure: wwebjs already delivered the private group+ // invite (GroupChat.js:203-240). Report it as success-with-invite — otherwise an all-invite+ // batch throws "failed for all" (HTTP 403) even though every participant was reached.+ const inviteSent = r.code === 403 && r.isInviteV4Sent === true;+ return {+ id,+ success: r.code === 200 || inviteSent,+ status: r.code,+ message: inviteSent+ ? 'the participant can only be added by private invitation — invite sent'+ : r.message || undefined,+ };+ });+ return this.assertParticipantResults('addParticipants', groupId, results);+ }++ async removeParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {+ return this.runStatusOnlyParticipantOp('removeParticipants', groupId, participants);+ }++ async promoteParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {+ return this.runStatusOnlyParticipantOp('promoteParticipants', groupId, participants);+ }++ async demoteParticipants(groupId: string, participants: string[]): Promise<ParticipantOperationResult[]> {+ return this.runStatusOnlyParticipantOp('demoteParticipants', groupId, participants);+ }++ /**+ * whatsapp-web.js remove/promote/demote resolve `{status: 200}` for the whole batch and reject on+ * a page-side failure (GroupChat.js:267-298,305-340,343-374) — there is no per-participant+ * breakdown to map: the page-side code even drops requested ids it can't find in the group and+ * still resolves 200, so a 200 confirms the batch, not any individual. A non-200 status is a+ * batch refusal. Within the per-participant shape the truthful report is one entry per requested+ * participant carrying the batch status, annotated so a consumer can tell it apart from an+ * individually-confirmed outcome (addParticipants); nothing per-participant exists to map.+ */+ private async runStatusOnlyParticipantOp(+ op: 'removeParticipants' | 'promoteParticipants' | 'demoteParticipants',+ groupId: string,+ participants: string[],+ ): Promise<ParticipantOperationResult[]> {+ this.host.ensureReady();+ const chat = await this.client().getChatById(groupId);+ if (!chat.isGroup) {+ throw new Error('Chat is not a group');+ }+ const participantIds = participants.map(p => (p.includes('@') ? p : `${p}@c.us`));+ const res = await (chat as unknown as GroupChat)[op](participantIds);+ if (res?.status !== 200) {+ throw new EngineRefusedError(`${op} refused for group ${groupId} (status ${res?.status ?? 'unknown'})`);+ }+ return participantIds.map(id => ({+ id,+ success: true,+ status: 200,+ message: 'confirmed with the batch — wwebjs reports no per-participant outcome',+ }));+ }++ /**+ * Shared gate for the membership writes: a result list with at least one success resolves as-is+ * (partial refusals stay visible per participant); a batch that failed for EVERY requested+ * participant is a refusal of the operation itself (HTTP 403), not a per-participant detail; and+ * an empty result is no evidence of success at all.+ */+ private assertParticipantResults(+ op: string,+ groupId: string,+ results: ParticipantOperationResult[],+ ): ParticipantOperationResult[] {+ if (results.length === 0) {+ throw new EngineRefusedError(`${op} returned no per-participant outcome for group ${groupId}`);+ }+ if (results.every(r => !r.success)) {+ const detail = results.map(r => `${r.id} (${r.status ?? '?'})`).join(', ');+ throw new EngineRefusedError(+ `${op} failed for all ${results.length} participant(s) in group ${groupId}: ${detail}`,+ );+ }+ return results;+ }++ async leaveGroup(groupId: string): Promise<void> {+ this.host.ensureReady();+ const chat = await this.client().getChatById(groupId);+ if (!chat.isGroup) {+ throw new Error('Chat is not a group');+ }+ await (chat as unknown as GroupChat).leave();+ }++ async setGroupSubject(groupId: string, subject: string): Promise<void> {+ this.host.ensureReady();+ const chat = await this.client().getChatById(groupId);+ if (!chat.isGroup) {+ throw new Error('Chat is not a group');+ }+ // GroupChat.setSubject resolves false when WA Web rejects the change (e.g. the account lacks+ // admin rights; index.d.ts:1982) instead of throwing — surface the refusal, not a false success.+ const ok = await (chat as unknown as GroupChat).setSubject(subject);+ if (!ok) {+ throw new EngineRefusedError(`Failed to set the subject for group ${groupId} — admin rights required`);+ }+ }++ async setGroupDescription(groupId: string, description: string): Promise<void> {+ this.host.ensureReady();+ const chat = await this.client().getChatById(groupId);+ if (!chat.isGroup) {+ throw new Error('Chat is not a group');+ }+ // Same discarded-boolean contract as setSubject (index.d.ts:1984).+ const ok = await (chat as unknown as GroupChat).setDescription(description);+ if (!ok) {+ throw new EngineRefusedError(`Failed to set the description for group ${groupId} — admin rights required`);+ }+ }++ async getGroupInviteCode(groupId: string): Promise<string> {+ this.host.ensureReady();+ const chat = await this.client().getChatById(groupId);+ if (!chat.isGroup) {+ throw new Error(`${groupId} is not a group`);+ }+ const inviteCode = await (chat as unknown as GroupChat).getInviteCode();+ this.host.logger.log(`Got invite code for group ${groupId}`);+ return String(inviteCode);+ }++ async revokeGroupInviteCode(groupId: string): Promise<string> {+ this.host.ensureReady();+ const chat = await this.client().getChatById(groupId);+ if (!chat.isGroup) {+ throw new Error(`${groupId} is not a group`);+ }+ const newCode = await (chat as unknown as GroupChat).revokeInvite();+ this.host.logger.log(`Revoked invite code for group ${groupId}, new code generated`);+ return String(newCode);+ }++ async joinGroupViaInviteCode(inviteCode: string): Promise<string> {+ this.host.ensureReady();+ // acceptInvite throws a page-side evaluation error when the invite is refused (invalid/expired/+ // revoked); otherwise it resolves the joined group's id (`res.gid._serialized || res.gid.$1`,+ // Client.js:1836-1845) — already the neutral `<id>@g.us` dialect. A gid-less result is the same+ // client-facing outcome as a thrown refusal: no such invite (400, not a 500).+ let groupId: string | undefined;+ try {+ groupId = await this.client().acceptInvite(inviteCode);+ } catch (error) {+ // A refused invite and a broken page both land here, and only the first is the caller's+ // fault. A transport death must not be reported as "invalid invite" (400): report the death+ // to the liveness path and answer 503 so the caller can tell the layers apart.+ if (this.host.isPageTransportError(error)) {+ this.host.reportIfPageTransportError(error, 'joinGroupViaInviteCode');+ throw new EngineTransportError('Transport died while accepting the group invite');+ }+ this.host.logger.warn(`Failed to accept group invite: ${String(error)}`);+ groupId = undefined;+ }+ if (!groupId) {+ throw new InvalidInviteCodeError();+ }+ this.host.logger.log(`Joined group ${groupId} via invite code`);+ return groupId;+ }++ /** Resolve a group chat or throw — the shared preamble of the group settings writes. */+ private async requireGroupChat(groupId: string): Promise<GroupChat> {+ this.host.ensureReady();+ const chat = await this.client().getChatById(groupId);+ // getChatById RESOLVES undefined for an unknown id (wwebjs does not throw): unknown id and a+ // non-group id are the same client-facing outcome — there is no such group (404, not a 500).+ if (!chat?.isGroup) {+ throw new GroupNotFoundError(groupId);+ }+ return chat as unknown as GroupChat;+ }++ // Set "only admins can send messages" (announce)+ async setGroupMessagesAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void> {+ const groupChat = await this.requireGroupChat(groupId);+ // Resolves false instead of throwing when the account lacks admin rights (GroupChat.js:503) —+ // surface that as an error rather than a silent no-op.+ const ok = await groupChat.setMessagesAdminsOnly(adminsOnly);+ if (!ok) {+ throw new EngineRefusedError(+ `Failed to update the messages-admins-only setting for group ${groupId} — admin rights required`,+ );+ }+ }++ // Set "only admins can edit group info" (locked/restrict)+ async setGroupInfoAdminsOnly(groupId: string, adminsOnly: boolean): Promise<void> {+ const groupChat = await this.requireGroupChat(groupId);+ const ok = await groupChat.setInfoAdminsOnly(adminsOnly);+ if (!ok) {+ throw new EngineRefusedError(+ `Failed to update the info-admins-only setting for group ${groupId} — admin rights required`,+ );+ }+ }++ // whatsapp-web.js 1.34.7 exposes no disappearing-messages setter (no Client/GroupChat symbol in+ // index.d.ts; only a create-time messageTimer option, Client.js:2371) — an honest 501, not a no-op.+ // eslint-disable-next-line @typescript-eslint/require-await, @typescript-eslint/no-unused-vars+ async setGroupEphemeral(_groupId: string, _durationSec: number): Promise<void> {+ this.host.ensureReady();+ throw new EngineNotSupportedError('setGroupEphemeral');+ }+}diff --git a/src/engine/adapters/wwebjs-host.ts b/src/engine/adapters/wwebjs-host.tsnew file mode 100644index 000000000..4398425e7--- /dev/null+++ b/src/engine/adapters/wwebjs-host.ts@@ -0,0 +1,23 @@+import { type Client, type Message } from 'whatsapp-web.js';+import { type IncomingMessage } from '../interfaces/whatsapp-engine.interface';+import { type createLogger } from '../../common/services/logger.service';+import { type WhatsAppWebJsConfig } from './whatsapp-web-js.adapter';++/**+ * Shared host surface for the delegates extracted from WhatsAppWebJsAdapter (./wwebjs-groups,+ * ./wwebjs-messaging, ./wwebjs-contacts, …). The adapter keeps the public methods as thin+ * forwarders and builds ONE object literal of these closures, handed to every delegate, so a+ * delegate never touches lifecycle state directly. `config` is exposed for the send-id resolution+ * path, which persists learned phone -> lid pairs (lidMappingStore) under this session's id.+ */+export interface WwebjsEngineHost {+ ensureReady(): void;+ getClient(): Client;+ readonly logger: ReturnType<typeof createLogger>;+ isPageTransportError(error: unknown): boolean;+ reportIfPageTransportError(error: unknown, context: string): void;+ ensureNotChannelRecipient(chatId: string): void;+ getNumberId(number: string): Promise<string | null>;+ capInboundMediaFor(msg: Message, maxBytesOverride?: number): Promise<IncomingMessage['media'] | undefined>;+ readonly config: WhatsAppWebJsConfig;+}diff --git a/src/engine/adapters/wwebjs-labels.ts b/src/engine/adapters/wwebjs-labels.tsnew file mode 100644index 000000000..dbbb8ce93--- /dev/null+++ b/src/engine/adapters/wwebjs-labels.ts@@ -0,0 +1,110 @@+import { type Client } from 'whatsapp-web.js';+import { Label } from '../interfaces/whatsapp-engine.interface';+import { GroupChat, BusinessClient } from '../types/whatsapp-web-js.types';+import { isChannelJid } from '../identity/wa-id';+import { ChatLabelsUnsupportedError } from '../../common/errors/chat-labels-unsupported.error';+import { type WwebjsEngineHost } from './wwebjs-host';++/**+ * Chat-label operations (WhatsApp Business only) extracted from WhatsAppWebJsAdapter. The adapter+ * keeps the public methods as thin forwarders and injects the shared host surface (./wwebjs-host)+ * via closures, so the delegate never touches lifecycle state directly.+ */+export class WwebjsLabels {+ constructor(private readonly host: WwebjsEngineHost) {}++ /** Post-ensureReady client handle. */+ private client(): Client {+ return this.host.getClient();+ }++ async getLabels(): Promise<Label[]> {+ this.host.ensureReady();+ const labels = await (this.client() as unknown as BusinessClient).getLabels();+ if (!labels) {+ return [];+ }++ return labels.map(label => ({+ id: String(label.id),+ name: String(label.name),+ hexColor: String(label.hexColor),+ }));+ }++ async getLabelById(labelId: string): Promise<Label | null> {+ this.host.ensureReady();+ const label = await (this.client() as unknown as BusinessClient).getLabelById(labelId);+ if (!label) {+ return null;+ }+ return {+ id: String(label.id),+ name: String(label.name),+ hexColor: String(label.hexColor),+ };+ }++ async getChatLabels(chatId: string): Promise<Label[]> {+ this.host.ensureReady();+ if (isChannelJid(chatId)) {+ // A channel resolves to a wwebjs `Channel`, which has no getLabels() and carries no chat labels.+ // Return empty instead of letting the unguarded call throw a TypeError (HTTP 500).+ return [];+ }+ const chat = await this.client().getChatById(chatId);+ const labels = await (chat as unknown as GroupChat).getLabels();+ if (!labels) {+ return [];+ }++ return labels.map(label => ({+ id: String(label.id),+ name: String(label.name),+ hexColor: String(label.hexColor),+ }));+ }++ async addLabelToChat(chatId: string, labelId: string): Promise<void> {+ this.host.ensureReady();+ await this.changeChatLabel(chatId, labelId, true);+ }++ async removeLabelFromChat(chatId: string, labelId: string): Promise<void> {+ this.host.ensureReady();+ await this.changeChatLabel(chatId, labelId, false);+ }++ /**+ * whatsapp-web.js has no add-/remove-one-label primitive: `client.addOrRemoveLabels(ids, chats)` REPLACES+ * a chat's label set with `ids` (adding the listed labels, removing any existing label not listed). So+ * toggle a single label by reading the current set, mutating it, and writing the whole set back.+ * Labels are a WhatsApp Business feature — the write throws `[LT01]` on a personal account; channels+ * carry no labels at all. Both are surfaced as a 422 rather than an opaque 500.+ *+ * The read and write are separate calls, so two concurrent single-label writes to the SAME chat can+ * lose an update (last write wins, as a full-set replace). Acceptable for low-frequency label admin;+ * serialize per (sessionId, chatId) if that ever becomes a real workload.+ */+ private async changeChatLabel(chatId: string, labelId: string, add: boolean): Promise<void> {+ if (isChannelJid(chatId)) {+ throw new ChatLabelsUnsupportedError('Channels do not support chat labels.');+ }+ const ids = new Set((await this.getChatLabels(chatId)).map(label => label.id));+ if (add) {+ ids.add(labelId);+ } else {+ ids.delete(labelId);+ }+ try {+ await this.client().addOrRemoveLabels([...ids], [chatId]);+ } catch (error) {+ // whatsapp-web.js throws `[LT01] Only Whatsapp business` from the page context on a personal account.+ if (String(error instanceof Error ? error.message : error).includes('LT01')) {+ throw new ChatLabelsUnsupportedError();+ }+ throw error;+ }+ this.host.logger.log(`${add ? 'Added' : 'Removed'} label ${labelId} ${add ? 'to' : 'from'} chat ${chatId}`);+ }+}diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.tsnew file mode 100644index 000000000..a3e7c56b8--- /dev/null+++ b/src/engine/adapters/wwebjs-messaging.ts@@ -0,0 +1,658 @@+import { MessageMedia, MessageTypes, type Client, type Message } from 'whatsapp-web.js';+import {+ IncomingMessage,+ LocationInput,+ ContactCard,+ DeliveryStatus,+ MediaInput,+ MessageReaction,+ MessageResult,+ PollInput,+} from '../interfaces/whatsapp-engine.interface';+import { MessageWithReactions, SerializedWid } from '../types/whatsapp-web-js.types';+import { MessageNotFoundError } from '../../common/errors/message-not-found.error';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';+import { chatKind, userPart } from '../identity/wa-id';+import { chatHistoryMediaBudgetBytes, coerceDeclaredSize, ingestMediaBudgetBytes } from './inbound-media-cap';+import { buildIncomingMessageBase } from './message-mapper';+import { buildVCard } from './vcard';+import { type WwebjsEngineHost } from './wwebjs-host';++/**+ * Map a whatsapp-web.js MessageAck integer to the neutral DeliveryStatus.+ * wwebjs: -1 ERROR, 0 PENDING, 1 SERVER (sent), 2 DEVICE (delivered), 3 READ, 4 PLAYED.+ * PLAYED collapses to `read` (preserving prior behaviour, which treated ack>=3 as read).+ */+export function wwebjsAckToDeliveryStatus(ack: number): DeliveryStatus {+ if (ack < 0) return 'failed';+ if (ack >= 3) return 'read';+ if (ack === 2) return 'delivered';+ if (ack === 1) return 'sent';+ return 'pending';+}++/**+ * Extract call detail from a whatsapp-web.js `call_log` message, or `undefined` for any other type.+ * The public Message wrapper doesn't expose call fields, so we read them off the raw `_data`. An+ * incoming call (`!fromMe`) with no recorded `callDuration` was never answered → missed; an outgoing+ * call is never "missed". Used by getChatHistory, where `call_log` entries actually appear.+ */+export function extractWwebjsCall(msg: Message): { video: boolean; missed: boolean } | undefined {+ if ((msg.type as string) !== 'call_log') return undefined;+ const d = (msg as unknown as { _data?: { isVideoCall?: boolean; callDuration?: number } })._data ?? {};+ return { video: Boolean(d.isVideoCall), missed: !msg.fromMe && !d.callDuration };+}++/**+ * The `media` envelope for a message whose blob is not downloaded: keeps the sender-declared metadata+ * so the `media` field stays present (n8n/dashboard contract) while carrying the `omitted` marker+ * instead of base64. Used when downloads are disabled, the size pre-gate trips, the aggregate history+ * budget is spent, or the download fails/times out.+ */+export function declaredOnlyMedia(msg: Message): IncomingMessage['media'] {+ const data = (msg as unknown as { _data?: { size?: number; mimetype?: string; filename?: string } })._data;+ return {+ mimetype: data?.mimetype ?? '',+ filename: data?.filename || undefined,+ omitted: true,+ sizeBytes: coerceDeclaredSize(data?.size),+ };+}++/**+ * Whether a MediaInput's string `data` is an http(s) URL (to be fetched through the SSRF-guarded+ * loadRemoteMedia) rather than base64. Case-insensitive, matching the Baileys adapter — a mixed-case+ * scheme like `HTTPS://` must still route through the guarded fetch, not be treated as base64.+ */+export function isHttpUrl(value: string): boolean {+ return /^https?:\/\//i.test(value);+}++/**+ * Fetch remote media for sending, with an SSRF host guard, a byte cap, and a timeout.+ * The guard runs BEFORE any network call, so an internal/reserved URL throws `SsrfBlockedError`+ * and no outbound socket is opened. The byte cap (node-fetch `size`) and `AbortSignal` timeout+ * bound memory use and hang time. `unsafeMime` is left at its default (false) to preserve the+ * existing MIME-detection behavior.+ */+export async function loadRemoteMedia(url: string): Promise<MessageMedia> {+ // Fetch through the SSRF-pinned path: it validates the host, pins the connection to the vetted IP+ // (so a DNS rebind can't redirect it to an internal target between check and connect), caps bytes,+ // and refuses redirects. We then build the MessageMedia from the returned bytes — NOT via+ // MessageMedia.fromUrl, whose bundled node-fetch performs its own unpinned DNS re-resolution.+ const { data, mimetype } = await loadRemoteMediaBuffer(url);+ const filename = new URL(url).pathname.split('/').pop() || undefined;+ return new MessageMedia(mimetype || 'application/octet-stream', data.toString('base64'), filename);+}++/**+ * True when a send error is whatsapp-web.js's "recipient needs a LID we don't have" failure, raised+ * when sending to a `@c.us` for a contact WhatsApp has migrated to `@lid`.+ * ponytail: matched on the wwjs error text — there is no structured code; revisit if wwjs changes it.+ */+export function isNoLidForUserError(err: unknown): boolean {+ return err instanceof Error && err.message.includes('No LID for user');+}++/**+ * Build a MessageMedia from a MediaInput (URL → fetched, base64/Buffer → wrapped).+ *+ * `trustDeclaredType: false` keeps the fetched response's content-type for a remote URL. Use it+ * wherever the mimetype is an INSTRUCTION rather than a label: whatsapp-web.js decides how to+ * convert a sticker from it, and `Util.formatImageToWebpSticker` returns the media untouched when it+ * already says webp. A caller that declares `image/webp` over bytes that are not webp would then+ * have raw bytes shipped as a sticker. The response describes bytes the caller never saw, so for+ * that one decision it is the better source. The declared filename still wins either way — that is+ * a label, and nothing branches on it.+ */+export async function toMessageMedia(media: MediaInput, opts?: { trustDeclaredType?: boolean }): Promise<MessageMedia> {+ if (typeof media.data === 'string' && isHttpUrl(media.data)) {+ const fetched = await loadRemoteMedia(media.data);+ // `loadRemoteMedia` derives both fields from the response (content-type, URL basename) because+ // that is all it has. The caller usually knows better, so let an explicit `mimetype`/`filename`+ // win — matching `resolveMediaBuffer` on the Baileys adapter, which already prefers the caller's.+ // `application/octet-stream` is the DTO's own placeholder, not a statement about the bytes.+ if (opts?.trustDeclaredType !== false && media.mimetype && media.mimetype !== 'application/octet-stream') {+ fetched.mimetype = media.mimetype;+ }+ // Sticker path (trustDeclaredType:false): a specific fetched image/video MIME stays authoritative,+ // but a generic/empty fetched MIME carries no information, and the caller's declared+ // image/* or video/* would otherwise be discarded — whatsapp-web.js then rejects the format+ // before running the sticker conversion. Fall back ONLY in that one shape: remote URL ++ // trustDeclaredType:false + generic fetched type + convertible declared type. Canonicalize the+ // value handed downstream (lowercased, params stripped) so a mixed-case declared type is+ // normalized exactly once. A declared image/webp IS accepted here when the fetched response+ // carries no usable MIME — the caller is asserting what the bytes actually are, so trusting it+ // only in the generic-fetched shape can't bypass the sticker conversion the way globally+ // trusting a declared WebP over a specific fetched type would. Arbitrary application/* is+ // rejected (e.g. the DTO's own octet-stream placeholder, or application/pdf).+ const normalizeMediaType = (value?: string): string => (value ?? '').split(';', 1)[0].trim().toLowerCase();+ const fetchedType = normalizeMediaType(fetched.mimetype);+ const declaredType = normalizeMediaType(media.mimetype);+ const fetchedTypeIsGeneric = !fetchedType || fetchedType === 'application/octet-stream';+ const declaredTypeIsConvertible = declaredType.startsWith('image/') || declaredType.startsWith('video/');+ if (opts?.trustDeclaredType === false && fetchedTypeIsGeneric && declaredTypeIsConvertible) {+ fetched.mimetype = declaredType;+ }+ if (media.filename) {+ fetched.filename = media.filename;+ }+ return fetched;+ }+ const data = typeof media.data === 'string' ? media.data : media.data.toString('base64');+ return new MessageMedia(media.mimetype, data, media.filename);+}++/**+ * Build the `MessageResult` for a send from whatever whatsapp-web.js hands back.+ *+ * `client.sendMessage()` can RESOLVE with `undefined` instead of throwing, and it collapses two+ * opposite outcomes into that one value (`Client.js:1558`): the chat could not be resolved so nothing+ * was sent (`if (!chat) return null`, `Client.js:1539`), or the message went out and only its id could+ * not be read back (`Msg.get` miss, `Injected/Utils.js:585`). Nothing here can tell those apart, so an+ * absent message is reported as a failed send: a false negative is visible and retryable, while+ * claiming delivery for a message that never left is not recoverable. wwebjs's own typings hide the+ * case entirely — `index.d.ts` declares `Promise<Message>`, so `strict` never flagged these reads.+ *+ * A `Message` instance is different: wwebjs only builds one from a real message model, so its presence+ * proves the send happened. An id it cannot read there means "sent, id unknown" and carries the empty+ * sentinel `forwardMessage` already returns — which `saveOutgoingMessage` stores as NULL rather than a+ * fabricated id that a later ack could mis-match.+ */+export function toMessageResult(msg: Message | undefined): MessageResult {+ if (!msg) {+ throw new Error(+ 'the engine returned no message for this send, so it may not have been delivered — check the chat before retrying',+ );+ }+ const id = msg.id as unknown as SerializedWid | undefined;+ return { id: id?._serialized ?? id?.$1 ?? '', timestamp: msg.timestamp };+}++/**+ * Messaging operations extracted from WhatsAppWebJsAdapter: the send paths (with the @c.us -> @lid+ * resolution cache), reactions, history, delete and edit. The adapter keeps the public methods as+ * thin forwarders and injects the shared host surface (./wwebjs-host) via closures, so the delegate+ * never touches lifecycle state directly.+ */+export class WwebjsMessaging {+ constructor(private readonly host: WwebjsEngineHost) {}++ /** Post-ensureReady client handle. */+ private client(): Client {+ return this.host.getClient();+ }++ // Cache of resolved individual recipients: `<phone>@c.us` -> the id `sendMessage` accepts (a+ // `<lid>@lid` for a migrated contact, or the confirmed `@c.us` for a non-migrated one). `getNumberId`+ // is a rate-limited WhatsApp Web existence probe that also throws intermittently, so caching every+ // confirmed resolution keeps ordinary sends from re-probing on each message (#580). A `@lid` is+ // stable; a stale entry (a contact that migrates mid-session) self-heals via the retry in+ // `sendResolved`.+ // ponytail: unbounded Map, bounded in practice by distinct recipients per session; add an LRU only+ // if a session ever addresses a truly unbounded set of fresh numbers.+ private readonly resolvedSendIds = new Map<string, string>();++ /**+ * Resolve an individual (`@c.us`) recipient to the id whatsapp-web.js will accept. WhatsApp has+ * migrated some contacts to privacy-id addressing, for which `sendMessage` throws `No LID for user`+ * on the phone WID but accepts the `@lid` that `getNumberId` returns (#573). Any server-confirmed+ * resolution (a distinct `@lid` OR a confirmed non-migrated `@c.us`) is cached, since it is stable+ * and re-probing costs a rate-limited round-trip (#580); a `null`/thrown lookup is NOT cached so an+ * unregistered or transiently-flaky contact keeps being retried. Groups/channels and already-`@lid`+ * targets are returned unchanged, and any resolution failure falls back to the original id so a send+ * is never blocked on it.+ */+ async resolveSendId(chatId: string): Promise<string> {+ if (!chatId.endsWith('@c.us')) {+ return chatId;+ }+ const cached = this.resolvedSendIds.get(chatId);+ if (cached) {+ return cached;+ }+ try {+ const wid = await this.host.getNumberId(chatId);+ if (wid) {+ this.resolvedSendIds.set(chatId, wid);+ if (wid.endsWith('@lid')) {+ // Persist the learned phone -> lid so the message read-path (resolveJidCandidates) can+ // bridge this contact's `@c.us` and `@lid` rows on a pure whatsapp-web.js deployment+ // (#583 R3). Fire-and-forget: resolution (and the send) must never block/fail on the write.+ void this.host.config.lidMappingStore+ ?.remember(userPart(wid), userPart(chatId), this.host.config.sessionId)+ ?.catch(() => {});+ }+ return wid;+ }+ return chatId;+ } catch {+ return chatId;+ }+ }++ /**+ * Resolve `chatId` and run `send` against the resolved id. If the send fails with `No LID for user`+ * — the signature of a contact whose cached/resolved id is stale (typically a `@c.us` for a contact+ * that has since migrated to `@lid`) — drop the mapping, re-resolve once, and retry only if the+ * fresh id differs, so a genuinely unreachable recipient surfaces its error instead of looping.+ */+ private async sendResolved<T>(chatId: string, send: (to: string) => Promise<T>): Promise<T> {+ const to = await this.resolveSendId(chatId);+ try {+ return await send(to);+ } catch (err) {+ // A transport-level failure means the page/browser is gone — report it as a death signal.+ // No-op for ordinary send errors; the retry/throw behavior below is unchanged.+ this.host.reportIfPageTransportError(err, 'sendMessage');+ if (!chatId.endsWith('@c.us') || !isNoLidForUserError(err)) {+ throw err;+ }+ this.resolvedSendIds.delete(chatId);+ const fresh = await this.resolveSendId(chatId);+ if (fresh === to) {+ throw err;+ }+ // The first send threw, but wwjs can throw after the message is already on the wire — so this+ // retry may produce a duplicate. Log it: without this the second copy is invisible.+ this.host.logger.warn('Send retried against a re-resolved id after "No LID for user"; may duplicate', {+ chatId,+ staleId: to,+ freshId: fresh,+ });+ return send(fresh);+ }+ }++ async sendTextMessage(chatId: string, text: string, mentions?: string[]): Promise<MessageResult> {+ this.host.ensureReady();+ // wwebjs accepts neutral `<phone>@c.us` WIDs directly as mentionedJidList, so no de-normalization+ // is needed. Omit the options object entirely when none are given to keep today's send behavior.+ const msg = await this.sendResolved(chatId, to =>+ mentions?.length ? this.client().sendMessage(to, text, { mentions }) : this.client().sendMessage(to, text),+ );+ return toMessageResult(msg);+ }++ async sendImageMessage(chatId: string, media: MediaInput): Promise<MessageResult> {+ return this.sendMediaMessage(chatId, media);+ }++ async sendVideoMessage(chatId: string, media: MediaInput): Promise<MessageResult> {+ return this.sendMediaMessage(chatId, media);+ }++ async sendAudioMessage(chatId: string, media: MediaInput): Promise<MessageResult> {+ return this.sendMediaMessage(chatId, media, media.ptt ? { sendAudioAsVoice: true } : undefined);+ }++ /**+ * Without `sendMediaAsDocument` whatsapp-web.js lets WA Web classify the attachment from its declared+ * mimetype (`Injected/Utils.js` `processMediaData` -> `prepRawMedia`), so an `image/*`, `video/*` or+ * `audio/*` payload posted here reached the recipient as a photo/video/audio bubble — re-encoded and+ * stripped of its filename — instead of a document (#989). Baileys has always forced it via the+ * explicit `document:` content key, so the two engines disagreed on the same request.+ *+ * The flag is withheld for `status@broadcast` and broadcast lists: whatsapp-web.js refuses every+ * `@broadcast` recipient outright once it is set (`Client.js` returns `null`, which `toMessageResult`+ * surfaces as a failed send), so setting it there would turn a working send into an error rather than+ * improve it. Those recipients keep the classification they have today.+ */+ async sendDocumentMessage(chatId: string, media: MediaInput): Promise<MessageResult> {+ const kind = chatKind(chatId);+ const asDocument = kind !== 'status' && kind !== 'broadcast';+ return this.sendMediaMessage(chatId, media, asDocument ? { sendMediaAsDocument: true } : undefined);+ }++ private async sendMediaMessage(+ chatId: string,+ media: MediaInput,+ extraOptions?: { sendAudioAsVoice?: boolean; sendMediaAsDocument?: boolean },+ ): Promise<MessageResult> {+ this.host.ensureReady();+ this.host.ensureNotChannelRecipient(chatId);++ // Build the media once (a remote URL is fetched here); sendResolved may retry the send itself.+ const messageMedia = await toMessageMedia(media);+ // A nameless document reaches WA Web as `new File([blob], undefined)` and is labelled literally+ // "undefined". Only documents render a filename, so default just this path — as Baileys does.+ if (extraOptions?.sendMediaAsDocument && !messageMedia.filename) {+ messageMedia.filename = 'file';+ }+ const msg = await this.sendResolved(chatId, to =>+ this.client().sendMessage(to, messageMedia, {+ caption: media.caption,+ ...(media.mentions?.length ? { mentions: media.mentions } : {}),+ // sendAudioAsVoice only for audio, sendMediaAsDocument only for documents;+ // {...undefined} contributes no keys.+ ...extraOptions,+ }),+ );++ return toMessageResult(msg);+ }++ async sendLocationMessage(chatId: string, location: LocationInput): Promise<MessageResult> {+ this.host.ensureReady();+ // Import Location class dynamically from whatsapp-web.js+ const module = await import('whatsapp-web.js');+ const Location = module.Location || module.default?.Location;++ const loc = new Location(location.latitude, location.longitude, {+ name: location.description || '',+ address: location.address || '',+ });+ const msg = await this.sendResolved(chatId, to => this.client().sendMessage(to, loc));+ return toMessageResult(msg);+ }++ async sendContactMessage(chatId: string, contact: ContactCard): Promise<MessageResult> {+ this.host.ensureReady();+ // Shared builder sanitizes name/number (strips CR/LF, digits-only waid) so a crafted contact+ // can't inject extra vCard fields — the previous inline build interpolated raw values.+ const vcard = buildVCard(contact);++ const msg = await this.sendResolved(chatId, to =>+ this.client().sendMessage(to, vcard, {+ parseVCards: true,+ }),+ );+ return toMessageResult(msg);+ }++ async sendStickerMessage(chatId: string, media: MediaInput): Promise<MessageResult> {+ this.host.ensureReady();+ // Sticker has its own send path (sendMediaAsSticker), not the sendMediaMessage funnel, but it+ // hits the same channel crash: for a channel wwjs drops the sticker form and runs processMediaData+ // with sendToChannel, which still ends at msg.avParams() (Utils.js:518). Guard it too (#673).+ this.host.ensureNotChannelRecipient(chatId);+ // Keep the fetched content-type for a remote URL: here the mimetype selects the conversion, and+ // whatsapp-web.js returns the media unconverted once it reads as webp (Util.formatImageToWebpSticker).+ const messageMedia = await toMessageMedia(media, { trustDeclaredType: false });++ const msg = await this.sendResolved(chatId, to =>+ this.client().sendMessage(to, messageMedia, {+ sendMediaAsSticker: true,+ }),+ );+ return toMessageResult(msg);+ }++ async sendPollMessage(chatId: string, poll: PollInput): Promise<MessageResult> {+ this.host.ensureReady();+ // Import Poll dynamically like Location; the .default fallback covers builds where the+ // classes land on module.default (a plain `module.Poll` would be undefined there and+ // `new Poll` fails with "not a constructor").+ const module = await import('whatsapp-web.js');+ const Poll = module.Poll || module.default?.Poll;++ // wwebjs's typings mark `messageSecret` as required, but at runtime it is optional (it is+ // only used as a custom poll id), so cast to the constructor's options type to pass just+ // allowMultipleAnswers.+ type PollSendOptions = ConstructorParameters<typeof Poll>[2];+ const pollOptions = { allowMultipleAnswers: poll.allowMultipleAnswers === true } as PollSendOptions;+ const msg = await this.sendResolved(chatId, to =>+ this.client().sendMessage(to, new Poll(poll.name, poll.options, pollOptions)),+ );+ return toMessageResult(msg);+ }++ async replyToMessage(chatId: string, quotedMsgId: string, text: string): Promise<MessageResult> {+ this.host.ensureReady();+ try {+ // Find the message to quote+ const chat = await this.client().getChatById(chatId);+ const messages = await chat.fetchMessages({ limit: 100 });+ const quotedMsg = messages.find(m => m.id._serialized === quotedMsgId);++ if (!quotedMsg) {+ throw new MessageNotFoundError(quotedMsgId);+ }++ // Reply's send leg hits the same `No LID for user` path as a normal send for a migrated contact,+ // so route it through sendResolved (resolve @c.us->@lid, cache, self-heal). reply(content, chatId)+ // accepts an explicit target (#583 R1).+ const msg = await this.sendResolved(chatId, to => quotedMsg.reply(text, to));+ return toMessageResult(msg);+ } catch (error) {+ this.host.reportIfPageTransportError(error, 'replyToMessage');+ throw error;+ }+ }++ async forwardMessage(fromChatId: string, toChatId: string, messageId: string): Promise<MessageResult> {+ this.host.ensureReady();+ try {+ const chat = await this.client().getChatById(fromChatId);+ const messages = await chat.fetchMessages({ limit: 100 });+ const msgToForward = messages.find(m => m.id._serialized === messageId);++ if (!msgToForward) {+ throw new MessageNotFoundError(messageId);+ }++ // The forward's send leg fails with `No LID for user` for a LID-migrated destination, so resolve+ // it (and self-heal a stale mapping) via sendResolved. Capture the id actually sent to so the+ // id-recovery below reads back from the SAME (resolved) chat, not the raw @c.us (#583 R1).+ let resolvedTo = toChatId;+ await this.sendResolved(toChatId, to => {+ resolvedTo = to;+ return msgToForward.forward(to);+ });++ // whatsapp-web.js's forward() returns void, so BEST-EFFORT recover the REAL id of the sent copy by+ // reading it back from the destination chat (the most recent outgoing message). The delivery-ack+ // matcher keys on this id, so a synthetic one would leave the forward stuck at SENT; Baileys already+ // returns the real id. The forward already succeeded here, so recovery must NEVER fail the operation.+ // When the copy can't be identified we return an explicit-unknown id (empty): message.service then+ // leaves the row's waMessageId unset so no ack can mis-match it — unlike a synthetic or source id,+ // which could cross-drive another row's delivery status. Concurrent forwards to the same chat may+ // mis-identify the copy — acceptable for delivery-status accuracy.+ try {+ const destChat = await this.client().getChatById(resolvedTo);+ const sentByMe = (await destChat?.fetchMessages({ limit: 5, fromMe: true })) ?? [];+ let sent: (typeof sentByMe)[number] | undefined;+ for (const m of sentByMe) {+ if (!sent || m.timestamp > sent.timestamp) {+ sent = m;+ }+ }+ if (sent) {+ return toMessageResult(sent);+ }+ } catch (error) {+ // Still surface a dead page even though the send itself succeeded (detection only; the+ // forward's best-effort recovery contract is unchanged).+ this.host.reportIfPageTransportError(error, 'forwardMessage');+ this.host.logger.warn(`Forward succeeded but recovering the sent message id failed: ${String(error)}`);+ }+ return { id: '', timestamp: Math.floor(Date.now() / 1000) };+ } catch (error) {+ this.host.reportIfPageTransportError(error, 'forwardMessage');+ throw error;+ }+ }++ async reactToMessage(chatId: string, messageId: string, emoji: string): Promise<void> {+ this.host.ensureReady();+ try {+ // NOTE: do NOT resolve chatId to @lid here — whatsapp-web.js reacts using the found message's own+ // id, not this chatId, so LID-resolving the lookup gives no send benefit and would miss a message+ // stored under the pre-migration @c.us chat (#583 R1 review).+ const chat = await this.client().getChatById(chatId);+ const messages = await chat.fetchMessages({ limit: 100 });+ const message = messages.find(m => m.id._serialized === messageId);+ if (!message) {+ throw new MessageNotFoundError(messageId, chatId);+ }+ await (message as MessageWithReactions).react(emoji);+ this.host.logger.log(`Reacted to message ${messageId} with ${emoji || '(removed)'}`);+ } catch (error) {+ this.host.reportIfPageTransportError(error, 'reactToMessage');+ throw error;+ }+ }++ async getMessageReactions(chatId: string, messageId: string): Promise<MessageReaction[]> {+ this.host.ensureReady();+ const chat = await this.client().getChatById(chatId);+ const messages = await chat.fetchMessages({ limit: 100 });+ const message = messages.find(m => m.id._serialized === messageId);+ if (!message) {+ throw new MessageNotFoundError(messageId, chatId);+ }+ const msgWithReactions = message as MessageWithReactions;+ if (!msgWithReactions.hasReaction) {+ return [];+ }+ const reactions = await msgWithReactions.getReactions();+ if (!reactions) {+ return [];+ }+ // Map reactions to our interface format+ const result: MessageReaction[] = [];++ for (const r of reactions) {+ result.push({+ emoji: String(r.id),+ senders: (r.senders || []).map(s => ({+ senderId: String(s.senderId),+ emoji: String(s.reaction),+ timestamp: Number(s.timestamp),+ })),+ });+ }+ return result;+ }++ async getChatHistory(+ chatId: string,+ limit: number = 50,+ includeMedia: boolean = false,+ mediaMaxBytes?: number,+ signal?: AbortSignal,+ ): Promise<IncomingMessage[]> {+ this.host.ensureReady();+ const chat = await this.client().getChatById(chatId);+ const messages = await chat.fetchMessages({ limit });+ const results: IncomingMessage[] = [];+ // Aggregate base64 budget across the whole pass: the per-message cap bounds ONE blob, but without+ // an aggregate bound a 100-message history could stack ~100 × 50 MiB into one response. Once the+ // running total crosses the budget, later media messages get the declared-only `omitted` marker —+ // no download — while everything already inlined stays inline (a small history is byte-identical+ // to before). `signal` (client disconnect) stops the loop between messages; partials are returned.+ // The 25 MiB default is sized for ONE HTTP response and is too tight for a caller that ingests+ // into a store instead (mediaMaxBytes — the status seed): two ~10 MiB videos are ~28 MiB of+ // base64 and would strip every later status. Such a caller gets a budget derived from its own+ // per-item cap rather than an exemption — unbounded here would mean a 50-item seed could stack+ // ~650 MiB of base64 on the heap at connect time.+ let mediaBudget = !includeMedia+ ? Number.POSITIVE_INFINITY+ : mediaMaxBytes === undefined+ ? chatHistoryMediaBudgetBytes()+ : ingestMediaBudgetBytes(mediaMaxBytes);+ for (const msg of messages) {+ if (signal?.aborted) {+ break;+ }+ // Reuse the shared mapper so history messages carry the same author/contact+ // enrichment as live incoming messages (#223). The mapper defaults chatId to+ // msg.from, which is wrong here (history includes fromMe messages whose `from`+ // is our own number), so override it to the requested chat and recompute the+ // chatId-derived flags (isGroup, isStatusBroadcast, kind) from the real chat.+ const out = buildIncomingMessageBase(msg);+ out.chatId = chatId;+ out.isGroup = chatId.endsWith('@g.us');+ out.isStatusBroadcast = chatId === 'status@broadcast';+ out.kind = chatKind(chatId);+ const call = extractWwebjsCall(msg);+ if (call) out.call = call;+ // Mirror the live handler's location + quoted-message enrichment so history renders identically —+ // buildIncomingMessageBase sets type='location' but no coordinates, and never resolves quotes.+ if (msg.type === MessageTypes.LOCATION && msg.location) {+ out.location = {+ latitude: Number(msg.location.latitude),+ longitude: Number(msg.location.longitude),+ description: msg.location.description || undefined,+ address: msg.location.address || undefined,+ url: msg.location.url || undefined,+ };+ }+ if (msg.hasQuotedMsg) {+ try {+ const quoted = await msg.getQuotedMessage();+ out.quotedMessage = { id: quoted.id._serialized, body: quoted.body };+ } catch (error) {+ this.host.logger.warn(`Failed to resolve quoted message for ${msg.id._serialized}: ${String(error)}`);+ }+ }+ if (includeMedia && msg.hasMedia) {+ if (mediaBudget <= 0) {+ out.media = declaredOnlyMedia(msg);+ } else {+ try {+ // Same pre-gate + limiter as live media: a large historical blob shouldn't bloat the+ // response/heap. Callers (the status seed) can tighten the cap below the global default.+ const capped = await this.host.capInboundMediaFor(msg, mediaMaxBytes);+ if (capped) {+ out.media = capped;+ // Only an inlined payload spends budget; an omitted marker carries no base64.+ if (capped.data) {+ mediaBudget -= capped.data.length;+ }+ }+ } catch (error) {+ this.host.logger.warn(`Failed to download media for ${msg.id._serialized}: ${String(error)}`);+ }+ }+ }+ results.push(out);+ }+ return results;+ }++ async deleteMessage(chatId: string, messageId: string, forEveryone: boolean = true): Promise<void> {+ this.host.ensureReady();+ // NOTE: do NOT resolve chatId to @lid here — delete operates on the found message's own key, not+ // this chatId, so LID-resolving the lookup gives no benefit and would miss a message stored under+ // the pre-migration @c.us chat (#583 R1 review).+ const chat = await this.client().getChatById(chatId);+ const messages = await chat.fetchMessages({ limit: 100 });+ const message = messages.find(m => m.id._serialized === messageId || m.id.id === messageId);+ if (!message) {+ throw new MessageNotFoundError(messageId, chatId);+ }+ await message.delete(forEveryone);+ this.host.logger.log(`Deleted message ${messageId} from chat ${chatId} (forEveryone: ${forEveryone})`);+ }++ async editMessage(chatId: string, messageId: string, body: string): Promise<MessageResult> {+ this.host.ensureReady();+ // Same lookup window as react/delete: fetchMessages sees only the 100 most recent messages.+ // NOTE: do NOT resolve chatId to @lid here — edit operates on the found message's own key, not+ // this chatId, so LID-resolving the lookup would miss a message stored under the pre-migration+ // @c.us chat (#583 R1 review).+ const chat = await this.client().getChatById(chatId);+ // getChatById RESOLVES undefined for an unknown chat (wwebjs does not throw) — that is the same+ // client-facing outcome as a message outside the fetch window, not a TypeError (-> 500).+ if (!chat) {+ throw new MessageNotFoundError(messageId, chatId);+ }+ const messages = await chat.fetchMessages({ limit: 100 });+ const message = messages.find(m => m.id._serialized === messageId || m.id.id === messageId);+ if (!message) {+ throw new MessageNotFoundError(messageId, chatId);+ }+ const edited = await message.edit(body);+ if (!edited) {+ // wwebjs RESOLVES null (instead of throwing) when the page-side edit is refused — only the+ // account's own text messages are editable; surface the refusal, not a phantom success.+ throw new EngineRefusedError(+ `the edit of message ${messageId} was rejected — only the account's own text messages can be edited`,+ );+ }+ this.host.logger.log(`Edited message ${messageId} in chat ${chatId}`);+ return toMessageResult(edited);+ }+}diff --git a/src/engine/adapters/wwebjs-onboarding.ts b/src/engine/adapters/wwebjs-onboarding.tsnew file mode 100644index 000000000..d47486550--- /dev/null+++ b/src/engine/adapters/wwebjs-onboarding.ts@@ -0,0 +1,77 @@+/** The modal's confirm-button label on an English WhatsApp Web. */+export const ONBOARDING_DEFAULT_CONTINUE_LABEL = 'Continue';++/**+ * Extra confirm-button labels for a deployment whose WhatsApp Web does not render this modal in+ * English, comma-separated (`WWEBJS_ONBOARDING_CONTINUE_LABELS=Continuar,Weiter`).+ *+ * Needed because the match is on visible text and WhatsApp controls those strings — we are not going+ * to carry its translation table. Read per probe, not cached, so an operator can correct a running+ * deployment through the infra config without a restart.+ *+ * Supplying labels also drops the heading requirement for THOSE labels: the English heading regex+ * would reject a localised modal anyway, so requiring both would make the setting useless. That is a+ * deliberate, operator-opted-in loosening — see {@link probeOnboardingModal}.+ */+export function resolveOnboardingContinueLabels(): string[] {+ const extra = (process.env.WWEBJS_ONBOARDING_CONTINUE_LABELS ?? '')+ .split(',')+ .map(label => label.trim())+ .filter(Boolean);+ return [ONBOARDING_DEFAULT_CONTINUE_LABEL, ...extra];+}++/**+ * In-page probe for the onboarding modal: click its confirm button if it is on screen.+ *+ * Exported and self-contained on purpose. `page.evaluate` stringifies this into the browser, so it+ * may not close over anything in this module — every input arrives as an argument — and being a plain+ * function means the DOM matching can be unit-tested directly, rather than only through a mocked+ * `evaluate` that proves nothing about the matching itself.+ *+ * The BUTTON is the presence signal, never the heading text on its own. `textContent` on a `div`+ * concatenates every descendant, so a chat-list row previewing the words "what's new" — an ordinary+ * English message — satisfies a heading-only test. Treating that as a stuck modal would take a+ * perfectly healthy session out of READY and block every send. A visible control whose exact label is+ * the confirm label, sitting within a few levels of an element that also carries the heading, is a+ * shape the chat list does not produce. The ancestor walk is bounded for the same reason: matching+ * against `<body>` would just be the loose text test again.+ *+ * LANGUAGE. The default label and the heading are English, and the modal is rendered in whatever+ * language WhatsApp Web decides. Two things address that, both defaulting to today's behaviour:+ * the launch args pin `--lang` so the page has a deterministic locale, and an operator can add+ * their own labels (see {@link resolveOnboardingContinueLabels}). An operator-supplied label matches+ * WITHOUT the heading check — the English heading would reject a localised modal regardless, so+ * requiring both would make the setting inert. The default `Continue` keeps the heading requirement,+ * so the out-of-the-box false-positive surface is unchanged.+ */+export function probeOnboardingModal(options?: { labels?: string[]; headingOptionalFor?: string[] }): {+ modalPresent: boolean;+ dismissed: boolean;+} {+ const isVisible = (el: Element): boolean => {+ const rect = (el as HTMLElement).getBoundingClientRect();+ return rect.width > 0 && rect.height > 0 && (el as HTMLElement).offsetParent !== null;+ };+ const labels = options?.labels?.length ? options.labels : ['Continue'];+ const headingOptional = new Set(options?.headingOptionalFor ?? []);+ // Both apostrophes: WhatsApp Web renders the typographic U+2019, and an ASCII quote appears in+ // older builds. Matching only the ASCII form means never recognising the real modal.+ const heading = /what[’']?s new/i;+ const candidates = Array.from(document.querySelectorAll('button, [role="button"]'))+ .map(el => ({ el, label: (el.textContent || '').trim() }))+ .filter(c => isVisible(c.el) && labels.includes(c.label));+ for (const { el, label } of candidates.reverse()) {+ if (headingOptional.has(label)) {+ (el as HTMLElement).click();+ return { modalPresent: true, dismissed: true };+ }+ let scope: Element | null = el;+ for (let depth = 0; depth < 8 && scope; depth++, scope = scope.parentElement) {+ if (!heading.test(scope.textContent || '')) continue;+ (el as HTMLElement).click();+ return { modalPresent: true, dismissed: true };+ }+ }+ return { modalPresent: false, dismissed: false };+}diff --git a/src/engine/adapters/wwebjs-profile.ts b/src/engine/adapters/wwebjs-profile.tsnew file mode 100644index 000000000..f4465b9d0--- /dev/null+++ b/src/engine/adapters/wwebjs-profile.ts@@ -0,0 +1,46 @@+import { type Client } from 'whatsapp-web.js';+import { MediaInput } from '../interfaces/whatsapp-engine.interface';+import { EngineRefusedError } from '../../common/errors/engine-refused.error';+import { toMessageMedia } from './wwebjs-messaging';+import { type WwebjsEngineHost } from './wwebjs-host';++/**+ * Own-account profile operations extracted from WhatsAppWebJsAdapter. The adapter keeps the public+ * methods as thin forwarders and injects the shared host surface (./wwebjs-host) via closures, so+ * the delegate never touches lifecycle state directly.+ */+export class WwebjsProfile {+ constructor(private readonly host: WwebjsEngineHost) {}++ /** Post-ensureReady client handle. */+ private client(): Client {+ return this.host.getClient();+ }++ async setProfileName(name: string): Promise<void> {+ this.host.ensureReady();+ // setDisplayName resolves false (rather than throwing) when WhatsApp refuses the rename.+ const ok = await this.client().setDisplayName(name);+ if (!ok) {+ throw new EngineRefusedError('the engine rejected the profile name change');+ }+ this.host.logger.log('Updated profile name');+ }++ async setProfileStatus(status: string): Promise<void> {+ this.host.ensureReady();+ await this.client().setStatus(status);+ this.host.logger.log('Updated profile status');+ }++ async setProfilePicture(media: MediaInput): Promise<void> {+ this.host.ensureReady();+ const messageMedia = await toMessageMedia(media);+ // setProfilePicture resolves false (rather than throwing) when the upload is refused.+ const ok = await this.client().setProfilePicture(messageMedia);+ if (!ok) {+ throw new EngineRefusedError('the engine rejected the profile picture change');+ }+ this.host.logger.log('Updated profile picture');+ }+}diff --git a/src/engine/adapters/wwebjs-proxy.ts b/src/engine/adapters/wwebjs-proxy.tsnew file mode 100644index 000000000..5175bdf88--- /dev/null+++ b/src/engine/adapters/wwebjs-proxy.ts@@ -0,0 +1,42 @@+/**+ * Whether a per-session proxy URL parses to a supported scheme — defense-in-depth for a stored proxy+ * that bypassed DTO validation (e.g. loaded from the DB on restart). The host is NOT SSRF-blocked: a+ * per-session proxy is operator-chosen egress, and a loopback proxy sidecar is a legitimate setup.+ */+export function isSupportedProxyUrl(url: string): boolean {+ try {+ return ['http:', 'https:', 'socks4:', 'socks5:'].includes(new URL(url).protocol);+ } catch {+ return false;+ }+}++export interface ProxyLaunchConfig {+ /** Credential-less `--proxy-server` value — Chromium ignores credentials embedded in this flag. */+ serverArg: string;+ /** Username/password for whatsapp-web.js's `proxyAuthentication` (→ `page.authenticate`, HTTP/HTTPS only). */+ proxyAuthentication?: { username: string; password: string };+ /** The URL carries credentials for a SOCKS proxy, which Chromium cannot authenticate at all. */+ socksAuthUnsupported: boolean;+}++/**+ * Split a proxy URL into a credential-less `--proxy-server` value plus, for an HTTP/HTTPS proxy, the+ * username/password to hand to whatsapp-web.js's `proxyAuthentication` (which calls `page.authenticate`+ * — the only way Chromium authenticates a proxy). Credentials embedded in `--proxy-server` are ignored+ * by Chromium, and SOCKS proxies cannot be authenticated at all, so SOCKS credentials are surfaced via+ * `socksAuthUnsupported` for the caller to warn about instead of failing with an opaque nav timeout (#628).+ * Call only with a URL that already passed {@link isSupportedProxyUrl}.+ */+export function buildProxyLaunchConfig(url: string): ProxyLaunchConfig {+ const parsed = new URL(url);+ const serverArg = `${parsed.protocol}//${parsed.host}`;+ const username = decodeURIComponent(parsed.username);+ const password = decodeURIComponent(parsed.password);+ const hasCredentials = username !== '' || password !== '';+ const isSocks = parsed.protocol === 'socks4:' || parsed.protocol === 'socks5:';+ if (hasCredentials && !isSocks) {+ return { serverArg, proxyAuthentication: { username, password }, socksAuthUnsupported: false };+ }+ return { serverArg, socksAuthUnsupported: hasCredentials && isSocks };+}diff --git a/src/engine/adapters/wwebjs-status.ts b/src/engine/adapters/wwebjs-status.tsnew file mode 100644index 000000000..c6dba9d14--- /dev/null+++ b/src/engine/adapters/wwebjs-status.ts@@ -0,0 +1,178 @@+import { InternalServerErrorException } from '@nestjs/common';+import { MessageTypes, type Client, type Message } from 'whatsapp-web.js';+import {+ IncomingMessage,+ MediaInput,+ Status,+ StatusPostOptions,+ StatusResult,+} from '../interfaces/whatsapp-engine.interface';+import { SerializedWid } from '../types/whatsapp-web-js.types';+import { toMessageMedia } from './wwebjs-messaging';+import { type WwebjsEngineHost } from './wwebjs-host';++/**+ * The status-post counterpart of `toMessageResult`, but its absent-message case is *narrower* than a+ * send's. `Injected/Utils.js` builds the status model and returns it from the `isStatus` branch before+ * ever reaching the `Msg.get` miss that makes an ordinary send ambiguous — so the only way back with no+ * message is `Client.js`'s `if (!chat) return null`, i.e. nothing was posted at all. Not an ambiguity:+ * a plain failure, which was previously dressed up as a `201` carrying a `new Date()` invented for a+ * status that never existed.+ *+ * Thrown as an `InternalServerErrorException` rather than a bare `Error` because there is no global+ * exception filter (see `message-not-found.error.spec.ts`), so a bare `Error` reaches the caller as+ * `{"statusCode":500,"message":"Internal server error"}` — and unlike a send, which routes its message+ * into the `message:failed` hook, HTTP is the only consumer a status post has. The same 500, with the+ * reason surviving.+ *+ * A present `Message` proves the post happened, so an id it cannot read there carries the same empty+ * sentinel `toMessageResult` uses. Read `$1` before falling back to it (#747): the sentinel means+ * "posted, id unknown", and `deleteStatus` takes this id as the revoke handle — spending it on an id+ * that was readable all along leaves a status nothing can revoke.+ */+export function toStatusResult(msg: Message | undefined): StatusResult {+ if (!msg) {+ throw new InternalServerErrorException(+ 'the engine returned no message for this status post, so it may not have been published — check your status before retrying',+ );+ }+ const id = msg.id as unknown as SerializedWid | undefined;+ const ts = msg.timestamp ? new Date(msg.timestamp * 1000) : new Date();+ return {+ statusId: id?._serialized ?? id?.$1 ?? '',+ timestamp: ts,+ expiresAt: new Date(ts.getTime() + 24 * 3_600_000),+ };+}++/**+ * Status/Stories operations extracted from WhatsAppWebJsAdapter. The adapter keeps the public+ * methods as thin forwarders and injects the shared host surface (./wwebjs-host) via closures, so+ * the delegate never touches lifecycle state directly.+ */+export class WwebjsStatus {+ constructor(private readonly host: WwebjsEngineHost) {}++ /** Post-ensureReady client handle. */+ private client(): Client {+ return this.host.getClient();+ }++ async getContactStatuses(): Promise<Status[]> {+ this.host.ensureReady();+ return this.collectStatuses(await this.client().getBroadcasts());+ }++ async getContactStatus(contactId: string): Promise<Status[]> {+ this.host.ensureReady();+ // A contact with no active 24h story resolves to an "empty" Broadcast (id/msgs/getContact+ // undefined — Broadcast._patch only runs when data is truthy). That is the common case, so guard+ // it: return [] rather than dereferencing undefined inside collectStatuses (→ 500).+ const broadcast = await this.client().getBroadcastById(contactId);+ return broadcast?.msgs?.length ? this.collectStatuses([broadcast]) : [];+ }++ /**+ * Map whatsapp-web.js story Broadcasts (+ their Messages) into the neutral Status shape. Each+ * Broadcast is one contact's story (its `msgs`); we flatten across broadcasts. type collapses to+ * the Status union (image/video, else text — audio/other stories are rare and become 'text').+ * expiresAt is timestamp + 24h (WhatsApp status TTL). Broadcasts without msgs are skipped (a story+ * that expired between getBroadcasts and here, or a phantom entry).+ */+ private async collectStatuses(+ broadcasts: ReadonlyArray<{+ msgs?: Message[];+ getContact: () => Promise<{ id: { _serialized: string }; name?: string; pushname?: string }>;+ }>,+ ): Promise<Status[]> {+ const statuses: Status[] = [];+ for (const broadcast of broadcasts) {+ if (!broadcast?.msgs?.length) {+ continue;+ }+ const contact = await broadcast.getContact();+ const contactSummary = {+ id: contact.id._serialized,+ ...(contact.name ? { name: contact.name } : {}),+ ...(contact.pushname ? { pushName: contact.pushname } : {}),+ };+ for (const msg of broadcast.msgs) {+ const ts = new Date(msg.timestamp * 1000);+ // Reuse the same capped/limited/timeout-bounded inbound media download the live message path+ // uses (capInboundMediaFor), so a seeded status renders identically to one that arrived live.+ let media: IncomingMessage['media'];+ if (msg.hasMedia) {+ try {+ media = await this.host.capInboundMediaFor(msg);+ } catch (error) {+ this.host.logger.warn(`Failed to download media for status ${msg.id._serialized}: ${String(error)}`);+ }+ }+ statuses.push({+ // `deleteStatus` takes this id as its revoke handle, so losing it to the rename makes a+ // listed status unactionable (#747). The contact id above is a Wid and is unaffected.+ id: ((msg.id as unknown as SerializedWid)?._serialized ?? (msg.id as unknown as SerializedWid)?.$1) || '',+ contact: contactSummary,+ type: msg.type === MessageTypes.IMAGE ? 'image' : msg.type === MessageTypes.VIDEO ? 'video' : 'text',+ ...(msg.body ? { caption: msg.body } : {}),+ ...(media ? { media } : {}),+ timestamp: ts,+ expiresAt: new Date(ts.getTime() + 24 * 3_600_000),+ });+ }+ }+ return statuses;+ }++ private warnedStatusRecipients = false;++ async postTextStatus(text: string, options: StatusPostOptions): Promise<StatusResult> {+ this.host.ensureReady();+ this.warnStatusRecipientsOnce(options);+ // whatsapp-web.js posts a text status by messaging status@broadcast with styling in `extra`+ // (Client.js maps options.extra → page extraOptions → sendStatusTextMsgAction in Utils.js).+ // backgroundColor is a #RRGGBB hex; font is the fontStyle index 0-7.+ const msg = await this.client().sendMessage('status@broadcast', text, {+ extra: {+ ...(options.backgroundColor !== undefined ? { backgroundColor: options.backgroundColor } : {}),+ ...(options.font !== undefined ? { fontStyle: options.font } : {}),+ },+ });+ return toStatusResult(msg);+ }++ async postImageStatus(media: MediaInput, options: StatusPostOptions): Promise<StatusResult> {+ return this.postMediaStatus(media, options);+ }++ async postVideoStatus(media: MediaInput, options: StatusPostOptions): Promise<StatusResult> {+ return this.postMediaStatus(media, options);+ }++ private async postMediaStatus(media: MediaInput, options: StatusPostOptions): Promise<StatusResult> {+ this.host.ensureReady();+ this.warnStatusRecipientsOnce(options);+ const messageMedia = await toMessageMedia(media);+ const msg = await this.client().sendMessage('status@broadcast', messageMedia, {+ ...(options.caption !== undefined ? { caption: options.caption } : {}),+ });+ return toStatusResult(msg);+ }++ private warnStatusRecipientsOnce(options: StatusPostOptions): void {+ if (this.warnedStatusRecipients || !options.recipients?.length) return;+ this.warnedStatusRecipients = true;+ this.host.logger.warn(+ "postStatus on the whatsapp-web.js engine broadcasts to the account's status-privacy audience; " ++ 'the recipients allow-list is not honored by whatsapp-web.js (it is on the Baileys engine).',+ );+ }++ async deleteStatus(statusId: string): Promise<void> {+ this.host.ensureReady();+ // Revokes the caller's own status post. revokeStatusMessage resolves the message by id and+ // throws if it isn't fromMe/isn't a status — the statusId returned by postText/Image/VideoStatus+ // (msg.id._serialized) is the id it expects.+ await this.client().revokeStatusMessage(statusId);+ }+}