chat-adapter-wwebjs 0.1.5 → 0.2.1

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,30 @@
1
1
  # chat-adapter-wwebjs
2
2
 
3
+ ## 0.2.1
4
+
5
+ ### Fixed
6
+
7
+ - No session could link since WhatsApp Web removed the module whatsapp-web.js waited on, around 2026-11-25: `connect()` failed after 30 seconds with `auth timeout`, with every release up to 1.34.8 and with the commit this adapter pointed to. It is now tested against whatsapp-web.js `38eb45b`, which reads the new one, and the README installs that commit by its full SHA, since npm resolves a short one over SSH and fails without a GitHub SSH key.
8
+ - `connect()` now says what to do when whatsapp-web.js times out this way: the error names the installed version and the commit to install.
9
+ - A second signal while the browser was closing, as Ctrl+C under `npx` or `npm exec` sends, ended the process before the browser closed, leaving Chromium running with the profile locked. Signals are now listened for until every session has closed.
10
+ - The README says how to let npm 11 and bun download Chromium, which they skip until allowed, and how to use a browser you already have.
11
+
12
+ ## 0.2.0
13
+
14
+ ### Changed
15
+
16
+ - With `receiveOwnMessages`, what the account's owner does on the phone or another linked device reaches your handlers as a person's: `isMe` and `isBot` are `false` and the author is `botUserId`, so `message.author.userId === adapter.botUserId` tells them apart. Everything the account sent used to count as the bot's own, so the Chat SDK skipped its messages, edits, reactions and commands, and only its deletes came through. What the adapter itself sends stays its own, even when WhatsApp echoes a send before it returns: its messages, an edit of one, a reaction it made and a forward. Its messages are recorded in the Chat SDK state for as long as `catchUpMs` reaches back, so catching up after a restart never hands the bot its own; from a position recorded before 0.2.0 or with the option off, which kept no such record, it skips the account's messages altogether. History still counts everything the account sent as the bot's.
17
+ - With `receiveOwnMessages`, the owner answers a modal opened for them and runs slash commands like anyone, and quoting the account's own message is no longer a mention. The adapter's own echoes never answer a modal or run a command; one could have answered a modal with its own question.
18
+ - `numberedActions()` skips whatever the paired account sends, so its owner never picks a contact's option.
19
+
20
+ ### Fixed
21
+
22
+ - `manageClient: true` on a client you already started called `initialize()` again, launching a second browser on the same profile that never became ready. Its session is now adopted, as a bridged one is, and the adapter runs it from then on.
23
+ - A signal's 8 seconds could end the process while the browser was still closing, leaving Chromium running with the profile locked. A browser still closing then is now ended outright first.
24
+ - A process killed outright, by `kill -9`, the OOM killer or a process manager, left its browser running with the profile locked, and every start failed with "The browser is already running" until someone ended it. The next start now ends it and opens the session, but only a browser on the same host and profile whose launching process is gone, never one another process runs.
25
+ - A catch-up that could not read its position from the Chat SDK state, or list the chats, never ran again until the session reconnected, and a position that could not be written waited for the next message. The watchdog now tries both again, and `disconnect()` writes a failed position once more. Two catch-ups no longer run at once after quick reconnects.
26
+ - An attempt to open the session that a newer one replaced could finish late and take over the newer one's watch on its browser, so closing that browser on purpose read as a crash and opened the session again. A replaced attempt now leaves the session alone, and a bridged client connected again no longer stacks a second watch.
27
+
3
28
  ## 0.1.5
4
29
 
5
30
  ### Fixed
