Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(baileys): wire catalog reads and sendProduct on the Baileys engine (#1060)

Yudhi Armyndharis090961ed833c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fa44c2fdd..226eb965d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- `BAILEYS_MARK_ONLINE_ON_CONNECT=false` keeps phone push notifications alive while a Baileys gateway is connected (default `true`, prior behavior). (#871)
+- **The catalog endpoints now work on the Baileys engine.** `GET /catalog`, `GET /catalog/products`,
+ `GET /catalog/products/:id` and `POST /messages/send-product` were `501` on both engines even
+ though Baileys has exposed the full catalog surface (`getCatalog`/`getCollections`) for a while —
+ the adapter simply never called it. The reads walk the library's cursor-based catalog in full and
+ slice page/limit in memory, so `pagination.total`/`totalPages` are exact rather than estimated;
+ catalog metadata is synthesized from the first collection (a business without collections gets
+ `null`). `sendProduct` resolves the product from the catalog and sends it as a native product
+ card — unknown ids come back `404`, products without an image `400`, since the card cannot render
+ without one. `send-catalog` stays `501` on both engines: neither library has a catalog-share
+ message type. whatsapp-web.js is unchanged (`501` throughout — it has no catalog API). (#905)
### Fixed
@@ -121,7 +131,7 @@ consequences.
where the next send would deliver it to the wrong recipient. It is now cleared as soon as another
chat is opened, and cleared when the session is switched.
- Closing and reopening the *same* room still keeps it, so the round trip is lossless — the same
+ Closing and reopening the _same_ room still keeps it, so the round trip is lossless — the same
guarantee the typed message draft already had. Both lifetimes are pinned by regression tests.
## [0.12.3] - 2026-08-01
@@ -147,7 +157,7 @@ consequences.
- **Eight settings written to `data/.env.generated` were silently ignored under the bundled Docker
Compose stack.** `docker-compose.yml` forwards a variable as `- KEY=${KEY:-}` so a real host value
- reaches the container; with nothing set, that line renders an *empty* value. An empty value still
+ reaches the container; with nothing set, that line renders an _empty_ value. An empty value still
occupies `process.env`, and both lower-priority layers — the project `.env` and
`data/.env.generated` — are loaded with dotenv `override: false`, which will not replace a key that
is already present, blank or not. `clearBlankEnv` exists to delete exactly those blanks before the
@@ -158,9 +168,9 @@ consequences.
invites operators to edit directly — did nothing, with no error and no warning.
`AUTO_START_SESSIONS` is the one that got noticed, and it is worth being precise about the shape of
- the regression. The bundled *production* compose gained its forward in 0.12.0 — before that it had
+ the regression. The bundled _production_ compose gained its forward in 0.12.0 — before that it had
none, so an operator's `data/.env.generated` supplied the flag unobstructed, because there was no
- blank value to shadow it. (The *dev* compose has forwarded it since 0.10.0, defaulting it to `true`.)
+ blank value to shadow it. (The _dev_ compose has forwarded it since 0.10.0, defaulting it to `true`.)
Adding the production forward without the matching clear entry therefore did not relocate an older
failure; it switched off the one route that had been working. The flag resolved to off,
`SessionService`'s bootstrap hook returned before it looked at a single session, and previously
@@ -193,7 +203,7 @@ consequences.
every path from the process environment alone, while the application fills the same settings from
three layers: the environment, then `./.env`, then `<data dir>/.env.generated` — the file Dashboard >
Infrastructure writes. An install configured through the dashboard was therefore backed up at the
- *default* paths.
+ _default_ paths.
That is not reliably loud. A missing database already failed the run, but a database left at a
default path from before the operator switched was archived instead and the run exited 0. A backup
@@ -215,7 +225,7 @@ consequences.
dashboard control still moved, saved and reported success, while the running value never changed.
The blank-forward fix above cannot reach this. `clearBlankEnv` runs before `.env` is read, so it
- only clears blanks arriving from the process environment. A value in `.env` — including an *empty*
+ only clears blanks arriving from the process environment. A value in `.env` — including an _empty_
one, since dotenv treats `KEY=` as present rather than absent — is never cleared. The copied
`DATABASE_TYPE=sqlite` was enough on its own to shadow a dashboard switch to Postgres, leaving the
app quietly on SQLite; and for an operator who had also set `DATABASE_TYPE=postgres` by hand, the
@@ -227,7 +237,7 @@ consequences.
All 23 blank-forwarded keys are now commented out with their defaults shown, so copying the file no
longer pins any of them, and a test derives that set from both compose files and fails if one is
shipped uncommented again. Each was checked against its application-level default first; none
- changes behaviour *silently* when absent — `DATABASE_USERNAME` has no application default at all, so
+ changes behaviour _silently_ when absent — `DATABASE_USERNAME` has no application default at all, so
under `DATABASE_TYPE=postgres` it now fails boot validation naming the variable instead of resolving
to `openwa`. One further exception is called out in the file: the dev compose defaults an unset
`AUTO_START_SESSIONS` to `true`, so a dev stack that had inherited `false` from a copied
@@ -277,7 +287,7 @@ consequences.
- **Six self-contained concerns were lifted out of `SessionService`.** Each was previously reachable
only by driving the full session lifecycle, so the trickiest logic in the file had the least direct
coverage. The `@lid`→phone read-through cache became `SessionLidResolver` (and took an `@Optional`
- constructor dependency with it); the reconnect backoff *decision* became a pure `decideReconnect()`
+ constructor dependency with it); the reconnect backoff _decision_ became a pure `decideReconnect()`
with injected clock and jitter, leaving the service to apply only the effects; the liveness watchdog
became `SessionLivenessWatchdog`, which owns its interval and failure counter and reports back
through a single `onDead` callback; the per-message serialization chain became a general
@@ -354,7 +364,7 @@ consequences.
same constant the registry path is built from so the two cannot drift apart again.
Existing installs keep working: when `PLUGINS_DIR` is unset, the old `./plugins` is still scanned as
- a compatibility fallback, *in addition to* the configured directory (a host part-way through
+ a compatibility fallback, _in addition to_ the configured directory (a host part-way through
migrating keeps both halves; the configured copy loads first and wins a duplicate id). The fallback
is keyed on actually finding a plugin package — a non-dot subdirectory with a `manifest.json` — not
on the directory existing, because `<dataDir>/plugins/<id>` doubles as each plugin's `ctx.storage`
@@ -386,11 +396,11 @@ consequences.
restarting a plugin to clear a fault saw the same fault reported against the healthy worker that
replaced it.
- The record is now cleared where a generation *starts*, so it holds for every way one can end rather
+ The record is now cleared where a generation _starts_, so it holds for every way one can end rather
than for the single path that happened to be handled.
- **A rolled-back `POST /api/infra/import-data` no longer denies the engines it already stopped.** The
- orphan pre-flight runs *before* the transaction opens, and `stopOrphans: true` really destroys those
+ orphan pre-flight runs _before_ the transaction opens, and `stopOrphans: true` really destroys those
engines there — a teardown the rollback cannot undo. Both rollback branches nevertheless returned a
hardcoded `restartRequired: false` with three empty orphan arrays, so an operator who hit a per-row
warning read "nothing was stopped, no restart needed" while their sessions were in fact down. They
@@ -403,7 +413,7 @@ consequences.
unchanged and `openapi.json` is untouched — only the values were wrong.
- **A missing dashboard asset returns 404 instead of the SPA shell.** `ServeStaticModule`'s built-in
- fallback answered *every* unmatched GET with `index.html`, so a mistyped or stale `<script src>`
+ fallback answered _every_ unmatched GET with `index.html`, so a mistyped or stale `<script src>`
came back `200 text/html` and the browser reported a JavaScript syntax error from parsing the HTML
shell — pointing at the wrong file and hiding a broken build. `main.ts` already serves dashboard
documents (it injects the per-response CSP nonce, so it must own them) and is correctly narrow:
@@ -740,7 +750,7 @@ races around engine teardown and re-initialization are closed.
neither applier accepts one whose lines end CRLF — both stop at this patch's first empty context
line (`git apply`: "corrupt patch at line 7"; `patch`: "malformed patch at line 7"). Windows checks
the file out exactly that way whenever `core.autocrlf` is on, which is its default, so the `git
- apply` fallback introduced for Windows could never run on Windows, and its failure was additionally
+apply` fallback introduced for Windows could never run on Windows, and its failure was additionally
misread as a half-written tree — which turned a skippable warning into a hard install failure.
Three changes: the patch is normalized to LF before either applier sees it, which also repairs
clones already on disk with CRLF; a `.gitattributes` rule keeps fresh clones on LF; and a refusal to
@@ -773,7 +783,7 @@ races around engine teardown and re-initialization are closed.
whatsapp-web.js adapter clears a session's auth directory to recover one that authenticated but never
reached runtime readiness within 90 seconds, and that directory holds the only copy of the
credentials — once removed, no restart can restore the link and every later start can do nothing but
- present a fresh QR. The adapter logged only the *failure* to remove it, so a successful wipe left no
+ present a fresh QR. The adapter logged only the _failure_ to remove it, so a successful wipe left no
trace at all: the sole symptom was a session that quietly stopped reconnecting, indistinguishable in
the logs from a WhatsApp-side logout or a profile nothing had touched. The removal now logs a warning
naming the directory and the session, and the readiness-timeout warning that precedes it carries the
@@ -851,7 +861,7 @@ races around engine teardown and re-initialization are closed.
`:-false` and an absent variable are read identically. Once you do set it, spell it exactly `true`
or `false`: the value now reaches boot validation, which rejects anything else by name rather than
silently falling back, so a typo fails the boot instead of quietly choosing a security posture.
- Note also that the *refusal* it opts out of is new in this release — see the Security item for the
+ Note also that the _refusal_ it opts out of is new in this release — see the Security item for the
upgrade impact.
- **A caller's timeout now bounds the SSRF guard's own DNS resolution, and reports itself honestly.**
@@ -1291,7 +1301,7 @@ races around engine teardown and re-initialization are closed.
the download host and seizing it would mis-verify an unrelated URL. The dashboard plugin config UI
rendered in an `allow-scripts` sandbox that inherits the dashboard CSP (which allows any `https:`
`img-src`/`media-src`) — a meta-CSP (`img-src 'self' data:`, `media-src 'self' data:`, `connect-src
- 'none'`) is now injected as the frame's first `<head>` element, closing the egress channel `sandbox` alone
+'none'`) is now injected as the frame's first `<head>` element, closing the egress channel `sandbox` alone
cannot block. The audit-log CSV export quoted only `,`/`\n`/`"`, so an attacker-influenced string starting
with `=`/`+`/`@`/`-` became a formula when an operator opened the export in a spreadsheet — cells are now
apostrophe-prefixed before structural quoting. **Breaking (behavior):** legitimate concurrent sends that
@@ -1330,7 +1340,7 @@ races around engine teardown and re-initialization are closed.
- **The create-instance and regenerate-secret responses no longer echo plaintext values for secret-flagged
config fields, and the whatsapp-web.js engine no longer reports phantom success for operations it never
performed.** Two related honesty fixes: `(POST /integration/plugins/:pluginId/instances,
- …/regenerate-secret)` rendered the raw instance row when `reveal=true`, bypassing `maskedView` — so any
+…/regenerate-secret)` rendered the raw instance row when `reveal=true`, bypassing `maskedView` — so any
config field flagged `secret: true` at any nesting depth (a nested `credentials.apiToken`, an array-row
`webhooks[].signingKey`) was returned in plaintext alongside the one-time ingress secret/verifyToken
reveal. The view builder now always starts from `maskedView` (fail-closed when the schema is unavailable)
@@ -1454,7 +1464,7 @@ races around engine teardown and re-initialization are closed.
- **Dashboard stats aggregates now use a standalone `messages(createdAt)` index and a short TTL
memo, and ingress replay/dedup-row growth is now bounded.** The dashboard timeline and stats
queries (`getOverview`, `getMessageStats`) filter on `createdAt` alone (`WHERE m.createdAt >=
- :since`, no `sessionId`), which the existing composite `(sessionId, createdAt)` cannot serve
+:since`, no `sessionId`), which the existing composite `(sessionId, createdAt)` cannot serve
(Postgres has no skip-scan; SQLite without `ANALYZE` full-scans) — a new standalone index
`IDX_messages_createdAt` serves the predicate directly (the migration lifts the runtime
`statement_timeout` on Postgres to mirror the sibling index migrations), and the per-period
@@ -1476,7 +1486,7 @@ races around engine teardown and re-initialization are closed.
- **The message `from`-filter now matches group authors, JID candidate expansion is scoped by chat
kind, and session delete purges both engines' auth directories.** `GET /api/sessions/:id/messages
- ?from=<phone>` filtered only the `from` column, but both engine mappers store a group message's
+?from=<phone>` filtered only the `from` column, but both engine mappers store a group message's
real sender in `author` (with the group JID in `from`), so the filter silently skipped every
group message that person wrote. It now matches `(message.from IN (:…) OR message.author IN (:…))`
against the same lid-expanded candidate set. `resolveJidCandidates` previously expanded ANY filter
@@ -1529,7 +1539,7 @@ races around engine teardown and re-initialization are closed.
`securityContext`, so an operator following the manifest ran the plugin sandbox without its
OS-containment half (read-only rootfs, non-root, `cap_drop: ALL`) — weaker than the threat model
assumes. The manifest now sets `runAsNonRoot`, `readOnlyRootFilesystem`, `allowPrivilegeEscalation:
- false`, and `capabilities.drop: ['ALL']`, with the writable `/app/data` and `/tmp` mounts that
+false`, and `capabilities.drop: ['ALL']`, with the writable `/app/data` and `/tmp` mounts that
`readOnlyRootFilesystem` requires. The stale image tag (`0.4.6`) was also bumped to the current
release.
@@ -1607,7 +1617,7 @@ races around engine teardown and re-initialization are closed.
### Changed
- **Status font selection now follows the real WhatsApp font enum.** `POST
- /sessions/:id/status/send-text` accepts the font indices that actually exist on the wire — 0
+/sessions/:id/status/send-text` accepts the font indices that actually exist on the wire — 0
(default), 1, 2, 6 (system bold), 7, 8, 9, 10 — instead of a 0–5 range that included
non-existent indices 3–5 and rejected the valid 6–10. The dashboard viewer renders the full
enum (bold/script/serif/mono slots approximated with generic families), and the compose
@@ -1677,7 +1687,7 @@ races around engine teardown and re-initialization are closed.
### Changed
- **Status `recipients` is now optional on the post-status endpoints.** `POST
- /sessions/:id/status/send-text`, `send-image`, and `send-video` accept an omitted or empty
+/sessions/:id/status/send-text`, `send-image`, and `send-video` accept an omitted or empty
`recipients` list. The Baileys engine still requires it — it posts to exactly that allow-list, so
an absent/empty list now 400s there with a clear message — while whatsapp-web.js, which broadcasts
to the account's status-privacy audience and always ignored the field, no longer needs a
@@ -1741,7 +1751,7 @@ races around engine teardown and re-initialization are closed.
stream the body (media / plugin downloads) are unchanged.
- **Expired status media now 404s instead of 500ing when the purge races a stream.** A `GET
- /sessions/:id/status/:statusId/media` landing in the sub-second window where the 24h purge deletes
+/sessions/:id/status/:statusId/media` landing in the sub-second window where the 24h purge deletes
the backing file mid-request previously surfaced a generic 500; a missing file now maps to the
same 404 as an unknown or omitted status.
@@ -1962,6 +1972,7 @@ of boolean and numeric request fields.
> `input.chatId` unconditionally should branch on the `source` or `type` field first.
### Added
+
- **Outbound message edit.** `POST /api/sessions/:sessionId/messages/edit` edits the text of a
message sent by the account, on both engines (whatsapp-web.js `Message.edit`, Baileys
`sendMessage` with an `edit` key). Attempting to edit another sender's message fails with `403`,
@@ -1980,7 +1991,7 @@ of boolean and numeric request fields.
`timestamp` (the engine does not forward the original occurrence time).
- **Join groups & group settings.** `POST /api/sessions/:sessionId/groups/join` joins a group via
invite code (an invalid/expired code returns a typed `400`). `GET`/`PUT
- /api/sessions/:sessionId/groups/:groupId/settings` read and update the admin-only flags
+/api/sessions/:sessionId/groups/:groupId/settings` read and update the admin-only flags
(`announce`, `locked`) and the disappearing-message timer (`ephemeralSeconds`, Baileys only — it
returns a documented `501` on whatsapp-web.js, which has no such API). A settings patch applies
the timer first, so a `501` can never silently follow an already-applied flag change, and
@@ -2006,6 +2017,7 @@ of boolean and numeric request fields.
`docs/23-community-integrations.md` clarifies that it lists community projects only.
### Changed
+
- **The security audit runs as its own CI job.** `npm audit` reports against the advisory database
rather than against the diff, so a newly published advisory turns red on unrelated pull requests.
While it was the first step of the Lint job, that failure aborted the job before ESLint, the
@@ -2026,6 +2038,7 @@ of boolean and numeric request fields.
A handler that reads `input.chatId` unconditionally should branch on `source` or `type` first.
### Fixed
+
- **`forEveryone: false` on message delete is honoured again.** `POST /api/sessions/:sessionId/messages/delete`
defaults `forEveryone` to `true`, so sending it at all means "delete only for me" — but a request
that carried the value as a string (any form-encoded body, since that parser produces only string
@@ -2076,6 +2089,7 @@ of boolean and numeric request fields.
put across parent re-renders. Reported in #837, fixed in #838.
### Security
+
- **Resolved every known advisory in the dependency tree (17 → 0, including one critical).** The
critical one was a set of path-traversal and symlink issues in `node-tar`, reached only through
`sqlite3@5` → `node-gyp` → `tar`. `sqlite3` moves to `6.0.1`, which drops the `node-gyp`
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index 009917285..f9dd98a41 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -698,11 +698,11 @@ curl -X DELETE "$BASE/api/sessions/$SESSION_ID/templates/$TEMPLATE_ID" \
### 07.8 Catalog & Channels
-The five catalog routes are registered but **no engine implements them**: both whatsapp-web.js and Baileys raise `EngineNotSupportedError`, so each of them returns `501 Not Implemented` once the session is READY. On whatsapp-web.js the readiness check runs first, so a session that exists but is not yet READY returns `409` instead; Baileys raises the unsupported error unconditionally. They are listed for route completeness only. The channel routes that follow are a separate group with real engine support — the per-engine gaps are listed in `docs/29-engine-capability-matrix.md`.
+The catalog routes work on the **Baileys** engine (WhatsApp Business accounts) — `getCatalog`/`getProducts`/`getProduct` read the session's own catalog and `sendProduct` sends a native product card. On **whatsapp-web.js** they raise `EngineNotSupportedError` (`501 Not Implemented`) — the library has no catalog API at all; on that engine the readiness check runs first, so a session that exists but is not yet READY returns `409` instead. The exception is `send-catalog`, which returns `501` on **both** engines (no catalog-share message type exists in either library). The per-engine gaps are listed in `docs/29-engine-capability-matrix.md`. The channel routes that follow are a separate group with real engine support.
#### GET /api/sessions/:sessionId/catalog
-Get business catalog info for the session. Returns `501` on both engines.
+Get business catalog info for the session. On Baileys returns the first catalog collection's metadata (`200`, or `null` when the business has no collections); on whatsapp-web.js returns `501`.
```bash
curl -X GET "$BASE/api/sessions/$SESSION_ID/catalog" \
@@ -711,7 +711,7 @@ curl -X GET "$BASE/api/sessions/$SESSION_ID/catalog" \
#### GET /api/sessions/:sessionId/catalog/products
-List catalog products with pagination. Returns `501` on both engines.
+List catalog products with pagination. Works on Baileys (page/limit over the full catalog walk); returns `501` on whatsapp-web.js.
```bash
curl -X GET "$BASE/api/sessions/$SESSION_ID/catalog/products?page=1&limit=20" \
@@ -720,7 +720,7 @@ curl -X GET "$BASE/api/sessions/$SESSION_ID/catalog/products?page=1&limit=20" \
#### GET /api/sessions/:sessionId/catalog/products/:productId
-Get a specific catalog product by id. Returns `501` on both engines, whatever the id.
+Get a specific catalog product by id. On Baileys returns the product (`200`) or `null` for an unknown id; on whatsapp-web.js returns `501`.
```bash
curl -X GET "$BASE/api/sessions/$SESSION_ID/catalog/products/PROD_12345" \
@@ -729,7 +729,7 @@ curl -X GET "$BASE/api/sessions/$SESSION_ID/catalog/products/PROD_12345" \
#### POST /api/sessions/:sessionId/messages/send-product
-Send a product card to a chat (OPERATOR key required). Returns `501` on both engines.
+Send a product card to a chat (OPERATOR key required). On Baileys returns `404` for an unknown product id and `400` when the product has no image; on whatsapp-web.js returns `501`.
```bash
curl -X POST "$BASE/api/sessions/$SESSION_ID/messages/send-product" \
@@ -1444,7 +1444,7 @@ socket.on('connect', () => {
});
});
-socket.on('message', (msg) => {
+socket.on('message', msg => {
if (msg.type === 'event') {
console.log(`[${msg.payload.event}] ${msg.payload.sessionId}`, msg.payload.data);
} else {
@@ -1452,6 +1452,6 @@ socket.on('message', (msg) => {
}
});
-socket.on('connect_error', (err) => console.error('connect_error:', err.message));
-socket.on('disconnect', (reason) => console.log('disconnected:', reason));
+socket.on('connect_error', err => console.error('connect_error:', err.message));
+socket.on('disconnect', reason => console.log('disconnected:', reason));
```
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index 36dc2f997..cf038741c 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -1,6 +1,6 @@
# 29 - Engine Capability Matrix
-This page is the operator- and engineer-facing view of which `IWhatsAppEngine` capabilities are real on each adapter — `wwjs` (whatsapp-web.js, the default) and `baileys` (the browser-free alternative) — and, for the ones that are missing, *why* and *where to start*.
+This page is the operator- and engineer-facing view of which `IWhatsAppEngine` capabilities are real on each adapter — `wwjs` (whatsapp-web.js, the default) and `baileys` (the browser-free alternative) — and, for the ones that are missing, _why_ and _where to start_.
The committed source of truth is `src/engine/engine-capability-matrix.ts`. Every `IWhatsAppEngine` method has a row with two adapters; each adapter is either `supported` (works end-to-end) or `not-available`, and each `not-available` cell carries a **rootCause**:
@@ -26,75 +26,77 @@ The `rootCause`/`evidence` fields are hand-curated from source traces of the ins
### Channels / Newsletter
-| Method | baileys | wwjs |
-|---|---|---|
-| `getChannelMessages` | not-available — **adapter-gap** | supported |
-| `getSubscribedChannels` | not-available — **library-limitation** | supported |
-| `subscribeToChannel` | supported | not-available — **adapter-gap** |
+| Method | baileys | wwjs |
+| ----------------------- | -------------------------------------- | ------------------------------- |
+| `getChannelMessages` | not-available — **adapter-gap** | supported |
+| `getSubscribedChannels` | not-available — **library-limitation** | supported |
+| `subscribeToChannel` | supported | not-available — **adapter-gap** |
> **Wired.** ✅ `getChannelById`, `subscribeToChannel`, `unsubscribeFromChannel` on Baileys — via `newsletterMetadata('jid'|'invite', …)` → `NewsletterMetadata` mapped to `Channel` (id/name/description/inviteCode/subscriberCount/picture/verified/createdAt), `newsletterFollow` (subscribe, invite→jid bridge), `newsletterUnfollow` (unsubscribe, 1:1). `getChannelById` on Baileys resolves ANY channel by jid (richer than the wwjs subscribed-list lookup).
+
- **`subscribeToChannel` (wwjs, adapter-gap).** whatsapp-web.js `Client.subscribeToChannel(channelId)` takes a channel ID and resolves a boolean (`Client.js:2533`) — it cannot satisfy the subscribe-by-invite-code contract on its own. The correct wiring is two-step: `getChannelByInviteCode(inviteCode)` (`Client.js:1707`) → `subscribeToChannel(channel.id)`. The adapter previously passed the invite code straight in and fabricated a `Channel` out of the returned boolean (`{ id: "undefined" }` — a reported success that never subscribed); it now throws an honest `EngineNotSupportedError` (501) until the two-step flow is verified against a live session.
- **`getChannelMessages` (baileys, adapter-gap).** `sock.newsletterFetchMessages(channelId, limit, 0, 0)` (`Socket/newsletter.d.ts:19`) returns the **raw `BinaryNode`** of `<message_updates>` children (`newsletter.js:149`). The fetch is one line; the real work is walking the children and mapping each to `ChannelMessage{id,body,timestamp,hasMedia}` — no library parser is exposed. Not wired: a hand-written BinaryNode walk can't be verified without a live WhatsApp session, so it stays a documented gap rather than an unverified implementation.
- **`getSubscribedChannels` (baileys, library-limitation).** No enumerate-subscribed-newsletters query in the library. All 19 newsletter members of `Socket/newsletter.d.ts` address a single newsletter — by jid, by invite key, or by creating one (`newsletterMetadata('invite'|'jid', key)` requires a key; `newsletterSubscribers(jid)` returns the count of one newsletter; `newsletterCreate(name, description?)` makes a new one). The `newsletter` event surfaces jids opportunistically during live sync, but that is incremental, not a list-all. Would require a raw WMex/app-state hack against an undocumented XWAPath.
### Labels (WhatsApp Business)
-| Method | baileys | wwjs |
-|---|---|---|
-| `getLabels` | not-available — **library-limitation** | supported |
-| `getLabelById` | not-available — **library-limitation** | supported |
+| Method | baileys | wwjs |
+| --------------- | -------------------------------------- | --------- |
+| `getLabels` | not-available — **library-limitation** | supported |
+| `getLabelById` | not-available — **library-limitation** | supported |
| `getChatLabels` | not-available — **library-limitation** | supported |
-> **Wired.** ✅ `addLabelToChat` / `removeLabelFromChat` on the Baileys engine — 1:1 to `sock.addChatLabel(chatId, labelId)` / `sock.removeChatLabel(chatId, labelId)` (`Socket/chats.d.ts:70-71`). WhatsApp-Business-only (rejects on personal accounts). Do **not** use `addLabel(jid, LabelActionBody)` (`chats.d.ts:69`) — that creates/edits the label *definition*, not the chat association.
+> **Wired.** ✅ `addLabelToChat` / `removeLabelFromChat` on the Baileys engine — 1:1 to `sock.addChatLabel(chatId, labelId)` / `sock.removeChatLabel(chatId, labelId)` (`Socket/chats.d.ts:70-71`). WhatsApp-Business-only (rejects on personal accounts). Do **not** use `addLabel(jid, LabelActionBody)` (`chats.d.ts:69`) — that creates/edits the label _definition_, not the chat association.
+
- **`getLabels` / `getLabelById` / `getChatLabels` (baileys, library-limitation).** No label read/fetch symbol anywhere in `lib/**/*.d.ts` (`Types/Label.d.ts` has only the interface + `LabelColor` enum; `chats.d.ts`/`business.d.ts` expose only writes). Label data does arrive via app-state sync (`messaging-history.set`), so a determined adapter could capture+cache labels from the event stream — but that is a relay/cache hack, not a first-class getter, and there is no network fetch to seed/refresh it on demand.
### Catalog / Products / Orders (WhatsApp Business)
-| Method | baileys | wwjs |
-|---|---|---|
-| `getCatalog` | not-available — **adapter-gap** (medium-confidence) | not-available — **library-limitation** |
-| `getProducts` | not-available — **adapter-gap** | not-available — **library-limitation** |
-| `getProduct` | not-available — **adapter-gap** (medium-confidence) | not-available — **library-limitation** |
-| `sendProduct` | not-available — **adapter-gap** | not-available — **library-limitation** |
+| Method | baileys | wwjs |
+| ------------- | -------------------------------------- | -------------------------------------- |
+| `getCatalog` | supported | not-available — **library-limitation** |
+| `getProducts` | supported | not-available — **library-limitation** |
+| `getProduct` | supported | not-available — **library-limitation** |
+| `sendProduct` | supported | not-available — **library-limitation** |
| `sendCatalog` | not-available — **library-limitation** | not-available — **library-limitation** |
-- **`getProducts` (baileys, adapter-gap).** `sock.getCatalog({jid, limit, cursor})` (`Socket/business.d.ts:7`) returns `{products, nextPageCursor}` — paginated, maps to `PaginatedProducts`. Caveat: cursor-based, so `total` is unknown (approximate or iterate).
-- **`getCatalog` (baileys, adapter-gap, medium-confidence).** `getCatalog` returns a product list + cursor, **not** the OpenWA `Catalog` metadata wrapper. Name needs `getCollections(jid)` (`business.d.ts:11`); `id`/`description`/`url` have no source — the adapter would synthesize a partial Catalog (`productCount=products.length`, rest best-effort).
-- **`getProduct` (baileys, adapter-gap, medium-confidence).** No direct `getProduct(id)`; call `getCatalog({jid,limit})` then `products.find(p=>p.id===productId)` — loads the whole page to fetch one product.
-- **`sendProduct` (baileys, adapter-gap).** `AnyRegularMessageContent` accepts `{product: WASendableProduct, businessOwnerJid, body}` (`Types/Message.d.ts:203`, built in `messages.js:397`). Two-step wiring: `getCatalog` lookup to resolve the product's image/title/price, then `sock.sendMessage(chatId, {product:{...}, body})`. `productId`-only send without the lookup is not possible.
+> **Wired (#905).** ✅ `getCatalog` / `getProducts` / `getProduct` / `sendProduct` on the Baileys engine (`src/engine/adapters/baileys-catalog.ts`, `baileys-messaging.ts`). `getProducts` cursor-walks `sock.getCatalog({jid, limit, cursor})` (`Socket/business.d.ts:7`) to exhaustion, then slices page/limit in memory — `pagination.total`/`totalPages` are exact. `getCatalog` synthesizes the `Catalog` metadata from the first `getCollections(jid)` entry (`business.d.ts:11`; `null` when the business has no collections). `getProduct` reuses the walk + find-by-id. `sendProduct` is the documented 2-step: the adapter resolves the product, then sends `{product: WASendableProduct, businessOwnerJid, body}` (`Types/Message.d.ts:203`) with `priceAmount1000 = price × 1000` and the catalog image handed to Baileys as a URL upload; a product without an image is rejected `400`, an unknown id `404`.
+
- **`sendCatalog` (both, library-limitation).** No catalog-share message type exists in either library. Baileys `AnyMessageContent` has only `{product}` (single product); the catalog CRUD nodes (`Socket/business.js:294-362`) mutate the catalog, they don't send it. Would require raw-proto relay hacks (unverified).
- **wwjs catalog (library-limitation).** `whatsapp-web.js` has no `Client.getCatalog`/`getProducts`/`getProduct`/`sendProduct`/`sendCatalog` (`index.d.ts` grep = 0 hits). `Product`/`Order` are inbound-only parsers. The adapter throws an explicit `EngineNotSupportedError` (501) for the reads (they used to be phantom `null`/`[]` stubs) and the sends alike.
### Status — post / delete
> **Wired.** ✅ `postTextStatus` / `postImageStatus` / `postVideoStatus` + `deleteStatus` on whatsapp-web.js. Posts route via `sendMessage('status@broadcast', …)` (`{ extra: { backgroundColor, fontStyle } }` for text; `{ caption }` for media); `deleteStatus` calls `revokeStatusMessage(statusId)` (own-status only). **Caveat:** whatsapp-web.js has no status-recipient arg, so `StatusPostOptions.recipients` is not honored on this engine (it broadcasts to the account's status-privacy audience; a one-time warning is logged). The Baileys engine honors `recipients` (`statusJidList`).
-- **`deleteStatus` (baileys) caveat.** Marked `supported` (no throw), but the adapter self-describes its `sendMessage(status@broadcast,{delete})` revoke shape as *empirically unverified* (`baileys.adapter.ts`, the `deleteStatus()` doc comment) — only posting was live-spiked. May need a fallback to `EngineNotSupportedError` if WA rejects the shape.
+
+- **`deleteStatus` (baileys) caveat.** Marked `supported` (no throw), but the adapter self-describes its `sendMessage(status@broadcast,{delete})` revoke shape as _empirically unverified_ (`baileys.adapter.ts`, the `deleteStatus()` doc comment) — only posting was live-spiked. May need a fallback to `EngineNotSupportedError` if WA rejects the shape.
### Status — read (contact stories)
-| Method | baileys | wwjs |
-|---|---|---|
-| `getContactStatus` | not-available — **library-limitation** | supported |
+| Method | baileys | wwjs |
+| -------------------- | -------------------------------------- | --------- |
+| `getContactStatus` | not-available — **library-limitation** | supported |
| `getContactStatuses` | not-available — **library-limitation** | supported |
> **Wired.** ✅ `getContactStatus` / `getContactStatuses` on whatsapp-web.js — `getBroadcastById(id)` / `getBroadcasts()` flattened to `Status[]` (contact via `broadcast.getContact()`; type from `MessageTypes`; 24h TTL). **Caveat:** `Status.type` is the `text|image|video` union — audio/other story types collapse to `text`.
-- **`getContactStatus` / `getContactStatuses` (baileys, library-limitation).** `fetchStatus` (`Socket/chats.d.ts:42` via `USyncStatusProtocol`) returns the *about/profile text* line (`{status, setAt}`), **not** 24h stories. No story-read getter exists; story broadcasts surface only as `status@broadcast` messages via `messages.upsert` / `messaging-history.set` events. These raw engine methods are still unimplemented on Baileys and still throw `EngineNotSupportedError` (`501`) if called directly.
+
+- **`getContactStatus` / `getContactStatuses` (baileys, library-limitation).** `fetchStatus` (`Socket/chats.d.ts:42` via `USyncStatusProtocol`) returns the _about/profile text_ line (`{status, setAt}`), **not** 24h stories. No story-read getter exists; story broadcasts surface only as `status@broadcast` messages via `messages.upsert` / `messaging-history.set` events. These raw engine methods are still unimplemented on Baileys and still throw `EngineNotSupportedError` (`501`) if called directly.
- **API-level parity shipped without adapter wiring.** The `status@broadcast` accumulator this row calls for exists now — as an OpenWA-side store (`StatusStoreService`, `src/modules/status-store/`) fed by inbound status ingestion on both engines, not inside the Baileys adapter. `GET /sessions/:id/status` and `GET /sessions/:id/status/:contactId` read from that store instead of calling `getContactStatus`/`getContactStatuses`, so the REST API is at parity across engines even though these two adapter cells remain, correctly, `not-available`.
### Messaging misc — delete / history / reactions
-| Method | baileys | wwjs |
-|---|---|---|
-| `getChatHistory` | not-available — **library-limitation** | supported |
+| Method | baileys | wwjs |
+| --------------------- | -------------------------------------- | --------- |
+| `getChatHistory` | not-available — **library-limitation** | supported |
| `getMessageReactions` | not-available — **library-limitation** | supported |
-- **`getChatHistory` (baileys, library-limitation).** The only history primitive is `fetchMessageHistory(count, oldestMsgKey, oldestMsgTimestamp)` (`Socket/business.d.ts:25`) — it returns a sync-token *string*, not messages; the messages are delivered later via the `messaging-history.set` event. There is no per-chat `fetchMessages(chatId, limit)` on the socket. A synchronous `Promise<IncomingMessage[]>` for one chat would require an OpenWA-side chat-indexed store populated from `messages.upsert` + `messaging-history.set` events.
+- **`getChatHistory` (baileys, library-limitation).** The only history primitive is `fetchMessageHistory(count, oldestMsgKey, oldestMsgTimestamp)` (`Socket/business.d.ts:25`) — it returns a sync-token _string_, not messages; the messages are delivered later via the `messaging-history.set` event. There is no per-chat `fetchMessages(chatId, limit)` on the socket. A synchronous `Promise<IncomingMessage[]>` for one chat would require an OpenWA-side chat-indexed store populated from `messages.upsert` + `messaging-history.set` events.
- **`getMessageReactions` (baileys, library-limitation).** No on-demand server fetch. Reactions exist only as event-augmented state on `WAMessage.reactions` (`proto.IReaction[]` at `WAProto/index.d.ts:10623`), mutated by `updateMessageWithReaction` and surfaced via the `messages.reaction` event. The adapter already processes `reactionMessage` events (`baileys.adapter.ts`, the `reactionMessage` branch of `processInboundMessage()`) and emits `onMessageReaction`, but it does **not** persist `.reactions` into its `messageStore` (that branch returns before the `messageStore.put`). A store-backed read would need that persistence added first; even then, only reactions observed since session start are known (no historical backfill).
### Groups — disappearing messages
-| Method | baileys | wwjs |
-|---|---|---|
+| Method | baileys | wwjs |
+| ------------------- | --------- | -------------------------------------- |
| `setGroupEphemeral` | supported | not-available — **library-limitation** |
- **`setGroupEphemeral` (wwjs, library-limitation).** whatsapp-web.js 1.34.7 exposes no disappearing-timer setter (0 hits for `ephemeral` in `index.d.ts`); the only timer surface is the create-time `messageTimer` option (`Client.js:2371`). The adapter throws `EngineNotSupportedError` (501). Baileys wires `groupToggleEphemeral(jid, ephemeralExpiration)` (`Socket/groups.d.ts:40`).
@@ -110,6 +112,7 @@ These are the capabilities the underlying library already supports but the OpenW
### Tier 1 — small effort, high value ✅ shipped
All Tier-1 adapter-gaps have been wired:
+
- ✅ `deleteMessage(forEveryone=false)` — Baileys (`chatModify({ deleteForMe })`)
- ✅ `postTextStatus` / `postImageStatus` / `postVideoStatus` — whatsapp-web.js (`sendMessage('status@broadcast', …)`; `recipients` not honored)
- ✅ `addLabelToChat` / `removeLabelFromChat` — Baileys (`addChatLabel` / `removeChatLabel`; WhatsApp-Business-only)
@@ -121,19 +124,19 @@ _All Tier-2 items wired (see progress above). Remaining channel work is Tier 3:
### Tier 3 — medium effort
-| # | Method : engine | Library call to wire | Effort | Value |
-|---|---|---|---|---|
-| 13 | `getChannelMessages` : **baileys** | `sock.newsletterFetchMessages(jid,count,since,after)` (`Socket/newsletter.d.ts:19`) + hand-written `BinaryNode`→`ChannelMessage` parser | **M** | Read channel posts. The fetch is 1 line; the BinaryNode parsing/normalization is the real work (no library parser exposed). |
-| 14 | `getProducts` : **baileys** | `sock.getCatalog({jid,limit,cursor})` → `{products, nextPageCursor}` (`Socket/business.d.ts:7`) | **M** | Commerce. Derive `pagination.total`/`totalPages` (cursor-based, total unknown — approximate or iterate). |
-| 15 | `sendProduct` : **baileys** | 2-step: `getCatalog` lookup (image/title/price) then `sendMessage({product:{...},body})` (`Types/Message.d.ts:203`) | **M** | Outbound commerce. `productId`-only send is not possible without the lookup. |
-| 16 | `getCatalog` : **baileys** | `getCatalog` + `getCollections` (`Socket/business.d.ts:7,11`); synthesize partial `Catalog` (medium-confidence shape) | **M** | Catalog metadata. Fields `id`/`description`/`url` have no source — best-effort. |
+| # | Method : engine | Library call to wire | Effort | Value |
+| --- | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- |
+| 13 | `getChannelMessages` : **baileys** | `sock.newsletterFetchMessages(jid,count,since,after)` (`Socket/newsletter.d.ts:19`) + hand-written `BinaryNode`→`ChannelMessage` parser | **M** | Read channel posts. The fetch is 1 line; the BinaryNode parsing/normalization is the real work (no library parser exposed). |
+
+_✅ #14 `getProducts`, #15 `sendProduct`, #16 `getCatalog` — wired on Baileys (#905); see §Catalog / Products / Orders above._
### Tier 4 — small effort, lower value
-| # | Method : engine | Library call to wire | Effort | Value |
-|---|---|---|---|---|
-| 17 | `getProduct` : **baileys** | `getCatalog({jid,limit})` then `products.find(p=>p.id===productId)` (`Socket/business.d.ts:7`) | **S** | Single-product read. Inelegant — loads a whole page to fetch one product. Ship after #14 reuses the same catalog call. |
-| 18 | `subscribeToChannel` : **wwjs** | 2-step: `getChannelByInviteCode(inviteCode)` (`index.d.ts:103`; `Client.js:1707`) → `subscribeToChannel(channel.id)` (`Client.js:2533`, boolean → throw on false) | **S** | Channel subscribe-by-invite parity with Baileys. Must be verified against a live session — the previous one-step call was a phantom (it passed the invite code where a channel id belongs and fabricated the returned Channel). |
+| # | Method : engine | Library call to wire | Effort | Value |
+| --- | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| 18 | `subscribeToChannel` : **wwjs** | 2-step: `getChannelByInviteCode(inviteCode)` (`index.d.ts:103`; `Client.js:1707`) → `subscribeToChannel(channel.id)` (`Client.js:2533`, boolean → throw on false) | **S** | Channel subscribe-by-invite parity with Baileys. Must be verified against a live session — the previous one-step call was a phantom (it passed the invite code where a channel id belongs and fabricated the returned Channel). |
+
+_✅ #17 `getProduct` — wired on Baileys (#905); see §Catalog / Products / Orders above._
---
@@ -142,14 +145,16 @@ _All Tier-2 items wired (see progress above). Remaining channel work is Tier 3:
These are honestly out of reach of a clean adapter wiring because the installed library exposes no first-class symbol. Listed so operators can plan around them rather than file unactionable bugs.
**baileys (9 cells):**
+
- `getSubscribedChannels` — no enumerate-newsletters query; all 19 newsletter members of `Socket/newsletter.d.ts` address a single newsletter (by jid, by invite key, or by creating one). Needs a raw WMex/app-state hack.
- `getLabels` / `getLabelById` / `getChatLabels` — no label read symbol; only writes (`Types/Label.d.ts` is types-only). Workaround: capture labels from the `messaging-history.set` app-state event into an in-memory cache (relay hack, no on-demand refresh).
- `getChatHistory` — only `fetchMessageHistory` (event-delivered sync token); no synchronous per-chat `fetchMessages`. Needs an OpenWA-side chat-indexed store fed from `messages.upsert` + `messaging-history.set`.
- `getMessageReactions` — no on-demand fetch; reactions only arrive via the `messages.reaction` event. Partial local path: persist each event into the `messageStore`, then read (no historical backfill).
-- `getContactStatus` / `getContactStatuses` — `fetchStatus` returns the *about* text, not 24h stories; stories only surface as `status@broadcast` messages. The engine-level Baileys adapter methods remain unimplemented (`501`); however, the REST API reads are served from the `StatusStoreService` accumulator (see §Status — read above), so API-level parity is shipped.
+- `getContactStatus` / `getContactStatuses` — `fetchStatus` returns the _about_ text, not 24h stories; stories only surface as `status@broadcast` messages. The engine-level Baileys adapter methods remain unimplemented (`501`); however, the REST API reads are served from the `StatusStoreService` accumulator (see §Status — read above), so API-level parity is shipped.
- `sendCatalog` — no catalog-share message type in `AnyMessageContent` (only single `{product}`).
**wwjs (6 cells):**
+
- `getCatalog` / `getProducts` / `getProduct` — no catalog API at all (`index.d.ts` 0 hits; `Product` is inbound-only).
- `sendProduct` — no outbound product content type.
- `sendCatalog` — no outbound catalog content type.
diff --git a/openapi.json b/openapi.json
index 93c7bef42..fb7c85775 100644
--- a/openapi.json
+++ b/openapi.json
@@ -4552,10 +4552,10 @@
],
"responses": {
"501": {
- "description": "Not supported: neither engine implements catalog reads."
+ "description": "Not supported by the active engine: whatsapp-web.js has no catalog API."
}
},
- "summary": "Get business catalog info (not implemented by any engine)",
+ "summary": "Get business catalog info (Baileys engine only)",
"tags": [
"catalog"
]
@@ -4598,10 +4598,10 @@
],
"responses": {
"501": {
- "description": "Not supported: neither engine implements catalog reads."
+ "description": "Not supported by the active engine: whatsapp-web.js has no catalog API."
}
},
- "summary": "List catalog products (not implemented by any engine)",
+ "summary": "List catalog products (Baileys engine only)",
"tags": [
"catalog"
]
@@ -4630,10 +4630,10 @@
],
"responses": {
"501": {
- "description": "Not supported: neither engine implements catalog reads."
+ "description": "Not supported by the active engine: whatsapp-web.js has no catalog API."
}
},
- "summary": "Get a specific product (not implemented by any engine)",
+ "summary": "Get a specific product (Baileys engine only)",
"tags": [
"catalog"
]
@@ -4663,11 +4663,17 @@
}
},
"responses": {
+ "400": {
+ "description": "Product has no image — a product card requires one."
+ },
+ "404": {
+ "description": "Product id not found in the session catalog."
+ },
"501": {
- "description": "Not supported by the active engine: no engine can send product messages."
+ "description": "Not supported by the active engine: whatsapp-web.js cannot send product messages."
}
},
- "summary": "Send a product message (not supported by any engine)",
+ "summary": "Send a product message (Baileys engine only)",
"tags": [
"catalog"
]
diff --git a/src/engine/adapters/baileys-catalog.ts b/src/engine/adapters/baileys-catalog.ts
new file mode 100644
index 000000000..45a126c1f
--- /dev/null
+++ b/src/engine/adapters/baileys-catalog.ts
@@ -0,0 +1,116 @@
+import type { Product as BaileysProduct, WASocket } from '@whiskeysockets/baileys';
+import { Catalog, PaginatedProducts, Product, ProductQueryOptions } from '../interfaces/whatsapp-engine.interface';
+
+/**
+ * Catalog-domain operations extracted from BaileysAdapter (#905). makeBusinessSocket already
+ * exposes getCatalog/getCollections — these are adapter mappings, not library workarounds.
+ * The adapter keeps the public methods as thin forwarders and injects this narrow host surface
+ * via closures, so the delegate never touches lifecycle state directly.
+ */
+export interface BaileysCatalogHost {
+ ensureReady(): void;
+ /** Post-ensureReady socket handle — call host.ensureReady() first. */
+ getSocket(): WASocket;
+ normalizedSelfJid(): string;
+}
+
+/** Fetch page size for the catalog walk; larger pages mean fewer round trips to WhatsApp. */
+const CATALOG_PAGE_SIZE = 50;
+
+export class BaileysCatalog {
+ constructor(private readonly host: BaileysCatalogHost) {}
+
+ /** Post-ensureReady socket handle. */
+ private sock(): WASocket {
+ return this.host.getSocket();
+ }
+
+ /**
+ * Baileys' getCatalog returns products + cursor only; the catalog metadata our Catalog type
+ * expects is synthesized from the first collection (the only named grouping the library
+ * exposes). A business without collections has no catalog to describe — null.
+ */
+ async getCatalog(): Promise<Catalog | null> {
+ this.host.ensureReady();
+ const jid = this.host.normalizedSelfJid();
+ const { collections } = await this.sock().getCollections(jid);
+ const first = collections[0];
+ if (!first) {
+ return null;
+ }
+ const phone = jid.split('@')[0];
+ return {
+ id: first.id,
+ name: first.name,
+ productCount: first.products.length,
+ url: `https://wa.me/c/${phone}`,
+ };
+ }
+
+ async getProducts(options: ProductQueryOptions = {}): Promise<PaginatedProducts> {
+ const all = (await this.fetchAllProducts()).map(mapProduct);
+ const page = options.page ?? 1;
+ const limit = options.limit ?? 20;
+ return {
+ products: all.slice((page - 1) * limit, page * limit),
+ pagination: {
+ page,
+ limit,
+ total: all.length,
+ totalPages: Math.ceil(all.length / limit),
+ },
+ };
+ }
+
+ async getProduct(productId: string): Promise<Product | null> {
+ const found = (await this.fetchAllProducts()).find(p => p.id === productId);
+ return found ? mapProduct(found) : null;
+ }
+
+ /**
+ * ponytail: walks the whole cursor chain on every call (no cursor cache), so page N costs the
+ * full catalog. WhatsApp caps catalogs at ~500 products; if profiling shows the walk matters,
+ * cache pages keyed by cursor and serve offsets from the cache.
+ */
+ private async fetchAllProducts(): Promise<BaileysProduct[]> {
+ this.host.ensureReady();
+ const jid = this.host.normalizedSelfJid();
+ const products: BaileysProduct[] = [];
+ let cursor: string | undefined;
+ do {
+ const page = await this.sock().getCatalog({ jid, limit: CATALOG_PAGE_SIZE, cursor });
+ products.push(...page.products);
+ cursor = page.nextPageCursor;
+ } while (cursor);
+ return products;
+ }
+}
+
+/**
+ * Map Baileys' product node onto the engine-neutral Product: priceFormatted is synthesized
+ * (Baileys carries only price + currency), the imageUrls map collapses to its first URL, and
+ * availability is the library's 'in stock' literal.
+ */
+function mapProduct(p: BaileysProduct): Product {
+ return {
+ id: p.id,
+ name: p.name,
+ description: p.description || undefined,
+ price: p.price,
+ currency: p.currency,
+ priceFormatted: formatPrice(p.price, p.currency),
+ imageUrl: Object.values(p.imageUrls ?? {})[0],
+ url: p.url ?? '',
+ isAvailable: p.availability === 'in stock',
+ retailerId: p.retailerId,
+ };
+}
+
+function formatPrice(price: number, currency: string): string {
+ try {
+ return new Intl.NumberFormat('en', { style: 'currency', currency }).format(price);
+ } catch {
+ // Unknown/invalid ISO currency code — Intl throws RangeError; fall back to a plain pair.
+ return `${currency} ${price}`;
+ }
+}
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.ts
index 6a74b88e6..78a7231e9 100644
--- a/src/engine/adapters/baileys-messaging.ts
+++ b/src/engine/adapters/baileys-messaging.ts
@@ -9,10 +9,12 @@ import {
MediaInput,
MessageResult,
PollInput,
+ Product,
} from '../interfaces/whatsapp-engine.interface';
import { toEngineParticipants } from './baileys-groups';
import { buildVCard } from './vcard';
import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';
+import { BadRequestException } from '@nestjs/common';
import { EngineRefusedError } from '../../common/errors/engine-refused.error';
import { MessageNotFoundError } from '../../common/errors/message-not-found.error';
import { type createLogger } from '../../common/services/logger.service';
@@ -29,6 +31,7 @@ export interface BaileysMessagingHost {
readonly logger: ReturnType<typeof createLogger>;
toNeutralJid(jid: string): string;
toEngineJid(jid: string): string;
+ normalizedSelfJid(): string;
/** The chat's cached disappearing-messages timer (#473), or undefined when none is known. */
getEphemeralExpiration(chatId: string): number | undefined;
/** Baileys timestamps are `number | Long`; normalize to unix seconds. */
@@ -126,6 +129,34 @@ export class BaileysMessaging {
}
}
+ /**
+ * Send a native product card (#905). Baileys has no catalog-lookup-then-send helper, so the
+ * adapter resolves the Product first; here it becomes a {product} message whose snapshot is
+ * priced in thousandths (priceAmount1000) and whose image is handed to Baileys as a URL upload.
+ * The card needs an image — a product whose catalog entry has none cannot be sent this way.
+ */
+ async sendProductMessage(chatId: string, product: Product, body?: string): Promise<MessageResult> {
+ this.host.ensureReady();
+ if (!product.imageUrl) {
+ throw new BadRequestException(`Product ${product.id} has no image — a product card requires one`);
+ }
+ const content: AnyMessageContent = {
+ product: {
+ productId: product.id,
+ title: product.name,
+ description: product.description,
+ currencyCode: product.currency,
+ priceAmount1000: Math.round(product.price * 1000),
+ retailerId: product.retailerId,
+ url: product.url || undefined,
+ productImage: { url: product.imageUrl },
+ },
+ businessOwnerJid: this.host.toEngineJid(this.host.normalizedSelfJid()),
+ body,
+ };
+ return this.sendContent(chatId, content);
+ }
+
async sendImageMessage(chatId: string, media: MediaInput): Promise<MessageResult> {
this.host.ensureReady();
const { data, mimetype } = await resolveMediaBuffer(media);
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 786b08fd9..1fecc0b19 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -54,6 +54,8 @@ class FakeSock extends EventEmitter {
public addChatLabel = jest.fn().mockResolvedValue(undefined);
public removeChatLabel = jest.fn().mockResolvedValue(undefined);
public newsletterMetadata = jest.fn();
+ public getCatalog = jest.fn();
+ public getCollections = jest.fn();
public newsletterFollow = jest.fn().mockResolvedValue(undefined);
public newsletterUnfollow = jest.fn().mockResolvedValue(undefined);
public rejectCall = jest.fn().mockResolvedValue(undefined);
@@ -106,6 +108,7 @@ jest.mock('@whiskeysockets/baileys', () => ({
}));
import { HttpsProxyAgent } from 'https-proxy-agent';
+import { NotFoundException, BadRequestException } from '@nestjs/common';
import { SocksProxyAgent } from 'socks-proxy-agent';
import { BaileysAdapter, createProxyAgent } from './baileys.adapter';
import {
@@ -3811,3 +3814,163 @@ describe('BaileysAdapter proxy support', () => {
expect(makeWASocketMock()).not.toHaveBeenCalled();
});
});
+
+describe('BaileysAdapter catalog (#905)', () => {
+ const selfUser = { id: '628999:[email protected]', name: 'Me' };
+
+ const baileysProduct = (over: Record<string, unknown> = {}) => ({
+ id: 'p1',
+ name: 'Coffee',
+ description: 'Beans',
+ price: 1500,
+ currency: 'USD',
+ imageUrls: { requested: 'https://img.example/x.jpg' },
+ reviewStatus: { whatsapp: 'approved' },
+ availability: 'in stock',
+ retailerId: 'SKU1',
+ url: 'https://shop.example/p1',
+ isHidden: false,
+ ...over,
+ });
+
+ beforeEach(() => {
+ fakeSock.user = undefined;
+ fakeSock.signalRepository = undefined;
+ fakeSock.resetEmitter();
+ jest.clearAllMocks();
+ });
+
+ const ready = async (): Promise<BaileysAdapter> => {
+ const adapter = newAdapter();
+ await adapter.initialize({});
+ fakeSock.user = selfUser;
+ fakeSock.fire('connection.update', { connection: 'open' });
+ return adapter;
+ };
+
+ it('getCatalog maps the first collection to catalog metadata', async () => {
+ const adapter = await ready();
+ fakeSock.getCollections.mockResolvedValue({
+ collections: [
+ {
+ id: 'coll-1',
+ name: 'Best Sellers',
+ products: [baileysProduct(), baileysProduct({ id: 'p2' })],
+ status: { status: 'ok', canAppeal: false },
+ },
+ ],
+ });
+
+ await expect(adapter.getCatalog()).resolves.toEqual({
+ id: 'coll-1',
+ name: 'Best Sellers',
+ productCount: 2,
+ url: 'https://wa.me/c/628999',
+ });
+ expect(fakeSock.getCollections).toHaveBeenCalledWith('[email protected]');
+ });
+
+ it('getCatalog returns null when the business has no collections', async () => {
+ const adapter = await ready();
+ fakeSock.getCollections.mockResolvedValue({ collections: [] });
+
+ await expect(adapter.getCatalog()).resolves.toBeNull();
+ });
+
+ it('getProducts walks the catalog cursor and slices the requested page', async () => {
+ const adapter = await ready();
+ fakeSock.getCatalog
+ .mockResolvedValueOnce({ products: [baileysProduct(), baileysProduct({ id: 'p2' })], nextPageCursor: 'C2' })
+ .mockResolvedValueOnce({ products: [baileysProduct({ id: 'p3' })], nextPageCursor: undefined });
+
+ const res = await adapter.getProducts({ page: 2, limit: 2 });
+
+ expect(res.products.map(p => p.id)).toEqual(['p3']);
+ expect(res.pagination).toEqual({ page: 2, limit: 2, total: 3, totalPages: 2 });
+ expect(fakeSock.getCatalog).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({ jid: '[email protected]', cursor: undefined }),
+ );
+ expect(fakeSock.getCatalog).toHaveBeenNthCalledWith(2, expect.objectContaining({ cursor: 'C2' }));
+ });
+
+ it('getProducts maps the Baileys product shape onto Product', async () => {
+ const adapter = await ready();
+ fakeSock.getCatalog.mockResolvedValue({ products: [baileysProduct()], nextPageCursor: undefined });
+
+ const { products } = await adapter.getProducts({ page: 1, limit: 10 });
+
+ expect(products[0]).toEqual({
+ id: 'p1',
+ name: 'Coffee',
+ description: 'Beans',
+ price: 1500,
+ currency: 'USD',
+ priceFormatted: '$1,500.00',
+ imageUrl: 'https://img.example/x.jpg',
+ url: 'https://shop.example/p1',
+ isAvailable: true,
+ retailerId: 'SKU1',
+ });
+ });
+
+ it('getProduct returns the product with the matching id', async () => {
+ const adapter = await ready();
+ fakeSock.getCatalog.mockResolvedValue({
+ products: [baileysProduct(), baileysProduct({ id: 'p2', name: 'Tea' })],
+ nextPageCursor: undefined,
+ });
+
+ const res = await adapter.getProduct('p2');
+
+ expect(res?.id).toBe('p2');
+ expect(res?.name).toBe('Tea');
+ });
+
+ it('getProduct returns null for an unknown id', async () => {
+ const adapter = await ready();
+ fakeSock.getCatalog.mockResolvedValue({ products: [baileysProduct()], nextPageCursor: undefined });
+
+ await expect(adapter.getProduct('nope')).resolves.toBeNull();
+ });
+
+ it('sendProduct sends a product message built from the catalog entry', async () => {
+ const adapter = await ready();
+ fakeSock.getCatalog.mockResolvedValue({ products: [baileysProduct()], nextPageCursor: undefined });
+ fakeSock.sendMessage.mockResolvedValue({ key: { id: 'M1' }, messageTimestamp: 1700000005 });
+
+ const res = await adapter.sendProduct('[email protected]', 'p1', 'check this');
+
+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', {
+ product: {
+ productId: 'p1',
+ title: 'Coffee',
+ description: 'Beans',
+ currencyCode: 'USD',
+ priceAmount1000: 1500000,
+ retailerId: 'SKU1',
+ url: 'https://shop.example/p1',
+ productImage: { url: 'https://img.example/x.jpg' },
+ },
+ businessOwnerJid: '[email protected]',
+ body: 'check this',
+ });
+ expect(res).toEqual({ id: 'M1', timestamp: 1700000005 });
+ });
+
+ it('sendProduct rejects NotFound when the product id is unknown', async () => {
+ const adapter = await ready();
+ fakeSock.getCatalog.mockResolvedValue({ products: [baileysProduct()], nextPageCursor: undefined });
+
+ await expect(adapter.sendProduct('[email protected]', 'nope')).rejects.toThrow(NotFoundException);
+ expect(fakeSock.sendMessage).not.toHaveBeenCalled();
+ });
+
+ it('sendProduct rejects BadRequest when the product has no image', async () => {
+ const adapter = await ready();
+ fakeSock.getCatalog.mockResolvedValue({ products: [baileysProduct({ imageUrls: {} })], nextPageCursor: undefined });
+
+ await expect(adapter.sendProduct('[email protected]', 'p1')).rejects.toThrow(BadRequestException);
+ expect(fakeSock.sendMessage).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 47bca7187..8c15ee8f5 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -2,6 +2,7 @@ import * as path from 'path';
import type * as BaileysLib from '@whiskeysockets/baileys';
import type { WASocket } from '@whiskeysockets/baileys';
import { BaileysChannels } from './baileys-channels';
+import { BaileysCatalog } from './baileys-catalog';
import { BaileysContacts } from './baileys-contacts';
import { BaileysEvents } from './baileys-events';
import { BaileysGroups } from './baileys-groups';
@@ -38,6 +39,7 @@ import {
StatusPostOptions,
} from '../interfaces/whatsapp-engine.interface';
import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';
+import { NotFoundException } from '@nestjs/common';
import { createLogger } from '../../common/services/logger.service';
import { BaileysAdapterConfig } from '../types/baileys.types';
import { BaileysSessionStore } from './baileys-session-store';
@@ -65,6 +67,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
private readonly contacts: BaileysContacts;
private readonly statusOps: BaileysStatus;
private readonly channels: BaileysChannels;
+ private readonly catalog: BaileysCatalog;
private readonly history: BaileysHistory;
private readonly events: BaileysEvents;
private readonly lifecycle: BaileysLifecycle;
@@ -142,6 +145,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
logger: this.logger,
toNeutralJid: jid => this.sessionStore.toNeutralJid(jid),
toEngineJid: jid => this.sessionStore.toEngineJid(jid),
+ normalizedSelfJid: () => this.normalizedSelfJid(),
getEphemeralExpiration: chatId => this.sessionStore.getEphemeralExpiration(chatId),
toUnixSeconds,
loadLib: () => this.loadLib(),
@@ -172,6 +176,11 @@ export class BaileysAdapter implements IWhatsAppEngine {
ensureReady: () => this.ensureReady(),
getSocket: () => this.sock!,
});
+ this.catalog = new BaileysCatalog({
+ ensureReady: () => this.ensureReady(),
+ getSocket: () => this.sock!,
+ normalizedSelfJid: () => this.normalizedSelfJid(),
+ });
this.history = new BaileysHistory({
getSocket: () => this.sock!,
logger: this.logger,
@@ -531,17 +540,23 @@ export class BaileysAdapter implements IWhatsAppEngine {
return this.statusOps.deleteStatus(statusId);
}
getCatalog(): Promise<Catalog | null> {
- return this.unsupported('getCatalog');
+ return this.catalog.getCatalog();
}
- getProducts(_options?: ProductQueryOptions): Promise<PaginatedProducts> {
- return this.unsupported('getProducts');
+ getProducts(options?: ProductQueryOptions): Promise<PaginatedProducts> {
+ return this.catalog.getProducts(options);
}
- getProduct(_productId: string): Promise<Product | null> {
- return this.unsupported('getProduct');
+ getProduct(productId: string): Promise<Product | null> {
+ return this.catalog.getProduct(productId);
}
- sendProduct(_chatId: string, _productId: string, _body?: string): Promise<MessageResult> {
- return this.unsupported('sendProduct');
+ async sendProduct(chatId: string, productId: string, body?: string): Promise<MessageResult> {
+ const product = await this.catalog.getProduct(productId);
+ if (!product) {
+ throw new NotFoundException(`Product ${productId} not found in the session catalog`);
+ }
+ return this.messaging.sendProductMessage(chatId, product, body);
}
+ // No catalog-level message primitive exists in Baileys (only the single-product {product}
+ // content), so sendCatalog stays a documented library limitation.
sendCatalog(_chatId: string, _body?: string): Promise<MessageResult> {
return this.unsupported('sendCatalog');
}
diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.ts
index d12886dae..b4d9ca6c9 100644
--- a/src/engine/engine-capability-matrix.ts
+++ b/src/engine/engine-capability-matrix.ts
@@ -86,9 +86,9 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {
forwardMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
getCatalog: {
wwjs: { status: 'not-available', rootCause: 'library-limitation' },
- baileys: { status: 'not-available', rootCause: 'adapter-gap' },
+ baileys: { status: 'supported' },
evidence:
- 'baileys Socket/business.d.ts:7 getCatalog({jid,limit,cursor}) + getCollections (business.d.ts:11) — adapter unwired (returns Product[]+cursor, not Catalog metadata; medium-confidence shape synthesis); wwjs index.d.ts has NO Client.getCatalog (0 hits) — adapter throws EngineNotSupportedError (was a phantom null stub)',
+ 'baileys getCollections(jid) (Socket/business.d.ts:11) → first collection synthesized into Catalog metadata at BaileysCatalog (adapters/baileys-catalog.ts; #905); wwjs index.d.ts has NO Client.getCatalog (0 hits) — adapter throws EngineNotSupportedError',
},
getChannelById: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
getChannelMessages: {
@@ -148,15 +148,15 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {
getPhoneNumber: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
getProduct: {
wwjs: { status: 'not-available', rootCause: 'library-limitation' },
- baileys: { status: 'not-available', rootCause: 'adapter-gap' },
+ baileys: { status: 'supported' },
evidence:
- 'baileys only getCatalog (Socket/business.d.ts:7); getProduct = getCatalog then find-by-id (compose-and-filter, loads whole page; medium-confidence); wwjs no Client.getProduct — only page-internal getProductMetadata (Utils.js:1253), not a public Client fn — adapter throws EngineNotSupportedError (was a phantom null stub)',
+ 'baileys getCatalog cursor-walk then find-by-id (compose-and-filter over the full catalog; adapters/baileys-catalog.ts; #905); wwjs no Client.getProduct — only page-internal getProductMetadata (Utils.js:1253), not a public Client fn — adapter throws EngineNotSupportedError',
},
getProducts: {
wwjs: { status: 'not-available', rootCause: 'library-limitation' },
- baileys: { status: 'not-available', rootCause: 'adapter-gap' },
+ baileys: { status: 'supported' },
evidence:
- 'baileys Socket/business.d.ts:7 getCatalog({jid,limit,cursor}) → {products, nextPageCursor} — adapter unwired; wwjs no Client.getProducts in index.d.ts (0 hits) — adapter throws EngineNotSupportedError (was a phantom empty-list stub)',
+ 'baileys getCatalog({jid,limit,cursor}) (Socket/business.d.ts:7) cursor-walked in full, then page/limit sliced at the adapter (adapters/baileys-catalog.ts; #905); wwjs no Client.getProducts in index.d.ts (0 hits) — adapter throws EngineNotSupportedError',
},
getProfilePicture: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
getPushName: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
@@ -220,9 +220,9 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {
sendPollMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
sendProduct: {
wwjs: { status: 'not-available', rootCause: 'library-limitation' },
- baileys: { status: 'not-available', rootCause: 'adapter-gap' },
+ baileys: { status: 'supported' },
evidence:
- 'baileys AnyRegularMessageContent {product: WASendableProduct} (Types/Message.d.ts:203) built in messages.js:397 — adapter unwired (2-step: getCatalog lookup for image/title/price THEN sendMessage); wwjs no Client.sendProduct — Product/Order are inbound-only parsers',
+ 'baileys AnyRegularMessageContent {product: WASendableProduct} (Types/Message.d.ts:203) — adapter resolves the product via getCatalog then sends the snapshot with businessOwnerJid=self (adapters/baileys-messaging.ts; #905); wwjs no Client.sendProduct — Product/Order are inbound-only parsers',
},
sendSeen: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
sendStickerMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
diff --git a/src/modules/catalog/catalog.controller.ts b/src/modules/catalog/catalog.controller.ts
index 35997790e..fea195e8b 100644
--- a/src/modules/catalog/catalog.controller.ts
+++ b/src/modules/catalog/catalog.controller.ts
@@ -11,30 +11,30 @@ export class CatalogController {
constructor(private readonly catalogService: CatalogService) {}
@Get('catalog')
- @ApiOperation({ summary: 'Get business catalog info (not implemented by any engine)' })
+ @ApiOperation({ summary: 'Get business catalog info (Baileys engine only)' })
@ApiResponse({
status: 501,
- description: 'Not supported: neither engine implements catalog reads.',
+ description: 'Not supported by the active engine: whatsapp-web.js has no catalog API.',
})
async getCatalog(@Param('sessionId') sessionId: string) {
return this.catalogService.getCatalog(sessionId);
}
@Get('catalog/products')
- @ApiOperation({ summary: 'List catalog products (not implemented by any engine)' })
+ @ApiOperation({ summary: 'List catalog products (Baileys engine only)' })
@ApiResponse({
status: 501,
- description: 'Not supported: neither engine implements catalog reads.',
+ description: 'Not supported by the active engine: whatsapp-web.js has no catalog API.',
})
async getProducts(@Param('sessionId') sessionId: string, @Query() query: ProductQueryDto) {
return this.catalogService.getProducts(sessionId, query.page, query.limit);
}
@Get('catalog/products/:productId')
- @ApiOperation({ summary: 'Get a specific product (not implemented by any engine)' })
+ @ApiOperation({ summary: 'Get a specific product (Baileys engine only)' })
@ApiResponse({
status: 501,
- description: 'Not supported: neither engine implements catalog reads.',
+ description: 'Not supported by the active engine: whatsapp-web.js has no catalog API.',
})
async getProduct(@Param('sessionId') sessionId: string, @Param('productId') productId: string) {
return this.catalogService.getProduct(sessionId, productId);
@@ -42,8 +42,13 @@ export class CatalogController {
@Post('messages/send-product')
@RequireRole(ApiKeyRole.OPERATOR)
- @ApiOperation({ summary: 'Send a product message (not supported by any engine)' })
- @ApiResponse({ status: 501, description: 'Not supported by the active engine: no engine can send product messages.' })
+ @ApiOperation({ summary: 'Send a product message (Baileys engine only)' })
+ @ApiResponse({ status: 404, description: 'Product id not found in the session catalog.' })
+ @ApiResponse({ status: 400, description: 'Product has no image — a product card requires one.' })
+ @ApiResponse({
+ status: 501,
+ description: 'Not supported by the active engine: whatsapp-web.js cannot send product messages.',
+ })
async sendProduct(@Param('sessionId') sessionId: string, @Body() dto: SendProductDto) {
return this.catalogService.sendProduct(sessionId, dto.chatId, dto.productId, dto.body);
}