@oxidezap/baileyrs 0.3.7 → 0.3.8
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 +48 -8
- package/lib/Bridge/history-sync-wire.d.ts +2 -2
- package/lib/Bridge/history-sync-wire.js +4 -4
- package/lib/Bridge/schema.js +7 -1
- package/lib/Bridge/types.d.ts +7 -1
- package/lib/Compatibility/auth-state.d.ts +30 -0
- package/lib/Compatibility/auth-state.js +96 -0
- package/lib/Compatibility/encode-proto-core.d.ts +31 -0
- package/lib/Compatibility/encode-proto-core.js +51 -0
- package/lib/Compatibility/encode-proto.d.ts +0 -29
- package/lib/Compatibility/encode-proto.js +3 -50
- package/lib/Compatibility/host-auth-state.d.ts +6 -0
- package/lib/Compatibility/host-auth-state.js +162 -0
- package/lib/Compatibility/internal/auth-state.d.ts +3 -7
- package/lib/Compatibility/internal/auth-state.js +34 -1
- package/lib/Compatibility/internal/host-auth-state.d.ts +4 -0
- package/lib/Compatibility/internal/host-auth-state.js +14 -0
- package/lib/Compatibility/legacy-store/device.js +5 -5
- package/lib/Compatibility/message-ids.d.ts +17 -0
- package/lib/Compatibility/message-ids.js +47 -0
- package/lib/Compatibility/message-relay.d.ts +2 -2
- package/lib/Compatibility/message-relay.js +4 -4
- package/lib/Compatibility/proto-runtime.js +33 -11
- package/lib/Compatibility/socket-results.d.ts +1 -1
- package/lib/Compatibility/tagged-message-waiter.d.ts +5 -2
- package/lib/Compatibility/tagged-message-waiter.js +5 -5
- package/lib/Compatibility/usync/adapter.d.ts +1 -1
- package/lib/Compatibility/websocket-client.d.ts +11 -3
- package/lib/Compatibility/websocket-client.js +84 -11
- package/lib/Defaults/index.d.ts +8 -8
- package/lib/Defaults/index.js +8 -8
- package/lib/Media/content.d.ts +28 -0
- package/lib/Media/content.js +129 -0
- package/lib/Media/core.d.ts +34 -0
- package/lib/Media/core.js +120 -0
- package/lib/Media/mutations.d.ts +24 -0
- package/lib/Media/mutations.js +38 -0
- package/lib/Runtime/aes-gcm.d.ts +4 -0
- package/lib/Runtime/aes-gcm.js +11 -0
- package/lib/Runtime/bridge.d.ts +44 -0
- package/lib/Runtime/bridge.js +76 -0
- package/lib/Runtime/buffer.d.ts +9 -0
- package/lib/Runtime/buffer.js +22 -0
- package/lib/Runtime/bytes.d.ts +61 -0
- package/lib/Runtime/bytes.js +270 -0
- package/lib/Runtime/host.d.ts +22 -0
- package/lib/Runtime/host.js +43 -0
- package/lib/Runtime/long.d.ts +33 -0
- package/lib/Runtime/long.js +64 -0
- package/lib/Runtime/node-media-processors.d.ts +4 -0
- package/lib/Runtime/node-media-processors.js +29 -0
- package/lib/Runtime/node-media.d.ts +28 -0
- package/lib/Runtime/node-media.js +115 -0
- package/lib/Runtime/node.d.ts +14 -0
- package/lib/Runtime/node.js +81 -0
- package/lib/Runtime/paths.d.ts +4 -0
- package/lib/Runtime/paths.js +7 -0
- package/lib/Runtime/stream.d.ts +11 -0
- package/lib/Runtime/stream.js +25 -0
- package/lib/Runtime/types.d.ts +98 -0
- package/lib/Runtime/types.js +13 -0
- package/lib/Socket/core.d.ts +312 -0
- package/lib/Socket/core.js +1122 -0
- package/lib/Socket/events-core.d.ts +75 -0
- package/lib/Socket/events-core.js +1058 -0
- package/lib/Socket/events.d.ts +1 -63
- package/lib/Socket/events.js +4 -1047
- package/lib/Socket/groups.js +4 -3
- package/lib/Socket/index.d.ts +521 -103
- package/lib/Socket/index.js +10 -1007
- package/lib/Socket/messages-core.d.ts +41 -0
- package/lib/Socket/messages-core.js +270 -0
- package/lib/Socket/messages.d.ts +9 -36
- package/lib/Socket/messages.js +3 -260
- package/lib/Socket/newsletter.js +3 -3
- package/lib/Socket/profile.js +1 -1
- package/lib/Socket/terminal-close-reporter.d.ts +2 -0
- package/lib/Socket/terminal-close-reporter.js +3 -3
- package/lib/Socket/transport.d.ts +2 -0
- package/lib/Socket/transport.js +16 -1
- package/lib/Socket/types.d.ts +2 -0
- package/lib/Types/Auth.d.ts +11 -0
- package/lib/Types/Message.d.ts +1 -1
- package/lib/Types/Socket.d.ts +2 -2
- package/lib/Types/index.d.ts +6 -1
- package/lib/Utils/browser-utils.d.ts +4 -0
- package/lib/Utils/browser-utils.js +53 -2
- package/lib/Utils/crypto.d.ts +1 -0
- package/lib/Utils/crypto.js +1 -0
- package/lib/Utils/event-buffer.d.ts +6 -1
- package/lib/Utils/event-buffer.js +28 -27
- package/lib/Utils/link-preview.d.ts +4 -3
- package/lib/Utils/logger.d.ts +3 -0
- package/lib/Utils/logger.js +35 -6
- package/lib/Utils/messages-core.d.ts +174 -0
- package/lib/Utils/messages-core.js +1042 -0
- package/lib/Utils/messages-media-core.d.ts +73 -0
- package/lib/Utils/messages-media-core.js +319 -0
- package/lib/Utils/messages-media.d.ts +1 -72
- package/lib/Utils/messages-media.js +9 -358
- package/lib/Utils/messages.d.ts +1 -166
- package/lib/Utils/messages.js +7 -1040
- package/lib/Utils/optional-peer.js +14 -5
- package/lib/Utils/process-history-message-core.d.ts +36 -0
- package/lib/Utils/process-history-message-core.js +187 -0
- package/lib/Utils/process-history-message.d.ts +5 -43
- package/lib/Utils/process-history-message.js +11 -197
- package/lib/Utils/process-message-core.d.ts +29 -0
- package/lib/Utils/process-message-core.js +112 -0
- package/lib/Utils/process-message.d.ts +4 -24
- package/lib/Utils/process-message.js +6 -111
- package/lib/WABinary/generic-utils.js +7 -5
- package/lib/host-shared.d.ts +74 -0
- package/lib/host-shared.js +15 -0
- package/lib/host-socket-operations.d.ts +3 -0
- package/lib/host-socket-operations.js +2 -0
- package/lib/host-surface.d.ts +21 -0
- package/lib/host-surface.js +35 -0
- package/lib/host-types.d.ts +356 -0
- package/lib/host-types.js +2 -0
- package/lib/host.d.ts +33 -0
- package/lib/host.js +31 -0
- package/lib/node-surface.d.ts +9 -0
- package/lib/node-surface.js +15 -0
- package/lib/surface.d.ts +5 -0
- package/lib/surface.js +6 -0
- package/lib/wasm.d.ts +27 -0
- package/lib/wasm.js +27 -0
- package/package.json +18 -6
|
@@ -0,0 +1,1058 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical → Baileys event dispatcher.
|
|
3
|
+
*
|
|
4
|
+
* `adaptBridgeEvent` (Bridge/schema.ts) yields a `CanonicalEvent`
|
|
5
|
+
* discriminated union; `DISPATCHERS` is a `{ [K in CanonicalEvent['type']]: … }`
|
|
6
|
+
* mapped type so TS forces a handler per variant — a missing handler
|
|
7
|
+
* is a compile error.
|
|
8
|
+
*/
|
|
9
|
+
import DefaultLong from 'long';
|
|
10
|
+
import { BinaryReader as DefaultBinaryReader, decodeMessageWireBatch as defaultDecodeMessageWireBatch, decodeReceiptWireBatch as defaultDecodeReceiptWireBatch, decodeServerAckWireBatch as defaultDecodeServerAckWireBatch } from '@oxidezap/whatsapp-rust-bridge/host';
|
|
11
|
+
import { adaptBridgeEvent, adaptBridgeMessageWire } from '../Bridge/index.js';
|
|
12
|
+
import { decodeHistorySyncWireBatch } from '../Bridge/history-sync-wire.js';
|
|
13
|
+
import { bridgeGroupMetadataToBaileys } from '../Compatibility/group-metadata.js';
|
|
14
|
+
import { DEF_CALLBACK_PREFIX, DEF_TAG_PREFIX, HISTORY_SYNC_PAUSED_TIMEOUT_MS } from '../Defaults/index.js';
|
|
15
|
+
import { DisconnectReason, WAMessageStatus, WAProto } from '../Types/index.js';
|
|
16
|
+
import { LabelAssociationType } from '../Types/LabelAssociation.js';
|
|
17
|
+
import { Boom } from '../Utils/boom.js';
|
|
18
|
+
import { toNumber, unrefTimer } from '../Runtime/bytes.js';
|
|
19
|
+
import { CONVERSATION_HISTORY_SYNC_TYPES } from '../Utils/process-history-message-core.js';
|
|
20
|
+
import { isJidBroadcast, isJidGroup } from '../WABinary/jid-utils.js';
|
|
21
|
+
import { buildGroupCreateStubMessage, buildGroupJoinRequestEvents, buildGroupNotificationChatUpdates, buildGroupNotificationDomainEvent, buildGroupNotificationStubMessages } from '../Compatibility/group-notifications.js';
|
|
22
|
+
import { emitMessageUpsert } from '../Compatibility/message-upsert.js';
|
|
23
|
+
import { extractMessageCappingPayload } from './message-capping.js';
|
|
24
|
+
import { mapReachoutTimelock } from './reachout.js';
|
|
25
|
+
import { isReconnectableConnectFailure, mapConnectFailureToDisconnect } from './terminal-close.js';
|
|
26
|
+
const CANONICAL_MESSAGE_EVENT = 'message';
|
|
27
|
+
const MESSAGE_UPSERT_APPEND = 'append';
|
|
28
|
+
const MESSAGE_UPSERT_NOTIFY = 'notify';
|
|
29
|
+
/** Emit CB: pattern events on the ws EventEmitter for retrocompat. */
|
|
30
|
+
const emitCBEvents = (ctx, node) => {
|
|
31
|
+
const { ws } = ctx;
|
|
32
|
+
const l0 = node.tag;
|
|
33
|
+
const l1 = node.attrs || {};
|
|
34
|
+
const l2 = Array.isArray(node.content) ? node.content[0]?.tag : '';
|
|
35
|
+
const id = l1.id;
|
|
36
|
+
if (id)
|
|
37
|
+
ws.emit(`${DEF_TAG_PREFIX}${id}`, node);
|
|
38
|
+
// `for..in` over the attrs rather than `Object.entries`: this runs for every
|
|
39
|
+
// stanza the socket sees and the pair array it built was thrown away
|
|
40
|
+
// immediately. `Object.entries` was own-only by construction though, and
|
|
41
|
+
// `BinaryNode` is public, so the walk is guarded rather than trusting every
|
|
42
|
+
// caller to hand over an attrs map with a bare prototype. An inherited
|
|
43
|
+
// enumerable would otherwise fire CB events for an attr the stanza does not
|
|
44
|
+
// carry; the check costs nothing next to the emits below.
|
|
45
|
+
for (const key in l1) {
|
|
46
|
+
if (!Object.hasOwn(l1, key))
|
|
47
|
+
continue;
|
|
48
|
+
const val = l1[key];
|
|
49
|
+
if (l2)
|
|
50
|
+
ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${val},${l2}`, node);
|
|
51
|
+
ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}:${val}`, node);
|
|
52
|
+
// Bare-key pattern (no value): upstream `socket.ts:610` emits this
|
|
53
|
+
// so consumers wiring `ws.on('CB:iq,id', …)` (any id) catch every
|
|
54
|
+
// stanza carrying that attr. Missing here meant id-pattern matchers
|
|
55
|
+
// silently never fired.
|
|
56
|
+
ws.emit(`${DEF_CALLBACK_PREFIX}${l0},${key}`, node);
|
|
57
|
+
}
|
|
58
|
+
if (l2)
|
|
59
|
+
ws.emit(`${DEF_CALLBACK_PREFIX}${l0},,${l2}`, node);
|
|
60
|
+
ws.emit(`${DEF_CALLBACK_PREFIX}${l0}`, node);
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Build a Baileys `WAMessage` from a canonical message.
|
|
64
|
+
*
|
|
65
|
+
* Lives at this layer (not in the adapter) because `WAProto.WebMessageInfo`
|
|
66
|
+
* is the Baileys upstream contract — it's the OUTBOUND end of the
|
|
67
|
+
* bridge → canonical → Baileys pipeline. Adapters never reach for the proto.
|
|
68
|
+
*/
|
|
69
|
+
const canonicalMessageToWAMessage = (m, Long) => {
|
|
70
|
+
// Direct construction instead of a `WebMessageInfo.fromObject` envelope:
|
|
71
|
+
// every input is already in its wire-correct runtime type, so the schema
|
|
72
|
+
// walk would only re-derive them field by field on the hottest path. `new`
|
|
73
|
+
// keeps protobufjs parity (instanceof, prototype defaults and own
|
|
74
|
+
// repeated/map fields), and `Message.fromObject` still normalizes the
|
|
75
|
+
// payload while short-circuiting the already-decoded runtime instances.
|
|
76
|
+
const key = new WAProto.MessageKey();
|
|
77
|
+
key.remoteJid = m.chatJid;
|
|
78
|
+
key.fromMe = m.isFromMe;
|
|
79
|
+
key.id = m.id;
|
|
80
|
+
if (m.senderJid !== undefined)
|
|
81
|
+
key.participant = m.senderJid;
|
|
82
|
+
const wm = new WAProto.WebMessageInfo();
|
|
83
|
+
wm.key = key;
|
|
84
|
+
if (m.messageProto !== undefined)
|
|
85
|
+
wm.message = WAProto.Message.fromObject(m.messageProto);
|
|
86
|
+
// Source-side WAProto types 64-bit fields via the bridge shapes (plain
|
|
87
|
+
// number); the published facade and the previous fromObject path both
|
|
88
|
+
// carry a protobufjs `Long` here, so keep that runtime shape.
|
|
89
|
+
wm.messageTimestamp = Long.fromValue(m.timestamp);
|
|
90
|
+
if (m.pushName !== undefined)
|
|
91
|
+
wm.pushName = m.pushName;
|
|
92
|
+
wm.status = WAProto.WebMessageInfo.Status.SERVER_ACK;
|
|
93
|
+
if (m.participantAlt)
|
|
94
|
+
wm.key.participantAlt = m.participantAlt;
|
|
95
|
+
if (m.remoteJidAlt)
|
|
96
|
+
wm.key.remoteJidAlt = m.remoteJidAlt;
|
|
97
|
+
if (m.isViewOnce)
|
|
98
|
+
wm.key.isViewOnce = true;
|
|
99
|
+
// Surface the raw EditAttribute so consumers that dedupe by `key.id`
|
|
100
|
+
// can branch on edits ("1") vs originals (""). Mirrors upstream's
|
|
101
|
+
// `decodeMessageNode` which sets `key.editAttribute` from the same
|
|
102
|
+
// stanza attribute.
|
|
103
|
+
if (m.editAttribute)
|
|
104
|
+
wm.key.editAttribute = m.editAttribute;
|
|
105
|
+
return wm;
|
|
106
|
+
};
|
|
107
|
+
const messageUpsertMetadata = (message) => ({
|
|
108
|
+
type: message.isOffline ? MESSAGE_UPSERT_APPEND : MESSAGE_UPSERT_NOTIFY,
|
|
109
|
+
requestId: message.unavailableRequestId
|
|
110
|
+
});
|
|
111
|
+
const hasMessageSideEffects = (message) => message.messageProto.reactionMessage != null || message.messageProto.protocolMessage != null;
|
|
112
|
+
// Mirror upstream `messages-recv.ts`: every inbound envelope that carries a
|
|
113
|
+
// push name surfaces it as `contacts.update` with `notify`. This is also what
|
|
114
|
+
// replaces the bridge's dedicated `push_name_update` event, gone in 0.14.0.
|
|
115
|
+
const emitInboundPushName = (ctx, evt) => {
|
|
116
|
+
if (!evt.pushName || evt.isFromMe)
|
|
117
|
+
return;
|
|
118
|
+
const id = evt.senderJid ?? evt.chatJid;
|
|
119
|
+
// A broadcast envelope resolves to the pseudo-contact (the canonical layer
|
|
120
|
+
// drops the participant for non-groups); naming `status@broadcast` after
|
|
121
|
+
// whoever posted last would corrupt it, so stay silent instead.
|
|
122
|
+
if (isJidBroadcast(id))
|
|
123
|
+
return;
|
|
124
|
+
ctx.ev.emit('contacts.update', [{ id, notify: evt.pushName }]);
|
|
125
|
+
};
|
|
126
|
+
const hasSameUpsertMetadata = (left, right) => left.type === right.type && left.requestId === right.requestId;
|
|
127
|
+
const clearHistorySyncPausedTimeout = (state, runtime) => {
|
|
128
|
+
if (state.pausedTimeout !== undefined)
|
|
129
|
+
runtime.clearTimeout(state.pausedTimeout);
|
|
130
|
+
state.pausedTimeout = undefined;
|
|
131
|
+
};
|
|
132
|
+
/**
|
|
133
|
+
* Report a disconnect the engine will NOT recover from.
|
|
134
|
+
*
|
|
135
|
+
* `connection: 'close'` carries one meaning on this socket, the same one it
|
|
136
|
+
* carries in upstream Baileys: the socket is finished and the consumer has to
|
|
137
|
+
* build a new one. Disconnects the engine is still retrying never come through
|
|
138
|
+
* here — see `emitRetrying` and `terminal-close.ts`.
|
|
139
|
+
*
|
|
140
|
+
* `onTerminalClose` owns both the teardown and the publish, so the socket can
|
|
141
|
+
* be fully torn down before the consumer sees the event — the order upstream
|
|
142
|
+
* uses, and what keeps a replacement socket from overlapping the old one's
|
|
143
|
+
* store flush. Without that callback (a bare `makeEventHandler`), the close
|
|
144
|
+
* goes out immediately.
|
|
145
|
+
*/
|
|
146
|
+
const emitClose = ({ ctx, callbacks, historySync, runtime }, reason, statusCode, data) => {
|
|
147
|
+
// Every terminal path cancels the history-sync pause timer, not just the
|
|
148
|
+
// one in `disconnected`. A transient drop deliberately keeps it armed, so
|
|
149
|
+
// without this a drop followed by a terminal close leaves it to fire a
|
|
150
|
+
// `messaging-history.status: paused` from a socket that has already ended.
|
|
151
|
+
clearHistorySyncPausedTimeout(historySync, runtime);
|
|
152
|
+
const error = new Boom(reason, { statusCode, data });
|
|
153
|
+
const publish = () => ctx.ev.emit('connection.update', {
|
|
154
|
+
connection: 'close',
|
|
155
|
+
lastDisconnect: { error, date: new Date() }
|
|
156
|
+
});
|
|
157
|
+
if (callbacks?.onTerminalClose) {
|
|
158
|
+
callbacks.onTerminalClose(error, publish);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
publish();
|
|
162
|
+
};
|
|
163
|
+
/**
|
|
164
|
+
* Report a disconnect the engine is retrying on its own.
|
|
165
|
+
*
|
|
166
|
+
* Emitted as `connecting` rather than `close` on purpose. The canonical
|
|
167
|
+
* upstream handler is `if (connection === 'close') reconnect()`, and upstream
|
|
168
|
+
* has no auto-reconnect — so surfacing a transient drop as `close` makes that
|
|
169
|
+
* handler build a second socket while the engine is already backing off to
|
|
170
|
+
* restore the first. Two live sockets for one connection. `connecting` is the
|
|
171
|
+
* state upstream itself uses while a connection is being (re)established, so
|
|
172
|
+
* consumers read this as `open → connecting → open` and stay out of the way.
|
|
173
|
+
*/
|
|
174
|
+
/**
|
|
175
|
+
* `<stream:error code="429">` — the server rate limiting this session. The one
|
|
176
|
+
* stream error the engine forwards that is not a preserved connection; see the
|
|
177
|
+
* `streamError` dispatcher.
|
|
178
|
+
*/
|
|
179
|
+
const RATE_LIMITED_STREAM_ERROR = '429';
|
|
180
|
+
const emitRetrying = (ctx) => ctx.ev.emit('connection.update', {
|
|
181
|
+
connection: 'connecting',
|
|
182
|
+
// Same shape upstream's own `connecting` always carries. Without the
|
|
183
|
+
// explicit clear, a consumer merging partial state keeps rendering the
|
|
184
|
+
// QR from before the drop — one the server has already rotated away.
|
|
185
|
+
qr: undefined,
|
|
186
|
+
receivedPendingNotifications: false
|
|
187
|
+
});
|
|
188
|
+
/**
|
|
189
|
+
* `<failure reason="405">` — the wire code, kept as-is rather than folded into
|
|
190
|
+
* `DisconnectReason`, which has no member for it. See the `clientOutdated`
|
|
191
|
+
* dispatcher for why `badSession` was the wrong home.
|
|
192
|
+
*/
|
|
193
|
+
const CLIENT_OUTDATED_STATUS = 405;
|
|
194
|
+
const describeTempBan = (code) => {
|
|
195
|
+
switch (code) {
|
|
196
|
+
case 101:
|
|
197
|
+
return 'sent_to_too_many_people';
|
|
198
|
+
case 102:
|
|
199
|
+
return 'blocked_by_users';
|
|
200
|
+
case 103:
|
|
201
|
+
return 'created_too_many_groups';
|
|
202
|
+
case 104:
|
|
203
|
+
return 'sent_too_many_same_message';
|
|
204
|
+
case 106:
|
|
205
|
+
return 'broadcast_list';
|
|
206
|
+
default:
|
|
207
|
+
return code != null ? `code_${code}` : 'unknown';
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
/**
|
|
211
|
+
* Sole `as` cast in the dispatch path. The bridge runtime's
|
|
212
|
+
* `connection.update` slot accepts the full ConnectionState union, but we
|
|
213
|
+
* only ever emit partials shaped as `{ connection, … }`. The Baileys event
|
|
214
|
+
* map types `connection.update` as the full state which is unsafe to
|
|
215
|
+
* widen; centralizing the cast here keeps every dispatcher clean.
|
|
216
|
+
*/
|
|
217
|
+
const emitConnectionUpdate = (ctx, update) => ctx.ev.emit('connection.update', update);
|
|
218
|
+
const DISPATCHERS = {
|
|
219
|
+
// ── Connection lifecycle ──
|
|
220
|
+
connected: (_, { ctx }) => emitConnectionUpdate(ctx, { connection: 'open' }),
|
|
221
|
+
offlineSyncCompleted: (_, { ctx }) => emitConnectionUpdate(ctx, {
|
|
222
|
+
receivedPendingNotifications: true
|
|
223
|
+
}),
|
|
224
|
+
// The engine dispatches `Disconnected` only for an *unexpected* loop exit,
|
|
225
|
+
// and every terminal path marks `expected_disconnect` first — so this is
|
|
226
|
+
// normally "the Fibonacci backoff is already running".
|
|
227
|
+
//
|
|
228
|
+
// The exception is `sock.setAutoReconnect(false)`: `client/lifecycle.rs`
|
|
229
|
+
// dispatches `Disconnected` and only *then* tests the flag and breaks out
|
|
230
|
+
// of the run loop. Treating that as transient would leave the socket
|
|
231
|
+
// reporting `connecting` forever, with the wasm client never freed and the
|
|
232
|
+
// consumer's reconnect handler never firing.
|
|
233
|
+
disconnected: (_, dispatchCtx) => {
|
|
234
|
+
if (dispatchCtx.callbacks?.isAutoReconnectEnabled?.() === false) {
|
|
235
|
+
emitClose(dispatchCtx, 'Connection closed', DisconnectReason.connectionClosed);
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
// The pause timer survives a retrying drop. It is the only pending
|
|
239
|
+
// transition to `messaging-history.status: paused`, and this socket
|
|
240
|
+
// lives on — clearing it left a RECENT sync that had reported progress
|
|
241
|
+
// below 100 with neither `paused` nor `complete` if the reconnect
|
|
242
|
+
// produced no further chunk, hanging consumers waiting on hydration.
|
|
243
|
+
emitRetrying(dispatchCtx.ctx);
|
|
244
|
+
},
|
|
245
|
+
qr: (evt, { ctx }) => emitConnectionUpdate(ctx, { qr: evt.code }),
|
|
246
|
+
pairSuccess: (evt, { ctx, callbacks }) => {
|
|
247
|
+
const { id, lid, businessName, platform } = evt;
|
|
248
|
+
ctx.setUser({ id, lid });
|
|
249
|
+
callbacks?.onPairSuccess?.({ platform, businessName });
|
|
250
|
+
// Synthetic `creds.update` so upstream-style auth code
|
|
251
|
+
// (`ev.on('creds.update', saveCreds)`) gets a single tick to persist
|
|
252
|
+
// post-pair state. The bridge owns the real creds; this emission is
|
|
253
|
+
// a compat hook for upstream's lifecycle.
|
|
254
|
+
ctx.ev.emit('creds.update', { registered: true, me: { id, lid, name: businessName }, platform });
|
|
255
|
+
},
|
|
256
|
+
// Pairing failed, but the engine keeps its loop and re-emits a QR — nothing
|
|
257
|
+
// about the client is dead, so this must not read as `close`. It still
|
|
258
|
+
// belongs on the bus: the QR the user was shown is spent, and `connecting`
|
|
259
|
+
// clears it while telling the consumer a fresh one is coming.
|
|
260
|
+
pairError: (evt, { ctx }) => {
|
|
261
|
+
ctx.logger.error({ err: evt.error, rejection: evt.rejection, backoff: evt.backoff }, 'pairing failed; the engine will retry');
|
|
262
|
+
emitRetrying(ctx);
|
|
263
|
+
},
|
|
264
|
+
loggedOut: (evt, dispatchCtx) => emitClose(dispatchCtx, evt.reason ? `Logged out: ${evt.reason}` : 'Logged out', DisconnectReason.loggedOut),
|
|
265
|
+
connectFailure: (evt, dispatchCtx) => {
|
|
266
|
+
// Map bridge `ConnectFailureReason` wire codes onto Baileys'
|
|
267
|
+
// DisconnectReason. Defaults to connectionClosed for unknown codes.
|
|
268
|
+
// LoggedOut paths (401/403/406) drive bots' "should I re-pair?"
|
|
269
|
+
// branch — folding them into connectionClosed kept that broken.
|
|
270
|
+
// "Reconnectable" is only true while the engine is allowed to reconnect.
|
|
271
|
+
// With `setAutoReconnect(false)` the run loop breaks on the next pass,
|
|
272
|
+
// so reporting `connecting` for a 500/503 would leave the socket stuck
|
|
273
|
+
// in that state with nothing left to restore it.
|
|
274
|
+
if (isReconnectableConnectFailure(evt.reason) && dispatchCtx.callbacks?.isAutoReconnectEnabled?.() !== false) {
|
|
275
|
+
dispatchCtx.ctx.logger.warn({ reason: evt.reason, message: evt.message }, 'connect failure; the engine will retry');
|
|
276
|
+
emitRetrying(dispatchCtx.ctx);
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
const status = mapConnectFailureToDisconnect(evt.reason);
|
|
280
|
+
emitClose(dispatchCtx, evt.message ?? 'Connection failure', status);
|
|
281
|
+
},
|
|
282
|
+
// NOT a close, in either branch below. This used to report
|
|
283
|
+
// `DisconnectReason.badSession`, the code bots use to wipe credentials and
|
|
284
|
+
// re-pair, so a routine stream recycle could destroy a working session.
|
|
285
|
+
//
|
|
286
|
+
// Two kinds of event arrive here, and they are not interchangeable:
|
|
287
|
+
//
|
|
288
|
+
// - the engine's catch-all `<stream:error>` branch — an unknown code, an
|
|
289
|
+
// `<ack/>` it still owes the server, or `<xml-not-well-formed>` — where
|
|
290
|
+
// it keeps or deliberately recycles the connection. Nothing to publish:
|
|
291
|
+
// the recycle reaches the consumer as a `disconnected` of its own.
|
|
292
|
+
//
|
|
293
|
+
// - `429`, which is a *rejected session*, not a preserved connection.
|
|
294
|
+
// `client/node_io.rs` clears `is_logged_in`, adds five rungs to the
|
|
295
|
+
// Fibonacci backoff and suppresses the reset that would undo them, then
|
|
296
|
+
// dispatches this event so an embedder can act on it — the core's comment
|
|
297
|
+
// says as much ("An embedder has none, so report the rate limit through
|
|
298
|
+
// `StreamError`"). It falls through the handler's `should_disconnect`
|
|
299
|
+
// block, so the transport is still up at this instant and the socket
|
|
300
|
+
// would keep reporting `open` until the server ends the stream.
|
|
301
|
+
//
|
|
302
|
+
// `connecting` for 429 is not a new state: it is the one this library
|
|
303
|
+
// already defines for "the engine is restoring the connection", and the one
|
|
304
|
+
// the next server frame produces anyway. Publishing it here just moves it to
|
|
305
|
+
// the moment the engine already knows, instead of the round trip that
|
|
306
|
+
// confirms it. The coded errors that *are* terminal (401/409/515/516) never
|
|
307
|
+
// reach this dispatcher; they emit `loggedOut` / `streamReplaced` instead.
|
|
308
|
+
streamError: (evt, { ctx, callbacks }) => {
|
|
309
|
+
if (evt.code === RATE_LIMITED_STREAM_ERROR) {
|
|
310
|
+
ctx.logger.warn({ code: evt.code }, 'stream error: the server rate limited this session; the engine will retry with an extended backoff');
|
|
311
|
+
// `connecting` promises the engine is restoring this connection.
|
|
312
|
+
// Under `setAutoReconnect(false)` it will not — the run loop breaks
|
|
313
|
+
// on the pass after the disconnect that follows — so publishing it
|
|
314
|
+
// would leave a retrying state nobody resolves. Silence, not a
|
|
315
|
+
// close: the engine still dispatches `Disconnected` when the server
|
|
316
|
+
// ends the stream, and that dispatcher already turns it into a
|
|
317
|
+
// terminal close under this flag. Closing here too would publish two
|
|
318
|
+
// for one failure, the second after teardown had already run.
|
|
319
|
+
if (callbacks?.isAutoReconnectEnabled?.() !== false)
|
|
320
|
+
emitRetrying(ctx);
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
ctx.logger.warn({ code: evt.code }, 'stream error; the connection is preserved');
|
|
324
|
+
},
|
|
325
|
+
streamReplaced: (_, dispatchCtx) => emitClose(dispatchCtx, 'Connection replaced', DisconnectReason.connectionReplaced),
|
|
326
|
+
// Carries the wire code (405), not `DisconnectReason.badSession`. Upstream
|
|
327
|
+
// does the same for stream errors — `+node.attrs.code` first, `badSession`
|
|
328
|
+
// only as the no-code fallback (`Utils/generics.ts` `getErrorCodeFromStreamError`).
|
|
329
|
+
// badSession is 500, the code bots use to wipe credentials and re-pair; an
|
|
330
|
+
// outdated build is the one failure where wiping a perfectly good session
|
|
331
|
+
// helps nobody, and the next connect fails identically.
|
|
332
|
+
clientOutdated: (_, dispatchCtx) => emitClose(dispatchCtx, 'Client outdated', CLIENT_OUTDATED_STATUS),
|
|
333
|
+
temporaryBan: (evt, dispatchCtx) => {
|
|
334
|
+
// Surface the wire code + expire on the Boom so consumers reading
|
|
335
|
+
// `lastDisconnect.error.data` can act on the specific reason.
|
|
336
|
+
const reason = describeTempBan(evt.code);
|
|
337
|
+
const message = evt.expire
|
|
338
|
+
? `Temporary ban (${reason}); expires at ${new Date(evt.expire * 1000).toISOString()}`
|
|
339
|
+
: `Temporary ban (${reason})`;
|
|
340
|
+
emitClose(dispatchCtx, message, DisconnectReason.forbidden, { code: evt.code, expire: evt.expire });
|
|
341
|
+
},
|
|
342
|
+
qrScannedWithoutMultidevice: (_, { ctx }) => ctx.logger.warn('QR scanned but multi-device not enabled on phone'),
|
|
343
|
+
// ── Messages ──
|
|
344
|
+
message: (evt, { ctx, runtime }) => {
|
|
345
|
+
if (ctx.fullConfig.shouldIgnoreJid?.(evt.chatJid))
|
|
346
|
+
return;
|
|
347
|
+
emitInboundPushName(ctx, evt);
|
|
348
|
+
// Note: `emitOwnEvents=false` is NOT applied here. Upstream Baileys
|
|
349
|
+
// uses that flag to suppress the local echo when `sendMessage()`
|
|
350
|
+
// succeeds, not to drop inbound `fromMe` messages from other linked
|
|
351
|
+
// devices.
|
|
352
|
+
const waMsg = canonicalMessageToWAMessage(evt, runtime.Long);
|
|
353
|
+
emitMessageUpsert(ctx, [waMsg], messageUpsertMetadata(evt));
|
|
354
|
+
// Mirror upstream `process-message.ts:523-533`: when the inbound
|
|
355
|
+
// proto carries a `reactionMessage`, surface it on the dedicated
|
|
356
|
+
// `messages.reaction` channel as well. The `key` in the event
|
|
357
|
+
// payload is the TARGET (the message being reacted to), and
|
|
358
|
+
// `reaction.key` is the reaction's own envelope key — that's the
|
|
359
|
+
// exact shape upstream consumers index by.
|
|
360
|
+
const reactionMessage = evt.messageProto.reactionMessage;
|
|
361
|
+
if (reactionMessage?.key) {
|
|
362
|
+
ctx.ev.emit('messages.reaction', [
|
|
363
|
+
{
|
|
364
|
+
key: reactionMessage.key,
|
|
365
|
+
reaction: { ...reactionMessage, key: waMsg.key }
|
|
366
|
+
}
|
|
367
|
+
]);
|
|
368
|
+
}
|
|
369
|
+
// Mirror upstream `process-message.ts:404-414` (REVOKE) and
|
|
370
|
+
// `:474-490` (MESSAGE_EDIT). Both surface as `messages.update` with
|
|
371
|
+
// the TARGET key (id taken from protocolMessage.key).
|
|
372
|
+
const protocolMsg = evt.messageProto.protocolMessage;
|
|
373
|
+
// `group.member-tag.update` doesn't reuse `protocolMsg.key.id` — the
|
|
374
|
+
// label change applies to the participant directly, identified by
|
|
375
|
+
// the envelope key. Mirror upstream `process-message.ts:492-503`.
|
|
376
|
+
if (protocolMsg?.type === WAProto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE &&
|
|
377
|
+
protocolMsg.memberLabel?.label) {
|
|
378
|
+
// `senderJid` is required for this event — it identifies the
|
|
379
|
+
// participant whose label changed. If the bridge ever surfaced a
|
|
380
|
+
// label-change without one (server bug / non-group context), an
|
|
381
|
+
// empty-string fallback would corrupt downstream consumer state.
|
|
382
|
+
// Skip with a warn instead.
|
|
383
|
+
if (!evt.senderJid) {
|
|
384
|
+
ctx.logger.warn({ chatJid: evt.chatJid, label: protocolMsg.memberLabel.label }, 'GROUP_MEMBER_LABEL_CHANGE without senderJid — dropping (no participant to attribute)');
|
|
385
|
+
}
|
|
386
|
+
else {
|
|
387
|
+
ctx.ev.emit('group.member-tag.update', {
|
|
388
|
+
groupId: evt.chatJid,
|
|
389
|
+
label: protocolMsg.memberLabel.label,
|
|
390
|
+
participant: evt.senderJid,
|
|
391
|
+
participantAlt: evt.participantAlt,
|
|
392
|
+
messageTimestamp: evt.timestamp
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
const protocolKeyId = protocolMsg?.key?.id;
|
|
397
|
+
if (protocolMsg && protocolKeyId) {
|
|
398
|
+
if (protocolMsg.type === WAProto.Message.ProtocolMessage.Type.REVOKE) {
|
|
399
|
+
ctx.ev.emit('messages.update', [
|
|
400
|
+
{
|
|
401
|
+
key: { ...waMsg.key, id: protocolKeyId },
|
|
402
|
+
update: {
|
|
403
|
+
message: null,
|
|
404
|
+
messageStubType: WAProto.WebMessageInfo.StubType.REVOKE,
|
|
405
|
+
key: waMsg.key
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
]);
|
|
409
|
+
}
|
|
410
|
+
else if (protocolMsg.type === WAProto.Message.ProtocolMessage.Type.MESSAGE_EDIT && protocolMsg.editedMessage) {
|
|
411
|
+
// `timestampMs` is an int64 proto field → a protobufjs `Long`
|
|
412
|
+
// object from the bridge; `toNumber` is Long-safe (plain
|
|
413
|
+
// `Number()` would yield NaN and corrupt the edit timestamp).
|
|
414
|
+
const tsMs = protocolMsg.timestampMs;
|
|
415
|
+
const editedTs = tsMs != null ? Math.floor(toNumber(tsMs) / 1000) : (evt.timestamp ?? waMsg.messageTimestamp);
|
|
416
|
+
ctx.ev.emit('messages.update', [
|
|
417
|
+
{
|
|
418
|
+
key: { ...waMsg.key, id: protocolKeyId },
|
|
419
|
+
update: {
|
|
420
|
+
message: { editedMessage: { message: protocolMsg.editedMessage } },
|
|
421
|
+
messageTimestamp: editedTs
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
]);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
},
|
|
428
|
+
receipt: (evt, { ctx }) => {
|
|
429
|
+
// Fan out one MessageUserReceiptUpdate per id (upstream emits
|
|
430
|
+
// per-id) and pick the timestamp slot from the receipt type so
|
|
431
|
+
// consumers branching on `receipt.readTimestamp` /
|
|
432
|
+
// `receipt.playedTimestamp` see the right field populated.
|
|
433
|
+
const participant = evt.isGroup ? evt.senderJid : undefined;
|
|
434
|
+
const receipt = {};
|
|
435
|
+
if (evt.receiptType === 'read' || evt.receiptType === 'read-self') {
|
|
436
|
+
receipt.readTimestamp = evt.timestamp;
|
|
437
|
+
}
|
|
438
|
+
else if (evt.receiptType === 'played' || evt.receiptType === 'played-self') {
|
|
439
|
+
receipt.playedTimestamp = evt.timestamp;
|
|
440
|
+
}
|
|
441
|
+
else {
|
|
442
|
+
receipt.receiptTimestamp = evt.timestamp;
|
|
443
|
+
}
|
|
444
|
+
ctx.ev.emit('message-receipt.update', evt.messageIds.map(id => ({
|
|
445
|
+
key: { remoteJid: evt.chatJid, id, fromMe: evt.isFromMe, participant },
|
|
446
|
+
receipt
|
|
447
|
+
})));
|
|
448
|
+
},
|
|
449
|
+
undecryptableMessage: (evt, { ctx }) => {
|
|
450
|
+
// Mirror upstream `messages-recv.ts:1352-…`: surface a CIPHERTEXT
|
|
451
|
+
// stub on `messages.upsert` so consumers see the placeholder and
|
|
452
|
+
// can request a resend (PLACEHOLDER_MESSAGE_RESEND PDO). Logging
|
|
453
|
+
// happens at debug — upstream considers this routine.
|
|
454
|
+
ctx.logger.debug({ id: evt.id, chat: evt.chatJid, isUnavailable: evt.isUnavailable, fail: evt.decryptFailMode }, 'undecryptable message received');
|
|
455
|
+
// The name is envelope metadata, independent of whether the failure
|
|
456
|
+
// may be surfaced, so it goes out even for `hide`. The stub below
|
|
457
|
+
// predates `shouldIgnoreJid` and stays unguarded; the push name
|
|
458
|
+
// emission is new, so it honors the predicate like the other two
|
|
459
|
+
// call sites do.
|
|
460
|
+
if (!ctx.fullConfig.shouldIgnoreJid?.(evt.chatJid))
|
|
461
|
+
emitInboundPushName(ctx, evt);
|
|
462
|
+
// `decrypt_fail_mode === 'hide'` means the server told us to
|
|
463
|
+
// silently drop — match that by NOT emitting an upsert.
|
|
464
|
+
if (evt.decryptFailMode === 'hide')
|
|
465
|
+
return;
|
|
466
|
+
const stubMsg = WAProto.WebMessageInfo.fromObject({
|
|
467
|
+
key: {
|
|
468
|
+
remoteJid: evt.chatJid,
|
|
469
|
+
fromMe: evt.isFromMe,
|
|
470
|
+
id: evt.id,
|
|
471
|
+
participant: evt.senderJid
|
|
472
|
+
},
|
|
473
|
+
messageTimestamp: evt.timestamp,
|
|
474
|
+
pushName: evt.pushName,
|
|
475
|
+
messageStubType: WAProto.WebMessageInfo.StubType.CIPHERTEXT,
|
|
476
|
+
messageStubParameters: evt.unavailableType ? [evt.unavailableType] : []
|
|
477
|
+
});
|
|
478
|
+
if (evt.participantAlt)
|
|
479
|
+
stubMsg.key.participantAlt = evt.participantAlt;
|
|
480
|
+
if (evt.remoteJidAlt)
|
|
481
|
+
stubMsg.key.remoteJidAlt = evt.remoteJidAlt;
|
|
482
|
+
// A field of its own, not a second slot in `messageStubParameters`:
|
|
483
|
+
// that array is positional, and two independently optional values in it
|
|
484
|
+
// cannot be told apart — a lone `"pay"` would sit where an
|
|
485
|
+
// unavailability reason used to. This is the one thing that survives a
|
|
486
|
+
// decryption failure to say what the message was (the server stamps it
|
|
487
|
+
// on the sender's own outgoing stanza, in the clear), so it is named
|
|
488
|
+
// rather than placed.
|
|
489
|
+
if (evt.stanzaType)
|
|
490
|
+
stubMsg.stanzaType = evt.stanzaType;
|
|
491
|
+
ctx.ev.emit('messages.upsert', { messages: [stubMsg], type: 'notify' });
|
|
492
|
+
},
|
|
493
|
+
// ── Contacts ──
|
|
494
|
+
contactUpdate: (evt, { ctx }) => {
|
|
495
|
+
// Promote ContactAction fields into upstream's `Partial<Contact>`
|
|
496
|
+
// shape so consumers (sidebar UIs, contact pickers) see real names
|
|
497
|
+
// instead of bare ids. `verifiedName` is intentionally not set —
|
|
498
|
+
// that comes from a different notification path (business-level
|
|
499
|
+
// verification).
|
|
500
|
+
const update = { id: evt.jid };
|
|
501
|
+
const name = evt.fullName ?? evt.firstName;
|
|
502
|
+
if (name)
|
|
503
|
+
update.name = name;
|
|
504
|
+
if (evt.lidJid)
|
|
505
|
+
update.lid = evt.lidJid;
|
|
506
|
+
if (evt.pnJid)
|
|
507
|
+
update.phoneNumber = evt.pnJid;
|
|
508
|
+
ctx.ev.emit('contacts.update', [update]);
|
|
509
|
+
},
|
|
510
|
+
pictureUpdate: (evt, { ctx }) =>
|
|
511
|
+
// Upstream emits `imgUrl: null` on removal so consumers cache the
|
|
512
|
+
// absence instead of refetching forever. `'changed'` is the
|
|
513
|
+
// sentinel for "invalidate cache, refetch on demand".
|
|
514
|
+
ctx.ev.emit('contacts.update', [{ id: evt.jid, imgUrl: evt.removed ? null : 'changed' }]),
|
|
515
|
+
// ── Presence ──
|
|
516
|
+
presence: (evt, { ctx }) => ctx.ev.emit('presence.update', {
|
|
517
|
+
id: evt.from,
|
|
518
|
+
presences: {
|
|
519
|
+
[evt.from]: {
|
|
520
|
+
lastKnownPresence: (evt.unavailable ? 'unavailable' : 'available'),
|
|
521
|
+
lastSeen: evt.lastSeen
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
}),
|
|
525
|
+
chatPresence: (evt, { ctx }) => {
|
|
526
|
+
// Bridge `ChatPresenceUpdate.state` is `'composing' | 'paused'`.
|
|
527
|
+
// `recording` is signaled via `media === 'audio'` riding on top of
|
|
528
|
+
// `composing` — upstream Baileys' `WAPresence` collapses the two
|
|
529
|
+
// signals into 'composing' / 'recording' / 'paused'. Anything
|
|
530
|
+
// outside this set falls back to `'paused'` (the safe sentinel —
|
|
531
|
+
// "stopped doing whatever they were doing") rather than passing
|
|
532
|
+
// through unvalidated, which previously could leak unknown wire
|
|
533
|
+
// values onto consumer-facing `WAPresence`.
|
|
534
|
+
let mapped;
|
|
535
|
+
if (evt.state === 'composing')
|
|
536
|
+
mapped = evt.media === 'audio' ? 'recording' : 'composing';
|
|
537
|
+
else if (evt.state === 'paused')
|
|
538
|
+
mapped = 'paused';
|
|
539
|
+
else {
|
|
540
|
+
ctx.logger.debug({ state: evt.state, media: evt.media }, 'chat_presence: unknown state — falling back to paused');
|
|
541
|
+
mapped = 'paused';
|
|
542
|
+
}
|
|
543
|
+
ctx.ev.emit('presence.update', {
|
|
544
|
+
id: evt.chatJid,
|
|
545
|
+
presences: { [evt.senderJid]: { lastKnownPresence: mapped } }
|
|
546
|
+
});
|
|
547
|
+
},
|
|
548
|
+
// ── Groups ──
|
|
549
|
+
groupUpdate: (evt, { ctx }) => {
|
|
550
|
+
const user = ctx.getUser();
|
|
551
|
+
const fromMe = !!(evt.author && (evt.author === user?.id || evt.author === user?.lid));
|
|
552
|
+
if (evt.action.type === 'create') {
|
|
553
|
+
// The neutral bridge marker intentionally carries no Baileys-shaped
|
|
554
|
+
// metadata. Resolve it here, at the compatibility boundary, then emit
|
|
555
|
+
// the same complete lifecycle and ordering as upstream.
|
|
556
|
+
void (async () => {
|
|
557
|
+
try {
|
|
558
|
+
const bridgeMetadata = await ctx.withClient(client => client.getGroupMetadata(evt.groupJid));
|
|
559
|
+
const metadata = bridgeGroupMetadataToBaileys(bridgeMetadata);
|
|
560
|
+
ctx.ev.emit('chats.upsert', [
|
|
561
|
+
{ id: metadata.id, name: metadata.subject, conversationTimestamp: metadata.creation }
|
|
562
|
+
]);
|
|
563
|
+
ctx.ev.emit('groups.upsert', [
|
|
564
|
+
{
|
|
565
|
+
...metadata,
|
|
566
|
+
author: evt.author,
|
|
567
|
+
authorPn: evt.authorPn,
|
|
568
|
+
authorUsername: evt.authorUsername
|
|
569
|
+
}
|
|
570
|
+
]);
|
|
571
|
+
ctx.ev.emit('messages.upsert', {
|
|
572
|
+
messages: [buildGroupCreateStubMessage(evt, metadata, fromMe)],
|
|
573
|
+
type: 'append'
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
catch (err) {
|
|
577
|
+
ctx.logger.warn({ err, groupJid: evt.groupJid }, 'group create notification: metadata resolution failed');
|
|
578
|
+
}
|
|
579
|
+
})();
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
// Upstream upserts the synthesized notification message before
|
|
583
|
+
// process-message derives high-level group/chat events from it.
|
|
584
|
+
const stubMessages = buildGroupNotificationStubMessages(evt, fromMe);
|
|
585
|
+
if (stubMessages.length > 0) {
|
|
586
|
+
ctx.ev.emit('messages.upsert', { messages: stubMessages, type: 'append' });
|
|
587
|
+
}
|
|
588
|
+
// Dispatch via discriminator instead of `as never` so TS validates
|
|
589
|
+
// payload ↔ event-name pairing.
|
|
590
|
+
const domainEvent = buildGroupNotificationDomainEvent(evt);
|
|
591
|
+
if (domainEvent) {
|
|
592
|
+
if (domainEvent.name === 'groups.update')
|
|
593
|
+
ctx.ev.emit('groups.update', domainEvent.payload);
|
|
594
|
+
else
|
|
595
|
+
ctx.ev.emit('group-participants.update', domainEvent.payload);
|
|
596
|
+
}
|
|
597
|
+
// Fan out `group.join-request` for membership_approval_request /
|
|
598
|
+
// created_membership_requests / revoked_membership_requests.
|
|
599
|
+
// Upstream emits one event per affected participant.
|
|
600
|
+
for (const joinReq of buildGroupJoinRequestEvents(evt)) {
|
|
601
|
+
ctx.ev.emit('group.join-request', joinReq);
|
|
602
|
+
}
|
|
603
|
+
const chatUpdates = buildGroupNotificationChatUpdates(evt);
|
|
604
|
+
if (chatUpdates.length > 0)
|
|
605
|
+
ctx.ev.emit('chats.update', chatUpdates);
|
|
606
|
+
},
|
|
607
|
+
// ── Chat state ──
|
|
608
|
+
archiveUpdate: (evt, { ctx }) => ctx.ev.emit('chats.update', [{ id: evt.jid, archived: evt.archived }]),
|
|
609
|
+
pinUpdate: (evt, { ctx }) =>
|
|
610
|
+
// Upstream Baileys' `chat-utils.ts:878` emits `null` (not
|
|
611
|
+
// `undefined`) on unpin so consumers using `'pinned' in update`
|
|
612
|
+
// can distinguish "not touched" from "explicitly unpinned" —
|
|
613
|
+
// matters for ChatUpdate-shaped diffs where the property's
|
|
614
|
+
// presence is the signal.
|
|
615
|
+
ctx.ev.emit('chats.update', [{ id: evt.jid, pinned: evt.pinned ? evt.timestamp : null }]),
|
|
616
|
+
muteUpdate: (evt, { ctx }) =>
|
|
617
|
+
// Mirrors upstream `chat-utils.ts:809`: when muted, surface
|
|
618
|
+
// `muteEndTimestamp` (0 = forever); on unmute, surface `null`.
|
|
619
|
+
ctx.ev.emit('chats.update', [{ id: evt.jid, muteEndTime: evt.muted ? (evt.muteEndTimestamp ?? 0) : null }]),
|
|
620
|
+
starUpdate: (evt, { ctx }) => ctx.ev.emit('messages.update', [
|
|
621
|
+
{
|
|
622
|
+
key: { remoteJid: evt.chatJid, id: evt.messageId, fromMe: evt.fromMe, participant: evt.participantJid },
|
|
623
|
+
update: { starred: evt.starred }
|
|
624
|
+
}
|
|
625
|
+
]),
|
|
626
|
+
markChatAsReadUpdate: (evt, { ctx }) =>
|
|
627
|
+
// Mirrors upstream `chat-utils.ts:852`: read=true → unreadCount=0,
|
|
628
|
+
// read=false (mark as unread) → -1 sentinel.
|
|
629
|
+
ctx.ev.emit('chats.update', [{ id: evt.jid, unreadCount: evt.read ? 0 : -1 }]),
|
|
630
|
+
// Upstream `chat-utils.ts:819` emits `chats.lock` from `lockChatAction.locked`.
|
|
631
|
+
lockChatUpdate: (evt, { ctx }) => ctx.ev.emit('chats.lock', { id: evt.jid, locked: evt.locked }),
|
|
632
|
+
labelEdit: (evt, { ctx }) =>
|
|
633
|
+
// Upstream `labels.edit` carries a `Label`. A delete arrives with
|
|
634
|
+
// `deleted: true` (consumers remove it from their store).
|
|
635
|
+
ctx.ev.emit('labels.edit', {
|
|
636
|
+
id: evt.labelId,
|
|
637
|
+
name: evt.name,
|
|
638
|
+
color: evt.color,
|
|
639
|
+
deleted: evt.deleted,
|
|
640
|
+
predefinedId: evt.predefinedId
|
|
641
|
+
}),
|
|
642
|
+
labelAssociation: (evt, { ctx }) => ctx.ev.emit('labels.association', {
|
|
643
|
+
// The two halves arrive on separate bridge events and upstream tells
|
|
644
|
+
// them apart by the association's own type, so a message id is what
|
|
645
|
+
// decides which of the two shapes this is.
|
|
646
|
+
association: evt.messageId
|
|
647
|
+
? {
|
|
648
|
+
type: LabelAssociationType.Message,
|
|
649
|
+
chatId: evt.chatJid,
|
|
650
|
+
messageId: evt.messageId,
|
|
651
|
+
labelId: evt.labelId
|
|
652
|
+
}
|
|
653
|
+
: { type: LabelAssociationType.Chat, chatId: evt.chatJid, labelId: evt.labelId },
|
|
654
|
+
type: evt.labeled ? 'add' : 'remove'
|
|
655
|
+
}),
|
|
656
|
+
appStateSyncFailed: (evt, { ctx }) => {
|
|
657
|
+
// Logged as well as published: a fatal collection is an operator's
|
|
658
|
+
// problem before it is a handler's, and `critical_block` carries the
|
|
659
|
+
// push name, so presence stays unavailable until it syncs.
|
|
660
|
+
if (evt.fatal.length) {
|
|
661
|
+
ctx.logger.warn({ fatal: evt.fatal, connected: evt.connected }, 'app state collections refused by the server');
|
|
662
|
+
}
|
|
663
|
+
ctx.ev.emit('app-state-sync.failed', {
|
|
664
|
+
fatal: evt.fatal,
|
|
665
|
+
retryable: evt.retryable,
|
|
666
|
+
skipped: evt.skipped,
|
|
667
|
+
connected: evt.connected
|
|
668
|
+
});
|
|
669
|
+
},
|
|
670
|
+
// Upstream ends the socket with `timedOut` when its own QR timer gives up
|
|
671
|
+
// (`Socket/socket.ts`), so the canonical reconnect handler already knows
|
|
672
|
+
// this state. Reporting anything else would make it learn a second one.
|
|
673
|
+
qrCodesExhausted: (_, dispatchCtx) => emitClose(dispatchCtx, 'QR refs attempts ended', DisconnectReason.timedOut),
|
|
674
|
+
// Straight onto upstream's own channel for this: `settings.update` already
|
|
675
|
+
// declares the `disableLinkPreviews` arm, and a consumer that reads it is
|
|
676
|
+
// reading the account-wide setting whichever device changed it.
|
|
677
|
+
settingUpdate: (evt, { ctx }) => ctx.ev.emit('settings.update', { setting: evt.setting, value: evt.value }),
|
|
678
|
+
// ── Calls ──
|
|
679
|
+
incomingCall: (evt, { ctx, callbacks }) => {
|
|
680
|
+
callbacks?.onIncomingCall?.(evt);
|
|
681
|
+
const isGroup = isJidGroup(evt.from);
|
|
682
|
+
// Canonical call actions use the exact public Baileys status spelling;
|
|
683
|
+
// missed-call notifications are normalized to `timeout` by the adapter.
|
|
684
|
+
const status = evt.action.type;
|
|
685
|
+
const callEvt = {
|
|
686
|
+
chatId: evt.from,
|
|
687
|
+
from: evt.action.callCreator ?? evt.from,
|
|
688
|
+
...(evt.action.callCreator ? { callCreator: evt.action.callCreator } : {}),
|
|
689
|
+
id: evt.action.callId,
|
|
690
|
+
date: new Date(evt.timestamp * 1000),
|
|
691
|
+
status,
|
|
692
|
+
offline: evt.offline,
|
|
693
|
+
isGroup,
|
|
694
|
+
// Group JID = `evt.from` only when the stanza came from a group
|
|
695
|
+
// JID itself. The bridge offer payload doesn't carry a separate
|
|
696
|
+
// `group_jid` field today, so the group's JID IS the `from` for
|
|
697
|
+
// `<call>` stanzas in groups.
|
|
698
|
+
...(isGroup ? { groupJid: evt.from } : {}),
|
|
699
|
+
...(evt.action.callerPn ? { callerPn: evt.action.callerPn } : {}),
|
|
700
|
+
...(evt.action.type === 'offer' ? { isVideo: !!evt.action.isVideo } : {}),
|
|
701
|
+
// Bridge auxiliary fields (offer-only / terminate-only / always)
|
|
702
|
+
...(evt.action.callerCountryCode ? { callerCountryCode: evt.action.callerCountryCode } : {}),
|
|
703
|
+
...(evt.action.deviceClass ? { deviceClass: evt.action.deviceClass } : {}),
|
|
704
|
+
...(evt.action.joinable !== undefined ? { joinable: evt.action.joinable } : {}),
|
|
705
|
+
...(evt.action.audio ? { audio: evt.action.audio } : {}),
|
|
706
|
+
...(evt.action.duration !== undefined ? { duration: evt.action.duration } : {}),
|
|
707
|
+
...(evt.action.audioDuration !== undefined ? { audioDuration: evt.action.audioDuration } : {}),
|
|
708
|
+
...(evt.stanzaId ? { stanzaId: evt.stanzaId } : {}),
|
|
709
|
+
...(evt.notify ? { notify: evt.notify } : {}),
|
|
710
|
+
...(evt.platform ? { platform: evt.platform } : {}),
|
|
711
|
+
...(evt.version ? { version: evt.version } : {})
|
|
712
|
+
};
|
|
713
|
+
ctx.ev.emit('call', [callEvt]);
|
|
714
|
+
},
|
|
715
|
+
// ── Raw passthrough ──
|
|
716
|
+
dirtyState: (evt, { callbacks }) => callbacks?.onDirtyState?.(evt),
|
|
717
|
+
rawNode: (evt, { ctx }) => emitCBEvents(ctx, evt.node),
|
|
718
|
+
notification: (evt, { ctx }) => ctx.logger.trace({ tag: evt.tag, attrs: evt.attrs }, 'bridge generic notification (no Baileys mapping)'),
|
|
719
|
+
mexNotification: (evt, { ctx }) => {
|
|
720
|
+
// Route by op_name. Adding a new MEX-driven event means a new entry
|
|
721
|
+
// here — no per-op_name plumbing in the Bridge layer.
|
|
722
|
+
if (evt.opName === 'NotificationUserReachoutTimelockUpdate') {
|
|
723
|
+
const state = mapReachoutTimelock(evt.payload);
|
|
724
|
+
if (state)
|
|
725
|
+
emitConnectionUpdate(ctx, { reachoutTimeLock: state });
|
|
726
|
+
else
|
|
727
|
+
ctx.logger.warn({ payload: evt.payload }, 'reachout-timelock push: payload missing expected fields');
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
if (evt.opName === 'MessageCappingInfoNotification') {
|
|
731
|
+
const payload = extractMessageCappingPayload(evt.payload);
|
|
732
|
+
if (payload)
|
|
733
|
+
ctx.ev.emit('message-capping.update', payload);
|
|
734
|
+
else
|
|
735
|
+
ctx.logger.warn({ payload: evt.payload }, 'message-capping push: payload missing expected fields');
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
ctx.logger.trace({ opName: evt.opName, offline: evt.offline }, 'bridge mex notification with no Baileys mapping (drop)');
|
|
739
|
+
},
|
|
740
|
+
serverAck: (evt, { ctx }) => {
|
|
741
|
+
// The public CB surface comes exclusively from Event::RawNode. Rebuilding
|
|
742
|
+
// an ACK from this semantic event would drop optional wire attributes and
|
|
743
|
+
// emit the same stanza twice whenever raw forwarding is enabled.
|
|
744
|
+
if (evt.class === 'message' && evt.error) {
|
|
745
|
+
ctx.logger.warn({ msgId: evt.id, from: evt.from, error: evt.error }, 'outgoing message was rejected by the server');
|
|
746
|
+
ctx.ev.emit('messages.update', [
|
|
747
|
+
{
|
|
748
|
+
key: { remoteJid: evt.from, fromMe: true, id: evt.id },
|
|
749
|
+
update: {
|
|
750
|
+
status: WAMessageStatus.ERROR,
|
|
751
|
+
messageStubParameters: [evt.error]
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
]);
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
757
|
+
ctx.logger.debug({ msgId: evt.id, class: evt.class, from: evt.from, timestamp: evt.timestamp }, 'server acknowledged outgoing stanza');
|
|
758
|
+
},
|
|
759
|
+
noop: (evt, { ctx }) => ctx.logger.trace({ bridgeType: evt.bridgeType, detail: evt.detail }, 'bridge event acknowledged (no Baileys equivalent)'),
|
|
760
|
+
lidMappingUpdate: (evt, { ctx }) => {
|
|
761
|
+
// Mirror upstream `messages-recv.ts:287`: one `lid-mapping.update`
|
|
762
|
+
// event per pair, payload is the bare `{ lid, pn }` shape.
|
|
763
|
+
for (const mapping of evt.mappings) {
|
|
764
|
+
ctx.ev.emit('lid-mapping.update', mapping);
|
|
765
|
+
}
|
|
766
|
+
},
|
|
767
|
+
chatDelete: (evt, { ctx }) => ctx.ev.emit('chats.delete', [evt.jid]),
|
|
768
|
+
chatClear: (evt, { ctx }) => ctx.ev.emit('messages.delete', { jid: evt.jid, all: true }),
|
|
769
|
+
messageDelete: (evt, { ctx }) =>
|
|
770
|
+
// Upstream `chat-utils.ts:857` shape: `{ keys: WAMessageKey[] }` for
|
|
771
|
+
// per-message delete (not the `{ jid, all: true }` chat-clear case
|
|
772
|
+
// — that's a different sync action surface).
|
|
773
|
+
ctx.ev.emit('messages.delete', {
|
|
774
|
+
keys: [
|
|
775
|
+
{
|
|
776
|
+
remoteJid: evt.chatJid,
|
|
777
|
+
id: evt.messageId,
|
|
778
|
+
fromMe: evt.fromMe,
|
|
779
|
+
...(evt.participantJid ? { participant: evt.participantJid } : {})
|
|
780
|
+
}
|
|
781
|
+
]
|
|
782
|
+
}),
|
|
783
|
+
newsletterLiveUpdate: (evt, { ctx }) => {
|
|
784
|
+
// Fan out one `newsletter.reaction` per (message, reaction) pair —
|
|
785
|
+
// matches upstream `messages-recv.ts:320` semantics. Upstream sets
|
|
786
|
+
// `removed: true` when count is 0 (user removed their reaction);
|
|
787
|
+
// we mirror that.
|
|
788
|
+
for (const msg of evt.messages) {
|
|
789
|
+
for (const reaction of msg.reactions) {
|
|
790
|
+
ctx.ev.emit('newsletter.reaction', {
|
|
791
|
+
id: evt.newsletterJid,
|
|
792
|
+
server_id: msg.serverId,
|
|
793
|
+
reaction: {
|
|
794
|
+
code: reaction.code,
|
|
795
|
+
count: reaction.count,
|
|
796
|
+
removed: reaction.count === 0
|
|
797
|
+
}
|
|
798
|
+
});
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
},
|
|
802
|
+
disappearingModeChanged: (evt, { ctx }) =>
|
|
803
|
+
// Upstream surfaces this through `chats.update.ephemeralExpiration`
|
|
804
|
+
// (set in `process-message.ts:417` for the protocolMessage path).
|
|
805
|
+
// Bridge gives us the same data via a dedicated event — emit on
|
|
806
|
+
// the same channel for parity.
|
|
807
|
+
ctx.ev.emit('chats.update', [
|
|
808
|
+
{
|
|
809
|
+
id: evt.jid,
|
|
810
|
+
ephemeralExpiration: evt.duration > 0 ? evt.duration : null,
|
|
811
|
+
ephemeralSettingTimestamp: evt.settingTimestamp
|
|
812
|
+
}
|
|
813
|
+
]),
|
|
814
|
+
historySync: (evt, { ctx, historySync, runtime }) => {
|
|
815
|
+
// 1:1 with upstream `process-message.ts:371-376`. `isLatest` is true
|
|
816
|
+
// when this is the first history sync the bot has seen since
|
|
817
|
+
// pairing — upstream tracks it in `creds.processedHistoryMessages`,
|
|
818
|
+
// but in baileyrs the bridge owns creds, so we approximate with the
|
|
819
|
+
// `INITIAL_BOOTSTRAP` syncType which only fires once per pair. Bots
|
|
820
|
+
// gating "first hydrate" logic on `isLatest` see the same boolean.
|
|
821
|
+
const HSType = WAProto.HistorySync.HistorySyncType;
|
|
822
|
+
const isInitial = evt.syncType === HSType.INITIAL_BOOTSTRAP;
|
|
823
|
+
// The bridge may split one chunk into bounded batches (isFinalBatch=false
|
|
824
|
+
// on all but the last). `isLatest`/`progress` are chunk-level signals, so
|
|
825
|
+
// they only fire on the final batch — intermediate batches just append
|
|
826
|
+
// data. A non-batched bridge omits the flag → `!== false` keeps the old
|
|
827
|
+
// single-event behavior.
|
|
828
|
+
const isFinalBatch = evt.isFinalBatch !== false;
|
|
829
|
+
if (isFinalBatch && isInitial && !historySync.initialBootstrapComplete) {
|
|
830
|
+
historySync.initialBootstrapComplete = true;
|
|
831
|
+
ctx.ev.emit('messaging-history.status', {
|
|
832
|
+
syncType: HSType.INITIAL_BOOTSTRAP,
|
|
833
|
+
status: 'complete',
|
|
834
|
+
explicit: true
|
|
835
|
+
});
|
|
836
|
+
}
|
|
837
|
+
if (isFinalBatch && evt.syncType === HSType.RECENT && !historySync.recentSyncComplete) {
|
|
838
|
+
clearHistorySyncPausedTimeout(historySync, runtime);
|
|
839
|
+
if (evt.progress === 100) {
|
|
840
|
+
historySync.recentSyncComplete = true;
|
|
841
|
+
ctx.ev.emit('messaging-history.status', { syncType: HSType.RECENT, status: 'complete', explicit: true });
|
|
842
|
+
}
|
|
843
|
+
else {
|
|
844
|
+
historySync.pausedTimeout = unrefTimer(runtime.setTimeout(() => {
|
|
845
|
+
if (!historySync.recentSyncComplete) {
|
|
846
|
+
historySync.recentSyncComplete = true;
|
|
847
|
+
ctx.ev.emit('messaging-history.status', {
|
|
848
|
+
syncType: HSType.RECENT,
|
|
849
|
+
status: 'paused',
|
|
850
|
+
explicit: false
|
|
851
|
+
});
|
|
852
|
+
}
|
|
853
|
+
historySync.pausedTimeout = undefined;
|
|
854
|
+
}, HISTORY_SYNC_PAUSED_TIMEOUT_MS));
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
const payload = {
|
|
858
|
+
chats: evt.chats,
|
|
859
|
+
contacts: evt.contacts,
|
|
860
|
+
messages: evt.messages,
|
|
861
|
+
isLatest: evt.syncType === HSType.ON_DEMAND ? undefined : isInitial && isFinalBatch,
|
|
862
|
+
progress: isFinalBatch ? evt.progress : undefined,
|
|
863
|
+
syncType: evt.syncType,
|
|
864
|
+
pastParticipants: evt.pastParticipants,
|
|
865
|
+
chunkOrder: evt.chunkOrder,
|
|
866
|
+
peerDataRequestSessionId: evt.peerDataRequestSessionId,
|
|
867
|
+
lidPnMappings: evt.lidPnMappings.length > 0 ? evt.lidPnMappings : undefined
|
|
868
|
+
};
|
|
869
|
+
ctx.ev.emit('messaging-history.set', payload);
|
|
870
|
+
// Keep the chat hydration fan-out for compatibility. Contacts are part
|
|
871
|
+
// of the history snapshot and must not be re-emitted as mutations.
|
|
872
|
+
if (evt.chats.length > 0)
|
|
873
|
+
ctx.ev.emit('chats.upsert', evt.chats);
|
|
874
|
+
}
|
|
875
|
+
};
|
|
876
|
+
const dispatchCanonicalEvent = (canonical, dispatchCtx) => {
|
|
877
|
+
// Type-safe table lookup. The runtime cast through `DispatcherFn` is a
|
|
878
|
+
// no-op TS-wise (the table is exhaustively typed) — needed only because TS
|
|
879
|
+
// cannot follow the discriminator across an indexed mapped type.
|
|
880
|
+
const dispatcher = DISPATCHERS[canonical.type];
|
|
881
|
+
try {
|
|
882
|
+
dispatcher(canonical, dispatchCtx);
|
|
883
|
+
}
|
|
884
|
+
catch (err) {
|
|
885
|
+
// One bad event must not poison the rest of the pipeline.
|
|
886
|
+
dispatchCtx.ctx.reportUnexpectedError(err, `dispatching a '${canonical.type}' event`);
|
|
887
|
+
}
|
|
888
|
+
};
|
|
889
|
+
/** Aggregate adjacent ordinary messages while preserving every side-effecting
|
|
890
|
+
* event boundary. Both bridge object events and protobuf-wire batches enter
|
|
891
|
+
* through this single state machine. */
|
|
892
|
+
const dispatchCanonicalBatch = (ctx, dispatchCtx, count, canonicalAt) => {
|
|
893
|
+
let pending;
|
|
894
|
+
for (let index = 0; index < count; index++) {
|
|
895
|
+
const canonical = canonicalAt(index);
|
|
896
|
+
if (!canonical)
|
|
897
|
+
continue;
|
|
898
|
+
// Only ordinary messages can share one messages.upsert emission.
|
|
899
|
+
// Flush before every other event or a message with secondary
|
|
900
|
+
// channels (reaction, revoke, edit, member-label) to preserve the
|
|
901
|
+
// exact observable order of those side effects.
|
|
902
|
+
if (canonical.type !== CANONICAL_MESSAGE_EVENT || hasMessageSideEffects(canonical)) {
|
|
903
|
+
if (pending) {
|
|
904
|
+
emitMessageUpsert(ctx, pending.messages, pending);
|
|
905
|
+
pending = undefined;
|
|
906
|
+
}
|
|
907
|
+
dispatchCanonicalEvent(canonical, dispatchCtx);
|
|
908
|
+
continue;
|
|
909
|
+
}
|
|
910
|
+
if (ctx.fullConfig.shouldIgnoreJid?.(canonical.chatJid))
|
|
911
|
+
continue;
|
|
912
|
+
try {
|
|
913
|
+
// This branch bypasses the single-message dispatcher, so the push
|
|
914
|
+
// name has to be surfaced here too. Inside the try: a throwing
|
|
915
|
+
// consumer listener skips this message only, like the containment
|
|
916
|
+
// in dispatchCanonicalEvent.
|
|
917
|
+
emitInboundPushName(ctx, canonical);
|
|
918
|
+
const metadata = messageUpsertMetadata(canonical);
|
|
919
|
+
const message = canonicalMessageToWAMessage(canonical, dispatchCtx.runtime.Long);
|
|
920
|
+
if (pending && hasSameUpsertMetadata(pending, metadata)) {
|
|
921
|
+
pending.messages.push(message);
|
|
922
|
+
}
|
|
923
|
+
else {
|
|
924
|
+
if (pending)
|
|
925
|
+
emitMessageUpsert(ctx, pending.messages, pending);
|
|
926
|
+
pending = { ...metadata, messages: [message] };
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
catch (err) {
|
|
930
|
+
ctx.reportUnexpectedError(err, `dispatching a '${CANONICAL_MESSAGE_EVENT}' event`);
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
if (pending)
|
|
934
|
+
emitMessageUpsert(ctx, pending.messages, pending);
|
|
935
|
+
};
|
|
936
|
+
/**
|
|
937
|
+
* Create typed single and batch handlers for the bridge. The bridge only uses
|
|
938
|
+
* the batch capability when adjacent messages are already queued, while this
|
|
939
|
+
* layer owns all Baileys-specific translation and EventEmitter aggregation.
|
|
940
|
+
*/
|
|
941
|
+
export const makeEventHandlers = (ctx, callbacks, runtime = {
|
|
942
|
+
BinaryReader: DefaultBinaryReader,
|
|
943
|
+
Long: DefaultLong,
|
|
944
|
+
setTimeout: (callback, ms) => setTimeout(callback, ms),
|
|
945
|
+
clearTimeout: handle => clearTimeout(handle),
|
|
946
|
+
decodeMessageWireBatch: defaultDecodeMessageWireBatch,
|
|
947
|
+
decodeReceiptWireBatch: defaultDecodeReceiptWireBatch,
|
|
948
|
+
decodeServerAckWireBatch: defaultDecodeServerAckWireBatch
|
|
949
|
+
}) => {
|
|
950
|
+
const dispatchCtx = {
|
|
951
|
+
ctx,
|
|
952
|
+
callbacks,
|
|
953
|
+
runtime,
|
|
954
|
+
historySync: { initialBootstrapComplete: false, recentSyncComplete: false }
|
|
955
|
+
};
|
|
956
|
+
callbacks?.onCleanup?.(() => clearHistorySyncPausedTimeout(dispatchCtx.historySync, runtime));
|
|
957
|
+
const onEvent = (event) => {
|
|
958
|
+
const canonical = adaptBridgeEvent(event, ctx.logger);
|
|
959
|
+
if (canonical)
|
|
960
|
+
dispatchCanonicalEvent(canonical, dispatchCtx);
|
|
961
|
+
};
|
|
962
|
+
const onMessageBatch = (batch) => {
|
|
963
|
+
// The batch crosses as one buffer; the decoder validates its header and
|
|
964
|
+
// returns views over it, so payload count and metadata count agree by
|
|
965
|
+
// construction.
|
|
966
|
+
let view;
|
|
967
|
+
try {
|
|
968
|
+
view = runtime.decodeMessageWireBatch(batch);
|
|
969
|
+
}
|
|
970
|
+
catch (err) {
|
|
971
|
+
ctx.reportUnexpectedError(err, 'decoding the message wire batch');
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
const { messageData, messageOffsets, infos } = view;
|
|
975
|
+
// Decode through the runtime facade so each payload materializes as a
|
|
976
|
+
// hydrated runtime instance: `WebMessageInfo.fromObject` then keeps the
|
|
977
|
+
// message subtree via its instanceof short-circuit instead of walking
|
|
978
|
+
// and reallocating the whole tree — the dominant per-message allocation
|
|
979
|
+
// cost on the hot path. Lenient like the history-sync decoder: one
|
|
980
|
+
// malformed payload is skipped, not fatal to the batch.
|
|
981
|
+
const messages = Array.from({ length: infos.length });
|
|
982
|
+
const reader = new runtime.BinaryReader(messageData);
|
|
983
|
+
for (let index = 0; index < infos.length; index++) {
|
|
984
|
+
try {
|
|
985
|
+
const start = messageOffsets[index];
|
|
986
|
+
const end = messageOffsets[index + 1];
|
|
987
|
+
reader.pos = start;
|
|
988
|
+
messages[index] = WAProto.Message.decode(reader, end - start);
|
|
989
|
+
}
|
|
990
|
+
catch (err) {
|
|
991
|
+
messages[index] = null;
|
|
992
|
+
ctx.logger.warn({ err, index }, 'skipping malformed wire message');
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
dispatchCanonicalBatch(ctx, dispatchCtx, infos.length, index => adaptBridgeMessageWire(messages[index], infos[index], ctx.logger));
|
|
996
|
+
};
|
|
997
|
+
const onHistorySyncBatch = (batch) => {
|
|
998
|
+
const decoded = decodeHistorySyncWireBatch(batch, ctx.logger, runtime.BinaryReader);
|
|
999
|
+
onEvent(decoded.event);
|
|
1000
|
+
return decoded.skippedConversations;
|
|
1001
|
+
};
|
|
1002
|
+
// Packed receipt/ack batches reconstruct the single-event wire shape and
|
|
1003
|
+
// reuse the same adapter path, so transport is the only thing that changes.
|
|
1004
|
+
const onReceiptBatch = (batch) => {
|
|
1005
|
+
let receipts;
|
|
1006
|
+
try {
|
|
1007
|
+
receipts = runtime.decodeReceiptWireBatch(batch);
|
|
1008
|
+
}
|
|
1009
|
+
catch (err) {
|
|
1010
|
+
ctx.reportUnexpectedError(err, 'decoding the receipt wire batch');
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
// The decoded payload matches the single-event wire shape; the union's
|
|
1014
|
+
// declared type is narrower than the adapter's tolerance.
|
|
1015
|
+
for (const data of receipts)
|
|
1016
|
+
onEvent({ type: 'receipt', data });
|
|
1017
|
+
};
|
|
1018
|
+
const onServerAckBatch = (batch) => {
|
|
1019
|
+
let acks;
|
|
1020
|
+
try {
|
|
1021
|
+
acks = runtime.decodeServerAckWireBatch(batch);
|
|
1022
|
+
}
|
|
1023
|
+
catch (err) {
|
|
1024
|
+
ctx.reportUnexpectedError(err, 'decoding the server-ack wire batch');
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
for (const data of acks)
|
|
1028
|
+
onEvent({ type: 'server_ack', data });
|
|
1029
|
+
};
|
|
1030
|
+
// Opting the two packed paths into the bridge's borrowing contract, which
|
|
1031
|
+
// lets it hand every batch out of one reused buffer instead of allocating
|
|
1032
|
+
// per batch. Both handlers already satisfied the contract unchanged: each
|
|
1033
|
+
// decodes as its first act, and `decodeReceiptWireBatch` /
|
|
1034
|
+
// `decodeServerAckWireBatch` materialise every field rather than keeping a
|
|
1035
|
+
// view, so nothing points at the buffer once they return. Neither is async,
|
|
1036
|
+
// and no exception escapes them — the decode is guarded here and the
|
|
1037
|
+
// dispatch is guarded in `dispatchCanonicalEvent` — both of which the
|
|
1038
|
+
// contract requires, since either one drops the whole session back to a
|
|
1039
|
+
// buffer per batch.
|
|
1040
|
+
//
|
|
1041
|
+
// Declaring a borrowing name replaces its copying counterpart as the sink,
|
|
1042
|
+
// so the pair below is the whole opt-in. There is deliberately none for
|
|
1043
|
+
// messages: `decodeMessageWireBatch` returns views over the batch, so reuse
|
|
1044
|
+
// would alias the decoded result and not just the buffer.
|
|
1045
|
+
return {
|
|
1046
|
+
onEvent,
|
|
1047
|
+
onMessageBatch,
|
|
1048
|
+
onHistorySyncBatch,
|
|
1049
|
+
onReceiptBatch,
|
|
1050
|
+
onServerAckBatch,
|
|
1051
|
+
onReceiptBatchBorrowed: onReceiptBatch,
|
|
1052
|
+
onServerAckBatchBorrowed: onServerAckBatch,
|
|
1053
|
+
historySyncConversationTypes: CONVERSATION_HISTORY_SYNC_TYPES
|
|
1054
|
+
};
|
|
1055
|
+
};
|
|
1056
|
+
/** Legacy single-event helper retained for direct consumers and tests. */
|
|
1057
|
+
export const makeEventHandler = (ctx, callbacks) => makeEventHandlers(ctx, callbacks).onEvent;
|
|
1058
|
+
//# sourceMappingURL=events-core.js.map
|