package/README.md CHANGED
@@ -22,12 +22,12 @@ Documentation: [chat-sdk.dev/adapters/community/wwebjs](https://chat-sdk.dev/ada
22
22
  ## Installation
23
23
 
24
24
  ```bash
25
- pnpm add chat-adapter-wwebjs chat @chat-adapter/shared github:pedroslopez/whatsapp-web.js#064a3d5
25
+ pnpm add chat-adapter-wwebjs chat @chat-adapter/shared github:pedroslopez/whatsapp-web.js#38eb45b2759450cc6fccb6a7a3f2cbc3bdb87db2
26
26
  ```
27
27
 
28
- ESM only, Node >= 20. `chat`, `@chat-adapter/shared` and `whatsapp-web.js` are peers, so you control their versions. WhatsApp Web renamed the IDs whatsapp-web.js reads, and 1.34.7 cannot send or find chats since, so until a release carries the fix, install the commit this adapter is tested against, as above.
28
+ ESM only, Node >= 20. `chat`, `@chat-adapter/shared` and `whatsapp-web.js` are peers, so you control their versions. WhatsApp Web removed a module whatsapp-web.js waited on, so since 2026-11-25 every release up to 1.34.8 times out before showing a QR. Until a release carries the fix, install the commit this adapter is tested against, as above. Give the full commit SHA: with a short one, npm resolves it over SSH and fails without a GitHub SSH key.
29
29
 
30
- whatsapp-web.js builds when installed from GitHub, and Puppeteer downloads a Chromium build on install. pnpm 10 and later run those scripts only when you allow them, in `pnpm-workspace.yaml`:
30
+ whatsapp-web.js builds when installed from GitHub, and Puppeteer downloads a Chromium build on install. Package managers that run install scripts only when you allow them skip both, and the first start fails with "Could not find Chrome". In pnpm 10 and later, allow them in `pnpm-workspace.yaml`:
31
31
 
32
32
  ```yaml
33
33
  onlyBuiltDependencies:
@@ -35,7 +35,7 @@ onlyBuiltDependencies:
35
35
  - puppeteer
36
36
  ```
37
37
 
38
- pnpm pins the commit in the lockfile rather than in `package.json`, so commit the lockfile.
38
+ pnpm pins the commit in the lockfile rather than in `package.json`, so commit the lockfile. With npm 11, run `npm approve-scripts puppeteer whatsapp-web.js`; with bun, list both under `trustedDependencies` in `package.json`. Or skip the download: `npx puppeteer browsers install chrome`, or point `PUPPETEER_EXECUTABLE_PATH` or `clientOptions.puppeteer.executablePath` at a Chromium you have.
39
39
 
40
40
  ## Usage
41
41
 
@@ -105,16 +105,16 @@ This is a live browser session, not a webhook: `handleWebhook` answers `501`. A
105
105
  | `client` | — | An existing whatsapp-web.js `Client`, exposed as `adapter.client`. One already started is bridged; one never started is the adapter's to run. See [Bridging your own client](#bridging-your-own-client). When omitted, one is built from `clientOptions`. |
106
106
  | `clientOptions` | `{}` | Options for the client the adapter builds: `authStrategy`, `puppeteer`, `webVersionCache`, and so on. Ignored when `client` is set. |
107
107
  | `connectTimeoutMs` | 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. |
108
- | `handleSignals` | `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. Closing is given 8 seconds. |
108
+ | `handleSignals` | `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. Closing is given 8 seconds; a browser still closing then is ended outright. |
109
109
  | `logger` | `ConsoleLogger` | Logger used until `Chat` hands over its own. |
110
110
  | `modalTexts` | English | The phrases a conversational modal sends, such as its _cancel_ and _skip_ words, to put them in your users' language. See [Modals](#modals). |
111
- | `manageClient` | by state | Force who runs a `client` you passed: `true` has the adapter reconnect it, close it on `disconnect()` and on a signal, even if you started it; `false` only bridges it, even if you didn't. |
111
+ | `manageClient` | by state | Force who runs a `client` you passed: `true` has the adapter reconnect it, close it on `disconnect()` and on a signal, adopting one you started without a second browser; `false` only bridges it, even if you didn't. |
112
112
  | `markSeen` | `false` | Send a read receipt for every inbound message as it arrives. |
113
113
  | `maxMediaBytes` | 64 MB | Largest media read into memory, inbound or fetched from a `url`. The size is checked before reading and the bytes are counted as they arrive, whatever size the sender claims. |
114
114
  | `onPairingCode` | — | Receives the 8-character pairing code when `phoneNumber` is set. |
115
115
  | `onQR` | — | Receives the QR string during login. Render it with `qrcode-terminal` or similar. |
116
116
  | `phoneNumber` | — | Log in with a pairing code instead of a QR. E.164 without the leading `+`. |
117
- | `receiveOwnMessages` | `false` | Pass what the paired account did — its messages, edits, deletes and reactions — to the Chat SDK, which still skips most of its own. |
117
+ | `receiveOwnMessages` | `false` | Deliver what the account's owner does on the phone — messages, edits, deletes and reactions — as a person's, from `botUserId`. What the adapter sends stays its own. See [Messages from the phone](#messages-from-the-phone). |
118
118
  | `richContent` | `false` | Imitate what WhatsApp lacks: cards in its markup with their images as media, and modals as conversations. Off, a card is plain text and the adapter has no `openModal`. See [Rich content](#rich-content). |
119
119
  | `recommendedArgs` | `true` | Start Chromium with `RECOMMENDED_CHROMIUM_ARGS`: one renderer process, no GPU, no component updates. |
120
120
  | `reconnect` | `true` | Open the session again when WhatsApp drops it, backing off from 5 seconds to 5 minutes. A logout is never retried. |
@@ -242,7 +242,7 @@ bot.onAction("approve", async (event) => {
242
242
  });
243
243
  ```
244
244
 
245
- The options of a thread's latest card answer for a day (`ttlMs`) and live in the Chat SDK state. The first pick ends them, so a repeated answer runs nothing twice; a reply quoting another message is not a pick, and neither is anything the bot's own account sends. In a group anyone can answer, and `event.user` says who did. The reply that picked an option is not delivered as a message unless `keepMessage` is set.
245
+ The options of a thread's latest card answer for a day (`ttlMs`) and live in the Chat SDK state. The first pick ends them, so a repeated answer runs nothing twice; a reply quoting another message is not a pick, and neither is anything the paired account sends, its owner's messages included. In a group anyone can answer, and `event.user` says who did. The reply that picked an option is not delivered as a message unless `keepMessage` is set.
246
246
 
247
247
  An addon is a plain object with optional `renderCard`, `cardSent` and `onMessage` hooks, so other layers fit the same way.
248
248
 
@@ -343,7 +343,7 @@ What the adapter does with it depends on whether it was started when you passed
343
343
  - **Already started**, as above, it is bridged as it is. `connect()` adopts its session without a second `initialize()`, or waits for it if it is still starting. Its options and listeners are left alone, and its lifecycle stays yours: the adapter never reconnects or destroys it, nor closes it on a signal, and `disconnect()` only detaches the adapter.
344
344
  - **Never started**, it is the adapter's to run, exactly as one it built: `connect()` starts it, and the adapter reconnects it, closes it on `disconnect()` and on a signal.
345
345
 
346
- `manageClient` forces either way: `true` hands even a client you started to the adapter, and `false` keeps even an unstarted one a bridge, which `connect()` starts but never reconnects or closes.
346
+ `manageClient` forces either way: `true` hands even a client you started to the adapter, which adopts its session without a second `initialize()` and runs it from then on, and `false` keeps even an unstarted one a bridge, which `connect()` starts but never reconnects or closes.
347
347
 
348
348
  ## Message history
349
349
 
@@ -353,7 +353,24 @@ What the adapter does with it depends on whether it was started when you passed
353
353
 
354
354
  ## Catching up after downtime
355
355
 
356
- WhatsApp Web loads what arrived while the session was down without firing an event for each message, so the adapter catches up on its own once the session is back: it gathers what every recent chat missed, oldest first, and hands each message to your handlers. The position lives in the Chat SDK state with the account it belongs to, so a restart starts where the last process stopped, and pairing a new number starts afresh. A restart part-way through delivers again rather than skip, and a message that arrives live while it is caught up is handled once. 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, and the adapter logs a warning when that happens.
356
+ WhatsApp Web loads what arrived while the session was down without firing an event for each message, so the adapter catches up on its own once the session is back: it gathers what every recent chat missed, oldest first, and hands each message to your handlers. The position lives in the Chat SDK state with the account it belongs to, so a restart starts where the last process stopped, and pairing a new number starts afresh. A restart part-way through delivers again rather than skip, and a message that arrives live while it is caught up is handled once. 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, and the adapter logs a warning when that happens. A catch-up that could not read its position or list the chats, and a position that could not be recorded, are tried again on the watchdog's next check.
357
+
358
+ ## Messages from the phone
359
+
360
+ The paired account is someone's WhatsApp, and they may keep using it. By default nothing the account sends reaches your handlers. With `receiveOwnMessages`, what its owner does on the phone or another linked device — messages, edits, deletes and reactions — arrives as a person's, from the bot's own account:
361
+
362
+ ```typescript
363
+ const whatsapp = createWWebJSAdapter({ receiveOwnMessages: true });
364
+
365
+ bot.onSubscribedMessage(async (thread, message) => {
366
+ if (message.author.userId === whatsapp.botUserId) return thread.unsubscribe(); // the owner took over
367
+ await thread.post(`You said: ${message.text}`);
368
+ });
369
+ ```
370
+
371
+ What the adapter itself sends stays its own, `isMe`, which the Chat SDK skips. It knows each message it sent, even one WhatsApp echoes back before the send returns, and records it in the Chat SDK state for as long as `catchUpMs` reaches back, so a restart that catches up on the account's messages still skips its own. Catching up from a position recorded without that record, before 0.2.0 or with the option off, skips the account's messages altogether. An edit is its own when it edits a message the adapter sent, a reaction when the adapter reacted to that message, and a forward when its echo answers one the adapter made. Deletes carry no author, so the adapter's come through too.
372
+
373
+ The owner answers a modal opened for them and runs your slash commands like anyone, while the adapter's own echoes never do. Nothing the account sends picks a card's numbered option, and the owner quoting the account's own message is no mention. History — `fetchMessages` and the like — still counts everything the account sent as the bot's own, since what the adapter sent is remembered only that long.
357
374
 
358
375
  ## Multiple accounts
359
376
 
@@ -396,17 +413,19 @@ Examples: `wwebjs:15551234567@c.us` (DM by phone), `wwebjs:99990000111122@lid` (
396
413
 
397
414
  ### The QR never appears
398
415
 
416
+ - `connect()` fails with `auth timeout` or `Waiting failed`: the installed whatsapp-web.js no longer reads current WhatsApp Web. Install the commit in [Installation](#installation); the error names the version you have.
399
417
  - Check that Chromium can start: run locally with `clientOptions.puppeteer.headless: false`, or look for missing shared libraries on Linux.
400
418
  - WhatsApp replaces the QR every 20 seconds or so; render each one `onQR` receives.
401
419
 
402
420
  ### Sends fail or chats are not found
403
421
 
404
- - whatsapp-web.js 1.34.7 cannot read current WhatsApp Web. Install `github:pedroslopez/whatsapp-web.js#064a3d5`.
422
+ - whatsapp-web.js 1.34.8 and older cannot read current WhatsApp Web. Install `github:pedroslopez/whatsapp-web.js#38eb45b2759450cc6fccb6a7a3f2cbc3bdb87db2`.
405
423
 
406
424
  ### "The browser is already running"
407
425
 
408
426
  - Another process holds the same `LocalAuth` profile. The adapter ends every browser it launches before reopening, even one whatsapp-web.js never handed over; a client you started yourself is yours to close.
409
- - A process killed outright, by `kill -9` or the OOM killer, leaves its browser running. End it before starting again: on Linux and macOS the profile's `SingletonLock` points at `<host>-<pid>`.
427
+ - A process killed outright, by `kill -9`, the OOM killer or a process manager out of patience, leaves its browser running. The next start ends it when it runs on the same host, on the same profile, with the process that launched it gone, found through `ps`, which slim images may lack.
428
+ - A lock left on the profile by another host, as by a container recreated with a new hostname, is never cleared, since that browser may still run there. Give the container a fixed `hostname`, or remove the profile's `SingletonLock` once you are sure.
410
429
 
411
430
  ### The session drops
412
431
 
@@ -417,7 +436,7 @@ Examples: `wwebjs:15551234567@c.us` (DM by phone), `wwebjs:99990000111122@lid` (
417
436
  - **Unofficial.** It automates WhatsApp Web, which WhatsApp may block or change at any time.
418
437
  - **One session per number**, as WhatsApp Web itself allows.
419
438
  - **No scheduling or ephemeral messages.** `postEphemeral` falls back to a DM; `thread.schedule()` throws.
420
- - **Everything the paired account sends counts as the bot's own**, from the phone too, so the Chat SDK skips its messages, edits and reactions even with `receiveOwnMessages`; only its deletes come through.
439
+ - **History counts everything the paired account sent as the bot's own.** Only what arrives, live or caught up, tells its owner's messages from the adapter's; see [Messages from the phone](#messages-from-the-phone).
421
440
  - **An attachment given only by `url` is fetched over HTTPS**, never from a private or internal address, with a 30-second timeout and `maxMediaBytes` as its limit.
422
441
  - **A bare `@number` in outgoing text stays text.** Mention someone with `thread.mentionUser(id)`.
423
442
  - **`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.
package/dist/index.d.ts CHANGED
@@ -73,8 +73,9 @@ interface WWebJSAdapterConfig {
73
73
  /**
74
74
  * Close the session on SIGINT, SIGTERM and SIGHUP, then let the signal end
75
75
  * the process as it otherwise would — unless the app listens for it, and
76
- * shuts down itself. Puppeteer alone closes the browser and leaves the
77
- * process running. Defaults to `true`.
76
+ * shuts down itself. A browser still closing after 8 seconds is ended
77
+ * outright first, so it never outlives the process. Puppeteer alone closes
78
+ * the browser and leaves the process running. Defaults to `true`.
78
79
  */
79
80
  handleSignals?: boolean;
80
81
  /** Logger instance. Replaced by the Chat SDK logger once initialized. */
@@ -82,8 +83,8 @@ interface WWebJSAdapterConfig {
82
83
  /**
83
84
  * Force who runs a `client` you passed, whatever its state: `true` has the
84
85
  * adapter reconnect it, destroy it on `disconnect()` and close it on a
85
- * signal; `false` only bridges it. Decided by whether it was started when
86
- * omitted.
86
+ * signal, adopting one already started rather than starting it twice;
87
+ * `false` only bridges it. Decided by whether it was started when omitted.
87
88
  */
88
89
  manageClient?: boolean;
89
90
  /** The few phrases a conversational modal sends, to put them in your users' language. */
@@ -114,9 +115,13 @@ interface WWebJSAdapterConfig {
114
115
  */
115
116
  maxMediaBytes?: number;
116
117
  /**
117
- * Deliver messages the paired account sent — from the phone or from this
118
- * adapter — to the Chat SDK, along with its own edits, deletes and
119
- * reactions. Defaults to `false`.
118
+ * Deliver what the paired account's owner does from the phone or another
119
+ * linked device — messages, edits, deletes and reactions — as a person's,
120
+ * from `botUserId`, so `message.author.userId === adapter.botUserId` tells
121
+ * them apart. What this adapter sends, edits or reacts with stays its own,
122
+ * `isMe`, which the Chat SDK skips, after a restart too for as long as
123
+ * `catchUpMs` reaches back. Deletes carry no author, so the adapter's come
124
+ * through too. Defaults to `false`.
120
125
  */
121
126
  receiveOwnMessages?: boolean;
122
127
  /**
@@ -340,6 +345,14 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
340
345
  private _behind?;
341
346
  private readonly _recent;
342
347
  private _saving;
348
+ private _unsaved;
349
+ /** Catch-ups run in turn, so two never hold or move the position at once. */
350
+ private _catching;
351
+ private _owed;
352
+ /** What this adapter sent or reacted to, so the account's echo of it is told apart from what its owner does. */
353
+ private readonly _own;
354
+ private readonly _sending;
355
+ private _forwards;
343
356
  constructor(config?: WWebJSAdapterConfig);
344
357
  /** Where the session stands; a health check reads `connection === "connected"`. */
345
358
  get connection(): WWebJSConnection;
@@ -375,6 +388,8 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
375
388
  deleteMessage(threadId: string, messageId: string): Promise<void>;
376
389
  addReaction(threadId: string, messageId: string, emoji: EmojiValue | string): Promise<void>;
377
390
  removeReaction(threadId: string, messageId: string, _emoji: EmojiValue | string): Promise<void>;
391
+ /** Marked before it is sent, since its echo can arrive before `react()` returns. */
392
+ private _react;
378
393
  fetchMessages(threadId: string, options?: FetchOptions): Promise<FetchResult<Message>>;
379
394
  fetchChannelMessages(channelId: string, options?: FetchOptions): Promise<FetchResult<Message>>;
380
395
  fetchMessage(threadId: string, messageId: string): Promise<Message$1<Message> | null>;
@@ -461,7 +476,11 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
461
476
  private _running;
462
477
  /** Closes the browser this adapter runs; closing it on purpose is not a crash to recover from. */
463
478
  private _close;
464
- /** `destroy()` closes only a browser it still sees connected, so one that dropped keeps its profile locked. */
479
+ /**
480
+ * `destroy()` closes only a browser it still sees connected, so one that
481
+ * dropped keeps its profile locked. It is ended at once, as a signal whose
482
+ * time runs out needs, and the promise waits for it to exit.
483
+ */
465
484
  private _killBrowser;
466
485
  private _listen;
467
486
  private _unlisten;
@@ -478,21 +497,27 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
478
497
  private _addons;
479
498
  private _context;
480
499
  private _seenKey;
481
- /** Writes run in turn, so an older position never lands after a newer one. */
500
+ /** Writes run in turn, so an older position never lands after a newer one; one that fails is written again by the watchdog. */
482
501
  private _save;
483
502
  /** While a catch-up runs the position holds still, so a crash part-way replays rather than skips. */
484
503
  private _remember;
485
504
  private _advance;
505
+ private _position;
506
+ /** One that fails, reading its position or the chats, is owed, and the watchdog runs it again. */
507
+ private _catchUpNext;
486
508
  /** WhatsApp Web loads what arrived while the session was down without announcing every message. */
487
509
  private _catchUp;
510
+ /** The account's edit of a message this adapter sent is the adapter's own; any other is the operator's. */
488
511
  private _onEdit;
489
512
  private _onRevoke;
513
+ /** The account's reaction to a message this adapter reacted to is the adapter's own; any other is the operator's. */
490
514
  private _onReaction;
491
515
  private _onAck;
492
516
  private _onGroup;
493
517
  private _onVote;
494
518
  private _dispatch;
495
519
  private _parse;
520
+ /** The account's own messages come from `botUserId`, whether the adapter sent them or its owner did. */
496
521
  private _author;
497
522
  private _indicator;
498
523
  /** Groups address the bot by its LID or its phone number, whichever they know it by. */
@@ -516,6 +541,16 @@ declare class WWebJSAdapter implements Adapter<WWebJSThreadId, Message> {
516
541
  private _cardSent;
517
542
  private _send;
518
543
  private _sendContent;
544
+ /** Every send goes through here, under way before it starts, so its echo stays the adapter's own even when it arrives before the id. */
545
+ private _post;
546
+ /** Kept in state too, for as long as a catch-up reaches back, so an echo replayed after a restart is still its own. */
547
+ private _mark;
548
+ private _marked;
549
+ private _ownKey;
550
+ /** whatsapp-web.js can emit a send's echo before `sendMessage()` returns its id, so the sends under way settle first. */
551
+ private _echo;
552
+ /** Claimed on arrival, by a forward the adapter made that no echo has claimed yet. */
553
+ private _forwarded;
519
554
  private _raw;
520
555
  private _page;
521
556
  private _findChat;
@@ -588,4 +623,5 @@ interface NumberedActionsOptions {
588
623
  */
589
624
  declare function numberedActions(options?: NumberedActionsOptions): WWebJSAddon;
590
625
 
591
- 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 WWebJSModalTexts, 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, triggerIdOf };
626
+ export { RECOMMENDED_CHROMIUM_ARGS, WWebJSAdapter, WWebJSFormatConverter, createWWebJSAdapter, download, extractMentions, isAudio, isCaptionable, isGroupId, isNewsletterId, isUserId, isWWebJSAdapter, numberedActions, requireWWebJSAdapter, toAttachments, toChatId, toMedia, toMediaList, toUser, triggerIdOf };
627
+ export type { NumberedActionsOptions, WWebJSAck, WWebJSAckHandler, WWebJSAckStatus, WWebJSAdapterConfig, WWebJSAddon, WWebJSAddonContext, WWebJSCallHandler, WWebJSConnection, WWebJSGroupEvent, WWebJSGroupEventHandler, WWebJSGroupParticipant, WWebJSModalTexts, WWebJSPollVote, WWebJSPollVoteHandler, WWebJSSendEventArgs, WWebJSSendLocationArgs, WWebJSSendPollArgs, WWebJSThreadId };
package/dist/index.js CHANGED
@@ -1,7 +1,6 @@
1
1
  // src/adapter.ts
2
2
  import { randomUUID } from "crypto";
3
- import { once } from "events";
4
- import { extractCard, ResourceNotFoundError, ValidationError as ValidationError3 } from "@chat-adapter/shared";
3
+ import { extractCard, ResourceNotFoundError, ValidationError as ValidationError4 } from "@chat-adapter/shared";
5
4
  import {
6
5
  ConsoleLogger,
7
6
  defaultEmojiResolver,
@@ -168,12 +167,27 @@ import {
168
167
  downloadAttachment,
169
168
  extractFiles,
170
169
  extractPostableAttachments,
171
- ValidationError
170
+ ValidationError as ValidationError2
172
171
  } from "@chat-adapter/shared";
173
172
 
174
173
  // src/wwebjs.ts
174
+ import { createRequire } from "module";
175
+ import { ValidationError } from "@chat-adapter/shared";
175
176
  import wwebjs from "whatsapp-web.js";
176
177
  var { Client, Location, MessageMedia, Poll, ScheduledEvent } = wwebjs;
178
+ var TESTED_WWEBJS = "github:pedroslopez/whatsapp-web.js#38eb45b2759450cc6fccb6a7a3f2cbc3bdb87db2";
179
+ function outdatedError(error) {
180
+ if (!/auth timeout|Waiting failed/i.test(String(error))) return void 0;
181
+ let version = "unknown";
182
+ try {
183
+ version = createRequire(import.meta.url)("whatsapp-web.js/package.json").version;
184
+ } catch {
185
+ }
186
+ return new ValidationError(
187
+ "wwebjs",
188
+ `WhatsApp Web did not load (${String(error)}). The installed whatsapp-web.js ${version} likely cannot read current WhatsApp Web; install ${TESTED_WWEBJS}.`
189
+ );
190
+ }
177
191
 
178
192
  // src/media.ts
179
193
  var ATTACHMENT_TYPES = {
@@ -257,7 +271,7 @@ async function toMedia(source, maxBytes = DEFAULT_MAX_MEDIA_BYTES) {
257
271
  const data = source.data ?? await source.fetchData?.();
258
272
  if (!data) {
259
273
  if (!source.url) {
260
- throw new ValidationError("wwebjs", "Attachment has no data, fetchData, or url to send.");
274
+ throw new ValidationError2("wwebjs", "Attachment has no data, fetchData, or url to send.");
261
275
  }
262
276
  return fetchMedia(source.url, source, maxBytes);
263
277
  }
@@ -305,13 +319,13 @@ async function collect(stream, maxBytes, label) {
305
319
  return Buffer.concat(chunks);
306
320
  }
307
321
  function tooLarge(label, size, maxBytes) {
308
- return new ValidationError(
322
+ return new ValidationError2(
309
323
  "wwebjs",
310
324
  `Media for ${label} is ${size} bytes or more, over the ${maxBytes}-byte limit.`
311
325
  );
312
326
  }
313
327
  function unavailable(messageId) {
314
- return new ValidationError(
328
+ return new ValidationError2(
315
329
  "wwebjs",
316
330
  `Media for message ${messageId} is no longer available for download.`
317
331
  );
@@ -323,7 +337,7 @@ async function toBase64(data) {
323
337
  }
324
338
 
325
339
  // src/modals.ts
326
- import { ValidationError as ValidationError2 } from "@chat-adapter/shared";
340
+ import { ValidationError as ValidationError3 } from "@chat-adapter/shared";
327
341
  var DEFAULT_MODAL_TEXTS = {
328
342
  cancel: "cancel",
329
343
  cancelHint: "Send *cancel* to stop.",
@@ -354,7 +368,7 @@ function fromTrigger(triggerId) {
354
368
  }
355
369
  const [threadId, userId] = Array.isArray(ids) ? ids : [];
356
370
  if (typeof threadId === "string" && typeof userId === "string") return [threadId, userId];
357
- throw new ValidationError2("wwebjs", `Not a trigger this adapter issued: ${triggerId}`);
371
+ throw new ValidationError3("wwebjs", `Not a trigger this adapter issued: ${triggerId}`);
358
372
  }
359
373
  function createForm(modal, viewId, contextId) {
360
374
  const fields = modal.children.filter((child) => INPUTS.has(child.type));
@@ -451,24 +465,77 @@ function flattenOptions(result) {
451
465
  return (result ?? []).flatMap((entry) => "options" in entry ? entry.options : [entry]);
452
466
  }
453
467
 
468
+ // src/profile.ts
469
+ import { execFile } from "child_process";
470
+ import { readlink } from "fs/promises";
471
+ import { hostname } from "os";
472
+ import { join, resolve as resolvePath } from "path";
473
+ var EXIT_WAIT_MS = 2e3;
474
+ var POLL_MS = 100;
475
+ async function freeProfile(dir) {
476
+ if (!dir) return false;
477
+ const profile = resolvePath(dir);
478
+ const lock = await readlink(join(profile, "SingletonLock")).catch(() => "");
479
+ const [, host, pid] = /^(.+)-(\d+)$/.exec(lock) ?? [];
480
+ if (!pid || host !== hostname()) return false;
481
+ const [, parent, args] = /^(\d+)\s+(.*)$/.exec(await commandOf(pid)) ?? [];
482
+ if (parent !== "1" || !`${args} `.includes(` --user-data-dir=${profile} `)) return false;
483
+ try {
484
+ process.kill(-Number(pid), "SIGKILL");
485
+ } catch {
486
+ return false;
487
+ }
488
+ for (let waited = 0; alive(Number(pid)) && waited < EXIT_WAIT_MS; waited += POLL_MS) {
489
+ await new Promise((resolve) => setTimeout(resolve, POLL_MS));
490
+ }
491
+ return true;
492
+ }
493
+ function commandOf(pid) {
494
+ return new Promise(
495
+ (resolve) => execFile(
496
+ "ps",
497
+ ["-ww", "-o", "ppid=,args=", "-p", pid],
498
+ (error, stdout) => resolve(error ? "" : stdout.trim())
499
+ )
500
+ );
501
+ }
502
+ function alive(pid) {
503
+ try {
504
+ process.kill(pid, 0);
505
+ return true;
506
+ } catch {
507
+ return false;
508
+ }
509
+ }
510
+
454
511
  // src/shutdown.ts
455
512
  var SIGNALS = ["SIGHUP", "SIGINT", "SIGTERM"];
456
513
  var CLOSE_TIMEOUT_MS = 8e3;
457
- var sessions = /* @__PURE__ */ new Set();
458
- async function onSignal(signal) {
459
- for (const name of SIGNALS) process.off(name, onSignal);
514
+ var sessions = /* @__PURE__ */ new Map();
515
+ var shuttingDown = false;
516
+ function onSignal(signal) {
517
+ if (shuttingDown) return;
518
+ shuttingDown = true;
519
+ void shutdown(signal);
520
+ }
521
+ async function shutdown(signal) {
522
+ const closing = [...sessions];
460
523
  await Promise.race([
461
- Promise.allSettled([...sessions].map((close) => close())),
524
+ Promise.allSettled(closing.map(([close]) => close())),
462
525
  new Promise((resolve) => setTimeout(resolve, CLOSE_TIMEOUT_MS).unref())
463
526
  ]);
527
+ for (const [, kill] of closing) kill();
528
+ for (const name of SIGNALS) process.off(name, onSignal);
464
529
  if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);
465
530
  }
466
- function closeOnSignal(close) {
531
+ function closeOnSignal(close, kill) {
467
532
  if (sessions.size === 0) for (const name of SIGNALS) process.on(name, onSignal);
468
- sessions.add(close);
533
+ sessions.set(close, kill);
469
534
  return () => {
470
535
  sessions.delete(close);
471
- if (sessions.size === 0) for (const name of SIGNALS) process.off(name, onSignal);
536
+ if (sessions.size === 0 && !shuttingDown) {
537
+ for (const name of SIGNALS) process.off(name, onSignal);
538
+ }
472
539
  };
473
540
  }
474
541
 
@@ -566,10 +633,18 @@ var WWebJSAdapter = class {
566
633
  _behind;
567
634
  _recent = /* @__PURE__ */ new Set();
568
635
  _saving = Promise.resolve();
636
+ _unsaved = false;
637
+ /** Catch-ups run in turn, so two never hold or move the position at once. */
638
+ _catching = Promise.resolve();
639
+ _owed = false;
640
+ /** What this adapter sent or reacted to, so the account's echo of it is told apart from what its owner does. */
641
+ _own = /* @__PURE__ */ new Set();
642
+ _sending = /* @__PURE__ */ new Set();
643
+ _forwards = 0;
569
644
  constructor(config = {}) {
570
645
  const name = config.adapterName ?? "wwebjs";
571
646
  if (name.includes(":")) {
572
- throw new ValidationError3("wwebjs", `Invalid adapterName "${name}". ":" is not allowed.`);
647
+ throw new ValidationError4("wwebjs", `Invalid adapterName "${name}". ":" is not allowed.`);
573
648
  }
574
649
  this._config = config;
575
650
  this.name = name;
@@ -615,7 +690,10 @@ var WWebJSAdapter = class {
615
690
  if (this._listeners.length === 0) this._listen();
616
691
  this._watch();
617
692
  if (this._owned && this._config.handleSignals !== false) {
618
- this._unsignal ??= closeOnSignal(() => this.disconnect());
693
+ this._unsignal ??= closeOnSignal(
694
+ () => this.disconnect(),
695
+ () => void this._killBrowser()
696
+ );
619
697
  }
620
698
  if (this._connection) return this._connection;
621
699
  const attempt = ++this._attempts;
@@ -638,7 +716,7 @@ var WWebJSAdapter = class {
638
716
  this._connection = null;
639
717
  this._unsignal?.();
640
718
  this._unsignal = void 0;
641
- await this._saving;
719
+ await (this._unsaved ? this._save() : this._saving);
642
720
  if (!this._owned) return this._unlisten();
643
721
  await this._close();
644
722
  }
@@ -648,7 +726,7 @@ var WWebJSAdapter = class {
648
726
  decodeThreadId(threadId) {
649
727
  const prefix = `${this.name}:`;
650
728
  if (!threadId.startsWith(prefix)) {
651
- throw new ValidationError3("wwebjs", `Invalid WhatsApp thread ID: ${threadId}`);
729
+ throw new ValidationError4("wwebjs", `Invalid WhatsApp thread ID: ${threadId}`);
652
730
  }
653
731
  return { chatId: threadId.slice(prefix.length) };
654
732
  }
@@ -719,7 +797,7 @@ var WWebJSAdapter = class {
719
797
  edited = await edit();
720
798
  }
721
799
  if (!edited) {
722
- throw new ValidationError3(
800
+ throw new ValidationError4(
723
801
  "wwebjs",
724
802
  `Message ${messageId} could not be edited. WhatsApp only allows editing your own messages within 15 minutes.`
725
803
  );
@@ -751,10 +829,16 @@ var WWebJSAdapter = class {
751
829
  await (await this._requireMessage(messageId, threadId)).delete(true);
752
830
  }
753
831
  async addReaction(threadId, messageId, emoji) {
754
- await (await this._requireMessage(messageId, threadId)).react(defaultEmojiResolver.toGChat(emoji));
832
+ await this._react(threadId, messageId, defaultEmojiResolver.toGChat(emoji));
755
833
  }
756
834
  async removeReaction(threadId, messageId, _emoji) {
757
- await (await this._requireMessage(messageId, threadId)).react("");
835
+ await this._react(threadId, messageId, "");
836
+ }
837
+ /** Marked before it is sent, since its echo can arrive before `react()` returns. */
838
+ async _react(threadId, messageId, reaction) {
839
+ const target = await this._requireMessage(messageId, threadId);
840
+ await this._mark(`reacted:${serialize(target.id)}`);
841
+ await target.react(reaction);
758
842
  }
759
843
  async fetchMessages(threadId, options) {
760
844
  return this._page(await this._requireChat(threadId), options);
@@ -882,7 +966,7 @@ var WWebJSAdapter = class {
882
966
  /** Send a native WhatsApp poll. Between 2 and 12 options. */
883
967
  async sendPoll(args) {
884
968
  if (args.options.length < MIN_POLL_OPTIONS || args.options.length > MAX_POLL_OPTIONS) {
885
- throw new ValidationError3(
969
+ throw new ValidationError4(
886
970
  "wwebjs",
887
971
  `sendPoll: WhatsApp polls need between ${MIN_POLL_OPTIONS} and ${MAX_POLL_OPTIONS} options. Received ${args.options.length}.`
888
972
  );
@@ -913,7 +997,13 @@ var WWebJSAdapter = class {
913
997
  /** Forward an existing message into another thread. */
914
998
  async forwardMessage(messageId, targetThreadId) {
915
999
  const { chatId } = this.decodeThreadId(targetThreadId);
916
- await (await this._requireMessage(messageId)).forward(chatId);
1000
+ const message = await this._requireMessage(messageId);
1001
+ const claims = this._config.receiveOwnMessages ? 1 : 0;
1002
+ this._forwards += claims;
1003
+ await message.forward(chatId).catch((error) => {
1004
+ this._forwards -= claims;
1005
+ throw error;
1006
+ });
917
1007
  }
918
1008
  /** Pin a message for the given number of seconds. */
919
1009
  async pinMessage(messageId, seconds) {
@@ -950,7 +1040,7 @@ var WWebJSAdapter = class {
950
1040
  async fetchGroupParticipants(threadId) {
951
1041
  const chat = await this._requireChat(threadId);
952
1042
  if (!isGroupChat(chat)) {
953
- throw new ValidationError3("wwebjs", "fetchGroupParticipants: thread is not a group.");
1043
+ throw new ValidationError4("wwebjs", "fetchGroupParticipants: thread is not a group.");
954
1044
  }
955
1045
  return chat.participants.map((participant) => ({
956
1046
  isAdmin: participant.isAdmin || participant.isSuperAdmin,
@@ -1000,7 +1090,7 @@ var WWebJSAdapter = class {
1000
1090
  return;
1001
1091
  }
1002
1092
  if (!second) {
1003
- throw new ValidationError3(
1093
+ throw new ValidationError4(
1004
1094
  "wwebjs",
1005
1095
  "onPollVote: a handler is required when filtering by poll message ID."
1006
1096
  );
@@ -1047,7 +1137,7 @@ var WWebJSAdapter = class {
1047
1137
  let timer;
1048
1138
  const timedOut = new Promise((_resolve, reject) => {
1049
1139
  timer = setTimeout(
1050
- () => reject(new ValidationError3("wwebjs", `WhatsApp was not ready within ${timeoutMs}ms.`)),
1140
+ () => reject(new ValidationError4("wwebjs", `WhatsApp was not ready within ${timeoutMs}ms.`)),
1051
1141
  timeoutMs
1052
1142
  );
1053
1143
  timer.unref?.();
@@ -1056,27 +1146,31 @@ var WWebJSAdapter = class {
1056
1146
  this.client.once("qr", waiting);
1057
1147
  this.client.once("code", waiting);
1058
1148
  try {
1059
- await Promise.race([this._open(), timedOut]);
1149
+ await Promise.race([this._open(attempt), timedOut]);
1060
1150
  } catch (error) {
1061
1151
  if (this._owned && attempt === this._attempts) await this._close().catch(() => void 0);
1062
- throw error;
1152
+ throw outdatedError(error) ?? error;
1063
1153
  } finally {
1064
1154
  clearTimeout(timer);
1065
1155
  this.client.off("qr", waiting);
1066
1156
  this.client.off("code", waiting);
1067
1157
  }
1068
1158
  }
1069
- async _open() {
1159
+ async _open(attempt) {
1070
1160
  this._state = this._initialized ? "reconnecting" : "connecting";
1071
- if (!this._owned && await this._running()) {
1161
+ const adopted = this._owned ? !this._initialized && !!this.client.pupBrowser?.isConnected() : !!this.client.pupBrowser;
1162
+ if (adopted && await this._running()) {
1163
+ if (attempt !== this._attempts) return;
1164
+ this._initialized = true;
1072
1165
  this._watchBrowser();
1073
1166
  return this._onReady();
1074
1167
  }
1168
+ const options = this.client.options;
1075
1169
  let onReady;
1076
1170
  let onFailure;
1077
1171
  const ready = new Promise((resolve, reject) => {
1078
1172
  onReady = resolve;
1079
- onFailure = (message) => reject(new ValidationError3("wwebjs", `WhatsApp authentication failed: ${message}`));
1173
+ onFailure = (message) => reject(new ValidationError4("wwebjs", `WhatsApp authentication failed: ${message}`));
1080
1174
  });
1081
1175
  ready.catch(() => void 0);
1082
1176
  this.client.on("ready", onReady);
@@ -1084,16 +1178,21 @@ var WWebJSAdapter = class {
1084
1178
  try {
1085
1179
  if (this._owned && this._initialized) await this._close().catch(() => void 0);
1086
1180
  this._initialized = true;
1087
- if (this._owned) {
1088
- this._launch = new AbortController();
1089
- const options = this.client.options;
1090
- options.puppeteer = { ...options.puppeteer, signal: this._launch.signal };
1181
+ if (!adopted) {
1182
+ if (this._owned) {
1183
+ this._launch = new AbortController();
1184
+ options.puppeteer = { ...options.puppeteer, signal: this._launch.signal };
1185
+ }
1186
+ await this.client.initialize().catch(async (error) => {
1187
+ if (!this._owned || !await freeProfile(options.puppeteer?.userDataDir)) throw error;
1188
+ await this.client.initialize();
1189
+ });
1091
1190
  }
1092
- if (this._owned || !this.client.pupBrowser) await this.client.initialize();
1093
1191
  if (this._closed) {
1094
1192
  if (this._owned) await this._close();
1095
1193
  return;
1096
1194
  }
1195
+ if (attempt !== this._attempts) return;
1097
1196
  this._watchBrowser();
1098
1197
  await ready;
1099
1198
  } finally {
@@ -1103,6 +1202,7 @@ var WWebJSAdapter = class {
1103
1202
  }
1104
1203
  /** A crashed browser ends the session without WhatsApp ever reporting a disconnect. */
1105
1204
  _watchBrowser() {
1205
+ this._unwatch?.();
1106
1206
  const browser = this.client.pupBrowser;
1107
1207
  if (!browser) return;
1108
1208
  const onClose = () => this._onDisconnected("BROWSER_CLOSED");
@@ -1124,21 +1224,27 @@ var WWebJSAdapter = class {
1124
1224
  await this._killBrowser();
1125
1225
  }
1126
1226
  }
1127
- /** `destroy()` closes only a browser it still sees connected, so one that dropped keeps its profile locked. */
1128
- async _killBrowser() {
1227
+ /**
1228
+ * `destroy()` closes only a browser it still sees connected, so one that
1229
+ * dropped keeps its profile locked. It is ended at once, as a signal whose
1230
+ * time runs out needs, and the promise waits for it to exit.
1231
+ */
1232
+ _killBrowser() {
1129
1233
  this._launch?.abort();
1130
1234
  const browser = this.client.pupBrowser?.process?.();
1131
- if (!browser?.pid || browser.exitCode !== null || browser.signalCode !== null) return;
1132
- const exited = once(browser, "exit");
1235
+ if (!browser?.pid || browser.exitCode !== null || browser.signalCode !== null) {
1236
+ return Promise.resolve();
1237
+ }
1238
+ const exited = new Promise((resolve) => {
1239
+ browser.once("exit", resolve);
1240
+ setTimeout(resolve, KILL_WAIT_MS).unref?.();
1241
+ });
1133
1242
  try {
1134
1243
  process.kill(process.platform === "win32" ? browser.pid : -browser.pid, "SIGKILL");
1135
1244
  } catch {
1136
1245
  browser.kill("SIGKILL");
1137
1246
  }
1138
- await Promise.race([
1139
- exited,
1140
- new Promise((resolve) => setTimeout(resolve, KILL_WAIT_MS).unref?.())
1141
- ]);
1247
+ return exited;
1142
1248
  }
1143
1249
  _listen() {
1144
1250
  const { onPairingCode, onQR } = this._config;
@@ -1152,9 +1258,12 @@ var WWebJSAdapter = class {
1152
1258
  on("ready", () => this._onReady());
1153
1259
  on("disconnected", (reason) => this._onDisconnected(String(reason)));
1154
1260
  on("message_create", (message) => this._guard("message", this._onMessage(message)));
1155
- on("message_edit", (message, _new, previous) => this._onEdit(message, String(previous)));
1261
+ on(
1262
+ "message_edit",
1263
+ (message, _new, previous) => this._guard("edit", this._onEdit(message, String(previous)))
1264
+ );
1156
1265
  on("message_revoke_everyone", (message, revoked) => this._onRevoke(message, revoked));
1157
- on("message_reaction", (reaction) => this._onReaction(reaction));
1266
+ on("message_reaction", (reaction) => this._guard("reaction", this._onReaction(reaction)));
1158
1267
  on("message_ack", (message, ack) => this._onAck(message, ack));
1159
1268
  on("vote_update", (vote) => this._guard("poll vote", this._onVote(vote)));
1160
1269
  on("call", (call) => void this._dispatch(this._callHandlers, call, "onCall"));
@@ -1174,7 +1283,7 @@ var WWebJSAdapter = class {
1174
1283
  }
1175
1284
  this._logger.info("WhatsApp session ready", { userId: this.botUserId });
1176
1285
  void this._learnLid();
1177
- this._guard("catch-up", this._catchUp());
1286
+ this._catchUpNext();
1178
1287
  }
1179
1288
  async _onMessage(raw) {
1180
1289
  if (!this._chat || this._isOwn(raw.fromMe)) return;
@@ -1182,22 +1291,22 @@ var WWebJSAdapter = class {
1182
1291
  if (raw.isStatus || isBroadcastId(chatId) || SYSTEM_TYPES.has(raw.type)) return;
1183
1292
  const id = serialize(raw.id);
1184
1293
  if (this._recent.has(id)) return;
1185
- this._recent.add(id);
1186
- if (this._recent.size > MAX_RECENT) this._recent.delete(this._recent.values().next().value);
1294
+ addRecent(this._recent, id);
1187
1295
  const threadId = this.encodeThreadId({ chatId });
1188
1296
  if (this._config.markSeen && !raw.fromMe) {
1189
1297
  await this.markAsRead(threadId).catch(
1190
1298
  (error) => this._logger.warn("Failed to send a read receipt", { error, threadId })
1191
1299
  );
1192
1300
  }
1193
- const author = this._author(raw);
1194
- if (await this._answer(raw, threadId, author) || this._command(raw, threadId, author)) {
1301
+ const isMe = raw.fromMe && (this._forwarded(raw) || await this._echo(id));
1302
+ const author = this._author(raw, isMe);
1303
+ if (!author.isMe && (await this._answer(raw, threadId, author) || this._command(raw, threadId, author))) {
1195
1304
  await this._remember(raw);
1196
1305
  return;
1197
1306
  }
1198
- const parsed = this._addons("onMessage").length > 0 ? await this._parse(raw) : void 0;
1307
+ const parsed = this._addons("onMessage").length > 0 ? await this._parse(raw, author) : void 0;
1199
1308
  if (!parsed || !await this._claimed(parsed, threadId)) {
1200
- await this._chat.processMessage(this, threadId, parsed ?? (() => this._parse(raw)));
1309
+ await this._chat.processMessage(this, threadId, parsed ?? (() => this._parse(raw, author)));
1201
1310
  }
1202
1311
  await this._remember(raw);
1203
1312
  }
@@ -1208,7 +1317,7 @@ var WWebJSAdapter = class {
1208
1317
  return { ...DEFAULT_MODAL_TEXTS, ...this._config.modalTexts };
1209
1318
  }
1210
1319
  async _start(threadId, userId, modal, form) {
1211
- if (!this._chat) throw new ValidationError3("wwebjs", "A modal needs Chat to be initialized.");
1320
+ if (!this._chat) throw new ValidationError4("wwebjs", "A modal needs Chat to be initialized.");
1212
1321
  const field = currentField(form);
1213
1322
  await this._chat.getState().set(this._formKey(threadId, userId), form, FORM_TTL_MS);
1214
1323
  const intro = introOf(modal, this._texts());
@@ -1344,12 +1453,16 @@ ${questionOf(first, retry, texts)}`);
1344
1453
  _seenKey() {
1345
1454
  return `wwebjs:${this.name}:seen`;
1346
1455
  }
1347
- /** Writes run in turn, so an older position never lands after a newer one. */
1456
+ /** Writes run in turn, so an older position never lands after a newer one; one that fails is written again by the watchdog. */
1348
1457
  _save() {
1349
1458
  const state = this._chat?.getState();
1350
1459
  if (!state) return Promise.resolve();
1351
- this._saving = this._saving.then(() => state.set(this._seenKey(), this._seen)).catch(
1352
- (error) => this._logger.warn("Could not record the last message delivered", { error })
1460
+ this._saving = this._saving.then(() => state.set(this._seenKey(), this._seen)).then(
1461
+ () => this._unsaved = false,
1462
+ (error) => {
1463
+ this._unsaved = true;
1464
+ this._logger.warn("Could not record the last message delivered", { error });
1465
+ }
1353
1466
  );
1354
1467
  return this._saving;
1355
1468
  }
@@ -1365,9 +1478,23 @@ ${questionOf(first, retry, texts)}`);
1365
1478
  const at = Math.min(raw.timestamp, Math.floor(Date.now() / 1e3) + CLOCK_SKEW_S);
1366
1479
  const { ids } = this._seen;
1367
1480
  if (at < this._seen.at || at === this._seen.at && ids.includes(id)) return false;
1368
- this._seen = { at, ids: at === this._seen.at ? [...ids, id] : [id], wid: this.botUserId };
1481
+ this._seen = this._position(at, at === this._seen.at ? [...ids, id] : [id]);
1369
1482
  return true;
1370
1483
  }
1484
+ _position(at, ids) {
1485
+ return { at, ids, own: this._config.receiveOwnMessages || void 0, wid: this.botUserId };
1486
+ }
1487
+ /** One that fails, reading its position or the chats, is owed, and the watchdog runs it again. */
1488
+ _catchUpNext() {
1489
+ this._owed = false;
1490
+ this._catching = this._catching.then(() => this._catchUp()).then(
1491
+ () => this._owed = false,
1492
+ (error) => {
1493
+ this._owed = true;
1494
+ this._logger.warn("Inbound catch-up was not handled", { error });
1495
+ }
1496
+ );
1497
+ }
1371
1498
  /** WhatsApp Web loads what arrived while the session was down without announcing every message. */
1372
1499
  async _catchUp() {
1373
1500
  const windowMs = this._config.catchUpMs ?? CATCH_UP_MS;
@@ -1377,7 +1504,7 @@ ${questionOf(first, retry, texts)}`);
1377
1504
  if (this._seen?.wid && this._seen.wid !== this.botUserId) this._seen = null;
1378
1505
  const seen = this._seen;
1379
1506
  if (!seen) {
1380
- this._seen = { at: Math.floor(Date.now() / 1e3), ids: [], wid: this.botUserId };
1507
+ this._seen = this._position(Math.floor(Date.now() / 1e3), []);
1381
1508
  await this._save();
1382
1509
  return;
1383
1510
  }
@@ -1398,7 +1525,7 @@ ${questionOf(first, retry, texts)}`);
1398
1525
  });
1399
1526
  const behind = messages.filter(unseen);
1400
1527
  truncated ||= behind.length === MAX_CATCH_UP_MESSAGES;
1401
- missed.push(...behind);
1528
+ missed.push(...behind.filter((message) => seen.own || !message.fromMe));
1402
1529
  }
1403
1530
  if (truncated) {
1404
1531
  this._logger.warn(
@@ -1419,13 +1546,16 @@ ${questionOf(first, retry, texts)}`);
1419
1546
  if (delivered.map((message) => this._advance(message)).some(Boolean)) await this._save();
1420
1547
  }
1421
1548
  }
