chat-adapter-wwebjs 0.1.2 → 0.1.4
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 +44 -0
- package/README.md +313 -100
- package/dist/index.d.ts +119 -21
- package/dist/index.js +657 -129
- package/package.json +7 -7
package/dist/index.js
CHANGED
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
// src/adapter.ts
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
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
|
|
74
|
+
return DIVIDER;
|
|
74
75
|
default:
|
|
75
76
|
return this.defaultNodeToText(node, (child) => this.toWhatsApp(child));
|
|
76
77
|
}
|
|
@@ -79,6 +80,50 @@ ${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 "actions":
|
|
100
|
+
return linkButtons(child);
|
|
101
|
+
case "divider":
|
|
102
|
+
return DIVIDER;
|
|
103
|
+
default:
|
|
104
|
+
return "";
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
function linkButtons(child) {
|
|
108
|
+
return child.children.flatMap((action) => action.type === "link-button" ? [`${action.label}: ${action.url}`] : []).join("\n");
|
|
109
|
+
}
|
|
110
|
+
function plainText(child) {
|
|
111
|
+
if (child.type === "actions") return linkButtons(child);
|
|
112
|
+
if (child.type === "section") return child.children.map(plainText).filter(Boolean).join("\n");
|
|
113
|
+
return cardChildToFallbackText(child);
|
|
114
|
+
}
|
|
115
|
+
function cardToText(card) {
|
|
116
|
+
return [card.title && `*${card.title}*`, card.subtitle, ...card.children.map(childText)].filter(Boolean).join("\n");
|
|
117
|
+
}
|
|
118
|
+
function cardToPlainText(card) {
|
|
119
|
+
return [card.title, card.subtitle, ...card.children.map(plainText)].filter(Boolean).join("\n");
|
|
120
|
+
}
|
|
121
|
+
function cardImages(card) {
|
|
122
|
+
const inside = (children) => children.flatMap(
|
|
123
|
+
(child) => child.type === "image" ? [child.url] : child.type === "section" ? inside(child.children) : []
|
|
124
|
+
);
|
|
125
|
+
return [...card.imageUrl ? [card.imageUrl] : [], ...inside(card.children)];
|
|
126
|
+
}
|
|
82
127
|
|
|
83
128
|
// src/jid.ts
|
|
84
129
|
var BROADCAST_SUFFIX = "@broadcast";
|
|
@@ -115,15 +160,16 @@ function extractMentions(text) {
|
|
|
115
160
|
mentions.add(chatId);
|
|
116
161
|
return `@${toUser(chatId)}`;
|
|
117
162
|
});
|
|
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
163
|
return { mentions: [...mentions], text: rendered };
|
|
123
164
|
}
|
|
124
165
|
|
|
125
166
|
// src/media.ts
|
|
126
|
-
import {
|
|
167
|
+
import {
|
|
168
|
+
downloadAttachment,
|
|
169
|
+
extractFiles,
|
|
170
|
+
extractPostableAttachments,
|
|
171
|
+
ValidationError
|
|
172
|
+
} from "@chat-adapter/shared";
|
|
127
173
|
|
|
128
174
|
// src/wwebjs.ts
|
|
129
175
|
import wwebjs from "whatsapp-web.js";
|
|
@@ -158,7 +204,6 @@ var MIME_TYPES = {
|
|
|
158
204
|
};
|
|
159
205
|
var DEFAULT_MIME_TYPE = "application/octet-stream";
|
|
160
206
|
var DEFAULT_MAX_MEDIA_BYTES = 64 * 1024 * 1024;
|
|
161
|
-
var URL_TIMEOUT_MS = 3e4;
|
|
162
207
|
function toAttachments(message, maxBytes) {
|
|
163
208
|
if (!message.hasMedia) return [];
|
|
164
209
|
const data = message.rawData ?? {};
|
|
@@ -183,6 +228,9 @@ async function download(message, maxBytes = DEFAULT_MAX_MEDIA_BYTES) {
|
|
|
183
228
|
if (downloadMediaStream) {
|
|
184
229
|
const streamed = await downloadMediaStream.call(message);
|
|
185
230
|
if (!streamed) throw unavailable(message.id._serialized);
|
|
231
|
+
if (streamed.blobSize && streamed.blobSize > maxBytes) {
|
|
232
|
+
throw tooLarge(message.id._serialized, streamed.blobSize, maxBytes);
|
|
233
|
+
}
|
|
186
234
|
return collect(streamed.stream, maxBytes, message.id._serialized);
|
|
187
235
|
}
|
|
188
236
|
const media = await message.downloadMedia();
|
|
@@ -226,18 +274,24 @@ function isCaptionable(media) {
|
|
|
226
274
|
function isAudio(media) {
|
|
227
275
|
return media.mimetype.startsWith("audio/");
|
|
228
276
|
}
|
|
277
|
+
function isVoiceNote(media) {
|
|
278
|
+
return media.mimetype.startsWith("audio/ogg");
|
|
279
|
+
}
|
|
229
280
|
function mimeTypeOf(filename) {
|
|
230
281
|
const extension = filename?.split(".").pop()?.toLowerCase();
|
|
231
282
|
return extension && Object.hasOwn(MIME_TYPES, extension) && MIME_TYPES[extension] || DEFAULT_MIME_TYPE;
|
|
232
283
|
}
|
|
233
284
|
async function fetchMedia(url, source, maxBytes) {
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
285
|
+
let contentType;
|
|
286
|
+
const data = await downloadAttachment(url, {
|
|
287
|
+
adapter: "wwebjs",
|
|
288
|
+
limit: maxBytes,
|
|
289
|
+
onResponse: (response) => {
|
|
290
|
+
contentType = response.headers["content-type"]?.split(";")[0];
|
|
291
|
+
}
|
|
292
|
+
});
|
|
239
293
|
const name = source.name ?? new URL(url).pathname.split("/").pop() ?? null;
|
|
240
|
-
const mimeType = source.mimeType ??
|
|
294
|
+
const mimeType = source.mimeType ?? contentType ?? mimeTypeOf(name ?? void 0);
|
|
241
295
|
return new MessageMedia(mimeType, data.toString("base64"), name);
|
|
242
296
|
}
|
|
243
297
|
async function collect(stream, maxBytes, label) {
|
|
@@ -268,12 +322,145 @@ async function toBase64(data) {
|
|
|
268
322
|
return Buffer.from(await data.arrayBuffer()).toString("base64");
|
|
269
323
|
}
|
|
270
324
|
|
|
325
|
+
// src/modals.ts
|
|
326
|
+
import { ValidationError as ValidationError2 } from "@chat-adapter/shared";
|
|
327
|
+
var DEFAULT_MODAL_TEXTS = {
|
|
328
|
+
cancel: "cancel",
|
|
329
|
+
cancelHint: "Send *cancel* to stop.",
|
|
330
|
+
cancelled: "Cancelled.",
|
|
331
|
+
invalid: "That doesn't fit. Try again:",
|
|
332
|
+
noResults: "Nothing matched. Try other words:",
|
|
333
|
+
search: "Send a few words to search.",
|
|
334
|
+
skip: "skip",
|
|
335
|
+
skipHint: "Send *skip* to leave it as it is."
|
|
336
|
+
};
|
|
337
|
+
var INPUTS = /* @__PURE__ */ new Set([
|
|
338
|
+
"date_input",
|
|
339
|
+
"external_select",
|
|
340
|
+
"number_input",
|
|
341
|
+
"radio_select",
|
|
342
|
+
"select",
|
|
343
|
+
"text_input"
|
|
344
|
+
]);
|
|
345
|
+
function triggerIdOf(threadId, userId) {
|
|
346
|
+
return JSON.stringify([threadId, userId]);
|
|
347
|
+
}
|
|
348
|
+
function fromTrigger(triggerId) {
|
|
349
|
+
let ids;
|
|
350
|
+
try {
|
|
351
|
+
ids = JSON.parse(triggerId);
|
|
352
|
+
} catch {
|
|
353
|
+
ids = void 0;
|
|
354
|
+
}
|
|
355
|
+
const [threadId, userId] = Array.isArray(ids) ? ids : [];
|
|
356
|
+
if (typeof threadId === "string" && typeof userId === "string") return [threadId, userId];
|
|
357
|
+
throw new ValidationError2("wwebjs", `Not a trigger this adapter issued: ${triggerId}`);
|
|
358
|
+
}
|
|
359
|
+
function createForm(modal, viewId, contextId) {
|
|
360
|
+
const fields = modal.children.filter((child) => INPUTS.has(child.type));
|
|
361
|
+
return {
|
|
362
|
+
callbackId: modal.callbackId,
|
|
363
|
+
closeLabel: modal.closeLabel,
|
|
364
|
+
contextId,
|
|
365
|
+
fields,
|
|
366
|
+
notifyOnClose: modal.notifyOnClose,
|
|
367
|
+
pending: fields.map(({ id }) => id),
|
|
368
|
+
privateMetadata: modal.privateMetadata,
|
|
369
|
+
values: {},
|
|
370
|
+
viewId
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
function introOf(modal, texts) {
|
|
374
|
+
const shown = modal.children.filter((child) => child.type === "text" || child.type === "fields");
|
|
375
|
+
return [
|
|
376
|
+
cardToText({ children: shown, title: modal.title, type: "card" }),
|
|
377
|
+
`_${texts.cancelHint}_`
|
|
378
|
+
].filter(Boolean).join("\n\n");
|
|
379
|
+
}
|
|
380
|
+
function currentField(form) {
|
|
381
|
+
return form.fields.find(({ id }) => id === form.pending[0]);
|
|
382
|
+
}
|
|
383
|
+
function optionsOf(field, form) {
|
|
384
|
+
if (field.type === "select" || field.type === "radio_select") return field.options;
|
|
385
|
+
return field.type === "external_select" ? form.found : void 0;
|
|
386
|
+
}
|
|
387
|
+
function initialOf(field) {
|
|
388
|
+
switch (field.type) {
|
|
389
|
+
case "select":
|
|
390
|
+
case "radio_select":
|
|
391
|
+
return field.initialOption;
|
|
392
|
+
case "external_select":
|
|
393
|
+
return field.initialOption?.value;
|
|
394
|
+
case "number_input":
|
|
395
|
+
return field.initialValue === void 0 ? void 0 : String(field.initialValue);
|
|
396
|
+
default:
|
|
397
|
+
return field.initialValue;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
function questionOf(field, form, texts) {
|
|
401
|
+
const options = optionsOf(field, form);
|
|
402
|
+
const initial = initialOf(field);
|
|
403
|
+
const shown = field.type === "external_select" ? field.initialOption?.label : options?.find(({ value }) => value === initial)?.label ?? initial;
|
|
404
|
+
const range = field.type === "number_input" && [field.min, field.max].some((n) => n !== void 0);
|
|
405
|
+
return [
|
|
406
|
+
`*${field.label}*`,
|
|
407
|
+
"placeholder" in field && field.placeholder && `_${field.placeholder}_`,
|
|
408
|
+
options?.map(
|
|
409
|
+
(option, index) => [`${index + 1}. ${option.label}`, option.description].filter(Boolean).join(": ")
|
|
410
|
+
).join("\n"),
|
|
411
|
+
field.type === "date_input" && "_YYYY-MM-DD_",
|
|
412
|
+
range && `_${field.min ?? "\u2026"} \u2013 ${field.max ?? "\u2026"}_`,
|
|
413
|
+
field.type === "external_select" && !options && `_${texts.search}_`,
|
|
414
|
+
(field.optional || initial !== void 0) && `_${texts.skipHint}_${shown === void 0 ? "" : ` (${shown})`}`
|
|
415
|
+
].filter(Boolean).join("\n");
|
|
416
|
+
}
|
|
417
|
+
function pick(options, text) {
|
|
418
|
+
return /^\d+$/.test(text) ? options[Number(text) - 1] : options.find(({ label }) => label.toLowerCase() === text.toLowerCase());
|
|
419
|
+
}
|
|
420
|
+
function answerOf(field, form, text, texts) {
|
|
421
|
+
const invalid = { error: texts.invalid };
|
|
422
|
+
if (text.toLowerCase() === texts.skip.toLowerCase()) {
|
|
423
|
+
const initial = initialOf(field);
|
|
424
|
+
return field.optional || initial !== void 0 ? { value: initial } : invalid;
|
|
425
|
+
}
|
|
426
|
+
switch (field.type) {
|
|
427
|
+
case "text_input":
|
|
428
|
+
return text && text.length <= (field.maxLength ?? Infinity) ? { value: text } : invalid;
|
|
429
|
+
case "number_input": {
|
|
430
|
+
const number = Number(text.replace(",", "."));
|
|
431
|
+
const fits = text !== "" && Number.isFinite(number) && (field.decimal || Number.isInteger(number)) && number >= (field.min ?? -Infinity) && number <= (field.max ?? Infinity);
|
|
432
|
+
return fits ? { value: String(number) } : invalid;
|
|
433
|
+
}
|
|
434
|
+
case "date_input": {
|
|
435
|
+
const date = /* @__PURE__ */ new Date(`${text}T00:00:00Z`);
|
|
436
|
+
const valid = /^\d{4}-\d{2}-\d{2}$/.test(text) && !Number.isNaN(date.getTime()) && date.toISOString().startsWith(text);
|
|
437
|
+
return valid ? { value: text } : invalid;
|
|
438
|
+
}
|
|
439
|
+
case "external_select": {
|
|
440
|
+
const chosen = form.found && pick(form.found, text);
|
|
441
|
+
if (chosen) return { value: chosen.value };
|
|
442
|
+
return text.length >= (field.minQueryLength ?? 1) ? { search: text } : invalid;
|
|
443
|
+
}
|
|
444
|
+
default: {
|
|
445
|
+
const chosen = pick(field.options, text);
|
|
446
|
+
return chosen ? { value: chosen.value } : invalid;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
function flattenOptions(result) {
|
|
451
|
+
return (result ?? []).flatMap((entry) => "options" in entry ? entry.options : [entry]);
|
|
452
|
+
}
|
|
453
|
+
|
|
271
454
|
// src/shutdown.ts
|
|
272
455
|
var SIGNALS = ["SIGHUP", "SIGINT", "SIGTERM"];
|
|
456
|
+
var CLOSE_TIMEOUT_MS = 8e3;
|
|
273
457
|
var sessions = /* @__PURE__ */ new Set();
|
|
274
458
|
async function onSignal(signal) {
|
|
275
459
|
for (const name of SIGNALS) process.off(name, onSignal);
|
|
276
|
-
await Promise.
|
|
460
|
+
await Promise.race([
|
|
461
|
+
Promise.allSettled([...sessions].map((close) => close())),
|
|
462
|
+
new Promise((resolve) => setTimeout(resolve, CLOSE_TIMEOUT_MS).unref())
|
|
463
|
+
]);
|
|
277
464
|
if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);
|
|
278
465
|
}
|
|
279
466
|
function closeOnSignal(close) {
|
|
@@ -325,11 +512,16 @@ var CONNECT_TIMEOUT_MS = 12e4;
|
|
|
325
512
|
var WATCHDOG_INTERVAL_MS = 6e4;
|
|
326
513
|
var RECONNECT_MIN_MS = 5e3;
|
|
327
514
|
var RECONNECT_MAX_MS = 3e5;
|
|
515
|
+
var KILL_WAIT_MS = 2e3;
|
|
516
|
+
var STREAM_EDIT_MS = 1e3;
|
|
517
|
+
var FORM_TTL_MS = 864e5;
|
|
328
518
|
var MAX_POLL_OPTIONS = 12;
|
|
329
519
|
var MIN_POLL_OPTIONS = 2;
|
|
330
520
|
var CATCH_UP_MS = 864e5;
|
|
331
521
|
var MAX_CATCH_UP_CHATS = 100;
|
|
332
522
|
var MAX_CATCH_UP_MESSAGES = 50;
|
|
523
|
+
var MAX_RECENT = 1e3;
|
|
524
|
+
var CLOCK_SKEW_S = 60;
|
|
333
525
|
var RECOMMENDED_CHROMIUM_ARGS = [
|
|
334
526
|
"--renderer-process-limit=1",
|
|
335
527
|
"--disable-gpu",
|
|
@@ -341,6 +533,13 @@ var WWebJSAdapter = class {
|
|
|
341
533
|
/** The underlying whatsapp-web.js client, for anything this adapter does not wrap. */
|
|
342
534
|
client;
|
|
343
535
|
userName;
|
|
536
|
+
/**
|
|
537
|
+
* WhatsApp has no modals, so with `richContent` one becomes a conversation:
|
|
538
|
+
* each field is asked in turn, a select by number, and the answers reach
|
|
539
|
+
* `onModalSubmit`. `cancel`, or the modal's `closeLabel`, stops it. Absent
|
|
540
|
+
* otherwise, so the SDK knows a modal cannot open.
|
|
541
|
+
*/
|
|
542
|
+
openModal;
|
|
344
543
|
_config;
|
|
345
544
|
_converter = new WWebJSFormatConverter();
|
|
346
545
|
_ackHandlers = [];
|
|
@@ -357,19 +556,33 @@ var WWebJSAdapter = class {
|
|
|
357
556
|
_state = "idle";
|
|
358
557
|
_watchdog;
|
|
359
558
|
_strikes = 0;
|
|
559
|
+
_owned;
|
|
560
|
+
_attempts = 0;
|
|
561
|
+
_launch;
|
|
562
|
+
_unwatch;
|
|
563
|
+
_listeners = [];
|
|
360
564
|
_unsignal;
|
|
361
565
|
_seen;
|
|
566
|
+
_behind;
|
|
567
|
+
_recent = /* @__PURE__ */ new Set();
|
|
362
568
|
_saving = Promise.resolve();
|
|
363
569
|
constructor(config = {}) {
|
|
364
570
|
const name = config.adapterName ?? "wwebjs";
|
|
365
571
|
if (name.includes(":")) {
|
|
366
|
-
throw new
|
|
572
|
+
throw new ValidationError3("wwebjs", `Invalid adapterName "${name}". ":" is not allowed.`);
|
|
367
573
|
}
|
|
368
574
|
this._config = config;
|
|
369
575
|
this.name = name;
|
|
370
576
|
this.userName = config.userName ?? "wwebjs-bot";
|
|
371
577
|
this._logger = config.logger ?? new ConsoleLogger("info").child(name);
|
|
372
578
|
this.client = config.client ?? new Client(this._clientOptions());
|
|
579
|
+
if (config.client?.constructor.name === "Client" && !(config.client instanceof Client)) {
|
|
580
|
+
this._logger.warn(
|
|
581
|
+
"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."
|
|
582
|
+
);
|
|
583
|
+
}
|
|
584
|
+
this._owned = config.manageClient ?? !config.client?.pupBrowser?.isConnected();
|
|
585
|
+
if (config.richContent) this.openModal = (...args) => this._openModal(...args);
|
|
373
586
|
this._listen();
|
|
374
587
|
}
|
|
375
588
|
/** Where the session stands; a health check reads `connection === "connected"`. */
|
|
@@ -399,18 +612,23 @@ var WWebJSAdapter = class {
|
|
|
399
612
|
this._closed = false;
|
|
400
613
|
clearTimeout(this._retry);
|
|
401
614
|
this._retry = void 0;
|
|
615
|
+
if (this._listeners.length === 0) this._listen();
|
|
402
616
|
this._watch();
|
|
403
|
-
if (this._config.handleSignals !== false) {
|
|
617
|
+
if (this._owned && this._config.handleSignals !== false) {
|
|
404
618
|
this._unsignal ??= closeOnSignal(() => this.disconnect());
|
|
405
619
|
}
|
|
406
|
-
this._connection
|
|
407
|
-
|
|
408
|
-
|
|
620
|
+
if (this._connection) return this._connection;
|
|
621
|
+
const attempt = ++this._attempts;
|
|
622
|
+
this._connection = this._connect(attempt).catch((error) => {
|
|
623
|
+
if (attempt === this._attempts) {
|
|
624
|
+
this._connection = null;
|
|
625
|
+
if (this._state !== "logged_out" && !this._closed) this._state = "disconnected";
|
|
626
|
+
}
|
|
409
627
|
throw error;
|
|
410
628
|
});
|
|
411
629
|
return this._connection;
|
|
412
630
|
}
|
|
413
|
-
/** Close the browser session. */
|
|
631
|
+
/** Close the browser session, or only detach from a client the adapter does not manage. */
|
|
414
632
|
async disconnect() {
|
|
415
633
|
this._closed = true;
|
|
416
634
|
this._state = "closed";
|
|
@@ -420,7 +638,9 @@ var WWebJSAdapter = class {
|
|
|
420
638
|
this._connection = null;
|
|
421
639
|
this._unsignal?.();
|
|
422
640
|
this._unsignal = void 0;
|
|
423
|
-
await this.
|
|
641
|
+
await this._saving;
|
|
642
|
+
if (!this._owned) return this._unlisten();
|
|
643
|
+
await this._close();
|
|
424
644
|
}
|
|
425
645
|
encodeThreadId(platformData) {
|
|
426
646
|
return `${this.name}:${platformData.chatId}`;
|
|
@@ -428,7 +648,7 @@ var WWebJSAdapter = class {
|
|
|
428
648
|
decodeThreadId(threadId) {
|
|
429
649
|
const prefix = `${this.name}:`;
|
|
430
650
|
if (!threadId.startsWith(prefix)) {
|
|
431
|
-
throw new
|
|
651
|
+
throw new ValidationError3("wwebjs", `Invalid WhatsApp thread ID: ${threadId}`);
|
|
432
652
|
}
|
|
433
653
|
return { chatId: threadId.slice(prefix.length) };
|
|
434
654
|
}
|
|
@@ -457,7 +677,7 @@ var WWebJSAdapter = class {
|
|
|
457
677
|
parseMessage(raw) {
|
|
458
678
|
const bot = this._botUsers();
|
|
459
679
|
const text = this._named(
|
|
460
|
-
raw.body ?? "",
|
|
680
|
+
raw.location ? locationText(raw.location) : raw.body ?? "",
|
|
461
681
|
this._mentioned(raw).filter((user) => bot.has(user)),
|
|
462
682
|
() => this.userName
|
|
463
683
|
);
|
|
@@ -466,7 +686,7 @@ var WWebJSAdapter = class {
|
|
|
466
686
|
author: this._author(raw),
|
|
467
687
|
formatted: this._converter.toAst(text),
|
|
468
688
|
id: serialize(raw.id),
|
|
469
|
-
isMention: this._mentionsBot(raw),
|
|
689
|
+
isMention: this._mentionsBot(raw) || void 0,
|
|
470
690
|
links: (raw.links ?? []).map(({ link }) => ({ url: link })),
|
|
471
691
|
metadata: {
|
|
472
692
|
dateSent: new Date(raw.timestamp * 1e3),
|
|
@@ -490,7 +710,7 @@ var WWebJSAdapter = class {
|
|
|
490
710
|
async editMessage(threadId, messageId, message) {
|
|
491
711
|
const { card, text: rendered } = this._render(message, threadId);
|
|
492
712
|
const { mentions, text } = extractMentions(rendered);
|
|
493
|
-
const target = await this._requireMessage(messageId);
|
|
713
|
+
const target = await this._requireMessage(messageId, threadId);
|
|
494
714
|
const edit = () => target.edit(text, mentions.length > 0 ? { mentions } : void 0);
|
|
495
715
|
let edited = await edit();
|
|
496
716
|
const fresh = target.fromMe && Date.now() - target.timestamp * 1e3 < FRESH_MS;
|
|
@@ -499,7 +719,7 @@ var WWebJSAdapter = class {
|
|
|
499
719
|
edited = await edit();
|
|
500
720
|
}
|
|
501
721
|
if (!edited) {
|
|
502
|
-
throw new
|
|
722
|
+
throw new ValidationError3(
|
|
503
723
|
"wwebjs",
|
|
504
724
|
`Message ${messageId} could not be edited. WhatsApp only allows editing your own messages within 15 minutes.`
|
|
505
725
|
);
|
|
@@ -508,14 +728,33 @@ var WWebJSAdapter = class {
|
|
|
508
728
|
await this._cardSent(card, raw.id, threadId);
|
|
509
729
|
return raw;
|
|
510
730
|
}
|
|
511
|
-
|
|
512
|
-
|
|
731
|
+
/** WhatsApp cannot stream, and editing twice a second as the SDK otherwise would floods the chat; the reply goes out once, whole. */
|
|
732
|
+
async stream(threadId, textStream) {
|
|
733
|
+
const edits = this._config.streaming === "edit";
|
|
734
|
+
let text = "";
|
|
735
|
+
let sent;
|
|
736
|
+
let shown = "";
|
|
737
|
+
let at = 0;
|
|
738
|
+
for await (const chunk of textStream) {
|
|
739
|
+
if (typeof chunk === "string") text += chunk;
|
|
740
|
+
else if (chunk.type === "markdown_text") text += chunk.text;
|
|
741
|
+
if (!edits || !text.trim() || Date.now() - at < STREAM_EDIT_MS) continue;
|
|
742
|
+
sent = sent ? await this.editMessage(threadId, sent.id, { markdown: text }).catch(() => sent) : await this.postMessage(threadId, { markdown: text });
|
|
743
|
+
shown = text;
|
|
744
|
+
at = Date.now();
|
|
745
|
+
}
|
|
746
|
+
if (!text.trim()) return null;
|
|
747
|
+
if (!sent) return this.postMessage(threadId, { markdown: text });
|
|
748
|
+
return text === shown ? sent : this.editMessage(threadId, sent.id, { markdown: text });
|
|
513
749
|
}
|
|
514
|
-
async
|
|
515
|
-
await (await this._requireMessage(messageId)).
|
|
750
|
+
async deleteMessage(threadId, messageId) {
|
|
751
|
+
await (await this._requireMessage(messageId, threadId)).delete(true);
|
|
516
752
|
}
|
|
517
|
-
async
|
|
518
|
-
await (await this._requireMessage(messageId)).react(
|
|
753
|
+
async addReaction(threadId, messageId, emoji) {
|
|
754
|
+
await (await this._requireMessage(messageId, threadId)).react(defaultEmojiResolver.toGChat(emoji));
|
|
755
|
+
}
|
|
756
|
+
async removeReaction(threadId, messageId, _emoji) {
|
|
757
|
+
await (await this._requireMessage(messageId, threadId)).react("");
|
|
519
758
|
}
|
|
520
759
|
async fetchMessages(threadId, options) {
|
|
521
760
|
return this._page(await this._requireChat(threadId), options);
|
|
@@ -523,8 +762,8 @@ var WWebJSAdapter = class {
|
|
|
523
762
|
async fetchChannelMessages(channelId, options) {
|
|
524
763
|
return this.fetchMessages(channelId, options);
|
|
525
764
|
}
|
|
526
|
-
async fetchMessage(
|
|
527
|
-
const message = await this.
|
|
765
|
+
async fetchMessage(threadId, messageId) {
|
|
766
|
+
const message = await this._findMessage(messageId, threadId);
|
|
528
767
|
return message ? this.parseMessage(message) : null;
|
|
529
768
|
}
|
|
530
769
|
async fetchThread(threadId) {
|
|
@@ -551,9 +790,39 @@ var WWebJSAdapter = class {
|
|
|
551
790
|
name: chat?.name
|
|
552
791
|
};
|
|
553
792
|
}
|
|
554
|
-
/** WhatsApp
|
|
555
|
-
async listThreads() {
|
|
556
|
-
|
|
793
|
+
/** A WhatsApp chat is one flat conversation, so a channel holds just its own thread. */
|
|
794
|
+
async listThreads(channelId) {
|
|
795
|
+
const chat = await this._findChat(this.decodeThreadId(channelId).chatId);
|
|
796
|
+
return { threads: chat ? this._summaries([chat]) : [] };
|
|
797
|
+
}
|
|
798
|
+
/** Every chat the account has, newest first, with its latest message: an inbox's list. */
|
|
799
|
+
async listChats(options) {
|
|
800
|
+
const chats = (await this.client.getChats()).filter(
|
|
801
|
+
(chat) => !isBroadcastId(serialize(chat.id))
|
|
802
|
+
);
|
|
803
|
+
const start = Number(options?.cursor) || 0;
|
|
804
|
+
const end = start + Math.max(1, options?.limit ?? DEFAULT_LIMIT);
|
|
805
|
+
return {
|
|
806
|
+
nextCursor: end < chats.length ? String(end) : void 0,
|
|
807
|
+
threads: this._summaries(chats.slice(start, end))
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
_summaries(chats) {
|
|
811
|
+
return chats.flatMap(
|
|
812
|
+
(chat) => chat.lastMessage ? [
|
|
813
|
+
{
|
|
814
|
+
id: this.encodeThreadId({ chatId: serialize(chat.id) }),
|
|
815
|
+
lastReplyAt: new Date(chat.lastMessage.timestamp * 1e3),
|
|
816
|
+
rootMessage: this.parseMessage(chat.lastMessage)
|
|
817
|
+
}
|
|
818
|
+
] : []
|
|
819
|
+
);
|
|
820
|
+
}
|
|
821
|
+
async _openModal(triggerId, modal, contextId) {
|
|
822
|
+
const [threadId, userId] = fromTrigger(triggerId);
|
|
823
|
+
const form = createForm(modal, randomUUID(), contextId);
|
|
824
|
+
await this._start(threadId, userId, modal, form);
|
|
825
|
+
return { viewId: form.viewId };
|
|
557
826
|
}
|
|
558
827
|
async getUser(userId) {
|
|
559
828
|
const contact = await this.client.getContactById(toChatId(userId)).catch(() => null);
|
|
@@ -613,7 +882,7 @@ var WWebJSAdapter = class {
|
|
|
613
882
|
/** Send a native WhatsApp poll. Between 2 and 12 options. */
|
|
614
883
|
async sendPoll(args) {
|
|
615
884
|
if (args.options.length < MIN_POLL_OPTIONS || args.options.length > MAX_POLL_OPTIONS) {
|
|
616
|
-
throw new
|
|
885
|
+
throw new ValidationError3(
|
|
617
886
|
"wwebjs",
|
|
618
887
|
`sendPoll: WhatsApp polls need between ${MIN_POLL_OPTIONS} and ${MAX_POLL_OPTIONS} options. Received ${args.options.length}.`
|
|
619
888
|
);
|
|
@@ -681,7 +950,7 @@ var WWebJSAdapter = class {
|
|
|
681
950
|
async fetchGroupParticipants(threadId) {
|
|
682
951
|
const chat = await this._requireChat(threadId);
|
|
683
952
|
if (!isGroupChat(chat)) {
|
|
684
|
-
throw new
|
|
953
|
+
throw new ValidationError3("wwebjs", "fetchGroupParticipants: thread is not a group.");
|
|
685
954
|
}
|
|
686
955
|
return chat.participants.map((participant) => ({
|
|
687
956
|
isAdmin: participant.isAdmin || participant.isSuperAdmin,
|
|
@@ -731,7 +1000,7 @@ var WWebJSAdapter = class {
|
|
|
731
1000
|
return;
|
|
732
1001
|
}
|
|
733
1002
|
if (!second) {
|
|
734
|
-
throw new
|
|
1003
|
+
throw new ValidationError3(
|
|
735
1004
|
"wwebjs",
|
|
736
1005
|
"onPollVote: a handler is required when filtering by poll message ID."
|
|
737
1006
|
);
|
|
@@ -773,12 +1042,12 @@ var WWebJSAdapter = class {
|
|
|
773
1042
|
}
|
|
774
1043
|
return options;
|
|
775
1044
|
}
|
|
776
|
-
async _connect() {
|
|
1045
|
+
async _connect(attempt) {
|
|
777
1046
|
const timeoutMs = this._config.connectTimeoutMs ?? CONNECT_TIMEOUT_MS;
|
|
778
1047
|
let timer;
|
|
779
1048
|
const timedOut = new Promise((_resolve, reject) => {
|
|
780
1049
|
timer = setTimeout(
|
|
781
|
-
() => reject(new
|
|
1050
|
+
() => reject(new ValidationError3("wwebjs", `WhatsApp was not ready within ${timeoutMs}ms.`)),
|
|
782
1051
|
timeoutMs
|
|
783
1052
|
);
|
|
784
1053
|
timer.unref?.();
|
|
@@ -789,7 +1058,7 @@ var WWebJSAdapter = class {
|
|
|
789
1058
|
try {
|
|
790
1059
|
await Promise.race([this._open(), timedOut]);
|
|
791
1060
|
} catch (error) {
|
|
792
|
-
await this.
|
|
1061
|
+
if (this._owned && attempt === this._attempts) await this._close().catch(() => void 0);
|
|
793
1062
|
throw error;
|
|
794
1063
|
} finally {
|
|
795
1064
|
clearTimeout(timer);
|
|
@@ -799,77 +1068,267 @@ var WWebJSAdapter = class {
|
|
|
799
1068
|
}
|
|
800
1069
|
async _open() {
|
|
801
1070
|
this._state = this._initialized ? "reconnecting" : "connecting";
|
|
1071
|
+
if (!this._owned && await this._running()) {
|
|
1072
|
+
this._watchBrowser();
|
|
1073
|
+
return this._onReady();
|
|
1074
|
+
}
|
|
1075
|
+
let onReady;
|
|
1076
|
+
let onFailure;
|
|
802
1077
|
const ready = new Promise((resolve, reject) => {
|
|
803
|
-
|
|
804
|
-
|
|
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);
|
|
1078
|
+
onReady = resolve;
|
|
1079
|
+
onFailure = (message) => reject(new ValidationError3("wwebjs", `WhatsApp authentication failed: ${message}`));
|
|
814
1080
|
});
|
|
815
|
-
|
|
816
|
-
this.
|
|
817
|
-
|
|
818
|
-
|
|
1081
|
+
ready.catch(() => void 0);
|
|
1082
|
+
this.client.on("ready", onReady);
|
|
1083
|
+
this.client.on("auth_failure", onFailure);
|
|
1084
|
+
try {
|
|
1085
|
+
if (this._owned && this._initialized) await this._close().catch(() => void 0);
|
|
1086
|
+
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 };
|
|
1091
|
+
}
|
|
1092
|
+
if (this._owned || !this.client.pupBrowser) await this.client.initialize();
|
|
1093
|
+
if (this._closed) {
|
|
1094
|
+
if (this._owned) await this._close();
|
|
1095
|
+
return;
|
|
1096
|
+
}
|
|
1097
|
+
this._watchBrowser();
|
|
1098
|
+
await ready;
|
|
1099
|
+
} finally {
|
|
1100
|
+
this.client.off("ready", onReady);
|
|
1101
|
+
this.client.off("auth_failure", onFailure);
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
/** A crashed browser ends the session without WhatsApp ever reporting a disconnect. */
|
|
1105
|
+
_watchBrowser() {
|
|
1106
|
+
const browser = this.client.pupBrowser;
|
|
1107
|
+
if (!browser) return;
|
|
1108
|
+
const onClose = () => this._onDisconnected("BROWSER_CLOSED");
|
|
1109
|
+
browser.once("disconnected", onClose);
|
|
1110
|
+
this._unwatch = () => browser.off("disconnected", onClose);
|
|
1111
|
+
}
|
|
1112
|
+
/** A client started elsewhere is up when its browser is connected and WhatsApp answers. */
|
|
1113
|
+
async _running() {
|
|
1114
|
+
if (!this.client.pupBrowser?.isConnected()) return false;
|
|
1115
|
+
return await within(this.client.getState()) === "CONNECTED";
|
|
1116
|
+
}
|
|
1117
|
+
/** Closes the browser this adapter runs; closing it on purpose is not a crash to recover from. */
|
|
1118
|
+
async _close() {
|
|
1119
|
+
this._unwatch?.();
|
|
1120
|
+
this._unwatch = void 0;
|
|
1121
|
+
try {
|
|
819
1122
|
await this.client.destroy();
|
|
820
|
-
|
|
1123
|
+
} finally {
|
|
1124
|
+
await this._killBrowser();
|
|
821
1125
|
}
|
|
822
|
-
|
|
823
|
-
|
|
1126
|
+
}
|
|
1127
|
+
/** `destroy()` closes only a browser it still sees connected, so one that dropped keeps its profile locked. */
|
|
1128
|
+
async _killBrowser() {
|
|
1129
|
+
this._launch?.abort();
|
|
1130
|
+
const browser = this.client.pupBrowser?.process?.();
|
|
1131
|
+
if (!browser?.pid || browser.exitCode !== null || browser.signalCode !== null) return;
|
|
1132
|
+
const exited = once(browser, "exit");
|
|
1133
|
+
try {
|
|
1134
|
+
process.kill(process.platform === "win32" ? browser.pid : -browser.pid, "SIGKILL");
|
|
1135
|
+
} catch {
|
|
1136
|
+
browser.kill("SIGKILL");
|
|
1137
|
+
}
|
|
1138
|
+
await Promise.race([
|
|
1139
|
+
exited,
|
|
1140
|
+
new Promise((resolve) => setTimeout(resolve, KILL_WAIT_MS).unref?.())
|
|
1141
|
+
]);
|
|
824
1142
|
}
|
|
825
1143
|
_listen() {
|
|
826
1144
|
const { onPairingCode, onQR } = this._config;
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
this.
|
|
842
|
-
|
|
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"));
|
|
1145
|
+
const on = (event, listener) => {
|
|
1146
|
+
this._listeners.push([event, listener]);
|
|
1147
|
+
return this.client.on(event, listener);
|
|
1148
|
+
};
|
|
1149
|
+
if (onQR) on("qr", (qr) => void this._dispatch([onQR], qr, "onQR"));
|
|
1150
|
+
if (onPairingCode)
|
|
1151
|
+
on("code", (code) => void this._dispatch([onPairingCode], code, "onPairingCode"));
|
|
1152
|
+
on("ready", () => this._onReady());
|
|
1153
|
+
on("disconnected", (reason) => this._onDisconnected(String(reason)));
|
|
1154
|
+
on("message_create", (message) => this._guard("message", this._onMessage(message)));
|
|
1155
|
+
on("message_edit", (message, _new, previous) => this._onEdit(message, String(previous)));
|
|
1156
|
+
on("message_revoke_everyone", (message, revoked) => this._onRevoke(message, revoked));
|
|
1157
|
+
on("message_reaction", (reaction) => this._onReaction(reaction));
|
|
1158
|
+
on("message_ack", (message, ack) => this._onAck(message, ack));
|
|
1159
|
+
on("vote_update", (vote) => this._guard("poll vote", this._onVote(vote)));
|
|
1160
|
+
on("call", (call) => void this._dispatch(this._callHandlers, call, "onCall"));
|
|
853
1161
|
for (const [event, type] of Object.entries(GROUP_EVENTS)) {
|
|
854
|
-
|
|
1162
|
+
on(event, (notification) => this._onGroup(type, notification));
|
|
855
1163
|
}
|
|
856
1164
|
}
|
|
1165
|
+
_unlisten() {
|
|
1166
|
+
for (const [event, listener] of this._listeners) this.client.off(event, listener);
|
|
1167
|
+
this._listeners = [];
|
|
1168
|
+
}
|
|
1169
|
+
_onReady() {
|
|
1170
|
+
this._state = "connected";
|
|
1171
|
+
this._strikes = 0;
|
|
1172
|
+
if (!this._config.userName && this.client.info?.pushname) {
|
|
1173
|
+
this.userName = this.client.info.pushname;
|
|
1174
|
+
}
|
|
1175
|
+
this._logger.info("WhatsApp session ready", { userId: this.botUserId });
|
|
1176
|
+
void this._learnLid();
|
|
1177
|
+
this._guard("catch-up", this._catchUp());
|
|
1178
|
+
}
|
|
857
1179
|
async _onMessage(raw) {
|
|
858
1180
|
if (!this._chat || this._isOwn(raw.fromMe)) return;
|
|
859
1181
|
const chatId = chatIdOf(raw);
|
|
860
1182
|
if (raw.isStatus || isBroadcastId(chatId) || SYSTEM_TYPES.has(raw.type)) return;
|
|
1183
|
+
const id = serialize(raw.id);
|
|
1184
|
+
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);
|
|
861
1187
|
const threadId = this.encodeThreadId({ chatId });
|
|
862
1188
|
if (this._config.markSeen && !raw.fromMe) {
|
|
863
1189
|
await this.markAsRead(threadId).catch(
|
|
864
1190
|
(error) => this._logger.warn("Failed to send a read receipt", { error, threadId })
|
|
865
1191
|
);
|
|
866
1192
|
}
|
|
1193
|
+
const author = this._author(raw);
|
|
1194
|
+
if (await this._answer(raw, threadId, author) || this._command(raw, threadId, author)) {
|
|
1195
|
+
await this._remember(raw);
|
|
1196
|
+
return;
|
|
1197
|
+
}
|
|
867
1198
|
const parsed = this._addons("onMessage").length > 0 ? await this._parse(raw) : void 0;
|
|
868
1199
|
if (!parsed || !await this._claimed(parsed, threadId)) {
|
|
869
1200
|
await this._chat.processMessage(this, threadId, parsed ?? (() => this._parse(raw)));
|
|
870
1201
|
}
|
|
871
1202
|
await this._remember(raw);
|
|
872
1203
|
}
|
|
1204
|
+
_formKey(threadId, userId) {
|
|
1205
|
+
return `wwebjs:${this.name}:form:${threadId}:${userId}`;
|
|
1206
|
+
}
|
|
1207
|
+
_texts() {
|
|
1208
|
+
return { ...DEFAULT_MODAL_TEXTS, ...this._config.modalTexts };
|
|
1209
|
+
}
|
|
1210
|
+
async _start(threadId, userId, modal, form) {
|
|
1211
|
+
if (!this._chat) throw new ValidationError3("wwebjs", "A modal needs Chat to be initialized.");
|
|
1212
|
+
const field = currentField(form);
|
|
1213
|
+
await this._chat.getState().set(this._formKey(threadId, userId), form, FORM_TTL_MS);
|
|
1214
|
+
const intro = introOf(modal, this._texts());
|
|
1215
|
+
await this.postMessage(
|
|
1216
|
+
threadId,
|
|
1217
|
+
field ? `${intro}
|
|
1218
|
+
|
|
1219
|
+
${questionOf(field, form, this._texts())}` : intro
|
|
1220
|
+
);
|
|
1221
|
+
}
|
|
1222
|
+
/** A reply from someone filling in a modal answers it, before anything else sees it. */
|
|
1223
|
+
async _answer(raw, threadId, user) {
|
|
1224
|
+
const state = this._chat.getState();
|
|
1225
|
+
const key = this._formKey(threadId, user.userId);
|
|
1226
|
+
const form = await state.get(key);
|
|
1227
|
+
const field = form && currentField(form);
|
|
1228
|
+
if (!form || !field) return false;
|
|
1229
|
+
const texts = this._texts();
|
|
1230
|
+
const text = (raw.body ?? "").trim();
|
|
1231
|
+
const event = { adapter: this, callbackId: form.callbackId, raw, user, viewId: form.viewId };
|
|
1232
|
+
if ([texts.cancel, form.closeLabel].some((word) => word?.toLowerCase() === text.toLowerCase())) {
|
|
1233
|
+
await state.delete(key);
|
|
1234
|
+
await this.postMessage(threadId, texts.cancelled);
|
|
1235
|
+
if (form.notifyOnClose) {
|
|
1236
|
+
await this._chat.processModalClose(
|
|
1237
|
+
{ ...event, privateMetadata: form.privateMetadata },
|
|
1238
|
+
form.contextId
|
|
1239
|
+
);
|
|
1240
|
+
}
|
|
1241
|
+
return true;
|
|
1242
|
+
}
|
|
1243
|
+
const answer = answerOf(field, form, text, texts);
|
|
1244
|
+
if ("search" in answer) {
|
|
1245
|
+
const found = flattenOptions(
|
|
1246
|
+
await this._chat.processOptionsLoad({
|
|
1247
|
+
actionId: field.id,
|
|
1248
|
+
adapter: this,
|
|
1249
|
+
query: answer.search,
|
|
1250
|
+
raw,
|
|
1251
|
+
user
|
|
1252
|
+
})
|
|
1253
|
+
);
|
|
1254
|
+
const next2 = { ...form, found: found.length > 0 ? found : void 0 };
|
|
1255
|
+
await state.set(key, next2, FORM_TTL_MS);
|
|
1256
|
+
const question = questionOf(field, next2, texts);
|
|
1257
|
+
await this.postMessage(
|
|
1258
|
+
threadId,
|
|
1259
|
+
found.length > 0 ? question : `${texts.noResults}
|
|
1260
|
+
|
|
1261
|
+
${question}`
|
|
1262
|
+
);
|
|
1263
|
+
return true;
|
|
1264
|
+
}
|
|
1265
|
+
if ("error" in answer) {
|
|
1266
|
+
await this.postMessage(threadId, `${answer.error}
|
|
1267
|
+
|
|
1268
|
+
${questionOf(field, form, texts)}`);
|
|
1269
|
+
return true;
|
|
1270
|
+
}
|
|
1271
|
+
const { [field.id]: _previous, ...rest } = form.values;
|
|
1272
|
+
const next = {
|
|
1273
|
+
...form,
|
|
1274
|
+
found: void 0,
|
|
1275
|
+
pending: form.pending.slice(1),
|
|
1276
|
+
values: answer.value === void 0 ? rest : { ...rest, [field.id]: answer.value }
|
|
1277
|
+
};
|
|
1278
|
+
const following = currentField(next);
|
|
1279
|
+
if (following) {
|
|
1280
|
+
await state.set(key, next, FORM_TTL_MS);
|
|
1281
|
+
await this.postMessage(threadId, questionOf(following, next, texts));
|
|
1282
|
+
return true;
|
|
1283
|
+
}
|
|
1284
|
+
await state.delete(key);
|
|
1285
|
+
const response = await this._chat.processModalSubmit(
|
|
1286
|
+
{ ...event, privateMetadata: next.privateMetadata, values: next.values },
|
|
1287
|
+
next.contextId
|
|
1288
|
+
);
|
|
1289
|
+
if (response?.action === "errors") {
|
|
1290
|
+
const retry = {
|
|
1291
|
+
...next,
|
|
1292
|
+
pending: next.fields.map(({ id }) => id).filter((id) => id in response.errors)
|
|
1293
|
+
};
|
|
1294
|
+
const first = currentField(retry);
|
|
1295
|
+
if (first) {
|
|
1296
|
+
await state.set(key, retry, FORM_TTL_MS);
|
|
1297
|
+
const reasons = Object.values(response.errors).join("\n");
|
|
1298
|
+
await this.postMessage(threadId, `${reasons}
|
|
1299
|
+
|
|
1300
|
+
${questionOf(first, retry, texts)}`);
|
|
1301
|
+
}
|
|
1302
|
+
} else if (response?.action === "update" || response?.action === "push") {
|
|
1303
|
+
const viewId = response.action === "update" ? next.viewId : randomUUID();
|
|
1304
|
+
await this._start(
|
|
1305
|
+
threadId,
|
|
1306
|
+
user.userId,
|
|
1307
|
+
response.modal,
|
|
1308
|
+
createForm(response.modal, viewId, next.contextId)
|
|
1309
|
+
);
|
|
1310
|
+
}
|
|
1311
|
+
return true;
|
|
1312
|
+
}
|
|
1313
|
+
/** WhatsApp has no slash commands, so a message naming a declared one becomes one. */
|
|
1314
|
+
_command(raw, threadId, user) {
|
|
1315
|
+
const match = /^(\/\S+)(?:\s+([\s\S]*))?$/.exec((raw.body ?? "").trim());
|
|
1316
|
+
const command = match && this._config.slashCommands?.find((name) => name.toLowerCase() === match[1].toLowerCase());
|
|
1317
|
+
if (!command) return false;
|
|
1318
|
+
this._chat.processSlashCommand(
|
|
1319
|
+
{
|
|
1320
|
+
adapter: this,
|
|
1321
|
+
channelId: threadId,
|
|
1322
|
+
command,
|
|
1323
|
+
raw,
|
|
1324
|
+
text: match[2] ?? "",
|
|
1325
|
+
triggerId: triggerIdOf(threadId, user.userId),
|
|
1326
|
+
user
|
|
1327
|
+
},
|
|
1328
|
+
void 0
|
|
1329
|
+
);
|
|
1330
|
+
return true;
|
|
1331
|
+
}
|
|
873
1332
|
async _claimed(message, threadId) {
|
|
874
1333
|
for (const addon of this._addons("onMessage")) {
|
|
875
1334
|
if (await addon.onMessage(message, this._context(threadId))) return true;
|
|
@@ -880,7 +1339,7 @@ var WWebJSAdapter = class {
|
|
|
880
1339
|
return (this._config.addons ?? []).filter((addon) => addon[hook]);
|
|
881
1340
|
}
|
|
882
1341
|
_context(threadId) {
|
|
883
|
-
return { adapter: this, chat: this._chat, threadId };
|
|
1342
|
+
return { adapter: this, chat: this._chat, richContent: !!this._config.richContent, threadId };
|
|
884
1343
|
}
|
|
885
1344
|
_seenKey() {
|
|
886
1345
|
return `wwebjs:${this.name}:seen`;
|
|
@@ -894,13 +1353,20 @@ var WWebJSAdapter = class {
|
|
|
894
1353
|
);
|
|
895
1354
|
return this._saving;
|
|
896
1355
|
}
|
|
1356
|
+
/** While a catch-up runs the position holds still, so a crash part-way replays rather than skips. */
|
|
897
1357
|
async _remember(raw) {
|
|
898
|
-
if (this._config.catchUpMs === false
|
|
1358
|
+
if (this._config.catchUpMs === false) return;
|
|
1359
|
+
if (this._behind) this._behind.push(raw);
|
|
1360
|
+
else if (this._advance(raw)) await this._save();
|
|
1361
|
+
}
|
|
1362
|
+
_advance(raw) {
|
|
1363
|
+
if (!this._seen) return false;
|
|
899
1364
|
const id = serialize(raw.id);
|
|
900
|
-
const
|
|
901
|
-
|
|
902
|
-
this._seen
|
|
903
|
-
|
|
1365
|
+
const at = Math.min(raw.timestamp, Math.floor(Date.now() / 1e3) + CLOCK_SKEW_S);
|
|
1366
|
+
const { ids } = this._seen;
|
|
1367
|
+
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 };
|
|
1369
|
+
return true;
|
|
904
1370
|
}
|
|
905
1371
|
/** WhatsApp Web loads what arrived while the session was down without announcing every message. */
|
|
906
1372
|
async _catchUp() {
|
|
@@ -908,18 +1374,49 @@ var WWebJSAdapter = class {
|
|
|
908
1374
|
const state = this._chat?.getState();
|
|
909
1375
|
if (windowMs === false || !state) return;
|
|
910
1376
|
this._seen ??= await state.get(this._seenKey());
|
|
1377
|
+
if (this._seen?.wid && this._seen.wid !== this.botUserId) this._seen = null;
|
|
911
1378
|
const seen = this._seen;
|
|
912
1379
|
if (!seen) {
|
|
913
|
-
this._seen = { at: Math.floor(Date.now() / 1e3), ids: [] };
|
|
1380
|
+
this._seen = { at: Math.floor(Date.now() / 1e3), ids: [], wid: this.botUserId };
|
|
914
1381
|
await this._save();
|
|
915
1382
|
return;
|
|
916
1383
|
}
|
|
917
1384
|
const oldest = Math.max(seen.at, Math.floor((Date.now() - windowMs) / 1e3));
|
|
918
1385
|
const unseen = (message) => message.timestamp > oldest || message.timestamp === seen.at && !seen.ids.includes(serialize(message.id));
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
const
|
|
922
|
-
|
|
1386
|
+
this._behind = [];
|
|
1387
|
+
try {
|
|
1388
|
+
const chats = (await this.client.getChats()).filter((chat) => chat.timestamp >= oldest);
|
|
1389
|
+
const missed = [];
|
|
1390
|
+
let truncated = chats.length > MAX_CATCH_UP_CHATS;
|
|
1391
|
+
for (const chat of chats.slice(0, MAX_CATCH_UP_CHATS)) {
|
|
1392
|
+
const messages = await chat.fetchMessages({ limit: MAX_CATCH_UP_MESSAGES }).catch((error) => {
|
|
1393
|
+
this._logger.warn("Could not catch up on a chat", {
|
|
1394
|
+
chatId: serialize(chat.id),
|
|
1395
|
+
error
|
|
1396
|
+
});
|
|
1397
|
+
return [];
|
|
1398
|
+
});
|
|
1399
|
+
const behind = messages.filter(unseen);
|
|
1400
|
+
truncated ||= behind.length === MAX_CATCH_UP_MESSAGES;
|
|
1401
|
+
missed.push(...behind);
|
|
1402
|
+
}
|
|
1403
|
+
if (truncated) {
|
|
1404
|
+
this._logger.warn(
|
|
1405
|
+
`Caught up on the ${MAX_CATCH_UP_CHATS} most recent chats and ${MAX_CATCH_UP_MESSAGES} messages each; older ones were missed`
|
|
1406
|
+
);
|
|
1407
|
+
}
|
|
1408
|
+
for (const message of missed.sort((a, b) => a.timestamp - b.timestamp)) {
|
|
1409
|
+
await this._onMessage(message).catch(
|
|
1410
|
+
(error) => this._logger.warn("A missed message was not handled", {
|
|
1411
|
+
error,
|
|
1412
|
+
messageId: serialize(message.id)
|
|
1413
|
+
})
|
|
1414
|
+
);
|
|
1415
|
+
}
|
|
1416
|
+
} finally {
|
|
1417
|
+
const delivered = this._behind;
|
|
1418
|
+
this._behind = void 0;
|
|
1419
|
+
if (delivered.map((message) => this._advance(message)).some(Boolean)) await this._save();
|
|
923
1420
|
}
|
|
924
1421
|
}
|
|
925
1422
|
_onEdit(raw, previousBody) {
|
|
@@ -1107,7 +1604,7 @@ var WWebJSAdapter = class {
|
|
|
1107
1604
|
_onDisconnected(reason) {
|
|
1108
1605
|
if (this._closed) return;
|
|
1109
1606
|
this._connection = null;
|
|
1110
|
-
this._state = this.
|
|
1607
|
+
this._state = this._reconnects() ? "reconnecting" : "disconnected";
|
|
1111
1608
|
if (reason === "LOGOUT") {
|
|
1112
1609
|
this._state = "logged_out";
|
|
1113
1610
|
this._logger.error("WhatsApp logged this session out; pair it again to reconnect", {
|
|
@@ -1118,8 +1615,11 @@ var WWebJSAdapter = class {
|
|
|
1118
1615
|
this._logger.warn("WhatsApp disconnected", { reason });
|
|
1119
1616
|
this._reconnect(RECONNECT_MIN_MS);
|
|
1120
1617
|
}
|
|
1618
|
+
_reconnects() {
|
|
1619
|
+
return this._owned && this._config.reconnect !== false;
|
|
1620
|
+
}
|
|
1121
1621
|
_reconnect(delayMs) {
|
|
1122
|
-
if (this._closed || this.
|
|
1622
|
+
if (this._closed || !this._reconnects()) return;
|
|
1123
1623
|
clearTimeout(this._retry);
|
|
1124
1624
|
this._state = "reconnecting";
|
|
1125
1625
|
this._retry = setTimeout(() => {
|
|
@@ -1161,7 +1661,10 @@ var WWebJSAdapter = class {
|
|
|
1161
1661
|
const text = addon.renderCard(card, this._context(threadId));
|
|
1162
1662
|
if (text !== void 0) return { card, text };
|
|
1163
1663
|
}
|
|
1164
|
-
return {
|
|
1664
|
+
return {
|
|
1665
|
+
card,
|
|
1666
|
+
text: this._config.richContent ? cardToText(card) : cardToPlainText(card)
|
|
1667
|
+
};
|
|
1165
1668
|
}
|
|
1166
1669
|
/** The card is already on WhatsApp, so an addon failing here must not fail the send. */
|
|
1167
1670
|
async _cardSent(card, messageId, threadId) {
|
|
@@ -1178,12 +1681,19 @@ var WWebJSAdapter = class {
|
|
|
1178
1681
|
const { chatId } = this.decodeThreadId(threadId);
|
|
1179
1682
|
const { card, text: rendered } = this._render(message, threadId);
|
|
1180
1683
|
const { mentions, text } = extractMentions(rendered);
|
|
1181
|
-
const media =
|
|
1684
|
+
const media = [
|
|
1685
|
+
...await toMediaList(message, this._config.maxMediaBytes),
|
|
1686
|
+
...await Promise.all(
|
|
1687
|
+
(card && this._config.richContent ? cardImages(card) : []).map(
|
|
1688
|
+
(url) => toMedia({ type: "image", url }, this._config.maxMediaBytes)
|
|
1689
|
+
)
|
|
1690
|
+
)
|
|
1691
|
+
];
|
|
1182
1692
|
const send = {
|
|
1183
1693
|
...options,
|
|
1184
1694
|
...mentions.length > 0 ? { mentions } : {}
|
|
1185
1695
|
};
|
|
1186
|
-
const voice = this._config.voiceNotes
|
|
1696
|
+
const voice = this._config.voiceNotes ?? true;
|
|
1187
1697
|
const captionIndex = text ? media.findIndex(isCaptionable) : -1;
|
|
1188
1698
|
const payloads = [];
|
|
1189
1699
|
if (media.length === 0 || text && captionIndex === -1) payloads.push([text, send]);
|
|
@@ -1191,7 +1701,7 @@ var WWebJSAdapter = class {
|
|
|
1191
1701
|
const itemOptions = index === captionIndex ? { ...send, caption: text } : send;
|
|
1192
1702
|
payloads.push([
|
|
1193
1703
|
item,
|
|
1194
|
-
voice && isAudio(item) ? { ...itemOptions, sendAudioAsVoice: true } : itemOptions
|
|
1704
|
+
(voice === "ogg" ? isVoiceNote(item) : voice && isAudio(item)) ? { ...itemOptions, sendAudioAsVoice: true } : itemOptions
|
|
1195
1705
|
]);
|
|
1196
1706
|
});
|
|
1197
1707
|
let first;
|
|
@@ -1213,7 +1723,7 @@ var WWebJSAdapter = class {
|
|
|
1213
1723
|
}
|
|
1214
1724
|
_raw(sent, threadId) {
|
|
1215
1725
|
if (!sent) {
|
|
1216
|
-
throw new
|
|
1726
|
+
throw new ValidationError3(
|
|
1217
1727
|
"wwebjs",
|
|
1218
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."
|
|
1219
1729
|
);
|
|
@@ -1254,8 +1764,16 @@ var WWebJSAdapter = class {
|
|
|
1254
1764
|
}
|
|
1255
1765
|
return chat;
|
|
1256
1766
|
}
|
|
1257
|
-
|
|
1767
|
+
/** A DM can be addressed by phone or by LID, so only a group's messages must match the thread exactly. */
|
|
1768
|
+
async _findMessage(messageId, threadId) {
|
|
1258
1769
|
const message = await this.client.getMessageById(messageId).catch(() => null);
|
|
1770
|
+
if (!message || !threadId) return message;
|
|
1771
|
+
const chatId = chatIdOf(message);
|
|
1772
|
+
const expected = this.decodeThreadId(threadId).chatId;
|
|
1773
|
+
return chatId === expected || !(isGroupId(chatId) || isGroupId(expected)) ? message : null;
|
|
1774
|
+
}
|
|
1775
|
+
async _requireMessage(messageId, threadId) {
|
|
1776
|
+
const message = await this._findMessage(messageId, threadId);
|
|
1259
1777
|
if (!message) {
|
|
1260
1778
|
throw new ResourceNotFoundError("wwebjs", "message", messageId);
|
|
1261
1779
|
}
|
|
@@ -1268,6 +1786,9 @@ function createWWebJSAdapter(config = {}) {
|
|
|
1268
1786
|
function chatIdOf(message) {
|
|
1269
1787
|
return message.id?.remote || (message.fromMe ? message.to : message.from);
|
|
1270
1788
|
}
|
|
1789
|
+
function locationText({ address, latitude, longitude, name }) {
|
|
1790
|
+
return [name, address, `https://maps.google.com/?q=${latitude},${longitude}`].filter(Boolean).join("\n");
|
|
1791
|
+
}
|
|
1271
1792
|
function within(lookup) {
|
|
1272
1793
|
return Promise.race([
|
|
1273
1794
|
lookup.catch(() => null),
|
|
@@ -1282,7 +1803,7 @@ function participantAuthor(userId, isMe) {
|
|
|
1282
1803
|
}
|
|
1283
1804
|
function assertRange(label, value, bound) {
|
|
1284
1805
|
if (!Number.isFinite(value) || value < -bound || value > bound) {
|
|
1285
|
-
throw new
|
|
1806
|
+
throw new ValidationError3(
|
|
1286
1807
|
"wwebjs",
|
|
1287
1808
|
`sendLocation: ${label} must be between -${bound} and ${bound}. Received ${value}.`
|
|
1288
1809
|
);
|
|
@@ -1290,25 +1811,24 @@ function assertRange(label, value, bound) {
|
|
|
1290
1811
|
}
|
|
1291
1812
|
|
|
1292
1813
|
// src/guards.ts
|
|
1293
|
-
import { ValidationError as
|
|
1814
|
+
import { ValidationError as ValidationError4 } from "@chat-adapter/shared";
|
|
1294
1815
|
function isWWebJSAdapter(value) {
|
|
1295
1816
|
return value instanceof WWebJSAdapter;
|
|
1296
1817
|
}
|
|
1297
1818
|
function requireWWebJSAdapter(value) {
|
|
1298
1819
|
const adapter = value && typeof value === "object" && "adapter" in value ? value.adapter : value;
|
|
1299
1820
|
if (isWWebJSAdapter(adapter)) return adapter;
|
|
1300
|
-
throw new
|
|
1821
|
+
throw new ValidationError4("wwebjs", "This context does not belong to a wwebjs adapter.");
|
|
1301
1822
|
}
|
|
1302
1823
|
|
|
1303
1824
|
// src/numbered-actions.ts
|
|
1304
|
-
import { cardToFallbackText as cardToFallbackText2 } from "@chat-adapter/shared";
|
|
1305
1825
|
var TTL_MS = 864e5;
|
|
1306
1826
|
function actionsOf(children) {
|
|
1307
1827
|
return children.flatMap(
|
|
1308
1828
|
(child) => child.type === "actions" ? [child] : child.type === "section" ? actionsOf(child.children) : []
|
|
1309
1829
|
);
|
|
1310
1830
|
}
|
|
1311
|
-
function layout(card) {
|
|
1831
|
+
function layout(card, richContent) {
|
|
1312
1832
|
const choices = [];
|
|
1313
1833
|
const lines = [];
|
|
1314
1834
|
const offer = (choice) => {
|
|
@@ -1317,13 +1837,12 @@ function layout(card) {
|
|
|
1317
1837
|
};
|
|
1318
1838
|
for (const { children } of actionsOf(card.children)) {
|
|
1319
1839
|
for (const action of children) {
|
|
1320
|
-
if (action.type === "
|
|
1321
|
-
else if (action.type === "button") {
|
|
1840
|
+
if (action.type === "button") {
|
|
1322
1841
|
if (!action.disabled && action.actionType !== "modal") {
|
|
1323
1842
|
offer({ actionId: action.id, label: action.label, value: action.value });
|
|
1324
1843
|
}
|
|
1325
|
-
} else {
|
|
1326
|
-
lines.push(`*${action.label}*`);
|
|
1844
|
+
} else if (action.type !== "link-button") {
|
|
1845
|
+
lines.push(richContent ? `*${action.label}*` : action.label);
|
|
1327
1846
|
for (const option of action.options) {
|
|
1328
1847
|
offer({ actionId: action.id, label: option.label, value: option.value });
|
|
1329
1848
|
}
|
|
@@ -1337,22 +1856,29 @@ function keyOf({ adapter, threadId }) {
|
|
|
1337
1856
|
}
|
|
1338
1857
|
function numberedActions(options = {}) {
|
|
1339
1858
|
return {
|
|
1340
|
-
renderCard(card) {
|
|
1341
|
-
const { lines } = layout(card);
|
|
1859
|
+
renderCard(card, { richContent }) {
|
|
1860
|
+
const { lines } = layout(card, richContent);
|
|
1342
1861
|
if (lines.length === 0) return void 0;
|
|
1343
|
-
|
|
1862
|
+
const text = richContent ? cardToText(card) : cardToPlainText(card);
|
|
1863
|
+
return [text, lines.join("\n")].filter(Boolean).join("\n\n");
|
|
1344
1864
|
},
|
|
1345
1865
|
async cardSent(card, messageId, context) {
|
|
1346
|
-
const { choices } = layout(card);
|
|
1866
|
+
const { choices } = layout(card, context.richContent);
|
|
1347
1867
|
if (choices.length === 0 || !context.chat) return;
|
|
1348
1868
|
await context.chat.getState().set(keyOf(context), { choices, messageId }, options.ttlMs ?? TTL_MS);
|
|
1349
1869
|
},
|
|
1350
1870
|
async onMessage(message, context) {
|
|
1351
|
-
|
|
1352
|
-
|
|
1871
|
+
if (message.author.isMe || !context.chat) return false;
|
|
1872
|
+
const state = context.chat.getState();
|
|
1873
|
+
const offer = await state.get(keyOf(context));
|
|
1874
|
+
if (!offer || message.replyTo && message.replyTo.id !== offer.messageId) return false;
|
|
1353
1875
|
const reply = message.text.trim();
|
|
1354
1876
|
const choice = /^\d+$/.test(reply) ? offer.choices[Number(reply) - 1] : offer.choices.find(({ label }) => label.toLowerCase() === reply.toLowerCase());
|
|
1355
1877
|
if (!choice) return false;
|
|
1878
|
+
const ttlMs = options.ttlMs ?? TTL_MS;
|
|
1879
|
+
if (!await state.setIfNotExists(`${keyOf(context)}:${offer.messageId}`, true, ttlMs)) {
|
|
1880
|
+
return false;
|
|
1881
|
+
}
|
|
1356
1882
|
await context.chat.processAction(
|
|
1357
1883
|
{
|
|
1358
1884
|
actionId: choice.actionId,
|
|
@@ -1360,6 +1886,7 @@ function numberedActions(options = {}) {
|
|
|
1360
1886
|
messageId: offer.messageId,
|
|
1361
1887
|
raw: message.raw,
|
|
1362
1888
|
threadId: context.threadId,
|
|
1889
|
+
triggerId: triggerIdOf(context.threadId, message.author.userId),
|
|
1363
1890
|
user: message.author,
|
|
1364
1891
|
value: choice.value
|
|
1365
1892
|
},
|
|
@@ -1388,5 +1915,6 @@ export {
|
|
|
1388
1915
|
toChatId,
|
|
1389
1916
|
toMedia,
|
|
1390
1917
|
toMediaList,
|
|
1391
|
-
toUser
|
|
1918
|
+
toUser,
|
|
1919
|
+
triggerIdOf
|
|
1392
1920
|
};
|