chat-adapter-wwebjs 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # chat-adapter-wwebjs
2
2
 
3
+ ## 0.1.2
4
+
5
+ ### Added
6
+
7
+ - Messages that arrived while the session was down are delivered once it is back, in order and each once, up to `catchUpMs` old. WhatsApp Web loads them without firing an event, so they were lost.
8
+ - Audio goes out as a voice note, played inline with a waveform; `voiceNotes: false` sends it as a file.
9
+ - `numberedActions()` lists a card's buttons and select options by number, and a reply with one reaches `onAction`. WhatsApp Web cannot send buttons, so they used to vanish. It is the first of `addons`, layers with hooks for how cards are sent and messages received.
10
+ - Chromium starts with `RECOMMENDED_CHROMIUM_ARGS` — one renderer process, no GPU, no component updates — before any `puppeteer.args` of your own; `recommendedArgs: false` leaves them out.
11
+
12
+ ### Fixed
13
+
14
+ - A SIGTERM never ended the process: Puppeteer closed the browser and kept the process alive, and the adapter read the closed browser as a crash and opened a new one. Every session now closes on SIGINT, SIGTERM and SIGHUP, and the signal then ends the process unless the app handles it; `handleSignals: false` leaves signals alone.
15
+
16
+ ## 0.1.1
17
+
18
+ ### Fixed
19
+
20
+ - `connectTimeoutMs` also counted the wait for a QR scan, so a first pairing gave up after 2 minutes and the QR on screen stopped working. Once a QR or pairing code is shown, the connection waits on the person scanning it.
21
+
3
22
  ## 0.1.0
4
23
 
5
24
  Initial release, tested against live WhatsApp in DMs and groups through `chat-adapter-remote`.
package/README.md CHANGED
@@ -70,48 +70,54 @@ None. This adapter takes no credentials from the environment — a WhatsApp Web
70
70
 
71
71
  ## Configuration
72
72
 
73
- | Field | Type | Default | Description |
74
- | -------------------- | --------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
75
- | `adapterName` | `string` | `"wwebjs"` | Adapter identity and thread-ID prefix. Must match the key it is registered under in `Chat`, and must not contain `:`. |
76
- | `client` | `Client` | — | An existing whatsapp-web.js client to drive. When omitted, one is built from `clientOptions`. |
77
- | `clientOptions` | `ClientOptions` | `{}` | Options for the client the adapter builds — `authStrategy`, `puppeteer`, `webVersionCache`, and so on. Ignored when `client` is set. |
78
- | `connectTimeoutMs` | `number` | 2 minutes | How long opening the session may take before it is abandoned and, with `reconnect`, tried again. |
79
- | `logger` | `Logger` | `ConsoleLogger` | Logger used until `Chat` hands over its own. |
80
- | `markSeen` | `boolean` | `false` | Send a read receipt for every inbound message as it arrives. |
81
- | `maxMediaBytes` | `number` | 64 MB | Largest media read into memory, inbound or fetched from a `url`. Bytes are counted as they arrive, whatever size the sender claims. |
82
- | `onPairingCode` | `(code: string) => unknown` | — | Receives the 8-character pairing code when `phoneNumber` is set. |
83
- | `onQR` | `(qr: string) => unknown` | — | Receives the QR string during login. Render it with `qrcode-terminal` or similar. |
84
- | `phoneNumber` | `string` | — | Log in with a pairing code instead of a QR. E.164 without the leading `+`. |
85
- | `receiveOwnMessages` | `boolean` | `false` | Pass what the paired account did — its messages, edits, deletes and reactions — to the Chat SDK, which still skips most of its own. |
86
- | `reconnect` | `boolean` | `true` | Open the session again when WhatsApp drops it, backing off from 5 seconds to 5 minutes. A logout is never retried. |
87
- | `watchdogIntervalMs` | `number \| false` | 1 minute | How often a connected session is asked whether WhatsApp still answers; two failed checks count as a disconnect. |
88
- | `userName` | `string` | `"wwebjs-bot"` | Bot display name. When unset, the account's WhatsApp push name is adopted once the session is ready. |
73
+ | Field | Type | Default | Description |
74
+ | -------------------- | --------------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
75
+ | `adapterName` | `string` | `"wwebjs"` | Adapter identity and thread-ID prefix. Must match the key it is registered under in `Chat`, and must not contain `:`. |
76
+ | `addons` | `WWebJSAddon[]` | `[]` | Layers over how cards are sent and messages received, such as `numberedActions()`. |
77
+ | `catchUpMs` | `number \| false` | 1 day | Messages that arrived while the session was down are delivered once it is back, up to this old, in order and each once. |
78
+ | `client` | `Client` | — | An existing whatsapp-web.js client to drive. When omitted, one is built from `clientOptions`. |
79
+ | `clientOptions` | `ClientOptions` | `{}` | Options for the client the adapter builds — `authStrategy`, `puppeteer`, `webVersionCache`, and so on. `puppeteer.args` come after the recommended ones, so yours win. Ignored when `client` is set. |
80
+ | `connectTimeoutMs` | `number` | 2 minutes | How long opening the session may take before it is abandoned and, with `reconnect`, tried again. Once a QR or pairing code is shown, it waits for the scan. |
81
+ | `handleSignals` | `boolean` | `true` | Close the session on SIGINT, SIGTERM and SIGHUP, then let the signal end the process — unless your app listens for it and shuts down itself. |
82
+ | `logger` | `Logger` | `ConsoleLogger` | Logger used until `Chat` hands over its own. |
83
+ | `markSeen` | `boolean` | `false` | Send a read receipt for every inbound message as it arrives. |
84
+ | `maxMediaBytes` | `number` | 64 MB | Largest media read into memory, inbound or fetched from a `url`. Bytes are counted as they arrive, whatever size the sender claims. |
85
+ | `onPairingCode` | `(code: string) => unknown` | — | Receives the 8-character pairing code when `phoneNumber` is set. |
86
+ | `onQR` | `(qr: string) => unknown` | — | Receives the QR string during login. Render it with `qrcode-terminal` or similar. |
87
+ | `phoneNumber` | `string` | — | Log in with a pairing code instead of a QR. E.164 without the leading `+`. |
88
+ | `receiveOwnMessages` | `boolean` | `false` | Pass what the paired account did — its messages, edits, deletes and reactions — to the Chat SDK, which still skips most of its own. |
89
+ | `recommendedArgs` | `boolean` | `true` | Start Chromium with `RECOMMENDED_CHROMIUM_ARGS`: one renderer process, no GPU, no component updates. |
90
+ | `reconnect` | `boolean` | `true` | Open the session again when WhatsApp drops it, backing off from 5 seconds to 5 minutes. A logout is never retried. |
91
+ | `watchdogIntervalMs` | `number \| false` | 1 minute | How often a connected session is asked whether WhatsApp still answers; two failed checks count as a disconnect. |
92
+ | `userName` | `string` | `"wwebjs-bot"` | Bot display name. When unset, the account's WhatsApp push name is adopted once the session is ready. |
93
+ | `voiceNotes` | `boolean` | `true` | Send audio as a voice note, played inline with a waveform, rather than as a file. |
89
94
 