1422
- _onEdit(raw, previousBody) {
1549
+ /** The account's edit of a message this adapter sent is the adapter's own; any other is the operator's. */
1550
+ async _onEdit(raw, previousBody) {
1423
1551
  if (this._isOwn(raw.fromMe)) return;
1552
+ const author = this._author(raw, raw.fromMe && await this._echo(serialize(raw.id)));
1424
1553
  this._chat?.processMessageUpdated({
1425
1554
  adapter: this,
1426
- message: () => this._parse(raw),
1555
+ message: () => this._parse(raw, author),
1427
1556
  previousMessage: async () => {
1428
1557
  const previous = this.parseMessage(raw);
1558
+ previous.author = author;
1429
1559
  previous.text = previousBody;
1430
1560
  previous.formatted = this._converter.toAst(previousBody);
1431
1561
  return previous;
@@ -1446,17 +1576,20 @@ ${questionOf(first, retry, texts)}`);
1446
1576
  threadId
1447
1577
  });
1448
1578
  }
1449
- _onReaction(reaction) {
1579
+ /** The account's reaction to a message this adapter reacted to is the adapter's own; any other is the operator's. */
1580
+ async _onReaction(reaction) {
1450
1581
  if (this._isOwn(reaction.id.fromMe)) return;
1582
+ const messageId = serialize(reaction.msgId);
1583
+ const isMe = reaction.id.fromMe && await this._marked(`reacted:${messageId}`);
1451
1584
  this._chat?.processReaction({
1452
1585
  adapter: this,
1453
1586
  added: reaction.reaction.length > 0,
1454
1587
  emoji: defaultEmojiResolver.fromGChat(reaction.reaction),
1455
- messageId: serialize(reaction.msgId),
1588
+ messageId,
1456
1589
  raw: reaction,
1457
1590
  rawEmoji: reaction.reaction,
1458
1591
  threadId: this.encodeThreadId({ chatId: serialize(reaction.id.remote) }),
1459
- user: participantAuthor(serialize(reaction.senderId), reaction.id.fromMe)
1592
+ user: participantAuthor(serialize(reaction.senderId), isMe)
1460
1593
  });
1461
1594
  }
1462
1595
  _onAck(raw, ack) {
@@ -1522,8 +1655,9 @@ ${questionOf(first, retry, texts)}`);
1522
1655
  }
1523
1656
  }
1524
1657
  }
1525
- async _parse(raw) {
1658
+ async _parse(raw, author) {
1526
1659
  const parsed = this.parseMessage(raw);
1660
+ parsed.author = author;
1527
1661
  const bot = this._botUsers();
1528
1662
  const others = [
1529
1663
  ...new Set((raw.mentionedIds ?? []).map(serialize).filter((id) => !bot.has(toUser(id))))
@@ -1541,18 +1675,19 @@ ${questionOf(first, retry, texts)}`);
1541
1675
  if (raw.hasQuotedMsg) {
1542
1676
  const quoted = await within(raw.getQuotedMessage());
1543
1677
  if (quoted) parsed.replyTo = this.parseMessage(quoted);
1544
- if (quoted?.fromMe) parsed.isMention = true;
1678
+ if (quoted?.fromMe && !raw.fromMe) parsed.isMention = true;
1545
1679
  }
1546
1680
  return parsed;
1547
1681
  }
1548
- _author(raw) {
1682
+ /** The account's own messages come from `botUserId`, whether the adapter sent them or its owner did. */
1683
+ _author(raw, isMe = raw.fromMe) {
1549
1684
  const chatId = chatIdOf(raw);
1550
1685
  const userId = raw.fromMe ? this.botUserId ?? chatId : isGroupId(chatId) ? raw.author ?? chatId : chatId;
1551
1686
  const pushName = raw.rawData?.notifyName;
1552
1687
  return {
1553
1688
  fullName: pushName ?? "",
1554
- isBot: raw.fromMe,
1555
- isMe: raw.fromMe,
1689
+ isBot: isMe,
1690
+ isMe,
1556
1691
  userId,
1557
1692
  userName: pushName || toUser(userId)
1558
1693
  };
@@ -1645,6 +1780,8 @@ ${questionOf(first, retry, texts)}`);
1645
1780
  return;
1646
1781
  }
1647
1782
  if (this._state !== "connected") return;
1783
+ if (this._owed) this._catchUpNext();
1784
+ if (this._unsaved) void this._save();
1648
1785
  const state = await within(this.client.getState());
1649
1786
  if (state === "CONNECTED") {
1650
1787
  this._strikes = 0;
@@ -1706,7 +1843,7 @@ ${questionOf(first, retry, texts)}`);
1706
1843
  });
1707
1844
  let first;
1708
1845
  for (const [content, sendOptions] of payloads) {
1709
- const sent = await this.client.sendMessage(
1846
+ const sent = await this._post(
1710
1847
  chatId,
1711
1848
  content,
1712
1849
  first ? { ...sendOptions, quotedMessageId: void 0 } : sendOptions
@@ -1719,13 +1856,54 @@ ${questionOf(first, retry, texts)}`);
1719
1856
  }
1720
1857
  async _sendContent(threadId, content, options) {
1721
1858
  const { chatId } = this.decodeThreadId(threadId);
1722
- return this._raw(await this.client.sendMessage(chatId, content, options), threadId);
1859
+ return this._raw(await this._post(chatId, content, options), threadId);
1860
+ }
1861
+ /** Every send goes through here, under way before it starts, so its echo stays the adapter's own even when it arrives before the id. */
1862
+ async _post(chatId, content, options) {
1863
+ if (!this._config.receiveOwnMessages) return this.client.sendMessage(chatId, content, options);
1864
+ let settle;
1865
+ const sending = new Promise((resolve) => settle = resolve);
1866
+ this._sending.add(sending);
1867
+ try {
1868
+ const sent = await this.client.sendMessage(chatId, content, options);
1869
+ if (sent) await this._mark(`sent:${serialize(sent.id)}`);
1870
+ return sent;
1871
+ } finally {
1872
+ this._sending.delete(sending);
1873
+ settle();
1874
+ }
1875
+ }
1876
+ /** Kept in state too, for as long as a catch-up reaches back, so an echo replayed after a restart is still its own. */
1877
+ async _mark(key) {
1878
+ if (!this._config.receiveOwnMessages) return;
1879
+ addRecent(this._own, key);
1880
+ await this._chat?.getState().set(this._ownKey(key), true, this._config.catchUpMs || CATCH_UP_MS).catch(
1881
+ (error) => this._logger.warn("Could not record what the adapter did", { error, key })
1882
+ );
1883
+ }
1884
+ async _marked(key) {
1885
+ return this._own.has(key) || !!await this._chat?.getState().get(this._ownKey(key));
1886
+ }
1887
+ _ownKey(key) {
1888
+ return `wwebjs:${this.name}:${key}`;
1889
+ }
1890
+ /** whatsapp-web.js can emit a send's echo before `sendMessage()` returns its id, so the sends under way settle first. */
1891
+ async _echo(id) {
1892
+ await Promise.allSettled(this._sending);
1893
+ return this._marked(`sent:${id}`);
1894
+ }
1895
+ /** Claimed on arrival, by a forward the adapter made that no echo has claimed yet. */
1896
+ _forwarded(raw) {
1897
+ if (!raw.isForwarded || this._forwards === 0) return false;
1898
+ this._forwards--;
1899
+ void this._mark(`sent:${serialize(raw.id)}`);
1900
+ return true;
1723
1901
  }
1724
1902
  _raw(sent, threadId) {
1725
1903
  if (!sent) {
1726
- throw new ValidationError3(
1904
+ throw new ValidationError4(
1727
1905
  "wwebjs",
1728
- "WhatsApp did not return the sent message. whatsapp-web.js 1.34.7 and older cannot read current WhatsApp Web; install github:pedroslopez/whatsapp-web.js#064a3d5."
1906
+ `WhatsApp did not return the sent message. whatsapp-web.js 1.34.8 and older cannot read current WhatsApp Web; install ${TESTED_WWEBJS}.`
1729
1907
  );
1730
1908
  }
1731
1909
  return { id: sent.id._serialized, raw: sent, threadId };
@@ -1789,6 +1967,10 @@ function chatIdOf(message) {
1789
1967
  function locationText({ address, latitude, longitude, name }) {
1790
1968
  return [name, address, `https://maps.google.com/?q=${latitude},${longitude}`].filter(Boolean).join("\n");
1791
1969
  }
1970
+ function addRecent(ids, id) {
1971
+ ids.add(id);
1972
+ if (ids.size > MAX_RECENT) ids.delete(ids.values().next().value);
1973
+ }
1792
1974
  function within(lookup) {
1793
1975
  return Promise.race([
1794
1976
  lookup.catch(() => null),
@@ -1803,7 +1985,7 @@ function participantAuthor(userId, isMe) {
1803
1985
  }
1804
1986
  function assertRange(label, value, bound) {
1805
1987
  if (!Number.isFinite(value) || value < -bound || value > bound) {
1806
- throw new ValidationError3(
1988
+ throw new ValidationError4(
1807
1989
  "wwebjs",
1808
1990
  `sendLocation: ${label} must be between -${bound} and ${bound}. Received ${value}.`
1809
1991
  );
@@ -1811,14 +1993,14 @@ function assertRange(label, value, bound) {
1811
1993
  }
1812
1994
 
1813
1995
  // src/guards.ts
1814
- import { ValidationError as ValidationError4 } from "@chat-adapter/shared";
1996
+ import { ValidationError as ValidationError5 } from "@chat-adapter/shared";
1815
1997
  function isWWebJSAdapter(value) {
1816
1998
  return value instanceof WWebJSAdapter;
1817
1999
  }
1818
2000
  function requireWWebJSAdapter(value) {
1819
2001
  const adapter = value && typeof value === "object" && "adapter" in value ? value.adapter : value;
1820
2002
  if (isWWebJSAdapter(adapter)) return adapter;
1821
- throw new ValidationError4("wwebjs", "This context does not belong to a wwebjs adapter.");
2003
+ throw new ValidationError5("wwebjs", "This context does not belong to a wwebjs adapter.");
1822
2004
  }
1823
2005
 
1824
2006
  // src/numbered-actions.ts
@@ -1868,7 +2050,7 @@ function numberedActions(options = {}) {
1868
2050
  await context.chat.getState().set(keyOf(context), { choices, messageId }, options.ttlMs ?? TTL_MS);
1869
2051
  },
1870
2052
  async onMessage(message, context) {
1871
- if (message.author.isMe || !context.chat) return false;
2053
+ if (message.raw.fromMe || !context.chat) return false;
1872
2054
  const state = context.chat.getState();
1873
2055
  const offer = await state.get(keyOf(context));
1874
2056
  if (!offer || message.replyTo && message.replyTo.id !== offer.messageId) return false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chat-adapter-wwebjs",
3
- "version": "0.1.5",
3
+ "version": "0.2.1",
4
4
  "description": "WhatsApp adapter for Chat SDK, backed by whatsapp-web.js",
5
5
  "author": "nivandres",
6
6
  "license": "MIT",
@@ -60,10 +60,10 @@
60
60
  "oxlint": "^1.61.0",
61
61
  "prettier": "^3.8.3",
62
62
  "qrcode-terminal": "^0.12.0",
63
- "tsup": "^8.3.0",
63
+ "tsup": "^9.0.0",
64
64
  "typescript": "^5.7.0",
65
65
  "vitest": "^5.1.0",
66
- "whatsapp-web.js": "github:pedroslopez/whatsapp-web.js#064a3d5"
66
+ "whatsapp-web.js": "github:pedroslopez/whatsapp-web.js#38eb45b2759450cc6fccb6a7a3f2cbc3bdb87db2"
67
67
  },
68
68
  "publishConfig": {
69
69
  "access": "public"