chat-adapter-wwebjs 0.1.2 → 0.1.3

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/dist/index.js CHANGED
@@ -1,10 +1,7 @@
1
1
  // src/adapter.ts
2
- import {
3
- cardToFallbackText,
4
- extractCard,
5
- ResourceNotFoundError,
6
- ValidationError as ValidationError2
7
- } from "@chat-adapter/shared";
2
+ import { randomUUID } from "crypto";
3
+ import { once } from "events";
4
+ import { extractCard, ResourceNotFoundError, ValidationError as ValidationError3 } from "@chat-adapter/shared";
8
5
  import {
9
6
  ConsoleLogger,
10
7
  defaultEmojiResolver,
@@ -14,11 +11,15 @@ import {
14
11
  // src/format-converter.ts
15
12
  import {
16
13
  BaseFormatConverter,
14
+ cardChildToFallbackText,
15
+ chartElementToFallbackText,
17
16
  getNodeChildren,
18
17
  parseMarkdown,
18
+ tableElementToAscii,
19
19
  tableToAscii
20
20
  } from "chat";
21
21
  var MAX_MARKDOWN_LENGTH = 16e3;
22
+ var DIVIDER = "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500";
22
23
  function plain(value) {
23
24
  return { children: [{ children: [{ type: "text", value }], type: "paragraph" }], type: "root" };
24
25
  }
@@ -70,7 +71,7 @@ ${node.value}
70
71
  ${tableToAscii(node)}
71
72
  \`\`\``;
72
73
  case "thematicBreak":
73
- return "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500";
74
+ return DIVIDER;
74
75
  default:
75
76
  return this.defaultNodeToText(node, (child) => this.toWhatsApp(child));
76
77
  }
@@ -79,6 +80,40 @@ ${tableToAscii(node)}
79
80
  return getNodeChildren(node).map((child) => this.toWhatsApp(child)).join(separator);
80
81
  }
81
82
  };
83
+ function childText(child) {
84
+ switch (child.type) {
85
+ case "text":
86
+ return child.style === "bold" ? `*${child.content}*` : child.style === "muted" ? `_${child.content}_` : child.content;
87
+ case "link":
88
+ return `${child.label}: ${child.url}`;
89
+ case "fields":
90
+ return child.children.map(({ label, value }) => `*${label}:* ${value}`).join("\n");
91
+ case "table":
92
+ return `\`\`\`
93
+ ${tableElementToAscii(child.headers, child.rows)}
94
+ \`\`\``;
95
+ case "chart":
96
+ return chartElementToFallbackText(child);
97
+ case "section":
98
+ return child.children.map(childText).filter(Boolean).join("\n");
99
+ case "divider":
100
+ return DIVIDER;
101
+ default:
102
+ return "";
103
+ }
104
+ }
105
+ function cardToText(card) {
106
+ return [card.title && `*${card.title}*`, card.subtitle, ...card.children.map(childText)].filter(Boolean).join("\n");
107
+ }
108
+ function cardToPlainText(card) {
109
+ return [card.title, card.subtitle, ...card.children.map(cardChildToFallbackText)].filter(Boolean).join("\n");
110
+ }
111
+ function cardImages(card) {
112
+ const inside = (children) => children.flatMap(
113
+ (child) => child.type === "image" ? [child.url] : child.type === "section" ? inside(child.children) : []
114
+ );
115
+ return [...card.imageUrl ? [card.imageUrl] : [], ...inside(card.children)];
116
+ }
82
117
 
83
118
  // src/jid.ts
84
119
  var BROADCAST_SUFFIX = "@broadcast";
@@ -115,15 +150,16 @@ function extractMentions(text) {
115
150
  mentions.add(chatId);
116
151
  return `@${toUser(chatId)}`;
117
152
  });
118
- const named = new Set([...mentions].map(toUser));
119
- for (const [, user] of rendered.matchAll(/@(\d{6,})\b/g)) {
120
- if (user && !named.has(user)) mentions.add(`${user}${USER_SUFFIX}`);
121
- }
122
153
  return { mentions: [...mentions], text: rendered };
123
154
  }
124
155
 
125
156
  // src/media.ts
126
- import { extractFiles, extractPostableAttachments, ValidationError } from "@chat-adapter/shared";
157
+ import {
158
+ downloadAttachment,
159
+ extractFiles,
160
+ extractPostableAttachments,
161
+ ValidationError
162
+ } from "@chat-adapter/shared";
127
163
 
128
164
  // src/wwebjs.ts
129
165
  import wwebjs from "whatsapp-web.js";
@@ -158,7 +194,6 @@ var MIME_TYPES = {
158
194
  };
159
195
  var DEFAULT_MIME_TYPE = "application/octet-stream";
160
196
  var DEFAULT_MAX_MEDIA_BYTES = 64 * 1024 * 1024;
