@12-apps/messaging 1.5.0 → 1.6.0
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/README.md +7 -4
- package/dist/{channel-CZjNEBLC.d.ts → channel-BWhnnuip.d.ts} +22 -2
- package/dist/{engine-BJse1HAX.d.ts → engine-BybESJ7p.d.ts} +27 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +65 -8
- package/dist/index.js.map +1 -1
- package/dist/manifest/server.d.ts +2 -2
- package/dist/server/index.d.ts +2 -2
- package/dist/whatsapp/index.d.ts +1 -1
- package/dist/whatsapp-web/index.d.ts +140 -5
- package/dist/whatsapp-web/index.js +371 -3
- package/dist/whatsapp-web/index.js.map +1 -1
- package/package.json +1 -1
- package/src/core/inbound.ts +6 -1
- package/src/core/ports.ts +16 -0
- package/src/core/sent-elsewhere.ts +87 -0
- package/src/core/types.ts +22 -1
- package/src/index.ts +1 -0
- package/src/whatsapp-web/baileys-port.ts +22 -0
- package/src/whatsapp-web/choices.ts +126 -0
- package/src/whatsapp-web/envelope.ts +10 -0
- package/src/whatsapp-web/history.ts +171 -0
- package/src/whatsapp-web/index.ts +15 -1
- package/src/whatsapp-web/normalize.ts +44 -4
- package/src/whatsapp-web/own-sends.ts +124 -0
- package/src/whatsapp-web/session.ts +91 -6
- package/src/whatsapp-web/timers.ts +19 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { s as OutboundContent, c as ChannelMedia, S as SendPolicy, a as ChannelAdapter, N as NormalizedEvent, n as InboundContent, v as StatusEvent, R as ReceiptStatus } from '../channel-
|
|
1
|
+
import { s as OutboundContent, c as ChannelMedia, S as SendPolicy, a as ChannelAdapter, N as NormalizedEvent, n as InboundContent, v as SentElsewhereEvent, w as StatusEvent, R as ReceiptStatus } from '../channel-BWhnnuip.js';
|
|
2
2
|
|
|
3
3
|
/** `WAMessageKey`: Baileys' `proto.IMessageKey` plus the v7 LID alternates. */
|
|
4
4
|
interface BaileysMessageKey {
|
|
@@ -43,6 +43,16 @@ interface BaileysConnectionUpdate {
|
|
|
43
43
|
lastDisconnect?: BaileysDisconnect;
|
|
44
44
|
qr?: string;
|
|
45
45
|
}
|
|
46
|
+
/** `messaging-history.set`: a history sync. `syncType` is `proto.HistorySync.HistorySyncType` (6 is ON_DEMAND), a number or its name. */
|
|
47
|
+
interface BaileysHistorySet<Msg extends BaileysMessage = BaileysMessage> {
|
|
48
|
+
messages: Msg[];
|
|
49
|
+
syncType?: number | string | null;
|
|
50
|
+
/** The id `fetchMessageHistory` returned, on the answer to that request. */
|
|
51
|
+
peerDataRequestSessionId?: string | null;
|
|
52
|
+
isLatest?: boolean;
|
|
53
|
+
}
|
|
54
|
+
/** `WAPresence` values this layer sends. */
|
|
55
|
+
type BaileysPresence = "composing" | "paused";
|
|
46
56
|
/** The events this layer listens to, by Baileys' own names. */
|
|
47
57
|
interface BaileysEventMap<Msg extends BaileysMessage = BaileysMessage> {
|
|
48
58
|
"connection.update": BaileysConnectionUpdate;
|
|
@@ -52,6 +62,7 @@ interface BaileysEventMap<Msg extends BaileysMessage = BaileysMessage> {
|
|
|
52
62
|
type: "notify" | "append" | string;
|
|
53
63
|
};
|
|
54
64
|
"messages.update": BaileysMessageUpdate[];
|
|
65
|
+
"messaging-history.set": BaileysHistorySet<Msg>;
|
|
55
66
|
}
|
|
56
67
|
/** `SignalKeyStore`: keyed by category, then id. A null value deletes. */
|
|
57
68
|
interface BaileysKeyStore {
|
|
@@ -76,6 +87,15 @@ interface BaileysSocket<Msg extends BaileysMessage = BaileysMessage> {
|
|
|
76
87
|
sendMessage(jid: string, content: {
|
|
77
88
|
text: string;
|
|
78
89
|
}): Promise<Msg | undefined>;
|
|
90
|
+
/** `sendPresenceUpdate(type, toJid?)`: "digitando…" (`composing`) or its end (`paused`) in one chat. */
|
|
91
|
+
sendPresenceUpdate(type: BaileysPresence, toJid?: string): Promise<void>;
|
|
92
|
+
/** `readMessages(keys)`: marks those messages read (blue ticks). */
|
|
93
|
+
readMessages(keys: BaileysMessageKey[]): Promise<void>;
|
|
94
|
+
/**
|
|
95
|
+
* `fetchMessageHistory(count, oldestMsgKey, oldestMsgTimestamp)`: asks the phone for up to `count` messages
|
|
96
|
+
* before that one. Returns the request id; the answer arrives on `messaging-history.set`.
|
|
97
|
+
*/
|
|
98
|
+
fetchMessageHistory(count: number, oldestMsgKey: BaileysMessageKey, oldestMsgTimestamp: number): Promise<string>;
|
|
79
99
|
requestPairingCode(phoneNumber: string): Promise<string>;
|
|
80
100
|
logout(msg?: string): Promise<void>;
|
|
81
101
|
end(error: Error | undefined): Promise<void> | void;
|
|
@@ -177,6 +197,45 @@ declare function loadAuthState(baileys: Pick<BaileysModule<unknown>, "initAuthCr
|
|
|
177
197
|
/** Forget a session's keys, after a logout: the next start pairs a NEW device. */
|
|
178
198
|
declare function clearAuthState(store: AuthStateStore): Promise<void>;
|
|
179
199
|
|
|
200
|
+
/**
|
|
201
|
+
* The timer pair the session's deadlines run on: a history request's timeout and
|
|
202
|
+
* the longest an echo-suspect event is held. Injectable so a test fires them by
|
|
203
|
+
* hand; every timer set here is cleared once what it guards settles.
|
|
204
|
+
*/
|
|
205
|
+
interface WhatsAppWebTimers {
|
|
206
|
+
setTimeout(run: () => void, ms: number): unknown;
|
|
207
|
+
clearTimeout(handle: unknown): void;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* On-demand history: the messages of ONE chat, read from the phone and handed
|
|
212
|
+
* back to the caller, never to the inbox or the engine.
|
|
213
|
+
*
|
|
214
|
+
* `fetchMessageHistory` asks the phone for messages before an anchor and
|
|
215
|
+
* returns only a request id; the answer arrives later on `messaging-history.set`
|
|
216
|
+
* (which can even come BEFORE the call resolves). This module holds the
|
|
217
|
+
* pending requests, matches an answer to the chat it is for, and reduces each
|
|
218
|
+
* message to what a model may read: text, or a placeholder kind for media.
|
|
219
|
+
* Nothing here keeps a message after its request settles.
|
|
220
|
+
*/
|
|
221
|
+
/** The message a history read starts before: the inbound message that began the turn. */
|
|
222
|
+
interface HistoryAnchor {
|
|
223
|
+
externalId: string;
|
|
224
|
+
sentAt: Date;
|
|
225
|
+
fromMe: boolean;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* One message of a chat's history. `kind` is `text`, `interactive`, `audio`, or the channel's own type for
|
|
229
|
+
* anything else (`image`, `sticker`, `video`): text is carried only for `text` and `interactive`.
|
|
230
|
+
*/
|
|
231
|
+
interface WhatsAppWebHistoryMessage {
|
|
232
|
+
externalId: string;
|
|
233
|
+
fromMe: boolean;
|
|
234
|
+
sentAt: Date;
|
|
235
|
+
text: string | null;
|
|
236
|
+
kind: string;
|
|
237
|
+
}
|
|
238
|
+
|
|
180
239
|
/**
|
|
181
240
|
* ONE linked WhatsApp account, over Baileys: the socket, its pairing, its
|
|
182
241
|
* reconnects, and the bridge to the engine.
|
|
@@ -230,14 +289,15 @@ interface WhatsAppWebSessionConfig<Auth = BaileysAuthState, Msg extends BaileysM
|
|
|
230
289
|
authStore: AuthStateStore;
|
|
231
290
|
/**
|
|
232
291
|
* Store one inbound raw body: `(rawBody) => engine.receive(channel, rawBody)`.
|
|
233
|
-
* Called
|
|
234
|
-
*
|
|
292
|
+
* Called one at a time, in socket order, except that a phone-sent message held
|
|
293
|
+
* while a send was in flight comes when it is judged (see the README). A socket
|
|
294
|
+
* does not redeliver, so a throw is reported through `onError` and that body is lost.
|
|
235
295
|
*/
|
|
236
296
|
deliver(rawBody: string): Promise<unknown>;
|
|
237
297
|
/** Every status change. Show the QR or the pairing code from here. */
|
|
238
298
|
onStatus?(status: WhatsAppWebStatus): void;
|
|
239
299
|
/** A failure the session could not hand to a caller: a delivery or a creds save. Never carries a key. */
|
|
240
|
-
onError?(error: unknown, where: "deliver" | "save-creds" | "pairing-code"): void;
|
|
300
|
+
onError?(error: unknown, where: "deliver" | "save-creds" | "pairing-code" | "presence" | "mark-read" | "history"): void;
|
|
241
301
|
/** Pair with a code typed on the phone instead of a QR: the account's number, digits with country code. */
|
|
242
302
|
pairingPhoneNumber?: string;
|
|
243
303
|
/** Opt-out words, as the Cloud adapter's `optOutKeywords`. */
|
|
@@ -253,9 +313,15 @@ interface WhatsAppWebSessionConfig<Auth = BaileysAuthState, Msg extends BaileysM
|
|
|
253
313
|
};
|
|
254
314
|
/** How many recent audio messages are kept in memory for `downloadMedia`. Default 200. */
|
|
255
315
|
mediaCacheSize?: number;
|
|
316
|
+
/** How many contacts' last offered choices are kept to read a typed "1" as a tap. Default 500. */
|
|
317
|
+
choiceMemorySize?: number;
|
|
318
|
+
/** How long offered choices stay answerable by number or title. Default 2 hours. */
|
|
319
|
+
choiceTtlMs?: number;
|
|
256
320
|
/** For tests. */
|
|
257
321
|
now?(): Date;
|
|
258
322
|
sleep?(ms: number): Promise<void>;
|
|
323
|
+
/** The deadlines (a history request's, an echo-suspect's 30 s hold). Default: the global timers. For tests. */
|
|
324
|
+
timers?: WhatsAppWebTimers;
|
|
259
325
|
}
|
|
260
326
|
interface WhatsAppWebSession {
|
|
261
327
|
/** Open the socket: resume the stored device, or pair a new one. Idempotent while running. */
|
|
@@ -271,6 +337,20 @@ interface WhatsAppWebSession {
|
|
|
271
337
|
send(to: string, content: OutboundContent): Promise<{
|
|
272
338
|
externalId: string;
|
|
273
339
|
}>;
|
|
340
|
+
/**
|
|
341
|
+
* Show "digitando…" (`composing`) or its end (`paused`) to one contact. Fire and forget: it never
|
|
342
|
+
* rejects. A failure goes to `onError` (`presence`); a session that is not open reports `NOT_CONNECTED` there.
|
|
343
|
+
*/
|
|
344
|
+
sendPresence(contactId: string, state: "composing" | "paused"): Promise<void>;
|
|
345
|
+
/** Mark messages of one contact read, by their ids. Same failure rules as `sendPresence` (`mark-read`). */
|
|
346
|
+
markRead(contactId: string, externalIds: readonly string[]): Promise<void>;
|
|
347
|
+
/**
|
|
348
|
+
* Read up to `count` messages of one chat that came BEFORE `anchor`, from the phone, on demand. Text only, both
|
|
349
|
+
* sides, media as a placeholder `kind`, oldest first. Nothing is stored here or delivered to the engine. Resolves
|
|
350
|
+
* `[]` when the session is not open, the phone does not answer within `timeoutMs`, or the call fails (`history`);
|
|
351
|
+
* a late answer is dropped.
|
|
352
|
+
*/
|
|
353
|
+
fetchHistory(contactId: string, anchor: HistoryAnchor, count: number, timeoutMs: number): Promise<WhatsAppWebHistoryMessage[]>;
|
|
274
354
|
/** Download a recent inbound audio by its media id (the message id). Throws `ChannelMediaFailure`. */
|
|
275
355
|
downloadMedia(mediaId: string, options: {
|
|
276
356
|
maxBytes: number;
|
|
@@ -361,9 +441,64 @@ declare function normalizeUpsert(accountId: string, upsert: {
|
|
|
361
441
|
messages: readonly BaileysMessage[];
|
|
362
442
|
type: string;
|
|
363
443
|
}, options?: NormalizeOptions): NormalizedEvent[];
|
|
444
|
+
/**
|
|
445
|
+
* One live `messages.upsert` → events for the messages the account sent itself
|
|
446
|
+
* (from another device, or the echo of one of this session's own sends: the
|
|
447
|
+
* CALLER tells them apart by id). `accountId` is the linked account's digits.
|
|
448
|
+
*/
|
|
449
|
+
declare function normalizeSentElsewhere(accountId: string, upsert: {
|
|
450
|
+
messages: readonly BaileysMessage[];
|
|
451
|
+
type: string;
|
|
452
|
+
}): SentElsewhereEvent[];
|
|
364
453
|
/** `proto.WebMessageInfo.Status` → a receipt. PENDING (1) and unknown values are not receipts. */
|
|
365
454
|
declare function receiptOf(status: unknown): ReceiptStatus | null;
|
|
366
455
|
/** One `messages.update` → receipts for the messages this account sent. `at` is when the socket saw it. */
|
|
367
456
|
declare function normalizeUpdates(accountId: string, updates: readonly BaileysMessageUpdate[], at: Date): StatusEvent[];
|
|
368
457
|
|
|
369
|
-
|
|
458
|
+
/**
|
|
459
|
+
* The choices a personal account offered, remembered so the contact's typed
|
|
460
|
+
* answer reads as the tap it stands for.
|
|
461
|
+
*
|
|
462
|
+
* A personal account cannot send reply buttons or lists: `renderOutboundText`
|
|
463
|
+
* sends them as numbered lines, and the contact answers with text. An agent
|
|
464
|
+
* built for the Cloud adapter expects `INTERACTIVE { replyId, title }`. This
|
|
465
|
+
* module keeps the last choices offered to each contact (in memory, bounded,
|
|
466
|
+
* expiring) and turns an answer that is EXACTLY a listed number or EXACTLY a
|
|
467
|
+
* choice's title into that `INTERACTIVE`. Anything else stays `TEXT`.
|
|
468
|
+
*
|
|
469
|
+
* An offer maps only the first reply after it: any later message to that
|
|
470
|
+
* contact, from this session (plain text included) or from the owner's phone
|
|
471
|
+
* (`sent_elsewhere`), clears it, because the "1" that follows answers that.
|
|
472
|
+
*/
|
|
473
|
+
/** One offered choice: the id the agent gave it and the title the contact sees. */
|
|
474
|
+
interface OfferedChoice {
|
|
475
|
+
replyId: string;
|
|
476
|
+
title: string;
|
|
477
|
+
}
|
|
478
|
+
interface ChoiceMemoryOptions {
|
|
479
|
+
/** How many contacts are remembered; the least recently offered goes first. Default 500. */
|
|
480
|
+
maxContacts?: number;
|
|
481
|
+
/** How long an offer stays answerable. Default 2 hours. */
|
|
482
|
+
ttlMs?: number;
|
|
483
|
+
now?(): Date;
|
|
484
|
+
}
|
|
485
|
+
declare class ChoiceMemory {
|
|
486
|
+
private readonly offers;
|
|
487
|
+
private readonly maxContacts;
|
|
488
|
+
private readonly ttlMs;
|
|
489
|
+
private readonly now;
|
|
490
|
+
constructor(options?: ChoiceMemoryOptions);
|
|
491
|
+
/** Remember what was just sent to a contact: its choices replace the earlier offer, and plain text clears it. */
|
|
492
|
+
offer(contactId: string, content: OutboundContent): void;
|
|
493
|
+
/**
|
|
494
|
+
* The choice a typed answer stands for, or null. A listed number wins over a
|
|
495
|
+
* title. A match uses the offer up (the answer was given); a miss, an
|
|
496
|
+
* expired offer or a contact never offered anything clears nothing.
|
|
497
|
+
*/
|
|
498
|
+
resolve(contactId: string, answer: string): OfferedChoice | null;
|
|
499
|
+
/** Something else was said to the contact since: the offer no longer maps their reply. */
|
|
500
|
+
forget(contactId: string): void;
|
|
501
|
+
get size(): number;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
export { type AuthStateStore, type BaileysAuthState, type BaileysConnectionUpdate, type BaileysHistorySet, type BaileysLogger, type BaileysMessage, type BaileysMessageKey, type BaileysMessageUpdate, type BaileysModule, type BaileysPresence, type BaileysSocket, ChoiceMemory, type ChoiceMemoryOptions, DISCONNECT, ENVELOPE_FORMAT, type HistoryAnchor, type NormalizeOptions, type OfferedChoice, type WhatsAppWebAdapterConfig, type WhatsAppWebHistoryMessage, type WhatsAppWebSession, type WhatsAppWebSessionConfig, type WhatsAppWebStatus, type WhatsAppWebTimers, addressJid, clearAuthState, contactAddress, contentOf, createMemoryAuthStateStore, createWhatsAppWebAdapter, createWhatsAppWebSession, disconnectCode, encodeEnvelope, loadAuthState, normalizeSentElsewhere, normalizeUpdates, normalizeUpsert, parseEnvelope, receiptOf, renderOutboundText };
|
|
@@ -62,10 +62,20 @@ function optOutEvent(value, accountId) {
|
|
|
62
62
|
return contactId && at ? { type: "opt_out", accountId, contactId, at } : null;
|
|
63
63
|
}
|
|
64
64
|
__name(optOutEvent, "optOutEvent");
|
|
65
|
+
function sentElsewhereEvent(value, accountId) {
|
|
66
|
+
const contactId = str(value.contactId);
|
|
67
|
+
const externalId = str(value.externalId);
|
|
68
|
+
const sentAt = date(value.sentAt);
|
|
69
|
+
const body = content(value.content);
|
|
70
|
+
if (!contactId || !externalId || !sentAt || !body) return null;
|
|
71
|
+
return { type: "sent_elsewhere", accountId, contactId, externalId, sentAt, content: body };
|
|
72
|
+
}
|
|
73
|
+
__name(sentElsewhereEvent, "sentElsewhereEvent");
|
|
65
74
|
var EVENTS = {
|
|
66
75
|
message: messageEvent,
|
|
67
76
|
status: statusEvent,
|
|
68
|
-
opt_out: optOutEvent
|
|
77
|
+
opt_out: optOutEvent,
|
|
78
|
+
sent_elsewhere: sentElsewhereEvent
|
|
69
79
|
};
|
|
70
80
|
function event(value) {
|
|
71
81
|
if (!isObject(value) || typeof value.type !== "string") return null;
|
|
@@ -183,6 +193,86 @@ function disconnectCode(disconnect) {
|
|
|
183
193
|
}
|
|
184
194
|
__name(disconnectCode, "disconnectCode");
|
|
185
195
|
|
|
196
|
+
// src/whatsapp-web/choices.ts
|
|
197
|
+
function choicesOf(content2) {
|
|
198
|
+
if (content2.kind === "TEXT") return [];
|
|
199
|
+
if (content2.kind === "BUTTONS") return content2.buttons.map((button) => ({ replyId: button.id, title: button.title }));
|
|
200
|
+
return content2.sections.flatMap((section) => section.rows.map((row) => ({ replyId: row.id, title: row.title })));
|
|
201
|
+
}
|
|
202
|
+
__name(choicesOf, "choicesOf");
|
|
203
|
+
function foldTitle(value) {
|
|
204
|
+
return value.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase().replace(/\s+/g, " ").trim();
|
|
205
|
+
}
|
|
206
|
+
__name(foldTitle, "foldTitle");
|
|
207
|
+
function listedNumber(value) {
|
|
208
|
+
const text2 = value.trim();
|
|
209
|
+
if (text2.length > 8) return null;
|
|
210
|
+
const match = /^(\d{1,3})(?:\s*[.)])?$/.exec(text2);
|
|
211
|
+
return match ? Number(match[1]) : null;
|
|
212
|
+
}
|
|
213
|
+
__name(listedNumber, "listedNumber");
|
|
214
|
+
var ChoiceMemory = class {
|
|
215
|
+
static {
|
|
216
|
+
__name(this, "ChoiceMemory");
|
|
217
|
+
}
|
|
218
|
+
offers = /* @__PURE__ */ new Map();
|
|
219
|
+
maxContacts;
|
|
220
|
+
ttlMs;
|
|
221
|
+
now;
|
|
222
|
+
constructor(options = {}) {
|
|
223
|
+
this.maxContacts = options.maxContacts ?? 500;
|
|
224
|
+
this.ttlMs = options.ttlMs ?? 2 * 60 * 60 * 1e3;
|
|
225
|
+
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
226
|
+
}
|
|
227
|
+
/** Remember what was just sent to a contact: its choices replace the earlier offer, and plain text clears it. */
|
|
228
|
+
offer(contactId, content2) {
|
|
229
|
+
const choices = choicesOf(content2);
|
|
230
|
+
this.offers.delete(contactId);
|
|
231
|
+
if (choices.length === 0) return;
|
|
232
|
+
this.offers.set(contactId, { choices, folded: choices.map((choice) => foldTitle(choice.title)), at: this.now().getTime() });
|
|
233
|
+
for (const oldest of this.offers.keys()) {
|
|
234
|
+
if (this.offers.size <= this.maxContacts) break;
|
|
235
|
+
this.offers.delete(oldest);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* The choice a typed answer stands for, or null. A listed number wins over a
|
|
240
|
+
* title. A match uses the offer up (the answer was given); a miss, an
|
|
241
|
+
* expired offer or a contact never offered anything clears nothing.
|
|
242
|
+
*/
|
|
243
|
+
resolve(contactId, answer) {
|
|
244
|
+
const offer = this.offers.get(contactId);
|
|
245
|
+
if (!offer) return null;
|
|
246
|
+
if (this.now().getTime() - offer.at > this.ttlMs) {
|
|
247
|
+
this.offers.delete(contactId);
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
const number = listedNumber(answer);
|
|
251
|
+
const index = number === null ? offer.folded.indexOf(foldTitle(answer)) : number - 1;
|
|
252
|
+
const choice = offer.choices[index];
|
|
253
|
+
if (!choice || index < 0) return null;
|
|
254
|
+
this.offers.delete(contactId);
|
|
255
|
+
return choice;
|
|
256
|
+
}
|
|
257
|
+
/** Something else was said to the contact since: the offer no longer maps their reply. */
|
|
258
|
+
forget(contactId) {
|
|
259
|
+
this.offers.delete(contactId);
|
|
260
|
+
}
|
|
261
|
+
get size() {
|
|
262
|
+
return this.offers.size;
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
function applyChoices(memory, events) {
|
|
266
|
+
return events.map((event2) => {
|
|
267
|
+
if (event2.type === "sent_elsewhere") memory.forget(event2.contactId);
|
|
268
|
+
if (event2.type !== "message" || event2.content.kind !== "TEXT") return event2;
|
|
269
|
+
const choice = memory.resolve(event2.contactId, event2.content.text);
|
|
270
|
+
const content2 = choice ? { kind: "INTERACTIVE", replyId: choice.replyId, title: choice.title } : null;
|
|
271
|
+
return content2 ? { ...event2, content: content2 } : event2;
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
__name(applyChoices, "applyChoices");
|
|
275
|
+
|
|
186
276
|
// src/whatsapp-web/normalize.ts
|
|
187
277
|
var isObject2 = /* @__PURE__ */ __name((value) => typeof value === "object" && value !== null && !Array.isArray(value), "isObject");
|
|
188
278
|
var text = /* @__PURE__ */ __name((value) => typeof value === "string" && value.length > 0 ? value : null, "text");
|
|
@@ -208,6 +298,10 @@ function addressJid(address) {
|
|
|
208
298
|
return `${digits}${PN_SUFFIX}`;
|
|
209
299
|
}
|
|
210
300
|
__name(addressJid, "addressJid");
|
|
301
|
+
function replyAddress(to, sentKey) {
|
|
302
|
+
return contactAddress({ remoteJid: addressJid(to), remoteJidAlt: sentKey?.remoteJidAlt ?? null });
|
|
303
|
+
}
|
|
304
|
+
__name(replyAddress, "replyAddress");
|
|
211
305
|
function longNumber(value) {
|
|
212
306
|
if (typeof value === "number") return Number.isFinite(value) && value > 0 ? value : null;
|
|
213
307
|
if (typeof value === "string") return longNumber(Number(value));
|
|
@@ -273,6 +367,28 @@ function normalizeUpsert(accountId, upsert, options = {}) {
|
|
|
273
367
|
return upsert.messages.map((message) => inboundEvent(accountId, message, keywords)).filter((event2) => event2 !== null);
|
|
274
368
|
}
|
|
275
369
|
__name(normalizeUpsert, "normalizeUpsert");
|
|
370
|
+
function sentContent(raw) {
|
|
371
|
+
const content2 = contentOf(raw);
|
|
372
|
+
if (!content2) return null;
|
|
373
|
+
if (content2.kind === "AUDIO") return { kind: "OTHER", channelType: "audio" };
|
|
374
|
+
return content2.kind === "INTERACTIVE" ? { kind: "TEXT", text: content2.title } : content2;
|
|
375
|
+
}
|
|
376
|
+
__name(sentContent, "sentContent");
|
|
377
|
+
function sentElsewhereEvent2(accountId, message) {
|
|
378
|
+
if (!isObject2(message) || !isObject2(message.key) || !message.key.fromMe) return null;
|
|
379
|
+
const id = text(message.key.id);
|
|
380
|
+
const contactId = contactAddress(message.key);
|
|
381
|
+
const seconds = longNumber(message.messageTimestamp);
|
|
382
|
+
const content2 = sentContent(message.message);
|
|
383
|
+
if (!id || !contactId || seconds === null || !content2) return null;
|
|
384
|
+
return { type: "sent_elsewhere", accountId, contactId, externalId: id, sentAt: new Date(seconds * 1e3), content: content2 };
|
|
385
|
+
}
|
|
386
|
+
__name(sentElsewhereEvent2, "sentElsewhereEvent");
|
|
387
|
+
function normalizeSentElsewhere(accountId, upsert) {
|
|
388
|
+
if (upsert.type !== "notify") return [];
|
|
389
|
+
return upsert.messages.map((message) => sentElsewhereEvent2(accountId, message)).filter((event2) => event2 !== null);
|
|
390
|
+
}
|
|
391
|
+
__name(normalizeSentElsewhere, "normalizeSentElsewhere");
|
|
276
392
|
function receiptOf(status) {
|
|
277
393
|
switch (status) {
|
|
278
394
|
case 0:
|
|
@@ -311,6 +427,203 @@ function normalizeUpdates(accountId, updates, at) {
|
|
|
311
427
|
}
|
|
312
428
|
__name(normalizeUpdates, "normalizeUpdates");
|
|
313
429
|
|
|
430
|
+
// src/whatsapp-web/timers.ts
|
|
431
|
+
var systemTimers = {
|
|
432
|
+
setTimeout: /* @__PURE__ */ __name((run, ms) => {
|
|
433
|
+
const handle = setTimeout(run, ms);
|
|
434
|
+
handle.unref?.();
|
|
435
|
+
return handle;
|
|
436
|
+
}, "setTimeout"),
|
|
437
|
+
clearTimeout: /* @__PURE__ */ __name((handle) => clearTimeout(handle), "clearTimeout")
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
// src/whatsapp-web/history.ts
|
|
441
|
+
var ON_DEMAND = 6;
|
|
442
|
+
var isOnDemand = /* @__PURE__ */ __name((syncType) => syncType === ON_DEMAND || syncType === "ON_DEMAND", "isOnDemand");
|
|
443
|
+
function kept(content2) {
|
|
444
|
+
switch (content2.kind) {
|
|
445
|
+
case "TEXT":
|
|
446
|
+
return { text: content2.text, kind: "text" };
|
|
447
|
+
case "INTERACTIVE":
|
|
448
|
+
return { text: content2.title || null, kind: "interactive" };
|
|
449
|
+
case "AUDIO":
|
|
450
|
+
return { text: null, kind: "audio" };
|
|
451
|
+
default:
|
|
452
|
+
return { text: null, kind: content2.channelType.toLowerCase() };
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
__name(kept, "kept");
|
|
456
|
+
function historyMessage(message) {
|
|
457
|
+
const id = message?.key?.id;
|
|
458
|
+
const seconds = longNumber(message?.messageTimestamp);
|
|
459
|
+
const content2 = contentOf(message?.message);
|
|
460
|
+
if (typeof id !== "string" || id === "" || seconds === null || !content2) return null;
|
|
461
|
+
return { externalId: id, fromMe: message.key.fromMe === true, sentAt: new Date(seconds * 1e3), ...kept(content2) };
|
|
462
|
+
}
|
|
463
|
+
__name(historyMessage, "historyMessage");
|
|
464
|
+
var inChat = /* @__PURE__ */ __name((contactId, key) => contactAddress(key) === contactId || [key.remoteJid, key.remoteJidAlt].includes(addressJid(contactId)), "inChat");
|
|
465
|
+
function chatHistory(contactId, messages, count) {
|
|
466
|
+
const seen = /* @__PURE__ */ new Set();
|
|
467
|
+
const found = [];
|
|
468
|
+
for (const raw of messages) {
|
|
469
|
+
if (!raw?.key || !inChat(contactId, raw.key)) continue;
|
|
470
|
+
const message = historyMessage(raw);
|
|
471
|
+
if (!message || seen.has(message.externalId)) continue;
|
|
472
|
+
seen.add(message.externalId);
|
|
473
|
+
found.push(message);
|
|
474
|
+
}
|
|
475
|
+
found.sort((a, b) => a.sentAt.getTime() - b.sentAt.getTime());
|
|
476
|
+
return count > 0 ? found.slice(-count) : [];
|
|
477
|
+
}
|
|
478
|
+
__name(chatHistory, "chatHistory");
|
|
479
|
+
var HistoryRequests = class {
|
|
480
|
+
constructor(timers = systemTimers) {
|
|
481
|
+
this.timers = timers;
|
|
482
|
+
}
|
|
483
|
+
timers;
|
|
484
|
+
static {
|
|
485
|
+
__name(this, "HistoryRequests");
|
|
486
|
+
}
|
|
487
|
+
/** Oldest first: an answer that names no request goes to the oldest one for its chat. */
|
|
488
|
+
pending = /* @__PURE__ */ new Set();
|
|
489
|
+
/**
|
|
490
|
+
* Ask, and wait for the answer without waiting on the call: `call` (which returns the request id) may never
|
|
491
|
+
* settle, and the deadline still ends the wait. A rejected call abandons the request and goes to `onError`.
|
|
492
|
+
*/
|
|
493
|
+
fetch(contactId, count, timeoutMs, call, onError) {
|
|
494
|
+
const wait = this.wait(contactId, count, timeoutMs);
|
|
495
|
+
Promise.resolve().then(call).then(wait.setRequestId, (error) => {
|
|
496
|
+
wait.abandon();
|
|
497
|
+
try {
|
|
498
|
+
onError(error);
|
|
499
|
+
} catch {
|
|
500
|
+
}
|
|
501
|
+
});
|
|
502
|
+
return wait.result;
|
|
503
|
+
}
|
|
504
|
+
/** Register a request BEFORE the call is made: the answer may beat the call's own return. The deadline is cleared once it settles. */
|
|
505
|
+
wait(contactId, count, timeoutMs) {
|
|
506
|
+
let entry;
|
|
507
|
+
let timer = null;
|
|
508
|
+
const result = new Promise((resolve) => {
|
|
509
|
+
entry = {
|
|
510
|
+
contactId,
|
|
511
|
+
count,
|
|
512
|
+
requestId: null,
|
|
513
|
+
settle: /* @__PURE__ */ __name((messages) => {
|
|
514
|
+
if (!this.pending.delete(entry)) return;
|
|
515
|
+
this.timers.clearTimeout(timer);
|
|
516
|
+
resolve(messages);
|
|
517
|
+
}, "settle")
|
|
518
|
+
};
|
|
519
|
+
});
|
|
520
|
+
this.pending.add(entry);
|
|
521
|
+
timer = this.timers.setTimeout(() => entry.settle([]), timeoutMs);
|
|
522
|
+
return { result, setRequestId: /* @__PURE__ */ __name((id) => void (entry.requestId = id), "setRequestId"), abandon: /* @__PURE__ */ __name(() => entry.settle([]), "abandon") };
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* A `messaging-history.set`. An answer naming a request id settles THAT request; one naming an id nobody holds
|
|
526
|
+
* yet, or none, settles the oldest request for its chat whose id it cannot contradict. A late answer is dropped.
|
|
527
|
+
*/
|
|
528
|
+
answer(set) {
|
|
529
|
+
if (!isOnDemand(set.syncType) || !Array.isArray(set.messages)) return;
|
|
530
|
+
const named = typeof set.peerDataRequestSessionId === "string" ? set.peerDataRequestSessionId : null;
|
|
531
|
+
const entries = [...this.pending];
|
|
532
|
+
const exact = named ? entries.find((entry) => entry.requestId === named) : void 0;
|
|
533
|
+
const candidates = exact ? [exact] : entries.filter((entry) => !named || entry.requestId === null);
|
|
534
|
+
for (const entry of candidates) {
|
|
535
|
+
const messages = chatHistory(entry.contactId, set.messages, entry.count);
|
|
536
|
+
if (messages.length === 0) continue;
|
|
537
|
+
entry.settle(messages);
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
/** The socket closed: nothing more will come. */
|
|
542
|
+
flush() {
|
|
543
|
+
for (const entry of [...this.pending]) entry.settle([]);
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
|
|
547
|
+
// src/whatsapp-web/own-sends.ts
|
|
548
|
+
var OwnSends = class {
|
|
549
|
+
/** `release` gets the held events that turned out to be from another device, when they are judged. */
|
|
550
|
+
constructor(release, options = {}) {
|
|
551
|
+
this.release = release;
|
|
552
|
+
this.timers = options.timers ?? systemTimers;
|
|
553
|
+
this.maxHoldMs = options.maxHoldMs ?? 3e4;
|
|
554
|
+
this.maxHeld = options.maxHeld ?? 200;
|
|
555
|
+
this.remembered = options.remembered ?? 1e3;
|
|
556
|
+
}
|
|
557
|
+
release;
|
|
558
|
+
static {
|
|
559
|
+
__name(this, "OwnSends");
|
|
560
|
+
}
|
|
561
|
+
ids = /* @__PURE__ */ new Set();
|
|
562
|
+
inFlight = /* @__PURE__ */ new Set();
|
|
563
|
+
sequence = 0;
|
|
564
|
+
held = [];
|
|
565
|
+
timers;
|
|
566
|
+
maxHoldMs;
|
|
567
|
+
maxHeld;
|
|
568
|
+
remembered;
|
|
569
|
+
/** Run one send. Its id is remembered whether the caller or the echo gets there first. */
|
|
570
|
+
async track(run) {
|
|
571
|
+
this.sequence += 1;
|
|
572
|
+
const send = this.sequence;
|
|
573
|
+
this.inFlight.add(send);
|
|
574
|
+
let id = null;
|
|
575
|
+
try {
|
|
576
|
+
const result = await run();
|
|
577
|
+
id = result.externalId;
|
|
578
|
+
return result;
|
|
579
|
+
} finally {
|
|
580
|
+
this.inFlight.delete(send);
|
|
581
|
+
if (id) this.remember(id);
|
|
582
|
+
for (const entry of this.held) entry.waitingOn.delete(send);
|
|
583
|
+
this.releaseWhere((entry) => entry.waitingOn.size === 0);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
/** The events to hand on NOW: not our own, and none while a send is in flight (those are held). */
|
|
587
|
+
accept(events) {
|
|
588
|
+
if (this.inFlight.size === 0) return this.judge(events);
|
|
589
|
+
for (const event2 of events) this.hold(event2);
|
|
590
|
+
const excess = new Set(this.held.slice(0, Math.max(0, this.held.length - this.maxHeld)));
|
|
591
|
+
this.releaseWhere((entry) => excess.has(entry));
|
|
592
|
+
return [];
|
|
593
|
+
}
|
|
594
|
+
/** The socket closed: release everything held, and hold nothing for the sends that were in flight. */
|
|
595
|
+
reset() {
|
|
596
|
+
this.inFlight.clear();
|
|
597
|
+
this.releaseWhere(() => true);
|
|
598
|
+
}
|
|
599
|
+
hold(event2) {
|
|
600
|
+
const entry = { event: event2, waitingOn: new Set(this.inFlight), timer: null };
|
|
601
|
+
entry.timer = this.timers.setTimeout(() => this.releaseWhere((held) => held === entry), this.maxHoldMs);
|
|
602
|
+
this.held.push(entry);
|
|
603
|
+
}
|
|
604
|
+
/** Release the held entries `done` picks, in the order they arrived, judged against the ids known now. */
|
|
605
|
+
releaseWhere(done) {
|
|
606
|
+
const out = [];
|
|
607
|
+
const kept2 = [];
|
|
608
|
+
for (const entry of this.held) (done(entry) ? out : kept2).push(entry);
|
|
609
|
+
if (out.length === 0) return;
|
|
610
|
+
this.held = kept2;
|
|
611
|
+
for (const entry of out) this.timers.clearTimeout(entry.timer);
|
|
612
|
+
const events = this.judge(out.map((entry) => entry.event));
|
|
613
|
+
if (events.length > 0) this.release(events);
|
|
614
|
+
}
|
|
615
|
+
judge(events) {
|
|
616
|
+
return events.filter((event2) => !this.ids.has(event2.externalId));
|
|
617
|
+
}
|
|
618
|
+
remember(id) {
|
|
619
|
+
this.ids.add(id);
|
|
620
|
+
for (const oldest of this.ids) {
|
|
621
|
+
if (this.ids.size <= this.remembered) break;
|
|
622
|
+
this.ids.delete(oldest);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
};
|
|
626
|
+
|
|
314
627
|
// src/whatsapp-web/media.ts
|
|
315
628
|
var AudioCache = class {
|
|
316
629
|
constructor(size) {
|
|
@@ -393,7 +706,14 @@ var TERMINAL = {
|
|
|
393
706
|
var BaileysSession = class {
|
|
394
707
|
constructor(config) {
|
|
395
708
|
this.config = config;
|
|
709
|
+
this.history = new HistoryRequests(config.timers);
|
|
710
|
+
this.ownSends = new OwnSends((events) => this.deliver(applyChoices(this.choices, events)), config.timers ? { timers: config.timers } : {});
|
|
396
711
|
this.audio = new AudioCache(config.mediaCacheSize ?? 200);
|
|
712
|
+
this.choices = new ChoiceMemory({
|
|
713
|
+
...config.choiceMemorySize !== void 0 ? { maxContacts: config.choiceMemorySize } : {},
|
|
714
|
+
...config.choiceTtlMs !== void 0 ? { ttlMs: config.choiceTtlMs } : {},
|
|
715
|
+
now: /* @__PURE__ */ __name(() => (config.now ?? (() => /* @__PURE__ */ new Date()))(), "now")
|
|
716
|
+
});
|
|
397
717
|
}
|
|
398
718
|
config;
|
|
399
719
|
static {
|
|
@@ -407,6 +727,9 @@ var BaileysSession = class {
|
|
|
407
727
|
pairingRequested = false;
|
|
408
728
|
deliveries = Promise.resolve();
|
|
409
729
|
audio;
|
|
730
|
+
choices;
|
|
731
|
+
history;
|
|
732
|
+
ownSends;
|
|
410
733
|
status = /* @__PURE__ */ __name(() => this.current, "status");
|
|
411
734
|
accountId = /* @__PURE__ */ __name(() => this.account, "accountId");
|
|
412
735
|
async start() {
|
|
@@ -436,13 +759,44 @@ var BaileysSession = class {
|
|
|
436
759
|
async send(to, content2) {
|
|
437
760
|
const sock = this.socket;
|
|
438
761
|
if (!sock || this.current.state !== "open") throw new ChannelSendFailure("NOT_CONNECTED", "the WhatsApp Web session is not open");
|
|
762
|
+
const { externalId, key } = await this.ownSends.track(() => this.dispatch(sock, to, content2));
|
|
763
|
+
const contact = replyAddress(to, key);
|
|
764
|
+
if (contact) this.choices.offer(contact, content2);
|
|
765
|
+
return { externalId };
|
|
766
|
+
}
|
|
767
|
+
async dispatch(sock, to, content2) {
|
|
439
768
|
const sent = await sock.sendMessage(addressJid(to), { text: renderOutboundText(content2) }).catch((error) => {
|
|
440
769
|
const code = disconnectCode({ error });
|
|
441
770
|
throw new ChannelSendFailure(code === null ? "SEND_FAILED" : String(code), "the WhatsApp Web socket refused the send");
|
|
442
771
|
});
|
|
443
772
|
const externalId = sent?.key?.id;
|
|
444
773
|
if (!externalId) throw new ChannelSendFailure("NO_MESSAGE_ID", "the WhatsApp Web socket returned no message id");
|
|
445
|
-
return { externalId };
|
|
774
|
+
return { externalId, key: sent?.key ?? {} };
|
|
775
|
+
}
|
|
776
|
+
sendPresence(contactId, state) {
|
|
777
|
+
return this.fireAndForget("presence", (sock) => sock.sendPresenceUpdate(state, addressJid(contactId)));
|
|
778
|
+
}
|
|
779
|
+
markRead(contactId, externalIds) {
|
|
780
|
+
if (externalIds.length === 0) return Promise.resolve();
|
|
781
|
+
const remoteJid = addressJid(contactId);
|
|
782
|
+
return this.fireAndForget("mark-read", (sock) => sock.readMessages(externalIds.map((id) => ({ remoteJid, id, fromMe: false }))));
|
|
783
|
+
}
|
|
784
|
+
/** One call on the open socket whose failure is reported, never thrown. */
|
|
785
|
+
async fireAndForget(where, call) {
|
|
786
|
+
const sock = this.socket;
|
|
787
|
+
try {
|
|
788
|
+
if (!sock || this.current.state !== "open") throw new ChannelSendFailure("NOT_CONNECTED", "the WhatsApp Web session is not open");
|
|
789
|
+
await call(sock);
|
|
790
|
+
} catch (error) {
|
|
791
|
+
this.config.onError?.(error, where);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
async fetchHistory(contactId, anchor, count, timeoutMs) {
|
|
795
|
+
const sock = this.socket;
|
|
796
|
+
if (!sock || this.current.state !== "open" || count <= 0) return [];
|
|
797
|
+
const key = { remoteJid: addressJid(contactId), id: anchor.externalId, fromMe: anchor.fromMe };
|
|
798
|
+
const call = /* @__PURE__ */ __name(() => sock.fetchMessageHistory(count, key, Math.floor(anchor.sentAt.getTime() / 1e3)), "call");
|
|
799
|
+
return this.history.fetch(contactId, count, timeoutMs, call, (error) => this.config.onError?.(error, "history"));
|
|
446
800
|
}
|
|
447
801
|
downloadMedia(mediaId, options) {
|
|
448
802
|
const sock = this.socket;
|
|
@@ -461,6 +815,8 @@ var BaileysSession = class {
|
|
|
461
815
|
const sock = this.socket;
|
|
462
816
|
this.socket = null;
|
|
463
817
|
this.account = null;
|
|
818
|
+
this.history.flush();
|
|
819
|
+
this.ownSends.reset();
|
|
464
820
|
return sock;
|
|
465
821
|
}
|
|
466
822
|
setStatus(status) {
|
|
@@ -489,7 +845,15 @@ var BaileysSession = class {
|
|
|
489
845
|
const account = this.linked(sock);
|
|
490
846
|
if (!account) return;
|
|
491
847
|
if (upsert.type === "notify") upsert.messages.forEach((message) => this.audio.remember(message));
|
|
492
|
-
|
|
848
|
+
const options = this.config.optOutKeywords ? { optOutKeywords: this.config.optOutKeywords } : {};
|
|
849
|
+
const events = upsert.messages.flatMap((message) => {
|
|
850
|
+
const one = { type: upsert.type, messages: [message] };
|
|
851
|
+
return [...normalizeUpsert(account, one, options), ...this.ownSends.accept(normalizeSentElsewhere(account, one))];
|
|
852
|
+
});
|
|
853
|
+
this.deliver(applyChoices(this.choices, events));
|
|
854
|
+
});
|
|
855
|
+
sock.ev.on("messaging-history.set", (set) => {
|
|
856
|
+
if (sock === this.socket) this.history.answer(set);
|
|
493
857
|
});
|
|
494
858
|
sock.ev.on("messages.update", (updates) => {
|
|
495
859
|
const account = this.linked(sock);
|
|
@@ -537,6 +901,8 @@ var BaileysSession = class {
|
|
|
537
901
|
async onClose(code) {
|
|
538
902
|
this.socket = null;
|
|
539
903
|
this.account = null;
|
|
904
|
+
this.history.flush();
|
|
905
|
+
this.ownSends.reset();
|
|
540
906
|
if (this.stopping) return this.setStatus({ state: "stopped" });
|
|
541
907
|
if (code === DISCONNECT.loggedOut) {
|
|
542
908
|
await clearAuthState(this.config.authStore);
|
|
@@ -567,6 +933,7 @@ function createWhatsAppWebSession(config) {
|
|
|
567
933
|
}
|
|
568
934
|
__name(createWhatsAppWebSession, "createWhatsAppWebSession");
|
|
569
935
|
export {
|
|
936
|
+
ChoiceMemory,
|
|
570
937
|
DISCONNECT,
|
|
571
938
|
ENVELOPE_FORMAT,
|
|
572
939
|
addressJid,
|
|
@@ -579,6 +946,7 @@ export {
|
|
|
579
946
|
disconnectCode,
|
|
580
947
|
encodeEnvelope,
|
|
581
948
|
loadAuthState,
|
|
949
|
+
normalizeSentElsewhere,
|
|
582
950
|
normalizeUpdates,
|
|
583
951
|
normalizeUpsert,
|
|
584
952
|
parseEnvelope,
|