90
95
  ## Platform setup
91
96
 
92
97
  1. Install a Chromium that Puppeteer can launch. The bundled download covers most machines; on slim Linux images install the usual shared libraries, or point `clientOptions.puppeteer.executablePath` at your own browser.
93
98
  2. Pick an auth strategy. `LocalAuth` stores the session in a directory; `RemoteAuth` stores it in a database you provide. Persist it — without one you re-scan on every start.
94
99
  3. Start the process and link the device: scan the QR from `onQR`, or set `phoneNumber` and enter the code from `onPairingCode` under WhatsApp → **Linked devices** → **Link with phone number**.
95
- 4. Keep the process alive. This is a live browser session, not a webhook — `handleWebhook` always answers `501`.
100
+ 4. Keep the process alive. This is a live browser session, not a webhook — `handleWebhook` always answers `501`. A SIGTERM closes the browser and ends the process, so `docker stop` is clean; with your own handler, call `chat.shutdown()` or the adapter's `disconnect()` and exit when you are done.
96
101
 
97
102
  ## Features
98
103
 
99
104
  Everything in the Chat SDK `Adapter` interface that WhatsApp can express:
100
105
 
101
- | Capability | Notes |
102
- | ------------------- | -------------------------------------------------------------------------------------------- |
103
- | Post, edit, delete | Editing is WhatsApp's own 15-minute window on your own messages; delete is for everyone. |
104
- | Reply | `thread.reply()` produces a native quoted bubble. |
105
- | Fetch messages | Real history with forward and backward pagination — see [History](#history). |
106
- | Fetch a message | By ID, via `getMessageById`. |
107
- | Reactions | Send, remove, and receive, normalized to the SDK's `EmojiValue`. |
108
- | Typing and presence | `startTyping()` composes, `startTyping("recording")` records, `endTyping()` clears. |
109
- | Read receipts | `thread.markAsRead()`, or `markSeen: true` for every inbound message. |
110
- | Attachments | Images, video, audio, voice notes, stickers and documents, in and out, downloaded on demand. |
111
- | Mentions | `thread.mentionUser(id)` renders `@number` and registers the mention with WhatsApp. |
112
- | Threads, channels | Metadata, group member counts, DMs opened by phone number, contact lookup. |
113
- | Edits and deletes | `onMessageUpdated` carries the body it replaced; `onMessageDeleted` carries the original. |
114
- | Group joins | Bridged to `onMemberJoinedChannel`. |
106
+ | Capability | Notes |
107
+ | ------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
108
+ | Post, edit, delete | Editing is WhatsApp's own 15-minute window on your own messages; delete is for everyone. |
109
+ | Reply | `thread.reply()` produces a native quoted bubble. |
110
+ | Fetch messages | Real history with forward and backward pagination — see [History](#history). |
111
+ | Fetch a message | By ID, via `getMessageById`. |
112
+ | Reactions | Send, remove, and receive, normalized to the SDK's `EmojiValue`. |
113
+ | Typing and presence | `startTyping()` composes, `startTyping("recording")` records, `endTyping()` clears. |
114
+ | Read receipts | `thread.markAsRead()`, or `markSeen: true` for every inbound message. |
115
+ | Attachments | Images, video, audio, voice notes, stickers and documents, in and out, downloaded on demand. Audio goes out as a voice note. |
116
+ | Cards | Sent as text; with `numberedActions()` their buttons and selects work — see [Card actions](#card-actions). |
117
+ | Mentions | `thread.mentionUser(id)` renders `@number` and registers the mention with WhatsApp. |
118
+ | Threads, channels | Metadata, group member counts, DMs opened by phone number, contact lookup. |
119
+ | Edits and deletes | `onMessageUpdated` carries the body it replaced; `onMessageDeleted` carries the original. |
120
+ | Group joins | Bridged to `onMemberJoinedChannel`. |
115
121
 
116
122
  WhatsApp-specific extras live on the adapter, past the shared interface:
117
123
 
@@ -145,6 +151,22 @@ Backward (the default) asks WhatsApp for `offset + limit` messages and returns t
145
151
 
146
152
  Markdown is converted to WhatsApp's markup: `*bold*`, `_italic_`, `~strikethrough~`, `` `code` ``, fenced blocks, `>` quotes and lists. WhatsApp has no link syntax, so links render as `text (url)`, and no tables, so tables render as ASCII inside a code block. Cards fall back to text.
147
153
 
154
+ ### Card actions
155
+
156
+ WhatsApp Web cannot send buttons, so a card's buttons are dropped from its text. Add `numberedActions()` and they are listed by number instead, select options included, and a reply with a number — or a label — reaches `onAction` as a click would. Link buttons keep their URL; a button that opens a modal is left out, since WhatsApp has none.
157
+
158
+ ```ts
159
+ import { createWWebJSAdapter, numberedActions } from "chat-adapter-wwebjs";
160
+
161
+ const whatsapp = createWWebJSAdapter({ addons: [numberedActions()] });
162
+
163
+ bot.onAction("approve", async (event) => {
164
+ await event.thread?.post(`Approved by ${event.user.userName}`);
165
+ });
166
+ ```
167
+
168
+ The options of a thread's latest card answer for a day (`ttlMs`) and live in the Chat SDK state. The reply that picked one is not delivered as a message unless `keepMessage` is set. An addon is a plain object with `renderCard`, `cardSent` and `onMessage` hooks, so other layers fit the same way.
169
+
148
170
  ### Multiple accounts
149
171
 
150
172
  Give each adapter its own `adapterName`, matching the key it is registered under. It becomes the thread-ID prefix, so `sales:…` and `support:…` never collide on one `Chat` instance.
@@ -175,7 +197,7 @@ const bot = new Chat({ adapters: { sales, support }, state, userName: "my-bot" }
175
197
  - **`adapter.connection` tells where the session stands** — `connected`, `reconnecting`, `logged_out` and so on — for a health check, such as `chat-adapter-remote`'s `healthy: () => adapter.connection === "connected"`.
176
198
  - **Statuses, broadcast lists and WhatsApp's own notifications never reach your handlers.**
177
199
  - **`forwardMessage` and event call links fail on current WhatsApp Web.** whatsapp-web.js still calls modules WhatsApp has renamed; both return once it catches up. `sendEvent` without `callType` attaches no link and works.
178
- - **Messages received while the session was down are not replayed.** WhatsApp Web syncs them into history, where `fetchMessages` finds them, but no event fires for them.
200
+ - **Messages received while the session was down are caught up from history** once it is back, since WhatsApp Web fires no event for them. The position is kept in the Chat SDK state, so a restart starts where the last process stopped; the first run starts counting and replays nothing older. A chat outside the 100 most recent, or more than 50 messages behind, is not caught up in full.
179
201
 
180
202
  ## License
181
203
 
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Attachment, FileUpload, AdapterPostableMessage, Logger, Author, Adapter, LockScope, ChatInstance, ChannelVisibility, WebhookOptions, Message as Message$1, RawMessage, EmojiValue, FetchOptions, FetchResult, ThreadInfo, ChannelInfo, ListThreadsResult, UserInfo, FormattedContent, BaseFormatConverter, Root } from 'chat';
1
+ import { Attachment, FileUpload, AdapterPostableMessage, CardElement, ChatInstance, Message as Message$1, Logger, Author, Adapter, LockScope, ChannelVisibility, WebhookOptions, RawMessage, EmojiValue, FetchOptions, FetchResult, ThreadInfo, ChannelInfo, ListThreadsResult, UserInfo, FormattedContent, BaseFormatConverter, Root } from 'chat';
2
2
  import { MessageMedia, Message, Client, ClientOptions, PollVote, Call, GroupNotification } from 'whatsapp-web.js';
3
3
 
4
4
  /** Describe an inbound message's media as a Chat SDK attachment. */
@@ -15,6 +15,7 @@ declare function toMediaList(message: AdapterPostableMessage, maxBytes?: number)
15
15
  declare function toMedia(source: Attachment | FileUpload, maxBytes?: number): Promise<MessageMedia>;
16
16
  /** WhatsApp renders a caption on every media kind except audio. */
17
17
  declare function isCaptionable(media: MessageMedia): boolean;
18
+ declare function isAudio(media: MessageMedia): boolean;
18
19
 
19
20
  /**
20
21
  * Where the WhatsApp session stands. Only `connected` can send and receive;
@@ -34,19 +35,39 @@ interface WWebJSAdapterConfig {
34
35
  * Must not contain `:`. Defaults to `"wwebjs"`.
35
36
  */
36
37
  adapterName?: string;
38
+ /** Layers that change how cards are sent or messages received; see `numberedActions()`. */
39
+ addons?: WWebJSAddon[];
40
+ /**
41
+ * Messages that arrived while the session was down are delivered once it is
42
+ * back, up to this old, in order and each once. Defaults to 1 day; `false`
43
+ * turns it off.
44
+ */
45
+ catchUpMs?: number | false;
37
46
  /**
38
47
  * An existing whatsapp-web.js client to drive. When omitted the adapter
39
48
  * constructs one from {@link WWebJSAdapterConfig.clientOptions}.
40
49
  */
41
50
  client?: Client;
42
- /** Options for the client the adapter constructs. Ignored when `client` is set. */
51
+ /**
52
+ * Options for the client the adapter constructs, Puppeteer's included.
53
+ * `puppeteer.args` are added after {@link RECOMMENDED_CHROMIUM_ARGS}, so a
54
+ * flag given here wins. Ignored when `client` is set.
55
+ */
43
56
  clientOptions?: ClientOptions;
44
57
  /**
45
58
  * How long opening the session may take before it is abandoned — and, with
46
- * `reconnect`, tried again. whatsapp-web.js itself never gives up. Defaults
47
- * to 2 minutes.
59
+ * `reconnect`, tried again. whatsapp-web.js itself never gives up. Once a QR
60
+ * or pairing code is shown it waits on a person instead, without limit.
61
+ * Defaults to 2 minutes.
48
62
  */
49
63
  connectTimeoutMs?: number;
64
+ /**
65
+ * Close the session on SIGINT, SIGTERM and SIGHUP, then let the signal end
66
+ * the process as it otherwise would — unless the app listens for it, and
67
+ * shuts down itself. Puppeteer alone closes the browser and leaves the
68
+ * process running. Defaults to `true`.
69
+ */
70
+ handleSignals?: boolean;
50
71
  /** Logger instance. Replaced by the Chat SDK logger once initialized. */
51
72
  logger?: Logger;
52
73
  /**
@@ -80,6 +101,11 @@ interface WWebJSAdapterConfig {
80
101
  * reactions. Defaults to `false`.
81
102
  */
82
103
  receiveOwnMessages?: boolean;
104
+ /**
105
+ * Start Chromium with {@link RECOMMENDED_CHROMIUM_ARGS}, which keep it lean
106
+ * and steady in a container. Defaults to `true`.
107
+ */
108
+ recommendedArgs?: boolean;
83
109
  /**
84
110
  * Open the session again when WhatsApp drops it, waiting longer after each
85
111
  * failed attempt. A logout is never retried, since it needs a new pairing.
@@ -95,6 +121,27 @@ interface WWebJSAdapterConfig {
95
121
  watchdogIntervalMs?: number | false;
96
122
  /** Bot display name. Defaults to `"wwebjs-bot"`. */
97
123
  userName?: string;
124
+ /**
125
+ * Send audio as a voice note, played inline with a waveform, rather than as
126
+ * a file. Defaults to `true`.
127
+ */
128
+ voiceNotes?: boolean;
129
+ }
130
+ /** What an addon is handed alongside each card or message. */
131
+ interface WWebJSAddonContext {
132
+ adapter: WWebJSAdapter;
133
+ /** Absent until the Chat SDK has initialized the adapter. */
134
+ chat: ChatInstance | null;
135
+ threadId: string;
136
+ }
137
+ /** A layer over the adapter; every hook is optional. */
138
+ interface WWebJSAddon {
139
+ /** Text for a card in place of its plain fallback; the first addon to answer wins. */
140
+ renderCard?(card: CardElement, context: WWebJSAddonContext): string | undefined;
141
+ /** Called once a card is on WhatsApp, with the id of the message carrying it. */
142
+ cardSent?(card: CardElement, messageId: string, context: WWebJSAddonContext): unknown;
143
+ /** Return `true` to keep an inbound message from reaching the Chat SDK as one. */
144
+ onMessage?(message: Message$1<Message>, context: WWebJSAddonContext): boolean | Promise<boolean>;
98
145
  }
99
146
  /** Delivery state of a sent message, reported by {@link WWebJSAdapter.onAck}. */
100
147
  type WWebJSAckStatus = "delivered" | "error" | "pending" | "played" | "read" | "sent";
@@ -200,6 +247,8 @@ type WWebJSGroupEventHandler = (event: WWebJSGroupEvent) => unknown;
200
247
  /** Handler for poll votes. */
201
248
  type WWebJSPollVoteHandler = (vote: WWebJSPollVote) => unknown;
202
249
 
250
+ /** What a single WhatsApp Web tab can do without, on top of the flags Puppeteer already passes. */
251
+ declare const RECOMMENDED_CHROMIUM_ARGS: string[];
203
252
  declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
204
253
  readonly name: string;
205
254
  readonly lockScope: LockScope;
@@ -222,6 +271,9 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
222
271
  private _state;
223
272
  private _watchdog?;
224
273
  private _strikes;
274
+ private _unsignal?;
275
+ private _seen?;
276
+ private _saving;
225
277
  constructor(config?: WWebJSAdapterConfig);
226
278
  /** Where the session stands; a health check reads `connection === "connected"`. */
227
279
  get connection(): WWebJSConnection;
@@ -333,6 +385,15 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
333
385
  private _open;
334
386
  private _listen;
335
387
  private _onMessage;
388
+ private _claimed;
389
+ private _addons;
390
+ private _context;
391
+ private _seenKey;
392
+ /** Writes run in turn, so an older position never lands after a newer one. */
393
+ private _save;
394
+ private _remember;
395
+ /** WhatsApp Web loads what arrived while the session was down without announcing every message. */
396
+ private _catchUp;
336
397
  private _onEdit;
337
398
  private _onRevoke;
338
399
  private _onReaction;
@@ -359,6 +420,8 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
359
420
  /** Revives a session that died without an event, or a first connection that failed. */
360
421
  private _check;
361
422
  private _render;
423
+ /** The card is already on WhatsApp, so an addon failing here must not fail the send. */
424
+ private _cardSent;
362
425
  private _send;
363
426
  private _sendContent;
364
427
  private _raw;
@@ -415,4 +478,16 @@ declare function extractMentions(text: string): {
415
478
  text: string;
416
479
  };
417
480
 
418
- export { type WWebJSAck, type WWebJSAckHandler, type WWebJSAckStatus, WWebJSAdapter, type WWebJSAdapterConfig, type WWebJSCallHandler, type WWebJSConnection, WWebJSFormatConverter, type WWebJSGroupEvent, type WWebJSGroupEventHandler, type WWebJSGroupParticipant, type WWebJSPollVote, type WWebJSPollVoteHandler, type WWebJSSendEventArgs, type WWebJSSendLocationArgs, type WWebJSSendPollArgs, type WWebJSThreadId, createWWebJSAdapter, download, extractMentions, isCaptionable, isGroupId, isNewsletterId, isUserId, isWWebJSAdapter, requireWWebJSAdapter, toAttachments, toChatId, toMedia, toMediaList, toUser };
481
+ interface NumberedActionsOptions {
482
+ /** Also deliver the reply that picked an option as a message. Defaults to `false`. */
483
+ keepMessage?: boolean;
484
+ /** How long a card's options answer to their number or label. Defaults to 1 day. */
485
+ ttlMs?: number;
486
+ }
487
+ /**
488
+ * WhatsApp Web cannot send buttons, so a card's buttons and select options are
489
+ * listed by number, and a reply with one — or its label — reaches `onAction`.
490
+ */
491
+ declare function numberedActions(options?: NumberedActionsOptions): WWebJSAddon;
492
+
493
+ export { type NumberedActionsOptions, RECOMMENDED_CHROMIUM_ARGS, type WWebJSAck, type WWebJSAckHandler, type WWebJSAckStatus, WWebJSAdapter, type WWebJSAdapterConfig, type WWebJSAddon, type WWebJSAddonContext, type WWebJSCallHandler, type WWebJSConnection, WWebJSFormatConverter, type WWebJSGroupEvent, type WWebJSGroupEventHandler, type WWebJSGroupParticipant, type WWebJSPollVote, type WWebJSPollVoteHandler, type WWebJSSendEventArgs, type WWebJSSendLocationArgs, type WWebJSSendPollArgs, type WWebJSThreadId, createWWebJSAdapter, download, extractMentions, isAudio, isCaptionable, isGroupId, isNewsletterId, isUserId, isWWebJSAdapter, numberedActions, requireWWebJSAdapter, toAttachments, toChatId, toMedia, toMediaList, toUser };
package/dist/index.js CHANGED
@@ -221,7 +221,10 @@ async function toMedia(source, maxBytes = DEFAULT_MAX_MEDIA_BYTES) {
221
221
  );
222
222
  }
223
223
  function isCaptionable(media) {
224
- return !media.mimetype.startsWith("audio/");
224
+ return !isAudio(media);
225
+ }
226
+ function isAudio(media) {
227
+ return media.mimetype.startsWith("audio/");
225
228
  }
226
229
  function mimeTypeOf(filename) {
227
230
  const extension = filename?.split(".").pop()?.toLowerCase();
@@ -265,6 +268,23 @@ async function toBase64(data) {
265
268
  return Buffer.from(await data.arrayBuffer()).toString("base64");
266
269
  }
267
270
 
271
+ // src/shutdown.ts
272
+ var SIGNALS = ["SIGHUP", "SIGINT", "SIGTERM"];
273
+ var sessions = /* @__PURE__ */ new Set();
274
+ async function onSignal(signal) {
275
+ for (const name of SIGNALS) process.off(name, onSignal);
276
+ await Promise.allSettled([...sessions].map((close) => close()));
277
+ if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);
278
+ }
279
+ function closeOnSignal(close) {
280
+ if (sessions.size === 0) for (const name of SIGNALS) process.on(name, onSignal);
281
+ sessions.add(close);
282
+ return () => {
283
+ sessions.delete(close);
284
+ if (sessions.size === 0) for (const name of SIGNALS) process.off(name, onSignal);
285
+ };
286
+ }
287
+
268
288
  // src/adapter.ts
269
289
  var ACK_STATUSES = {
270
290
  [-1]: "error",
@@ -307,6 +327,14 @@ var RECONNECT_MIN_MS = 5e3;
307
327
  var RECONNECT_MAX_MS = 3e5;
308
328
  var MAX_POLL_OPTIONS = 12;
309
329
  var MIN_POLL_OPTIONS = 2;
330
+ var CATCH_UP_MS = 864e5;
331
+ var MAX_CATCH_UP_CHATS = 100;
332
+ var MAX_CATCH_UP_MESSAGES = 50;
333
+ var RECOMMENDED_CHROMIUM_ARGS = [
334
+ "--renderer-process-limit=1",
335
+ "--disable-gpu",
336
+ "--disable-component-update"
337
+ ];
310
338
  var WWebJSAdapter = class {
311
339
  name;
312
340
  lockScope = "channel";
@@ -329,6 +357,9 @@ var WWebJSAdapter = class {
329
357
  _state = "idle";
330
358
  _watchdog;
331
359
  _strikes = 0;
360
+ _unsignal;
361
+ _seen;
362
+ _saving = Promise.resolve();
332
363
  constructor(config = {}) {
333
364
  const name = config.adapterName ?? "wwebjs";
334
365
  if (name.includes(":")) {
@@ -369,6 +400,9 @@ var WWebJSAdapter = class {
369
400
  clearTimeout(this._retry);
370
401
  this._retry = void 0;
371
402
  this._watch();
403
+ if (this._config.handleSignals !== false) {
404
+ this._unsignal ??= closeOnSignal(() => this.disconnect());
405
+ }
372
406
  this._connection ??= this._connect().catch((error) => {
373
407
  this._connection = null;
374
408
  if (this._state !== "logged_out" && !this._closed) this._state = "disconnected";
@@ -384,6 +418,8 @@ var WWebJSAdapter = class {
384
418
  clearInterval(this._watchdog);
385
419
  this._watchdog = void 0;
386
420
  this._connection = null;
421
+ this._unsignal?.();
422
+ this._unsignal = void 0;
387
423
  await this.client.destroy();
388
424
  }
389
425
  encodeThreadId(platformData) {
@@ -452,7 +488,8 @@ var WWebJSAdapter = class {
452
488
  return this._send(threadId, message, { quotedMessageId: messageId });
453
489
  }
454
490
  async editMessage(threadId, messageId, message) {
455
- const { mentions, text } = extractMentions(this._render(message));
491
+ const { card, text: rendered } = this._render(message, threadId);
492
+ const { mentions, text } = extractMentions(rendered);
456
493
  const target = await this._requireMessage(messageId);
457
494
  const edit = () => target.edit(text, mentions.length > 0 ? { mentions } : void 0);
458
495
  let edited = await edit();
@@ -467,7 +504,9 @@ var WWebJSAdapter = class {
467
504
  `Message ${messageId} could not be edited. WhatsApp only allows editing your own messages within 15 minutes.`
468
505
  );
469
506
  }
470
- return this._raw(edited, threadId);
507
+ const raw = this._raw(edited, threadId);
508
+ await this._cardSent(card, raw.id, threadId);
509
+ return raw;
471
510
  }
472
511
  async deleteMessage(_threadId, messageId) {
473
512
  await (await this._requireMessage(messageId)).delete(true);
@@ -716,6 +755,16 @@ var WWebJSAdapter = class {
716
755
  }
717
756
  _clientOptions() {
718
757
  const options = { ...this._config.clientOptions };
758
+ const puppeteer = options.puppeteer ?? {};
759
+ options.puppeteer = {
760
+ // Puppeteer's handlers close the browser on a signal and keep the process alive; closeOnSignal does both.
761
+ ...this._config.handleSignals === false ? {} : { handleSIGHUP: false, handleSIGINT: false, handleSIGTERM: false },
762
+ ...puppeteer,
763
+ args: [
764
+ ...this._config.recommendedArgs === false ? [] : RECOMMENDED_CHROMIUM_ARGS,
765
+ ...puppeteer.args ?? []
766
+ ]
767
+ };
719
768
  if (this._config.phoneNumber) {
720
769
  options.pairWithPhoneNumber = {
721
770
  phoneNumber: this._config.phoneNumber,
@@ -734,6 +783,9 @@ var WWebJSAdapter = class {
734
783
  );
735
784
  timer.unref?.();
736
785
  });
786
+ const waiting = () => clearTimeout(timer);
787
+ this.client.once("qr", waiting);
788
+ this.client.once("code", waiting);
737
789
  try {
738
790
  await Promise.race([this._open(), timedOut]);
739
791
  } catch (error) {
@@ -741,6 +793,8 @@ var WWebJSAdapter = class {
741
793
  throw error;
742
794
  } finally {
743
795
  clearTimeout(timer);
796
+ this.client.off("qr", waiting);
797
+ this.client.off("code", waiting);
744
798
  }
745
799
  }
746
800
  async _open() {
@@ -780,6 +834,7 @@ var WWebJSAdapter = class {
780
834
  }
781
835
  this._logger.info("WhatsApp session ready", { userId: this.botUserId });
782
836
  void this._learnLid();
837
+ this._guard("catch-up", this._catchUp());
783
838
  });
784
839
  this.client.on("disconnected", (reason) => this._onDisconnected(String(reason)));
785
840
  this.client.on("message_create", (message) => this._guard("message", this._onMessage(message)));
@@ -809,7 +864,63 @@ var WWebJSAdapter = class {
809
864
  (error) => this._logger.warn("Failed to send a read receipt", { error, threadId })
810
865
  );
811
866
  }
812
- await this._chat.processMessage(this, threadId, () => this._parse(raw));
867
+ const parsed = this._addons("onMessage").length > 0 ? await this._parse(raw) : void 0;
868
+ if (!parsed || !await this._claimed(parsed, threadId)) {
869
+ await this._chat.processMessage(this, threadId, parsed ?? (() => this._parse(raw)));
870
+ }
871
+ await this._remember(raw);
872
+ }
873
+ async _claimed(message, threadId) {
874
+ for (const addon of this._addons("onMessage")) {
875
+ if (await addon.onMessage(message, this._context(threadId))) return true;
876
+ }
877
+ return false;
878
+ }
879
+ _addons(hook) {
880
+ return (this._config.addons ?? []).filter((addon) => addon[hook]);
881
+ }
882
+ _context(threadId) {
883
+ return { adapter: this, chat: this._chat, threadId };
884
+ }
885
+ _seenKey() {
886
+ return `wwebjs:${this.name}:seen`;
887
+ }
888
+ /** Writes run in turn, so an older position never lands after a newer one. */
889
+ _save() {
890
+ const state = this._chat?.getState();
891
+ if (!state) return Promise.resolve();
892
+ this._saving = this._saving.then(() => state.set(this._seenKey(), this._seen)).catch(
893
+ (error) => this._logger.warn("Could not record the last message delivered", { error })
894
+ );
895
+ return this._saving;
896
+ }
897
+ async _remember(raw) {
898
+ if (this._config.catchUpMs === false || !this._seen) return;
899
+ const id = serialize(raw.id);
900
+ const { at, ids } = this._seen;
901
+ if (raw.timestamp < at || raw.timestamp === at && ids.includes(id)) return;
902
+ this._seen = { at: raw.timestamp, ids: raw.timestamp === at ? [...ids, id] : [id] };
903
+ await this._save();
904
+ }
905
+ /** WhatsApp Web loads what arrived while the session was down without announcing every message. */
906
+ async _catchUp() {
907
+ const windowMs = this._config.catchUpMs ?? CATCH_UP_MS;
908
+ const state = this._chat?.getState();
909
+ if (windowMs === false || !state) return;
910
+ this._seen ??= await state.get(this._seenKey());
911
+ const seen = this._seen;
912
+ if (!seen) {
913
+ this._seen = { at: Math.floor(Date.now() / 1e3), ids: [] };
914
+ await this._save();
915
+ return;
916
+ }
917
+ const oldest = Math.max(seen.at, Math.floor((Date.now() - windowMs) / 1e3));
918
+ const unseen = (message) => message.timestamp > oldest || message.timestamp === seen.at && !seen.ids.includes(serialize(message.id));
919
+ const chats = (await this.client.getChats()).filter((chat) => chat.timestamp >= oldest).slice(0, MAX_CATCH_UP_CHATS);
920
+ for (const chat of chats) {
921
+ const missed = (await chat.fetchMessages({ limit: MAX_CATCH_UP_MESSAGES })).filter(unseen);
922
+ for (const message of missed) await this._onMessage(message);
923
+ }
813
924
  }
814
925
  _onEdit(raw, previousBody) {
815
926
  if (this._isOwn(raw.fromMe)) return;
@@ -1043,23 +1154,45 @@ var WWebJSAdapter = class {
1043
1154
  this._strikes = 0;
1044
1155
  this._onDisconnected(`UNRESPONSIVE (${state ?? "no answer"})`);
1045
1156
  }
1046
- _render(message) {
1157
+ _render(message, threadId) {
1047
1158
  const card = extractCard(message);
1048
- return card ? cardToFallbackText(card, { boldFormat: "*" }) : this._converter.renderPostable(message);
1159
+ if (!card) return { text: this._converter.renderPostable(message) };
1160
+ for (const addon of this._addons("renderCard")) {
1161
+ const text = addon.renderCard(card, this._context(threadId));
1162
+ if (text !== void 0) return { card, text };
1163
+ }
1164
+ return { card, text: cardToFallbackText(card, { boldFormat: "*" }) };
1165
+ }
1166
+ /** The card is already on WhatsApp, so an addon failing here must not fail the send. */
1167
+ async _cardSent(card, messageId, threadId) {
1168
+ if (!card) return;
1169
+ for (const addon of this._addons("cardSent")) {
1170
+ try {
1171
+ await addon.cardSent(card, messageId, this._context(threadId));
1172
+ } catch (error) {
1173
+ this._logger.warn("An addon failed after a card was sent", { error, threadId });
1174
+ }
1175
+ }
1049
1176
  }
1050
1177
  async _send(threadId, message, options = {}) {
1051
1178
  const { chatId } = this.decodeThreadId(threadId);
1052
- const { mentions, text } = extractMentions(this._render(message));
1179
+ const { card, text: rendered } = this._render(message, threadId);
1180
+ const { mentions, text } = extractMentions(rendered);
1053
1181
  const media = await toMediaList(message, this._config.maxMediaBytes);
1054
1182
  const send = {
1055
1183
  ...options,
1056
1184
  ...mentions.length > 0 ? { mentions } : {}
1057
1185
  };
1186
+ const voice = this._config.voiceNotes !== false;
1058
1187
  const captionIndex = text ? media.findIndex(isCaptionable) : -1;
1059
1188
  const payloads = [];
1060
1189
  if (media.length === 0 || text && captionIndex === -1) payloads.push([text, send]);
1061
1190
  media.forEach((item, index) => {
1062
- payloads.push([item, index === captionIndex ? { ...send, caption: text } : send]);
1191
+ const itemOptions = index === captionIndex ? { ...send, caption: text } : send;
1192
+ payloads.push([
1193
+ item,
1194
+ voice && isAudio(item) ? { ...itemOptions, sendAudioAsVoice: true } : itemOptions
1195
+ ]);
1063
1196
  });
1064
1197
  let first;
1065
1198
  for (const [content, sendOptions] of payloads) {
@@ -1070,7 +1203,9 @@ var WWebJSAdapter = class {
1070
1203
  );
1071
1204
  first ??= sent;
1072
1205
  }
1073
- return this._raw(first, threadId);
1206
+ const raw = this._raw(first, threadId);
1207
+ await this._cardSent(card, raw.id, threadId);
1208
+ return raw;
1074
1209
  }
1075
1210
  async _sendContent(threadId, content, options) {
1076
1211
  const { chatId } = this.decodeThreadId(threadId);
@@ -1164,17 +1299,90 @@ function requireWWebJSAdapter(value) {
1164
1299
  if (isWWebJSAdapter(adapter)) return adapter;
1165
1300
  throw new ValidationError3("wwebjs", "This context does not belong to a wwebjs adapter.");
1166
1301
  }
1302
+
1303
+ // src/numbered-actions.ts
1304
+ import { cardToFallbackText as cardToFallbackText2 } from "@chat-adapter/shared";
1305
+ var TTL_MS = 864e5;
1306
+ function actionsOf(children) {
1307
+ return children.flatMap(
1308
+ (child) => child.type === "actions" ? [child] : child.type === "section" ? actionsOf(child.children) : []
1309
+ );
1310
+ }
1311
+ function layout(card) {
1312
+ const choices = [];
1313
+ const lines = [];
1314
+ const offer = (choice) => {
1315
+ choices.push(choice);
1316
+ lines.push(`${choices.length}. ${choice.label}`);
1317
+ };
1318
+ for (const { children } of actionsOf(card.children)) {
1319
+ for (const action of children) {
1320
+ if (action.type === "link-button") lines.push(`${action.label}: ${action.url}`);
1321
+ else if (action.type === "button") {
1322
+ if (!action.disabled && action.actionType !== "modal") {
1323
+ offer({ actionId: action.id, label: action.label, value: action.value });
1324
+ }
1325
+ } else {
1326
+ lines.push(`*${action.label}*`);
1327
+ for (const option of action.options) {
1328
+ offer({ actionId: action.id, label: option.label, value: option.value });
1329
+ }
1330
+ }
1331
+ }
1332
+ }
1333
+ return { choices, lines };
1334
+ }
1335
+ function keyOf({ adapter, threadId }) {
1336
+ return `wwebjs:${adapter.name}:offer:${threadId}`;
1337
+ }
1338
+ function numberedActions(options = {}) {
1339
+ return {
1340
+ renderCard(card) {
1341
+ const { lines } = layout(card);
1342
+ if (lines.length === 0) return void 0;
1343
+ return [cardToFallbackText2(card, { boldFormat: "*" }), lines.join("\n")].filter(Boolean).join("\n\n");
1344
+ },
1345
+ async cardSent(card, messageId, context) {
1346
+ const { choices } = layout(card);
1347
+ if (choices.length === 0 || !context.chat) return;
1348
+ await context.chat.getState().set(keyOf(context), { choices, messageId }, options.ttlMs ?? TTL_MS);
1349
+ },
1350
+ async onMessage(message, context) {
1351
+ const offer = await context.chat?.getState().get(keyOf(context));
1352
+ if (!offer || !context.chat) return false;
1353
+ const reply = message.text.trim();
1354
+ const choice = /^\d+$/.test(reply) ? offer.choices[Number(reply) - 1] : offer.choices.find(({ label }) => label.toLowerCase() === reply.toLowerCase());
1355
+ if (!choice) return false;
1356
+ await context.chat.processAction(
1357
+ {
1358
+ actionId: choice.actionId,
1359
+ adapter: context.adapter,
1360
+ messageId: offer.messageId,
1361
+ raw: message.raw,
1362
+ threadId: context.threadId,
1363
+ user: message.author,
1364
+ value: choice.value
1365
+ },
1366
+ void 0
1367
+ );
1368
+ return !options.keepMessage;
1369
+ }
1370
+ };
1371
+ }
1167
1372
  export {
1373
+ RECOMMENDED_CHROMIUM_ARGS,
1168
1374
  WWebJSAdapter,
1169
1375
  WWebJSFormatConverter,
1170
1376
  createWWebJSAdapter,
1171
1377
  download,
1172
1378
  extractMentions,
1379
+ isAudio,
1173
1380
  isCaptionable,
1174
1381
  isGroupId,
1175
1382
  isNewsletterId,
1176
1383
  isUserId,
1177
1384
  isWWebJSAdapter,
1385
+ numberedActions,
1178
1386
  requireWWebJSAdapter,
1179
1387
  toAttachments,
1180
1388
  toChatId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chat-adapter-wwebjs",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "WhatsApp adapter for Chat SDK, backed by whatsapp-web.js",
5
5
  "author": "nivandres",
6
6
  "license": "MIT",