@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
|
@@ -8,12 +8,17 @@ import {
|
|
|
8
8
|
type BaileysConnectionUpdate,
|
|
9
9
|
type BaileysLogger,
|
|
10
10
|
type BaileysMessage,
|
|
11
|
+
type BaileysMessageKey,
|
|
11
12
|
type BaileysModule,
|
|
12
13
|
type BaileysSocket,
|
|
13
14
|
} from "./baileys-port";
|
|
15
|
+
import { applyChoices, ChoiceMemory } from "./choices";
|
|
14
16
|
import { encodeEnvelope } from "./envelope";
|
|
17
|
+
import { HistoryRequests, type HistoryAnchor, type WhatsAppWebHistoryMessage } from "./history";
|
|
18
|
+
import { OwnSends } from "./own-sends";
|
|
15
19
|
import { AudioCache, downloadAudio } from "./media";
|
|
16
|
-
import { addressJid, jidUser, normalizeUpdates, normalizeUpsert } from "./normalize";
|
|
20
|
+
import { addressJid, jidUser, normalizeSentElsewhere, normalizeUpdates, normalizeUpsert, replyAddress } from "./normalize";
|
|
21
|
+
import type { WhatsAppWebTimers } from "./timers";
|
|
17
22
|
|
|
18
23
|
/**
|
|
19
24
|
* ONE linked WhatsApp account, over Baileys: the socket, its pairing, its
|
|
@@ -49,14 +54,15 @@ export interface WhatsAppWebSessionConfig<Auth = BaileysAuthState, Msg extends B
|
|
|
49
54
|
authStore: AuthStateStore;
|
|
50
55
|
/**
|
|
51
56
|
* Store one inbound raw body: `(rawBody) => engine.receive(channel, rawBody)`.
|
|
52
|
-
* Called
|
|
53
|
-
*
|
|
57
|
+
* Called one at a time, in socket order, except that a phone-sent message held
|
|
58
|
+
* while a send was in flight comes when it is judged (see the README). A socket
|
|
59
|
+
* does not redeliver, so a throw is reported through `onError` and that body is lost.
|
|
54
60
|
*/
|
|
55
61
|
deliver(rawBody: string): Promise<unknown>;
|
|
56
62
|
/** Every status change. Show the QR or the pairing code from here. */
|
|
57
63
|
onStatus?(status: WhatsAppWebStatus): void;
|
|
58
64
|
/** A failure the session could not hand to a caller: a delivery or a creds save. Never carries a key. */
|
|
59
|
-
onError?(error: unknown, where: "deliver" | "save-creds" | "pairing-code"): void;
|
|
65
|
+
onError?(error: unknown, where: "deliver" | "save-creds" | "pairing-code" | "presence" | "mark-read" | "history"): void;
|
|
60
66
|
/** Pair with a code typed on the phone instead of a QR: the account's number, digits with country code. */
|
|
61
67
|
pairingPhoneNumber?: string;
|
|
62
68
|
/** Opt-out words, as the Cloud adapter's `optOutKeywords`. */
|
|
@@ -69,9 +75,15 @@ export interface WhatsAppWebSessionConfig<Auth = BaileysAuthState, Msg extends B
|
|
|
69
75
|
reconnect?: { maxAttempts?: number; delayMs?: number };
|
|
70
76
|
/** How many recent audio messages are kept in memory for `downloadMedia`. Default 200. */
|
|
71
77
|
mediaCacheSize?: number;
|
|
78
|
+
/** How many contacts' last offered choices are kept to read a typed "1" as a tap. Default 500. */
|
|
79
|
+
choiceMemorySize?: number;
|
|
80
|
+
/** How long offered choices stay answerable by number or title. Default 2 hours. */
|
|
81
|
+
choiceTtlMs?: number;
|
|
72
82
|
/** For tests. */
|
|
73
83
|
now?(): Date;
|
|
74
84
|
sleep?(ms: number): Promise<void>;
|
|
85
|
+
/** The deadlines (a history request's, an echo-suspect's 30 s hold). Default: the global timers. For tests. */
|
|
86
|
+
timers?: WhatsAppWebTimers;
|
|
75
87
|
}
|
|
76
88
|
|
|
77
89
|
export interface WhatsAppWebSession {
|
|
@@ -86,6 +98,20 @@ export interface WhatsAppWebSession {
|
|
|
86
98
|
accountId(): string | null;
|
|
87
99
|
/** Send one message. Throws `ChannelSendFailure`. */
|
|
88
100
|
send(to: string, content: OutboundContent): Promise<{ externalId: string }>;
|
|
101
|
+
/**
|
|
102
|
+
* Show "digitando…" (`composing`) or its end (`paused`) to one contact. Fire and forget: it never
|
|
103
|
+
* rejects. A failure goes to `onError` (`presence`); a session that is not open reports `NOT_CONNECTED` there.
|
|
104
|
+
*/
|
|
105
|
+
sendPresence(contactId: string, state: "composing" | "paused"): Promise<void>;
|
|
106
|
+
/** Mark messages of one contact read, by their ids. Same failure rules as `sendPresence` (`mark-read`). */
|
|
107
|
+
markRead(contactId: string, externalIds: readonly string[]): Promise<void>;
|
|
108
|
+
/**
|
|
109
|
+
* Read up to `count` messages of one chat that came BEFORE `anchor`, from the phone, on demand. Text only, both
|
|
110
|
+
* sides, media as a placeholder `kind`, oldest first. Nothing is stored here or delivered to the engine. Resolves
|
|
111
|
+
* `[]` when the session is not open, the phone does not answer within `timeoutMs`, or the call fails (`history`);
|
|
112
|
+
* a late answer is dropped.
|
|
113
|
+
*/
|
|
114
|
+
fetchHistory(contactId: string, anchor: HistoryAnchor, count: number, timeoutMs: number): Promise<WhatsAppWebHistoryMessage[]>;
|
|
89
115
|
/** Download a recent inbound audio by its media id (the message id). Throws `ChannelMediaFailure`. */
|
|
90
116
|
downloadMedia(mediaId: string, options: { maxBytes: number; timeoutMs?: number }): Promise<ChannelMedia>;
|
|
91
117
|
}
|
|
@@ -124,9 +150,19 @@ class BaileysSession<Auth, Msg extends BaileysMessage> implements WhatsAppWebSes
|
|
|
124
150
|
private pairingRequested = false;
|
|
125
151
|
private deliveries: Promise<void> = Promise.resolve();
|
|
126
152
|
private readonly audio: AudioCache<Msg>;
|
|
153
|
+
private readonly choices: ChoiceMemory;
|
|
154
|
+
private readonly history: HistoryRequests;
|
|
155
|
+
private readonly ownSends: OwnSends;
|
|
127
156
|
|
|
128
157
|
constructor(private readonly config: WhatsAppWebSessionConfig<Auth, Msg>) {
|
|
158
|
+
this.history = new HistoryRequests(config.timers);
|
|
159
|
+
this.ownSends = new OwnSends((events) => this.deliver(applyChoices(this.choices, events)), config.timers ? { timers: config.timers } : {});
|
|
129
160
|
this.audio = new AudioCache(config.mediaCacheSize ?? 200);
|
|
161
|
+
this.choices = new ChoiceMemory({
|
|
162
|
+
...(config.choiceMemorySize !== undefined ? { maxContacts: config.choiceMemorySize } : {}),
|
|
163
|
+
...(config.choiceTtlMs !== undefined ? { ttlMs: config.choiceTtlMs } : {}),
|
|
164
|
+
now: () => (config.now ?? (() => new Date()))(),
|
|
165
|
+
});
|
|
130
166
|
}
|
|
131
167
|
|
|
132
168
|
status = (): WhatsAppWebStatus => this.current;
|
|
@@ -162,13 +198,49 @@ class BaileysSession<Auth, Msg extends BaileysMessage> implements WhatsAppWebSes
|
|
|
162
198
|
async send(to: string, content: OutboundContent): Promise<{ externalId: string }> {
|
|
163
199
|
const sock = this.socket;
|
|
164
200
|
if (!sock || this.current.state !== "open") throw new ChannelSendFailure("NOT_CONNECTED", "the WhatsApp Web session is not open");
|
|
201
|
+
const { externalId, key } = await this.ownSends.track(() => this.dispatch(sock, to, content));
|
|
202
|
+
const contact = replyAddress(to, key);
|
|
203
|
+
if (contact) this.choices.offer(contact, content);
|
|
204
|
+
return { externalId };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
private async dispatch(sock: BaileysSocket<Msg>, to: string, content: OutboundContent): Promise<{ externalId: string; key: BaileysMessageKey }> {
|
|
165
208
|
const sent = await sock.sendMessage(addressJid(to), { text: renderOutboundText(content) }).catch((error: unknown) => {
|
|
166
209
|
const code = disconnectCode({ error: error as Error });
|
|
167
210
|
throw new ChannelSendFailure(code === null ? "SEND_FAILED" : String(code), "the WhatsApp Web socket refused the send");
|
|
168
211
|
});
|
|
169
212
|
const externalId = sent?.key?.id;
|
|
170
213
|
if (!externalId) throw new ChannelSendFailure("NO_MESSAGE_ID", "the WhatsApp Web socket returned no message id");
|
|
171
|
-
return { externalId };
|
|
214
|
+
return { externalId, key: sent?.key ?? {} };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
sendPresence(contactId: string, state: "composing" | "paused"): Promise<void> {
|
|
218
|
+
return this.fireAndForget("presence", (sock) => sock.sendPresenceUpdate(state, addressJid(contactId)));
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
markRead(contactId: string, externalIds: readonly string[]): Promise<void> {
|
|
222
|
+
if (externalIds.length === 0) return Promise.resolve();
|
|
223
|
+
const remoteJid = addressJid(contactId);
|
|
224
|
+
return this.fireAndForget("mark-read", (sock) => sock.readMessages(externalIds.map((id) => ({ remoteJid, id, fromMe: false }))));
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** One call on the open socket whose failure is reported, never thrown. */
|
|
228
|
+
private async fireAndForget(where: "presence" | "mark-read", call: (sock: BaileysSocket<Msg>) => Promise<void>): Promise<void> {
|
|
229
|
+
const sock = this.socket;
|
|
230
|
+
try {
|
|
231
|
+
if (!sock || this.current.state !== "open") throw new ChannelSendFailure("NOT_CONNECTED", "the WhatsApp Web session is not open");
|
|
232
|
+
await call(sock);
|
|
233
|
+
} catch (error) {
|
|
234
|
+
this.config.onError?.(error, where);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async fetchHistory(contactId: string, anchor: HistoryAnchor, count: number, timeoutMs: number): Promise<WhatsAppWebHistoryMessage[]> {
|
|
239
|
+
const sock = this.socket;
|
|
240
|
+
if (!sock || this.current.state !== "open" || count <= 0) return [];
|
|
241
|
+
const key = { remoteJid: addressJid(contactId), id: anchor.externalId, fromMe: anchor.fromMe };
|
|
242
|
+
const call = () => sock.fetchMessageHistory(count, key, Math.floor(anchor.sentAt.getTime() / 1000));
|
|
243
|
+
return this.history.fetch(contactId, count, timeoutMs, call, (error) => this.config.onError?.(error, "history"));
|
|
172
244
|
}
|
|
173
245
|
|
|
174
246
|
downloadMedia(mediaId: string, options: { maxBytes: number; timeoutMs?: number }): Promise<ChannelMedia> {
|
|
@@ -190,6 +262,8 @@ class BaileysSession<Auth, Msg extends BaileysMessage> implements WhatsAppWebSes
|
|
|
190
262
|
const sock = this.socket;
|
|
191
263
|
this.socket = null;
|
|
192
264
|
this.account = null;
|
|
265
|
+
this.history.flush();
|
|
266
|
+
this.ownSends.reset();
|
|
193
267
|
return sock;
|
|
194
268
|
}
|
|
195
269
|
|
|
@@ -220,7 +294,16 @@ class BaileysSession<Auth, Msg extends BaileysMessage> implements WhatsAppWebSes
|
|
|
220
294
|
const account = this.linked(sock);
|
|
221
295
|
if (!account) return;
|
|
222
296
|
if (upsert.type === "notify") upsert.messages.forEach((message) => this.audio.remember(message));
|
|
223
|
-
|
|
297
|
+
const options = this.config.optOutKeywords ? { optOutKeywords: this.config.optOutKeywords } : {};
|
|
298
|
+
// One message at a time: a phone message clears an offer only for the replies that come after it.
|
|
299
|
+
const events = upsert.messages.flatMap((message) => {
|
|
300
|
+
const one = { type: upsert.type, messages: [message] };
|
|
301
|
+
return [...normalizeUpsert(account, one, options), ...this.ownSends.accept(normalizeSentElsewhere(account, one))];
|
|
302
|
+
});
|
|
303
|
+
this.deliver(applyChoices(this.choices, events));
|
|
304
|
+
});
|
|
305
|
+
sock.ev.on("messaging-history.set", (set) => {
|
|
306
|
+
if (sock === this.socket) this.history.answer(set);
|
|
224
307
|
});
|
|
225
308
|
sock.ev.on("messages.update", (updates) => {
|
|
226
309
|
const account = this.linked(sock);
|
|
@@ -273,6 +356,8 @@ class BaileysSession<Auth, Msg extends BaileysMessage> implements WhatsAppWebSes
|
|
|
273
356
|
private async onClose(code: number | null): Promise<void> {
|
|
274
357
|
this.socket = null;
|
|
275
358
|
this.account = null;
|
|
359
|
+
this.history.flush();
|
|
360
|
+
this.ownSends.reset();
|
|
276
361
|
if (this.stopping) return this.setStatus({ state: "stopped" });
|
|
277
362
|
if (code === DISCONNECT.loggedOut) {
|
|
278
363
|
await clearAuthState(this.config.authStore);
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The timer pair the session's deadlines run on: a history request's timeout and
|
|
3
|
+
* the longest an echo-suspect event is held. Injectable so a test fires them by
|
|
4
|
+
* hand; every timer set here is cleared once what it guards settles.
|
|
5
|
+
*/
|
|
6
|
+
export interface WhatsAppWebTimers {
|
|
7
|
+
setTimeout(run: () => void, ms: number): unknown;
|
|
8
|
+
clearTimeout(handle: unknown): void;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export const systemTimers: WhatsAppWebTimers = {
|
|
12
|
+
setTimeout: (run, ms) => {
|
|
13
|
+
const handle = setTimeout(run, ms);
|
|
14
|
+
// A pending hold or history deadline never keeps a short-lived host process alive.
|
|
15
|
+
(handle as { unref?: () => void }).unref?.();
|
|
16
|
+
return handle;
|
|
17
|
+
},
|
|
18
|
+
clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
|
19
|
+
};
|