161
- var URL_TIMEOUT_MS = 3e4;
162
197
  function toAttachments(message, maxBytes) {
163
198
  if (!message.hasMedia) return [];
164
199
  const data = message.rawData ?? {};
@@ -183,6 +218,9 @@ async function download(message, maxBytes = DEFAULT_MAX_MEDIA_BYTES) {
183
218
  if (downloadMediaStream) {
184
219
  const streamed = await downloadMediaStream.call(message);
185
220
  if (!streamed) throw unavailable(message.id._serialized);
221
+ if (streamed.blobSize && streamed.blobSize > maxBytes) {
222
+ throw tooLarge(message.id._serialized, streamed.blobSize, maxBytes);
223
+ }
186
224
  return collect(streamed.stream, maxBytes, message.id._serialized);
187
225
  }
188
226
  const media = await message.downloadMedia();
@@ -226,18 +264,24 @@ function isCaptionable(media) {
226
264
  function isAudio(media) {
227
265
  return media.mimetype.startsWith("audio/");
228
266
  }
267
+ function isVoiceNote(media) {
268
+ return media.mimetype.startsWith("audio/ogg");
269
+ }
229
270
  function mimeTypeOf(filename) {
230
271
  const extension = filename?.split(".").pop()?.toLowerCase();
231
272
  return extension && Object.hasOwn(MIME_TYPES, extension) && MIME_TYPES[extension] || DEFAULT_MIME_TYPE;
232
273
  }
233
274
  async function fetchMedia(url, source, maxBytes) {
234
- const response = await fetch(url, { signal: AbortSignal.timeout(URL_TIMEOUT_MS) });
235
- if (!response.ok || !response.body) {
236
- throw new ValidationError("wwebjs", `Could not fetch ${url}: HTTP ${response.status}.`);
237
- }
238
- const data = await collect(response.body, maxBytes, url);
275
+ let contentType;
276
+ const data = await downloadAttachment(url, {
277
+ adapter: "wwebjs",
278
+ limit: maxBytes,
279
+ onResponse: (response) => {
280
+ contentType = response.headers["content-type"]?.split(";")[0];
281
+ }
282
+ });
239
283
  const name = source.name ?? new URL(url).pathname.split("/").pop() ?? null;
240
- const mimeType = source.mimeType ?? response.headers.get("content-type")?.split(";")[0] ?? mimeTypeOf(name ?? void 0);
284
+ const mimeType = source.mimeType ?? contentType ?? mimeTypeOf(name ?? void 0);
241
285
  return new MessageMedia(mimeType, data.toString("base64"), name);
242
286
  }
243
287
  async function collect(stream, maxBytes, label) {
@@ -268,12 +312,145 @@ async function toBase64(data) {
268
312
  return Buffer.from(await data.arrayBuffer()).toString("base64");
269
313
  }
270
314
 
315
+ // src/modals.ts
316
+ import { ValidationError as ValidationError2 } from "@chat-adapter/shared";
317
+ var DEFAULT_MODAL_TEXTS = {
318
+ cancel: "cancel",
319
+ cancelHint: "Send *cancel* to stop.",
320
+ cancelled: "Cancelled.",
321
+ invalid: "That doesn't fit. Try again:",
322
+ noResults: "Nothing matched. Try other words:",
323
+ search: "Send a few words to search.",
324
+ skip: "skip",
325
+ skipHint: "Send *skip* to leave it as it is."
326
+ };
327
+ var INPUTS = /* @__PURE__ */ new Set([
328
+ "date_input",
329
+ "external_select",
330
+ "number_input",
331
+ "radio_select",
332
+ "select",
333
+ "text_input"
334
+ ]);
335
+ function triggerIdOf(threadId, userId) {
336
+ return JSON.stringify([threadId, userId]);
337
+ }
338
+ function fromTrigger(triggerId) {
339
+ let ids;
340
+ try {
341
+ ids = JSON.parse(triggerId);
342
+ } catch {
343
+ ids = void 0;
344
+ }
345
+ const [threadId, userId] = Array.isArray(ids) ? ids : [];
346
+ if (typeof threadId === "string" && typeof userId === "string") return [threadId, userId];
347
+ throw new ValidationError2("wwebjs", `Not a trigger this adapter issued: ${triggerId}`);
348
+ }
349
+ function createForm(modal, viewId, contextId) {
350
+ const fields = modal.children.filter((child) => INPUTS.has(child.type));
351
+ return {
352
+ callbackId: modal.callbackId,
353
+ closeLabel: modal.closeLabel,
354
+ contextId,
355
+ fields,
356
+ notifyOnClose: modal.notifyOnClose,
357
+ pending: fields.map(({ id }) => id),
358
+ privateMetadata: modal.privateMetadata,
359
+ values: {},
360
+ viewId
361
+ };
362
+ }
363
+ function introOf(modal, texts) {
364
+ const shown = modal.children.filter((child) => child.type === "text" || child.type === "fields");
365
+ return [
366
+ cardToText({ children: shown, title: modal.title, type: "card" }),
367
+ `_${texts.cancelHint}_`
368
+ ].filter(Boolean).join("\n\n");
369
+ }
370
+ function currentField(form) {
371
+ return form.fields.find(({ id }) => id === form.pending[0]);
372
+ }
373
+ function optionsOf(field, form) {
374
+ if (field.type === "select" || field.type === "radio_select") return field.options;
375
+ return field.type === "external_select" ? form.found : void 0;
376
+ }
377
+ function initialOf(field) {
378
+ switch (field.type) {
379
+ case "select":
380
+ case "radio_select":
381
+ return field.initialOption;
382
+ case "external_select":
383
+ return field.initialOption?.value;
384
+ case "number_input":
385
+ return field.initialValue === void 0 ? void 0 : String(field.initialValue);
386
+ default:
387
+ return field.initialValue;
388
+ }
389
+ }
390
+ function questionOf(field, form, texts) {
391
+ const options = optionsOf(field, form);
392
+ const initial = initialOf(field);
393
+ const shown = field.type === "external_select" ? field.initialOption?.label : options?.find(({ value }) => value === initial)?.label ?? initial;
394
+ const range = field.type === "number_input" && [field.min, field.max].some((n) => n !== void 0);
395
+ return [
396
+ `*${field.label}*`,
397
+ "placeholder" in field && field.placeholder && `_${field.placeholder}_`,
398
+ options?.map(
399
+ (option, index) => [`${index + 1}. ${option.label}`, option.description].filter(Boolean).join(": ")
400
+ ).join("\n"),
401
+ field.type === "date_input" && "_YYYY-MM-DD_",
402
+ range && `_${field.min ?? "\u2026"} \u2013 ${field.max ?? "\u2026"}_`,
403
+ field.type === "external_select" && !options && `_${texts.search}_`,
404
+ (field.optional || initial !== void 0) && `_${texts.skipHint}_${shown === void 0 ? "" : ` (${shown})`}`
405
+ ].filter(Boolean).join("\n");
406
+ }
407
+ function pick(options, text) {
408
+ return /^\d+$/.test(text) ? options[Number(text) - 1] : options.find(({ label }) => label.toLowerCase() === text.toLowerCase());
409
+ }
410
+ function answerOf(field, form, text, texts) {
411
+ const invalid = { error: texts.invalid };
412
+ if (text.toLowerCase() === texts.skip.toLowerCase()) {
413
+ const initial = initialOf(field);
414
+ return field.optional || initial !== void 0 ? { value: initial } : invalid;
415
+ }
416
+ switch (field.type) {
417
+ case "text_input":
418
+ return text && text.length <= (field.maxLength ?? Infinity) ? { value: text } : invalid;
419
+ case "number_input": {
420
+ const number = Number(text.replace(",", "."));
421
+ const fits = text !== "" && Number.isFinite(number) && (field.decimal || Number.isInteger(number)) && number >= (field.min ?? -Infinity) && number <= (field.max ?? Infinity);
422
+ return fits ? { value: String(number) } : invalid;
423
+ }
424
+ case "date_input": {
425
+ const date = /* @__PURE__ */ new Date(`${text}T00:00:00Z`);
426
+ const valid = /^\d{4}-\d{2}-\d{2}$/.test(text) && !Number.isNaN(date.getTime()) && date.toISOString().startsWith(text);
427
+ return valid ? { value: text } : invalid;
428
+ }
429
+ case "external_select": {
430
+ const chosen = form.found && pick(form.found, text);
431
+ if (chosen) return { value: chosen.value };
432
+ return text.length >= (field.minQueryLength ?? 1) ? { search: text } : invalid;
433
+ }
434
+ default: {
435
+ const chosen = pick(field.options, text);
436
+ return chosen ? { value: chosen.value } : invalid;
437
+ }
438
+ }
439
+ }
440
+ function flattenOptions(result) {
441
+ return (result ?? []).flatMap((entry) => "options" in entry ? entry.options : [entry]);
442
+ }
443
+
271
444
  // src/shutdown.ts
272
445
  var SIGNALS = ["SIGHUP", "SIGINT", "SIGTERM"];
446
+ var CLOSE_TIMEOUT_MS = 8e3;
273
447
  var sessions = /* @__PURE__ */ new Set();
274
448
  async function onSignal(signal) {
275
449
  for (const name of SIGNALS) process.off(name, onSignal);
276
- await Promise.allSettled([...sessions].map((close) => close()));
450
+ await Promise.race([
451
+ Promise.allSettled([...sessions].map((close) => close())),
452
+ new Promise((resolve) => setTimeout(resolve, CLOSE_TIMEOUT_MS).unref())
453
+ ]);
277
454
  if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);
278
455
  }
279
456
  function closeOnSignal(close) {
@@ -325,11 +502,16 @@ var CONNECT_TIMEOUT_MS = 12e4;
325
502
  var WATCHDOG_INTERVAL_MS = 6e4;
326
503
  var RECONNECT_MIN_MS = 5e3;
327
504
  var RECONNECT_MAX_MS = 3e5;
505
+ var KILL_WAIT_MS = 2e3;
506
+ var STREAM_EDIT_MS = 1e3;
507
+ var FORM_TTL_MS = 864e5;
328
508
  var MAX_POLL_OPTIONS = 12;
329
509
  var MIN_POLL_OPTIONS = 2;
330
510
  var CATCH_UP_MS = 864e5;
331
511
  var MAX_CATCH_UP_CHATS = 100;
332
512
  var MAX_CATCH_UP_MESSAGES = 50;
513
+ var MAX_RECENT = 1e3;
514
+ var CLOCK_SKEW_S = 60;
333
515
  var RECOMMENDED_CHROMIUM_ARGS = [
334
516
  "--renderer-process-limit=1",
335
517
  "--disable-gpu",
@@ -341,6 +523,13 @@ var WWebJSAdapter = class {
341
523
  /** The underlying whatsapp-web.js client, for anything this adapter does not wrap. */
342
524
  client;
343
525
  userName;
526
+ /**
527
+ * WhatsApp has no modals, so with `richContent` one becomes a conversation:
528
+ * each field is asked in turn, a select by number, and the answers reach
529
+ * `onModalSubmit`. `cancel`, or the modal's `closeLabel`, stops it. Absent
530
+ * otherwise, so the SDK knows a modal cannot open.
531
+ */
532
+ openModal;
344
533
  _config;
345
534
  _converter = new WWebJSFormatConverter();
346
535
  _ackHandlers = [];
@@ -357,19 +546,33 @@ var WWebJSAdapter = class {
357
546
  _state = "idle";
358
547
  _watchdog;
359
548
  _strikes = 0;
549
+ _owned;
550
+ _attempts = 0;
551
+ _launch;
552
+ _unwatch;
553
+ _listeners = [];
360
554
  _unsignal;
361
555
  _seen;
556
+ _behind;
557
+ _recent = /* @__PURE__ */ new Set();
362
558
  _saving = Promise.resolve();
363
559
  constructor(config = {}) {
364
560
  const name = config.adapterName ?? "wwebjs";
365
561
  if (name.includes(":")) {
366
- throw new ValidationError2("wwebjs", `Invalid adapterName "${name}". ":" is not allowed.`);
562
+ throw new ValidationError3("wwebjs", `Invalid adapterName "${name}". ":" is not allowed.`);
367
563
  }
368
564
  this._config = config;
369
565
  this.name = name;
370
566
  this.userName = config.userName ?? "wwebjs-bot";
371
567
  this._logger = config.logger ?? new ConsoleLogger("info").child(name);
372
568
  this.client = config.client ?? new Client(this._clientOptions());
569
+ if (config.client?.constructor.name === "Client" && !(config.client instanceof Client)) {
570
+ this._logger.warn(
571
+ "This client comes from another copy of whatsapp-web.js than the adapter's, so the media, locations and polls it sends will fail. Install a single copy: it is a peer dependency."
572
+ );
573
+ }
574
+ this._owned = config.manageClient ?? !config.client?.pupBrowser?.isConnected();
575
+ if (config.richContent) this.openModal = (...args) => this._openModal(...args);
373
576
  this._listen();
374
577
  }
375
578
  /** Where the session stands; a health check reads `connection === "connected"`. */
@@ -399,18 +602,23 @@ var WWebJSAdapter = class {
399
602
  this._closed = false;
400
603
  clearTimeout(this._retry);
401
604
  this._retry = void 0;
605
+ if (this._listeners.length === 0) this._listen();
402
606
  this._watch();
403
- if (this._config.handleSignals !== false) {
607
+ if (this._owned && this._config.handleSignals !== false) {
404
608
  this._unsignal ??= closeOnSignal(() => this.disconnect());
405
609
  }
406
- this._connection ??= this._connect().catch((error) => {
407
- this._connection = null;
408
- if (this._state !== "logged_out" && !this._closed) this._state = "disconnected";
610
+ if (this._connection) return this._connection;
611
+ const attempt = ++this._attempts;
612
+ this._connection = this._connect(attempt).catch((error) => {
613
+ if (attempt === this._attempts) {
614
+ this._connection = null;
615
+ if (this._state !== "logged_out" && !this._closed) this._state = "disconnected";
616
+ }
409
617
  throw error;
410
618
  });
411
619
  return this._connection;
412
620
  }
413
- /** Close the browser session. */
621
+ /** Close the browser session, or only detach from a client the adapter does not manage. */
414
622
  async disconnect() {
415
623
  this._closed = true;
416
624
  this._state = "closed";
@@ -420,7 +628,9 @@ var WWebJSAdapter = class {
420
628
  this._connection = null;
421
629
  this._unsignal?.();
422
630
  this._unsignal = void 0;
423
- await this.client.destroy();
631
+ await this._saving;
632
+ if (!this._owned) return this._unlisten();
633
+ await this._close();
424
634
  }
425
635
  encodeThreadId(platformData) {
426
636
  return `${this.name}:${platformData.chatId}`;
@@ -428,7 +638,7 @@ var WWebJSAdapter = class {
428
638
  decodeThreadId(threadId) {
429
639
  const prefix = `${this.name}:`;
430
640
  if (!threadId.startsWith(prefix)) {
431
- throw new ValidationError2("wwebjs", `Invalid WhatsApp thread ID: ${threadId}`);
641
+ throw new ValidationError3("wwebjs", `Invalid WhatsApp thread ID: ${threadId}`);
432
642
  }
433
643
  return { chatId: threadId.slice(prefix.length) };
434
644
  }
@@ -457,7 +667,7 @@ var WWebJSAdapter = class {
457
667
  parseMessage(raw) {
458
668
  const bot = this._botUsers();
459
669
  const text = this._named(
460
- raw.body ?? "",
670
+ raw.location ? locationText(raw.location) : raw.body ?? "",
461
671
  this._mentioned(raw).filter((user) => bot.has(user)),
462
672
  () => this.userName
463
673
  );
@@ -490,7 +700,7 @@ var WWebJSAdapter = class {
490
700
  async editMessage(threadId, messageId, message) {
491
701
  const { card, text: rendered } = this._render(message, threadId);
492
702
  const { mentions, text } = extractMentions(rendered);
493
- const target = await this._requireMessage(messageId);
703
+ const target = await this._requireMessage(messageId, threadId);
494
704
  const edit = () => target.edit(text, mentions.length > 0 ? { mentions } : void 0);
495
705
  let edited = await edit();
496
706
  const fresh = target.fromMe && Date.now() - target.timestamp * 1e3 < FRESH_MS;
@@ -499,7 +709,7 @@ var WWebJSAdapter = class {
499
709
  edited = await edit();
500
710
  }
501
711
  if (!edited) {
502
- throw new ValidationError2(
712
+ throw new ValidationError3(
503
713
  "wwebjs",
504
714
  `Message ${messageId} could not be edited. WhatsApp only allows editing your own messages within 15 minutes.`
505
715
  );
@@ -508,14 +718,33 @@ var WWebJSAdapter = class {
508
718
  await this._cardSent(card, raw.id, threadId);
509
719
  return raw;
510
720
  }
511
- async deleteMessage(_threadId, messageId) {
512
- await (await this._requireMessage(messageId)).delete(true);
721
+ /** WhatsApp cannot stream, and editing twice a second as the SDK otherwise would floods the chat; the reply goes out once, whole. */
722
+ async stream(threadId, textStream) {
723
+ const edits = this._config.streaming === "edit";
724
+ let text = "";
725
+ let sent;
726
+ let shown = "";
727
+ let at = 0;
728
+ for await (const chunk of textStream) {
729
+ if (typeof chunk === "string") text += chunk;
730
+ else if (chunk.type === "markdown_text") text += chunk.text;
731
+ if (!edits || !text.trim() || Date.now() - at < STREAM_EDIT_MS) continue;
732
+ sent = sent ? await this.editMessage(threadId, sent.id, { markdown: text }).catch(() => sent) : await this.postMessage(threadId, { markdown: text });
733
+ shown = text;
734
+ at = Date.now();
735
+ }
736
+ if (!text.trim()) return null;
737
+ if (!sent) return this.postMessage(threadId, { markdown: text });
738
+ return text === shown ? sent : this.editMessage(threadId, sent.id, { markdown: text });
739
+ }
740
+ async deleteMessage(threadId, messageId) {
741
+ await (await this._requireMessage(messageId, threadId)).delete(true);
513
742
  }
514
- async addReaction(_threadId, messageId, emoji) {
515
- await (await this._requireMessage(messageId)).react(defaultEmojiResolver.toGChat(emoji));
743
+ async addReaction(threadId, messageId, emoji) {
744
+ await (await this._requireMessage(messageId, threadId)).react(defaultEmojiResolver.toGChat(emoji));
516
745
  }
517
- async removeReaction(_threadId, messageId, _emoji) {
518
- await (await this._requireMessage(messageId)).react("");
746
+ async removeReaction(threadId, messageId, _emoji) {
747
+ await (await this._requireMessage(messageId, threadId)).react("");
519
748
  }
520
749
  async fetchMessages(threadId, options) {
521
750
  return this._page(await this._requireChat(threadId), options);
@@ -523,8 +752,8 @@ var WWebJSAdapter = class {
523
752
  async fetchChannelMessages(channelId, options) {
524
753
  return this.fetchMessages(channelId, options);
525
754
  }
526
- async fetchMessage(_threadId, messageId) {
527
- const message = await this.client.getMessageById(messageId).catch(() => null);
755
+ async fetchMessage(threadId, messageId) {
756
+ const message = await this._findMessage(messageId, threadId);
528
757
  return message ? this.parseMessage(message) : null;
529
758
  }
530
759
  async fetchThread(threadId) {
@@ -551,9 +780,39 @@ var WWebJSAdapter = class {
551
780
  name: chat?.name
552
781
  };
553
782
  }
554
- /** WhatsApp conversations are flat, so a channel never contains sub-threads. */
555
- async listThreads() {
556
- return { threads: [] };
783
+ /** A WhatsApp chat is one flat conversation, so a channel holds just its own thread. */
784
+ async listThreads(channelId) {
785
+ const chat = await this._findChat(this.decodeThreadId(channelId).chatId);
786
+ return { threads: chat ? this._summaries([chat]) : [] };
787
+ }
788
+ /** Every chat the account has, newest first, with its latest message: an inbox's list. */
789
+ async listChats(options) {
790
+ const chats = (await this.client.getChats()).filter(
791
+ (chat) => !isBroadcastId(serialize(chat.id))
792
+ );
793
+ const start = Number(options?.cursor) || 0;
794
+ const end = start + Math.max(1, options?.limit ?? DEFAULT_LIMIT);
795
+ return {
796
+ nextCursor: end < chats.length ? String(end) : void 0,
797
+ threads: this._summaries(chats.slice(start, end))
798
+ };
799
+ }
800
+ _summaries(chats) {
801
+ return chats.flatMap(
802
+ (chat) => chat.lastMessage ? [
803
+ {
804
+ id: this.encodeThreadId({ chatId: serialize(chat.id) }),
805
+ lastReplyAt: new Date(chat.lastMessage.timestamp * 1e3),
806
+ rootMessage: this.parseMessage(chat.lastMessage)
807
+ }
808
+ ] : []
809
+ );
810
+ }
811
+ async _openModal(triggerId, modal, contextId) {
812
+ const [threadId, userId] = fromTrigger(triggerId);
813
+ const form = createForm(modal, randomUUID(), contextId);
814
+ await this._start(threadId, userId, modal, form);
815
+ return { viewId: form.viewId };
557
816
  }
558
817
  async getUser(userId) {
559
818
  const contact = await this.client.getContactById(toChatId(userId)).catch(() => null);
@@ -613,7 +872,7 @@ var WWebJSAdapter = class {
613
872
  /** Send a native WhatsApp poll. Between 2 and 12 options. */
614
873
  async sendPoll(args) {
615
874
  if (args.options.length < MIN_POLL_OPTIONS || args.options.length > MAX_POLL_OPTIONS) {
616
- throw new ValidationError2(
875
+ throw new ValidationError3(
617
876
  "wwebjs",
618
877
  `sendPoll: WhatsApp polls need between ${MIN_POLL_OPTIONS} and ${MAX_POLL_OPTIONS} options. Received ${args.options.length}.`
619
878
  );
@@ -681,7 +940,7 @@ var WWebJSAdapter = class {
681
940
  async fetchGroupParticipants(threadId) {
682
941
  const chat = await this._requireChat(threadId);
683
942
  if (!isGroupChat(chat)) {
684
- throw new ValidationError2("wwebjs", "fetchGroupParticipants: thread is not a group.");
943
+ throw new ValidationError3("wwebjs", "fetchGroupParticipants: thread is not a group.");
685
944
  }
686
945
  return chat.participants.map((participant) => ({
687
946
  isAdmin: participant.isAdmin || participant.isSuperAdmin,
@@ -731,7 +990,7 @@ var WWebJSAdapter = class {
731
990
  return;
732
991
  }
733
992
  if (!second) {
734
- throw new ValidationError2(
993
+ throw new ValidationError3(
735
994
  "wwebjs",
736
995
  "onPollVote: a handler is required when filtering by poll message ID."
737
996
  );
@@ -773,12 +1032,12 @@ var WWebJSAdapter = class {
773
1032
  }
774
1033
  return options;
775
1034
  }
776
- async _connect() {
1035
+ async _connect(attempt) {
777
1036
  const timeoutMs = this._config.connectTimeoutMs ?? CONNECT_TIMEOUT_MS;
778
1037
  let timer;
779
1038
  const timedOut = new Promise((_resolve, reject) => {
780
1039
  timer = setTimeout(
781
- () => reject(new ValidationError2("wwebjs", `WhatsApp was not ready within ${timeoutMs}ms.`)),
1040
+ () => reject(new ValidationError3("wwebjs", `WhatsApp was not ready within ${timeoutMs}ms.`)),
782
1041
  timeoutMs
783
1042
  );
784
1043
  timer.unref?.();
@@ -789,7 +1048,7 @@ var WWebJSAdapter = class {
789
1048
  try {
790
1049
  await Promise.race([this._open(), timedOut]);
791
1050
  } catch (error) {
792
- await this.client.destroy().catch(() => void 0);
1051
+ if (this._owned && attempt === this._attempts) await this._close().catch(() => void 0);
793
1052
  throw error;
794
1053
  } finally {
795
1054
  clearTimeout(timer);
@@ -799,77 +1058,267 @@ var WWebJSAdapter = class {
799
1058
  }
800
1059
  async _open() {
801
1060
  this._state = this._initialized ? "reconnecting" : "connecting";
1061
+ if (!this._owned && await this._running()) {
1062
+ this._watchBrowser();
1063
+ return this._onReady();
1064
+ }
1065
+ let onReady;
1066
+ let onFailure;
802
1067
  const ready = new Promise((resolve, reject) => {
803
- const onReady = () => settle(resolve);
804
- const onFailure = (message) => settle(
805
- () => reject(new ValidationError2("wwebjs", `WhatsApp authentication failed: ${message}`))
806
- );
807
- const settle = (finish) => {
808
- this.client.off("ready", onReady);
809
- this.client.off("auth_failure", onFailure);
810
- finish();
811
- };
812
- this.client.on("ready", onReady);
813
- this.client.on("auth_failure", onFailure);
1068
+ onReady = resolve;
1069
+ onFailure = (message) => reject(new ValidationError3("wwebjs", `WhatsApp authentication failed: ${message}`));
814
1070
  });
815
- if (this._initialized) await this.client.destroy().catch(() => void 0);
816
- this._initialized = true;
817
- await this.client.initialize();
818
- if (this._closed) {
1071
+ ready.catch(() => void 0);
1072
+ this.client.on("ready", onReady);
1073
+ this.client.on("auth_failure", onFailure);
1074
+ try {
1075
+ if (this._owned && this._initialized) await this._close().catch(() => void 0);
1076
+ this._initialized = true;
1077
+ if (this._owned) {
1078
+ this._launch = new AbortController();
1079
+ const options = this.client.options;
1080
+ options.puppeteer = { ...options.puppeteer, signal: this._launch.signal };
1081
+ }
1082
+ if (this._owned || !this.client.pupBrowser) await this.client.initialize();
1083
+ if (this._closed) {
1084
+ if (this._owned) await this._close();
1085
+ return;
1086
+ }
1087
+ this._watchBrowser();
1088
+ await ready;
1089
+ } finally {
1090
+ this.client.off("ready", onReady);
1091
+ this.client.off("auth_failure", onFailure);
1092
+ }
1093
+ }
1094
+ /** A crashed browser ends the session without WhatsApp ever reporting a disconnect. */
1095
+ _watchBrowser() {
1096
+ const browser = this.client.pupBrowser;
1097
+ if (!browser) return;
1098
+ const onClose = () => this._onDisconnected("BROWSER_CLOSED");
1099
+ browser.once("disconnected", onClose);
1100
+ this._unwatch = () => browser.off("disconnected", onClose);
1101
+ }
1102
+ /** A client started elsewhere is up when its browser is connected and WhatsApp answers. */
1103
+ async _running() {
1104
+ if (!this.client.pupBrowser?.isConnected()) return false;
1105
+ return await within(this.client.getState()) === "CONNECTED";
1106
+ }
1107
+ /** Closes the browser this adapter runs; closing it on purpose is not a crash to recover from. */
1108
+ async _close() {
1109
+ this._unwatch?.();
1110
+ this._unwatch = void 0;
1111
+ try {
819
1112
  await this.client.destroy();
820
- return;
1113
+ } finally {
1114
+ await this._killBrowser();
821
1115
  }
822
- this.client.pupBrowser?.once("disconnected", () => this._onDisconnected("BROWSER_CLOSED"));
823
- await ready;
1116
+ }
1117
+ /** `destroy()` closes only a browser it still sees connected, so one that dropped keeps its profile locked. */
1118
+ async _killBrowser() {
1119
+ this._launch?.abort();
1120
+ const browser = this.client.pupBrowser?.process?.();
1121
+ if (!browser?.pid || browser.exitCode !== null || browser.signalCode !== null) return;
1122
+ const exited = once(browser, "exit");
1123
+ try {
1124
+ process.kill(process.platform === "win32" ? browser.pid : -browser.pid, "SIGKILL");
1125
+ } catch {
1126
+ browser.kill("SIGKILL");
1127
+ }
1128
+ await Promise.race([
1129
+ exited,
1130
+ new Promise((resolve) => setTimeout(resolve, KILL_WAIT_MS).unref?.())
1131
+ ]);
824
1132
  }
825
1133
  _listen() {
826
1134
  const { onPairingCode, onQR } = this._config;
827
- if (onQR) this.client.on("qr", (qr) => void onQR(qr));
828
- if (onPairingCode) this.client.on("code", (code) => void onPairingCode(code));
829
- this.client.on("ready", () => {
830
- this._state = "connected";
831
- this._strikes = 0;
832
- if (!this._config.userName && this.client.info?.pushname) {
833
- this.userName = this.client.info.pushname;
834
- }
835
- this._logger.info("WhatsApp session ready", { userId: this.botUserId });
836
- void this._learnLid();
837
- this._guard("catch-up", this._catchUp());
838
- });
839
- this.client.on("disconnected", (reason) => this._onDisconnected(String(reason)));
840
- this.client.on("message_create", (message) => this._guard("message", this._onMessage(message)));
841
- this.client.on(
842
- "message_edit",
843
- (message, _new, previous) => this._onEdit(message, String(previous))
844
- );
845
- this.client.on(
846
- "message_revoke_everyone",
847
- (message, revoked) => this._onRevoke(message, revoked)
848
- );
849
- this.client.on("message_reaction", (reaction) => this._onReaction(reaction));
850
- this.client.on("message_ack", (message, ack) => this._onAck(message, ack));
851
- this.client.on("vote_update", (vote) => this._guard("poll vote", this._onVote(vote)));
852
- this.client.on("call", (call) => void this._dispatch(this._callHandlers, call, "onCall"));
1135
+ const on = (event, listener) => {
1136
+ this._listeners.push([event, listener]);
1137
+ return this.client.on(event, listener);
1138
+ };
1139
+ if (onQR) on("qr", (qr) => void this._dispatch([onQR], qr, "onQR"));
1140
+ if (onPairingCode)
1141
+ on("code", (code) => void this._dispatch([onPairingCode], code, "onPairingCode"));
1142
+ on("ready", () => this._onReady());
1143
+ on("disconnected", (reason) => this._onDisconnected(String(reason)));
1144
+ on("message_create", (message) => this._guard("message", this._onMessage(message)));
1145
+ on("message_edit", (message, _new, previous) => this._onEdit(message, String(previous)));
1146
+ on("message_revoke_everyone", (message, revoked) => this._onRevoke(message, revoked));
1147
+ on("message_reaction", (reaction) => this._onReaction(reaction));
1148
+ on("message_ack", (message, ack) => this._onAck(message, ack));
1149
+ on("vote_update", (vote) => this._guard("poll vote", this._onVote(vote)));
1150
+ on("call", (call) => void this._dispatch(this._callHandlers, call, "onCall"));
853
1151
  for (const [event, type] of Object.entries(GROUP_EVENTS)) {
854
- this.client.on(event, (notification) => this._onGroup(type, notification));
1152
+ on(event, (notification) => this._onGroup(type, notification));
855
1153
  }
856
1154
  }
1155
+ _unlisten() {
1156
+ for (const [event, listener] of this._listeners) this.client.off(event, listener);
1157
+ this._listeners = [];
1158
+ }
1159
+ _onReady() {
1160
+ this._state = "connected";
1161
+ this._strikes = 0;
1162
+ if (!this._config.userName && this.client.info?.pushname) {
1163
+ this.userName = this.client.info.pushname;
1164
+ }
1165
+ this._logger.info("WhatsApp session ready", { userId: this.botUserId });
1166
+ void this._learnLid();
1167
+ this._guard("catch-up", this._catchUp());
1168
+ }
857
1169
  async _onMessage(raw) {
858
1170
  if (!this._chat || this._isOwn(raw.fromMe)) return;
859
1171
  const chatId = chatIdOf(raw);
860
1172
  if (raw.isStatus || isBroadcastId(chatId) || SYSTEM_TYPES.has(raw.type)) return;
1173
+ const id = serialize(raw.id);
1174
+ if (this._recent.has(id)) return;
1175
+ this._recent.add(id);
1176
+ if (this._recent.size > MAX_RECENT) this._recent.delete(this._recent.values().next().value);
861
1177
  const threadId = this.encodeThreadId({ chatId });
862
1178
  if (this._config.markSeen && !raw.fromMe) {
863
1179
  await this.markAsRead(threadId).catch(
864
1180
  (error) => this._logger.warn("Failed to send a read receipt", { error, threadId })
865
1181
  );
866
1182
  }
1183
+ const author = this._author(raw);
1184
+ if (await this._answer(raw, threadId, author) || this._command(raw, threadId, author)) {
1185
+ await this._remember(raw);
1186
+ return;
1187
+ }
867
1188
  const parsed = this._addons("onMessage").length > 0 ? await this._parse(raw) : void 0;
868
1189
  if (!parsed || !await this._claimed(parsed, threadId)) {
869
1190
  await this._chat.processMessage(this, threadId, parsed ?? (() => this._parse(raw)));
870
1191
  }
871
1192
  await this._remember(raw);
872
1193
  }
1194
+ _formKey(threadId, userId) {
1195
+ return `wwebjs:${this.name}:form:${threadId}:${userId}`;
1196
+ }
1197
+ _texts() {
1198
+ return { ...DEFAULT_MODAL_TEXTS, ...this._config.modalTexts };
1199
+ }
1200
+ async _start(threadId, userId, modal, form) {
1201
+ if (!this._chat) throw new ValidationError3("wwebjs", "A modal needs Chat to be initialized.");
1202
+ const field = currentField(form);
1203
+ await this._chat.getState().set(this._formKey(threadId, userId), form, FORM_TTL_MS);
1204
+ const intro = introOf(modal, this._texts());
1205
+ await this.postMessage(
1206
+ threadId,
1207
+ field ? `${intro}
1208
+
1209
+ ${questionOf(field, form, this._texts())}` : intro
1210
+ );
1211
+ }
1212
+ /** A reply from someone filling in a modal answers it, before anything else sees it. */
1213
+ async _answer(raw, threadId, user) {
1214
+ const state = this._chat.getState();
1215
+ const key = this._formKey(threadId, user.userId);
1216
+ const form = await state.get(key);
1217
+ const field = form && currentField(form);
1218
+ if (!form || !field) return false;
1219
+ const texts = this._texts();
1220
+ const text = (raw.body ?? "").trim();
1221
+ const event = { adapter: this, callbackId: form.callbackId, raw, user, viewId: form.viewId };
1222
+ if (text.toLowerCase() === (form.closeLabel ?? texts.cancel).toLowerCase()) {
1223
+ await state.delete(key);
1224
+ await this.postMessage(threadId, texts.cancelled);
1225
+ if (form.notifyOnClose) {
1226
+ await this._chat.processModalClose(
1227
+ { ...event, privateMetadata: form.privateMetadata },
1228
+ form.contextId
1229
+ );
1230
+ }
1231
+ return true;
1232
+ }
1233
+ const answer = answerOf(field, form, text, texts);
1234
+ if ("search" in answer) {
1235
+ const found = flattenOptions(
1236
+ await this._chat.processOptionsLoad({
1237
+ actionId: field.id,
1238
+ adapter: this,
1239
+ query: answer.search,
1240
+ raw,
1241
+ user
1242
+ })
1243
+ );
1244
+ const next2 = { ...form, found: found.length > 0 ? found : void 0 };
1245
+ await state.set(key, next2, FORM_TTL_MS);
1246
+ const question = questionOf(field, next2, texts);
1247
+ await this.postMessage(
1248
+ threadId,
1249
+ found.length > 0 ? question : `${texts.noResults}
1250
+
1251
+ ${question}`
1252
+ );
1253
+ return true;
1254
+ }
1255
+ if ("error" in answer) {
1256
+ await this.postMessage(threadId, `${answer.error}
1257
+
1258
+ ${questionOf(field, form, texts)}`);
1259
+ return true;
1260
+ }
1261
+ const { [field.id]: _previous, ...rest } = form.values;
1262
+ const next = {
1263
+ ...form,
1264
+ found: void 0,
1265
+ pending: form.pending.slice(1),
1266
+ values: answer.value === void 0 ? rest : { ...rest, [field.id]: answer.value }
1267
+ };
1268
+ const following = currentField(next);
1269
+ if (following) {
1270
+ await state.set(key, next, FORM_TTL_MS);
1271
+ await this.postMessage(threadId, questionOf(following, next, texts));
1272
+ return true;
1273
+ }
1274
+ await state.delete(key);
1275
+ const response = await this._chat.processModalSubmit(
1276
+ { ...event, privateMetadata: next.privateMetadata, values: next.values },
1277
+ next.contextId
1278
+ );
1279
+ if (response?.action === "errors") {
1280
+ const retry = {
1281
+ ...next,
1282
+ pending: next.fields.map(({ id }) => id).filter((id) => id in response.errors)
1283
+ };
1284
+ const first = currentField(retry);
1285
+ if (first) {
1286
+ await state.set(key, retry, FORM_TTL_MS);
1287
+ const reasons = Object.values(response.errors).join("\n");
1288
+ await this.postMessage(threadId, `${reasons}
1289
+
1290
+ ${questionOf(first, retry, texts)}`);
1291
+ }
1292
+ } else if (response?.action === "update" || response?.action === "push") {
1293
+ const viewId = response.action === "update" ? next.viewId : randomUUID();
1294
+ await this._start(
1295
+ threadId,
1296
+ user.userId,
1297
+ response.modal,
1298
+ createForm(response.modal, viewId, next.contextId)
1299
+ );
1300
+ }
1301
+ return true;
1302
+ }
1303
+ /** WhatsApp has no slash commands, so a message naming a declared one becomes one. */
1304
+ _command(raw, threadId, user) {
1305
+ const match = /^(\/\S+)(?:\s+([\s\S]*))?$/.exec((raw.body ?? "").trim());
1306
+ const command = match && this._config.slashCommands?.find((name) => name.toLowerCase() === match[1].toLowerCase());
1307
+ if (!command) return false;
1308
+ this._chat.processSlashCommand(
1309
+ {
1310
+ adapter: this,
1311
+ channelId: threadId,
1312
+ command,
1313
+ raw,
1314
+ text: match[2] ?? "",
1315
+ triggerId: triggerIdOf(threadId, user.userId),
1316
+ user
1317
+ },
1318
+ void 0
1319
+ );
1320
+ return true;
1321
+ }
873
1322
  async _claimed(message, threadId) {
874
1323
  for (const addon of this._addons("onMessage")) {
875
1324
  if (await addon.onMessage(message, this._context(threadId))) return true;
@@ -894,13 +1343,20 @@ var WWebJSAdapter = class {
894
1343
  );
895
1344
  return this._saving;
896
1345
  }
1346
+ /** While a catch-up runs the position holds still, so a crash part-way replays rather than skips. */
897
1347
  async _remember(raw) {
898
- if (this._config.catchUpMs === false || !this._seen) return;
1348
+ if (this._config.catchUpMs === false) return;
1349
+ if (this._behind) this._behind.push(raw);
1350
+ else if (this._advance(raw)) await this._save();
1351
+ }
1352
+ _advance(raw) {
1353
+ if (!this._seen) return false;
899
1354
  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();
1355
+ const at = Math.min(raw.timestamp, Math.floor(Date.now() / 1e3) + CLOCK_SKEW_S);
1356
+ const { ids } = this._seen;
1357
+ if (at < this._seen.at || at === this._seen.at && ids.includes(id)) return false;
1358
+ this._seen = { at, ids: at === this._seen.at ? [...ids, id] : [id], wid: this.botUserId };
1359
+ return true;
904
1360
  }
905
1361
  /** WhatsApp Web loads what arrived while the session was down without announcing every message. */
906
1362
  async _catchUp() {
@@ -908,18 +1364,49 @@ var WWebJSAdapter = class {
908
1364
  const state = this._chat?.getState();
909
1365
  if (windowMs === false || !state) return;
910
1366
  this._seen ??= await state.get(this._seenKey());
1367
+ if (this._seen?.wid && this._seen.wid !== this.botUserId) this._seen = null;
911
1368
  const seen = this._seen;
912
1369
  if (!seen) {
913
- this._seen = { at: Math.floor(Date.now() / 1e3), ids: [] };
1370
+ this._seen = { at: Math.floor(Date.now() / 1e3), ids: [], wid: this.botUserId };
914
1371
  await this._save();
915
1372
  return;
916
1373
  }
917
1374
  const oldest = Math.max(seen.at, Math.floor((Date.now() - windowMs) / 1e3));
918
1375
  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);
1376
+ this._behind = [];
1377
+ try {
1378
+ const chats = (await this.client.getChats()).filter((chat) => chat.timestamp >= oldest);
1379
+ const missed = [];
1380
+ let truncated = chats.length > MAX_CATCH_UP_CHATS;
1381
+ for (const chat of chats.slice(0, MAX_CATCH_UP_CHATS)) {
1382
+ const messages = await chat.fetchMessages({ limit: MAX_CATCH_UP_MESSAGES }).catch((error) => {
1383
+ this._logger.warn("Could not catch up on a chat", {
1384
+ chatId: serialize(chat.id),
1385
+ error
1386
+ });
1387
+ return [];
1388
+ });
1389
+ const behind = messages.filter(unseen);
1390
+ truncated ||= behind.length === MAX_CATCH_UP_MESSAGES;
1391
+ missed.push(...behind);
1392
+ }
1393
+ if (truncated) {
1394
+ this._logger.warn(
1395
+ `Caught up on the ${MAX_CATCH_UP_CHATS} most recent chats and ${MAX_CATCH_UP_MESSAGES} messages each; older ones were missed`
1396
+ );
1397
+ }
1398
+ for (const message of missed.sort((a, b) => a.timestamp - b.timestamp)) {
1399
+ await this._onMessage(message).catch(
1400
+ (error) => this._logger.warn("A missed message was not handled", {
1401
+ error,
1402
+ messageId: serialize(message.id)
1403
+ })
1404
+ );
1405
+ }
1406
+ } finally {
1407
+ const delivered = this._behind;
1408
+ this._behind = void 0;
1409
+ if (delivered.map((message) => this._advance(message)).some(Boolean)) await this._save();
923
1410
  }
924
1411
  }
925
1412
  _onEdit(raw, previousBody) {
@@ -1107,7 +1594,7 @@ var WWebJSAdapter = class {
1107
1594
  _onDisconnected(reason) {
1108
1595
  if (this._closed) return;
1109
1596
  this._connection = null;
1110
- this._state = this._config.reconnect === false ? "disconnected" : "reconnecting";
1597
+ this._state = this._reconnects() ? "reconnecting" : "disconnected";
1111
1598
  if (reason === "LOGOUT") {
1112
1599
  this._state = "logged_out";
1113
1600
  this._logger.error("WhatsApp logged this session out; pair it again to reconnect", {
@@ -1118,8 +1605,11 @@ var WWebJSAdapter = class {
1118
1605
  this._logger.warn("WhatsApp disconnected", { reason });
1119
1606
  this._reconnect(RECONNECT_MIN_MS);
1120
1607
  }
1608
+ _reconnects() {
1609
+ return this._owned && this._config.reconnect !== false;
1610
+ }
1121
1611
  _reconnect(delayMs) {
1122
- if (this._closed || this._config.reconnect === false) return;
1612
+ if (this._closed || !this._reconnects()) return;
1123
1613
  clearTimeout(this._retry);
1124
1614
  this._state = "reconnecting";
1125
1615
  this._retry = setTimeout(() => {
@@ -1161,7 +1651,10 @@ var WWebJSAdapter = class {
1161
1651
  const text = addon.renderCard(card, this._context(threadId));
1162
1652
  if (text !== void 0) return { card, text };
1163
1653
  }
1164
- return { card, text: cardToFallbackText(card, { boldFormat: "*" }) };
1654
+ return {
1655
+ card,
1656
+ text: this._config.richContent ? cardToText(card) : cardToPlainText(card)
1657
+ };
1165
1658
  }
1166
1659
  /** The card is already on WhatsApp, so an addon failing here must not fail the send. */
1167
1660
  async _cardSent(card, messageId, threadId) {
@@ -1178,12 +1671,19 @@ var WWebJSAdapter = class {
1178
1671
  const { chatId } = this.decodeThreadId(threadId);
1179
1672
  const { card, text: rendered } = this._render(message, threadId);
1180
1673
  const { mentions, text } = extractMentions(rendered);
1181
- const media = await toMediaList(message, this._config.maxMediaBytes);
1674
+ const media = [
1675
+ ...await toMediaList(message, this._config.maxMediaBytes),
1676
+ ...await Promise.all(
1677
+ (card && this._config.richContent ? cardImages(card) : []).map(
1678
+ (url) => toMedia({ type: "image", url }, this._config.maxMediaBytes)
1679
+ )
1680
+ )
1681
+ ];
1182
1682
  const send = {
1183
1683
  ...options,
1184
1684
  ...mentions.length > 0 ? { mentions } : {}
1185
1685
  };
1186
- const voice = this._config.voiceNotes !== false;
1686
+ const voice = this._config.voiceNotes ?? true;
1187
1687
  const captionIndex = text ? media.findIndex(isCaptionable) : -1;
1188
1688
  const payloads = [];
1189
1689
  if (media.length === 0 || text && captionIndex === -1) payloads.push([text, send]);
@@ -1191,7 +1691,7 @@ var WWebJSAdapter = class {
1191
1691
  const itemOptions = index === captionIndex ? { ...send, caption: text } : send;
1192
1692
  payloads.push([
1193
1693
  item,
1194
- voice && isAudio(item) ? { ...itemOptions, sendAudioAsVoice: true } : itemOptions
1694
+ (voice === "ogg" ? isVoiceNote(item) : voice && isAudio(item)) ? { ...itemOptions, sendAudioAsVoice: true } : itemOptions
1195
1695
  ]);
1196
1696
  });
1197
1697
  let first;
@@ -1213,7 +1713,7 @@ var WWebJSAdapter = class {
1213
1713
  }
1214
1714
  _raw(sent, threadId) {
1215
1715
  if (!sent) {
1216
- throw new ValidationError2(
1716
+ throw new ValidationError3(
1217
1717
  "wwebjs",
1218
1718
  "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."
1219
1719
  );
@@ -1254,8 +1754,16 @@ var WWebJSAdapter = class {
1254
1754
  }
1255
1755
  return chat;
1256
1756
  }
1257
- async _requireMessage(messageId) {
1757
+ /** A DM can be addressed by phone or by LID, so only a group's messages must match the thread exactly. */
1758
+ async _findMessage(messageId, threadId) {
1258
1759
  const message = await this.client.getMessageById(messageId).catch(() => null);
1760
+ if (!message || !threadId) return message;
1761
+ const chatId = chatIdOf(message);
1762
+ const expected = this.decodeThreadId(threadId).chatId;
1763
+ return chatId === expected || !(isGroupId(chatId) || isGroupId(expected)) ? message : null;
1764
+ }
1765
+ async _requireMessage(messageId, threadId) {
1766
+ const message = await this._findMessage(messageId, threadId);
1259
1767
  if (!message) {
1260
1768
  throw new ResourceNotFoundError("wwebjs", "message", messageId);
1261
1769
  }
@@ -1268,6 +1776,9 @@ function createWWebJSAdapter(config = {}) {
1268
1776
  function chatIdOf(message) {
1269
1777
  return message.id?.remote || (message.fromMe ? message.to : message.from);
1270
1778
  }
1779
+ function locationText({ address, latitude, longitude, name }) {
1780
+ return [name, address, `https://maps.google.com/?q=${latitude},${longitude}`].filter(Boolean).join("\n");
1781
+ }
1271
1782
  function within(lookup) {
1272
1783
  return Promise.race([
1273
1784
  lookup.catch(() => null),
@@ -1282,7 +1793,7 @@ function participantAuthor(userId, isMe) {
1282
1793
  }
1283
1794
  function assertRange(label, value, bound) {
1284
1795
  if (!Number.isFinite(value) || value < -bound || value > bound) {
1285
- throw new ValidationError2(
1796
+ throw new ValidationError3(
1286
1797
  "wwebjs",
1287
1798
  `sendLocation: ${label} must be between -${bound} and ${bound}. Received ${value}.`
1288
1799
  );
@@ -1290,18 +1801,17 @@ function assertRange(label, value, bound) {
1290
1801
  }
1291
1802
 
1292
1803
  // src/guards.ts
1293
- import { ValidationError as ValidationError3 } from "@chat-adapter/shared";
1804
+ import { ValidationError as ValidationError4 } from "@chat-adapter/shared";
1294
1805
  function isWWebJSAdapter(value) {
1295
1806
  return value instanceof WWebJSAdapter;
1296
1807
  }
1297
1808
  function requireWWebJSAdapter(value) {
1298
1809
  const adapter = value && typeof value === "object" && "adapter" in value ? value.adapter : value;
1299
1810
  if (isWWebJSAdapter(adapter)) return adapter;
1300
- throw new ValidationError3("wwebjs", "This context does not belong to a wwebjs adapter.");
1811
+ throw new ValidationError4("wwebjs", "This context does not belong to a wwebjs adapter.");
1301
1812
  }
1302
1813
 
1303
1814
  // src/numbered-actions.ts
1304
- import { cardToFallbackText as cardToFallbackText2 } from "@chat-adapter/shared";
1305
1815
  var TTL_MS = 864e5;
1306
1816
  function actionsOf(children) {
1307
1817
  return children.flatMap(
@@ -1340,7 +1850,7 @@ function numberedActions(options = {}) {
1340
1850
  renderCard(card) {
1341
1851
  const { lines } = layout(card);
1342
1852
  if (lines.length === 0) return void 0;
1343
- return [cardToFallbackText2(card, { boldFormat: "*" }), lines.join("\n")].filter(Boolean).join("\n\n");
1853
+ return [cardToText(card), lines.join("\n")].filter(Boolean).join("\n\n");
1344
1854
  },
1345
1855
  async cardSent(card, messageId, context) {
1346
1856
  const { choices } = layout(card);
@@ -1348,11 +1858,17 @@ function numberedActions(options = {}) {
1348
1858
  await context.chat.getState().set(keyOf(context), { choices, messageId }, options.ttlMs ?? TTL_MS);
1349
1859
  },
1350
1860
  async onMessage(message, context) {
1351
- const offer = await context.chat?.getState().get(keyOf(context));
1352
- if (!offer || !context.chat) return false;
1861
+ if (message.author.isMe || !context.chat) return false;
1862
+ const state = context.chat.getState();
1863
+ const offer = await state.get(keyOf(context));
1864
+ if (!offer || message.replyTo && message.replyTo.id !== offer.messageId) return false;
1353
1865
  const reply = message.text.trim();
1354
1866
  const choice = /^\d+$/.test(reply) ? offer.choices[Number(reply) - 1] : offer.choices.find(({ label }) => label.toLowerCase() === reply.toLowerCase());
1355
1867
  if (!choice) return false;
1868
+ const ttlMs = options.ttlMs ?? TTL_MS;
1869
+ if (!await state.setIfNotExists(`${keyOf(context)}:${offer.messageId}`, true, ttlMs)) {
1870
+ return false;
1871
+ }
1356
1872
  await context.chat.processAction(
1357
1873
  {
1358
1874
  actionId: choice.actionId,
@@ -1360,6 +1876,7 @@ function numberedActions(options = {}) {
1360
1876
  messageId: offer.messageId,
1361
1877
  raw: message.raw,
1362
1878
  threadId: context.threadId,
1879
+ triggerId: triggerIdOf(context.threadId, message.author.userId),
1363
1880
  user: message.author,
1364
1881
  value: choice.value
1365
1882
  },
@@ -1388,5 +1905,6 @@ export {
1388
1905
  toChatId,
1389
1906
  toMedia,
1390
1907
  toMediaList,
1391
- toUser
1908
+ toUser,
1909
+ triggerIdOf
1392
1910
  };