@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
|
@@ -49,12 +49,25 @@ export interface BaileysConnectionUpdate {
|
|
|
49
49
|
qr?: string;
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
+
/** `messaging-history.set`: a history sync. `syncType` is `proto.HistorySync.HistorySyncType` (6 is ON_DEMAND), a number or its name. */
|
|
53
|
+
export interface BaileysHistorySet<Msg extends BaileysMessage = BaileysMessage> {
|
|
54
|
+
messages: Msg[];
|
|
55
|
+
syncType?: number | string | null;
|
|
56
|
+
/** The id `fetchMessageHistory` returned, on the answer to that request. */
|
|
57
|
+
peerDataRequestSessionId?: string | null;
|
|
58
|
+
isLatest?: boolean;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** `WAPresence` values this layer sends. */
|
|
62
|
+
export type BaileysPresence = "composing" | "paused";
|
|
63
|
+
|
|
52
64
|
/** The events this layer listens to, by Baileys' own names. */
|
|
53
65
|
export interface BaileysEventMap<Msg extends BaileysMessage = BaileysMessage> {
|
|
54
66
|
"connection.update": BaileysConnectionUpdate;
|
|
55
67
|
"creds.update": Record<string, unknown>;
|
|
56
68
|
"messages.upsert": { messages: Msg[]; type: "notify" | "append" | string };
|
|
57
69
|
"messages.update": BaileysMessageUpdate[];
|
|
70
|
+
"messaging-history.set": BaileysHistorySet<Msg>;
|
|
58
71
|
}
|
|
59
72
|
|
|
60
73
|
/** `SignalKeyStore`: keyed by category, then id. A null value deletes. */
|
|
@@ -78,6 +91,15 @@ export interface BaileysSocket<Msg extends BaileysMessage = BaileysMessage> {
|
|
|
78
91
|
/** The linked account, once open: `id` is `5511999999999:12@s.whatsapp.net`. */
|
|
79
92
|
user?: { id?: string | null | undefined } | null | undefined;
|
|
80
93
|
sendMessage(jid: string, content: { text: string }): Promise<Msg | undefined>;
|
|
94
|
+
/** `sendPresenceUpdate(type, toJid?)`: "digitando…" (`composing`) or its end (`paused`) in one chat. */
|
|
95
|
+
sendPresenceUpdate(type: BaileysPresence, toJid?: string): Promise<void>;
|
|
96
|
+
/** `readMessages(keys)`: marks those messages read (blue ticks). */
|
|
97
|
+
readMessages(keys: BaileysMessageKey[]): Promise<void>;
|
|
98
|
+
/**
|
|
99
|
+
* `fetchMessageHistory(count, oldestMsgKey, oldestMsgTimestamp)`: asks the phone for up to `count` messages
|
|
100
|
+
* before that one. Returns the request id; the answer arrives on `messaging-history.set`.
|
|
101
|
+
*/
|
|
102
|
+
fetchMessageHistory(count: number, oldestMsgKey: BaileysMessageKey, oldestMsgTimestamp: number): Promise<string>;
|
|
81
103
|
requestPairingCode(phoneNumber: string): Promise<string>;
|
|
82
104
|
logout(msg?: string): Promise<void>;
|
|
83
105
|
end(error: Error | undefined): Promise<void> | void;
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import type { InboundContent, NormalizedEvent, OutboundContent } from "../core/types";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The choices a personal account offered, remembered so the contact's typed
|
|
5
|
+
* answer reads as the tap it stands for.
|
|
6
|
+
*
|
|
7
|
+
* A personal account cannot send reply buttons or lists: `renderOutboundText`
|
|
8
|
+
* sends them as numbered lines, and the contact answers with text. An agent
|
|
9
|
+
* built for the Cloud adapter expects `INTERACTIVE { replyId, title }`. This
|
|
10
|
+
* module keeps the last choices offered to each contact (in memory, bounded,
|
|
11
|
+
* expiring) and turns an answer that is EXACTLY a listed number or EXACTLY a
|
|
12
|
+
* choice's title into that `INTERACTIVE`. Anything else stays `TEXT`.
|
|
13
|
+
*
|
|
14
|
+
* An offer maps only the first reply after it: any later message to that
|
|
15
|
+
* contact, from this session (plain text included) or from the owner's phone
|
|
16
|
+
* (`sent_elsewhere`), clears it, because the "1" that follows answers that.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** One offered choice: the id the agent gave it and the title the contact sees. */
|
|
20
|
+
export interface OfferedChoice {
|
|
21
|
+
replyId: string;
|
|
22
|
+
title: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The choices an outbound message offers, in the order {@link renderOutboundText} numbers them. Empty for plain text. */
|
|
26
|
+
export function choicesOf(content: OutboundContent): OfferedChoice[] {
|
|
27
|
+
if (content.kind === "TEXT") return [];
|
|
28
|
+
if (content.kind === "BUTTONS") return content.buttons.map((button) => ({ replyId: button.id, title: button.title }));
|
|
29
|
+
return content.sections.flatMap((section) => section.rows.map((row) => ({ replyId: row.id, title: row.title })));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Case, accents and spacing out of the way: `" Sim, Por Favor "` and `"sim, por favor"` are one title. */
|
|
33
|
+
export function foldTitle(value: string): string {
|
|
34
|
+
return value.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase().replace(/\s+/g, " ").trim();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** `"1"`, `"1."`, `" 2 "`, `"3)"` → the number; anything else (`"1 pizza"`, `"2x"`) → null. */
|
|
38
|
+
export function listedNumber(value: string): number | null {
|
|
39
|
+
// Trimmed and bounded first, so the pattern has one whitespace run and stays linear on any input.
|
|
40
|
+
const text = value.trim();
|
|
41
|
+
if (text.length > 8) return null;
|
|
42
|
+
const match = /^(\d{1,3})(?:\s*[.)])?$/.exec(text);
|
|
43
|
+
return match ? Number(match[1]) : null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
interface Offer {
|
|
47
|
+
choices: readonly OfferedChoice[];
|
|
48
|
+
folded: readonly string[];
|
|
49
|
+
at: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface ChoiceMemoryOptions {
|
|
53
|
+
/** How many contacts are remembered; the least recently offered goes first. Default 500. */
|
|
54
|
+
maxContacts?: number;
|
|
55
|
+
/** How long an offer stays answerable. Default 2 hours. */
|
|
56
|
+
ttlMs?: number;
|
|
57
|
+
now?(): Date;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export class ChoiceMemory {
|
|
61
|
+
private readonly offers = new Map<string, Offer>();
|
|
62
|
+
private readonly maxContacts: number;
|
|
63
|
+
private readonly ttlMs: number;
|
|
64
|
+
private readonly now: () => Date;
|
|
65
|
+
|
|
66
|
+
constructor(options: ChoiceMemoryOptions = {}) {
|
|
67
|
+
this.maxContacts = options.maxContacts ?? 500;
|
|
68
|
+
this.ttlMs = options.ttlMs ?? 2 * 60 * 60 * 1000;
|
|
69
|
+
this.now = options.now ?? (() => new Date());
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Remember what was just sent to a contact: its choices replace the earlier offer, and plain text clears it. */
|
|
73
|
+
offer(contactId: string, content: OutboundContent): void {
|
|
74
|
+
const choices = choicesOf(content);
|
|
75
|
+
this.offers.delete(contactId);
|
|
76
|
+
if (choices.length === 0) return;
|
|
77
|
+
this.offers.set(contactId, { choices, folded: choices.map((choice) => foldTitle(choice.title)), at: this.now().getTime() });
|
|
78
|
+
for (const oldest of this.offers.keys()) {
|
|
79
|
+
if (this.offers.size <= this.maxContacts) break;
|
|
80
|
+
this.offers.delete(oldest);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The choice a typed answer stands for, or null. A listed number wins over a
|
|
86
|
+
* title. A match uses the offer up (the answer was given); a miss, an
|
|
87
|
+
* expired offer or a contact never offered anything clears nothing.
|
|
88
|
+
*/
|
|
89
|
+
resolve(contactId: string, answer: string): OfferedChoice | null {
|
|
90
|
+
const offer = this.offers.get(contactId);
|
|
91
|
+
if (!offer) return null;
|
|
92
|
+
if (this.now().getTime() - offer.at > this.ttlMs) {
|
|
93
|
+
this.offers.delete(contactId);
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
const number = listedNumber(answer);
|
|
97
|
+
const index = number === null ? offer.folded.indexOf(foldTitle(answer)) : number - 1;
|
|
98
|
+
const choice = offer.choices[index];
|
|
99
|
+
if (!choice || index < 0) return null;
|
|
100
|
+
this.offers.delete(contactId);
|
|
101
|
+
return choice;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Something else was said to the contact since: the offer no longer maps their reply. */
|
|
105
|
+
forget(contactId: string): void {
|
|
106
|
+
this.offers.delete(contactId);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
get size(): number {
|
|
110
|
+
return this.offers.size;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The events, in socket order, with each TEXT answer that picks an offered choice read as `INTERACTIVE`. A
|
|
116
|
+
* `sent_elsewhere` clears its contact's offer. Every other event is returned as it came.
|
|
117
|
+
*/
|
|
118
|
+
export function applyChoices(memory: ChoiceMemory, events: readonly NormalizedEvent[]): NormalizedEvent[] {
|
|
119
|
+
return events.map((event) => {
|
|
120
|
+
if (event.type === "sent_elsewhere") memory.forget(event.contactId);
|
|
121
|
+
if (event.type !== "message" || event.content.kind !== "TEXT") return event;
|
|
122
|
+
const choice = memory.resolve(event.contactId, event.content.text);
|
|
123
|
+
const content: InboundContent | null = choice ? { kind: "INTERACTIVE", replyId: choice.replyId, title: choice.title } : null;
|
|
124
|
+
return content ? { ...event, content } : event;
|
|
125
|
+
});
|
|
126
|
+
}
|
|
@@ -64,10 +64,20 @@ function optOutEvent(value: Json, accountId: string): NormalizedEvent | null {
|
|
|
64
64
|
return contactId && at ? { type: "opt_out", accountId, contactId, at } : null;
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
function sentElsewhereEvent(value: Json, accountId: string): NormalizedEvent | null {
|
|
68
|
+
const contactId = str(value.contactId);
|
|
69
|
+
const externalId = str(value.externalId);
|
|
70
|
+
const sentAt = date(value.sentAt);
|
|
71
|
+
const body = content(value.content);
|
|
72
|
+
if (!contactId || !externalId || !sentAt || !body) return null;
|
|
73
|
+
return { type: "sent_elsewhere", accountId, contactId, externalId, sentAt, content: body };
|
|
74
|
+
}
|
|
75
|
+
|
|
67
76
|
const EVENTS: Readonly<Record<string, (value: Json, accountId: string) => NormalizedEvent | null>> = {
|
|
68
77
|
message: messageEvent,
|
|
69
78
|
status: statusEvent,
|
|
70
79
|
opt_out: optOutEvent,
|
|
80
|
+
sent_elsewhere: sentElsewhereEvent,
|
|
71
81
|
};
|
|
72
82
|
|
|
73
83
|
function event(value: unknown): NormalizedEvent | null {
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import type { InboundContent } from "../core/types";
|
|
2
|
+
import type { BaileysHistorySet, BaileysMessage } from "./baileys-port";
|
|
3
|
+
import { addressJid, contactAddress, contentOf, longNumber } from "./normalize";
|
|
4
|
+
import { systemTimers, type WhatsAppWebTimers } from "./timers";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* On-demand history: the messages of ONE chat, read from the phone and handed
|
|
8
|
+
* back to the caller, never to the inbox or the engine.
|
|
9
|
+
*
|
|
10
|
+
* `fetchMessageHistory` asks the phone for messages before an anchor and
|
|
11
|
+
* returns only a request id; the answer arrives later on `messaging-history.set`
|
|
12
|
+
* (which can even come BEFORE the call resolves). This module holds the
|
|
13
|
+
* pending requests, matches an answer to the chat it is for, and reduces each
|
|
14
|
+
* message to what a model may read: text, or a placeholder kind for media.
|
|
15
|
+
* Nothing here keeps a message after its request settles.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** The message a history read starts before: the inbound message that began the turn. */
|
|
19
|
+
export interface HistoryAnchor {
|
|
20
|
+
externalId: string;
|
|
21
|
+
sentAt: Date;
|
|
22
|
+
fromMe: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* One message of a chat's history. `kind` is `text`, `interactive`, `audio`, or the channel's own type for
|
|
27
|
+
* anything else (`image`, `sticker`, `video`): text is carried only for `text` and `interactive`.
|
|
28
|
+
*/
|
|
29
|
+
export interface WhatsAppWebHistoryMessage {
|
|
30
|
+
externalId: string;
|
|
31
|
+
fromMe: boolean;
|
|
32
|
+
sentAt: Date;
|
|
33
|
+
text: string | null;
|
|
34
|
+
kind: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** `proto.HistorySync.HistorySyncType.ON_DEMAND`. */
|
|
38
|
+
const ON_DEMAND = 6;
|
|
39
|
+
|
|
40
|
+
const isOnDemand = (syncType: unknown): boolean => syncType === ON_DEMAND || syncType === "ON_DEMAND";
|
|
41
|
+
|
|
42
|
+
/** What a content keeps: its text (or none) and the placeholder `kind`. Media keeps neither bytes nor keys. */
|
|
43
|
+
function kept(content: InboundContent): { text: string | null; kind: string } {
|
|
44
|
+
switch (content.kind) {
|
|
45
|
+
case "TEXT":
|
|
46
|
+
return { text: content.text, kind: "text" };
|
|
47
|
+
case "INTERACTIVE":
|
|
48
|
+
return { text: content.title || null, kind: "interactive" };
|
|
49
|
+
case "AUDIO":
|
|
50
|
+
return { text: null, kind: "audio" };
|
|
51
|
+
default:
|
|
52
|
+
return { text: null, kind: content.channelType.toLowerCase() };
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** One raw message → its text-only form, or null for a protocol message, a malformed one or one with no id or time. */
|
|
57
|
+
export function historyMessage(message: BaileysMessage): WhatsAppWebHistoryMessage | null {
|
|
58
|
+
const id = message?.key?.id;
|
|
59
|
+
const seconds = longNumber(message?.messageTimestamp);
|
|
60
|
+
const content = contentOf(message?.message);
|
|
61
|
+
if (typeof id !== "string" || id === "" || seconds === null || !content) return null;
|
|
62
|
+
return { externalId: id, fromMe: message.key.fromMe === true, sentAt: new Date(seconds * 1000), ...kept(content) };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Whether a message key belongs to the contact's chat, by either of the chat's addresses (a LID or its phone number). */
|
|
66
|
+
const inChat = (contactId: string, key: BaileysMessage["key"]): boolean =>
|
|
67
|
+
contactAddress(key) === contactId || [key.remoteJid, key.remoteJidAlt].includes(addressJid(contactId));
|
|
68
|
+
|
|
69
|
+
/** The messages of one contact's chat out of a history batch: oldest first, each id once, the newest `count`. */
|
|
70
|
+
export function chatHistory(contactId: string, messages: readonly BaileysMessage[], count: number): WhatsAppWebHistoryMessage[] {
|
|
71
|
+
const seen = new Set<string>();
|
|
72
|
+
const found: WhatsAppWebHistoryMessage[] = [];
|
|
73
|
+
for (const raw of messages) {
|
|
74
|
+
if (!raw?.key || !inChat(contactId, raw.key)) continue;
|
|
75
|
+
const message = historyMessage(raw);
|
|
76
|
+
if (!message || seen.has(message.externalId)) continue;
|
|
77
|
+
seen.add(message.externalId);
|
|
78
|
+
found.push(message);
|
|
79
|
+
}
|
|
80
|
+
found.sort((a, b) => a.sentAt.getTime() - b.sentAt.getTime());
|
|
81
|
+
return count > 0 ? found.slice(-count) : [];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
interface Pending {
|
|
85
|
+
contactId: string;
|
|
86
|
+
count: number;
|
|
87
|
+
requestId: string | null;
|
|
88
|
+
settle(messages: WhatsAppWebHistoryMessage[]): void;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** A request waiting for its answer. */
|
|
92
|
+
export interface HistoryWait {
|
|
93
|
+
/** The messages, or `[]` on a timeout, an abandoned request or a closed socket. Never rejects. */
|
|
94
|
+
result: Promise<WhatsAppWebHistoryMessage[]>;
|
|
95
|
+
/** The id `fetchMessageHistory` returned: from then on an answer naming another id is not this one's. */
|
|
96
|
+
setRequestId(id: string): void;
|
|
97
|
+
/** Settle with nothing: the call that was to fetch it failed. */
|
|
98
|
+
abandon(): void;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export class HistoryRequests {
|
|
102
|
+
/** Oldest first: an answer that names no request goes to the oldest one for its chat. */
|
|
103
|
+
private readonly pending = new Set<Pending>();
|
|
104
|
+
|
|
105
|
+
constructor(private readonly timers: WhatsAppWebTimers = systemTimers) {}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Ask, and wait for the answer without waiting on the call: `call` (which returns the request id) may never
|
|
109
|
+
* settle, and the deadline still ends the wait. A rejected call abandons the request and goes to `onError`.
|
|
110
|
+
*/
|
|
111
|
+
fetch(contactId: string, count: number, timeoutMs: number, call: () => Promise<string>, onError: (error: unknown) => void): Promise<WhatsAppWebHistoryMessage[]> {
|
|
112
|
+
// Registered BEFORE the call: the phone's answer can beat the call's own return.
|
|
113
|
+
const wait = this.wait(contactId, count, timeoutMs);
|
|
114
|
+
Promise.resolve()
|
|
115
|
+
.then(call)
|
|
116
|
+
.then(wait.setRequestId, (error: unknown) => {
|
|
117
|
+
wait.abandon();
|
|
118
|
+
// A throwing host callback must not become an unhandled rejection of this detached chain.
|
|
119
|
+
try {
|
|
120
|
+
onError(error);
|
|
121
|
+
} catch {
|
|
122
|
+
/* the host's own error */
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
return wait.result;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Register a request BEFORE the call is made: the answer may beat the call's own return. The deadline is cleared once it settles. */
|
|
129
|
+
wait(contactId: string, count: number, timeoutMs: number): HistoryWait {
|
|
130
|
+
let entry!: Pending;
|
|
131
|
+
let timer: unknown = null;
|
|
132
|
+
const result = new Promise<WhatsAppWebHistoryMessage[]>((resolve) => {
|
|
133
|
+
entry = {
|
|
134
|
+
contactId,
|
|
135
|
+
count,
|
|
136
|
+
requestId: null,
|
|
137
|
+
settle: (messages) => {
|
|
138
|
+
if (!this.pending.delete(entry)) return;
|
|
139
|
+
this.timers.clearTimeout(timer);
|
|
140
|
+
resolve(messages);
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
});
|
|
144
|
+
this.pending.add(entry);
|
|
145
|
+
timer = this.timers.setTimeout(() => entry.settle([]), timeoutMs);
|
|
146
|
+
return { result, setRequestId: (id) => void (entry.requestId = id), abandon: () => entry.settle([]) };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* A `messaging-history.set`. An answer naming a request id settles THAT request; one naming an id nobody holds
|
|
151
|
+
* yet, or none, settles the oldest request for its chat whose id it cannot contradict. A late answer is dropped.
|
|
152
|
+
*/
|
|
153
|
+
answer(set: BaileysHistorySet): void {
|
|
154
|
+
if (!isOnDemand(set.syncType) || !Array.isArray(set.messages)) return;
|
|
155
|
+
const named = typeof set.peerDataRequestSessionId === "string" ? set.peerDataRequestSessionId : null;
|
|
156
|
+
const entries = [...this.pending];
|
|
157
|
+
const exact = named ? entries.find((entry) => entry.requestId === named) : undefined;
|
|
158
|
+
const candidates = exact ? [exact] : entries.filter((entry) => !named || entry.requestId === null);
|
|
159
|
+
for (const entry of candidates) {
|
|
160
|
+
const messages = chatHistory(entry.contactId, set.messages, entry.count);
|
|
161
|
+
if (messages.length === 0) continue;
|
|
162
|
+
entry.settle(messages);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** The socket closed: nothing more will come. */
|
|
168
|
+
flush(): void {
|
|
169
|
+
for (const entry of [...this.pending]) entry.settle([]);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
@@ -21,12 +21,26 @@ export {
|
|
|
21
21
|
} from "./session";
|
|
22
22
|
export { clearAuthState, createMemoryAuthStateStore, loadAuthState, type AuthStateStore } from "./auth-state";
|
|
23
23
|
export { ENVELOPE_FORMAT, encodeEnvelope, parseEnvelope } from "./envelope";
|
|
24
|
-
export {
|
|
24
|
+
export {
|
|
25
|
+
addressJid,
|
|
26
|
+
contactAddress,
|
|
27
|
+
contentOf,
|
|
28
|
+
normalizeSentElsewhere,
|
|
29
|
+
normalizeUpdates,
|
|
30
|
+
normalizeUpsert,
|
|
31
|
+
receiptOf,
|
|
32
|
+
type NormalizeOptions,
|
|
33
|
+
} from "./normalize";
|
|
34
|
+
export { ChoiceMemory, type ChoiceMemoryOptions, type OfferedChoice } from "./choices";
|
|
35
|
+
export type { HistoryAnchor, WhatsAppWebHistoryMessage } from "./history";
|
|
36
|
+
export type { WhatsAppWebTimers } from "./timers";
|
|
25
37
|
export {
|
|
26
38
|
DISCONNECT,
|
|
27
39
|
disconnectCode,
|
|
28
40
|
type BaileysAuthState,
|
|
29
41
|
type BaileysConnectionUpdate,
|
|
42
|
+
type BaileysHistorySet,
|
|
43
|
+
type BaileysPresence,
|
|
30
44
|
type BaileysLogger,
|
|
31
45
|
type BaileysMessage,
|
|
32
46
|
type BaileysMessageKey,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { InboundContent, NormalizedEvent, ReceiptStatus, StatusEvent } from "../core/types";
|
|
1
|
+
import type { InboundContent, NormalizedEvent, ReceiptStatus, SentElsewhereEvent, StatusEvent } from "../core/types";
|
|
2
2
|
import { DEFAULT_OPT_OUT_KEYWORDS, isOptOutText } from "../whatsapp/opt-out";
|
|
3
3
|
import type { BaileysMessage, BaileysMessageKey, BaileysMessageUpdate, LongLike } from "./baileys-port";
|
|
4
4
|
|
|
@@ -11,9 +11,11 @@ import type { BaileysMessage, BaileysMessageKey, BaileysMessageUpdate, LongLike
|
|
|
11
11
|
* left out, on purpose:
|
|
12
12
|
* - groups, broadcast lists, Status and channels (`@g.us`, `@broadcast`,
|
|
13
13
|
* `@newsletter`): the engine's conversation is one contact;
|
|
14
|
-
* - messages the account sent itself (`fromMe`)
|
|
15
|
-
*
|
|
16
|
-
*
|
|
14
|
+
* - messages the account sent itself (`fromMe`) are NOT inbound: `normalizeUpsert`
|
|
15
|
+
* drops them, and `normalizeSentElsewhere` reads them as a separate event (the
|
|
16
|
+
* session drops the echo of its own sends before it hands them on);
|
|
17
|
+
* - history sync (`messages.upsert` of type `append`, `messaging-history.set`):
|
|
18
|
+
* only live messages reach the inbox; on-demand history never leaves the session;
|
|
17
19
|
* - protocol messages (a deletion, an edit, a key distribution).
|
|
18
20
|
*/
|
|
19
21
|
|
|
@@ -53,6 +55,15 @@ export function addressJid(address: string): string {
|
|
|
53
55
|
return `${digits}${PN_SUFFIX}`;
|
|
54
56
|
}
|
|
55
57
|
|
|
58
|
+
/**
|
|
59
|
+
* The address a contact's reply to a send will carry, keyed as {@link contactAddress} keys an inbound message:
|
|
60
|
+
* `+55 11 98765-4321`, `5511987654321` and `5511987654321:12@s.whatsapp.net` are all `5511987654321`, and a LID
|
|
61
|
+
* the socket reports beside its phone-number JID (`sentKey.remoteJidAlt`) is that number. Null when it is not one person.
|
|
62
|
+
*/
|
|
63
|
+
export function replyAddress(to: string, sentKey?: BaileysMessageKey | null): string | null {
|
|
64
|
+
return contactAddress({ remoteJid: addressJid(to), remoteJidAlt: sentKey?.remoteJidAlt ?? null });
|
|
65
|
+
}
|
|
66
|
+
|
|
56
67
|
/** A protobuf Long (a timestamp in seconds, a byte length) as a positive number, or null. */
|
|
57
68
|
export function longNumber(value: LongLike): number | null {
|
|
58
69
|
if (typeof value === "number") return Number.isFinite(value) && value > 0 ? value : null;
|
|
@@ -143,6 +154,35 @@ export function normalizeUpsert(
|
|
|
143
154
|
return upsert.messages.map((message) => inboundEvent(accountId, message, keywords)).filter((event): event is NormalizedEvent => event !== null);
|
|
144
155
|
}
|
|
145
156
|
|
|
157
|
+
/** What a message the account sent from another device carried: its text, or `OTHER` for anything else (never media keys). */
|
|
158
|
+
function sentContent(raw: unknown): InboundContent | null {
|
|
159
|
+
const content = contentOf(raw);
|
|
160
|
+
if (!content) return null;
|
|
161
|
+
if (content.kind === "AUDIO") return { kind: "OTHER", channelType: "audio" };
|
|
162
|
+
return content.kind === "INTERACTIVE" ? { kind: "TEXT", text: content.title } : content;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** One message → the event for a message the account sent itself, or null when it is not one a person sent to one contact. */
|
|
166
|
+
function sentElsewhereEvent(accountId: string, message: BaileysMessage): SentElsewhereEvent | null {
|
|
167
|
+
if (!isObject(message) || !isObject(message.key) || !message.key.fromMe) return null;
|
|
168
|
+
const id = text(message.key.id);
|
|
169
|
+
const contactId = contactAddress(message.key);
|
|
170
|
+
const seconds = longNumber(message.messageTimestamp);
|
|
171
|
+
const content = sentContent(message.message);
|
|
172
|
+
if (!id || !contactId || seconds === null || !content) return null;
|
|
173
|
+
return { type: "sent_elsewhere", accountId, contactId, externalId: id, sentAt: new Date(seconds * 1000), content };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* One live `messages.upsert` → events for the messages the account sent itself
|
|
178
|
+
* (from another device, or the echo of one of this session's own sends: the
|
|
179
|
+
* CALLER tells them apart by id). `accountId` is the linked account's digits.
|
|
180
|
+
*/
|
|
181
|
+
export function normalizeSentElsewhere(accountId: string, upsert: { messages: readonly BaileysMessage[]; type: string }): SentElsewhereEvent[] {
|
|
182
|
+
if (upsert.type !== "notify") return [];
|
|
183
|
+
return upsert.messages.map((message) => sentElsewhereEvent(accountId, message)).filter((event): event is SentElsewhereEvent => event !== null);
|
|
184
|
+
}
|
|
185
|
+
|
|
146
186
|
/** `proto.WebMessageInfo.Status` → a receipt. PENDING (1) and unknown values are not receipts. */
|
|
147
187
|
export function receiptOf(status: unknown): ReceiptStatus | null {
|
|
148
188
|
switch (status) {
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { SentElsewhereEvent } from "../core/types";
|
|
2
|
+
import { systemTimers, type WhatsAppWebTimers } from "./timers";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Tells a message the account sent from ANOTHER device from the echo of a
|
|
6
|
+
* send this session made.
|
|
7
|
+
*
|
|
8
|
+
* A linked device sees every message of the account on `messages.upsert`,
|
|
9
|
+
* its own sends included, and the echo can arrive BEFORE `sendMessage`
|
|
10
|
+
* resolves with the id. So: the ids of finished sends are remembered (bounded),
|
|
11
|
+
* and a `fromMe` event that arrives while sends are in flight is HELD, stamped
|
|
12
|
+
* with THOSE sends, and judged against the ids once they settle (a send that
|
|
13
|
+
* starts later never holds it). The engine already recorded its own sends; an
|
|
14
|
+
* echo reaching the host as "the owner replied from the phone" would pause the
|
|
15
|
+
* agent on its own reply.
|
|
16
|
+
*
|
|
17
|
+
* Bounded: an event is held at most `maxHoldMs` (a send that never settles
|
|
18
|
+
* cannot pin it), at most `maxHeld` events are held (the oldest is judged and
|
|
19
|
+
* released first), and `reset` (the socket closed) releases everything. A
|
|
20
|
+
* released event is judged against the ids known then. Released events reach
|
|
21
|
+
* the host later than events that arrived after them.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
export interface OwnSendsOptions {
|
|
25
|
+
timers?: WhatsAppWebTimers;
|
|
26
|
+
/** The longest an event waits for its sends. Default 30 s. */
|
|
27
|
+
maxHoldMs?: number;
|
|
28
|
+
/** How many events may be held at once. Default 200. */
|
|
29
|
+
maxHeld?: number;
|
|
30
|
+
/** How many sent ids are remembered. Default 1000. */
|
|
31
|
+
remembered?: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface Held {
|
|
35
|
+
event: SentElsewhereEvent;
|
|
36
|
+
/** The sends in flight when it arrived that have not settled yet. */
|
|
37
|
+
waitingOn: Set<number>;
|
|
38
|
+
timer: unknown;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export class OwnSends {
|
|
42
|
+
private readonly ids = new Set<string>();
|
|
43
|
+
private readonly inFlight = new Set<number>();
|
|
44
|
+
private sequence = 0;
|
|
45
|
+
private held: Held[] = [];
|
|
46
|
+
private readonly timers: WhatsAppWebTimers;
|
|
47
|
+
private readonly maxHoldMs: number;
|
|
48
|
+
private readonly maxHeld: number;
|
|
49
|
+
private readonly remembered: number;
|
|
50
|
+
|
|
51
|
+
/** `release` gets the held events that turned out to be from another device, when they are judged. */
|
|
52
|
+
constructor(
|
|
53
|
+
private readonly release: (events: SentElsewhereEvent[]) => void,
|
|
54
|
+
options: OwnSendsOptions = {},
|
|
55
|
+
) {
|
|
56
|
+
this.timers = options.timers ?? systemTimers;
|
|
57
|
+
this.maxHoldMs = options.maxHoldMs ?? 30_000;
|
|
58
|
+
this.maxHeld = options.maxHeld ?? 200;
|
|
59
|
+
this.remembered = options.remembered ?? 1000;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Run one send. Its id is remembered whether the caller or the echo gets there first. */
|
|
63
|
+
async track<T extends { externalId: string }>(run: () => Promise<T>): Promise<T> {
|
|
64
|
+
this.sequence += 1;
|
|
65
|
+
const send = this.sequence;
|
|
66
|
+
this.inFlight.add(send);
|
|
67
|
+
let id: string | null = null;
|
|
68
|
+
try {
|
|
69
|
+
const result = await run();
|
|
70
|
+
id = result.externalId;
|
|
71
|
+
return result;
|
|
72
|
+
} finally {
|
|
73
|
+
this.inFlight.delete(send);
|
|
74
|
+
if (id) this.remember(id);
|
|
75
|
+
for (const entry of this.held) entry.waitingOn.delete(send);
|
|
76
|
+
this.releaseWhere((entry) => entry.waitingOn.size === 0);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The events to hand on NOW: not our own, and none while a send is in flight (those are held). */
|
|
81
|
+
accept(events: readonly SentElsewhereEvent[]): SentElsewhereEvent[] {
|
|
82
|
+
if (this.inFlight.size === 0) return this.judge(events);
|
|
83
|
+
for (const event of events) this.hold(event);
|
|
84
|
+
const excess = new Set(this.held.slice(0, Math.max(0, this.held.length - this.maxHeld)));
|
|
85
|
+
this.releaseWhere((entry) => excess.has(entry));
|
|
86
|
+
return [];
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The socket closed: release everything held, and hold nothing for the sends that were in flight. */
|
|
90
|
+
reset(): void {
|
|
91
|
+
this.inFlight.clear();
|
|
92
|
+
this.releaseWhere(() => true);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
private hold(event: SentElsewhereEvent): void {
|
|
96
|
+
const entry: Held = { event, waitingOn: new Set(this.inFlight), timer: null };
|
|
97
|
+
entry.timer = this.timers.setTimeout(() => this.releaseWhere((held) => held === entry), this.maxHoldMs);
|
|
98
|
+
this.held.push(entry);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Release the held entries `done` picks, in the order they arrived, judged against the ids known now. */
|
|
102
|
+
private releaseWhere(done: (entry: Held) => boolean): void {
|
|
103
|
+
const out: Held[] = [];
|
|
104
|
+
const kept: Held[] = [];
|
|
105
|
+
for (const entry of this.held) (done(entry) ? out : kept).push(entry);
|
|
106
|
+
if (out.length === 0) return;
|
|
107
|
+
this.held = kept;
|
|
108
|
+
for (const entry of out) this.timers.clearTimeout(entry.timer);
|
|
109
|
+
const events = this.judge(out.map((entry) => entry.event));
|
|
110
|
+
if (events.length > 0) this.release(events);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
private judge(events: readonly SentElsewhereEvent[]): SentElsewhereEvent[] {
|
|
114
|
+
return events.filter((event) => !this.ids.has(event.externalId));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
private remember(id: string): void {
|
|
118
|
+
this.ids.add(id);
|
|
119
|
+
for (const oldest of this.ids) {
|
|
120
|
+
if (this.ids.size <= this.remembered) break;
|
|
121
|
+
this.ids.delete(oldest);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|